boards.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. import {
  2. ALLOWED_BOARD_COLORS,
  3. ALLOWED_COLORS,
  4. TYPE_BOARD,
  5. TYPE_TEMPLATE_BOARD,
  6. TYPE_TEMPLATE_CONTAINER,
  7. } from '/config/const';
  8. const escapeForRegex = require('escape-string-regexp');
  9. Boards = new Mongo.Collection('boards');
  10. /**
  11. * This is a Board.
  12. */
  13. Boards.attachSchema(
  14. new SimpleSchema({
  15. title: {
  16. /**
  17. * The title of the board
  18. */
  19. type: String,
  20. },
  21. slug: {
  22. /**
  23. * The title slugified.
  24. */
  25. type: String,
  26. // eslint-disable-next-line consistent-return
  27. autoValue() {
  28. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  29. // return an empty string. This is causes bugs in our application so we set
  30. // a default slug in this case.
  31. // Improvment would be to change client URL after slug is changed
  32. const title = this.field('title');
  33. if (title.isSet && !this.isSet) {
  34. let slug = 'board';
  35. slug = getSlug(title.value) || slug;
  36. return slug;
  37. }
  38. },
  39. },
  40. archived: {
  41. /**
  42. * Is the board archived?
  43. */
  44. type: Boolean,
  45. // eslint-disable-next-line consistent-return
  46. autoValue() {
  47. if (this.isInsert && !this.isSet) {
  48. return false;
  49. }
  50. },
  51. },
  52. archivedAt: {
  53. /**
  54. * Latest archiving time of the board
  55. */
  56. type: Date,
  57. optional: true,
  58. },
  59. createdAt: {
  60. /**
  61. * Creation time of the board
  62. */
  63. type: Date,
  64. // eslint-disable-next-line consistent-return
  65. autoValue() {
  66. if (this.isInsert) {
  67. return new Date();
  68. } else if (this.isUpsert) {
  69. return { $setOnInsert: new Date() };
  70. } else {
  71. this.unset();
  72. }
  73. },
  74. },
  75. // XXX Inconsistent field naming
  76. modifiedAt: {
  77. /**
  78. * Last modification time of the board
  79. */
  80. type: Date,
  81. optional: true,
  82. // eslint-disable-next-line consistent-return
  83. autoValue() {
  84. if (this.isInsert || this.isUpsert || this.isUpdate) {
  85. return new Date();
  86. } else {
  87. this.unset();
  88. }
  89. },
  90. },
  91. // De-normalized number of users that have starred this board
  92. stars: {
  93. /**
  94. * How many stars the board has
  95. */
  96. type: Number,
  97. // eslint-disable-next-line consistent-return
  98. autoValue() {
  99. if (this.isInsert) {
  100. return 0;
  101. }
  102. },
  103. },
  104. // De-normalized label system
  105. labels: {
  106. /**
  107. * List of labels attached to a board
  108. */
  109. type: [Object],
  110. optional: true,
  111. /* Commented out, so does not create labels to new boards.
  112. // eslint-disable-next-line consistent-return
  113. autoValue() {
  114. if (this.isInsert && !this.isSet) {
  115. const colors = Boards.simpleSchema()._schema['labels.$.color']
  116. .allowedValues;
  117. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  118. return defaultLabelsColors.map(color => ({
  119. color,
  120. _id: Random.id(6),
  121. name: '',
  122. }));
  123. }
  124. },
  125. */
  126. },
  127. 'labels.$._id': {
  128. /**
  129. * Unique id of a label
  130. */
  131. // We don't specify that this field must be unique in the board because that
  132. // will cause performance penalties and is not necessary since this field is
  133. // always set on the server.
  134. // XXX Actually if we create a new label, the `_id` is set on the client
  135. // without being overwritten by the server, could it be a problem?
  136. type: String,
  137. },
  138. 'labels.$.name': {
  139. /**
  140. * Name of a label
  141. */
  142. type: String,
  143. optional: true,
  144. },
  145. 'labels.$.color': {
  146. /**
  147. * color of a label.
  148. *
  149. * Can be amongst `green`, `yellow`, `orange`, `red`, `purple`,
  150. * `blue`, `sky`, `lime`, `pink`, `black`,
  151. * `silver`, `peachpuff`, `crimson`, `plum`, `darkgreen`,
  152. * `slateblue`, `magenta`, `gold`, `navy`, `gray`,
  153. * `saddlebrown`, `paleturquoise`, `mistyrose`, `indigo`
  154. */
  155. type: String,
  156. allowedValues: ALLOWED_COLORS,
  157. },
  158. // XXX We might want to maintain more informations under the member sub-
  159. // documents like de-normalized meta-data (the date the member joined the
  160. // board, the number of contributions, etc.).
  161. members: {
  162. /**
  163. * List of members of a board
  164. */
  165. type: [Object],
  166. // eslint-disable-next-line consistent-return
  167. autoValue() {
  168. if (this.isInsert && !this.isSet) {
  169. return [
  170. {
  171. userId: this.userId,
  172. isAdmin: true,
  173. isActive: true,
  174. isNoComments: false,
  175. isCommentOnly: false,
  176. isWorker: false,
  177. },
  178. ];
  179. }
  180. },
  181. },
  182. 'members.$.userId': {
  183. /**
  184. * The uniq ID of the member
  185. */
  186. type: String,
  187. },
  188. 'members.$.isAdmin': {
  189. /**
  190. * Is the member an admin of the board?
  191. */
  192. type: Boolean,
  193. },
  194. 'members.$.isActive': {
  195. /**
  196. * Is the member active?
  197. */
  198. type: Boolean,
  199. },
  200. 'members.$.isNoComments': {
  201. /**
  202. * Is the member not allowed to make comments
  203. */
  204. type: Boolean,
  205. optional: true,
  206. },
  207. 'members.$.isCommentOnly': {
  208. /**
  209. * Is the member only allowed to comment on the board
  210. */
  211. type: Boolean,
  212. optional: true,
  213. },
  214. 'members.$.isWorker': {
  215. /**
  216. * Is the member only allowed to move card, assign himself to card and comment
  217. */
  218. type: Boolean,
  219. optional: true,
  220. },
  221. permission: {
  222. /**
  223. * visibility of the board
  224. */
  225. type: String,
  226. allowedValues: ['public', 'private'],
  227. },
  228. color: {
  229. /**
  230. * The color of the board.
  231. */
  232. type: String,
  233. allowedValues: ALLOWED_BOARD_COLORS,
  234. // eslint-disable-next-line consistent-return
  235. autoValue() {
  236. if (this.isInsert && !this.isSet) {
  237. return ALLOWED_BOARD_COLORS[0];
  238. }
  239. },
  240. },
  241. description: {
  242. /**
  243. * The description of the board
  244. */
  245. type: String,
  246. optional: true,
  247. },
  248. subtasksDefaultBoardId: {
  249. /**
  250. * The default board ID assigned to subtasks.
  251. */
  252. type: String,
  253. optional: true,
  254. defaultValue: null,
  255. },
  256. subtasksDefaultListId: {
  257. /**
  258. * The default List ID assigned to subtasks.
  259. */
  260. type: String,
  261. optional: true,
  262. defaultValue: null,
  263. },
  264. dateSettingsDefaultBoardId: {
  265. type: String,
  266. optional: true,
  267. defaultValue: null,
  268. },
  269. dateSettingsDefaultListId: {
  270. type: String,
  271. optional: true,
  272. defaultValue: null,
  273. },
  274. allowsSubtasks: {
  275. /**
  276. * Does the board allows subtasks?
  277. */
  278. type: Boolean,
  279. defaultValue: true,
  280. },
  281. allowsAttachments: {
  282. /**
  283. * Does the board allows attachments?
  284. */
  285. type: Boolean,
  286. defaultValue: true,
  287. },
  288. allowsChecklists: {
  289. /**
  290. * Does the board allows checklists?
  291. */
  292. type: Boolean,
  293. defaultValue: true,
  294. },
  295. allowsComments: {
  296. /**
  297. * Does the board allows comments?
  298. */
  299. type: Boolean,
  300. defaultValue: true,
  301. },
  302. allowsDescriptionTitle: {
  303. /**
  304. * Does the board allows description title?
  305. */
  306. type: Boolean,
  307. defaultValue: true,
  308. },
  309. allowsDescriptionText: {
  310. /**
  311. * Does the board allows description text?
  312. */
  313. type: Boolean,
  314. defaultValue: true,
  315. },
  316. allowsActivities: {
  317. /**
  318. * Does the board allows comments?
  319. */
  320. type: Boolean,
  321. defaultValue: true,
  322. },
  323. allowsLabels: {
  324. /**
  325. * Does the board allows labels?
  326. */
  327. type: Boolean,
  328. defaultValue: true,
  329. },
  330. allowsCreator: {
  331. /**
  332. * Does the board allow creator?
  333. */
  334. type: Boolean,
  335. defaultValue: true,
  336. },
  337. allowsAssignee: {
  338. /**
  339. * Does the board allows assignee?
  340. */
  341. type: Boolean,
  342. defaultValue: true,
  343. },
  344. allowsMembers: {
  345. /**
  346. * Does the board allows members?
  347. */
  348. type: Boolean,
  349. defaultValue: true,
  350. },
  351. allowsRequestedBy: {
  352. /**
  353. * Does the board allows requested by?
  354. */
  355. type: Boolean,
  356. defaultValue: true,
  357. },
  358. allowsCardSortingByNumber: {
  359. /**
  360. * Does the board allows card sorting by number?
  361. */
  362. type: Boolean,
  363. defaultValue: true,
  364. },
  365. allowsAssignedBy: {
  366. /**
  367. * Does the board allows requested by?
  368. */
  369. type: Boolean,
  370. defaultValue: true,
  371. },
  372. allowsReceivedDate: {
  373. /**
  374. * Does the board allows received date?
  375. */
  376. type: Boolean,
  377. defaultValue: true,
  378. },
  379. allowsStartDate: {
  380. /**
  381. * Does the board allows start date?
  382. */
  383. type: Boolean,
  384. defaultValue: true,
  385. },
  386. allowsEndDate: {
  387. /**
  388. * Does the board allows end date?
  389. */
  390. type: Boolean,
  391. defaultValue: true,
  392. },
  393. allowsDueDate: {
  394. /**
  395. * Does the board allows due date?
  396. */
  397. type: Boolean,
  398. defaultValue: true,
  399. },
  400. presentParentTask: {
  401. /**
  402. * Controls how to present the parent task:
  403. *
  404. * - `prefix-with-full-path`: add a prefix with the full path
  405. * - `prefix-with-parent`: add a prefisx with the parent name
  406. * - `subtext-with-full-path`: add a subtext with the full path
  407. * - `subtext-with-parent`: add a subtext with the parent name
  408. * - `no-parent`: does not show the parent at all
  409. */
  410. type: String,
  411. allowedValues: [
  412. 'prefix-with-full-path',
  413. 'prefix-with-parent',
  414. 'subtext-with-full-path',
  415. 'subtext-with-parent',
  416. 'no-parent',
  417. ],
  418. optional: true,
  419. defaultValue: 'no-parent',
  420. },
  421. startAt: {
  422. /**
  423. * Starting date of the board.
  424. */
  425. type: Date,
  426. optional: true,
  427. },
  428. dueAt: {
  429. /**
  430. * Due date of the board.
  431. */
  432. type: Date,
  433. optional: true,
  434. },
  435. endAt: {
  436. /**
  437. * End date of the board.
  438. */
  439. type: Date,
  440. optional: true,
  441. },
  442. spentTime: {
  443. /**
  444. * Time spent in the board.
  445. */
  446. type: Number,
  447. decimal: true,
  448. optional: true,
  449. },
  450. isOvertime: {
  451. /**
  452. * Is the board overtimed?
  453. */
  454. type: Boolean,
  455. defaultValue: false,
  456. optional: true,
  457. },
  458. type: {
  459. /**
  460. * The type of board
  461. * possible values: board, template-board, template-container
  462. */
  463. type: String,
  464. defaultValue: TYPE_BOARD,
  465. allowedValues: [TYPE_BOARD, TYPE_TEMPLATE_BOARD, TYPE_TEMPLATE_CONTAINER],
  466. },
  467. sort: {
  468. /**
  469. * Sort value
  470. */
  471. type: Number,
  472. decimal: true,
  473. defaultValue: -1,
  474. },
  475. }),
  476. );
  477. Boards.helpers({
  478. copy() {
  479. const oldId = this._id;
  480. delete this._id;
  481. delete this.slug;
  482. this.title = this.copyTitle();
  483. const _id = Boards.insert(this);
  484. // Copy all swimlanes in board
  485. Swimlanes.find({
  486. boardId: oldId,
  487. archived: false,
  488. }).forEach(swimlane => {
  489. swimlane.type = 'swimlane';
  490. swimlane.copy(_id);
  491. });
  492. // copy custom field definitions
  493. const cfMap = {};
  494. CustomFields.find({ boardIds: oldId }).forEach(cf => {
  495. const id = cf._id;
  496. delete cf._id;
  497. cf.boardIds = [_id];
  498. cfMap[id] = CustomFields.insert(cf);
  499. });
  500. Cards.find({ boardId: _id }).forEach(card => {
  501. Cards.update(card._id, {
  502. $set: {
  503. customFields: card.customFields.map(cf => {
  504. cf._id = cfMap[cf._id];
  505. return cf;
  506. }),
  507. },
  508. });
  509. });
  510. // copy rules, actions, and triggers
  511. const actionsMap = {};
  512. Actions.find({ boardId: oldId }).forEach(action => {
  513. const id = action._id;
  514. delete action._id;
  515. action.boardId = _id;
  516. actionsMap[id] = Actions.insert(action);
  517. });
  518. const triggersMap = {};
  519. Triggers.find({ boardId: oldId }).forEach(trigger => {
  520. const id = trigger._id;
  521. delete trigger._id;
  522. trigger.boardId = _id;
  523. triggersMap[id] = Triggers.insert(trigger);
  524. });
  525. Rules.find({ boardId: oldId }).forEach(rule => {
  526. delete rule._id;
  527. rule.boardId = _id;
  528. rule.actionId = actionsMap[rule.actionId];
  529. rule.triggerId = triggersMap[rule.triggerId];
  530. Rules.insert(rule);
  531. });
  532. },
  533. /**
  534. * Return a unique title based on the current title
  535. *
  536. * @returns {string|null}
  537. */
  538. copyTitle() {
  539. return Boards.uniqueTitle(this.title);
  540. },
  541. /**
  542. * Is supplied user authorized to view this board?
  543. */
  544. isVisibleBy(user) {
  545. if (this.isPublic()) {
  546. // public boards are visible to everyone
  547. return true;
  548. } else {
  549. // otherwise you have to be logged-in and active member
  550. return user && this.isActiveMember(user._id);
  551. }
  552. },
  553. /**
  554. * Is the user one of the active members of the board?
  555. *
  556. * @param userId
  557. * @returns {boolean} the member that matches, or undefined/false
  558. */
  559. isActiveMember(userId) {
  560. if (userId) {
  561. return this.members.find(
  562. member => member.userId === userId && member.isActive,
  563. );
  564. } else {
  565. return false;
  566. }
  567. },
  568. isPublic() {
  569. return this.permission === 'public';
  570. },
  571. cards() {
  572. return Cards.find(
  573. { boardId: this._id, archived: false },
  574. { sort: { title: 1 } },
  575. );
  576. },
  577. lists() {
  578. //currentUser = Meteor.user();
  579. //if (currentUser) {
  580. // enabled = Meteor.user().hasSortBy();
  581. //}
  582. //return enabled ? this.newestLists() : this.draggableLists();
  583. return this.draggableLists();
  584. },
  585. newestLists() {
  586. // sorted lists from newest to the oldest, by its creation date or its cards' last modification date
  587. const value = Meteor.user()._getListSortBy();
  588. const sortKey = { starred: -1, [value[0]]: value[1] }; // [["starred",-1],value];
  589. return Lists.find(
  590. {
  591. boardId: this._id,
  592. archived: false,
  593. },
  594. { sort: sortKey },
  595. );
  596. },
  597. draggableLists() {
  598. return Lists.find({ boardId: this._id }, { sort: { sort: 1 } });
  599. },
  600. nullSortLists() {
  601. return Lists.find({
  602. boardId: this._id,
  603. archived: false,
  604. sort: { $eq: null },
  605. });
  606. },
  607. swimlanes() {
  608. return Swimlanes.find(
  609. { boardId: this._id, archived: false },
  610. { sort: { sort: 1 } },
  611. );
  612. },
  613. nextSwimlane(swimlane) {
  614. return Swimlanes.findOne(
  615. {
  616. boardId: this._id,
  617. archived: false,
  618. sort: { $gte: swimlane.sort },
  619. _id: { $ne: swimlane._id },
  620. },
  621. {
  622. sort: { sort: 1 },
  623. },
  624. );
  625. },
  626. nullSortSwimlanes() {
  627. return Swimlanes.find({
  628. boardId: this._id,
  629. archived: false,
  630. sort: { $eq: null },
  631. });
  632. },
  633. hasOvertimeCards() {
  634. const card = Cards.findOne({
  635. isOvertime: true,
  636. boardId: this._id,
  637. archived: false,
  638. });
  639. return card !== undefined;
  640. },
  641. hasSpentTimeCards() {
  642. const card = Cards.findOne({
  643. spentTime: { $gt: 0 },
  644. boardId: this._id,
  645. archived: false,
  646. });
  647. return card !== undefined;
  648. },
  649. activities() {
  650. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  651. },
  652. activeMembers() {
  653. return _.where(this.members, { isActive: true });
  654. },
  655. activeAdmins() {
  656. return _.where(this.members, { isActive: true, isAdmin: true });
  657. },
  658. memberUsers() {
  659. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  660. },
  661. getLabel(name, color) {
  662. return _.findWhere(this.labels, { name, color });
  663. },
  664. getLabelById(labelId) {
  665. return _.findWhere(this.labels, { _id: labelId });
  666. },
  667. labelIndex(labelId) {
  668. return _.pluck(this.labels, '_id').indexOf(labelId);
  669. },
  670. memberIndex(memberId) {
  671. return _.pluck(this.members, 'userId').indexOf(memberId);
  672. },
  673. hasMember(memberId) {
  674. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  675. },
  676. hasAdmin(memberId) {
  677. return !!_.findWhere(this.members, {
  678. userId: memberId,
  679. isActive: true,
  680. isAdmin: true,
  681. });
  682. },
  683. hasNoComments(memberId) {
  684. return !!_.findWhere(this.members, {
  685. userId: memberId,
  686. isActive: true,
  687. isAdmin: false,
  688. isNoComments: true,
  689. isWorker: false,
  690. });
  691. },
  692. hasCommentOnly(memberId) {
  693. return !!_.findWhere(this.members, {
  694. userId: memberId,
  695. isActive: true,
  696. isAdmin: false,
  697. isCommentOnly: true,
  698. isWorker: false,
  699. });
  700. },
  701. hasWorker(memberId) {
  702. return !!_.findWhere(this.members, {
  703. userId: memberId,
  704. isActive: true,
  705. isAdmin: false,
  706. isCommentOnly: false,
  707. isWorker: true,
  708. });
  709. },
  710. absoluteUrl() {
  711. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  712. },
  713. originRelativeUrl() {
  714. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  715. },
  716. colorClass() {
  717. return `board-color-${this.color}`;
  718. },
  719. customFields() {
  720. return CustomFields.find(
  721. { boardIds: { $in: [this._id] } },
  722. { sort: { name: 1 } },
  723. );
  724. },
  725. // XXX currently mutations return no value so we have an issue when using addLabel in import
  726. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  727. pushLabel(name, color) {
  728. const _id = Random.id(6);
  729. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  730. return _id;
  731. },
  732. searchBoards(term) {
  733. check(term, Match.OneOf(String, null, undefined));
  734. const query = { boardId: this._id };
  735. query.type = 'cardType-linkedBoard';
  736. query.archived = false;
  737. const projection = { limit: 10, sort: { createdAt: -1 } };
  738. if (term) {
  739. const regex = new RegExp(term, 'i');
  740. query.$or = [{ title: regex }, { description: regex }];
  741. }
  742. return Cards.find(query, projection);
  743. },
  744. searchSwimlanes(term) {
  745. check(term, Match.OneOf(String, null, undefined));
  746. const query = { boardId: this._id };
  747. if (this.isTemplatesBoard()) {
  748. query.type = 'template-swimlane';
  749. query.archived = false;
  750. } else {
  751. query.type = { $nin: ['template-swimlane'] };
  752. }
  753. const projection = { limit: 10, sort: { createdAt: -1 } };
  754. if (term) {
  755. const regex = new RegExp(term, 'i');
  756. query.$or = [{ title: regex }, { description: regex }];
  757. }
  758. return Swimlanes.find(query, projection);
  759. },
  760. searchLists(term) {
  761. check(term, Match.OneOf(String, null, undefined));
  762. const query = { boardId: this._id };
  763. if (this.isTemplatesBoard()) {
  764. query.type = 'template-list';
  765. query.archived = false;
  766. } else {
  767. query.type = { $nin: ['template-list'] };
  768. }
  769. const projection = { limit: 10, sort: { createdAt: -1 } };
  770. if (term) {
  771. const regex = new RegExp(term, 'i');
  772. query.$or = [{ title: regex }, { description: regex }];
  773. }
  774. return Lists.find(query, projection);
  775. },
  776. searchCards(term, excludeLinked) {
  777. check(term, Match.OneOf(String, null, undefined));
  778. const query = { boardId: this._id };
  779. if (excludeLinked) {
  780. query.linkedId = null;
  781. }
  782. if (this.isTemplatesBoard()) {
  783. query.type = 'template-card';
  784. query.archived = false;
  785. } else {
  786. query.type = { $nin: ['template-card'] };
  787. }
  788. const projection = { limit: 10, sort: { createdAt: -1 } };
  789. if (term) {
  790. const regex = new RegExp(term, 'i');
  791. query.$or = [
  792. { title: regex },
  793. { description: regex },
  794. { customFields: { $elemMatch: { value: regex } } },
  795. ];
  796. }
  797. return Cards.find(query, projection);
  798. },
  799. // A board alwasy has another board where it deposits subtasks of thasks
  800. // that belong to itself.
  801. getDefaultSubtasksBoardId() {
  802. if (
  803. this.subtasksDefaultBoardId === null ||
  804. this.subtasksDefaultBoardId === undefined
  805. ) {
  806. this.subtasksDefaultBoardId = Boards.insert({
  807. title: `^${this.title}^`,
  808. permission: this.permission,
  809. members: this.members,
  810. color: this.color,
  811. description: TAPi18n.__('default-subtasks-board', {
  812. board: this.title,
  813. }),
  814. });
  815. Swimlanes.insert({
  816. title: TAPi18n.__('default'),
  817. boardId: this.subtasksDefaultBoardId,
  818. });
  819. Boards.update(this._id, {
  820. $set: {
  821. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  822. },
  823. });
  824. }
  825. return this.subtasksDefaultBoardId;
  826. },
  827. getDefaultSubtasksBoard() {
  828. return Boards.findOne(this.getDefaultSubtasksBoardId());
  829. },
  830. //Date Settings option such as received date, start date and so on.
  831. getDefaultDateSettingsBoardId() {
  832. if (
  833. this.dateSettingsDefaultBoardId === null ||
  834. this.dateSettingsDefaultBoardId === undefined
  835. ) {
  836. this.dateSettingsDefaultBoardId = Boards.insert({
  837. title: `^${this.title}^`,
  838. permission: this.permission,
  839. members: this.members,
  840. color: this.color,
  841. description: TAPi18n.__('default-dates-board', {
  842. board: this.title,
  843. }),
  844. });
  845. Swimlanes.insert({
  846. title: TAPi18n.__('default'),
  847. boardId: this.dateSettingsDefaultBoardId,
  848. });
  849. Boards.update(this._id, {
  850. $set: {
  851. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  852. },
  853. });
  854. }
  855. return this.dateSettingsDefaultBoardId;
  856. },
  857. getDefaultDateSettingsBoard() {
  858. return Boards.findOne(this.getDefaultDateSettingsBoardId());
  859. },
  860. getDefaultSubtasksListId() {
  861. if (
  862. this.subtasksDefaultListId === null ||
  863. this.subtasksDefaultListId === undefined
  864. ) {
  865. this.subtasksDefaultListId = Lists.insert({
  866. title: TAPi18n.__('queue'),
  867. boardId: this._id,
  868. });
  869. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  870. }
  871. return this.subtasksDefaultListId;
  872. },
  873. getDefaultSubtasksList() {
  874. return Lists.findOne(this.getDefaultSubtasksListId());
  875. },
  876. getDefaultDateSettingsListId() {
  877. if (
  878. this.dateSettingsDefaultListId === null ||
  879. this.dateSettingsDefaultListId === undefined
  880. ) {
  881. this.dateSettingsDefaultListId = Lists.insert({
  882. title: TAPi18n.__('queue'),
  883. boardId: this._id,
  884. });
  885. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  886. }
  887. return this.dateSettingsDefaultListId;
  888. },
  889. getDefaultDateSettingsList() {
  890. return Lists.findOne(this.getDefaultDateSettingsListId());
  891. },
  892. getDefaultSwimline() {
  893. let result = Swimlanes.findOne({ boardId: this._id });
  894. if (result === undefined) {
  895. Swimlanes.insert({
  896. title: TAPi18n.__('default'),
  897. boardId: this._id,
  898. });
  899. result = Swimlanes.findOne({ boardId: this._id });
  900. }
  901. return result;
  902. },
  903. cardsDueInBetween(start, end) {
  904. return Cards.find({
  905. boardId: this._id,
  906. dueAt: { $gte: start, $lte: end },
  907. });
  908. },
  909. cardsInInterval(start, end) {
  910. return Cards.find({
  911. boardId: this._id,
  912. $or: [
  913. {
  914. startAt: {
  915. $lte: start,
  916. },
  917. endAt: {
  918. $gte: start,
  919. },
  920. },
  921. {
  922. startAt: {
  923. $lte: end,
  924. },
  925. endAt: {
  926. $gte: end,
  927. },
  928. },
  929. {
  930. startAt: {
  931. $gte: start,
  932. },
  933. endAt: {
  934. $lte: end,
  935. },
  936. },
  937. ],
  938. });
  939. },
  940. isTemplateBoard() {
  941. return this.type === 'template-board';
  942. },
  943. isTemplatesBoard() {
  944. return this.type === 'template-container';
  945. },
  946. });
  947. Boards.mutations({
  948. archive() {
  949. return { $set: { archived: true, archivedAt: new Date() } };
  950. },
  951. restore() {
  952. return { $set: { archived: false } };
  953. },
  954. rename(title) {
  955. return { $set: { title } };
  956. },
  957. setDescription(description) {
  958. return { $set: { description } };
  959. },
  960. setColor(color) {
  961. return { $set: { color } };
  962. },
  963. setVisibility(visibility) {
  964. return { $set: { permission: visibility } };
  965. },
  966. addLabel(name, color) {
  967. // If label with the same name and color already exists we don't want to
  968. // create another one because they would be indistinguishable in the UI
  969. // (they would still have different `_id` but that is not exposed to the
  970. // user).
  971. if (!this.getLabel(name, color)) {
  972. const _id = Random.id(6);
  973. return { $push: { labels: { _id, name, color } } };
  974. }
  975. return {};
  976. },
  977. editLabel(labelId, name, color) {
  978. if (!this.getLabel(name, color)) {
  979. const labelIndex = this.labelIndex(labelId);
  980. return {
  981. $set: {
  982. [`labels.${labelIndex}.name`]: name,
  983. [`labels.${labelIndex}.color`]: color,
  984. },
  985. };
  986. }
  987. return {};
  988. },
  989. removeLabel(labelId) {
  990. return { $pull: { labels: { _id: labelId } } };
  991. },
  992. changeOwnership(fromId, toId) {
  993. const memberIndex = this.memberIndex(fromId);
  994. return {
  995. $set: {
  996. [`members.${memberIndex}.userId`]: toId,
  997. },
  998. };
  999. },
  1000. addMember(memberId) {
  1001. const memberIndex = this.memberIndex(memberId);
  1002. if (memberIndex >= 0) {
  1003. return {
  1004. $set: {
  1005. [`members.${memberIndex}.isActive`]: true,
  1006. },
  1007. };
  1008. }
  1009. return {
  1010. $push: {
  1011. members: {
  1012. userId: memberId,
  1013. isAdmin: false,
  1014. isActive: true,
  1015. isNoComments: false,
  1016. isCommentOnly: false,
  1017. isWorker: false,
  1018. },
  1019. },
  1020. };
  1021. },
  1022. removeMember(memberId) {
  1023. const memberIndex = this.memberIndex(memberId);
  1024. // we do not allow the only one admin to be removed
  1025. const allowRemove =
  1026. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1027. if (!allowRemove) {
  1028. return {
  1029. $set: {
  1030. [`members.${memberIndex}.isActive`]: true,
  1031. },
  1032. };
  1033. }
  1034. return {
  1035. $set: {
  1036. [`members.${memberIndex}.isActive`]: false,
  1037. [`members.${memberIndex}.isAdmin`]: false,
  1038. },
  1039. };
  1040. },
  1041. setMemberPermission(
  1042. memberId,
  1043. isAdmin,
  1044. isNoComments,
  1045. isCommentOnly,
  1046. isWorker,
  1047. currentUserId = Meteor.userId(),
  1048. ) {
  1049. const memberIndex = this.memberIndex(memberId);
  1050. // do not allow change permission of self
  1051. if (memberId === currentUserId) {
  1052. isAdmin = this.members[memberIndex].isAdmin;
  1053. }
  1054. return {
  1055. $set: {
  1056. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1057. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1058. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1059. [`members.${memberIndex}.isWorker`]: isWorker,
  1060. },
  1061. };
  1062. },
  1063. setAllowsSubtasks(allowsSubtasks) {
  1064. return { $set: { allowsSubtasks } };
  1065. },
  1066. setAllowsCreator(allowsCreator) {
  1067. return { $set: { allowsCreator } };
  1068. },
  1069. setAllowsMembers(allowsMembers) {
  1070. return { $set: { allowsMembers } };
  1071. },
  1072. setAllowsChecklists(allowsChecklists) {
  1073. return { $set: { allowsChecklists } };
  1074. },
  1075. setAllowsAssignee(allowsAssignee) {
  1076. return { $set: { allowsAssignee } };
  1077. },
  1078. setAllowsAssignedBy(allowsAssignedBy) {
  1079. return { $set: { allowsAssignedBy } };
  1080. },
  1081. setAllowsRequestedBy(allowsRequestedBy) {
  1082. return { $set: { allowsRequestedBy } };
  1083. },
  1084. setAllowsCardSortingByNumber(allowsCardSortingByNumber) {
  1085. return { $set: { allowsCardSortingByNumber } };
  1086. },
  1087. setAllowsAttachments(allowsAttachments) {
  1088. return { $set: { allowsAttachments } };
  1089. },
  1090. setAllowsLabels(allowsLabels) {
  1091. return { $set: { allowsLabels } };
  1092. },
  1093. setAllowsComments(allowsComments) {
  1094. return { $set: { allowsComments } };
  1095. },
  1096. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1097. return { $set: { allowsDescriptionTitle } };
  1098. },
  1099. setAllowsDescriptionText(allowsDescriptionText) {
  1100. return { $set: { allowsDescriptionText } };
  1101. },
  1102. setAllowsActivities(allowsActivities) {
  1103. return { $set: { allowsActivities } };
  1104. },
  1105. setAllowsReceivedDate(allowsReceivedDate) {
  1106. return { $set: { allowsReceivedDate } };
  1107. },
  1108. setAllowsStartDate(allowsStartDate) {
  1109. return { $set: { allowsStartDate } };
  1110. },
  1111. setAllowsEndDate(allowsEndDate) {
  1112. return { $set: { allowsEndDate } };
  1113. },
  1114. setAllowsDueDate(allowsDueDate) {
  1115. return { $set: { allowsDueDate } };
  1116. },
  1117. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1118. return { $set: { subtasksDefaultBoardId } };
  1119. },
  1120. setSubtasksDefaultListId(subtasksDefaultListId) {
  1121. return { $set: { subtasksDefaultListId } };
  1122. },
  1123. setPresentParentTask(presentParentTask) {
  1124. return { $set: { presentParentTask } };
  1125. },
  1126. move(sortIndex) {
  1127. return { $set: { sort: sortIndex } };
  1128. },
  1129. });
  1130. function boardRemover(userId, doc) {
  1131. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1132. element => {
  1133. element.remove({ boardId: doc._id });
  1134. },
  1135. );
  1136. }
  1137. Boards.uniqueTitle = title => {
  1138. const m = title.match(
  1139. new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
  1140. );
  1141. const base = escapeForRegex(m.groups.title);
  1142. let num = 0;
  1143. Boards.find({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) }).forEach(
  1144. board => {
  1145. const m = board.title.match(
  1146. new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
  1147. );
  1148. if (m) {
  1149. const n = parseInt(m.groups.num, 10);
  1150. num = num < n ? n : num;
  1151. }
  1152. },
  1153. );
  1154. if (num > 0) {
  1155. return `${base} [${num + 1}]`;
  1156. }
  1157. return title;
  1158. };
  1159. Boards.userSearch = (
  1160. userId,
  1161. selector = {},
  1162. projection = {},
  1163. // includeArchived = false,
  1164. ) => {
  1165. // if (!includeArchived) {
  1166. // selector.archived = false;
  1167. // }
  1168. selector.$or = [{ permission: 'public' }];
  1169. if (userId) {
  1170. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1171. }
  1172. return Boards.find(selector, projection);
  1173. };
  1174. Boards.userBoards = (userId, archived = false, selector = {}) => {
  1175. if (typeof archived === 'boolean') {
  1176. selector.archived = archived;
  1177. }
  1178. if (!selector.type) {
  1179. selector.type = 'board';
  1180. }
  1181. selector.$or = [{ permission: 'public' }];
  1182. if (userId) {
  1183. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1184. }
  1185. return Boards.find(selector);
  1186. };
  1187. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1188. return Boards.userBoards(userId, archived, selector).map(board => {
  1189. return board._id;
  1190. });
  1191. };
  1192. Boards.colorMap = () => {
  1193. const colors = {};
  1194. for (const color of Boards.labelColors()) {
  1195. colors[TAPi18n.__(`color-${color}`)] = color;
  1196. }
  1197. return colors;
  1198. };
  1199. Boards.labelColors = () => {
  1200. return ALLOWED_COLORS;
  1201. };
  1202. if (Meteor.isServer) {
  1203. Boards.allow({
  1204. insert: Meteor.userId,
  1205. update: allowIsBoardAdmin,
  1206. remove: allowIsBoardAdmin,
  1207. fetch: ['members'],
  1208. });
  1209. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1210. Boards.allow({
  1211. update(userId, board, fieldNames) {
  1212. return _.contains(fieldNames, 'sort');
  1213. },
  1214. fetch: [],
  1215. });
  1216. // The number of users that have starred this board is managed by trusted code
  1217. // and the user is not allowed to update it
  1218. Boards.deny({
  1219. update(userId, board, fieldNames) {
  1220. return _.contains(fieldNames, 'stars');
  1221. },
  1222. fetch: [],
  1223. });
  1224. // We can't remove a member if it is the last administrator
  1225. Boards.deny({
  1226. update(userId, doc, fieldNames, modifier) {
  1227. if (!_.contains(fieldNames, 'members')) return false;
  1228. // We only care in case of a $pull operation, ie remove a member
  1229. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1230. // If there is more than one admin, it's ok to remove anyone
  1231. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1232. .length;
  1233. if (nbAdmins > 1) return false;
  1234. // If all the previous conditions were verified, we can't remove
  1235. // a user if it's an admin
  1236. const removedMemberId = modifier.$pull.members.userId;
  1237. return Boolean(
  1238. _.findWhere(doc.members, {
  1239. userId: removedMemberId,
  1240. isAdmin: true,
  1241. }),
  1242. );
  1243. },
  1244. fetch: ['members'],
  1245. });
  1246. Meteor.methods({
  1247. quitBoard(boardId) {
  1248. check(boardId, String);
  1249. const board = Boards.findOne(boardId);
  1250. if (board) {
  1251. const userId = Meteor.userId();
  1252. const index = board.memberIndex(userId);
  1253. if (index >= 0) {
  1254. board.removeMember(userId);
  1255. return true;
  1256. } else throw new Meteor.Error('error-board-notAMember');
  1257. } else throw new Meteor.Error('error-board-doesNotExist');
  1258. },
  1259. acceptInvite(boardId) {
  1260. check(boardId, String);
  1261. const board = Boards.findOne(boardId);
  1262. if (!board) {
  1263. throw new Meteor.Error('error-board-doesNotExist');
  1264. }
  1265. Meteor.users.update(Meteor.userId(), {
  1266. $pull: {
  1267. 'profile.invitedBoards': boardId,
  1268. },
  1269. });
  1270. },
  1271. myLabelNames() {
  1272. let names = [];
  1273. Boards.userBoards(Meteor.userId()).forEach(board => {
  1274. names = names.concat(
  1275. board.labels
  1276. .filter(label => !!label.name)
  1277. .map(label => {
  1278. return label.name;
  1279. }),
  1280. );
  1281. });
  1282. return _.uniq(names).sort();
  1283. },
  1284. myBoardNames() {
  1285. return _.uniq(
  1286. Boards.userBoards(Meteor.userId()).map(board => {
  1287. return board.title;
  1288. }),
  1289. ).sort();
  1290. },
  1291. });
  1292. Meteor.methods({
  1293. archiveBoard(boardId) {
  1294. check(boardId, String);
  1295. const board = Boards.findOne(boardId);
  1296. if (board) {
  1297. const userId = Meteor.userId();
  1298. const index = board.memberIndex(userId);
  1299. if (index >= 0) {
  1300. board.archive();
  1301. return true;
  1302. } else throw new Meteor.Error('error-board-notAMember');
  1303. } else throw new Meteor.Error('error-board-doesNotExist');
  1304. },
  1305. });
  1306. }
  1307. // Insert new board at last position in sort order.
  1308. Boards.before.insert((userId, doc) => {
  1309. const lastBoard = Boards.findOne(
  1310. { sort: { $exists: true } },
  1311. { sort: { sort: -1 } },
  1312. );
  1313. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1314. doc.sort = lastBoard.sort + 1;
  1315. }
  1316. });
  1317. if (Meteor.isServer) {
  1318. // Let MongoDB ensure that a member is not included twice in the same board
  1319. Meteor.startup(() => {
  1320. Boards._collection._ensureIndex({ modifiedAt: -1 });
  1321. Boards._collection._ensureIndex(
  1322. {
  1323. _id: 1,
  1324. 'members.userId': 1,
  1325. },
  1326. { unique: true },
  1327. );
  1328. Boards._collection._ensureIndex({ 'members.userId': 1 });
  1329. });
  1330. // Genesis: the first activity of the newly created board
  1331. Boards.after.insert((userId, doc) => {
  1332. Activities.insert({
  1333. userId,
  1334. type: 'board',
  1335. activityTypeId: doc._id,
  1336. activityType: 'createBoard',
  1337. boardId: doc._id,
  1338. });
  1339. });
  1340. // If the user remove one label from a board, we cant to remove reference of
  1341. // this label in any card of this board.
  1342. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1343. if (
  1344. !_.contains(fieldNames, 'labels') ||
  1345. !modifier.$pull ||
  1346. !modifier.$pull.labels ||
  1347. !modifier.$pull.labels._id
  1348. ) {
  1349. return;
  1350. }
  1351. const removedLabelId = modifier.$pull.labels._id;
  1352. Cards.update(
  1353. { boardId: doc._id },
  1354. {
  1355. $pull: {
  1356. labelIds: removedLabelId,
  1357. },
  1358. },
  1359. { multi: true },
  1360. );
  1361. });
  1362. const foreachRemovedMember = (doc, modifier, callback) => {
  1363. Object.keys(modifier).forEach(set => {
  1364. if (modifier[set] !== false) {
  1365. return;
  1366. }
  1367. const parts = set.split('.');
  1368. if (
  1369. parts.length === 3 &&
  1370. parts[0] === 'members' &&
  1371. parts[2] === 'isActive'
  1372. ) {
  1373. callback(doc.members[parts[1]].userId);
  1374. }
  1375. });
  1376. };
  1377. // Remove a member from all objects of the board before leaving the board
  1378. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1379. if (!_.contains(fieldNames, 'members')) {
  1380. return;
  1381. }
  1382. if (modifier.$set) {
  1383. const boardId = doc._id;
  1384. foreachRemovedMember(doc, modifier.$set, memberId => {
  1385. Cards.update(
  1386. { boardId },
  1387. {
  1388. $pull: {
  1389. members: memberId,
  1390. watchers: memberId,
  1391. },
  1392. },
  1393. { multi: true },
  1394. );
  1395. Lists.update(
  1396. { boardId },
  1397. {
  1398. $pull: {
  1399. watchers: memberId,
  1400. },
  1401. },
  1402. { multi: true },
  1403. );
  1404. const board = Boards._transform(doc);
  1405. board.setWatcher(memberId, false);
  1406. // Remove board from users starred list
  1407. if (!board.isPublic()) {
  1408. Users.update(memberId, {
  1409. $pull: {
  1410. 'profile.starredBoards': boardId,
  1411. },
  1412. });
  1413. }
  1414. });
  1415. }
  1416. });
  1417. Boards.before.remove((userId, doc) => {
  1418. boardRemover(userId, doc);
  1419. // Add removeBoard activity to keep it
  1420. Activities.insert({
  1421. userId,
  1422. type: 'board',
  1423. activityTypeId: doc._id,
  1424. activityType: 'removeBoard',
  1425. boardId: doc._id,
  1426. });
  1427. });
  1428. // Add a new activity if we add or remove a member to the board
  1429. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1430. if (!_.contains(fieldNames, 'members')) {
  1431. return;
  1432. }
  1433. // Say hello to the new member
  1434. if (modifier.$push && modifier.$push.members) {
  1435. const memberId = modifier.$push.members.userId;
  1436. Activities.insert({
  1437. userId,
  1438. memberId,
  1439. type: 'member',
  1440. activityType: 'addBoardMember',
  1441. boardId: doc._id,
  1442. });
  1443. }
  1444. // Say goodbye to the former member
  1445. if (modifier.$set) {
  1446. foreachRemovedMember(doc, modifier.$set, memberId => {
  1447. Activities.insert({
  1448. userId,
  1449. memberId,
  1450. type: 'member',
  1451. activityType: 'removeBoardMember',
  1452. boardId: doc._id,
  1453. });
  1454. });
  1455. }
  1456. });
  1457. }
  1458. //BOARDS REST API
  1459. if (Meteor.isServer) {
  1460. /**
  1461. * @operation get_boards_from_user
  1462. * @summary Get all boards attached to a user
  1463. *
  1464. * @param {string} userId the ID of the user to retrieve the data
  1465. * @return_type [{_id: string,
  1466. title: string}]
  1467. */
  1468. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1469. try {
  1470. Authentication.checkLoggedIn(req.userId);
  1471. const paramUserId = req.params.userId;
  1472. // A normal user should be able to see their own boards,
  1473. // admins can access boards of any user
  1474. Authentication.checkAdminOrCondition(
  1475. req.userId,
  1476. req.userId === paramUserId,
  1477. );
  1478. const data = Boards.find(
  1479. {
  1480. archived: false,
  1481. 'members.userId': paramUserId,
  1482. },
  1483. {
  1484. sort: { sort: 1 /* boards default sorting */ },
  1485. },
  1486. ).map(function(board) {
  1487. return {
  1488. _id: board._id,
  1489. title: board.title,
  1490. };
  1491. });
  1492. JsonRoutes.sendResult(res, { code: 200, data });
  1493. } catch (error) {
  1494. JsonRoutes.sendResult(res, {
  1495. code: 200,
  1496. data: error,
  1497. });
  1498. }
  1499. });
  1500. /**
  1501. * @operation get_public_boards
  1502. * @summary Get all public boards
  1503. *
  1504. * @return_type [{_id: string,
  1505. title: string}]
  1506. */
  1507. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1508. try {
  1509. Authentication.checkUserId(req.userId);
  1510. JsonRoutes.sendResult(res, {
  1511. code: 200,
  1512. data: Boards.find(
  1513. { permission: 'public' },
  1514. {
  1515. sort: { sort: 1 /* boards default sorting */ },
  1516. },
  1517. ).map(function(doc) {
  1518. return {
  1519. _id: doc._id,
  1520. title: doc.title,
  1521. };
  1522. }),
  1523. });
  1524. } catch (error) {
  1525. JsonRoutes.sendResult(res, {
  1526. code: 200,
  1527. data: error,
  1528. });
  1529. }
  1530. });
  1531. /**
  1532. * @operation get_boards_count
  1533. * @summary Get public and private boards count
  1534. *
  1535. * @return_type {private: integer, public: integer}
  1536. */
  1537. JsonRoutes.add('GET', '/api/boards_count', function(req, res) {
  1538. try {
  1539. Authentication.checkUserId(req.userId);
  1540. JsonRoutes.sendResult(res, {
  1541. code: 200,
  1542. data: {
  1543. private: Boards.find({ permission: 'private' }).count(),
  1544. public: Boards.find({ permission: 'public' }).count(),
  1545. },
  1546. });
  1547. } catch (error) {
  1548. JsonRoutes.sendResult(res, {
  1549. code: 200,
  1550. data: error,
  1551. });
  1552. }
  1553. });
  1554. /**
  1555. * @operation get_board
  1556. * @summary Get the board with that particular ID
  1557. *
  1558. * @param {string} boardId the ID of the board to retrieve the data
  1559. * @return_type Boards
  1560. */
  1561. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1562. try {
  1563. const id = req.params.boardId;
  1564. Authentication.checkBoardAccess(req.userId, id);
  1565. JsonRoutes.sendResult(res, {
  1566. code: 200,
  1567. data: Boards.findOne({ _id: id }),
  1568. });
  1569. } catch (error) {
  1570. JsonRoutes.sendResult(res, {
  1571. code: 200,
  1572. data: error,
  1573. });
  1574. }
  1575. });
  1576. /**
  1577. * @operation new_board
  1578. * @summary Create a board
  1579. *
  1580. * @description This allows to create a board.
  1581. *
  1582. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1583. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1584. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1585. *
  1586. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1587. *
  1588. * @param {string} title the new title of the board
  1589. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1590. * (Not username or email)
  1591. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1592. * @param {boolean} [isActive] is the board active (default true)
  1593. * @param {boolean} [isNoComments] disable comments (default false)
  1594. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1595. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1596. * @param {string} [permission] "private" board <== Set to "public" if you
  1597. * want public Wekan board
  1598. * @param {string} [color] the color of the board
  1599. *
  1600. * @return_type {_id: string,
  1601. defaultSwimlaneId: string}
  1602. */
  1603. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1604. try {
  1605. Authentication.checkUserId(req.userId);
  1606. const id = Boards.insert({
  1607. title: req.body.title,
  1608. members: [
  1609. {
  1610. userId: req.body.owner,
  1611. isAdmin: req.body.isAdmin || true,
  1612. isActive: req.body.isActive || true,
  1613. isNoComments: req.body.isNoComments || false,
  1614. isCommentOnly: req.body.isCommentOnly || false,
  1615. isWorker: req.body.isWorker || false,
  1616. },
  1617. ],
  1618. permission: req.body.permission || 'private',
  1619. color: req.body.color || 'belize',
  1620. });
  1621. const swimlaneId = Swimlanes.insert({
  1622. title: TAPi18n.__('default'),
  1623. boardId: id,
  1624. });
  1625. JsonRoutes.sendResult(res, {
  1626. code: 200,
  1627. data: {
  1628. _id: id,
  1629. defaultSwimlaneId: swimlaneId,
  1630. },
  1631. });
  1632. } catch (error) {
  1633. JsonRoutes.sendResult(res, {
  1634. code: 200,
  1635. data: error,
  1636. });
  1637. }
  1638. });
  1639. /**
  1640. * @operation delete_board
  1641. * @summary Delete a board
  1642. *
  1643. * @param {string} boardId the ID of the board
  1644. */
  1645. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1646. try {
  1647. Authentication.checkUserId(req.userId);
  1648. const id = req.params.boardId;
  1649. Boards.remove({ _id: id });
  1650. JsonRoutes.sendResult(res, {
  1651. code: 200,
  1652. data: {
  1653. _id: id,
  1654. },
  1655. });
  1656. } catch (error) {
  1657. JsonRoutes.sendResult(res, {
  1658. code: 200,
  1659. data: error,
  1660. });
  1661. }
  1662. });
  1663. /**
  1664. * @operation add_board_label
  1665. * @summary Add a label to a board
  1666. *
  1667. * @description If the board doesn't have the name/color label, this function
  1668. * adds the label to the board.
  1669. *
  1670. * @param {string} boardId the board
  1671. * @param {string} color the color of the new label
  1672. * @param {string} name the name of the new label
  1673. *
  1674. * @return_type string
  1675. */
  1676. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1677. Authentication.checkUserId(req.userId);
  1678. const id = req.params.boardId;
  1679. try {
  1680. if (req.body.hasOwnProperty('label')) {
  1681. const board = Boards.findOne({ _id: id });
  1682. const color = req.body.label.color;
  1683. const name = req.body.label.name;
  1684. const labelId = Random.id(6);
  1685. if (!board.getLabel(name, color)) {
  1686. Boards.direct.update(
  1687. { _id: id },
  1688. { $push: { labels: { _id: labelId, name, color } } },
  1689. );
  1690. JsonRoutes.sendResult(res, {
  1691. code: 200,
  1692. data: labelId,
  1693. });
  1694. } else {
  1695. JsonRoutes.sendResult(res, {
  1696. code: 200,
  1697. });
  1698. }
  1699. }
  1700. } catch (error) {
  1701. JsonRoutes.sendResult(res, {
  1702. data: error,
  1703. });
  1704. }
  1705. });
  1706. /**
  1707. * @operation set_board_member_permission
  1708. * @tag Users
  1709. * @summary Change the permission of a member of a board
  1710. *
  1711. * @param {string} boardId the ID of the board that we are changing
  1712. * @param {string} memberId the ID of the user to change permissions
  1713. * @param {boolean} isAdmin admin capability
  1714. * @param {boolean} isNoComments NoComments capability
  1715. * @param {boolean} isCommentOnly CommentsOnly capability
  1716. * @param {boolean} isWorker Worker capability
  1717. */
  1718. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1719. req,
  1720. res,
  1721. ) {
  1722. try {
  1723. const boardId = req.params.boardId;
  1724. const memberId = req.params.memberId;
  1725. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  1726. Authentication.checkBoardAccess(req.userId, boardId);
  1727. const board = Boards.findOne({ _id: boardId });
  1728. function isTrue(data) {
  1729. try {
  1730. return data.toLowerCase() === 'true';
  1731. } catch (error) {
  1732. return data;
  1733. }
  1734. }
  1735. const query = board.setMemberPermission(
  1736. memberId,
  1737. isTrue(isAdmin),
  1738. isTrue(isNoComments),
  1739. isTrue(isCommentOnly),
  1740. isTrue(isWorker),
  1741. req.userId,
  1742. );
  1743. JsonRoutes.sendResult(res, {
  1744. code: 200,
  1745. data: query,
  1746. });
  1747. } catch (error) {
  1748. JsonRoutes.sendResult(res, {
  1749. code: 200,
  1750. data: error,
  1751. });
  1752. }
  1753. });
  1754. //ATTACHMENTS REST API
  1755. /**
  1756. * @operation get_board_attachments
  1757. * @summary Get the list of attachments of a board
  1758. *
  1759. * @param {string} boardId the board ID
  1760. * @return_type [{attachmentId: string,
  1761. * attachmentName: string,
  1762. * attachmentType: string,
  1763. * cardId: string,
  1764. * listId: string,
  1765. * swimlaneId: string}]
  1766. */
  1767. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  1768. const paramBoardId = req.params.boardId;
  1769. Authentication.checkBoardAccess(req.userId, paramBoardId);
  1770. JsonRoutes.sendResult(res, {
  1771. code: 200,
  1772. data: Attachments.files
  1773. .find({ boardId: paramBoardId }, { fields: { boardId: 0 } })
  1774. .map(function(doc) {
  1775. return {
  1776. attachmentId: doc._id,
  1777. attachmentName: doc.original.name,
  1778. attachmentType: doc.original.type,
  1779. url: FlowRouter.url(doc.url()),
  1780. urlDownload: `${FlowRouter.url(doc.url())}?download=true&token=`,
  1781. cardId: doc.cardId,
  1782. listId: doc.listId,
  1783. swimlaneId: doc.swimlaneId,
  1784. };
  1785. }),
  1786. });
  1787. });
  1788. }
  1789. export default Boards;