boards.js 47 KB

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