boards.js 63 KB

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