boards.js 44 KB

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