boards.js 35 KB

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