boards.js 46 KB

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