@fctc/interface-logic 1.7.4 → 1.7.5

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.
package/dist/services.mjs CHANGED
@@ -28,634 +28,6 @@ var UriConstants = /* @__PURE__ */ ((UriConstants2) => {
28
28
  return UriConstants2;
29
29
  })(UriConstants || {});
30
30
 
31
- // src/store/index.ts
32
- import { useDispatch, useSelector } from "react-redux";
33
-
34
- // src/store/reducers/breadcrums-slice/index.ts
35
- import { createSlice } from "@reduxjs/toolkit";
36
- var initialState = {
37
- breadCrumbs: []
38
- };
39
- var breadcrumbsSlice = createSlice({
40
- name: "breadcrumbs",
41
- initialState,
42
- reducers: {
43
- setBreadCrumbs: (state, action) => {
44
- state.breadCrumbs = [...state.breadCrumbs, action.payload];
45
- }
46
- }
47
- });
48
- var { setBreadCrumbs } = breadcrumbsSlice.actions;
49
- var breadcrums_slice_default = breadcrumbsSlice.reducer;
50
-
51
- // src/store/reducers/env-slice/index.ts
52
- import { createSlice as createSlice2 } from "@reduxjs/toolkit";
53
- var initialState2 = {
54
- baseUrl: "",
55
- companies: [],
56
- user: {},
57
- db: "",
58
- refreshTokenEndpoint: "",
59
- config: {
60
- grantType: "",
61
- clientId: "",
62
- clientSecret: "",
63
- redirectUri: ""
64
- },
65
- envFile: null,
66
- requests: {
67
- get: async (url, headers) => ({}),
68
- post: async (url, body, headers) => ({}),
69
- post_excel: async (url, body, headers) => ({}),
70
- put: async (url, body, headers) => ({}),
71
- patch: async (url, body) => ({}),
72
- delete: async (url, body) => ({})
73
- },
74
- defaultCompany: {
75
- id: null,
76
- logo: "",
77
- secondary_color: "",
78
- primary_color: ""
79
- },
80
- context: {
81
- uid: null,
82
- allowed_company_ids: [],
83
- lang: "vi_VN",
84
- tz: "Asia/Saigon"
85
- }
86
- };
87
- var envSlice = createSlice2({
88
- name: "env",
89
- initialState: initialState2,
90
- reducers: {
91
- setEnv: (state, action) => {
92
- Object.assign(state, action.payload);
93
- },
94
- setUid: (state, action) => {
95
- state.context.uid = action.payload;
96
- },
97
- setAllowCompanies: (state, action) => {
98
- state.context.allowed_company_ids = action.payload;
99
- },
100
- setCompanies: (state, action) => {
101
- state.companies = action.payload;
102
- },
103
- setDefaultCompany: (state, action) => {
104
- state.defaultCompany = action.payload;
105
- },
106
- setLang: (state, action) => {
107
- state.context.lang = action.payload;
108
- },
109
- setUser: (state, action) => {
110
- state.user = action.payload;
111
- },
112
- setConfig: (state, action) => {
113
- state.config = action.payload;
114
- },
115
- setEnvFile: (state, action) => {
116
- state.envFile = action.payload;
117
- }
118
- }
119
- });
120
- var {
121
- setEnv,
122
- setUid,
123
- setLang,
124
- setAllowCompanies,
125
- setCompanies,
126
- setDefaultCompany,
127
- setUser,
128
- setConfig,
129
- setEnvFile
130
- } = envSlice.actions;
131
- var env_slice_default = envSlice.reducer;
132
-
133
- // src/store/reducers/excel-slice/index.ts
134
- import { createSlice as createSlice3 } from "@reduxjs/toolkit";
135
- var initialState3 = {
136
- dataParse: null,
137
- idFile: null,
138
- isFileLoaded: false,
139
- loadingImport: false,
140
- selectedFile: null,
141
- errorData: null
142
- };
143
- var excelSlice = createSlice3({
144
- name: "excel",
145
- initialState: initialState3,
146
- reducers: {
147
- setDataParse: (state, action) => {
148
- state.dataParse = action.payload;
149
- },
150
- setIdFile: (state, action) => {
151
- state.idFile = action.payload;
152
- },
153
- setIsFileLoaded: (state, action) => {
154
- state.isFileLoaded = action.payload;
155
- },
156
- setLoadingImport: (state, action) => {
157
- state.loadingImport = action.payload;
158
- },
159
- setSelectedFile: (state, action) => {
160
- state.selectedFile = action.payload;
161
- },
162
- setErrorData: (state, action) => {
163
- state.errorData = action.payload;
164
- }
165
- }
166
- });
167
- var {
168
- setDataParse,
169
- setIdFile,
170
- setIsFileLoaded,
171
- setLoadingImport,
172
- setSelectedFile,
173
- setErrorData
174
- } = excelSlice.actions;
175
- var excel_slice_default = excelSlice.reducer;
176
-
177
- // src/store/reducers/form-slice/index.ts
178
- import { createSlice as createSlice4 } from "@reduxjs/toolkit";
179
- var initialState4 = {
180
- viewDataStore: {},
181
- isShowingModalDetail: false,
182
- isShowModalTranslate: false,
183
- formSubmitComponent: {},
184
- fieldTranslation: null,
185
- listSubject: {},
186
- dataUser: {}
187
- };
188
- var formSlice = createSlice4({
189
- name: "form",
190
- initialState: initialState4,
191
- reducers: {
192
- setViewDataStore: (state, action) => {
193
- state.viewDataStore = action.payload;
194
- },
195
- setIsShowingModalDetail: (state, action) => {
196
- state.isShowingModalDetail = action.payload;
197
- },
198
- setIsShowModalTranslate: (state, action) => {
199
- state.isShowModalTranslate = action.payload;
200
- },
201
- setFormSubmitComponent: (state, action) => {
202
- state.formSubmitComponent[action.payload.key] = action.payload.component;
203
- },
204
- setFieldTranslate: (state, action) => {
205
- state.fieldTranslation = action.payload;
206
- },
207
- setListSubject: (state, action) => {
208
- state.listSubject = action.payload;
209
- },
210
- setDataUser: (state, action) => {
211
- state.dataUser = action.payload;
212
- }
213
- }
214
- });
215
- var {
216
- setViewDataStore,
217
- setIsShowingModalDetail,
218
- setIsShowModalTranslate,
219
- setFormSubmitComponent,
220
- setFieldTranslate,
221
- setListSubject,
222
- setDataUser
223
- } = formSlice.actions;
224
- var form_slice_default = formSlice.reducer;
225
-
226
- // src/store/reducers/header-slice/index.ts
227
- import { createSlice as createSlice5 } from "@reduxjs/toolkit";
228
- var headerSlice = createSlice5({
229
- name: "header",
230
- initialState: {
231
- value: { allowedCompanyIds: [] }
232
- },
233
- reducers: {
234
- setHeader: (state, action) => {
235
- state.value = { ...state.value, ...action.payload };
236
- },
237
- setAllowedCompanyIds: (state, action) => {
238
- state.value.allowedCompanyIds = action.payload;
239
- }
240
- }
241
- });
242
- var { setAllowedCompanyIds, setHeader } = headerSlice.actions;
243
- var header_slice_default = headerSlice.reducer;
244
-
245
- // src/store/reducers/list-slice/index.ts
246
- import { createSlice as createSlice6 } from "@reduxjs/toolkit";
247
- var initialState5 = {
248
- pageLimit: 10,
249
- fields: {},
250
- order: "",
251
- selectedRowKeys: [],
252
- selectedRadioKey: 0,
253
- indexRowTableModal: -2,
254
- isUpdateTableModal: false,
255
- footerGroupTable: {},
256
- transferDetail: null,
257
- page: 0,
258
- domainTable: []
259
- };
260
- var listSlice = createSlice6({
261
- name: "list",
262
- initialState: initialState5,
263
- reducers: {
264
- setPageLimit: (state, action) => {
265
- state.pageLimit = action.payload;
266
- },
267
- setFields: (state, action) => {
268
- state.fields = action.payload;
269
- },
270
- setOrder: (state, action) => {
271
- state.order = action.payload;
272
- },
273
- setSelectedRowKeys: (state, action) => {
274
- state.selectedRowKeys = action.payload;
275
- },
276
- setSelectedRadioKey: (state, action) => {
277
- state.selectedRadioKey = action.payload;
278
- },
279
- setIndexRowTableModal: (state, action) => {
280
- state.indexRowTableModal = action.payload;
281
- },
282
- setTransferDetail: (state, action) => {
283
- state.transferDetail = action.payload;
284
- },
285
- setIsUpdateTableModal: (state, action) => {
286
- state.isUpdateTableModal = action.payload;
287
- },
288
- setPage: (state, action) => {
289
- state.page = action.payload;
290
- },
291
- setDomainTable: (state, action) => {
292
- state.domainTable = action.payload;
293
- }
294
- }
295
- });
296
- var {
297
- setPageLimit,
298
- setFields,
299
- setOrder,
300
- setSelectedRowKeys,
301
- setIndexRowTableModal,
302
- setIsUpdateTableModal,
303
- setPage,
304
- setSelectedRadioKey,
305
- setTransferDetail,
306
- setDomainTable
307
- } = listSlice.actions;
308
- var list_slice_default = listSlice.reducer;
309
-
310
- // src/store/reducers/login-slice/index.ts
311
- import { createSlice as createSlice7 } from "@reduxjs/toolkit";
312
- var initialState6 = {
313
- db: "",
314
- redirectTo: "/",
315
- forgotPasswordUrl: "/"
316
- };
317
- var loginSlice = createSlice7({
318
- name: "login",
319
- initialState: initialState6,
320
- reducers: {
321
- setDb: (state, action) => {
322
- state.db = action.payload;
323
- },
324
- setRedirectTo: (state, action) => {
325
- state.redirectTo = action.payload;
326
- },
327
- setForgotPasswordUrl: (state, action) => {
328
- state.forgotPasswordUrl = action.payload;
329
- }
330
- }
331
- });
332
- var { setDb, setRedirectTo, setForgotPasswordUrl } = loginSlice.actions;
333
- var login_slice_default = loginSlice.reducer;
334
-
335
- // src/store/reducers/navbar-slice/index.ts
336
- import { createSlice as createSlice8 } from "@reduxjs/toolkit";
337
- var initialState7 = {
338
- menuFocus: {},
339
- menuAction: {},
340
- navbarWidth: 250,
341
- menuList: []
342
- };
343
- var navbarSlice = createSlice8({
344
- name: "navbar",
345
- initialState: initialState7,
346
- reducers: {
347
- setMenuFocus: (state, action) => {
348
- state.menuFocus = action.payload;
349
- },
350
- setMenuFocusAction: (state, action) => {
351
- state.menuAction = action.payload;
352
- },
353
- setNavbarWidth: (state, action) => {
354
- state.navbarWidth = action.payload;
355
- },
356
- setMenuList: (state, action) => {
357
- state.menuList = action.payload;
358
- }
359
- }
360
- });
361
- var { setMenuFocus, setMenuFocusAction, setNavbarWidth, setMenuList } = navbarSlice.actions;
362
- var navbar_slice_default = navbarSlice.reducer;
363
-
364
- // src/store/reducers/profile-slice/index.ts
365
- import { createSlice as createSlice9 } from "@reduxjs/toolkit";
366
- var initialState8 = {
367
- profile: {}
368
- };
369
- var profileSlice = createSlice9({
370
- name: "profile",
371
- initialState: initialState8,
372
- reducers: {
373
- setProfile: (state, action) => {
374
- state.profile = action.payload;
375
- }
376
- }
377
- });
378
- var { setProfile } = profileSlice.actions;
379
- var profile_slice_default = profileSlice.reducer;
380
-
381
- // src/store/reducers/search-slice/index.ts
382
- import { createSlice as createSlice10 } from "@reduxjs/toolkit";
383
- var initialState9 = {
384
- groupByDomain: null,
385
- searchBy: [],
386
- searchString: "",
387
- hoveredIndexSearchList: null,
388
- selectedTags: [],
389
- firstDomain: null,
390
- searchMap: {},
391
- filterBy: [],
392
- groupBy: []
393
- };
394
- var searchSlice = createSlice10({
395
- name: "search",
396
- initialState: initialState9,
397
- reducers: {
398
- setGroupByDomain: (state, action) => {
399
- state.groupByDomain = action.payload;
400
- },
401
- setSearchBy: (state, action) => {
402
- state.searchBy = action.payload;
403
- },
404
- setSearchString: (state, action) => {
405
- state.searchString = action.payload;
406
- },
407
- setHoveredIndexSearchList: (state, action) => {
408
- state.hoveredIndexSearchList = action.payload;
409
- },
410
- setSelectedTags: (state, action) => {
411
- state.selectedTags = action.payload;
412
- },
413
- setFirstDomain: (state, action) => {
414
- state.firstDomain = action.payload;
415
- },
416
- setFilterBy: (state, action) => {
417
- state.filterBy = action.payload;
418
- },
419
- setGroupBy: (state, action) => {
420
- state.groupBy = action.payload;
421
- },
422
- setSearchMap: (state, action) => {
423
- state.searchMap = action.payload;
424
- },
425
- updateSearchMap: (state, action) => {
426
- if (!state.searchMap[action.payload.key]) {
427
- state.searchMap[action.payload.key] = [];
428
- }
429
- state.searchMap[action.payload.key].push(action.payload.value);
430
- },
431
- removeKeyFromSearchMap: (state, action) => {
432
- const { key, item } = action.payload;
433
- const values = state.searchMap[key];
434
- if (!values) return;
435
- if (item) {
436
- const filtered = values.filter((value) => value.name !== item.name);
437
- if (filtered.length > 0) {
438
- state.searchMap[key] = filtered;
439
- } else {
440
- delete state.searchMap[key];
441
- }
442
- } else {
443
- delete state.searchMap[key];
444
- }
445
- },
446
- clearSearchMap: (state) => {
447
- state.searchMap = {};
448
- }
449
- }
450
- });
451
- var {
452
- setGroupByDomain,
453
- setSelectedTags,
454
- setSearchString,
455
- setHoveredIndexSearchList,
456
- setFirstDomain,
457
- setSearchBy,
458
- setFilterBy,
459
- setSearchMap,
460
- updateSearchMap,
461
- removeKeyFromSearchMap,
462
- setGroupBy,
463
- clearSearchMap
464
- } = searchSlice.actions;
465
- var search_slice_default = searchSlice.reducer;
466
-
467
- // src/store/store.ts
468
- import { configureStore } from "@reduxjs/toolkit";
469
-
470
- // node_modules/redux/dist/redux.mjs
471
- function formatProdErrorMessage(code) {
472
- return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
473
- }
474
- var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
475
- var ActionTypes = {
476
- INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
477
- REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
478
- PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
479
- };
480
- var actionTypes_default = ActionTypes;
481
- function isPlainObject(obj) {
482
- if (typeof obj !== "object" || obj === null)
483
- return false;
484
- let proto = obj;
485
- while (Object.getPrototypeOf(proto) !== null) {
486
- proto = Object.getPrototypeOf(proto);
487
- }
488
- return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
489
- }
490
- function miniKindOf(val) {
491
- if (val === void 0)
492
- return "undefined";
493
- if (val === null)
494
- return "null";
495
- const type = typeof val;
496
- switch (type) {
497
- case "boolean":
498
- case "string":
499
- case "number":
500
- case "symbol":
501
- case "function": {
502
- return type;
503
- }
504
- }
505
- if (Array.isArray(val))
506
- return "array";
507
- if (isDate(val))
508
- return "date";
509
- if (isError(val))
510
- return "error";
511
- const constructorName = ctorName(val);
512
- switch (constructorName) {
513
- case "Symbol":
514
- case "Promise":
515
- case "WeakMap":
516
- case "WeakSet":
517
- case "Map":
518
- case "Set":
519
- return constructorName;
520
- }
521
- return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
522
- }
523
- function ctorName(val) {
524
- return typeof val.constructor === "function" ? val.constructor.name : null;
525
- }
526
- function isError(val) {
527
- return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
528
- }
529
- function isDate(val) {
530
- if (val instanceof Date)
531
- return true;
532
- return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
533
- }
534
- function kindOf(val) {
535
- let typeOfVal = typeof val;
536
- if (process.env.NODE_ENV !== "production") {
537
- typeOfVal = miniKindOf(val);
538
- }
539
- return typeOfVal;
540
- }
541
- function warning(message) {
542
- if (typeof console !== "undefined" && typeof console.error === "function") {
543
- console.error(message);
544
- }
545
- try {
546
- throw new Error(message);
547
- } catch (e) {
548
- }
549
- }
550
- function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
551
- const reducerKeys = Object.keys(reducers);
552
- const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
553
- if (reducerKeys.length === 0) {
554
- return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
555
- }
556
- if (!isPlainObject(inputState)) {
557
- return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
558
- }
559
- const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
560
- unexpectedKeys.forEach((key) => {
561
- unexpectedKeyCache[key] = true;
562
- });
563
- if (action && action.type === actionTypes_default.REPLACE)
564
- return;
565
- if (unexpectedKeys.length > 0) {
566
- return `Unexpected ${unexpectedKeys.length > 1 ? "keys" : "key"} "${unexpectedKeys.join('", "')}" found in ${argumentName}. Expected to find one of the known reducer keys instead: "${reducerKeys.join('", "')}". Unexpected keys will be ignored.`;
567
- }
568
- }
569
- function assertReducerShape(reducers) {
570
- Object.keys(reducers).forEach((key) => {
571
- const reducer = reducers[key];
572
- const initialState10 = reducer(void 0, {
573
- type: actionTypes_default.INIT
574
- });
575
- if (typeof initialState10 === "undefined") {
576
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : `The slice reducer for key "${key}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
577
- }
578
- if (typeof reducer(void 0, {
579
- type: actionTypes_default.PROBE_UNKNOWN_ACTION()
580
- }) === "undefined") {
581
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : `The slice reducer for key "${key}" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);
582
- }
583
- });
584
- }
585
- function combineReducers(reducers) {
586
- const reducerKeys = Object.keys(reducers);
587
- const finalReducers = {};
588
- for (let i = 0; i < reducerKeys.length; i++) {
589
- const key = reducerKeys[i];
590
- if (process.env.NODE_ENV !== "production") {
591
- if (typeof reducers[key] === "undefined") {
592
- warning(`No reducer provided for key "${key}"`);
593
- }
594
- }
595
- if (typeof reducers[key] === "function") {
596
- finalReducers[key] = reducers[key];
597
- }
598
- }
599
- const finalReducerKeys = Object.keys(finalReducers);
600
- let unexpectedKeyCache;
601
- if (process.env.NODE_ENV !== "production") {
602
- unexpectedKeyCache = {};
603
- }
604
- let shapeAssertionError;
605
- try {
606
- assertReducerShape(finalReducers);
607
- } catch (e) {
608
- shapeAssertionError = e;
609
- }
610
- return function combination(state = {}, action) {
611
- if (shapeAssertionError) {
612
- throw shapeAssertionError;
613
- }
614
- if (process.env.NODE_ENV !== "production") {
615
- const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
616
- if (warningMessage) {
617
- warning(warningMessage);
618
- }
619
- }
620
- let hasChanged = false;
621
- const nextState = {};
622
- for (let i = 0; i < finalReducerKeys.length; i++) {
623
- const key = finalReducerKeys[i];
624
- const reducer = finalReducers[key];
625
- const previousStateForKey = state[key];
626
- const nextStateForKey = reducer(previousStateForKey, action);
627
- if (typeof nextStateForKey === "undefined") {
628
- const actionType = action && action.type;
629
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : `When called with an action of type ${actionType ? `"${String(actionType)}"` : "(unknown type)"}, the slice reducer for key "${key}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);
630
- }
631
- nextState[key] = nextStateForKey;
632
- hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
633
- }
634
- hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
635
- return hasChanged ? nextState : state;
636
- };
637
- }
638
-
639
- // src/store/store.ts
640
- var rootReducer = combineReducers({
641
- env: env_slice_default,
642
- header: header_slice_default,
643
- navbar: navbar_slice_default,
644
- list: list_slice_default,
645
- search: search_slice_default,
646
- form: form_slice_default,
647
- breadcrumbs: breadcrums_slice_default,
648
- login: login_slice_default,
649
- excel: excel_slice_default,
650
- profile: profile_slice_default
651
- });
652
- var envStore = configureStore({
653
- reducer: rootReducer,
654
- middleware: (getDefaultMiddleware) => getDefaultMiddleware({
655
- serializableCheck: false
656
- })
657
- });
658
-
659
31
  // src/configs/axios-client.ts
660
32
  import axios from "axios";
661
33
 
@@ -2775,11 +2147,331 @@ var toQueryString = (params) => {
2775
2147
  (key) => encodeURIComponent(key) + "=" + encodeURIComponent(params[key].toString())
2776
2148
  ).join("&");
2777
2149
  };
2150
+ var updateTokenParamInOriginalRequest = (originalRequest, newAccessToken) => {
2151
+ if (!originalRequest.data) return originalRequest.data;
2152
+ if (typeof originalRequest.data === "string") {
2153
+ try {
2154
+ const parsedData = JSON.parse(originalRequest.data);
2155
+ if (parsedData.with_context && typeof parsedData.with_context === "object") {
2156
+ parsedData.with_context.token = newAccessToken;
2157
+ }
2158
+ return JSON.stringify(parsedData);
2159
+ } catch (e) {
2160
+ console.warn("Failed to parse originalRequest.data", e);
2161
+ return originalRequest.data;
2162
+ }
2163
+ }
2164
+ if (typeof originalRequest.data === "object" && originalRequest.data.with_context) {
2165
+ originalRequest.data.with_context.token = newAccessToken;
2166
+ }
2167
+ return originalRequest.data;
2168
+ };
2169
+
2170
+ // src/utils/storage/local-storage.ts
2171
+ var localStorageUtils = () => {
2172
+ const setToken = async (access_token) => {
2173
+ localStorage.setItem("accessToken", access_token);
2174
+ };
2175
+ const setRefreshToken = async (refresh_token) => {
2176
+ localStorage.setItem("refreshToken", refresh_token);
2177
+ };
2178
+ const getAccessToken = async () => {
2179
+ return localStorage.getItem("accessToken");
2180
+ };
2181
+ const getRefreshToken = async () => {
2182
+ return localStorage.getItem("refreshToken");
2183
+ };
2184
+ const clearToken = async () => {
2185
+ localStorage.removeItem("accessToken");
2186
+ localStorage.removeItem("refreshToken");
2187
+ };
2188
+ return {
2189
+ setToken,
2190
+ setRefreshToken,
2191
+ getAccessToken,
2192
+ getRefreshToken,
2193
+ clearToken
2194
+ };
2195
+ };
2196
+
2197
+ // src/utils/storage/session-storage.ts
2198
+ var sessionStorageUtils = () => {
2199
+ const getBrowserSession = async () => {
2200
+ return sessionStorage.getItem("browserSession");
2201
+ };
2202
+ return {
2203
+ getBrowserSession
2204
+ };
2205
+ };
2206
+
2207
+ // src/configs/axios-client.ts
2208
+ var axiosClient = {
2209
+ init(config) {
2210
+ const localStorage2 = config.localStorageUtils ?? localStorageUtils();
2211
+ const sessionStorage2 = config.sessionStorageUtils ?? sessionStorageUtils();
2212
+ const db = config.db;
2213
+ let isRefreshing = false;
2214
+ let failedQueue = [];
2215
+ const processQueue = (error, token = null) => {
2216
+ failedQueue?.forEach((prom) => {
2217
+ if (error) {
2218
+ prom.reject(error);
2219
+ } else {
2220
+ prom.resolve(token);
2221
+ }
2222
+ });
2223
+ failedQueue = [];
2224
+ };
2225
+ const instance = axios.create({
2226
+ adapter: axios.defaults.adapter,
2227
+ baseURL: config.baseUrl,
2228
+ timeout: 5e4,
2229
+ paramsSerializer: (params) => new URLSearchParams(params).toString()
2230
+ });
2231
+ instance.interceptors.request.use(
2232
+ async (config2) => {
2233
+ const useRefreshToken = config2.useRefreshToken;
2234
+ const token = useRefreshToken ? await localStorage2.getRefreshToken() : await localStorage2.getAccessToken();
2235
+ if (token) {
2236
+ config2.headers["Authorization"] = "Bearer " + token;
2237
+ }
2238
+ return config2;
2239
+ },
2240
+ (error) => {
2241
+ Promise.reject(error);
2242
+ }
2243
+ );
2244
+ instance.interceptors.response.use(
2245
+ (response) => {
2246
+ return handleResponse(response);
2247
+ },
2248
+ async (error) => {
2249
+ const handleError3 = async (error2) => {
2250
+ if (!error2.response) {
2251
+ return error2;
2252
+ }
2253
+ const { data } = error2.response;
2254
+ if (data && data.code === 400 && ["invalid_grant"].includes(data.data?.error)) {
2255
+ await clearAuthToken();
2256
+ }
2257
+ return data;
2258
+ };
2259
+ const originalRequest = error.config;
2260
+ if ((error.response?.status === 403 || error.response?.status === 401 || error.response?.status === 404) && ["TOKEN_EXPIRED", "AUTHEN_FAIL", 401, "ERR_2FA_006"].includes(
2261
+ error.response.data.code
2262
+ )) {
2263
+ if (isRefreshing) {
2264
+ return new Promise(function(resolve, reject) {
2265
+ failedQueue.push({ resolve, reject });
2266
+ }).then((token) => {
2267
+ originalRequest.headers["Authorization"] = "Bearer " + token;
2268
+ originalRequest.data = updateTokenParamInOriginalRequest(
2269
+ originalRequest,
2270
+ token
2271
+ );
2272
+ return instance.request(originalRequest);
2273
+ }).catch(async (err) => {
2274
+ if ((err.response?.status === 400 || err.response?.status === 401) && ["invalid_grant"].includes(err.response.data.error)) {
2275
+ await clearAuthToken();
2276
+ }
2277
+ });
2278
+ }
2279
+ const browserSession = await sessionStorage2.getBrowserSession();
2280
+ const refreshToken = await localStorage2.getRefreshToken();
2281
+ const accessTokenExp = await localStorage2.getAccessToken();
2282
+ isRefreshing = true;
2283
+ if (!refreshToken && (!browserSession || browserSession == "unActive")) {
2284
+ await clearAuthToken();
2285
+ } else {
2286
+ const payload = Object.fromEntries(
2287
+ Object.entries({
2288
+ refresh_token: refreshToken,
2289
+ grant_type: "refresh_token",
2290
+ client_id: config.config.clientId,
2291
+ client_secret: config.config.clientSecret
2292
+ }).filter(([_, value]) => !!value)
2293
+ );
2294
+ return new Promise(function(resolve) {
2295
+ axios.post(
2296
+ `${config.baseUrl}${config.refreshTokenEndpoint ?? "/authentication/oauth2/token" /* AUTH_TOKEN_PATH */}`,
2297
+ payload,
2298
+ {
2299
+ headers: {
2300
+ "Content-Type": config.refreshTokenEndpoint ? "application/x-www-form-urlencoded" : "multipart/form-data",
2301
+ Authorization: `Bearer ${accessTokenExp}`
2302
+ }
2303
+ }
2304
+ ).then(async (res) => {
2305
+ const data = res.data;
2306
+ await localStorage2.setToken(data.access_token);
2307
+ await localStorage2.setRefreshToken(data.refresh_token);
2308
+ axios.defaults.headers.common["Authorization"] = "Bearer " + data.access_token;
2309
+ originalRequest.headers["Authorization"] = "Bearer " + data.access_token;
2310
+ originalRequest.data = updateTokenParamInOriginalRequest(
2311
+ originalRequest,
2312
+ data.access_token
2313
+ );
2314
+ processQueue(null, data.access_token);
2315
+ resolve(instance.request(originalRequest));
2316
+ }).catch(async (err) => {
2317
+ if (err && (err?.error_code === "AUTHEN_FAIL" || err?.error_code === "TOKEN_EXPIRED" || err?.error_code === "TOKEN_INCORRECT" || err?.code === "ERR_BAD_REQUEST") || err?.error_code === "ERR_2FA_006") {
2318
+ await clearAuthToken();
2319
+ }
2320
+ if (err && err.response) {
2321
+ const { error_code } = err.response?.data || {};
2322
+ if (error_code === "AUTHEN_FAIL") {
2323
+ await clearAuthToken();
2324
+ }
2325
+ }
2326
+ processQueue(err, null);
2327
+ }).finally(() => {
2328
+ isRefreshing = false;
2329
+ });
2330
+ });
2331
+ }
2332
+ }
2333
+ return Promise.reject(await handleError3(error));
2334
+ }
2335
+ );
2336
+ const handleResponse = (res) => {
2337
+ if (res && res.data) {
2338
+ return res.data;
2339
+ }
2340
+ return res;
2341
+ };
2342
+ const handleError2 = (error) => {
2343
+ if (error.isAxiosError && error.code === "ECONNABORTED") {
2344
+ console.error("Request Timeout Error:", error);
2345
+ return "Request Timeout Error";
2346
+ } else if (error.isAxiosError && !error.response) {
2347
+ console.error("Network Error:", error);
2348
+ return "Network Error";
2349
+ } else {
2350
+ console.error("Other Error:", error?.response);
2351
+ const errorMessage = error?.response?.data?.message || "An error occurred";
2352
+ return { message: errorMessage, status: error?.response?.status };
2353
+ }
2354
+ };
2355
+ const clearAuthToken = async () => {
2356
+ await localStorage2.clearToken();
2357
+ if (typeof window !== "undefined") {
2358
+ window.location.href = `/login`;
2359
+ }
2360
+ };
2361
+ function formatUrl(url, db2) {
2362
+ return url + (db2 ? "?db=" + db2 : "");
2363
+ }
2364
+ const responseBody = (response) => response;
2365
+ const requests = {
2366
+ get: (url, headers) => instance.get(formatUrl(url, db), headers).then(responseBody),
2367
+ post: (url, body, headers) => instance.post(formatUrl(url, db), body, headers).then(responseBody),
2368
+ post_excel: (url, body, headers) => instance.post(formatUrl(url, db), body, {
2369
+ responseType: "arraybuffer",
2370
+ headers: {
2371
+ "Content-Type": typeof window !== "undefined" ? "application/json" : "application/javascript",
2372
+ Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
2373
+ }
2374
+ }).then(responseBody),
2375
+ put: (url, body, headers) => instance.put(formatUrl(url, db), body, headers).then(responseBody),
2376
+ patch: (url, body) => instance.patch(formatUrl(url, db), body).then(responseBody),
2377
+ delete: (url, body) => instance.delete(formatUrl(url, db), body).then(responseBody)
2378
+ };
2379
+ return requests;
2380
+ }
2381
+ };
2778
2382
 
2779
2383
  // src/environment/EnvStore.ts
2384
+ var EnvStore = class _EnvStore {
2385
+ static instance = null;
2386
+ state = {};
2387
+ localStorageUtils;
2388
+ sessionStorageUtils;
2389
+ constructor(localStorageUtils2, sessionStorageUtils2) {
2390
+ this.localStorageUtils = localStorageUtils2;
2391
+ this.sessionStorageUtils = sessionStorageUtils2;
2392
+ }
2393
+ static getInstance(localStorageUtils2, sessionStorageUtils2) {
2394
+ if (!_EnvStore.instance) {
2395
+ console.log("Creating new EnvStore instance");
2396
+ _EnvStore.instance = new _EnvStore(localStorageUtils2, sessionStorageUtils2);
2397
+ } else {
2398
+ console.log("Returning existing EnvStore instance");
2399
+ }
2400
+ return _EnvStore.instance;
2401
+ }
2402
+ setupEnv(envConfig) {
2403
+ this.state = {
2404
+ ...this.state,
2405
+ ...envConfig,
2406
+ localStorageUtils: this.localStorageUtils,
2407
+ sessionStorageUtils: this.sessionStorageUtils
2408
+ };
2409
+ console.log("Setting up env with config:", envConfig);
2410
+ this.state.requests = axiosClient.init(this.state);
2411
+ console.log("axiosClient.init result:", this.state.requests);
2412
+ }
2413
+ setUid(uid) {
2414
+ this.state.uid = uid;
2415
+ }
2416
+ setLang(lang) {
2417
+ this.state.lang = lang;
2418
+ }
2419
+ setAllowCompanies(allowCompanies) {
2420
+ this.state.allowCompanies = allowCompanies;
2421
+ }
2422
+ setCompanies(companies) {
2423
+ this.state.companies = companies;
2424
+ }
2425
+ setDefaultCompany(company) {
2426
+ this.state.defaultCompany = company;
2427
+ }
2428
+ setUserInfo(userInfo) {
2429
+ this.state.user = userInfo;
2430
+ }
2431
+ // Getters để truy cập trạng thái
2432
+ get baseUrl() {
2433
+ return this.state.baseUrl;
2434
+ }
2435
+ get requests() {
2436
+ return this.state.requests;
2437
+ }
2438
+ get context() {
2439
+ return this.state.context;
2440
+ }
2441
+ get defaultCompany() {
2442
+ return this.state.defaultCompany;
2443
+ }
2444
+ get config() {
2445
+ return this.state.config;
2446
+ }
2447
+ get companies() {
2448
+ return this.state.companies;
2449
+ }
2450
+ get user() {
2451
+ return this.state.user;
2452
+ }
2453
+ get db() {
2454
+ return this.state.db;
2455
+ }
2456
+ get refreshTokenEndpoint() {
2457
+ return this.state.refreshTokenEndpoint;
2458
+ }
2459
+ get uid() {
2460
+ return this.state.uid;
2461
+ }
2462
+ get lang() {
2463
+ return this.state.lang;
2464
+ }
2465
+ get allowCompanies() {
2466
+ return this.state.allowCompanies;
2467
+ }
2468
+ };
2780
2469
  function getEnv() {
2781
- console.log("getEnv", envStore.getState().env);
2782
- return envStore.getState().env;
2470
+ const instance = EnvStore.getInstance();
2471
+ if (!instance) {
2472
+ throw new Error("EnvStore has not been initialized \u2014 call initEnv() first");
2473
+ }
2474
+ return instance;
2783
2475
  }
2784
2476
 
2785
2477
  // src/services/action-service/index.ts
@@ -2947,7 +2639,7 @@ var AuthService = {
2947
2639
  }).filter(([_, value]) => !!value)
2948
2640
  );
2949
2641
  const encodedData = new URLSearchParams(payload).toString();
2950
- return env?.requests?.post(body?.path ?? "", encodedData, {
2642
+ return env?.requests?.post(body.path, encodedData, {
2951
2643
  headers: {
2952
2644
  "Content-Type": "application/x-www-form-urlencoded"
2953
2645
  }
@@ -3044,20 +2736,6 @@ var AuthService = {
3044
2736
  }
3045
2737
  });
3046
2738
  },
3047
- async isValidActionToken(actionToken, path) {
3048
- const env = getEnv();
3049
- return env?.requests?.post(
3050
- path,
3051
- {},
3052
- {
3053
- headers: {
3054
- "Content-Type": "application/json"
3055
- },
3056
- useActionToken: true,
3057
- actionToken
3058
- }
3059
- );
3060
- },
3061
2739
  async loginSocial({
3062
2740
  db,
3063
2741
  state,
@@ -3822,7 +3500,7 @@ var model_service_default = ModelService;
3822
3500
  var UserService = {
3823
3501
  async getProfile(path) {
3824
3502
  const env = getEnv();
3825
- return env?.requests?.get(path ?? "/userinfo" /* PROFILE_PATH */, {
3503
+ return env.requests.get(path ?? "/userinfo" /* PROFILE_PATH */, {
3826
3504
  headers: {
3827
3505
  "Content-Type": "application/x-www-form-urlencoded"
3828
3506
  }
@@ -4141,7 +3819,8 @@ var ViewService = {
4141
3819
  },
4142
3820
  async getVersion() {
4143
3821
  const env = getEnv();
4144
- return env?.requests.get("", {
3822
+ console.log("env?.requests", env, env?.requests);
3823
+ return env?.requests?.get("", {
4145
3824
  headers: {
4146
3825
  "Content-Type": "application/json"
4147
3826
  }