@northern.tech/store 0.29.0 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (446) hide show
  1. package/dist/actions.cjs +21 -1131
  2. package/dist/actions.cjs.map +1 -1
  3. package/dist/actions.d.cts +212 -221
  4. package/dist/actions.d.ts +212 -220
  5. package/dist/actions.js +21 -18
  6. package/dist/actions.js.map +1 -1
  7. package/dist/api/general-api.cjs +61 -459
  8. package/dist/api/general-api.cjs.map +1 -1
  9. package/dist/api/general-api.d.cts +15 -17
  10. package/dist/api/general-api.d.ts +15 -17
  11. package/dist/api/general-api.js +56 -15
  12. package/dist/api/general-api.js.map +1 -1
  13. package/dist/api/users-api.cjs +32 -469
  14. package/dist/api/users-api.cjs.map +1 -1
  15. package/dist/api/users-api.d.cts +19 -14
  16. package/dist/api/users-api.d.ts +19 -13
  17. package/dist/api/users-api.js +30 -12
  18. package/dist/api/users-api.js.map +1 -1
  19. package/dist/appSlice/constants.cjs +190 -144
  20. package/dist/appSlice/constants.cjs.map +1 -1
  21. package/dist/appSlice/constants.d.cts +2 -159
  22. package/dist/appSlice/constants.d.ts +2 -159
  23. package/dist/appSlice/constants.js +181 -29
  24. package/dist/appSlice/constants.js.map +1 -1
  25. package/dist/appSlice/index.cjs +147 -179
  26. package/dist/appSlice/index.cjs.map +1 -1
  27. package/dist/appSlice/index.d.cts +2 -148
  28. package/dist/appSlice/index.d.ts +2 -148
  29. package/dist/appSlice/index.js +142 -18
  30. package/dist/appSlice/index.js.map +1 -1
  31. package/dist/appSlice/mocks.cjs +17 -192
  32. package/dist/appSlice/mocks.cjs.map +1 -1
  33. package/dist/appSlice/mocks.d.cts +33 -36
  34. package/dist/appSlice/mocks.d.ts +33 -36
  35. package/dist/appSlice/mocks.js +17 -25
  36. package/dist/appSlice/mocks.js.map +1 -1
  37. package/dist/appSlice/selectors.cjs +49 -91
  38. package/dist/appSlice/selectors.cjs.map +1 -1
  39. package/dist/appSlice/selectors.d.cts +216 -230
  40. package/dist/appSlice/selectors.d.ts +216 -230
  41. package/dist/appSlice/selectors.js +29 -44
  42. package/dist/appSlice/selectors.js.map +1 -1
  43. package/dist/appSlice/thunks.cjs +6 -4642
  44. package/dist/appSlice/thunks.d.cts +59 -62
  45. package/dist/appSlice/thunks.d.ts +59 -62
  46. package/dist/appSlice/thunks.js +2 -45
  47. package/dist/auth.cjs +68 -433
  48. package/dist/auth.cjs.map +1 -1
  49. package/dist/auth.d.cts +14 -14
  50. package/dist/auth.d.ts +14 -14
  51. package/dist/auth.js +65 -18
  52. package/dist/auth.js.map +1 -1
  53. package/dist/chunk-CKQMccvm.cjs +28 -0
  54. package/dist/commonConstants.cjs +14 -393
  55. package/dist/commonConstants.d.cts +2 -83
  56. package/dist/commonConstants.d.ts +2 -83
  57. package/dist/commonConstants.js +2 -33
  58. package/dist/commonSelectors.cjs +284 -1281
  59. package/dist/commonSelectors.cjs.map +1 -1
  60. package/dist/commonSelectors.d.cts +1607 -1460
  61. package/dist/commonSelectors.d.ts +1607 -1460
  62. package/dist/commonSelectors.js +277 -55
  63. package/dist/commonSelectors.js.map +1 -1
  64. package/dist/constants-5cdwz1iH.d.ts +160 -0
  65. package/dist/constants-BWEsNG5c.d.ts +28 -0
  66. package/dist/constants-BciiayPt.d.ts +17 -0
  67. package/dist/constants-C5AU0mCY.d.ts +157 -0
  68. package/dist/constants-CIx3fnBv.d.cts +17 -0
  69. package/dist/constants-CNhpIMME.d.cts +93 -0
  70. package/dist/constants-Cpgyuy_r.d.ts +57 -0
  71. package/dist/constants-D41U_jbR.d.cts +160 -0
  72. package/dist/constants-DK7fI3Rh.d.cts +28 -0
  73. package/dist/constants-DPLHhjVN.d.cts +157 -0
  74. package/dist/constants-DrwXHsJ1.d.ts +120 -0
  75. package/dist/constants-G3wymKIl.d.cts +57 -0
  76. package/dist/constants-MPLfugsi.d.cts +120 -0
  77. package/dist/constants-y2XVLQWf.d.ts +93 -0
  78. package/dist/constants.cjs +784 -974
  79. package/dist/constants.cjs.map +1 -1
  80. package/dist/constants.d.cts +8 -14
  81. package/dist/constants.d.ts +8 -14
  82. package/dist/constants.js +674 -234
  83. package/dist/constants.js.map +1 -1
  84. package/dist/deploymentsSlice/constants.cjs +15 -214
  85. package/dist/deploymentsSlice/constants.d.cts +2 -163
  86. package/dist/deploymentsSlice/constants.d.ts +2 -163
  87. package/dist/deploymentsSlice/constants.js +2 -35
  88. package/dist/deploymentsSlice/index.cjs +168 -302
  89. package/dist/deploymentsSlice/index.cjs.map +1 -1
  90. package/dist/deploymentsSlice/index.d.cts +2 -157
  91. package/dist/deploymentsSlice/index.d.ts +2 -157
  92. package/dist/deploymentsSlice/index.js +161 -18
  93. package/dist/deploymentsSlice/index.js.map +1 -1
  94. package/dist/deploymentsSlice/mocks.cjs +178 -433
  95. package/dist/deploymentsSlice/mocks.cjs.map +1 -1
  96. package/dist/deploymentsSlice/mocks.d.cts +176 -178
  97. package/dist/deploymentsSlice/mocks.d.ts +176 -178
  98. package/dist/deploymentsSlice/mocks.js +178 -144
  99. package/dist/deploymentsSlice/mocks.js.map +1 -1
  100. package/dist/deploymentsSlice/selectors.cjs +44 -223
  101. package/dist/deploymentsSlice/selectors.cjs.map +1 -1
  102. package/dist/deploymentsSlice/selectors.d.cts +73 -87
  103. package/dist/deploymentsSlice/selectors.d.ts +73 -87
  104. package/dist/deploymentsSlice/selectors.js +37 -25
  105. package/dist/deploymentsSlice/selectors.js.map +1 -1
  106. package/dist/deploymentsSlice/thunks.cjs +16 -4660
  107. package/dist/deploymentsSlice/thunks.d.cts +222 -235
  108. package/dist/deploymentsSlice/thunks.d.ts +222 -235
  109. package/dist/deploymentsSlice/thunks.js +2 -65
  110. package/dist/devicesSlice/constants.cjs +9 -68
  111. package/dist/devicesSlice/constants.d.cts +2 -37
  112. package/dist/devicesSlice/constants.d.ts +2 -37
  113. package/dist/devicesSlice/constants.js +2 -23
  114. package/dist/devicesSlice/index.cjs +215 -225
  115. package/dist/devicesSlice/index.cjs.map +1 -1
  116. package/dist/devicesSlice/index.d.cts +2 -202
  117. package/dist/devicesSlice/index.d.ts +2 -202
  118. package/dist/devicesSlice/index.js +209 -18
  119. package/dist/devicesSlice/index.js.map +1 -1
  120. package/dist/devicesSlice/mocks.cjs +146 -339
  121. package/dist/devicesSlice/mocks.cjs.map +1 -1
  122. package/dist/devicesSlice/mocks.d.cts +150 -148
  123. package/dist/devicesSlice/mocks.d.ts +150 -148
  124. package/dist/devicesSlice/mocks.js +145 -132
  125. package/dist/devicesSlice/mocks.js.map +1 -1
  126. package/dist/devicesSlice/selectors.cjs +145 -539
  127. package/dist/devicesSlice/selectors.cjs.map +1 -1
  128. package/dist/devicesSlice/selectors.d.cts +685 -699
  129. package/dist/devicesSlice/selectors.d.ts +685 -699
  130. package/dist/devicesSlice/selectors.js +123 -59
  131. package/dist/devicesSlice/selectors.js.map +1 -1
  132. package/dist/devicesSlice/thunks.cjs +48 -4724
  133. package/dist/devicesSlice/thunks.d.cts +800 -752
  134. package/dist/devicesSlice/thunks.d.ts +800 -752
  135. package/dist/devicesSlice/thunks.js +2 -129
  136. package/dist/index-4eaLEXy_.d.cts +152 -0
  137. package/dist/index-BEVkIiNa.d.cts +95 -0
  138. package/dist/index-BP0uAq36.d.cts +159 -0
  139. package/dist/index-Bwx9jEiL.d.cts +71 -0
  140. package/dist/index-CJkrL0oA.d.ts +64 -0
  141. package/dist/index-CO-py5d4.d.ts +95 -0
  142. package/dist/index-CTt-eIY8.d.cts +154 -0
  143. package/dist/index-CkwVnIqd.d.ts +159 -0
  144. package/dist/index-Cvkvcz4r.d.ts +115 -0
  145. package/dist/index-DJSlDPRX.d.ts +71 -0
  146. package/dist/index-DqyY6oZ3.d.ts +205 -0
  147. package/dist/index-DtePEQPT.d.ts +152 -0
  148. package/dist/index-Dv3Hfxk_.d.ts +154 -0
  149. package/dist/index-FyYBBeN-.d.cts +115 -0
  150. package/dist/index-Lz5JsJ6O.d.cts +205 -0
  151. package/dist/index-UPc3wvVd.d.cts +64 -0
  152. package/dist/liststatehook.cjs +83 -948
  153. package/dist/liststatehook.cjs.map +1 -1
  154. package/dist/liststatehook.d.cts +29 -239
  155. package/dist/liststatehook.d.ts +29 -239
  156. package/dist/liststatehook.js +77 -85
  157. package/dist/liststatehook.js.map +1 -1
  158. package/dist/locationutils.cjs +459 -916
  159. package/dist/locationutils.cjs.map +1 -1
  160. package/dist/locationutils.d.cts +244 -110
  161. package/dist/locationutils.d.ts +244 -110
  162. package/dist/locationutils.js +440 -44
  163. package/dist/locationutils.js.map +1 -1
  164. package/dist/monitorSlice/constants.cjs +0 -19
  165. package/dist/monitorSlice/constants.d.cts +2 -5
  166. package/dist/monitorSlice/constants.d.ts +2 -5
  167. package/dist/monitorSlice/constants.js +1 -2
  168. package/dist/monitorSlice/index.cjs +65 -82
  169. package/dist/monitorSlice/index.cjs.map +1 -1
  170. package/dist/monitorSlice/index.d.cts +2 -94
  171. package/dist/monitorSlice/index.d.ts +2 -94
  172. package/dist/monitorSlice/index.js +59 -18
  173. package/dist/monitorSlice/index.js.map +1 -1
  174. package/dist/monitorSlice/mocks.cjs +50 -127
  175. package/dist/monitorSlice/mocks.cjs.map +1 -1
  176. package/dist/monitorSlice/mocks.d.cts +49 -49
  177. package/dist/monitorSlice/mocks.d.ts +49 -49
  178. package/dist/monitorSlice/mocks.js +49 -63
  179. package/dist/monitorSlice/mocks.js.map +1 -1
  180. package/dist/monitorSlice/selectors.cjs +5 -29
  181. package/dist/monitorSlice/selectors.cjs.map +1 -1
  182. package/dist/monitorSlice/selectors.d.cts +10 -1
  183. package/dist/monitorSlice/selectors.d.ts +10 -1
  184. package/dist/monitorSlice/selectors.js +5 -6
  185. package/dist/monitorSlice/selectors.js.map +1 -1
  186. package/dist/monitorSlice/thunks.cjs +83 -2513
  187. package/dist/monitorSlice/thunks.cjs.map +1 -1
  188. package/dist/monitorSlice/thunks.d.cts +112 -120
  189. package/dist/monitorSlice/thunks.d.ts +112 -120
  190. package/dist/monitorSlice/thunks.js +78 -42
  191. package/dist/monitorSlice/thunks.js.map +1 -1
  192. package/dist/onboardingSlice/constants.cjs +44 -69
  193. package/dist/onboardingSlice/constants.cjs.map +1 -1
  194. package/dist/onboardingSlice/constants.d.cts +2 -26
  195. package/dist/onboardingSlice/constants.d.ts +2 -26
  196. package/dist/onboardingSlice/constants.js +43 -7
  197. package/dist/onboardingSlice/constants.js.map +1 -1
  198. package/dist/onboardingSlice/index.cjs +53 -73
  199. package/dist/onboardingSlice/index.cjs.map +1 -1
  200. package/dist/onboardingSlice/index.d.cts +2 -62
  201. package/dist/onboardingSlice/index.d.ts +2 -62
  202. package/dist/onboardingSlice/index.js +47 -13
  203. package/dist/onboardingSlice/index.js.map +1 -1
  204. package/dist/onboardingSlice/mocks.cjs +12 -81
  205. package/dist/onboardingSlice/mocks.cjs.map +1 -1
  206. package/dist/onboardingSlice/mocks.d.cts +14 -15
  207. package/dist/onboardingSlice/mocks.d.ts +14 -15
  208. package/dist/onboardingSlice/mocks.js +12 -15
  209. package/dist/onboardingSlice/mocks.js.map +1 -1
  210. package/dist/onboardingSlice/selectors.cjs +5 -29
  211. package/dist/onboardingSlice/selectors.cjs.map +1 -1
  212. package/dist/onboardingSlice/selectors.d.cts +6 -1
  213. package/dist/onboardingSlice/selectors.d.ts +6 -1
  214. package/dist/onboardingSlice/selectors.js +5 -6
  215. package/dist/onboardingSlice/selectors.js.map +1 -1
  216. package/dist/onboardingSlice/thunks.cjs +8 -4752
  217. package/dist/onboardingSlice/thunks.d.cts +124 -143
  218. package/dist/onboardingSlice/thunks.d.ts +124 -143
  219. package/dist/onboardingSlice/thunks.js +2 -49
  220. package/dist/organizationSlice/constants.cjs +11 -95
  221. package/dist/organizationSlice/constants.d.cts +2 -91
  222. package/dist/organizationSlice/constants.d.ts +2 -91
  223. package/dist/organizationSlice/constants.js +2 -27
  224. package/dist/organizationSlice/index.cjs +113 -152
  225. package/dist/organizationSlice/index.cjs.map +1 -1
  226. package/dist/organizationSlice/index.d.cts +2 -74
  227. package/dist/organizationSlice/index.d.ts +2 -74
  228. package/dist/organizationSlice/index.js +106 -18
  229. package/dist/organizationSlice/index.js.map +1 -1
  230. package/dist/organizationSlice/mocks.cjs +215 -406
  231. package/dist/organizationSlice/mocks.cjs.map +1 -1
  232. package/dist/organizationSlice/mocks.d.cts +209 -212
  233. package/dist/organizationSlice/mocks.d.ts +209 -212
  234. package/dist/organizationSlice/mocks.js +214 -184
  235. package/dist/organizationSlice/mocks.js.map +1 -1
  236. package/dist/organizationSlice/selectors.cjs +97 -474
  237. package/dist/organizationSlice/selectors.cjs.map +1 -1
  238. package/dist/organizationSlice/selectors.d.cts +381 -389
  239. package/dist/organizationSlice/selectors.d.ts +381 -389
  240. package/dist/organizationSlice/selectors.js +78 -50
  241. package/dist/organizationSlice/selectors.js.map +1 -1
  242. package/dist/organizationSlice/thunks.cjs +43 -5156
  243. package/dist/organizationSlice/thunks.d.cts +638 -649
  244. package/dist/organizationSlice/thunks.d.ts +638 -649
  245. package/dist/organizationSlice/thunks.js +2 -119
  246. package/dist/organizationSlice/types.cjs +0 -19
  247. package/dist/organizationSlice/types.d.cts +2 -88
  248. package/dist/organizationSlice/types.d.ts +2 -88
  249. package/dist/organizationSlice/types.js +1 -1
  250. package/dist/releasesSlice/constants.cjs +17 -41
  251. package/dist/releasesSlice/constants.cjs.map +1 -1
  252. package/dist/releasesSlice/constants.d.cts +2 -15
  253. package/dist/releasesSlice/constants.d.ts +2 -15
  254. package/dist/releasesSlice/constants.js +13 -14
  255. package/dist/releasesSlice/constants.js.map +1 -1
  256. package/dist/releasesSlice/index.cjs +106 -179
  257. package/dist/releasesSlice/index.cjs.map +1 -1
  258. package/dist/releasesSlice/index.d.cts +2 -113
  259. package/dist/releasesSlice/index.d.ts +2 -113
  260. package/dist/releasesSlice/index.js +100 -18
  261. package/dist/releasesSlice/index.js.map +1 -1
  262. package/dist/releasesSlice/mocks.cjs +44 -220
  263. package/dist/releasesSlice/mocks.cjs.map +1 -1
  264. package/dist/releasesSlice/mocks.d.cts +63 -61
  265. package/dist/releasesSlice/mocks.d.ts +63 -61
  266. package/dist/releasesSlice/mocks.js +43 -59
  267. package/dist/releasesSlice/mocks.js.map +1 -1
  268. package/dist/releasesSlice/selectors.cjs +44 -439
  269. package/dist/releasesSlice/selectors.cjs.map +1 -1
  270. package/dist/releasesSlice/selectors.d.cts +268 -280
  271. package/dist/releasesSlice/selectors.d.ts +268 -280
  272. package/dist/releasesSlice/selectors.js +31 -36
  273. package/dist/releasesSlice/selectors.js.map +1 -1
  274. package/dist/releasesSlice/thunks.cjs +436 -2885
  275. package/dist/releasesSlice/thunks.cjs.map +1 -1
  276. package/dist/releasesSlice/thunks.d.cts +305 -307
  277. package/dist/releasesSlice/thunks.d.ts +305 -307
  278. package/dist/releasesSlice/thunks.js +413 -74
  279. package/dist/releasesSlice/thunks.js.map +1 -1
  280. package/dist/selectors.cjs +136 -1542
  281. package/dist/selectors.d.cts +10 -36
  282. package/dist/selectors.d.ts +10 -36
  283. package/dist/selectors.js +10 -284
  284. package/dist/sockethook.cjs +140 -515
  285. package/dist/sockethook.cjs.map +1 -1
  286. package/dist/sockethook.d.cts +25 -9
  287. package/dist/sockethook.d.ts +25 -9
  288. package/dist/sockethook.js +134 -135
  289. package/dist/sockethook.js.map +1 -1
  290. package/dist/store-BQxOSRC1.d.ts +234 -0
  291. package/dist/store-BiIA0r0A.d.cts +234 -0
  292. package/dist/store.cjs +117 -1291
  293. package/dist/store.cjs.map +1 -1
  294. package/dist/store.d.cts +3 -206
  295. package/dist/store.d.ts +3 -206
  296. package/dist/store.js +110 -32
  297. package/dist/store.js.map +1 -1
  298. package/dist/storehooks.cjs +240 -5790
  299. package/dist/storehooks.cjs.map +1 -1
  300. package/dist/storehooks.d.cts +76 -4
  301. package/dist/storehooks.d.ts +76 -4
  302. package/dist/storehooks.js +229 -266
  303. package/dist/storehooks.js.map +1 -1
  304. package/dist/thunks.cjs +2614 -5924
  305. package/dist/thunks.cjs.map +1 -1
  306. package/dist/thunks.d.cts +9 -36
  307. package/dist/thunks.d.ts +9 -36
  308. package/dist/thunks.js +2439 -385
  309. package/dist/thunks.js.map +1 -1
  310. package/dist/types-B2NRQLFw.d.ts +88 -0
  311. package/dist/types-ClEfo0dK.d.cts +88 -0
  312. package/dist/useDeploymentDevice.cjs +26 -4656
  313. package/dist/useDeploymentDevice.cjs.map +1 -1
  314. package/dist/useDeploymentDevice.d.cts +4 -2
  315. package/dist/useDeploymentDevice.d.ts +4 -2
  316. package/dist/useDeploymentDevice.js +21 -60
  317. package/dist/useDeploymentDevice.js.map +1 -1
  318. package/dist/usersSlice/constants.cjs +8 -55
  319. package/dist/usersSlice/constants.d.cts +2 -52
  320. package/dist/usersSlice/constants.d.ts +2 -52
  321. package/dist/usersSlice/constants.js +2 -21
  322. package/dist/usersSlice/index.cjs +132 -172
  323. package/dist/usersSlice/index.cjs.map +1 -1
  324. package/dist/usersSlice/index.d.cts +2 -152
  325. package/dist/usersSlice/index.d.ts +2 -152
  326. package/dist/usersSlice/index.js +125 -18
  327. package/dist/usersSlice/index.js.map +1 -1
  328. package/dist/usersSlice/mocks.cjs +55 -196
  329. package/dist/usersSlice/mocks.cjs.map +1 -1
  330. package/dist/usersSlice/mocks.d.cts +68 -72
  331. package/dist/usersSlice/mocks.d.ts +68 -72
  332. package/dist/usersSlice/mocks.js +54 -46
  333. package/dist/usersSlice/mocks.js.map +1 -1
  334. package/dist/usersSlice/selectors.cjs +65 -567
  335. package/dist/usersSlice/selectors.cjs.map +1 -1
  336. package/dist/usersSlice/selectors.d.cts +364 -376
  337. package/dist/usersSlice/selectors.d.ts +364 -376
  338. package/dist/usersSlice/selectors.js +44 -50
  339. package/dist/usersSlice/selectors.js.map +1 -1
  340. package/dist/usersSlice/thunks.cjs +39 -4704
  341. package/dist/usersSlice/thunks.d.cts +807 -843
  342. package/dist/usersSlice/thunks.d.ts +807 -843
  343. package/dist/usersSlice/thunks.js +2 -111
  344. package/dist/utils-B4I595rf.d.cts +104 -0
  345. package/dist/utils-DNnSR4S_.d.ts +104 -0
  346. package/dist/utils.cjs +229 -850
  347. package/dist/utils.cjs.map +1 -1
  348. package/dist/utils.d.cts +2 -80
  349. package/dist/utils.d.ts +2 -80
  350. package/dist/utils.js +210 -50
  351. package/dist/utils.js.map +1 -1
  352. package/package.json +11 -13
  353. package/dist/appSlice/thunks.cjs.map +0 -1
  354. package/dist/appSlice/thunks.js.map +0 -1
  355. package/dist/chunk-2DYA3X77.js +0 -15
  356. package/dist/chunk-2DYA3X77.js.map +0 -1
  357. package/dist/chunk-2QIGK5IU.js +0 -143
  358. package/dist/chunk-2QIGK5IU.js.map +0 -1
  359. package/dist/chunk-4573DUCR.js +0 -396
  360. package/dist/chunk-4573DUCR.js.map +0 -1
  361. package/dist/chunk-4BHM6WVX.js +0 -50
  362. package/dist/chunk-4BHM6WVX.js.map +0 -1
  363. package/dist/chunk-4BUO44SS.js +0 -316
  364. package/dist/chunk-4BUO44SS.js.map +0 -1
  365. package/dist/chunk-4YLOOOZH.js +0 -144
  366. package/dist/chunk-4YLOOOZH.js.map +0 -1
  367. package/dist/chunk-525LX7VL.js +0 -157
  368. package/dist/chunk-525LX7VL.js.map +0 -1
  369. package/dist/chunk-5OLM3HEG.js +0 -41
  370. package/dist/chunk-5OLM3HEG.js.map +0 -1
  371. package/dist/chunk-66LI4BJO.js +0 -162
  372. package/dist/chunk-66LI4BJO.js.map +0 -1
  373. package/dist/chunk-CMXRPUOF.js +0 -723
  374. package/dist/chunk-CMXRPUOF.js.map +0 -1
  375. package/dist/chunk-CQXDAXQF.js +0 -51
  376. package/dist/chunk-CQXDAXQF.js.map +0 -1
  377. package/dist/chunk-DBBE6D36.js +0 -115
  378. package/dist/chunk-DBBE6D36.js.map +0 -1
  379. package/dist/chunk-FAJ3I2UQ.js +0 -47
  380. package/dist/chunk-FAJ3I2UQ.js.map +0 -1
  381. package/dist/chunk-FAKWYYOB.js +0 -59
  382. package/dist/chunk-FAKWYYOB.js.map +0 -1
  383. package/dist/chunk-FXPRG4WH.js +0 -2875
  384. package/dist/chunk-FXPRG4WH.js.map +0 -1
  385. package/dist/chunk-GX3X2E57.js +0 -157
  386. package/dist/chunk-GX3X2E57.js.map +0 -1
  387. package/dist/chunk-HVZ5BOM6.js +0 -61
  388. package/dist/chunk-HVZ5BOM6.js.map +0 -1
  389. package/dist/chunk-JIS4PA3R.js +0 -7
  390. package/dist/chunk-JIS4PA3R.js.map +0 -1
  391. package/dist/chunk-KEQAPMP6.js +0 -110
  392. package/dist/chunk-KEQAPMP6.js.map +0 -1
  393. package/dist/chunk-LSAJE3IU.js +0 -115
  394. package/dist/chunk-LSAJE3IU.js.map +0 -1
  395. package/dist/chunk-NMAXZ3ZY.js +0 -1
  396. package/dist/chunk-NMAXZ3ZY.js.map +0 -1
  397. package/dist/chunk-QX67O5A2.js +0 -82
  398. package/dist/chunk-QX67O5A2.js.map +0 -1
  399. package/dist/chunk-SDHCQ62K.js +0 -246
  400. package/dist/chunk-SDHCQ62K.js.map +0 -1
  401. package/dist/chunk-SDWPOLHM.js +0 -25
  402. package/dist/chunk-SDWPOLHM.js.map +0 -1
  403. package/dist/chunk-UBFFGYQ4.js +0 -204
  404. package/dist/chunk-UBFFGYQ4.js.map +0 -1
  405. package/dist/chunk-UE2EPKRU.js +0 -142
  406. package/dist/chunk-UE2EPKRU.js.map +0 -1
  407. package/dist/chunk-VK6FVQ5K.js +0 -58
  408. package/dist/chunk-VK6FVQ5K.js.map +0 -1
  409. package/dist/chunk-VLII64V6.js +0 -44
  410. package/dist/chunk-VLII64V6.js.map +0 -1
  411. package/dist/chunk-WXRYJOL3.js +0 -68
  412. package/dist/chunk-WXRYJOL3.js.map +0 -1
  413. package/dist/chunk-XHLNGIAP.js +0 -100
  414. package/dist/chunk-XHLNGIAP.js.map +0 -1
  415. package/dist/chunk-YO22XLHI.js +0 -7
  416. package/dist/chunk-YO22XLHI.js.map +0 -1
  417. package/dist/chunk-Z4QLZNAN.js +0 -448
  418. package/dist/chunk-Z4QLZNAN.js.map +0 -1
  419. package/dist/chunk-ZKAH3APE.js +0 -1
  420. package/dist/chunk-ZKAH3APE.js.map +0 -1
  421. package/dist/commonConstants.cjs.map +0 -1
  422. package/dist/commonConstants.js.map +0 -1
  423. package/dist/deploymentsSlice/constants.cjs.map +0 -1
  424. package/dist/deploymentsSlice/constants.js.map +0 -1
  425. package/dist/deploymentsSlice/thunks.cjs.map +0 -1
  426. package/dist/deploymentsSlice/thunks.js.map +0 -1
  427. package/dist/devicesSlice/constants.cjs.map +0 -1
  428. package/dist/devicesSlice/constants.js.map +0 -1
  429. package/dist/devicesSlice/thunks.cjs.map +0 -1
  430. package/dist/devicesSlice/thunks.js.map +0 -1
  431. package/dist/monitorSlice/constants.cjs.map +0 -1
  432. package/dist/monitorSlice/constants.js.map +0 -1
  433. package/dist/onboardingSlice/thunks.cjs.map +0 -1
  434. package/dist/onboardingSlice/thunks.js.map +0 -1
  435. package/dist/organizationSlice/constants.cjs.map +0 -1
  436. package/dist/organizationSlice/constants.js.map +0 -1
  437. package/dist/organizationSlice/thunks.cjs.map +0 -1
  438. package/dist/organizationSlice/thunks.js.map +0 -1
  439. package/dist/organizationSlice/types.cjs.map +0 -1
  440. package/dist/organizationSlice/types.js.map +0 -1
  441. package/dist/selectors.cjs.map +0 -1
  442. package/dist/selectors.js.map +0 -1
  443. package/dist/usersSlice/constants.cjs.map +0 -1
  444. package/dist/usersSlice/constants.js.map +0 -1
  445. package/dist/usersSlice/thunks.cjs.map +0 -1
  446. package/dist/usersSlice/thunks.js.map +0 -1
