boards.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. Boards = new Mongo.Collection('boards');
  2. /**
  3. * This is a Board.
  4. */
  5. Boards.attachSchema(
  6. new SimpleSchema({
  7. title: {
  8. /**
  9. * The title of the board
  10. */
  11. type: String,
  12. },
  13. slug: {
  14. /**
  15. * The title slugified.
  16. */
  17. type: String,
  18. // eslint-disable-next-line consistent-return
  19. autoValue() {
  20. // XXX We need to improve slug management. Only the id should be necessary
  21. // to identify a board in the code.
  22. // XXX If the board title is updated, the slug should also be updated.
  23. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  24. // return an empty string. This is causes bugs in our application so we set
  25. // a default slug in this case.
  26. if (this.isInsert && !this.isSet) {
  27. let slug = 'board';
  28. const title = this.field('title');
  29. if (title.isSet) {
  30. slug = getSlug(title.value) || slug;
  31. }
  32. return slug;
  33. }
  34. },
  35. },
  36. archived: {
  37. /**
  38. * Is the board archived?
  39. */
  40. type: Boolean,
  41. // eslint-disable-next-line consistent-return
  42. autoValue() {
  43. if (this.isInsert && !this.isSet) {
  44. return false;
  45. }
  46. },
  47. },
  48. createdAt: {
  49. /**
  50. * Creation time of the board
  51. */
  52. type: Date,
  53. // eslint-disable-next-line consistent-return
  54. autoValue() {
  55. if (this.isInsert) {
  56. return new Date();
  57. } else {
  58. this.unset();
  59. }
  60. },
  61. },
  62. // XXX Inconsistent field naming
  63. modifiedAt: {
  64. /**
  65. * Last modification time of the board
  66. */
  67. type: Date,
  68. optional: true,
  69. // eslint-disable-next-line consistent-return
  70. autoValue() {
  71. if (this.isInsert || this.isUpsert || this.isUpdate) {
  72. return new Date();
  73. } else {
  74. this.unset();
  75. }
  76. },
  77. },
  78. // De-normalized number of users that have starred this board
  79. stars: {
  80. /**
  81. * How many stars the board has
  82. */
  83. type: Number,
  84. // eslint-disable-next-line consistent-return
  85. autoValue() {
  86. if (this.isInsert) {
  87. return 0;
  88. }
  89. },
  90. },
  91. // De-normalized label system
  92. labels: {
  93. /**
  94. * List of labels attached to a board
  95. */
  96. type: [Object],
  97. // eslint-disable-next-line consistent-return
  98. autoValue() {
  99. if (this.isInsert && !this.isSet) {
  100. const colors = Boards.simpleSchema()._schema['labels.$.color']
  101. .allowedValues;
  102. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  103. return defaultLabelsColors.map(color => ({
  104. color,
  105. _id: Random.id(6),
  106. name: '',
  107. }));
  108. }
  109. },
  110. },
  111. 'labels.$._id': {
  112. /**
  113. * Unique id of a label
  114. */
  115. // We don't specify that this field must be unique in the board because that
  116. // will cause performance penalties and is not necessary since this field is
  117. // always set on the server.
  118. // XXX Actually if we create a new label, the `_id` is set on the client
  119. // without being overwritten by the server, could it be a problem?
  120. type: String,
  121. },
  122. 'labels.$.name': {
  123. /**
  124. * Name of a label
  125. */
  126. type: String,
  127. optional: true,
  128. },
  129. 'labels.$.color': {
  130. /**
  131. * color of a label.
  132. *
  133. * Can be amongst `green`, `yellow`, `orange`, `red`, `purple`,
  134. * `blue`, `sky`, `lime`, `pink`, `black`,
  135. * `silver`, `peachpuff`, `crimson`, `plum`, `darkgreen`,
  136. * `slateblue`, `magenta`, `gold`, `navy`, `gray`,
  137. * `saddlebrown`, `paleturquoise`, `mistyrose`, `indigo`
  138. */
  139. type: String,
  140. allowedValues: [
  141. 'green',
  142. 'yellow',
  143. 'orange',
  144. 'red',
  145. 'purple',
  146. 'blue',
  147. 'sky',
  148. 'lime',
  149. 'pink',
  150. 'black',
  151. 'silver',
  152. 'peachpuff',
  153. 'crimson',
  154. 'plum',
  155. 'darkgreen',
  156. 'slateblue',
  157. 'magenta',
  158. 'gold',
  159. 'navy',
  160. 'gray',
  161. 'saddlebrown',
  162. 'paleturquoise',
  163. 'mistyrose',
  164. 'indigo',
  165. ],
  166. },
  167. // XXX We might want to maintain more informations under the member sub-
  168. // documents like de-normalized meta-data (the date the member joined the
  169. // board, the number of contributions, etc.).
  170. members: {
  171. /**
  172. * List of members of a board
  173. */
  174. type: [Object],
  175. // eslint-disable-next-line consistent-return
  176. autoValue() {
  177. if (this.isInsert && !this.isSet) {
  178. return [
  179. {
  180. userId: this.userId,
  181. isAdmin: true,
  182. isActive: true,
  183. isNoComments: false,
  184. isCommentOnly: 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. permission: {
  223. /**
  224. * visibility of the board
  225. */
  226. type: String,
  227. allowedValues: ['public', 'private'],
  228. },
  229. color: {
  230. /**
  231. * The color of the board.
  232. */
  233. type: String,
  234. allowedValues: [
  235. 'belize',
  236. 'nephritis',
  237. 'pomegranate',
  238. 'pumpkin',
  239. 'wisteria',
  240. 'moderatepink',
  241. 'strongcyan',
  242. 'limegreen',
  243. 'midnight',
  244. 'dark',
  245. 'relax',
  246. 'corteza',
  247. ],
  248. // eslint-disable-next-line consistent-return
  249. autoValue() {
  250. if (this.isInsert && !this.isSet) {
  251. return Boards.simpleSchema()._schema.color.allowedValues[0];
  252. }
  253. },
  254. },
  255. description: {
  256. /**
  257. * The description of the board
  258. */
  259. type: String,
  260. optional: true,
  261. },
  262. subtasksDefaultBoardId: {
  263. /**
  264. * The default board ID assigned to subtasks.
  265. */
  266. type: String,
  267. optional: true,
  268. defaultValue: null,
  269. },
  270. subtasksDefaultListId: {
  271. /**
  272. * The default List ID assigned to subtasks.
  273. */
  274. type: String,
  275. optional: true,
  276. defaultValue: null,
  277. },
  278. allowsSubtasks: {
  279. /**
  280. * Does the board allows subtasks?
  281. */
  282. type: Boolean,
  283. defaultValue: true,
  284. },
  285. presentParentTask: {
  286. /**
  287. * Controls how to present the parent task:
  288. *
  289. * - `prefix-with-full-path`: add a prefix with the full path
  290. * - `prefix-with-parent`: add a prefisx with the parent name
  291. * - `subtext-with-full-path`: add a subtext with the full path
  292. * - `subtext-with-parent`: add a subtext with the parent name
  293. * - `no-parent`: does not show the parent at all
  294. */
  295. type: String,
  296. allowedValues: [
  297. 'prefix-with-full-path',
  298. 'prefix-with-parent',
  299. 'subtext-with-full-path',
  300. 'subtext-with-parent',
  301. 'no-parent',
  302. ],
  303. optional: true,
  304. defaultValue: 'no-parent',
  305. },
  306. startAt: {
  307. /**
  308. * Starting date of the board.
  309. */
  310. type: Date,
  311. optional: true,
  312. },
  313. dueAt: {
  314. /**
  315. * Due date of the board.
  316. */
  317. type: Date,
  318. optional: true,
  319. },
  320. endAt: {
  321. /**
  322. * End date of the board.
  323. */
  324. type: Date,
  325. optional: true,
  326. },
  327. spentTime: {
  328. /**
  329. * Time spent in the board.
  330. */
  331. type: Number,
  332. decimal: true,
  333. optional: true,
  334. },
  335. isOvertime: {
  336. /**
  337. * Is the board overtimed?
  338. */
  339. type: Boolean,
  340. defaultValue: false,
  341. optional: true,
  342. },
  343. type: {
  344. /**
  345. * The type of board
  346. */
  347. type: String,
  348. defaultValue: 'board',
  349. },
  350. }),
  351. );
  352. Boards.helpers({
  353. copy() {
  354. const oldId = this._id;
  355. delete this._id;
  356. const _id = Boards.insert(this);
  357. // Copy all swimlanes in board
  358. Swimlanes.find({
  359. boardId: oldId,
  360. archived: false,
  361. }).forEach(swimlane => {
  362. swimlane.type = 'swimlane';
  363. swimlane.copy(_id);
  364. });
  365. },
  366. /**
  367. * Is supplied user authorized to view this board?
  368. */
  369. isVisibleBy(user) {
  370. if (this.isPublic()) {
  371. // public boards are visible to everyone
  372. return true;
  373. } else {
  374. // otherwise you have to be logged-in and active member
  375. return user && this.isActiveMember(user._id);
  376. }
  377. },
  378. /**
  379. * Is the user one of the active members of the board?
  380. *
  381. * @param userId
  382. * @returns {boolean} the member that matches, or undefined/false
  383. */
  384. isActiveMember(userId) {
  385. if (userId) {
  386. return this.members.find(
  387. member => member.userId === userId && member.isActive,
  388. );
  389. } else {
  390. return false;
  391. }
  392. },
  393. isPublic() {
  394. return this.permission === 'public';
  395. },
  396. cards() {
  397. return Cards.find(
  398. { boardId: this._id, archived: false },
  399. { sort: { title: 1 } },
  400. );
  401. },
  402. lists() {
  403. return Lists.find(
  404. { boardId: this._id, archived: false },
  405. { sort: { sort: 1 } },
  406. );
  407. },
  408. nullSortLists() {
  409. return Lists.find({
  410. boardId: this._id,
  411. archived: false,
  412. sort: { $eq: null },
  413. });
  414. },
  415. swimlanes() {
  416. return Swimlanes.find(
  417. { boardId: this._id, archived: false },
  418. { sort: { sort: 1 } },
  419. );
  420. },
  421. nextSwimlane(swimlane) {
  422. return Swimlanes.findOne(
  423. {
  424. boardId: this._id,
  425. archived: false,
  426. sort: { $gte: swimlane.sort },
  427. _id: { $ne: swimlane._id },
  428. },
  429. {
  430. sort: { sort: 1 },
  431. },
  432. );
  433. },
  434. nullSortSwimlanes() {
  435. return Swimlanes.find({
  436. boardId: this._id,
  437. archived: false,
  438. sort: { $eq: null },
  439. });
  440. },
  441. hasOvertimeCards() {
  442. const card = Cards.findOne({
  443. isOvertime: true,
  444. boardId: this._id,
  445. archived: false,
  446. });
  447. return card !== undefined;
  448. },
  449. hasSpentTimeCards() {
  450. const card = Cards.findOne({
  451. spentTime: { $gt: 0 },
  452. boardId: this._id,
  453. archived: false,
  454. });
  455. return card !== undefined;
  456. },
  457. activities() {
  458. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  459. },
  460. activeMembers() {
  461. return _.where(this.members, { isActive: true });
  462. },
  463. activeAdmins() {
  464. return _.where(this.members, { isActive: true, isAdmin: true });
  465. },
  466. memberUsers() {
  467. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  468. },
  469. getLabel(name, color) {
  470. return _.findWhere(this.labels, { name, color });
  471. },
  472. getLabelById(labelId) {
  473. return _.findWhere(this.labels, { _id: labelId });
  474. },
  475. labelIndex(labelId) {
  476. return _.pluck(this.labels, '_id').indexOf(labelId);
  477. },
  478. memberIndex(memberId) {
  479. return _.pluck(this.members, 'userId').indexOf(memberId);
  480. },
  481. hasMember(memberId) {
  482. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  483. },
  484. hasAdmin(memberId) {
  485. return !!_.findWhere(this.members, {
  486. userId: memberId,
  487. isActive: true,
  488. isAdmin: true,
  489. });
  490. },
  491. hasNoComments(memberId) {
  492. return !!_.findWhere(this.members, {
  493. userId: memberId,
  494. isActive: true,
  495. isAdmin: false,
  496. isNoComments: true,
  497. });
  498. },
  499. hasCommentOnly(memberId) {
  500. return !!_.findWhere(this.members, {
  501. userId: memberId,
  502. isActive: true,
  503. isAdmin: false,
  504. isCommentOnly: true,
  505. });
  506. },
  507. absoluteUrl() {
  508. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  509. },
  510. colorClass() {
  511. return `board-color-${this.color}`;
  512. },
  513. customFields() {
  514. return CustomFields.find(
  515. { boardIds: { $in: [this._id] } },
  516. { sort: { name: 1 } },
  517. );
  518. },
  519. // XXX currently mutations return no value so we have an issue when using addLabel in import
  520. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  521. pushLabel(name, color) {
  522. const _id = Random.id(6);
  523. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  524. return _id;
  525. },
  526. searchBoards(term) {
  527. check(term, Match.OneOf(String, null, undefined));
  528. const query = { boardId: this._id };
  529. query.type = 'cardType-linkedBoard';
  530. query.archived = false;
  531. const projection = { limit: 10, sort: { createdAt: -1 } };
  532. if (term) {
  533. const regex = new RegExp(term, 'i');
  534. query.$or = [{ title: regex }, { description: regex }];
  535. }
  536. return Cards.find(query, projection);
  537. },
  538. searchSwimlanes(term) {
  539. check(term, Match.OneOf(String, null, undefined));
  540. const query = { boardId: this._id };
  541. if (this.isTemplatesBoard()) {
  542. query.type = 'template-swimlane';
  543. query.archived = false;
  544. } else {
  545. query.type = { $nin: ['template-swimlane'] };
  546. }
  547. const projection = { limit: 10, sort: { createdAt: -1 } };
  548. if (term) {
  549. const regex = new RegExp(term, 'i');
  550. query.$or = [{ title: regex }, { description: regex }];
  551. }
  552. return Swimlanes.find(query, projection);
  553. },
  554. searchLists(term) {
  555. check(term, Match.OneOf(String, null, undefined));
  556. const query = { boardId: this._id };
  557. if (this.isTemplatesBoard()) {
  558. query.type = 'template-list';
  559. query.archived = false;
  560. } else {
  561. query.type = { $nin: ['template-list'] };
  562. }
  563. const projection = { limit: 10, sort: { createdAt: -1 } };
  564. if (term) {
  565. const regex = new RegExp(term, 'i');
  566. query.$or = [{ title: regex }, { description: regex }];
  567. }
  568. return Lists.find(query, projection);
  569. },
  570. searchCards(term, excludeLinked) {
  571. check(term, Match.OneOf(String, null, undefined));
  572. const query = { boardId: this._id };
  573. if (excludeLinked) {
  574. query.linkedId = null;
  575. }
  576. if (this.isTemplatesBoard()) {
  577. query.type = 'template-card';
  578. query.archived = false;
  579. } else {
  580. query.type = { $nin: ['template-card'] };
  581. }
  582. const projection = { limit: 10, sort: { createdAt: -1 } };
  583. if (term) {
  584. const regex = new RegExp(term, 'i');
  585. query.$or = [{ title: regex }, { description: regex }];
  586. }
  587. return Cards.find(query, projection);
  588. },
  589. // A board alwasy has another board where it deposits subtasks of thasks
  590. // that belong to itself.
  591. getDefaultSubtasksBoardId() {
  592. if (
  593. this.subtasksDefaultBoardId === null ||
  594. this.subtasksDefaultBoardId === undefined
  595. ) {
  596. this.subtasksDefaultBoardId = Boards.insert({
  597. title: `^${this.title}^`,
  598. permission: this.permission,
  599. members: this.members,
  600. color: this.color,
  601. description: TAPi18n.__('default-subtasks-board', {
  602. board: this.title,
  603. }),
  604. });
  605. Swimlanes.insert({
  606. title: TAPi18n.__('default'),
  607. boardId: this.subtasksDefaultBoardId,
  608. });
  609. Boards.update(this._id, {
  610. $set: {
  611. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  612. },
  613. });
  614. }
  615. return this.subtasksDefaultBoardId;
  616. },
  617. getDefaultSubtasksBoard() {
  618. return Boards.findOne(this.getDefaultSubtasksBoardId());
  619. },
  620. getDefaultSubtasksListId() {
  621. if (
  622. this.subtasksDefaultListId === null ||
  623. this.subtasksDefaultListId === undefined
  624. ) {
  625. this.subtasksDefaultListId = Lists.insert({
  626. title: TAPi18n.__('queue'),
  627. boardId: this._id,
  628. });
  629. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  630. }
  631. return this.subtasksDefaultListId;
  632. },
  633. getDefaultSubtasksList() {
  634. return Lists.findOne(this.getDefaultSubtasksListId());
  635. },
  636. getDefaultSwimline() {
  637. let result = Swimlanes.findOne({ boardId: this._id });
  638. if (result === undefined) {
  639. Swimlanes.insert({
  640. title: TAPi18n.__('default'),
  641. boardId: this._id,
  642. });
  643. result = Swimlanes.findOne({ boardId: this._id });
  644. }
  645. return result;
  646. },
  647. cardsInInterval(start, end) {
  648. return Cards.find({
  649. boardId: this._id,
  650. $or: [
  651. {
  652. startAt: {
  653. $lte: start,
  654. },
  655. endAt: {
  656. $gte: start,
  657. },
  658. },
  659. {
  660. startAt: {
  661. $lte: end,
  662. },
  663. endAt: {
  664. $gte: end,
  665. },
  666. },
  667. {
  668. startAt: {
  669. $gte: start,
  670. },
  671. endAt: {
  672. $lte: end,
  673. },
  674. },
  675. ],
  676. });
  677. },
  678. isTemplateBoard() {
  679. return this.type === 'template-board';
  680. },
  681. isTemplatesBoard() {
  682. return this.type === 'template-container';
  683. },
  684. });
  685. Boards.mutations({
  686. archive() {
  687. return { $set: { archived: true } };
  688. },
  689. restore() {
  690. return { $set: { archived: false } };
  691. },
  692. rename(title) {
  693. return { $set: { title } };
  694. },
  695. setDescription(description) {
  696. return { $set: { description } };
  697. },
  698. setColor(color) {
  699. return { $set: { color } };
  700. },
  701. setVisibility(visibility) {
  702. return { $set: { permission: visibility } };
  703. },
  704. addLabel(name, color) {
  705. // If label with the same name and color already exists we don't want to
  706. // create another one because they would be indistinguishable in the UI
  707. // (they would still have different `_id` but that is not exposed to the
  708. // user).
  709. if (!this.getLabel(name, color)) {
  710. const _id = Random.id(6);
  711. return { $push: { labels: { _id, name, color } } };
  712. }
  713. return {};
  714. },
  715. editLabel(labelId, name, color) {
  716. if (!this.getLabel(name, color)) {
  717. const labelIndex = this.labelIndex(labelId);
  718. return {
  719. $set: {
  720. [`labels.${labelIndex}.name`]: name,
  721. [`labels.${labelIndex}.color`]: color,
  722. },
  723. };
  724. }
  725. return {};
  726. },
  727. removeLabel(labelId) {
  728. return { $pull: { labels: { _id: labelId } } };
  729. },
  730. changeOwnership(fromId, toId) {
  731. const memberIndex = this.memberIndex(fromId);
  732. return {
  733. $set: {
  734. [`members.${memberIndex}.userId`]: toId,
  735. },
  736. };
  737. },
  738. addMember(memberId) {
  739. const memberIndex = this.memberIndex(memberId);
  740. if (memberIndex >= 0) {
  741. return {
  742. $set: {
  743. [`members.${memberIndex}.isActive`]: true,
  744. },
  745. };
  746. }
  747. return {
  748. $push: {
  749. members: {
  750. userId: memberId,
  751. isAdmin: false,
  752. isActive: true,
  753. isNoComments: false,
  754. isCommentOnly: false,
  755. },
  756. },
  757. };
  758. },
  759. removeMember(memberId) {
  760. const memberIndex = this.memberIndex(memberId);
  761. // we do not allow the only one admin to be removed
  762. const allowRemove =
  763. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  764. if (!allowRemove) {
  765. return {
  766. $set: {
  767. [`members.${memberIndex}.isActive`]: true,
  768. },
  769. };
  770. }
  771. return {
  772. $set: {
  773. [`members.${memberIndex}.isActive`]: false,
  774. [`members.${memberIndex}.isAdmin`]: false,
  775. },
  776. };
  777. },
  778. setMemberPermission(
  779. memberId,
  780. isAdmin,
  781. isNoComments,
  782. isCommentOnly,
  783. currentUserId = Meteor.userId(),
  784. ) {
  785. const memberIndex = this.memberIndex(memberId);
  786. // do not allow change permission of self
  787. if (memberId === currentUserId) {
  788. isAdmin = this.members[memberIndex].isAdmin;
  789. }
  790. return {
  791. $set: {
  792. [`members.${memberIndex}.isAdmin`]: isAdmin,
  793. [`members.${memberIndex}.isNoComments`]: isNoComments,
  794. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  795. },
  796. };
  797. },
  798. setAllowsSubtasks(allowsSubtasks) {
  799. return { $set: { allowsSubtasks } };
  800. },
  801. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  802. return { $set: { subtasksDefaultBoardId } };
  803. },
  804. setSubtasksDefaultListId(subtasksDefaultListId) {
  805. return { $set: { subtasksDefaultListId } };
  806. },
  807. setPresentParentTask(presentParentTask) {
  808. return { $set: { presentParentTask } };
  809. },
  810. });
  811. function boardRemover(userId, doc) {
  812. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  813. element => {
  814. element.remove({ boardId: doc._id });
  815. },
  816. );
  817. }
  818. if (Meteor.isServer) {
  819. Boards.allow({
  820. insert: Meteor.userId,
  821. update: allowIsBoardAdmin,
  822. remove: allowIsBoardAdmin,
  823. fetch: ['members'],
  824. });
  825. // The number of users that have starred this board is managed by trusted code
  826. // and the user is not allowed to update it
  827. Boards.deny({
  828. update(userId, board, fieldNames) {
  829. return _.contains(fieldNames, 'stars');
  830. },
  831. fetch: [],
  832. });
  833. // We can't remove a member if it is the last administrator
  834. Boards.deny({
  835. update(userId, doc, fieldNames, modifier) {
  836. if (!_.contains(fieldNames, 'members')) return false;
  837. // We only care in case of a $pull operation, ie remove a member
  838. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  839. // If there is more than one admin, it's ok to remove anyone
  840. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  841. .length;
  842. if (nbAdmins > 1) return false;
  843. // If all the previous conditions were verified, we can't remove
  844. // a user if it's an admin
  845. const removedMemberId = modifier.$pull.members.userId;
  846. return Boolean(
  847. _.findWhere(doc.members, {
  848. userId: removedMemberId,
  849. isAdmin: true,
  850. }),
  851. );
  852. },
  853. fetch: ['members'],
  854. });
  855. Meteor.methods({
  856. quitBoard(boardId) {
  857. check(boardId, String);
  858. const board = Boards.findOne(boardId);
  859. if (board) {
  860. const userId = Meteor.userId();
  861. const index = board.memberIndex(userId);
  862. if (index >= 0) {
  863. board.removeMember(userId);
  864. return true;
  865. } else throw new Meteor.Error('error-board-notAMember');
  866. } else throw new Meteor.Error('error-board-doesNotExist');
  867. },
  868. });
  869. Meteor.methods({
  870. archiveBoard(boardId) {
  871. check(boardId, String);
  872. const board = Boards.findOne(boardId);
  873. if (board) {
  874. const userId = Meteor.userId();
  875. const index = board.memberIndex(userId);
  876. if (index >= 0) {
  877. board.archive();
  878. return true;
  879. } else throw new Meteor.Error('error-board-notAMember');
  880. } else throw new Meteor.Error('error-board-doesNotExist');
  881. },
  882. });
  883. }
  884. if (Meteor.isServer) {
  885. // Let MongoDB ensure that a member is not included twice in the same board
  886. Meteor.startup(() => {
  887. Boards._collection._ensureIndex({ modifiedAt: -1 });
  888. Boards._collection._ensureIndex(
  889. {
  890. _id: 1,
  891. 'members.userId': 1,
  892. },
  893. { unique: true },
  894. );
  895. Boards._collection._ensureIndex({ 'members.userId': 1 });
  896. });
  897. // Genesis: the first activity of the newly created board
  898. Boards.after.insert((userId, doc) => {
  899. Activities.insert({
  900. userId,
  901. type: 'board',
  902. activityTypeId: doc._id,
  903. activityType: 'createBoard',
  904. boardId: doc._id,
  905. });
  906. });
  907. // If the user remove one label from a board, we cant to remove reference of
  908. // this label in any card of this board.
  909. Boards.after.update((userId, doc, fieldNames, modifier) => {
  910. if (
  911. !_.contains(fieldNames, 'labels') ||
  912. !modifier.$pull ||
  913. !modifier.$pull.labels ||
  914. !modifier.$pull.labels._id
  915. ) {
  916. return;
  917. }
  918. const removedLabelId = modifier.$pull.labels._id;
  919. Cards.update(
  920. { boardId: doc._id },
  921. {
  922. $pull: {
  923. labelIds: removedLabelId,
  924. },
  925. },
  926. { multi: true },
  927. );
  928. });
  929. const foreachRemovedMember = (doc, modifier, callback) => {
  930. Object.keys(modifier).forEach(set => {
  931. if (modifier[set] !== false) {
  932. return;
  933. }
  934. const parts = set.split('.');
  935. if (
  936. parts.length === 3 &&
  937. parts[0] === 'members' &&
  938. parts[2] === 'isActive'
  939. ) {
  940. callback(doc.members[parts[1]].userId);
  941. }
  942. });
  943. };
  944. // Remove a member from all objects of the board before leaving the board
  945. Boards.before.update((userId, doc, fieldNames, modifier) => {
  946. if (!_.contains(fieldNames, 'members')) {
  947. return;
  948. }
  949. if (modifier.$set) {
  950. const boardId = doc._id;
  951. foreachRemovedMember(doc, modifier.$set, memberId => {
  952. Cards.update(
  953. { boardId },
  954. {
  955. $pull: {
  956. members: memberId,
  957. watchers: memberId,
  958. },
  959. },
  960. { multi: true },
  961. );
  962. Lists.update(
  963. { boardId },
  964. {
  965. $pull: {
  966. watchers: memberId,
  967. },
  968. },
  969. { multi: true },
  970. );
  971. const board = Boards._transform(doc);
  972. board.setWatcher(memberId, false);
  973. // Remove board from users starred list
  974. if (!board.isPublic()) {
  975. Users.update(memberId, {
  976. $pull: {
  977. 'profile.starredBoards': boardId,
  978. },
  979. });
  980. }
  981. });
  982. }
  983. });
  984. Boards.before.remove((userId, doc) => {
  985. boardRemover(userId, doc);
  986. // Add removeBoard activity to keep it
  987. Activities.insert({
  988. userId,
  989. type: 'board',
  990. activityTypeId: doc._id,
  991. activityType: 'removeBoard',
  992. boardId: doc._id,
  993. });
  994. });
  995. // Add a new activity if we add or remove a member to the board
  996. Boards.after.update((userId, doc, fieldNames, modifier) => {
  997. if (!_.contains(fieldNames, 'members')) {
  998. return;
  999. }
  1000. // Say hello to the new member
  1001. if (modifier.$push && modifier.$push.members) {
  1002. const memberId = modifier.$push.members.userId;
  1003. Activities.insert({
  1004. userId,
  1005. memberId,
  1006. type: 'member',
  1007. activityType: 'addBoardMember',
  1008. boardId: doc._id,
  1009. });
  1010. }
  1011. // Say goodbye to the former member
  1012. if (modifier.$set) {
  1013. foreachRemovedMember(doc, modifier.$set, memberId => {
  1014. Activities.insert({
  1015. userId,
  1016. memberId,
  1017. type: 'member',
  1018. activityType: 'removeBoardMember',
  1019. boardId: doc._id,
  1020. });
  1021. });
  1022. }
  1023. });
  1024. }
  1025. //BOARDS REST API
  1026. if (Meteor.isServer) {
  1027. /**
  1028. * @operation get_boards_from_user
  1029. * @summary Get all boards attached to a user
  1030. *
  1031. * @param {string} userId the ID of the user to retrieve the data
  1032. * @return_type [{_id: string,
  1033. title: string}]
  1034. */
  1035. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1036. try {
  1037. Authentication.checkLoggedIn(req.userId);
  1038. const paramUserId = req.params.userId;
  1039. // A normal user should be able to see their own boards,
  1040. // admins can access boards of any user
  1041. Authentication.checkAdminOrCondition(
  1042. req.userId,
  1043. req.userId === paramUserId,
  1044. );
  1045. const data = Boards.find(
  1046. {
  1047. archived: false,
  1048. 'members.userId': paramUserId,
  1049. },
  1050. {
  1051. sort: ['title'],
  1052. },
  1053. ).map(function(board) {
  1054. return {
  1055. _id: board._id,
  1056. title: board.title,
  1057. };
  1058. });
  1059. JsonRoutes.sendResult(res, { code: 200, data });
  1060. } catch (error) {
  1061. JsonRoutes.sendResult(res, {
  1062. code: 200,
  1063. data: error,
  1064. });
  1065. }
  1066. });
  1067. /**
  1068. * @operation get_public_boards
  1069. * @summary Get all public boards
  1070. *
  1071. * @return_type [{_id: string,
  1072. title: string}]
  1073. */
  1074. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1075. try {
  1076. Authentication.checkUserId(req.userId);
  1077. JsonRoutes.sendResult(res, {
  1078. code: 200,
  1079. data: Boards.find({ permission: 'public' }).map(function(doc) {
  1080. return {
  1081. _id: doc._id,
  1082. title: doc.title,
  1083. };
  1084. }),
  1085. });
  1086. } catch (error) {
  1087. JsonRoutes.sendResult(res, {
  1088. code: 200,
  1089. data: error,
  1090. });
  1091. }
  1092. });
  1093. /**
  1094. * @operation get_board
  1095. * @summary Get the board with that particular ID
  1096. *
  1097. * @param {string} boardId the ID of the board to retrieve the data
  1098. * @return_type Boards
  1099. */
  1100. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1101. try {
  1102. const id = req.params.boardId;
  1103. Authentication.checkBoardAccess(req.userId, id);
  1104. JsonRoutes.sendResult(res, {
  1105. code: 200,
  1106. data: Boards.findOne({ _id: id }),
  1107. });
  1108. } catch (error) {
  1109. JsonRoutes.sendResult(res, {
  1110. code: 200,
  1111. data: error,
  1112. });
  1113. }
  1114. });
  1115. /**
  1116. * @operation new_board
  1117. * @summary Create a board
  1118. *
  1119. * @description This allows to create a board.
  1120. *
  1121. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1122. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1123. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1124. *
  1125. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1126. *
  1127. * @param {string} title the new title of the board
  1128. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1129. * (Not username or email)
  1130. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1131. * @param {boolean} [isActive] is the board active (default true)
  1132. * @param {boolean} [isNoComments] disable comments (default false)
  1133. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1134. * @param {string} [permission] "private" board <== Set to "public" if you
  1135. * want public Wekan board
  1136. * @param {string} [color] the color of the board
  1137. *
  1138. * @return_type {_id: string,
  1139. defaultSwimlaneId: string}
  1140. */
  1141. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1142. try {
  1143. Authentication.checkUserId(req.userId);
  1144. const id = Boards.insert({
  1145. title: req.body.title,
  1146. members: [
  1147. {
  1148. userId: req.body.owner,
  1149. isAdmin: req.body.isAdmin || true,
  1150. isActive: req.body.isActive || true,
  1151. isNoComments: req.body.isNoComments || false,
  1152. isCommentOnly: req.body.isCommentOnly || false,
  1153. },
  1154. ],
  1155. permission: req.body.permission || 'private',
  1156. color: req.body.color || 'belize',
  1157. });
  1158. const swimlaneId = Swimlanes.insert({
  1159. title: TAPi18n.__('default'),
  1160. boardId: id,
  1161. });
  1162. JsonRoutes.sendResult(res, {
  1163. code: 200,
  1164. data: {
  1165. _id: id,
  1166. defaultSwimlaneId: swimlaneId,
  1167. },
  1168. });
  1169. } catch (error) {
  1170. JsonRoutes.sendResult(res, {
  1171. code: 200,
  1172. data: error,
  1173. });
  1174. }
  1175. });
  1176. /**
  1177. * @operation delete_board
  1178. * @summary Delete a board
  1179. *
  1180. * @param {string} boardId the ID of the board
  1181. */
  1182. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1183. try {
  1184. Authentication.checkUserId(req.userId);
  1185. const id = req.params.boardId;
  1186. Boards.remove({ _id: id });
  1187. JsonRoutes.sendResult(res, {
  1188. code: 200,
  1189. data: {
  1190. _id: id,
  1191. },
  1192. });
  1193. } catch (error) {
  1194. JsonRoutes.sendResult(res, {
  1195. code: 200,
  1196. data: error,
  1197. });
  1198. }
  1199. });
  1200. /**
  1201. * @operation add_board_label
  1202. * @summary Add a label to a board
  1203. *
  1204. * @description If the board doesn't have the name/color label, this function
  1205. * adds the label to the board.
  1206. *
  1207. * @param {string} boardId the board
  1208. * @param {string} color the color of the new label
  1209. * @param {string} name the name of the new label
  1210. *
  1211. * @return_type string
  1212. */
  1213. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1214. Authentication.checkUserId(req.userId);
  1215. const id = req.params.boardId;
  1216. try {
  1217. if (req.body.hasOwnProperty('label')) {
  1218. const board = Boards.findOne({ _id: id });
  1219. const color = req.body.label.color;
  1220. const name = req.body.label.name;
  1221. const labelId = Random.id(6);
  1222. if (!board.getLabel(name, color)) {
  1223. Boards.direct.update(
  1224. { _id: id },
  1225. { $push: { labels: { _id: labelId, name, color } } },
  1226. );
  1227. JsonRoutes.sendResult(res, {
  1228. code: 200,
  1229. data: labelId,
  1230. });
  1231. } else {
  1232. JsonRoutes.sendResult(res, {
  1233. code: 200,
  1234. });
  1235. }
  1236. }
  1237. } catch (error) {
  1238. JsonRoutes.sendResult(res, {
  1239. data: error,
  1240. });
  1241. }
  1242. });
  1243. /**
  1244. * @operation set_board_member_permission
  1245. * @tag Users
  1246. * @summary Change the permission of a member of a board
  1247. *
  1248. * @param {string} boardId the ID of the board that we are changing
  1249. * @param {string} memberId the ID of the user to change permissions
  1250. * @param {boolean} isAdmin admin capability
  1251. * @param {boolean} isNoComments NoComments capability
  1252. * @param {boolean} isCommentOnly CommentsOnly capability
  1253. */
  1254. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1255. req,
  1256. res,
  1257. ) {
  1258. try {
  1259. const boardId = req.params.boardId;
  1260. const memberId = req.params.memberId;
  1261. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1262. Authentication.checkBoardAccess(req.userId, boardId);
  1263. const board = Boards.findOne({ _id: boardId });
  1264. function isTrue(data) {
  1265. try {
  1266. return data.toLowerCase() === 'true';
  1267. } catch (error) {
  1268. return data;
  1269. }
  1270. }
  1271. const query = board.setMemberPermission(
  1272. memberId,
  1273. isTrue(isAdmin),
  1274. isTrue(isNoComments),
  1275. isTrue(isCommentOnly),
  1276. req.userId,
  1277. );
  1278. JsonRoutes.sendResult(res, {
  1279. code: 200,
  1280. data: query,
  1281. });
  1282. } catch (error) {
  1283. JsonRoutes.sendResult(res, {
  1284. code: 200,
  1285. data: error,
  1286. });
  1287. }
  1288. });
  1289. }
  1290. export default Boards;