boards.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  1. import {
  2. ALLOWED_BOARD_COLORS,
  3. ALLOWED_COLORS,
  4. TYPE_BOARD,
  5. TYPE_TEMPLATE_BOARD,
  6. TYPE_TEMPLATE_CONTAINER,
  7. } from '/config/const';
  8. import Users from "./users";
  9. const escapeForRegex = require('escape-string-regexp');
  10. Boards = new Mongo.Collection('boards');
  11. /**
  12. * This is a Board.
  13. */
  14. Boards.attachSchema(
  15. new SimpleSchema({
  16. title: {
  17. /**
  18. * The title of the board
  19. */
  20. type: String,
  21. },
  22. slug: {
  23. /**
  24. * The title slugified.
  25. */
  26. type: String,
  27. // eslint-disable-next-line consistent-return
  28. autoValue() {
  29. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  30. // return an empty string. This is causes bugs in our application so we set
  31. // a default slug in this case.
  32. // Improvment would be to change client URL after slug is changed
  33. const title = this.field('title');
  34. if (title.isSet && !this.isSet) {
  35. let slug = 'board';
  36. slug = getSlug(title.value) || slug;
  37. return slug;
  38. }
  39. },
  40. },
  41. archived: {
  42. /**
  43. * Is the board archived?
  44. */
  45. type: Boolean,
  46. // eslint-disable-next-line consistent-return
  47. autoValue() {
  48. if (this.isInsert && !this.isSet) {
  49. return false;
  50. }
  51. },
  52. },
  53. archivedAt: {
  54. /**
  55. * Latest archiving time of the board
  56. */
  57. type: Date,
  58. optional: true,
  59. },
  60. createdAt: {
  61. /**
  62. * Creation time of the board
  63. */
  64. type: Date,
  65. // eslint-disable-next-line consistent-return
  66. autoValue() {
  67. if (this.isInsert) {
  68. return new Date();
  69. } else if (this.isUpsert) {
  70. return { $setOnInsert: new Date() };
  71. } else {
  72. this.unset();
  73. }
  74. },
  75. },
  76. // XXX Inconsistent field naming
  77. modifiedAt: {
  78. /**
  79. * Last modification time of the board
  80. */
  81. type: Date,
  82. optional: true,
  83. // eslint-disable-next-line consistent-return
  84. autoValue() {
  85. if (this.isInsert || this.isUpsert || this.isUpdate) {
  86. return new Date();
  87. } else {
  88. this.unset();
  89. }
  90. },
  91. },
  92. // De-normalized number of users that have starred this board
  93. stars: {
  94. /**
  95. * How many stars the board has
  96. */
  97. type: Number,
  98. // eslint-disable-next-line consistent-return
  99. autoValue() {
  100. if (this.isInsert) {
  101. return 0;
  102. }
  103. },
  104. },
  105. // De-normalized label system
  106. labels: {
  107. /**
  108. * List of labels attached to a board
  109. */
  110. type: [Object],
  111. optional: true,
  112. /* Commented out, so does not create labels to new boards.
  113. // eslint-disable-next-line consistent-return
  114. autoValue() {
  115. if (this.isInsert && !this.isSet) {
  116. const colors = Boards.simpleSchema()._schema['labels.$.color']
  117. .allowedValues;
  118. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  119. return defaultLabelsColors.map(color => ({
  120. color,
  121. _id: Random.id(6),
  122. name: '',
  123. }));
  124. }
  125. },
  126. */
  127. },
  128. 'labels.$._id': {
  129. /**
  130. * Unique id of a label
  131. */
  132. // We don't specify that this field must be unique in the board because that
  133. // will cause performance penalties and is not necessary since this field is
  134. // always set on the server.
  135. // XXX Actually if we create a new label, the `_id` is set on the client
  136. // without being overwritten by the server, could it be a problem?
  137. type: String,
  138. },
  139. 'labels.$.name': {
  140. /**
  141. * Name of a label
  142. */
  143. type: String,
  144. optional: true,
  145. },
  146. 'labels.$.color': {
  147. /**
  148. * color of a label.
  149. *
  150. * Can be amongst `green`, `yellow`, `orange`, `red`, `purple`,
  151. * `blue`, `sky`, `lime`, `pink`, `black`,
  152. * `silver`, `peachpuff`, `crimson`, `plum`, `darkgreen`,
  153. * `slateblue`, `magenta`, `gold`, `navy`, `gray`,
  154. * `saddlebrown`, `paleturquoise`, `mistyrose`, `indigo`
  155. */
  156. type: String,
  157. allowedValues: ALLOWED_COLORS,
  158. },
  159. // XXX We might want to maintain more informations under the member sub-
  160. // documents like de-normalized meta-data (the date the member joined the
  161. // board, the number of contributions, etc.).
  162. members: {
  163. /**
  164. * List of members of a board
  165. */
  166. type: [Object],
  167. // eslint-disable-next-line consistent-return
  168. autoValue() {
  169. if (this.isInsert && !this.isSet) {
  170. return [
  171. {
  172. userId: this.userId,
  173. isAdmin: true,
  174. isActive: true,
  175. isNoComments: false,
  176. isCommentOnly: false,
  177. isWorker: false,
  178. },
  179. ];
  180. }
  181. },
  182. },
  183. 'members.$.userId': {
  184. /**
  185. * The uniq ID of the member
  186. */
  187. type: String,
  188. },
  189. 'members.$.isAdmin': {
  190. /**
  191. * Is the member an admin of the board?
  192. */
  193. type: Boolean,
  194. },
  195. 'members.$.isActive': {
  196. /**
  197. * Is the member active?
  198. */
  199. type: Boolean,
  200. },
  201. 'members.$.isNoComments': {
  202. /**
  203. * Is the member not allowed to make comments
  204. */
  205. type: Boolean,
  206. optional: true,
  207. },
  208. 'members.$.isCommentOnly': {
  209. /**
  210. * Is the member only allowed to comment on the board
  211. */
  212. type: Boolean,
  213. optional: true,
  214. },
  215. 'members.$.isWorker': {
  216. /**
  217. * Is the member only allowed to move card, assign himself to card and comment
  218. */
  219. type: Boolean,
  220. optional: true,
  221. },
  222. permission: {
  223. /**
  224. * visibility of the board
  225. */
  226. type: String,
  227. allowedValues: ['public', 'private'],
  228. },
  229. orgs: {
  230. /**
  231. * the list of organizations that a board belongs to
  232. */
  233. type: [Object],
  234. optional: true,
  235. },
  236. 'orgs.$.orgId':{
  237. /**
  238. * The uniq ID of the organization
  239. */
  240. type: String,
  241. },
  242. 'orgs.$.orgDisplayName':{
  243. /**
  244. * The display name of the organization
  245. */
  246. type: String,
  247. },
  248. 'orgs.$.isActive': {
  249. /**
  250. * Is the organization active?
  251. */
  252. type: Boolean,
  253. },
  254. teams: {
  255. /**
  256. * the list of teams that a board belongs to
  257. */
  258. type: [Object],
  259. optional: true,
  260. },
  261. 'teams.$.teamId':{
  262. /**
  263. * The uniq ID of the team
  264. */
  265. type: String,
  266. },
  267. 'teams.$.teamDisplayName':{
  268. /**
  269. * The display name of the team
  270. */
  271. type: String,
  272. },
  273. 'teams.$.isActive': {
  274. /**
  275. * Is the team active?
  276. */
  277. type: Boolean,
  278. },
  279. color: {
  280. /**
  281. * The color of the board.
  282. */
  283. type: String,
  284. allowedValues: ALLOWED_BOARD_COLORS,
  285. // eslint-disable-next-line consistent-return
  286. autoValue() {
  287. if (this.isInsert && !this.isSet) {
  288. return ALLOWED_BOARD_COLORS[0];
  289. }
  290. },
  291. },
  292. description: {
  293. /**
  294. * The description of the board
  295. */
  296. type: String,
  297. optional: true,
  298. },
  299. subtasksDefaultBoardId: {
  300. /**
  301. * The default board ID assigned to subtasks.
  302. */
  303. type: String,
  304. optional: true,
  305. defaultValue: null,
  306. },
  307. subtasksDefaultListId: {
  308. /**
  309. * The default List ID assigned to subtasks.
  310. */
  311. type: String,
  312. optional: true,
  313. defaultValue: null,
  314. },
  315. dateSettingsDefaultBoardId: {
  316. type: String,
  317. optional: true,
  318. defaultValue: null,
  319. },
  320. dateSettingsDefaultListId: {
  321. type: String,
  322. optional: true,
  323. defaultValue: null,
  324. },
  325. allowsSubtasks: {
  326. /**
  327. * Does the board allows subtasks?
  328. */
  329. type: Boolean,
  330. defaultValue: true,
  331. },
  332. allowsAttachments: {
  333. /**
  334. * Does the board allows attachments?
  335. */
  336. type: Boolean,
  337. defaultValue: true,
  338. },
  339. allowsChecklists: {
  340. /**
  341. * Does the board allows checklists?
  342. */
  343. type: Boolean,
  344. defaultValue: true,
  345. },
  346. allowsComments: {
  347. /**
  348. * Does the board allows comments?
  349. */
  350. type: Boolean,
  351. defaultValue: true,
  352. },
  353. allowsDescriptionTitle: {
  354. /**
  355. * Does the board allows description title?
  356. */
  357. type: Boolean,
  358. defaultValue: true,
  359. },
  360. allowsDescriptionText: {
  361. /**
  362. * Does the board allows description text?
  363. */
  364. type: Boolean,
  365. defaultValue: true,
  366. },
  367. allowsCardNumber: {
  368. /**
  369. * Does the board allows card numbers?
  370. */
  371. type: Boolean,
  372. defaultValue: false,
  373. },
  374. allowsActivities: {
  375. /**
  376. * Does the board allows comments?
  377. */
  378. type: Boolean,
  379. defaultValue: true,
  380. },
  381. allowsLabels: {
  382. /**
  383. * Does the board allows labels?
  384. */
  385. type: Boolean,
  386. defaultValue: true,
  387. },
  388. allowsCreator: {
  389. /**
  390. * Does the board allow creator?
  391. */
  392. type: Boolean,
  393. defaultValue: true,
  394. },
  395. allowsAssignee: {
  396. /**
  397. * Does the board allows assignee?
  398. */
  399. type: Boolean,
  400. defaultValue: true,
  401. },
  402. allowsMembers: {
  403. /**
  404. * Does the board allows members?
  405. */
  406. type: Boolean,
  407. defaultValue: true,
  408. },
  409. allowsRequestedBy: {
  410. /**
  411. * Does the board allows requested by?
  412. */
  413. type: Boolean,
  414. defaultValue: true,
  415. },
  416. allowsCardSortingByNumber: {
  417. /**
  418. * Does the board allows card sorting by number?
  419. */
  420. type: Boolean,
  421. defaultValue: true,
  422. },
  423. allowsAssignedBy: {
  424. /**
  425. * Does the board allows requested by?
  426. */
  427. type: Boolean,
  428. defaultValue: true,
  429. },
  430. allowsReceivedDate: {
  431. /**
  432. * Does the board allows received date?
  433. */
  434. type: Boolean,
  435. defaultValue: true,
  436. },
  437. allowsStartDate: {
  438. /**
  439. * Does the board allows start date?
  440. */
  441. type: Boolean,
  442. defaultValue: true,
  443. },
  444. allowsEndDate: {
  445. /**
  446. * Does the board allows end date?
  447. */
  448. type: Boolean,
  449. defaultValue: true,
  450. },
  451. allowsDueDate: {
  452. /**
  453. * Does the board allows due date?
  454. */
  455. type: Boolean,
  456. defaultValue: true,
  457. },
  458. presentParentTask: {
  459. /**
  460. * Controls how to present the parent task:
  461. *
  462. * - `prefix-with-full-path`: add a prefix with the full path
  463. * - `prefix-with-parent`: add a prefisx with the parent name
  464. * - `subtext-with-full-path`: add a subtext with the full path
  465. * - `subtext-with-parent`: add a subtext with the parent name
  466. * - `no-parent`: does not show the parent at all
  467. */
  468. type: String,
  469. allowedValues: [
  470. 'prefix-with-full-path',
  471. 'prefix-with-parent',
  472. 'subtext-with-full-path',
  473. 'subtext-with-parent',
  474. 'no-parent',
  475. ],
  476. optional: true,
  477. defaultValue: 'no-parent',
  478. },
  479. receivedAt: {
  480. /**
  481. * Date the card was received
  482. */
  483. type: Date,
  484. optional: true,
  485. },
  486. startAt: {
  487. /**
  488. * Starting date of the board.
  489. */
  490. type: Date,
  491. optional: true,
  492. },
  493. dueAt: {
  494. /**
  495. * Due date of the board.
  496. */
  497. type: Date,
  498. optional: true,
  499. },
  500. endAt: {
  501. /**
  502. * End date of the board.
  503. */
  504. type: Date,
  505. optional: true,
  506. },
  507. spentTime: {
  508. /**
  509. * Time spent in the board.
  510. */
  511. type: Number,
  512. decimal: true,
  513. optional: true,
  514. },
  515. isOvertime: {
  516. /**
  517. * Is the board overtimed?
  518. */
  519. type: Boolean,
  520. defaultValue: false,
  521. optional: true,
  522. },
  523. type: {
  524. /**
  525. * The type of board
  526. * possible values: board, template-board, template-container
  527. */
  528. type: String,
  529. defaultValue: TYPE_BOARD,
  530. allowedValues: [TYPE_BOARD, TYPE_TEMPLATE_BOARD, TYPE_TEMPLATE_CONTAINER],
  531. },
  532. sort: {
  533. /**
  534. * Sort value
  535. */
  536. type: Number,
  537. decimal: true,
  538. defaultValue: -1,
  539. },
  540. }),
  541. );
  542. Boards.helpers({
  543. copy() {
  544. const oldId = this._id;
  545. delete this._id;
  546. delete this.slug;
  547. this.title = this.copyTitle();
  548. const _id = Boards.insert(this);
  549. // Copy all swimlanes in board
  550. Swimlanes.find({
  551. boardId: oldId,
  552. archived: false,
  553. }).forEach(swimlane => {
  554. swimlane.type = 'swimlane';
  555. swimlane.copy(_id);
  556. });
  557. // copy custom field definitions
  558. const cfMap = {};
  559. CustomFields.find({ boardIds: oldId }).forEach(cf => {
  560. const id = cf._id;
  561. delete cf._id;
  562. cf.boardIds = [_id];
  563. cfMap[id] = CustomFields.insert(cf);
  564. });
  565. Cards.find({ boardId: _id }).forEach(card => {
  566. Cards.update(card._id, {
  567. $set: {
  568. customFields: card.customFields.map(cf => {
  569. cf._id = cfMap[cf._id];
  570. return cf;
  571. }),
  572. },
  573. });
  574. });
  575. // copy rules, actions, and triggers
  576. const actionsMap = {};
  577. Actions.find({ boardId: oldId }).forEach(action => {
  578. const id = action._id;
  579. delete action._id;
  580. action.boardId = _id;
  581. actionsMap[id] = Actions.insert(action);
  582. });
  583. const triggersMap = {};
  584. Triggers.find({ boardId: oldId }).forEach(trigger => {
  585. const id = trigger._id;
  586. delete trigger._id;
  587. trigger.boardId = _id;
  588. triggersMap[id] = Triggers.insert(trigger);
  589. });
  590. Rules.find({ boardId: oldId }).forEach(rule => {
  591. delete rule._id;
  592. rule.boardId = _id;
  593. rule.actionId = actionsMap[rule.actionId];
  594. rule.triggerId = triggersMap[rule.triggerId];
  595. Rules.insert(rule);
  596. });
  597. },
  598. /**
  599. * Return a unique title based on the current title
  600. *
  601. * @returns {string|null}
  602. */
  603. copyTitle() {
  604. return Boards.uniqueTitle(this.title);
  605. },
  606. /**
  607. * Is supplied user authorized to view this board?
  608. */
  609. isVisibleBy(user) {
  610. if (this.isPublic()) {
  611. // public boards are visible to everyone
  612. return true;
  613. } else {
  614. // otherwise you have to be logged-in and active member
  615. return user && this.isActiveMember(user._id);
  616. }
  617. },
  618. /**
  619. * Is the user one of the active members of the board?
  620. *
  621. * @param userId
  622. * @returns {boolean} the member that matches, or undefined/false
  623. */
  624. isActiveMember(userId) {
  625. if (userId) {
  626. return this.members.find(
  627. member => member.userId === userId && member.isActive,
  628. );
  629. } else {
  630. return false;
  631. }
  632. },
  633. isPublic() {
  634. return this.permission === 'public';
  635. },
  636. cards() {
  637. return Cards.find(
  638. { boardId: this._id, archived: false },
  639. { sort: { title: 1 } },
  640. );
  641. },
  642. lists() {
  643. //currentUser = Meteor.user();
  644. //if (currentUser) {
  645. // enabled = Meteor.user().hasSortBy();
  646. //}
  647. //return enabled ? this.newestLists() : this.draggableLists();
  648. return this.draggableLists();
  649. },
  650. newestLists() {
  651. // sorted lists from newest to the oldest, by its creation date or its cards' last modification date
  652. const value = Meteor.user()._getListSortBy();
  653. const sortKey = { starred: -1, [value[0]]: value[1] }; // [["starred",-1],value];
  654. return Lists.find(
  655. {
  656. boardId: this._id,
  657. archived: false,
  658. },
  659. { sort: sortKey },
  660. );
  661. },
  662. draggableLists() {
  663. return Lists.find({ boardId: this._id }, { sort: { sort: 1 } });
  664. },
  665. /** returns the last list
  666. * @returns Document the last list
  667. */
  668. getLastList() {
  669. const ret = Lists.findOne({ boardId: this._id }, { sort: { sort: 'desc' } });
  670. return ret;
  671. },
  672. nullSortLists() {
  673. return Lists.find({
  674. boardId: this._id,
  675. archived: false,
  676. sort: { $eq: null },
  677. });
  678. },
  679. swimlanes() {
  680. return Swimlanes.find(
  681. { boardId: this._id, archived: false },
  682. { sort: { sort: 1 } },
  683. );
  684. },
  685. nextSwimlane(swimlane) {
  686. return Swimlanes.findOne(
  687. {
  688. boardId: this._id,
  689. archived: false,
  690. sort: { $gte: swimlane.sort },
  691. _id: { $ne: swimlane._id },
  692. },
  693. {
  694. sort: { sort: 1 },
  695. },
  696. );
  697. },
  698. nullSortSwimlanes() {
  699. return Swimlanes.find({
  700. boardId: this._id,
  701. archived: false,
  702. sort: { $eq: null },
  703. });
  704. },
  705. hasOvertimeCards() {
  706. const card = Cards.findOne({
  707. isOvertime: true,
  708. boardId: this._id,
  709. archived: false,
  710. });
  711. return card !== undefined;
  712. },
  713. hasSpentTimeCards() {
  714. const card = Cards.findOne({
  715. spentTime: { $gt: 0 },
  716. boardId: this._id,
  717. archived: false,
  718. });
  719. return card !== undefined;
  720. },
  721. activities() {
  722. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  723. },
  724. activeMembers(){
  725. return _.where(this.members, { isActive: true });
  726. },
  727. activeMembers2(members, boardTeamUsers) {
  728. let allMembers = members;
  729. if(this.teams !== undefined && this.teams.length > 0){
  730. let index;
  731. if(boardTeamUsers && boardTeamUsers.count() > 0){
  732. boardTeamUsers.forEach((u) => {
  733. index = allMembers.findIndex(function(m){ return m.userId == u._id});
  734. if(index == -1){
  735. allMembers.push({
  736. "isActive": true,
  737. "isAdmin": u.isAdmin !== undefined ? u.isAdmin : false,
  738. "isCommentOnly" : false,
  739. "isNoComments" : false,
  740. "userId": u._id,
  741. });
  742. }
  743. });
  744. }
  745. }
  746. return allMembers;
  747. },
  748. activeOrgs() {
  749. return _.where(this.orgs, { isActive: true });
  750. },
  751. // hasNotAnyOrg(){
  752. // return this.orgs === undefined || this.orgs.length <= 0;
  753. // },
  754. activeTeams() {
  755. return _.where(this.teams, { isActive: true });
  756. },
  757. // hasNotAnyTeam(){
  758. // return this.teams === undefined || this.teams.length <= 0;
  759. // },
  760. activeAdmins() {
  761. return _.where(this.members, { isActive: true, isAdmin: true });
  762. },
  763. memberUsers() {
  764. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  765. },
  766. getLabel(name, color) {
  767. return _.findWhere(this.labels, { name, color });
  768. },
  769. getLabelById(labelId) {
  770. return _.findWhere(this.labels, { _id: labelId });
  771. },
  772. labelIndex(labelId) {
  773. return _.pluck(this.labels, '_id').indexOf(labelId);
  774. },
  775. memberIndex(memberId) {
  776. return _.pluck(this.members, 'userId').indexOf(memberId);
  777. },
  778. hasMember(memberId) {
  779. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  780. },
  781. hasAdmin(memberId) {
  782. return !!_.findWhere(this.members, {
  783. userId: memberId,
  784. isActive: true,
  785. isAdmin: true,
  786. });
  787. },
  788. hasNoComments(memberId) {
  789. return !!_.findWhere(this.members, {
  790. userId: memberId,
  791. isActive: true,
  792. isAdmin: false,
  793. isNoComments: true,
  794. isWorker: false,
  795. });
  796. },
  797. hasCommentOnly(memberId) {
  798. return !!_.findWhere(this.members, {
  799. userId: memberId,
  800. isActive: true,
  801. isAdmin: false,
  802. isCommentOnly: true,
  803. isWorker: false,
  804. });
  805. },
  806. hasWorker(memberId) {
  807. return !!_.findWhere(this.members, {
  808. userId: memberId,
  809. isActive: true,
  810. isAdmin: false,
  811. isCommentOnly: false,
  812. isWorker: true,
  813. });
  814. },
  815. hasAnyAllowsDate() {
  816. const ret = this.allowsReceivedDate || this.allowsStartDate || this.allowsDueDate || this.allowsEndDate;
  817. return ret;
  818. },
  819. hasAnyAllowsUser() {
  820. const ret = this.allowsCreator || this.allowsMembers || this.allowsAssignee || this.allowsRequestedBy || this.allowsAssignedBy;
  821. return ret;
  822. },
  823. absoluteUrl() {
  824. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  825. },
  826. originRelativeUrl() {
  827. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  828. },
  829. colorClass() {
  830. return `board-color-${this.color}`;
  831. },
  832. customFields() {
  833. return CustomFields.find(
  834. { boardIds: { $in: [this._id] } },
  835. { sort: { name: 1 } },
  836. );
  837. },
  838. // XXX currently mutations return no value so we have an issue when using addLabel in import
  839. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  840. pushLabel(name, color) {
  841. const _id = Random.id(6);
  842. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  843. return _id;
  844. },
  845. /** sets the new label order
  846. * @param newLabelOrderOnlyIds new order array of _id, e.g. Array(4) [ "FvtD34", "PAEgDP", "LjRBxH", "YJ8sZz" ]
  847. */
  848. setNewLabelOrder(newLabelOrderOnlyIds) {
  849. if (this.labels.length == newLabelOrderOnlyIds.length) {
  850. if (this.labels.every(_label => newLabelOrderOnlyIds.indexOf(_label._id) >= 0)) {
  851. const newLabels = _.sortBy(this.labels, _label => newLabelOrderOnlyIds.indexOf(_label._id));
  852. if (this.labels.length == newLabels.length) {
  853. Boards.direct.update(this._id, {$set: {labels: newLabels}});
  854. }
  855. }
  856. }
  857. },
  858. searchBoards(term) {
  859. check(term, Match.OneOf(String, null, undefined));
  860. const query = { boardId: this._id };
  861. query.type = 'cardType-linkedBoard';
  862. query.archived = false;
  863. const projection = { limit: 10, sort: { createdAt: -1 } };
  864. if (term) {
  865. const regex = new RegExp(term, 'i');
  866. query.$or = [{ title: regex }, { description: regex }];
  867. }
  868. return Cards.find(query, projection);
  869. },
  870. searchSwimlanes(term) {
  871. check(term, Match.OneOf(String, null, undefined));
  872. const query = { boardId: this._id };
  873. if (this.isTemplatesBoard()) {
  874. query.type = 'template-swimlane';
  875. query.archived = false;
  876. } else {
  877. query.type = { $nin: ['template-swimlane'] };
  878. }
  879. const projection = { limit: 10, sort: { createdAt: -1 } };
  880. if (term) {
  881. const regex = new RegExp(term, 'i');
  882. query.$or = [{ title: regex }, { description: regex }];
  883. }
  884. return Swimlanes.find(query, projection);
  885. },
  886. searchLists(term) {
  887. let ret = null;
  888. if (term) {
  889. check(term, Match.OneOf(String));
  890. term = term.trim();
  891. }
  892. if (term) {
  893. const query = { boardId: this._id };
  894. if (this.isTemplatesBoard()) {
  895. query.type = 'template-list';
  896. query.archived = false;
  897. } else {
  898. query.type = { $nin: ['template-list'] };
  899. }
  900. const projection = { sort: { createdAt: -1 } };
  901. if (term) {
  902. const regex = new RegExp(term, 'i');
  903. query.$or = [{ title: regex }, { description: regex }];
  904. }
  905. ret = Lists.find(query, projection);
  906. }
  907. return ret;
  908. },
  909. searchCards(term, excludeLinked) {
  910. let ret = null;
  911. if (term) {
  912. check(term, Match.OneOf(String));
  913. term = term.trim();
  914. }
  915. if (term) {
  916. const query = { boardId: this._id };
  917. if (excludeLinked) {
  918. query.linkedId = null;
  919. }
  920. if (this.isTemplatesBoard()) {
  921. query.type = 'template-card';
  922. query.archived = false;
  923. } else {
  924. query.type = { $nin: ['template-card'] };
  925. }
  926. const projection = { sort: { createdAt: -1 } };
  927. const regex = new RegExp(term, 'i');
  928. query.$or = [
  929. { title: regex },
  930. { description: regex },
  931. { customFields: { $elemMatch: { value: regex } } },
  932. ];
  933. ret = Cards.find(query, projection);
  934. }
  935. return ret;
  936. },
  937. // A board alwasy has another board where it deposits subtasks of thasks
  938. // that belong to itself.
  939. getDefaultSubtasksBoardId() {
  940. if (
  941. this.subtasksDefaultBoardId === null ||
  942. this.subtasksDefaultBoardId === undefined
  943. ) {
  944. this.subtasksDefaultBoardId = Boards.insert({
  945. title: `^${this.title}^`,
  946. permission: this.permission,
  947. members: this.members,
  948. color: this.color,
  949. description: TAPi18n.__('default-subtasks-board', {
  950. board: this.title,
  951. }),
  952. });
  953. Swimlanes.insert({
  954. title: TAPi18n.__('default'),
  955. boardId: this.subtasksDefaultBoardId,
  956. });
  957. Boards.update(this._id, {
  958. $set: {
  959. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  960. },
  961. });
  962. }
  963. return this.subtasksDefaultBoardId;
  964. },
  965. getDefaultSubtasksBoard() {
  966. return Boards.findOne(this.getDefaultSubtasksBoardId());
  967. },
  968. //Date Settings option such as received date, start date and so on.
  969. getDefaultDateSettingsBoardId() {
  970. if (
  971. this.dateSettingsDefaultBoardId === null ||
  972. this.dateSettingsDefaultBoardId === undefined
  973. ) {
  974. this.dateSettingsDefaultBoardId = Boards.insert({
  975. title: `^${this.title}^`,
  976. permission: this.permission,
  977. members: this.members,
  978. color: this.color,
  979. description: TAPi18n.__('default-dates-board', {
  980. board: this.title,
  981. }),
  982. });
  983. Swimlanes.insert({
  984. title: TAPi18n.__('default'),
  985. boardId: this.dateSettingsDefaultBoardId,
  986. });
  987. Boards.update(this._id, {
  988. $set: {
  989. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  990. },
  991. });
  992. }
  993. return this.dateSettingsDefaultBoardId;
  994. },
  995. getDefaultDateSettingsBoard() {
  996. return Boards.findOne(this.getDefaultDateSettingsBoardId());
  997. },
  998. getDefaultSubtasksListId() {
  999. if (
  1000. this.subtasksDefaultListId === null ||
  1001. this.subtasksDefaultListId === undefined
  1002. ) {
  1003. this.subtasksDefaultListId = Lists.insert({
  1004. title: TAPi18n.__('queue'),
  1005. boardId: this._id,
  1006. });
  1007. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  1008. }
  1009. return this.subtasksDefaultListId;
  1010. },
  1011. getDefaultSubtasksList() {
  1012. return Lists.findOne(this.getDefaultSubtasksListId());
  1013. },
  1014. getDefaultDateSettingsListId() {
  1015. if (
  1016. this.dateSettingsDefaultListId === null ||
  1017. this.dateSettingsDefaultListId === undefined
  1018. ) {
  1019. this.dateSettingsDefaultListId = Lists.insert({
  1020. title: TAPi18n.__('queue'),
  1021. boardId: this._id,
  1022. });
  1023. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  1024. }
  1025. return this.dateSettingsDefaultListId;
  1026. },
  1027. getDefaultDateSettingsList() {
  1028. return Lists.findOne(this.getDefaultDateSettingsListId());
  1029. },
  1030. getDefaultSwimline() {
  1031. let result = Swimlanes.findOne({ boardId: this._id });
  1032. if (result === undefined) {
  1033. Swimlanes.insert({
  1034. title: TAPi18n.__('default'),
  1035. boardId: this._id,
  1036. });
  1037. result = Swimlanes.findOne({ boardId: this._id });
  1038. }
  1039. return result;
  1040. },
  1041. getNextCardNumber() {
  1042. const boardCards = Cards.find(
  1043. {
  1044. boardId: this._id
  1045. },
  1046. {
  1047. sort: { cardNumber: -1 },
  1048. limit: 1
  1049. }
  1050. ).fetch();
  1051. // If no card is assigned to the board, return 1
  1052. if (!boardCards || boardCards.length === 0) {
  1053. return 1;
  1054. }
  1055. const maxCardNr = !!boardCards[0].cardNumber ? boardCards[0].cardNumber : 0;
  1056. return maxCardNr + 1;
  1057. },
  1058. cardsDueInBetween(start, end) {
  1059. return Cards.find({
  1060. boardId: this._id,
  1061. dueAt: { $gte: start, $lte: end },
  1062. });
  1063. },
  1064. cardsInInterval(start, end) {
  1065. return Cards.find({
  1066. boardId: this._id,
  1067. $or: [
  1068. {
  1069. startAt: {
  1070. $lte: start,
  1071. },
  1072. endAt: {
  1073. $gte: start,
  1074. },
  1075. },
  1076. {
  1077. startAt: {
  1078. $lte: end,
  1079. },
  1080. endAt: {
  1081. $gte: end,
  1082. },
  1083. },
  1084. {
  1085. startAt: {
  1086. $gte: start,
  1087. },
  1088. endAt: {
  1089. $lte: end,
  1090. },
  1091. },
  1092. ],
  1093. });
  1094. },
  1095. isTemplateBoard() {
  1096. return this.type === 'template-board';
  1097. },
  1098. isTemplatesBoard() {
  1099. return this.type === 'template-container';
  1100. },
  1101. });
  1102. Boards.mutations({
  1103. archive() {
  1104. return { $set: { archived: true, archivedAt: new Date() } };
  1105. },
  1106. restore() {
  1107. return { $set: { archived: false } };
  1108. },
  1109. rename(title) {
  1110. return { $set: { title } };
  1111. },
  1112. setDescription(description) {
  1113. return { $set: { description } };
  1114. },
  1115. setColor(color) {
  1116. return { $set: { color } };
  1117. },
  1118. setVisibility(visibility) {
  1119. return { $set: { permission: visibility } };
  1120. },
  1121. addLabel(name, color) {
  1122. // If label with the same name and color already exists we don't want to
  1123. // create another one because they would be indistinguishable in the UI
  1124. // (they would still have different `_id` but that is not exposed to the
  1125. // user).
  1126. if (!this.getLabel(name, color)) {
  1127. const _id = Random.id(6);
  1128. return { $push: { labels: { _id, name, color } } };
  1129. }
  1130. return {};
  1131. },
  1132. editLabel(labelId, name, color) {
  1133. if (!this.getLabel(name, color)) {
  1134. const labelIndex = this.labelIndex(labelId);
  1135. return {
  1136. $set: {
  1137. [`labels.${labelIndex}.name`]: name,
  1138. [`labels.${labelIndex}.color`]: color,
  1139. },
  1140. };
  1141. }
  1142. return {};
  1143. },
  1144. removeLabel(labelId) {
  1145. return { $pull: { labels: { _id: labelId } } };
  1146. },
  1147. changeOwnership(fromId, toId) {
  1148. const memberIndex = this.memberIndex(fromId);
  1149. return {
  1150. $set: {
  1151. [`members.${memberIndex}.userId`]: toId,
  1152. },
  1153. };
  1154. },
  1155. addMember(memberId) {
  1156. const memberIndex = this.memberIndex(memberId);
  1157. if (memberIndex >= 0) {
  1158. return {
  1159. $set: {
  1160. [`members.${memberIndex}.isActive`]: true,
  1161. },
  1162. };
  1163. }
  1164. return {
  1165. $push: {
  1166. members: {
  1167. userId: memberId,
  1168. isAdmin: false,
  1169. isActive: true,
  1170. isNoComments: false,
  1171. isCommentOnly: false,
  1172. isWorker: false,
  1173. },
  1174. },
  1175. };
  1176. },
  1177. removeMember(memberId) {
  1178. const memberIndex = this.memberIndex(memberId);
  1179. // we do not allow the only one admin to be removed
  1180. const allowRemove =
  1181. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1182. if (!allowRemove) {
  1183. return {
  1184. $set: {
  1185. [`members.${memberIndex}.isActive`]: true,
  1186. },
  1187. };
  1188. }
  1189. return {
  1190. $set: {
  1191. [`members.${memberIndex}.isActive`]: false,
  1192. [`members.${memberIndex}.isAdmin`]: false,
  1193. },
  1194. };
  1195. },
  1196. setMemberPermission(
  1197. memberId,
  1198. isAdmin,
  1199. isNoComments,
  1200. isCommentOnly,
  1201. isWorker,
  1202. currentUserId = Meteor.userId(),
  1203. ) {
  1204. const memberIndex = this.memberIndex(memberId);
  1205. // do not allow change permission of self
  1206. if (memberId === currentUserId) {
  1207. isAdmin = this.members[memberIndex].isAdmin;
  1208. }
  1209. return {
  1210. $set: {
  1211. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1212. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1213. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1214. [`members.${memberIndex}.isWorker`]: isWorker,
  1215. },
  1216. };
  1217. },
  1218. setAllowsSubtasks(allowsSubtasks) {
  1219. return { $set: { allowsSubtasks } };
  1220. },
  1221. setAllowsCreator(allowsCreator) {
  1222. return { $set: { allowsCreator } };
  1223. },
  1224. setAllowsMembers(allowsMembers) {
  1225. return { $set: { allowsMembers } };
  1226. },
  1227. setAllowsChecklists(allowsChecklists) {
  1228. return { $set: { allowsChecklists } };
  1229. },
  1230. setAllowsAssignee(allowsAssignee) {
  1231. return { $set: { allowsAssignee } };
  1232. },
  1233. setAllowsAssignedBy(allowsAssignedBy) {
  1234. return { $set: { allowsAssignedBy } };
  1235. },
  1236. setAllowsRequestedBy(allowsRequestedBy) {
  1237. return { $set: { allowsRequestedBy } };
  1238. },
  1239. setAllowsCardSortingByNumber(allowsCardSortingByNumber) {
  1240. return { $set: { allowsCardSortingByNumber } };
  1241. },
  1242. setAllowsAttachments(allowsAttachments) {
  1243. return { $set: { allowsAttachments } };
  1244. },
  1245. setAllowsLabels(allowsLabels) {
  1246. return { $set: { allowsLabels } };
  1247. },
  1248. setAllowsComments(allowsComments) {
  1249. return { $set: { allowsComments } };
  1250. },
  1251. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1252. return { $set: { allowsDescriptionTitle } };
  1253. },
  1254. setAllowsCardNumber(allowsCardNumber) {
  1255. return { $set: { allowsCardNumber } };
  1256. },
  1257. setAllowsDescriptionText(allowsDescriptionText) {
  1258. return { $set: { allowsDescriptionText } };
  1259. },
  1260. setAllowsActivities(allowsActivities) {
  1261. return { $set: { allowsActivities } };
  1262. },
  1263. setAllowsReceivedDate(allowsReceivedDate) {
  1264. return { $set: { allowsReceivedDate } };
  1265. },
  1266. setAllowsStartDate(allowsStartDate) {
  1267. return { $set: { allowsStartDate } };
  1268. },
  1269. setAllowsEndDate(allowsEndDate) {
  1270. return { $set: { allowsEndDate } };
  1271. },
  1272. setAllowsDueDate(allowsDueDate) {
  1273. return { $set: { allowsDueDate } };
  1274. },
  1275. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1276. return { $set: { subtasksDefaultBoardId } };
  1277. },
  1278. setSubtasksDefaultListId(subtasksDefaultListId) {
  1279. return { $set: { subtasksDefaultListId } };
  1280. },
  1281. setPresentParentTask(presentParentTask) {
  1282. return { $set: { presentParentTask } };
  1283. },
  1284. move(sortIndex) {
  1285. return { $set: { sort: sortIndex } };
  1286. },
  1287. });
  1288. function boardRemover(userId, doc) {
  1289. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1290. element => {
  1291. element.remove({ boardId: doc._id });
  1292. },
  1293. );
  1294. }
  1295. Boards.uniqueTitle = title => {
  1296. const m = title.match(
  1297. new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
  1298. );
  1299. const base = escapeForRegex(m.groups.title);
  1300. let num = 0;
  1301. Boards.find({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) }).forEach(
  1302. board => {
  1303. const m = board.title.match(
  1304. new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
  1305. );
  1306. if (m) {
  1307. const n = parseInt(m.groups.num, 10);
  1308. num = num < n ? n : num;
  1309. }
  1310. },
  1311. );
  1312. if (num > 0) {
  1313. return `${base} [${num + 1}]`;
  1314. }
  1315. return title;
  1316. };
  1317. Boards.userSearch = (
  1318. userId,
  1319. selector = {},
  1320. projection = {},
  1321. // includeArchived = false,
  1322. ) => {
  1323. // if (!includeArchived) {
  1324. // selector.archived = false;
  1325. // }
  1326. selector.$or = [{ permission: 'public' }];
  1327. if (userId) {
  1328. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1329. }
  1330. return Boards.find(selector, projection);
  1331. };
  1332. Boards.userBoards = (
  1333. userId,
  1334. archived = false,
  1335. selector = {},
  1336. projection = {},
  1337. ) => {
  1338. const user = Users.findOne(userId);
  1339. if (!user) {
  1340. return [];
  1341. }
  1342. if (typeof archived === 'boolean') {
  1343. selector.archived = archived;
  1344. }
  1345. if (!selector.type) {
  1346. selector.type = 'board';
  1347. }
  1348. selector.$or = [
  1349. { permission: 'public' },
  1350. { members: { $elemMatch: { userId, isActive: true } } },
  1351. { orgs: { $elemMatch: { orgId: { $in: user.orgIds() }, isActive: true } } },
  1352. { teams: { $elemMatch: { teamId: { $in: user.teamIds() }, isActive: true } } },
  1353. ];
  1354. return Boards.find(selector, projection);
  1355. };
  1356. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1357. return Boards.userBoards(userId, archived, selector, {
  1358. fields: { _id: 1 },
  1359. }).map(board => {
  1360. return board._id;
  1361. });
  1362. };
  1363. Boards.colorMap = () => {
  1364. const colors = {};
  1365. for (const color of Boards.labelColors()) {
  1366. colors[TAPi18n.__(`color-${color}`)] = color;
  1367. }
  1368. return colors;
  1369. };
  1370. Boards.labelColors = () => {
  1371. return ALLOWED_COLORS;
  1372. };
  1373. if (Meteor.isServer) {
  1374. Boards.allow({
  1375. insert: Meteor.userId,
  1376. update: allowIsBoardAdmin,
  1377. remove: allowIsBoardAdmin,
  1378. fetch: ['members'],
  1379. });
  1380. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1381. Boards.allow({
  1382. update(userId, board, fieldNames) {
  1383. return _.contains(fieldNames, 'sort');
  1384. },
  1385. fetch: [],
  1386. });
  1387. // The number of users that have starred this board is managed by trusted code
  1388. // and the user is not allowed to update it
  1389. Boards.deny({
  1390. update(userId, board, fieldNames) {
  1391. return _.contains(fieldNames, 'stars');
  1392. },
  1393. fetch: [],
  1394. });
  1395. // We can't remove a member if it is the last administrator
  1396. Boards.deny({
  1397. update(userId, doc, fieldNames, modifier) {
  1398. if (!_.contains(fieldNames, 'members')) return false;
  1399. // We only care in case of a $pull operation, ie remove a member
  1400. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1401. // If there is more than one admin, it's ok to remove anyone
  1402. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1403. .length;
  1404. if (nbAdmins > 1) return false;
  1405. // If all the previous conditions were verified, we can't remove
  1406. // a user if it's an admin
  1407. const removedMemberId = modifier.$pull.members.userId;
  1408. return Boolean(
  1409. _.findWhere(doc.members, {
  1410. userId: removedMemberId,
  1411. isAdmin: true,
  1412. }),
  1413. );
  1414. },
  1415. fetch: ['members'],
  1416. });
  1417. Meteor.methods({
  1418. quitBoard(boardId) {
  1419. check(boardId, String);
  1420. const board = Boards.findOne(boardId);
  1421. if (board) {
  1422. const userId = Meteor.userId();
  1423. const index = board.memberIndex(userId);
  1424. if (index >= 0) {
  1425. board.removeMember(userId);
  1426. return true;
  1427. } else throw new Meteor.Error('error-board-notAMember');
  1428. } else throw new Meteor.Error('error-board-doesNotExist');
  1429. },
  1430. acceptInvite(boardId) {
  1431. check(boardId, String);
  1432. const board = Boards.findOne(boardId);
  1433. if (!board) {
  1434. throw new Meteor.Error('error-board-doesNotExist');
  1435. }
  1436. Meteor.users.update(Meteor.userId(), {
  1437. $pull: {
  1438. 'profile.invitedBoards': boardId,
  1439. },
  1440. });
  1441. },
  1442. myLabelNames() {
  1443. let names = [];
  1444. Boards.userBoards(Meteor.userId()).forEach(board => {
  1445. // Only return labels when they exist.
  1446. if (board.labels !== undefined) {
  1447. names = names.concat(
  1448. board.labels
  1449. .filter(label => !!label.name)
  1450. .map(label => {
  1451. return label.name;
  1452. }),
  1453. );
  1454. } else {
  1455. return [];
  1456. }
  1457. });
  1458. return _.uniq(names).sort();
  1459. },
  1460. myBoardNames() {
  1461. return _.uniq(
  1462. Boards.userBoards(Meteor.userId()).map(board => {
  1463. return board.title;
  1464. }),
  1465. ).sort();
  1466. },
  1467. });
  1468. Meteor.methods({
  1469. archiveBoard(boardId) {
  1470. check(boardId, String);
  1471. const board = Boards.findOne(boardId);
  1472. if (board) {
  1473. const userId = Meteor.userId();
  1474. const index = board.memberIndex(userId);
  1475. if (index >= 0) {
  1476. board.archive();
  1477. return true;
  1478. } else throw new Meteor.Error('error-board-notAMember');
  1479. } else throw new Meteor.Error('error-board-doesNotExist');
  1480. },
  1481. setBoardOrgs(boardOrgsArray, currBoardId){
  1482. check(boardOrgsArray, Array);
  1483. check(currBoardId, String);
  1484. Boards.update(currBoardId, {
  1485. $set: {
  1486. orgs: boardOrgsArray,
  1487. },
  1488. });
  1489. },
  1490. setBoardTeams(boardTeamsArray, membersArray, currBoardId){
  1491. check(boardTeamsArray, Array);
  1492. check(membersArray, Array);
  1493. check(currBoardId, String);
  1494. Boards.update(currBoardId, {
  1495. $set: {
  1496. members: membersArray,
  1497. teams: boardTeamsArray,
  1498. },
  1499. });
  1500. },
  1501. });
  1502. }
  1503. // Insert new board at last position in sort order.
  1504. Boards.before.insert((userId, doc) => {
  1505. const lastBoard = Boards.findOne(
  1506. { sort: { $exists: true } },
  1507. { sort: { sort: -1 } },
  1508. );
  1509. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1510. doc.sort = lastBoard.sort + 1;
  1511. }
  1512. });
  1513. if (Meteor.isServer) {
  1514. // Let MongoDB ensure that a member is not included twice in the same board
  1515. Meteor.startup(() => {
  1516. Boards._collection._ensureIndex({ modifiedAt: -1 });
  1517. Boards._collection._ensureIndex(
  1518. {
  1519. _id: 1,
  1520. 'members.userId': 1,
  1521. },
  1522. { unique: true },
  1523. );
  1524. Boards._collection._ensureIndex({ 'members.userId': 1 });
  1525. });
  1526. // Genesis: the first activity of the newly created board
  1527. Boards.after.insert((userId, doc) => {
  1528. Activities.insert({
  1529. userId,
  1530. type: 'board',
  1531. activityTypeId: doc._id,
  1532. activityType: 'createBoard',
  1533. boardId: doc._id,
  1534. });
  1535. });
  1536. // If the user remove one label from a board, we cant to remove reference of
  1537. // this label in any card of this board.
  1538. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1539. if (
  1540. !_.contains(fieldNames, 'labels') ||
  1541. !modifier.$pull ||
  1542. !modifier.$pull.labels ||
  1543. !modifier.$pull.labels._id
  1544. ) {
  1545. return;
  1546. }
  1547. const removedLabelId = modifier.$pull.labels._id;
  1548. Cards.update(
  1549. { boardId: doc._id },
  1550. {
  1551. $pull: {
  1552. labelIds: removedLabelId,
  1553. },
  1554. },
  1555. { multi: true },
  1556. );
  1557. });
  1558. const foreachRemovedMember = (doc, modifier, callback) => {
  1559. Object.keys(modifier).forEach(set => {
  1560. if (modifier[set] !== false) {
  1561. return;
  1562. }
  1563. const parts = set.split('.');
  1564. if (
  1565. parts.length === 3 &&
  1566. parts[0] === 'members' &&
  1567. parts[2] === 'isActive'
  1568. ) {
  1569. callback(doc.members[parts[1]].userId);
  1570. }
  1571. });
  1572. };
  1573. // Remove a member from all objects of the board before leaving the board
  1574. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1575. if (!_.contains(fieldNames, 'members')) {
  1576. return;
  1577. }
  1578. if (modifier.$set) {
  1579. const boardId = doc._id;
  1580. foreachRemovedMember(doc, modifier.$set, memberId => {
  1581. Cards.update(
  1582. { boardId },
  1583. {
  1584. $pull: {
  1585. members: memberId,
  1586. watchers: memberId,
  1587. },
  1588. },
  1589. { multi: true },
  1590. );
  1591. Lists.update(
  1592. { boardId },
  1593. {
  1594. $pull: {
  1595. watchers: memberId,
  1596. },
  1597. },
  1598. { multi: true },
  1599. );
  1600. const board = Boards._transform(doc);
  1601. board.setWatcher(memberId, false);
  1602. // Remove board from users starred list
  1603. if (!board.isPublic()) {
  1604. Users.update(memberId, {
  1605. $pull: {
  1606. 'profile.starredBoards': boardId,
  1607. },
  1608. });
  1609. }
  1610. });
  1611. }
  1612. });
  1613. Boards.before.remove((userId, doc) => {
  1614. boardRemover(userId, doc);
  1615. // Add removeBoard activity to keep it
  1616. Activities.insert({
  1617. userId,
  1618. type: 'board',
  1619. activityTypeId: doc._id,
  1620. activityType: 'removeBoard',
  1621. boardId: doc._id,
  1622. });
  1623. });
  1624. // Add a new activity if we add or remove a member to the board
  1625. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1626. if (!_.contains(fieldNames, 'members')) {
  1627. return;
  1628. }
  1629. // Say hello to the new member
  1630. if (modifier.$push && modifier.$push.members) {
  1631. const memberId = modifier.$push.members.userId;
  1632. Activities.insert({
  1633. userId,
  1634. memberId,
  1635. type: 'member',
  1636. activityType: 'addBoardMember',
  1637. boardId: doc._id,
  1638. });
  1639. }
  1640. // Say goodbye to the former member
  1641. if (modifier.$set) {
  1642. foreachRemovedMember(doc, modifier.$set, memberId => {
  1643. Activities.insert({
  1644. userId,
  1645. memberId,
  1646. type: 'member',
  1647. activityType: 'removeBoardMember',
  1648. boardId: doc._id,
  1649. });
  1650. });
  1651. }
  1652. });
  1653. }
  1654. //BOARDS REST API
  1655. if (Meteor.isServer) {
  1656. /**
  1657. * @operation get_boards_from_user
  1658. * @summary Get all boards attached to a user
  1659. *
  1660. * @param {string} userId the ID of the user to retrieve the data
  1661. * @return_type [{_id: string,
  1662. title: string}]
  1663. */
  1664. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1665. try {
  1666. Authentication.checkLoggedIn(req.userId);
  1667. const paramUserId = req.params.userId;
  1668. // A normal user should be able to see their own boards,
  1669. // admins can access boards of any user
  1670. Authentication.checkAdminOrCondition(
  1671. req.userId,
  1672. req.userId === paramUserId,
  1673. );
  1674. const data = Boards.find(
  1675. {
  1676. archived: false,
  1677. 'members.userId': paramUserId,
  1678. },
  1679. {
  1680. sort: { sort: 1 /* boards default sorting */ },
  1681. },
  1682. ).map(function(board) {
  1683. return {
  1684. _id: board._id,
  1685. title: board.title,
  1686. };
  1687. });
  1688. JsonRoutes.sendResult(res, { code: 200, data });
  1689. } catch (error) {
  1690. JsonRoutes.sendResult(res, {
  1691. code: 200,
  1692. data: error,
  1693. });
  1694. }
  1695. });
  1696. /**
  1697. * @operation get_public_boards
  1698. * @summary Get all public boards
  1699. *
  1700. * @return_type [{_id: string,
  1701. title: string}]
  1702. */
  1703. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1704. try {
  1705. Authentication.checkUserId(req.userId);
  1706. JsonRoutes.sendResult(res, {
  1707. code: 200,
  1708. data: Boards.find(
  1709. { permission: 'public' },
  1710. {
  1711. sort: { sort: 1 /* boards default sorting */ },
  1712. },
  1713. ).map(function(doc) {
  1714. return {
  1715. _id: doc._id,
  1716. title: doc.title,
  1717. };
  1718. }),
  1719. });
  1720. } catch (error) {
  1721. JsonRoutes.sendResult(res, {
  1722. code: 200,
  1723. data: error,
  1724. });
  1725. }
  1726. });
  1727. /**
  1728. * @operation get_boards_count
  1729. * @summary Get public and private boards count
  1730. *
  1731. * @return_type {private: integer, public: integer}
  1732. */
  1733. JsonRoutes.add('GET', '/api/boards_count', function(req, res) {
  1734. try {
  1735. Authentication.checkUserId(req.userId);
  1736. JsonRoutes.sendResult(res, {
  1737. code: 200,
  1738. data: {
  1739. private: Boards.find({ permission: 'private' }).count(),
  1740. public: Boards.find({ permission: 'public' }).count(),
  1741. },
  1742. });
  1743. } catch (error) {
  1744. JsonRoutes.sendResult(res, {
  1745. code: 200,
  1746. data: error,
  1747. });
  1748. }
  1749. });
  1750. /**
  1751. * @operation get_board
  1752. * @summary Get the board with that particular ID
  1753. *
  1754. * @param {string} boardId the ID of the board to retrieve the data
  1755. * @return_type Boards
  1756. */
  1757. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1758. try {
  1759. Authentication.checkUserId(req.userId);
  1760. const id = req.params.boardId;
  1761. JsonRoutes.sendResult(res, {
  1762. code: 200,
  1763. data: Boards.findOne({ _id: id }),
  1764. });
  1765. } catch (error) {
  1766. JsonRoutes.sendResult(res, {
  1767. code: 200,
  1768. data: error,
  1769. });
  1770. }
  1771. });
  1772. /**
  1773. * @operation new_board
  1774. * @summary Create a board
  1775. *
  1776. * @description This allows to create a board.
  1777. *
  1778. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1779. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1780. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1781. *
  1782. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1783. *
  1784. * @param {string} title the new title of the board
  1785. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1786. * (Not username or email)
  1787. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1788. * @param {boolean} [isActive] is the board active (default true)
  1789. * @param {boolean} [isNoComments] disable comments (default false)
  1790. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1791. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1792. * @param {string} [permission] "private" board <== Set to "public" if you
  1793. * want public Wekan board
  1794. * @param {string} [color] the color of the board
  1795. *
  1796. * @return_type {_id: string,
  1797. defaultSwimlaneId: string}
  1798. */
  1799. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1800. try {
  1801. Authentication.checkUserId(req.userId);
  1802. const id = Boards.insert({
  1803. title: req.body.title,
  1804. members: [
  1805. {
  1806. userId: req.body.owner,
  1807. isAdmin: req.body.isAdmin || true,
  1808. isActive: req.body.isActive || true,
  1809. isNoComments: req.body.isNoComments || false,
  1810. isCommentOnly: req.body.isCommentOnly || false,
  1811. isWorker: req.body.isWorker || false,
  1812. },
  1813. ],
  1814. permission: req.body.permission || 'private',
  1815. color: req.body.color || 'belize',
  1816. });
  1817. const swimlaneId = Swimlanes.insert({
  1818. title: TAPi18n.__('default'),
  1819. boardId: id,
  1820. });
  1821. JsonRoutes.sendResult(res, {
  1822. code: 200,
  1823. data: {
  1824. _id: id,
  1825. defaultSwimlaneId: swimlaneId,
  1826. },
  1827. });
  1828. } catch (error) {
  1829. JsonRoutes.sendResult(res, {
  1830. code: 200,
  1831. data: error,
  1832. });
  1833. }
  1834. });
  1835. /**
  1836. * @operation delete_board
  1837. * @summary Delete a board
  1838. *
  1839. * @param {string} boardId the ID of the board
  1840. */
  1841. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1842. try {
  1843. Authentication.checkUserId(req.userId);
  1844. const id = req.params.boardId;
  1845. Boards.remove({ _id: id });
  1846. JsonRoutes.sendResult(res, {
  1847. code: 200,
  1848. data: {
  1849. _id: id,
  1850. },
  1851. });
  1852. } catch (error) {
  1853. JsonRoutes.sendResult(res, {
  1854. code: 200,
  1855. data: error,
  1856. });
  1857. }
  1858. });
  1859. /**
  1860. * @operation add_board_label
  1861. * @summary Add a label to a board
  1862. *
  1863. * @description If the board doesn't have the name/color label, this function
  1864. * adds the label to the board.
  1865. *
  1866. * @param {string} boardId the board
  1867. * @param {string} color the color of the new label
  1868. * @param {string} name the name of the new label
  1869. *
  1870. * @return_type string
  1871. */
  1872. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1873. Authentication.checkUserId(req.userId);
  1874. const id = req.params.boardId;
  1875. try {
  1876. if (req.body.hasOwnProperty('label')) {
  1877. const board = Boards.findOne({ _id: id });
  1878. const color = req.body.label.color;
  1879. const name = req.body.label.name;
  1880. const labelId = Random.id(6);
  1881. if (!board.getLabel(name, color)) {
  1882. Boards.direct.update(
  1883. { _id: id },
  1884. { $push: { labels: { _id: labelId, name, color } } },
  1885. );
  1886. JsonRoutes.sendResult(res, {
  1887. code: 200,
  1888. data: labelId,
  1889. });
  1890. } else {
  1891. JsonRoutes.sendResult(res, {
  1892. code: 200,
  1893. });
  1894. }
  1895. }
  1896. } catch (error) {
  1897. JsonRoutes.sendResult(res, {
  1898. data: error,
  1899. });
  1900. }
  1901. });
  1902. /**
  1903. * @operation set_board_member_permission
  1904. * @tag Users
  1905. * @summary Change the permission of a member of a board
  1906. *
  1907. * @param {string} boardId the ID of the board that we are changing
  1908. * @param {string} memberId the ID of the user to change permissions
  1909. * @param {boolean} isAdmin admin capability
  1910. * @param {boolean} isNoComments NoComments capability
  1911. * @param {boolean} isCommentOnly CommentsOnly capability
  1912. * @param {boolean} isWorker Worker capability
  1913. */
  1914. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1915. req,
  1916. res,
  1917. ) {
  1918. try {
  1919. Authentication.checkUserId(req.userId);
  1920. const boardId = req.params.boardId;
  1921. const memberId = req.params.memberId;
  1922. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  1923. const board = Boards.findOne({ _id: boardId });
  1924. function isTrue(data) {
  1925. try {
  1926. return data.toLowerCase() === 'true';
  1927. } catch (error) {
  1928. return data;
  1929. }
  1930. }
  1931. const query = board.setMemberPermission(
  1932. memberId,
  1933. isTrue(isAdmin),
  1934. isTrue(isNoComments),
  1935. isTrue(isCommentOnly),
  1936. isTrue(isWorker),
  1937. req.userId,
  1938. );
  1939. JsonRoutes.sendResult(res, {
  1940. code: 200,
  1941. data: query,
  1942. });
  1943. } catch (error) {
  1944. JsonRoutes.sendResult(res, {
  1945. code: 200,
  1946. data: error,
  1947. });
  1948. }
  1949. });
  1950. //ATTACHMENTS REST API
  1951. /**
  1952. * @operation get_board_attachments
  1953. * @summary Get the list of attachments of a board
  1954. *
  1955. * @param {string} boardId the board ID
  1956. * @return_type [{attachmentId: string,
  1957. * attachmentName: string,
  1958. * attachmentType: string,
  1959. * cardId: string,
  1960. * listId: string,
  1961. * swimlaneId: string}]
  1962. */
  1963. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  1964. Authentication.checkUserId(req.userId);
  1965. const paramBoardId = req.params.boardId;
  1966. JsonRoutes.sendResult(res, {
  1967. code: 200,
  1968. data: Attachments.files
  1969. .find({ boardId: paramBoardId }, { fields: { boardId: 0 } })
  1970. .map(function(doc) {
  1971. return {
  1972. attachmentId: doc._id,
  1973. attachmentName: doc.original.name,
  1974. attachmentType: doc.original.type,
  1975. url: FlowRouter.url(doc.url()),
  1976. urlDownload: `${FlowRouter.url(doc.url())}?download=true&token=`,
  1977. cardId: doc.cardId,
  1978. listId: doc.listId,
  1979. swimlaneId: doc.swimlaneId,
  1980. };
  1981. }),
  1982. });
  1983. });
  1984. }
  1985. export default Boards;