boards.js 28 KB

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