boards.js 60 KB

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