boards.js 56 KB

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