boards.js 35 KB

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