boards.js 52 KB

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