boards.js 54 KB

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