boards.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. Boards = new Mongo.Collection('boards');
  2. Boards.attachSchema(new SimpleSchema({
  3. title: {
  4. type: String,
  5. },
  6. slug: {
  7. type: String,
  8. autoValue() { // eslint-disable-line consistent-return
  9. // XXX We need to improve slug management. Only the id should be necessary
  10. // to identify a board in the code.
  11. // XXX If the board title is updated, the slug should also be updated.
  12. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  13. // return an empty string. This is causes bugs in our application so we set
  14. // a default slug in this case.
  15. if (this.isInsert && !this.isSet) {
  16. let slug = 'board';
  17. const title = this.field('title');
  18. if (title.isSet) {
  19. slug = getSlug(title.value) || slug;
  20. }
  21. return slug;
  22. }
  23. },
  24. },
  25. archived: {
  26. type: Boolean,
  27. autoValue() { // eslint-disable-line consistent-return
  28. if (this.isInsert && !this.isSet) {
  29. return false;
  30. }
  31. },
  32. },
  33. createdAt: {
  34. type: Date,
  35. autoValue() { // eslint-disable-line consistent-return
  36. if (this.isInsert) {
  37. return new Date();
  38. } else {
  39. this.unset();
  40. }
  41. },
  42. },
  43. // XXX Inconsistent field naming
  44. modifiedAt: {
  45. type: Date,
  46. optional: true,
  47. autoValue() { // eslint-disable-line consistent-return
  48. if (this.isUpdate) {
  49. return new Date();
  50. } else {
  51. this.unset();
  52. }
  53. },
  54. },
  55. // De-normalized number of users that have starred this board
  56. stars: {
  57. type: Number,
  58. autoValue() { // eslint-disable-line consistent-return
  59. if (this.isInsert) {
  60. return 0;
  61. }
  62. },
  63. },
  64. // De-normalized label system
  65. 'labels': {
  66. type: [Object],
  67. autoValue() { // eslint-disable-line consistent-return
  68. if (this.isInsert && !this.isSet) {
  69. const colors = Boards.simpleSchema()._schema['labels.$.color'].allowedValues;
  70. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  71. return defaultLabelsColors.map((color) => ({
  72. color,
  73. _id: Random.id(6),
  74. name: '',
  75. }));
  76. }
  77. },
  78. },
  79. 'labels.$._id': {
  80. // We don't specify that this field must be unique in the board because that
  81. // will cause performance penalties and is not necessary since this field is
  82. // always set on the server.
  83. // XXX Actually if we create a new label, the `_id` is set on the client
  84. // without being overwritten by the server, could it be a problem?
  85. type: String,
  86. },
  87. 'labels.$.name': {
  88. type: String,
  89. optional: true,
  90. },
  91. 'labels.$.color': {
  92. type: String,
  93. allowedValues: [
  94. 'green', 'yellow', 'orange', 'red', 'purple',
  95. 'blue', 'sky', 'lime', 'pink', 'black',
  96. ],
  97. },
  98. // XXX We might want to maintain more informations under the member sub-
  99. // documents like de-normalized meta-data (the date the member joined the
  100. // board, the number of contributions, etc.).
  101. 'members': {
  102. type: [Object],
  103. autoValue() { // eslint-disable-line consistent-return
  104. if (this.isInsert && !this.isSet) {
  105. return [{
  106. userId: this.userId,
  107. isAdmin: true,
  108. isActive: true,
  109. isCommentOnly: false,
  110. }];
  111. }
  112. },
  113. },
  114. 'members.$.userId': {
  115. type: String,
  116. },
  117. 'members.$.isAdmin': {
  118. type: Boolean,
  119. },
  120. 'members.$.isActive': {
  121. type: Boolean,
  122. },
  123. 'members.$.isCommentOnly': {
  124. type: Boolean,
  125. },
  126. permission: {
  127. type: String,
  128. allowedValues: ['public', 'private'],
  129. },
  130. color: {
  131. type: String,
  132. allowedValues: [
  133. 'belize',
  134. 'nephritis',
  135. 'pomegranate',
  136. 'pumpkin',
  137. 'wisteria',
  138. 'midnight',
  139. ],
  140. autoValue() { // eslint-disable-line consistent-return
  141. if (this.isInsert && !this.isSet) {
  142. return Boards.simpleSchema()._schema.color.allowedValues[0];
  143. }
  144. },
  145. },
  146. description: {
  147. type: String,
  148. optional: true,
  149. },
  150. }));
  151. Boards.helpers({
  152. /**
  153. * Is supplied user authorized to view this board?
  154. */
  155. isVisibleBy(user) {
  156. if (this.isPublic()) {
  157. // public boards are visible to everyone
  158. return true;
  159. } else {
  160. // otherwise you have to be logged-in and active member
  161. return user && this.isActiveMember(user._id);
  162. }
  163. },
  164. /**
  165. * Is the user one of the active members of the board?
  166. *
  167. * @param userId
  168. * @returns {boolean} the member that matches, or undefined/false
  169. */
  170. isActiveMember(userId) {
  171. if (userId) {
  172. return this.members.find((member) => (member.userId === userId && member.isActive));
  173. } else {
  174. return false;
  175. }
  176. },
  177. isPublic() {
  178. return this.permission === 'public';
  179. },
  180. lists() {
  181. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  182. },
  183. hasOvertimeCards(){
  184. const card = Cards.findOne({isOvertime: true, boardId: this._id, archived: false} );
  185. return card !== undefined;
  186. },
  187. hasSpentTimeCards(){
  188. const card = Cards.findOne({spentTime: { $gt: 0 }, boardId: this._id, archived: false} );
  189. return card !== undefined;
  190. },
  191. activities() {
  192. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  193. },
  194. activeMembers() {
  195. return _.where(this.members, { isActive: true });
  196. },
  197. activeAdmins() {
  198. return _.where(this.members, { isActive: true, isAdmin: true });
  199. },
  200. memberUsers() {
  201. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  202. },
  203. getLabel(name, color) {
  204. return _.findWhere(this.labels, { name, color });
  205. },
  206. labelIndex(labelId) {
  207. return _.pluck(this.labels, '_id').indexOf(labelId);
  208. },
  209. memberIndex(memberId) {
  210. return _.pluck(this.members, 'userId').indexOf(memberId);
  211. },
  212. hasMember(memberId) {
  213. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  214. },
  215. hasAdmin(memberId) {
  216. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: true });
  217. },
  218. hasCommentOnly(memberId) {
  219. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isCommentOnly: true });
  220. },
  221. absoluteUrl() {
  222. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  223. },
  224. colorClass() {
  225. return `board-color-${this.color}`;
  226. },
  227. // XXX currently mutations return no value so we have an issue when using addLabel in import
  228. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  229. pushLabel(name, color) {
  230. const _id = Random.id(6);
  231. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  232. return _id;
  233. },
  234. });
  235. Boards.mutations({
  236. archive() {
  237. return { $set: { archived: true } };
  238. },
  239. restore() {
  240. return { $set: { archived: false } };
  241. },
  242. rename(title) {
  243. return { $set: { title } };
  244. },
  245. setDescription(description) {
  246. return { $set: { description } };
  247. },
  248. setColor(color) {
  249. return { $set: { color } };
  250. },
  251. setVisibility(visibility) {
  252. return { $set: { permission: visibility } };
  253. },
  254. addLabel(name, color) {
  255. // If label with the same name and color already exists we don't want to
  256. // create another one because they would be indistinguishable in the UI
  257. // (they would still have different `_id` but that is not exposed to the
  258. // user).
  259. if (!this.getLabel(name, color)) {
  260. const _id = Random.id(6);
  261. return { $push: { labels: { _id, name, color } } };
  262. }
  263. return {};
  264. },
  265. editLabel(labelId, name, color) {
  266. if (!this.getLabel(name, color)) {
  267. const labelIndex = this.labelIndex(labelId);
  268. return {
  269. $set: {
  270. [`labels.${labelIndex}.name`]: name,
  271. [`labels.${labelIndex}.color`]: color,
  272. },
  273. };
  274. }
  275. return {};
  276. },
  277. removeLabel(labelId) {
  278. return { $pull: { labels: { _id: labelId } } };
  279. },
  280. changeOwnership(fromId, toId) {
  281. const memberIndex = this.memberIndex(fromId);
  282. return {
  283. $set: {
  284. [`members.${memberIndex}.userId`]: toId,
  285. },
  286. };
  287. },
  288. addMember(memberId) {
  289. const memberIndex = this.memberIndex(memberId);
  290. if (memberIndex >= 0) {
  291. return {
  292. $set: {
  293. [`members.${memberIndex}.isActive`]: true,
  294. },
  295. };
  296. }
  297. return {
  298. $push: {
  299. members: {
  300. userId: memberId,
  301. isAdmin: false,
  302. isActive: true,
  303. isCommentOnly: false,
  304. },
  305. },
  306. };
  307. },
  308. removeMember(memberId) {
  309. const memberIndex = this.memberIndex(memberId);
  310. // we do not allow the only one admin to be removed
  311. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  312. if (!allowRemove) {
  313. return {
  314. $set: {
  315. [`members.${memberIndex}.isActive`]: true,
  316. },
  317. };
  318. }
  319. return {
  320. $set: {
  321. [`members.${memberIndex}.isActive`]: false,
  322. [`members.${memberIndex}.isAdmin`]: false,
  323. },
  324. };
  325. },
  326. setMemberPermission(memberId, isAdmin, isCommentOnly) {
  327. const memberIndex = this.memberIndex(memberId);
  328. // do not allow change permission of self
  329. if (memberId === Meteor.userId()) {
  330. isAdmin = this.members[memberIndex].isAdmin;
  331. }
  332. return {
  333. $set: {
  334. [`members.${memberIndex}.isAdmin`]: isAdmin,
  335. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  336. },
  337. };
  338. },
  339. });
  340. if (Meteor.isServer) {
  341. Boards.allow({
  342. insert: Meteor.userId,
  343. update: allowIsBoardAdmin,
  344. remove: allowIsBoardAdmin,
  345. fetch: ['members'],
  346. });
  347. // The number of users that have starred this board is managed by trusted code
  348. // and the user is not allowed to update it
  349. Boards.deny({
  350. update(userId, board, fieldNames) {
  351. return _.contains(fieldNames, 'stars');
  352. },
  353. fetch: [],
  354. });
  355. // We can't remove a member if it is the last administrator
  356. Boards.deny({
  357. update(userId, doc, fieldNames, modifier) {
  358. if (!_.contains(fieldNames, 'members'))
  359. return false;
  360. // We only care in case of a $pull operation, ie remove a member
  361. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  362. return false;
  363. // If there is more than one admin, it's ok to remove anyone
  364. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  365. if (nbAdmins > 1)
  366. return false;
  367. // If all the previous conditions were verified, we can't remove
  368. // a user if it's an admin
  369. const removedMemberId = modifier.$pull.members.userId;
  370. return Boolean(_.findWhere(doc.members, {
  371. userId: removedMemberId,
  372. isAdmin: true,
  373. }));
  374. },
  375. fetch: ['members'],
  376. });
  377. Meteor.methods({
  378. quitBoard(boardId) {
  379. check(boardId, String);
  380. const board = Boards.findOne(boardId);
  381. if (board) {
  382. const userId = Meteor.userId();
  383. const index = board.memberIndex(userId);
  384. if (index >= 0) {
  385. board.removeMember(userId);
  386. return true;
  387. } else throw new Meteor.Error('error-board-notAMember');
  388. } else throw new Meteor.Error('error-board-doesNotExist');
  389. },
  390. });
  391. }
  392. if (Meteor.isServer) {
  393. // Let MongoDB ensure that a member is not included twice in the same board
  394. Meteor.startup(() => {
  395. Boards._collection._ensureIndex({
  396. _id: 1,
  397. 'members.userId': 1,
  398. }, { unique: true });
  399. Boards._collection._ensureIndex({ 'members.userId': 1 });
  400. });
  401. // Genesis: the first activity of the newly created board
  402. Boards.after.insert((userId, doc) => {
  403. Activities.insert({
  404. userId,
  405. type: 'board',
  406. activityTypeId: doc._id,
  407. activityType: 'createBoard',
  408. boardId: doc._id,
  409. });
  410. });
  411. // If the user remove one label from a board, we cant to remove reference of
  412. // this label in any card of this board.
  413. Boards.after.update((userId, doc, fieldNames, modifier) => {
  414. if (!_.contains(fieldNames, 'labels') ||
  415. !modifier.$pull ||
  416. !modifier.$pull.labels ||
  417. !modifier.$pull.labels._id) {
  418. return;
  419. }
  420. const removedLabelId = modifier.$pull.labels._id;
  421. Cards.update(
  422. { boardId: doc._id },
  423. {
  424. $pull: {
  425. labelIds: removedLabelId,
  426. },
  427. },
  428. { multi: true }
  429. );
  430. });
  431. const foreachRemovedMember = (doc, modifier, callback) => {
  432. Object.keys(modifier).forEach((set) => {
  433. if (modifier[set] !== false) {
  434. return;
  435. }
  436. const parts = set.split('.');
  437. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  438. callback(doc.members[parts[1]].userId);
  439. }
  440. });
  441. };
  442. // Remove a member from all objects of the board before leaving the board
  443. Boards.before.update((userId, doc, fieldNames, modifier) => {
  444. if (!_.contains(fieldNames, 'members')) {
  445. return;
  446. }
  447. if (modifier.$set) {
  448. const boardId = doc._id;
  449. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  450. Cards.update(
  451. { boardId },
  452. {
  453. $pull: {
  454. members: memberId,
  455. watchers: memberId,
  456. },
  457. },
  458. { multi: true }
  459. );
  460. Lists.update(
  461. { boardId },
  462. {
  463. $pull: {
  464. watchers: memberId,
  465. },
  466. },
  467. { multi: true }
  468. );
  469. const board = Boards._transform(doc);
  470. board.setWatcher(memberId, false);
  471. // Remove board from users starred list
  472. if (!board.isPublic()) {
  473. Users.update(
  474. memberId,
  475. {
  476. $pull: {
  477. 'profile.starredBoards': boardId,
  478. },
  479. }
  480. );
  481. }
  482. });
  483. }
  484. });
  485. // Add a new activity if we add or remove a member to the board
  486. Boards.after.update((userId, doc, fieldNames, modifier) => {
  487. if (!_.contains(fieldNames, 'members')) {
  488. return;
  489. }
  490. // Say hello to the new member
  491. if (modifier.$push && modifier.$push.members) {
  492. const memberId = modifier.$push.members.userId;
  493. Activities.insert({
  494. userId,
  495. memberId,
  496. type: 'member',
  497. activityType: 'addBoardMember',
  498. boardId: doc._id,
  499. });
  500. }
  501. // Say goodbye to the former member
  502. if (modifier.$set) {
  503. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  504. Activities.insert({
  505. userId,
  506. memberId,
  507. type: 'member',
  508. activityType: 'removeBoardMember',
  509. boardId: doc._id,
  510. });
  511. });
  512. }
  513. });
  514. }
  515. //BOARDS REST API
  516. if (Meteor.isServer) {
  517. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res, next) {
  518. try {
  519. Authentication.checkLoggedIn(req.userId);
  520. const paramUserId = req.params.userId;
  521. // A normal user should be able to see their own boards,
  522. // admins can access boards of any user
  523. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  524. const data = Boards.find({
  525. archived: false,
  526. 'members.userId': paramUserId,
  527. }, {
  528. sort: ['title'],
  529. }).map(function(board) {
  530. return {
  531. _id: board._id,
  532. title: board.title,
  533. };
  534. });
  535. JsonRoutes.sendResult(res, {code: 200, data});
  536. }
  537. catch (error) {
  538. JsonRoutes.sendResult(res, {
  539. code: 200,
  540. data: error,
  541. });
  542. }
  543. });
  544. JsonRoutes.add('GET', '/api/boards', function (req, res, next) {
  545. try {
  546. Authentication.checkUserId(req.userId);
  547. JsonRoutes.sendResult(res, {
  548. code: 200,
  549. data: Boards.find({ permission: 'public' }).map(function (doc) {
  550. return {
  551. _id: doc._id,
  552. title: doc.title,
  553. };
  554. }),
  555. });
  556. }
  557. catch (error) {
  558. JsonRoutes.sendResult(res, {
  559. code: 200,
  560. data: error,
  561. });
  562. }
  563. });
  564. JsonRoutes.add('GET', '/api/boards/:id', function (req, res, next) {
  565. try {
  566. const id = req.params.id;
  567. Authentication.checkBoardAccess(req.userId, id);
  568. JsonRoutes.sendResult(res, {
  569. code: 200,
  570. data: Boards.findOne({ _id: id }),
  571. });
  572. }
  573. catch (error) {
  574. JsonRoutes.sendResult(res, {
  575. code: 200,
  576. data: error,
  577. });
  578. }
  579. });
  580. JsonRoutes.add('POST', '/api/boards', function (req, res, next) {
  581. try {
  582. Authentication.checkUserId(req.userId);
  583. const id = Boards.insert({
  584. title: req.body.title,
  585. members: [
  586. {
  587. userId: req.body.owner,
  588. isAdmin: true,
  589. isActive: true,
  590. isCommentOnly: false,
  591. },
  592. ],
  593. permission: 'public',
  594. color: 'belize',
  595. });
  596. JsonRoutes.sendResult(res, {
  597. code: 200,
  598. data: {
  599. _id: id,
  600. },
  601. });
  602. }
  603. catch (error) {
  604. JsonRoutes.sendResult(res, {
  605. code: 200,
  606. data: error,
  607. });
  608. }
  609. });
  610. JsonRoutes.add('DELETE', '/api/boards/:id', function (req, res, next) {
  611. try {
  612. Authentication.checkUserId(req.userId);
  613. const id = req.params.id;
  614. Boards.remove({ _id: id });
  615. JsonRoutes.sendResult(res, {
  616. code: 200,
  617. data:{
  618. _id: id,
  619. },
  620. });
  621. }
  622. catch (error) {
  623. JsonRoutes.sendResult(res, {
  624. code: 200,
  625. data: error,
  626. });
  627. }
  628. });
  629. }