boards.js 46 KB

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