boards.js 46 KB

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