2
0

boards.js 51 KB

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