boards.js 33 KB

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