boards.js 44 KB

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