boards.js 55 KB

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