boards.js 53 KB

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