boards.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. function boardRemover(userId, doc) {
  725. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach((element) => {
  726. element.remove({ boardId: doc._id });
  727. });
  728. }
  729. if (Meteor.isServer) {
  730. Boards.allow({
  731. insert: Meteor.userId,
  732. update: allowIsBoardAdmin,
  733. remove: allowIsBoardAdmin,
  734. fetch: ['members'],
  735. });
  736. // The number of users that have starred this board is managed by trusted code
  737. // and the user is not allowed to update it
  738. Boards.deny({
  739. update(userId, board, fieldNames) {
  740. return _.contains(fieldNames, 'stars');
  741. },
  742. fetch: [],
  743. });
  744. // We can't remove a member if it is the last administrator
  745. Boards.deny({
  746. update(userId, doc, fieldNames, modifier) {
  747. if (!_.contains(fieldNames, 'members'))
  748. return false;
  749. // We only care in case of a $pull operation, ie remove a member
  750. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  751. return false;
  752. // If there is more than one admin, it's ok to remove anyone
  753. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  754. if (nbAdmins > 1)
  755. return false;
  756. // If all the previous conditions were verified, we can't remove
  757. // a user if it's an admin
  758. const removedMemberId = modifier.$pull.members.userId;
  759. return Boolean(_.findWhere(doc.members, {
  760. userId: removedMemberId,
  761. isAdmin: true,
  762. }));
  763. },
  764. fetch: ['members'],
  765. });
  766. Meteor.methods({
  767. quitBoard(boardId) {
  768. check(boardId, String);
  769. const board = Boards.findOne(boardId);
  770. if (board) {
  771. const userId = Meteor.userId();
  772. const index = board.memberIndex(userId);
  773. if (index >= 0) {
  774. board.removeMember(userId);
  775. return true;
  776. } else throw new Meteor.Error('error-board-notAMember');
  777. } else throw new Meteor.Error('error-board-doesNotExist');
  778. },
  779. });
  780. }
  781. if (Meteor.isServer) {
  782. // Let MongoDB ensure that a member is not included twice in the same board
  783. Meteor.startup(() => {
  784. Boards._collection._ensureIndex({
  785. _id: 1,
  786. 'members.userId': 1,
  787. }, { unique: true });
  788. Boards._collection._ensureIndex({ 'members.userId': 1 });
  789. });
  790. // Genesis: the first activity of the newly created board
  791. Boards.after.insert((userId, doc) => {
  792. Activities.insert({
  793. userId,
  794. type: 'board',
  795. activityTypeId: doc._id,
  796. activityType: 'createBoard',
  797. boardId: doc._id,
  798. });
  799. });
  800. // If the user remove one label from a board, we cant to remove reference of
  801. // this label in any card of this board.
  802. Boards.after.update((userId, doc, fieldNames, modifier) => {
  803. if (!_.contains(fieldNames, 'labels') ||
  804. !modifier.$pull ||
  805. !modifier.$pull.labels ||
  806. !modifier.$pull.labels._id) {
  807. return;
  808. }
  809. const removedLabelId = modifier.$pull.labels._id;
  810. Cards.update(
  811. { boardId: doc._id },
  812. {
  813. $pull: {
  814. labelIds: removedLabelId,
  815. },
  816. },
  817. { multi: true }
  818. );
  819. });
  820. const foreachRemovedMember = (doc, modifier, callback) => {
  821. Object.keys(modifier).forEach((set) => {
  822. if (modifier[set] !== false) {
  823. return;
  824. }
  825. const parts = set.split('.');
  826. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  827. callback(doc.members[parts[1]].userId);
  828. }
  829. });
  830. };
  831. // Remove a member from all objects of the board before leaving the board
  832. Boards.before.update((userId, doc, fieldNames, modifier) => {
  833. if (!_.contains(fieldNames, 'members')) {
  834. return;
  835. }
  836. if (modifier.$set) {
  837. const boardId = doc._id;
  838. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  839. Cards.update(
  840. { boardId },
  841. {
  842. $pull: {
  843. members: memberId,
  844. watchers: memberId,
  845. },
  846. },
  847. { multi: true }
  848. );
  849. Lists.update(
  850. { boardId },
  851. {
  852. $pull: {
  853. watchers: memberId,
  854. },
  855. },
  856. { multi: true }
  857. );
  858. const board = Boards._transform(doc);
  859. board.setWatcher(memberId, false);
  860. // Remove board from users starred list
  861. if (!board.isPublic()) {
  862. Users.update(
  863. memberId,
  864. {
  865. $pull: {
  866. 'profile.starredBoards': boardId,
  867. },
  868. }
  869. );
  870. }
  871. });
  872. }
  873. });
  874. Boards.before.remove((userId, doc) => {
  875. boardRemover(userId, doc);
  876. // Add removeBoard activity to keep it
  877. Activities.insert({
  878. userId,
  879. type: 'board',
  880. activityTypeId: doc._id,
  881. activityType: 'removeBoard',
  882. boardId: doc._id,
  883. });
  884. });
  885. // Add a new activity if we add or remove a member to the board
  886. Boards.after.update((userId, doc, fieldNames, modifier) => {
  887. if (!_.contains(fieldNames, 'members')) {
  888. return;
  889. }
  890. // Say hello to the new member
  891. if (modifier.$push && modifier.$push.members) {
  892. const memberId = modifier.$push.members.userId;
  893. Activities.insert({
  894. userId,
  895. memberId,
  896. type: 'member',
  897. activityType: 'addBoardMember',
  898. boardId: doc._id,
  899. });
  900. }
  901. // Say goodbye to the former member
  902. if (modifier.$set) {
  903. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  904. Activities.insert({
  905. userId,
  906. memberId,
  907. type: 'member',
  908. activityType: 'removeBoardMember',
  909. boardId: doc._id,
  910. });
  911. });
  912. }
  913. });
  914. }
  915. //BOARDS REST API
  916. if (Meteor.isServer) {
  917. /**
  918. * @operation get_boards_from_user
  919. * @summary Get all boards attached to a user
  920. *
  921. * @param {string} userId the ID of the user to retrieve the data
  922. * @return_type [{_id: string,
  923. title: string}]
  924. */
  925. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res) {
  926. try {
  927. Authentication.checkLoggedIn(req.userId);
  928. const paramUserId = req.params.userId;
  929. // A normal user should be able to see their own boards,
  930. // admins can access boards of any user
  931. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  932. const data = Boards.find({
  933. archived: false,
  934. 'members.userId': paramUserId,
  935. }, {
  936. sort: ['title'],
  937. }).map(function(board) {
  938. return {
  939. _id: board._id,
  940. title: board.title,
  941. };
  942. });
  943. JsonRoutes.sendResult(res, {code: 200, data});
  944. }
  945. catch (error) {
  946. JsonRoutes.sendResult(res, {
  947. code: 200,
  948. data: error,
  949. });
  950. }
  951. });
  952. /**
  953. * @operation get_public_boards
  954. * @summary Get all public boards
  955. *
  956. * @return_type [{_id: string,
  957. title: string}]
  958. */
  959. JsonRoutes.add('GET', '/api/boards', function (req, res) {
  960. try {
  961. Authentication.checkUserId(req.userId);
  962. JsonRoutes.sendResult(res, {
  963. code: 200,
  964. data: Boards.find({ permission: 'public' }).map(function (doc) {
  965. return {
  966. _id: doc._id,
  967. title: doc.title,
  968. };
  969. }),
  970. });
  971. }
  972. catch (error) {
  973. JsonRoutes.sendResult(res, {
  974. code: 200,
  975. data: error,
  976. });
  977. }
  978. });
  979. /**
  980. * @operation get_board
  981. * @summary Get the board with that particular ID
  982. *
  983. * @param {string} boardId the ID of the board to retrieve the data
  984. * @return_type Boards
  985. */
  986. JsonRoutes.add('GET', '/api/boards/:boardId', function (req, res) {
  987. try {
  988. const id = req.params.boardId;
  989. Authentication.checkBoardAccess(req.userId, id);
  990. JsonRoutes.sendResult(res, {
  991. code: 200,
  992. data: Boards.findOne({ _id: id }),
  993. });
  994. }
  995. catch (error) {
  996. JsonRoutes.sendResult(res, {
  997. code: 200,
  998. data: error,
  999. });
  1000. }
  1001. });
  1002. /**
  1003. * @operation new_board
  1004. * @summary Create a board
  1005. *
  1006. * @description This allows to create a board.
  1007. *
  1008. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1009. * `pumpkin`, `wisteria`, `midnight`:
  1010. *
  1011. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1012. *
  1013. * @param {string} title the new title of the board
  1014. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1015. * (Not username or email)
  1016. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1017. * @param {boolean} [isActive] is the board active (default true)
  1018. * @param {boolean} [isNoComments] disable comments (default false)
  1019. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1020. * @param {string} [permission] "private" board <== Set to "public" if you
  1021. * want public Wekan board
  1022. * @param {string} [color] the color of the board
  1023. *
  1024. * @return_type {_id: string,
  1025. defaultSwimlaneId: string}
  1026. */
  1027. JsonRoutes.add('POST', '/api/boards', function (req, res) {
  1028. try {
  1029. Authentication.checkUserId(req.userId);
  1030. const id = Boards.insert({
  1031. title: req.body.title,
  1032. members: [
  1033. {
  1034. userId: req.body.owner,
  1035. isAdmin: req.body.isAdmin || true,
  1036. isActive: req.body.isActive || true,
  1037. isNoComments: req.body.isNoComments || false,
  1038. isCommentOnly: req.body.isCommentOnly || false,
  1039. },
  1040. ],
  1041. permission: req.body.permission || 'private',
  1042. color: req.body.color || 'belize',
  1043. });
  1044. const swimlaneId = Swimlanes.insert({
  1045. title: TAPi18n.__('default'),
  1046. boardId: id,
  1047. });
  1048. JsonRoutes.sendResult(res, {
  1049. code: 200,
  1050. data: {
  1051. _id: id,
  1052. defaultSwimlaneId: swimlaneId,
  1053. },
  1054. });
  1055. }
  1056. catch (error) {
  1057. JsonRoutes.sendResult(res, {
  1058. code: 200,
  1059. data: error,
  1060. });
  1061. }
  1062. });
  1063. /**
  1064. * @operation delete_board
  1065. * @summary Delete a board
  1066. *
  1067. * @param {string} boardId the ID of the board
  1068. */
  1069. JsonRoutes.add('DELETE', '/api/boards/:boardId', function (req, res) {
  1070. try {
  1071. Authentication.checkUserId(req.userId);
  1072. const id = req.params.boardId;
  1073. Boards.remove({ _id: id });
  1074. JsonRoutes.sendResult(res, {
  1075. code: 200,
  1076. data:{
  1077. _id: id,
  1078. },
  1079. });
  1080. }
  1081. catch (error) {
  1082. JsonRoutes.sendResult(res, {
  1083. code: 200,
  1084. data: error,
  1085. });
  1086. }
  1087. });
  1088. /**
  1089. * @operation add_board_label
  1090. * @summary Add a label to a board
  1091. *
  1092. * @description If the board doesn't have the name/color label, this function
  1093. * adds the label to the board.
  1094. *
  1095. * @param {string} boardId the board
  1096. * @param {string} color the color of the new label
  1097. * @param {string} name the name of the new label
  1098. *
  1099. * @return_type string
  1100. */
  1101. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function (req, res) {
  1102. Authentication.checkUserId(req.userId);
  1103. const id = req.params.boardId;
  1104. try {
  1105. if (req.body.hasOwnProperty('label')) {
  1106. const board = Boards.findOne({ _id: id });
  1107. const color = req.body.label.color;
  1108. const name = req.body.label.name;
  1109. const labelId = Random.id(6);
  1110. if (!board.getLabel(name, color)) {
  1111. Boards.direct.update({ _id: id }, { $push: { labels: { _id: labelId, name, color } } });
  1112. JsonRoutes.sendResult(res, {
  1113. code: 200,
  1114. data: labelId,
  1115. });
  1116. } else {
  1117. JsonRoutes.sendResult(res, {
  1118. code: 200,
  1119. });
  1120. }
  1121. }
  1122. }
  1123. catch (error) {
  1124. JsonRoutes.sendResult(res, {
  1125. data: error,
  1126. });
  1127. }
  1128. });
  1129. /**
  1130. * @operation set_board_member_permission
  1131. * @tag Users
  1132. * @summary Change the permission of a member of a board
  1133. *
  1134. * @param {string} boardId the ID of the board that we are changing
  1135. * @param {string} memberId the ID of the user to change permissions
  1136. * @param {boolean} isAdmin admin capability
  1137. * @param {boolean} isNoComments NoComments capability
  1138. * @param {boolean} isCommentOnly CommentsOnly capability
  1139. */
  1140. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function (req, res) {
  1141. try {
  1142. const boardId = req.params.boardId;
  1143. const memberId = req.params.memberId;
  1144. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  1145. Authentication.checkBoardAccess(req.userId, boardId);
  1146. const board = Boards.findOne({ _id: boardId });
  1147. function isTrue(data){
  1148. try {
  1149. return data.toLowerCase() === 'true';
  1150. }
  1151. catch (error) {
  1152. return data;
  1153. }
  1154. }
  1155. const query = board.setMemberPermission(memberId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), req.userId);
  1156. JsonRoutes.sendResult(res, {
  1157. code: 200,
  1158. data: query,
  1159. });
  1160. }
  1161. catch (error) {
  1162. JsonRoutes.sendResult(res, {
  1163. code: 200,
  1164. data: error,
  1165. });
  1166. }
  1167. });
  1168. }