boards.js 47 KB

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