boards.js 34 KB

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