@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.js CHANGED
@@ -72,634 +72,6 @@ var UriConstants = /* @__PURE__ */ ((UriConstants2) => {
72
72
  return UriConstants2;
73
73
  })(UriConstants || {});
74
74
 
75
- // src/store/index.ts
76
- var import_react_redux = require("react-redux");
77
-
78
- // src/store/reducers/breadcrums-slice/index.ts
79
- var import_toolkit = require("@reduxjs/toolkit");
80
- var initialState = {
81
- breadCrumbs: []
82
- };
83
- var breadcrumbsSlice = (0, import_toolkit.createSlice)({
84
- name: "breadcrumbs",
85
- initialState,
86
- reducers: {
87
- setBreadCrumbs: (state, action) => {
88
- state.breadCrumbs = [...state.breadCrumbs, action.payload];
89
- }
90
- }
91
- });
92
- var { setBreadCrumbs } = breadcrumbsSlice.actions;
93
- var breadcrums_slice_default = breadcrumbsSlice.reducer;
94
-
95
- // src/store/reducers/env-slice/index.ts
96
- var import_toolkit2 = require("@reduxjs/toolkit");
97
- var initialState2 = {
98
- baseUrl: "",
99
- companies: [],
100
- user: {},
101
- db: "",
102
- refreshTokenEndpoint: "",
103
- config: {
104
- grantType: "",
105
- clientId: "",
106
- clientSecret: "",
107
- redirectUri: ""
108
- },
109
- envFile: null,
110
- requests: {
111
- get: async (url, headers) => ({}),
112
- post: async (url, body, headers) => ({}),
113
- post_excel: async (url, body, headers) => ({}),
114
- put: async (url, body, headers) => ({}),
115
- patch: async (url, body) => ({}),
116
- delete: async (url, body) => ({})
117
- },
118
- defaultCompany: {
119
- id: null,
120
- logo: "",
121
- secondary_color: "",
122
- primary_color: ""
123
- },
124
- context: {
125
- uid: null,
126
- allowed_company_ids: [],
127
- lang: "vi_VN",
128
- tz: "Asia/Saigon"
129
- }
130
- };
131
- var envSlice = (0, import_toolkit2.createSlice)({
132
- name: "env",
133
- initialState: initialState2,
134
- reducers: {
135
- setEnv: (state, action) => {
136
- Object.assign(state, action.payload);
137
- },
138
- setUid: (state, action) => {
139
- state.context.uid = action.payload;
140
- },
141
- setAllowCompanies: (state, action) => {
142
- state.context.allowed_company_ids = action.payload;
143
- },
144
- setCompanies: (state, action) => {
145
- state.companies = action.payload;
146
- },
147
- setDefaultCompany: (state, action) => {
148
- state.defaultCompany = action.payload;
149
- },
150
- setLang: (state, action) => {
151
- state.context.lang = action.payload;
152
- },
153
- setUser: (state, action) => {
154
- state.user = action.payload;
155
- },
156
- setConfig: (state, action) => {
157
- state.config = action.payload;
158
- },
159
- setEnvFile: (state, action) => {
160
- state.envFile = action.payload;
161
- }
162
- }
163
- });
164
- var {
165
- setEnv,
166
- setUid,
167
- setLang,
168
- setAllowCompanies,
169
- setCompanies,
170
- setDefaultCompany,
171
- setUser,
172
- setConfig,
173
- setEnvFile
174
- } = envSlice.actions;
175
- var env_slice_default = envSlice.reducer;
176
-
177
- // src/store/reducers/excel-slice/index.ts
178
- var import_toolkit3 = require("@reduxjs/toolkit");
179
- var initialState3 = {
180
- dataParse: null,
181
- idFile: null,
182
- isFileLoaded: false,
183
- loadingImport: false,
184
- selectedFile: null,
185
- errorData: null
186
- };
187
- var excelSlice = (0, import_toolkit3.createSlice)({
188
- name: "excel",
189
- initialState: initialState3,
190
- reducers: {
191
- setDataParse: (state, action) => {
192
- state.dataParse = action.payload;
193
- },
194
- setIdFile: (state, action) => {
195
- state.idFile = action.payload;
196
- },
197
- setIsFileLoaded: (state, action) => {
198
- state.isFileLoaded = action.payload;
199
- },
200
- setLoadingImport: (state, action) => {
201
- state.loadingImport = action.payload;
202
- },
203
- setSelectedFile: (state, action) => {
204
- state.selectedFile = action.payload;
205
- },
206
- setErrorData: (state, action) => {
207
- state.errorData = action.payload;
208
- }
209
- }
210
- });
211
- var {
212
- setDataParse,
213
- setIdFile,
214
- setIsFileLoaded,
215
- setLoadingImport,
216
- setSelectedFile,
217
- setErrorData
218
- } = excelSlice.actions;
219
- var excel_slice_default = excelSlice.reducer;
220
-
221
- // src/store/reducers/form-slice/index.ts
222
- var import_toolkit4 = require("@reduxjs/toolkit");
223
- var initialState4 = {
224
- viewDataStore: {},
225
- isShowingModalDetail: false,
226
- isShowModalTranslate: false,
227
- formSubmitComponent: {},
228
- fieldTranslation: null,
229
- listSubject: {},
230
- dataUser: {}
231
- };
232
- var formSlice = (0, import_toolkit4.createSlice)({
233
- name: "form",
234
- initialState: initialState4,
235
- reducers: {
236
- setViewDataStore: (state, action) => {
237
- state.viewDataStore = action.payload;
238
- },
239
- setIsShowingModalDetail: (state, action) => {
240
- state.isShowingModalDetail = action.payload;
241
- },
242
- setIsShowModalTranslate: (state, action) => {
243
- state.isShowModalTranslate = action.payload;
244
- },
245
- setFormSubmitComponent: (state, action) => {
246
- state.formSubmitComponent[action.payload.key] = action.payload.component;
247
- },
248
- setFieldTranslate: (state, action) => {
249
- state.fieldTranslation = action.payload;
250
- },
251
- setListSubject: (state, action) => {
252
- state.listSubject = action.payload;
253
- },
254
- setDataUser: (state, action) => {
255
- state.dataUser = action.payload;
256
- }
257
- }
258
- });
259
- var {
260
- setViewDataStore,
261
- setIsShowingModalDetail,
262
- setIsShowModalTranslate,
263
- setFormSubmitComponent,
264
- setFieldTranslate,
265
- setListSubject,
266
- setDataUser
267
- } = formSlice.actions;
268
- var form_slice_default = formSlice.reducer;
269
-
270
- // src/store/reducers/header-slice/index.ts
271
- var import_toolkit5 = require("@reduxjs/toolkit");
272
- var headerSlice = (0, import_toolkit5.createSlice)({
273
- name: "header",
274
- initialState: {
275
- value: { allowedCompanyIds: [] }
276
- },
277
- reducers: {
278
- setHeader: (state, action) => {
279
- state.value = { ...state.value, ...action.payload };
280
- },
281
- setAllowedCompanyIds: (state, action) => {
282
- state.value.allowedCompanyIds = action.payload;
283
- }
284
- }
285
- });
286
- var { setAllowedCompanyIds, setHeader } = headerSlice.actions;
287
- var header_slice_default = headerSlice.reducer;
288
-
289
- // src/store/reducers/list-slice/index.ts
290
- var import_toolkit6 = require("@reduxjs/toolkit");
291
- var initialState5 = {
292
- pageLimit: 10,
293
- fields: {},
294
- order: "",
295
- selectedRowKeys: [],
296
- selectedRadioKey: 0,
297
- indexRowTableModal: -2,
298
- isUpdateTableModal: false,
299
- footerGroupTable: {},
300
- transferDetail: null,
301
- page: 0,
302
- domainTable: []
303
- };
304
- var listSlice = (0, import_toolkit6.createSlice)({
305
- name: "list",
306
- initialState: initialState5,
307
- reducers: {
308
- setPageLimit: (state, action) => {
309
- state.pageLimit = action.payload;
310
- },
311
- setFields: (state, action) => {
312
- state.fields = action.payload;
313
- },
314
- setOrder: (state, action) => {
315
- state.order = action.payload;
316
- },
317
- setSelectedRowKeys: (state, action) => {
318
- state.selectedRowKeys = action.payload;
319
- },
320
- setSelectedRadioKey: (state, action) => {
321
- state.selectedRadioKey = action.payload;
322
- },
323
- setIndexRowTableModal: (state, action) => {
324
- state.indexRowTableModal = action.payload;
325
- },
326
- setTransferDetail: (state, action) => {
327
- state.transferDetail = action.payload;
328
- },
329
- setIsUpdateTableModal: (state, action) => {
330
- state.isUpdateTableModal = action.payload;
331
- },
332
- setPage: (state, action) => {
333
- state.page = action.payload;
334
- },
335
- setDomainTable: (state, action) => {
336
- state.domainTable = action.payload;
337
- }
338
- }
339
- });
340
- var {
341
- setPageLimit,
342
- setFields,
343
- setOrder,
344
- setSelectedRowKeys,
345
- setIndexRowTableModal,
346
- setIsUpdateTableModal,
347
- setPage,
348
- setSelectedRadioKey,
349
- setTransferDetail,
350
- setDomainTable
351
- } = listSlice.actions;
352
- var list_slice_default = listSlice.reducer;
353
-
354
- // src/store/reducers/login-slice/index.ts
355
- var import_toolkit7 = require("@reduxjs/toolkit");
356
- var initialState6 = {
357
- db: "",
358
- redirectTo: "/",
359
- forgotPasswordUrl: "/"
360
- };
361
- var loginSlice = (0, import_toolkit7.createSlice)({
362
- name: "login",
363
- initialState: initialState6,
364
- reducers: {
365
- setDb: (state, action) => {
366
- state.db = action.payload;
367
- },
368
- setRedirectTo: (state, action) => {
369
- state.redirectTo = action.payload;
370
- },
371
- setForgotPasswordUrl: (state, action) => {
372
- state.forgotPasswordUrl = action.payload;
373
- }
374
- }
375
- });
376
- var { setDb, setRedirectTo, setForgotPasswordUrl } = loginSlice.actions;
377
- var login_slice_default = loginSlice.reducer;
378
-
379
- // src/store/reducers/navbar-slice/index.ts
380
- var import_toolkit8 = require("@reduxjs/toolkit");
381
- var initialState7 = {
382
- menuFocus: {},
383
- menuAction: {},
384
- navbarWidth: 250,
385
- menuList: []
386
- };
387
- var navbarSlice = (0, import_toolkit8.createSlice)({
388
- name: "navbar",
389
- initialState: initialState7,
390
- reducers: {
391
- setMenuFocus: (state, action) => {
392
- state.menuFocus = action.payload;
393
- },
394
- setMenuFocusAction: (state, action) => {
395
- state.menuAction = action.payload;
396
- },
397
- setNavbarWidth: (state, action) => {
398
- state.navbarWidth = action.payload;
399
- },
400
- setMenuList: (state, action) => {
401
- state.menuList = action.payload;
402
- }
403
- }
404
- });
405
- var { setMenuFocus, setMenuFocusAction, setNavbarWidth, setMenuList } = navbarSlice.actions;
406
- var navbar_slice_default = navbarSlice.reducer;
407
-
408
- // src/store/reducers/profile-slice/index.ts
409
- var import_toolkit9 = require("@reduxjs/toolkit");
410
- var initialState8 = {
411
- profile: {}
412
- };
413
- var profileSlice = (0, import_toolkit9.createSlice)({
414
- name: "profile",
415
- initialState: initialState8,
416
- reducers: {
417
- setProfile: (state, action) => {
418
- state.profile = action.payload;
419
- }
420
- }
421
- });
422
- var { setProfile } = profileSlice.actions;
423
- var profile_slice_default = profileSlice.reducer;
424
-
425
- // src/store/reducers/search-slice/index.ts
426
- var import_toolkit10 = require("@reduxjs/toolkit");
427
- var initialState9 = {
428
- groupByDomain: null,
429
- searchBy: [],
430
- searchString: "",
431
- hoveredIndexSearchList: null,
432
- selectedTags: [],
433
- firstDomain: null,
434
- searchMap: {},
435
- filterBy: [],
436
- groupBy: []
437
- };
438
- var searchSlice = (0, import_toolkit10.createSlice)({
439
- name: "search",
440
- initialState: initialState9,
441
- reducers: {
442
- setGroupByDomain: (state, action) => {
443
- state.groupByDomain = action.payload;
444
- },
445
- setSearchBy: (state, action) => {
446
- state.searchBy = action.payload;
447
- },
448
- setSearchString: (state, action) => {
449
- state.searchString = action.payload;
450
- },
451
- setHoveredIndexSearchList: (state, action) => {
452
- state.hoveredIndexSearchList = action.payload;
453
- },
454
- setSelectedTags: (state, action) => {
455
- state.selectedTags = action.payload;
456
- },
457
- setFirstDomain: (state, action) => {
458
- state.firstDomain = action.payload;
459
- },
460
- setFilterBy: (state, action) => {
461
- state.filterBy = action.payload;
462
- },
463
- setGroupBy: (state, action) => {
464
- state.groupBy = action.payload;
465
- },
466
- setSearchMap: (state, action) => {
467
- state.searchMap = action.payload;
468
- },
469
- updateSearchMap: (state, action) => {
470
- if (!state.searchMap[action.payload.key]) {
471
- state.searchMap[action.payload.key] = [];
472
- }
473
- state.searchMap[action.payload.key].push(action.payload.value);
474
- },
475
- removeKeyFromSearchMap: (state, action) => {
476
- const { key, item } = action.payload;
477
- const values = state.searchMap[key];
478
- if (!values) return;
479
- if (item) {
480
- const filtered = values.filter((value) => value.name !== item.name);
481
- if (filtered.length > 0) {
482
- state.searchMap[key] = filtered;
483
- } else {
484
- delete state.searchMap[key];
485
- }
486
- } else {
487
- delete state.searchMap[key];
488
- }
489
- },
490
- clearSearchMap: (state) => {
491
- state.searchMap = {};
492
- }
493
- }
494
- });
495
- var {
496
- setGroupByDomain,
497
- setSelectedTags,
498
- setSearchString,
499
- setHoveredIndexSearchList,
500
- setFirstDomain,
501
- setSearchBy,
502
- setFilterBy,
503
- setSearchMap,
504
- updateSearchMap,
505
- removeKeyFromSearchMap,
506
- setGroupBy,
507
- clearSearchMap
508
- } = searchSlice.actions;
509
- var search_slice_default = searchSlice.reducer;
510
-
511
- // src/store/store.ts
512
- var import_toolkit11 = require("@reduxjs/toolkit");
513
-
514
- // node_modules/redux/dist/redux.mjs
515
- function formatProdErrorMessage(code) {
516
- 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. `;
517
- }
518
- var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
519
- var ActionTypes = {
520
- INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
521
- REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
522
- PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
523
- };
524
- var actionTypes_default = ActionTypes;
525
- function isPlainObject(obj) {
526
- if (typeof obj !== "object" || obj === null)
527
- return false;
528
- let proto = obj;
529
- while (Object.getPrototypeOf(proto) !== null) {
530
- proto = Object.getPrototypeOf(proto);
531
- }
532
- return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
533
- }
534
- function miniKindOf(val) {
535
- if (val === void 0)
536
- return "undefined";
537
- if (val === null)
538
- return "null";
539
- const type = typeof val;
540
- switch (type) {
541
- case "boolean":
542
- case "string":
543
- case "number":
544
- case "symbol":
545
- case "function": {
546
- return type;
547
- }
548
- }
549
- if (Array.isArray(val))
550
- return "array";
551
- if (isDate(val))
552
- return "date";
553
- if (isError(val))
554
- return "error";
555
- const constructorName = ctorName(val);
556
- switch (constructorName) {
557
- case "Symbol":
558
- case "Promise":
559
- case "WeakMap":
560
- case "WeakSet":
561
- case "Map":
562
- case "Set":
563
- return constructorName;
564
- }
565
- return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
566
- }
567
- function ctorName(val) {
568
- return typeof val.constructor === "function" ? val.constructor.name : null;
569
- }
570
- function isError(val) {
571
- return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
572
- }
573
- function isDate(val) {
574
- if (val instanceof Date)
575
- return true;
576
- return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
577
- }
578
- function kindOf(val) {
579
- let typeOfVal = typeof val;
580
- if (process.env.NODE_ENV !== "production") {
581
- typeOfVal = miniKindOf(val);
582
- }
583
- return typeOfVal;
584
- }
585
- function warning(message) {
586
- if (typeof console !== "undefined" && typeof console.error === "function") {
587
- console.error(message);
588
- }
589
- try {
590
- throw new Error(message);
591
- } catch (e) {
592
- }
593
- }
594
- function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
595
- const reducerKeys = Object.keys(reducers);
596
- const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
597
- if (reducerKeys.length === 0) {
598
- return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
599
- }
600
- if (!isPlainObject(inputState)) {
601
- return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
602
- }
603
- const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
604
- unexpectedKeys.forEach((key) => {
605
- unexpectedKeyCache[key] = true;
606
- });
607
- if (action && action.type === actionTypes_default.REPLACE)
608
- return;
609
- if (unexpectedKeys.length > 0) {
610
- 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.`;
611
- }
612
- }
613
- function assertReducerShape(reducers) {
614
- Object.keys(reducers).forEach((key) => {
615
- const reducer = reducers[key];
616
- const initialState10 = reducer(void 0, {
617
- type: actionTypes_default.INIT
618
- });
619
- if (typeof initialState10 === "undefined") {
620
- 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.`);
621
- }
622
- if (typeof reducer(void 0, {
623
- type: actionTypes_default.PROBE_UNKNOWN_ACTION()
624
- }) === "undefined") {
625
- 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.`);
626
- }
627
- });
628
- }
629
- function combineReducers(reducers) {
630
- const reducerKeys = Object.keys(reducers);
631
- const finalReducers = {};
632
- for (let i = 0; i < reducerKeys.length; i++) {
633
- const key = reducerKeys[i];
634
- if (process.env.NODE_ENV !== "production") {
635
- if (typeof reducers[key] === "undefined") {
636
- warning(`No reducer provided for key "${key}"`);
637
- }
638
- }
639
- if (typeof reducers[key] === "function") {
640
- finalReducers[key] = reducers[key];
641
- }
642
- }
643
- const finalReducerKeys = Object.keys(finalReducers);
644
- let unexpectedKeyCache;
645
- if (process.env.NODE_ENV !== "production") {
646
- unexpectedKeyCache = {};
647
- }
648
- let shapeAssertionError;
649
- try {
650
- assertReducerShape(finalReducers);
651
- } catch (e) {
652
- shapeAssertionError = e;
653
- }
654
- return function combination(state = {}, action) {
655
- if (shapeAssertionError) {
656
- throw shapeAssertionError;
657
- }
658
- if (process.env.NODE_ENV !== "production") {
659
- const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
660
- if (warningMessage) {
661
- warning(warningMessage);
662
- }
663
- }
664
- let hasChanged = false;
665
- const nextState = {};
666
- for (let i = 0; i < finalReducerKeys.length; i++) {
667
- const key = finalReducerKeys[i];
668
- const reducer = finalReducers[key];
669
- const previousStateForKey = state[key];
670
- const nextStateForKey = reducer(previousStateForKey, action);
671
- if (typeof nextStateForKey === "undefined") {
672
- const actionType = action && action.type;
673
- 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.`);
674
- }
675
- nextState[key] = nextStateForKey;
676
- hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
677
- }
678
- hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
679
- return hasChanged ? nextState : state;
680
- };
681
- }
682
-
683
- // src/store/store.ts
684
- var rootReducer = combineReducers({
685
- env: env_slice_default,
686
- header: header_slice_default,
687
- navbar: navbar_slice_default,
688
- list: list_slice_default,
689
- search: search_slice_default,
690
- form: form_slice_default,
691
- breadcrumbs: breadcrums_slice_default,
692
- login: login_slice_default,
693
- excel: excel_slice_default,
694
- profile: profile_slice_default
695
- });
696
- var envStore = (0, import_toolkit11.configureStore)({
697
- reducer: rootReducer,
698
- middleware: (getDefaultMiddleware) => getDefaultMiddleware({
699
- serializableCheck: false
700
- })
701
- });
702
-
703
75
  // src/configs/axios-client.ts
704
76
  var import_axios = __toESM(require("axios"));
705
77
 
@@ -2819,11 +2191,331 @@ var toQueryString = (params) => {
2819
2191
  (key) => encodeURIComponent(key) + "=" + encodeURIComponent(params[key].toString())
2820
2192
  ).join("&");
2821
2193
  };
2194
+ var updateTokenParamInOriginalRequest = (originalRequest, newAccessToken) => {
2195
+ if (!originalRequest.data) return originalRequest.data;
2196
+ if (typeof originalRequest.data === "string") {
2197
+ try {
2198
+ const parsedData = JSON.parse(originalRequest.data);
2199
+ if (parsedData.with_context && typeof parsedData.with_context === "object") {
2200
+ parsedData.with_context.token = newAccessToken;
2201
+ }
2202
+ return JSON.stringify(parsedData);
2203
+ } catch (e) {
2204
+ console.warn("Failed to parse originalRequest.data", e);
2205
+ return originalRequest.data;
2206
+ }
2207
+ }
2208
+ if (typeof originalRequest.data === "object" && originalRequest.data.with_context) {
2209
+ originalRequest.data.with_context.token = newAccessToken;
2210
+ }
2211
+ return originalRequest.data;
2212
+ };
2213
+
2214
+ // src/utils/storage/local-storage.ts
2215
+ var localStorageUtils = () => {
2216
+ const setToken = async (access_token) => {
2217
+ localStorage.setItem("accessToken", access_token);
2218
+ };
2219
+ const setRefreshToken = async (refresh_token) => {
2220
+ localStorage.setItem("refreshToken", refresh_token);
2221
+ };
2222
+ const getAccessToken = async () => {
2223
+ return localStorage.getItem("accessToken");
2224
+ };
2225
+ const getRefreshToken = async () => {
2226
+ return localStorage.getItem("refreshToken");
2227
+ };
2228
+ const clearToken = async () => {
2229
+ localStorage.removeItem("accessToken");
2230
+ localStorage.removeItem("refreshToken");
2231
+ };
2232
+ return {
2233
+ setToken,
2234
+ setRefreshToken,
2235
+ getAccessToken,
2236
+ getRefreshToken,
2237
+ clearToken
2238
+ };
2239
+ };
2240
+
2241
+ // src/utils/storage/session-storage.ts
2242
+ var sessionStorageUtils = () => {
2243
+ const getBrowserSession = async () => {
2244
+ return sessionStorage.getItem("browserSession");
2245
+ };
2246
+ return {
2247
+ getBrowserSession
2248
+ };
2249
+ };
2250
+
2251
+ // src/configs/axios-client.ts
2252
+ var axiosClient = {
2253
+ init(config) {
2254
+ const localStorage2 = config.localStorageUtils ?? localStorageUtils();
2255
+ const sessionStorage2 = config.sessionStorageUtils ?? sessionStorageUtils();
2256
+ const db = config.db;
2257
+ let isRefreshing = false;
2258
+ let failedQueue = [];
2259
+ const processQueue = (error, token = null) => {
2260
+ failedQueue?.forEach((prom) => {
2261
+ if (error) {
2262
+ prom.reject(error);
2263
+ } else {
2264
+ prom.resolve(token);
2265
+ }
2266
+ });
2267
+ failedQueue = [];
2268
+ };
2269
+ const instance = import_axios.default.create({
2270
+ adapter: import_axios.default.defaults.adapter,
2271
+ baseURL: config.baseUrl,
2272
+ timeout: 5e4,
2273
+ paramsSerializer: (params) => new URLSearchParams(params).toString()
2274
+ });
2275
+ instance.interceptors.request.use(
2276
+ async (config2) => {
2277
+ const useRefreshToken = config2.useRefreshToken;
2278
+ const token = useRefreshToken ? await localStorage2.getRefreshToken() : await localStorage2.getAccessToken();
2279
+ if (token) {
2280
+ config2.headers["Authorization"] = "Bearer " + token;
2281
+ }
2282
+ return config2;
2283
+ },
2284
+ (error) => {
2285
+ Promise.reject(error);
2286
+ }
2287
+ );
2288
+ instance.interceptors.response.use(
2289
+ (response) => {
2290
+ return handleResponse(response);
2291
+ },
2292
+ async (error) => {
2293
+ const handleError3 = async (error2) => {
2294
+ if (!error2.response) {
2295
+ return error2;
2296
+ }
2297
+ const { data } = error2.response;
2298
+ if (data && data.code === 400 && ["invalid_grant"].includes(data.data?.error)) {
2299
+ await clearAuthToken();
2300
+ }
2301
+ return data;
2302
+ };
2303
+ const originalRequest = error.config;
2304
+ if ((error.response?.status === 403 || error.response?.status === 401 || error.response?.status === 404) && ["TOKEN_EXPIRED", "AUTHEN_FAIL", 401, "ERR_2FA_006"].includes(
2305
+ error.response.data.code
2306
+ )) {
2307
+ if (isRefreshing) {
2308
+ return new Promise(function(resolve, reject) {
2309
+ failedQueue.push({ resolve, reject });
2310
+ }).then((token) => {
2311
+ originalRequest.headers["Authorization"] = "Bearer " + token;
2312
+ originalRequest.data = updateTokenParamInOriginalRequest(
2313
+ originalRequest,
2314
+ token
2315
+ );
2316
+ return instance.request(originalRequest);
2317
+ }).catch(async (err) => {
2318
+ if ((err.response?.status === 400 || err.response?.status === 401) && ["invalid_grant"].includes(err.response.data.error)) {
2319
+ await clearAuthToken();
2320
+ }
2321
+ });
2322
+ }
2323
+ const browserSession = await sessionStorage2.getBrowserSession();
2324
+ const refreshToken = await localStorage2.getRefreshToken();
2325
+ const accessTokenExp = await localStorage2.getAccessToken();
2326
+ isRefreshing = true;
2327
+ if (!refreshToken && (!browserSession || browserSession == "unActive")) {
2328
+ await clearAuthToken();
2329
+ } else {
2330
+ const payload = Object.fromEntries(
2331
+ Object.entries({
2332
+ refresh_token: refreshToken,
2333
+ grant_type: "refresh_token",
2334
+ client_id: config.config.clientId,
2335
+ client_secret: config.config.clientSecret
2336
+ }).filter(([_, value]) => !!value)
2337
+ );
2338
+ return new Promise(function(resolve) {
2339
+ import_axios.default.post(
2340
+ `${config.baseUrl}${config.refreshTokenEndpoint ?? "/authentication/oauth2/token" /* AUTH_TOKEN_PATH */}`,
2341
+ payload,
2342
+ {
2343
+ headers: {
2344
+ "Content-Type": config.refreshTokenEndpoint ? "application/x-www-form-urlencoded" : "multipart/form-data",
2345
+ Authorization: `Bearer ${accessTokenExp}`
2346
+ }
2347
+ }
2348
+ ).then(async (res) => {
2349
+ const data = res.data;
2350
+ await localStorage2.setToken(data.access_token);
2351
+ await localStorage2.setRefreshToken(data.refresh_token);
2352
+ import_axios.default.defaults.headers.common["Authorization"] = "Bearer " + data.access_token;
2353
+ originalRequest.headers["Authorization"] = "Bearer " + data.access_token;
2354
+ originalRequest.data = updateTokenParamInOriginalRequest(
2355
+ originalRequest,
2356
+ data.access_token
2357
+ );
2358
+ processQueue(null, data.access_token);
2359
+ resolve(instance.request(originalRequest));
2360
+ }).catch(async (err) => {
2361
+ 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") {
2362
+ await clearAuthToken();
2363
+ }
2364
+ if (err && err.response) {
2365
+ const { error_code } = err.response?.data || {};
2366
+ if (error_code === "AUTHEN_FAIL") {
2367
+ await clearAuthToken();
2368
+ }
2369
+ }
2370
+ processQueue(err, null);
2371
+ }).finally(() => {
2372
+ isRefreshing = false;
2373
+ });
2374
+ });
2375
+ }
2376
+ }
2377
+ return Promise.reject(await handleError3(error));
2378
+ }
2379
+ );
2380
+ const handleResponse = (res) => {
2381
+ if (res && res.data) {
2382
+ return res.data;
2383
+ }
2384
+ return res;
2385
+ };
2386
+ const handleError2 = (error) => {
2387
+ if (error.isAxiosError && error.code === "ECONNABORTED") {
2388
+ console.error("Request Timeout Error:", error);
2389
+ return "Request Timeout Error";
2390
+ } else if (error.isAxiosError && !error.response) {
2391
+ console.error("Network Error:", error);
2392
+ return "Network Error";
2393
+ } else {
2394
+ console.error("Other Error:", error?.response);
2395
+ const errorMessage = error?.response?.data?.message || "An error occurred";
2396
+ return { message: errorMessage, status: error?.response?.status };
2397
+ }
2398
+ };
2399
+ const clearAuthToken = async () => {
2400
+ await localStorage2.clearToken();
2401
+ if (typeof window !== "undefined") {
2402
+ window.location.href = `/login`;
2403
+ }
2404
+ };
2405
+ function formatUrl(url, db2) {
2406
+ return url + (db2 ? "?db=" + db2 : "");
2407
+ }
2408
+ const responseBody = (response) => response;
2409
+ const requests = {
2410
+ get: (url, headers) => instance.get(formatUrl(url, db), headers).then(responseBody),
2411
+ post: (url, body, headers) => instance.post(formatUrl(url, db), body, headers).then(responseBody),
2412
+ post_excel: (url, body, headers) => instance.post(formatUrl(url, db), body, {
2413
+ responseType: "arraybuffer",
2414
+ headers: {
2415
+ "Content-Type": typeof window !== "undefined" ? "application/json" : "application/javascript",
2416
+ Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
2417
+ }
2418
+ }).then(responseBody),
2419
+ put: (url, body, headers) => instance.put(formatUrl(url, db), body, headers).then(responseBody),
2420
+ patch: (url, body) => instance.patch(formatUrl(url, db), body).then(responseBody),
2421
+ delete: (url, body) => instance.delete(formatUrl(url, db), body).then(responseBody)
2422
+ };
2423
+ return requests;
2424
+ }
2425
+ };
2822
2426
 
2823
2427
  // src/environment/EnvStore.ts
2428
+ var EnvStore = class _EnvStore {
2429
+ static instance = null;
2430
+ state = {};
2431
+ localStorageUtils;
2432
+ sessionStorageUtils;
2433
+ constructor(localStorageUtils2, sessionStorageUtils2) {
2434
+ this.localStorageUtils = localStorageUtils2;
2435
+ this.sessionStorageUtils = sessionStorageUtils2;
2436
+ }
2437
+ static getInstance(localStorageUtils2, sessionStorageUtils2) {
2438
+ if (!_EnvStore.instance) {
2439
+ console.log("Creating new EnvStore instance");
2440
+ _EnvStore.instance = new _EnvStore(localStorageUtils2, sessionStorageUtils2);
2441
+ } else {
2442
+ console.log("Returning existing EnvStore instance");
2443
+ }
2444
+ return _EnvStore.instance;
2445
+ }
2446
+ setupEnv(envConfig) {
2447
+ this.state = {
2448
+ ...this.state,
2449
+ ...envConfig,
2450
+ localStorageUtils: this.localStorageUtils,
2451
+ sessionStorageUtils: this.sessionStorageUtils
2452
+ };
2453
+ console.log("Setting up env with config:", envConfig);
2454
+ this.state.requests = axiosClient.init(this.state);
2455
+ console.log("axiosClient.init result:", this.state.requests);
2456
+ }
2457
+ setUid(uid) {
2458
+ this.state.uid = uid;
2459
+ }
2460
+ setLang(lang) {
2461
+ this.state.lang = lang;
2462
+ }
2463
+ setAllowCompanies(allowCompanies) {
2464
+ this.state.allowCompanies = allowCompanies;
2465
+ }
2466
+ setCompanies(companies) {
2467
+ this.state.companies = companies;
2468
+ }
2469
+ setDefaultCompany(company) {
2470
+ this.state.defaultCompany = company;
2471
+ }
2472
+ setUserInfo(userInfo) {
2473
+ this.state.user = userInfo;
2474
+ }
2475
+ // Getters để truy cập trạng thái
2476
+ get baseUrl() {
2477
+ return this.state.baseUrl;
2478
+ }
2479
+ get requests() {
2480
+ return this.state.requests;
2481
+ }
2482
+ get context() {
2483
+ return this.state.context;
2484
+ }
2485
+ get defaultCompany() {
2486
+ return this.state.defaultCompany;
2487
+ }
2488
+ get config() {
2489
+ return this.state.config;
2490
+ }
2491
+ get companies() {
2492
+ return this.state.companies;
2493
+ }
2494
+ get user() {
2495
+ return this.state.user;
2496
+ }
2497
+ get db() {
2498
+ return this.state.db;
2499
+ }
2500
+ get refreshTokenEndpoint() {
2501
+ return this.state.refreshTokenEndpoint;
2502
+ }
2503
+ get uid() {
2504
+ return this.state.uid;
2505
+ }
2506
+ get lang() {
2507
+ return this.state.lang;
2508
+ }
2509
+ get allowCompanies() {
2510
+ return this.state.allowCompanies;
2511
+ }
2512
+ };
2824
2513
  function getEnv() {
2825
- console.log("getEnv", envStore.getState().env);
2826
- return envStore.getState().env;
2514
+ const instance = EnvStore.getInstance();
2515
+ if (!instance) {
2516
+ throw new Error("EnvStore has not been initialized \u2014 call initEnv() first");
2517
+ }
2518
+ return instance;
2827
2519
  }
2828
2520
 
2829
2521
  // src/services/action-service/index.ts
@@ -2991,7 +2683,7 @@ var AuthService = {
2991
2683
  }).filter(([_, value]) => !!value)
2992
2684
  );
2993
2685
  const encodedData = new URLSearchParams(payload).toString();
2994
- return env?.requests?.post(body?.path ?? "", encodedData, {
2686
+ return env?.requests?.post(body.path, encodedData, {
2995
2687
  headers: {
2996
2688
  "Content-Type": "application/x-www-form-urlencoded"
2997
2689
  }
@@ -3088,20 +2780,6 @@ var AuthService = {
3088
2780
  }
3089
2781
  });
3090
2782
  },
3091
- async isValidActionToken(actionToken, path) {
3092
- const env = getEnv();
3093
- return env?.requests?.post(
3094
- path,
3095
- {},
3096
- {
3097
- headers: {
3098
- "Content-Type": "application/json"
3099
- },
3100
- useActionToken: true,
3101
- actionToken
3102
- }
3103
- );
3104
- },
3105
2783
  async loginSocial({
3106
2784
  db,
3107
2785
  state,
@@ -3866,7 +3544,7 @@ var model_service_default = ModelService;
3866
3544
  var UserService = {
3867
3545
  async getProfile(path) {
3868
3546
  const env = getEnv();
3869
- return env?.requests?.get(path ?? "/userinfo" /* PROFILE_PATH */, {
3547
+ return env.requests.get(path ?? "/userinfo" /* PROFILE_PATH */, {
3870
3548
  headers: {
3871
3549
  "Content-Type": "application/x-www-form-urlencoded"
3872
3550
  }
@@ -4185,7 +3863,8 @@ var ViewService = {
4185
3863
  },
4186
3864
  async getVersion() {
4187
3865
  const env = getEnv();
4188
- return env?.requests.get("", {
3866
+ console.log("env?.requests", env, env?.requests);
3867
+ return env?.requests?.get("", {
4189
3868
  headers: {
4190
3869
  "Content-Type": "application/json"
4191
3870
  }