@fctc/edu-logic-lib 1.0.3 → 1.0.4

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 (55) hide show
  1. package/dist/index.d.mts +1076 -23
  2. package/dist/index.d.ts +1076 -23
  3. package/dist/index.js +4 -618
  4. package/dist/index.mjs +3 -572
  5. package/package.json +1 -1
  6. package/dist/base-model-type-DvO53Lwi.d.mts +0 -7
  7. package/dist/base-model-type-DvO53Lwi.d.ts +0 -7
  8. package/dist/config.d.mts +0 -15
  9. package/dist/config.d.ts +0 -15
  10. package/dist/config.js +0 -262
  11. package/dist/config.mjs +0 -256
  12. package/dist/constants.d.mts +0 -120
  13. package/dist/constants.d.ts +0 -120
  14. package/dist/constants.js +0 -154
  15. package/dist/constants.mjs +0 -141
  16. package/dist/context-type-D5XefoL-.d.mts +0 -8
  17. package/dist/context-type-D5XefoL-.d.ts +0 -8
  18. package/dist/environment.d.mts +0 -37
  19. package/dist/environment.d.ts +0 -37
  20. package/dist/environment.js +0 -849
  21. package/dist/environment.mjs +0 -841
  22. package/dist/hooks.d.mts +0 -218
  23. package/dist/hooks.d.ts +0 -218
  24. package/dist/hooks.js +0 -4865
  25. package/dist/hooks.mjs +0 -4814
  26. package/dist/index-C_nK1Mii.d.mts +0 -19
  27. package/dist/index-C_nK1Mii.d.ts +0 -19
  28. package/dist/models.d.mts +0 -35
  29. package/dist/models.d.ts +0 -35
  30. package/dist/models.js +0 -3225
  31. package/dist/models.mjs +0 -3217
  32. package/dist/provider.d.mts +0 -16
  33. package/dist/provider.d.ts +0 -16
  34. package/dist/provider.js +0 -3232
  35. package/dist/provider.mjs +0 -3224
  36. package/dist/services.d.mts +0 -160
  37. package/dist/services.d.ts +0 -160
  38. package/dist/services.js +0 -4045
  39. package/dist/services.mjs +0 -4032
  40. package/dist/store.d.mts +0 -505
  41. package/dist/store.d.ts +0 -505
  42. package/dist/store.js +0 -582
  43. package/dist/store.mjs +0 -519
  44. package/dist/types.d.mts +0 -12
  45. package/dist/types.d.ts +0 -12
  46. package/dist/types.js +0 -2
  47. package/dist/types.mjs +0 -1
  48. package/dist/use-get-selection-DFh6sc49.d.mts +0 -26
  49. package/dist/use-get-selection-DFh6sc49.d.ts +0 -26
  50. package/dist/utils.d.mts +0 -52
  51. package/dist/utils.d.ts +0 -52
  52. package/dist/utils.js +0 -2360
  53. package/dist/utils.mjs +0 -2344
  54. package/dist/view-type-BTzRpkT7.d.mts +0 -106
  55. package/dist/view-type-BTzRpkT7.d.ts +0 -106
