boards.js 54 KB

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