boards.js 50 KB

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