boards.js 19 KB

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