boards.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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. return Lists.find({ boardId: this._id }, { sort: { sort: 1 } });
  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. cardsDueInBetween(start, end) {
  647. return Cards.find({
  648. boardId: this._id,
  649. dueAt: { $gte: start, $lte: end },
  650. });
  651. },
  652. cardsInInterval(start, end) {
  653. return Cards.find({
  654. boardId: this._id,
  655. $or: [
  656. {
  657. startAt: {
  658. $lte: start,
  659. },
  660. endAt: {
  661. $gte: start,
  662. },
  663. },
  664. {
  665. startAt: {
  666. $lte: end,
  667. },
  668. endAt: {
  669. $gte: end,
  670. },
  671. },
  672. {
  673. startAt: {
  674. $gte: start,
  675. },
  676. endAt: {
  677. $lte: end,
  678. },
  679. },
  680. ],
  681. });
  682. },
  683. isTemplateBoard() {
  684. return this.type === 'template-board';
  685. },
  686. isTemplatesBoard() {
  687. return this.type === 'template-container';
  688. },
  689. });
  690. Boards.mutations({
  691. archive() {
  692. return { $set: { archived: true } };
  693. },
  694. restore() {
  695. return { $set: { archived: false } };
  696. },
  697. rename(title) {
  698. return { $set: { title } };
  699. },
  700. setDescription(description) {
  701. return { $set: { description } };
  702. },
  703. setColor(color) {
  704. return { $set: { color } };
  705. },
  706. setVisibility(visibility) {
  707. return { $set: { permission: visibility } };
  708. },
  709. addLabel(name, color) {
  710. // If label with the same name and color already exists we don't want to
  711. // create another one because they would be indistinguishable in the UI
  712. // (they would still have different `_id` but that is not exposed to the
  713. // user).
  714. if (!this.getLabel(name, color)) {
  715. const _id = Random.id(6);
  716. return { $push: { labels: { _id, name, color } } };
  717. }
  718. return {};
  719. },
  720. editLabel(labelId, name, color) {
  721. if (!this.getLabel(name, color)) {
  722. const labelIndex = this.labelIndex(labelId);
  723. return {
  724. $set: {
  725. [`labels.${labelIndex}.name`]: name,
  726. [`labels.${labelIndex}.color`]: color,
  727. },
  728. };
  729. }
  730. return {};
  731. },
  732. removeLabel(labelId) {
  733. return { $pull: { labels: { _id: labelId } } };
  734. },
  735. changeOwnership(fromId, toId) {
  736. const memberIndex = this.memberIndex(fromId);
  737. return {
  738. $set: {
  739. [`members.${memberIndex}.userId`]: toId,
  740. },
  741. };
  742. },
  743. addMember(memberId) {
  744. const memberIndex = this.memberIndex(memberId);
  745. if (memberIndex >= 0) {
  746. return {
  747. $set: {
  748. [`members.${memberIndex}.isActive`]: true,
  749. },
  750. };
  751. }
  752. return {
  753. $push: {
  754. members: {
  755. userId: memberId,
  756. isAdmin: false,
  757. isActive: true,
  758. isNoComments: false,
  759. isCommentOnly: false,
  760. },
  761. },
  762. };
  763. },
  764. removeMember(memberId) {
  765. const memberIndex = this.memberIndex(memberId);
  766. // we do not allow the only one admin to be removed
  767. const allowRemove =
  768. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  769. if (!allowRemove) {
  770. return {
  771. $set: {
  772. [`members.${memberIndex}.isActive`]: true,
  773. },
  774. };
  775. }
  776. return {
  777. $set: {
  778. [`members.${memberIndex}.isActive`]: false,
  779. [`members.${memberIndex}.isAdmin`]: false,
  780. },
  781. };
  782. },
  783. setMemberPermission(
  784. memberId,
  785. isAdmin,
  786. isNoComments,
  787. isCommentOnly,
  788. currentUserId = Meteor.userId(),
  789. ) {
  790. const memberIndex = this.memberIndex(memberId);
  791. // do not allow change permission of self
  792. if (memberId === currentUserId) {
  793. isAdmin = this.members[memberIndex].isAdmin;
  794. }
  795. return {
  796. $set: {
  797. [`members.${memberIndex}.isAdmin`]: isAdmin,
  798. [`members.${memberIndex}.isNoComments`]: isNoComments,
  799. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  800. },
  801. };
  802. },
  803. setAllowsSubtasks(allowsSubtasks) {
  804. return { $set: { allowsSubtasks } };
  805. },
  806. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  807. return { $set: { subtasksDefaultBoardId } };
  808. },
  809. setSubtasksDefaultListId(subtasksDefaultListId) {
  810. return { $set: { subtasksDefaultListId } };
  811. },
  812. setPresentParentTask(presentParentTask) {
  813. return { $set: { presentParentTask } };
  814. },
  815. });
  816. function boardRemover(userId, doc) {
  817. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  818. element => {
  819. element.remove({ boardId: doc._id });
  820. },
  821. );
  822. }
  823. if (Meteor.isServer) {
  824. Boards.allow({
  825. insert: Meteor.userId,
  826. update: allowIsBoardAdmin,
  827. remove: allowIsBoardAdmin,
  828. fetch: ['members'],
  829. });
  830. // The number of users that have starred this board is managed by trusted code
  831. // and the user is not allowed to update it
  832. Boards.deny({
  833. update(userId, board, fieldNames) {
  834. return _.contains(fieldNames, 'stars');
  835. },
  836. fetch: [],
  837. });
  838. // We can't remove a member if it is the last administrator
  839. Boards.deny({
  840. update(userId, doc, fieldNames, modifier) {
  841. if (!_.contains(fieldNames, 'members')) return false;
  842. // We only care in case of a $pull operation, ie remove a member
  843. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  844. // If there is more than one admin, it's ok to remove anyone
  845. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  846. .length;
  847. if (nbAdmins > 1) return false;
  848. // If all the previous conditions were verified, we can't remove
  849. // a user if it's an admin
  850. const removedMemberId = modifier.$pull.members.userId;
  851. return Boolean(
  852. _.findWhere(doc.members, {
  853. userId: removedMemberId,
  854. isAdmin: true,
  855. }),
  856. );
  857. },
  858. fetch: ['members'],
  859. });
  860. Meteor.methods({
  861. quitBoard(boardId) {
  862. check(boardId, String);
  863. const board = Boards.findOne(boardId);
  864. if (board) {
  865. const userId = Meteor.userId();
  866. const index = board.memberIndex(userId);
  867. if (index >= 0) {
  868. board.removeMember(userId);
  869. return true;
  870. } else throw new Meteor.Error('error-board-notAMember');
  871. } else throw new Meteor.Error('error-board-doesNotExist');
  872. },
  873. acceptInvite(boardId) {
  874. check(boardId, String);
  875. const board = Boards.findOne(boardId);
  876. if (!board) {
  877. throw new Meteor.Error('error-board-doesNotExist');
  878. }
  879. Meteor.users.update(Meteor.userId(), {
  880. $pull: {
  881. 'profile.invitedBoards': boardId,
  882. },
  883. });
  884. },
  885. });
  886. Meteor.methods({
  887. archiveBoard(boardId) {
  888. check(boardId, String);
  889. const board = Boards.findOne(boardId);
  890. if (board) {
  891. const userId = Meteor.userId();
  892. const index = board.memberIndex(userId);
  893. if (index >= 0) {
  894. board.archive();
  895. return true;
  896. } else throw new Meteor.Error('error-board-notAMember');
  897. } else throw new Meteor.Error('error-board-doesNotExist');
  898. },
  899. });
  900. }
  901. if (Meteor.isServer) {
  902. // Let MongoDB ensure that a member is not included twice in the same board
  903. Meteor.startup(() => {
  904. Boards._collection._ensureIndex({ modifiedAt: -1 });
  905. Boards._collection._ensureIndex(
  906. {
  907. _id: 1,
  908. 'members.userId': 1,
  909. },
  910. { unique: true },
  911. );
  912. Boards._collection._ensureIndex({ 'members.userId': 1 });
  913. });
  914. // Genesis: the first activity of the newly created board
  915. Boards.after.insert((userId, doc) => {
  916. Activities.insert({
  917. userId,
  918. type: 'board',
  919. activityTypeId: doc._id,
  920. activityType: 'createBoard',
  921. boardId: doc._id,
  922. });
  923. });
  924. // If the user remove one label from a board, we cant to remove reference of
  925. // this label in any card of this board.
  926. Boards.after.update((userId, doc, fieldNames, modifier) => {
  927. if (
  928. !_.contains(fieldNames, 'labels') ||
  929. !modifier.$pull ||
  930. !modifier.$pull.labels ||
  931. !modifier.$pull.labels._id
  932. ) {
  933. return;
  934. }
  935. const removedLabelId = modifier.$pull.labels._id;
  936. Cards.update(
  937. { boardId: doc._id },
  938. {
  939. $pull: {
  940. labelIds: removedLabelId,
  941. },
  942. },
  943. { multi: true },
  944. );
  945. });
  946. const foreachRemovedMember = (doc, modifier, callback) => {
  947. Object.keys(modifier).forEach(set => {
  948. if (modifier[set] !== false) {
  949. return;
  950. }
  951. const parts = set.split('.');
  952. if (
  953. parts.length === 3 &&
  954. parts[0] === 'members' &&
  955. parts[2] === 'isActive'
  956. ) {
  957. callback(doc.members[parts[1]].userId);
  958. }
  959. });
  960. };
  961. // Remove a member from all objects of the board before leaving the board
  962. Boards.before.update((userId, doc, fieldNames, modifier) => {
  963. if (!_.contains(fieldNames, 'members')) {
  964. return;
  965. }
  966. if (modifier.$set) {
  967. const boardId = doc._id;
  968. foreachRemovedMember(doc, modifier.$set, memberId => {
  969. Cards.update(
  970. { boardId },
  971. {
  972. $pull: {
  973. members: memberId,
  974. watchers: memberId,
  975. },
  976. },
  977. { multi: true },
  978. );
  979. Lists.update(
  980. { boardId },
  981. {
  982. $pull: {
  983. watchers: memberId,
  984. },
  985. },
  986. { multi: true },
  987. );
  988. const board = Boards._transform(doc);
  989. board.setWatcher(memberId, false);
  990. // Remove board from users starred list
  991. if (!board.isPublic()) {
  992. Users.update(memberId, {
  993. $pull: {
  994. 'profile.starredBoards': boardId,
  995. },
  996. });
  997. }
  998. });
  999. }
  1000. });
  1001. Boards.before.remove((userId, doc) => {
  1002. boardRemover(userId, doc);
  1003. // Add removeBoard activity to keep it
  1004. Activities.insert({
  1005. userId,
  1006. type: 'board',
  1007. activityTypeId: doc._id,
  1008. activityType: 'removeBoard',
  1009. boardId: doc._id,
  1010. });
  1011. });
  1012. // Add a new activity if we add or remove a member to the board
  1013. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1014. if (!_.contains(fieldNames, 'members')) {
  1015. return;
  1016. }
  1017. // Say hello to the new member
  1018. if (modifier.$push && modifier.$push.members) {
  1019. const memberId = modifier.$push.members.userId;
  1020. Activities.insert({
  1021. userId,
  1022. memberId,
  1023. type: 'member',
  1024. activityType: 'addBoardMember',
  1025. boardId: doc._id,
  1026. });
  1027. }
  1028. // Say goodbye to the former member
  1029. if (modifier.$set) {
  1030. foreachRemovedMember(doc, modifier.$set, memberId => {
  1031. Activities.insert({
  1032. userId,
  1033. memberId,
  1034. type: 'member',
  1035. activityType: 'removeBoardMember',
  1036. boardId: doc._id,
  1037. });
  1038. });
  1039. }
  1040. });
  1041. }
  1042. //BOARDS REST API
  1043. if (Meteor.isServer) {
  1044. /**
  1045. * @operation get_boards_from_user
  1046. * @summary Get all boards attached to a user
  1047. *
  1048. * @param {string} userId the ID of the user to retrieve the data
  1049. * @return_type [{_id: string,
  1050. title: string}]
  1051. */
  1052. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1053. try {
  1054. Authentication.checkLoggedIn(req.userId);
  1055. const paramUserId = req.params.userId;
  1056. // A normal user should be able to see their own boards,
  1057. // admins can access boards of any user
  1058. Authentication.checkAdminOrCondition(
  1059. req.userId,
  1060. req.userId === paramUserId,
  1061. );
  1062. const data = Boards.find(
  1063. {
  1064. archived: false,
  1065. 'members.userId': paramUserId,
  1066. },
  1067. {
  1068. sort: ['title'],
  1069. },
  1070. ).map(function(board) {
  1071. return {
  1072. _id: board._id,
  1073. title: board.title,
  1074. };
  1075. });
  1076. JsonRoutes.sendResult(res, { code: 200, data });
  1077. } catch (error) {
  1078. JsonRoutes.sendResult(res, {
  1079. code: 200,
  1080. data: error,
  1081. });
  1082. }
  1083. });
  1084. /**
  1085. * @operation get_public_boards
  1086. * @summary Get all public boards
  1087. *
  1088. * @return_type [{_id: string,
  1089. title: string}]
  1090. */
  1091. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1092. try {
  1093. Authentication.checkUserId(req.userId);
  1094. JsonRoutes.sendResult(res, {
  1095. code: 200,
  1096. data: Boards.find({ permission: 'public' }).map(function(doc) {
  1097. return {
  1098. _id: doc._id,
  1099. title: doc.title,
  1100. };
  1101. }),
  1102. });
  1103. } catch (error) {
  1104. JsonRoutes.sendResult(res, {
  1105. code: 200,
  1106. data: error,
  1107. });
  1108. }
  1109. });
  1110. /**
  1111. * @operation get_board
  1112. * @summary Get the board with that particular ID
  1113. *
  1114. * @param {string} boardId the ID of the board to retrieve the data
  1115. * @return_type Boards
  1116. */
  1117. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1118. try {
  1119. const id = req.params.boardId;
  1120. Authentication.checkBoardAccess(req.userId, id);
  1121. JsonRoutes.sendResult(res, {
  1122. code: 200,
  1123. data: Boards.findOne({ _id: id }),
  1124. });
  1125. } catch (error) {
  1126. JsonRoutes.sendResult(res, {
  1127. code: 200,
  1128. data: error,
  1129. });
  1130. }
  1131. });
  1132. /**
  1133. * @operation new_board
  1134. * @summary Create a board
  1135. *
  1136. * @description This allows to create a board.
  1137. *
  1138. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1139. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1140. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1141. *
  1142. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1143. *
  1144. * @param {string} title the new title of the board
  1145. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1146. * (Not username or email)
  1147. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1148. * @param {boolean} [isActive] is the board active (default true)
  1149. * @param {boolean} [isNoComments] disable comments (default false)
  1150. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1151. * @param {string} [permission] "private" board <== Set to "public" if you
  1152. * want public Wekan board
  1153. * @param {string} [color] the color of the board
  1154. *
  1155. * @return_type {_id: string,
  1156. defaultSwimlaneId: string}
  1157. */
  1158. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1159. try {
  1160. Authentication.checkUserId(req.userId);
  1161. const id = Boards.insert({
  1162. title: req.body.title,
  1163. members: [
  1164. {
  1165. userId: req.body.owner,
  1166. isAdmin: req.body.isAdmin || true,
  1167. isActive: req.body.isActive || true,
  1168. isNoComments: req.body.isNoComments || false,
  1169. isCommentOnly: req.body.isCommentOnly || false,
  1170. },
  1171. ],
  1172. permission: req.body.permission || 'private',
  1173. color: req.body.color || 'belize',
  1174. });
  1175. const swimlaneId = Swimlanes.insert({
  1176. title: TAPi18n.__('default'),
  1177. boardId: id,
  1178. });
  1179. JsonRoutes.sendResult(res, {
  1180. code: 200,
  1181. data: {
  1182. _id: id,
  1183. defaultSwimlaneId: swimlaneId,
  1184. },
  1185. });
  1186. } catch (error) {
  1187. JsonRoutes.sendResult(res, {
  1188. code: 200,
  1189. data: error,
  1190. });
  1191. }
  1192. });
  1193. /**
  1194. * @operation delete_board
  1195. * @summary Delete a board
  1196. *
  1197. * @param {string} boardId the ID of the board
  1198. */
  1199. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1200. try {
  1201. Authentication.checkUserId(req.userId);
  1202. const id = req.params.boardId;
  1203. Boards.remove({ _id: id });
  1204. JsonRoutes.sendResult(res, {
  1205. code: 200,
  1206. data: {
  1207. _id: id,
  1208. },
  1209. });
  1210. } catch (error) {
  1211. JsonRoutes.sendResult(res, {
  1212. code: 200,
  1213. data: error,
  1214. });
  1215. }
  1216. });
  1217. /**
  1218. * @operation add_board_label
  1219. * @summary Add a label to a board
  1220. *
  1221. * @description If the board doesn't have the name/color label, this function
  1222. * adds the label to the board.
  1223. *
  1224. * @param {string} boardId the board
  1225. * @param {string} color the color of the new label
  1226. * @param {string} name the name of the new label
  1227. *
  1228. * @return_type string
  1229. */
  1230. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1231. Authentication.checkUserId(req.userId);
  1232. const id = req.params.boardId;
  1233. try {
  1234. if (req.body.hasOwnProperty('label')) {
  1235. const board = Boards.findOne({ _id: id });
  1236. const color = req.body.label.color;
  1237. const name = req.body.label.name;
  1238. const labelId = Random.id(6);
  1239. if (!board.getLabel(name, color)) {
  1240. Boards.direct.update(
  1241. { _id: id },
  1242. { $push: { labels: { _id: labelId, name, color } } },
  1243. );
  1244. JsonRoutes.sendResult(res, {
  1245. code: 200,
  1246. data: labelId,
  1247. });
  1248. } else {
  1249. JsonRoutes.sendResult(res, {
  1250. code: 200,
  1251. });
  1252. }
  1253. }
  1254. } catch (error) {
  1255. JsonRoutes.sendResult(res, {
  1256. data: error,
  1257. });
  1258. }
  1259. });
  1260. /**
  1261. * @operation set_board_member_permission
  1262. * @tag Users
  1263. * @summary Change the permission of a member of a board
  1264. *
  1265. * @param {string} boardId the ID of the board that we are changing
  1266. * @param {string} memberId the ID of the user to change permissions
  1267. * @param {boolean} isAdmin admin capability
  1268. * @param {boolean} isNoComments NoComments capability
  1269. * @param {boolean} isCommentOnly CommentsOnly capability
  1270. */
  1271. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1272. req,
  1273. res,
  1274. ) {
  1275. try {
  1276. const boardId = req.params.boardId;
  1277. const memberId = req.params.memberId;
  1278. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1279. Authentication.checkBoardAccess(req.userId, boardId);
  1280. const board = Boards.findOne({ _id: boardId });
  1281. function isTrue(data) {
  1282. try {
  1283. return data.toLowerCase() === 'true';
  1284. } catch (error) {
  1285. return data;
  1286. }
  1287. }
  1288. const query = board.setMemberPermission(
  1289. memberId,
  1290. isTrue(isAdmin),
  1291. isTrue(isNoComments),
  1292. isTrue(isCommentOnly),
  1293. req.userId,
  1294. );
  1295. JsonRoutes.sendResult(res, {
  1296. code: 200,
  1297. data: query,
  1298. });
  1299. } catch (error) {
  1300. JsonRoutes.sendResult(res, {
  1301. code: 200,
  1302. data: error,
  1303. });
  1304. }
  1305. });
  1306. }
  1307. export default Boards;