boards.js 55 KB

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