2
0

boards.js 46 KB

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