2
0

boards.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304
  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. Actions.find({ 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. Triggers.find({ 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. Rules.find({ 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. return Activities.find({ boardId: { $in: linkedBoardId } }, { sort: { createdAt: -1 } });
  786. //return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  787. },
  788. activeMembers(){
  789. return _.where(this.members, { isActive: true });
  790. },
  791. activeMembers2(members, boardTeamUsers) {
  792. let allMembers = members;
  793. if(this.teams !== undefined && this.teams.length > 0){
  794. let index;
  795. if(boardTeamUsers && boardTeamUsers.count() > 0){
  796. boardTeamUsers.forEach((u) => {
  797. index = allMembers.findIndex(function(m){ return m.userId == u._id});
  798. if(index == -1){
  799. allMembers.push({
  800. "isActive": true,
  801. "isAdmin": u.isAdmin !== undefined ? u.isAdmin : false,
  802. "isCommentOnly" : false,
  803. "isNoComments" : false,
  804. "userId": u._id,
  805. });
  806. }
  807. });
  808. }
  809. }
  810. return allMembers;
  811. },
  812. activeOrgs() {
  813. return _.where(this.orgs, { isActive: true });
  814. },
  815. // hasNotAnyOrg(){
  816. // return this.orgs === undefined || this.orgs.length <= 0;
  817. // },
  818. activeTeams() {
  819. return _.where(this.teams, { isActive: true });
  820. },
  821. // hasNotAnyTeam(){
  822. // return this.teams === undefined || this.teams.length <= 0;
  823. // },
  824. activeAdmins() {
  825. return _.where(this.members, { isActive: true, isAdmin: true });
  826. },
  827. memberUsers() {
  828. return ReactiveCache.getUsers({ _id: { $in: _.pluck(this.members, 'userId') } });
  829. },
  830. getLabel(name, color) {
  831. return _.findWhere(this.labels, { name, color });
  832. },
  833. getLabelById(labelId) {
  834. return _.findWhere(this.labels, { _id: labelId });
  835. },
  836. labelIndex(labelId) {
  837. return _.pluck(this.labels, '_id').indexOf(labelId);
  838. },
  839. memberIndex(memberId) {
  840. return _.pluck(this.members, 'userId').indexOf(memberId);
  841. },
  842. hasMember(memberId) {
  843. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  844. },
  845. hasAdmin(memberId) {
  846. return !!_.findWhere(this.members, {
  847. userId: memberId,
  848. isActive: true,
  849. isAdmin: true,
  850. });
  851. },
  852. hasNoComments(memberId) {
  853. return !!_.findWhere(this.members, {
  854. userId: memberId,
  855. isActive: true,
  856. isAdmin: false,
  857. isNoComments: true,
  858. isWorker: false,
  859. });
  860. },
  861. hasCommentOnly(memberId) {
  862. return !!_.findWhere(this.members, {
  863. userId: memberId,
  864. isActive: true,
  865. isAdmin: false,
  866. isCommentOnly: true,
  867. isWorker: false,
  868. });
  869. },
  870. hasWorker(memberId) {
  871. return !!_.findWhere(this.members, {
  872. userId: memberId,
  873. isActive: true,
  874. isAdmin: false,
  875. isCommentOnly: false,
  876. isWorker: true,
  877. });
  878. },
  879. hasAnyAllowsDate() {
  880. const ret = this.allowsReceivedDate || this.allowsStartDate || this.allowsDueDate || this.allowsEndDate;
  881. return ret;
  882. },
  883. hasAnyAllowsUser() {
  884. const ret = this.allowsCreator || this.allowsMembers || this.allowsAssignee || this.allowsRequestedBy || this.allowsAssignedBy;
  885. return ret;
  886. },
  887. absoluteUrl() {
  888. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  889. },
  890. originRelativeUrl() {
  891. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  892. },
  893. colorClass() {
  894. return `board-color-${this.color}`;
  895. },
  896. customFields() {
  897. const ret = ReactiveCache.getCustomFields(
  898. { boardIds: { $in: [this._id] } },
  899. { sort: { name: 1 } },
  900. );
  901. return ret;
  902. },
  903. // XXX currently mutations return no value so we have an issue when using addLabel in import
  904. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  905. pushLabel(name, color) {
  906. const _id = Random.id(6);
  907. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  908. return _id;
  909. },
  910. /** sets the new label order
  911. * @param newLabelOrderOnlyIds new order array of _id, e.g. Array(4) [ "FvtD34", "PAEgDP", "LjRBxH", "YJ8sZz" ]
  912. */
  913. setNewLabelOrder(newLabelOrderOnlyIds) {
  914. if (this.labels.length == newLabelOrderOnlyIds.length) {
  915. if (this.labels.every(_label => newLabelOrderOnlyIds.indexOf(_label._id) >= 0)) {
  916. const newLabels = _.sortBy(this.labels, _label => newLabelOrderOnlyIds.indexOf(_label._id));
  917. if (this.labels.length == newLabels.length) {
  918. Boards.direct.update(this._id, {$set: {labels: newLabels}});
  919. }
  920. }
  921. }
  922. },
  923. searchBoards(term) {
  924. check(term, Match.OneOf(String, null, undefined));
  925. const query = { boardId: this._id };
  926. query.type = 'cardType-linkedBoard';
  927. query.archived = false;
  928. const projection = { limit: 10, sort: { createdAt: -1 } };
  929. if (term) {
  930. const regex = new RegExp(term, 'i');
  931. query.$or = [{ title: regex }, { description: regex }];
  932. }
  933. const ret = ReactiveCache.getCards(query, projection);
  934. return ret;
  935. },
  936. searchSwimlanes(term) {
  937. check(term, Match.OneOf(String, null, undefined));
  938. const query = { boardId: this._id };
  939. if (this.isTemplatesBoard()) {
  940. query.type = 'template-swimlane';
  941. query.archived = false;
  942. } else {
  943. query.type = { $nin: ['template-swimlane'] };
  944. }
  945. const projection = { limit: 10, sort: { createdAt: -1 } };
  946. if (term) {
  947. const regex = new RegExp(term, 'i');
  948. query.$or = [{ title: regex }, { description: regex }];
  949. }
  950. return ReactiveCache.getSwimlanes(query, projection);
  951. },
  952. searchLists(term) {
  953. let ret = null;
  954. if (term) {
  955. check(term, Match.OneOf(String));
  956. term = term.trim();
  957. }
  958. if (term) {
  959. const query = { boardId: this._id };
  960. if (this.isTemplatesBoard()) {
  961. query.type = 'template-list';
  962. query.archived = false;
  963. } else {
  964. query.type = { $nin: ['template-list'] };
  965. }
  966. const projection = { sort: { createdAt: -1 } };
  967. if (term) {
  968. const regex = new RegExp(term, 'i');
  969. query.$or = [{ title: regex }, { description: regex }];
  970. }
  971. ret = ReactiveCache.getLists(query, projection);
  972. }
  973. return ret;
  974. },
  975. searchCards(term, excludeLinked) {
  976. let ret = null;
  977. if (term) {
  978. check(term, Match.OneOf(String));
  979. term = term.trim();
  980. }
  981. if (term) {
  982. const query = { boardId: this._id };
  983. if (excludeLinked) {
  984. query.linkedId = null;
  985. }
  986. if (this.isTemplatesBoard()) {
  987. query.type = 'template-card';
  988. query.archived = false;
  989. } else {
  990. query.type = { $nin: ['template-card'] };
  991. }
  992. const projection = { sort: { createdAt: -1 } };
  993. const regex = new RegExp(term, 'i');
  994. query.$or = [
  995. { title: regex },
  996. { description: regex },
  997. { customFields: { $elemMatch: { value: regex } } },
  998. ];
  999. ret = ReactiveCache.getCards(query, projection);
  1000. }
  1001. return ret;
  1002. },
  1003. // A board alwasy has another board where it deposits subtasks of thasks
  1004. // that belong to itself.
  1005. getDefaultSubtasksBoardId() {
  1006. if (
  1007. this.subtasksDefaultBoardId === null ||
  1008. this.subtasksDefaultBoardId === undefined
  1009. ) {
  1010. this.subtasksDefaultBoardId = Boards.insert({
  1011. title: `^${this.title}^`,
  1012. permission: this.permission,
  1013. members: this.members,
  1014. color: this.color,
  1015. description: TAPi18n.__('default-subtasks-board', {
  1016. board: this.title,
  1017. }),
  1018. });
  1019. Swimlanes.insert({
  1020. title: TAPi18n.__('default'),
  1021. boardId: this.subtasksDefaultBoardId,
  1022. });
  1023. Boards.update(this._id, {
  1024. $set: {
  1025. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  1026. },
  1027. });
  1028. }
  1029. return this.subtasksDefaultBoardId;
  1030. },
  1031. getDefaultSubtasksBoard() {
  1032. return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
  1033. },
  1034. //Date Settings option such as received date, start date and so on.
  1035. getDefaultDateSettingsBoardId() {
  1036. if (
  1037. this.dateSettingsDefaultBoardId === null ||
  1038. this.dateSettingsDefaultBoardId === undefined
  1039. ) {
  1040. this.dateSettingsDefaultBoardId = Boards.insert({
  1041. title: `^${this.title}^`,
  1042. permission: this.permission,
  1043. members: this.members,
  1044. color: this.color,
  1045. description: TAPi18n.__('default-dates-board', {
  1046. board: this.title,
  1047. }),
  1048. });
  1049. Swimlanes.insert({
  1050. title: TAPi18n.__('default'),
  1051. boardId: this.dateSettingsDefaultBoardId,
  1052. });
  1053. Boards.update(this._id, {
  1054. $set: {
  1055. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  1056. },
  1057. });
  1058. }
  1059. return this.dateSettingsDefaultBoardId;
  1060. },
  1061. getDefaultDateSettingsBoard() {
  1062. return ReactiveCache.getBoard(this.getDefaultDateSettingsBoardId());
  1063. },
  1064. getDefaultSubtasksListId() {
  1065. if (
  1066. this.subtasksDefaultListId === null ||
  1067. this.subtasksDefaultListId === undefined
  1068. ) {
  1069. this.subtasksDefaultListId = Lists.insert({
  1070. title: TAPi18n.__('queue'),
  1071. boardId: this._id,
  1072. });
  1073. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  1074. }
  1075. return this.subtasksDefaultListId;
  1076. },
  1077. getDefaultSubtasksList() {
  1078. return ReactiveCache.getList(this.getDefaultSubtasksListId());
  1079. },
  1080. getDefaultDateSettingsListId() {
  1081. if (
  1082. this.dateSettingsDefaultListId === null ||
  1083. this.dateSettingsDefaultListId === undefined
  1084. ) {
  1085. this.dateSettingsDefaultListId = Lists.insert({
  1086. title: TAPi18n.__('queue'),
  1087. boardId: this._id,
  1088. });
  1089. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  1090. }
  1091. return this.dateSettingsDefaultListId;
  1092. },
  1093. getDefaultDateSettingsList() {
  1094. return ReactiveCache.getList(this.getDefaultDateSettingsListId());
  1095. },
  1096. getDefaultSwimline() {
  1097. let result = ReactiveCache.getSwimlane({ boardId: this._id });
  1098. if (result === undefined) {
  1099. Swimlanes.insert({
  1100. title: TAPi18n.__('default'),
  1101. boardId: this._id,
  1102. });
  1103. result = ReactiveCache.getSwimlane({ boardId: this._id });
  1104. }
  1105. return result;
  1106. },
  1107. getNextCardNumber() {
  1108. const boardCards = ReactiveCache.getCard(
  1109. {
  1110. boardId: this._id
  1111. },
  1112. {
  1113. sort: { cardNumber: -1 },
  1114. limit: 1
  1115. }
  1116. , true);
  1117. // If no card is assigned to the board, return 1
  1118. if (!boardCards) {
  1119. return 1;
  1120. }
  1121. const maxCardNr = !!boardCards.cardNumber ? boardCards.cardNumber : 0;
  1122. return maxCardNr + 1;
  1123. },
  1124. cardsDueInBetween(start, end) {
  1125. const ret = ReactiveCache.getCards({
  1126. boardId: this._id,
  1127. dueAt: { $gte: start, $lte: end },
  1128. });
  1129. return ret;
  1130. },
  1131. cardsInInterval(start, end) {
  1132. const ret = ReactiveCache.getCards({
  1133. boardId: this._id,
  1134. $or: [
  1135. {
  1136. startAt: {
  1137. $lte: start,
  1138. },
  1139. endAt: {
  1140. $gte: start,
  1141. },
  1142. },
  1143. {
  1144. startAt: {
  1145. $lte: end,
  1146. },
  1147. endAt: {
  1148. $gte: end,
  1149. },
  1150. },
  1151. {
  1152. startAt: {
  1153. $gte: start,
  1154. },
  1155. endAt: {
  1156. $lte: end,
  1157. },
  1158. },
  1159. ],
  1160. });
  1161. return ret;
  1162. },
  1163. isTemplateBoard() {
  1164. return this.type === 'template-board';
  1165. },
  1166. isTemplatesBoard() {
  1167. return this.type === 'template-container';
  1168. },
  1169. });
  1170. Boards.mutations({
  1171. archive() {
  1172. return { $set: { archived: true, archivedAt: new Date() } };
  1173. },
  1174. restore() {
  1175. return { $set: { archived: false } };
  1176. },
  1177. rename(title) {
  1178. return { $set: { title } };
  1179. },
  1180. setDescription(description) {
  1181. return { $set: { description } };
  1182. },
  1183. setColor(color) {
  1184. return { $set: { color } };
  1185. },
  1186. setBackgroundImageURL(backgroundImageURL) {
  1187. const currentUser = ReactiveCache.getCurrentUser();
  1188. if(currentUser.isBoardAdmin()) {
  1189. return { $set: { backgroundImageURL } };
  1190. } else if (currentUser.isAdmin()) {
  1191. return { $set: { backgroundImageURL } };
  1192. } else {
  1193. return false;
  1194. }
  1195. },
  1196. setVisibility(visibility) {
  1197. return { $set: { permission: visibility } };
  1198. },
  1199. addLabel(name, color) {
  1200. // If label with the same name and color already exists we don't want to
  1201. // create another one because they would be indistinguishable in the UI
  1202. // (they would still have different `_id` but that is not exposed to the
  1203. // user).
  1204. if (!this.getLabel(name, color)) {
  1205. const _id = Random.id(6);
  1206. return { $push: { labels: { _id, name, color } } };
  1207. }
  1208. return {};
  1209. },
  1210. editLabel(labelId, name, color) {
  1211. if (!this.getLabel(name, color)) {
  1212. const labelIndex = this.labelIndex(labelId);
  1213. return {
  1214. $set: {
  1215. [`labels.${labelIndex}.name`]: name,
  1216. [`labels.${labelIndex}.color`]: color,
  1217. },
  1218. };
  1219. }
  1220. return {};
  1221. },
  1222. removeLabel(labelId) {
  1223. return { $pull: { labels: { _id: labelId } } };
  1224. },
  1225. changeOwnership(fromId, toId) {
  1226. const memberIndex = this.memberIndex(fromId);
  1227. return {
  1228. $set: {
  1229. [`members.${memberIndex}.userId`]: toId,
  1230. },
  1231. };
  1232. },
  1233. addMember(memberId) {
  1234. const memberIndex = this.memberIndex(memberId);
  1235. if (memberIndex >= 0) {
  1236. return {
  1237. $set: {
  1238. [`members.${memberIndex}.isActive`]: true,
  1239. },
  1240. };
  1241. }
  1242. return {
  1243. $push: {
  1244. members: {
  1245. userId: memberId,
  1246. isAdmin: false,
  1247. isActive: true,
  1248. isNoComments: false,
  1249. isCommentOnly: false,
  1250. isWorker: false,
  1251. },
  1252. },
  1253. };
  1254. },
  1255. removeMember(memberId) {
  1256. const memberIndex = this.memberIndex(memberId);
  1257. // we do not allow the only one admin to be removed
  1258. const allowRemove =
  1259. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1260. if (!allowRemove) {
  1261. return {
  1262. $set: {
  1263. [`members.${memberIndex}.isActive`]: true,
  1264. },
  1265. };
  1266. }
  1267. return {
  1268. $set: {
  1269. [`members.${memberIndex}.isActive`]: false,
  1270. [`members.${memberIndex}.isAdmin`]: false,
  1271. },
  1272. };
  1273. },
  1274. setMemberPermission(
  1275. memberId,
  1276. isAdmin,
  1277. isNoComments,
  1278. isCommentOnly,
  1279. isWorker,
  1280. currentUserId = Meteor.userId(),
  1281. ) {
  1282. const memberIndex = this.memberIndex(memberId);
  1283. // do not allow change permission of self
  1284. if (memberId === currentUserId) {
  1285. isAdmin = this.members[memberIndex].isAdmin;
  1286. }
  1287. return {
  1288. $set: {
  1289. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1290. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1291. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1292. [`members.${memberIndex}.isWorker`]: isWorker,
  1293. },
  1294. };
  1295. },
  1296. setAllowsSubtasks(allowsSubtasks) {
  1297. return { $set: { allowsSubtasks } };
  1298. },
  1299. setAllowsCreator(allowsCreator) {
  1300. return { $set: { allowsCreator } };
  1301. },
  1302. setAllowsMembers(allowsMembers) {
  1303. return { $set: { allowsMembers } };
  1304. },
  1305. setAllowsChecklists(allowsChecklists) {
  1306. return { $set: { allowsChecklists } };
  1307. },
  1308. setAllowsAssignee(allowsAssignee) {
  1309. return { $set: { allowsAssignee } };
  1310. },
  1311. setAllowsAssignedBy(allowsAssignedBy) {
  1312. return { $set: { allowsAssignedBy } };
  1313. },
  1314. setAllowsRequestedBy(allowsRequestedBy) {
  1315. return { $set: { allowsRequestedBy } };
  1316. },
  1317. setAllowsCardSortingByNumber(allowsCardSortingByNumber) {
  1318. return { $set: { allowsCardSortingByNumber } };
  1319. },
  1320. setAllowsShowLists(allowsShowLists) {
  1321. return { $set: { allowsShowLists } };
  1322. },
  1323. setAllowsAttachments(allowsAttachments) {
  1324. return { $set: { allowsAttachments } };
  1325. },
  1326. setAllowsLabels(allowsLabels) {
  1327. return { $set: { allowsLabels } };
  1328. },
  1329. setAllowsComments(allowsComments) {
  1330. return { $set: { allowsComments } };
  1331. },
  1332. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1333. return { $set: { allowsDescriptionTitle } };
  1334. },
  1335. setAllowsCardNumber(allowsCardNumber) {
  1336. return { $set: { allowsCardNumber } };
  1337. },
  1338. setAllowsDescriptionText(allowsDescriptionText) {
  1339. return { $set: { allowsDescriptionText } };
  1340. },
  1341. setallowsDescriptionTextOnMinicard(allowsDescriptionTextOnMinicard) {
  1342. return { $set: { allowsDescriptionTextOnMinicard } };
  1343. },
  1344. setallowsCoverAttachmentOnMinicard(allowsCoverAttachmentOnMinicard) {
  1345. return { $set: { allowsCoverAttachmentOnMinicard } };
  1346. },
  1347. setallowsBadgeAttachmentOnMinicard(allowsBadgeAttachmentOnMinicard) {
  1348. return { $set: { allowsBadgeAttachmentOnMinicard } };
  1349. },
  1350. setallowsCardSortingByNumberOnMinicard(allowsCardSortingByNumberOnMinicard) {
  1351. return { $set: { allowsCardSortingByNumberOnMinicard } };
  1352. },
  1353. setAllowsActivities(allowsActivities) {
  1354. return { $set: { allowsActivities } };
  1355. },
  1356. setAllowsReceivedDate(allowsReceivedDate) {
  1357. return { $set: { allowsReceivedDate } };
  1358. },
  1359. setAllowsCardCounterList(allowsCardCounterList) {
  1360. return { $set: { allowsCardCounterList } };
  1361. },
  1362. setAllowsBoardMemberList(allowsBoardMemberList) {
  1363. return { $set: { allowsBoardMemberList } };
  1364. },
  1365. setAllowsStartDate(allowsStartDate) {
  1366. return { $set: { allowsStartDate } };
  1367. },
  1368. setAllowsEndDate(allowsEndDate) {
  1369. return { $set: { allowsEndDate } };
  1370. },
  1371. setAllowsDueDate(allowsDueDate) {
  1372. return { $set: { allowsDueDate } };
  1373. },
  1374. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1375. return { $set: { subtasksDefaultBoardId } };
  1376. },
  1377. setSubtasksDefaultListId(subtasksDefaultListId) {
  1378. return { $set: { subtasksDefaultListId } };
  1379. },
  1380. setPresentParentTask(presentParentTask) {
  1381. return { $set: { presentParentTask } };
  1382. },
  1383. move(sortIndex) {
  1384. return { $set: { sort: sortIndex } };
  1385. },
  1386. });
  1387. function boardRemover(userId, doc) {
  1388. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1389. element => {
  1390. element.remove({ boardId: doc._id });
  1391. },
  1392. );
  1393. }
  1394. Boards.uniqueTitle = title => {
  1395. const m = title.match(
  1396. new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
  1397. );
  1398. const base = escapeForRegex(m.groups.title);
  1399. const baseTitle = m.groups.title;
  1400. boards = Boards.find({ title: new RegExp(`^${base}\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)`) });
  1401. if (boards.count() > 0) {
  1402. let num = 0;
  1403. Boards.find({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) }).forEach(
  1404. board => {
  1405. const m = board.title.match(
  1406. new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
  1407. );
  1408. if (m) {
  1409. const n = parseInt(m.groups.num, 10);
  1410. num = num < n ? n : num;
  1411. }
  1412. },
  1413. );
  1414. return `${baseTitle} [${num + 1}]`;
  1415. }
  1416. return title;
  1417. };
  1418. Boards.userSearch = (
  1419. userId,
  1420. selector = {},
  1421. projection = {},
  1422. // includeArchived = false,
  1423. ) => {
  1424. // if (!includeArchived) {
  1425. // selector.archived = false;
  1426. // }
  1427. selector.$or = [{ permission: 'public' }];
  1428. if (userId) {
  1429. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1430. }
  1431. return Boards.find(selector, projection);
  1432. };
  1433. Boards.userBoards = (
  1434. userId,
  1435. archived = false,
  1436. selector = {},
  1437. projection = {},
  1438. ) => {
  1439. const user = ReactiveCache.getUser(userId);
  1440. if (!user) {
  1441. return [];
  1442. }
  1443. if (typeof archived === 'boolean') {
  1444. selector.archived = archived;
  1445. }
  1446. if (!selector.type) {
  1447. selector.type = 'board';
  1448. }
  1449. selector.$or = [
  1450. { permission: 'public' },
  1451. { members: { $elemMatch: { userId, isActive: true } } },
  1452. { orgs: { $elemMatch: { orgId: { $in: user.orgIds() }, isActive: true } } },
  1453. { teams: { $elemMatch: { teamId: { $in: user.teamIds() }, isActive: true } } },
  1454. ];
  1455. return Boards.find(selector, projection);
  1456. };
  1457. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1458. return Boards.userBoards(userId, archived, selector, {
  1459. fields: { _id: 1 },
  1460. }).map(board => {
  1461. return board._id;
  1462. });
  1463. };
  1464. Boards.colorMap = () => {
  1465. const colors = {};
  1466. for (const color of Boards.labelColors()) {
  1467. colors[TAPi18n.__(`color-${color}`)] = color;
  1468. }
  1469. return colors;
  1470. };
  1471. Boards.labelColors = () => {
  1472. return ALLOWED_COLORS;
  1473. };
  1474. if (Meteor.isServer) {
  1475. Boards.allow({
  1476. insert: Meteor.userId,
  1477. update: allowIsBoardAdmin,
  1478. remove: allowIsBoardAdmin,
  1479. fetch: ['members'],
  1480. });
  1481. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1482. Boards.allow({
  1483. update(userId, board, fieldNames) {
  1484. return _.contains(fieldNames, 'sort');
  1485. },
  1486. fetch: [],
  1487. });
  1488. // The number of users that have starred this board is managed by trusted code
  1489. // and the user is not allowed to update it
  1490. Boards.deny({
  1491. update(userId, board, fieldNames) {
  1492. return _.contains(fieldNames, 'stars');
  1493. },
  1494. fetch: [],
  1495. });
  1496. // We can't remove a member if it is the last administrator
  1497. Boards.deny({
  1498. update(userId, doc, fieldNames, modifier) {
  1499. if (!_.contains(fieldNames, 'members')) return false;
  1500. // We only care in case of a $pull operation, ie remove a member
  1501. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1502. // If there is more than one admin, it's ok to remove anyone
  1503. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1504. .length;
  1505. if (nbAdmins > 1) return false;
  1506. // If all the previous conditions were verified, we can't remove
  1507. // a user if it's an admin
  1508. const removedMemberId = modifier.$pull.members.userId;
  1509. return Boolean(
  1510. _.findWhere(doc.members, {
  1511. userId: removedMemberId,
  1512. isAdmin: true,
  1513. }),
  1514. );
  1515. },
  1516. fetch: ['members'],
  1517. });
  1518. Meteor.methods({
  1519. getBackgroundImageURL(boardId) {
  1520. check(boardId, String);
  1521. return ReactiveCache.getBoard(boardId, {}, { backgroundImageUrl: 1 });
  1522. },
  1523. quitBoard(boardId) {
  1524. check(boardId, String);
  1525. const board = ReactiveCache.getBoard(boardId);
  1526. if (board) {
  1527. const userId = Meteor.userId();
  1528. const index = board.memberIndex(userId);
  1529. if (index >= 0) {
  1530. board.removeMember(userId);
  1531. return true;
  1532. } else throw new Meteor.Error('error-board-notAMember');
  1533. } else throw new Meteor.Error('error-board-doesNotExist');
  1534. },
  1535. acceptInvite(boardId) {
  1536. check(boardId, String);
  1537. const board = ReactiveCache.getBoard(boardId);
  1538. if (!board) {
  1539. throw new Meteor.Error('error-board-doesNotExist');
  1540. }
  1541. Meteor.users.update(Meteor.userId(), {
  1542. $pull: {
  1543. 'profile.invitedBoards': boardId,
  1544. },
  1545. });
  1546. },
  1547. myLabelNames() {
  1548. let names = [];
  1549. Boards.userBoards(Meteor.userId()).forEach(board => {
  1550. // Only return labels when they exist.
  1551. if (board.labels !== undefined) {
  1552. names = names.concat(
  1553. board.labels
  1554. .filter(label => !!label.name)
  1555. .map(label => {
  1556. return label.name;
  1557. }),
  1558. );
  1559. } else {
  1560. return [];
  1561. }
  1562. });
  1563. return _.uniq(names).sort();
  1564. },
  1565. myBoardNames() {
  1566. return _.uniq(
  1567. Boards.userBoards(Meteor.userId()).map(board => {
  1568. return board.title;
  1569. }),
  1570. ).sort();
  1571. },
  1572. });
  1573. Meteor.methods({
  1574. archiveBoard(boardId) {
  1575. check(boardId, String);
  1576. const board = ReactiveCache.getBoard(boardId);
  1577. if (board) {
  1578. const userId = Meteor.userId();
  1579. const index = board.memberIndex(userId);
  1580. if (index >= 0) {
  1581. board.archive();
  1582. return true;
  1583. } else throw new Meteor.Error('error-board-notAMember');
  1584. } else throw new Meteor.Error('error-board-doesNotExist');
  1585. },
  1586. setBoardOrgs(boardOrgsArray, currBoardId){
  1587. check(boardOrgsArray, Array);
  1588. check(currBoardId, String);
  1589. Boards.update(currBoardId, {
  1590. $set: {
  1591. orgs: boardOrgsArray,
  1592. },
  1593. });
  1594. },
  1595. setBoardTeams(boardTeamsArray, membersArray, currBoardId){
  1596. check(boardTeamsArray, Array);
  1597. check(membersArray, Array);
  1598. check(currBoardId, String);
  1599. Boards.update(currBoardId, {
  1600. $set: {
  1601. members: membersArray,
  1602. teams: boardTeamsArray,
  1603. },
  1604. });
  1605. },
  1606. });
  1607. }
  1608. // Insert new board at last position in sort order.
  1609. Boards.before.insert((userId, doc) => {
  1610. const lastBoard = ReactiveCache.getBoard(
  1611. { sort: { $exists: true } },
  1612. { sort: { sort: -1 } },
  1613. );
  1614. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1615. doc.sort = lastBoard.sort + 1;
  1616. }
  1617. });
  1618. if (Meteor.isServer) {
  1619. // Let MongoDB ensure that a member is not included twice in the same board
  1620. Meteor.startup(() => {
  1621. Boards._collection.createIndex({ modifiedAt: -1 });
  1622. Boards._collection.createIndex(
  1623. {
  1624. _id: 1,
  1625. 'members.userId': 1,
  1626. },
  1627. { unique: true },
  1628. );
  1629. Boards._collection.createIndex({ 'members.userId': 1 });
  1630. });
  1631. // Genesis: the first activity of the newly created board
  1632. Boards.after.insert((userId, doc) => {
  1633. Activities.insert({
  1634. userId,
  1635. type: 'board',
  1636. activityTypeId: doc._id,
  1637. activityType: 'createBoard',
  1638. boardId: doc._id,
  1639. });
  1640. });
  1641. // If the user remove one label from a board, we cant to remove reference of
  1642. // this label in any card of this board.
  1643. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1644. if (
  1645. !_.contains(fieldNames, 'labels') ||
  1646. !modifier.$pull ||
  1647. !modifier.$pull.labels ||
  1648. !modifier.$pull.labels._id
  1649. ) {
  1650. return;
  1651. }
  1652. const removedLabelId = modifier.$pull.labels._id;
  1653. Cards.update(
  1654. { boardId: doc._id },
  1655. {
  1656. $pull: {
  1657. labelIds: removedLabelId,
  1658. },
  1659. },
  1660. { multi: true },
  1661. );
  1662. });
  1663. const foreachRemovedMember = (doc, modifier, callback) => {
  1664. Object.keys(modifier).forEach(set => {
  1665. if (modifier[set] !== false) {
  1666. return;
  1667. }
  1668. const parts = set.split('.');
  1669. if (
  1670. parts.length === 3 &&
  1671. parts[0] === 'members' &&
  1672. parts[2] === 'isActive'
  1673. ) {
  1674. callback(doc.members[parts[1]].userId);
  1675. }
  1676. });
  1677. };
  1678. // Remove a member from all objects of the board before leaving the board
  1679. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1680. if (!_.contains(fieldNames, 'members')) {
  1681. return;
  1682. }
  1683. if (modifier.$set) {
  1684. const boardId = doc._id;
  1685. foreachRemovedMember(doc, modifier.$set, memberId => {
  1686. Cards.update(
  1687. { boardId },
  1688. {
  1689. $pull: {
  1690. members: memberId,
  1691. watchers: memberId,
  1692. },
  1693. },
  1694. { multi: true },
  1695. );
  1696. Lists.update(
  1697. { boardId },
  1698. {
  1699. $pull: {
  1700. watchers: memberId,
  1701. },
  1702. },
  1703. { multi: true },
  1704. );
  1705. const board = Boards._transform(doc);
  1706. board.setWatcher(memberId, false);
  1707. // Remove board from users starred list
  1708. if (!board.isPublic()) {
  1709. Users.update(memberId, {
  1710. $pull: {
  1711. 'profile.starredBoards': boardId,
  1712. },
  1713. });
  1714. }
  1715. });
  1716. }
  1717. });
  1718. Boards.before.remove((userId, doc) => {
  1719. boardRemover(userId, doc);
  1720. // Add removeBoard activity to keep it
  1721. Activities.insert({
  1722. userId,
  1723. type: 'board',
  1724. activityTypeId: doc._id,
  1725. activityType: 'removeBoard',
  1726. boardId: doc._id,
  1727. });
  1728. });
  1729. // Add a new activity if we add or remove a member to the board
  1730. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1731. if (!_.contains(fieldNames, 'members')) {
  1732. return;
  1733. }
  1734. // Say hello to the new member
  1735. if (modifier.$push && modifier.$push.members) {
  1736. const memberId = modifier.$push.members.userId;
  1737. Activities.insert({
  1738. userId,
  1739. memberId,
  1740. type: 'member',
  1741. activityType: 'addBoardMember',
  1742. boardId: doc._id,
  1743. });
  1744. }
  1745. // Say goodbye to the former member
  1746. if (modifier.$set) {
  1747. foreachRemovedMember(doc, modifier.$set, memberId => {
  1748. Activities.insert({
  1749. userId,
  1750. memberId,
  1751. type: 'member',
  1752. activityType: 'removeBoardMember',
  1753. boardId: doc._id,
  1754. });
  1755. });
  1756. }
  1757. });
  1758. }
  1759. //BOARDS REST API
  1760. if (Meteor.isServer) {
  1761. /**
  1762. * @operation get_boards_from_user
  1763. * @summary Get all boards attached to a user
  1764. *
  1765. * @param {string} userId the ID of the user to retrieve the data
  1766. * @return_type [{_id: string,
  1767. title: string}]
  1768. */
  1769. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1770. try {
  1771. Authentication.checkLoggedIn(req.userId);
  1772. const paramUserId = req.params.userId;
  1773. // A normal user should be able to see their own boards,
  1774. // admins can access boards of any user
  1775. Authentication.checkAdminOrCondition(
  1776. req.userId,
  1777. req.userId === paramUserId,
  1778. );
  1779. const data = Boards.find(
  1780. {
  1781. archived: false,
  1782. 'members.userId': paramUserId,
  1783. },
  1784. {
  1785. sort: { sort: 1 /* boards default sorting */ },
  1786. },
  1787. ).map(function(board) {
  1788. return {
  1789. _id: board._id,
  1790. title: board.title,
  1791. };
  1792. });
  1793. JsonRoutes.sendResult(res, { code: 200, data });
  1794. } catch (error) {
  1795. JsonRoutes.sendResult(res, {
  1796. code: 200,
  1797. data: error,
  1798. });
  1799. }
  1800. });
  1801. /**
  1802. * @operation get_public_boards
  1803. * @summary Get all public boards
  1804. *
  1805. * @return_type [{_id: string,
  1806. title: string}]
  1807. */
  1808. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1809. try {
  1810. Authentication.checkUserId(req.userId);
  1811. JsonRoutes.sendResult(res, {
  1812. code: 200,
  1813. data: Boards.find(
  1814. { permission: 'public' },
  1815. {
  1816. sort: { sort: 1 /* boards default sorting */ },
  1817. },
  1818. ).map(function(doc) {
  1819. return {
  1820. _id: doc._id,
  1821. title: doc.title,
  1822. };
  1823. }),
  1824. });
  1825. } catch (error) {
  1826. JsonRoutes.sendResult(res, {
  1827. code: 200,
  1828. data: error,
  1829. });
  1830. }
  1831. });
  1832. /**
  1833. * @operation get_boards_count
  1834. * @summary Get public and private boards count
  1835. *
  1836. * @return_type {private: integer, public: integer}
  1837. */
  1838. JsonRoutes.add('GET', '/api/boards_count', function(req, res) {
  1839. try {
  1840. Authentication.checkUserId(req.userId);
  1841. JsonRoutes.sendResult(res, {
  1842. code: 200,
  1843. data: {
  1844. private: Boards.find({ permission: 'private' }).count(),
  1845. public: Boards.find({ permission: 'public' }).count(),
  1846. },
  1847. });
  1848. } catch (error) {
  1849. JsonRoutes.sendResult(res, {
  1850. code: 200,
  1851. data: error,
  1852. });
  1853. }
  1854. });
  1855. /**
  1856. * @operation get_board
  1857. * @summary Get the board with that particular ID
  1858. *
  1859. * @param {string} boardId the ID of the board to retrieve the data
  1860. * @return_type Boards
  1861. */
  1862. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1863. try {
  1864. const paramBoardId = req.params.boardId;
  1865. Authentication.checkBoardAccess(req.userId, paramBoardId);
  1866. JsonRoutes.sendResult(res, {
  1867. code: 200,
  1868. data: ReactiveCache.getBoard(paramBoardId),
  1869. });
  1870. } catch (error) {
  1871. JsonRoutes.sendResult(res, {
  1872. code: 200,
  1873. data: error,
  1874. });
  1875. }
  1876. });
  1877. /**
  1878. * @operation new_board
  1879. * @summary Create a board
  1880. *
  1881. * @description This allows to create a board.
  1882. *
  1883. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1884. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1885. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1886. *
  1887. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1888. *
  1889. * @param {string} title the new title of the board
  1890. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1891. * (Not username or email)
  1892. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1893. * @param {boolean} [isActive] is the board active (default true)
  1894. * @param {boolean} [isNoComments] disable comments (default false)
  1895. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1896. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1897. * @param {string} [permission] "private" board <== Set to "public" if you
  1898. * want public Wekan board
  1899. * @param {string} [color] the color of the board
  1900. *
  1901. * @return_type {_id: string,
  1902. defaultSwimlaneId: string}
  1903. */
  1904. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1905. try {
  1906. Authentication.checkLoggedIn(req.userId);
  1907. const id = Boards.insert({
  1908. title: req.body.title,
  1909. members: [
  1910. {
  1911. userId: req.body.owner,
  1912. isAdmin: req.body.isAdmin || true,
  1913. isActive: req.body.isActive || true,
  1914. isNoComments: req.body.isNoComments || false,
  1915. isCommentOnly: req.body.isCommentOnly || false,
  1916. isWorker: req.body.isWorker || false,
  1917. },
  1918. ],
  1919. permission: req.body.permission || 'private',
  1920. color: req.body.color || 'belize',
  1921. });
  1922. const swimlaneId = Swimlanes.insert({
  1923. title: TAPi18n.__('default'),
  1924. boardId: id,
  1925. });
  1926. JsonRoutes.sendResult(res, {
  1927. code: 200,
  1928. data: {
  1929. _id: id,
  1930. defaultSwimlaneId: swimlaneId,
  1931. },
  1932. });
  1933. } catch (error) {
  1934. JsonRoutes.sendResult(res, {
  1935. code: 200,
  1936. data: error,
  1937. });
  1938. }
  1939. });
  1940. /**
  1941. * @operation delete_board
  1942. * @summary Delete a board
  1943. *
  1944. * @param {string} boardId the ID of the board
  1945. */
  1946. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1947. try {
  1948. Authentication.checkUserId(req.userId);
  1949. const id = req.params.boardId;
  1950. Boards.remove({ _id: id });
  1951. JsonRoutes.sendResult(res, {
  1952. code: 200,
  1953. data: {
  1954. _id: id,
  1955. },
  1956. });
  1957. } catch (error) {
  1958. JsonRoutes.sendResult(res, {
  1959. code: 200,
  1960. data: error,
  1961. });
  1962. }
  1963. });
  1964. /**
  1965. * @operation add_board_label
  1966. * @summary Add a label to a board
  1967. *
  1968. * @description If the board doesn't have the name/color label, this function
  1969. * adds the label to the board.
  1970. *
  1971. * @param {string} boardId the board
  1972. * @param {string} color the color of the new label
  1973. * @param {string} name the name of the new label
  1974. *
  1975. * @return_type string
  1976. */
  1977. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1978. const id = req.params.boardId;
  1979. Authentication.checkBoardAccess(req.userId, id);
  1980. try {
  1981. if (req.body.hasOwnProperty('label')) {
  1982. const board = ReactiveCache.getBoard(id);
  1983. const color = req.body.label.color;
  1984. const name = req.body.label.name;
  1985. const labelId = Random.id(6);
  1986. if (!board.getLabel(name, color)) {
  1987. Boards.direct.update(
  1988. { _id: id },
  1989. { $push: { labels: { _id: labelId, name, color } } },
  1990. );
  1991. JsonRoutes.sendResult(res, {
  1992. code: 200,
  1993. data: labelId,
  1994. });
  1995. } else {
  1996. JsonRoutes.sendResult(res, {
  1997. code: 200,
  1998. });
  1999. }
  2000. }
  2001. } catch (error) {
  2002. JsonRoutes.sendResult(res, {
  2003. data: error,
  2004. });
  2005. }
  2006. });
  2007. /**
  2008. * @operation set_board_member_permission
  2009. * @tag Users
  2010. * @summary Change the permission of a member of a board
  2011. *
  2012. * @param {string} boardId the ID of the board that we are changing
  2013. * @param {string} memberId the ID of the user to change permissions
  2014. * @param {boolean} isAdmin admin capability
  2015. * @param {boolean} isNoComments NoComments capability
  2016. * @param {boolean} isCommentOnly CommentsOnly capability
  2017. * @param {boolean} isWorker Worker capability
  2018. */
  2019. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  2020. req,
  2021. res,
  2022. ) {
  2023. try {
  2024. Authentication.checkUserId(req.userId);
  2025. const boardId = req.params.boardId;
  2026. const memberId = req.params.memberId;
  2027. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  2028. const board = ReactiveCache.getBoard(boardId);
  2029. function isTrue(data) {
  2030. try {
  2031. return data.toLowerCase() === 'true';
  2032. } catch (error) {
  2033. return data;
  2034. }
  2035. }
  2036. const query = board.setMemberPermission(
  2037. memberId,
  2038. isTrue(isAdmin),
  2039. isTrue(isNoComments),
  2040. isTrue(isCommentOnly),
  2041. isTrue(isWorker),
  2042. req.userId,
  2043. );
  2044. JsonRoutes.sendResult(res, {
  2045. code: 200,
  2046. data: query,
  2047. });
  2048. } catch (error) {
  2049. JsonRoutes.sendResult(res, {
  2050. code: 200,
  2051. data: error,
  2052. });
  2053. }
  2054. });
  2055. //ATTACHMENTS REST API
  2056. /**
  2057. * @operation get_board_attachments
  2058. * @summary Get the list of attachments of a board
  2059. *
  2060. * @param {string} boardId the board ID
  2061. * @return_type [{attachmentId: string,
  2062. * attachmentName: string,
  2063. * attachmentType: string,
  2064. * url: string,
  2065. * urlDownload: string,
  2066. * boardId: string,
  2067. * swimlaneId: string,
  2068. * listId: string,
  2069. * cardId: string
  2070. * }]
  2071. */
  2072. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  2073. const paramBoardId = req.params.boardId;
  2074. Authentication.checkBoardAccess(req.userId, paramBoardId);
  2075. JsonRoutes.sendResult(res, {
  2076. code: 200,
  2077. data: Attachments
  2078. .find({'meta.boardId': paramBoardId })
  2079. .each()
  2080. .map(function(attachment) {
  2081. return {
  2082. attachmentId: attachment._id,
  2083. attachmentName: attachment.name,
  2084. attachmentType: attachment.type,
  2085. url: attachment.link(),
  2086. urlDownload: `${attachment.link()}?download=true&token=`,
  2087. boardId: attachment.meta.boardId,
  2088. swimlaneId: attachment.meta.swimlaneId,
  2089. listId: attachment.meta.listId,
  2090. cardId: attachment.meta.cardId
  2091. };
  2092. }),
  2093. });
  2094. });
  2095. }
  2096. export default Boards;