boards.js 46 KB

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