boards.js 29 KB

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