boards.js 51 KB

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