boards.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. Boards = new Mongo.Collection('boards');
  2. /**
  3. * This is a Board.
  4. */
  5. Boards.attachSchema(new SimpleSchema({
  6. title: {
  7. /**
  8. * The title of the board
  9. */
  10. type: String,
  11. },
  12. slug: {
  13. /**
  14. * The title slugified.
  15. */
  16. type: String,
  17. autoValue() { // eslint-disable-line consistent-return
  18. // XXX We need to improve slug management. Only the id should be necessary
  19. // to identify a board in the code.
  20. // XXX If the board title is updated, the slug should also be updated.
  21. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  22. // return an empty string. This is causes bugs in our application so we set
  23. // a default slug in this case.
  24. if (this.isInsert && !this.isSet) {
  25. let slug = 'board';
  26. const title = this.field('title');
  27. if (title.isSet) {
  28. slug = getSlug(title.value) || slug;
  29. }
  30. return slug;
  31. }
  32. },
  33. },
  34. archived: {
  35. /**
  36. * Is the board archived?
  37. */
  38. type: Boolean,
  39. autoValue() { // eslint-disable-line consistent-return
  40. if (this.isInsert && !this.isSet) {
  41. return false;
  42. }
  43. },
  44. },
  45. createdAt: {
  46. /**
  47. * Creation time of the board
  48. */
  49. type: Date,
  50. autoValue() { // eslint-disable-line consistent-return
  51. if (this.isInsert) {
  52. return new Date();
  53. } else {
  54. this.unset();
  55. }
  56. },
  57. },
  58. // XXX Inconsistent field naming
  59. modifiedAt: {
  60. /**
  61. * Last modification time of the board
  62. */
  63. type: Date,
  64. optional: true,
  65. autoValue() { // eslint-disable-line consistent-return
  66. if (this.isUpdate) {
  67. return new Date();
  68. } else {
  69. this.unset();
  70. }
  71. },
  72. },
  73. // De-normalized number of users that have starred this board
  74. stars: {
  75. /**
  76. * How many stars the board has
  77. */
  78. type: Number,
  79. autoValue() { // eslint-disable-line consistent-return
  80. if (this.isInsert) {
  81. return 0;
  82. }
  83. },
  84. },
  85. // De-normalized label system
  86. 'labels': {
  87. /**
  88. * List of labels attached to a board
  89. */
  90. type: [Object],
  91. autoValue() { // eslint-disable-line consistent-return
  92. if (this.isInsert && !this.isSet) {
  93. const colors = Boards.simpleSchema()._schema['labels.$.color'].allowedValues;
  94. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  95. return defaultLabelsColors.map((color) => ({
  96. color,
  97. _id: Random.id(6),
  98. name: '',
  99. }));
  100. }
  101. },
  102. },
  103. 'labels.$._id': {
  104. /**
  105. * Unique id of a label
  106. */
  107. // We don't specify that this field must be unique in the board because that
  108. // will cause performance penalties and is not necessary since this field is
  109. // always set on the server.
  110. // XXX Actually if we create a new label, the `_id` is set on the client
  111. // without being overwritten by the server, could it be a problem?
  112. type: String,
  113. },
  114. 'labels.$.name': {
  115. /**
  116. * Name of a label
  117. */
  118. type: String,
  119. optional: true,
  120. },
  121. 'labels.$.color': {
  122. /**
  123. * color of a label.
  124. *
  125. * Can be amongst `green`, `yellow`, `orange`, `red`, `purple`,
  126. * `blue`, `sky`, `lime`, `pink`, `black`,
  127. * `silver`, `peachpuff`, `crimson`, `plum`, `darkgreen`,
  128. * `slateblue`, `magenta`, `gold`, `navy`, `gray`,
  129. * `saddlebrown`, `paleturquoise`, `mistyrose`, `indigo`
  130. */
  131. type: String,
  132. allowedValues: [
  133. 'green', 'yellow', 'orange', 'red', 'purple',
  134. 'blue', 'sky', 'lime', 'pink', 'black',
  135. 'silver', 'peachpuff', 'crimson', 'plum', 'darkgreen',
  136. 'slateblue', 'magenta', 'gold', 'navy', 'gray',
  137. 'saddlebrown', 'paleturquoise', 'mistyrose', 'indigo',
  138. ],
  139. },
  140. // XXX We might want to maintain more informations under the member sub-
  141. // documents like de-normalized meta-data (the date the member joined the
  142. // board, the number of contributions, etc.).
  143. 'members': {
  144. /**
  145. * List of members of a board
  146. */
  147. type: [Object],
  148. autoValue() { // eslint-disable-line consistent-return
  149. if (this.isInsert && !this.isSet) {
  150. return [{
  151. userId: this.userId,
  152. isAdmin: true,
  153. isActive: true,
  154. isNoComments: false,
  155. isCommentOnly: false,
  156. }];
  157. }
  158. },
  159. },
  160. 'members.$.userId': {
  161. /**
  162. * The uniq ID of the member
  163. */
  164. type: String,
  165. },
  166. 'members.$.isAdmin': {
  167. /**
  168. * Is the member an admin of the board?
  169. */
  170. type: Boolean,
  171. },
  172. 'members.$.isActive': {
  173. /**
  174. * Is the member active?
  175. */
  176. type: Boolean,
  177. },
  178. 'members.$.isNoComments': {
  179. /**
  180. * Is the member not allowed to make comments
  181. */
  182. type: Boolean,
  183. optional: true,
  184. },
  185. 'members.$.isCommentOnly': {
  186. /**
  187. * Is the member only allowed to comment on the board
  188. */
  189. type: Boolean,
  190. optional: true,
  191. },
  192. permission: {
  193. /**
  194. * visibility of the board
  195. */
  196. type: String,
  197. allowedValues: ['public', 'private'],
  198. },
  199. color: {
  200. /**
  201. * The color of the board.
  202. */
  203. type: String,
  204. allowedValues: [
  205. 'belize',
  206. 'nephritis',
  207. 'pomegranate',
  208. 'pumpkin',
  209. 'wisteria',
  210. 'midnight',
  211. ],
  212. autoValue() { // eslint-disable-line consistent-return
  213. if (this.isInsert && !this.isSet) {
  214. return Boards.simpleSchema()._schema.color.allowedValues[0];
  215. }
  216. },
  217. },
  218. description: {
  219. /**
  220. * The description of the board
  221. */
  222. type: String,
  223. optional: true,
  224. },
  225. subtasksDefaultBoardId: {
  226. /**
  227. * The default board ID assigned to subtasks.
  228. */
  229. type: String,
  230. optional: true,
  231. defaultValue: null,
  232. },
  233. subtasksDefaultListId: {
  234. /**
  235. * The default List ID assigned to subtasks.
  236. */
  237. type: String,
  238. optional: true,
  239. defaultValue: null,
  240. },
  241. allowsSubtasks: {
  242. /**
  243. * Does the board allows subtasks?
  244. */
  245. type: Boolean,
  246. defaultValue: true,
  247. },
  248. presentParentTask: {
  249. /**
  250. * Controls how to present the parent task:
  251. *
  252. * - `prefix-with-full-path`: add a prefix with the full path
  253. * - `prefix-with-parent`: add a prefisx with the parent name
  254. * - `subtext-with-full-path`: add a subtext with the full path
  255. * - `subtext-with-parent`: add a subtext with the parent name
  256. * - `no-parent`: does not show the parent at all
  257. */
  258. type: String,
  259. allowedValues: [
  260. 'prefix-with-full-path',
  261. 'prefix-with-parent',
  262. 'subtext-with-full-path',
  263. 'subtext-with-parent',
  264. 'no-parent',
  265. ],
  266. optional: true,
  267. defaultValue: 'no-parent',
  268. },
  269. startAt: {
  270. /**
  271. * Starting date of the board.
  272. */
  273. type: Date,
  274. optional: true,
  275. },
  276. dueAt: {
  277. /**
  278. * Due date of the board.
  279. */
  280. type: Date,
  281. optional: true,
  282. },
  283. endAt: {
  284. /**
  285. * End date of the board.
  286. */
  287. type: Date,
  288. optional: true,
  289. },
  290. spentTime: {
  291. /**
  292. * Time spent in the board.
  293. */
  294. type: Number,
  295. decimal: true,
  296. optional: true,
  297. },
  298. isOvertime: {
  299. /**
  300. * Is the board overtimed?
  301. */
  302. type: Boolean,
  303. defaultValue: false,
  304. optional: true,
  305. },
  306. type: {
  307. /**
  308. * The type of board
  309. */
  310. type: String,
  311. defaultValue: 'board',
  312. },
  313. }));
  314. Boards.helpers({
  315. copy() {
  316. const oldId = this._id;
  317. delete this._id;
  318. const _id = Boards.insert(this);
  319. // Copy all swimlanes in board
  320. Swimlanes.find({
  321. boardId: oldId,
  322. archived: false,
  323. }).forEach((swimlane) => {
  324. swimlane.type = 'swimlane';
  325. swimlane.boardId = _id;
  326. swimlane.copy(oldId);
  327. });
  328. },
  329. /**
  330. * Is supplied user authorized to view this board?
  331. */
  332. isVisibleBy(user) {
  333. if (this.isPublic()) {
  334. // public boards are visible to everyone
  335. return true;
  336. } else {
  337. // otherwise you have to be logged-in and active member
  338. return user && this.isActiveMember(user._id);
  339. }
  340. },
  341. /**
  342. * Is the user one of the active members of the board?
  343. *
  344. * @param userId
  345. * @returns {boolean} the member that matches, or undefined/false
  346. */
  347. isActiveMember(userId) {
  348. if (userId) {
  349. return this.members.find((member) => (member.userId === userId && member.isActive));
  350. } else {
  351. return false;
  352. }
  353. },
  354. isPublic() {
  355. return this.permission === 'public';
  356. },
  357. cards() {
  358. return Cards.find({ boardId: this._id, archived: false }, { sort: { title: 1 } });
  359. },
  360. lists() {
  361. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  362. },
  363. nullSortLists() {
  364. return Lists.find({
  365. boardId: this._id,
  366. archived: false,
  367. sort: { $eq: null },
  368. });
  369. },
  370. swimlanes() {
  371. return Swimlanes.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  372. },
  373. nextSwimlane(swimlane) {
  374. return Swimlanes.findOne({
  375. boardId: this._id,
  376. archived: false,
  377. sort: { $gte: swimlane.sort },
  378. _id: { $ne: swimlane._id },
  379. }, {
  380. sort: { sort: 1 },
  381. });
  382. },
  383. nullSortSwimlanes() {
  384. return Swimlanes.find({
  385. boardId: this._id,
  386. archived: false,
  387. sort: { $eq: null },
  388. });
  389. },
  390. hasOvertimeCards(){
  391. const card = Cards.findOne({isOvertime: true, boardId: this._id, archived: false} );
  392. return card !== undefined;
  393. },
  394. hasSpentTimeCards(){
  395. const card = Cards.findOne({spentTime: { $gt: 0 }, boardId: this._id, archived: false} );
  396. return card !== undefined;
  397. },
  398. activities() {
  399. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  400. },
  401. activeMembers() {
  402. return _.where(this.members, { isActive: true });
  403. },
  404. activeAdmins() {
  405. return _.where(this.members, { isActive: true, isAdmin: true });
  406. },
  407. memberUsers() {
  408. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  409. },
  410. getLabel(name, color) {
  411. return _.findWhere(this.labels, { name, color });
  412. },
  413. getLabelById(labelId){
  414. return _.findWhere(this.labels, { _id: labelId });
  415. },
  416. labelIndex(labelId) {
  417. return _.pluck(this.labels, '_id').indexOf(labelId);
  418. },
  419. memberIndex(memberId) {
  420. return _.pluck(this.members, 'userId').indexOf(memberId);
  421. },
  422. hasMember(memberId) {
  423. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  424. },
  425. hasAdmin(memberId) {
  426. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: true });
  427. },
  428. hasNoComments(memberId) {
  429. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isNoComments: true });
  430. },
  431. hasCommentOnly(memberId) {
  432. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isCommentOnly: true });
  433. },
  434. absoluteUrl() {
  435. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  436. },
  437. colorClass() {
  438. return `board-color-${this.color}`;
  439. },
  440. customFields() {
  441. return CustomFields.find({ boardId: this._id }, { sort: { name: 1 } });
  442. },
  443. // XXX currently mutations return no value so we have an issue when using addLabel in import
  444. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  445. pushLabel(name, color) {
  446. const _id = Random.id(6);
  447. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  448. return _id;
  449. },
  450. searchBoards(term) {
  451. check(term, Match.OneOf(String, null, undefined));
  452. const query = { boardId: this._id };
  453. query.type = 'cardType-linkedBoard';
  454. query.archived = false;
  455. const projection = { limit: 10, sort: { createdAt: -1 } };
  456. if (term) {
  457. const regex = new RegExp(term, 'i');
  458. query.$or = [
  459. { title: regex },
  460. { description: regex },
  461. ];
  462. }
  463. return Cards.find(query, projection);
  464. },
  465. searchSwimlanes(term) {
  466. check(term, Match.OneOf(String, null, undefined));
  467. const query = { boardId: this._id };
  468. if (this.isTemplatesBoard()) {
  469. query.type = 'template-swimlane';
  470. query.archived = false;
  471. } else {
  472. query.type = {$nin: ['template-swimlane']};
  473. }
  474. const projection = { limit: 10, sort: { createdAt: -1 } };
  475. if (term) {
  476. const regex = new RegExp(term, 'i');
  477. query.$or = [
  478. { title: regex },
  479. { description: regex },
  480. ];
  481. }
  482. return Swimlanes.find(query, projection);
  483. },
  484. searchLists(term) {
  485. check(term, Match.OneOf(String, null, undefined));
  486. const query = { boardId: this._id };
  487. if (this.isTemplatesBoard()) {
  488. query.type = 'template-list';
  489. query.archived = false;
  490. } else {
  491. query.type = {$nin: ['template-list']};
  492. }
  493. const projection = { limit: 10, sort: { createdAt: -1 } };
  494. if (term) {
  495. const regex = new RegExp(term, 'i');
  496. query.$or = [
  497. { title: regex },
  498. { description: regex },
  499. ];
  500. }
  501. return Lists.find(query, projection);
  502. },
  503. searchCards(term, excludeLinked) {
  504. check(term, Match.OneOf(String, null, undefined));
  505. const query = { boardId: this._id };
  506. if (excludeLinked) {
  507. query.linkedId = null;
  508. }
  509. if (this.isTemplatesBoard()) {
  510. query.type = 'template-card';
  511. query.archived = false;
  512. } else {
  513. query.type = {$nin: ['template-card']};
  514. }
  515. const projection = { limit: 10, sort: { createdAt: -1 } };
  516. if (term) {
  517. const regex = new RegExp(term, 'i');
  518. query.$or = [
  519. { title: regex },
  520. { description: regex },
  521. ];
  522. }
  523. return Cards.find(query, projection);
  524. },
  525. // A board alwasy has another board where it deposits subtasks of thasks
  526. // that belong to itself.
  527. getDefaultSubtasksBoardId() {
  528. if ((this.subtasksDefaultBoardId === null) || (this.subtasksDefaultBoardId === undefined)) {
  529. this.subtasksDefaultBoardId = Boards.insert({
  530. title: `^${this.title}^`,
  531. permission: this.permission,
  532. members: this.members,
  533. color: this.color,
  534. description: TAPi18n.__('default-subtasks-board', {board: this.title}),
  535. });
  536. Swimlanes.insert({
  537. title: TAPi18n.__('default'),
  538. boardId: this.subtasksDefaultBoardId,
  539. });
  540. Boards.update(this._id, {$set: {
  541. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  542. }});
  543. }
  544. return this.subtasksDefaultBoardId;
  545. },
  546. getDefaultSubtasksBoard() {
  547. return Boards.findOne(this.getDefaultSubtasksBoardId());
  548. },
  549. getDefaultSubtasksListId() {
  550. if ((this.subtasksDefaultListId === null) || (this.subtasksDefaultListId === undefined)) {
  551. this.subtasksDefaultListId = Lists.insert({
  552. title: TAPi18n.__('queue'),
  553. boardId: this._id,
  554. });
  555. Boards.update(this._id, {$set: {
  556. subtasksDefaultListId: this.subtasksDefaultListId,
  557. }});
  558. }
  559. return this.subtasksDefaultListId;
  560. },
  561. getDefaultSubtasksList() {
  562. return Lists.findOne(this.getDefaultSubtasksListId());
  563. },
  564. getDefaultSwimline() {
  565. let result = Swimlanes.findOne({boardId: this._id});
  566. if (result === undefined) {
  567. Swimlanes.insert({
  568. title: TAPi18n.__('default'),
  569. boardId: this._id,
  570. });
  571. result = Swimlanes.findOne({boardId: this._id});
  572. }
  573. return result;
  574. },
  575. cardsInInterval(start, end) {
  576. return Cards.find({
  577. boardId: this._id,
  578. $or: [
  579. {
  580. startAt: {
  581. $lte: start,
  582. }, endAt: {
  583. $gte: start,
  584. },
  585. }, {
  586. startAt: {
  587. $lte: end,
  588. }, endAt: {
  589. $gte: end,
  590. },
  591. }, {
  592. startAt: {
  593. $gte: start,
  594. }, endAt: {
  595. $lte: end,
  596. },
  597. },
  598. ],
  599. });
  600. },
  601. isTemplateBoard() {
  602. return this.type === 'template-board';
  603. },
  604. isTemplatesBoard() {
  605. return this.type === 'template-container';
  606. },
  607. });
  608. Boards.mutations({
  609. archive() {
  610. return { $set: { archived: true } };
  611. },
  612. restore() {
  613. return { $set: { archived: false } };
  614. },
  615. rename(title) {
  616. return { $set: { title } };
  617. },
  618. setDescription(description) {
  619. return { $set: { description } };
  620. },
  621. setColor(color) {
  622. return { $set: { color } };
  623. },
  624. setVisibility(visibility) {
  625. return { $set: { permission: visibility } };
  626. },
  627. addLabel(name, color) {
  628. // If label with the same name and color already exists we don't want to
  629. // create another one because they would be indistinguishable in the UI
  630. // (they would still have different `_id` but that is not exposed to the
  631. // user).
  632. if (!this.getLabel(name, color)) {
  633. const _id = Random.id(6);
  634. return { $push: { labels: { _id, name, color } } };
  635. }
  636. return {};
  637. },
  638. editLabel(labelId, name, color) {
  639. if (!this.getLabel(name, color)) {
  640. const labelIndex = this.labelIndex(labelId);
  641. return {
  642. $set: {
  643. [`labels.${labelIndex}.name`]: name,
  644. [`labels.${labelIndex}.color`]: color,
  645. },
  646. };
  647. }
  648. return {};
  649. },
  650. removeLabel(labelId) {
  651. return { $pull: { labels: { _id: labelId } } };
  652. },
  653. changeOwnership(fromId, toId) {
  654. const memberIndex = this.memberIndex(fromId);
  655. return {
  656. $set: {
  657. [`members.${memberIndex}.userId`]: toId,
  658. },
  659. };
  660. },
  661. addMember(memberId) {
  662. const memberIndex = this.memberIndex(memberId);
  663. if (memberIndex >= 0) {
  664. return {
  665. $set: {
  666. [`members.${memberIndex}.isActive`]: true,
  667. },
  668. };
  669. }
  670. return {
  671. $push: {
  672. members: {
  673. userId: memberId,
  674. isAdmin: false,
  675. isActive: true,
  676. isNoComments: false,
  677. isCommentOnly: false,
  678. },
  679. },
  680. };
  681. },
  682. removeMember(memberId) {
  683. const memberIndex = this.memberIndex(memberId);
  684. // we do not allow the only one admin to be removed
  685. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  686. if (!allowRemove) {
  687. return {
  688. $set: {
  689. [`members.${memberIndex}.isActive`]: true,
  690. },
  691. };
  692. }
  693. return {
  694. $set: {
  695. [`members.${memberIndex}.isActive`]: false,
  696. [`members.${memberIndex}.isAdmin`]: false,
  697. },
  698. };
  699. },
  700. setMemberPermission(memberId, isAdmin, isNoComments, isCommentOnly, currentUserId = Meteor.userId()) {
  701. const memberIndex = this.memberIndex(memberId);
  702. // do not allow change permission of self
  703. if (memberId === currentUserId) {
  704. isAdmin = this.members[memberIndex].isAdmin;
  705. }
  706. return {
  707. $set: {
  708. [`members.${memberIndex}.isAdmin`]: isAdmin,
  709. [`members.${memberIndex}.isNoComments`]: isNoComments,
  710. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  711. },
  712. };
  713. },
  714. setAllowsSubtasks(allowsSubtasks) {
  715. return { $set: { allowsSubtasks } };
  716. },
  717. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  718. return { $set: { subtasksDefaultBoardId } };
  719. },
  720. setSubtasksDefaultListId(subtasksDefaultListId) {
  721. return { $set: { subtasksDefaultListId } };
  722. },
  723. setPresentParentTask(presentParentTask) {
  724. return { $set: { presentParentTask } };
  725. },
  726. });
  727. if (Meteor.isServer) {
  728. Boards.allow({
  729. insert: Meteor.userId,
  730. update: allowIsBoardAdmin,
  731. remove: allowIsBoardAdmin,
  732. fetch: ['members'],
  733. });
  734. // The number of users that have starred this board is managed by trusted code
  735. // and the user is not allowed to update it
  736. Boards.deny({
  737. update(userId, board, fieldNames) {
  738. return _.contains(fieldNames, 'stars');
  739. },
  740. fetch: [],
  741. });
  742. // We can't remove a member if it is the last administrator
  743. Boards.deny({
  744. update(userId, doc, fieldNames, modifier) {
  745. if (!_.contains(fieldNames, 'members'))
  746. return false;
  747. // We only care in case of a $pull operation, ie remove a member
  748. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  749. return false;
  750. // If there is more than one admin, it's ok to remove anyone
  751. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  752. if (nbAdmins > 1)
  753. return false;
  754. // If all the previous conditions were verified, we can't remove
  755. // a user if it's an admin
  756. const removedMemberId = modifier.$pull.members.userId;
  757. return Boolean(_.findWhere(doc.members, {
  758. userId: removedMemberId,
  759. isAdmin: true,
  760. }));
  761. },
  762. fetch: ['members'],
  763. });
  764. Meteor.methods({
  765. quitBoard(boardId) {
  766. check(boardId, String);
  767. const board = Boards.findOne(boardId);
  768. if (board) {
  769. const userId = Meteor.userId();
  770. const index = board.memberIndex(userId);
  771. if (index >= 0) {
  772. board.removeMember(userId);
  773. return true;
  774. } else throw new Meteor.Error('error-board-notAMember');
  775. } else throw new Meteor.Error('error-board-doesNotExist');
  776. },
  777. });
  778. }
  779. if (Meteor.isServer) {
  780. // Let MongoDB ensure that a member is not included twice in the same board
  781. Meteor.startup(() => {
  782. Boards._collection._ensureIndex({
  783. _id: 1,
  784. 'members.userId': 1,
  785. }, { unique: true });
  786. Boards._collection._ensureIndex({ 'members.userId': 1 });
  787. });
  788. // Genesis: the first activity of the newly created board
  789. Boards.after.insert((userId, doc) => {
  790. Activities.insert({
  791. userId,
  792. type: 'board',
  793. activityTypeId: doc._id,
  794. activityType: 'createBoard',
  795. boardId: doc._id,
  796. });
  797. });
  798. // If the user remove one label from a board, we cant to remove reference of
  799. // this label in any card of this board.
  800. Boards.after.update((userId, doc, fieldNames, modifier) => {
  801. if (!_.contains(fieldNames, 'labels') ||
  802. !modifier.$pull ||
  803. !modifier.$pull.labels ||
  804. !modifier.$pull.labels._id) {
  805. return;
  806. }
  807. const removedLabelId = modifier.$pull.labels._id;
  808. Cards.update(
  809. { boardId: doc._id },
  810. {
  811. $pull: {
  812. labelIds: removedLabelId,
  813. },
  814. },
  815. { multi: true }
  816. );
  817. });
  818. const foreachRemovedMember = (doc, modifier, callback) => {
  819. Object.keys(modifier).forEach((set) => {
  820. if (modifier[set] !== false) {
  821. return;
  822. }
  823. const parts = set.split('.');
  824. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  825. callback(doc.members[parts[1]].userId);
  826. }
  827. });
  828. };
  829. // Remove a member from all objects of the board before leaving the board
  830. Boards.before.update((userId, doc, fieldNames, modifier) => {
  831. if (!_.contains(fieldNames, 'members')) {
  832. return;
  833. }
  834. if (modifier.$set) {
  835. const boardId = doc._id;
  836. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  837. Cards.update(
  838. { boardId },
  839. {
  840. $pull: {
  841. members: memberId,
  842. watchers: memberId,
  843. },
  844. },
  845. { multi: true }
  846. );
  847. Lists.update(
  848. { boardId },
  849. {
  850. $pull: {
  851. watchers: memberId,
  852. },
  853. },
  854. { multi: true }
  855. );
  856. const board = Boards._transform(doc);
  857. board.setWatcher(memberId, false);
  858. // Remove board from users starred list
  859. if (!board.isPublic()) {
  860. Users.update(
  861. memberId,
  862. {
  863. $pull: {
  864. 'profile.starredBoards': boardId,
  865. },
  866. }
  867. );
  868. }
  869. });
  870. }
  871. });
  872. // Add a new activity if we add or remove a member to the board
  873. Boards.after.update((userId, doc, fieldNames, modifier) => {
  874. if (!_.contains(fieldNames, 'members')) {
  875. return;
  876. }
  877. // Say hello to the new member
  878. if (modifier.$push && modifier.$push.members) {
  879. const memberId = modifier.$push.members.userId;
  880. Activities.insert({
  881. userId,
  882. memberId,
  883. type: 'member',
  884. activityType: 'addBoardMember',
  885. boardId: doc._id,
  886. });
  887. }
  888. // Say goodbye to the former member
  889. if (modifier.$set) {
  890. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  891. Activities.insert({
  892. userId,
  893. memberId,
  894. type: 'member',
  895. activityType: 'removeBoardMember',
  896. boardId: doc._id,
  897. });
  898. });
  899. }
  900. });
  901. }
  902. //BOARDS REST API
  903. if (Meteor.isServer) {
  904. /**
  905. * @operation get_boards_from_user
  906. * @summary Get all boards attached to a user
  907. *
  908. * @param {string} userId the ID of the user to retrieve the data
  909. * @return_type [{_id: string,
  910. title: string}]
  911. */
  912. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  913. try {
  914. Authentication.checkLoggedIn(req.userId);
  915. const paramUserId = req.params.userId;
  916. // A normal user should be able to see their own boards,
  917. // admins can access boards of any user
  918. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  919. const data = Boards.find({
  920. archived: false,
  921. 'members.userId': paramUserId,
  922. }, {
  923. sort: ['title'],
  924. }).map(function(board) {
  925. return {
  926. _id: board._id,
  927. title: board.title,
  928. };
  929. });
  930. JsonRoutes.sendResult(res, {code: 200, data});
  931. }
  932. catch (error) {
  933. JsonRoutes.sendResult(res, {
  934. code: 200,
  935. data: error,
  936. });
  937. }
  938. });
  939. /**
  940. * @operation get_public_boards
  941. * @summary Get all public boards
  942. *
  943. * @return_type [{_id: string,
  944. title: string}]
  945. */
  946. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  947. try {
  948. Authentication.checkUserId(req.userId);
  949. JsonRoutes.sendResult(res, {
  950. code: 200,
  951. data: Boards.find({ permission: 'public' }).map(function (doc) {
  952. return {
  953. _id: doc._id,
  954. title: doc.title,
  955. };
  956. }),
  957. });
  958. }
  959. catch (error) {
  960. JsonRoutes.sendResult(res, {
  961. code: 200,
  962. data: error,
  963. });
  964. }
  965. });
  966. /**
  967. * @operation get_board
  968. * @summary Get the board with that particular ID
  969. *
  970. * @param {string} boardId the ID of the board to retrieve the data
  971. * @return_type Boards
  972. */
  973. JsonRoutes.add('GET', '/api/boards/:boardId', function (req, res) {
  974. try {
  975. const id = req.params.boardId;
  976. Authentication.checkBoardAccess(req.userId, id);
  977. JsonRoutes.sendResult(res, {
  978. code: 200,
  979. data: Boards.findOne({ _id: id }),
  980. });
  981. }
  982. catch (error) {
  983. JsonRoutes.sendResult(res, {
  984. code: 200,
  985. data: error,
  986. });
  987. }
  988. });
  989. /**
  990. * @operation new_board
  991. * @summary Create a board
  992. *
  993. * @description This allows to create a board.
  994. *
  995. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  996. * `pumpkin`, `wisteria`, `midnight`:
  997. *
  998. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  999. *
  1000. * @param {string} title the new title of the board
  1001. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1002. * (Not username or email)
  1003. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1004. * @param {boolean} [isActive] is the board active (default true)
  1005. * @param {boolean} [isNoComments] disable comments (default false)
  1006. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1007. * @param {string} [permission] "private" board <== Set to "public" if you
  1008. * want public Wekan board
  1009. * @param {string} [color] the color of the board
  1010. *
  1011. * @return_type {_id: string,
  1012. defaultSwimlaneId: string}
  1013. */
  1014. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  1015. try {
  1016. Authentication.checkUserId(req.userId);
  1017. const id = Boards.insert({
  1018. title: req.body.title,
  1019. members: [
  1020. {
  1021. userId: req.body.owner,
  1022. isAdmin: req.body.isAdmin || true,
  1023. isActive: req.body.isActive || true,
  1024. isNoComments: req.body.isNoComments || false,
  1025. isCommentOnly: req.body.isCommentOnly || false,
  1026. },
  1027. ],
  1028. permission: req.body.permission || 'private',
  1029. color: req.body.color || 'belize',
  1030. });
  1031. const swimlaneId = Swimlanes.insert({
  1032. title: TAPi18n.__('default'),
  1033. boardId: id,
  1034. });
  1035. JsonRoutes.sendResult(res, {
  1036. code: 200,
  1037. data: {
  1038. _id: id,
  1039. defaultSwimlaneId: swimlaneId,
  1040. },
  1041. });
  1042. }
  1043. catch (error) {
  1044. JsonRoutes.sendResult(res, {
  1045. code: 200,
  1046. data: error,
  1047. });
  1048. }
  1049. });
  1050. /**
  1051. * @operation delete_board
  1052. * @summary Delete a board
  1053. *
  1054. * @param {string} boardId the ID of the board
  1055. */
  1056. JsonRoutes.add('DELETE', '/api/boards/:boardId', function (req, res) {
  1057. try {
  1058. Authentication.checkUserId(req.userId);
  1059. const id = req.params.boardId;
  1060. Boards.remove({ _id: id });
  1061. JsonRoutes.sendResult(res, {
  1062. code: 200,
  1063. data:{
  1064. _id: id,
  1065. },
  1066. });
  1067. }
  1068. catch (error) {
  1069. JsonRoutes.sendResult(res, {
  1070. code: 200,
  1071. data: error,
  1072. });
  1073. }
  1074. });
  1075. /**
  1076. * @operation add_board_label
  1077. * @summary Add a label to a board
  1078. *
  1079. * @description If the board doesn't have the name/color label, this function
  1080. * adds the label to the board.
  1081. *
  1082. * @param {string} boardId the board
  1083. * @param {string} color the color of the new label
  1084. * @param {string} name the name of the new label
  1085. *
  1086. * @return_type string
  1087. */
  1088. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function (req, res) {
  1089. Authentication.checkUserId(req.userId);
  1090. const id = req.params.boardId;
  1091. try {
  1092. if (req.body.hasOwnProperty('label')) {
  1093. const board = Boards.findOne({ _id: id });
  1094. const color = req.body.label.color;
  1095. const name = req.body.label.name;
  1096. const labelId = Random.id(6);
  1097. if (!board.getLabel(name, color)) {
  1098. Boards.direct.update({ _id: id }, { $push: { labels: { _id: labelId, name, color } } });
  1099. JsonRoutes.sendResult(res, {
  1100. code: 200,
  1101. data: labelId,
  1102. });
  1103. } else {
  1104. JsonRoutes.sendResult(res, {
  1105. code: 200,
  1106. });
  1107. }
  1108. }
  1109. }
  1110. catch (error) {
  1111. JsonRoutes.sendResult(res, {
  1112. data: error,
  1113. });
  1114. }
  1115. });
  1116. /**
  1117. * @operation set_board_member_permission
  1118. * @tag Users
  1119. * @summary Change the permission of a member of a board
  1120. *
  1121. * @param {string} boardId the ID of the board that we are changing
  1122. * @param {string} memberId the ID of the user to change permissions
  1123. * @param {boolean} isAdmin admin capability
  1124. * @param {boolean} isNoComments NoComments capability
  1125. * @param {boolean} isCommentOnly CommentsOnly capability
  1126. */
  1127. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function (req, res) {
  1128. try {
  1129. const boardId = req.params.boardId;
  1130. const memberId = req.params.memberId;
  1131. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  1132. Authentication.checkBoardAccess(req.userId, boardId);
  1133. const board = Boards.findOne({ _id: boardId });
  1134. function isTrue(data){
  1135. try {
  1136. return data.toLowerCase() === 'true';
  1137. }
  1138. catch (error) {
  1139. return data;
  1140. }
  1141. }
  1142. const query = board.setMemberPermission(memberId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), req.userId);
  1143. JsonRoutes.sendResult(res, {
  1144. code: 200,
  1145. data: query,
  1146. });
  1147. }
  1148. catch (error) {
  1149. JsonRoutes.sendResult(res, {
  1150. code: 200,
  1151. data: error,
  1152. });
  1153. }
  1154. });
  1155. }