boards.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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. type: {
  307. /**
  308. * The type of board
  309. */
  310. type: String,
  311. defaultValue: 'board',
  312. },
  313. }));
  314. Boards.helpers({
  315. copy() {
  316. const oldId = this._id;
  317. delete this._id;
  318. const _id = Boards.insert(this);
  319. // Copy all swimlanes in board
  320. Swimlanes.find({
  321. boardId: oldId,
  322. archived: false,
  323. }).forEach((swimlane) => {
  324. swimlane.type = 'swimlane';
  325. swimlane.copy(_id);
  326. });
  327. },
  328. /**
  329. * Is supplied user authorized to view this board?
  330. */
  331. isVisibleBy(user) {
  332. if (this.isPublic()) {
  333. // public boards are visible to everyone
  334. return true;
  335. } else {
  336. // otherwise you have to be logged-in and active member
  337. return user && this.isActiveMember(user._id);
  338. }
  339. },
  340. /**
  341. * Is the user one of the active members of the board?
  342. *
  343. * @param userId
  344. * @returns {boolean} the member that matches, or undefined/false
  345. */
  346. isActiveMember(userId) {
  347. if (userId) {
  348. return this.members.find((member) => (member.userId === userId && member.isActive));
  349. } else {
  350. return false;
  351. }
  352. },
  353. isPublic() {
  354. return this.permission === 'public';
  355. },
  356. cards() {
  357. return Cards.find({ boardId: this._id, archived: false }, { sort: { title: 1 } });
  358. },
  359. lists() {
  360. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  361. },
  362. nullSortLists() {
  363. return Lists.find({
  364. boardId: this._id,
  365. archived: false,
  366. sort: { $eq: null },
  367. });
  368. },
  369. swimlanes() {
  370. return Swimlanes.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  371. },
  372. nextSwimlane(swimlane) {
  373. return Swimlanes.findOne({
  374. boardId: this._id,
  375. archived: false,
  376. sort: { $gte: swimlane.sort },
  377. _id: { $ne: swimlane._id },
  378. }, {
  379. sort: { sort: 1 },
  380. });
  381. },
  382. nullSortSwimlanes() {
  383. return Swimlanes.find({
  384. boardId: this._id,
  385. archived: false,
  386. sort: { $eq: null },
  387. });
  388. },
  389. hasOvertimeCards(){
  390. const card = Cards.findOne({isOvertime: true, boardId: this._id, archived: false} );
  391. return card !== undefined;
  392. },
  393. hasSpentTimeCards(){
  394. const card = Cards.findOne({spentTime: { $gt: 0 }, boardId: this._id, archived: false} );
  395. return card !== undefined;
  396. },
  397. activities() {
  398. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  399. },
  400. activeMembers() {
  401. return _.where(this.members, { isActive: true });
  402. },
  403. activeAdmins() {
  404. return _.where(this.members, { isActive: true, isAdmin: true });
  405. },
  406. memberUsers() {
  407. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  408. },
  409. getLabel(name, color) {
  410. return _.findWhere(this.labels, { name, color });
  411. },
  412. getLabelById(labelId){
  413. return _.findWhere(this.labels, { _id: labelId });
  414. },
  415. labelIndex(labelId) {
  416. return _.pluck(this.labels, '_id').indexOf(labelId);
  417. },
  418. memberIndex(memberId) {
  419. return _.pluck(this.members, 'userId').indexOf(memberId);
  420. },
  421. hasMember(memberId) {
  422. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  423. },
  424. hasAdmin(memberId) {
  425. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: true });
  426. },
  427. hasNoComments(memberId) {
  428. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isNoComments: true });
  429. },
  430. hasCommentOnly(memberId) {
  431. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isCommentOnly: true });
  432. },
  433. absoluteUrl() {
  434. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  435. },
  436. colorClass() {
  437. return `board-color-${this.color}`;
  438. },
  439. customFields() {
  440. return CustomFields.find({ boardIds: {$in: [this._id]} }, { sort: { name: 1 } });
  441. },
  442. // XXX currently mutations return no value so we have an issue when using addLabel in import
  443. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  444. pushLabel(name, color) {
  445. const _id = Random.id(6);
  446. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  447. return _id;
  448. },
  449. searchBoards(term) {
  450. check(term, Match.OneOf(String, null, undefined));
  451. const query = { boardId: this._id };
  452. query.type = 'cardType-linkedBoard';
  453. query.archived = false;
  454. const projection = { limit: 10, sort: { createdAt: -1 } };
  455. if (term) {
  456. const regex = new RegExp(term, 'i');
  457. query.$or = [
  458. { title: regex },
  459. { description: regex },
  460. ];
  461. }
  462. return Cards.find(query, projection);
  463. },
  464. searchSwimlanes(term) {
  465. check(term, Match.OneOf(String, null, undefined));
  466. const query = { boardId: this._id };
  467. if (this.isTemplatesBoard()) {
  468. query.type = 'template-swimlane';
  469. query.archived = false;
  470. } else {
  471. query.type = {$nin: ['template-swimlane']};
  472. }
  473. const projection = { limit: 10, sort: { createdAt: -1 } };
  474. if (term) {
  475. const regex = new RegExp(term, 'i');
  476. query.$or = [
  477. { title: regex },
  478. { description: regex },
  479. ];
  480. }
  481. return Swimlanes.find(query, projection);
  482. },
  483. searchLists(term) {
  484. check(term, Match.OneOf(String, null, undefined));
  485. const query = { boardId: this._id };
  486. if (this.isTemplatesBoard()) {
  487. query.type = 'template-list';
  488. query.archived = false;
  489. } else {
  490. query.type = {$nin: ['template-list']};
  491. }
  492. const projection = { limit: 10, sort: { createdAt: -1 } };
  493. if (term) {
  494. const regex = new RegExp(term, 'i');
  495. query.$or = [
  496. { title: regex },
  497. { description: regex },
  498. ];
  499. }
  500. return Lists.find(query, projection);
  501. },
  502. searchCards(term, excludeLinked) {
  503. check(term, Match.OneOf(String, null, undefined));
  504. const query = { boardId: this._id };
  505. if (excludeLinked) {
  506. query.linkedId = null;
  507. }
  508. if (this.isTemplatesBoard()) {
  509. query.type = 'template-card';
  510. query.archived = false;
  511. } else {
  512. query.type = {$nin: ['template-card']};
  513. }
  514. const projection = { limit: 10, sort: { createdAt: -1 } };
  515. if (term) {
  516. const regex = new RegExp(term, 'i');
  517. query.$or = [
  518. { title: regex },
  519. { description: regex },
  520. ];
  521. }
  522. return Cards.find(query, projection);
  523. },
  524. // A board alwasy has another board where it deposits subtasks of thasks
  525. // that belong to itself.
  526. getDefaultSubtasksBoardId() {
  527. if ((this.subtasksDefaultBoardId === null) || (this.subtasksDefaultBoardId === undefined)) {
  528. this.subtasksDefaultBoardId = Boards.insert({
  529. title: `^${this.title}^`,
  530. permission: this.permission,
  531. members: this.members,
  532. color: this.color,
  533. description: TAPi18n.__('default-subtasks-board', {board: this.title}),
  534. });
  535. Swimlanes.insert({
  536. title: TAPi18n.__('default'),
  537. boardId: this.subtasksDefaultBoardId,
  538. });
  539. Boards.update(this._id, {$set: {
  540. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  541. }});
  542. }
  543. return this.subtasksDefaultBoardId;
  544. },
  545. getDefaultSubtasksBoard() {
  546. return Boards.findOne(this.getDefaultSubtasksBoardId());
  547. },
  548. getDefaultSubtasksListId() {
  549. if ((this.subtasksDefaultListId === null) || (this.subtasksDefaultListId === undefined)) {
  550. this.subtasksDefaultListId = Lists.insert({
  551. title: TAPi18n.__('queue'),
  552. boardId: this._id,
  553. });
  554. Boards.update(this._id, {$set: {
  555. subtasksDefaultListId: this.subtasksDefaultListId,
  556. }});
  557. }
  558. return this.subtasksDefaultListId;
  559. },
  560. getDefaultSubtasksList() {
  561. return Lists.findOne(this.getDefaultSubtasksListId());
  562. },
  563. getDefaultSwimline() {
  564. let result = Swimlanes.findOne({boardId: this._id});
  565. if (result === undefined) {
  566. Swimlanes.insert({
  567. title: TAPi18n.__('default'),
  568. boardId: this._id,
  569. });
  570. result = Swimlanes.findOne({boardId: this._id});
  571. }
  572. return result;
  573. },
  574. cardsInInterval(start, end) {
  575. return Cards.find({
  576. boardId: this._id,
  577. $or: [
  578. {
  579. startAt: {
  580. $lte: start,
  581. }, endAt: {
  582. $gte: start,
  583. },
  584. }, {
  585. startAt: {
  586. $lte: end,
  587. }, endAt: {
  588. $gte: end,
  589. },
  590. }, {
  591. startAt: {
  592. $gte: start,
  593. }, endAt: {
  594. $lte: end,
  595. },
  596. },
  597. ],
  598. });
  599. },
  600. isTemplateBoard() {
  601. return this.type === 'template-board';
  602. },
  603. isTemplatesBoard() {
  604. return this.type === 'template-container';
  605. },
  606. });
  607. Boards.mutations({
  608. archive() {
  609. return { $set: { archived: true } };
  610. },
  611. restore() {
  612. return { $set: { archived: false } };
  613. },
  614. rename(title) {
  615. return { $set: { title } };
  616. },
  617. setDescription(description) {
  618. return { $set: { description } };
  619. },
  620. setColor(color) {
  621. return { $set: { color } };
  622. },
  623. setVisibility(visibility) {
  624. return { $set: { permission: visibility } };
  625. },
  626. addLabel(name, color) {
  627. // If label with the same name and color already exists we don't want to
  628. // create another one because they would be indistinguishable in the UI
  629. // (they would still have different `_id` but that is not exposed to the
  630. // user).
  631. if (!this.getLabel(name, color)) {
  632. const _id = Random.id(6);
  633. return { $push: { labels: { _id, name, color } } };
  634. }
  635. return {};
  636. },
  637. editLabel(labelId, name, color) {
  638. if (!this.getLabel(name, color)) {
  639. const labelIndex = this.labelIndex(labelId);
  640. return {
  641. $set: {
  642. [`labels.${labelIndex}.name`]: name,
  643. [`labels.${labelIndex}.color`]: color,
  644. },
  645. };
  646. }
  647. return {};
  648. },
  649. removeLabel(labelId) {
  650. return { $pull: { labels: { _id: labelId } } };
  651. },
  652. changeOwnership(fromId, toId) {
  653. const memberIndex = this.memberIndex(fromId);
  654. return {
  655. $set: {
  656. [`members.${memberIndex}.userId`]: toId,
  657. },
  658. };
  659. },
  660. addMember(memberId) {
  661. const memberIndex = this.memberIndex(memberId);
  662. if (memberIndex >= 0) {
  663. return {
  664. $set: {
  665. [`members.${memberIndex}.isActive`]: true,
  666. },
  667. };
  668. }
  669. return {
  670. $push: {
  671. members: {
  672. userId: memberId,
  673. isAdmin: false,
  674. isActive: true,
  675. isNoComments: false,
  676. isCommentOnly: false,
  677. },
  678. },
  679. };
  680. },
  681. removeMember(memberId) {
  682. const memberIndex = this.memberIndex(memberId);
  683. // we do not allow the only one admin to be removed
  684. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  685. if (!allowRemove) {
  686. return {
  687. $set: {
  688. [`members.${memberIndex}.isActive`]: true,
  689. },
  690. };
  691. }
  692. return {
  693. $set: {
  694. [`members.${memberIndex}.isActive`]: false,
  695. [`members.${memberIndex}.isAdmin`]: false,
  696. },
  697. };
  698. },
  699. setMemberPermission(memberId, isAdmin, isNoComments, isCommentOnly, currentUserId = Meteor.userId()) {
  700. const memberIndex = this.memberIndex(memberId);
  701. // do not allow change permission of self
  702. if (memberId === currentUserId) {
  703. isAdmin = this.members[memberIndex].isAdmin;
  704. }
  705. return {
  706. $set: {
  707. [`members.${memberIndex}.isAdmin`]: isAdmin,
  708. [`members.${memberIndex}.isNoComments`]: isNoComments,
  709. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  710. },
  711. };
  712. },
  713. setAllowsSubtasks(allowsSubtasks) {
  714. return { $set: { allowsSubtasks } };
  715. },
  716. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  717. return { $set: { subtasksDefaultBoardId } };
  718. },
  719. setSubtasksDefaultListId(subtasksDefaultListId) {
  720. return { $set: { subtasksDefaultListId } };
  721. },
  722. setPresentParentTask(presentParentTask) {
  723. return { $set: { presentParentTask } };
  724. },
  725. });
  726. if (Meteor.isServer) {
  727. Boards.allow({
  728. insert: Meteor.userId,
  729. update: allowIsBoardAdmin,
  730. remove: allowIsBoardAdmin,
  731. fetch: ['members'],
  732. });
  733. // The number of users that have starred this board is managed by trusted code
  734. // and the user is not allowed to update it
  735. Boards.deny({
  736. update(userId, board, fieldNames) {
  737. return _.contains(fieldNames, 'stars');
  738. },
  739. fetch: [],
  740. });
  741. // We can't remove a member if it is the last administrator
  742. Boards.deny({
  743. update(userId, doc, fieldNames, modifier) {
  744. if (!_.contains(fieldNames, 'members'))
  745. return false;
  746. // We only care in case of a $pull operation, ie remove a member
  747. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  748. return false;
  749. // If there is more than one admin, it's ok to remove anyone
  750. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  751. if (nbAdmins > 1)
  752. return false;
  753. // If all the previous conditions were verified, we can't remove
  754. // a user if it's an admin
  755. const removedMemberId = modifier.$pull.members.userId;
  756. return Boolean(_.findWhere(doc.members, {
  757. userId: removedMemberId,
  758. isAdmin: true,
  759. }));
  760. },
  761. fetch: ['members'],
  762. });
  763. Meteor.methods({
  764. quitBoard(boardId) {
  765. check(boardId, String);
  766. const board = Boards.findOne(boardId);
  767. if (board) {
  768. const userId = Meteor.userId();
  769. const index = board.memberIndex(userId);
  770. if (index >= 0) {
  771. board.removeMember(userId);
  772. return true;
  773. } else throw new Meteor.Error('error-board-notAMember');
  774. } else throw new Meteor.Error('error-board-doesNotExist');
  775. },
  776. });
  777. }
  778. if (Meteor.isServer) {
  779. // Let MongoDB ensure that a member is not included twice in the same board
  780. Meteor.startup(() => {
  781. Boards._collection._ensureIndex({
  782. _id: 1,
  783. 'members.userId': 1,
  784. }, { unique: true });
  785. Boards._collection._ensureIndex({ 'members.userId': 1 });
  786. });
  787. // Genesis: the first activity of the newly created board
  788. Boards.after.insert((userId, doc) => {
  789. Activities.insert({
  790. userId,
  791. type: 'board',
  792. activityTypeId: doc._id,
  793. activityType: 'createBoard',
  794. boardId: doc._id,
  795. });
  796. });
  797. // If the user remove one label from a board, we cant to remove reference of
  798. // this label in any card of this board.
  799. Boards.after.update((userId, doc, fieldNames, modifier) => {
  800. if (!_.contains(fieldNames, 'labels') ||
  801. !modifier.$pull ||
  802. !modifier.$pull.labels ||
  803. !modifier.$pull.labels._id) {
  804. return;
  805. }
  806. const removedLabelId = modifier.$pull.labels._id;
  807. Cards.update(
  808. { boardId: doc._id },
  809. {
  810. $pull: {
  811. labelIds: removedLabelId,
  812. },
  813. },
  814. { multi: true }
  815. );
  816. });
  817. const foreachRemovedMember = (doc, modifier, callback) => {
  818. Object.keys(modifier).forEach((set) => {
  819. if (modifier[set] !== false) {
  820. return;
  821. }
  822. const parts = set.split('.');
  823. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  824. callback(doc.members[parts[1]].userId);
  825. }
  826. });
  827. };
  828. // Remove a member from all objects of the board before leaving the board
  829. Boards.before.update((userId, doc, fieldNames, modifier) => {
  830. if (!_.contains(fieldNames, 'members')) {
  831. return;
  832. }
  833. if (modifier.$set) {
  834. const boardId = doc._id;
  835. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  836. Cards.update(
  837. { boardId },
  838. {
  839. $pull: {
  840. members: memberId,
  841. watchers: memberId,
  842. },
  843. },
  844. { multi: true }
  845. );
  846. Lists.update(
  847. { boardId },
  848. {
  849. $pull: {
  850. watchers: memberId,
  851. },
  852. },
  853. { multi: true }
  854. );
  855. const board = Boards._transform(doc);
  856. board.setWatcher(memberId, false);
  857. // Remove board from users starred list
  858. if (!board.isPublic()) {
  859. Users.update(
  860. memberId,
  861. {
  862. $pull: {
  863. 'profile.starredBoards': boardId,
  864. },
  865. }
  866. );
  867. }
  868. });
  869. }
  870. });
  871. // Add a new activity if we add or remove a member to the board
  872. Boards.after.update((userId, doc, fieldNames, modifier) => {
  873. if (!_.contains(fieldNames, 'members')) {
  874. return;
  875. }
  876. // Say hello to the new member
  877. if (modifier.$push && modifier.$push.members) {
  878. const memberId = modifier.$push.members.userId;
  879. Activities.insert({
  880. userId,
  881. memberId,
  882. type: 'member',
  883. activityType: 'addBoardMember',
  884. boardId: doc._id,
  885. });
  886. }
  887. // Say goodbye to the former member
  888. if (modifier.$set) {
  889. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  890. Activities.insert({
  891. userId,
  892. memberId,
  893. type: 'member',
  894. activityType: 'removeBoardMember',
  895. boardId: doc._id,
  896. });
  897. });
  898. }
  899. });
  900. }
  901. //BOARDS REST API
  902. if (Meteor.isServer) {
  903. /**
  904. * @operation get_boards_from_user
  905. * @summary Get all boards attached to a user
  906. *
  907. * @param {string} userId the ID of the user to retrieve the data
  908. * @return_type [{_id: string,
  909. title: string}]
  910. */
  911. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  912. try {
  913. Authentication.checkLoggedIn(req.userId);
  914. const paramUserId = req.params.userId;
  915. // A normal user should be able to see their own boards,
  916. // admins can access boards of any user
  917. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  918. const data = Boards.find({
  919. archived: false,
  920. 'members.userId': paramUserId,
  921. }, {
  922. sort: ['title'],
  923. }).map(function(board) {
  924. return {
  925. _id: board._id,
  926. title: board.title,
  927. };
  928. });
  929. JsonRoutes.sendResult(res, {code: 200, data});
  930. }
  931. catch (error) {
  932. JsonRoutes.sendResult(res, {
  933. code: 200,
  934. data: error,
  935. });
  936. }
  937. });
  938. /**
  939. * @operation get_public_boards
  940. * @summary Get all public boards
  941. *
  942. * @return_type [{_id: string,
  943. title: string}]
  944. */
  945. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  946. try {
  947. Authentication.checkUserId(req.userId);
  948. JsonRoutes.sendResult(res, {
  949. code: 200,
  950. data: Boards.find({ permission: 'public' }).map(function (doc) {
  951. return {
  952. _id: doc._id,
  953. title: doc.title,
  954. };
  955. }),
  956. });
  957. }
  958. catch (error) {
  959. JsonRoutes.sendResult(res, {
  960. code: 200,
  961. data: error,
  962. });
  963. }
  964. });
  965. /**
  966. * @operation get_board
  967. * @summary Get the board with that particular ID
  968. *
  969. * @param {string} boardId the ID of the board to retrieve the data
  970. * @return_type Boards
  971. */
  972. JsonRoutes.add('GET', '/api/boards/:boardId', function (req, res) {
  973. try {
  974. const id = req.params.boardId;
  975. Authentication.checkBoardAccess(req.userId, id);
  976. JsonRoutes.sendResult(res, {
  977. code: 200,
  978. data: Boards.findOne({ _id: id }),
  979. });
  980. }
  981. catch (error) {
  982. JsonRoutes.sendResult(res, {
  983. code: 200,
  984. data: error,
  985. });
  986. }
  987. });
  988. /**
  989. * @operation new_board
  990. * @summary Create a board
  991. *
  992. * @description This allows to create a board.
  993. *
  994. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  995. * `pumpkin`, `wisteria`, `midnight`:
  996. *
  997. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  998. *
  999. * @param {string} title the new title of the board
  1000. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1001. * (Not username or email)
  1002. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1003. * @param {boolean} [isActive] is the board active (default true)
  1004. * @param {boolean} [isNoComments] disable comments (default false)
  1005. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1006. * @param {string} [permission] "private" board <== Set to "public" if you
  1007. * want public Wekan board
  1008. * @param {string} [color] the color of the board
  1009. *
  1010. * @return_type {_id: string,
  1011. defaultSwimlaneId: string}
  1012. */
  1013. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  1014. try {
  1015. Authentication.checkUserId(req.userId);
  1016. const id = Boards.insert({
  1017. title: req.body.title,
  1018. members: [
  1019. {
  1020. userId: req.body.owner,
  1021. isAdmin: req.body.isAdmin || true,
  1022. isActive: req.body.isActive || true,
  1023. isNoComments: req.body.isNoComments || false,
  1024. isCommentOnly: req.body.isCommentOnly || false,
  1025. },
  1026. ],
  1027. permission: req.body.permission || 'private',
  1028. color: req.body.color || 'belize',
  1029. });
  1030. const swimlaneId = Swimlanes.insert({
  1031. title: TAPi18n.__('default'),
  1032. boardId: id,
  1033. });
  1034. JsonRoutes.sendResult(res, {
  1035. code: 200,
  1036. data: {
  1037. _id: id,
  1038. defaultSwimlaneId: swimlaneId,
  1039. },
  1040. });
  1041. }
  1042. catch (error) {
  1043. JsonRoutes.sendResult(res, {
  1044. code: 200,
  1045. data: error,
  1046. });
  1047. }
  1048. });
  1049. /**
  1050. * @operation delete_board
  1051. * @summary Delete a board
  1052. *
  1053. * @param {string} boardId the ID of the board
  1054. */
  1055. JsonRoutes.add('DELETE', '/api/boards/:boardId', function (req, res) {
  1056. try {
  1057. Authentication.checkUserId(req.userId);
  1058. const id = req.params.boardId;
  1059. Boards.remove({ _id: id });
  1060. JsonRoutes.sendResult(res, {
  1061. code: 200,
  1062. data:{
  1063. _id: id,
  1064. },
  1065. });
  1066. }
  1067. catch (error) {
  1068. JsonRoutes.sendResult(res, {
  1069. code: 200,
  1070. data: error,
  1071. });
  1072. }
  1073. });
  1074. /**
  1075. * @operation add_board_label
  1076. * @summary Add a label to a board
  1077. *
  1078. * @description If the board doesn't have the name/color label, this function
  1079. * adds the label to the board.
  1080. *
  1081. * @param {string} boardId the board
  1082. * @param {string} color the color of the new label
  1083. * @param {string} name the name of the new label
  1084. *
  1085. * @return_type string
  1086. */
  1087. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function (req, res) {
  1088. Authentication.checkUserId(req.userId);
  1089. const id = req.params.boardId;
  1090. try {
  1091. if (req.body.hasOwnProperty('label')) {
  1092. const board = Boards.findOne({ _id: id });
  1093. const color = req.body.label.color;
  1094. const name = req.body.label.name;
  1095. const labelId = Random.id(6);
  1096. if (!board.getLabel(name, color)) {
  1097. Boards.direct.update({ _id: id }, { $push: { labels: { _id: labelId, name, color } } });
  1098. JsonRoutes.sendResult(res, {
  1099. code: 200,
  1100. data: labelId,
  1101. });
  1102. } else {
  1103. JsonRoutes.sendResult(res, {
  1104. code: 200,
  1105. });
  1106. }
  1107. }
  1108. }
  1109. catch (error) {
  1110. JsonRoutes.sendResult(res, {
  1111. data: error,
  1112. });
  1113. }
  1114. });
  1115. /**
  1116. * @operation set_board_member_permission
  1117. * @tag Users
  1118. * @summary Change the permission of a member of a board
  1119. *
  1120. * @param {string} boardId the ID of the board that we are changing
  1121. * @param {string} memberId the ID of the user to change permissions
  1122. * @param {boolean} isAdmin admin capability
  1123. * @param {boolean} isNoComments NoComments capability
  1124. * @param {boolean} isCommentOnly CommentsOnly capability
  1125. */
  1126. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function (req, res) {
  1127. try {
  1128. const boardId = req.params.boardId;
  1129. const memberId = req.params.memberId;
  1130. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  1131. Authentication.checkBoardAccess(req.userId, boardId);
  1132. const board = Boards.findOne({ _id: boardId });
  1133. function isTrue(data){
  1134. try {
  1135. return data.toLowerCase() === 'true';
  1136. }
  1137. catch (error) {
  1138. return data;
  1139. }
  1140. }
  1141. const query = board.setMemberPermission(memberId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), req.userId);
  1142. JsonRoutes.sendResult(res, {
  1143. code: 200,
  1144. data: query,
  1145. });
  1146. }
  1147. catch (error) {
  1148. JsonRoutes.sendResult(res, {
  1149. code: 200,
  1150. data: error,
  1151. });
  1152. }
  1153. });
  1154. }