boards.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  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. if (num > 0) {
  1162. return `${base} [${num + 1}]`;
  1163. }
  1164. return title;
  1165. };
  1166. Boards.userSearch = (
  1167. userId,
  1168. selector = {},
  1169. projection = {},
  1170. // includeArchived = false,
  1171. ) => {
  1172. // if (!includeArchived) {
  1173. // selector.archived = false;
  1174. // }
  1175. selector.$or = [{ permission: 'public' }];
  1176. if (userId) {
  1177. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1178. }
  1179. return Boards.find(selector, projection);
  1180. };
  1181. Boards.userBoards = (userId, archived = false, selector = {}) => {
  1182. if (typeof archived === 'boolean') {
  1183. selector.archived = archived;
  1184. }
  1185. selector.$or = [{ permission: 'public' }];
  1186. if (userId) {
  1187. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1188. }
  1189. return Boards.find(selector);
  1190. };
  1191. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1192. return Boards.userBoards(userId, archived, selector).map(board => {
  1193. return board._id;
  1194. });
  1195. };
  1196. Boards.colorMap = () => {
  1197. const colors = {};
  1198. for (const color of Boards.labelColors()) {
  1199. colors[TAPi18n.__(`color-${color}`)] = color;
  1200. }
  1201. return colors;
  1202. };
  1203. Boards.labelColors = () => {
  1204. return _.clone(Boards.simpleSchema()._schema['labels.$.color'].allowedValues);
  1205. };
  1206. if (Meteor.isServer) {
  1207. Boards.allow({
  1208. insert: Meteor.userId,
  1209. update: allowIsBoardAdmin,
  1210. remove: allowIsBoardAdmin,
  1211. fetch: ['members'],
  1212. });
  1213. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1214. Boards.allow({
  1215. update(userId, board, fieldNames) {
  1216. return _.contains(fieldNames, 'sort');
  1217. },
  1218. fetch: [],
  1219. });
  1220. // The number of users that have starred this board is managed by trusted code
  1221. // and the user is not allowed to update it
  1222. Boards.deny({
  1223. update(userId, board, fieldNames) {
  1224. return _.contains(fieldNames, 'stars');
  1225. },
  1226. fetch: [],
  1227. });
  1228. // We can't remove a member if it is the last administrator
  1229. Boards.deny({
  1230. update(userId, doc, fieldNames, modifier) {
  1231. if (!_.contains(fieldNames, 'members')) return false;
  1232. // We only care in case of a $pull operation, ie remove a member
  1233. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1234. // If there is more than one admin, it's ok to remove anyone
  1235. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1236. .length;
  1237. if (nbAdmins > 1) return false;
  1238. // If all the previous conditions were verified, we can't remove
  1239. // a user if it's an admin
  1240. const removedMemberId = modifier.$pull.members.userId;
  1241. return Boolean(
  1242. _.findWhere(doc.members, {
  1243. userId: removedMemberId,
  1244. isAdmin: true,
  1245. }),
  1246. );
  1247. },
  1248. fetch: ['members'],
  1249. });
  1250. Meteor.methods({
  1251. quitBoard(boardId) {
  1252. check(boardId, String);
  1253. const board = Boards.findOne(boardId);
  1254. if (board) {
  1255. const userId = Meteor.userId();
  1256. const index = board.memberIndex(userId);
  1257. if (index >= 0) {
  1258. board.removeMember(userId);
  1259. return true;
  1260. } else throw new Meteor.Error('error-board-notAMember');
  1261. } else throw new Meteor.Error('error-board-doesNotExist');
  1262. },
  1263. acceptInvite(boardId) {
  1264. check(boardId, String);
  1265. const board = Boards.findOne(boardId);
  1266. if (!board) {
  1267. throw new Meteor.Error('error-board-doesNotExist');
  1268. }
  1269. Meteor.users.update(Meteor.userId(), {
  1270. $pull: {
  1271. 'profile.invitedBoards': boardId,
  1272. },
  1273. });
  1274. },
  1275. myLabelNames() {
  1276. let names = [];
  1277. Boards.userBoards(Meteor.userId(), false, { type: 'board' }).forEach(
  1278. board => {
  1279. names = names.concat(
  1280. board.labels
  1281. .filter(label => !!label.name)
  1282. .map(label => {
  1283. return label.name;
  1284. }),
  1285. );
  1286. },
  1287. );
  1288. return _.uniq(names).sort();
  1289. },
  1290. myBoardNames() {
  1291. return _.uniq(
  1292. Boards.userBoards(Meteor.userId()).map(board => {
  1293. return board.title;
  1294. }),
  1295. ).sort();
  1296. },
  1297. });
  1298. Meteor.methods({
  1299. archiveBoard(boardId) {
  1300. check(boardId, String);
  1301. const board = Boards.findOne(boardId);
  1302. if (board) {
  1303. const userId = Meteor.userId();
  1304. const index = board.memberIndex(userId);
  1305. if (index >= 0) {
  1306. board.archive();
  1307. return true;
  1308. } else throw new Meteor.Error('error-board-notAMember');
  1309. } else throw new Meteor.Error('error-board-doesNotExist');
  1310. },
  1311. });
  1312. }
  1313. // Insert new board at last position in sort order.
  1314. Boards.before.insert((userId, doc) => {
  1315. const lastBoard = Boards.findOne(
  1316. { sort: { $exists: true } },
  1317. { sort: { sort: -1 } },
  1318. );
  1319. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1320. doc.sort = lastBoard.sort + 1;
  1321. }
  1322. });
  1323. if (Meteor.isServer) {
  1324. // Let MongoDB ensure that a member is not included twice in the same board
  1325. Meteor.startup(() => {
  1326. Boards._collection._ensureIndex({ modifiedAt: -1 });
  1327. Boards._collection._ensureIndex(
  1328. {
  1329. _id: 1,
  1330. 'members.userId': 1,
  1331. },
  1332. { unique: true },
  1333. );
  1334. Boards._collection._ensureIndex({ 'members.userId': 1 });
  1335. });
  1336. // Genesis: the first activity of the newly created board
  1337. Boards.after.insert((userId, doc) => {
  1338. Activities.insert({
  1339. userId,
  1340. type: 'board',
  1341. activityTypeId: doc._id,
  1342. activityType: 'createBoard',
  1343. boardId: doc._id,
  1344. });
  1345. });
  1346. // If the user remove one label from a board, we cant to remove reference of
  1347. // this label in any card of this board.
  1348. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1349. if (
  1350. !_.contains(fieldNames, 'labels') ||
  1351. !modifier.$pull ||
  1352. !modifier.$pull.labels ||
  1353. !modifier.$pull.labels._id
  1354. ) {
  1355. return;
  1356. }
  1357. const removedLabelId = modifier.$pull.labels._id;
  1358. Cards.update(
  1359. { boardId: doc._id },
  1360. {
  1361. $pull: {
  1362. labelIds: removedLabelId,
  1363. },
  1364. },
  1365. { multi: true },
  1366. );
  1367. });
  1368. const foreachRemovedMember = (doc, modifier, callback) => {
  1369. Object.keys(modifier).forEach(set => {
  1370. if (modifier[set] !== false) {
  1371. return;
  1372. }
  1373. const parts = set.split('.');
  1374. if (
  1375. parts.length === 3 &&
  1376. parts[0] === 'members' &&
  1377. parts[2] === 'isActive'
  1378. ) {
  1379. callback(doc.members[parts[1]].userId);
  1380. }
  1381. });
  1382. };
  1383. // Remove a member from all objects of the board before leaving the board
  1384. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1385. if (!_.contains(fieldNames, 'members')) {
  1386. return;
  1387. }
  1388. if (modifier.$set) {
  1389. const boardId = doc._id;
  1390. foreachRemovedMember(doc, modifier.$set, memberId => {
  1391. Cards.update(
  1392. { boardId },
  1393. {
  1394. $pull: {
  1395. members: memberId,
  1396. watchers: memberId,
  1397. },
  1398. },
  1399. { multi: true },
  1400. );
  1401. Lists.update(
  1402. { boardId },
  1403. {
  1404. $pull: {
  1405. watchers: memberId,
  1406. },
  1407. },
  1408. { multi: true },
  1409. );
  1410. const board = Boards._transform(doc);
  1411. board.setWatcher(memberId, false);
  1412. // Remove board from users starred list
  1413. if (!board.isPublic()) {
  1414. Users.update(memberId, {
  1415. $pull: {
  1416. 'profile.starredBoards': boardId,
  1417. },
  1418. });
  1419. }
  1420. });
  1421. }
  1422. });
  1423. Boards.before.remove((userId, doc) => {
  1424. boardRemover(userId, doc);
  1425. // Add removeBoard activity to keep it
  1426. Activities.insert({
  1427. userId,
  1428. type: 'board',
  1429. activityTypeId: doc._id,
  1430. activityType: 'removeBoard',
  1431. boardId: doc._id,
  1432. });
  1433. });
  1434. // Add a new activity if we add or remove a member to the board
  1435. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1436. if (!_.contains(fieldNames, 'members')) {
  1437. return;
  1438. }
  1439. // Say hello to the new member
  1440. if (modifier.$push && modifier.$push.members) {
  1441. const memberId = modifier.$push.members.userId;
  1442. Activities.insert({
  1443. userId,
  1444. memberId,
  1445. type: 'member',
  1446. activityType: 'addBoardMember',
  1447. boardId: doc._id,
  1448. });
  1449. }
  1450. // Say goodbye to the former member
  1451. if (modifier.$set) {
  1452. foreachRemovedMember(doc, modifier.$set, memberId => {
  1453. Activities.insert({
  1454. userId,
  1455. memberId,
  1456. type: 'member',
  1457. activityType: 'removeBoardMember',
  1458. boardId: doc._id,
  1459. });
  1460. });
  1461. }
  1462. });
  1463. }
  1464. //BOARDS REST API
  1465. if (Meteor.isServer) {
  1466. /**
  1467. * @operation get_boards_from_user
  1468. * @summary Get all boards attached to a user
  1469. *
  1470. * @param {string} userId the ID of the user to retrieve the data
  1471. * @return_type [{_id: string,
  1472. title: string}]
  1473. */
  1474. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1475. try {
  1476. Authentication.checkLoggedIn(req.userId);
  1477. const paramUserId = req.params.userId;
  1478. // A normal user should be able to see their own boards,
  1479. // admins can access boards of any user
  1480. Authentication.checkAdminOrCondition(
  1481. req.userId,
  1482. req.userId === paramUserId,
  1483. );
  1484. const data = Boards.find(
  1485. {
  1486. archived: false,
  1487. 'members.userId': paramUserId,
  1488. },
  1489. {
  1490. sort: { sort: 1 /* boards default sorting */ },
  1491. },
  1492. ).map(function(board) {
  1493. return {
  1494. _id: board._id,
  1495. title: board.title,
  1496. };
  1497. });
  1498. JsonRoutes.sendResult(res, { code: 200, data });
  1499. } catch (error) {
  1500. JsonRoutes.sendResult(res, {
  1501. code: 200,
  1502. data: error,
  1503. });
  1504. }
  1505. });
  1506. /**
  1507. * @operation get_public_boards
  1508. * @summary Get all public boards
  1509. *
  1510. * @return_type [{_id: string,
  1511. title: string}]
  1512. */
  1513. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1514. try {
  1515. Authentication.checkUserId(req.userId);
  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. Authentication.checkUserId(req.userId);
  1684. const id = req.params.boardId;
  1685. try {
  1686. if (req.body.hasOwnProperty('label')) {
  1687. const board = Boards.findOne({ _id: id });
  1688. const color = req.body.label.color;
  1689. const name = req.body.label.name;
  1690. const labelId = Random.id(6);
  1691. if (!board.getLabel(name, color)) {
  1692. Boards.direct.update(
  1693. { _id: id },
  1694. { $push: { labels: { _id: labelId, name, color } } },
  1695. );
  1696. JsonRoutes.sendResult(res, {
  1697. code: 200,
  1698. data: labelId,
  1699. });
  1700. } else {
  1701. JsonRoutes.sendResult(res, {
  1702. code: 200,
  1703. });
  1704. }
  1705. }
  1706. } catch (error) {
  1707. JsonRoutes.sendResult(res, {
  1708. data: error,
  1709. });
  1710. }
  1711. });
  1712. /**
  1713. * @operation set_board_member_permission
  1714. * @tag Users
  1715. * @summary Change the permission of a member of a board
  1716. *
  1717. * @param {string} boardId the ID of the board that we are changing
  1718. * @param {string} memberId the ID of the user to change permissions
  1719. * @param {boolean} isAdmin admin capability
  1720. * @param {boolean} isNoComments NoComments capability
  1721. * @param {boolean} isCommentOnly CommentsOnly capability
  1722. * @param {boolean} isWorker Worker capability
  1723. */
  1724. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1725. req,
  1726. res,
  1727. ) {
  1728. try {
  1729. const boardId = req.params.boardId;
  1730. const memberId = req.params.memberId;
  1731. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  1732. Authentication.checkBoardAccess(req.userId, boardId);
  1733. const board = Boards.findOne({ _id: boardId });
  1734. function isTrue(data) {
  1735. try {
  1736. return data.toLowerCase() === 'true';
  1737. } catch (error) {
  1738. return data;
  1739. }
  1740. }
  1741. const query = board.setMemberPermission(
  1742. memberId,
  1743. isTrue(isAdmin),
  1744. isTrue(isNoComments),
  1745. isTrue(isCommentOnly),
  1746. isTrue(isWorker),
  1747. req.userId,
  1748. );
  1749. JsonRoutes.sendResult(res, {
  1750. code: 200,
  1751. data: query,
  1752. });
  1753. } catch (error) {
  1754. JsonRoutes.sendResult(res, {
  1755. code: 200,
  1756. data: error,
  1757. });
  1758. }
  1759. });
  1760. //ATTACHMENTS REST API
  1761. /**
  1762. * @operation get_board_attachments
  1763. * @summary Get the list of attachments of a board
  1764. *
  1765. * @param {string} boardId the board ID
  1766. * @return_type [{attachmentId: string,
  1767. * attachmentName: string,
  1768. * attachmentType: string,
  1769. * cardId: string,
  1770. * listId: string,
  1771. * swimlaneId: string}]
  1772. */
  1773. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  1774. const paramBoardId = req.params.boardId;
  1775. Authentication.checkBoardAccess(req.userId, paramBoardId);
  1776. JsonRoutes.sendResult(res, {
  1777. code: 200,
  1778. data: Attachments.files
  1779. .find({ boardId: paramBoardId }, { fields: { boardId: 0 } })
  1780. .map(function(doc) {
  1781. return {
  1782. attachmentId: doc._id,
  1783. attachmentName: doc.original.name,
  1784. attachmentType: doc.original.type,
  1785. url: FlowRouter.url(doc.url()),
  1786. urlDownload: `${FlowRouter.url(doc.url())}?download=true&token=`,
  1787. cardId: doc.cardId,
  1788. listId: doc.listId,
  1789. swimlaneId: doc.swimlaneId,
  1790. };
  1791. }),
  1792. });
  1793. });
  1794. }
  1795. export default Boards;