boards.js 18 KB

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