@@ -1,2875 +0,0 @@
1
- import {
2
- getDeviceMonitorConfig,
3
- getLatestDeviceAlerts
4
- } from "./chunk-KEQAPMP6.js";
5
- import {
6
- commonErrorFallback,
7
- commonErrorHandler,
8
- createAppAsyncThunk
9
- } from "./chunk-UE2EPKRU.js";
10
- import {
11
- users_api_default
12
- } from "./chunk-SDWPOLHM.js";
13
- import {
14
- general_api_default
15
- } from "./chunk-VK6FVQ5K.js";
16
- import {
17
- actions_default
18
- } from "./chunk-5OLM3HEG.js";
19
- import {
20
- actions as actions6,
21
- sliceName as sliceName6
22
- } from "./chunk-4YLOOOZH.js";
23
- import {
24
- actions as actions5,
25
- sliceName as sliceName5
26
- } from "./chunk-LSAJE3IU.js";
27
- import {
28
- actions as actions4,
29
- sliceName as sliceName4
30
- } from "./chunk-CQXDAXQF.js";
31
- import {
32
- actions as actions3,
33
- sliceName as sliceName3
34
- } from "./chunk-UBFFGYQ4.js";
35
- import {
36
- actions,
37
- sliceName
38
- } from "./chunk-GX3X2E57.js";
39
- import {
40
- actions as actions2,
41
- sliceName as sliceName2
42
- } from "./chunk-2QIGK5IU.js";
43
- import {
44
- cleanUp,
45
- getSessionInfo,
46
- setSessionInfo
47
- } from "./chunk-WXRYJOL3.js";
48
- import {
49
- getAttrsEndpoint,
50
- getDeviceReportsForUser,
51
- getOnboardingState,
52
- getSearchEndpoint,
53
- getTenantCapabilities,
54
- getUserCapabilities
55
- } from "./chunk-4BUO44SS.js";
56
- import {
57
- getCurrentUser,
58
- getGlobalSettings,
59
- getIdAttribute,
60
- getOfflineThresholdSettings,
61
- getRolesById,
62
- getSelectedDeviceAttribute,
63
- getTooltipsState,
64
- getUserSettings,
65
- getUsersById
66
- } from "./chunk-QX67O5A2.js";
67
- import {
68
- getAuditlogState,
69
- getDeviceTwinIntegrations,
70
- getOrganization,
71
- getSpLimits,
72
- getTenantsList
73
- } from "./chunk-XHLNGIAP.js";
74
- import {
75
- getDeploymentsById,
76
- getDeploymentsByStatus
77
- } from "./chunk-FAKWYYOB.js";
78
- import {
79
- getAcceptedDevices,
80
- getDeviceById,
81
- getDeviceCountsByStatus,
82
- getDeviceFilters,
83
- getDeviceListState,
84
- getDeviceReports,
85
- getDevicesById,
86
- getGroupsById,
87
- getSelectedGroup
88
- } from "./chunk-66LI4BJO.js";
89
- import {
90
- getFeatures,
91
- getHostedAnnouncement,
92
- getSearchState
93
- } from "./chunk-4BHM6WVX.js";
94
- import {
95
- convertDeviceListStateToFilters,
96
- convertToBackendSPLimits,
97
- extractErrorMessage,
98
- filtersFilter,
99
- getComparisonCompatibleVersion,
100
- mapDeviceAttributes,
101
- mapFiltersToTerms,
102
- mapTermsToFilters,
103
- mergePermissions,
104
- parseSubscriptionPreview,
105
- progress
106
- } from "./chunk-SDHCQ62K.js";
107
- import {
108
- ALL_DEVICE_STATES,
109
- ALL_RELEASES,
110
- APPLICATION_JSON_CONTENT_TYPE,
111
- APPLICATION_JWT_CONTENT_TYPE,
112
- DEPLOYMENT_ROUTES,
113
- DEPLOYMENT_STATES,
114
- DEPLOYMENT_TYPES,
115
- DEVICE_FILTERING_OPTIONS,
116
- DEVICE_LIST_DEFAULTS,
117
- DEVICE_STATES,
118
- EXTERNAL_PROVIDER,
119
- MAX_PAGE_SIZE,
120
- OWN_USER_ID,
121
- PermissionTypes,
122
- READ_STATES,
123
- SORTING_OPTIONS,
124
- SSO_TYPES,
125
- TENANT_LIST_DEFAULT,
126
- TIMEOUTS,
127
- UNGROUPED_GROUP,
128
- USER_LOGOUT,
129
- apiRoot,
130
- auditLogsApiUrl,
131
- defaultPermissionSets,
132
- deploymentPrototype,
133
- deploymentsApiUrl,
134
- deploymentsApiUrlV2,
135
- deviceAuthV2,
136
- deviceConfig,
137
- deviceConnect,
138
- emptyFilter,
139
- emptyRole,
140
- emptyUiPermissions,
141
- headerNames,
142
- inventoryApiUrl,
143
- inventoryApiUrlV2,
144
- iotManagerBaseURL,
145
- itemUiPermissionsReducer,
146
- maxSessionAge,
147
- rolesById,
148
- scopedPermissionAreas,
149
- settingsKeys,
150
- ssoIdpApiUrlv1,
151
- tenantadmApiUrlv1,
152
- tenantadmApiUrlv2,
153
- twoFAStates,
154
- uiPermissionsByArea,
155
- uiPermissionsById,
156
- useradmApiUrl,
157
- useradmApiUrlv2
158
- } from "./chunk-CMXRPUOF.js";
159
- import {
160
- rootfsImageVersion
161
- } from "./chunk-2DYA3X77.js";
162
- import {
163
- onboardingSteps,
164
- orderedOnboardingSteps
165
- } from "./chunk-FAJ3I2UQ.js";
166
- import {
167
- ADDONS,
168
- PLANS,
169
- locations
170
- } from "./chunk-DBBE6D36.js";
171
-
172
- // src/appSlice/thunks.ts
173
- import { deepCompare as deepCompare4, extractErrorMessage as extractErrorMessage3 } from "@northern.tech/utils/helpers";
174
- import Cookies4 from "universal-cookie";
175
-
176
- // src/deploymentsSlice/thunks.ts
177
- import { customSort, deepCompare, isEmpty, standardizePhases } from "@northern.tech/utils/helpers";
178
- import Tracking from "@northern.tech/utils/tracking";
179
- import validator from "validator";
180
- var { isUUID } = validator;
181
- var { receivedDevice, setSnackbar } = actions_default;
182
- var { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
183
- var deriveDeploymentGroup = ({ filter, group, groups = [], name }) => group || groups.length === 1 && !isUUID(name) ? groups[0] : filter?.name;
184
- var transformDeployments = (deployments, deploymentsById) => deployments.sort(customSort(true, "created")).reduce(
185
- (accu, item) => {
186
- const filter = item.filter;
187
- let deployment = {
188
- ...deploymentPrototype,
189
- ...deploymentsById[item.id],
190
- ...item,
191
- // TODO: explicitly set filter term types to address scope type mismatch in deployment specs
192
- // @ts-expect-error: type misalignment in filter terms type
193
- filter: filter ? { ...filter, name: filter.name ?? filter.id, filters: mapTermsToFilters(filter.terms) } : void 0,
194
- name: decodeURIComponent(item.name)
195
- };
196
- deployment = { ...deployment, group: deriveDeploymentGroup(deployment) };
197
- accu.deployments[item.id] = deployment;
198
- accu.deploymentIds.push(item.id);
199
- return accu;
200
- },
201
- { deployments: {}, deploymentIds: [] }
202
- );
203
- var getDeploymentsByStatus2 = createAppAsyncThunk(
204
- `${sliceName2}/getDeploymentsByStatus`,
205
- (options, { dispatch, getState }) => {
206
- const { status, page = defaultPage, perPage = defaultPerPage, startDate, endDate, group, type, shouldSelect = true, sort = SORTING_OPTIONS.desc } = options;
207
- const created_after = startDate ? `&created_after=${startDate}` : "";
208
- const created_before = endDate ? `&created_before=${endDate}` : "";
209
- const { attribute, scope } = getIdAttribute(getState());
210
- const attributeHint = `&id_attribute=${attribute}&id_scope=${scope}`;
211
- const search = group ? `&name=${group}${attributeHint}` : "";
212
- const typeFilter = type ? `&type=${type}` : "";
213
- return general_api_default.get(
214
- `${deploymentsApiUrlV2}/deployments?status=${status}&per_page=${perPage}&page=${page}${created_after}${created_before}${search}${typeFilter}&sort=${sort}`
215
- ).then((res) => {
216
- const { deployments, deploymentIds } = transformDeployments(res.data, getState().deployments.byId);
217
- const total = Number(res.headers[headerNames.total]);
218
- let tasks = [
219
- dispatch(actions2.receivedDeployments(deployments)),
220
- dispatch(
221
- actions2.receivedDeploymentsForStatus({
222
- deploymentIds,
223
- status,
224
- total: !(startDate || endDate || group || type) ? total : getState().deployments.byStatus[status].total
225
- })
226
- )
227
- ];
228
- tasks = deploymentIds.reduce((accu, deploymentId) => {
229
- if (deployments[deploymentId].type === DEPLOYMENT_TYPES.configuration) {
230
- accu.push(dispatch(getSingleDeployment(deploymentId)));
231
- }
232
- return accu;
233
- }, tasks);
234
- if (shouldSelect) {
235
- tasks.push(dispatch(actions2.selectDeploymentsForStatus({ deploymentIds, status, total })));
236
- }
237
- tasks.push({ deploymentIds, total });
238
- return Promise.all(tasks);
239
- });
240
- }
241
- );
242
- var isWithinFirstMonth = (expirationDate) => {
243
- if (!expirationDate) {
244
- return false;
245
- }
246
- const endOfFirstMonth = new Date(expirationDate);
247
- endOfFirstMonth.setMonth(endOfFirstMonth.getMonth() - 11);
248
- return endOfFirstMonth > /* @__PURE__ */ new Date();
249
- };
250
- var trackDeploymentCreation = (totalDeploymentCount, hasDeployments, trial_expiration) => {
251
- Tracking.event({ category: "deployments", action: "create" });
252
- if (!totalDeploymentCount) {
253
- if (!hasDeployments) {
254
- Tracking.event({ category: "deployments", action: "create_initial_deployment" });
255
- if (isWithinFirstMonth(trial_expiration)) {
256
- Tracking.event({ category: "deployments", action: "create_initial_deployment_first_month" });
257
- }
258
- }
259
- Tracking.event({ category: "deployments", action: "create_initial_deployment_user" });
260
- }
261
- };
262
- var MAX_PREVIOUS_PHASES_COUNT = 5;
263
- var createDeployment = createAppAsyncThunk(
264
- `${sliceName2}/createDeployment`,
265
- ({
266
- newDeployment,
267
- hasNewRetryDefault = false
268
- }, { dispatch, getState }) => {
269
- let request;
270
- if ("filter_id" in newDeployment && newDeployment.filter_id) {
271
- request = general_api_default.post(`${deploymentsApiUrlV2}/deployments`, newDeployment);
272
- } else if ("group" in newDeployment && newDeployment.group) {
273
- request = general_api_default.post(`${deploymentsApiUrl}/deployments/group/${newDeployment.group}`, newDeployment);
274
- } else {
275
- request = general_api_default.post(`${deploymentsApiUrl}/deployments`, newDeployment);
276
- }
277
- const totalDeploymentCount = Object.values(getDeploymentsByStatus(getState())).reduce(
278
- (accu, item) => accu + item.total,
279
- 0
280
- );
281
- const { hasDeployments } = getGlobalSettings(getState());
282
- const { trial_expiration } = getOrganization(getState());
283
- return request.catch((err) => commonErrorHandler(err, "Error creating deployment.", dispatch)).then((data) => {
284
- const lastslashindex = data.headers.location.lastIndexOf("/");
285
- const deploymentId = data.headers.location.substring(lastslashindex + 1);
286
- const deployment = {
287
- ...newDeployment,
288
- id: deploymentId,
289
- devices: "devices" in newDeployment && newDeployment.devices ? newDeployment.devices.map((id) => ({ id, status: "pending" })) : [],
290
- statistics: { status: {} }
291
- };
292
- const tasks = [
293
- dispatch(actions2.createdDeployment(deployment)),
294
- dispatch(getSingleDeployment(deploymentId)),
295
- dispatch(setSnackbar({ message: "Deployment created successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))
296
- ];
297
- trackDeploymentCreation(totalDeploymentCount, hasDeployments, trial_expiration);
298
- const { canManageUsers } = getUserCapabilities(getState());
299
- if (canManageUsers) {
300
- const { phases, retries } = newDeployment;
301
- const { previousPhases = [], retries: previousRetries = 0 } = getGlobalSettings(getState());
302
- const newSettings = { retries: hasNewRetryDefault ? retries : previousRetries, hasDeployments: true };
303
- if (phases) {
304
- const standardPhases = standardizePhases(phases);
305
- const prevPhases = previousPhases.map(standardizePhases);
306
- if (!prevPhases.find((previousPhaseList) => previousPhaseList.every((oldPhase) => standardPhases.find((phase) => deepCompare(phase, oldPhase))))) {
307
- prevPhases.push(standardPhases);
308
- }
309
- newSettings.previousPhases = prevPhases.slice(-1 * MAX_PREVIOUS_PHASES_COUNT);
310
- }
311
- tasks.push(dispatch(saveGlobalSettings(newSettings)));
312
- }
313
- return Promise.all(tasks);
314
- });
315
- }
316
- );
317
- var getDeploymentDevices = createAppAsyncThunk(
318
- `${sliceName2}/getDeploymentDevices`,
319
- (options, { dispatch, getState }) => {
320
- const { id, page = defaultPage, perPage = defaultPerPage } = options;
321
- return general_api_default.get(`${deploymentsApiUrl}/deployments/${id}/devices/list?&page=${page}&per_page=${perPage}`).then((response) => {
322
- const { devices: deploymentDevices = {} } = getState().deployments.byId[id] || {};
323
- const devices = response.data.reduce((accu, item) => {
324
- accu[item.id] = item;
325
- const log = (deploymentDevices[item.id] || {}).log;
326
- if (log) {
327
- accu[item.id].log = log;
328
- }
329
- return accu;
330
- }, {});
331
- const selectedDeviceIds = Object.keys(devices);
332
- let tasks = [
333
- dispatch(
334
- actions2.receivedDeploymentDevices({
335
- id,
336
- devices,
337
- selectedDeviceIds,
338
- totalDeviceCount: Number(response.headers[headerNames.total])
339
- })
340
- )
341
- ];
342
- const devicesById = getDevicesById(getState());
343
- const lackingData = selectedDeviceIds.reduce((accu, deviceId) => {
344
- const device = devicesById[deviceId];
345
- if (!device || !device.identity_data || !device.attributes || Object.keys(device.attributes).length === 0) {
346
- accu.push(deviceId);
347
- }
348
- return accu;
349
- }, []);
350
- tasks = lackingData.reduce((accu, deviceId) => [...accu, dispatch(getDeviceById2(deviceId)), dispatch(getDeviceAuth(deviceId))], tasks);
351
- return Promise.all(tasks);
352
- });
353
- }
354
- );
355
- var parseDeviceDeployment = ({
356
- deployment: { id, artifact_name: release, status: deploymentStatus },
357
- device: { created, deleted, id: deviceId, finished, status, log }
358
- }) => ({
359
- id,
360
- release,
361
- created,
362
- deleted,
363
- deviceId,
364
- finished,
365
- status,
366
- log,
367
- route: Object.values(DEPLOYMENT_ROUTES).reduce((accu, { key, states }) => {
368
- if (!accu) {
369
- return states.includes(deploymentStatus) ? key : accu;
370
- }
371
- return accu;
372
- }, "")
373
- });
374
- var getDeviceDeployments = createAppAsyncThunk(`${sliceName2}/getDeviceDeployments`, (options, { dispatch }) => {
375
- const { deviceId, filterSelection = [], page = defaultPage, perPage = defaultPerPage } = options;
376
- const filters = filterSelection.map((item) => `&status=${item}`).join("");
377
- return general_api_default.get(`${deploymentsApiUrl}/deployments/devices/${deviceId}?page=${page}&per_page=${perPage}${filters}`).then(
378
- ({ data, headers }) => Promise.resolve(
379
- dispatch(
380
- receivedDevice({
381
- id: deviceId,
382
- deviceDeployments: data.map(parseDeviceDeployment),
383
- deploymentsCount: Number(headers[headerNames.total])
384
- })
385
- )
386
- )
387
- ).catch((err) => commonErrorHandler(err, "There was an error retrieving the device deployment history:", dispatch));
388
- });
389
- var resetDeviceDeployments = createAppAsyncThunk(
390
- `${sliceName2}/resetDeviceDeployments`,
391
- (deviceId, { dispatch }) => general_api_default.delete(`${deploymentsApiUrl}/deployments/devices/${deviceId}/history`).then(() => Promise.resolve(dispatch(getDeviceDeployments({ deviceId })))).catch((err) => commonErrorHandler(err, "There was an error resetting the device deployment history:", dispatch))
392
- );
393
- var getSingleDeployment = createAppAsyncThunk(
394
- `${sliceName2}/getSingleDeployment`,
395
- (id, { dispatch, getState }) => general_api_default.get(`${deploymentsApiUrl}/deployments/${id}`).then(({ data }) => {
396
- const { deployments } = transformDeployments([data], getState().deployments.byId);
397
- return Promise.resolve(dispatch(actions2.receivedDeployment(deployments[id])));
398
- })
399
- );
400
- var getDeviceLog = createAppAsyncThunk(
401
- `${sliceName2}/getDeviceLog`,
402
- ({ deploymentId, deviceId }, { dispatch }) => general_api_default.get(`${deploymentsApiUrl}/deployments/${deploymentId}/devices/${deviceId}/log`).catch((e) => {
403
- console.log("no log here", e);
404
- return Promise.reject();
405
- }).then(
406
- ({ data: log }) => Promise.all([Promise.resolve(dispatch(actions2.receivedDeploymentDeviceLog({ id: deploymentId, deviceId, log }))), Promise.resolve(log)])
407
- )
408
- );
409
- var abortDeployment = createAppAsyncThunk(
410
- `${sliceName2}/abortDeployment`,
411
- (deploymentId, { dispatch, getState }) => general_api_default.put(`${deploymentsApiUrl}/deployments/${deploymentId}/status`, { status: "aborted" }).then(() => {
412
- const deploymentsByStatus = getDeploymentsByStatus(getState());
413
- let status = DEPLOYMENT_STATES.pending;
414
- let index = deploymentsByStatus.pending.deploymentIds.findIndex((id) => id === deploymentId);
415
- if (index < 0) {
416
- status = DEPLOYMENT_STATES.inprogress;
417
- index = deploymentsByStatus.inprogress.deploymentIds.findIndex((id) => id === deploymentId);
418
- }
419
- const deploymentIds = [...deploymentsByStatus[status].deploymentIds.slice(0, index), ...deploymentsByStatus[status].deploymentIds.slice(index + 1)];
420
- const deploymentsById = getDeploymentsById(getState());
421
- const deployments = deploymentIds.reduce((accu, id) => {
422
- accu[id] = deploymentsById[id];
423
- return accu;
424
- }, {});
425
- const total = Math.max(deploymentsByStatus[status].total - 1, 0);
426
- return Promise.all([
427
- dispatch(actions2.receivedDeployments(deployments)),
428
- dispatch(actions2.receivedDeploymentsForStatus({ deploymentIds, status, total })),
429
- dispatch(actions2.removedDeployment(deploymentId)),
430
- dispatch(setSnackbar("The deployment was successfully aborted"))
431
- ]);
432
- }).catch((err) => commonErrorHandler(err, "There was an error while aborting the deployment:", dispatch))
433
- );
434
- var updateDeploymentControlMap = createAppAsyncThunk(
435
- `${sliceName2}/updateDeploymentControlMap`,
436
- ({ deploymentId, updateControlMap }, { dispatch }) => general_api_default.patch(`${deploymentsApiUrl}/deployments/${deploymentId}`, { update_control_map: updateControlMap }).catch((err) => commonErrorHandler(err, "There was an error while updating the deployment status:", dispatch)).then(() => Promise.resolve(dispatch(getSingleDeployment(deploymentId))))
437
- );
438
- var setDeploymentsState = createAppAsyncThunk(`${sliceName2}/setDeploymentsState`, (selection, { dispatch, getState }) => {
439
- const { page, perPage, ...selectionState } = selection;
440
- const currentState = getState().deployments.selectionState;
441
- const nextState = {
442
- ...currentState,
443
- ...selectionState,
444
- ...Object.keys(DEPLOYMENT_STATES).reduce((accu, item) => {
445
- accu[item] = {
446
- ...currentState[item],
447
- ...selectionState[item]
448
- };
449
- return accu;
450
- }, {}),
451
- general: {
452
- ...currentState.general,
453
- ...selectionState.general
454
- }
455
- };
456
- const tasks = [dispatch(actions2.setDeploymentsState(nextState))];
457
- if (nextState.selectedId && currentState.selectedId !== nextState.selectedId) {
458
- tasks.push(dispatch(getSingleDeployment(nextState.selectedId)));
459
- }
460
- return Promise.all(tasks);
461
- });
462
- var deltaAttributeMappings = [
463
- { here: "compressionLevel", there: "compression_level" },
464
- { here: "disableChecksum", there: "disable_checksum" },
465
- { here: "disableDecompression", there: "disable_external_decompression" },
466
- { here: "sourceWindow", there: "source_window_size" },
467
- { here: "inputWindow", there: "input_window_size" },
468
- { here: "duplicatesWindow", there: "compression_duplicates_window" },
469
- { here: "instructionBuffer", there: "instruction_buffer_size" }
470
- ];
471
- var mapExternalDeltaConfig = (config = {}) => deltaAttributeMappings.reduce((accu, { here, there }) => {
472
- if (config[there] !== void 0) {
473
- accu[here] = config[there];
474
- }
475
- return accu;
476
- }, {});
477
- var getDeploymentsConfig = createAppAsyncThunk(
478
- `${sliceName2}/getDeploymentsConfig`,
479
- (_, { dispatch, getState }) => general_api_default.get(`${deploymentsApiUrl}/config`).then(({ data }) => {
480
- const oldConfig = getState().deployments.config;
481
- const { delta = {} } = data;
482
- const { binary_delta = {}, binary_delta_limits = {} } = delta;
483
- const { xdelta_args = {} } = binary_delta;
484
- const { xdelta_args_limits = {} } = binary_delta_limits;
485
- const config = {
486
- ...oldConfig,
487
- hasDelta: Boolean(delta.enabled),
488
- binaryDelta: {
489
- ...oldConfig.binaryDelta,
490
- ...mapExternalDeltaConfig(xdelta_args)
491
- },
492
- binaryDeltaLimits: {
493
- ...oldConfig.binaryDeltaLimits,
494
- ...mapExternalDeltaConfig(xdelta_args_limits)
495
- }
496
- };
497
- return Promise.resolve(dispatch(actions2.setDeploymentsConfig(config)));
498
- })
499
- );
500
- var deepClean = (source) => Object.entries(source).reduce((accu, [key, value]) => {
501
- if (value !== void 0) {
502
- const cleanedValue = typeof value === "object" ? deepClean(value) : value;
503
- if (cleanedValue === void 0 || typeof cleanedValue === "object" && isEmpty(cleanedValue)) {
504
- return accu;
505
- }
506
- accu = { ...accu ?? {}, [key]: cleanedValue };
507
- }
508
- return accu;
509
- }, void 0);
510
- var saveDeltaDeploymentsConfig = createAppAsyncThunk(
511
- `${sliceName2}/saveDeltaDeploymentsConfig`,
512
- (config, { dispatch, getState }) => {
513
- const configChange = {
514
- xdelta_args: deltaAttributeMappings.reduce((accu, { here, there }) => {
515
- if (config[here] !== void 0) {
516
- accu[there] = config[here];
517
- }
518
- return accu;
519
- }, {})
520
- };
521
- const result = deepClean(configChange);
522
- if (!result) {
523
- return Promise.resolve();
524
- }
525
- return general_api_default.put(`${deploymentsApiUrl}/config/binary_delta`, result).catch((err) => commonErrorHandler(err, "There was a problem storing your delta artifact generation configuration.", dispatch)).then(() => {
526
- const oldConfig = getState().deployments.config;
527
- const newConfig = {
528
- ...oldConfig,
529
- binaryDelta: {
530
- ...oldConfig.binaryDelta,
531
- ...config
532
- }
533
- };
534
- return Promise.all([dispatch(actions2.setDeploymentsConfig(newConfig)), dispatch(setSnackbar("Settings saved successfully"))]);
535
- });
536
- }
537
- );
538
- var generateDeploymentLogAnalysis = createAppAsyncThunk(
539
- `${sliceName2}/generateDeploymentLogAnalysis`,
540
- ({ deploymentId, deviceId }, { dispatch, rejectWithValue }) => general_api_default.get(`${apiRoot}/v1alpha1/deployments/deployments/${deploymentId}/devices/${deviceId}/log/explain`, { timeout: 60 * TIMEOUTS.oneSecond }).then(({ data: result }) => Promise.resolve(result)).catch((err) => {
541
- if (err.response.status === 429) {
542
- return rejectWithValue(err.response);
543
- }
544
- commonErrorHandler(err, "There was an error analysing the deployment log:", dispatch);
545
- })
546
- );
547
-
548
- // src/devicesSlice/thunks.tsx
549
- import { Link } from "react-router-dom";
550
- import { attributeDuplicateFilter, dateRangeToUnix, deepCompare as deepCompare2, getSnackbarMessage } from "@northern.tech/utils/helpers";
551
- import { isCancel } from "axios";
552
- import pluralize from "pluralize";
553
- import { v4 as uuid } from "uuid";
554
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
555
- var { cleanUpUpload, initUpload, setSnackbar: setSnackbar2, uploadProgress } = actions_default;
556
- var { page: defaultPage2, perPage: defaultPerPage2 } = DEVICE_LIST_DEFAULTS;
557
- var defaultAttributes = [
558
- { scope: "identity", attribute: "status" },
559
- { scope: "inventory", attribute: "artifact_name" },
560
- { scope: "inventory", attribute: "device_type" },
561
- { scope: "inventory", attribute: "mender_is_gateway" },
562
- { scope: "inventory", attribute: "mender_gateway_system_id" },
563
- { scope: "inventory", attribute: rootfsImageVersion },
564
- { scope: "monitor", attribute: "alerts" },
565
- { scope: "system", attribute: "created_ts" },
566
- { scope: "system", attribute: "updated_ts" },
567
- { scope: "system", attribute: "check_in_time" },
568
- { scope: "system", attribute: "group" },
569
- { scope: "tags", attribute: "name" }
570
- ];
571
- var getGroups = createAppAsyncThunk(
572
- `${sliceName3}/getGroups`,
573
- (_, { dispatch, getState }) => general_api_default.get(`${inventoryApiUrl}/groups`).then((res) => {
574
- const state = getGroupsById(getState());
575
- const dynamicGroups = Object.entries(state).reduce((accu, [id, group]) => {
576
- if (group.id || group.filters?.length && id !== UNGROUPED_GROUP.id) {
577
- accu[id] = group;
578
- }
579
- return accu;
580
- }, {});
581
- const groups = res.data.reduce((accu, group) => {
582
- accu[group] = { deviceIds: [], filters: [], total: 0, ...state[group] };
583
- return accu;
584
- }, dynamicGroups);
585
- const filters = [{ key: "group", value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: "system" }];
586
- return Promise.all([
587
- dispatch(actions3.receivedGroups(groups)),
588
- dispatch(getDevicesByStatus({ filterSelection: filters, group: "", page: 1, perPage: 1, status: void 0 }))
589
- ]).then((promises) => {
590
- const devicesRetrieval = promises[promises.length - 1] || [];
591
- const { payload } = devicesRetrieval || {};
592
- const result = payload[payload.length - 1] || {};
593
- if (!result.total) {
594
- return Promise.resolve();
595
- }
596
- return Promise.resolve(
597
- dispatch(
598
- actions3.addGroup({
599
- groupName: UNGROUPED_GROUP.id,
600
- group: { filters: [{ key: "group", value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: "system" }] }
601
- })
602
- )
603
- );
604
- });
605
- })
606
- );
607
- var addDevicesToGroup = createAppAsyncThunk(
608
- `${sliceName3}/addDevicesToGroup`,
609
- ({ group, deviceIds, isCreation }, { dispatch }) => general_api_default.patch(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(() => dispatch(actions3.addToGroup({ group, deviceIds }))).finally(() => isCreation ? Promise.resolve(dispatch(getGroups())) : {})
610
- );
611
- var removeDevicesFromGroup = createAppAsyncThunk(
612
- `${sliceName3}/removeDevicesFromGroup`,
613
- ({ group, deviceIds }, { dispatch }) => general_api_default.delete(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(
614
- () => Promise.all([
615
- dispatch(actions3.removeFromGroup({ group, deviceIds })),
616
- dispatch(
617
- setSnackbar2({
618
- message: `The ${pluralize("devices", deviceIds.length)} ${pluralize("were", deviceIds.length)} removed from the group`,
619
- autoHideDuration: TIMEOUTS.fiveSeconds
620
- })
621
- )
622
- ])
623
- )
624
- );
625
- var getGroupNotification = (newGroup, selectedGroup) => {
626
- const successMessage = "The group was updated successfully";
627
- if (newGroup === selectedGroup) {
628
- return { message: successMessage, autoHideDuration: TIMEOUTS.fiveSeconds };
629
- }
630
- return {
631
- action: "",
632
- autoHideDuration: TIMEOUTS.fiveSeconds,
633
- message: /* @__PURE__ */ jsxs(Fragment, { children: [
634
- successMessage,
635
- " - ",
636
- /* @__PURE__ */ jsx(Link, { to: `/devices?inventory=group:eq:${newGroup}`, children: "click here" }),
637
- " to see it."
638
- ] }),
639
- preventClickToCopy: true
640
- };
641
- };
642
- var addStaticGroup = createAppAsyncThunk(
643
- `${sliceName3}/addStaticGroup`,
644
- ({ group, devices }, { dispatch, getState }) => Promise.resolve(dispatch(addDevicesToGroup({ group, deviceIds: devices.map(({ id }) => id), isCreation: true }))).then(
645
- () => Promise.resolve(
646
- dispatch(
647
- actions3.addGroup({
648
- group: { deviceIds: [], total: 0, filters: [], ...getState().devices.groups.byId[group] },
649
- groupName: group
650
- })
651
- )
652
- ).then(
653
- () => Promise.all([
654
- dispatch(setDeviceListState({ setOnly: true })),
655
- dispatch(getGroups()),
656
- dispatch(setSnackbar2(getGroupNotification(group, getState().devices.groups.selectedGroup)))
657
- ])
658
- )
659
- ).catch((err) => commonErrorHandler(err, `Group could not be updated:`, dispatch))
660
- );
661
- var removeReportsByGroupName = createAppAsyncThunk(`${sliceName3}/removeReportsByGroupName`, (groupName, { dispatch, getState }) => {
662
- if (!groupName) return Promise.resolve();
663
- const reports = getDeviceReportsForUser(getState());
664
- const filteredReports = reports.filter((report) => report.group !== groupName);
665
- dispatch(saveUserSettings({ reports: filteredReports }));
666
- });
667
- var removeStaticGroup = createAppAsyncThunk(
668
- `${sliceName3}/removeStaticGroup`,
669
- (groupName, { dispatch }) => general_api_default.delete(`${inventoryApiUrl}/groups/${groupName}`).then(
670
- () => Promise.all([
671
- dispatch(actions3.removeGroup(groupName)),
672
- dispatch(removeReportsByGroupName(groupName)),
673
- dispatch(getGroups()),
674
- dispatch(setSnackbar2({ message: "Group was removed successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))
675
- ])
676
- )
677
- );
678
- var getDynamicGroup = createAppAsyncThunk(
679
- `${sliceName3}/getDynamicGroupById`,
680
- (id, { dispatch }) => general_api_default.get(`${inventoryApiUrlV2}/filters/${id}`).catch((err) => {
681
- if (err.response && err.response.status === 404) {
682
- throw new Error("Request failed with status code 404");
683
- }
684
- return commonErrorHandler(err, `Error retrieving the group: `, dispatch, commonErrorFallback);
685
- })
686
- );
687
- var getDynamicGroups = createAppAsyncThunk(
688
- `${sliceName3}/getDynamicGroups`,
689
- (_, { dispatch, getState }) => general_api_default.get(`${inventoryApiUrlV2}/filters?per_page=${MAX_PAGE_SIZE}`).then(({ data: filters }) => {
690
- const state = getGroupsById(getState());
691
- const staticGroups = Object.entries(state).reduce((accu, [id, group]) => {
692
- if (!(group.id || group.filters?.length)) {
693
- accu[id] = group;
694
- }
695
- return accu;
696
- }, {});
697
- const groups = (filters || []).reduce((accu, filter) => {
698
- accu[filter.name] = {
699
- deviceIds: [],
700
- total: 0,
701
- ...state[filter.name],
702
- id: filter.id,
703
- filters: mapTermsToFilters(filter.terms)
704
- };
705
- return accu;
706
- }, staticGroups);
707
- return Promise.resolve(dispatch(actions3.receivedGroups(groups)));
708
- }).catch(() => console.log("Dynamic group retrieval failed - likely accessing a non-enterprise backend"))
709
- );
710
- var addDynamicGroup = createAppAsyncThunk(
711
- `${sliceName3}/addDynamicGroup`,
712
- ({ groupName, filterPredicates }, { dispatch, getState }) => general_api_default.post(`${inventoryApiUrlV2}/filters`, { name: groupName, terms: mapFiltersToTerms(filterPredicates) }).then(
713
- (res) => Promise.resolve(
714
- dispatch(
715
- actions3.addGroup({
716
- groupName,
717
- group: {
718
- id: res.headers[headerNames.location].substring(res.headers[headerNames.location].lastIndexOf("/") + 1),
719
- filters: filterPredicates
720
- }
721
- })
722
- )
723
- ).then(() => {
724
- const { cleanedFilters } = getGroupFilters(groupName, getState().devices.groups);
725
- return Promise.all([
726
- dispatch(actions3.setDeviceFilters(cleanedFilters)),
727
- dispatch(setSnackbar2(getGroupNotification(groupName, getState().devices.groups.selectedGroup))),
728
- dispatch(getDynamicGroups())
729
- ]);
730
- })
731
- ).catch((err) => commonErrorHandler(err, `Group could not be updated:`, dispatch))
732
- );
733
- var updateDynamicGroup = createAppAsyncThunk(
734
- `${sliceName3}/updateDynamicGroup`,
735
- ({ groupName, filterPredicates }, { dispatch, getState }) => {
736
- const filterId = getState().devices.groups.byId[groupName].id;
737
- return general_api_default.delete(`${inventoryApiUrlV2}/filters/${filterId}`).then(
738
- () => Promise.resolve(dispatch(addDynamicGroup({ groupName, filterPredicates })))
739
- );
740
- }
741
- );
742
- var removeDynamicGroup = createAppAsyncThunk(`${sliceName3}/removeDynamicGroup`, (groupName, { dispatch, getState }) => {
743
- const filterId = getState().devices.groups.byId[groupName].id;
744
- return general_api_default.delete(`${inventoryApiUrlV2}/filters/${filterId}`).then(
745
- () => Promise.all([
746
- dispatch(actions3.removeGroup(groupName)),
747
- dispatch(removeReportsByGroupName(groupName)),
748
- dispatch(setSnackbar2({ message: "Group was removed successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))
749
- ])
750
- );
751
- });
752
- var getGroupFilters = (group, groupsState, filters = []) => {
753
- const groupName = group === UNGROUPED_GROUP.id || group === UNGROUPED_GROUP.name ? UNGROUPED_GROUP.id : group;
754
- const selectedGroup = groupsState.byId[groupName];
755
- const groupFilterLength = selectedGroup?.filters?.length || 0;
756
- const cleanedFilters = groupFilterLength ? [...filters, ...selectedGroup.filters || []].filter(filtersFilter) : filters;
757
- return { cleanedFilters, groupName, selectedGroup, groupFilterLength };
758
- };
759
- var selectGroup = createAppAsyncThunk(
760
- `${sliceName3}/selectGroup`,
761
- ({ group, filters = [] }, { dispatch, getState }) => {
762
- const { cleanedFilters, groupName, selectedGroup, groupFilterLength } = getGroupFilters(group, getState().devices.groups, filters);
763
- if (getSelectedGroup(getState()) === groupName && (filters.length === 0 && !groupFilterLength || filters.length === cleanedFilters.length)) {
764
- return Promise.resolve();
765
- }
766
- const tasks = [];
767
- if (groupFilterLength) {
768
- tasks.push(dispatch(actions3.setDeviceFilters(cleanedFilters)));
769
- } else {
770
- tasks.push(dispatch(actions3.setDeviceFilters(filters)));
771
- tasks.push(dispatch(getGroupDevices({ group: groupName, perPage: 1, shouldIncludeAllStates: true })));
772
- }
773
- const selectedGroupName = selectedGroup || !Object.keys(getGroupsById(getState())).length ? groupName : void 0;
774
- tasks.push(dispatch(actions3.selectGroup(selectedGroupName)));
775
- return Promise.all(tasks);
776
- }
777
- );
778
- var getEarliestTs = (dateA = "", dateB = "") => !dateA || !dateB ? dateA || dateB : dateA < dateB ? dateA : dateB;
779
- var reduceReceivedDevices = (devices, ids, state, status) => devices.reduce(
780
- (accu, device) => {
781
- const stateDevice = getDeviceById(state, device.id);
782
- const {
783
- attributes: storedAttributes = {},
784
- identity_data: storedIdentity = {},
785
- monitor: storedMonitor = {},
786
- tags: storedTags = {},
787
- group: storedGroup
788
- } = stateDevice;
789
- const { identity, inventory, monitor, system = {}, tags } = mapDeviceAttributes(device.attributes);
790
- device.tags = { ...storedTags, ...tags };
791
- device.group = system.group ?? storedGroup;
792
- device.monitor = { ...storedMonitor, ...monitor };
793
- device.identity_data = { ...storedIdentity, ...identity, ...device.identity_data ? device.identity_data : {} };
794
- device.status = status ? status : device.status || identity.status;
795
- device.check_in_time_rounded = system.check_in_time ?? stateDevice.check_in_time_rounded;
796
- device.check_in_time_exact = device.check_in_time ?? stateDevice.check_in_time_exact;
797
- device.created_ts = getEarliestTs(getEarliestTs(system.created_ts, device.created_ts), stateDevice.created_ts);
798
- device.updated_ts = device.attributes ? device.updated_ts : stateDevice.updated_ts;
799
- device.isNew = new Date(device.created_ts) > new Date(state.app.newThreshold);
800
- device.isOffline = new Date(device.check_in_time_rounded) < new Date(state.app.offlineThreshold) || device.check_in_time_rounded === void 0;
801
- device.attributes = device.attributes ? { ...storedAttributes, ...inventory } : storedAttributes;
802
- accu.devicesById[device.id] = { ...stateDevice, ...device };
803
- accu.ids.push(device.id);
804
- return accu;
805
- },
806
- { ids, devicesById: {} }
807
- );
808
- var getGroupDevices = createAppAsyncThunk(`${sliceName3}/getGroupDevices`, (options, { dispatch, getState }) => {
809
- const { group, shouldIncludeAllStates, ...remainder } = options;
810
- const { cleanedFilters: filterSelection } = getGroupFilters(group, getState().devices.groups);
811
- return dispatch(
812
- getDevicesByStatus({
813
- ...remainder,
814
- filterSelection,
815
- group,
816
- status: shouldIncludeAllStates ? void 0 : DEVICE_STATES.accepted
817
- })
818
- ).unwrap().then((results) => {
819
- if (!group) {
820
- return Promise.resolve();
821
- }
822
- const { deviceAccu, total } = results[results.length - 1];
823
- const stateGroup = getState().devices.groups.byId[group];
824
- if (!stateGroup && !total && !deviceAccu.ids.length) {
825
- return Promise.resolve();
826
- }
827
- return Promise.resolve(
828
- dispatch(
829
- actions3.addGroup({
830
- group: {
831
- deviceIds: deviceAccu.ids.length === total || stateGroup && stateGroup.deviceIds && deviceAccu.ids.length > stateGroup.deviceIds ? deviceAccu.ids : stateGroup.deviceIds,
832
- total
833
- },
834
- groupName: group
835
- })
836
- )
837
- );
838
- });
839
- });
840
- var getAllGroupDevices = createAppAsyncThunk(
841
- `${sliceName3}/getAllGroupDevices`,
842
- ({ group, attribute }, { dispatch, getState }) => {
843
- if (!group || !!group && (!getGroupsById(getState())[group] || getGroupsById(getState())[group].filters.length)) {
844
- return Promise.resolve();
845
- }
846
- const { attributes, filterTerms } = prepareSearchArguments({
847
- filters: [],
848
- group,
849
- state: getState(),
850
- status: DEVICE_STATES.accepted
851
- });
852
- const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage2, devices = []) => general_api_default.post(getSearchEndpoint(getState()), {
853
- page,
854
- per_page: perPage,
855
- filters: filterTerms,
856
- attributes: [...attributes, { scope: "inventory", attribute }]
857
- }).then((res) => {
858
- const state = getState();
859
- const deviceAccu = reduceReceivedDevices(res.data, devices, state);
860
- dispatch(actions3.receivedDevices(deviceAccu.devicesById));
861
- const total = Number(res.headers[headerNames.total]);
862
- if (total > perPage * page) {
863
- return getAllDevices(perPage, page + 1, deviceAccu.ids);
864
- }
865
- return Promise.resolve(dispatch(actions3.addGroup({ group: { deviceIds: deviceAccu.ids, total: deviceAccu.ids.length }, groupName: group })));
866
- });
867
- return getAllDevices();
868
- }
869
- );
870
- var getAllDynamicGroupDevices = createAppAsyncThunk(
871
- `${sliceName3}/getAllDynamicGroupDevices`,
872
- ({ group, attribute }, { dispatch, getState }) => {
873
- if (!!group && (!getGroupsById(getState())[group] || !getGroupsById(getState())[group].filters.length)) {
874
- return Promise.resolve();
875
- }
876
- const { attributes, filterTerms: filters } = prepareSearchArguments({
877
- filters: getState().devices.groups.byId[group].filters,
878
- state: getState(),
879
- status: DEVICE_STATES.accepted
880
- });
881
- const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage2, devices = []) => general_api_default.post(getSearchEndpoint(getState()), { page, per_page: perPage, filters, attributes: [...attributes, { scope: "inventory", attribute }] }).then(
882
- (res) => {
883
- const state = getState();
884
- const deviceAccu = reduceReceivedDevices(res.data, devices, state);
885
- dispatch(actions3.receivedDevices(deviceAccu.devicesById));
886
- const total = Number(res.headers[headerNames.total]);
887
- if (total > deviceAccu.ids.length) {
888
- return getAllDevices(perPage, page + 1, deviceAccu.ids);
889
- }
890
- return Promise.resolve(dispatch(actions3.addGroup({ group: { deviceIds: deviceAccu.ids, total }, groupName: group })));
891
- }
892
- );
893
- return getAllDevices();
894
- }
895
- );
896
- var getDeviceById2 = createAppAsyncThunk(
897
- `${sliceName3}/getDeviceById`,
898
- (id, { dispatch, getState }) => general_api_default.get(`${inventoryApiUrl}/devices/${id}`).then((res) => {
899
- const device = reduceReceivedDevices([res.data], [], getState()).devicesById[id];
900
- device.etag = res.headers.etag;
901
- dispatch(actions3.receivedDevice(device));
902
- return Promise.resolve(device);
903
- }).catch((err) => {
904
- const errMsg = extractErrorMessage(err);
905
- if (errMsg.includes("Not Found")) {
906
- console.log(`${id} does not have any inventory information`);
907
- const device = reduceReceivedDevices(
908
- [
909
- {
910
- id,
911
- attributes: [
912
- { name: "status", value: "decomissioned", scope: "identity" },
913
- { name: "decomissioned", value: "true", scope: "inventory" }
914
- ],
915
- log: false
916
- }
917
- ],
918
- [],
919
- getState()
920
- ).devicesById[id];
921
- dispatch(actions3.receivedDevice(device));
922
- }
923
- })
924
- );
925
- var getDeviceInfo = createAppAsyncThunk(`${sliceName3}/getDeviceInfo`, (deviceId, { dispatch, getState }) => {
926
- const device = getDeviceById(getState(), deviceId);
927
- const { hasDeviceConfig, hasDeviceConnect, hasMonitor } = getTenantCapabilities(getState());
928
- const { canConfigure } = getUserCapabilities(getState());
929
- const integrations = getDeviceTwinIntegrations(getState());
930
- const tasks = [
931
- dispatch(getDeviceAuth(deviceId)),
932
- dispatch(getDeviceById2(deviceId)),
933
- ...integrations.map((integration) => dispatch(getDeviceTwin({ deviceId, integration })))
934
- ];
935
- if (hasDeviceConfig && canConfigure && (device.status === DEVICE_STATES.accepted || device.status === DEVICE_STATES.preauth)) {
936
- tasks.push(dispatch(getDeviceConfig(deviceId)));
937
- }
938
- if (device.status === DEVICE_STATES.accepted) {
939
- if (hasDeviceConnect) {
940
- tasks.push(dispatch(getDeviceConnect(deviceId)));
941
- }
942
- if (hasMonitor) {
943
- tasks.push(dispatch(getLatestDeviceAlerts({ id: deviceId })));
944
- tasks.push(dispatch(getDeviceMonitorConfig(deviceId)));
945
- }
946
- }
947
- return Promise.all(tasks);
948
- });
949
- var getAllDeviceCounts = createAppAsyncThunk(
950
- `${sliceName3}/getAllDeviceCounts`,
951
- (_, { dispatch }) => general_api_default.get(`${inventoryApiUrlV2}/statistics`).then(({ data }) => {
952
- const { devices_by_status } = data;
953
- Object.entries(devices_by_status).map(([status, countsPerTier]) => dispatch(actions3.setDevicesCountByStatus({ countsPerTier, status })));
954
- return;
955
- })
956
- );
957
- var getDeviceLimits = createAppAsyncThunk(
958
- `${sliceName3}/getDeviceLimit`,
959
- (_, { dispatch }) => general_api_default.get(`${deviceAuthV2}/limits/devices`).then((res) => dispatch(actions3.setDeviceLimits(res.data)))
960
- );
961
- var setDeviceListState = createAppAsyncThunk(
962
- `${sliceName3}/setDeviceListState`,
963
- ({ shouldSelectDevices = true, forceRefresh, fetchAuth = true, ...selectionState }, { dispatch, getState }) => {
964
- const currentState = getDeviceListState(getState());
965
- const refreshTrigger = forceRefresh ? !currentState.refreshTrigger : selectionState.refreshTrigger;
966
- const nextState = {
967
- ...currentState,
968
- setOnly: false,
969
- refreshTrigger,
970
- ...selectionState,
971
- sort: { ...currentState.sort, ...selectionState.sort }
972
- };
973
- const tasks = [];
974
- const { isLoading: currentLoading, deviceIds: currentDevices, selection: currentSelection, ...currentRequestState } = currentState;
975
- const { isLoading: nextLoading, deviceIds: nextDevices, selection: nextSelection, ...nextRequestState } = nextState;
976
- if (!nextState.setOnly && !deepCompare2(currentRequestState, nextRequestState)) {
977
- const { direction: sortDown = SORTING_OPTIONS.desc, key: sortCol, scope: sortScope = "" } = nextState.sort ?? {};
978
- const sortBy = sortCol ? [{ attribute: sortCol, order: sortDown, scope: sortScope }] : void 0;
979
- const applicableSelectedState = nextState.state === ALL_DEVICE_STATES ? void 0 : nextState.state;
980
- nextState.isLoading = true;
981
- tasks.push(
982
- dispatch(getDevicesByStatus({ ...nextState, status: applicableSelectedState, sortOptions: sortBy, fetchAuth })).unwrap().then((results) => {
983
- const { deviceAccu, total } = results[results.length - 1];
984
- const devicesState = shouldSelectDevices ? { deviceIds: deviceAccu.ids, total, isLoading: false } : { isLoading: false };
985
- return Promise.resolve(dispatch(actions3.setDeviceListState(devicesState)));
986
- }).catch(() => Promise.resolve({ isLoading: false }))
987
- );
988
- }
989
- if (currentState.page !== nextState.page || currentState.perPage > nextState.perPage || currentState.state !== nextState.state || !deepCompare2(currentState.sort, nextState.sort)) {
990
- nextState.selection = [];
991
- }
992
- tasks.push(dispatch(actions3.setDeviceListState(nextState)));
993
- return Promise.all(tasks);
994
- }
995
- );
996
- var getDevicesByStatus = createAppAsyncThunk(
997
- `${sliceName3}/getDevicesByStatus`,
998
- (options, { dispatch, getState }) => {
999
- const {
1000
- status,
1001
- fetchAuth = true,
1002
- filterSelection,
1003
- group,
1004
- selectedIssues = [],
1005
- page = defaultPage2,
1006
- perPage = defaultPerPage2,
1007
- sortOptions = [],
1008
- selectedAttributes = getSelectedDeviceAttribute(getState())
1009
- } = options;
1010
- const state = getState();
1011
- const { applicableFilters, filterTerms } = convertDeviceListStateToFilters({
1012
- filters: filterSelection ?? getDeviceFilters(state),
1013
- group: group ?? getSelectedGroup(state),
1014
- groups: state.devices.groups,
1015
- offlineThreshold: state.app.offlineThreshold,
1016
- selectedIssues,
1017
- status
1018
- });
1019
- const attributes = [...defaultAttributes, getIdAttribute(getState()), ...selectedAttributes];
1020
- return general_api_default.post(getSearchEndpoint(getState()), {
1021
- page,
1022
- per_page: perPage,
1023
- filters: filterTerms,
1024
- sort: sortOptions,
1025
- attributes
1026
- }).then((response) => {
1027
- const state2 = getState();
1028
- const deviceAccu = reduceReceivedDevices(response.data, [], state2, status);
1029
- let total = !applicableFilters.length ? Number(response.headers[headerNames.total]) : 0;
1030
- if (status && state2.devices.byStatus[status].counts.total === deviceAccu.ids.length) {
1031
- total = deviceAccu.ids.length;
1032
- }
1033
- const tasks = [dispatch(actions3.receivedDevices(deviceAccu.devicesById))];
1034
- if (status) {
1035
- tasks.push(dispatch(actions3.setDevicesByStatus({ deviceIds: deviceAccu.ids, status, total })));
1036
- }
1037
- const receivedDevices = Object.values(deviceAccu.devicesById);
1038
- if (receivedDevices.length && fetchAuth) {
1039
- tasks.push(dispatch(getDevicesWithAuth(receivedDevices)));
1040
- }
1041
- tasks.push(Promise.resolve({ deviceAccu, total: Number(response.headers[headerNames.total]) }));
1042
- return Promise.all(tasks);
1043
- }).catch((err) => commonErrorHandler(err, `${status} devices couldn't be loaded.`, dispatch, commonErrorFallback));
1044
- }
1045
- );
1046
- var getAllDevicesByStatus = createAppAsyncThunk(
1047
- `${sliceName3}/getAllDevicesByStatus`,
1048
- ({ status, attribute }, { dispatch, getState }) => {
1049
- const attributes = [...defaultAttributes, getIdAttribute(getState())];
1050
- const getAllDevices = (perPage = MAX_PAGE_SIZE, page = 1, devices = []) => general_api_default.post(getSearchEndpoint(getState()), {
1051
- page,
1052
- per_page: perPage,
1053
- filters: mapFiltersToTerms([{ key: "status", value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: "identity" }]),
1054
- attributes: [...attributes, { scope: "inventory", attribute }]
1055
- }).then((res) => {
1056
- const state = getState();
1057
- const deviceAccu = reduceReceivedDevices(res.data, devices, state, status);
1058
- dispatch(actions3.receivedDevices(deviceAccu.devicesById));
1059
- const total = Number(res.headers[headerNames.total]);
1060
- if (total > state.deployments.deploymentDeviceLimit) {
1061
- return Promise.resolve();
1062
- }
1063
- if (total > perPage * page) {
1064
- return getAllDevices(perPage, page + 1, deviceAccu.ids);
1065
- }
1066
- return Promise.resolve();
1067
- });
1068
- return getAllDevices();
1069
- }
1070
- );
1071
- var searchDevices = createAppAsyncThunk(`${sliceName3}/searchDevices`, (passedOptions = {}, { dispatch, getState }) => {
1072
- const state = getState();
1073
- const options = { ...state.app.searchState, ...passedOptions };
1074
- const { page = defaultPage2, searchTerm, sortOptions = [] } = options;
1075
- const { columnSelection = [] } = getUserSettings(state);
1076
- const selectedAttributes = columnSelection.map((column) => ({ attribute: column.key, scope: column.scope }));
1077
- const attributes = attributeDuplicateFilter([...defaultAttributes, getIdAttribute(state), ...selectedAttributes], "attribute");
1078
- return general_api_default.post(getSearchEndpoint(getState()), {
1079
- page,
1080
- per_page: 10,
1081
- filters: [],
1082
- sort: sortOptions,
1083
- text: searchTerm,
1084
- attributes
1085
- }).then((response) => {
1086
- const deviceAccu = reduceReceivedDevices(response.data, [], getState());
1087
- return Promise.all([
1088
- dispatch(actions3.receivedDevices(deviceAccu.devicesById)),
1089
- Promise.resolve({ deviceIds: deviceAccu.ids, searchTotal: Number(response.headers[headerNames.total]) })
1090
- ]);
1091
- }).catch((err) => commonErrorHandler(err, `devices couldn't be searched.`, dispatch, commonErrorFallback));
1092
- });
1093
- var ATTRIBUTE_LIST_CUTOFF = 100;
1094
- var attributeReducer = (attributes = []) => attributes.slice(0, ATTRIBUTE_LIST_CUTOFF).reduce(
1095
- (accu, { name, scope }) => {
1096
- if (!accu[scope]) {
1097
- accu[scope] = [];
1098
- }
1099
- accu[scope].push(name);
1100
- return accu;
1101
- },
1102
- { identity: [], inventory: [], system: [], tags: [] }
1103
- );
1104
- var getDeviceAttributes = createAppAsyncThunk(
1105
- `${sliceName3}/getDeviceAttributes`,
1106
- (_, { dispatch, getState }) => general_api_default.get(getAttrsEndpoint(getState())).then(({ data }) => {
1107
- const { identity: identityAttributes, inventory: inventoryAttributes, system: systemAttributes, tags: tagAttributes } = attributeReducer(data || []);
1108
- return dispatch(actions3.setFilterAttributes({ identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }));
1109
- })
1110
- );
1111
- var initializeDistributionData = (report, groups, devices, totalDeviceCount) => {
1112
- const { attribute, group = "", software = "" } = report;
1113
- const effectiveAttribute = software ? software : attribute;
1114
- const { deviceIds, total = 0 } = groups[group] || {};
1115
- const relevantDevices = deviceIds ? deviceIds.map((id) => devices[id]) : Object.values(devices);
1116
- const distributionByAttribute = relevantDevices.reduce((accu, item) => {
1117
- if (!item.attributes || item.status !== DEVICE_STATES.accepted) return accu;
1118
- const attributeValue = item.attributes[effectiveAttribute];
1119
- if (!accu[attributeValue]) {
1120
- accu[attributeValue] = 0;
1121
- }
1122
- accu[attributeValue] = accu[attributeValue] + 1;
1123
- return accu;
1124
- }, {});
1125
- const distributionByAttributeSorted = Object.entries(distributionByAttribute).sort((pairA, pairB) => pairB[1] - pairA[1]);
1126
- const items = distributionByAttributeSorted.map(([key, count]) => ({ key, count }));
1127
- const dataCount = items.reduce((accu, item) => accu + item.count, 0);
1128
- const otherCount = (groups[group] ? total : totalDeviceCount) - dataCount;
1129
- return { items, otherCount, total: otherCount + dataCount };
1130
- };
1131
- var updateReportData = createAppAsyncThunk(`${sliceName3}/updateReportData`, (reportIndex, { dispatch, getState }) => {
1132
- const reports = getDeviceReportsForUser(getState());
1133
- const report = reports[reportIndex];
1134
- const { group = "" } = report;
1135
- const devicesById = getDevicesById(getState());
1136
- const groups = getGroupsById(getState());
1137
- const { accepted: acceptedDevicesCount } = getDeviceCountsByStatus(getState());
1138
- const totalDeviceCount = groups[group] ? groups[group].total : acceptedDevicesCount;
1139
- const reportsData = getDeviceReports(getState());
1140
- const newReports = [...reportsData];
1141
- newReports[reportIndex] = initializeDistributionData(report, groups, devicesById, totalDeviceCount);
1142
- return Promise.resolve(dispatch(actions3.setDeviceReports(newReports)));
1143
- });
1144
- var getReportDataWithoutBackendSupport = createAppAsyncThunk(
1145
- `${sliceName3}/getReportDataWithoutBackendSupport`,
1146
- (reportIndex, { dispatch, getState }) => {
1147
- const reports = getDeviceReportsForUser(getState());
1148
- const report = reports[reportIndex];
1149
- if (!report) {
1150
- return;
1151
- }
1152
- const { attribute, group = "", software = "" } = report;
1153
- const effectiveAttribute = software ? software : attribute;
1154
- const devicesById = getDevicesById(getState());
1155
- const acceptedDevices = getAcceptedDevices(getState());
1156
- const { accepted: acceptedDevicesCount } = getDeviceCountsByStatus(getState());
1157
- const groups = getGroupsById(getState());
1158
- const { deviceIds = [], filters = [], total = 0 } = groups[group] || {};
1159
- let groupDevicesRequest = Promise.resolve({
1160
- payload: { groupName: "", group: { deviceIds: Object.keys(devicesById), total: Object.keys(devicesById).length } }
1161
- });
1162
- if (group && (!(deviceIds.length && total) || deviceIds.length !== total || !deviceIds.every((id) => !!devicesById[id]))) {
1163
- groupDevicesRequest = filters.length ? dispatch(getAllDynamicGroupDevices({ group, attribute: effectiveAttribute })).unwrap() : dispatch(getAllGroupDevices({ group, attribute: effectiveAttribute })).unwrap();
1164
- } else if (!group && (acceptedDevices.deviceIds.length !== acceptedDevicesCount || !acceptedDevices.deviceIds.every((id) => !!devicesById[id]))) {
1165
- groupDevicesRequest = dispatch(getAllDevicesByStatus({ status: DEVICE_STATES.accepted, attribute: effectiveAttribute })).unwrap();
1166
- }
1167
- return groupDevicesRequest.then(() => dispatch(updateReportData(reportIndex)));
1168
- }
1169
- );
1170
- var getDeviceConnect = createAppAsyncThunk(
1171
- `${sliceName3}/getDeviceConnect`,
1172
- (id, { dispatch }) => general_api_default.get(`${deviceConnect}/devices/${id}`).then(
1173
- ({ data }) => Promise.all([dispatch(actions3.receivedDevice({ connect_status: data.status, connect_updated_ts: data.updated_ts, id })), Promise.resolve(data)])
1174
- )
1175
- );
1176
- var updateTypeMap = { deploymentUpdate: "check-update", inventoryUpdate: "send-inventory" };
1177
- var triggerDeviceUpdate = createAppAsyncThunk(
1178
- `${sliceName3}/triggerDeviceUpdate`,
1179
- ({ id, type }, { dispatch }) => general_api_default.post(`${deviceConnect}/devices/${id}/${updateTypeMap[type] ?? updateTypeMap.deploymentUpdate}`).catch((err) => commonErrorHandler(err, `The request couldn\u2019t be sent.`, dispatch)).then(() => {
1180
- dispatch(setSnackbar2("Request has been sent."));
1181
- return new Promise((resolve) => setTimeout(() => resolve(dispatch(getDeviceById2(id))), TIMEOUTS.threeSeconds));
1182
- })
1183
- );
1184
- var getSessionDetails = createAppAsyncThunk(
1185
- `${sliceName3}/getSessionDetails`,
1186
- ({ sessionId, deviceId, userId, startDate, endDate }) => {
1187
- const { start: startUnix, end: endUnix } = dateRangeToUnix(startDate, endDate);
1188
- const createdAfter = startDate ? `&created_after=${startUnix}` : "";
1189
- const createdBefore = endDate ? `&created_before=${endUnix}` : "";
1190
- const objectSearch = `&object_id=${deviceId}`;
1191
- return general_api_default.get(`${auditLogsApiUrl}/logs?per_page=500${createdAfter}${createdBefore}&actor_id=${userId}${objectSearch}`).then(
1192
- ({ data: auditLogEntries }) => {
1193
- const { start, end } = auditLogEntries.reduce(
1194
- (accu, item) => {
1195
- if (item.meta?.session_id?.includes(sessionId)) {
1196
- accu.start = new Date(item.action.startsWith("open") ? item.time : accu.start);
1197
- accu.end = new Date(item.action.startsWith("close") ? item.time : accu.end);
1198
- }
1199
- return accu;
1200
- },
1201
- { start: startDate || endDate, end: endDate || startDate }
1202
- );
1203
- return Promise.resolve({ start, end });
1204
- }
1205
- );
1206
- }
1207
- );
1208
- var getDeviceFileDownloadLink = createAppAsyncThunk(
1209
- `${sliceName3}/getDeviceFileDownloadLink`,
1210
- ({ deviceId, path }) => Promise.resolve(`${window.location.origin}${deviceConnect}/devices/${deviceId}/download?path=${encodeURIComponent(path)}`)
1211
- );
1212
- var deviceFileUpload = createAppAsyncThunk(
1213
- `${sliceName3}/deviceFileUpload`,
1214
- ({ deviceId, path, file }, { dispatch }) => {
1215
- const formData = new FormData();
1216
- formData.append("path", path);
1217
- formData.append("file", file);
1218
- const uploadId = uuid();
1219
- const cancelSource = new AbortController();
1220
- return Promise.all([
1221
- dispatch(setSnackbar2("Uploading file")),
1222
- dispatch(initUpload({ id: uploadId, upload: { progress: 0, cancelSource } })),
1223
- general_api_default.uploadPut(
1224
- `${deviceConnect}/devices/${deviceId}/upload`,
1225
- formData,
1226
- (e) => dispatch(uploadProgress({ id: uploadId, progress: progress(e) })),
1227
- cancelSource.signal
1228
- )
1229
- ]).then(() => Promise.resolve(dispatch(setSnackbar2({ message: "Upload successful", autoHideDuration: TIMEOUTS.fiveSeconds })))).catch((err) => {
1230
- if (isCancel(err)) {
1231
- return dispatch(setSnackbar2({ message: "The upload has been cancelled", autoHideDuration: TIMEOUTS.fiveSeconds }));
1232
- }
1233
- return commonErrorHandler(err, `Error uploading file to device.`, dispatch);
1234
- }).finally(() => dispatch(cleanUpUpload(uploadId)));
1235
- }
1236
- );
1237
- var getDeviceAuth = createAppAsyncThunk(
1238
- `${sliceName3}/getDeviceAuth`,
1239
- (id, { dispatch }) => dispatch(getDevicesWithAuth([{ id }])).unwrap().then((results) => {
1240
- if (results[results.length - 1]) {
1241
- return Promise.resolve(results[results.length - 1][0]);
1242
- }
1243
- return Promise.resolve();
1244
- })
1245
- );
1246
- var getDevicesWithAuth = createAppAsyncThunk(
1247
- `${sliceName3}/getDevicesWithAuth`,
1248
- (devices, { dispatch, getState }) => devices.length ? general_api_default.get(`${deviceAuthV2}/devices?id=${devices.map((device) => device.id).join("&id=")}`).then(({ data: receivedDevices }) => {
1249
- const { devicesById } = reduceReceivedDevices(receivedDevices, [], getState());
1250
- return Promise.all([dispatch(actions3.receivedDevices(devicesById)), Promise.resolve(receivedDevices)]);
1251
- }).catch((err) => commonErrorHandler(err, `Error: ${err}`, dispatch)) : Promise.resolve([[], []])
1252
- );
1253
- var updateDeviceAuth = createAppAsyncThunk(
1254
- `${sliceName3}/updateDeviceAuth`,
1255
- ({ deviceId, authId, status }, { dispatch, getState }) => general_api_default.put(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}/status`, { status }).then(() => Promise.all([dispatch(getDeviceAuth(deviceId)), dispatch(setSnackbar2("Device authorization status was updated successfully"))])).catch((err) => commonErrorHandler(err, "There was a problem updating the device authorization status:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getDeviceListState(getState()).refreshTrigger })))
1256
- );
1257
- var updateDevicesAuth = createAppAsyncThunk(
1258
- `${sliceName3}/updateDevicesAuth`,
1259
- ({ deviceIds, status }, { dispatch, getState }) => {
1260
- let devices = getDevicesById(getState());
1261
- const deviceIdsWithoutAuth = deviceIds.reduce((accu, id) => devices[id].auth_sets ? accu : [...accu, { id }], []);
1262
- return dispatch(getDevicesWithAuth(deviceIdsWithoutAuth)).then(() => {
1263
- devices = getDevicesById(getState());
1264
- const deviceAuthUpdates = deviceIds.map((id) => {
1265
- const device = devices[id];
1266
- if (device.auth_sets && device.auth_sets.length !== 1) {
1267
- return Promise.reject();
1268
- }
1269
- return dispatch(updateDeviceAuth({ authId: device.auth_sets[0].id, deviceId: device.id, status })).unwrap().catch((err) => commonErrorHandler(err, "The action was stopped as there was a problem updating a device authorization status: ", dispatch, "", false));
1270
- });
1271
- return Promise.allSettled(deviceAuthUpdates).then((results) => {
1272
- const { skipped, count } = results.reduce(
1273
- (accu, item) => {
1274
- if (item.status === "rejected") {
1275
- accu.skipped = accu.skipped + 1;
1276
- } else {
1277
- accu.count = accu.count + 1;
1278
- }
1279
- return accu;
1280
- },
1281
- { skipped: 0, count: 0 }
1282
- );
1283
- const message = getSnackbarMessage(skipped, count);
1284
- return dispatch(setSnackbar2(message));
1285
- });
1286
- });
1287
- }
1288
- );
1289
- var deleteAuthset = createAppAsyncThunk(
1290
- `${sliceName3}/deleteAuthset`,
1291
- ({ deviceId, authId }, { dispatch, getState }) => general_api_default.delete(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}`).then(() => Promise.all([dispatch(setSnackbar2("Device authorization status was updated successfully"))])).catch((err) => commonErrorHandler(err, "There was a problem updating the device authorization status:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })))
1292
- );
1293
- var preauthDevice = createAppAsyncThunk(
1294
- `${sliceName3}/preauthDevice`,
1295
- (authset, { dispatch, rejectWithValue }) => general_api_default.post(`${deviceAuthV2}/devices`, authset).then(
1296
- () => Promise.resolve(dispatch(setSnackbar2({ message: "Device was successfully added to the preauthorization list", autoHideDuration: TIMEOUTS.fiveSeconds })))
1297
- ).catch((err) => {
1298
- if (err.response.status === 409) {
1299
- return rejectWithValue("A device with a matching identity data set already exists");
1300
- }
1301
- return commonErrorHandler(err, "The device could not be added:", dispatch);
1302
- })
1303
- );
1304
- var decommissionDevice = createAppAsyncThunk(
1305
- `${sliceName3}/decommissionDevice`,
1306
- ({ deviceId, authId }, { dispatch, getState }) => general_api_default.delete(`${deviceAuthV2}/devices/${deviceId}`).then(() => Promise.resolve(dispatch(setSnackbar2("Device was decommissioned successfully")))).catch((err) => commonErrorHandler(err, "There was a problem decommissioning the device:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })))
1307
- );
1308
- var getDeviceConfig = createAppAsyncThunk(
1309
- `${sliceName3}/getDeviceConfig`,
1310
- (deviceId, { dispatch }) => general_api_default.get(`${deviceConfig}/${deviceId}`).then(({ data }) => Promise.all([dispatch(actions3.receivedDevice({ id: deviceId, config: data })), Promise.resolve(data)])).catch((err) => {
1311
- if (err.response?.data?.error.status_code !== 404) {
1312
- return commonErrorHandler(err, `There was an error retrieving the configuration for device ${deviceId}.`, dispatch, commonErrorFallback);
1313
- }
1314
- })
1315
- );
1316
- var setDeviceConfig = createAppAsyncThunk(
1317
- `${sliceName3}/setDeviceConfig`,
1318
- ({ deviceId, config }, { dispatch }) => general_api_default.put(`${deviceConfig}/${deviceId}`, config).catch((err) => commonErrorHandler(err, `There was an error setting the configuration for device ${deviceId}.`, dispatch, commonErrorFallback)).then(() => Promise.resolve(dispatch(getDeviceConfig(deviceId))))
1319
- );
1320
- var applyDeviceConfig = createAppAsyncThunk(
1321
- `${sliceName3}/applyDeviceConfig`,
1322
- ({ deviceId, configDeploymentConfiguration, isDefault, config }, { dispatch, getState }) => general_api_default.post(`${deviceConfig}/${deviceId}/deploy`, configDeploymentConfiguration).catch((err) => commonErrorHandler(err, `There was an error deploying the configuration to device ${deviceId}.`, dispatch, commonErrorFallback)).then(({ data }) => {
1323
- const device = getDeviceById(getState(), deviceId);
1324
- const { canManageUsers } = getUserCapabilities(getState());
1325
- const tasks = [
1326
- dispatch(actions3.receivedDevice({ ...device, config: { ...device.config, deployment_id: data.deployment_id } })),
1327
- new Promise((resolve) => setTimeout(() => resolve(dispatch(getSingleDeployment(data.deployment_id))), TIMEOUTS.oneSecond))
1328
- ];
1329
- if (isDefault && canManageUsers) {
1330
- const { previous } = getGlobalSettings(getState()).defaultDeviceConfig ?? {};
1331
- tasks.push(dispatch(saveGlobalSettings({ defaultDeviceConfig: { current: config, previous } })));
1332
- }
1333
- return Promise.all(tasks);
1334
- })
1335
- );
1336
- var setDeviceTags = createAppAsyncThunk(
1337
- `${sliceName3}/setDeviceTags`,
1338
- ({ deviceId, tags }, { dispatch }) => (
1339
- // to prevent tag set failures, retrieve the device & use the freshest etag we can get
1340
- dispatch(getDeviceById2(deviceId)).unwrap().then((device) => {
1341
- const headers = device.etag ? { "If-Match": device.etag } : {};
1342
- const tagList = Object.entries(tags).map(([name, value]) => ({ name, value }));
1343
- const isNameChange = tagList.some(({ name }) => name === "name");
1344
- return general_api_default.put(`${inventoryApiUrl}/devices/${deviceId}/tags`, tagList, { headers }).catch((err) => commonErrorHandler(err, `There was an error setting tags for device ${deviceId}.`, dispatch, "Please check your connection.")).then(
1345
- () => Promise.all([
1346
- dispatch(actions3.receivedDevice({ ...device, id: deviceId, tags })),
1347
- dispatch(setSnackbar2(`Device ${tagList.length === 1 && isNameChange ? "name" : "tags"} changed`))
1348
- ])
1349
- );
1350
- })
1351
- )
1352
- );
1353
- var getDeviceTwin = createAppAsyncThunk(`${sliceName3}/getDeviceTwin`, ({ deviceId, integration }, { dispatch, getState }) => {
1354
- let providerResult = {};
1355
- return general_api_default.get(`${iotManagerBaseURL}/devices/${deviceId}/state`).then(({ data }) => {
1356
- providerResult = { ...data, twinError: "" };
1357
- }).catch((err) => {
1358
- providerResult = {
1359
- twinError: `There was an error getting the ${EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}. ${err}`
1360
- };
1361
- }).finally(() => {
1362
- const device = getDeviceById(getState(), deviceId);
1363
- Promise.resolve(dispatch(actions3.receivedDevice({ ...device, twinsByIntegration: { ...device.twinsByIntegration, ...providerResult } })));
1364
- });
1365
- });
1366
- var setDeviceTwin = createAppAsyncThunk(
1367
- `${sliceName3}/setDeviceTwin`,
1368
- ({ deviceId, integration, settings }, { dispatch, getState }) => general_api_default.put(`${iotManagerBaseURL}/devices/${deviceId}/state/${integration.id}`, { desired: settings }).catch(
1369
- (err) => commonErrorHandler(
1370
- err,
1371
- `There was an error updating the ${EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}.`,
1372
- dispatch
1373
- )
1374
- ).then(() => {
1375
- const device = getDeviceById(getState(), deviceId);
1376
- const { twinsByIntegration = {} } = device;
1377
- const { [integration.id]: currentState = {} } = twinsByIntegration;
1378
- return Promise.resolve(
1379
- dispatch(
1380
- actions3.receivedDevice({ ...device, twinsByIntegration: { ...twinsByIntegration, [integration.id]: { ...currentState, desired: settings } } })
1381
- )
1382
- );
1383
- })
1384
- );
1385
- var prepareSearchArguments = ({ filters, group, state, status }) => {
1386
- const { filterTerms } = convertDeviceListStateToFilters({ filters, group, offlineThreshold: state.app.offlineThreshold, selectedIssues: [], status });
1387
- const { columnSelection = [] } = getUserSettings(state);
1388
- const selectedAttributes = columnSelection.map((column) => ({ attribute: column.key, scope: column.scope }));
1389
- const attributes = [...defaultAttributes, getIdAttribute(state), ...selectedAttributes];
1390
- return { attributes, filterTerms };
1391
- };
1392
- var getSystemDevices = createAppAsyncThunk(`${sliceName3}/getSystemDevices`, (options, { dispatch, getState }) => {
1393
- const { id, page = defaultPage2, perPage = defaultPerPage2, sortOptions = [] } = options;
1394
- const state = getState();
1395
- const { hasFullFiltering } = getTenantCapabilities(state);
1396
- if (!hasFullFiltering) {
1397
- return Promise.resolve();
1398
- }
1399
- const { attributes: deviceAttributes = {} } = getDeviceById(state, id);
1400
- const { mender_gateway_system_id = "" } = deviceAttributes;
1401
- const filters = [
1402
- { ...emptyFilter, key: "mender_is_gateway", operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: "true", scope: "inventory" },
1403
- { ...emptyFilter, key: "mender_gateway_system_id", value: mender_gateway_system_id, scope: "inventory" }
1404
- ];
1405
- const { attributes, filterTerms } = prepareSearchArguments({ filters, state });
1406
- return general_api_default.post(getSearchEndpoint(getState()), {
1407
- page,
1408
- per_page: perPage,
1409
- filters: filterTerms,
1410
- sort: sortOptions,
1411
- attributes
1412
- }).catch((err) => commonErrorHandler(err, `There was an error getting system devices device ${id}.`, dispatch, "Please check your connection.")).then(({ data, headers }) => {
1413
- const state2 = getState();
1414
- const { devicesById, ids } = reduceReceivedDevices(data, [], state2);
1415
- const device = {
1416
- ...getDeviceById(state2, id),
1417
- systemDeviceIds: ids,
1418
- systemDeviceTotal: Number(headers[headerNames.total])
1419
- };
1420
- return Promise.resolve(dispatch(actions3.receivedDevices({ ...devicesById, [id]: device })));
1421
- });
1422
- });
1423
- var getGatewayDevices = createAppAsyncThunk(`${sliceName3}/getGatewayDevices`, (deviceId, { dispatch, getState }) => {
1424
- const state = getState();
1425
- const { attributes = {} } = getDeviceById(state, deviceId);
1426
- const { mender_gateway_system_id = "" } = attributes;
1427
- const filters = [
1428
- { ...emptyFilter, key: "id", operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: deviceId, scope: "identity" },
1429
- { ...emptyFilter, key: "mender_is_gateway", value: "true", scope: "inventory" },
1430
- { ...emptyFilter, key: "mender_gateway_system_id", value: mender_gateway_system_id, scope: "inventory" }
1431
- ];
1432
- const { attributes: attributeSelection, filterTerms } = prepareSearchArguments({ filters, state });
1433
- return general_api_default.post(getSearchEndpoint(getState()), {
1434
- page: 1,
1435
- per_page: MAX_PAGE_SIZE,
1436
- filters: filterTerms,
1437
- attributes: attributeSelection
1438
- }).then(({ data }) => {
1439
- const { ids } = reduceReceivedDevices(data, [], getState());
1440
- const tasks = ids.map((deviceId2) => dispatch(getDeviceInfo(deviceId2)));
1441
- tasks.push(dispatch(actions3.receivedDevice({ id: deviceId, gatewayIds: ids })));
1442
- return Promise.all(tasks);
1443
- });
1444
- });
1445
-
1446
- // src/onboardingSlice/thunks.ts
1447
- import { getDemoDeviceAddress } from "@northern.tech/utils/helpers";
1448
- import Tracking2 from "@northern.tech/utils/tracking";
1449
- import Cookies from "universal-cookie";
1450
- var cookies = new Cookies();
1451
- var applyOnboardingFallbacks = (progress2) => {
1452
- const step = orderedOnboardingSteps[progress2];
1453
- if (step && step.fallbackStep) {
1454
- return step.fallbackStep;
1455
- }
1456
- return progress2;
1457
- };
1458
- var determineProgress = (acceptedDevices, pendingDevices, releases, pastDeployments) => {
1459
- const steps = orderedOnboardingSteps;
1460
- let progress2 = -1;
1461
- progress2 = pendingDevices.length > 1 ? steps.findIndex((step) => step === onboardingSteps.DEVICES_PENDING_ACCEPTING_ONBOARDING) : progress2;
1462
- progress2 = acceptedDevices.length >= 1 ? steps.findIndex((step) => step === onboardingSteps.DEVICES_ACCEPTED_ONBOARDING) : progress2;
1463
- progress2 = acceptedDevices.length > 1 && releases.length > 1 && pastDeployments.length > 1 ? steps.findIndex((step) => step === onboardingSteps.DEPLOYMENTS_PAST_COMPLETED) : progress2;
1464
- return steps[progress2];
1465
- };
1466
- var deductOnboardingState = ({ devicesById, devicesByStatus, onboardingState, pastDeployments, releases, userCapabilities, userId }) => {
1467
- const { canDeploy, canManageDevices, canReadDeployments, canReadDevices, canReadReleases, canUploadReleases } = userCapabilities;
1468
- const userCookie = cookies.get(`${userId}-onboarded`);
1469
- const acceptedDevices = devicesByStatus[DEVICE_STATES.accepted].deviceIds;
1470
- const pendingDevices = devicesByStatus[DEVICE_STATES.pending].deviceIds;
1471
- let deviceType = onboardingState.deviceType ?? [];
1472
- deviceType = !deviceType.length && acceptedDevices.length && devicesById[acceptedDevices[0]].hasOwnProperty("attributes") ? devicesById[acceptedDevices[0]].attributes.device_type : deviceType;
1473
- const deviceTier = acceptedDevices.length && devicesById[acceptedDevices[0]].tier;
1474
- let approach = null;
1475
- if (deviceType.some((type) => type.startsWith("qemu"))) {
1476
- approach = "virtual";
1477
- } else if (deviceType.some((type) => type.startsWith("esp32")) || deviceTier === "micro") {
1478
- approach = "mcu";
1479
- } else if (deviceType.length) {
1480
- approach = "physical";
1481
- }
1482
- const progress2 = applyOnboardingFallbacks(onboardingState.progress || determineProgress(acceptedDevices, pendingDevices, releases, pastDeployments));
1483
- return {
1484
- ...onboardingState,
1485
- complete: !!(Boolean(userCookie) || onboardingState.complete || acceptedDevices.length > 1 && pendingDevices.length > 0 && releases.length > 1 && pastDeployments.length > 1 || acceptedDevices.length >= 1 && releases.length >= 2 && pastDeployments.length > 2 || acceptedDevices.length >= 1 && pendingDevices.length > 0 && releases.length >= 2 && pastDeployments.length >= 2 || orderedOnboardingSteps.findIndex((step) => step === progress2) >= orderedOnboardingSteps.length - 1 || onboardingState.disable || ![canDeploy, canManageDevices, canReadDeployments, canReadDevices, canReadReleases, canUploadReleases].every((i) => i)),
1486
- showTips: onboardingState.showTips != null ? onboardingState.showTips : true,
1487
- deviceType,
1488
- approach: onboardingState.approach || approach,
1489
- progress: progress2
1490
- };
1491
- };
1492
- var getOnboardingState2 = createAppAsyncThunk(`${sliceName4}/getOnboardingState`, (_, { dispatch, getState }) => {
1493
- const state = getState();
1494
- let onboardingState = getOnboardingState(state);
1495
- if (!onboardingState.complete) {
1496
- const userId = state.users.currentUser;
1497
- onboardingState = deductOnboardingState({
1498
- devicesById: state.devices.byId,
1499
- devicesByStatus: state.devices.byStatus,
1500
- onboardingState,
1501
- pastDeployments: state.deployments.byStatus.finished.deploymentIds,
1502
- releases: Object.values(state.releases.byId),
1503
- userCapabilities: getUserCapabilities(state),
1504
- userId
1505
- });
1506
- }
1507
- onboardingState.progress = onboardingState.progress || onboardingSteps.DASHBOARD_ONBOARDING_START;
1508
- const demoDeviceAddress = `http://${getDemoDeviceAddress(Object.values(state.devices.byId), onboardingState.approach)}`;
1509
- onboardingState.address = state.onboarding.demoArtifactPort ? `${demoDeviceAddress}:${state.onboarding.demoArtifactPort}` : demoDeviceAddress;
1510
- return Promise.all([
1511
- dispatch(actions4.setOnboardingComplete(onboardingState.complete)),
1512
- dispatch(actions4.setOnboardingState(onboardingState)),
1513
- dispatch(saveUserSettings({ onboarding: onboardingState }))
1514
- ]);
1515
- });
1516
- var setOnboardingDeviceType = createAppAsyncThunk(
1517
- `${sliceName4}/setOnboardingDeviceType`,
1518
- (value, { dispatch }) => Promise.all([dispatch(actions4.setOnboardingDeviceType(value)), dispatch(saveUserSettings({ onboarding: { deviceType: value } }))])
1519
- );
1520
- var setOnboardingApproach = createAppAsyncThunk(
1521
- `${sliceName4}/setOnboardingApproach`,
1522
- (value, { dispatch }) => Promise.all([dispatch(actions4.setOnboardingApproach(value)), dispatch(saveUserSettings({ onboarding: { approach: value } }))])
1523
- );
1524
- var setOnboardingComplete = createAppAsyncThunk(`${sliceName4}/setOnboardingComplete`, (value, { dispatch }) => {
1525
- const tasks = [Promise.resolve(dispatch(actions4.setOnboardingComplete(value)))];
1526
- if (value) {
1527
- tasks.push(Promise.resolve(dispatch(actions4.setShowOnboardingHelp(false))));
1528
- tasks.push(Promise.resolve(dispatch(advanceOnboarding(onboardingSteps.DEPLOYMENTS_PAST_COMPLETED))));
1529
- }
1530
- return Promise.all(tasks);
1531
- });
1532
- var setOnboardingCanceled = createAppAsyncThunk(
1533
- `${sliceName4}/setOnboardingCanceled`,
1534
- (_, { dispatch }) => Promise.all([
1535
- Promise.resolve(dispatch(actions4.setShowOnboardingHelp(false))),
1536
- Promise.resolve(dispatch(actions4.setShowDismissOnboardingTipsDialog(false))),
1537
- Promise.resolve(dispatch(actions4.setOnboardingComplete(true)))
1538
- ]).then(() => dispatch(advanceOnboarding(onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_FAILURE))).then(() => Tracking2.event({ category: "onboarding", action: onboardingSteps.ONBOARDING_CANCELED }))
1539
- );
1540
- var advanceOnboarding = createAppAsyncThunk(`${sliceName4}/advanceOnboarding`, (stepId, { dispatch, getState }) => {
1541
- const steps = orderedOnboardingSteps;
1542
- const progress2 = steps.findIndex((step) => step === getState().onboarding.progress);
1543
- const stepIndex = steps.findIndex((step) => step === stepId);
1544
- if (progress2 > stepIndex || getState().onboarding.progress === null) {
1545
- return;
1546
- }
1547
- const madeProgress = steps[stepIndex + 1];
1548
- const state = { ...getOnboardingState(getState()), progress: madeProgress };
1549
- state.complete = stepIndex + 1 >= orderedOnboardingSteps.findIndex((step) => step === onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_FAILURE) ? true : state.complete;
1550
- Tracking2.event({ category: "onboarding", action: stepId });
1551
- return Promise.all([dispatch(actions4.setOnboardingProgress(madeProgress)), dispatch(saveUserSettings({ onboarding: state }))]);
1552
- });
1553
-
1554
- // src/organizationSlice/thunks.ts
1555
- import { dateRangeToUnix as dateRangeToUnix2, deepCompare as deepCompare3 } from "@northern.tech/utils/helpers";
1556
- import dayjs from "dayjs";
1557
- import utc from "dayjs/plugin/utc.js";
1558
- import hashString from "md5";
1559
- import Cookies2 from "universal-cookie";
1560
- var cookies2 = new Cookies2();
1561
- dayjs.extend(utc);
1562
- var { setAnnouncement, setSnackbar: setSnackbar3 } = actions_default;
1563
- var { page: defaultPage3, perPage: defaultPerPage3 } = DEVICE_LIST_DEFAULTS;
1564
- var cancelRequest = createAppAsyncThunk(`${sliceName5}/cancelRequest`, (reason, { dispatch, getState }) => {
1565
- const { id: tenantId } = getOrganization(getState());
1566
- return general_api_default.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/cancel`, { reason }).then(
1567
- () => Promise.resolve(dispatch(setSnackbar3({ message: "Deactivation request was sent successfully", autoHideDuration: TIMEOUTS.fiveSeconds })))
1568
- );
1569
- });
1570
- var getTierId = (tierName) => tierName.replace("mender_", "");
1571
- var getProductPlans = (products) => {
1572
- const backendPlansById = products.reduce(
1573
- (plansById, product) => {
1574
- const { name, prices } = product;
1575
- const tierId = getTierId(name);
1576
- prices.forEach((price) => {
1577
- const existing = plansById[price.plan] ?? { ...PLANS[price.plan], tierLimitsConstrains: {} };
1578
- const tierConstraints = price.constraints ? { [tierId]: { min: price.constraints.min, max: price.constraints.max, div: price.constraints.div } } : {};
1579
- plansById[price.plan] = {
1580
- ...existing,
1581
- tierLimitsConstrains: {
1582
- ...existing.tierLimitsConstrains,
1583
- ...tierConstraints
1584
- }
1585
- };
1586
- });
1587
- return plansById;
1588
- },
1589
- {}
1590
- );
1591
- return { ...backendPlansById, enterprise: { ...PLANS.enterprise } };
1592
- };
1593
- var getProductAddons = (products) => products.reduce((accu, product) => {
1594
- const { addons = [] } = product;
1595
- addons.forEach((addon) => {
1596
- const { name: addonName = "", prices: addonPrices = [] } = addon;
1597
- const existingEligible = accu[addonName]?.eligible ?? [];
1598
- const newEligible = addonPrices.map((p) => p.plan);
1599
- accu[addonName] = {
1600
- ...ADDONS[addonName],
1601
- eligible: [.../* @__PURE__ */ new Set([...existingEligible, ...newEligible, PLANS.enterprise.id])]
1602
- };
1603
- });
1604
- return accu;
1605
- }, {});
1606
- var transformProductResponse = (products) => {
1607
- const tiers = [];
1608
- const sortedProducts = products.sort((a, b) => a.name.localeCompare(b.name));
1609
- sortedProducts.forEach((tier) => {
1610
- const addonsSupported = Object.fromEntries((tier.addons || []).map((addon) => [addon.name, addon.prices?.map((p) => p.plan)]));
1611
- const allPlans = tier.prices.map((price) => price.plan);
1612
- const addonsTransposed = allPlans.reduce((acc, plan) => {
1613
- acc[plan] = Object.entries(addonsSupported).filter(([, addonSupportedPlans]) => addonSupportedPlans.includes(plan)).map(([addon]) => addon);
1614
- return acc;
1615
- }, {});
1616
- const tierId = getTierId(tier.name);
1617
- tiers.push({
1618
- id: tierId,
1619
- title: tierId,
1620
- stripeProductName: tier.name,
1621
- limitConstrains: Object.fromEntries(tier.prices.map((p) => [p.plan, p.constraints])),
1622
- addons: addonsSupported,
1623
- addonsByPlan: addonsTransposed
1624
- });
1625
- });
1626
- const plans = getProductPlans(products);
1627
- const addons = getProductAddons(products);
1628
- return { plans, tiers, addons };
1629
- };
1630
- var getTargetLocation = (key) => {
1631
- if (devLocations.includes(window.location.hostname)) {
1632
- return "";
1633
- }
1634
- let subdomainSections = window.location.hostname.substring(0, window.location.hostname.indexOf(locations.us.location)).split(".");
1635
- subdomainSections = subdomainSections.splice(0, subdomainSections.length - 1);
1636
- if (!subdomainSections.find((section) => section === key)) {
1637
- subdomainSections = key === locations.us.key ? subdomainSections.filter((section) => !locations[section]) : [...subdomainSections, key];
1638
- return `https://${[...subdomainSections, ...locations.us.location.split(".")].join(".")}`;
1639
- }
1640
- return `https://${window.location.hostname}`;
1641
- };
1642
- var devLocations = ["localhost", "docker.mender.io"];
1643
- var createOrganizationTrial = createAppAsyncThunk(`${sliceName5}/createOrganizationTrial`, (data, { dispatch }) => {
1644
- const { key } = locations[data.location];
1645
- const targetLocation = getTargetLocation(key);
1646
- const target = `${targetLocation}${tenantadmApiUrlv2}/tenants/trial`;
1647
- return general_api_default.postUnauthorized(target, data).catch((err) => {
1648
- if (err.response?.status >= 400 && err.response?.status < 500) {
1649
- dispatch(setSnackbar3({ message: err.response.data.error, autoHideDuration: TIMEOUTS.fiveSeconds }));
1650
- } else {
1651
- dispatch(setSnackbar3({ message: "There was an error creating your account", autoHideDuration: TIMEOUTS.fiveSeconds }));
1652
- }
1653
- return Promise.reject(err);
1654
- }).then(({ headers }) => {
1655
- cookies2.remove("oauth");
1656
- cookies2.remove("externalID");
1657
- cookies2.remove("email");
1658
- dispatch(setFirstLoginAfterSignup(true));
1659
- return new Promise(
1660
- (resolve) => setTimeout(() => {
1661
- window.location.assign(`${targetLocation}${headers.location || ""}`);
1662
- return resolve();
1663
- }, TIMEOUTS.fiveSeconds)
1664
- );
1665
- });
1666
- });
1667
- var startCardUpdate = createAppAsyncThunk(
1668
- `${sliceName5}/startCardUpdate`,
1669
- (_, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/billing/card`).then(({ data }) => {
1670
- dispatch(actions5.receiveSetupIntent(data.intent_id));
1671
- return Promise.resolve(data.secret);
1672
- }).catch((err) => commonErrorHandler(err, `Updating the card failed:`, dispatch))
1673
- );
1674
- var confirmCardUpdate = createAppAsyncThunk(
1675
- `${sliceName5}/confirmCardUpdate`,
1676
- (_, { dispatch, getState }) => general_api_default.post(`${tenantadmApiUrlv2}/billing/card/${getState().organization.intentId}/confirm`).then(() => Promise.all([dispatch(setSnackbar3("Payment card was updated successfully")), dispatch(actions5.receiveSetupIntent(null))])).catch((err) => commonErrorHandler(err, `Updating the card failed:`, dispatch))
1677
- );
1678
- var getCurrentCard = createAppAsyncThunk(
1679
- `${sliceName5}/getCurrentCard`,
1680
- (_, { dispatch }) => general_api_default.get(`${tenantadmApiUrlv2}/billing`).then((res) => {
1681
- const { last4, exp_month, exp_year, brand } = res.data.card || {};
1682
- return Promise.resolve(dispatch(actions5.receiveCurrentCard({ brand, last4, expiration: { month: exp_month, year: exp_year } })));
1683
- })
1684
- );
1685
- var startUpgrade = createAppAsyncThunk(
1686
- `${sliceName5}/startUpgrade`,
1687
- (tenantId, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/start`).then(({ data }) => Promise.resolve(data.secret)).catch((err) => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
1688
- );
1689
- var cancelUpgrade = createAppAsyncThunk(
1690
- `${sliceName5}/cancelUpgrade`,
1691
- (tenantId) => general_api_default.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/cancel`)
1692
- );
1693
- var completeUpgrade = createAppAsyncThunk(
1694
- `${sliceName5}/completeUpgrade`,
1695
- ({ tenantId, plan, billing_profile }, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/complete`, { plan, billing_profile }).catch((err) => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch)).then(() => Promise.all([dispatch(getDeviceLimits()), dispatch(getUserOrganization())]))
1696
- );
1697
- var prepareAuditlogQuery = ({
1698
- startDate,
1699
- endDate,
1700
- user: userFilter,
1701
- type,
1702
- detail: detailFilter,
1703
- sort = { direction: SORTING_OPTIONS.desc }
1704
- }) => {
1705
- const userId = typeof userFilter === "object" && userFilter ? userFilter.id : userFilter;
1706
- const detail = typeof detailFilter === "object" && detailFilter ? detailFilter.id : detailFilter;
1707
- const { start: startUnix, end: endUnix } = dateRangeToUnix2(startDate, endDate);
1708
- const createdAfter = startDate ? `&created_after=${startUnix}` : "";
1709
- const createdBefore = endDate ? `&created_before=${endUnix}` : "";
1710
- const typeSearch = type ? `&object_type=${type.value}`.toLowerCase() : "";
1711
- const userSearch = userId ? `&actor_id=${userId}` : "";
1712
- const objectSearch = type && detail ? `&${type.queryParameter}=${encodeURIComponent(detail)}` : "";
1713
- const { direction = SORTING_OPTIONS.desc } = sort;
1714
- return `${createdAfter}${createdBefore}${userSearch}${typeSearch}${objectSearch}&sort=${direction}`;
1715
- };
1716
- var getAuditLogs = createAppAsyncThunk(`${sliceName5}/getAuditLogs`, (selectionState, { dispatch, getState }) => {
1717
- const { page, perPage } = selectionState;
1718
- const { hasAuditlogs } = getTenantCapabilities(getState());
1719
- if (!hasAuditlogs) {
1720
- return Promise.resolve();
1721
- }
1722
- return general_api_default.get(`${auditLogsApiUrl}/logs?page=${page}&per_page=${perPage}${prepareAuditlogQuery(selectionState)}`).then(({ data, headers }) => {
1723
- let total = headers[headerNames.total];
1724
- total = Number(total || data.length);
1725
- return Promise.resolve(dispatch(actions5.receiveAuditLogs({ events: data, total })));
1726
- }).catch((err) => commonErrorHandler(err, `There was an error retrieving audit logs:`, dispatch));
1727
- });
1728
- var getAuditLogsCsvLink = createAppAsyncThunk(
1729
- `${sliceName5}/getAuditLogsCsvLink`,
1730
- (_, { getState }) => Promise.resolve(`${window.location.origin}${auditLogsApiUrl}/logs/export?limit=20000${prepareAuditlogQuery(getAuditlogState(getState()))}`)
1731
- );
1732
- var setAuditlogsState = createAppAsyncThunk(
1733
- `${sliceName5}/setAuditlogsState`,
1734
- (selectionState, { dispatch, getState }) => {
1735
- const currentState = getAuditlogState(getState());
1736
- const nextState = {
1737
- ...currentState,
1738
- ...selectionState,
1739
- sort: { ...currentState.sort, ...selectionState.sort }
1740
- };
1741
- const tasks = [];
1742
- const { isLoading: currentLoading, selectedIssue: currentIssue, ...currentRequestState } = currentState;
1743
- const { isLoading: selectionLoading, selectedIssue: selectionIssue, ...selectionRequestState } = nextState;
1744
- if (!deepCompare3(currentRequestState, selectionRequestState)) {
1745
- nextState.isLoading = true;
1746
- tasks.push(dispatch(getAuditLogs(nextState)).finally(() => dispatch(actions5.setAuditLogState({ isLoading: false }))));
1747
- }
1748
- tasks.push(dispatch(actions5.setAuditLogState(nextState)));
1749
- return Promise.all(tasks);
1750
- }
1751
- );
1752
- var tenantDataDivergedMessage = "The system detected there is a change in your plan or purchased add-ons. Please log out and log in again";
1753
- var addTenant = createAppAsyncThunk(
1754
- `${sliceName5}/createTenant`,
1755
- (selectionState, { dispatch, getState }) => {
1756
- const spLimits = getSpLimits(getState());
1757
- const { deviceLimits, ...rest } = selectionState;
1758
- const device_limits = convertToBackendSPLimits(deviceLimits, spLimits);
1759
- return general_api_default.post(`${tenantadmApiUrlv2}/tenants`, { ...rest, device_limits }).then(
1760
- () => Promise.all([
1761
- dispatch(setSnackbar3("Tenant was created successfully.")),
1762
- new Promise((resolve) => setTimeout(() => resolve(dispatch(getTenants())), TIMEOUTS.oneSecond))
1763
- ])
1764
- ).catch((err) => commonErrorHandler(err, "There was an error creating tenant", dispatch, commonErrorFallback));
1765
- }
1766
- );
1767
- var tenantListRetrieval = async (config) => {
1768
- const { page, perPage } = config;
1769
- const params = new URLSearchParams({ page, per_page: perPage, tiers: "true" }).toString();
1770
- const tenantList = await general_api_default.get(`${tenantadmApiUrlv2}/tenants?${params}`);
1771
- const totalCount = tenantList.headers[headerNames.total] || TENANT_LIST_DEFAULT.perPage;
1772
- return [tenantList.data, Number(totalCount)];
1773
- };
1774
- var getTenants = createAppAsyncThunk(`${sliceName5}/getTenants`, async (_, { dispatch, getState }) => {
1775
- const currentState = getTenantsList(getState());
1776
- const [tenants, pageCount] = await tenantListRetrieval(currentState);
1777
- dispatch(actions5.setTenantListState({ ...currentState, total: pageCount, tenants }));
1778
- });
1779
- var setTenantsListState = createAppAsyncThunk(
1780
- `${sliceName5}/setTenantsListState`,
1781
- async (selectionState, { dispatch, getState }) => {
1782
- const currentState = getTenantsList(getState());
1783
- const nextState = {
1784
- ...currentState,
1785
- ...selectionState
1786
- };
1787
- if (!deepCompare3(currentState, selectionState)) {
1788
- const [tenants, pageCount] = await tenantListRetrieval(nextState);
1789
- return dispatch(actions5.setTenantListState({ ...nextState, tenants, total: pageCount }));
1790
- }
1791
- return dispatch(actions5.setTenantListState({ ...nextState }));
1792
- }
1793
- );
1794
- var editTenant = createAppAsyncThunk(`${sliceName5}/editDeviceLimit`, ({ deviceLimits, id, name }, { dispatch, getState }) => {
1795
- const spLimits = getSpLimits(getState());
1796
- const device_limits = convertToBackendSPLimits(deviceLimits, spLimits);
1797
- return general_api_default.put(`${tenantadmApiUrlv2}/tenants/${id}/child`, { device_limits, name }).catch((err) => commonErrorHandler(err, `Device Limit cannot be changed`, dispatch)).then(
1798
- () => Promise.all([
1799
- dispatch(setSnackbar3("Tenant was changed successfully")),
1800
- dispatch(getUserOrganization()),
1801
- new Promise((resolve) => setTimeout(() => resolve(dispatch(getTenants())), TIMEOUTS.oneSecond))
1802
- ])
1803
- );
1804
- });
1805
- var editBillingProfile = createAppAsyncThunk(
1806
- `${sliceName5}/editBillingProfileEmail`,
1807
- ({ billingProfile }, { dispatch }) => general_api_default.patch(`${tenantadmApiUrlv2}/billing/profile`, billingProfile).catch((err) => commonErrorHandler(err, `Failed to change billing profile`, dispatch)).then(() => Promise.all([dispatch(setSnackbar3("Billing Profile was changed successfully")), dispatch(getUserBilling())]))
1808
- );
1809
- var createBillingProfile = createAppAsyncThunk(
1810
- `${sliceName5}/createBillingProfileEmail`,
1811
- ({ billingProfile }, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/billing/profile`, billingProfile).catch((err) => commonErrorHandler(err, `Failed to create billing profile`, dispatch)).then(() => Promise.all([dispatch(setSnackbar3("Billing Profile was created successfully")), dispatch(getUserBilling())]))
1812
- );
1813
- var removeTenant = createAppAsyncThunk(
1814
- `${sliceName5}/editDeviceLimit`,
1815
- ({ id }, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/tenants/${id}/remove/start`).catch((err) => commonErrorHandler(err, `There was an error removing the tenant`, dispatch)).then(
1816
- () => Promise.all([
1817
- dispatch(setSnackbar3("The tenant was removed successfully")),
1818
- dispatch(getUserOrganization()),
1819
- new Promise((resolve) => setTimeout(() => resolve(dispatch(getTenants())), TIMEOUTS.oneSecond))
1820
- ])
1821
- )
1822
- );
1823
- var getUserOrganization = createAppAsyncThunk(
1824
- `${sliceName5}/getUserOrganization`,
1825
- (_, { dispatch, getState }) => general_api_default.get(`${tenantadmApiUrlv1}/user/tenant?tiers=true`).then((res) => {
1826
- const { addons, plan, trial } = res.data;
1827
- const { addons: currentAddons, id: currentId, plan: currentPlan, trial: currentTrial } = getOrganization(getState());
1828
- const tasks = [dispatch(actions5.setOrganization(res.data))];
1829
- if (currentId && !deepCompare3({ addons, plan, trial }, { addons: currentAddons, plan: currentPlan, trial: currentTrial })) {
1830
- const hash = hashString(tenantDataDivergedMessage);
1831
- const { id: currentUserId } = getCurrentUser(getState());
1832
- cookies2.remove(`${currentUserId}${hash}`);
1833
- tasks.push(dispatch(setAnnouncement(tenantDataDivergedMessage)));
1834
- }
1835
- return Promise.all(tasks);
1836
- })
1837
- );
1838
- var getUserBilling = createAppAsyncThunk(
1839
- `${sliceName5}/getUserBilling`,
1840
- (_, { dispatch }) => general_api_default.get(`${tenantadmApiUrlv2}/billing/profile`).catch((err) => commonErrorHandler(err, "There was an error getting your billing profile:", dispatch, commonErrorFallback)).then((res) => dispatch(actions5.setBillingProfile(res.data)))
1841
- );
1842
- var getUserSubscription = createAppAsyncThunk(`${sliceName5}/getUserSubscription`, async (_, { dispatch }) => {
1843
- const currentSubscription = await dispatch(getCurrentSubscription()).unwrap();
1844
- const currentPreview = await dispatch(getBillingPreview({ preview_mode: "next" })).unwrap();
1845
- return dispatch(actions5.setSubscription({ ...currentPreview, ...currentSubscription }));
1846
- });
1847
- var getBillingPreview = createAppAsyncThunk(
1848
- `${sliceName5}/getBillingPreview`,
1849
- (order, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/billing/subscription/invoices/preview`, order).catch((err) => commonErrorHandler(err, "There was an error getting your billing information:", dispatch, commonErrorFallback)).then(({ data }) => order.preview_mode === "recurring" ? { items: parseSubscriptionPreview(data.lines), total: data.total } : data)
1850
- );
1851
- var getCurrentSubscription = createAppAsyncThunk(
1852
- `${sliceName5}/getCurrentSubscription`,
1853
- (_, { dispatch }) => general_api_default.get(`${tenantadmApiUrlv2}/billing/subscription`).then((res) => res.data).catch((err) => {
1854
- if (err.response && err.response.status === 404) {
1855
- throw new Error("Request failed with status code 404");
1856
- }
1857
- return commonErrorHandler(err, "There was an error retrieving your current subscription", dispatch, commonErrorFallback);
1858
- })
1859
- );
1860
- var getProducts = createAppAsyncThunk(
1861
- `${sliceName5}/getEnabledTiers`,
1862
- (_, { dispatch }) => general_api_default.get(`${tenantadmApiUrlv2}/billing/products`).catch((err) => commonErrorHandler(err, "There was an error getting Mender products:", dispatch, commonErrorFallback)).then((res) => dispatch(actions5.setProducts(transformProductResponse(res.data))))
1863
- );
1864
- var requestPlanUpgrade = createAppAsyncThunk(
1865
- `${sliceName5}/requestPlanUpgrade`,
1866
- (order, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/billing/subscription`, order).catch((err) => commonErrorHandler(err, "There was an error sending your request", dispatch, commonErrorFallback)).then(() => Promise.all([setTimeout(() => dispatch(getDeviceLimits()), TIMEOUTS.threeSeconds), dispatch(getUserOrganization())]))
1867
- );
1868
- var sendSupportMessage = createAppAsyncThunk(
1869
- `${sliceName5}/sendSupportMessage`,
1870
- (content, { dispatch }) => general_api_default.post(`${tenantadmApiUrlv2}/contact/support`, content).catch((err) => commonErrorHandler(err, "There was an error sending your request", dispatch, commonErrorFallback)).then(() => Promise.resolve(dispatch(setSnackbar3({ message: "Your request was sent successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))))
1871
- );
1872
- var requestPlanChange = createAppAsyncThunk(
1873
- `${sliceName5}/requestPlanChange`,
1874
- ({ content, tenantId }, { dispatch, rejectWithValue }) => general_api_default.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/plan`, content).catch(async (err) => {
1875
- await commonErrorHandler(err, "There was an error sending your request", dispatch, commonErrorFallback);
1876
- rejectWithValue(err);
1877
- }).then(() => Promise.resolve(dispatch(setSnackbar3({ message: "Your request was sent successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))))
1878
- );
1879
- var downloadLicenseReport = createAppAsyncThunk(
1880
- `${sliceName5}/downloadLicenseReport`,
1881
- (_, { dispatch }) => general_api_default.get(`${deviceAuthV2}/license`).catch((err) => commonErrorHandler(err, "There was an error downloading the report", dispatch, commonErrorFallback)).then((res) => res.data)
1882
- );
1883
- var createIntegration = createAppAsyncThunk(
1884
- `${sliceName5}/createIntegration`,
1885
- ({ id, ...integration }, { dispatch }) => general_api_default.post(`${iotManagerBaseURL}/integrations`, integration).catch((err) => commonErrorHandler(err, "There was an error creating the integration", dispatch, commonErrorFallback)).then(() => Promise.all([dispatch(setSnackbar3("The integration was set up successfully")), dispatch(getIntegrations())]))
1886
- );
1887
- var changeIntegration = createAppAsyncThunk(
1888
- `${sliceName5}/changeIntegration`,
1889
- ({ id, credentials }, { dispatch }) => general_api_default.put(`${iotManagerBaseURL}/integrations/${id}/credentials`, credentials).catch((err) => commonErrorHandler(err, "There was an error updating the integration", dispatch, commonErrorFallback)).then(() => Promise.all([dispatch(setSnackbar3("The integration was updated successfully")), dispatch(getIntegrations())]))
1890
- );
1891
- var deleteIntegration = createAppAsyncThunk(
1892
- `${sliceName5}/deleteIntegration`,
1893
- ({ id, provider }, { dispatch, getState }) => general_api_default.delete(`${iotManagerBaseURL}/integrations/${id}`, {}).catch((err) => commonErrorHandler(err, "There was an error removing the integration", dispatch, commonErrorFallback)).then(() => {
1894
- const integrations = getState().organization.externalDeviceIntegrations.filter((item) => provider !== item.provider);
1895
- return Promise.all([
1896
- dispatch(setSnackbar3("The integration was removed successfully")),
1897
- dispatch(actions5.receiveExternalDeviceIntegrations(integrations))
1898
- ]);
1899
- })
1900
- );
1901
- var getIntegrations = createAppAsyncThunk(
1902
- `${sliceName5}/getIntegrations`,
1903
- (_, { dispatch, getState }) => general_api_default.get(`${iotManagerBaseURL}/integrations`).catch((err) => commonErrorHandler(err, "There was an error retrieving the integration", dispatch, commonErrorFallback)).then(({ data }) => {
1904
- const existingIntegrations = getState().organization.externalDeviceIntegrations;
1905
- const integrations = data.reduce((accu, item) => {
1906
- const existingIntegration = existingIntegrations.find((integration2) => item.id === integration2.id) ?? {};
1907
- const integration = { ...existingIntegration, ...item };
1908
- accu.push(integration);
1909
- return accu;
1910
- }, []);
1911
- return Promise.resolve(dispatch(actions5.receiveExternalDeviceIntegrations(integrations)));
1912
- })
1913
- );
1914
- var getWebhookEvents = createAppAsyncThunk(`${sliceName5}/getWebhookEvents`, (config = {}, { dispatch, getState }) => {
1915
- const { isFollowUp, page = defaultPage3, perPage = defaultPerPage3 } = config;
1916
- return general_api_default.get(`${iotManagerBaseURL}/events?page=${page}&per_page=${perPage}`).catch((err) => commonErrorHandler(err, "There was an error retrieving activity for this integration", dispatch, commonErrorFallback)).then(({ data }) => {
1917
- const tasks = [
1918
- dispatch(
1919
- actions5.receiveWebhookEvents({
1920
- value: isFollowUp ? getState().organization.webhooks.events : data,
1921
- total: (page - 1) * perPage + data.length
1922
- })
1923
- )
1924
- ];
1925
- if (data.length >= perPage && !isFollowUp) {
1926
- tasks.push(dispatch(getWebhookEvents({ isFollowUp: true, page: page + 1, perPage: 1 })));
1927
- }
1928
- return Promise.all(tasks);
1929
- });
1930
- });
1931
- var ssoConfigActions = {
1932
- create: { success: "stored", error: "storing" },
1933
- edit: { success: "updated", error: "updating" },
1934
- read: { success: "", error: "retrieving" },
1935
- remove: { success: "removed", error: "removing" },
1936
- readMultiple: { success: "", error: "retrieving" }
1937
- };
1938
- var ssoConfigActionErrorHandler = (err, type) => (dispatch) => commonErrorHandler(err, `There was an error ${ssoConfigActions[type].error} the SSO configuration.`, dispatch, commonErrorFallback);
1939
- var ssoConfigActionSuccessHandler = (type) => (dispatch) => dispatch(setSnackbar3(`The SSO configuration was ${ssoConfigActions[type].success} successfully`));
1940
- var storeSsoConfig = createAppAsyncThunk(
1941
- `${sliceName5}/storeSsoConfig`,
1942
- ({ config, contentType }, { dispatch }) => general_api_default.post(ssoIdpApiUrlv1, config, { headers: { "Content-Type": contentType, Accept: "application/json" } }).catch((err) => dispatch(ssoConfigActionErrorHandler(err, "create"))).then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler("create")), dispatch(getSsoConfigs())]))
1943
- );
1944
- var changeSsoConfig = createAppAsyncThunk(
1945
- `${sliceName5}/changeSsoConfig`,
1946
- ({ config, contentType }, { dispatch }) => general_api_default.put(`${ssoIdpApiUrlv1}/${config.id}`, config.config, { headers: { "Content-Type": contentType, Accept: "application/json" } }).catch((err) => dispatch(ssoConfigActionErrorHandler(err, "edit"))).then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler("edit")), dispatch(getSsoConfigs())]))
1947
- );
1948
- var deleteSsoConfig = createAppAsyncThunk(
1949
- `${sliceName5}/deleteSsoConfig`,
1950
- ({ id }, { dispatch, getState }) => general_api_default.delete(`${ssoIdpApiUrlv1}/${id}`).catch((err) => dispatch(ssoConfigActionErrorHandler(err, "remove"))).then(() => {
1951
- const configs = getState().organization.ssoConfigs.filter((item) => id !== item.id);
1952
- return Promise.all([dispatch(ssoConfigActionSuccessHandler("remove")), dispatch(actions5.receiveSsoConfigs(configs))]);
1953
- })
1954
- );
1955
- var getSsoConfigById = createAppAsyncThunk(
1956
- `${sliceName5}/getSsoConfigById`,
1957
- (config, { dispatch }) => general_api_default.get(`${ssoIdpApiUrlv1}/${config.id}`).catch((err) => dispatch(ssoConfigActionErrorHandler(err, "read"))).then(({ data, headers }) => {
1958
- const sso = Object.values(SSO_TYPES).find(({ contentType }) => contentType === headers["content-type"]);
1959
- return sso ? Promise.resolve({ ...config, config: data, type: sso.id }) : Promise.reject("Unsupported SSO config content type.");
1960
- })
1961
- );
1962
- var getSsoConfigs = createAppAsyncThunk(
1963
- `${sliceName5}/getSsoConfigs`,
1964
- (_, { dispatch }) => general_api_default.get(ssoIdpApiUrlv1).catch((err) => dispatch(ssoConfigActionErrorHandler(err, "readMultiple"))).then(
1965
- ({ data }) => Promise.all(data.map((config) => dispatch(getSsoConfigById(config)).unwrap())).then((configs) => dispatch(actions5.receiveSsoConfigs(configs))).catch((err) => commonErrorHandler(err, err, dispatch, ""))
1966
- )
1967
- );
1968
-
1969
- // src/usersSlice/thunks.ts
1970
- import { duplicateFilter, extractErrorMessage as extractErrorMessage2, isEmpty as isEmpty2 } from "@northern.tech/utils/helpers";
1971
- import { clearAllRetryTimers } from "@northern.tech/utils/retrytimer";
1972
- import dayjs2 from "dayjs";
1973
- import hashString2 from "md5";
1974
- import Cookies3 from "universal-cookie";
1975
- var cookies3 = new Cookies3();
1976
- var { setAnnouncement: setAnnouncement2, setSnackbar: setSnackbar4 } = actions_default;
1977
- var handleLoginError = (err, { token2fa: has2FA, password }, rejectWithValue) => () => {
1978
- const errorText = extractErrorMessage2(err);
1979
- const is2FABackend = errorText.includes("2fa");
1980
- if (is2FABackend && !has2FA) {
1981
- return rejectWithValue({ error: "2fa code missing" });
1982
- }
1983
- if (password === void 0) {
1984
- return Promise.reject();
1985
- }
1986
- const twoFAError = is2FABackend ? " and verification code" : "";
1987
- const errorMessage = `There was a problem logging in. Please check your email${twoFAError ? "," : " and"} password${twoFAError}. If you still have problems, contact an administrator.`;
1988
- return rejectWithValue({ error: errorMessage });
1989
- };
1990
- var loginUser = createAppAsyncThunk(
1991
- `${sliceName6}/loginUser`,
1992
- ({ stayLoggedIn, ...userData }, { dispatch, rejectWithValue }) => users_api_default.postLogin(`${useradmApiUrl}/auth/login`, { ...userData, no_expiry: stayLoggedIn }).catch((err) => {
1993
- cleanUp();
1994
- return Promise.reject(dispatch(handleLoginError(err, userData, rejectWithValue)));
1995
- }).then(({ text: token, contentType }) => {
1996
- if (contentType.includes(APPLICATION_JSON_CONTENT_TYPE)) {
1997
- const { id, kind } = token;
1998
- const type = kind.split("/")[1];
1999
- const ssoLoginUrl = SSO_TYPES[type].getStartUrl(id);
2000
- window.location.replace(ssoLoginUrl);
2001
- return;
2002
- }
2003
- if (contentType !== APPLICATION_JWT_CONTENT_TYPE || !token) {
2004
- return;
2005
- }
2006
- const now = /* @__PURE__ */ new Date();
2007
- now.setSeconds(now.getSeconds() + maxSessionAge);
2008
- const expiresAt = stayLoggedIn ? void 0 : now.toISOString();
2009
- setSessionInfo({ token, expiresAt });
2010
- cookies3.remove("JWT", { path: "/" });
2011
- return dispatch(getUser(OWN_USER_ID)).unwrap().catch((e) => {
2012
- cleanUp();
2013
- return Promise.reject(dispatch(setSnackbar4(extractErrorMessage2(e))));
2014
- }).then(() => {
2015
- window.sessionStorage.removeItem("pendings-redirect");
2016
- if (window.location.pathname !== "/ui/") {
2017
- window.location.replace("/ui/");
2018
- }
2019
- return Promise.resolve(dispatch(actions6.successfullyLoggedIn({ expiresAt, token })));
2020
- });
2021
- })
2022
- );
2023
- var logoutUser = createAppAsyncThunk(`${sliceName6}/logoutUser`, (_, { dispatch, getState }) => {
2024
- if (Object.keys(getState().app.uploadsById).length) {
2025
- return Promise.reject();
2026
- }
2027
- return general_api_default.post(`${useradmApiUrl}/auth/logout`).finally(() => {
2028
- cleanUp();
2029
- clearAllRetryTimers(setSnackbar4);
2030
- return Promise.resolve(dispatch({ type: USER_LOGOUT }));
2031
- });
2032
- });
2033
- var switchUserOrganization = createAppAsyncThunk(`${sliceName6}/switchUserOrganization`, (tenantId, { getState }) => {
2034
- if (Object.keys(getState().app.uploadsById).length) {
2035
- return Promise.reject();
2036
- }
2037
- return general_api_default.get(`${useradmApiUrl}/users/tenants/${tenantId}/token`).then(({ data: token }) => {
2038
- window.sessionStorage.setItem("tenantChanged", "true");
2039
- setSessionInfo({ ...getSessionInfo(), token });
2040
- window.location.reload();
2041
- });
2042
- });
2043
- var passwordResetStart = createAppAsyncThunk(
2044
- `${sliceName6}/passwordResetStart`,
2045
- (email, { dispatch }) => general_api_default.post(`${useradmApiUrl}/auth/password-reset/start`, { email }).catch(
2046
- (err) => commonErrorHandler(err, `The password reset request cannot be processed:`, dispatch, void 0, true)
2047
- )
2048
- );
2049
- var passwordResetComplete = createAppAsyncThunk(
2050
- `${sliceName6}/passwordResetComplete`,
2051
- ({ secretHash, newPassword }, { dispatch }) => general_api_default.post(`${useradmApiUrl}/auth/password-reset/complete`, { secret_hash: secretHash, password: newPassword }).catch((err = {}) => {
2052
- const { error, response = {} } = err;
2053
- let errorMsg = "";
2054
- if (response.status == 400) {
2055
- errorMsg = "the link you are using expired or the request is not valid, please try again.";
2056
- } else {
2057
- errorMsg = error;
2058
- }
2059
- dispatch(setSnackbar4("The password reset request cannot be processed: " + errorMsg));
2060
- return Promise.reject(err);
2061
- })
2062
- );
2063
- var verifyEmailStart = createAppAsyncThunk(
2064
- `${sliceName6}/verifyEmailStart`,
2065
- (_, { dispatch, getState }) => general_api_default.post(`${useradmApiUrl}/auth/verify-email/start`, { email: getCurrentUser(getState()).email }).catch((err) => commonErrorHandler(err, "An error occured starting the email verification process:", dispatch)).finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
2066
- );
2067
- var verifyEmailComplete = createAppAsyncThunk(
2068
- `${sliceName6}/verifyEmailComplete`,
2069
- (secret_hash, { dispatch, rejectWithValue }) => general_api_default.post(`${useradmApiUrl}/auth/verify-email/complete`, { secret_hash }).catch((err) => rejectWithValue({ status: err.response?.status, data: err.response?.data })).finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
2070
- );
2071
- var verify2FA = createAppAsyncThunk(
2072
- `${sliceName6}/verify2FA`,
2073
- (tfaData, { dispatch }) => users_api_default.putVerifyTFA(`${useradmApiUrl}/2faverify`, tfaData).then(() => Promise.resolve(dispatch(getUser(OWN_USER_ID)))).catch(
2074
- (err) => commonErrorHandler(err, "An error occured validating the verification code: failed to verify token, please try again.", dispatch, void 0, true)
2075
- )
2076
- );
2077
- var getUserList = createAppAsyncThunk(
2078
- `${sliceName6}/getUserList`,
2079
- (_, { dispatch, getState }) => general_api_default.get(`${useradmApiUrl}/users`).then((res) => {
2080
- const currentUsersById = getUsersById(getState());
2081
- const users = res.data.reduce(
2082
- (accu, item) => {
2083
- accu[item.id] = {
2084
- ...accu[item.id],
2085
- ...item
2086
- };
2087
- return accu;
2088
- },
2089
- { ...currentUsersById }
2090
- );
2091
- return dispatch(actions6.receivedUserList(users));
2092
- }).catch((err) => commonErrorHandler(err, `Users couldn't be loaded.`, dispatch, commonErrorFallback))
2093
- );
2094
- var getUser = createAppAsyncThunk(
2095
- `${sliceName6}/getUser`,
2096
- (id, { dispatch, rejectWithValue }) => general_api_default.get(`${useradmApiUrl}/users/${id}`).then(
2097
- ({ data: user }) => Promise.all([
2098
- dispatch(actions6.receivedUser(user)),
2099
- dispatch(setHideAnnouncement({ shouldHide: false, userId: user.id })),
2100
- dispatch(updateUserColumnSettings({ currentUserId: user.id })),
2101
- user
2102
- ])
2103
- ).catch((e) => rejectWithValue(e))
2104
- );
2105
- var initializeSelf = createAppAsyncThunk(`${sliceName6}/initializeSelf`, (_, { dispatch }) => dispatch(getUser(OWN_USER_ID)));
2106
- var updateUserColumnSettings = createAppAsyncThunk(
2107
- `${sliceName6}/updateUserColumnSettings`,
2108
- ({ columns, currentUserId }, { dispatch, getState }) => {
2109
- const userId = currentUserId ?? getCurrentUser(getState()).id;
2110
- const storageKey = `${userId}-column-widths`;
2111
- let customColumns = [];
2112
- if (!columns) {
2113
- try {
2114
- customColumns = JSON.parse(window.localStorage.getItem(storageKey) || "") || customColumns;
2115
- } catch {
2116
- }
2117
- } else {
2118
- customColumns = columns;
2119
- }
2120
- window.localStorage.setItem(storageKey, JSON.stringify(customColumns));
2121
- return Promise.resolve(dispatch(actions6.setCustomColumns(customColumns)));
2122
- }
2123
- );
2124
- var userActions = {
2125
- add: {
2126
- successMessage: "The user was added successfully.",
2127
- errorMessage: "adding"
2128
- },
2129
- create: {
2130
- successMessage: "The user was created successfully.",
2131
- errorMessage: "creating"
2132
- },
2133
- edit: {
2134
- successMessage: "The user has been updated.",
2135
- errorMessage: "editing"
2136
- },
2137
- remove: {
2138
- successMessage: "The user was removed from the system.",
2139
- errorMessage: "removing"
2140
- }
2141
- };
2142
- var userActionErrorHandler = (err, type, dispatch) => commonErrorHandler(err, `There was an error ${userActions[type].errorMessage} the user.`, dispatch);
2143
- var createUser = createAppAsyncThunk(
2144
- `${sliceName6}/createUser`,
2145
- ({ shouldResetPassword, ...userData }, { dispatch }) => general_api_default.post(`${useradmApiUrl}/users`, { ...userData, send_reset_password: shouldResetPassword }).then(() => Promise.all([dispatch(getUserList()), dispatch(setSnackbar4(userActions.create.successMessage))])).catch((err) => userActionErrorHandler(err, "create", dispatch))
2146
- );
2147
- var removeUser = createAppAsyncThunk(
2148
- `${sliceName6}/removeUser`,
2149
- (userId, { dispatch }) => general_api_default.delete(`${useradmApiUrl}/users/${userId}`).then(() => Promise.all([dispatch(actions6.removedUser(userId)), dispatch(getUserList()), dispatch(setSnackbar4(userActions.remove.successMessage))])).catch((err) => userActionErrorHandler(err, "remove", dispatch))
2150
- );
2151
- var editUser = createAppAsyncThunk(
2152
- `${sliceName6}/editUser`,
2153
- ({ id, ...userData }, { dispatch, getState }) => general_api_default.put(`${useradmApiUrl}/users/${id}`, userData).then(
2154
- () => Promise.all([
2155
- dispatch(actions6.updatedUser({ ...userData, id: id === OWN_USER_ID ? getCurrentUser(getState()).id : id })),
2156
- dispatch(setSnackbar4(userActions.edit.successMessage))
2157
- ])
2158
- ).catch((err) => userActionErrorHandler(err, "edit", dispatch))
2159
- );
2160
- var checkEmailExists = createAppAsyncThunk(`${sliceName6}/checkEmailExists`, async (email) => {
2161
- const response = await general_api_default.get(`${useradmApiUrl}/users/exists?email=${encodeURIComponent(email)}`);
2162
- return response.data.exists;
2163
- });
2164
- var addUserToCurrentTenant = createAppAsyncThunk(`${sliceName6}/addUserToTenant`, (userId, { dispatch, getState }) => {
2165
- const { id } = getOrganization(getState());
2166
- return general_api_default.post(`${useradmApiUrl}/users/${userId}/assign`, { tenant_ids: [id] }).catch((err) => commonErrorHandler(err, `There was an error adding the user to your organization:`, dispatch)).then(() => Promise.all([dispatch(setSnackbar4(userActions.add.successMessage)), dispatch(getUserList())]));
2167
- });
2168
- var enableUser2fa = createAppAsyncThunk(
2169
- `${sliceName6}/enableUser2fa`,
2170
- (userId = OWN_USER_ID, { dispatch }) => general_api_default.post(`${useradmApiUrl}/users/${userId}/2fa/enable`).catch((err) => commonErrorHandler(err, `There was an error enabling Two Factor authentication for the user.`, dispatch)).then(() => Promise.resolve(dispatch(getUser(userId))))
2171
- );
2172
- var disableUser2fa = createAppAsyncThunk(
2173
- `${sliceName6}/disableUser2fa`,
2174
- (userId = OWN_USER_ID, { dispatch }) => general_api_default.post(`${useradmApiUrl}/users/${userId}/2fa/disable`).catch((err) => commonErrorHandler(err, `There was an error disabling Two Factor authentication for the user.`, dispatch)).then(() => Promise.all([dispatch(getUser(userId)), dispatch(actions6.receivedQrCode(null))]))
2175
- );
2176
- var mapHttpPermission = (permission) => Object.entries(uiPermissionsByArea).reduce(
2177
- (accu, [area, definition]) => {
2178
- const endpointMatches = definition.endpoints.filter(
2179
- (endpoint) => endpoint.path.test(permission.value) && (endpoint.types.includes(permission.type) || permission.type === PermissionTypes.Any)
2180
- );
2181
- if (permission.value === PermissionTypes.Any || permission.value.includes(apiRoot) && endpointMatches.length) {
2182
- const endpointUiPermission = endpointMatches.reduce((endpointAccu, endpoint) => [...endpointAccu, ...endpoint.uiPermissions], []);
2183
- const collector = (endpointUiPermission || definition.uiPermissions).reduce((permissionsAccu, uiPermission) => {
2184
- if (permission.type === PermissionTypes.Any || !endpointMatches.length && uiPermission.verbs.some((verb) => verb === permission.type)) {
2185
- permissionsAccu.push(uiPermission.value);
2186
- }
2187
- return permissionsAccu;
2188
- }, []).filter(duplicateFilter);
2189
- if (Array.isArray(accu[area])) {
2190
- accu[area] = [...accu[area], ...collector].filter(duplicateFilter);
2191
- } else {
2192
- accu[area] = mergePermissions(accu[area], { [scopedPermissionAreas[area].excessiveAccessSelector]: collector });
2193
- }
2194
- }
2195
- return accu;
2196
- },
2197
- { ...emptyUiPermissions }
2198
- );
2199
- var permissionActionTypes = {
2200
- any: mapHttpPermission,
2201
- CREATE_DEPLOYMENT: (permission) => permission.type === PermissionTypes.DeviceGroup ? {
2202
- deployments: [uiPermissionsById.deploy.value],
2203
- groups: { [permission.value]: [uiPermissionsById.deploy.value] }
2204
- } : {},
2205
- http: mapHttpPermission,
2206
- REMOTE_TERMINAL: (permission) => permission.type === PermissionTypes.DeviceGroup ? {
2207
- groups: { [permission.value]: [uiPermissionsById.connect.value] }
2208
- } : {},
2209
- VIEW_DEVICE: (permission) => permission.type === PermissionTypes.DeviceGroup ? {
2210
- groups: { [permission.value]: [uiPermissionsById.read.value] }
2211
- } : {}
2212
- };
2213
- var combinePermissions = (existingPermissions, additionalPermissions = {}) => Object.entries(additionalPermissions).reduce((accu, [name, permissions]) => {
2214
- const maybeExistingPermissions = accu[name] || [];
2215
- accu[name] = [...permissions, ...maybeExistingPermissions].filter(duplicateFilter);
2216
- return accu;
2217
- }, existingPermissions);
2218
- var tryParseCustomPermission = (permission) => {
2219
- const uiPermissions = permissionActionTypes[permission.action](permission.object);
2220
- const result = mergePermissions({ ...emptyUiPermissions }, uiPermissions);
2221
- return { isCustom: true, permission, result };
2222
- };
2223
- var customPermissionHandler = (accu, permission) => {
2224
- const processor = tryParseCustomPermission(permission);
2225
- return {
2226
- ...accu,
2227
- isCustom: accu.isCustom || processor.isCustom,
2228
- uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
2229
- };
2230
- };
2231
- var mapPermissionSet = (permissionSetName, names, scope, existingGroupsPermissions = {}) => {
2232
- const permission = Object.values(uiPermissionsById).find((permission2) => permission2.permissionSets[scope] === permissionSetName)?.value;
2233
- const scopedPermissions = names.reduce((accu, name) => combinePermissions(accu, { [name]: [permission] }), existingGroupsPermissions);
2234
- return Object.entries(scopedPermissions).reduce((accu, [key, permissions]) => ({ ...accu, [key]: deriveImpliedAreaPermissions(scope, permissions) }), {});
2235
- };
2236
- var isEmptyPermissionSet = (permissionSet) => !Object.values(permissionSet).reduce((accu, permissions) => {
2237
- if (Array.isArray(permissions)) {
2238
- return accu || !!permissions.length;
2239
- }
2240
- return accu || !isEmpty2(permissions);
2241
- }, false);
2242
- var parseRolePermissions = ({ permission_sets_with_scope = [], permissions = [] }, permissionSets) => {
2243
- const preliminaryResult = permission_sets_with_scope.reduce(
2244
- (accu, permissionSet) => {
2245
- if (!permissionSet.name) {
2246
- return accu;
2247
- }
2248
- const processor = permissionSets[permissionSet.name];
2249
- if (!processor) {
2250
- return accu;
2251
- }
2252
- const scope = Object.keys(scopedPermissionAreas).find((scope2) => uiPermissionsByArea[scope2].scope === permissionSet.scope?.type);
2253
- if (scope) {
2254
- const result = mapPermissionSet(
2255
- permissionSet.name,
2256
- permissionSet.scope?.value ?? [],
2257
- scope,
2258
- accu.uiPermissions[scope]
2259
- );
2260
- return { ...accu, uiPermissions: { ...accu.uiPermissions, [scope]: result } };
2261
- } else if (isEmptyPermissionSet(processor.result)) {
2262
- return processor.permissions?.reduce(customPermissionHandler, accu);
2263
- }
2264
- return {
2265
- ...accu,
2266
- isCustom: accu.isCustom || processor.isCustom,
2267
- uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
2268
- };
2269
- },
2270
- { isCustom: false, uiPermissions: { ...emptyUiPermissions, groups: {}, releases: {} } }
2271
- );
2272
- return permissions.reduce(customPermissionHandler, preliminaryResult);
2273
- };
2274
- var normalizeRbacRoles = (roles, rolesById2, permissionSets) => roles.reduce(
2275
- (accu, role) => {
2276
- let normalizedPermissions;
2277
- let isCustom = false;
2278
- if (rolesById2[role.name]) {
2279
- normalizedPermissions = {
2280
- ...rolesById2[role.name].uiPermissions,
2281
- groups: { ...rolesById2[role.name].uiPermissions.groups },
2282
- releases: { ...rolesById2[role.name].uiPermissions.releases }
2283
- };
2284
- } else {
2285
- const result = parseRolePermissions(role, permissionSets);
2286
- normalizedPermissions = result.uiPermissions;
2287
- isCustom = result.isCustom;
2288
- }
2289
- const roleState = accu[role.name] ?? { ...emptyRole };
2290
- accu[role.name] = {
2291
- ...roleState,
2292
- ...role,
2293
- description: roleState.description ? roleState.description : role.description,
2294
- editable: !rolesById[role.name] && !isCustom && (typeof roleState.editable !== "undefined" ? roleState.editable : true),
2295
- isCustom,
2296
- name: roleState.name ? roleState.name : role.name,
2297
- uiPermissions: normalizedPermissions
2298
- };
2299
- return accu;
2300
- },
2301
- { ...rolesById2 }
2302
- );
2303
- var getPermissionSets = createAppAsyncThunk(
2304
- `${sliceName6}/getPermissionSets`,
2305
- (_, { dispatch, getState }) => general_api_default.get(`${useradmApiUrlv2}/permission_sets?per_page=500`).then(({ data }) => {
2306
- const permissionSets = data.reduce(
2307
- (accu, permissionSet) => {
2308
- const permissionSetState = accu[permissionSet.name] ?? {};
2309
- let permissionSetObject = { ...permissionSetState, ...permissionSet };
2310
- permissionSetObject.result = Object.values(uiPermissionsById).reduce(
2311
- (accu2, item) => Object.entries(item.permissionSets).reduce((collector, [area, permissionSet2]) => {
2312
- if (scopedPermissionAreas[area]) {
2313
- return collector;
2314
- }
2315
- if (permissionSet2 === permissionSetObject.name) {
2316
- collector[area] = [...collector[area], item.value].filter(duplicateFilter);
2317
- }
2318
- return collector;
2319
- }, accu2),
2320
- { ...emptyUiPermissions, ...permissionSetObject.result ?? {} }
2321
- );
2322
- const scopes = Object.values(scopedPermissionAreas).reduce((accu2, { key, scopeType }) => {
2323
- if (permissionSetObject.supported_scope_types?.includes(key) || permissionSetObject.supported_scope_types?.includes(scopeType)) {
2324
- accu2.push(key);
2325
- }
2326
- return accu2;
2327
- }, []);
2328
- permissionSetObject = scopes.reduce((accu2, scope) => {
2329
- accu2.result = {
2330
- ...accu2.result,
2331
- [scope]: mapPermissionSet(permissionSetObject.name, [scopedPermissionAreas[scope].excessiveAccessSelector], scope)
2332
- };
2333
- return accu2;
2334
- }, permissionSetObject);
2335
- accu[permissionSet.name] = permissionSetObject;
2336
- return accu;
2337
- },
2338
- { ...getState().users.permissionSetsById }
2339
- );
2340
- return Promise.all([dispatch(actions6.receivedPermissionSets(permissionSets)), permissionSets]);
2341
- }).catch(() => console.log("Permission set retrieval failed - likely accessing a non-RBAC backend"))
2342
- );
2343
- var getRoles = createAppAsyncThunk(
2344
- `${sliceName6}/getRoles`,
2345
- (_, { dispatch, getState }) => Promise.all([general_api_default.get(`${useradmApiUrlv2}/roles?per_page=500`), dispatch(getPermissionSets())]).then((results) => {
2346
- if (!results) {
2347
- return Promise.resolve();
2348
- }
2349
- const [{ data: roles }, { payload: permissionSetTasks }] = results;
2350
- const rolesById2 = normalizeRbacRoles(roles, getRolesById(getState()), permissionSetTasks[permissionSetTasks.length - 1]);
2351
- return Promise.resolve(dispatch(actions6.receivedRoles(rolesById2)));
2352
- }).catch(() => console.log("Role retrieval failed - likely accessing a non-RBAC backend")).finally(() => Promise.resolve(dispatch(actions6.finishedRoleInitialization(true))))
2353
- );
2354
- var deriveImpliedAreaPermissions = (area, areaPermissions, skipPermissions = []) => {
2355
- const highestAreaPermissionLevelSelected = areaPermissions.reduce(
2356
- (highest, current) => uiPermissionsById[current].permissionLevel > highest ? uiPermissionsById[current].permissionLevel : highest,
2357
- 1
2358
- );
2359
- return uiPermissionsByArea[area].uiPermissions.reduce((permissions, current) => {
2360
- if ((current.permissionLevel < highestAreaPermissionLevelSelected || areaPermissions.includes(current.value)) && !skipPermissions.includes(current.value)) {
2361
- permissions.push(current.value);
2362
- }
2363
- return permissions;
2364
- }, []);
2365
- };
2366
- var transformAreaRoleDataToScopedPermissionsSets = (area, areaPermissions, excessiveAccessSelector) => {
2367
- const permissionSetObject = areaPermissions.reduce((accu, { item, uiPermissions }) => {
2368
- const skipPermissions = scopedPermissionAreas.releases.key === area && item !== ALL_RELEASES ? [uiPermissionsById.upload.value] : [];
2369
- const impliedPermissions = deriveImpliedAreaPermissions(area, uiPermissions, skipPermissions);
2370
- accu = impliedPermissions.reduce((itemPermissionAccu, impliedPermission) => {
2371
- const permissionSetState = itemPermissionAccu[uiPermissionsById[impliedPermission].permissionSets[area]] ?? {
2372
- type: uiPermissionsByArea[area].scope,
2373
- value: []
2374
- };
2375
- itemPermissionAccu[uiPermissionsById[impliedPermission].permissionSets[area]] = {
2376
- ...permissionSetState,
2377
- value: [...permissionSetState.value, item]
2378
- };
2379
- return itemPermissionAccu;
2380
- }, accu);
2381
- return accu;
2382
- }, {});
2383
- return Object.entries(permissionSetObject).map(([name, { value, ...scope }]) => {
2384
- if (value.includes(excessiveAccessSelector)) {
2385
- return { name };
2386
- }
2387
- return { name, scope: { ...scope, value: value.filter(duplicateFilter) } };
2388
- });
2389
- };
2390
- var transformRoleDataToRole = (roleData, roleState = {}) => {
2391
- const role = { ...roleState, ...roleData };
2392
- const { description = "", name, uiPermissions = emptyUiPermissions } = role;
2393
- const { maybeUiPermissions, remainderKeys } = Object.entries(emptyUiPermissions).reduce(
2394
- (accu, [key, emptyPermissions]) => {
2395
- if (!scopedPermissionAreas[key]) {
2396
- accu.remainderKeys.push(key);
2397
- } else if (uiPermissions[key]) {
2398
- accu.maybeUiPermissions[key] = uiPermissions[key].reduce(itemUiPermissionsReducer, emptyPermissions);
2399
- }
2400
- return accu;
2401
- },
2402
- { maybeUiPermissions: {}, remainderKeys: [] }
2403
- );
2404
- const { permissionSetsWithScope, roleUiPermissions } = remainderKeys.reduce(
2405
- (accu, area) => {
2406
- const areaPermissions = role.uiPermissions[area];
2407
- if (!Array.isArray(areaPermissions)) {
2408
- return accu;
2409
- }
2410
- const impliedPermissions = deriveImpliedAreaPermissions(area, areaPermissions);
2411
- accu.roleUiPermissions[area] = impliedPermissions;
2412
- const mappedPermissions = impliedPermissions.map((uiPermission) => ({ name: uiPermissionsById[uiPermission].permissionSets[area] }));
2413
- accu.permissionSetsWithScope.push(...mappedPermissions);
2414
- return accu;
2415
- },
2416
- { permissionSetsWithScope: [{ name: defaultPermissionSets.Basic.name }], roleUiPermissions: {} }
2417
- );
2418
- const scopedPermissionSets = Object.values(scopedPermissionAreas).reduce((accu, { key, excessiveAccessSelector }) => {
2419
- if (!uiPermissions[key]) {
2420
- return accu;
2421
- }
2422
- accu.push(
2423
- ...transformAreaRoleDataToScopedPermissionsSets(
2424
- key,
2425
- uiPermissions[key],
2426
- excessiveAccessSelector
2427
- )
2428
- );
2429
- return accu;
2430
- }, []);
2431
- return {
2432
- permissionSetsWithScope: [...permissionSetsWithScope, ...scopedPermissionSets],
2433
- role: {
2434
- ...emptyRole,
2435
- name,
2436
- description: description ? description : roleState.description || "",
2437
- uiPermissions: {
2438
- ...emptyUiPermissions,
2439
- ...roleUiPermissions,
2440
- ...maybeUiPermissions
2441
- }
2442
- }
2443
- };
2444
- };
2445
- var roleActions = {
2446
- create: {
2447
- successMessage: "The role was created successfully.",
2448
- errorMessage: "creating"
2449
- },
2450
- edit: {
2451
- successMessage: "The role has been updated.",
2452
- errorMessage: "editing"
2453
- },
2454
- remove: {
2455
- successMessage: "The role was deleted successfully.",
2456
- errorMessage: "removing"
2457
- }
2458
- };
2459
- var roleActionErrorHandler = (err, type, dispatch, meta) => {
2460
- let errorContext = `There was an error ${roleActions[type].errorMessage} the role.`;
2461
- if (meta) {
2462
- const { permissionSetsCreated, name } = meta;
2463
- errorContext += ` Tried to ${type} role ${name} with ${permissionSetsCreated} permission sets.`;
2464
- }
2465
- return commonErrorHandler(err, errorContext, dispatch);
2466
- };
2467
- var createRole = createAppAsyncThunk(`${sliceName6}/createRole`, (roleData, { dispatch }) => {
2468
- const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData);
2469
- return general_api_default.post(`${useradmApiUrlv2}/roles`, {
2470
- name: role.name,
2471
- description: role.description,
2472
- permission_sets_with_scope: permissionSetsWithScope
2473
- }).then(() => Promise.all([dispatch(actions6.createdRole(role)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.create.successMessage))])).catch((err) => roleActionErrorHandler(err, "create", dispatch, { permissionSetsCreated: permissionSetsWithScope.length, name: role.name }));
2474
- });
2475
- var editRole = createAppAsyncThunk(`${sliceName6}/editRole`, (roleData, { dispatch, getState }) => {
2476
- const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData, getRolesById(getState())[roleData.name]);
2477
- return general_api_default.put(`${useradmApiUrlv2}/roles/${role.name}`, {
2478
- description: role.description,
2479
- name: role.name,
2480
- permission_sets_with_scope: permissionSetsWithScope
2481
- }).then(() => Promise.all([dispatch(actions6.createdRole(role)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.edit.successMessage))])).catch((err) => roleActionErrorHandler(err, "edit", dispatch, { permissionSetsCreated: permissionSetsWithScope.length, name: role.name }));
2482
- });
2483
- var removeRole = createAppAsyncThunk(
2484
- `${sliceName6}/removeRole`,
2485
- (roleId, { dispatch }) => general_api_default.delete(`${useradmApiUrlv2}/roles/${roleId}`).then(() => Promise.all([dispatch(actions6.removedRole(roleId)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.remove.successMessage))])).catch((err) => roleActionErrorHandler(err, "remove", dispatch))
2486
- );
2487
- var getGlobalSettings2 = createAppAsyncThunk(
2488
- `${sliceName6}/getGlobalSettings`,
2489
- (_, { dispatch }) => general_api_default.get(`${useradmApiUrl}/settings`).then(({ data: settings, headers: { etag } }) => {
2490
- window.sessionStorage.setItem(settingsKeys.initialized, "true");
2491
- return Promise.all([dispatch(actions6.setGlobalSettings(settings)), dispatch(setOfflineThreshold()), etag]);
2492
- })
2493
- );
2494
- var saveGlobalSettings = createAppAsyncThunk(
2495
- `${sliceName6}/saveGlobalSettings`,
2496
- ({ beOptimistic = false, notify = false, ...settings }, { dispatch, getState }) => {
2497
- if (!window.sessionStorage.getItem(settingsKeys.initialized) && !beOptimistic) {
2498
- return;
2499
- }
2500
- return dispatch(getGlobalSettings2()).unwrap().then((result) => {
2501
- const updatedSettings = { ...getState().users.globalSettings, ...settings };
2502
- if (getCurrentUser(getState()).verified) {
2503
- updatedSettings["2fa"] = twoFAStates.enabled;
2504
- } else {
2505
- delete updatedSettings["2fa"];
2506
- }
2507
- const tasks = [dispatch(actions6.setGlobalSettings(updatedSettings))];
2508
- const headers = result[result.length - 1] ? { "If-Match": result[result.length - 1] } : {};
2509
- return general_api_default.post(`${useradmApiUrl}/settings`, updatedSettings, { headers }).then(() => {
2510
- if (notify) {
2511
- tasks.push(dispatch(setSnackbar4("Settings saved successfully")));
2512
- }
2513
- return Promise.all(tasks);
2514
- }).catch((err) => {
2515
- if (beOptimistic) {
2516
- return Promise.all([tasks]);
2517
- }
2518
- console.log(err);
2519
- return commonErrorHandler(err, `The settings couldn't be saved.`, dispatch);
2520
- });
2521
- });
2522
- }
2523
- );
2524
- var getUserSettings2 = createAppAsyncThunk(
2525
- `${sliceName6}/getUserSettings`,
2526
- (_, { dispatch }) => general_api_default.get(`${useradmApiUrl}/settings/me`).then(({ data: settings, headers: { etag } }) => {
2527
- window.sessionStorage.setItem(settingsKeys.initialized, "true");
2528
- return Promise.all([dispatch(actions6.setUserSettings(settings)), etag]);
2529
- })
2530
- );
2531
- var saveUserSettings = createAppAsyncThunk(
2532
- `${sliceName6}/saveUserSettings`,
2533
- (settings = { onboarding: {} }, { dispatch, getState }) => {
2534
- if (!getCurrentUser(getState()).id) {
2535
- return Promise.resolve();
2536
- }
2537
- return dispatch(getUserSettings2()).unwrap().then((result) => {
2538
- const userSettings = getUserSettings(getState());
2539
- const onboardingState = getOnboardingState(getState());
2540
- const tooltipState = getTooltipsState(getState());
2541
- const updatedSettings = {
2542
- ...userSettings,
2543
- ...settings,
2544
- firstLoginTimestamp: userSettings.firstLoginTimestamp ?? dayjs2().format(),
2545
- onboarding: {
2546
- ...onboardingState,
2547
- ...settings.onboarding
2548
- },
2549
- tooltips: tooltipState
2550
- };
2551
- const headers = result[result.length - 1] ? { "If-Match": result[result.length - 1] } : {};
2552
- return Promise.all([
2553
- Promise.resolve(dispatch(actions6.setUserSettings(updatedSettings))),
2554
- general_api_default.post(`${useradmApiUrl}/settings/me`, updatedSettings, { headers })
2555
- ]).catch(() => dispatch(actions6.setUserSettings(userSettings)));
2556
- });
2557
- }
2558
- );
2559
- var get2FAQRCode = createAppAsyncThunk(
2560
- `${sliceName6}/get2FAQRCode`,
2561
- (_, { dispatch }) => general_api_default.get(`${useradmApiUrl}/2faqr`).then((res) => dispatch(actions6.receivedQrCode(res.data.qr)))
2562
- );
2563
- var setHideAnnouncement = createAppAsyncThunk(
2564
- `${sliceName6}/setHideAnnouncement`,
2565
- ({ shouldHide, userId }, { dispatch, getState }) => {
2566
- const currentUserId = userId || getCurrentUser(getState()).id;
2567
- const announcement = getHostedAnnouncement(getState());
2568
- const hash = announcement ? hashString2(announcement) : "";
2569
- const announceCookie = cookies3.get(`${currentUserId}${hash}`);
2570
- if (shouldHide || hash.length && typeof announceCookie !== "undefined") {
2571
- cookies3.set(`${currentUserId}${hash}`, true, { maxAge: 604800 });
2572
- dispatch(setAnnouncement2(""));
2573
- }
2574
- }
2575
- );
2576
- var getTokens = createAppAsyncThunk(
2577
- `${sliceName6}/getTokens`,
2578
- (_, { dispatch, getState }) => general_api_default.get(`${useradmApiUrl}/settings/tokens`).then(({ data: tokens }) => {
2579
- const user = getCurrentUser(getState());
2580
- const updatedUser = {
2581
- ...user,
2582
- tokens
2583
- };
2584
- return Promise.resolve(dispatch(actions6.updatedUser(updatedUser)));
2585
- })
2586
- );
2587
- var ONE_YEAR = 31536e3;
2588
- var generateToken = createAppAsyncThunk(
2589
- `${sliceName6}/generateToken`,
2590
- ({ expiresIn = ONE_YEAR, name }, { dispatch }) => general_api_default.post(`${useradmApiUrl}/settings/tokens`, { name, expires_in: expiresIn }).then(({ data: token }) => Promise.all([dispatch(getTokens()), token])).catch((err) => commonErrorHandler(err, "There was an error creating the token:", dispatch))
2591
- );
2592
- var revokeToken = createAppAsyncThunk(
2593
- `${sliceName6}/revokeToken`,
2594
- (token, { dispatch }) => general_api_default.delete(`${useradmApiUrl}/settings/tokens/${token.id}`).then(() => Promise.resolve(dispatch(getTokens())))
2595
- );
2596
- var setTooltipReadState = createAppAsyncThunk(
2597
- `${sliceName6}/setTooltipReadState`,
2598
- async ({ persist, ...remainder }, { dispatch }) => {
2599
- dispatch(actions6.setTooltipState(remainder));
2600
- if (persist) {
2601
- await dispatch(saveUserSettings());
2602
- }
2603
- }
2604
- );
2605
- var setAllTooltipsReadState = createAppAsyncThunk(
2606
- `${sliceName6}/toggleHelptips`,
2607
- ({ readState = READ_STATES.read, tooltipIds }, { dispatch }) => {
2608
- const updatedTips = tooltipIds.reduce((accu, id) => ({ ...accu, [id]: { readState } }), {});
2609
- return Promise.resolve(dispatch(actions6.setTooltipsState(updatedTips))).then(() => dispatch(saveUserSettings()));
2610
- }
2611
- );
2612
- var submitUserFeedback = createAppAsyncThunk(
2613
- `${sliceName6}/submitFeedback`,
2614
- ({ formId, feedback }, { dispatch }) => general_api_default.post(`${useradmApiUrlv2}/support/feedback/${formId}`, feedback).then(() => {
2615
- if (formId === "product") {
2616
- const today = /* @__PURE__ */ new Date();
2617
- dispatch(saveUserSettings({ feedbackCollectedAt: today.toISOString().split("T")[0] }));
2618
- setTimeout(() => dispatch(actions6.setShowFeedbackDialog(false)), TIMEOUTS.threeSeconds);
2619
- }
2620
- })
2621
- );
2622
-
2623
- // src/appSlice/thunks.ts
2624
- var cookies4 = new Cookies4();
2625
- var setFirstLoginAfterSignup = createAppAsyncThunk(`${sliceName}/setFirstLoginAfterSignup`, (firstLoginAfterSignup, { dispatch }) => {
2626
- cookies4.set("firstLoginAfterSignup", !!firstLoginAfterSignup, { maxAge: 60, path: "/", domain: ".mender.io", sameSite: false });
2627
- dispatch(actions.setFirstLoginAfterSignup(!!firstLoginAfterSignup));
2628
- });
2629
- var dateFunctionMap = {
2630
- getDays: "getDate",
2631
- setDays: "setDate"
2632
- };
2633
- var setOfflineThreshold = createAppAsyncThunk(`${sliceName}/setOfflineThreshold`, (_, { dispatch, getState }) => {
2634
- const { interval, intervalUnit } = getOfflineThresholdSettings(getState());
2635
- const today = /* @__PURE__ */ new Date();
2636
- const intervalName = `${intervalUnit.charAt(0).toUpperCase()}${intervalUnit.substring(1)}`;
2637
- const setter = dateFunctionMap[`set${intervalName}`] ?? `set${intervalName}`;
2638
- const getter = dateFunctionMap[`get${intervalName}`] ?? `get${intervalName}`;
2639
- today[setter](today[getter]() - interval);
2640
- let value;
2641
- try {
2642
- value = today.toISOString();
2643
- } catch {
2644
- return Promise.resolve(dispatch(actions.setSnackbar("There was an error saving the offline threshold, please check your settings.")));
2645
- }
2646
- return Promise.resolve(dispatch(actions.setOfflineThreshold(value)));
2647
- });
2648
- var versionRegex = new RegExp(/\d+\.\d+/);
2649
- var getLatestRelease = (thing) => {
2650
- const latestKey = Object.keys(thing).filter((key) => versionRegex.test(key)).sort().reverse()[0];
2651
- return thing[latestKey];
2652
- };
2653
- var repoKeyMap = {
2654
- integration: "Integration",
2655
- "mender-artifact": "Mender-Artifact"
2656
- };
2657
- var deductSaasState = (latestRelease, guiTags) => {
2658
- const latestGuiTag = guiTags.length ? guiTags[0].name : "";
2659
- return latestGuiTag ? latestGuiTag : latestRelease.release;
2660
- };
2661
- var getLatestReleaseInfo = createAppAsyncThunk(`${sliceName}/getLatestReleaseInfo`, (_, { dispatch, getState }) => {
2662
- if (!getFeatures(getState()).isHosted) {
2663
- return Promise.resolve();
2664
- }
2665
- return Promise.all([general_api_default.get("/versions.json"), general_api_default.get("/tags.json")]).catch((err) => {
2666
- console.log("init error:", extractErrorMessage3(err));
2667
- return Promise.resolve([{ data: {} }, { data: [] }]);
2668
- }).then(([{ data }, { data: guiTags }]) => {
2669
- if (!guiTags.length) {
2670
- return Promise.resolve();
2671
- }
2672
- const { releases } = data;
2673
- const latestRelease = getLatestRelease(getLatestRelease(releases));
2674
- const { latestRepos, latestVersions } = latestRelease.repos.reduce(
2675
- (accu, item) => {
2676
- if (repoKeyMap[item.name]) {
2677
- accu.latestVersions[repoKeyMap[item.name]] = getComparisonCompatibleVersion(item.version);
2678
- }
2679
- accu.latestRepos[item.name] = getComparisonCompatibleVersion(item.version);
2680
- return accu;
2681
- },
2682
- { latestVersions: { ...getState().app.versionInformation }, latestRepos: {} }
2683
- );
2684
- const info = deductSaasState(latestRelease, guiTags);
2685
- return Promise.resolve(
2686
- dispatch(
2687
- actions.setVersionInformation({
2688
- ...latestVersions,
2689
- Server: info,
2690
- latestRelease: {
2691
- releaseDate: latestRelease.release_date,
2692
- repos: latestRepos
2693
- }
2694
- })
2695
- )
2696
- );
2697
- });
2698
- });
2699
- var setSearchState = createAppAsyncThunk(`${sliceName}/setSearchState`, (searchState, { dispatch, getState }) => {
2700
- const currentState = getSearchState(getState());
2701
- const nextState = {
2702
- ...currentState,
2703
- ...searchState,
2704
- sort: {
2705
- ...currentState.sort,
2706
- ...searchState.sort
2707
- }
2708
- };
2709
- const tasks = [];
2710
- const { isSearching: currentSearching, deviceIds: currentDevices, searchTotal: currentTotal, ...currentRequestState } = currentState;
2711
- const { isSearching: nextSearching, deviceIds: nextDevices, searchTotal: nextTotal, ...nextRequestState } = nextState;
2712
- if (nextRequestState.searchTerm && !deepCompare4(currentRequestState, nextRequestState)) {
2713
- nextState.isSearching = true;
2714
- tasks.push(
2715
- dispatch(searchDevices(nextState)).unwrap().then((results) => {
2716
- const searchResult = results[results.length - 1];
2717
- return dispatch(actions.setSearchState({ ...searchResult, isSearching: false }));
2718
- }).catch(() => dispatch(actions.setSearchState({ isSearching: false, searchTotal: 0 })))
2719
- );
2720
- }
2721
- tasks.push(dispatch(actions.setSearchState(nextState)));
2722
- return Promise.all(tasks);
2723
- });
2724
-
2725
- export {
2726
- setFirstLoginAfterSignup,
2727
- setOfflineThreshold,
2728
- getLatestReleaseInfo,
2729
- setSearchState,
2730
- deriveDeploymentGroup,
2731
- getDeploymentsByStatus2 as getDeploymentsByStatus,
2732
- createDeployment,
2733
- getDeploymentDevices,
2734
- getDeviceDeployments,
2735
- resetDeviceDeployments,
2736
- getSingleDeployment,
2737
- getDeviceLog,
2738
- abortDeployment,
2739
- updateDeploymentControlMap,
2740
- setDeploymentsState,
2741
- getDeploymentsConfig,
2742
- saveDeltaDeploymentsConfig,
2743
- generateDeploymentLogAnalysis,
2744
- getGroups,
2745
- addDevicesToGroup,
2746
- removeDevicesFromGroup,
2747
- addStaticGroup,
2748
- removeReportsByGroupName,
2749
- removeStaticGroup,
2750
- getDynamicGroup,
2751
- getDynamicGroups,
2752
- addDynamicGroup,
2753
- updateDynamicGroup,
2754
- removeDynamicGroup,
2755
- selectGroup,
2756
- getGroupDevices,
2757
- getAllGroupDevices,
2758
- getAllDynamicGroupDevices,
2759
- getDeviceById2 as getDeviceById,
2760
- getDeviceInfo,
2761
- getAllDeviceCounts,
2762
- getDeviceLimits,
2763
- setDeviceListState,
2764
- getDevicesByStatus,
2765
- getAllDevicesByStatus,
2766
- searchDevices,
2767
- getDeviceAttributes,
2768
- updateReportData,
2769
- getReportDataWithoutBackendSupport,
2770
- getDeviceConnect,
2771
- triggerDeviceUpdate,
2772
- getSessionDetails,
2773
- getDeviceFileDownloadLink,
2774
- deviceFileUpload,
2775
- getDeviceAuth,
2776
- getDevicesWithAuth,
2777
- updateDeviceAuth,
2778
- updateDevicesAuth,
2779
- deleteAuthset,
2780
- preauthDevice,
2781
- decommissionDevice,
2782
- getDeviceConfig,
2783
- setDeviceConfig,
2784
- applyDeviceConfig,
2785
- setDeviceTags,
2786
- getDeviceTwin,
2787
- setDeviceTwin,
2788
- getSystemDevices,
2789
- getGatewayDevices,
2790
- getOnboardingState2 as getOnboardingState,
2791
- setOnboardingDeviceType,
2792
- setOnboardingApproach,
2793
- setOnboardingComplete,
2794
- setOnboardingCanceled,
2795
- advanceOnboarding,
2796
- cancelRequest,
2797
- transformProductResponse,
2798
- getTargetLocation,
2799
- createOrganizationTrial,
2800
- startCardUpdate,
2801
- confirmCardUpdate,
2802
- getCurrentCard,
2803
- startUpgrade,
2804
- cancelUpgrade,
2805
- completeUpgrade,
2806
- getAuditLogs,
2807
- getAuditLogsCsvLink,
2808
- setAuditlogsState,
2809
- tenantDataDivergedMessage,
2810
- addTenant,
2811
- getTenants,
2812
- setTenantsListState,
2813
- editTenant,
2814
- editBillingProfile,
2815
- createBillingProfile,
2816
- removeTenant,
2817
- getUserOrganization,
2818
- getUserBilling,
2819
- getUserSubscription,
2820
- getBillingPreview,
2821
- getCurrentSubscription,
2822
- getProducts,
2823
- requestPlanUpgrade,
2824
- sendSupportMessage,
2825
- requestPlanChange,
2826
- downloadLicenseReport,
2827
- createIntegration,
2828
- changeIntegration,
2829
- deleteIntegration,
2830
- getIntegrations,
2831
- getWebhookEvents,
2832
- storeSsoConfig,
2833
- changeSsoConfig,
2834
- deleteSsoConfig,
2835
- getSsoConfigById,
2836
- getSsoConfigs,
2837
- loginUser,
2838
- logoutUser,
2839
- switchUserOrganization,
2840
- passwordResetStart,
2841
- passwordResetComplete,
2842
- verifyEmailStart,
2843
- verifyEmailComplete,
2844
- verify2FA,
2845
- getUserList,
2846
- getUser,
2847
- initializeSelf,
2848
- updateUserColumnSettings,
2849
- createUser,
2850
- removeUser,
2851
- editUser,
2852
- checkEmailExists,
2853
- addUserToCurrentTenant,
2854
- enableUser2fa,
2855
- disableUser2fa,
2856
- normalizeRbacRoles,
2857
- getPermissionSets,
2858
- getRoles,
2859
- createRole,
2860
- editRole,
2861
- removeRole,
2862
- getGlobalSettings2 as getGlobalSettings,
2863
- saveGlobalSettings,
2864
- getUserSettings2 as getUserSettings,
2865
- saveUserSettings,
2866
- get2FAQRCode,
2867
- setHideAnnouncement,
2868
- getTokens,
2869
- generateToken,
2870
- revokeToken,
2871
- setTooltipReadState,
2872
- setAllTooltipsReadState,
2873
- submitUserFeedback
2874
- };
2875
- //# sourceMappingURL=chunk-FXPRG4WH.js.map