boards.js 55 KB

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