boards.js 47 KB

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