boards.js 60 KB

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