boards.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. }];
  110. }
  111. },
  112. },
  113. 'members.$.userId': {
  114. type: String,
  115. },
  116. 'members.$.isAdmin': {
  117. type: Boolean,
  118. },
  119. 'members.$.isActive': {
  120. type: Boolean,
  121. },
  122. permission: {
  123. type: String,
  124. allowedValues: ['public', 'private'],
  125. },
  126. color: {
  127. type: String,
  128. allowedValues: [
  129. 'belize',
  130. 'nephritis',
  131. 'pomegranate',
  132. 'pumpkin',
  133. 'wisteria',
  134. 'midnight',
  135. ],
  136. autoValue() { // eslint-disable-line consistent-return
  137. if (this.isInsert && !this.isSet) {
  138. return Boards.simpleSchema()._schema.color.allowedValues[0];
  139. }
  140. },
  141. },
  142. description: {
  143. type: String,
  144. optional: true,
  145. },
  146. }));
  147. Boards.helpers({
  148. /**
  149. * Is supplied user authorized to view this board?
  150. */
  151. isVisibleBy(user) {
  152. if(this.isPublic()) {
  153. // public boards are visible to everyone
  154. return true;
  155. } else {
  156. // otherwise you have to be logged-in and active member
  157. return user && this.isActiveMember(user._id);
  158. }
  159. },
  160. /**
  161. * Is the user one of the active members of the board?
  162. *
  163. * @param userId
  164. * @returns {boolean} the member that matches, or undefined/false
  165. */
  166. isActiveMember(userId) {
  167. if(userId) {
  168. return this.members.find((member) => (member.userId === userId && member.isActive));
  169. } else {
  170. return false;
  171. }
  172. },
  173. isPublic() {
  174. return this.permission === 'public';
  175. },
  176. lists() {
  177. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 }});
  178. },
  179. activities() {
  180. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 }});
  181. },
  182. activeMembers() {
  183. return _.where(this.members, {isActive: true});
  184. },
  185. activeAdmins() {
  186. return _.where(this.members, {isActive: true, isAdmin: true});
  187. },
  188. memberUsers() {
  189. return Users.find({ _id: {$in: _.pluck(this.members, 'userId')} });
  190. },
  191. getLabel(name, color) {
  192. return _.findWhere(this.labels, { name, color });
  193. },
  194. labelIndex(labelId) {
  195. return _.pluck(this.labels, '_id').indexOf(labelId);
  196. },
  197. memberIndex(memberId) {
  198. return _.pluck(this.members, 'userId').indexOf(memberId);
  199. },
  200. hasMember(memberId) {
  201. return !!_.findWhere(this.members, {userId: memberId, isActive: true});
  202. },
  203. hasAdmin(memberId) {
  204. return !!_.findWhere(this.members, {userId: memberId, isActive: true, isAdmin: true});
  205. },
  206. absoluteUrl() {
  207. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  208. },
  209. colorClass() {
  210. return `board-color-${this.color}`;
  211. },
  212. // XXX currently mutations return no value so we have an issue when using addLabel in import
  213. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  214. pushLabel(name, color) {
  215. const _id = Random.id(6);
  216. Boards.direct.update(this._id, { $push: {labels: { _id, name, color }}});
  217. return _id;
  218. },
  219. });
  220. Boards.mutations({
  221. archive() {
  222. return { $set: { archived: true }};
  223. },
  224. restore() {
  225. return { $set: { archived: false }};
  226. },
  227. rename(title) {
  228. return { $set: { title }};
  229. },
  230. setDesciption(description) {
  231. return { $set: {description} };
  232. },
  233. setColor(color) {
  234. return { $set: { color }};
  235. },
  236. setVisibility(visibility) {
  237. return { $set: { permission: visibility }};
  238. },
  239. addLabel(name, color) {
  240. // If label with the same name and color already exists we don't want to
  241. // create another one because they would be indistinguishable in the UI
  242. // (they would still have different `_id` but that is not exposed to the
  243. // user).
  244. if (!this.getLabel(name, color)) {
  245. const _id = Random.id(6);
  246. return { $push: {labels: { _id, name, color }}};
  247. }
  248. return {};
  249. },
  250. editLabel(labelId, name, color) {
  251. if (!this.getLabel(name, color)) {
  252. const labelIndex = this.labelIndex(labelId);
  253. return {
  254. $set: {
  255. [`labels.${labelIndex}.name`]: name,
  256. [`labels.${labelIndex}.color`]: color,
  257. },
  258. };
  259. }
  260. return {};
  261. },
  262. removeLabel(labelId) {
  263. return { $pull: { labels: { _id: labelId }}};
  264. },
  265. addMember(memberId) {
  266. const memberIndex = this.memberIndex(memberId);
  267. if (memberIndex >= 0) {
  268. return {
  269. $set: {
  270. [`members.${memberIndex}.isActive`]: true,
  271. },
  272. };
  273. }
  274. return {
  275. $push: {
  276. members: {
  277. userId: memberId,
  278. isAdmin: false,
  279. isActive: true,
  280. },
  281. },
  282. };
  283. },
  284. removeMember(memberId) {
  285. const memberIndex = this.memberIndex(memberId);
  286. // we do not allow the only one admin to be removed
  287. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  288. if (!allowRemove) {
  289. return {
  290. $set: {
  291. [`members.${memberIndex}.isActive`]: true,
  292. },
  293. };
  294. }
  295. return {
  296. $set: {
  297. [`members.${memberIndex}.isActive`]: false,
  298. [`members.${memberIndex}.isAdmin`]: false,
  299. },
  300. };
  301. },
  302. setMemberPermission(memberId, isAdmin) {
  303. const memberIndex = this.memberIndex(memberId);
  304. // do not allow change permission of self
  305. if (memberId === Meteor.userId()) {
  306. isAdmin = this.members[memberIndex].isAdmin;
  307. }
  308. return {
  309. $set: {
  310. [`members.${memberIndex}.isAdmin`]: isAdmin,
  311. },
  312. };
  313. },
  314. });
  315. if (Meteor.isServer) {
  316. Boards.allow({
  317. insert: Meteor.userId,
  318. update: allowIsBoardAdmin,
  319. remove: allowIsBoardAdmin,
  320. fetch: ['members'],
  321. });
  322. // The number of users that have starred this board is managed by trusted code
  323. // and the user is not allowed to update it
  324. Boards.deny({
  325. update(userId, board, fieldNames) {
  326. return _.contains(fieldNames, 'stars');
  327. },
  328. fetch: [],
  329. });
  330. // We can't remove a member if it is the last administrator
  331. Boards.deny({
  332. update(userId, doc, fieldNames, modifier) {
  333. if (!_.contains(fieldNames, 'members'))
  334. return false;
  335. // We only care in case of a $pull operation, ie remove a member
  336. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  337. return false;
  338. // If there is more than one admin, it's ok to remove anyone
  339. const nbAdmins = _.where(doc.members, {isActive: true, isAdmin: true}).length;
  340. if (nbAdmins > 1)
  341. return false;
  342. // If all the previous conditions were verified, we can't remove
  343. // a user if it's an admin
  344. const removedMemberId = modifier.$pull.members.userId;
  345. return Boolean(_.findWhere(doc.members, {
  346. userId: removedMemberId,
  347. isAdmin: true,
  348. }));
  349. },
  350. fetch: ['members'],
  351. });
  352. Meteor.methods({
  353. quitBoard(boardId) {
  354. check(boardId, String);
  355. const board = Boards.findOne(boardId);
  356. if (board) {
  357. const userId = Meteor.userId();
  358. const index = board.memberIndex(userId);
  359. if (index>=0) {
  360. board.removeMember(userId);
  361. return true;
  362. } else throw new Meteor.Error('error-board-notAMember');
  363. } else throw new Meteor.Error('error-board-doesNotExist');
  364. },
  365. });
  366. }
  367. if (Meteor.isServer) {
  368. // Let MongoDB ensure that a member is not included twice in the same board
  369. Meteor.startup(() => {
  370. Boards._collection._ensureIndex({
  371. _id: 1,
  372. 'members.userId': 1,
  373. }, { unique: true });
  374. });
  375. // Genesis: the first activity of the newly created board
  376. Boards.after.insert((userId, doc) => {
  377. Activities.insert({
  378. userId,
  379. type: 'board',
  380. activityTypeId: doc._id,
  381. activityType: 'createBoard',
  382. boardId: doc._id,
  383. });
  384. });
  385. // If the user remove one label from a board, we cant to remove reference of
  386. // this label in any card of this board.
  387. Boards.after.update((userId, doc, fieldNames, modifier) => {
  388. if (!_.contains(fieldNames, 'labels') ||
  389. !modifier.$pull ||
  390. !modifier.$pull.labels ||
  391. !modifier.$pull.labels._id) {
  392. return;
  393. }
  394. const removedLabelId = modifier.$pull.labels._id;
  395. Cards.update(
  396. { boardId: doc._id },
  397. {
  398. $pull: {
  399. labelIds: removedLabelId,
  400. },
  401. },
  402. { multi: true }
  403. );
  404. });
  405. const foreachRemovedMember = (doc, modifier, callback) => {
  406. Object.keys(modifier).forEach((set) => {
  407. if (modifier[set] !== false) {
  408. return;
  409. }
  410. const parts = set.split('.');
  411. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  412. callback(doc.members[parts[1]].userId);
  413. }
  414. });
  415. };
  416. // Add a new activity if we add or remove a member to the board
  417. Boards.after.update((userId, doc, fieldNames, modifier) => {
  418. if (!_.contains(fieldNames, 'members')) {
  419. return;
  420. }
  421. // Say hello to the new member
  422. if (modifier.$push && modifier.$push.members) {
  423. const memberId = modifier.$push.members.userId;
  424. Activities.insert({
  425. userId,
  426. memberId,
  427. type: 'member',
  428. activityType: 'addBoardMember',
  429. boardId: doc._id,
  430. });
  431. }
  432. // Say goodbye to the former member
  433. if (modifier.$set) {
  434. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  435. Activities.insert({
  436. userId,
  437. memberId,
  438. type: 'member',
  439. activityType: 'removeBoardMember',
  440. boardId: doc._id,
  441. });
  442. });
  443. }
  444. });
  445. }