boards.js 55 KB

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