boards.js 55 KB

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