2
0

boards.js 54 KB

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