boards.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. isNoComments: false,
  113. isCommentOnly: false,
  114. }];
  115. }
  116. },
  117. },
  118. 'members.$.userId': {
  119. type: String,
  120. },
  121. 'members.$.isAdmin': {
  122. type: Boolean,
  123. },
  124. 'members.$.isActive': {
  125. type: Boolean,
  126. },
  127. 'members.$.isNoComments': {
  128. type: Boolean,
  129. optional: true,
  130. },
  131. 'members.$.isCommentOnly': {
  132. type: Boolean,
  133. optional: true,
  134. },
  135. permission: {
  136. type: String,
  137. allowedValues: ['public', 'private'],
  138. },
  139. color: {
  140. type: String,
  141. allowedValues: [
  142. 'belize',
  143. 'nephritis',
  144. 'pomegranate',
  145. 'pumpkin',
  146. 'wisteria',
  147. 'midnight',
  148. ],
  149. autoValue() { // eslint-disable-line consistent-return
  150. if (this.isInsert && !this.isSet) {
  151. return Boards.simpleSchema()._schema.color.allowedValues[0];
  152. }
  153. },
  154. },
  155. description: {
  156. type: String,
  157. optional: true,
  158. },
  159. subtasksDefaultBoardId: {
  160. type: String,
  161. optional: true,
  162. defaultValue: null,
  163. },
  164. subtasksDefaultListId: {
  165. type: String,
  166. optional: true,
  167. defaultValue: null,
  168. },
  169. allowsSubtasks: {
  170. type: Boolean,
  171. defaultValue: true,
  172. },
  173. presentParentTask: {
  174. type: String,
  175. allowedValues: [
  176. 'prefix-with-full-path',
  177. 'prefix-with-parent',
  178. 'subtext-with-full-path',
  179. 'subtext-with-parent',
  180. 'no-parent',
  181. ],
  182. optional: true,
  183. defaultValue: 'no-parent',
  184. },
  185. startAt: {
  186. type: Date,
  187. optional: true,
  188. },
  189. dueAt: {
  190. type: Date,
  191. optional: true,
  192. },
  193. endAt: {
  194. type: Date,
  195. optional: true,
  196. },
  197. spentTime: {
  198. type: Number,
  199. decimal: true,
  200. optional: true,
  201. },
  202. isOvertime: {
  203. type: Boolean,
  204. defaultValue: false,
  205. optional: true,
  206. },
  207. }));
  208. Boards.helpers({
  209. /**
  210. * Is supplied user authorized to view this board?
  211. */
  212. isVisibleBy(user) {
  213. if (this.isPublic()) {
  214. // public boards are visible to everyone
  215. return true;
  216. } else {
  217. // otherwise you have to be logged-in and active member
  218. return user && this.isActiveMember(user._id);
  219. }
  220. },
  221. /**
  222. * Is the user one of the active members of the board?
  223. *
  224. * @param userId
  225. * @returns {boolean} the member that matches, or undefined/false
  226. */
  227. isActiveMember(userId) {
  228. if (userId) {
  229. return this.members.find((member) => (member.userId === userId && member.isActive));
  230. } else {
  231. return false;
  232. }
  233. },
  234. isPublic() {
  235. return this.permission === 'public';
  236. },
  237. cards() {
  238. return Cards.find({ boardId: this._id, archived: false }, { sort: { title: 1 } });
  239. },
  240. lists() {
  241. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  242. },
  243. swimlanes() {
  244. return Swimlanes.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  245. },
  246. hasOvertimeCards(){
  247. const card = Cards.findOne({isOvertime: true, boardId: this._id, archived: false} );
  248. return card !== undefined;
  249. },
  250. hasSpentTimeCards(){
  251. const card = Cards.findOne({spentTime: { $gt: 0 }, boardId: this._id, archived: false} );
  252. return card !== undefined;
  253. },
  254. activities() {
  255. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  256. },
  257. activeMembers() {
  258. return _.where(this.members, { isActive: true });
  259. },
  260. activeAdmins() {
  261. return _.where(this.members, { isActive: true, isAdmin: true });
  262. },
  263. memberUsers() {
  264. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  265. },
  266. getMember(id) {
  267. return _.findWhere(this.members, { userId: id });
  268. },
  269. getLabel(name, color) {
  270. return _.findWhere(this.labels, { name, color });
  271. },
  272. getLabelById(labelId){
  273. return _.findWhere(this.labels, { _id: labelId });
  274. },
  275. labelIndex(labelId) {
  276. return _.pluck(this.labels, '_id').indexOf(labelId);
  277. },
  278. memberIndex(memberId) {
  279. return _.pluck(this.members, 'userId').indexOf(memberId);
  280. },
  281. hasMember(memberId) {
  282. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  283. },
  284. hasAdmin(memberId) {
  285. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: true });
  286. },
  287. hasNoComments(memberId) {
  288. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isNoComments: true });
  289. },
  290. hasCommentOnly(memberId) {
  291. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isCommentOnly: true });
  292. },
  293. absoluteUrl() {
  294. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  295. },
  296. colorClass() {
  297. return `board-color-${this.color}`;
  298. },
  299. customFields() {
  300. return CustomFields.find({ boardId: this._id }, { sort: { name: 1 } });
  301. },
  302. // XXX currently mutations return no value so we have an issue when using addLabel in import
  303. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  304. pushLabel(name, color) {
  305. const _id = Random.id(6);
  306. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  307. return _id;
  308. },
  309. searchCards(term, excludeLinked) {
  310. check(term, Match.OneOf(String, null, undefined));
  311. const query = { boardId: this._id };
  312. if (excludeLinked) {
  313. query.linkedId = null;
  314. }
  315. const projection = { limit: 10, sort: { createdAt: -1 } };
  316. if (term) {
  317. const regex = new RegExp(term, 'i');
  318. query.$or = [
  319. { title: regex },
  320. { description: regex },
  321. ];
  322. }
  323. return Cards.find(query, projection);
  324. },
  325. // A board alwasy has another board where it deposits subtasks of thasks
  326. // that belong to itself.
  327. getDefaultSubtasksBoardId() {
  328. if ((this.subtasksDefaultBoardId === null) || (this.subtasksDefaultBoardId === undefined)) {
  329. this.subtasksDefaultBoardId = Boards.insert({
  330. title: `^${this.title}^`,
  331. permission: this.permission,
  332. members: this.members,
  333. color: this.color,
  334. description: TAPi18n.__('default-subtasks-board', {board: this.title}),
  335. });
  336. Swimlanes.insert({
  337. title: TAPi18n.__('default'),
  338. boardId: this.subtasksDefaultBoardId,
  339. });
  340. Boards.update(this._id, {$set: {
  341. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  342. }});
  343. }
  344. return this.subtasksDefaultBoardId;
  345. },
  346. getDefaultSubtasksBoard() {
  347. return Boards.findOne(this.getDefaultSubtasksBoardId());
  348. },
  349. getDefaultSubtasksListId() {
  350. if ((this.subtasksDefaultListId === null) || (this.subtasksDefaultListId === undefined)) {
  351. this.subtasksDefaultListId = Lists.insert({
  352. title: TAPi18n.__('queue'),
  353. boardId: this._id,
  354. });
  355. Boards.update(this._id, {$set: {
  356. subtasksDefaultListId: this.subtasksDefaultListId,
  357. }});
  358. }
  359. return this.subtasksDefaultListId;
  360. },
  361. getDefaultSubtasksList() {
  362. return Lists.findOne(this.getDefaultSubtasksListId());
  363. },
  364. getDefaultSwimline() {
  365. let result = Swimlanes.findOne({boardId: this._id});
  366. if (result === undefined) {
  367. Swimlanes.insert({
  368. title: TAPi18n.__('default'),
  369. boardId: this._id,
  370. });
  371. result = Swimlanes.findOne({boardId: this._id});
  372. }
  373. return result;
  374. },
  375. cardsInInterval(start, end) {
  376. return Cards.find({
  377. boardId: this._id,
  378. $or: [
  379. {
  380. startAt: {
  381. $lte: start,
  382. }, endAt: {
  383. $gte: start,
  384. },
  385. }, {
  386. startAt: {
  387. $lte: end,
  388. }, endAt: {
  389. $gte: end,
  390. },
  391. }, {
  392. startAt: {
  393. $gte: start,
  394. }, endAt: {
  395. $lte: end,
  396. },
  397. },
  398. ],
  399. });
  400. },
  401. });
  402. Boards.mutations({
  403. archive() {
  404. return { $set: { archived: true } };
  405. },
  406. restore() {
  407. return { $set: { archived: false } };
  408. },
  409. rename(title) {
  410. return { $set: { title } };
  411. },
  412. setDescription(description) {
  413. return { $set: { description } };
  414. },
  415. setColor(color) {
  416. return { $set: { color } };
  417. },
  418. setVisibility(visibility) {
  419. return { $set: { permission: visibility } };
  420. },
  421. addLabel(name, color) {
  422. // If label with the same name and color already exists we don't want to
  423. // create another one because they would be indistinguishable in the UI
  424. // (they would still have different `_id` but that is not exposed to the
  425. // user).
  426. if (!this.getLabel(name, color)) {
  427. const _id = Random.id(6);
  428. return { $push: { labels: { _id, name, color } } };
  429. }
  430. return {};
  431. },
  432. editLabel(labelId, name, color) {
  433. if (!this.getLabel(name, color)) {
  434. const labelIndex = this.labelIndex(labelId);
  435. return {
  436. $set: {
  437. [`labels.${labelIndex}.name`]: name,
  438. [`labels.${labelIndex}.color`]: color,
  439. },
  440. };
  441. }
  442. return {};
  443. },
  444. removeLabel(labelId) {
  445. return { $pull: { labels: { _id: labelId } } };
  446. },
  447. changeOwnership(fromId, toId) {
  448. const memberIndex = this.memberIndex(fromId);
  449. return {
  450. $set: {
  451. [`members.${memberIndex}.userId`]: toId,
  452. },
  453. };
  454. },
  455. addMember(memberId) {
  456. const memberIndex = this.memberIndex(memberId);
  457. if (memberIndex >= 0) {
  458. return {
  459. $set: {
  460. [`members.${memberIndex}.isActive`]: true,
  461. },
  462. };
  463. }
  464. return {
  465. $push: {
  466. members: {
  467. userId: memberId,
  468. isAdmin: false,
  469. isActive: true,
  470. isNoComments: false,
  471. isCommentOnly: false,
  472. },
  473. },
  474. };
  475. },
  476. removeMember(memberId) {
  477. const memberIndex = this.memberIndex(memberId);
  478. // we do not allow the only one admin to be removed
  479. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  480. if (!allowRemove) {
  481. return {
  482. $set: {
  483. [`members.${memberIndex}.isActive`]: true,
  484. },
  485. };
  486. }
  487. return {
  488. $set: {
  489. [`members.${memberIndex}.isActive`]: false,
  490. [`members.${memberIndex}.isAdmin`]: false,
  491. },
  492. };
  493. },
  494. setMemberPermission(memberId, isAdmin, isNoComments, isCommentOnly, currentUserId = Meteor.userId()) {
  495. const memberIndex = this.memberIndex(memberId);
  496. // do not allow change permission of self
  497. if (memberId === currentUserId) {
  498. isAdmin = this.members[memberIndex].isAdmin;
  499. }
  500. return {
  501. $set: {
  502. [`members.${memberIndex}.isAdmin`]: isAdmin,
  503. [`members.${memberIndex}.isNoComments`]: isNoComments,
  504. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  505. },
  506. };
  507. },
  508. setAllowsSubtasks(allowsSubtasks) {
  509. return { $set: { allowsSubtasks } };
  510. },
  511. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  512. return { $set: { subtasksDefaultBoardId } };
  513. },
  514. setSubtasksDefaultListId(subtasksDefaultListId) {
  515. return { $set: { subtasksDefaultListId } };
  516. },
  517. setPresentParentTask(presentParentTask) {
  518. return { $set: { presentParentTask } };
  519. },
  520. });
  521. if (Meteor.isServer) {
  522. Boards.allow({
  523. insert: Meteor.userId,
  524. update: allowIsBoardAdmin,
  525. remove: allowIsBoardAdmin,
  526. fetch: ['members'],
  527. });
  528. // The number of users that have starred this board is managed by trusted code
  529. // and the user is not allowed to update it
  530. Boards.deny({
  531. update(userId, board, fieldNames) {
  532. return _.contains(fieldNames, 'stars');
  533. },
  534. fetch: [],
  535. });
  536. // We can't remove a member if it is the last administrator
  537. Boards.deny({
  538. update(userId, doc, fieldNames, modifier) {
  539. if (!_.contains(fieldNames, 'members'))
  540. return false;
  541. // We only care in case of a $pull operation, ie remove a member
  542. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  543. return false;
  544. // If there is more than one admin, it's ok to remove anyone
  545. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  546. if (nbAdmins > 1)
  547. return false;
  548. // If all the previous conditions were verified, we can't remove
  549. // a user if it's an admin
  550. const removedMemberId = modifier.$pull.members.userId;
  551. return Boolean(_.findWhere(doc.members, {
  552. userId: removedMemberId,
  553. isAdmin: true,
  554. }));
  555. },
  556. fetch: ['members'],
  557. });
  558. Meteor.methods({
  559. quitBoard(boardId) {
  560. check(boardId, String);
  561. const board = Boards.findOne(boardId);
  562. if (board) {
  563. const userId = Meteor.userId();
  564. const index = board.memberIndex(userId);
  565. if (index >= 0) {
  566. board.removeMember(userId);
  567. return true;
  568. } else throw new Meteor.Error('error-board-notAMember');
  569. } else throw new Meteor.Error('error-board-doesNotExist');
  570. },
  571. });
  572. }
  573. if (Meteor.isServer) {
  574. // Let MongoDB ensure that a member is not included twice in the same board
  575. Meteor.startup(() => {
  576. Boards._collection._ensureIndex({
  577. _id: 1,
  578. 'members.userId': 1,
  579. }, { unique: true });
  580. Boards._collection._ensureIndex({ 'members.userId': 1 });
  581. });
  582. // Genesis: the first activity of the newly created board
  583. Boards.after.insert((userId, doc) => {
  584. Activities.insert({
  585. userId,
  586. type: 'board',
  587. activityTypeId: doc._id,
  588. activityType: 'createBoard',
  589. boardId: doc._id,
  590. });
  591. });
  592. // If the user remove one label from a board, we cant to remove reference of
  593. // this label in any card of this board.
  594. Boards.after.update((userId, doc, fieldNames, modifier) => {
  595. if (!_.contains(fieldNames, 'labels') ||
  596. !modifier.$pull ||
  597. !modifier.$pull.labels ||
  598. !modifier.$pull.labels._id) {
  599. return;
  600. }
  601. const removedLabelId = modifier.$pull.labels._id;
  602. Cards.update(
  603. { boardId: doc._id },
  604. {
  605. $pull: {
  606. labelIds: removedLabelId,
  607. },
  608. },
  609. { multi: true }
  610. );
  611. });
  612. const foreachRemovedMember = (doc, modifier, callback) => {
  613. Object.keys(modifier).forEach((set) => {
  614. if (modifier[set] !== false) {
  615. return;
  616. }
  617. const parts = set.split('.');
  618. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  619. callback(doc.members[parts[1]].userId);
  620. }
  621. });
  622. };
  623. // Remove a member from all objects of the board before leaving the board
  624. Boards.before.update((userId, doc, fieldNames, modifier) => {
  625. if (!_.contains(fieldNames, 'members')) {
  626. return;
  627. }
  628. if (modifier.$set) {
  629. const boardId = doc._id;
  630. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  631. Cards.update(
  632. { boardId },
  633. {
  634. $pull: {
  635. members: memberId,
  636. watchers: memberId,
  637. },
  638. },
  639. { multi: true }
  640. );
  641. Lists.update(
  642. { boardId },
  643. {
  644. $pull: {
  645. watchers: memberId,
  646. },
  647. },
  648. { multi: true }
  649. );
  650. const board = Boards._transform(doc);
  651. board.setWatcher(memberId, false);
  652. // Remove board from users starred list
  653. if (!board.isPublic()) {
  654. Users.update(
  655. memberId,
  656. {
  657. $pull: {
  658. 'profile.starredBoards': boardId,
  659. },
  660. }
  661. );
  662. }
  663. });
  664. }
  665. });
  666. // Add a new activity if we add or remove a member to the board
  667. Boards.after.update((userId, doc, fieldNames, modifier) => {
  668. if (!_.contains(fieldNames, 'members')) {
  669. return;
  670. }
  671. // Say hello to the new member
  672. if (modifier.$push && modifier.$push.members) {
  673. const memberId = modifier.$push.members.userId;
  674. Activities.insert({
  675. userId,
  676. memberId,
  677. type: 'member',
  678. activityType: 'addBoardMember',
  679. boardId: doc._id,
  680. });
  681. }
  682. // Say goodbye to the former member
  683. if (modifier.$set) {
  684. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  685. Activities.insert({
  686. userId,
  687. memberId,
  688. type: 'member',
  689. activityType: 'removeBoardMember',
  690. boardId: doc._id,
  691. });
  692. });
  693. }
  694. });
  695. }
  696. //BOARDS REST API
  697. if (Meteor.isServer) {
  698. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  699. try {
  700. Authentication.checkLoggedIn(req.userId);
  701. const paramUserId = req.params.userId;
  702. // A normal user should be able to see their own boards,
  703. // admins can access boards of any user
  704. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  705. const data = Boards.find({
  706. archived: false,
  707. 'members.userId': paramUserId,
  708. }, {
  709. sort: ['title'],
  710. }).map(function(board) {
  711. return {
  712. _id: board._id,
  713. title: board.title,
  714. };
  715. });
  716. JsonRoutes.sendResult(res, {code: 200, data});
  717. }
  718. catch (error) {
  719. JsonRoutes.sendResult(res, {
  720. code: 200,
  721. data: error,
  722. });
  723. }
  724. });
  725. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  726. try {
  727. Authentication.checkUserId(req.userId);
  728. JsonRoutes.sendResult(res, {
  729. code: 200,
  730. data: Boards.find({ permission: 'public' }).map(function (doc) {
  731. return {
  732. _id: doc._id,
  733. title: doc.title,
  734. };
  735. }),
  736. });
  737. }
  738. catch (error) {
  739. JsonRoutes.sendResult(res, {
  740. code: 200,
  741. data: error,
  742. });
  743. }
  744. });
  745. JsonRoutes.add('GET', '/api/boards/:boardId', function (req, res) {
  746. try {
  747. const id = req.params.boardId;
  748. Authentication.checkBoardAccess(req.userId, id);
  749. JsonRoutes.sendResult(res, {
  750. code: 200,
  751. data: Boards.findOne({ _id: id }),
  752. });
  753. }
  754. catch (error) {
  755. JsonRoutes.sendResult(res, {
  756. code: 200,
  757. data: error,
  758. });
  759. }
  760. });
  761. JsonRoutes.add('PUT', '/api/boards/:boardId/members', function (req, res) {
  762. Authentication.checkUserId(req.userId);
  763. try {
  764. const boardId = req.params.boardId;
  765. const board = Boards.findOne({ _id: boardId });
  766. const userId = req.body.userId;
  767. const user = Users.findOne({ _id: userId });
  768. if (!board.getMember(userId)) {
  769. user.addInvite(boardId);
  770. board.addMember(userId);
  771. JsonRoutes.sendResult(res, {
  772. code: 200,
  773. data: id,
  774. });
  775. } else {
  776. JsonRoutes.sendResult(res, {
  777. code: 200,
  778. });
  779. }
  780. }
  781. catch (error) {
  782. JsonRoutes.sendResult(res, {
  783. data: error,
  784. });
  785. }
  786. });
  787. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  788. try {
  789. Authentication.checkUserId(req.userId);
  790. const id = Boards.insert({
  791. title: req.body.title,
  792. members: [
  793. {
  794. userId: req.body.owner,
  795. isAdmin: req.body.isAdmin || true,
  796. isActive: req.body.isActive || true,
  797. isNoComments: req.body.isNoComments || false,
  798. isCommentOnly: req.body.isCommentOnly || false,
  799. },
  800. ],
  801. permission: req.body.permission || 'private',
  802. color: req.body.color || 'belize',
  803. });
  804. const swimlaneId = Swimlanes.insert({
  805. title: TAPi18n.__('default'),
  806. boardId: id,
  807. });
  808. JsonRoutes.sendResult(res, {
  809. code: 200,
  810. data: {
  811. _id: id,
  812. defaultSwimlaneId: swimlaneId,
  813. },
  814. });
  815. }
  816. catch (error) {
  817. JsonRoutes.sendResult(res, {
  818. code: 200,
  819. data: error,
  820. });
  821. }
  822. });
  823. JsonRoutes.add('DELETE', '/api/boards/:boardId', function (req, res) {
  824. try {
  825. Authentication.checkUserId(req.userId);
  826. const id = req.params.boardId;
  827. Boards.remove({ _id: id });
  828. JsonRoutes.sendResult(res, {
  829. code: 200,
  830. data:{
  831. _id: id,
  832. },
  833. });
  834. }
  835. catch (error) {
  836. JsonRoutes.sendResult(res, {
  837. code: 200,
  838. data: error,
  839. });
  840. }
  841. });
  842. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function (req, res) {
  843. Authentication.checkUserId(req.userId);
  844. const id = req.params.boardId;
  845. try {
  846. if (req.body.hasOwnProperty('label')) {
  847. const board = Boards.findOne({ _id: id });
  848. const color = req.body.label.color;
  849. const name = req.body.label.name;
  850. const labelId = Random.id(6);
  851. if (!board.getLabel(name, color)) {
  852. Boards.direct.update({ _id: id }, { $push: { labels: { _id: labelId, name, color } } });
  853. JsonRoutes.sendResult(res, {
  854. code: 200,
  855. data: labelId,
  856. });
  857. } else {
  858. JsonRoutes.sendResult(res, {
  859. code: 200,
  860. });
  861. }
  862. }
  863. }
  864. catch (error) {
  865. JsonRoutes.sendResult(res, {
  866. data: error,
  867. });
  868. }
  869. });
  870. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function (req, res) {
  871. try {
  872. const boardId = req.params.boardId;
  873. const memberId = req.params.memberId;
  874. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  875. Authentication.checkBoardAccess(req.userId, boardId);
  876. const board = Boards.findOne({ _id: boardId });
  877. function isTrue(data){
  878. return data.toLowerCase() === 'true';
  879. }
  880. board.setMemberPermission(memberId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), req.userId);
  881. JsonRoutes.sendResult(res, {
  882. code: 200,
  883. data: query,
  884. });
  885. }
  886. catch (error) {
  887. JsonRoutes.sendResult(res, {
  888. code: 200,
  889. data: error,
  890. });
  891. }
  892. });
  893. }