boards.js 49 KB

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