boards.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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-lists';
  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. searchCards(term) {
  246. check(term, Match.OneOf(String, null, undefined));
  247. let query = { boardId: this._id };
  248. const projection = { limit: 10, sort: { createdAt: -1 } };
  249. if (term) {
  250. const regex = new RegExp(term, 'i');
  251. query = {
  252. boardId: this._id,
  253. $or: [
  254. { title: regex },
  255. { description: regex },
  256. ],
  257. };
  258. }
  259. return Cards.find(query, projection);
  260. },
  261. });
  262. Boards.mutations({
  263. archive() {
  264. return { $set: { archived: true } };
  265. },
  266. restore() {
  267. return { $set: { archived: false } };
  268. },
  269. rename(title) {
  270. return { $set: { title } };
  271. },
  272. setDescription(description) {
  273. return { $set: { description } };
  274. },
  275. setColor(color) {
  276. return { $set: { color } };
  277. },
  278. setVisibility(visibility) {
  279. return { $set: { permission: visibility } };
  280. },
  281. addLabel(name, color) {
  282. // If label with the same name and color already exists we don't want to
  283. // create another one because they would be indistinguishable in the UI
  284. // (they would still have different `_id` but that is not exposed to the
  285. // user).
  286. if (!this.getLabel(name, color)) {
  287. const _id = Random.id(6);
  288. return { $push: { labels: { _id, name, color } } };
  289. }
  290. return {};
  291. },
  292. editLabel(labelId, name, color) {
  293. if (!this.getLabel(name, color)) {
  294. const labelIndex = this.labelIndex(labelId);
  295. return {
  296. $set: {
  297. [`labels.${labelIndex}.name`]: name,
  298. [`labels.${labelIndex}.color`]: color,
  299. },
  300. };
  301. }
  302. return {};
  303. },
  304. removeLabel(labelId) {
  305. return { $pull: { labels: { _id: labelId } } };
  306. },
  307. changeOwnership(fromId, toId) {
  308. const memberIndex = this.memberIndex(fromId);
  309. return {
  310. $set: {
  311. [`members.${memberIndex}.userId`]: toId,
  312. },
  313. };
  314. },
  315. addMember(memberId) {
  316. const memberIndex = this.memberIndex(memberId);
  317. if (memberIndex >= 0) {
  318. return {
  319. $set: {
  320. [`members.${memberIndex}.isActive`]: true,
  321. },
  322. };
  323. }
  324. return {
  325. $push: {
  326. members: {
  327. userId: memberId,
  328. isAdmin: false,
  329. isActive: true,
  330. isCommentOnly: false,
  331. },
  332. },
  333. };
  334. },
  335. removeMember(memberId) {
  336. const memberIndex = this.memberIndex(memberId);
  337. // we do not allow the only one admin to be removed
  338. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  339. if (!allowRemove) {
  340. return {
  341. $set: {
  342. [`members.${memberIndex}.isActive`]: true,
  343. },
  344. };
  345. }
  346. return {
  347. $set: {
  348. [`members.${memberIndex}.isActive`]: false,
  349. [`members.${memberIndex}.isAdmin`]: false,
  350. },
  351. };
  352. },
  353. setMemberPermission(memberId, isAdmin, isCommentOnly) {
  354. const memberIndex = this.memberIndex(memberId);
  355. // do not allow change permission of self
  356. if (memberId === Meteor.userId()) {
  357. isAdmin = this.members[memberIndex].isAdmin;
  358. }
  359. return {
  360. $set: {
  361. [`members.${memberIndex}.isAdmin`]: isAdmin,
  362. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  363. },
  364. };
  365. },
  366. });
  367. if (Meteor.isServer) {
  368. Boards.allow({
  369. insert: Meteor.userId,
  370. update: allowIsBoardAdmin,
  371. remove: allowIsBoardAdmin,
  372. fetch: ['members'],
  373. });
  374. // The number of users that have starred this board is managed by trusted code
  375. // and the user is not allowed to update it
  376. Boards.deny({
  377. update(userId, board, fieldNames) {
  378. return _.contains(fieldNames, 'stars');
  379. },
  380. fetch: [],
  381. });
  382. // We can't remove a member if it is the last administrator
  383. Boards.deny({
  384. update(userId, doc, fieldNames, modifier) {
  385. if (!_.contains(fieldNames, 'members'))
  386. return false;
  387. // We only care in case of a $pull operation, ie remove a member
  388. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  389. return false;
  390. // If there is more than one admin, it's ok to remove anyone
  391. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  392. if (nbAdmins > 1)
  393. return false;
  394. // If all the previous conditions were verified, we can't remove
  395. // a user if it's an admin
  396. const removedMemberId = modifier.$pull.members.userId;
  397. return Boolean(_.findWhere(doc.members, {
  398. userId: removedMemberId,
  399. isAdmin: true,
  400. }));
  401. },
  402. fetch: ['members'],
  403. });
  404. Meteor.methods({
  405. quitBoard(boardId) {
  406. check(boardId, String);
  407. const board = Boards.findOne(boardId);
  408. if (board) {
  409. const userId = Meteor.userId();
  410. const index = board.memberIndex(userId);
  411. if (index >= 0) {
  412. board.removeMember(userId);
  413. return true;
  414. } else throw new Meteor.Error('error-board-notAMember');
  415. } else throw new Meteor.Error('error-board-doesNotExist');
  416. },
  417. });
  418. }
  419. if (Meteor.isServer) {
  420. // Let MongoDB ensure that a member is not included twice in the same board
  421. Meteor.startup(() => {
  422. Boards._collection._ensureIndex({
  423. _id: 1,
  424. 'members.userId': 1,
  425. }, { unique: true });
  426. Boards._collection._ensureIndex({ 'members.userId': 1 });
  427. });
  428. // Genesis: the first activity of the newly created board
  429. Boards.after.insert((userId, doc) => {
  430. Activities.insert({
  431. userId,
  432. type: 'board',
  433. activityTypeId: doc._id,
  434. activityType: 'createBoard',
  435. boardId: doc._id,
  436. });
  437. });
  438. // If the user remove one label from a board, we cant to remove reference of
  439. // this label in any card of this board.
  440. Boards.after.update((userId, doc, fieldNames, modifier) => {
  441. if (!_.contains(fieldNames, 'labels') ||
  442. !modifier.$pull ||
  443. !modifier.$pull.labels ||
  444. !modifier.$pull.labels._id) {
  445. return;
  446. }
  447. const removedLabelId = modifier.$pull.labels._id;
  448. Cards.update(
  449. { boardId: doc._id },
  450. {
  451. $pull: {
  452. labelIds: removedLabelId,
  453. },
  454. },
  455. { multi: true }
  456. );
  457. });
  458. const foreachRemovedMember = (doc, modifier, callback) => {
  459. Object.keys(modifier).forEach((set) => {
  460. if (modifier[set] !== false) {
  461. return;
  462. }
  463. const parts = set.split('.');
  464. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  465. callback(doc.members[parts[1]].userId);
  466. }
  467. });
  468. };
  469. // Remove a member from all objects of the board before leaving the board
  470. Boards.before.update((userId, doc, fieldNames, modifier) => {
  471. if (!_.contains(fieldNames, 'members')) {
  472. return;
  473. }
  474. if (modifier.$set) {
  475. const boardId = doc._id;
  476. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  477. Cards.update(
  478. { boardId },
  479. {
  480. $pull: {
  481. members: memberId,
  482. watchers: memberId,
  483. },
  484. },
  485. { multi: true }
  486. );
  487. Lists.update(
  488. { boardId },
  489. {
  490. $pull: {
  491. watchers: memberId,
  492. },
  493. },
  494. { multi: true }
  495. );
  496. const board = Boards._transform(doc);
  497. board.setWatcher(memberId, false);
  498. // Remove board from users starred list
  499. if (!board.isPublic()) {
  500. Users.update(
  501. memberId,
  502. {
  503. $pull: {
  504. 'profile.starredBoards': boardId,
  505. },
  506. }
  507. );
  508. }
  509. });
  510. }
  511. });
  512. // Add a new activity if we add or remove a member to the board
  513. Boards.after.update((userId, doc, fieldNames, modifier) => {
  514. if (!_.contains(fieldNames, 'members')) {
  515. return;
  516. }
  517. // Say hello to the new member
  518. if (modifier.$push && modifier.$push.members) {
  519. const memberId = modifier.$push.members.userId;
  520. Activities.insert({
  521. userId,
  522. memberId,
  523. type: 'member',
  524. activityType: 'addBoardMember',
  525. boardId: doc._id,
  526. });
  527. }
  528. // Say goodbye to the former member
  529. if (modifier.$set) {
  530. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  531. Activities.insert({
  532. userId,
  533. memberId,
  534. type: 'member',
  535. activityType: 'removeBoardMember',
  536. boardId: doc._id,
  537. });
  538. });
  539. }
  540. });
  541. }
  542. //BOARDS REST API
  543. if (Meteor.isServer) {
  544. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  545. try {
  546. Authentication.checkLoggedIn(req.userId);
  547. const paramUserId = req.params.userId;
  548. // A normal user should be able to see their own boards,
  549. // admins can access boards of any user
  550. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  551. const data = Boards.find({
  552. archived: false,
  553. 'members.userId': paramUserId,
  554. }, {
  555. sort: ['title'],
  556. }).map(function(board) {
  557. return {
  558. _id: board._id,
  559. title: board.title,
  560. };
  561. });
  562. JsonRoutes.sendResult(res, {code: 200, data});
  563. }
  564. catch (error) {
  565. JsonRoutes.sendResult(res, {
  566. code: 200,
  567. data: error,
  568. });
  569. }
  570. });
  571. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  572. try {
  573. Authentication.checkUserId(req.userId);
  574. JsonRoutes.sendResult(res, {
  575. code: 200,
  576. data: Boards.find({ permission: 'public' }).map(function (doc) {
  577. return {
  578. _id: doc._id,
  579. title: doc.title,
  580. };
  581. }),
  582. });
  583. }
  584. catch (error) {
  585. JsonRoutes.sendResult(res, {
  586. code: 200,
  587. data: error,
  588. });
  589. }
  590. });
  591. JsonRoutes.add('GET', '/api/boards/:id', function (req, res) {
  592. try {
  593. const id = req.params.id;
  594. Authentication.checkBoardAccess(req.userId, id);
  595. JsonRoutes.sendResult(res, {
  596. code: 200,
  597. data: Boards.findOne({ _id: id }),
  598. });
  599. }
  600. catch (error) {
  601. JsonRoutes.sendResult(res, {
  602. code: 200,
  603. data: error,
  604. });
  605. }
  606. });
  607. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  608. try {
  609. Authentication.checkUserId(req.userId);
  610. const id = Boards.insert({
  611. title: req.body.title,
  612. members: [
  613. {
  614. userId: req.body.owner,
  615. isAdmin: true,
  616. isActive: true,
  617. isCommentOnly: false,
  618. },
  619. ],
  620. permission: 'public',
  621. color: 'belize',
  622. });
  623. JsonRoutes.sendResult(res, {
  624. code: 200,
  625. data: {
  626. _id: id,
  627. },
  628. });
  629. }
  630. catch (error) {
  631. JsonRoutes.sendResult(res, {
  632. code: 200,
  633. data: error,
  634. });
  635. }
  636. });
  637. JsonRoutes.add('DELETE', '/api/boards/:id', function (req, res) {
  638. try {
  639. Authentication.checkUserId(req.userId);
  640. const id = req.params.id;
  641. Boards.remove({ _id: id });
  642. JsonRoutes.sendResult(res, {
  643. code: 200,
  644. data:{
  645. _id: id,
  646. },
  647. });
  648. }
  649. catch (error) {
  650. JsonRoutes.sendResult(res, {
  651. code: 200,
  652. data: error,
  653. });
  654. }
  655. });
  656. }