boards.js 35 KB

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