boards.js 34 KB

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