boards.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  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. const _id = Boards.insert(this);
  492. // Copy all swimlanes in board
  493. Swimlanes.find({
  494. boardId: oldId,
  495. archived: false,
  496. }).forEach(swimlane => {
  497. swimlane.type = 'swimlane';
  498. swimlane.copy(_id);
  499. });
  500. // copy custom field definitions
  501. const cfMap = {};
  502. CustomFields.find({ boardIds: oldId }).forEach(cf => {
  503. const id = cf._id;
  504. delete cf._id;
  505. cf.boardIds = [_id];
  506. cfMap[id] = CustomFields.insert(cf);
  507. });
  508. Cards.find({ boardId: _id }).forEach(card => {
  509. Cards.update(card._id, {
  510. $set: {
  511. customFields: card.customFields.map(cf => {
  512. cf._id = cfMap[cf._id];
  513. return cf;
  514. }),
  515. },
  516. });
  517. });
  518. // copy rules, actions, and triggers
  519. const actionsMap = {};
  520. Actions.find({ boardId: oldId }).forEach(action => {
  521. const id = action._id;
  522. delete action._id;
  523. action.boardId = _id;
  524. actionsMap[id] = Actions.insert(action);
  525. });
  526. const triggersMap = {};
  527. Triggers.find({ boardId: oldId }).forEach(trigger => {
  528. const id = trigger._id;
  529. delete trigger._id;
  530. trigger.boardId = _id;
  531. triggersMap[id] = Triggers.insert(trigger);
  532. });
  533. Rules.find({ boardId: oldId }).forEach(rule => {
  534. delete rule._id;
  535. rule.boardId = _id;
  536. rule.actionId = actionsMap[rule.actionId];
  537. rule.triggerId = triggersMap[rule.triggerId];
  538. Rules.insert(rule);
  539. });
  540. },
  541. /**
  542. * Return a unique title based on the current title
  543. *
  544. * @returns {string|null}
  545. */
  546. copyTitle() {
  547. const m = this.title.match(/^(?<title>.*?)\s*(\[(?<num>\d+)]\s*$|\s*$)/);
  548. const title = escapeForRegex(m.groups.title);
  549. let num = 0;
  550. Boards.find({ title: new RegExp(`^${title}\\s*\\[\\d+]\\s*$`) }).forEach(
  551. board => {
  552. const m = board.title.match(/^(?<title>.*?)\s*\[(?<num>\d+)]\s*$/);
  553. if (m) {
  554. const n = parseInt(m.groups.num, 10);
  555. num = num < n ? n : num;
  556. }
  557. },
  558. );
  559. return `${title} [${num + 1}]`;
  560. },
  561. /**
  562. * Is supplied user authorized to view this board?
  563. */
  564. isVisibleBy(user) {
  565. if (this.isPublic()) {
  566. // public boards are visible to everyone
  567. return true;
  568. } else {
  569. // otherwise you have to be logged-in and active member
  570. return user && this.isActiveMember(user._id);
  571. }
  572. },
  573. /**
  574. * Is the user one of the active members of the board?
  575. *
  576. * @param userId
  577. * @returns {boolean} the member that matches, or undefined/false
  578. */
  579. isActiveMember(userId) {
  580. if (userId) {
  581. return this.members.find(
  582. member => member.userId === userId && member.isActive,
  583. );
  584. } else {
  585. return false;
  586. }
  587. },
  588. isPublic() {
  589. return this.permission === 'public';
  590. },
  591. cards() {
  592. return Cards.find(
  593. { boardId: this._id, archived: false },
  594. { sort: { title: 1 } },
  595. );
  596. },
  597. lists() {
  598. //currentUser = Meteor.user();
  599. //if (currentUser) {
  600. // enabled = Meteor.user().hasSortBy();
  601. //}
  602. //return enabled ? this.newestLists() : this.draggableLists();
  603. return this.draggableLists();
  604. },
  605. newestLists() {
  606. // sorted lists from newest to the oldest, by its creation date or its cards' last modification date
  607. const value = Meteor.user()._getListSortBy();
  608. const sortKey = { starred: -1, [value[0]]: value[1] }; // [["starred",-1],value];
  609. return Lists.find(
  610. {
  611. boardId: this._id,
  612. archived: false,
  613. },
  614. { sort: sortKey },
  615. );
  616. },
  617. draggableLists() {
  618. return Lists.find({ boardId: this._id }, { sort: { sort: 1 } });
  619. },
  620. nullSortLists() {
  621. return Lists.find({
  622. boardId: this._id,
  623. archived: false,
  624. sort: { $eq: null },
  625. });
  626. },
  627. swimlanes() {
  628. return Swimlanes.find(
  629. { boardId: this._id, archived: false },
  630. { sort: { sort: 1 } },
  631. );
  632. },
  633. nextSwimlane(swimlane) {
  634. return Swimlanes.findOne(
  635. {
  636. boardId: this._id,
  637. archived: false,
  638. sort: { $gte: swimlane.sort },
  639. _id: { $ne: swimlane._id },
  640. },
  641. {
  642. sort: { sort: 1 },
  643. },
  644. );
  645. },
  646. nullSortSwimlanes() {
  647. return Swimlanes.find({
  648. boardId: this._id,
  649. archived: false,
  650. sort: { $eq: null },
  651. });
  652. },
  653. hasOvertimeCards() {
  654. const card = Cards.findOne({
  655. isOvertime: true,
  656. boardId: this._id,
  657. archived: false,
  658. });
  659. return card !== undefined;
  660. },
  661. hasSpentTimeCards() {
  662. const card = Cards.findOne({
  663. spentTime: { $gt: 0 },
  664. boardId: this._id,
  665. archived: false,
  666. });
  667. return card !== undefined;
  668. },
  669. activities() {
  670. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  671. },
  672. activeMembers() {
  673. return _.where(this.members, { isActive: true });
  674. },
  675. activeAdmins() {
  676. return _.where(this.members, { isActive: true, isAdmin: true });
  677. },
  678. memberUsers() {
  679. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  680. },
  681. getLabel(name, color) {
  682. return _.findWhere(this.labels, { name, color });
  683. },
  684. getLabelById(labelId) {
  685. return _.findWhere(this.labels, { _id: labelId });
  686. },
  687. labelIndex(labelId) {
  688. return _.pluck(this.labels, '_id').indexOf(labelId);
  689. },
  690. memberIndex(memberId) {
  691. return _.pluck(this.members, 'userId').indexOf(memberId);
  692. },
  693. hasMember(memberId) {
  694. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  695. },
  696. hasAdmin(memberId) {
  697. return !!_.findWhere(this.members, {
  698. userId: memberId,
  699. isActive: true,
  700. isAdmin: true,
  701. });
  702. },
  703. hasNoComments(memberId) {
  704. return !!_.findWhere(this.members, {
  705. userId: memberId,
  706. isActive: true,
  707. isAdmin: false,
  708. isNoComments: true,
  709. isWorker: false,
  710. });
  711. },
  712. hasCommentOnly(memberId) {
  713. return !!_.findWhere(this.members, {
  714. userId: memberId,
  715. isActive: true,
  716. isAdmin: false,
  717. isCommentOnly: true,
  718. isWorker: false,
  719. });
  720. },
  721. hasWorker(memberId) {
  722. return !!_.findWhere(this.members, {
  723. userId: memberId,
  724. isActive: true,
  725. isAdmin: false,
  726. isCommentOnly: false,
  727. isWorker: true,
  728. });
  729. },
  730. absoluteUrl() {
  731. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  732. },
  733. colorClass() {
  734. return `board-color-${this.color}`;
  735. },
  736. customFields() {
  737. return CustomFields.find(
  738. { boardIds: { $in: [this._id] } },
  739. { sort: { name: 1 } },
  740. );
  741. },
  742. // XXX currently mutations return no value so we have an issue when using addLabel in import
  743. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  744. pushLabel(name, color) {
  745. const _id = Random.id(6);
  746. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  747. return _id;
  748. },
  749. searchBoards(term) {
  750. check(term, Match.OneOf(String, null, undefined));
  751. const query = { boardId: this._id };
  752. query.type = 'cardType-linkedBoard';
  753. query.archived = false;
  754. const projection = { limit: 10, sort: { createdAt: -1 } };
  755. if (term) {
  756. const regex = new RegExp(term, 'i');
  757. query.$or = [{ title: regex }, { description: regex }];
  758. }
  759. return Cards.find(query, projection);
  760. },
  761. searchSwimlanes(term) {
  762. check(term, Match.OneOf(String, null, undefined));
  763. const query = { boardId: this._id };
  764. if (this.isTemplatesBoard()) {
  765. query.type = 'template-swimlane';
  766. query.archived = false;
  767. } else {
  768. query.type = { $nin: ['template-swimlane'] };
  769. }
  770. const projection = { limit: 10, sort: { createdAt: -1 } };
  771. if (term) {
  772. const regex = new RegExp(term, 'i');
  773. query.$or = [{ title: regex }, { description: regex }];
  774. }
  775. return Swimlanes.find(query, projection);
  776. },
  777. searchLists(term) {
  778. check(term, Match.OneOf(String, null, undefined));
  779. const query = { boardId: this._id };
  780. if (this.isTemplatesBoard()) {
  781. query.type = 'template-list';
  782. query.archived = false;
  783. } else {
  784. query.type = { $nin: ['template-list'] };
  785. }
  786. const projection = { limit: 10, sort: { createdAt: -1 } };
  787. if (term) {
  788. const regex = new RegExp(term, 'i');
  789. query.$or = [{ title: regex }, { description: regex }];
  790. }
  791. return Lists.find(query, projection);
  792. },
  793. searchCards(term, excludeLinked) {
  794. check(term, Match.OneOf(String, null, undefined));
  795. const query = { boardId: this._id };
  796. if (excludeLinked) {
  797. query.linkedId = null;
  798. }
  799. if (this.isTemplatesBoard()) {
  800. query.type = 'template-card';
  801. query.archived = false;
  802. } else {
  803. query.type = { $nin: ['template-card'] };
  804. }
  805. const projection = { limit: 10, sort: { createdAt: -1 } };
  806. if (term) {
  807. const regex = new RegExp(term, 'i');
  808. query.$or = [
  809. { title: regex },
  810. { description: regex },
  811. { customFields: { $elemMatch: { value: regex } } },
  812. ];
  813. }
  814. return Cards.find(query, projection);
  815. },
  816. // A board alwasy has another board where it deposits subtasks of thasks
  817. // that belong to itself.
  818. getDefaultSubtasksBoardId() {
  819. if (
  820. this.subtasksDefaultBoardId === null ||
  821. this.subtasksDefaultBoardId === undefined
  822. ) {
  823. this.subtasksDefaultBoardId = Boards.insert({
  824. title: `^${this.title}^`,
  825. permission: this.permission,
  826. members: this.members,
  827. color: this.color,
  828. description: TAPi18n.__('default-subtasks-board', {
  829. board: this.title,
  830. }),
  831. });
  832. Swimlanes.insert({
  833. title: TAPi18n.__('default'),
  834. boardId: this.subtasksDefaultBoardId,
  835. });
  836. Boards.update(this._id, {
  837. $set: {
  838. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  839. },
  840. });
  841. }
  842. return this.subtasksDefaultBoardId;
  843. },
  844. getDefaultSubtasksBoard() {
  845. return Boards.findOne(this.getDefaultSubtasksBoardId());
  846. },
  847. //Date Settings option such as received date, start date and so on.
  848. getDefaultDateSettingsBoardId() {
  849. if (
  850. this.dateSettingsDefaultBoardId === null ||
  851. this.dateSettingsDefaultBoardId === undefined
  852. ) {
  853. this.dateSettingsDefaultBoardId = Boards.insert({
  854. title: `^${this.title}^`,
  855. permission: this.permission,
  856. members: this.members,
  857. color: this.color,
  858. description: TAPi18n.__('default-dates-board', {
  859. board: this.title,
  860. }),
  861. });
  862. Swimlanes.insert({
  863. title: TAPi18n.__('default'),
  864. boardId: this.dateSettingsDefaultBoardId,
  865. });
  866. Boards.update(this._id, {
  867. $set: {
  868. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  869. },
  870. });
  871. }
  872. return this.dateSettingsDefaultBoardId;
  873. },
  874. getDefaultDateSettingsBoard() {
  875. return Boards.findOne(this.getDefaultDateSettingsBoardId());
  876. },
  877. getDefaultSubtasksListId() {
  878. if (
  879. this.subtasksDefaultListId === null ||
  880. this.subtasksDefaultListId === undefined
  881. ) {
  882. this.subtasksDefaultListId = Lists.insert({
  883. title: TAPi18n.__('queue'),
  884. boardId: this._id,
  885. });
  886. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  887. }
  888. return this.subtasksDefaultListId;
  889. },
  890. getDefaultSubtasksList() {
  891. return Lists.findOne(this.getDefaultSubtasksListId());
  892. },
  893. getDefaultDateSettingsListId() {
  894. if (
  895. this.dateSettingsDefaultListId === null ||
  896. this.dateSettingsDefaultListId === undefined
  897. ) {
  898. this.dateSettingsDefaultListId = Lists.insert({
  899. title: TAPi18n.__('queue'),
  900. boardId: this._id,
  901. });
  902. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  903. }
  904. return this.dateSettingsDefaultListId;
  905. },
  906. getDefaultDateSettingsList() {
  907. return Lists.findOne(this.getDefaultDateSettingsListId());
  908. },
  909. getDefaultSwimline() {
  910. let result = Swimlanes.findOne({ boardId: this._id });
  911. if (result === undefined) {
  912. Swimlanes.insert({
  913. title: TAPi18n.__('default'),
  914. boardId: this._id,
  915. });
  916. result = Swimlanes.findOne({ boardId: this._id });
  917. }
  918. return result;
  919. },
  920. cardsDueInBetween(start, end) {
  921. return Cards.find({
  922. boardId: this._id,
  923. dueAt: { $gte: start, $lte: end },
  924. });
  925. },
  926. cardsInInterval(start, end) {
  927. return Cards.find({
  928. boardId: this._id,
  929. $or: [
  930. {
  931. startAt: {
  932. $lte: start,
  933. },
  934. endAt: {
  935. $gte: start,
  936. },
  937. },
  938. {
  939. startAt: {
  940. $lte: end,
  941. },
  942. endAt: {
  943. $gte: end,
  944. },
  945. },
  946. {
  947. startAt: {
  948. $gte: start,
  949. },
  950. endAt: {
  951. $lte: end,
  952. },
  953. },
  954. ],
  955. });
  956. },
  957. isTemplateBoard() {
  958. return this.type === 'template-board';
  959. },
  960. isTemplatesBoard() {
  961. return this.type === 'template-container';
  962. },
  963. });
  964. Boards.mutations({
  965. archive() {
  966. return { $set: { archived: true } };
  967. },
  968. restore() {
  969. return { $set: { archived: false } };
  970. },
  971. rename(title) {
  972. return { $set: { title } };
  973. },
  974. setDescription(description) {
  975. return { $set: { description } };
  976. },
  977. setColor(color) {
  978. return { $set: { color } };
  979. },
  980. setVisibility(visibility) {
  981. return { $set: { permission: visibility } };
  982. },
  983. addLabel(name, color) {
  984. // If label with the same name and color already exists we don't want to
  985. // create another one because they would be indistinguishable in the UI
  986. // (they would still have different `_id` but that is not exposed to the
  987. // user).
  988. if (!this.getLabel(name, color)) {
  989. const _id = Random.id(6);
  990. return { $push: { labels: { _id, name, color } } };
  991. }
  992. return {};
  993. },
  994. editLabel(labelId, name, color) {
  995. if (!this.getLabel(name, color)) {
  996. const labelIndex = this.labelIndex(labelId);
  997. return {
  998. $set: {
  999. [`labels.${labelIndex}.name`]: name,
  1000. [`labels.${labelIndex}.color`]: color,
  1001. },
  1002. };
  1003. }
  1004. return {};
  1005. },
  1006. removeLabel(labelId) {
  1007. return { $pull: { labels: { _id: labelId } } };
  1008. },
  1009. changeOwnership(fromId, toId) {
  1010. const memberIndex = this.memberIndex(fromId);
  1011. return {
  1012. $set: {
  1013. [`members.${memberIndex}.userId`]: toId,
  1014. },
  1015. };
  1016. },
  1017. addMember(memberId) {
  1018. const memberIndex = this.memberIndex(memberId);
  1019. if (memberIndex >= 0) {
  1020. return {
  1021. $set: {
  1022. [`members.${memberIndex}.isActive`]: true,
  1023. },
  1024. };
  1025. }
  1026. return {
  1027. $push: {
  1028. members: {
  1029. userId: memberId,
  1030. isAdmin: false,
  1031. isActive: true,
  1032. isNoComments: false,
  1033. isCommentOnly: false,
  1034. isWorker: false,
  1035. },
  1036. },
  1037. };
  1038. },
  1039. removeMember(memberId) {
  1040. const memberIndex = this.memberIndex(memberId);
  1041. // we do not allow the only one admin to be removed
  1042. const allowRemove =
  1043. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1044. if (!allowRemove) {
  1045. return {
  1046. $set: {
  1047. [`members.${memberIndex}.isActive`]: true,
  1048. },
  1049. };
  1050. }
  1051. return {
  1052. $set: {
  1053. [`members.${memberIndex}.isActive`]: false,
  1054. [`members.${memberIndex}.isAdmin`]: false,
  1055. },
  1056. };
  1057. },
  1058. setMemberPermission(
  1059. memberId,
  1060. isAdmin,
  1061. isNoComments,
  1062. isCommentOnly,
  1063. isWorker,
  1064. currentUserId = Meteor.userId(),
  1065. ) {
  1066. const memberIndex = this.memberIndex(memberId);
  1067. // do not allow change permission of self
  1068. if (memberId === currentUserId) {
  1069. isAdmin = this.members[memberIndex].isAdmin;
  1070. }
  1071. return {
  1072. $set: {
  1073. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1074. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1075. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1076. [`members.${memberIndex}.isWorker`]: isWorker,
  1077. },
  1078. };
  1079. },
  1080. setAllowsSubtasks(allowsSubtasks) {
  1081. return { $set: { allowsSubtasks } };
  1082. },
  1083. setAllowsMembers(allowsMembers) {
  1084. return { $set: { allowsMembers } };
  1085. },
  1086. setAllowsChecklists(allowsChecklists) {
  1087. return { $set: { allowsChecklists } };
  1088. },
  1089. setAllowsAssignee(allowsAssignee) {
  1090. return { $set: { allowsAssignee } };
  1091. },
  1092. setAllowsAssignedBy(allowsAssignedBy) {
  1093. return { $set: { allowsAssignedBy } };
  1094. },
  1095. setAllowsRequestedBy(allowsRequestedBy) {
  1096. return { $set: { allowsRequestedBy } };
  1097. },
  1098. setAllowsAttachments(allowsAttachments) {
  1099. return { $set: { allowsAttachments } };
  1100. },
  1101. setAllowsLabels(allowsLabels) {
  1102. return { $set: { allowsLabels } };
  1103. },
  1104. setAllowsComments(allowsComments) {
  1105. return { $set: { allowsComments } };
  1106. },
  1107. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1108. return { $set: { allowsDescriptionTitle } };
  1109. },
  1110. setAllowsDescriptionText(allowsDescriptionText) {
  1111. return { $set: { allowsDescriptionText } };
  1112. },
  1113. setAllowsActivities(allowsActivities) {
  1114. return { $set: { allowsActivities } };
  1115. },
  1116. setAllowsReceivedDate(allowsReceivedDate) {
  1117. return { $set: { allowsReceivedDate } };
  1118. },
  1119. setAllowsStartDate(allowsStartDate) {
  1120. return { $set: { allowsStartDate } };
  1121. },
  1122. setAllowsEndDate(allowsEndDate) {
  1123. return { $set: { allowsEndDate } };
  1124. },
  1125. setAllowsDueDate(allowsDueDate) {
  1126. return { $set: { allowsDueDate } };
  1127. },
  1128. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1129. return { $set: { subtasksDefaultBoardId } };
  1130. },
  1131. setSubtasksDefaultListId(subtasksDefaultListId) {
  1132. return { $set: { subtasksDefaultListId } };
  1133. },
  1134. setPresentParentTask(presentParentTask) {
  1135. return { $set: { presentParentTask } };
  1136. },
  1137. move(sortIndex) {
  1138. return { $set: { sort: sortIndex } };
  1139. },
  1140. });
  1141. function boardRemover(userId, doc) {
  1142. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1143. element => {
  1144. element.remove({ boardId: doc._id });
  1145. },
  1146. );
  1147. }
  1148. Boards.userSearch = (
  1149. userId,
  1150. selector = {},
  1151. projection = {},
  1152. // includeArchived = false,
  1153. ) => {
  1154. // if (!includeArchived) {
  1155. // selector.archived = false;
  1156. // }
  1157. selector.$or = [{ permission: 'public' }];
  1158. if (userId) {
  1159. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1160. }
  1161. return Boards.find(selector, projection);
  1162. };
  1163. Boards.userBoards = (userId, archived = false, selector = {}) => {
  1164. if (typeof archived === 'boolean') {
  1165. selector.archived = archived;
  1166. }
  1167. selector.$or = [{ permission: 'public' }];
  1168. if (userId) {
  1169. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1170. }
  1171. return Boards.find(selector);
  1172. };
  1173. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1174. return Boards.userBoards(userId, archived, selector).map(board => {
  1175. return board._id;
  1176. });
  1177. };
  1178. if (Meteor.isServer) {
  1179. Boards.allow({
  1180. insert: Meteor.userId,
  1181. update: allowIsBoardAdmin,
  1182. remove: allowIsBoardAdmin,
  1183. fetch: ['members'],
  1184. });
  1185. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1186. Boards.allow({
  1187. update(userId, board, fieldNames) {
  1188. return _.contains(fieldNames, 'sort');
  1189. },
  1190. fetch: [],
  1191. });
  1192. // The number of users that have starred this board is managed by trusted code
  1193. // and the user is not allowed to update it
  1194. Boards.deny({
  1195. update(userId, board, fieldNames) {
  1196. return _.contains(fieldNames, 'stars');
  1197. },
  1198. fetch: [],
  1199. });
  1200. // We can't remove a member if it is the last administrator
  1201. Boards.deny({
  1202. update(userId, doc, fieldNames, modifier) {
  1203. if (!_.contains(fieldNames, 'members')) return false;
  1204. // We only care in case of a $pull operation, ie remove a member
  1205. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1206. // If there is more than one admin, it's ok to remove anyone
  1207. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1208. .length;
  1209. if (nbAdmins > 1) return false;
  1210. // If all the previous conditions were verified, we can't remove
  1211. // a user if it's an admin
  1212. const removedMemberId = modifier.$pull.members.userId;
  1213. return Boolean(
  1214. _.findWhere(doc.members, {
  1215. userId: removedMemberId,
  1216. isAdmin: true,
  1217. }),
  1218. );
  1219. },
  1220. fetch: ['members'],
  1221. });
  1222. Meteor.methods({
  1223. quitBoard(boardId) {
  1224. check(boardId, String);
  1225. const board = Boards.findOne(boardId);
  1226. if (board) {
  1227. const userId = Meteor.userId();
  1228. const index = board.memberIndex(userId);
  1229. if (index >= 0) {
  1230. board.removeMember(userId);
  1231. return true;
  1232. } else throw new Meteor.Error('error-board-notAMember');
  1233. } else throw new Meteor.Error('error-board-doesNotExist');
  1234. },
  1235. acceptInvite(boardId) {
  1236. check(boardId, String);
  1237. const board = Boards.findOne(boardId);
  1238. if (!board) {
  1239. throw new Meteor.Error('error-board-doesNotExist');
  1240. }
  1241. Meteor.users.update(Meteor.userId(), {
  1242. $pull: {
  1243. 'profile.invitedBoards': boardId,
  1244. },
  1245. });
  1246. },
  1247. myLabelNames() {
  1248. let names = [];
  1249. Boards.userBoards(Meteor.userId()).forEach(board => {
  1250. names = names.concat(
  1251. board.labels
  1252. .filter(label => !!label.name)
  1253. .map(label => {
  1254. return label.name;
  1255. }),
  1256. );
  1257. });
  1258. return _.uniq(names).sort();
  1259. },
  1260. myBoardNames() {
  1261. return _.uniq(
  1262. Boards.userBoards(Meteor.userId()).map(board => {
  1263. return board.title;
  1264. }),
  1265. ).sort();
  1266. },
  1267. });
  1268. Meteor.methods({
  1269. archiveBoard(boardId) {
  1270. check(boardId, String);
  1271. const board = Boards.findOne(boardId);
  1272. if (board) {
  1273. const userId = Meteor.userId();
  1274. const index = board.memberIndex(userId);
  1275. if (index >= 0) {
  1276. board.archive();
  1277. return true;
  1278. } else throw new Meteor.Error('error-board-notAMember');
  1279. } else throw new Meteor.Error('error-board-doesNotExist');
  1280. },
  1281. });
  1282. }
  1283. // Insert new board at last position in sort order.
  1284. Boards.before.insert((userId, doc) => {
  1285. const lastBoard = Boards.findOne(
  1286. { sort: { $exists: true } },
  1287. { sort: { sort: -1 } },
  1288. );
  1289. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1290. doc.sort = lastBoard.sort + 1;
  1291. }
  1292. });
  1293. if (Meteor.isServer) {
  1294. // Let MongoDB ensure that a member is not included twice in the same board
  1295. Meteor.startup(() => {
  1296. Boards._collection._ensureIndex({ modifiedAt: -1 });
  1297. Boards._collection._ensureIndex(
  1298. {
  1299. _id: 1,
  1300. 'members.userId': 1,
  1301. },
  1302. { unique: true },
  1303. );
  1304. Boards._collection._ensureIndex({ 'members.userId': 1 });
  1305. });
  1306. // Genesis: the first activity of the newly created board
  1307. Boards.after.insert((userId, doc) => {
  1308. Activities.insert({
  1309. userId,
  1310. type: 'board',
  1311. activityTypeId: doc._id,
  1312. activityType: 'createBoard',
  1313. boardId: doc._id,
  1314. });
  1315. });
  1316. // If the user remove one label from a board, we cant to remove reference of
  1317. // this label in any card of this board.
  1318. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1319. if (
  1320. !_.contains(fieldNames, 'labels') ||
  1321. !modifier.$pull ||
  1322. !modifier.$pull.labels ||
  1323. !modifier.$pull.labels._id
  1324. ) {
  1325. return;
  1326. }
  1327. const removedLabelId = modifier.$pull.labels._id;
  1328. Cards.update(
  1329. { boardId: doc._id },
  1330. {
  1331. $pull: {
  1332. labelIds: removedLabelId,
  1333. },
  1334. },
  1335. { multi: true },
  1336. );
  1337. });
  1338. const foreachRemovedMember = (doc, modifier, callback) => {
  1339. Object.keys(modifier).forEach(set => {
  1340. if (modifier[set] !== false) {
  1341. return;
  1342. }
  1343. const parts = set.split('.');
  1344. if (
  1345. parts.length === 3 &&
  1346. parts[0] === 'members' &&
  1347. parts[2] === 'isActive'
  1348. ) {
  1349. callback(doc.members[parts[1]].userId);
  1350. }
  1351. });
  1352. };
  1353. // Remove a member from all objects of the board before leaving the board
  1354. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1355. if (!_.contains(fieldNames, 'members')) {
  1356. return;
  1357. }
  1358. if (modifier.$set) {
  1359. const boardId = doc._id;
  1360. foreachRemovedMember(doc, modifier.$set, memberId => {
  1361. Cards.update(
  1362. { boardId },
  1363. {
  1364. $pull: {
  1365. members: memberId,
  1366. watchers: memberId,
  1367. },
  1368. },
  1369. { multi: true },
  1370. );
  1371. Lists.update(
  1372. { boardId },
  1373. {
  1374. $pull: {
  1375. watchers: memberId,
  1376. },
  1377. },
  1378. { multi: true },
  1379. );
  1380. const board = Boards._transform(doc);
  1381. board.setWatcher(memberId, false);
  1382. // Remove board from users starred list
  1383. if (!board.isPublic()) {
  1384. Users.update(memberId, {
  1385. $pull: {
  1386. 'profile.starredBoards': boardId,
  1387. },
  1388. });
  1389. }
  1390. });
  1391. }
  1392. });
  1393. Boards.before.remove((userId, doc) => {
  1394. boardRemover(userId, doc);
  1395. // Add removeBoard activity to keep it
  1396. Activities.insert({
  1397. userId,
  1398. type: 'board',
  1399. activityTypeId: doc._id,
  1400. activityType: 'removeBoard',
  1401. boardId: doc._id,
  1402. });
  1403. });
  1404. // Add a new activity if we add or remove a member to the board
  1405. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1406. if (!_.contains(fieldNames, 'members')) {
  1407. return;
  1408. }
  1409. // Say hello to the new member
  1410. if (modifier.$push && modifier.$push.members) {
  1411. const memberId = modifier.$push.members.userId;
  1412. Activities.insert({
  1413. userId,
  1414. memberId,
  1415. type: 'member',
  1416. activityType: 'addBoardMember',
  1417. boardId: doc._id,
  1418. });
  1419. }
  1420. // Say goodbye to the former member
  1421. if (modifier.$set) {
  1422. foreachRemovedMember(doc, modifier.$set, memberId => {
  1423. Activities.insert({
  1424. userId,
  1425. memberId,
  1426. type: 'member',
  1427. activityType: 'removeBoardMember',
  1428. boardId: doc._id,
  1429. });
  1430. });
  1431. }
  1432. });
  1433. }
  1434. //BOARDS REST API
  1435. if (Meteor.isServer) {
  1436. /**
  1437. * @operation get_boards_from_user
  1438. * @summary Get all boards attached to a user
  1439. *
  1440. * @param {string} userId the ID of the user to retrieve the data
  1441. * @return_type [{_id: string,
  1442. title: string}]
  1443. */
  1444. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1445. try {
  1446. Authentication.checkLoggedIn(req.userId);
  1447. const paramUserId = req.params.userId;
  1448. // A normal user should be able to see their own boards,
  1449. // admins can access boards of any user
  1450. Authentication.checkAdminOrCondition(
  1451. req.userId,
  1452. req.userId === paramUserId,
  1453. );
  1454. const data = Boards.find(
  1455. {
  1456. archived: false,
  1457. 'members.userId': paramUserId,
  1458. },
  1459. {
  1460. sort: { sort: 1 /* boards default sorting */ },
  1461. },
  1462. ).map(function(board) {
  1463. return {
  1464. _id: board._id,
  1465. title: board.title,
  1466. };
  1467. });
  1468. JsonRoutes.sendResult(res, { code: 200, data });
  1469. } catch (error) {
  1470. JsonRoutes.sendResult(res, {
  1471. code: 200,
  1472. data: error,
  1473. });
  1474. }
  1475. });
  1476. /**
  1477. * @operation get_public_boards
  1478. * @summary Get all public boards
  1479. *
  1480. * @return_type [{_id: string,
  1481. title: string}]
  1482. */
  1483. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1484. try {
  1485. Authentication.checkUserId(req.userId);
  1486. JsonRoutes.sendResult(res, {
  1487. code: 200,
  1488. data: Boards.find(
  1489. { permission: 'public' },
  1490. {
  1491. sort: { sort: 1 /* boards default sorting */ },
  1492. },
  1493. ).map(function(doc) {
  1494. return {
  1495. _id: doc._id,
  1496. title: doc.title,
  1497. };
  1498. }),
  1499. });
  1500. } catch (error) {
  1501. JsonRoutes.sendResult(res, {
  1502. code: 200,
  1503. data: error,
  1504. });
  1505. }
  1506. });
  1507. /**
  1508. * @operation get_board
  1509. * @summary Get the board with that particular ID
  1510. *
  1511. * @param {string} boardId the ID of the board to retrieve the data
  1512. * @return_type Boards
  1513. */
  1514. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1515. try {
  1516. const id = req.params.boardId;
  1517. Authentication.checkBoardAccess(req.userId, id);
  1518. JsonRoutes.sendResult(res, {
  1519. code: 200,
  1520. data: Boards.findOne({ _id: id }),
  1521. });
  1522. } catch (error) {
  1523. JsonRoutes.sendResult(res, {
  1524. code: 200,
  1525. data: error,
  1526. });
  1527. }
  1528. });
  1529. /**
  1530. * @operation new_board
  1531. * @summary Create a board
  1532. *
  1533. * @description This allows to create a board.
  1534. *
  1535. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1536. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1537. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1538. *
  1539. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1540. *
  1541. * @param {string} title the new title of the board
  1542. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1543. * (Not username or email)
  1544. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1545. * @param {boolean} [isActive] is the board active (default true)
  1546. * @param {boolean} [isNoComments] disable comments (default false)
  1547. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1548. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1549. * @param {string} [permission] "private" board <== Set to "public" if you
  1550. * want public Wekan board
  1551. * @param {string} [color] the color of the board
  1552. *
  1553. * @return_type {_id: string,
  1554. defaultSwimlaneId: string}
  1555. */
  1556. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1557. try {
  1558. Authentication.checkUserId(req.userId);
  1559. const id = Boards.insert({
  1560. title: req.body.title,
  1561. members: [
  1562. {
  1563. userId: req.body.owner,
  1564. isAdmin: req.body.isAdmin || true,
  1565. isActive: req.body.isActive || true,
  1566. isNoComments: req.body.isNoComments || false,
  1567. isCommentOnly: req.body.isCommentOnly || false,
  1568. isWorker: req.body.isWorker || false,
  1569. },
  1570. ],
  1571. permission: req.body.permission || 'private',
  1572. color: req.body.color || 'belize',
  1573. });
  1574. const swimlaneId = Swimlanes.insert({
  1575. title: TAPi18n.__('default'),
  1576. boardId: id,
  1577. });
  1578. JsonRoutes.sendResult(res, {
  1579. code: 200,
  1580. data: {
  1581. _id: id,
  1582. defaultSwimlaneId: swimlaneId,
  1583. },
  1584. });
  1585. } catch (error) {
  1586. JsonRoutes.sendResult(res, {
  1587. code: 200,
  1588. data: error,
  1589. });
  1590. }
  1591. });
  1592. /**
  1593. * @operation delete_board
  1594. * @summary Delete a board
  1595. *
  1596. * @param {string} boardId the ID of the board
  1597. */
  1598. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1599. try {
  1600. Authentication.checkUserId(req.userId);
  1601. const id = req.params.boardId;
  1602. Boards.remove({ _id: id });
  1603. JsonRoutes.sendResult(res, {
  1604. code: 200,
  1605. data: {
  1606. _id: id,
  1607. },
  1608. });
  1609. } catch (error) {
  1610. JsonRoutes.sendResult(res, {
  1611. code: 200,
  1612. data: error,
  1613. });
  1614. }
  1615. });
  1616. /**
  1617. * @operation add_board_label
  1618. * @summary Add a label to a board
  1619. *
  1620. * @description If the board doesn't have the name/color label, this function
  1621. * adds the label to the board.
  1622. *
  1623. * @param {string} boardId the board
  1624. * @param {string} color the color of the new label
  1625. * @param {string} name the name of the new label
  1626. *
  1627. * @return_type string
  1628. */
  1629. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1630. Authentication.checkUserId(req.userId);
  1631. const id = req.params.boardId;
  1632. try {
  1633. if (req.body.hasOwnProperty('label')) {
  1634. const board = Boards.findOne({ _id: id });
  1635. const color = req.body.label.color;
  1636. const name = req.body.label.name;
  1637. const labelId = Random.id(6);
  1638. if (!board.getLabel(name, color)) {
  1639. Boards.direct.update(
  1640. { _id: id },
  1641. { $push: { labels: { _id: labelId, name, color } } },
  1642. );
  1643. JsonRoutes.sendResult(res, {
  1644. code: 200,
  1645. data: labelId,
  1646. });
  1647. } else {
  1648. JsonRoutes.sendResult(res, {
  1649. code: 200,
  1650. });
  1651. }
  1652. }
  1653. } catch (error) {
  1654. JsonRoutes.sendResult(res, {
  1655. data: error,
  1656. });
  1657. }
  1658. });
  1659. /**
  1660. * @operation set_board_member_permission
  1661. * @tag Users
  1662. * @summary Change the permission of a member of a board
  1663. *
  1664. * @param {string} boardId the ID of the board that we are changing
  1665. * @param {string} memberId the ID of the user to change permissions
  1666. * @param {boolean} isAdmin admin capability
  1667. * @param {boolean} isNoComments NoComments capability
  1668. * @param {boolean} isCommentOnly CommentsOnly capability
  1669. * @param {boolean} isWorker Worker capability
  1670. */
  1671. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1672. req,
  1673. res,
  1674. ) {
  1675. try {
  1676. const boardId = req.params.boardId;
  1677. const memberId = req.params.memberId;
  1678. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  1679. Authentication.checkBoardAccess(req.userId, boardId);
  1680. const board = Boards.findOne({ _id: boardId });
  1681. function isTrue(data) {
  1682. try {
  1683. return data.toLowerCase() === 'true';
  1684. } catch (error) {
  1685. return data;
  1686. }
  1687. }
  1688. const query = board.setMemberPermission(
  1689. memberId,
  1690. isTrue(isAdmin),
  1691. isTrue(isNoComments),
  1692. isTrue(isCommentOnly),
  1693. isTrue(isWorker),
  1694. req.userId,
  1695. );
  1696. JsonRoutes.sendResult(res, {
  1697. code: 200,
  1698. data: query,
  1699. });
  1700. } catch (error) {
  1701. JsonRoutes.sendResult(res, {
  1702. code: 200,
  1703. data: error,
  1704. });
  1705. }
  1706. });
  1707. //ATTACHMENTS REST API
  1708. /**
  1709. * @operation get_board_attachments
  1710. * @summary Get the list of attachments of a board
  1711. *
  1712. * @param {string} boardId the board ID
  1713. * @return_type [{attachmentId: string,
  1714. * attachmentName: string,
  1715. * attachmentType: string,
  1716. * cardId: string,
  1717. * listId: string,
  1718. * swimlaneId: string}]
  1719. */
  1720. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  1721. const paramBoardId = req.params.boardId;
  1722. Authentication.checkBoardAccess(req.userId, paramBoardId);
  1723. JsonRoutes.sendResult(res, {
  1724. code: 200,
  1725. data: Attachments.files
  1726. .find({ boardId: paramBoardId }, { fields: { boardId: 0 } })
  1727. .map(function(doc) {
  1728. return {
  1729. attachmentId: doc._id,
  1730. attachmentName: doc.original.name,
  1731. attachmentType: doc.original.type,
  1732. url: FlowRouter.url(doc.url()),
  1733. urlDownload: `${FlowRouter.url(doc.url())}?download=true&token=`,
  1734. cardId: doc.cardId,
  1735. listId: doc.listId,
  1736. swimlaneId: doc.swimlaneId,
  1737. };
  1738. }),
  1739. });
  1740. });
  1741. }
  1742. export default Boards;