boards.js 60 KB

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