boards.js 47 KB

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