boards.js 34 KB

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