boards.js 60 KB

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