boards.js 34 KB

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