boards.js 47 KB

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