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. hasSharedListsConverted() {
  739. return this.hasSharedListsConverted === true;
  740. },
  741. cards() {
  742. const ret = ReactiveCache.getCards(
  743. { boardId: this._id, archived: false },
  744. { sort: { title: 1 } },
  745. );
  746. return ret;
  747. },
  748. lists() {
  749. return this.draggableLists();
  750. },
  751. newestLists() {
  752. // sorted lists from newest to the oldest, by its creation date or its cards' last modification date
  753. const value = ReactiveCache.getCurrentUser()._getListSortBy();
  754. const sortKey = { starred: -1, [value[0]]: value[1] }; // [["starred",-1],value];
  755. return ReactiveCache.getLists(
  756. {
  757. boardId: this._id,
  758. archived: false,
  759. },
  760. { sort: sortKey },
  761. );
  762. },
  763. draggableLists() {
  764. return ReactiveCache.getLists(
  765. {
  766. boardId: this._id,
  767. },
  768. { sort: { sort: 1 } }
  769. );
  770. },
  771. /** returns the last list
  772. * @returns Document the last list
  773. */
  774. getLastList() {
  775. const ret = ReactiveCache.getList({ boardId: this._id }, { sort: { sort: 'desc' } });
  776. return ret;
  777. },
  778. nullSortLists() {
  779. return ReactiveCache.getLists({
  780. boardId: this._id,
  781. archived: false,
  782. sort: { $eq: null },
  783. });
  784. },
  785. swimlanes() {
  786. return ReactiveCache.getSwimlanes(
  787. { boardId: this._id, archived: false },
  788. { sort: { sort: 1 } },
  789. );
  790. },
  791. nextSwimlane(swimlane) {
  792. return ReactiveCache.getSwimlane(
  793. {
  794. boardId: this._id,
  795. archived: false,
  796. sort: { $gte: swimlane.sort },
  797. _id: { $ne: swimlane._id },
  798. },
  799. {
  800. sort: { sort: 1 },
  801. },
  802. );
  803. },
  804. nullSortSwimlanes() {
  805. return ReactiveCache.getSwimlanes({
  806. boardId: this._id,
  807. archived: false,
  808. sort: { $eq: null },
  809. });
  810. },
  811. hasOvertimeCards() {
  812. const card = ReactiveCache.getCard({
  813. isOvertime: true,
  814. boardId: this._id,
  815. archived: false,
  816. });
  817. return card !== undefined;
  818. },
  819. hasSpentTimeCards() {
  820. const card = ReactiveCache.getCard({
  821. spentTime: { $gt: 0 },
  822. boardId: this._id,
  823. archived: false,
  824. });
  825. return card !== undefined;
  826. },
  827. activities() {
  828. let linkedBoardId = [this._id];
  829. ReactiveCache.getCards({
  830. "type": "cardType-linkedBoard",
  831. "boardId": this._id}
  832. ).forEach(card => {
  833. linkedBoardId.push(card.linkedId);
  834. });
  835. const ret = ReactiveCache.getActivities({ boardId: { $in: linkedBoardId } }, { sort: { createdAt: -1 } });
  836. return ret;
  837. },
  838. activeMembers(){
  839. const members = _.where(this.members, { isActive: true });
  840. return _.sortBy(members, 'username');
  841. },
  842. activeOrgs() {
  843. return _.where(this.orgs, { isActive: true });
  844. },
  845. // hasNotAnyOrg(){
  846. // return this.orgs === undefined || this.orgs.length <= 0;
  847. // },
  848. activeTeams() {
  849. return _.where(this.teams, { isActive: true });
  850. },
  851. // hasNotAnyTeam(){
  852. // return this.teams === undefined || this.teams.length <= 0;
  853. // },
  854. activeAdmins() {
  855. return _.where(this.members, { isActive: true, isAdmin: true });
  856. },
  857. memberUsers() {
  858. return ReactiveCache.getUsers({ _id: { $in: _.pluck(this.members, 'userId') } });
  859. },
  860. getLabel(name, color) {
  861. return _.findWhere(this.labels, { name, color });
  862. },
  863. getLabelById(labelId) {
  864. return _.findWhere(this.labels, { _id: labelId });
  865. },
  866. labelIndex(labelId) {
  867. return _.pluck(this.labels, '_id').indexOf(labelId);
  868. },
  869. memberIndex(memberId) {
  870. return _.pluck(this.members, 'userId').indexOf(memberId);
  871. },
  872. hasMember(memberId) {
  873. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  874. },
  875. hasAdmin(memberId) {
  876. return !!_.findWhere(this.members, {
  877. userId: memberId,
  878. isActive: true,
  879. isAdmin: true,
  880. });
  881. },
  882. hasNoComments(memberId) {
  883. return !!_.findWhere(this.members, {
  884. userId: memberId,
  885. isActive: true,
  886. isAdmin: false,
  887. isNoComments: true,
  888. isWorker: false,
  889. });
  890. },
  891. hasCommentOnly(memberId) {
  892. return !!_.findWhere(this.members, {
  893. userId: memberId,
  894. isActive: true,
  895. isAdmin: false,
  896. isCommentOnly: true,
  897. isWorker: false,
  898. });
  899. },
  900. hasWorker(memberId) {
  901. return !!_.findWhere(this.members, {
  902. userId: memberId,
  903. isActive: true,
  904. isAdmin: false,
  905. isCommentOnly: false,
  906. isWorker: true,
  907. });
  908. },
  909. hasAnyAllowsDate() {
  910. const ret = this.allowsReceivedDate || this.allowsStartDate || this.allowsDueDate || this.allowsEndDate;
  911. return ret;
  912. },
  913. hasAnyAllowsUser() {
  914. const ret = this.allowsCreator || this.allowsMembers || this.allowsAssignee || this.allowsRequestedBy || this.allowsAssignedBy;
  915. return ret;
  916. },
  917. absoluteUrl() {
  918. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  919. },
  920. originRelativeUrl() {
  921. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  922. },
  923. colorClass() {
  924. return `board-color-${this.color}`;
  925. },
  926. customFields() {
  927. const ret = ReactiveCache.getCustomFields(
  928. { boardIds: { $in: [this._id] } },
  929. { sort: { name: 1 } },
  930. );
  931. return ret;
  932. },
  933. // XXX currently mutations return no value so we have an issue when using addLabel in import
  934. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  935. pushLabel(name, color) {
  936. const _id = Random.id(6);
  937. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  938. return _id;
  939. },
  940. /** sets the new label order
  941. * @param newLabelOrderOnlyIds new order array of _id, e.g. Array(4) [ "FvtD34", "PAEgDP", "LjRBxH", "YJ8sZz" ]
  942. */
  943. setNewLabelOrder(newLabelOrderOnlyIds) {
  944. if (this.labels.length == newLabelOrderOnlyIds.length) {
  945. if (this.labels.every(_label => newLabelOrderOnlyIds.indexOf(_label._id) >= 0)) {
  946. const newLabels = _.sortBy(this.labels, _label => newLabelOrderOnlyIds.indexOf(_label._id));
  947. if (this.labels.length == newLabels.length) {
  948. Boards.direct.update(this._id, {$set: {labels: newLabels}});
  949. }
  950. }
  951. }
  952. },
  953. searchBoards(term) {
  954. check(term, Match.OneOf(String, null, undefined));
  955. const query = { boardId: this._id };
  956. query.type = 'cardType-linkedBoard';
  957. query.archived = false;
  958. const projection = { limit: 10, sort: { createdAt: -1 } };
  959. if (term) {
  960. const regex = new RegExp(term, 'i');
  961. query.$or = [{ title: regex }, { description: regex }];
  962. }
  963. const ret = ReactiveCache.getCards(query, projection);
  964. return ret;
  965. },
  966. searchSwimlanes(term) {
  967. check(term, Match.OneOf(String, null, undefined));
  968. const query = { boardId: this._id };
  969. if (this.isTemplatesBoard()) {
  970. query.type = 'template-swimlane';
  971. query.archived = false;
  972. } else {
  973. query.type = { $nin: ['template-swimlane'] };
  974. }
  975. const projection = { limit: 10, sort: { createdAt: -1 } };
  976. if (term) {
  977. const regex = new RegExp(term, 'i');
  978. query.$or = [{ title: regex }, { description: regex }];
  979. }
  980. return ReactiveCache.getSwimlanes(query, projection);
  981. },
  982. searchLists(term) {
  983. let ret = null;
  984. if (term) {
  985. check(term, Match.OneOf(String));
  986. term = term.trim();
  987. }
  988. if (term) {
  989. const query = { boardId: this._id };
  990. if (this.isTemplatesBoard()) {
  991. query.type = 'template-list';
  992. query.archived = false;
  993. } else {
  994. query.type = { $nin: ['template-list'] };
  995. }
  996. const projection = { sort: { createdAt: -1 } };
  997. if (term) {
  998. const regex = new RegExp(term, 'i');
  999. query.$or = [{ title: regex }, { description: regex }];
  1000. }
  1001. ret = ReactiveCache.getLists(query, projection);
  1002. }
  1003. return ret;
  1004. },
  1005. searchCards(term, excludeLinked) {
  1006. let ret = null;
  1007. if (term) {
  1008. check(term, Match.OneOf(String));
  1009. term = term.trim();
  1010. }
  1011. if (term) {
  1012. const query = { boardId: this._id };
  1013. if (excludeLinked) {
  1014. query.linkedId = null;
  1015. }
  1016. if (this.isTemplatesBoard()) {
  1017. query.type = 'template-card';
  1018. query.archived = false;
  1019. } else {
  1020. query.type = { $nin: ['template-card'] };
  1021. }
  1022. const projection = { sort: { createdAt: -1 } };
  1023. const regex = new RegExp(term, 'i');
  1024. query.$or = [
  1025. { title: regex },
  1026. { description: regex },
  1027. { customFields: { $elemMatch: { value: regex } } },
  1028. ];
  1029. ret = ReactiveCache.getCards(query, projection);
  1030. }
  1031. return ret;
  1032. },
  1033. // A board alwasy has another board where it deposits subtasks of thasks
  1034. // that belong to itself.
  1035. getDefaultSubtasksBoardId() {
  1036. if (
  1037. this.subtasksDefaultBoardId === null ||
  1038. this.subtasksDefaultBoardId === undefined
  1039. ) {
  1040. this.subtasksDefaultBoardId = Boards.insert({
  1041. title: `^${this.title}^`,
  1042. permission: this.permission,
  1043. members: this.members,
  1044. color: this.color,
  1045. description: TAPi18n && TAPi18n.i18n ? TAPi18n.__('default-subtasks-board', {
  1046. board: this.title,
  1047. }) : `Default subtasks board for ${this.title}`,
  1048. });
  1049. Swimlanes.insert({
  1050. title: TAPi18n && TAPi18n.i18n ? TAPi18n.__('default') : 'Default',
  1051. boardId: this.subtasksDefaultBoardId,
  1052. });
  1053. Boards.update(this._id, {
  1054. $set: {
  1055. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  1056. },
  1057. });
  1058. }
  1059. return this.subtasksDefaultBoardId;
  1060. },
  1061. getDefaultSubtasksBoard() {
  1062. return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
  1063. },
  1064. //Date Settings option such as received date, start date and so on.
  1065. getDefaultDateSettingsBoardId() {
  1066. if (
  1067. this.dateSettingsDefaultBoardId === null ||
  1068. this.dateSettingsDefaultBoardId === undefined
  1069. ) {
  1070. this.dateSettingsDefaultBoardId = Boards.insert({
  1071. title: `^${this.title}^`,
  1072. permission: this.permission,
  1073. members: this.members,
  1074. color: this.color,
  1075. description: TAPi18n && TAPi18n.i18n ? TAPi18n.__('default-dates-board', {
  1076. board: this.title,
  1077. }) : `Default dates board for ${this.title}`,
  1078. });
  1079. Swimlanes.insert({
  1080. title: TAPi18n && TAPi18n.i18n ? TAPi18n.__('default') : 'Default',
  1081. boardId: this.dateSettingsDefaultBoardId,
  1082. });
  1083. Boards.update(this._id, {
  1084. $set: {
  1085. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  1086. },
  1087. });
  1088. }
  1089. return this.dateSettingsDefaultBoardId;
  1090. },
  1091. getDefaultDateSettingsBoard() {
  1092. return ReactiveCache.getBoard(this.getDefaultDateSettingsBoardId());
  1093. },
  1094. getDefaultSubtasksListId() {
  1095. if (
  1096. this.subtasksDefaultListId === null ||
  1097. this.subtasksDefaultListId === undefined
  1098. ) {
  1099. this.subtasksDefaultListId = Lists.insert({
  1100. title: TAPi18n && TAPi18n.i18n ? TAPi18n.__('queue') : 'Queue',
  1101. boardId: this._id,
  1102. swimlaneId: this.getDefaultSwimline()._id, // Set default swimlane for subtasks list
  1103. });
  1104. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  1105. }
  1106. return this.subtasksDefaultListId;
  1107. },
  1108. getDefaultSubtasksList() {
  1109. return ReactiveCache.getList(this.getDefaultSubtasksListId());
  1110. },
  1111. getDefaultDateSettingsListId() {
  1112. if (
  1113. this.dateSettingsDefaultListId === null ||
  1114. this.dateSettingsDefaultListId === undefined
  1115. ) {
  1116. this.dateSettingsDefaultListId = Lists.insert({
  1117. title: TAPi18n && TAPi18n.i18n ? TAPi18n.__('queue') : 'Queue',
  1118. boardId: this._id,
  1119. swimlaneId: this.getDefaultSwimline()._id, // Set default swimlane for date settings list
  1120. });
  1121. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  1122. }
  1123. return this.dateSettingsDefaultListId;
  1124. },
  1125. getDefaultDateSettingsList() {
  1126. return ReactiveCache.getList(this.getDefaultDateSettingsListId());
  1127. },
  1128. getDefaultSwimline() {
  1129. let result = ReactiveCache.getSwimlane({ boardId: this._id });
  1130. if (result === undefined) {
  1131. // Check if any swimlane exists for this board to avoid duplicates
  1132. const existingSwimlanes = ReactiveCache.getSwimlanes({ boardId: this._id });
  1133. if (existingSwimlanes.length > 0) {
  1134. // Use the first existing swimlane
  1135. result = existingSwimlanes[0];
  1136. } else {
  1137. // Use fallback title if i18n is not available (e.g., during migration)
  1138. const title = TAPi18n && TAPi18n.i18n ? TAPi18n.__('default') : 'Default';
  1139. Swimlanes.insert({
  1140. title: title,
  1141. boardId: this._id,
  1142. });
  1143. result = ReactiveCache.getSwimlane({ boardId: this._id });
  1144. }
  1145. }
  1146. return result;
  1147. },
  1148. getNextCardNumber() {
  1149. const boardCards = ReactiveCache.getCard(
  1150. {
  1151. boardId: this._id
  1152. },
  1153. {
  1154. sort: { cardNumber: -1 },
  1155. limit: 1
  1156. }
  1157. , true);
  1158. // If no card is assigned to the board, return 1
  1159. if (!boardCards) {
  1160. return 1;
  1161. }
  1162. const maxCardNr = !!boardCards.cardNumber ? boardCards.cardNumber : 0;
  1163. return maxCardNr + 1;
  1164. },
  1165. cardsDueInBetween(start, end) {
  1166. const ret = ReactiveCache.getCards({
  1167. boardId: this._id,
  1168. dueAt: { $gte: start, $lte: end },
  1169. });
  1170. return ret;
  1171. },
  1172. cardsInInterval(start, end) {
  1173. const ret = ReactiveCache.getCards({
  1174. boardId: this._id,
  1175. $or: [
  1176. {
  1177. startAt: {
  1178. $lte: start,
  1179. },
  1180. endAt: {
  1181. $gte: start,
  1182. },
  1183. },
  1184. {
  1185. startAt: {
  1186. $lte: end,
  1187. },
  1188. endAt: {
  1189. $gte: end,
  1190. },
  1191. },
  1192. {
  1193. startAt: {
  1194. $gte: start,
  1195. },
  1196. endAt: {
  1197. $lte: end,
  1198. },
  1199. },
  1200. ],
  1201. });
  1202. return ret;
  1203. },
  1204. isTemplateBoard() {
  1205. return this.type === 'template-board';
  1206. },
  1207. isTemplatesBoard() {
  1208. return this.type === 'template-container';
  1209. },
  1210. });
  1211. Boards.mutations({
  1212. archive() {
  1213. return { $set: { archived: true, archivedAt: new Date() } };
  1214. },
  1215. restore() {
  1216. return { $set: { archived: false } };
  1217. },
  1218. rename(title) {
  1219. return { $set: { title } };
  1220. },
  1221. setDescription(description) {
  1222. return { $set: { description } };
  1223. },
  1224. setColor(color) {
  1225. return { $set: { color } };
  1226. },
  1227. setBackgroundImageURL(backgroundImageURL) {
  1228. const currentUser = ReactiveCache.getCurrentUser();
  1229. if(currentUser.isBoardAdmin()) {
  1230. return { $set: { backgroundImageURL } };
  1231. } else if (currentUser.isAdmin()) {
  1232. return { $set: { backgroundImageURL } };
  1233. } else {
  1234. return false;
  1235. }
  1236. },
  1237. setVisibility(visibility) {
  1238. return { $set: { permission: visibility } };
  1239. },
  1240. addLabel(name, color) {
  1241. // If label with the same name and color already exists we don't want to
  1242. // create another one because they would be indistinguishable in the UI
  1243. // (they would still have different `_id` but that is not exposed to the
  1244. // user).
  1245. if (!this.getLabel(name, color)) {
  1246. const _id = Random.id(6);
  1247. return { $push: { labels: { _id, name, color } } };
  1248. }
  1249. return {};
  1250. },
  1251. editLabel(labelId, name, color) {
  1252. if (!this.getLabel(name, color)) {
  1253. const labelIndex = this.labelIndex(labelId);
  1254. return {
  1255. $set: {
  1256. [`labels.${labelIndex}.name`]: name,
  1257. [`labels.${labelIndex}.color`]: color,
  1258. },
  1259. };
  1260. }
  1261. return {};
  1262. },
  1263. removeLabel(labelId) {
  1264. return { $pull: { labels: { _id: labelId } } };
  1265. },
  1266. changeOwnership(fromId, toId) {
  1267. const memberIndex = this.memberIndex(fromId);
  1268. return {
  1269. $set: {
  1270. [`members.${memberIndex}.userId`]: toId,
  1271. },
  1272. };
  1273. },
  1274. addMember(memberId) {
  1275. const memberIndex = this.memberIndex(memberId);
  1276. if (memberIndex >= 0) {
  1277. return {
  1278. $set: {
  1279. [`members.${memberIndex}.isActive`]: true,
  1280. },
  1281. };
  1282. }
  1283. return {
  1284. $push: {
  1285. members: {
  1286. userId: memberId,
  1287. isAdmin: false,
  1288. isActive: true,
  1289. isNoComments: false,
  1290. isCommentOnly: false,
  1291. isWorker: false,
  1292. },
  1293. },
  1294. };
  1295. },
  1296. removeMember(memberId) {
  1297. const memberIndex = this.memberIndex(memberId);
  1298. // we do not allow the only one admin to be removed
  1299. const allowRemove =
  1300. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1301. if (!allowRemove) {
  1302. return {
  1303. $set: {
  1304. [`members.${memberIndex}.isActive`]: true,
  1305. },
  1306. };
  1307. }
  1308. return {
  1309. $set: {
  1310. [`members.${memberIndex}.isActive`]: false,
  1311. [`members.${memberIndex}.isAdmin`]: false,
  1312. },
  1313. };
  1314. },
  1315. setMemberPermission(
  1316. memberId,
  1317. isAdmin,
  1318. isNoComments,
  1319. isCommentOnly,
  1320. isWorker,
  1321. currentUserId = Meteor.userId(),
  1322. ) {
  1323. const memberIndex = this.memberIndex(memberId);
  1324. // do not allow change permission of self
  1325. if (memberId === currentUserId) {
  1326. isAdmin = this.members[memberIndex].isAdmin;
  1327. }
  1328. return {
  1329. $set: {
  1330. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1331. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1332. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1333. [`members.${memberIndex}.isWorker`]: isWorker,
  1334. },
  1335. };
  1336. },
  1337. setAllowsSubtasks(allowsSubtasks) {
  1338. return { $set: { allowsSubtasks } };
  1339. },
  1340. setAllowsCreator(allowsCreator) {
  1341. return { $set: { allowsCreator } };
  1342. },
  1343. setAllowsCreatorOnMinicard(allowsCreatorOnMinicard) {
  1344. return { $set: { allowsCreatorOnMinicard } };
  1345. },
  1346. setAllowsMembers(allowsMembers) {
  1347. return { $set: { allowsMembers } };
  1348. },
  1349. setAllowsChecklists(allowsChecklists) {
  1350. return { $set: { allowsChecklists } };
  1351. },
  1352. setAllowsAssignee(allowsAssignee) {
  1353. return { $set: { allowsAssignee } };
  1354. },
  1355. setAllowsAssignedBy(allowsAssignedBy) {
  1356. return { $set: { allowsAssignedBy } };
  1357. },
  1358. setAllowsShowListsOnMinicard(allowsShowListsOnMinicard) {
  1359. return { $set: { allowsShowListsOnMinicard } };
  1360. },
  1361. setAllowsRequestedBy(allowsRequestedBy) {
  1362. return { $set: { allowsRequestedBy } };
  1363. },
  1364. setAllowsCardSortingByNumber(allowsCardSortingByNumber) {
  1365. return { $set: { allowsCardSortingByNumber } };
  1366. },
  1367. setAllowsShowLists(allowsShowLists) {
  1368. return { $set: { allowsShowLists } };
  1369. },
  1370. setAllowsAttachments(allowsAttachments) {
  1371. return { $set: { allowsAttachments } };
  1372. },
  1373. setAllowsLabels(allowsLabels) {
  1374. return { $set: { allowsLabels } };
  1375. },
  1376. setAllowsComments(allowsComments) {
  1377. return { $set: { allowsComments } };
  1378. },
  1379. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1380. return { $set: { allowsDescriptionTitle } };
  1381. },
  1382. setAllowsCardNumber(allowsCardNumber) {
  1383. return { $set: { allowsCardNumber } };
  1384. },
  1385. setAllowsDescriptionText(allowsDescriptionText) {
  1386. return { $set: { allowsDescriptionText } };
  1387. },
  1388. setallowsDescriptionTextOnMinicard(allowsDescriptionTextOnMinicard) {
  1389. return { $set: { allowsDescriptionTextOnMinicard } };
  1390. },
  1391. setallowsCoverAttachmentOnMinicard(allowsCoverAttachmentOnMinicard) {
  1392. return { $set: { allowsCoverAttachmentOnMinicard } };
  1393. },
  1394. setallowsBadgeAttachmentOnMinicard(allowsBadgeAttachmentOnMinicard) {
  1395. return { $set: { allowsBadgeAttachmentOnMinicard } };
  1396. },
  1397. setallowsCardSortingByNumberOnMinicard(allowsCardSortingByNumberOnMinicard) {
  1398. return { $set: { allowsCardSortingByNumberOnMinicard } };
  1399. },
  1400. setAllowsActivities(allowsActivities) {
  1401. return { $set: { allowsActivities } };
  1402. },
  1403. setAllowsReceivedDate(allowsReceivedDate) {
  1404. return { $set: { allowsReceivedDate } };
  1405. },
  1406. setAllowsCardCounterList(allowsCardCounterList) {
  1407. return { $set: { allowsCardCounterList } };
  1408. },
  1409. setAllowsBoardMemberList(allowsBoardMemberList) {
  1410. return { $set: { allowsBoardMemberList } };
  1411. },
  1412. setAllowsStartDate(allowsStartDate) {
  1413. return { $set: { allowsStartDate } };
  1414. },
  1415. setAllowsEndDate(allowsEndDate) {
  1416. return { $set: { allowsEndDate } };
  1417. },
  1418. setAllowsDueDate(allowsDueDate) {
  1419. return { $set: { allowsDueDate } };
  1420. },
  1421. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1422. return { $set: { subtasksDefaultBoardId } };
  1423. },
  1424. setSubtasksDefaultListId(subtasksDefaultListId) {
  1425. return { $set: { subtasksDefaultListId } };
  1426. },
  1427. setPresentParentTask(presentParentTask) {
  1428. return { $set: { presentParentTask } };
  1429. },
  1430. move(sortIndex) {
  1431. return { $set: { sort: sortIndex } };
  1432. },
  1433. toggleShowActivities() {
  1434. return { $set: { showActivities: !this.showActivities } };
  1435. },
  1436. });
  1437. function boardRemover(userId, doc) {
  1438. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1439. element => {
  1440. element.remove({ boardId: doc._id });
  1441. },
  1442. );
  1443. }
  1444. Boards.uniqueTitle = title => {
  1445. const m = title.match(
  1446. new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
  1447. );
  1448. const base = escapeForRegex(m.groups.title);
  1449. const baseTitle = m.groups.title;
  1450. boards = ReactiveCache.getBoards({ title: new RegExp(`^${base}\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)`) });
  1451. if (boards.length > 0) {
  1452. let num = 0;
  1453. ReactiveCache.getBoards({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) }).forEach(
  1454. board => {
  1455. const m = board.title.match(
  1456. new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
  1457. );
  1458. if (m) {
  1459. const n = parseInt(m.groups.num, 10);
  1460. num = num < n ? n : num;
  1461. }
  1462. },
  1463. );
  1464. return `${baseTitle} [${num + 1}]`;
  1465. }
  1466. return title;
  1467. };
  1468. Boards.userSearch = (
  1469. userId,
  1470. selector = {},
  1471. projection = {},
  1472. // includeArchived = false,
  1473. ) => {
  1474. // if (!includeArchived) {
  1475. // selector.archived = false;
  1476. // }
  1477. selector.$or = [{ permission: 'public' }];
  1478. if (userId) {
  1479. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1480. }
  1481. const ret = ReactiveCache.getBoards(selector, projection);
  1482. return ret;
  1483. };
  1484. Boards.userBoards = (
  1485. userId,
  1486. archived = false,
  1487. selector = {},
  1488. projection = {},
  1489. ) => {
  1490. const user = ReactiveCache.getUser(userId);
  1491. if (!user) {
  1492. return [];
  1493. }
  1494. if (typeof archived === 'boolean') {
  1495. selector.archived = archived;
  1496. }
  1497. if (!selector.type) {
  1498. selector.type = 'board';
  1499. }
  1500. selector.$or = [
  1501. { permission: 'public' },
  1502. { members: { $elemMatch: { userId, isActive: true } } },
  1503. { orgs: { $elemMatch: { orgId: { $in: user.orgIds() }, isActive: true } } },
  1504. { teams: { $elemMatch: { teamId: { $in: user.teamIds() }, isActive: true } } },
  1505. ];
  1506. return ReactiveCache.getBoards(selector, projection);
  1507. };
  1508. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1509. return Boards.userBoards(userId, archived, selector, {
  1510. fields: { _id: 1 },
  1511. }).map(board => {
  1512. return board._id;
  1513. });
  1514. };
  1515. Boards.colorMap = () => {
  1516. const colors = {};
  1517. for (const color of Boards.labelColors()) {
  1518. colors[TAPi18n.__(`color-${color}`)] = color;
  1519. }
  1520. return colors;
  1521. };
  1522. Boards.labelColors = () => {
  1523. return ALLOWED_COLORS;
  1524. };
  1525. if (Meteor.isServer) {
  1526. Boards.allow({
  1527. insert: Meteor.userId,
  1528. update: allowIsBoardAdmin,
  1529. remove: allowIsBoardAdmin,
  1530. fetch: ['members'],
  1531. });
  1532. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1533. Boards.allow({
  1534. update(userId, board, fieldNames) {
  1535. return _.contains(fieldNames, 'sort');
  1536. },
  1537. fetch: [],
  1538. });
  1539. // The number of users that have starred this board is managed by trusted code
  1540. // and the user is not allowed to update it
  1541. Boards.deny({
  1542. update(userId, board, fieldNames) {
  1543. return _.contains(fieldNames, 'stars');
  1544. },
  1545. fetch: [],
  1546. });
  1547. // We can't remove a member if it is the last administrator
  1548. Boards.deny({
  1549. update(userId, doc, fieldNames, modifier) {
  1550. if (!_.contains(fieldNames, 'members')) return false;
  1551. // We only care in case of a $pull operation, ie remove a member
  1552. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1553. // If there is more than one admin, it's ok to remove anyone
  1554. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1555. .length;
  1556. if (nbAdmins > 1) return false;
  1557. // If all the previous conditions were verified, we can't remove
  1558. // a user if it's an admin
  1559. const removedMemberId = modifier.$pull.members.userId;
  1560. return Boolean(
  1561. _.findWhere(doc.members, {
  1562. userId: removedMemberId,
  1563. isAdmin: true,
  1564. }),
  1565. );
  1566. },
  1567. fetch: ['members'],
  1568. });
  1569. Meteor.methods({
  1570. getBackgroundImageURL(boardId) {
  1571. check(boardId, String);
  1572. return ReactiveCache.getBoard(boardId, {}, { backgroundImageUrl: 1 });
  1573. },
  1574. quitBoard(boardId) {
  1575. check(boardId, String);
  1576. const board = ReactiveCache.getBoard(boardId);
  1577. if (board) {
  1578. const userId = Meteor.userId();
  1579. const index = board.memberIndex(userId);
  1580. if (index >= 0) {
  1581. board.removeMember(userId);
  1582. return true;
  1583. } else throw new Meteor.Error('error-board-notAMember');
  1584. } else throw new Meteor.Error('error-board-doesNotExist');
  1585. },
  1586. acceptInvite(boardId) {
  1587. check(boardId, String);
  1588. const board = ReactiveCache.getBoard(boardId);
  1589. if (!board) {
  1590. throw new Meteor.Error('error-board-doesNotExist');
  1591. }
  1592. Meteor.users.update(Meteor.userId(), {
  1593. $pull: {
  1594. 'profile.invitedBoards': boardId,
  1595. },
  1596. });
  1597. },
  1598. myLabelNames() {
  1599. let names = [];
  1600. Boards.userBoards(Meteor.userId()).forEach(board => {
  1601. // Only return labels when they exist.
  1602. if (board.labels !== undefined) {
  1603. names = names.concat(
  1604. board.labels
  1605. .filter(label => !!label.name)
  1606. .map(label => {
  1607. return label.name;
  1608. }),
  1609. );
  1610. } else {
  1611. return [];
  1612. }
  1613. });
  1614. return _.uniq(names).sort();
  1615. },
  1616. myBoardNames() {
  1617. return _.uniq(
  1618. Boards.userBoards(Meteor.userId()).map(board => {
  1619. return board.title;
  1620. }),
  1621. ).sort();
  1622. },
  1623. setAllBoardsHideActivities() {
  1624. if ((ReactiveCache.getCurrentUser() || {}).isAdmin) {
  1625. Boards.update(
  1626. {
  1627. showActivities: true
  1628. },
  1629. {
  1630. $set: {
  1631. showActivities: false,
  1632. },
  1633. },
  1634. {
  1635. multi: true,
  1636. },
  1637. );
  1638. return true;
  1639. } else {
  1640. return false;
  1641. }
  1642. },
  1643. });
  1644. Meteor.methods({
  1645. archiveBoard(boardId) {
  1646. check(boardId, String);
  1647. const board = ReactiveCache.getBoard(boardId);
  1648. if (board) {
  1649. const userId = Meteor.userId();
  1650. const index = board.memberIndex(userId);
  1651. if (index >= 0) {
  1652. board.archive();
  1653. return true;
  1654. } else throw new Meteor.Error('error-board-notAMember');
  1655. } else throw new Meteor.Error('error-board-doesNotExist');
  1656. },
  1657. setBoardOrgs(boardOrgsArray, currBoardId){
  1658. check(boardOrgsArray, Array);
  1659. check(currBoardId, String);
  1660. Boards.update(currBoardId, {
  1661. $set: {
  1662. orgs: boardOrgsArray,
  1663. },
  1664. });
  1665. },
  1666. setBoardTeams(boardTeamsArray, membersArray, currBoardId){
  1667. check(boardTeamsArray, Array);
  1668. check(membersArray, Array);
  1669. check(currBoardId, String);
  1670. Boards.update(currBoardId, {
  1671. $set: {
  1672. members: membersArray,
  1673. teams: boardTeamsArray,
  1674. },
  1675. });
  1676. },
  1677. });
  1678. }
  1679. // Insert new board at last position in sort order.
  1680. Boards.before.insert((userId, doc) => {
  1681. const lastBoard = ReactiveCache.getBoard(
  1682. { sort: { $exists: true } },
  1683. { sort: { sort: -1 } },
  1684. );
  1685. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1686. doc.sort = lastBoard.sort + 1;
  1687. }
  1688. });
  1689. if (Meteor.isServer) {
  1690. // Let MongoDB ensure that a member is not included twice in the same board
  1691. Meteor.startup(() => {
  1692. Boards._collection.createIndex({ modifiedAt: -1 });
  1693. Boards._collection.createIndex(
  1694. {
  1695. _id: 1,
  1696. 'members.userId': 1,
  1697. },
  1698. { unique: true },
  1699. );
  1700. Boards._collection.createIndex({ 'members.userId': 1 });
  1701. });
  1702. // Genesis: the first activity of the newly created board
  1703. Boards.after.insert((userId, doc) => {
  1704. Activities.insert({
  1705. userId,
  1706. type: 'board',
  1707. activityTypeId: doc._id,
  1708. activityType: 'createBoard',
  1709. boardId: doc._id,
  1710. });
  1711. });
  1712. // If the user remove one label from a board, we cant to remove reference of
  1713. // this label in any card of this board.
  1714. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1715. if (
  1716. !_.contains(fieldNames, 'labels') ||
  1717. !modifier.$pull ||
  1718. !modifier.$pull.labels ||
  1719. !modifier.$pull.labels._id
  1720. ) {
  1721. return;
  1722. }
  1723. const removedLabelId = modifier.$pull.labels._id;
  1724. Cards.update(
  1725. { boardId: doc._id },
  1726. {
  1727. $pull: {
  1728. labelIds: removedLabelId,
  1729. },
  1730. },
  1731. { multi: true },
  1732. );
  1733. });
  1734. const foreachRemovedMember = (doc, modifier, callback) => {
  1735. Object.keys(modifier).forEach(set => {
  1736. if (modifier[set] !== false) {
  1737. return;
  1738. }
  1739. const parts = set.split('.');
  1740. if (
  1741. parts.length === 3 &&
  1742. parts[0] === 'members' &&
  1743. parts[2] === 'isActive'
  1744. ) {
  1745. callback(doc.members[parts[1]].userId);
  1746. }
  1747. });
  1748. };
  1749. // Remove a member from all objects of the board before leaving the board
  1750. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1751. if (!_.contains(fieldNames, 'members')) {
  1752. return;
  1753. }
  1754. if (modifier.$set) {
  1755. const boardId = doc._id;
  1756. foreachRemovedMember(doc, modifier.$set, memberId => {
  1757. Cards.update(
  1758. { boardId },
  1759. {
  1760. $pull: {
  1761. members: memberId,
  1762. watchers: memberId,
  1763. },
  1764. },
  1765. { multi: true },
  1766. );
  1767. Lists.update(
  1768. { boardId },
  1769. {
  1770. $pull: {
  1771. watchers: memberId,
  1772. },
  1773. },
  1774. { multi: true },
  1775. );
  1776. const board = Boards._transform(doc);
  1777. board.setWatcher(memberId, false);
  1778. // Remove board from users starred list
  1779. if (!board.isPublic()) {
  1780. Users.update(memberId, {
  1781. $pull: {
  1782. 'profile.starredBoards': boardId,
  1783. },
  1784. });
  1785. }
  1786. });
  1787. }
  1788. });
  1789. Boards.before.remove((userId, doc) => {
  1790. boardRemover(userId, doc);
  1791. // Add removeBoard activity to keep it
  1792. Activities.insert({
  1793. userId,
  1794. type: 'board',
  1795. activityTypeId: doc._id,
  1796. activityType: 'removeBoard',
  1797. boardId: doc._id,
  1798. });
  1799. });
  1800. // Add a new activity if we add or remove a member to the board
  1801. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1802. if (fieldNames.includes('title')) {
  1803. Activities.insert({
  1804. userId,
  1805. type: 'board',
  1806. activityType: 'changedBoardTitle',
  1807. boardId: doc._id,
  1808. // this preserves the name so that the activity can be useful after the
  1809. // list is deleted
  1810. title: doc.title,
  1811. });
  1812. }
  1813. if (!_.contains(fieldNames, 'members')) {
  1814. return;
  1815. }
  1816. // Say hello to the new member
  1817. if (modifier.$push && modifier.$push.members) {
  1818. const memberId = modifier.$push.members.userId;
  1819. Activities.insert({
  1820. userId,
  1821. memberId,
  1822. type: 'member',
  1823. activityType: 'addBoardMember',
  1824. boardId: doc._id,
  1825. });
  1826. }
  1827. // Say goodbye to the former member
  1828. if (modifier.$set) {
  1829. foreachRemovedMember(doc, modifier.$set, memberId => {
  1830. Activities.insert({
  1831. userId,
  1832. memberId,
  1833. type: 'member',
  1834. activityType: 'removeBoardMember',
  1835. boardId: doc._id,
  1836. });
  1837. });
  1838. }
  1839. });
  1840. }
  1841. //BOARDS REST API
  1842. if (Meteor.isServer) {
  1843. /**
  1844. * @operation get_boards_from_user
  1845. * @summary Get all boards attached to a user
  1846. *
  1847. * @param {string} userId the ID of the user to retrieve the data
  1848. * @return_type [{_id: string,
  1849. * title: string}]
  1850. */
  1851. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1852. try {
  1853. Authentication.checkLoggedIn(req.userId);
  1854. const paramUserId = req.params.userId;
  1855. // A normal user should be able to see their own boards,
  1856. // admins can access boards of any user
  1857. Authentication.checkAdminOrCondition(
  1858. req.userId,
  1859. req.userId === paramUserId,
  1860. );
  1861. const data = ReactiveCache.getBoards(
  1862. {
  1863. archived: false,
  1864. 'members.userId': paramUserId,
  1865. },
  1866. {
  1867. sort: { sort: 1 /* boards default sorting */ },
  1868. },
  1869. ).map(function(board) {
  1870. return {
  1871. _id: board._id,
  1872. title: board.title,
  1873. };
  1874. });
  1875. JsonRoutes.sendResult(res, { code: 200, data });
  1876. } catch (error) {
  1877. JsonRoutes.sendResult(res, {
  1878. code: 200,
  1879. data: error,
  1880. });
  1881. }
  1882. });
  1883. /**
  1884. * @operation get_public_boards
  1885. * @summary Get all public boards
  1886. *
  1887. * @return_type [{_id: string,
  1888. title: string}]
  1889. */
  1890. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1891. try {
  1892. Authentication.checkUserId(req.userId);
  1893. JsonRoutes.sendResult(res, {
  1894. code: 200,
  1895. data: ReactiveCache.getBoards(
  1896. { permission: 'public' },
  1897. {
  1898. sort: { sort: 1 /* boards default sorting */ },
  1899. },
  1900. ).map(function(doc) {
  1901. return {
  1902. _id: doc._id,
  1903. title: doc.title,
  1904. };
  1905. }),
  1906. });
  1907. } catch (error) {
  1908. JsonRoutes.sendResult(res, {
  1909. code: 200,
  1910. data: error,
  1911. });
  1912. }
  1913. });
  1914. /**
  1915. * @operation get_boards_count
  1916. * @summary Get public and private boards count
  1917. *
  1918. * @return_type {private: integer, public: integer}
  1919. */
  1920. JsonRoutes.add('GET', '/api/boards_count', function(req, res) {
  1921. try {
  1922. Authentication.checkUserId(req.userId);
  1923. JsonRoutes.sendResult(res, {
  1924. code: 200,
  1925. data: {
  1926. private: ReactiveCache.getBoards({ permission: 'private' }).length,
  1927. public: ReactiveCache.getBoards({ permission: 'public' }).length,
  1928. },
  1929. });
  1930. } catch (error) {
  1931. JsonRoutes.sendResult(res, {
  1932. code: 200,
  1933. data: error,
  1934. });
  1935. }
  1936. });
  1937. /**
  1938. * @operation get_board
  1939. * @summary Get the board with that particular ID
  1940. *
  1941. * @param {string} boardId the ID of the board to retrieve the data
  1942. * @return_type Boards
  1943. */
  1944. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1945. try {
  1946. const paramBoardId = req.params.boardId;
  1947. Authentication.checkBoardAccess(req.userId, paramBoardId);
  1948. JsonRoutes.sendResult(res, {
  1949. code: 200,
  1950. data: ReactiveCache.getBoard(paramBoardId),
  1951. });
  1952. } catch (error) {
  1953. JsonRoutes.sendResult(res, {
  1954. code: 200,
  1955. data: error,
  1956. });
  1957. }
  1958. });
  1959. /**
  1960. * @operation new_board
  1961. * @summary Create a board
  1962. *
  1963. * @description This allows to create a board.
  1964. *
  1965. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1966. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1967. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1968. *
  1969. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1970. *
  1971. * @param {string} title the new title of the board
  1972. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1973. * (Not username or email)
  1974. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1975. * @param {boolean} [isActive] is the board active (default true)
  1976. * @param {boolean} [isNoComments] disable comments (default false)
  1977. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1978. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1979. * @param {string} [permission] "private" board <== Set to "public" if you
  1980. * want public Wekan board
  1981. * @param {string} [color] the color of the board
  1982. *
  1983. * @return_type {_id: string,
  1984. defaultSwimlaneId: string}
  1985. */
  1986. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1987. try {
  1988. Authentication.checkLoggedIn(req.userId);
  1989. const id = Boards.insert({
  1990. title: req.body.title,
  1991. members: [
  1992. {
  1993. userId: req.body.owner,
  1994. isAdmin: req.body.isAdmin || true,
  1995. isActive: req.body.isActive || true,
  1996. isNoComments: req.body.isNoComments || false,
  1997. isCommentOnly: req.body.isCommentOnly || false,
  1998. isWorker: req.body.isWorker || false,
  1999. },
  2000. ],
  2001. permission: req.body.permission || 'private',
  2002. color: req.body.color || 'belize',
  2003. migrationVersion: 1, // Latest version - no migration needed
  2004. });
  2005. const swimlaneId = Swimlanes.insert({
  2006. title: TAPi18n && TAPi18n.i18n ? TAPi18n.__('default') : 'Default',
  2007. boardId: id,
  2008. });
  2009. JsonRoutes.sendResult(res, {
  2010. code: 200,
  2011. data: {
  2012. _id: id,
  2013. defaultSwimlaneId: swimlaneId,
  2014. },
  2015. });
  2016. } catch (error) {
  2017. JsonRoutes.sendResult(res, {
  2018. code: 200,
  2019. data: error,
  2020. });
  2021. }
  2022. });
  2023. /**
  2024. * @operation delete_board
  2025. * @summary Delete a board
  2026. *
  2027. * @param {string} boardId the ID of the board
  2028. */
  2029. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  2030. try {
  2031. Authentication.checkUserId(req.userId);
  2032. const id = req.params.boardId;
  2033. Boards.remove({ _id: id });
  2034. JsonRoutes.sendResult(res, {
  2035. code: 200,
  2036. data: {
  2037. _id: id,
  2038. },
  2039. });
  2040. } catch (error) {
  2041. JsonRoutes.sendResult(res, {
  2042. code: 200,
  2043. data: error,
  2044. });
  2045. }
  2046. });
  2047. /**
  2048. * @operation update_board_title
  2049. * @summary Update the title of a board
  2050. *
  2051. * @param {string} boardId the ID of the board to update
  2052. * @param {string} title the new title for the board
  2053. */
  2054. JsonRoutes.add('PUT', '/api/boards/:boardId/title', function(req, res) {
  2055. try {
  2056. Authentication.checkUserId(req.userId);
  2057. const boardId = req.params.boardId;
  2058. const title = req.body.title;
  2059. Boards.direct.update({ _id: boardId }, { $set: { title } });
  2060. JsonRoutes.sendResult(res, {
  2061. code: 200,
  2062. data: {
  2063. _id: boardId,
  2064. title,
  2065. },
  2066. });
  2067. } catch (error) {
  2068. JsonRoutes.sendResult(res, {
  2069. code: 200,
  2070. data: error,
  2071. });
  2072. }
  2073. });
  2074. /**
  2075. * @operation add_board_label
  2076. * @summary Add a label to a board
  2077. *
  2078. * @description If the board doesn't have the name/color label, this function
  2079. * adds the label to the board.
  2080. *
  2081. * @param {string} boardId the board
  2082. * @param {string} color the color of the new label
  2083. * @param {string} name the name of the new label
  2084. *
  2085. * @return_type string
  2086. */
  2087. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  2088. const id = req.params.boardId;
  2089. Authentication.checkBoardAccess(req.userId, id);
  2090. try {
  2091. if (req.body.hasOwnProperty('label')) {
  2092. const board = ReactiveCache.getBoard(id);
  2093. const color = req.body.label.color;
  2094. const name = req.body.label.name;
  2095. const labelId = Random.id(6);
  2096. if (!board.getLabel(name, color)) {
  2097. Boards.direct.update(
  2098. { _id: id },
  2099. { $push: { labels: { _id: labelId, name, color } } },
  2100. );
  2101. JsonRoutes.sendResult(res, {
  2102. code: 200,
  2103. data: labelId,
  2104. });
  2105. } else {
  2106. JsonRoutes.sendResult(res, {
  2107. code: 200,
  2108. });
  2109. }
  2110. }
  2111. } catch (error) {
  2112. JsonRoutes.sendResult(res, {
  2113. data: error,
  2114. });
  2115. }
  2116. });
  2117. /**
  2118. * @operation copy_board
  2119. * @summary Copy a board to a new one
  2120. *
  2121. * @description If your are board admin or wekan admin, this copies the
  2122. * given board to a new one.
  2123. *
  2124. * @param {string} boardId the board
  2125. * @param {string} title the title of the new board (default to old one)
  2126. *
  2127. * @return_type string
  2128. */
  2129. JsonRoutes.add('POST', '/api/boards/:boardId/copy', function(req, res) {
  2130. const id = req.params.boardId;
  2131. const board = ReactiveCache.getBoard(id);
  2132. const adminAccess = board.members.some(e => e.userId === req.userId && e.isAdmin);
  2133. Authentication.checkAdminOrCondition(req.userId, adminAccess);
  2134. try {
  2135. board['title'] = req.body.title || Boards.uniqueTitle(board.title);
  2136. ret = board.copy();
  2137. JsonRoutes.sendResult(res, {
  2138. code: 200,
  2139. data: ret,
  2140. });
  2141. } catch (error) {
  2142. JsonRoutes.sendResult(res, {
  2143. data: error,
  2144. });
  2145. }
  2146. });
  2147. /**
  2148. * @operation set_board_member_permission
  2149. * @tag Users
  2150. * @summary Change the permission of a member of a board
  2151. *
  2152. * @param {string} boardId the ID of the board that we are changing
  2153. * @param {string} memberId the ID of the user to change permissions
  2154. * @param {boolean} isAdmin admin capability
  2155. * @param {boolean} isNoComments NoComments capability
  2156. * @param {boolean} isCommentOnly CommentsOnly capability
  2157. * @param {boolean} isWorker Worker capability
  2158. */
  2159. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  2160. req,
  2161. res,
  2162. ) {
  2163. try {
  2164. Authentication.checkUserId(req.userId);
  2165. const boardId = req.params.boardId;
  2166. const memberId = req.params.memberId;
  2167. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  2168. const board = ReactiveCache.getBoard(boardId);
  2169. function isTrue(data) {
  2170. try {
  2171. return data.toLowerCase() === 'true';
  2172. } catch (error) {
  2173. return data;
  2174. }
  2175. }
  2176. const query = board.setMemberPermission(
  2177. memberId,
  2178. isTrue(isAdmin),
  2179. isTrue(isNoComments),
  2180. isTrue(isCommentOnly),
  2181. isTrue(isWorker),
  2182. req.userId,
  2183. );
  2184. JsonRoutes.sendResult(res, {
  2185. code: 200,
  2186. data: query,
  2187. });
  2188. } catch (error) {
  2189. JsonRoutes.sendResult(res, {
  2190. code: 200,
  2191. data: error,
  2192. });
  2193. }
  2194. });
  2195. //ATTACHMENTS REST API
  2196. /**
  2197. * @operation get_board_attachments
  2198. * @summary Get the list of attachments of a board
  2199. *
  2200. * @param {string} boardId the board ID
  2201. * @return_type [{attachmentId: string,
  2202. * attachmentName: string,
  2203. * attachmentType: string,
  2204. * url: string,
  2205. * urlDownload: string,
  2206. * boardId: string,
  2207. * swimlaneId: string,
  2208. * listId: string,
  2209. * cardId: string
  2210. * }]
  2211. */
  2212. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  2213. const paramBoardId = req.params.boardId;
  2214. Authentication.checkBoardAccess(req.userId, paramBoardId);
  2215. JsonRoutes.sendResult(res, {
  2216. code: 200,
  2217. data: ReactiveCache
  2218. .getAttachments({'meta.boardId': paramBoardId }, {}, true)
  2219. .each()
  2220. .map(function(attachment) {
  2221. return {
  2222. attachmentId: attachment._id,
  2223. attachmentName: attachment.name,
  2224. attachmentType: attachment.type,
  2225. url: attachment.link(),
  2226. urlDownload: `${attachment.link()}?download=true&token=`,
  2227. boardId: attachment.meta.boardId,
  2228. swimlaneId: attachment.meta.swimlaneId,
  2229. listId: attachment.meta.listId,
  2230. cardId: attachment.meta.cardId
  2231. };
  2232. }),
  2233. });
  2234. });
  2235. }
  2236. export default Boards;