boards.js 35 KB

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