@fctc/edu-logic-lib 1.0.0 → 1.0.2

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.
@@ -0,0 +1,124 @@
1
+ import {
2
+ WIDGETAVATAR
3
+ } from "./chunk-S7B3VKMJ.mjs";
4
+
5
+ // src/models/base-model/index.ts
6
+ var BaseModel = class {
7
+ name;
8
+ view;
9
+ actContext;
10
+ fields;
11
+ constructor(init) {
12
+ this.name = init.name;
13
+ this.view = init.view;
14
+ this.actContext = init.actContext;
15
+ this.fields = init.fields;
16
+ }
17
+ getSpecificationByFields({
18
+ fields = [],
19
+ specification = {},
20
+ modelsData,
21
+ model,
22
+ modelRoot
23
+ }) {
24
+ if (Array.isArray(fields)) {
25
+ let spec = { ...specification };
26
+ fields.forEach((field) => {
27
+ if (!field?.type_co || field?.name && field?.type_co === "field" /* FIELD */) {
28
+ if (modelsData?.[model]?.[field?.name]) {
29
+ if (modelsData?.[model]?.[field?.name]?.type === "one2many" /* ONE2MANY */ || modelsData?.[model]?.[field?.name]?.type === "many2many" /* MANY2MANY */) {
30
+ const relation = modelsData?.[model]?.[field?.name]?.relation;
31
+ const modelRelation = modelsData?.[relation];
32
+ if (modelRelation) {
33
+ spec[field?.name] = {
34
+ fields: {}
35
+ };
36
+ if (modelRoot && modelRoot === relation) {
37
+ spec[field?.name].fields = { id: {} };
38
+ } else {
39
+ spec[field?.name].fields = this.getSpecificationByFields({
40
+ fields: Object.values(modelRelation),
41
+ specification: {},
42
+ modelsData,
43
+ model: relation,
44
+ modelRoot: model
45
+ });
46
+ }
47
+ } else {
48
+ spec[field?.name] = {
49
+ fields: {
50
+ id: {},
51
+ display_name: {}
52
+ }
53
+ };
54
+ }
55
+ } else if (modelsData?.[model]?.[field?.name]?.type === "many2one" /* MANY2ONE */) {
56
+ spec[field?.name] = {
57
+ fields: {
58
+ id: {},
59
+ display_name: {},
60
+ ...WIDGETAVATAR[field?.widget] ? { image_256: {} } : {},
61
+ ...field?.name === "currency_id" && fields?.find((item) => item?.widget === "monetary") ? { symbol: {} } : {},
62
+ ...field?.widget === "many2many_binary" ? { mimetype: {} } : {}
63
+ }
64
+ };
65
+ } else {
66
+ spec[field?.name] = {};
67
+ }
68
+ }
69
+ } else if (field?.type_co === "group" /* GROUP */ || field?.type_co === "div" /* DIV */ || field?.type_co === "span" /* SPAN */) {
70
+ const specGroup = this.getSpecificationByFields({
71
+ fields: field?.fields,
72
+ specification: spec,
73
+ modelsData,
74
+ model
75
+ });
76
+ spec = { ...spec, ...specGroup };
77
+ } else if (field?.type_co === "tree" /* TREE */ || field?.type_co === "list" /* LIST */) {
78
+ const relation = modelsData?.[model]?.[field?.name]?.relation;
79
+ const specTreee = this.getSpecificationByFields({
80
+ fields: field?.fields,
81
+ specification: {},
82
+ modelsData,
83
+ model: relation,
84
+ modelRoot: model
85
+ });
86
+ spec = {
87
+ ...spec,
88
+ [field?.name]: {
89
+ fields: { ...spec?.[field?.name]?.fields, ...specTreee }
90
+ }
91
+ };
92
+ }
93
+ });
94
+ return spec;
95
+ } else {
96
+ console.warn("fields is not array");
97
+ }
98
+ }
99
+ getTreeProps() {
100
+ const props = this.view?.views?.list || {};
101
+ return props;
102
+ }
103
+ getTreeFields() {
104
+ const fields = this.view?.views?.list?.fields || [];
105
+ return fields;
106
+ }
107
+ getSpecification() {
108
+ const specInit = {};
109
+ const modelData = this.view?.models || {};
110
+ const specification = this.getSpecificationByFields({
111
+ fields: this.fields,
112
+ specification: specInit,
113
+ modelsData: modelData,
114
+ model: this.name,
115
+ modelRoot: ""
116
+ });
117
+ return specification;
118
+ }
119
+ };
120
+ var base_model_default = BaseModel;
121
+
122
+ export {
123
+ base_model_default
124
+ };
@@ -0,0 +1,258 @@
1
+ // src/config/axios-client.ts
2
+ import axios from "axios";
3
+ var MAINT_KEY = "MAINTENANCE_ACTIVE";
4
+ var MAINT_AT = "MAINTENANCE_AT";
5
+ var MAINT_LAST_PATH = "MAINTENANCE_LAST_PATH";
6
+ var hasRedirectedToMaintenance = false;
7
+ function setMaintenanceFlags() {
8
+ if (typeof window === "undefined") return;
9
+ const { pathname, search } = window.location;
10
+ const lastPath = pathname + (search || "");
11
+ if (pathname !== "/maintenance" && !window.localStorage.getItem(MAINT_LAST_PATH)) {
12
+ window.localStorage.setItem(MAINT_LAST_PATH, lastPath);
13
+ }
14
+ window.localStorage.setItem(MAINT_KEY, "true");
15
+ window.localStorage.setItem(MAINT_AT, String(Date.now()));
16
+ }
17
+ async function clearMaintenanceAndExit(getToken, opts) {
18
+ if (typeof window === "undefined") return;
19
+ const forceLogin = opts?.forceLogin === true;
20
+ const clearTokenOnForce = opts?.clearTokenOnForce !== false;
21
+ window.localStorage.removeItem(MAINT_KEY);
22
+ window.localStorage.removeItem(MAINT_AT);
23
+ const lastPath = window.localStorage.getItem(MAINT_LAST_PATH);
24
+ window.localStorage.removeItem(MAINT_LAST_PATH);
25
+ try {
26
+ if (forceLogin) {
27
+ if (clearTokenOnForce) {
28
+ try {
29
+ await opts?.clearToken?.();
30
+ } catch {
31
+ }
32
+ }
33
+ window.location.replace("/login");
34
+ return;
35
+ }
36
+ const token = await getToken();
37
+ if (token) {
38
+ const target = lastPath && lastPath !== "/maintenance" ? lastPath : "/";
39
+ window.location.replace(target);
40
+ } else {
41
+ window.location.replace("/login");
42
+ }
43
+ } catch {
44
+ window.location.replace("/login");
45
+ }
46
+ }
47
+ var axiosClient = {
48
+ init(config) {
49
+ const localStorage = config.localStorageUtils;
50
+ const sessionStorage = config.sessionStorageUtils;
51
+ const db = config.db;
52
+ let isRefreshing = false;
53
+ let failedQueue = [];
54
+ const processQueue = (error, token = null) => {
55
+ failedQueue?.forEach((prom) => {
56
+ if (error) {
57
+ prom.reject(error);
58
+ } else {
59
+ prom.resolve(token);
60
+ }
61
+ });
62
+ failedQueue = [];
63
+ };
64
+ const instance = axios.create({
65
+ adapter: axios.defaults.adapter,
66
+ baseURL: config.baseUrl,
67
+ timeout: 5e4,
68
+ paramsSerializer: (params) => new URLSearchParams(params).toString()
69
+ });
70
+ if (typeof window !== "undefined") {
71
+ const isMaint = window.localStorage.getItem(MAINT_KEY) === "true";
72
+ const onMaintenancePage = window.location.pathname === "/maintenance";
73
+ if (isMaint && !onMaintenancePage) {
74
+ hasRedirectedToMaintenance = true;
75
+ window.location.replace("/maintenance");
76
+ }
77
+ if (isMaint && onMaintenancePage) {
78
+ const healthUrl = config.healthUrl || `${(config.baseUrl || "").replace(/\/+$/, "")}/health`;
79
+ (async () => {
80
+ try {
81
+ await axios.get(healthUrl, { timeout: 8e3 });
82
+ await clearMaintenanceAndExit(() => localStorage.getAccessToken(), {
83
+ forceLogin: true,
84
+ clearTokenOnForce: true,
85
+ clearToken: () => localStorage.clearToken()
86
+ });
87
+ } catch {
88
+ }
89
+ })();
90
+ }
91
+ }
92
+ instance.interceptors.request.use(
93
+ async (configReq) => {
94
+ const token = await localStorage.getAccessToken();
95
+ if (token) {
96
+ configReq.headers["Authorization"] = "Bearer " + token;
97
+ }
98
+ return configReq;
99
+ },
100
+ (error) => Promise.reject(error)
101
+ );
102
+ instance.interceptors.response.use(
103
+ (response) => {
104
+ if (typeof window !== "undefined") {
105
+ const isMaint = window.localStorage.getItem(MAINT_KEY) === "true";
106
+ const onMaintenancePage = window.location.pathname === "/maintenance";
107
+ if (isMaint && onMaintenancePage) {
108
+ ;
109
+ (async () => {
110
+ await clearMaintenanceAndExit(
111
+ () => localStorage.getAccessToken(),
112
+ {
113
+ forceLogin: true,
114
+ clearTokenOnForce: true,
115
+ clearToken: () => localStorage.clearToken()
116
+ }
117
+ );
118
+ })();
119
+ } else if (isMaint) {
120
+ window.localStorage.removeItem(MAINT_KEY);
121
+ window.localStorage.removeItem(MAINT_AT);
122
+ window.localStorage.removeItem(MAINT_LAST_PATH);
123
+ }
124
+ }
125
+ return handleResponse(response);
126
+ },
127
+ async (error) => {
128
+ const status = error?.response?.status;
129
+ if (status === 503) {
130
+ if (typeof window !== "undefined") {
131
+ setMaintenanceFlags();
132
+ if (!hasRedirectedToMaintenance && window.location.pathname !== "/maintenance") {
133
+ hasRedirectedToMaintenance = true;
134
+ window.location.replace("/maintenance");
135
+ }
136
+ }
137
+ return Promise.reject({
138
+ code: 503,
139
+ message: "SERVICE_UNAVAILABLE",
140
+ original: error?.response?.data
141
+ });
142
+ }
143
+ const handleError = async (err) => {
144
+ if (!err.response) {
145
+ return err;
146
+ }
147
+ const { data } = err.response;
148
+ if (data && data.code === 400 && ["invalid_grant"].includes(data.data?.error)) {
149
+ await clearAuthToken();
150
+ }
151
+ return data;
152
+ };
153
+ const originalRequest = error.config;
154
+ if ((error.response?.status === 403 || error.response?.status === 401 || error.response?.status === 404) && ["TOKEN_EXPIRED", "AUTHEN_FAIL", 401].includes(
155
+ error.response.data.code
156
+ )) {
157
+ if (isRefreshing) {
158
+ return new Promise(function(resolve, reject) {
159
+ failedQueue.push({ resolve, reject });
160
+ }).then((token) => {
161
+ originalRequest.headers["Authorization"] = "Bearer " + token;
162
+ return instance.request(originalRequest);
163
+ }).catch(async (err) => {
164
+ if ((err.response?.status === 400 || err.response?.status === 401) && ["invalid_grant"].includes(err.response.data.error)) {
165
+ await clearAuthToken();
166
+ }
167
+ });
168
+ }
169
+ const browserSession = await sessionStorage.getBrowserSession();
170
+ const refreshToken = await localStorage.getRefreshToken();
171
+ const accessTokenExp = await localStorage.getAccessToken();
172
+ isRefreshing = true;
173
+ if (!refreshToken && (!browserSession || browserSession == "unActive")) {
174
+ await clearAuthToken();
175
+ } else {
176
+ const payload = Object.fromEntries(
177
+ Object.entries({
178
+ refresh_token: refreshToken,
179
+ grant_type: "refresh_token",
180
+ client_id: config.config.clientId,
181
+ client_secret: config.config.clientSecret
182
+ }).filter(([_, value]) => !!value)
183
+ );
184
+ return new Promise(function(resolve) {
185
+ axios.post(
186
+ `${config.baseUrl}${"/authentication/oauth2/token" /* AUTH_TOKEN_PATH */}`,
187
+ payload,
188
+ {
189
+ headers: {
190
+ "Content-Type": "multipart/form-data",
191
+ Authorization: `Bearer ${accessTokenExp}`
192
+ }
193
+ }
194
+ ).then(async (res) => {
195
+ const data = res.data;
196
+ await localStorage.setToken(data.access_token);
197
+ await localStorage.setRefreshToken(data.refresh_token);
198
+ axios.defaults.headers.common["Authorization"] = "Bearer " + data.access_token;
199
+ originalRequest.headers["Authorization"] = "Bearer " + data.access_token;
200
+ processQueue(null, data.access_token);
201
+ resolve(instance.request(originalRequest));
202
+ }).catch(async (err) => {
203
+ if (err && (err?.error_code === "AUTHEN_FAIL" || err?.error_code === "TOKEN_EXPIRED" || err?.error_code === "TOKEN_INCORRECT" || err?.code === "ERR_BAD_REQUEST")) {
204
+ await clearAuthToken();
205
+ }
206
+ if (err && err.response) {
207
+ const { error_code } = err.response?.data || {};
208
+ if (error_code === "AUTHEN_FAIL") {
209
+ await clearAuthToken();
210
+ }
211
+ }
212
+ processQueue(err, null);
213
+ }).finally(() => {
214
+ isRefreshing = false;
215
+ });
216
+ });
217
+ }
218
+ }
219
+ return Promise.reject(await handleError(error));
220
+ }
221
+ );
222
+ const handleResponse = (res) => {
223
+ if (res && res.data) {
224
+ return res.data;
225
+ }
226
+ return res;
227
+ };
228
+ const clearAuthToken = async () => {
229
+ await localStorage.clearToken();
230
+ if (typeof window !== "undefined") {
231
+ window.location.href = `/login`;
232
+ }
233
+ };
234
+ function formatUrl(url, db2) {
235
+ return url + (db2 ? "?db=" + db2 : "");
236
+ }
237
+ const responseBody = (response) => response;
238
+ const requests = {
239
+ get: (url, headers) => instance.get(formatUrl(url, db), headers).then(responseBody),
240
+ post: (url, body, headers) => instance.post(formatUrl(url, db), body, { headers }).then(responseBody),
241
+ post_excel: (url, body, headers) => instance.post(formatUrl(url, db), body, {
242
+ responseType: "arraybuffer",
243
+ headers: {
244
+ "Content-Type": typeof window !== "undefined" ? "application/json" : "application/javascript",
245
+ Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
246
+ }
247
+ }).then(responseBody),
248
+ put: (url, body, headers) => instance.put(formatUrl(url, db), body, headers).then(responseBody),
249
+ patch: (url, body) => instance.patch(formatUrl(url, db), body).then(responseBody),
250
+ delete: (url, body) => instance.delete(formatUrl(url, db), body).then(responseBody)
251
+ };
252
+ return requests;
253
+ }
254
+ };
255
+
256
+ export {
257
+ axiosClient
258
+ };