boards.js 49 KB

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