boards.js 60 KB

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