boards.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  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. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  555. }
  556. return this.subtasksDefaultListId;
  557. },
  558. getDefaultSubtasksList() {
  559. return Lists.findOne(this.getDefaultSubtasksListId());
  560. },
  561. getDefaultSwimline() {
  562. let result = Swimlanes.findOne({boardId: this._id});
  563. if (result === undefined) {
  564. Swimlanes.insert({
  565. title: TAPi18n.__('default'),
  566. boardId: this._id,
  567. });
  568. result = Swimlanes.findOne({boardId: this._id});
  569. }
  570. return result;
  571. },
  572. cardsInInterval(start, end) {
  573. return Cards.find({
  574. boardId: this._id,
  575. $or: [
  576. {
  577. startAt: {
  578. $lte: start,
  579. }, endAt: {
  580. $gte: start,
  581. },
  582. }, {
  583. startAt: {
  584. $lte: end,
  585. }, endAt: {
  586. $gte: end,
  587. },
  588. }, {
  589. startAt: {
  590. $gte: start,
  591. }, endAt: {
  592. $lte: end,
  593. },
  594. },
  595. ],
  596. });
  597. },
  598. isTemplateBoard() {
  599. return this.type === 'template-board';
  600. },
  601. isTemplatesBoard() {
  602. return this.type === 'template-container';
  603. },
  604. });
  605. Boards.mutations({
  606. archive() {
  607. return { $set: { archived: true } };
  608. },
  609. restore() {
  610. return { $set: { archived: false } };
  611. },
  612. rename(title) {
  613. return { $set: { title } };
  614. },
  615. setDescription(description) {
  616. return { $set: { description } };
  617. },
  618. setColor(color) {
  619. return { $set: { color } };
  620. },
  621. setVisibility(visibility) {
  622. return { $set: { permission: visibility } };
  623. },
  624. addLabel(name, color) {
  625. // If label with the same name and color already exists we don't want to
  626. // create another one because they would be indistinguishable in the UI
  627. // (they would still have different `_id` but that is not exposed to the
  628. // user).
  629. if (!this.getLabel(name, color)) {
  630. const _id = Random.id(6);
  631. return { $push: { labels: { _id, name, color } } };
  632. }
  633. return {};
  634. },
  635. editLabel(labelId, name, color) {
  636. if (!this.getLabel(name, color)) {
  637. const labelIndex = this.labelIndex(labelId);
  638. return {
  639. $set: {
  640. [`labels.${labelIndex}.name`]: name,
  641. [`labels.${labelIndex}.color`]: color,
  642. },
  643. };
  644. }
  645. return {};
  646. },
  647. removeLabel(labelId) {
  648. return { $pull: { labels: { _id: labelId } } };
  649. },
  650. changeOwnership(fromId, toId) {
  651. const memberIndex = this.memberIndex(fromId);
  652. return {
  653. $set: {
  654. [`members.${memberIndex}.userId`]: toId,
  655. },
  656. };
  657. },
  658. addMember(memberId) {
  659. const memberIndex = this.memberIndex(memberId);
  660. if (memberIndex >= 0) {
  661. return {
  662. $set: {
  663. [`members.${memberIndex}.isActive`]: true,
  664. },
  665. };
  666. }
  667. return {
  668. $push: {
  669. members: {
  670. userId: memberId,
  671. isAdmin: false,
  672. isActive: true,
  673. isNoComments: false,
  674. isCommentOnly: false,
  675. },
  676. },
  677. };
  678. },
  679. removeMember(memberId) {
  680. const memberIndex = this.memberIndex(memberId);
  681. // we do not allow the only one admin to be removed
  682. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  683. if (!allowRemove) {
  684. return {
  685. $set: {
  686. [`members.${memberIndex}.isActive`]: true,
  687. },
  688. };
  689. }
  690. return {
  691. $set: {
  692. [`members.${memberIndex}.isActive`]: false,
  693. [`members.${memberIndex}.isAdmin`]: false,
  694. },
  695. };
  696. },
  697. setMemberPermission(memberId, isAdmin, isNoComments, isCommentOnly, currentUserId = Meteor.userId()) {
  698. const memberIndex = this.memberIndex(memberId);
  699. // do not allow change permission of self
  700. if (memberId === currentUserId) {
  701. isAdmin = this.members[memberIndex].isAdmin;
  702. }
  703. return {
  704. $set: {
  705. [`members.${memberIndex}.isAdmin`]: isAdmin,
  706. [`members.${memberIndex}.isNoComments`]: isNoComments,
  707. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  708. },
  709. };
  710. },
  711. setAllowsSubtasks(allowsSubtasks) {
  712. return { $set: { allowsSubtasks } };
  713. },
  714. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  715. return { $set: { subtasksDefaultBoardId } };
  716. },
  717. setSubtasksDefaultListId(subtasksDefaultListId) {
  718. return { $set: { subtasksDefaultListId } };
  719. },
  720. setPresentParentTask(presentParentTask) {
  721. return { $set: { presentParentTask } };
  722. },
  723. });
  724. function boardRemover(userId, doc) {
  725. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach((element) => {
  726. element.remove({ boardId: doc._id });
  727. });
  728. }
  729. if (Meteor.isServer) {
  730. Boards.allow({
  731. insert: Meteor.userId,
  732. update: allowIsBoardAdmin,
  733. remove: allowIsBoardAdmin,
  734. fetch: ['members'],
  735. });
  736. // The number of users that have starred this board is managed by trusted code
  737. // and the user is not allowed to update it
  738. Boards.deny({
  739. update(userId, board, fieldNames) {
  740. return _.contains(fieldNames, 'stars');
  741. },
  742. fetch: [],
  743. });
  744. // We can't remove a member if it is the last administrator
  745. Boards.deny({
  746. update(userId, doc, fieldNames, modifier) {
  747. if (!_.contains(fieldNames, 'members'))
  748. return false;
  749. // We only care in case of a $pull operation, ie remove a member
  750. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  751. return false;
  752. // If there is more than one admin, it's ok to remove anyone
  753. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  754. if (nbAdmins > 1)
  755. return false;
  756. // If all the previous conditions were verified, we can't remove
  757. // a user if it's an admin
  758. const removedMemberId = modifier.$pull.members.userId;
  759. return Boolean(_.findWhere(doc.members, {
  760. userId: removedMemberId,
  761. isAdmin: true,
  762. }));
  763. },
  764. fetch: ['members'],
  765. });
  766. Meteor.methods({
  767. quitBoard(boardId) {
  768. check(boardId, String);
  769. const board = Boards.findOne(boardId);
  770. if (board) {
  771. const userId = Meteor.userId();
  772. const index = board.memberIndex(userId);
  773. if (index >= 0) {
  774. board.removeMember(userId);
  775. return true;
  776. } else throw new Meteor.Error('error-board-notAMember');
  777. } else throw new Meteor.Error('error-board-doesNotExist');
  778. },
  779. });
  780. Meteor.methods({
  781. archiveBoard(boardId) {
  782. check(boardId, String);
  783. const board = Boards.findOne(boardId);
  784. if (board) {
  785. const userId = Meteor.userId();
  786. const index = board.memberIndex(userId);
  787. if (index >= 0) {
  788. board.archive();
  789. return true;
  790. } else throw new Meteor.Error('error-board-notAMember');
  791. } else throw new Meteor.Error('error-board-doesNotExist');
  792. },
  793. });
  794. }
  795. if (Meteor.isServer) {
  796. // Let MongoDB ensure that a member is not included twice in the same board
  797. Meteor.startup(() => {
  798. Boards._collection._ensureIndex({
  799. _id: 1,
  800. 'members.userId': 1,
  801. }, { unique: true });
  802. Boards._collection._ensureIndex({ 'members.userId': 1 });
  803. });
  804. // Genesis: the first activity of the newly created board
  805. Boards.after.insert((userId, doc) => {
  806. Activities.insert({
  807. userId,
  808. type: 'board',
  809. activityTypeId: doc._id,
  810. activityType: 'createBoard',
  811. boardId: doc._id,
  812. });
  813. });
  814. // If the user remove one label from a board, we cant to remove reference of
  815. // this label in any card of this board.
  816. Boards.after.update((userId, doc, fieldNames, modifier) => {
  817. if (!_.contains(fieldNames, 'labels') ||
  818. !modifier.$pull ||
  819. !modifier.$pull.labels ||
  820. !modifier.$pull.labels._id) {
  821. return;
  822. }
  823. const removedLabelId = modifier.$pull.labels._id;
  824. Cards.update(
  825. { boardId: doc._id },
  826. {
  827. $pull: {
  828. labelIds: removedLabelId,
  829. },
  830. },
  831. { multi: true }
  832. );
  833. });
  834. const foreachRemovedMember = (doc, modifier, callback) => {
  835. Object.keys(modifier).forEach((set) => {
  836. if (modifier[set] !== false) {
  837. return;
  838. }
  839. const parts = set.split('.');
  840. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  841. callback(doc.members[parts[1]].userId);
  842. }
  843. });
  844. };
  845. // Remove a member from all objects of the board before leaving the board
  846. Boards.before.update((userId, doc, fieldNames, modifier) => {
  847. if (!_.contains(fieldNames, 'members')) {
  848. return;
  849. }
  850. if (modifier.$set) {
  851. const boardId = doc._id;
  852. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  853. Cards.update(
  854. { boardId },
  855. {
  856. $pull: {
  857. members: memberId,
  858. watchers: memberId,
  859. },
  860. },
  861. { multi: true }
  862. );
  863. Lists.update(
  864. { boardId },
  865. {
  866. $pull: {
  867. watchers: memberId,
  868. },
  869. },
  870. { multi: true }
  871. );
  872. const board = Boards._transform(doc);
  873. board.setWatcher(memberId, false);
  874. // Remove board from users starred list
  875. if (!board.isPublic()) {
  876. Users.update(
  877. memberId,
  878. {
  879. $pull: {
  880. 'profile.starredBoards': boardId,
  881. },
  882. }
  883. );
  884. }
  885. });
  886. }
  887. });
  888. Boards.before.remove((userId, doc) => {
  889. boardRemover(userId, doc);
  890. // Add removeBoard activity to keep it
  891. Activities.insert({
  892. userId,
  893. type: 'board',
  894. activityTypeId: doc._id,
  895. activityType: 'removeBoard',
  896. boardId: doc._id,
  897. });
  898. });
  899. // Add a new activity if we add or remove a member to the board
  900. Boards.after.update((userId, doc, fieldNames, modifier) => {
  901. if (!_.contains(fieldNames, 'members')) {
  902. return;
  903. }
  904. // Say hello to the new member
  905. if (modifier.$push && modifier.$push.members) {
  906. const memberId = modifier.$push.members.userId;
  907. Activities.insert({
  908. userId,
  909. memberId,
  910. type: 'member',
  911. activityType: 'addBoardMember',
  912. boardId: doc._id,
  913. });
  914. }
  915. // Say goodbye to the former member
  916. if (modifier.$set) {
  917. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  918. Activities.insert({
  919. userId,
  920. memberId,
  921. type: 'member',
  922. activityType: 'removeBoardMember',
  923. boardId: doc._id,
  924. });
  925. });
  926. }
  927. });
  928. }
  929. //BOARDS REST API
  930. if (Meteor.isServer) {
  931. /**
  932. * @operation get_boards_from_user
  933. * @summary Get all boards attached to a user
  934. *
  935. * @param {string} userId the ID of the user to retrieve the data
  936. * @return_type [{_id: string,
  937. title: string}]
  938. */
  939. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  940. try {
  941. Authentication.checkLoggedIn(req.userId);
  942. const paramUserId = req.params.userId;
  943. // A normal user should be able to see their own boards,
  944. // admins can access boards of any user
  945. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  946. const data = Boards.find({
  947. archived: false,
  948. 'members.userId': paramUserId,
  949. }, {
  950. sort: ['title'],
  951. }).map(function(board) {
  952. return {
  953. _id: board._id,
  954. title: board.title,
  955. };
  956. });
  957. JsonRoutes.sendResult(res, {code: 200, data});
  958. }
  959. catch (error) {
  960. JsonRoutes.sendResult(res, {
  961. code: 200,
  962. data: error,
  963. });
  964. }
  965. });
  966. /**
  967. * @operation get_public_boards
  968. * @summary Get all public boards
  969. *
  970. * @return_type [{_id: string,
  971. title: string}]
  972. */
  973. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  974. try {
  975. Authentication.checkUserId(req.userId);
  976. JsonRoutes.sendResult(res, {
  977. code: 200,
  978. data: Boards.find({ permission: 'public' }).map(function (doc) {
  979. return {
  980. _id: doc._id,
  981. title: doc.title,
  982. };
  983. }),
  984. });
  985. }
  986. catch (error) {
  987. JsonRoutes.sendResult(res, {
  988. code: 200,
  989. data: error,
  990. });
  991. }
  992. });
  993. /**
  994. * @operation get_board
  995. * @summary Get the board with that particular ID
  996. *
  997. * @param {string} boardId the ID of the board to retrieve the data
  998. * @return_type Boards
  999. */
  1000. JsonRoutes.add('GET', '/api/boards/:boardId', function (req, res) {
  1001. try {
  1002. const id = req.params.boardId;
  1003. Authentication.checkBoardAccess(req.userId, id);
  1004. JsonRoutes.sendResult(res, {
  1005. code: 200,
  1006. data: Boards.findOne({ _id: id }),
  1007. });
  1008. }
  1009. catch (error) {
  1010. JsonRoutes.sendResult(res, {
  1011. code: 200,
  1012. data: error,
  1013. });
  1014. }
  1015. });
  1016. /**
  1017. * @operation new_board
  1018. * @summary Create a board
  1019. *
  1020. * @description This allows to create a board.
  1021. *
  1022. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1023. * `pumpkin`, `wisteria`, `midnight`:
  1024. *
  1025. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1026. *
  1027. * @param {string} title the new title of the board
  1028. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1029. * (Not username or email)
  1030. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1031. * @param {boolean} [isActive] is the board active (default true)
  1032. * @param {boolean} [isNoComments] disable comments (default false)
  1033. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1034. * @param {string} [permission] "private" board <== Set to "public" if you
  1035. * want public Wekan board
  1036. * @param {string} [color] the color of the board
  1037. *
  1038. * @return_type {_id: string,
  1039. defaultSwimlaneId: string}
  1040. */
  1041. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  1042. try {
  1043. Authentication.checkUserId(req.userId);
  1044. const id = Boards.insert({
  1045. title: req.body.title,
  1046. members: [
  1047. {
  1048. userId: req.body.owner,
  1049. isAdmin: req.body.isAdmin || true,
  1050. isActive: req.body.isActive || true,
  1051. isNoComments: req.body.isNoComments || false,
  1052. isCommentOnly: req.body.isCommentOnly || false,
  1053. },
  1054. ],
  1055. permission: req.body.permission || 'private',
  1056. color: req.body.color || 'belize',
  1057. });
  1058. const swimlaneId = Swimlanes.insert({
  1059. title: TAPi18n.__('default'),
  1060. boardId: id,
  1061. });
  1062. JsonRoutes.sendResult(res, {
  1063. code: 200,
  1064. data: {
  1065. _id: id,
  1066. defaultSwimlaneId: swimlaneId,
  1067. },
  1068. });
  1069. }
  1070. catch (error) {
  1071. JsonRoutes.sendResult(res, {
  1072. code: 200,
  1073. data: error,
  1074. });
  1075. }
  1076. });
  1077. /**
  1078. * @operation delete_board
  1079. * @summary Delete a board
  1080. *
  1081. * @param {string} boardId the ID of the board
  1082. */
  1083. JsonRoutes.add('DELETE', '/api/boards/:boardId', function (req, res) {
  1084. try {
  1085. Authentication.checkUserId(req.userId);
  1086. const id = req.params.boardId;
  1087. Boards.remove({ _id: id });
  1088. JsonRoutes.sendResult(res, {
  1089. code: 200,
  1090. data:{
  1091. _id: id,
  1092. },
  1093. });
  1094. }
  1095. catch (error) {
  1096. JsonRoutes.sendResult(res, {
  1097. code: 200,
  1098. data: error,
  1099. });
  1100. }
  1101. });
  1102. /**
  1103. * @operation add_board_label
  1104. * @summary Add a label to a board
  1105. *
  1106. * @description If the board doesn't have the name/color label, this function
  1107. * adds the label to the board.
  1108. *
  1109. * @param {string} boardId the board
  1110. * @param {string} color the color of the new label
  1111. * @param {string} name the name of the new label
  1112. *
  1113. * @return_type string
  1114. */
  1115. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function (req, res) {
  1116. Authentication.checkUserId(req.userId);
  1117. const id = req.params.boardId;
  1118. try {
  1119. if (req.body.hasOwnProperty('label')) {
  1120. const board = Boards.findOne({ _id: id });
  1121. const color = req.body.label.color;
  1122. const name = req.body.label.name;
  1123. const labelId = Random.id(6);
  1124. if (!board.getLabel(name, color)) {
  1125. Boards.direct.update({ _id: id }, { $push: { labels: { _id: labelId, name, color } } });
  1126. JsonRoutes.sendResult(res, {
  1127. code: 200,
  1128. data: labelId,
  1129. });
  1130. } else {
  1131. JsonRoutes.sendResult(res, {
  1132. code: 200,
  1133. });
  1134. }
  1135. }
  1136. }
  1137. catch (error) {
  1138. JsonRoutes.sendResult(res, {
  1139. data: error,
  1140. });
  1141. }
  1142. });
  1143. /**
  1144. * @operation set_board_member_permission
  1145. * @tag Users
  1146. * @summary Change the permission of a member of a board
  1147. *
  1148. * @param {string} boardId the ID of the board that we are changing
  1149. * @param {string} memberId the ID of the user to change permissions
  1150. * @param {boolean} isAdmin admin capability
  1151. * @param {boolean} isNoComments NoComments capability
  1152. * @param {boolean} isCommentOnly CommentsOnly capability
  1153. */
  1154. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function (req, res) {
  1155. try {
  1156. const boardId = req.params.boardId;
  1157. const memberId = req.params.memberId;
  1158. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  1159. Authentication.checkBoardAccess(req.userId, boardId);
  1160. const board = Boards.findOne({ _id: boardId });
  1161. function isTrue(data){
  1162. try {
  1163. return data.toLowerCase() === 'true';
  1164. }
  1165. catch (error) {
  1166. return data;
  1167. }
  1168. }
  1169. const query = board.setMemberPermission(memberId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), req.userId);
  1170. JsonRoutes.sendResult(res, {
  1171. code: 200,
  1172. data: query,
  1173. });
  1174. }
  1175. catch (error) {
  1176. JsonRoutes.sendResult(res, {
  1177. code: 200,
  1178. data: error,
  1179. });
  1180. }
  1181. });
  1182. }