boards.js 50 KB

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