boards.js 51 KB

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