boards.js 56 KB

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