boards.js 46 KB

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