boards.js 17 KB

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