package/dist/services.mjs DELETED
@@ -1,4032 +0,0 @@
1
- import 'react-redux';
2
- import { createSlice, configureStore } from '@reduxjs/toolkit';
3
- import axios from 'axios';
4
-
5
- // src/constants/api/uri-constant.ts
6
- var UriConstants = /* @__PURE__ */ ((UriConstants2) => {
7
- UriConstants2["AUTH_TOKEN_PATH"] = "/authentication/oauth2/token";
8
- UriConstants2["GENTOKEN_SOCIAL"] = "/token/generate";
9
- UriConstants2["CALL_PATH"] = "/call";
10
- UriConstants2["COMPANY_PATH"] = "/company";
11
- UriConstants2["PROFILE_PATH"] = "/userinfo";
12
- UriConstants2["RESET_PASSWORD_PATH"] = "/reset_password";
13
- UriConstants2["CHANGE_PASSWORD_PATH"] = "/change_password";
14
- UriConstants2["UPDATE_PASSWORD_PATH"] = "/change_password_parent";
15
- UriConstants2["LOAD_ACTION"] = `/load_action`;
16
- UriConstants2["REPORT_PATH"] = `/report`;
17
- UriConstants2["RUN_ACTION_PATH"] = `/run_action`;
18
- UriConstants2["UPLOAD_FILE_PATH"] = `/upload/file`;
19
- UriConstants2["GET_MESSAGE"] = `/chatter/thread/messages`;
20
- UriConstants2["SENT_MESSAGE"] = `/chatter/message/post`;
21
- UriConstants2["UPLOAD_IMAGE"] = `/mail/attachment/upload`;
22
- UriConstants2["DELETE_MESSAGE"] = `/chatter/message/update_content`;
23
- UriConstants2["IMAGE_PATH"] = `/web/image`;
24
- UriConstants2["LOAD_MESSAGE"] = `/load_message_failures`;
25
- UriConstants2["TOKEN"] = `/check_token`;
26
- UriConstants2["CREATE_UPDATE_PATH"] = `/create_update`;
27
- UriConstants2["TWOFA_METHOD_PATH"] = `/id/api/v2/call`;
28
- UriConstants2["SIGNIN_SSO"] = `/signin-sso/oauth`;
29
- return UriConstants2;
30
- })(UriConstants || {});
31
- var initialState = {
32
- baseUrl: "",
33
- requests: null,
34
- companies: [],
35
- user: {},
36
- envFile: null,
37
- defaultCompany: {
38
- id: null,
39
- logo: "",
40
- secondary_color: "",
41
- primary_color: ""
42
- },
43
- context: {
44
- uid: null,
45
- allowed_company_ids: [],
46
- lang: "vi_VN",
47
- tz: "Asia/Saigon"
48
- }
49
- };
50
- var envSlice = createSlice({
51
- name: "env",
52
- initialState,
53
- reducers: {
54
- setEnv: (state, action) => {
55
- Object.assign(state, action.payload);
56
- },
57
- setUid: (state, action) => {
58
- state.context.uid = action.payload;
59
- },
60
- setAllowCompanies: (state, action) => {
61
- state.context.allowed_company_ids = action.payload;
62
- },
63
- setCompanies: (state, action) => {
64
- state.companies = action.payload;
65
- },
66
- setDefaultCompany: (state, action) => {
67
- state.defaultCompany = action.payload;
68
- },
69
- setLang: (state, action) => {
70
- state.context.lang = action.payload;
71
- },
72
- setUser: (state, action) => {
73
- state.user = action.payload;
74
- },
75
- setEnvFile: (state, action) => {
76
- state.envFile = action.payload;
77
- }
78
- }
79
- });
80
- var {
81
- setEnv,
82
- setUid,
83
- setLang,
84
- setAllowCompanies,
85
- setCompanies,
86
- setDefaultCompany,
87
- setUser,
88
- setEnvFile
89
- } = envSlice.actions;
90
- var env_slice_default = envSlice.reducer;
91
- var initialState2 = {
92
- dataParse: null,
93
- idFile: null,
94
- isFileLoaded: false,
95
- loadingImport: false,
96
- selectedFile: null,
97
- errorData: null
98
- };
99
- var excelSlice = createSlice({
100
- name: "excel",
101
- initialState: initialState2,
102
- reducers: {
103
- setDataParse: (state, action) => {
104
- state.dataParse = action.payload;
105
- },
106
- setIdFile: (state, action) => {
107
- state.idFile = action.payload;
108
- },
109
- setIsFileLoaded: (state, action) => {
110
- state.isFileLoaded = action.payload;
111
- },
112
- setLoadingImport: (state, action) => {
113
- state.loadingImport = action.payload;
114
- },
115
- setSelectedFile: (state, action) => {
116
- state.selectedFile = action.payload;
117
- },
118
- setErrorData: (state, action) => {
119
- state.errorData = action.payload;
120
- }
121
- }
122
- });
123
- var {
124
- setDataParse,
125
- setIdFile,
126
- setIsFileLoaded,
127
- setLoadingImport,
128
- setSelectedFile,
129
- setErrorData
130
- } = excelSlice.actions;
131
- var excel_slice_default = excelSlice.reducer;
132
- var initialState3 = {
133
- viewDataStore: {},
134
- isShowingModalDetail: false,
135
- isShowModalTranslate: false,
136
- formSubmitComponent: {},
137
- fieldTranslation: null,
138
- listSubject: {},
139
- dataUser: {}
140
- };
141
- var formSlice = createSlice({
142
- name: "form",
143
- initialState: initialState3,
144
- reducers: {
145
- setViewDataStore: (state, action) => {
146
- state.viewDataStore = action.payload;
147
- },
148
- setIsShowingModalDetail: (state, action) => {
149
- state.isShowingModalDetail = action.payload;
150
- },
151
- setIsShowModalTranslate: (state, action) => {
152
- state.isShowModalTranslate = action.payload;
153
- },
154
- setFormSubmitComponent: (state, action) => {
155
- state.formSubmitComponent[action.payload.key] = action.payload.component;
156
- },
157
- setFieldTranslate: (state, action) => {
158
- state.fieldTranslation = action.payload;
159
- },
160
- setListSubject: (state, action) => {
161
- state.listSubject = action.payload;
162
- },
163
- setDataUser: (state, action) => {
164
- state.dataUser = action.payload;
165
- }
166
- }
167
- });
168
- var {
169
- setViewDataStore,
170
- setIsShowingModalDetail,
171
- setIsShowModalTranslate,
172
- setFormSubmitComponent,
173
- setFieldTranslate,
174
- setListSubject,
175
- setDataUser
176
- } = formSlice.actions;
177
- var form_slice_default = formSlice.reducer;
178
- var initialState4 = {
179
- pageLimit: 10,
180
- fields: {},
181
- order: "",
182
- selectedRowKeys: [],
183
- indexRowTableModal: -2,
184
- footerGroupTable: {},
185
- page: 0,
186
- domainTable: []
187
- };
188
- var listSlice = createSlice({
189
- name: "list",
190
- initialState: initialState4,
191
- reducers: {
192
- setPageLimit: (state, action) => {
193
- state.pageLimit = action.payload;
194
- },
195
- setFields: (state, action) => {
196
- state.fields = action.payload;
197
- },
198
- setOrder: (state, action) => {
199
- state.order = action.payload;
200
- },
201
- setSelectedRowKeys: (state, action) => {
202
- state.selectedRowKeys = action.payload;
203
- },
204
- setIndexRowTableModal: (state, action) => {
205
- state.indexRowTableModal = action.payload;
206
- },
207
- setPage: (state, action) => {
208
- state.page = action.payload;
209
- },
210
- setDomainTable: (state, action) => {
211
- state.domainTable = action.payload;
212
- }
213
- }
214
- });
215
- var {
216
- setPageLimit,
217
- setFields,
218
- setOrder,
219
- setSelectedRowKeys,
220
- setIndexRowTableModal,
221
- setPage,
222
- setDomainTable
223
- } = listSlice.actions;
224
- var list_slice_default = listSlice.reducer;
225
- var initialState5 = {
226
- menuList: []
227
- };
228
- var navbarSlice = createSlice({
229
- name: "navbar",
230
- initialState: initialState5,
231
- reducers: {
232
- setMenuList: (state, action) => {
233
- state.menuList = action.payload;
234
- }
235
- }
236
- });
237
- var { setMenuList } = navbarSlice.actions;
238
- var navbar_slice_default = navbarSlice.reducer;
239
- var initialState6 = {
240
- profile: {}
241
- };
242
- var profileSlice = createSlice({
243
- name: "profile",
244
- initialState: initialState6,
245
- reducers: {
246
- setProfile: (state, action) => {
247
- state.profile = action.payload;
248
- }
249
- }
250
- });
251
- var { setProfile } = profileSlice.actions;
252
- var profile_slice_default = profileSlice.reducer;
253
- var initialState7 = {
254
- groupByDomain: null,
255
- tableHead: [],
256
- searchString: "",
257
- hoveredIndexSearchList: null,
258
- selectedTags: [],
259
- firstDomain: null,
260
- searchMap: {},
261
- typeFieldsSearch: "",
262
- modelSearch: "",
263
- filterBy: [],
264
- groupBy: []
265
- };
266
- var searchSlice = createSlice({
267
- name: "search",
268
- initialState: initialState7,
269
- reducers: {
270
- setGroupByDomain: (state, action) => {
271
- state.groupByDomain = action.payload;
272
- },
273
- setTableHead: (state, action) => {
274
- state.tableHead = action.payload;
275
- },
276
- setSearchString: (state, action) => {
277
- state.searchString = action.payload;
278
- },
279
- setHoveredIndexSearchList: (state, action) => {
280
- state.hoveredIndexSearchList = action.payload;
281
- },
282
- setSelectedTags: (state, action) => {
283
- state.selectedTags = action.payload;
284
- },
285
- setFirstDomain: (state, action) => {
286
- state.firstDomain = action.payload;
287
- },
288
- setTypeFieldsSearch: (state, action) => {
289
- state.typeFieldsSearch = action.payload;
290
- },
291
- setModelSearch: (state, action) => {
292
- state.modelSearch = action.payload;
293
- },
294
- setFilterBy: (state, action) => {
295
- state.filterBy = action.payload;
296
- },
297
- setGroupBy: (state, action) => {
298
- state.groupBy = action.payload;
299
- },
300
- setSearchMap: (state, action) => {
301
- state.searchMap = action.payload;
302
- },
303
- updateSearchMap: (state, action) => {
304
- if (!state.searchMap[action.payload.key]) {
305
- state.searchMap[action.payload.key] = [];
306
- }
307
- state.searchMap[action.payload.key].push(action.payload.value);
308
- },
309
- removeKeyFromSearchMap: (state, action) => {
310
- const { key, item } = action.payload;
311
- const values = state.searchMap[key];
312
- if (!values) return;
313
- if (item) {
314
- const filtered = values.filter((value) => value.name !== item.name);
315
- if (filtered.length > 0) {
316
- state.searchMap[key] = filtered;
317
- } else {
318
- delete state.searchMap[key];
319
- }
320
- } else {
321
- delete state.searchMap[key];
322
- }
323
- },
324
- clearSearchMap: (state) => {
325
- state.searchMap = {};
326
- }
327
- }
328
- });
329
- var {
330
- setGroupByDomain,
331
- setSelectedTags,
332
- setSearchString,
333
- setHoveredIndexSearchList,
334
- setFirstDomain,
335
- setTableHead,
336
- setFilterBy,
337
- setTypeFieldsSearch,
338
- setModelSearch,
339
- setSearchMap,
340
- updateSearchMap,
341
- removeKeyFromSearchMap,
342
- setGroupBy,
343
- clearSearchMap
344
- } = searchSlice.actions;
345
- var search_slice_default = searchSlice.reducer;
346
-
347
- // node_modules/redux/dist/redux.mjs
348
- function formatProdErrorMessage(code) {
349
- 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. `;
350
- }
351
- var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
352
- var ActionTypes = {
353
- INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
354
- REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
355
- PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
356
- };
357
- var actionTypes_default = ActionTypes;
358
- function isPlainObject(obj) {
359
- if (typeof obj !== "object" || obj === null)
360
- return false;
361
- let proto = obj;
362
- while (Object.getPrototypeOf(proto) !== null) {
363
- proto = Object.getPrototypeOf(proto);
364
- }
365
- return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
366
- }
367
- function miniKindOf(val) {
368
- if (val === void 0)
369
- return "undefined";
370
- if (val === null)
371
- return "null";
372
- const type = typeof val;
373
- switch (type) {
374
- case "boolean":
375
- case "string":
376
- case "number":
377
- case "symbol":
378
- case "function": {
379
- return type;
380
- }
381
- }
382
- if (Array.isArray(val))
383
- return "array";
384
- if (isDate(val))
385
- return "date";
386
- if (isError(val))
387
- return "error";
388
- const constructorName = ctorName(val);
389
- switch (constructorName) {
390
- case "Symbol":
391
- case "Promise":
392
- case "WeakMap":
393
- case "WeakSet":
394
- case "Map":
395
- case "Set":
396
- return constructorName;
397
- }
398
- return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
399
- }
400
- function ctorName(val) {
401
- return typeof val.constructor === "function" ? val.constructor.name : null;
402
- }
403
- function isError(val) {
404
- return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
405
- }
406
- function isDate(val) {
407
- if (val instanceof Date)
408
- return true;
409
- return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
410
- }
411
- function kindOf(val) {
412
- let typeOfVal = typeof val;
413
- if (process.env.NODE_ENV !== "production") {
414
- typeOfVal = miniKindOf(val);
415
- }
416
- return typeOfVal;
417
- }
418
- function warning(message) {
419
- if (typeof console !== "undefined" && typeof console.error === "function") {
420
- console.error(message);
421
- }
422
- try {
423
- throw new Error(message);
424
- } catch (e) {
425
- }
426
- }
427
- function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
428
- const reducerKeys = Object.keys(reducers);
429
- const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
430
- if (reducerKeys.length === 0) {
431
- return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
432
- }
433
- if (!isPlainObject(inputState)) {
434
- return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
435
- }
436
- const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
437
- unexpectedKeys.forEach((key) => {
438
- unexpectedKeyCache[key] = true;
439
- });
440
- if (action && action.type === actionTypes_default.REPLACE)
441
- return;
442
- if (unexpectedKeys.length > 0) {
443
- 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.`;
444
- }
445
- }
446
- function assertReducerShape(reducers) {
447
- Object.keys(reducers).forEach((key) => {
448
- const reducer = reducers[key];
449
- const initialState8 = reducer(void 0, {
450
- type: actionTypes_default.INIT
451
- });
452
- if (typeof initialState8 === "undefined") {
453
- 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.`);
454
- }
455
- if (typeof reducer(void 0, {
456
- type: actionTypes_default.PROBE_UNKNOWN_ACTION()
457
- }) === "undefined") {
458
- 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.`);
459
- }
460
- });
461
- }
462
- function combineReducers(reducers) {
463
- const reducerKeys = Object.keys(reducers);
464
- const finalReducers = {};
465
- for (let i = 0; i < reducerKeys.length; i++) {
466
- const key = reducerKeys[i];
467
- if (process.env.NODE_ENV !== "production") {
468
- if (typeof reducers[key] === "undefined") {
469
- warning(`No reducer provided for key "${key}"`);
470
- }
471
- }
472
- if (typeof reducers[key] === "function") {
473
- finalReducers[key] = reducers[key];
474
- }
475
- }
476
- const finalReducerKeys = Object.keys(finalReducers);
477
- let unexpectedKeyCache;
478
- if (process.env.NODE_ENV !== "production") {
479
- unexpectedKeyCache = {};
480
- }
481
- let shapeAssertionError;
482
- try {
483
- assertReducerShape(finalReducers);
484
- } catch (e) {
485
- shapeAssertionError = e;
486
- }
487
- return function combination(state = {}, action) {
488
- if (shapeAssertionError) {
489
- throw shapeAssertionError;
490
- }
491
- if (process.env.NODE_ENV !== "production") {
492
- const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
493
- if (warningMessage) {
494
- warning(warningMessage);
495
- }
496
- }
497
- let hasChanged = false;
498
- const nextState = {};
499
- for (let i = 0; i < finalReducerKeys.length; i++) {
500
- const key = finalReducerKeys[i];
501
- const reducer = finalReducers[key];
502
- const previousStateForKey = state[key];
503
- const nextStateForKey = reducer(previousStateForKey, action);
504
- if (typeof nextStateForKey === "undefined") {
505
- const actionType = action && action.type;
506
- 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.`);
507
- }
508
- nextState[key] = nextStateForKey;
509
- hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
510
- }
511
- hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
512
- return hasChanged ? nextState : state;
513
- };
514
- }
515
-
516
- // src/store/store.ts
517
- var rootReducer = combineReducers({
518
- env: env_slice_default,
519
- navbar: navbar_slice_default,
520
- list: list_slice_default,
521
- search: search_slice_default,
522
- form: form_slice_default,
523
- excel: excel_slice_default,
524
- profile: profile_slice_default
525
- });
526
- var envStore = configureStore({
527
- reducer: rootReducer,
528
- middleware: (getDefaultMiddleware) => getDefaultMiddleware({
529
- serializableCheck: false
530
- })
531
- });
532
- var MAINT_KEY = "MAINTENANCE_ACTIVE";
533
- var MAINT_AT = "MAINTENANCE_AT";
534
- var MAINT_LAST_PATH = "MAINTENANCE_LAST_PATH";
535
- var hasRedirectedToMaintenance = false;
536
- function setMaintenanceFlags() {
537
- if (typeof window === "undefined") return;
538
- const { pathname, search } = window.location;
539
- const lastPath = pathname + (search || "");
540
- if (pathname !== "/maintenance" && !window.localStorage.getItem(MAINT_LAST_PATH)) {
541
- window.localStorage.setItem(MAINT_LAST_PATH, lastPath);
542
- }
543
- window.localStorage.setItem(MAINT_KEY, "true");
544
- window.localStorage.setItem(MAINT_AT, String(Date.now()));
545
- }
546
- async function clearMaintenanceAndExit(getToken, opts) {
547
- if (typeof window === "undefined") return;
548
- const forceLogin = opts?.forceLogin === true;
549
- const clearTokenOnForce = opts?.clearTokenOnForce !== false;
550
- window.localStorage.removeItem(MAINT_KEY);
551
- window.localStorage.removeItem(MAINT_AT);
552
- const lastPath = window.localStorage.getItem(MAINT_LAST_PATH);
553
- window.localStorage.removeItem(MAINT_LAST_PATH);
554
- try {
555
- if (forceLogin) {
556
- if (clearTokenOnForce) {
557
- try {
558
- await opts?.clearToken?.();
559
- } catch {
560
- }
561
- }
562
- window.location.replace("/login");
563
- return;
564
- }
565
- const token = await getToken();
566
- if (token) {
567
- const target = lastPath && lastPath !== "/maintenance" ? lastPath : "/";
568
- window.location.replace(target);
569
- } else {
570
- window.location.replace("/login");
571
- }
572
- } catch {
573
- window.location.replace("/login");
574
- }
575
- }
576
- var axiosClient = {
577
- init(config) {
578
- const localStorage = config.localStorageUtils;
579
- const sessionStorage = config.sessionStorageUtils;
580
- const db = config.db;
581
- let isRefreshing = false;
582
- let failedQueue = [];
583
- const processQueue = (error, token = null) => {
584
- failedQueue?.forEach((prom) => {
585
- if (error) {
586
- prom.reject(error);
587
- } else {
588
- prom.resolve(token);
589
- }
590
- });
591
- failedQueue = [];
592
- };
593
- const instance = axios.create({
594
- adapter: axios.defaults.adapter,
595
- baseURL: config.baseUrl,
596
- timeout: 5e4,
597
- paramsSerializer: (params) => new URLSearchParams(params).toString()
598
- });
599
- if (typeof window !== "undefined") {
600
- const isMaint = window.localStorage.getItem(MAINT_KEY) === "true";
601
- const onMaintenancePage = window.location.pathname === "/maintenance";
602
- if (isMaint && !onMaintenancePage) {
603
- hasRedirectedToMaintenance = true;
604
- window.location.replace("/maintenance");
605
- }
606
- if (isMaint && onMaintenancePage) {
607
- const healthUrl = config.healthUrl || `${(config.baseUrl || "").replace(/\/+$/, "")}/health`;
608
- (async () => {
609
- try {
610
- await axios.get(healthUrl, { timeout: 8e3 });
611
- await clearMaintenanceAndExit(() => localStorage.getAccessToken(), {
612
- forceLogin: true,
613
- clearTokenOnForce: true,
614
- clearToken: () => localStorage.clearToken()
615
- });
616
- } catch {
617
- }
618
- })();
619
- }
620
- }
621
- instance.interceptors.request.use(
622
- async (configReq) => {
623
- const token = await localStorage.getAccessToken();
624
- if (token) {
625
- configReq.headers["Authorization"] = "Bearer " + token;
626
- }
627
- return configReq;
628
- },
629
- (error) => Promise.reject(error)
630
- );
631
- instance.interceptors.response.use(
632
- (response) => {
633
- if (typeof window !== "undefined") {
634
- const isMaint = window.localStorage.getItem(MAINT_KEY) === "true";
635
- const onMaintenancePage = window.location.pathname === "/maintenance";
636
- if (isMaint && onMaintenancePage) {
637
- (async () => {
638
- await clearMaintenanceAndExit(
639
- () => localStorage.getAccessToken(),
640
- {
641
- forceLogin: true,
642
- clearTokenOnForce: true,
643
- clearToken: () => localStorage.clearToken()
644
- }
645
- );
646
- })();
647
- } else if (isMaint) {
648
- window.localStorage.removeItem(MAINT_KEY);
649
- window.localStorage.removeItem(MAINT_AT);
650
- window.localStorage.removeItem(MAINT_LAST_PATH);
651
- }
652
- }
653
- return handleResponse(response);
654
- },
655
- async (error) => {
656
- const status = error?.response?.status;
657
- if (status === 503) {
658
- if (typeof window !== "undefined") {
659
- setMaintenanceFlags();
660
- if (!hasRedirectedToMaintenance && window.location.pathname !== "/maintenance") {
661
- hasRedirectedToMaintenance = true;
662
- window.location.replace("/maintenance");
663
- }
664
- }
665
- return Promise.reject({
666
- code: 503,
667
- message: "SERVICE_UNAVAILABLE",
668
- original: error?.response?.data
669
- });
670
- }
671
- const handleError = async (err) => {
672
- if (!err.response) {
673
- return err;
674
- }
675
- const { data } = err.response;
676
- if (data && data.code === 400 && ["invalid_grant"].includes(data.data?.error)) {
677
- await clearAuthToken();
678
- }
679
- return data;
680
- };
681
- const originalRequest = error.config;
682
- if ((error.response?.status === 403 || error.response?.status === 401 || error.response?.status === 404) && ["TOKEN_EXPIRED", "AUTHEN_FAIL", 401].includes(
683
- error.response.data.code
684
- )) {
685
- if (isRefreshing) {
686
- return new Promise(function(resolve, reject) {
687
- failedQueue.push({ resolve, reject });
688
- }).then((token) => {
689
- originalRequest.headers["Authorization"] = "Bearer " + token;
690
- return instance.request(originalRequest);
691
- }).catch(async (err) => {
692
- if ((err.response?.status === 400 || err.response?.status === 401) && ["invalid_grant"].includes(err.response.data.error)) {
693
- await clearAuthToken();
694
- }
695
- });
696
- }
697
- const browserSession = await sessionStorage.getBrowserSession();
698
- const refreshToken = await localStorage.getRefreshToken();
699
- const accessTokenExp = await localStorage.getAccessToken();
700
- isRefreshing = true;
701
- if (!refreshToken && (!browserSession || browserSession == "unActive")) {
702
- await clearAuthToken();
703
- } else {
704
- const payload = Object.fromEntries(
705
- Object.entries({
706
- refresh_token: refreshToken,
707
- grant_type: "refresh_token",
708
- client_id: config.config.clientId,
709
- client_secret: config.config.clientSecret
710
- }).filter(([_, value]) => !!value)
711
- );
712
- return new Promise(function(resolve) {
713
- axios.post(
714
- `${config.baseUrl}${"/authentication/oauth2/token" /* AUTH_TOKEN_PATH */}`,
715
- payload,
716
- {
717
- headers: {
718
- "Content-Type": "multipart/form-data",
719
- Authorization: `Bearer ${accessTokenExp}`
720
- }
721
- }
722
- ).then(async (res) => {
723
- const data = res.data;
724
- await localStorage.setToken(data.access_token);
725
- await localStorage.setRefreshToken(data.refresh_token);
726
- axios.defaults.headers.common["Authorization"] = "Bearer " + data.access_token;
727
- originalRequest.headers["Authorization"] = "Bearer " + data.access_token;
728
- processQueue(null, data.access_token);
729
- resolve(instance.request(originalRequest));
730
- }).catch(async (err) => {
731
- if (err && (err?.error_code === "AUTHEN_FAIL" || err?.error_code === "TOKEN_EXPIRED" || err?.error_code === "TOKEN_INCORRECT" || err?.code === "ERR_BAD_REQUEST")) {
732
- await clearAuthToken();
733
- }
734
- if (err && err.response) {
735
- const { error_code } = err.response?.data || {};
736
- if (error_code === "AUTHEN_FAIL") {
737
- await clearAuthToken();
738
- }
739
- }
740
- processQueue(err, null);
741
- }).finally(() => {
742
- isRefreshing = false;
743
- });
744
- });
745
- }
746
- }
747
- return Promise.reject(await handleError(error));
748
- }
749
- );
750
- const handleResponse = (res) => {
751
- if (res && res.data) {
752
- return res.data;
753
- }
754
- return res;
755
- };
756
- const clearAuthToken = async () => {
757
- await localStorage.clearToken();
758
- if (typeof window !== "undefined") {
759
- window.location.href = `/login`;
760
- }
761
- };
762
- function formatUrl(url, db2) {
763
- return url + (db2 ? "?db=" + db2 : "");
764
- }
765
- const responseBody = (response) => response;
766
- const requests = {
767
- get: (url, headers) => instance.get(formatUrl(url, db), headers).then(responseBody),
768
- post: (url, body, headers) => instance.post(formatUrl(url, db), body, { headers }).then(responseBody),
769
- post_excel: (url, body, headers) => instance.post(formatUrl(url, db), body, {
770
- responseType: "arraybuffer",
771
- headers: {
772
- "Content-Type": typeof window !== "undefined" ? "application/json" : "application/javascript",
773
- Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
774
- }
775
- }).then(responseBody),
776
- put: (url, body, headers) => instance.put(formatUrl(url, db), body, headers).then(responseBody),
777
- patch: (url, body) => instance.patch(formatUrl(url, db), body).then(responseBody),
778
- delete: (url, body) => instance.delete(formatUrl(url, db), body).then(responseBody)
779
- };
780
- return requests;
781
- }
782
- };
783
-
784
- // src/environment/EnvStore.ts
785
- var EnvStore = class {
786
- envStore;
787
- baseUrl;
788
- requests;
789
- context;
790
- defaultCompany;
791
- config;
792
- companies;
793
- user;
794
- db;
795
- localStorageUtils;
796
- sessionStorageUtils;
797
- constructor(envStore2, localStorageUtils, sessionStorageUtils) {
798
- this.envStore = envStore2;
799
- this.localStorageUtils = localStorageUtils;
800
- this.sessionStorageUtils = sessionStorageUtils;
801
- this.setup();
802
- }
803
- setup() {
804
- const env2 = this.envStore.getState().env;
805
- this.baseUrl = env2?.baseUrl;
806
- this.requests = env2?.requests;
807
- this.context = env2?.context;
808
- this.defaultCompany = env2?.defaultCompany;
809
- this.config = env2?.config;
810
- this.companies = env2?.companies || [];
811
- this.user = env2?.user;
812
- this.db = env2?.db;
813
- }
814
- setupEnv(envConfig) {
815
- const dispatch = this.envStore.dispatch;
816
- const env2 = {
817
- ...envConfig,
818
- localStorageUtils: this.localStorageUtils,
819
- sessionStorageUtils: this.sessionStorageUtils
820
- };
821
- const requests = axiosClient.init(env2);
822
- dispatch(setEnv({ ...env2, requests }));
823
- this.setup();
824
- }
825
- setUid(uid) {
826
- const dispatch = this.envStore.dispatch;
827
- dispatch(setUid(uid));
828
- this.setup();
829
- }
830
- setLang(lang) {
831
- const dispatch = this.envStore.dispatch;
832
- dispatch(setLang(lang));
833
- this.setup();
834
- }
835
- setAllowCompanies(allowCompanies) {
836
- const dispatch = this.envStore.dispatch;
837
- dispatch(setAllowCompanies(allowCompanies));
838
- this.setup();
839
- }
840
- setCompanies(companies) {
841
- const dispatch = this.envStore.dispatch;
842
- dispatch(setCompanies(companies));
843
- this.setup();
844
- }
845
- setDefaultCompany(company) {
846
- const dispatch = this.envStore.dispatch;
847
- dispatch(setDefaultCompany(company));
848
- this.setup();
849
- }
850
- setUserInfo(userInfo) {
851
- const dispatch = this.envStore.dispatch;
852
- dispatch(setUser(userInfo));
853
- this.setup();
854
- }
855
- };
856
- var env = null;
857
- function getEnv() {
858
- if (!env) env = new EnvStore(envStore);
859
- return env;
860
- }
861
-
862
- // src/utils/domain/py_tokenizer.ts
863
- var TokenizerError = class extends Error {
864
- };
865
- var directMap = {
866
- "\\": "\\",
867
- '"': '"',
868
- "'": "'",
869
- a: "\x07",
870
- b: "\b",
871
- f: "\f",
872
- n: "\n",
873
- r: "\r",
874
- t: " ",
875
- v: "\v"
876
- };
877
- function decodeStringLiteral(str, unicode) {
878
- const out = [];
879
- let code;
880
- for (let i = 0; i < str.length; ++i) {
881
- if (str[i] !== "\\") {
882
- out.push(str[i]);
883
- continue;
884
- }
885
- const escape = str[i + 1];
886
- if (escape in directMap) {
887
- out.push(directMap[escape]);
888
- ++i;
889
- continue;
890
- }
891
- switch (escape) {
892
- case "\n":
893
- ++i;
894
- continue;
895
- case "N":
896
- if (!unicode) {
897
- break;
898
- }
899
- throw new TokenizerError("SyntaxError: \\N{} escape not implemented");
900
- case "u":
901
- if (!unicode) {
902
- break;
903
- }
904
- const uni = str.slice(i + 2, i + 6);
905
- if (!/[0-9a-f]{4}/i.test(uni)) {
906
- throw new TokenizerError(
907
- [
908
- "SyntaxError: (unicode error) 'unicodeescape' codec",
909
- " can't decode bytes in position ",
910
- i,
911
- "-",
912
- i + 4,
913
- ": truncated \\uXXXX escape"
914
- ].join("")
915
- );
916
- }
917
- code = parseInt(uni, 16);
918
- out.push(String.fromCharCode(code));
919
- i += 5;
920
- continue;
921
- case "U":
922
- if (!unicode) {
923
- break;
924
- }
925
- throw new TokenizerError("SyntaxError: \\U escape not implemented");
926
- case "x":
927
- const hex = str.slice(i + 2, i + 4);
928
- if (!/[0-9a-f]{2}/i.test(hex)) {
929
- if (!unicode) {
930
- throw new TokenizerError("ValueError: invalid \\x escape");
931
- }
932
- throw new TokenizerError(
933
- [
934
- "SyntaxError: (unicode error) 'unicodeescape'",
935
- " codec can't decode bytes in position ",
936
- i,
937
- "-",
938
- i + 2,
939
- ": truncated \\xXX escape"
940
- ].join("")
941
- );
942
- }
943
- code = parseInt(hex, 16);
944
- out.push(String.fromCharCode(code));
945
- i += 3;
946
- continue;
947
- default:
948
- if (!/[0-8]/.test(escape)) {
949
- break;
950
- }
951
- const r = /[0-8]{1,3}/g;
952
- r.lastIndex = i + 1;
953
- const m = r.exec(str);
954
- if (!m) break;
955
- const oct = m[0];
956
- code = parseInt(oct, 8);
957
- out.push(String.fromCharCode(code));
958
- i += oct.length;
959
- continue;
960
- }
961
- out.push("\\");
962
- }
963
- return out.join("");
964
- }
965
- var constants = /* @__PURE__ */ new Set(["None", "False", "True"]);
966
- var comparators = [
967
- "in",
968
- "not",
969
- "not in",
970
- "is",
971
- "is not",
972
- "<",
973
- "<=",
974
- ">",
975
- ">=",
976
- "<>",
977
- "!=",
978
- "=="
979
- ];
980
- var binaryOperators = [
981
- "or",
982
- "and",
983
- "|",
984
- "^",
985
- "&",
986
- "<<",
987
- ">>",
988
- "+",
989
- "-",
990
- "*",
991
- "/",
992
- "//",
993
- "%",
994
- "~",
995
- "**",
996
- "."
997
- ];
998
- var unaryOperators = ["-"];
999
- var symbols = /* @__PURE__ */ new Set([
1000
- ...["(", ")", "[", "]", "{", "}", ":", ","],
1001
- ...["if", "else", "lambda", "="],
1002
- ...comparators,
1003
- ...binaryOperators,
1004
- ...unaryOperators
1005
- ]);
1006
- function group(...args) {
1007
- return "(" + args.join("|") + ")";
1008
- }
1009
- var Name = "[a-zA-Z_]\\w*";
1010
- var Whitespace = "[ \\f\\t]*";
1011
- var DecNumber = "\\d+(L|l)?";
1012
- var IntNumber = DecNumber;
1013
- var Exponent = "[eE][+-]?\\d+";
1014
- var PointFloat = group(`\\d+\\.\\d*(${Exponent})?`, `\\.\\d+(${Exponent})?`);
1015
- var FloatNumber = group(PointFloat, `\\d+${Exponent}`);
1016
- var Number2 = group(FloatNumber, IntNumber);
1017
- var Operator = group(
1018
- "\\*\\*=?",
1019
- ">>=?",
1020
- "<<=?",
1021
- "<>",
1022
- "!=",
1023
- "//=?",
1024
- "[+\\-*/%&|^=<>]=?",
1025
- "~"
1026
- );
1027
- var Bracket = "[\\[\\]\\(\\)\\{\\}]";
1028
- var Special = "[:;.,`@]";
1029
- var Funny = group(Operator, Bracket, Special);
1030
- var ContStr = group(
1031
- "([uU])?'([^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*)'",
1032
- '([uU])?"([^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*)"'
1033
- );
1034
- var PseudoToken = Whitespace + group(Number2, Funny, ContStr, Name);
1035
- var NumberPattern = new RegExp("^" + Number2 + "$");
1036
- var StringPattern = new RegExp("^" + ContStr + "$");
1037
- var NamePattern = new RegExp("^" + Name + "$");
1038
- var strip = new RegExp("^" + Whitespace);
1039
- function tokenize(str) {
1040
- const tokens = [];
1041
- const max = str.length;
1042
- let start = 0;
1043
- let end = 0;
1044
- const pseudoprog = new RegExp(PseudoToken, "g");
1045
- while (pseudoprog.lastIndex < max) {
1046
- const pseudomatch = pseudoprog.exec(str);
1047
- if (!pseudomatch) {
1048
- if (/^\s+$/.test(str.slice(end))) {
1049
- break;
1050
- }
1051
- throw new TokenizerError(
1052
- "Failed to tokenize <<" + str + ">> at index " + (end || 0) + "; parsed so far: " + tokens
1053
- );
1054
- }
1055
- if (pseudomatch.index > end) {
1056
- if (str.slice(end, pseudomatch.index).trim()) {
1057
- throw new TokenizerError("Invalid expression");
1058
- }
1059
- }
1060
- start = pseudomatch.index;
1061
- end = pseudoprog.lastIndex;
1062
- let token = str.slice(start, end).replace(strip, "");
1063
- if (NumberPattern.test(token)) {
1064
- tokens.push({
1065
- type: 0,
1066
- value: parseFloat(token)
1067
- });
1068
- } else if (StringPattern.test(token)) {
1069
- const m = StringPattern.exec(token);
1070
- if (!m) throw new TokenizerError("Invalid string match");
1071
- tokens.push({
1072
- type: 1,
1073
- value: decodeStringLiteral(
1074
- m[3] !== void 0 ? m[3] : m[5],
1075
- !!(m[2] || m[4])
1076
- )
1077
- });
1078
- } else if (symbols.has(token)) {
1079
- if (token === "in" && tokens.length > 0 && tokens[tokens.length - 1].value === "not") {
1080
- token = "not in";
1081
- tokens.pop();
1082
- } else if (token === "not" && tokens.length > 0 && tokens[tokens.length - 1].value === "is") {
1083
- token = "is not";
1084
- tokens.pop();
1085
- }
1086
- tokens.push({
1087
- type: 2,
1088
- value: token
1089
- });
1090
- } else if (constants.has(token)) {
1091
- tokens.push({
1092
- type: 4,
1093
- value: token
1094
- });
1095
- } else if (NamePattern.test(token)) {
1096
- tokens.push({
1097
- type: 3,
1098
- value: token
1099
- });
1100
- } else {
1101
- throw new TokenizerError("Invalid expression");
1102
- }
1103
- }
1104
- return tokens;
1105
- }
1106
-
1107
- // src/utils/domain/py_parser.ts
1108
- var ParserError = class extends Error {
1109
- };
1110
- var chainedOperators = new Set(comparators);
1111
- var infixOperators = /* @__PURE__ */ new Set([...binaryOperators, ...comparators]);
1112
- function bp(symbol) {
1113
- switch (symbol) {
1114
- case "=":
1115
- return 10;
1116
- case "if":
1117
- return 20;
1118
- case "in":
1119
- case "not in":
1120
- case "is":
1121
- case "is not":
1122
- case "<":
1123
- case "<=":
1124
- case ">":
1125
- case ">=":
1126
- case "<>":
1127
- case "==":
1128
- case "!=":
1129
- return 60;
1130
- case "or":
1131
- return 30;
1132
- case "and":
1133
- return 40;
1134
- case "not":
1135
- return 50;
1136
- case "|":
1137
- return 70;
1138
- case "^":
1139
- return 80;
1140
- case "&":
1141
- return 90;
1142
- case "<<":
1143
- case ">>":
1144
- return 100;
1145
- case "+":
1146
- case "-":
1147
- return 110;
1148
- case "*":
1149
- case "/":
1150
- case "//":
1151
- case "%":
1152
- return 120;
1153
- case "**":
1154
- return 140;
1155
- case ".":
1156
- case "(":
1157
- case "[":
1158
- return 150;
1159
- default:
1160
- return 0;
1161
- }
1162
- }
1163
- function bindingPower(token) {
1164
- return token.type === 2 ? bp(token.value) : 0;
1165
- }
1166
- function isSymbol(token, value) {
1167
- return token.type === 2 && token.value === value;
1168
- }
1169
- function parsePrefix(current, tokens) {
1170
- switch (current.type) {
1171
- case 0:
1172
- return { type: 0, value: current.value };
1173
- case 1:
1174
- return { type: 1, value: current.value };
1175
- case 4:
1176
- if (current.value === "None") {
1177
- return {
1178
- type: 3
1179
- /* None */
1180
- };
1181
- } else {
1182
- return { type: 2, value: current.value === "True" };
1183
- }
1184
- case 3:
1185
- return { type: 5, value: current.value };
1186
- case 2:
1187
- switch (current.value) {
1188
- case "-":
1189
- case "+":
1190
- case "~":
1191
- return {
1192
- type: 6,
1193
- op: current.value,
1194
- right: _parse(tokens, 130)
1195
- };
1196
- case "not":
1197
- return {
1198
- type: 6,
1199
- op: current.value,
1200
- right: _parse(tokens, 50)
1201
- };
1202
- case "(":
1203
- const content = [];
1204
- let isTuple = false;
1205
- while (tokens[0] && !isSymbol(tokens[0], ")")) {
1206
- content.push(_parse(tokens, 0));
1207
- if (tokens[0]) {
1208
- if (tokens[0] && isSymbol(tokens[0], ",")) {
1209
- isTuple = true;
1210
- tokens.shift();
1211
- } else if (!isSymbol(tokens[0], ")")) {
1212
- throw new ParserError("parsing error");
1213
- }
1214
- } else {
1215
- throw new ParserError("parsing error");
1216
- }
1217
- }
1218
- if (!tokens[0] || !isSymbol(tokens[0], ")")) {
1219
- throw new ParserError("parsing error");
1220
- }
1221
- tokens.shift();
1222
- isTuple = isTuple || content.length === 0;
1223
- return isTuple ? { type: 10, value: content } : content[0];
1224
- case "[":
1225
- const value = [];
1226
- while (tokens[0] && !isSymbol(tokens[0], "]")) {
1227
- value.push(_parse(tokens, 0));
1228
- if (tokens[0]) {
1229
- if (isSymbol(tokens[0], ",")) {
1230
- tokens.shift();
1231
- } else if (!isSymbol(tokens[0], "]")) {
1232
- throw new ParserError("parsing error");
1233
- }
1234
- }
1235
- }
1236
- if (!tokens[0] || !isSymbol(tokens[0], "]")) {
1237
- throw new ParserError("parsing error");
1238
- }
1239
- tokens.shift();
1240
- return { type: 4, value };
1241
- case "{":
1242
- const dict = {};
1243
- while (tokens[0] && !isSymbol(tokens[0], "}")) {
1244
- const key = _parse(tokens, 0);
1245
- if (key.type !== 1 && key.type !== 0 || !tokens[0] || !isSymbol(tokens[0], ":")) {
1246
- throw new ParserError("parsing error");
1247
- }
1248
- tokens.shift();
1249
- const val = _parse(tokens, 0);
1250
- dict[key.value] = val;
1251
- if (isSymbol(tokens[0], ",")) {
1252
- tokens.shift();
1253
- }
1254
- }
1255
- if (!tokens.shift()) {
1256
- throw new ParserError("parsing error");
1257
- }
1258
- return { type: 11, value: dict };
1259
- default:
1260
- throw new ParserError("Token cannot be parsed");
1261
- }
1262
- default:
1263
- throw new ParserError("Token cannot be parsed");
1264
- }
1265
- }
1266
- function parseInfix(left, current, tokens) {
1267
- switch (current.type) {
1268
- case 2:
1269
- if (infixOperators.has(current.value)) {
1270
- let right = _parse(tokens, bindingPower(current));
1271
- if (current.value === "and" || current.value === "or") {
1272
- return {
1273
- type: 14,
1274
- op: current.value,
1275
- left,
1276
- right
1277
- };
1278
- } else if (current.value === ".") {
1279
- if (right.type === 5) {
1280
- return {
1281
- type: 15,
1282
- obj: left,
1283
- key: right.value
1284
- };
1285
- } else {
1286
- throw new ParserError("invalid obj lookup");
1287
- }
1288
- }
1289
- let op = {
1290
- type: 7,
1291
- op: current.value,
1292
- left,
1293
- right
1294
- };
1295
- while (chainedOperators.has(current.value) && tokens[0] && tokens[0].type === 2 && chainedOperators.has(tokens[0].value)) {
1296
- const nextToken = tokens.shift();
1297
- op = {
1298
- type: 14,
1299
- op: "and",
1300
- left: op,
1301
- right: {
1302
- type: 7,
1303
- op: nextToken.value,
1304
- left: right,
1305
- right: _parse(tokens, bindingPower(nextToken))
1306
- }
1307
- };
1308
- right = op.right;
1309
- }
1310
- return op;
1311
- }
1312
- switch (current.value) {
1313
- case "(":
1314
- const args = [];
1315
- const kwargs = {};
1316
- while (tokens[0] && !isSymbol(tokens[0], ")")) {
1317
- const arg = _parse(tokens, 0);
1318
- if (arg.type === 9) {
1319
- kwargs[arg.name.value] = arg.value;
1320
- } else {
1321
- args.push(arg);
1322
- }
1323
- if (tokens[0] && isSymbol(tokens[0], ",")) {
1324
- tokens.shift();
1325
- }
1326
- }
1327
- if (!tokens[0] || !isSymbol(tokens[0], ")")) {
1328
- throw new ParserError("parsing error");
1329
- }
1330
- tokens.shift();
1331
- return { type: 8, fn: left, args, kwargs };
1332
- case "=":
1333
- if (left.type === 5) {
1334
- return {
1335
- type: 9,
1336
- name: left,
1337
- value: _parse(tokens, 10)
1338
- };
1339
- }
1340
- break;
1341
- case "[":
1342
- const key = _parse(tokens);
1343
- if (!tokens[0] || !isSymbol(tokens[0], "]")) {
1344
- throw new ParserError("parsing error");
1345
- }
1346
- tokens.shift();
1347
- return {
1348
- type: 12,
1349
- target: left,
1350
- key
1351
- };
1352
- case "if":
1353
- const condition = _parse(tokens);
1354
- if (!tokens[0] || !isSymbol(tokens[0], "else")) {
1355
- throw new ParserError("parsing error");
1356
- }
1357
- tokens.shift();
1358
- const ifFalse = _parse(tokens);
1359
- return {
1360
- type: 13,
1361
- condition,
1362
- ifTrue: left,
1363
- ifFalse
1364
- };
1365
- }
1366
- }
1367
- throw new ParserError("Token cannot be parsed");
1368
- }
1369
- function _parse(tokens, bp2 = 0) {
1370
- const token = tokens.shift();
1371
- if (!token) {
1372
- throw new ParserError("Unexpected end of input");
1373
- }
1374
- let expr = parsePrefix(token, tokens);
1375
- while (tokens[0] && bindingPower(tokens[0]) > bp2) {
1376
- expr = parseInfix(expr, tokens.shift(), tokens);
1377
- }
1378
- return expr;
1379
- }
1380
- function parse(tokens) {
1381
- if (tokens.length) {
1382
- return _parse(tokens, 0);
1383
- }
1384
- throw new ParserError("Missing token");
1385
- }
1386
- function parseArgs(args, spec) {
1387
- const last = args[args.length - 1];
1388
- const unnamedArgs = typeof last === "object" ? args.slice(0, -1) : args;
1389
- const kwargs = typeof last === "object" ? last : {};
1390
- for (const [index, val] of unnamedArgs.entries()) {
1391
- kwargs[spec[index]] = val;
1392
- }
1393
- return kwargs;
1394
- }
1395
-
1396
- // src/utils/domain/py_date.ts
1397
- var AssertionError = class extends Error {
1398
- };
1399
- var ValueError = class extends Error {
1400
- };
1401
- var NotSupportedError = class extends Error {
1402
- };
1403
- function fmt2(n) {
1404
- return String(n).padStart(2, "0");
1405
- }
1406
- function fmt4(n) {
1407
- return String(n).padStart(4, "0");
1408
- }
1409
- function divmod(a, b, fn) {
1410
- let mod = a % b;
1411
- if (mod > 0 && b < 0 || mod < 0 && b > 0) {
1412
- mod += b;
1413
- }
1414
- return fn(Math.floor(a / b), mod);
1415
- }
1416
- function assert(bool, message = "AssertionError") {
1417
- if (!bool) {
1418
- throw new AssertionError(message);
1419
- }
1420
- }
1421
- var DAYS_IN_MONTH = [
1422
- null,
1423
- 31,
1424
- 28,
1425
- 31,
1426
- 30,
1427
- 31,
1428
- 30,
1429
- 31,
1430
- 31,
1431
- 30,
1432
- 31,
1433
- 30,
1434
- 31
1435
- ];
1436
- var DAYS_BEFORE_MONTH = [null];
1437
- for (let dbm = 0, i = 1; i < DAYS_IN_MONTH.length; ++i) {
1438
- DAYS_BEFORE_MONTH.push(dbm);
1439
- dbm += DAYS_IN_MONTH[i];
1440
- }
1441
- function daysInMonth(year, month) {
1442
- if (month === 2 && isLeap(year)) {
1443
- return 29;
1444
- }
1445
- return DAYS_IN_MONTH[month];
1446
- }
1447
- function isLeap(year) {
1448
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1449
- }
1450
- function daysBeforeYear(year) {
1451
- const y = year - 1;
1452
- return y * 365 + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
1453
- }
1454
- function daysBeforeMonth(year, month) {
1455
- const postLeapFeb = month > 2 && isLeap(year);
1456
- return DAYS_BEFORE_MONTH[month] + (postLeapFeb ? 1 : 0);
1457
- }
1458
- function ymd2ord(year, month, day) {
1459
- const dim = daysInMonth(year, month);
1460
- if (!(1 <= day && day <= dim)) {
1461
- throw new ValueError(`day must be in 1..${dim}`);
1462
- }
1463
- return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
1464
- }
1465
- var DI400Y = daysBeforeYear(401);
1466
- var DI100Y = daysBeforeYear(101);
1467
- var DI4Y = daysBeforeYear(5);
1468
- function ord2ymd(n) {
1469
- --n;
1470
- let n400 = 0, n100 = 0, n4 = 0, n1 = 0, n0 = 0;
1471
- divmod(n, DI400Y, (_n400, n2) => {
1472
- n400 = _n400;
1473
- divmod(n2, DI100Y, (_n100, n3) => {
1474
- n100 = _n100;
1475
- divmod(n3, DI4Y, (_n4, n5) => {
1476
- n4 = _n4;
1477
- divmod(n5, 365, (_n1, n6) => {
1478
- n1 = _n1;
1479
- n0 = n6;
1480
- });
1481
- });
1482
- });
1483
- });
1484
- n = n0;
1485
- const year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1;
1486
- if (n1 === 4 || n100 === 100) {
1487
- assert(n0 === 0);
1488
- return {
1489
- year: year - 1,
1490
- month: 12,
1491
- day: 31
1492
- };
1493
- }
1494
- const leapyear = n1 === 3 && (n4 !== 24 || n100 === 3);
1495
- assert(leapyear === isLeap(year));
1496
- let month = n + 50 >> 5;
1497
- let preceding = DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
1498
- if (preceding > n) {
1499
- --month;
1500
- preceding -= DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
1501
- }
1502
- n -= preceding;
1503
- return {
1504
- year,
1505
- month,
1506
- day: n + 1
1507
- };
1508
- }
1509
- function tmxxx(year, month, day, hour, minute, second, microsecond) {
1510
- hour = hour || 0;
1511
- minute = minute || 0;
1512
- second = second || 0;
1513
- microsecond = microsecond || 0;
1514
- if (microsecond < 0 || microsecond > 999999) {
1515
- divmod(microsecond, 1e6, (carry, ms) => {
1516
- microsecond = ms;
1517
- second += carry;
1518
- });
1519
- }
1520
- if (second < 0 || second > 59) {
1521
- divmod(second, 60, (carry, s) => {
1522
- second = s;
1523
- minute += carry;
1524
- });
1525
- }
1526
- if (minute < 0 || minute > 59) {
1527
- divmod(minute, 60, (carry, m) => {
1528
- minute = m;
1529
- hour += carry;
1530
- });
1531
- }
1532
- if (hour < 0 || hour > 23) {
1533
- divmod(hour, 24, (carry, h) => {
1534
- hour = h;
1535
- day += carry;
1536
- });
1537
- }
1538
- if (month < 1 || month > 12) {
1539
- divmod(month - 1, 12, (carry, m) => {
1540
- month = m + 1;
1541
- year += carry;
1542
- });
1543
- }
1544
- const dim = daysInMonth(year, month);
1545
- if (day < 1 || day > dim) {
1546
- if (day === 0) {
1547
- --month;
1548
- if (month > 0) {
1549
- day = daysInMonth(year, month);
1550
- } else {
1551
- --year;
1552
- month = 12;
1553
- day = 31;
1554
- }
1555
- } else if (day === dim + 1) {
1556
- ++month;
1557
- day = 1;
1558
- if (month > 12) {
1559
- month = 1;
1560
- ++year;
1561
- }
1562
- } else {
1563
- const r = ord2ymd(ymd2ord(year, month, 1) + (day - 1));
1564
- year = r.year;
1565
- month = r.month;
1566
- day = r.day;
1567
- }
1568
- }
1569
- return {
1570
- year,
1571
- month,
1572
- day,
1573
- hour,
1574
- minute,
1575
- second,
1576
- microsecond
1577
- };
1578
- }
1579
- var PyDate = class _PyDate {
1580
- constructor(year, month, day) {
1581
- this.year = year;
1582
- this.month = month;
1583
- this.day = day;
1584
- }
1585
- static today() {
1586
- return this.convertDate(/* @__PURE__ */ new Date());
1587
- }
1588
- static convertDate(date) {
1589
- const year = date.getFullYear();
1590
- const month = date.getMonth() + 1;
1591
- const day = date.getDate();
1592
- return new _PyDate(year, month, day);
1593
- }
1594
- static create(...args) {
1595
- const { year, month, day } = parseArgs(args, ["year", "month", "day"]);
1596
- return new _PyDate(year, month, day);
1597
- }
1598
- add(timedelta) {
1599
- const s = tmxxx(this.year, this.month, this.day + timedelta.days, 0, 0, 0);
1600
- return new _PyDate(s.year, s.month, s.day);
1601
- }
1602
- isEqual(other) {
1603
- if (!(other instanceof _PyDate)) {
1604
- return false;
1605
- }
1606
- return this.year === other.year && this.month === other.month && this.day === other.day;
1607
- }
1608
- strftime(format) {
1609
- return format.replace(/%([A-Za-z])/g, (m, c) => {
1610
- switch (c) {
1611
- case "Y":
1612
- return fmt4(this.year);
1613
- case "m":
1614
- return fmt2(this.month);
1615
- case "d":
1616
- return fmt2(this.day);
1617
- default:
1618
- throw new ValueError(`No known conversion for ${m}`);
1619
- }
1620
- });
1621
- }
1622
- substract(other) {
1623
- if (other instanceof PyTimeDelta) {
1624
- return this.add(other.negate());
1625
- }
1626
- if (other instanceof _PyDate) {
1627
- return PyTimeDelta.create(this.toordinal() - other.toordinal());
1628
- }
1629
- throw new NotSupportedError();
1630
- }
1631
- toJSON() {
1632
- return this.strftime("%Y-%m-%d");
1633
- }
1634
- toordinal() {
1635
- return ymd2ord(this.year, this.month, this.day);
1636
- }
1637
- };
1638
- var PyDateTime = class _PyDateTime {
1639
- constructor(year, month, day, hour, minute, second, microsecond) {
1640
- this.year = year;
1641
- this.month = month;
1642
- this.day = day;
1643
- this.hour = hour;
1644
- this.minute = minute;
1645
- this.second = second;
1646
- this.microsecond = microsecond;
1647
- }
1648
- static now() {
1649
- return this.convertDate(/* @__PURE__ */ new Date());
1650
- }
1651
- static convertDate(date) {
1652
- const year = date.getFullYear();
1653
- const month = date.getMonth() + 1;
1654
- const day = date.getDate();
1655
- const hour = date.getHours();
1656
- const minute = date.getMinutes();
1657
- const second = date.getSeconds();
1658
- return new _PyDateTime(year, month, day, hour, minute, second, 0);
1659
- }
1660
- static create(...args) {
1661
- const namedArgs = parseArgs(args, [
1662
- "year",
1663
- "month",
1664
- "day",
1665
- "hour",
1666
- "minute",
1667
- "second",
1668
- "microsecond"
1669
- ]);
1670
- const year = namedArgs.year;
1671
- const month = namedArgs.month;
1672
- const day = namedArgs.day;
1673
- const hour = namedArgs.hour || 0;
1674
- const minute = namedArgs.minute || 0;
1675
- const second = namedArgs.second || 0;
1676
- const ms = namedArgs.microsecond / 1e3 || 0;
1677
- return new _PyDateTime(year, month, day, hour, minute, second, ms);
1678
- }
1679
- static combine(...args) {
1680
- const { date, time } = parseArgs(args, ["date", "time"]);
1681
- return _PyDateTime.create(
1682
- date.year,
1683
- date.month,
1684
- date.day,
1685
- time.hour,
1686
- time.minute,
1687
- time.second
1688
- );
1689
- }
1690
- add(timedelta) {
1691
- const s = tmxxx(
1692
- this.year,
1693
- this.month,
1694
- this.day + timedelta.days,
1695
- this.hour,
1696
- this.minute,
1697
- this.second + timedelta.seconds,
1698
- this.microsecond + timedelta.microseconds
1699
- );
1700
- return new _PyDateTime(
1701
- s.year,
1702
- s.month,
1703
- s.day,
1704
- s.hour,
1705
- s.minute,
1706
- s.second,
1707
- s.microsecond
1708
- );
1709
- }
1710
- isEqual(other) {
1711
- if (!(other instanceof _PyDateTime)) {
1712
- return false;
1713
- }
1714
- return this.year === other.year && this.month === other.month && this.day === other.day && this.hour === other.hour && this.minute === other.minute && this.second === other.second && this.microsecond === other.microsecond;
1715
- }
1716
- strftime(format) {
1717
- return format.replace(/%([A-Za-z])/g, (m, c) => {
1718
- switch (c) {
1719
- case "Y":
1720
- return fmt4(this.year);
1721
- case "m":
1722
- return fmt2(this.month);
1723
- case "d":
1724
- return fmt2(this.day);
1725
- case "H":
1726
- return fmt2(this.hour);
1727
- case "M":
1728
- return fmt2(this.minute);
1729
- case "S":
1730
- return fmt2(this.second);
1731
- default:
1732
- throw new ValueError(`No known conversion for ${m}`);
1733
- }
1734
- });
1735
- }
1736
- substract(timedelta) {
1737
- return this.add(timedelta.negate());
1738
- }
1739
- toJSON() {
1740
- return this.strftime("%Y-%m-%d %H:%M:%S");
1741
- }
1742
- to_utc() {
1743
- const d = new Date(
1744
- this.year,
1745
- this.month - 1,
1746
- this.day,
1747
- this.hour,
1748
- this.minute,
1749
- this.second
1750
- );
1751
- const timedelta = PyTimeDelta.create({ minutes: d.getTimezoneOffset() });
1752
- return this.add(timedelta);
1753
- }
1754
- };
1755
- var PyTime = class _PyTime extends PyDate {
1756
- constructor(hour, minute, second) {
1757
- const now = /* @__PURE__ */ new Date();
1758
- const year = now.getFullYear();
1759
- const month = now.getMonth() + 1;
1760
- const day = now.getDate();
1761
- super(year, month, day);
1762
- this.hour = hour;
1763
- this.minute = minute;
1764
- this.second = second;
1765
- this.hour = hour;
1766
- this.minute = minute;
1767
- this.second = second;
1768
- }
1769
- static create(...args) {
1770
- const namedArgs = parseArgs(args, ["hour", "minute", "second"]);
1771
- const hour = namedArgs.hour || 0;
1772
- const minute = namedArgs.minute || 0;
1773
- const second = namedArgs.second || 0;
1774
- return new _PyTime(hour, minute, second);
1775
- }
1776
- strftime(format) {
1777
- return format.replace(/%([A-Za-z])/g, (m, c) => {
1778
- switch (c) {
1779
- case "Y":
1780
- return fmt4(this.year);
1781
- case "m":
1782
- return fmt2(this.month);
1783
- case "d":
1784
- return fmt2(this.day);
1785
- case "H":
1786
- return fmt2(this.hour);
1787
- case "M":
1788
- return fmt2(this.minute);
1789
- case "S":
1790
- return fmt2(this.second);
1791
- default:
1792
- throw new ValueError(`No known conversion for ${m}`);
1793
- }
1794
- });
1795
- }
1796
- toJSON() {
1797
- return this.strftime("%H:%M:%S");
1798
- }
1799
- };
1800
- var DAYS_IN_YEAR = [
1801
- 31,
1802
- 59,
1803
- 90,
1804
- 120,
1805
- 151,
1806
- 181,
1807
- 212,
1808
- 243,
1809
- 273,
1810
- 304,
1811
- 334,
1812
- 366
1813
- ];
1814
- var TIME_PERIODS = ["hour", "minute", "second"];
1815
- var PERIODS = ["year", "month", "day", ...TIME_PERIODS];
1816
- var RELATIVE_KEYS = "years months weeks days hours minutes seconds microseconds leapdays".split(
1817
- " "
1818
- );
1819
- var ABSOLUTE_KEYS = "year month day hour minute second microsecond weekday nlyearday yearday".split(
1820
- " "
1821
- );
1822
- var argsSpec = ["dt1", "dt2"];
1823
- var PyRelativeDelta = class _PyRelativeDelta {
1824
- static create(...args) {
1825
- const params = parseArgs(args, argsSpec);
1826
- if ("dt1" in params) {
1827
- throw new Error("relativedelta(dt1, dt2) is not supported for now");
1828
- }
1829
- for (const period of PERIODS) {
1830
- if (period in params) {
1831
- const val = params[period];
1832
- assert(val >= 0, `${period} ${val} is out of range`);
1833
- }
1834
- }
1835
- for (const key of RELATIVE_KEYS) {
1836
- params[key] = params[key] || 0;
1837
- }
1838
- for (const key of ABSOLUTE_KEYS) {
1839
- params[key] = key in params ? params[key] : null;
1840
- }
1841
- params.days += 7 * params.weeks;
1842
- let yearDay = 0;
1843
- if (params.nlyearday) {
1844
- yearDay = params.nlyearday;
1845
- } else if (params.yearday) {
1846
- yearDay = params.yearday;
1847
- if (yearDay > 59) {
1848
- params.leapDays = -1;
1849
- }
1850
- }
1851
- if (yearDay) {
1852
- for (let monthIndex = 0; monthIndex < DAYS_IN_YEAR.length; monthIndex++) {
1853
- if (yearDay <= DAYS_IN_YEAR[monthIndex]) {
1854
- params.month = monthIndex + 1;
1855
- if (monthIndex === 0) {
1856
- params.day = yearDay;
1857
- } else {
1858
- params.day = yearDay - DAYS_IN_YEAR[monthIndex - 1];
1859
- }
1860
- break;
1861
- }
1862
- }
1863
- }
1864
- return new _PyRelativeDelta(params);
1865
- }
1866
- static add(date, delta) {
1867
- if (!(date instanceof PyDate || date instanceof PyDateTime)) {
1868
- throw new NotSupportedError();
1869
- }
1870
- const s = tmxxx(
1871
- (delta.year || date.year) + delta.years,
1872
- (delta.month || date.month) + delta.months,
1873
- delta.day || date.day,
1874
- delta.hour || (date instanceof PyDateTime ? date.hour : 0),
1875
- delta.minute || (date instanceof PyDateTime ? date.minute : 0),
1876
- delta.second || (date instanceof PyDateTime ? date.second : 0),
1877
- delta.microseconds || (date instanceof PyDateTime ? date.microsecond : 0)
1878
- );
1879
- const newDateTime = new PyDateTime(
1880
- s.year,
1881
- s.month,
1882
- s.day,
1883
- s.hour,
1884
- s.minute,
1885
- s.second,
1886
- s.microsecond
1887
- );
1888
- let leapDays = 0;
1889
- if (delta.leapDays && newDateTime.month > 2 && isLeap(newDateTime.year)) {
1890
- leapDays = delta.leapDays;
1891
- }
1892
- const temp = newDateTime.add(
1893
- PyTimeDelta.create({
1894
- days: delta.days + leapDays,
1895
- hours: delta.hours,
1896
- minutes: delta.minutes,
1897
- seconds: delta.seconds,
1898
- microseconds: delta.microseconds
1899
- })
1900
- );
1901
- const hasTime = Boolean(
1902
- temp.hour || temp.minute || temp.second || temp.microsecond
1903
- );
1904
- const returnDate = !hasTime && date instanceof PyDate ? new PyDate(temp.year, temp.month, temp.day) : temp;
1905
- if (delta.weekday !== null) {
1906
- const wantedDow = delta.weekday + 1;
1907
- const _date = new Date(
1908
- returnDate.year,
1909
- returnDate.month - 1,
1910
- returnDate.day
1911
- );
1912
- const days = (7 - _date.getDay() + wantedDow) % 7;
1913
- return returnDate.add(new PyTimeDelta(days, 0, 0));
1914
- }
1915
- return returnDate;
1916
- }
1917
- static substract(date, delta) {
1918
- return _PyRelativeDelta.add(date, delta.negate());
1919
- }
1920
- constructor(params = {}, sign = 1) {
1921
- this.years = sign * params.years;
1922
- this.months = sign * params.months;
1923
- this.days = sign * params.days;
1924
- this.hours = sign * params.hours;
1925
- this.minutes = sign * params.minutes;
1926
- this.seconds = sign * params.seconds;
1927
- this.microseconds = sign * params.microseconds;
1928
- this.leapDays = params.leapDays;
1929
- this.year = params.year;
1930
- this.month = params.month;
1931
- this.day = params.day;
1932
- this.hour = params.hour;
1933
- this.minute = params.minute;
1934
- this.second = params.second;
1935
- this.microsecond = params.microsecond;
1936
- this.weekday = params.weekday;
1937
- }
1938
- years;
1939
- months;
1940
- days;
1941
- hours;
1942
- minutes;
1943
- seconds;
1944
- microseconds;
1945
- leapDays;
1946
- year;
1947
- month;
1948
- day;
1949
- hour;
1950
- minute;
1951
- second;
1952
- microsecond;
1953
- weekday;
1954
- negate() {
1955
- return new _PyRelativeDelta(this, -1);
1956
- }
1957
- isEqual() {
1958
- throw new NotSupportedError();
1959
- }
1960
- };
1961
- var TIME_DELTA_KEYS = "weeks days hours minutes seconds milliseconds microseconds".split(" ");
1962
- function modf(x) {
1963
- const mod = x % 1;
1964
- return [mod < 0 ? mod + 1 : mod, Math.floor(x)];
1965
- }
1966
- var PyTimeDelta = class _PyTimeDelta {
1967
- constructor(days, seconds, microseconds) {
1968
- this.days = days;
1969
- this.seconds = seconds;
1970
- this.microseconds = microseconds;
1971
- }
1972
- static create(...args) {
1973
- const namedArgs = parseArgs(args, ["days", "seconds", "microseconds"]);
1974
- for (const key of TIME_DELTA_KEYS) {
1975
- namedArgs[key] = namedArgs[key] || 0;
1976
- }
1977
- let d = 0;
1978
- let s = 0;
1979
- let us = 0;
1980
- const days = namedArgs.days + namedArgs.weeks * 7;
1981
- let seconds = namedArgs.seconds + 60 * namedArgs.minutes + 3600 * namedArgs.hours;
1982
- let microseconds = namedArgs.microseconds + 1e3 * namedArgs.milliseconds;
1983
- const [dFrac, dInt] = modf(days);
1984
- d = dInt;
1985
- let daysecondsfrac = 0;
1986
- if (dFrac) {
1987
- const [dsFrac, dsInt] = modf(dFrac * 24 * 3600);
1988
- s = dsInt;
1989
- daysecondsfrac = dsFrac;
1990
- }
1991
- const [sFrac, sInt] = modf(seconds);
1992
- seconds = sInt;
1993
- const secondsfrac = sFrac + daysecondsfrac;
1994
- divmod(seconds, 24 * 3600, (days2, seconds2) => {
1995
- d += days2;
1996
- s += seconds2;
1997
- });
1998
- microseconds += secondsfrac * 1e6;
1999
- divmod(microseconds, 1e6, (seconds2, microseconds2) => {
2000
- divmod(seconds2, 24 * 3600, (days2, seconds3) => {
2001
- d += days2;
2002
- s += seconds3;
2003
- us += Math.round(microseconds2);
2004
- });
2005
- });
2006
- return new _PyTimeDelta(d, s, us);
2007
- }
2008
- add(other) {
2009
- return _PyTimeDelta.create({
2010
- days: this.days + other.days,
2011
- seconds: this.seconds + other.seconds,
2012
- microseconds: this.microseconds + other.microseconds
2013
- });
2014
- }
2015
- divide(n) {
2016
- const us = (this.days * 24 * 3600 + this.seconds) * 1e6 + this.microseconds;
2017
- return _PyTimeDelta.create({ microseconds: Math.floor(us / n) });
2018
- }
2019
- isEqual(other) {
2020
- if (!(other instanceof _PyTimeDelta)) {
2021
- return false;
2022
- }
2023
- return this.days === other.days && this.seconds === other.seconds && this.microseconds === other.microseconds;
2024
- }
2025
- isTrue() {
2026
- return this.days !== 0 || this.seconds !== 0 || this.microseconds !== 0;
2027
- }
2028
- multiply(n) {
2029
- return _PyTimeDelta.create({
2030
- days: n * this.days,
2031
- seconds: n * this.seconds,
2032
- microseconds: n * this.microseconds
2033
- });
2034
- }
2035
- negate() {
2036
- return _PyTimeDelta.create({
2037
- days: -this.days,
2038
- seconds: -this.seconds,
2039
- microseconds: -this.microseconds
2040
- });
2041
- }
2042
- substract(other) {
2043
- return _PyTimeDelta.create({
2044
- days: this.days - other.days,
2045
- seconds: this.seconds - other.seconds,
2046
- microseconds: this.microseconds - other.microseconds
2047
- });
2048
- }
2049
- total_seconds() {
2050
- return this.days * 86400 + this.seconds + this.microseconds / 1e6;
2051
- }
2052
- };
2053
-
2054
- // src/utils/domain/py_builtin.ts
2055
- var EvaluationError = class extends Error {
2056
- constructor(message) {
2057
- super(message);
2058
- this.name = "EvaluationError";
2059
- }
2060
- };
2061
- function execOnIterable(iterable, func) {
2062
- if (iterable === null) {
2063
- throw new EvaluationError("value not iterable");
2064
- }
2065
- if (typeof iterable === "object" && !Array.isArray(iterable) && !(iterable instanceof Set)) {
2066
- iterable = Object.keys(iterable);
2067
- }
2068
- if (typeof iterable?.[Symbol.iterator] !== "function") {
2069
- throw new EvaluationError("value not iterable");
2070
- }
2071
- return func(iterable);
2072
- }
2073
- var BUILTINS = {
2074
- /**
2075
- * @param {any} value
2076
- * @returns {boolean}
2077
- */
2078
- bool(value) {
2079
- switch (typeof value) {
2080
- case "number":
2081
- return value !== 0;
2082
- case "string":
2083
- return value !== "";
2084
- case "boolean":
2085
- return value;
2086
- case "object":
2087
- if (value === null || value === void 0) {
2088
- return false;
2089
- }
2090
- if ("isTrue" in value && typeof value.isTrue === "function") {
2091
- return value.isTrue();
2092
- }
2093
- if (value instanceof Array) {
2094
- return !!value.length;
2095
- }
2096
- if (value instanceof Set) {
2097
- return !!value.size;
2098
- }
2099
- return Object.keys(value).length !== 0;
2100
- default:
2101
- return true;
2102
- }
2103
- },
2104
- set(iterable) {
2105
- if (arguments.length > 2) {
2106
- throw new EvaluationError(
2107
- `set expected at most 1 argument, got (${arguments.length - 1})`
2108
- );
2109
- }
2110
- return execOnIterable(
2111
- iterable,
2112
- (iterable2) => new Set(iterable2)
2113
- );
2114
- },
2115
- time: {
2116
- strftime(format) {
2117
- return PyDateTime.now().strftime(format);
2118
- }
2119
- },
2120
- context_today() {
2121
- return PyDate.today();
2122
- },
2123
- get current_date() {
2124
- return this.today;
2125
- },
2126
- get today() {
2127
- return PyDate.today().strftime("%Y-%m-%d");
2128
- },
2129
- get now() {
2130
- return PyDateTime.now().strftime("%Y-%m-%d %H:%M:%S");
2131
- },
2132
- datetime: {
2133
- time: PyTime,
2134
- timedelta: PyTimeDelta,
2135
- datetime: PyDateTime,
2136
- date: PyDate
2137
- },
2138
- relativedelta: PyRelativeDelta,
2139
- true: true,
2140
- false: false
2141
- };
2142
-
2143
- // src/utils/domain/py_utils.ts
2144
- function toPyValue(value) {
2145
- switch (typeof value) {
2146
- case "string":
2147
- return { type: 1, value };
2148
- case "number":
2149
- return { type: 0, value };
2150
- case "boolean":
2151
- return { type: 2, value };
2152
- case "object":
2153
- if (Array.isArray(value)) {
2154
- return { type: 4, value: value.map(toPyValue) };
2155
- } else if (value === null) {
2156
- return {
2157
- type: 3
2158
- /* None */
2159
- };
2160
- } else if (value instanceof Date) {
2161
- return {
2162
- type: 1,
2163
- value: String(PyDateTime.convertDate(value))
2164
- };
2165
- } else if (value instanceof PyDate || value instanceof PyDateTime) {
2166
- return { type: 1, value };
2167
- } else {
2168
- const content = {};
2169
- for (const key in value) {
2170
- content[key] = toPyValue(value[key]);
2171
- }
2172
- return { type: 11, value: content };
2173
- }
2174
- default:
2175
- throw new Error("Invalid type");
2176
- }
2177
- }
2178
- function formatAST(ast, lbp = 0) {
2179
- switch (ast.type) {
2180
- case 3:
2181
- return "None";
2182
- case 1:
2183
- return JSON.stringify(ast.value);
2184
- case 0:
2185
- return String(ast.value);
2186
- case 2:
2187
- return ast.value ? "True" : "False";
2188
- case 4:
2189
- return `[${ast.value.map(formatAST).join(", ")}]`;
2190
- case 6:
2191
- if (ast.op === "not") {
2192
- return `not ${formatAST(ast.right, 50)}`;
2193
- }
2194
- return `${ast.op}${formatAST(ast.right, 130)}`;
2195
- case 7:
2196
- const abp = bp(ast.op);
2197
- const binaryStr = `${formatAST(ast.left, abp)} ${ast.op} ${formatAST(ast.right, abp)}`;
2198
- return abp < lbp ? `(${binaryStr})` : binaryStr;
2199
- case 11:
2200
- const pairs = [];
2201
- for (const k in ast.value) {
2202
- pairs.push(`"${k}": ${formatAST(ast.value[k])}`);
2203
- }
2204
- return `{${pairs.join(", ")}}`;
2205
- case 10:
2206
- return `(${ast.value.map(formatAST).join(", ")})`;
2207
- case 5:
2208
- return ast.value;
2209
- case 12:
2210
- return `${formatAST(ast.target)}[${formatAST(ast.key)}]`;
2211
- case 13:
2212
- const { ifTrue, condition, ifFalse } = ast;
2213
- return `${formatAST(ifTrue)} if ${formatAST(condition)} else ${formatAST(ifFalse)}`;
2214
- case 14:
2215
- const boolAbp = bp(ast.op);
2216
- const boolStr = `${formatAST(ast.left, boolAbp)} ${ast.op} ${formatAST(ast.right, boolAbp)}`;
2217
- return boolAbp < lbp ? `(${boolStr})` : boolStr;
2218
- case 15:
2219
- return `${formatAST(ast.obj, 150)}.${ast.key}`;
2220
- case 8:
2221
- const args = ast.args.map(formatAST);
2222
- const kwargs = [];
2223
- for (const kwarg in ast.kwargs) {
2224
- kwargs.push(`${kwarg} = ${formatAST(ast.kwargs[kwarg])}`);
2225
- }
2226
- const argStr = args.concat(kwargs).join(", ");
2227
- return `${formatAST(ast.fn)}(${argStr})`;
2228
- default:
2229
- throw new Error("invalid expression: " + JSON.stringify(ast));
2230
- }
2231
- }
2232
- var PY_DICT = /* @__PURE__ */ Object.create(null);
2233
- function toPyDict(obj) {
2234
- return new Proxy(obj, {
2235
- getPrototypeOf() {
2236
- return PY_DICT;
2237
- }
2238
- });
2239
- }
2240
-
2241
- // src/utils/domain/py_interpreter.ts
2242
- var isTrue = BUILTINS.bool;
2243
- function applyUnaryOp(ast, context) {
2244
- const value = evaluate(ast.right, context);
2245
- switch (ast.op) {
2246
- case "-":
2247
- if (value instanceof Object && "negate" in value) {
2248
- return value.negate();
2249
- }
2250
- return -value;
2251
- case "+":
2252
- return value;
2253
- case "not":
2254
- return !isTrue(value);
2255
- default:
2256
- throw new EvaluationError(`Unknown unary operator: ${ast.op}`);
2257
- }
2258
- }
2259
- function pytypeIndex(val) {
2260
- switch (typeof val) {
2261
- case "object":
2262
- return val === null ? 1 : Array.isArray(val) ? 5 : 3;
2263
- case "number":
2264
- return 2;
2265
- case "string":
2266
- return 4;
2267
- default:
2268
- throw new EvaluationError(`Unknown type: ${typeof val}`);
2269
- }
2270
- }
2271
- function isLess(left, right) {
2272
- if (typeof left === "number" && typeof right === "number") {
2273
- return left < right;
2274
- }
2275
- if (typeof left === "boolean") {
2276
- left = left ? 1 : 0;
2277
- }
2278
- if (typeof right === "boolean") {
2279
- right = right ? 1 : 0;
2280
- }
2281
- const leftIndex = pytypeIndex(left);
2282
- const rightIndex = pytypeIndex(right);
2283
- if (leftIndex === rightIndex) {
2284
- return left < right;
2285
- }
2286
- return leftIndex < rightIndex;
2287
- }
2288
- function isEqual(left, right) {
2289
- if (typeof left !== typeof right) {
2290
- if (typeof left === "boolean" && typeof right === "number") {
2291
- return right === (left ? 1 : 0);
2292
- }
2293
- if (typeof left === "number" && typeof right === "boolean") {
2294
- return left === (right ? 1 : 0);
2295
- }
2296
- return false;
2297
- }
2298
- if (left instanceof Object && "isEqual" in left) {
2299
- return left.isEqual(right);
2300
- }
2301
- return left === right;
2302
- }
2303
- function isIn(left, right) {
2304
- if (Array.isArray(right)) {
2305
- return right.includes(left);
2306
- }
2307
- if (typeof right === "string" && typeof left === "string") {
2308
- return right.includes(left);
2309
- }
2310
- if (typeof right === "object") {
2311
- return left in right;
2312
- }
2313
- return false;
2314
- }
2315
- function applyBinaryOp(ast, context) {
2316
- const left = evaluate(ast.left, context);
2317
- const right = evaluate(ast.right, context);
2318
- switch (ast.op) {
2319
- case "+": {
2320
- const relativeDeltaOnLeft = left instanceof PyRelativeDelta;
2321
- const relativeDeltaOnRight = right instanceof PyRelativeDelta;
2322
- if (relativeDeltaOnLeft || relativeDeltaOnRight) {
2323
- const date = relativeDeltaOnLeft ? right : left;
2324
- const delta = relativeDeltaOnLeft ? left : right;
2325
- return PyRelativeDelta.add(date, delta);
2326
- }
2327
- const timeDeltaOnLeft = left instanceof PyTimeDelta;
2328
- const timeDeltaOnRight = right instanceof PyTimeDelta;
2329
- if (timeDeltaOnLeft && timeDeltaOnRight) {
2330
- return left.add(right);
2331
- }
2332
- if (timeDeltaOnLeft) {
2333
- if (right instanceof PyDate || right instanceof PyDateTime) {
2334
- return right.add(left);
2335
- } else {
2336
- throw new NotSupportedError();
2337
- }
2338
- }
2339
- if (timeDeltaOnRight) {
2340
- if (left instanceof PyDate || left instanceof PyDateTime) {
2341
- return left.add(right);
2342
- } else {
2343
- throw new NotSupportedError();
2344
- }
2345
- }
2346
- if (left instanceof Array && right instanceof Array) {
2347
- return [...left, ...right];
2348
- }
2349
- return left + right;
2350
- }
2351
- case "-": {
2352
- const isRightDelta = right instanceof PyRelativeDelta;
2353
- if (isRightDelta) {
2354
- return PyRelativeDelta.substract(left, right);
2355
- }
2356
- const timeDeltaOnRight = right instanceof PyTimeDelta;
2357
- if (timeDeltaOnRight) {
2358
- if (left instanceof PyTimeDelta) {
2359
- return left.substract(right);
2360
- } else if (left instanceof PyDate || left instanceof PyDateTime) {
2361
- return left.substract(right);
2362
- } else {
2363
- throw new NotSupportedError();
2364
- }
2365
- }
2366
- if (left instanceof PyDate) {
2367
- return left.substract(right);
2368
- }
2369
- return left - right;
2370
- }
2371
- case "*": {
2372
- const timeDeltaOnLeft = left instanceof PyTimeDelta;
2373
- const timeDeltaOnRight = right instanceof PyTimeDelta;
2374
- if (timeDeltaOnLeft || timeDeltaOnRight) {
2375
- const number = timeDeltaOnLeft ? right : left;
2376
- const delta = timeDeltaOnLeft ? left : right;
2377
- return delta.multiply(number);
2378
- }
2379
- return left * right;
2380
- }
2381
- case "/":
2382
- return left / right;
2383
- case "%":
2384
- return left % right;
2385
- case "//":
2386
- if (left instanceof PyTimeDelta) {
2387
- return left.divide(right);
2388
- }
2389
- return Math.floor(left / right);
2390
- case "**":
2391
- return left ** right;
2392
- case "==":
2393
- return isEqual(left, right);
2394
- case "<>":
2395
- case "!=":
2396
- return !isEqual(left, right);
2397
- case "<":
2398
- return isLess(left, right);
2399
- case ">":
2400
- return isLess(right, left);
2401
- case ">=":
2402
- return isEqual(left, right) || isLess(right, left);
2403
- case "<=":
2404
- return isEqual(left, right) || isLess(left, right);
2405
- case "in":
2406
- return isIn(left, right);
2407
- case "not in":
2408
- return !isIn(left, right);
2409
- default:
2410
- throw new EvaluationError(`Unknown binary operator: ${ast.op}`);
2411
- }
2412
- }
2413
- var DICT = {
2414
- get(...args) {
2415
- const { key, defValue } = parseArgs(args, ["key", "defValue"]);
2416
- const self = this;
2417
- if (key in self) {
2418
- return self[key];
2419
- } else if (defValue !== void 0) {
2420
- return defValue;
2421
- }
2422
- return null;
2423
- }
2424
- };
2425
- var STRING = {
2426
- lower() {
2427
- return this.toLowerCase();
2428
- },
2429
- upper() {
2430
- return this.toUpperCase();
2431
- }
2432
- };
2433
- function applyFunc(key, func, set, ...args) {
2434
- if (args.length === 1) {
2435
- return new Set(set);
2436
- }
2437
- if (args.length > 2) {
2438
- throw new EvaluationError(
2439
- `${key}: py_js supports at most 1 argument, got (${args.length - 1})`
2440
- );
2441
- }
2442
- return execOnIterable(args[0], func);
2443
- }
2444
- var SET = {
2445
- intersection(...args) {
2446
- return applyFunc(
2447
- "intersection",
2448
- (iterable) => {
2449
- const intersection = /* @__PURE__ */ new Set();
2450
- for (const i of iterable) {
2451
- if (this.has(i)) {
2452
- intersection.add(i);
2453
- }
2454
- }
2455
- return intersection;
2456
- },
2457
- this,
2458
- ...args
2459
- );
2460
- },
2461
- difference(...args) {
2462
- return applyFunc(
2463
- "difference",
2464
- (iterable) => {
2465
- iterable = new Set(iterable);
2466
- const difference = /* @__PURE__ */ new Set();
2467
- for (const e of this) {
2468
- if (!iterable.has(e)) {
2469
- difference.add(e);
2470
- }
2471
- }
2472
- return difference;
2473
- },
2474
- this,
2475
- ...args
2476
- );
2477
- },
2478
- union(...args) {
2479
- return applyFunc(
2480
- "union",
2481
- (iterable) => {
2482
- return /* @__PURE__ */ new Set([...this, ...iterable]);
2483
- },
2484
- this,
2485
- ...args
2486
- );
2487
- }
2488
- };
2489
- function methods(_class) {
2490
- return Object.getOwnPropertyNames(_class.prototype).map(
2491
- (prop) => _class.prototype[prop]
2492
- );
2493
- }
2494
- var allowedFns = /* @__PURE__ */ new Set([
2495
- BUILTINS.time.strftime,
2496
- BUILTINS.set,
2497
- BUILTINS.bool,
2498
- BUILTINS.context_today,
2499
- BUILTINS.datetime.datetime.now,
2500
- BUILTINS.datetime.datetime.combine,
2501
- BUILTINS.datetime.date.today,
2502
- ...methods(BUILTINS.relativedelta),
2503
- ...Object.values(BUILTINS.datetime).flatMap((obj) => methods(obj)),
2504
- ...Object.values(SET),
2505
- ...Object.values(DICT),
2506
- ...Object.values(STRING)
2507
- ]);
2508
- var unboundFn = /* @__PURE__ */ Symbol("unbound function");
2509
- function evaluate(ast, context = {}) {
2510
- const dicts = /* @__PURE__ */ new Set();
2511
- let pyContext;
2512
- const evalContext = Object.create(context);
2513
- if (!evalContext?.context) {
2514
- Object.defineProperty(evalContext, "context", {
2515
- get() {
2516
- if (!pyContext) {
2517
- pyContext = toPyDict(context);
2518
- }
2519
- return pyContext;
2520
- }
2521
- });
2522
- }
2523
- function _innerEvaluate(ast2) {
2524
- switch (ast2?.type) {
2525
- case 0:
2526
- // Number
2527
- case 1:
2528
- return ast2.value;
2529
- case 5:
2530
- if (ast2.value in evalContext) {
2531
- if (typeof evalContext[ast2.value] === "object" && evalContext[ast2.value]?.id && ast2?.value !== "parent") {
2532
- return evalContext[ast2.value]?.id;
2533
- }
2534
- return evalContext[ast2.value] ?? false;
2535
- } else if (ast2.value in BUILTINS) {
2536
- return BUILTINS[ast2.value];
2537
- } else {
2538
- return false;
2539
- }
2540
- case 3:
2541
- return null;
2542
- case 2:
2543
- return ast2.value;
2544
- case 6:
2545
- return applyUnaryOp(ast2, evalContext);
2546
- case 7:
2547
- return applyBinaryOp(ast2, evalContext);
2548
- case 14:
2549
- const left = _evaluate(ast2.left);
2550
- if (ast2.op === "and") {
2551
- return isTrue(left) ? _evaluate(ast2.right) : left;
2552
- } else {
2553
- return isTrue(left) ? left : _evaluate(ast2.right);
2554
- }
2555
- case 4:
2556
- // List
2557
- case 10:
2558
- return ast2.value.map(_evaluate);
2559
- case 11:
2560
- const dict = {};
2561
- for (const key2 in ast2.value) {
2562
- dict[key2] = _evaluate(ast2.value[key2]);
2563
- }
2564
- dicts.add(dict);
2565
- return dict;
2566
- case 8:
2567
- const fnValue = _evaluate(ast2.fn);
2568
- const args = ast2.args.map(_evaluate);
2569
- const kwargs = {};
2570
- for (const kwarg in ast2.kwargs) {
2571
- kwargs[kwarg] = _evaluate(ast2?.kwargs[kwarg]);
2572
- }
2573
- if (fnValue === PyDate || fnValue === PyDateTime || fnValue === PyTime || fnValue === PyRelativeDelta || fnValue === PyTimeDelta) {
2574
- return fnValue.create(...args, kwargs);
2575
- }
2576
- return fnValue(...args, kwargs);
2577
- case 12:
2578
- const dictVal = _evaluate(ast2.target);
2579
- const key = _evaluate(ast2.key);
2580
- return dictVal[key];
2581
- case 13:
2582
- if (isTrue(_evaluate(ast2.condition))) {
2583
- return _evaluate(ast2.ifTrue);
2584
- } else {
2585
- return _evaluate(ast2.ifFalse);
2586
- }
2587
- case 15:
2588
- let leftVal = _evaluate(ast2.obj);
2589
- let result;
2590
- if (dicts.has(leftVal) || Object.isPrototypeOf.call(PY_DICT, leftVal)) {
2591
- result = DICT[ast2.key];
2592
- } else if (typeof leftVal === "string") {
2593
- result = STRING[ast2.key];
2594
- } else if (leftVal instanceof Set) {
2595
- result = SET[ast2.key];
2596
- } else if (ast2.key === "get" && typeof leftVal === "object") {
2597
- result = DICT[ast2.key];
2598
- leftVal = toPyDict(leftVal);
2599
- } else if (typeof leftVal === "number") {
2600
- result = leftVal;
2601
- } else if (Array.isArray(leftVal[ast2.key])) {
2602
- result = leftVal[ast2.key]?.map(
2603
- (value) => value?.id ?? value
2604
- );
2605
- } else {
2606
- result = leftVal[ast2.key]?.id ?? leftVal[ast2.key] ?? false;
2607
- }
2608
- if (typeof result === "function") {
2609
- const bound = result.bind(leftVal);
2610
- bound[unboundFn] = result;
2611
- return bound;
2612
- }
2613
- return result;
2614
- default:
2615
- throw new EvaluationError(`AST of type ${ast2.type} cannot be evaluated`);
2616
- }
2617
- }
2618
- function _evaluate(ast2) {
2619
- const val = _innerEvaluate(ast2);
2620
- if (typeof val === "function" && !allowedFns.has(val) && !allowedFns.has(val[unboundFn])) {
2621
- throw new Error("Invalid Function Call");
2622
- }
2623
- return val;
2624
- }
2625
- return _evaluate(ast);
2626
- }
2627
-
2628
- // src/utils/domain/py.ts
2629
- function parseExpr(expr) {
2630
- const tokens = tokenize(expr);
2631
- return parse(tokens);
2632
- }
2633
-
2634
- // src/utils/domain/objects.ts
2635
- function shallowEqual(obj1, obj2, comparisonFn = (a, b) => a === b) {
2636
- if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") {
2637
- return obj1 === obj2;
2638
- }
2639
- const obj1Keys = Object.keys(obj1);
2640
- return obj1Keys.length === Object.keys(obj2).length && obj1Keys.every((key) => comparisonFn(obj1[key], obj2[key]));
2641
- }
2642
-
2643
- // src/utils/domain/arrays.ts
2644
- var shallowEqual2 = shallowEqual;
2645
-
2646
- // src/utils/domain/strings.ts
2647
- function escapeRegExp(str) {
2648
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2649
- }
2650
-
2651
- // src/utils/domain/domain.ts
2652
- var InvalidDomainError = class extends Error {
2653
- };
2654
- var Domain = class _Domain {
2655
- ast = { type: -1, value: null };
2656
- static TRUE;
2657
- static FALSE;
2658
- static combine(domains, operator) {
2659
- if (domains.length === 0) {
2660
- return new _Domain([]);
2661
- }
2662
- const domain1 = domains[0] instanceof _Domain ? domains[0] : new _Domain(domains[0]);
2663
- if (domains.length === 1) {
2664
- return domain1;
2665
- }
2666
- const domain2 = _Domain.combine(domains.slice(1), operator);
2667
- const result = new _Domain([]);
2668
- const astValues1 = domain1.ast.value;
2669
- const astValues2 = domain2.ast.value;
2670
- const op = operator === "AND" ? "&" : "|";
2671
- const combinedAST = {
2672
- type: 4,
2673
- value: astValues1.concat(astValues2)
2674
- };
2675
- result.ast = normalizeDomainAST(combinedAST, op);
2676
- return result;
2677
- }
2678
- static and(domains) {
2679
- return _Domain.combine(domains, "AND");
2680
- }
2681
- static or(domains) {
2682
- return _Domain.combine(domains, "OR");
2683
- }
2684
- static not(domain) {
2685
- const result = new _Domain(domain);
2686
- result.ast.value.unshift({ type: 1, value: "!" });
2687
- return result;
2688
- }
2689
- static removeDomainLeaves(domain, keysToRemove) {
2690
- function processLeaf(elements, idx, operatorCtx, newDomain2) {
2691
- const leaf = elements[idx];
2692
- if (leaf.type === 10) {
2693
- if (keysToRemove.includes(leaf.value[0].value)) {
2694
- if (operatorCtx === "&") {
2695
- newDomain2.ast.value.push(..._Domain.TRUE.ast.value);
2696
- } else if (operatorCtx === "|") {
2697
- newDomain2.ast.value.push(..._Domain.FALSE.ast.value);
2698
- }
2699
- } else {
2700
- newDomain2.ast.value.push(leaf);
2701
- }
2702
- return 1;
2703
- } else if (leaf.type === 1) {
2704
- if (leaf.value === "|" && elements[idx + 1].type === 10 && elements[idx + 2].type === 10 && keysToRemove.includes(elements[idx + 1].value[0].value) && keysToRemove.includes(elements[idx + 2].value[0].value)) {
2705
- newDomain2.ast.value.push(..._Domain.TRUE.ast.value);
2706
- return 3;
2707
- }
2708
- newDomain2.ast.value.push(leaf);
2709
- if (leaf.value === "!") {
2710
- return 1 + processLeaf(elements, idx + 1, "&", newDomain2);
2711
- }
2712
- const firstLeafSkip = processLeaf(
2713
- elements,
2714
- idx + 1,
2715
- leaf.value,
2716
- newDomain2
2717
- );
2718
- const secondLeafSkip = processLeaf(
2719
- elements,
2720
- idx + 1 + firstLeafSkip,
2721
- leaf.value,
2722
- newDomain2
2723
- );
2724
- return 1 + firstLeafSkip + secondLeafSkip;
2725
- }
2726
- return 0;
2727
- }
2728
- const d = new _Domain(domain);
2729
- if (d.ast.value.length === 0) {
2730
- return d;
2731
- }
2732
- const newDomain = new _Domain([]);
2733
- processLeaf(d.ast.value, 0, "&", newDomain);
2734
- return newDomain;
2735
- }
2736
- constructor(descr = []) {
2737
- if (descr instanceof _Domain) {
2738
- return new _Domain(descr.toString());
2739
- } else {
2740
- let rawAST;
2741
- try {
2742
- rawAST = typeof descr === "string" ? parseExpr(descr) : toAST(descr);
2743
- } catch (error) {
2744
- throw new InvalidDomainError(
2745
- `Invalid domain representation: ${descr}`,
2746
- {
2747
- cause: error
2748
- }
2749
- );
2750
- }
2751
- this.ast = normalizeDomainAST(rawAST);
2752
- }
2753
- }
2754
- contains(record) {
2755
- const expr = evaluate(this.ast, record);
2756
- return matchDomain(record, expr);
2757
- }
2758
- toString() {
2759
- return formatAST(this.ast);
2760
- }
2761
- toList(context) {
2762
- return evaluate(this.ast, context);
2763
- }
2764
- toJson() {
2765
- try {
2766
- const evaluatedAsList = this.toList({});
2767
- const evaluatedDomain = new _Domain(evaluatedAsList);
2768
- if (evaluatedDomain.toString() === this.toString()) {
2769
- return evaluatedAsList;
2770
- }
2771
- return this.toString();
2772
- } catch {
2773
- return this.toString();
2774
- }
2775
- }
2776
- };
2777
- var TRUE_LEAF = [1, "=", 1];
2778
- var FALSE_LEAF = [0, "=", 1];
2779
- var TRUE_DOMAIN = new Domain([TRUE_LEAF]);
2780
- var FALSE_DOMAIN = new Domain([FALSE_LEAF]);
2781
- Domain.TRUE = TRUE_DOMAIN;
2782
- Domain.FALSE = FALSE_DOMAIN;
2783
- function toAST(domain) {
2784
- const elems = domain.map((elem) => {
2785
- switch (elem) {
2786
- case "!":
2787
- case "&":
2788
- case "|":
2789
- return { type: 1, value: elem };
2790
- default:
2791
- return {
2792
- type: 10,
2793
- value: elem.map(toPyValue)
2794
- };
2795
- }
2796
- });
2797
- return { type: 4, value: elems };
2798
- }
2799
- function normalizeDomainAST(domain, op = "&") {
2800
- if (domain.type !== 4) {
2801
- if (domain.type === 10) {
2802
- const value = domain.value;
2803
- if (value.findIndex((e) => e.type === 10) === -1 || !value.every((e) => e.type === 10 || e.type === 1)) {
2804
- throw new InvalidDomainError("Invalid domain AST");
2805
- }
2806
- } else {
2807
- throw new InvalidDomainError("Invalid domain AST");
2808
- }
2809
- }
2810
- if (domain.value.length === 0) {
2811
- return domain;
2812
- }
2813
- let expected = 1;
2814
- for (const child of domain.value) {
2815
- switch (child.type) {
2816
- case 1:
2817
- if (child.value === "&" || child.value === "|") {
2818
- expected++;
2819
- } else if (child.value !== "!") {
2820
- throw new InvalidDomainError("Invalid domain AST");
2821
- }
2822
- break;
2823
- case 4:
2824
- /* list */
2825
- case 10:
2826
- if (child.value.length === 3) {
2827
- expected--;
2828
- break;
2829
- }
2830
- throw new InvalidDomainError("Invalid domain AST");
2831
- default:
2832
- throw new InvalidDomainError("Invalid domain AST");
2833
- }
2834
- }
2835
- const values = domain.value.slice();
2836
- while (expected < 0) {
2837
- expected++;
2838
- values.unshift({ type: 1, value: op });
2839
- }
2840
- if (expected > 0) {
2841
- throw new InvalidDomainError(
2842
- `invalid domain ${formatAST(domain)} (missing ${expected} segment(s))`
2843
- );
2844
- }
2845
- return { type: 4, value: values };
2846
- }
2847
- function matchCondition(record, condition) {
2848
- if (typeof condition === "boolean") {
2849
- return condition;
2850
- }
2851
- const [field, operator, value] = condition;
2852
- if (typeof field === "string") {
2853
- const names = field.split(".");
2854
- if (names.length >= 2) {
2855
- return matchCondition(record[names[0]], [
2856
- names.slice(1).join("."),
2857
- operator,
2858
- value
2859
- ]);
2860
- }
2861
- }
2862
- let likeRegexp, ilikeRegexp;
2863
- if (["like", "not like", "ilike", "not ilike"].includes(operator)) {
2864
- likeRegexp = new RegExp(
2865
- `(.*)${escapeRegExp(value).replaceAll("%", "(.*)")}(.*)`,
2866
- "g"
2867
- );
2868
- ilikeRegexp = new RegExp(
2869
- `(.*)${escapeRegExp(value).replaceAll("%", "(.*)")}(.*)`,
2870
- "gi"
2871
- );
2872
- }
2873
- const fieldValue = typeof field === "number" ? field : record[field];
2874
- switch (operator) {
2875
- case "=?":
2876
- if ([false, null].includes(value)) {
2877
- return true;
2878
- }
2879
- // eslint-disable-next-line no-fallthrough
2880
- case "=":
2881
- case "==":
2882
- if (Array.isArray(fieldValue) && Array.isArray(value)) {
2883
- return shallowEqual2(fieldValue, value);
2884
- }
2885
- return fieldValue === value;
2886
- case "!=":
2887
- case "<>":
2888
- return !matchCondition(record, [field, "==", value]);
2889
- case "<":
2890
- return fieldValue < value;
2891
- case "<=":
2892
- return fieldValue <= value;
2893
- case ">":
2894
- return fieldValue > value;
2895
- case ">=":
2896
- return fieldValue >= value;
2897
- case "in": {
2898
- const val = Array.isArray(value) ? value : [value];
2899
- const fieldVal = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
2900
- return fieldVal.some((fv) => val.includes(fv));
2901
- }
2902
- case "not in": {
2903
- const val = Array.isArray(value) ? value : [value];
2904
- const fieldVal = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
2905
- return !fieldVal.some((fv) => val.includes(fv));
2906
- }
2907
- case "like":
2908
- if (fieldValue === false) {
2909
- return false;
2910
- }
2911
- return Boolean(fieldValue.match(likeRegexp));
2912
- case "not like":
2913
- if (fieldValue === false) {
2914
- return false;
2915
- }
2916
- return Boolean(!fieldValue.match(likeRegexp));
2917
- case "=like":
2918
- if (fieldValue === false) {
2919
- return false;
2920
- }
2921
- return new RegExp(escapeRegExp(value).replace(/%/g, ".*")).test(
2922
- fieldValue
2923
- );
2924
- case "ilike":
2925
- if (fieldValue === false) {
2926
- return false;
2927
- }
2928
- return Boolean(fieldValue.match(ilikeRegexp));
2929
- case "not ilike":
2930
- if (fieldValue === false) {
2931
- return false;
2932
- }
2933
- return Boolean(!fieldValue.match(ilikeRegexp));
2934
- case "=ilike":
2935
- if (fieldValue === false) {
2936
- return false;
2937
- }
2938
- return new RegExp(escapeRegExp(value).replace(/%/g, ".*"), "i").test(
2939
- fieldValue
2940
- );
2941
- }
2942
- throw new InvalidDomainError("could not match domain");
2943
- }
2944
- function makeOperators(record) {
2945
- const match = matchCondition.bind(null, record);
2946
- return {
2947
- "!": (x) => !match(x),
2948
- "&": (a, b) => match(a) && match(b),
2949
- "|": (a, b) => match(a) || match(b)
2950
- };
2951
- }
2952
- function matchDomain(record, domain) {
2953
- if (domain.length === 0) {
2954
- return true;
2955
- }
2956
- const operators = makeOperators(record);
2957
- const reversedDomain = Array.from(domain).reverse();
2958
- const condStack = [];
2959
- for (const item of reversedDomain) {
2960
- const operator = typeof item === "string" && operators[item];
2961
- if (operator) {
2962
- const operands = condStack.splice(-operator.length);
2963
- condStack.push(operator(...operands));
2964
- } else {
2965
- condStack.push(item);
2966
- }
2967
- }
2968
- return matchCondition(record, condStack.pop());
2969
- }
2970
-
2971
- // src/utils/function.ts
2972
- var toQueryString = (params) => {
2973
- return Object.keys(params).map(
2974
- (key) => encodeURIComponent(key) + "=" + encodeURIComponent(params[key].toString())
2975
- ).join("&");
2976
- };
2977
-
2978
- // src/services/action-service/index.ts
2979
- var ActionService = {
2980
- async loadAction({
2981
- idAction,
2982
- context
2983
- }) {
2984
- const env2 = getEnv();
2985
- const jsonData = {
2986
- action_id: idAction,
2987
- with_context: {
2988
- ...context
2989
- }
2990
- };
2991
- return env2.requests.post(`${"/load_action" /* LOAD_ACTION */}`, jsonData, {
2992
- headers: {
2993
- "Content-Type": "application/json"
2994
- }
2995
- });
2996
- },
2997
- async callButton({
2998
- model,
2999
- ids = [],
3000
- context,
3001
- method
3002
- }) {
3003
- try {
3004
- const env2 = getEnv();
3005
- const jsonData = {
3006
- model,
3007
- method,
3008
- ids,
3009
- with_context: context
3010
- };
3011
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3012
- headers: {
3013
- "Content-Type": "application/json"
3014
- }
3015
- });
3016
- } catch (error) {
3017
- console.error("Error when calling button action:", error);
3018
- throw error;
3019
- }
3020
- },
3021
- async removeRows({
3022
- model,
3023
- ids,
3024
- context
3025
- }) {
3026
- const env2 = getEnv();
3027
- const jsonData = {
3028
- model,
3029
- method: "unlink",
3030
- ids,
3031
- with_context: context
3032
- };
3033
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3034
- headers: {
3035
- "Content-Type": "application/json"
3036
- }
3037
- });
3038
- },
3039
- async duplicateRecord({
3040
- model,
3041
- id,
3042
- context
3043
- }) {
3044
- const env2 = getEnv();
3045
- const jsonData = {
3046
- model,
3047
- method: "copy",
3048
- ids: id,
3049
- with_context: context
3050
- };
3051
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3052
- headers: {
3053
- "Content-Type": "application/json"
3054
- }
3055
- });
3056
- },
3057
- async print({ id, report, db }) {
3058
- const env2 = getEnv();
3059
- const jsonData = {
3060
- report,
3061
- id,
3062
- type: "pdf",
3063
- file_response: true,
3064
- db
3065
- };
3066
- const queryString = toQueryString(jsonData);
3067
- const urlWithParams = `${"/report" /* REPORT_PATH */}?${queryString}`;
3068
- return env2.requests.get(urlWithParams, {
3069
- headers: {
3070
- "Content-Type": "application/json"
3071
- },
3072
- responseType: "arraybuffer"
3073
- });
3074
- },
3075
- async runAction({
3076
- idAction,
3077
- context
3078
- }) {
3079
- const env2 = getEnv();
3080
- const jsonData = {
3081
- action_id: idAction,
3082
- with_context: {
3083
- ...context
3084
- }
3085
- };
3086
- return env2.requests.post(`${"/run_action" /* RUN_ACTION_PATH */}`, jsonData, {
3087
- headers: {
3088
- "Content-Type": "application/json"
3089
- }
3090
- });
3091
- }
3092
- };
3093
- var action_service_default = ActionService;
3094
-
3095
- // src/services/auth-service/index.ts
3096
- var AuthService = {
3097
- async login(body) {
3098
- const env2 = getEnv();
3099
- const payload = Object.fromEntries(
3100
- Object.entries({
3101
- username: body.email,
3102
- password: body.password,
3103
- grant_type: env2?.config?.grantType || "",
3104
- client_id: env2?.config?.clientId || "",
3105
- client_secret: env2?.config?.clientSecret || ""
3106
- }).filter(([_, value]) => !!value)
3107
- );
3108
- const encodedData = new URLSearchParams(payload).toString();
3109
- return env2?.requests?.post(body.path, encodedData, {
3110
- headers: {
3111
- "Content-Type": "application/x-www-form-urlencoded"
3112
- }
3113
- });
3114
- },
3115
- async forgotPassword(email) {
3116
- const env2 = getEnv();
3117
- const bodyData = {
3118
- login: email,
3119
- url: `${window.location.origin}/reset-password`
3120
- };
3121
- return env2?.requests?.post("/reset_password" /* RESET_PASSWORD_PATH */, bodyData, {
3122
- headers: {
3123
- "Content-Type": "application/json"
3124
- }
3125
- });
3126
- },
3127
- async resetPassword(data, token) {
3128
- const env2 = getEnv();
3129
- const bodyData = {
3130
- token,
3131
- password: data.password,
3132
- new_password: data.confirmPassword
3133
- };
3134
- return env2?.requests?.post("/change_password" /* CHANGE_PASSWORD_PATH */, bodyData, {
3135
- headers: {
3136
- "Content-Type": "application/json"
3137
- }
3138
- });
3139
- },
3140
- async updatePassword(data, token) {
3141
- const env2 = getEnv();
3142
- const bodyData = {
3143
- token,
3144
- old_password: data.oldPassword,
3145
- new_password: data.newPassword
3146
- };
3147
- return env2?.requests?.post("/change_password_parent" /* UPDATE_PASSWORD_PATH */, bodyData, {
3148
- headers: {
3149
- "Content-Type": "application/json"
3150
- }
3151
- });
3152
- },
3153
- async isValidToken(token) {
3154
- const env2 = getEnv();
3155
- const bodyData = {
3156
- token
3157
- };
3158
- return env2?.requests?.post("/check_token" /* TOKEN */, bodyData, {
3159
- headers: {
3160
- "Content-Type": "application/json"
3161
- }
3162
- });
3163
- },
3164
- async loginSocial({
3165
- state,
3166
- access_token
3167
- }) {
3168
- const env2 = getEnv();
3169
- return env2?.requests?.post(
3170
- "/token/generate" /* GENTOKEN_SOCIAL */,
3171
- { state, access_token },
3172
- {
3173
- headers: {
3174
- "Content-Type": "application/json"
3175
- }
3176
- }
3177
- );
3178
- },
3179
- async getProviders(db) {
3180
- const env2 = getEnv();
3181
- return env2?.requests?.get("/oauth/providers", { params: { db } });
3182
- }
3183
- };
3184
- var auth_service_default = AuthService;
3185
-
3186
- // src/services/company-service/index.ts
3187
- var CompanyService = {
3188
- async getCurrentCompany() {
3189
- const env2 = getEnv();
3190
- return await env2.requests.get("/company" /* COMPANY_PATH */, {
3191
- headers: {
3192
- "Content-Type": "application/json"
3193
- }
3194
- });
3195
- },
3196
- async getInfoCompany(id) {
3197
- const env2 = getEnv();
3198
- const jsonData = {
3199
- ids: [id],
3200
- model: "res.company" /* COMPANY */,
3201
- method: "web_read" /* WEB_READ */,
3202
- kwargs: {
3203
- specification: {
3204
- primary_color: {},
3205
- secondary_color: {},
3206
- logo: {},
3207
- display_name: {},
3208
- secondary_logo: {}
3209
- }
3210
- }
3211
- };
3212
- return await env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3213
- headers: {
3214
- "Content-Type": "application/json"
3215
- }
3216
- });
3217
- }
3218
- };
3219
- var company_service_default = CompanyService;
3220
-
3221
- // src/services/excel-service/index.ts
3222
- var ExcelService = {
3223
- async uploadFile({ formData }) {
3224
- const env2 = getEnv();
3225
- return env2.requests.post(`${"/upload/file" /* UPLOAD_FILE_PATH */}`, formData, {
3226
- headers: {
3227
- "Content-Type": "multipart/form-data"
3228
- }
3229
- });
3230
- },
3231
- async uploadIdFile({ formData }) {
3232
- const env2 = getEnv();
3233
- return env2.requests.post(`${"/upload/file" /* UPLOAD_FILE_PATH */}`, formData, {
3234
- headers: {
3235
- "Content-Type": "multipart/form-data"
3236
- }
3237
- });
3238
- },
3239
- async parsePreview({
3240
- id,
3241
- selectedSheet,
3242
- isHeader,
3243
- context
3244
- }) {
3245
- const env2 = getEnv();
3246
- const jsonData = {
3247
- model: "base_import.import" /* BASE_IMPORT */,
3248
- method: "parse_preview",
3249
- ids: [id],
3250
- kwargs: {
3251
- options: {
3252
- import_skip_records: [],
3253
- import_set_empty_fields: [],
3254
- fallback_values: {},
3255
- name_create_enabled_fields: {},
3256
- encoding: "",
3257
- separator: "",
3258
- quoting: '"',
3259
- date_format: "",
3260
- datetime_format: "",
3261
- float_thousand_separator: ",",
3262
- float_decimal_separator: ".",
3263
- advanced: true,
3264
- has_headers: isHeader,
3265
- keep_matches: false,
3266
- limit: 2e3,
3267
- sheets: [],
3268
- sheet: selectedSheet,
3269
- skip: 0,
3270
- tracking_disable: true
3271
- }
3272
- },
3273
- with_context: context
3274
- };
3275
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3276
- headers: {
3277
- "Content-Type": "multipart/form-data"
3278
- }
3279
- });
3280
- },
3281
- async executeImport({
3282
- columns,
3283
- fields,
3284
- idFile,
3285
- options,
3286
- dryrun,
3287
- context
3288
- }) {
3289
- const env2 = getEnv();
3290
- const jsonData = {
3291
- model: "base_import.import" /* BASE_IMPORT */,
3292
- method: "execute_import",
3293
- ids: [idFile],
3294
- kwargs: {
3295
- fields,
3296
- columns,
3297
- options,
3298
- dryrun
3299
- },
3300
- with_context: context
3301
- };
3302
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3303
- headers: {
3304
- "Content-Type": "multipart/form-data"
3305
- }
3306
- });
3307
- },
3308
- async getFileExcel({ model, context }) {
3309
- const env2 = getEnv();
3310
- const jsonData = {
3311
- model,
3312
- method: "get_import_templates" /* GET_IMPORT */,
3313
- args: [],
3314
- with_context: context
3315
- };
3316
- return env2.requests.post("/call" /* CALL_PATH */, jsonData);
3317
- },
3318
- async getFieldExport({
3319
- ids,
3320
- model,
3321
- isShow,
3322
- parentField,
3323
- fieldType,
3324
- parentName,
3325
- prefix,
3326
- name,
3327
- context,
3328
- importCompat
3329
- }) {
3330
- const env2 = getEnv();
3331
- const jsonData = {
3332
- model,
3333
- import_compat: importCompat,
3334
- domain: [["id", "in", ids]],
3335
- with_context: context
3336
- };
3337
- if (isShow) {
3338
- jsonData.parent_field = parentField;
3339
- jsonData.parent_field_type = fieldType;
3340
- jsonData.parent_name = parentName;
3341
- jsonData.name = name;
3342
- jsonData.prefix = prefix;
3343
- jsonData.exclude = [null];
3344
- }
3345
- return env2.requests.post("/export/get_fields", jsonData);
3346
- },
3347
- async exportExcel({
3348
- model,
3349
- domain,
3350
- ids,
3351
- fields,
3352
- type,
3353
- importCompat,
3354
- context,
3355
- groupby
3356
- }) {
3357
- const env2 = getEnv();
3358
- const jsonData = {
3359
- model,
3360
- domain,
3361
- ids,
3362
- import_compat: importCompat,
3363
- fields,
3364
- with_context: context,
3365
- groupby: groupby ?? []
3366
- };
3367
- return env2.requests.post_excel(`/export/${type}`, jsonData);
3368
- }
3369
- };
3370
- var excel_service_default = ExcelService;
3371
-
3372
- // src/services/form-service/index.ts
3373
- var FormService = {
3374
- async getComment({ data }) {
3375
- try {
3376
- const env2 = getEnv();
3377
- const jsonData = {
3378
- thread_id: data.thread_id,
3379
- thread_model: data.thread_model,
3380
- limit: 100,
3381
- with_context: {
3382
- lang: data.lang
3383
- }
3384
- };
3385
- return env2.requests.post("/chatter/thread/messages" /* GET_MESSAGE */, jsonData, {
3386
- headers: {
3387
- "Content-Type": "application/json"
3388
- }
3389
- });
3390
- } catch (error) {
3391
- console.error("Error when sending message:", error);
3392
- throw error;
3393
- }
3394
- },
3395
- async sentComment({ data }) {
3396
- try {
3397
- const env2 = getEnv();
3398
- const jsonData = {
3399
- context: {
3400
- tz: "Asia/Saigon",
3401
- uid: 2,
3402
- allowed_company_ids: [1],
3403
- mail_post_autofollow: false,
3404
- temporary_id: 142183.01
3405
- },
3406
- post_data: {
3407
- body: data.message,
3408
- message_type: "comment",
3409
- attachment_ids: data.attachment_ids,
3410
- attachment_tokens: [],
3411
- subtype_xmlid: data.subtype
3412
- },
3413
- thread_id: Number(data.thread_id),
3414
- thread_model: data.thread_model
3415
- };
3416
- return env2.requests.post("/chatter/message/post" /* SENT_MESSAGE */, jsonData, {
3417
- headers: {
3418
- "Content-Type": "application/json"
3419
- }
3420
- });
3421
- } catch (error) {
3422
- console.error("Error when sent message:", error);
3423
- throw error;
3424
- }
3425
- },
3426
- async deleteComment({ data }) {
3427
- try {
3428
- const env2 = getEnv();
3429
- const jsonData = {
3430
- attachment_ids: [],
3431
- attachment_tokens: [],
3432
- body: "",
3433
- message_id: data.message_id
3434
- };
3435
- return env2.requests.post("/chatter/message/update_content" /* DELETE_MESSAGE */, jsonData, {
3436
- headers: {
3437
- "Content-Type": "application/json"
3438
- }
3439
- });
3440
- } catch (error) {
3441
- console.error("Error when sent message:", error);
3442
- throw error;
3443
- }
3444
- },
3445
- async getImage({ data }) {
3446
- try {
3447
- const env2 = getEnv();
3448
- return env2.requests.get(
3449
- `${"/web/image" /* IMAGE_PATH */}?filename=${data.filename}&unique=${data.checksum}&width=1920&height=300`,
3450
- {
3451
- headers: {
3452
- "Content-Type": "application/json"
3453
- }
3454
- }
3455
- );
3456
- } catch (error) {
3457
- console.error("Error when sent message:", error);
3458
- throw error;
3459
- }
3460
- },
3461
- async uploadImage({ data }) {
3462
- try {
3463
- const env2 = getEnv();
3464
- return env2.requests.post("/mail/attachment/upload" /* UPLOAD_IMAGE */, data, {
3465
- headers: {
3466
- "Content-Type": "multipart/form-data"
3467
- }
3468
- });
3469
- } catch (error) {
3470
- console.error("Error when sent message:", error);
3471
- throw error;
3472
- }
3473
- },
3474
- async getFormView({ data }) {
3475
- try {
3476
- const env2 = getEnv();
3477
- const jsonData = {
3478
- model: data.model,
3479
- method: "get_formview_action",
3480
- ids: data.id ? [data.id] : [],
3481
- with_context: data.context
3482
- };
3483
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3484
- headers: {
3485
- "Content-Type": "application/json"
3486
- }
3487
- });
3488
- } catch (error) {
3489
- console.error("Error when fetching form view:", error);
3490
- throw error;
3491
- }
3492
- },
3493
- async changeStatus({ data }) {
3494
- const env2 = getEnv();
3495
- const vals = {
3496
- [data.name]: data.stage_id
3497
- };
3498
- const jsonData = {
3499
- model: data.model,
3500
- method: "web_save",
3501
- with_context: {
3502
- lang: data.lang,
3503
- allowed_company_ids: [1],
3504
- uid: 2,
3505
- search_default_my_ticket: true,
3506
- search_default_is_open: true
3507
- },
3508
- ids: [data.id],
3509
- kwargs: {
3510
- vals,
3511
- specification: {}
3512
- }
3513
- };
3514
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3515
- headers: {
3516
- "Content-Type": "application/json"
3517
- }
3518
- });
3519
- }
3520
- };
3521
- var form_service_default = FormService;
3522
-
3523
- // src/services/model-service/index.ts
3524
- var OBJECT_POSITION = 2;
3525
- var ModelService = {
3526
- async getAll({ data }) {
3527
- const env2 = getEnv();
3528
- const jsonReadGroup = data.type == "calendar" ? { fields: data?.fields } : data.fields && data.fields.length > 0 && data.groupby && data.groupby.length > 0 && data.groupby[0] ? {
3529
- fields: data.fields,
3530
- groupby: data.groupby
3531
- } : {
3532
- count_limit: 10001,
3533
- order: data.sort,
3534
- specification: data.specification
3535
- };
3536
- const jsonData = {
3537
- model: String(data.model),
3538
- method: data.type == "calendar" ? "search_read" : jsonReadGroup.fields && jsonReadGroup.groupby ? "web_read_group" : "web_search_read",
3539
- ids: data.ids,
3540
- with_context: data.context,
3541
- kwargs: {
3542
- domain: data.domain,
3543
- limit: data.limit,
3544
- offset: data.offset,
3545
- ...jsonReadGroup
3546
- }
3547
- };
3548
- return env2?.requests.post("/call" /* CALL_PATH */, jsonData, {
3549
- headers: {
3550
- "Content-Type": "application/json"
3551
- }
3552
- });
3553
- },
3554
- async getList({
3555
- model,
3556
- ids = [],
3557
- specification = {},
3558
- domain = [],
3559
- offset,
3560
- order,
3561
- context = {},
3562
- limit = 10
3563
- }) {
3564
- const env2 = getEnv();
3565
- const jsonData = {
3566
- model,
3567
- method: "web_search_read" /* WEB_SEARCH_READ */,
3568
- ids,
3569
- with_context: context,
3570
- kwargs: {
3571
- specification,
3572
- domain,
3573
- limit,
3574
- offset,
3575
- order
3576
- }
3577
- };
3578
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3579
- headers: {
3580
- "Content-Type": "application/json"
3581
- }
3582
- });
3583
- },
3584
- async getDetail({
3585
- ids = [],
3586
- model,
3587
- specification,
3588
- context
3589
- }) {
3590
- const env2 = getEnv();
3591
- const jsonData = {
3592
- model,
3593
- method: "web_read" /* WEB_READ */,
3594
- ids,
3595
- with_context: context,
3596
- kwargs: {
3597
- specification
3598
- }
3599
- };
3600
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3601
- headers: {
3602
- "Content-Type": "application/json"
3603
- }
3604
- });
3605
- },
3606
- async save({
3607
- model,
3608
- ids = [],
3609
- data = {},
3610
- specification = {},
3611
- context = {}
3612
- }) {
3613
- const env2 = getEnv();
3614
- const jsonData = {
3615
- model,
3616
- method: "web_save" /* WEB_SAVE */,
3617
- with_context: context,
3618
- ids,
3619
- kwargs: {
3620
- vals: data,
3621
- specification
3622
- }
3623
- };
3624
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3625
- headers: {
3626
- "Content-Type": "application/json"
3627
- }
3628
- });
3629
- },
3630
- async delete({ ids = [], model }) {
3631
- const env2 = getEnv();
3632
- const jsonData = {
3633
- model,
3634
- method: "unlink" /* UNLINK */,
3635
- ids
3636
- };
3637
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3638
- headers: {
3639
- "Content-Type": "application/json"
3640
- }
3641
- });
3642
- },
3643
- async onChange({
3644
- ids = [],
3645
- model,
3646
- object,
3647
- specification,
3648
- context,
3649
- fieldChange
3650
- }) {
3651
- const env2 = getEnv();
3652
- const jsonData = {
3653
- model,
3654
- method: "onchange" /* ONCHANGE */,
3655
- ids,
3656
- with_context: context,
3657
- args: [
3658
- object ? object : {},
3659
- fieldChange ? fieldChange : [],
3660
- specification
3661
- ]
3662
- };
3663
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3664
- headers: {
3665
- "Content-Type": "application/json"
3666
- }
3667
- });
3668
- },
3669
- async getListFieldsOnchange({ model }) {
3670
- const env2 = getEnv();
3671
- const jsonData = {
3672
- model,
3673
- method: "get_fields_onchange" /* GET_ONCHANGE_FIELDS */
3674
- };
3675
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3676
- headers: {
3677
- "Content-Type": "application/json"
3678
- }
3679
- });
3680
- },
3681
- parseORMOdoo(data) {
3682
- for (const key in data) {
3683
- if (key === "display_name") {
3684
- delete data[key];
3685
- }
3686
- if (!data[key] && data[key] !== 0) {
3687
- data[key] = false;
3688
- } else if (data[key] === "Draft") {
3689
- data[key] = "/";
3690
- }
3691
- }
3692
- return { ...data };
3693
- },
3694
- toDataJS(data, viewData, model) {
3695
- for (const key in data) {
3696
- if (data[key] === false) {
3697
- if (viewData && model) {
3698
- if (viewData?.models?.[model]?.[key]?.type !== "boolean" /* BOOLEAN */) {
3699
- data[key] = null;
3700
- }
3701
- } else {
3702
- data[key] = null;
3703
- }
3704
- } else if (data[key] === "/") {
3705
- data[key] = "Draft";
3706
- } else if (data[key] !== false) {
3707
- if (model !== void 0) {
3708
- if (viewData?.models?.[model]?.[key]?.type === "one2many" /* ONE2MANY */ || viewData?.models?.[model]?.[key]?.type === "many2many" /* MANY2MANY */) {
3709
- data[key] = (data[key] ??= [])?.map((item, index) => {
3710
- const relation = viewData?.models?.[model]?.[key]?.relation;
3711
- if (relation !== void 0) {
3712
- if (viewData?.models?.[relation]) {
3713
- if (item?.length >= 3) {
3714
- if (item[0] === 2 /* DELETE */) {
3715
- delete data[key][index];
3716
- return;
3717
- }
3718
- return ModelService.toDataJS(
3719
- { ...item[OBJECT_POSITION], id: `virtual_${index}` },
3720
- viewData,
3721
- relation
3722
- );
3723
- } else {
3724
- return ModelService.toDataJS(item, viewData, relation);
3725
- }
3726
- } else {
3727
- if (item?.length >= 3) {
3728
- if (!item[OBJECT_POSITION] || item[0] === 2 /* DELETE */) {
3729
- delete data[key][index];
3730
- return;
3731
- }
3732
- return item[OBJECT_POSITION];
3733
- } else {
3734
- return item;
3735
- }
3736
- }
3737
- }
3738
- });
3739
- }
3740
- }
3741
- }
3742
- }
3743
- return { ...data };
3744
- }
3745
- };
3746
- var model_service_default = ModelService;
3747
-
3748
- // src/services/user-service/index.ts
3749
- var UserService = {
3750
- async getProfile() {
3751
- const env2 = getEnv();
3752
- return env2.requests.get("/userinfo" /* PROFILE_PATH */, {
3753
- headers: {
3754
- "Content-Type": "application/x-www-form-urlencoded"
3755
- }
3756
- });
3757
- },
3758
- async getUser({ context, id }) {
3759
- const env2 = getEnv();
3760
- const jsonData = {
3761
- model: "res.users",
3762
- method: "web_read",
3763
- ids: [id],
3764
- with_context: context,
3765
- kwargs: {
3766
- specification: {
3767
- display_name: {},
3768
- image_1920: {},
3769
- name: {},
3770
- login: {},
3771
- email: {},
3772
- password: {},
3773
- visible_group_id: {
3774
- fields: {
3775
- id: {},
3776
- display_name: {}
3777
- }
3778
- },
3779
- company_id: {
3780
- fields: {
3781
- id: {},
3782
- display_name: {}
3783
- }
3784
- }
3785
- }
3786
- }
3787
- };
3788
- return env2.requests.post("/call" /* CALL_PATH */, jsonData, {
3789
- headers: {
3790
- "Content-Type": "application/json"
3791
- }
3792
- });
3793
- },
3794
- switchUserLocale: async ({ id, values }) => {
3795
- const env2 = getEnv();
3796
- const jsonData = {
3797
- model: "res.users",
3798
- domain: [["id", "=", id]],
3799
- values
3800
- };
3801
- return env2?.requests.post(UriConstants?.CREATE_UPDATE_PATH, jsonData, {
3802
- headers: {
3803
- "Content-Type": "application/json"
3804
- }
3805
- });
3806
- }
3807
- };
3808
- var user_service_default = UserService;
3809
-
3810
- // src/services/view-service/index.ts
3811
- var ViewService = {
3812
- async getView({
3813
- model,
3814
- views,
3815
- context = {},
3816
- options = {},
3817
- aid
3818
- }) {
3819
- const env2 = getEnv();
3820
- const defaultOptions = {
3821
- load_filters: true,
3822
- toolbar: true,
3823
- action_id: aid
3824
- };
3825
- const jsonDataView = {
3826
- model,
3827
- method: "get_fields_view_v2" /* GET_FIELD_VIEW */,
3828
- kwargs: {
3829
- views,
3830
- options: { ...options, ...defaultOptions }
3831
- },
3832
- with_context: context
3833
- };
3834
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonDataView, {
3835
- headers: {
3836
- "Content-Type": "application/json"
3837
- }
3838
- });
3839
- },
3840
- async getMenu(context) {
3841
- const env2 = getEnv();
3842
- const jsonData = {
3843
- model: "ir.ui.menu" /* MENU */,
3844
- method: "web_search_read" /* WEB_SEARCH_READ */,
3845
- ids: [],
3846
- with_context: context,
3847
- kwargs: {
3848
- specification: {
3849
- active: {},
3850
- name: {},
3851
- is_display: {},
3852
- sequence: {},
3853
- complete_name: {},
3854
- action: {
3855
- fields: {
3856
- display_name: {},
3857
- type: {},
3858
- binding_view_types: {}
3859
- // res_model: {},
3860
- }
3861
- },
3862
- url_icon: {},
3863
- web_icon: {},
3864
- web_icon_data: {},
3865
- groups_id: {
3866
- fields: {
3867
- full_name: {}
3868
- },
3869
- limit: 40,
3870
- order: ""
3871
- },
3872
- display_name: {},
3873
- child_id: {
3874
- fields: {
3875
- active: {},
3876
- name: {},
3877
- is_display: {},
3878
- sequence: {},
3879
- complete_name: {},
3880
- action: {
3881
- fields: {
3882
- display_name: {},
3883
- type: {},
3884
- binding_view_types: {}
3885
- // res_model: {},
3886
- }
3887
- },
3888
- url_icon: {},
3889
- web_icon: {},
3890
- web_icon_data: {},
3891
- groups_id: {
3892
- fields: {
3893
- full_name: {}
3894
- },
3895
- limit: 40,
3896
- order: ""
3897
- },
3898
- display_name: {},
3899
- child_id: {
3900
- fields: {
3901
- active: {},
3902
- name: {},
3903
- is_display: {},
3904
- sequence: {},
3905
- complete_name: {},
3906
- action: {
3907
- fields: {
3908
- display_name: {},
3909
- type: {},
3910
- binding_view_types: {}
3911
- // res_model: {},
3912
- }
3913
- },
3914
- url_icon: {},
3915
- web_icon: {},
3916
- web_icon_data: {},
3917
- groups_id: {
3918
- fields: {
3919
- full_name: {}
3920
- },
3921
- limit: 40,
3922
- order: ""
3923
- },
3924
- display_name: {},
3925
- child_id: {
3926
- fields: {
3927
- active: {},
3928
- name: {},
3929
- is_display: {},
3930
- sequence: {},
3931
- complete_name: {},
3932
- action: {
3933
- fields: {
3934
- display_name: {},
3935
- type: {},
3936
- binding_view_types: {}
3937
- // res_model: {},
3938
- }
3939
- },
3940
- url_icon: {},
3941
- web_icon: {},
3942
- web_icon_data: {},
3943
- groups_id: {
3944
- fields: {
3945
- full_name: {}
3946
- },
3947
- limit: 40,
3948
- order: ""
3949
- },
3950
- display_name: {},
3951
- child_id: {
3952
- fields: {},
3953
- limit: 40,
3954
- order: ""
3955
- }
3956
- },
3957
- limit: 40,
3958
- order: ""
3959
- }
3960
- },
3961
- limit: 40,
3962
- order: ""
3963
- }
3964
- },
3965
- limit: 40,
3966
- order: ""
3967
- }
3968
- },
3969
- domain: [
3970
- "&",
3971
- ["is_display", "=", true],
3972
- "&",
3973
- ["active", "=", true],
3974
- ["parent_id", "=", false]
3975
- ]
3976
- }
3977
- };
3978
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3979
- headers: {
3980
- "Content-Type": "application/json"
3981
- }
3982
- });
3983
- },
3984
- async getSelectionItem({ data }) {
3985
- const env2 = getEnv();
3986
- const jsonData = {
3987
- model: data.model,
3988
- ids: [],
3989
- method: "get_data_select",
3990
- with_context: data.context,
3991
- kwargs: {
3992
- count_limit: 10001,
3993
- domain: data.domain ? data.domain : [],
3994
- offset: 0,
3995
- order: "",
3996
- specification: data?.specification ?? {
3997
- id: {},
3998
- name: {},
3999
- display_name: {}
4000
- }
4001
- }
4002
- };
4003
- return env2?.requests.post("/call" /* CALL_PATH */, jsonData, {
4004
- headers: {
4005
- "Content-Type": "application/json"
4006
- }
4007
- });
4008
- },
4009
- async loadMessages() {
4010
- const env2 = getEnv();
4011
- return env2.requests.post(
4012
- "/load_message_failures" /* LOAD_MESSAGE */,
4013
- {},
4014
- {
4015
- headers: {
4016
- "Content-Type": "application/json"
4017
- }
4018
- }
4019
- );
4020
- },
4021
- async getVersion() {
4022
- const env2 = getEnv();
4023
- return env2?.requests.get("", {
4024
- headers: {
4025
- "Content-Type": "application/json"
4026
- }
4027
- });
4028
- }
4029
- };
4030
- var view_service_default = ViewService;
4031
-
4032
- export { action_service_default as ActionService, auth_service_default as AuthService, company_service_default as CompanyService, excel_service_default as ExcelService, form_service_default as FormService, model_service_default as ModelService, user_service_default as UserService, view_service_default as ViewService };