boards.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  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. originRelativeUrl() {
  730. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  731. },
  732. colorClass() {
  733. return `board-color-${this.color}`;
  734. },
  735. customFields() {
  736. return CustomFields.find(
  737. { boardIds: { $in: [this._id] } },
  738. { sort: { name: 1 } },
  739. );
  740. },
  741. // XXX currently mutations return no value so we have an issue when using addLabel in import
  742. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  743. pushLabel(name, color) {
  744. const _id = Random.id(6);
  745. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  746. return _id;
  747. },
  748. searchBoards(term) {
  749. check(term, Match.OneOf(String, null, undefined));
  750. const query = { boardId: this._id };
  751. query.type = 'cardType-linkedBoard';
  752. query.archived = false;
  753. const projection = { limit: 10, sort: { createdAt: -1 } };
  754. if (term) {
  755. const regex = new RegExp(term, 'i');
  756. query.$or = [{ title: regex }, { description: regex }];
  757. }
  758. return Cards.find(query, projection);
  759. },
  760. searchSwimlanes(term) {
  761. check(term, Match.OneOf(String, null, undefined));
  762. const query = { boardId: this._id };
  763. if (this.isTemplatesBoard()) {
  764. query.type = 'template-swimlane';
  765. query.archived = false;
  766. } else {
  767. query.type = { $nin: ['template-swimlane'] };
  768. }
  769. const projection = { limit: 10, sort: { createdAt: -1 } };
  770. if (term) {
  771. const regex = new RegExp(term, 'i');
  772. query.$or = [{ title: regex }, { description: regex }];
  773. }
  774. return Swimlanes.find(query, projection);
  775. },
  776. searchLists(term) {
  777. check(term, Match.OneOf(String, null, undefined));
  778. const query = { boardId: this._id };
  779. if (this.isTemplatesBoard()) {
  780. query.type = 'template-list';
  781. query.archived = false;
  782. } else {
  783. query.type = { $nin: ['template-list'] };
  784. }
  785. const projection = { limit: 10, sort: { createdAt: -1 } };
  786. if (term) {
  787. const regex = new RegExp(term, 'i');
  788. query.$or = [{ title: regex }, { description: regex }];
  789. }
  790. return Lists.find(query, projection);
  791. },
  792. searchCards(term, excludeLinked) {
  793. check(term, Match.OneOf(String, null, undefined));
  794. const query = { boardId: this._id };
  795. if (excludeLinked) {
  796. query.linkedId = null;
  797. }
  798. if (this.isTemplatesBoard()) {
  799. query.type = 'template-card';
  800. query.archived = false;
  801. } else {
  802. query.type = { $nin: ['template-card'] };
  803. }
  804. const projection = { limit: 10, sort: { createdAt: -1 } };
  805. if (term) {
  806. const regex = new RegExp(term, 'i');
  807. query.$or = [
  808. { title: regex },
  809. { description: regex },
  810. { customFields: { $elemMatch: { value: regex } } },
  811. ];
  812. }
  813. return Cards.find(query, projection);
  814. },
  815. // A board alwasy has another board where it deposits subtasks of thasks
  816. // that belong to itself.
  817. getDefaultSubtasksBoardId() {
  818. if (
  819. this.subtasksDefaultBoardId === null ||
  820. this.subtasksDefaultBoardId === undefined
  821. ) {
  822. this.subtasksDefaultBoardId = Boards.insert({
  823. title: `^${this.title}^`,
  824. permission: this.permission,
  825. members: this.members,
  826. color: this.color,
  827. description: TAPi18n.__('default-subtasks-board', {
  828. board: this.title,
  829. }),
  830. });
  831. Swimlanes.insert({
  832. title: TAPi18n.__('default'),
  833. boardId: this.subtasksDefaultBoardId,
  834. });
  835. Boards.update(this._id, {
  836. $set: {
  837. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  838. },
  839. });
  840. }
  841. return this.subtasksDefaultBoardId;
  842. },
  843. getDefaultSubtasksBoard() {
  844. return Boards.findOne(this.getDefaultSubtasksBoardId());
  845. },
  846. //Date Settings option such as received date, start date and so on.
  847. getDefaultDateSettingsBoardId() {
  848. if (
  849. this.dateSettingsDefaultBoardId === null ||
  850. this.dateSettingsDefaultBoardId === undefined
  851. ) {
  852. this.dateSettingsDefaultBoardId = Boards.insert({
  853. title: `^${this.title}^`,
  854. permission: this.permission,
  855. members: this.members,
  856. color: this.color,
  857. description: TAPi18n.__('default-dates-board', {
  858. board: this.title,
  859. }),
  860. });
  861. Swimlanes.insert({
  862. title: TAPi18n.__('default'),
  863. boardId: this.dateSettingsDefaultBoardId,
  864. });
  865. Boards.update(this._id, {
  866. $set: {
  867. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  868. },
  869. });
  870. }
  871. return this.dateSettingsDefaultBoardId;
  872. },
  873. getDefaultDateSettingsBoard() {
  874. return Boards.findOne(this.getDefaultDateSettingsBoardId());
  875. },
  876. getDefaultSubtasksListId() {
  877. if (
  878. this.subtasksDefaultListId === null ||
  879. this.subtasksDefaultListId === undefined
  880. ) {
  881. this.subtasksDefaultListId = Lists.insert({
  882. title: TAPi18n.__('queue'),
  883. boardId: this._id,
  884. });
  885. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  886. }
  887. return this.subtasksDefaultListId;
  888. },
  889. getDefaultSubtasksList() {
  890. return Lists.findOne(this.getDefaultSubtasksListId());
  891. },
  892. getDefaultDateSettingsListId() {
  893. if (
  894. this.dateSettingsDefaultListId === null ||
  895. this.dateSettingsDefaultListId === undefined
  896. ) {
  897. this.dateSettingsDefaultListId = Lists.insert({
  898. title: TAPi18n.__('queue'),
  899. boardId: this._id,
  900. });
  901. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  902. }
  903. return this.dateSettingsDefaultListId;
  904. },
  905. getDefaultDateSettingsList() {
  906. return Lists.findOne(this.getDefaultDateSettingsListId());
  907. },
  908. getDefaultSwimline() {
  909. let result = Swimlanes.findOne({ boardId: this._id });
  910. if (result === undefined) {
  911. Swimlanes.insert({
  912. title: TAPi18n.__('default'),
  913. boardId: this._id,
  914. });
  915. result = Swimlanes.findOne({ boardId: this._id });
  916. }
  917. return result;
  918. },
  919. cardsDueInBetween(start, end) {
  920. return Cards.find({
  921. boardId: this._id,
  922. dueAt: { $gte: start, $lte: end },
  923. });
  924. },
  925. cardsInInterval(start, end) {
  926. return Cards.find({
  927. boardId: this._id,
  928. $or: [
  929. {
  930. startAt: {
  931. $lte: start,
  932. },
  933. endAt: {
  934. $gte: start,
  935. },
  936. },
  937. {
  938. startAt: {
  939. $lte: end,
  940. },
  941. endAt: {
  942. $gte: end,
  943. },
  944. },
  945. {
  946. startAt: {
  947. $gte: start,
  948. },
  949. endAt: {
  950. $lte: end,
  951. },
  952. },
  953. ],
  954. });
  955. },
  956. isTemplateBoard() {
  957. return this.type === 'template-board';
  958. },
  959. isTemplatesBoard() {
  960. return this.type === 'template-container';
  961. },
  962. });
  963. Boards.mutations({
  964. archive() {
  965. return { $set: { archived: true, archivedAt: new Date() } };
  966. },
  967. restore() {
  968. return { $set: { archived: false } };
  969. },
  970. rename(title) {
  971. return { $set: { title } };
  972. },
  973. setDescription(description) {
  974. return { $set: { description } };
  975. },
  976. setColor(color) {
  977. return { $set: { color } };
  978. },
  979. setVisibility(visibility) {
  980. return { $set: { permission: visibility } };
  981. },
  982. addLabel(name, color) {
  983. // If label with the same name and color already exists we don't want to
  984. // create another one because they would be indistinguishable in the UI
  985. // (they would still have different `_id` but that is not exposed to the
  986. // user).
  987. if (!this.getLabel(name, color)) {
  988. const _id = Random.id(6);
  989. return { $push: { labels: { _id, name, color } } };
  990. }
  991. return {};
  992. },
  993. editLabel(labelId, name, color) {
  994. if (!this.getLabel(name, color)) {
  995. const labelIndex = this.labelIndex(labelId);
  996. return {
  997. $set: {
  998. [`labels.${labelIndex}.name`]: name,
  999. [`labels.${labelIndex}.color`]: color,
  1000. },
  1001. };
  1002. }
  1003. return {};
  1004. },
  1005. removeLabel(labelId) {
  1006. return { $pull: { labels: { _id: labelId } } };
  1007. },
  1008. changeOwnership(fromId, toId) {
  1009. const memberIndex = this.memberIndex(fromId);
  1010. return {
  1011. $set: {
  1012. [`members.${memberIndex}.userId`]: toId,
  1013. },
  1014. };
  1015. },
  1016. addMember(memberId) {
  1017. const memberIndex = this.memberIndex(memberId);
  1018. if (memberIndex >= 0) {
  1019. return {
  1020. $set: {
  1021. [`members.${memberIndex}.isActive`]: true,
  1022. },
  1023. };
  1024. }
  1025. return {
  1026. $push: {
  1027. members: {
  1028. userId: memberId,
  1029. isAdmin: false,
  1030. isActive: true,
  1031. isNoComments: false,
  1032. isCommentOnly: false,
  1033. isWorker: false,
  1034. },
  1035. },
  1036. };
  1037. },
  1038. removeMember(memberId) {
  1039. const memberIndex = this.memberIndex(memberId);
  1040. // we do not allow the only one admin to be removed
  1041. const allowRemove =
  1042. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1043. if (!allowRemove) {
  1044. return {
  1045. $set: {
  1046. [`members.${memberIndex}.isActive`]: true,
  1047. },
  1048. };
  1049. }
  1050. return {
  1051. $set: {
  1052. [`members.${memberIndex}.isActive`]: false,
  1053. [`members.${memberIndex}.isAdmin`]: false,
  1054. },
  1055. };
  1056. },
  1057. setMemberPermission(
  1058. memberId,
  1059. isAdmin,
  1060. isNoComments,
  1061. isCommentOnly,
  1062. isWorker,
  1063. currentUserId = Meteor.userId(),
  1064. ) {
  1065. const memberIndex = this.memberIndex(memberId);
  1066. // do not allow change permission of self
  1067. if (memberId === currentUserId) {
  1068. isAdmin = this.members[memberIndex].isAdmin;
  1069. }
  1070. return {
  1071. $set: {
  1072. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1073. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1074. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1075. [`members.${memberIndex}.isWorker`]: isWorker,
  1076. },
  1077. };
  1078. },
  1079. setAllowsSubtasks(allowsSubtasks) {
  1080. return { $set: { allowsSubtasks } };
  1081. },
  1082. setAllowsMembers(allowsMembers) {
  1083. return { $set: { allowsMembers } };
  1084. },
  1085. setAllowsChecklists(allowsChecklists) {
  1086. return { $set: { allowsChecklists } };
  1087. },
  1088. setAllowsAssignee(allowsAssignee) {
  1089. return { $set: { allowsAssignee } };
  1090. },
  1091. setAllowsAssignedBy(allowsAssignedBy) {
  1092. return { $set: { allowsAssignedBy } };
  1093. },
  1094. setAllowsRequestedBy(allowsRequestedBy) {
  1095. return { $set: { allowsRequestedBy } };
  1096. },
  1097. setAllowsAttachments(allowsAttachments) {
  1098. return { $set: { allowsAttachments } };
  1099. },
  1100. setAllowsLabels(allowsLabels) {
  1101. return { $set: { allowsLabels } };
  1102. },
  1103. setAllowsComments(allowsComments) {
  1104. return { $set: { allowsComments } };
  1105. },
  1106. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1107. return { $set: { allowsDescriptionTitle } };
  1108. },
  1109. setAllowsDescriptionText(allowsDescriptionText) {
  1110. return { $set: { allowsDescriptionText } };
  1111. },
  1112. setAllowsActivities(allowsActivities) {
  1113. return { $set: { allowsActivities } };
  1114. },
  1115. setAllowsReceivedDate(allowsReceivedDate) {
  1116. return { $set: { allowsReceivedDate } };
  1117. },
  1118. setAllowsStartDate(allowsStartDate) {
  1119. return { $set: { allowsStartDate } };
  1120. },
  1121. setAllowsEndDate(allowsEndDate) {
  1122. return { $set: { allowsEndDate } };
  1123. },
  1124. setAllowsDueDate(allowsDueDate) {
  1125. return { $set: { allowsDueDate } };
  1126. },
  1127. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1128. return { $set: { subtasksDefaultBoardId } };
  1129. },
  1130. setSubtasksDefaultListId(subtasksDefaultListId) {
  1131. return { $set: { subtasksDefaultListId } };
  1132. },
  1133. setPresentParentTask(presentParentTask) {
  1134. return { $set: { presentParentTask } };
  1135. },
  1136. move(sortIndex) {
  1137. return { $set: { sort: sortIndex } };
  1138. },
  1139. });
  1140. function boardRemover(userId, doc) {
  1141. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1142. element => {
  1143. element.remove({ boardId: doc._id });
  1144. },
  1145. );
  1146. }
  1147. Boards.uniqueTitle = title => {
  1148. const m = title.match(
  1149. new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
  1150. );
  1151. const base = escapeForRegex(m.groups.title);
  1152. let num = 0;
  1153. Boards.find({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) }).forEach(
  1154. board => {
  1155. const m = board.title.match(
  1156. new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
  1157. );
  1158. if (m) {
  1159. const n = parseInt(m.groups.num, 10);
  1160. num = num < n ? n : num;
  1161. }
  1162. },
  1163. );
  1164. if (num > 0) {
  1165. return `${base} [${num + 1}]`;
  1166. }
  1167. return title;
  1168. };
  1169. Boards.userSearch = (
  1170. userId,
  1171. selector = {},
  1172. projection = {},
  1173. // includeArchived = false,
  1174. ) => {
  1175. // if (!includeArchived) {
  1176. // selector.archived = false;
  1177. // }
  1178. selector.$or = [{ permission: 'public' }];
  1179. if (userId) {
  1180. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1181. }
  1182. return Boards.find(selector, projection);
  1183. };
  1184. Boards.userBoards = (userId, archived = false, selector = {}) => {
  1185. if (typeof archived === 'boolean') {
  1186. selector.archived = archived;
  1187. }
  1188. selector.$or = [{ permission: 'public' }];
  1189. if (userId) {
  1190. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1191. }
  1192. return Boards.find(selector);
  1193. };
  1194. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1195. return Boards.userBoards(userId, archived, selector).map(board => {
  1196. return board._id;
  1197. });
  1198. };
  1199. Boards.colorMap = () => {
  1200. const colors = {};
  1201. for (const color of Boards.labelColors()) {
  1202. colors[TAPi18n.__(`color-${color}`)] = color;
  1203. }
  1204. return colors;
  1205. };
  1206. Boards.labelColors = () => {
  1207. return _.clone(Boards.simpleSchema()._schema['labels.$.color'].allowedValues);
  1208. };
  1209. if (Meteor.isServer) {
  1210. Boards.allow({
  1211. insert: Meteor.userId,
  1212. update: allowIsBoardAdmin,
  1213. remove: allowIsBoardAdmin,
  1214. fetch: ['members'],
  1215. });
  1216. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1217. Boards.allow({
  1218. update(userId, board, fieldNames) {
  1219. return _.contains(fieldNames, 'sort');
  1220. },
  1221. fetch: [],
  1222. });
  1223. // The number of users that have starred this board is managed by trusted code
  1224. // and the user is not allowed to update it
  1225. Boards.deny({
  1226. update(userId, board, fieldNames) {
  1227. return _.contains(fieldNames, 'stars');
  1228. },
  1229. fetch: [],
  1230. });
  1231. // We can't remove a member if it is the last administrator
  1232. Boards.deny({
  1233. update(userId, doc, fieldNames, modifier) {
  1234. if (!_.contains(fieldNames, 'members')) return false;
  1235. // We only care in case of a $pull operation, ie remove a member
  1236. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1237. // If there is more than one admin, it's ok to remove anyone
  1238. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1239. .length;
  1240. if (nbAdmins > 1) return false;
  1241. // If all the previous conditions were verified, we can't remove
  1242. // a user if it's an admin
  1243. const removedMemberId = modifier.$pull.members.userId;
  1244. return Boolean(
  1245. _.findWhere(doc.members, {
  1246. userId: removedMemberId,
  1247. isAdmin: true,
  1248. }),
  1249. );
  1250. },
  1251. fetch: ['members'],
  1252. });
  1253. Meteor.methods({
  1254. quitBoard(boardId) {
  1255. check(boardId, String);
  1256. const board = Boards.findOne(boardId);
  1257. if (board) {
  1258. const userId = Meteor.userId();
  1259. const index = board.memberIndex(userId);
  1260. if (index >= 0) {
  1261. board.removeMember(userId);
  1262. return true;
  1263. } else throw new Meteor.Error('error-board-notAMember');
  1264. } else throw new Meteor.Error('error-board-doesNotExist');
  1265. },
  1266. acceptInvite(boardId) {
  1267. check(boardId, String);
  1268. const board = Boards.findOne(boardId);
  1269. if (!board) {
  1270. throw new Meteor.Error('error-board-doesNotExist');
  1271. }
  1272. Meteor.users.update(Meteor.userId(), {
  1273. $pull: {
  1274. 'profile.invitedBoards': boardId,
  1275. },
  1276. });
  1277. },
  1278. myLabelNames() {
  1279. let names = [];
  1280. Boards.userBoards(Meteor.userId(), false, { type: 'board' }).forEach(
  1281. board => {
  1282. names = names.concat(
  1283. board.labels
  1284. .filter(label => !!label.name)
  1285. .map(label => {
  1286. return label.name;
  1287. }),
  1288. );
  1289. },
  1290. );
  1291. return _.uniq(names).sort();
  1292. },
  1293. myBoardNames() {
  1294. return _.uniq(
  1295. Boards.userBoards(Meteor.userId()).map(board => {
  1296. return board.title;
  1297. }),
  1298. ).sort();
  1299. },
  1300. });
  1301. Meteor.methods({
  1302. archiveBoard(boardId) {
  1303. check(boardId, String);
  1304. const board = Boards.findOne(boardId);
  1305. if (board) {
  1306. const userId = Meteor.userId();
  1307. const index = board.memberIndex(userId);
  1308. if (index >= 0) {
  1309. board.archive();
  1310. return true;
  1311. } else throw new Meteor.Error('error-board-notAMember');
  1312. } else throw new Meteor.Error('error-board-doesNotExist');
  1313. },
  1314. });
  1315. }
  1316. // Insert new board at last position in sort order.
  1317. Boards.before.insert((userId, doc) => {
  1318. const lastBoard = Boards.findOne(
  1319. { sort: { $exists: true } },
  1320. { sort: { sort: -1 } },
  1321. );
  1322. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1323. doc.sort = lastBoard.sort + 1;
  1324. }
  1325. });
  1326. if (Meteor.isServer) {
  1327. // Let MongoDB ensure that a member is not included twice in the same board
  1328. Meteor.startup(() => {
  1329. Boards._collection._ensureIndex({ modifiedAt: -1 });
  1330. Boards._collection._ensureIndex(
  1331. {
  1332. _id: 1,
  1333. 'members.userId': 1,
  1334. },
  1335. { unique: true },
  1336. );
  1337. Boards._collection._ensureIndex({ 'members.userId': 1 });
  1338. });
  1339. // Genesis: the first activity of the newly created board
  1340. Boards.after.insert((userId, doc) => {
  1341. Activities.insert({
  1342. userId,
  1343. type: 'board',
  1344. activityTypeId: doc._id,
  1345. activityType: 'createBoard',
  1346. boardId: doc._id,
  1347. });
  1348. });
  1349. // If the user remove one label from a board, we cant to remove reference of
  1350. // this label in any card of this board.
  1351. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1352. if (
  1353. !_.contains(fieldNames, 'labels') ||
  1354. !modifier.$pull ||
  1355. !modifier.$pull.labels ||
  1356. !modifier.$pull.labels._id
  1357. ) {
  1358. return;
  1359. }
  1360. const removedLabelId = modifier.$pull.labels._id;
  1361. Cards.update(
  1362. { boardId: doc._id },
  1363. {
  1364. $pull: {
  1365. labelIds: removedLabelId,
  1366. },
  1367. },
  1368. { multi: true },
  1369. );
  1370. });
  1371. const foreachRemovedMember = (doc, modifier, callback) => {
  1372. Object.keys(modifier).forEach(set => {
  1373. if (modifier[set] !== false) {
  1374. return;
  1375. }
  1376. const parts = set.split('.');
  1377. if (
  1378. parts.length === 3 &&
  1379. parts[0] === 'members' &&
  1380. parts[2] === 'isActive'
  1381. ) {
  1382. callback(doc.members[parts[1]].userId);
  1383. }
  1384. });
  1385. };
  1386. // Remove a member from all objects of the board before leaving the board
  1387. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1388. if (!_.contains(fieldNames, 'members')) {
  1389. return;
  1390. }
  1391. if (modifier.$set) {
  1392. const boardId = doc._id;
  1393. foreachRemovedMember(doc, modifier.$set, memberId => {
  1394. Cards.update(
  1395. { boardId },
  1396. {
  1397. $pull: {
  1398. members: memberId,
  1399. watchers: memberId,
  1400. },
  1401. },
  1402. { multi: true },
  1403. );
  1404. Lists.update(
  1405. { boardId },
  1406. {
  1407. $pull: {
  1408. watchers: memberId,
  1409. },
  1410. },
  1411. { multi: true },
  1412. );
  1413. const board = Boards._transform(doc);
  1414. board.setWatcher(memberId, false);
  1415. // Remove board from users starred list
  1416. if (!board.isPublic()) {
  1417. Users.update(memberId, {
  1418. $pull: {
  1419. 'profile.starredBoards': boardId,
  1420. },
  1421. });
  1422. }
  1423. });
  1424. }
  1425. });
  1426. Boards.before.remove((userId, doc) => {
  1427. boardRemover(userId, doc);
  1428. // Add removeBoard activity to keep it
  1429. Activities.insert({
  1430. userId,
  1431. type: 'board',
  1432. activityTypeId: doc._id,
  1433. activityType: 'removeBoard',
  1434. boardId: doc._id,
  1435. });
  1436. });
  1437. // Add a new activity if we add or remove a member to the board
  1438. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1439. if (!_.contains(fieldNames, 'members')) {
  1440. return;
  1441. }
  1442. // Say hello to the new member
  1443. if (modifier.$push && modifier.$push.members) {
  1444. const memberId = modifier.$push.members.userId;
  1445. Activities.insert({
  1446. userId,
  1447. memberId,
  1448. type: 'member',
  1449. activityType: 'addBoardMember',
  1450. boardId: doc._id,
  1451. });
  1452. }
  1453. // Say goodbye to the former member
  1454. if (modifier.$set) {
  1455. foreachRemovedMember(doc, modifier.$set, memberId => {
  1456. Activities.insert({
  1457. userId,
  1458. memberId,
  1459. type: 'member',
  1460. activityType: 'removeBoardMember',
  1461. boardId: doc._id,
  1462. });
  1463. });
  1464. }
  1465. });
  1466. }
  1467. //BOARDS REST API
  1468. if (Meteor.isServer) {
  1469. /**
  1470. * @operation get_boards_from_user
  1471. * @summary Get all boards attached to a user
  1472. *
  1473. * @param {string} userId the ID of the user to retrieve the data
  1474. * @return_type [{_id: string,
  1475. title: string}]
  1476. */
  1477. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1478. try {
  1479. Authentication.checkLoggedIn(req.userId);
  1480. const paramUserId = req.params.userId;
  1481. // A normal user should be able to see their own boards,
  1482. // admins can access boards of any user
  1483. Authentication.checkAdminOrCondition(
  1484. req.userId,
  1485. req.userId === paramUserId,
  1486. );
  1487. const data = Boards.find(
  1488. {
  1489. archived: false,
  1490. 'members.userId': paramUserId,
  1491. },
  1492. {
  1493. sort: { sort: 1 /* boards default sorting */ },
  1494. },
  1495. ).map(function(board) {
  1496. return {
  1497. _id: board._id,
  1498. title: board.title,
  1499. };
  1500. });
  1501. JsonRoutes.sendResult(res, { code: 200, data });
  1502. } catch (error) {
  1503. JsonRoutes.sendResult(res, {
  1504. code: 200,
  1505. data: error,
  1506. });
  1507. }
  1508. });
  1509. /**
  1510. * @operation get_public_boards
  1511. * @summary Get all public boards
  1512. *
  1513. * @return_type [{_id: string,
  1514. title: string}]
  1515. */
  1516. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1517. try {
  1518. Authentication.checkUserId(req.userId);
  1519. JsonRoutes.sendResult(res, {
  1520. code: 200,
  1521. data: Boards.find(
  1522. { permission: 'public' },
  1523. {
  1524. sort: { sort: 1 /* boards default sorting */ },
  1525. },
  1526. ).map(function(doc) {
  1527. return {
  1528. _id: doc._id,
  1529. title: doc.title,
  1530. };
  1531. }),
  1532. });
  1533. } catch (error) {
  1534. JsonRoutes.sendResult(res, {
  1535. code: 200,
  1536. data: error,
  1537. });
  1538. }
  1539. });
  1540. /**
  1541. * @operation get_boards_count
  1542. * @summary Get public and private boards count
  1543. *
  1544. * @return_type {private: integer, public: integer}
  1545. */
  1546. JsonRoutes.add('GET', '/api/boards_count', function(req, res) {
  1547. try {
  1548. Authentication.checkUserId(req.userId);
  1549. JsonRoutes.sendResult(res, {
  1550. code: 200,
  1551. data: {
  1552. private: Boards.find({ permission: 'private' }).count(),
  1553. public: Boards.find({ permission: 'public' }).count(),
  1554. },
  1555. });
  1556. } catch (error) {
  1557. JsonRoutes.sendResult(res, {
  1558. code: 200,
  1559. data: error,
  1560. });
  1561. }
  1562. });
  1563. /**
  1564. * @operation get_board
  1565. * @summary Get the board with that particular ID
  1566. *
  1567. * @param {string} boardId the ID of the board to retrieve the data
  1568. * @return_type Boards
  1569. */
  1570. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1571. try {
  1572. const id = req.params.boardId;
  1573. Authentication.checkBoardAccess(req.userId, id);
  1574. JsonRoutes.sendResult(res, {
  1575. code: 200,
  1576. data: Boards.findOne({ _id: id }),
  1577. });
  1578. } catch (error) {
  1579. JsonRoutes.sendResult(res, {
  1580. code: 200,
  1581. data: error,
  1582. });
  1583. }
  1584. });
  1585. /**
  1586. * @operation new_board
  1587. * @summary Create a board
  1588. *
  1589. * @description This allows to create a board.
  1590. *
  1591. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1592. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1593. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1594. *
  1595. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1596. *
  1597. * @param {string} title the new title of the board
  1598. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1599. * (Not username or email)
  1600. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1601. * @param {boolean} [isActive] is the board active (default true)
  1602. * @param {boolean} [isNoComments] disable comments (default false)
  1603. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1604. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1605. * @param {string} [permission] "private" board <== Set to "public" if you
  1606. * want public Wekan board
  1607. * @param {string} [color] the color of the board
  1608. *
  1609. * @return_type {_id: string,
  1610. defaultSwimlaneId: string}
  1611. */
  1612. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1613. try {
  1614. Authentication.checkUserId(req.userId);
  1615. const id = Boards.insert({
  1616. title: req.body.title,
  1617. members: [
  1618. {
  1619. userId: req.body.owner,
  1620. isAdmin: req.body.isAdmin || true,
  1621. isActive: req.body.isActive || true,
  1622. isNoComments: req.body.isNoComments || false,
  1623. isCommentOnly: req.body.isCommentOnly || false,
  1624. isWorker: req.body.isWorker || false,
  1625. },
  1626. ],
  1627. permission: req.body.permission || 'private',
  1628. color: req.body.color || 'belize',
  1629. });
  1630. const swimlaneId = Swimlanes.insert({
  1631. title: TAPi18n.__('default'),
  1632. boardId: id,
  1633. });
  1634. JsonRoutes.sendResult(res, {
  1635. code: 200,
  1636. data: {
  1637. _id: id,
  1638. defaultSwimlaneId: swimlaneId,
  1639. },
  1640. });
  1641. } catch (error) {
  1642. JsonRoutes.sendResult(res, {
  1643. code: 200,
  1644. data: error,
  1645. });
  1646. }
  1647. });
  1648. /**
  1649. * @operation delete_board
  1650. * @summary Delete a board
  1651. *
  1652. * @param {string} boardId the ID of the board
  1653. */
  1654. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1655. try {
  1656. Authentication.checkUserId(req.userId);
  1657. const id = req.params.boardId;
  1658. Boards.remove({ _id: id });
  1659. JsonRoutes.sendResult(res, {
  1660. code: 200,
  1661. data: {
  1662. _id: id,
  1663. },
  1664. });
  1665. } catch (error) {
  1666. JsonRoutes.sendResult(res, {
  1667. code: 200,
  1668. data: error,
  1669. });
  1670. }
  1671. });
  1672. /**
  1673. * @operation add_board_label
  1674. * @summary Add a label to a board
  1675. *
  1676. * @description If the board doesn't have the name/color label, this function
  1677. * adds the label to the board.
  1678. *
  1679. * @param {string} boardId the board
  1680. * @param {string} color the color of the new label
  1681. * @param {string} name the name of the new label
  1682. *
  1683. * @return_type string
  1684. */
  1685. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1686. Authentication.checkUserId(req.userId);
  1687. const id = req.params.boardId;
  1688. try {
  1689. if (req.body.hasOwnProperty('label')) {
  1690. const board = Boards.findOne({ _id: id });
  1691. const color = req.body.label.color;
  1692. const name = req.body.label.name;
  1693. const labelId = Random.id(6);
  1694. if (!board.getLabel(name, color)) {
  1695. Boards.direct.update(
  1696. { _id: id },
  1697. { $push: { labels: { _id: labelId, name, color } } },
  1698. );
  1699. JsonRoutes.sendResult(res, {
  1700. code: 200,
  1701. data: labelId,
  1702. });
  1703. } else {
  1704. JsonRoutes.sendResult(res, {
  1705. code: 200,
  1706. });
  1707. }
  1708. }
  1709. } catch (error) {
  1710. JsonRoutes.sendResult(res, {
  1711. data: error,
  1712. });
  1713. }
  1714. });
  1715. /**
  1716. * @operation set_board_member_permission
  1717. * @tag Users
  1718. * @summary Change the permission of a member of a board
  1719. *
  1720. * @param {string} boardId the ID of the board that we are changing
  1721. * @param {string} memberId the ID of the user to change permissions
  1722. * @param {boolean} isAdmin admin capability
  1723. * @param {boolean} isNoComments NoComments capability
  1724. * @param {boolean} isCommentOnly CommentsOnly capability
  1725. * @param {boolean} isWorker Worker capability
  1726. */
  1727. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1728. req,
  1729. res,
  1730. ) {
  1731. try {
  1732. const boardId = req.params.boardId;
  1733. const memberId = req.params.memberId;
  1734. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  1735. Authentication.checkBoardAccess(req.userId, boardId);
  1736. const board = Boards.findOne({ _id: boardId });
  1737. function isTrue(data) {
  1738. try {
  1739. return data.toLowerCase() === 'true';
  1740. } catch (error) {
  1741. return data;
  1742. }
  1743. }
  1744. const query = board.setMemberPermission(
  1745. memberId,
  1746. isTrue(isAdmin),
  1747. isTrue(isNoComments),
  1748. isTrue(isCommentOnly),
  1749. isTrue(isWorker),
  1750. req.userId,
  1751. );
  1752. JsonRoutes.sendResult(res, {
  1753. code: 200,
  1754. data: query,
  1755. });
  1756. } catch (error) {
  1757. JsonRoutes.sendResult(res, {
  1758. code: 200,
  1759. data: error,
  1760. });
  1761. }
  1762. });
  1763. //ATTACHMENTS REST API
  1764. /**
  1765. * @operation get_board_attachments
  1766. * @summary Get the list of attachments of a board
  1767. *
  1768. * @param {string} boardId the board ID
  1769. * @return_type [{attachmentId: string,
  1770. * attachmentName: string,
  1771. * attachmentType: string,
  1772. * cardId: string,
  1773. * listId: string,
  1774. * swimlaneId: string}]
  1775. */
  1776. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  1777. const paramBoardId = req.params.boardId;
  1778. Authentication.checkBoardAccess(req.userId, paramBoardId);
  1779. JsonRoutes.sendResult(res, {
  1780. code: 200,
  1781. data: Attachments.files
  1782. .find({ boardId: paramBoardId }, { fields: { boardId: 0 } })
  1783. .map(function(doc) {
  1784. return {
  1785. attachmentId: doc._id,
  1786. attachmentName: doc.original.name,
  1787. attachmentType: doc.original.type,
  1788. url: FlowRouter.url(doc.url()),
  1789. urlDownload: `${FlowRouter.url(doc.url())}?download=true&token=`,
  1790. cardId: doc.cardId,
  1791. listId: doc.listId,
  1792. swimlaneId: doc.swimlaneId,
  1793. };
  1794. }),
  1795. });
  1796. });
  1797. }
  1798. export default Boards;