boards.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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.copy(_id);
  326. });
  327. },
  328. /**
  329. * Is supplied user authorized to view this board?
  330. */
  331. isVisibleBy(user) {
  332. if (this.isPublic()) {
  333. // public boards are visible to everyone
  334. return true;
  335. } else {
  336. // otherwise you have to be logged-in and active member
  337. return user && this.isActiveMember(user._id);
  338. }
  339. },
  340. /**
  341. * Is the user one of the active members of the board?
  342. *
  343. * @param userId
  344. * @returns {boolean} the member that matches, or undefined/false
  345. */
  346. isActiveMember(userId) {
  347. if (userId) {
  348. return this.members.find((member) => (member.userId === userId && member.isActive));
  349. } else {
  350. return false;
  351. }
  352. },
  353. isPublic() {
  354. return this.permission === 'public';
  355. },
  356. cards() {
  357. return Cards.find({ boardId: this._id, archived: false }, { sort: { title: 1 } });
  358. },
  359. lists() {
  360. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  361. },
  362. nullSortLists() {
  363. return Lists.find({
  364. boardId: this._id,
  365. archived: false,
  366. sort: { $eq: null },
  367. });
  368. },
  369. swimlanes() {
  370. return Swimlanes.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  371. },
  372. nextSwimlane(swimlane) {
  373. return Swimlanes.findOne({
  374. boardId: this._id,
  375. archived: false,
  376. sort: { $gte: swimlane.sort },
  377. _id: { $ne: swimlane._id },
  378. }, {
  379. sort: { sort: 1 },
  380. });
  381. },
  382. nullSortSwimlanes() {
  383. return Swimlanes.find({
  384. boardId: this._id,
  385. archived: false,
  386. sort: { $eq: null },
  387. });
  388. },
  389. hasOvertimeCards(){
  390. const card = Cards.findOne({isOvertime: true, boardId: this._id, archived: false} );
  391. return card !== undefined;
  392. },
  393. hasSpentTimeCards(){
  394. const card = Cards.findOne({spentTime: { $gt: 0 }, boardId: this._id, archived: false} );
  395. return card !== undefined;
  396. },
  397. activities() {
  398. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  399. },
  400. activeMembers() {
  401. return _.where(this.members, { isActive: true });
  402. },
  403. activeAdmins() {
  404. return _.where(this.members, { isActive: true, isAdmin: true });
  405. },
  406. memberUsers() {
  407. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  408. },
  409. getLabel(name, color) {
  410. return _.findWhere(this.labels, { name, color });
  411. },
  412. getLabelById(labelId){
  413. return _.findWhere(this.labels, { _id: labelId });
  414. },
  415. labelIndex(labelId) {
  416. return _.pluck(this.labels, '_id').indexOf(labelId);
  417. },
  418. memberIndex(memberId) {
  419. return _.pluck(this.members, 'userId').indexOf(memberId);
  420. },
  421. hasMember(memberId) {
  422. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  423. },
  424. hasAdmin(memberId) {
  425. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: true });
  426. },
  427. hasNoComments(memberId) {
  428. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isNoComments: true });
  429. },
  430. hasCommentOnly(memberId) {
  431. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isCommentOnly: true });
  432. },
  433. absoluteUrl() {
  434. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  435. },
  436. colorClass() {
  437. return `board-color-${this.color}`;
  438. },
  439. customFields() {
  440. return CustomFields.find({ boardIds: {$in: [this._id]} }, { sort: { name: 1 } });
  441. },
  442. // XXX currently mutations return no value so we have an issue when using addLabel in import
  443. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  444. pushLabel(name, color) {
  445. const _id = Random.id(6);
  446. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  447. return _id;
  448. },
  449. searchBoards(term) {
  450. check(term, Match.OneOf(String, null, undefined));
  451. const query = { boardId: this._id };
  452. query.type = 'cardType-linkedBoard';
  453. query.archived = false;
  454. const projection = { limit: 10, sort: { createdAt: -1 } };
  455. if (term) {
  456. const regex = new RegExp(term, 'i');
  457. query.$or = [
  458. { title: regex },
  459. { description: regex },
  460. ];
  461. }
  462. return Cards.find(query, projection);
  463. },
  464. searchSwimlanes(term) {
  465. check(term, Match.OneOf(String, null, undefined));
  466. const query = { boardId: this._id };
  467. if (this.isTemplatesBoard()) {
  468. query.type = 'template-swimlane';
  469. query.archived = false;
  470. } else {
  471. query.type = {$nin: ['template-swimlane']};
  472. }
  473. const projection = { limit: 10, sort: { createdAt: -1 } };
  474. if (term) {
  475. const regex = new RegExp(term, 'i');
  476. query.$or = [
  477. { title: regex },
  478. { description: regex },
  479. ];
  480. }
  481. return Swimlanes.find(query, projection);
  482. },
  483. searchLists(term) {
  484. check(term, Match.OneOf(String, null, undefined));
  485. const query = { boardId: this._id };
  486. if (this.isTemplatesBoard()) {
  487. query.type = 'template-list';
  488. query.archived = false;
  489. } else {
  490. query.type = {$nin: ['template-list']};
  491. }
  492. const projection = { limit: 10, sort: { createdAt: -1 } };
  493. if (term) {
  494. const regex = new RegExp(term, 'i');
  495. query.$or = [
  496. { title: regex },
  497. { description: regex },
  498. ];
  499. }
  500. return Lists.find(query, projection);
  501. },
  502. searchCards(term, excludeLinked) {
  503. check(term, Match.OneOf(String, null, undefined));
  504. const query = { boardId: this._id };
  505. if (excludeLinked) {
  506. query.linkedId = null;
  507. }
  508. if (this.isTemplatesBoard()) {
  509. query.type = 'template-card';
  510. query.archived = false;
  511. } else {
  512. query.type = {$nin: ['template-card']};
  513. }
  514. const projection = { limit: 10, sort: { createdAt: -1 } };
  515. if (term) {
  516. const regex = new RegExp(term, 'i');
  517. query.$or = [
  518. { title: regex },
  519. { description: regex },
  520. ];
  521. }
  522. return Cards.find(query, projection);
  523. },
  524. // A board alwasy has another board where it deposits subtasks of thasks
  525. // that belong to itself.
  526. getDefaultSubtasksBoardId() {
  527. if ((this.subtasksDefaultBoardId === null) || (this.subtasksDefaultBoardId === undefined)) {
  528. this.subtasksDefaultBoardId = Boards.insert({
  529. title: `^${this.title}^`,
  530. permission: this.permission,
  531. members: this.members,
  532. color: this.color,
  533. description: TAPi18n.__('default-subtasks-board', {board: this.title}),
  534. });
  535. Swimlanes.insert({
  536. title: TAPi18n.__('default'),
  537. boardId: this.subtasksDefaultBoardId,
  538. });
  539. Boards.update(this._id, {$set: {
  540. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  541. }});
  542. }
  543. return this.subtasksDefaultBoardId;
  544. },
  545. getDefaultSubtasksBoard() {
  546. return Boards.findOne(this.getDefaultSubtasksBoardId());
  547. },
  548. getDefaultSubtasksListId() {
  549. if ((this.subtasksDefaultListId === null) || (this.subtasksDefaultListId === undefined)) {
  550. this.subtasksDefaultListId = Lists.insert({
  551. title: TAPi18n.__('queue'),
  552. boardId: this._id,
  553. });
  554. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  555. }
  556. return this.subtasksDefaultListId;
  557. },
  558. getDefaultSubtasksList() {
  559. return Lists.findOne(this.getDefaultSubtasksListId());
  560. },
  561. getDefaultSwimline() {
  562. let result = Swimlanes.findOne({boardId: this._id});
  563. if (result === undefined) {
  564. Swimlanes.insert({
  565. title: TAPi18n.__('default'),
  566. boardId: this._id,
  567. });
  568. result = Swimlanes.findOne({boardId: this._id});
  569. }
  570. return result;
  571. },
  572. cardsInInterval(start, end) {
  573. return Cards.find({
  574. boardId: this._id,
  575. $or: [
  576. {
  577. startAt: {
  578. $lte: start,
  579. }, endAt: {
  580. $gte: start,
  581. },
  582. }, {
  583. startAt: {
  584. $lte: end,
  585. }, endAt: {
  586. $gte: end,
  587. },
  588. }, {
  589. startAt: {
  590. $gte: start,
  591. }, endAt: {
  592. $lte: end,
  593. },
  594. },
  595. ],
  596. });
  597. },
  598. isTemplateBoard() {
  599. return this.type === 'template-board';
  600. },
  601. isTemplatesBoard() {
  602. return this.type === 'template-container';
  603. },
  604. });
  605. Boards.mutations({
  606. archive() {
  607. return { $set: { archived: true } };
  608. },
  609. restore() {
  610. return { $set: { archived: false } };
  611. },
  612. rename(title) {
  613. return { $set: { title } };
  614. },
  615. setDescription(description) {
  616. return { $set: { description } };
  617. },
  618. setColor(color) {
  619. return { $set: { color } };
  620. },
  621. setVisibility(visibility) {
  622. return { $set: { permission: visibility } };
  623. },
  624. addLabel(name, color) {
  625. // If label with the same name and color already exists we don't want to
  626. // create another one because they would be indistinguishable in the UI
  627. // (they would still have different `_id` but that is not exposed to the
  628. // user).
  629. if (!this.getLabel(name, color)) {
  630. const _id = Random.id(6);
  631. return { $push: { labels: { _id, name, color } } };
  632. }
  633. return {};
  634. },
  635. editLabel(labelId, name, color) {
  636. if (!this.getLabel(name, color)) {
  637. const labelIndex = this.labelIndex(labelId);
  638. return {
  639. $set: {
  640. [`labels.${labelIndex}.name`]: name,
  641. [`labels.${labelIndex}.color`]: color,
  642. },
  643. };
  644. }
  645. return {};
  646. },
  647. removeLabel(labelId) {
  648. return { $pull: { labels: { _id: labelId } } };
  649. },
  650. changeOwnership(fromId, toId) {
  651. const memberIndex = this.memberIndex(fromId);
  652. return {
  653. $set: {
  654. [`members.${memberIndex}.userId`]: toId,
  655. },
  656. };
  657. },
  658. addMember(memberId) {
  659. const memberIndex = this.memberIndex(memberId);
  660. if (memberIndex >= 0) {
  661. return {
  662. $set: {
  663. [`members.${memberIndex}.isActive`]: true,
  664. },
  665. };
  666. }
  667. return {
  668. $push: {
  669. members: {
  670. userId: memberId,
  671. isAdmin: false,
  672. isActive: true,
  673. isNoComments: false,
  674. isCommentOnly: false,
  675. },
  676. },
  677. };
  678. },
  679. removeMember(memberId) {
  680. const memberIndex = this.memberIndex(memberId);
  681. // we do not allow the only one admin to be removed
  682. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  683. if (!allowRemove) {
  684. return {
  685. $set: {
  686. [`members.${memberIndex}.isActive`]: true,
  687. },
  688. };
  689. }
  690. return {
  691. $set: {
  692. [`members.${memberIndex}.isActive`]: false,
  693. [`members.${memberIndex}.isAdmin`]: false,
  694. },
  695. };
  696. },
  697. setMemberPermission(memberId, isAdmin, isNoComments, isCommentOnly, currentUserId = Meteor.userId()) {
  698. const memberIndex = this.memberIndex(memberId);
  699. // do not allow change permission of self
  700. if (memberId === currentUserId) {
  701. isAdmin = this.members[memberIndex].isAdmin;
  702. }
  703. return {
  704. $set: {
  705. [`members.${memberIndex}.isAdmin`]: isAdmin,
  706. [`members.${memberIndex}.isNoComments`]: isNoComments,
  707. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  708. },
  709. };
  710. },
  711. setAllowsSubtasks(allowsSubtasks) {
  712. return { $set: { allowsSubtasks } };
  713. },
  714. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  715. return { $set: { subtasksDefaultBoardId } };
  716. },
  717. setSubtasksDefaultListId(subtasksDefaultListId) {
  718. return { $set: { subtasksDefaultListId } };
  719. },
  720. setPresentParentTask(presentParentTask) {
  721. return { $set: { presentParentTask } };
  722. },
  723. });
  724. if (Meteor.isServer) {
  725. Boards.allow({
  726. insert: Meteor.userId,
  727. update: allowIsBoardAdmin,
  728. remove: allowIsBoardAdmin,
  729. fetch: ['members'],
  730. });
  731. // The number of users that have starred this board is managed by trusted code
  732. // and the user is not allowed to update it
  733. Boards.deny({
  734. update(userId, board, fieldNames) {
  735. return _.contains(fieldNames, 'stars');
  736. },
  737. fetch: [],
  738. });
  739. // We can't remove a member if it is the last administrator
  740. Boards.deny({
  741. update(userId, doc, fieldNames, modifier) {
  742. if (!_.contains(fieldNames, 'members'))
  743. return false;
  744. // We only care in case of a $pull operation, ie remove a member
  745. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  746. return false;
  747. // If there is more than one admin, it's ok to remove anyone
  748. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  749. if (nbAdmins > 1)
  750. return false;
  751. // If all the previous conditions were verified, we can't remove
  752. // a user if it's an admin
  753. const removedMemberId = modifier.$pull.members.userId;
  754. return Boolean(_.findWhere(doc.members, {
  755. userId: removedMemberId,
  756. isAdmin: true,
  757. }));
  758. },
  759. fetch: ['members'],
  760. });
  761. Meteor.methods({
  762. quitBoard(boardId) {
  763. check(boardId, String);
  764. const board = Boards.findOne(boardId);
  765. if (board) {
  766. const userId = Meteor.userId();
  767. const index = board.memberIndex(userId);
  768. if (index >= 0) {
  769. board.removeMember(userId);
  770. return true;
  771. } else throw new Meteor.Error('error-board-notAMember');
  772. } else throw new Meteor.Error('error-board-doesNotExist');
  773. },
  774. });
  775. }
  776. if (Meteor.isServer) {
  777. // Let MongoDB ensure that a member is not included twice in the same board
  778. Meteor.startup(() => {
  779. Boards._collection._ensureIndex({
  780. _id: 1,
  781. 'members.userId': 1,
  782. }, { unique: true });
  783. Boards._collection._ensureIndex({ 'members.userId': 1 });
  784. });
  785. // Genesis: the first activity of the newly created board
  786. Boards.after.insert((userId, doc) => {
  787. Activities.insert({
  788. userId,
  789. type: 'board',
  790. activityTypeId: doc._id,
  791. activityType: 'createBoard',
  792. boardId: doc._id,
  793. });
  794. });
  795. // If the user remove one label from a board, we cant to remove reference of
  796. // this label in any card of this board.
  797. Boards.after.update((userId, doc, fieldNames, modifier) => {
  798. if (!_.contains(fieldNames, 'labels') ||
  799. !modifier.$pull ||
  800. !modifier.$pull.labels ||
  801. !modifier.$pull.labels._id) {
  802. return;
  803. }
  804. const removedLabelId = modifier.$pull.labels._id;
  805. Cards.update(
  806. { boardId: doc._id },
  807. {
  808. $pull: {
  809. labelIds: removedLabelId,
  810. },
  811. },
  812. { multi: true }
  813. );
  814. });
  815. const foreachRemovedMember = (doc, modifier, callback) => {
  816. Object.keys(modifier).forEach((set) => {
  817. if (modifier[set] !== false) {
  818. return;
  819. }
  820. const parts = set.split('.');
  821. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  822. callback(doc.members[parts[1]].userId);
  823. }
  824. });
  825. };
  826. // Remove a member from all objects of the board before leaving the board
  827. Boards.before.update((userId, doc, fieldNames, modifier) => {
  828. if (!_.contains(fieldNames, 'members')) {
  829. return;
  830. }
  831. if (modifier.$set) {
  832. const boardId = doc._id;
  833. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  834. Cards.update(
  835. { boardId },
  836. {
  837. $pull: {
  838. members: memberId,
  839. watchers: memberId,
  840. },
  841. },
  842. { multi: true }
  843. );
  844. Lists.update(
  845. { boardId },
  846. {
  847. $pull: {
  848. watchers: memberId,
  849. },
  850. },
  851. { multi: true }
  852. );
  853. const board = Boards._transform(doc);
  854. board.setWatcher(memberId, false);
  855. // Remove board from users starred list
  856. if (!board.isPublic()) {
  857. Users.update(
  858. memberId,
  859. {
  860. $pull: {
  861. 'profile.starredBoards': boardId,
  862. },
  863. }
  864. );
  865. }
  866. });
  867. }
  868. });
  869. // Add a new activity if we add or remove a member to the board
  870. Boards.after.update((userId, doc, fieldNames, modifier) => {
  871. if (!_.contains(fieldNames, 'members')) {
  872. return;
  873. }
  874. // Say hello to the new member
  875. if (modifier.$push && modifier.$push.members) {
  876. const memberId = modifier.$push.members.userId;
  877. Activities.insert({
  878. userId,
  879. memberId,
  880. type: 'member',
  881. activityType: 'addBoardMember',
  882. boardId: doc._id,
  883. });
  884. }
  885. // Say goodbye to the former member
  886. if (modifier.$set) {
  887. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  888. Activities.insert({
  889. userId,
  890. memberId,
  891. type: 'member',
  892. activityType: 'removeBoardMember',
  893. boardId: doc._id,
  894. });
  895. });
  896. }
  897. });
  898. }
  899. //BOARDS REST API
  900. if (Meteor.isServer) {
  901. /**
  902. * @operation get_boards_from_user
  903. * @summary Get all boards attached to a user
  904. *
  905. * @param {string} userId the ID of the user to retrieve the data
  906. * @return_type [{_id: string,
  907. title: string}]
  908. */
  909. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  910. try {
  911. Authentication.checkLoggedIn(req.userId);
  912. const paramUserId = req.params.userId;
  913. // A normal user should be able to see their own boards,
  914. // admins can access boards of any user
  915. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  916. const data = Boards.find({
  917. archived: false,
  918. 'members.userId': paramUserId,
  919. }, {
  920. sort: ['title'],
  921. }).map(function(board) {
  922. return {
  923. _id: board._id,
  924. title: board.title,
  925. };
  926. });
  927. JsonRoutes.sendResult(res, {code: 200, data});
  928. }
  929. catch (error) {
  930. JsonRoutes.sendResult(res, {
  931. code: 200,
  932. data: error,
  933. });
  934. }
  935. });
  936. /**
  937. * @operation get_public_boards
  938. * @summary Get all public boards
  939. *
  940. * @return_type [{_id: string,
  941. title: string}]
  942. */
  943. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  944. try {
  945. Authentication.checkUserId(req.userId);
  946. JsonRoutes.sendResult(res, {
  947. code: 200,
  948. data: Boards.find({ permission: 'public' }).map(function (doc) {
  949. return {
  950. _id: doc._id,
  951. title: doc.title,
  952. };
  953. }),
  954. });
  955. }
  956. catch (error) {
  957. JsonRoutes.sendResult(res, {
  958. code: 200,
  959. data: error,
  960. });
  961. }
  962. });
  963. /**
  964. * @operation get_board
  965. * @summary Get the board with that particular ID
  966. *
  967. * @param {string} boardId the ID of the board to retrieve the data
  968. * @return_type Boards
  969. */
  970. JsonRoutes.add('GET', '/api/boards/:boardId', function (req, res) {
  971. try {
  972. const id = req.params.boardId;
  973. Authentication.checkBoardAccess(req.userId, id);
  974. JsonRoutes.sendResult(res, {
  975. code: 200,
  976. data: Boards.findOne({ _id: id }),
  977. });
  978. }
  979. catch (error) {
  980. JsonRoutes.sendResult(res, {
  981. code: 200,
  982. data: error,
  983. });
  984. }
  985. });
  986. /**
  987. * @operation new_board
  988. * @summary Create a board
  989. *
  990. * @description This allows to create a board.
  991. *
  992. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  993. * `pumpkin`, `wisteria`, `midnight`:
  994. *
  995. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  996. *
  997. * @param {string} title the new title of the board
  998. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  999. * (Not username or email)
  1000. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1001. * @param {boolean} [isActive] is the board active (default true)
  1002. * @param {boolean} [isNoComments] disable comments (default false)
  1003. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1004. * @param {string} [permission] "private" board <== Set to "public" if you
  1005. * want public Wekan board
  1006. * @param {string} [color] the color of the board
  1007. *
  1008. * @return_type {_id: string,
  1009. defaultSwimlaneId: string}
  1010. */
  1011. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  1012. try {
  1013. Authentication.checkUserId(req.userId);
  1014. const id = Boards.insert({
  1015. title: req.body.title,
  1016. members: [
  1017. {
  1018. userId: req.body.owner,
  1019. isAdmin: req.body.isAdmin || true,
  1020. isActive: req.body.isActive || true,
  1021. isNoComments: req.body.isNoComments || false,
  1022. isCommentOnly: req.body.isCommentOnly || false,
  1023. },
  1024. ],
  1025. permission: req.body.permission || 'private',
  1026. color: req.body.color || 'belize',
  1027. });
  1028. const swimlaneId = Swimlanes.insert({
  1029. title: TAPi18n.__('default'),
  1030. boardId: id,
  1031. });
  1032. JsonRoutes.sendResult(res, {
  1033. code: 200,
  1034. data: {
  1035. _id: id,
  1036. defaultSwimlaneId: swimlaneId,
  1037. },
  1038. });
  1039. }
  1040. catch (error) {
  1041. JsonRoutes.sendResult(res, {
  1042. code: 200,
  1043. data: error,
  1044. });
  1045. }
  1046. });
  1047. /**
  1048. * @operation delete_board
  1049. * @summary Delete a board
  1050. *
  1051. * @param {string} boardId the ID of the board
  1052. */
  1053. JsonRoutes.add('DELETE', '/api/boards/:boardId', function (req, res) {
  1054. try {
  1055. Authentication.checkUserId(req.userId);
  1056. const id = req.params.boardId;
  1057. Boards.remove({ _id: id });
  1058. JsonRoutes.sendResult(res, {
  1059. code: 200,
  1060. data:{
  1061. _id: id,
  1062. },
  1063. });
  1064. }
  1065. catch (error) {
  1066. JsonRoutes.sendResult(res, {
  1067. code: 200,
  1068. data: error,
  1069. });
  1070. }
  1071. });
  1072. /**
  1073. * @operation add_board_label
  1074. * @summary Add a label to a board
  1075. *
  1076. * @description If the board doesn't have the name/color label, this function
  1077. * adds the label to the board.
  1078. *
  1079. * @param {string} boardId the board
  1080. * @param {string} color the color of the new label
  1081. * @param {string} name the name of the new label
  1082. *
  1083. * @return_type string
  1084. */
  1085. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function (req, res) {
  1086. Authentication.checkUserId(req.userId);
  1087. const id = req.params.boardId;
  1088. try {
  1089. if (req.body.hasOwnProperty('label')) {
  1090. const board = Boards.findOne({ _id: id });
  1091. const color = req.body.label.color;
  1092. const name = req.body.label.name;
  1093. const labelId = Random.id(6);
  1094. if (!board.getLabel(name, color)) {
  1095. Boards.direct.update({ _id: id }, { $push: { labels: { _id: labelId, name, color } } });
  1096. JsonRoutes.sendResult(res, {
  1097. code: 200,
  1098. data: labelId,
  1099. });
  1100. } else {
  1101. JsonRoutes.sendResult(res, {
  1102. code: 200,
  1103. });
  1104. }
  1105. }
  1106. }
  1107. catch (error) {
  1108. JsonRoutes.sendResult(res, {
  1109. data: error,
  1110. });
  1111. }
  1112. });
  1113. /**
  1114. * @operation set_board_member_permission
  1115. * @tag Users
  1116. * @summary Change the permission of a member of a board
  1117. *
  1118. * @param {string} boardId the ID of the board that we are changing
  1119. * @param {string} memberId the ID of the user to change permissions
  1120. * @param {boolean} isAdmin admin capability
  1121. * @param {boolean} isNoComments NoComments capability
  1122. * @param {boolean} isCommentOnly CommentsOnly capability
  1123. */
  1124. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function (req, res) {
  1125. try {
  1126. const boardId = req.params.boardId;
  1127. const memberId = req.params.memberId;
  1128. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  1129. Authentication.checkBoardAccess(req.userId, boardId);
  1130. const board = Boards.findOne({ _id: boardId });
  1131. function isTrue(data){
  1132. try {
  1133. return data.toLowerCase() === 'true';
  1134. }
  1135. catch (error) {
  1136. return data;
  1137. }
  1138. }
  1139. const query = board.setMemberPermission(memberId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), req.userId);
  1140. JsonRoutes.sendResult(res, {
  1141. code: 200,
  1142. data: query,
  1143. });
  1144. }
  1145. catch (error) {
  1146. JsonRoutes.sendResult(res, {
  1147. code: 200,
  1148. data: error,
  1149. });
  1150. }
  1151. });
  1152. }