@fctc/widget-logic 5.3.7-beta.15 → 5.3.7-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs DELETED
@@ -1,3089 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
-
19
- // src/index.ts
20
- var index_exports = {};
21
- __export(index_exports, {
22
- AppProvider: () => AppProvider,
23
- STORAGES: () => STORAGES,
24
- binaryFieldController: () => binaryFieldController,
25
- colorFieldController: () => colorFieldController,
26
- copyLinkButtonController: () => copyLinkButtonController,
27
- countSum: () => countSum,
28
- downLoadBinaryController: () => downLoadBinaryController,
29
- downloadFileController: () => downloadFileController,
30
- durationController: () => durationController,
31
- guessTypeFromUrl: () => guessTypeFromUrl,
32
- isObjectEmpty: () => isObjectEmpty,
33
- languages: () => languages,
34
- many2manyBinaryController: () => many2manyBinaryController,
35
- many2manyFieldController: () => many2manyFieldController,
36
- many2manyTagsController: () => many2manyTagsController,
37
- many2oneButtonController: () => many2oneButtonController,
38
- many2oneFieldController: () => many2oneFieldController,
39
- mergeButtons: () => mergeButtons,
40
- priorityFieldController: () => priorityFieldController,
41
- providerEinvoiceFieldController: () => providerEinvoiceFieldController,
42
- searchController: () => searchController,
43
- setStorageItemAsync: () => setStorageItemAsync,
44
- statusDropdownController: () => statusDropdownController,
45
- tableController: () => tableController,
46
- tableGroupController: () => tableGroupController,
47
- tableHeadController: () => tableHeadController,
48
- useAddEntity: () => useAddEntity,
49
- useAppProvider: () => useAppProvider,
50
- useButton: () => useButton,
51
- useCallAction: () => useCallAction,
52
- useChangeOrderPreparationState: () => useChangeOrderPreparationState,
53
- useChangeStatus: () => useChangeStatus,
54
- useCheckPayment: () => useCheckPayment,
55
- useCompany: () => useCompany,
56
- useConfig: () => useConfig,
57
- useCreateEntity: () => useCreateEntity,
58
- useCreatePosConfig: () => useCreatePosConfig,
59
- useCreateSession: () => useCreateSession,
60
- useDebounce: () => useDebounce,
61
- useDelete: () => useDelete,
62
- useDeleteComment: () => useDeleteComment,
63
- useDeleteEntity: () => useDeleteEntity,
64
- useDetail: () => useDetail,
65
- useDuplicateRecord: () => useDuplicateRecord,
66
- useExecuteImport: () => useExecuteImport,
67
- useExportExcel: () => useExportExcel,
68
- useForgotPassword: () => useForgotPassword,
69
- useForgotPasswordSSO: () => useForgotPasswordSSO,
70
- useGenSerialNumber: () => useGenSerialNumber,
71
- useGeneratePaymentQrInfo: () => useGeneratePaymentQrInfo,
72
- useGet2FAMethods: () => useGet2FAMethods,
73
- useGetASession: () => useGetASession,
74
- useGetAccessByCode: () => useGetAccessByCode,
75
- useGetAction: () => useGetAction,
76
- useGetActionDetail: () => useGetActionDetail,
77
- useGetAll: () => useGetAll,
78
- useGetCalendar: () => useGetCalendar,
79
- useGetComment: () => useGetComment,
80
- useGetCompanyInfo: () => useGetCompanyInfo,
81
- useGetConversionRate: () => useGetConversionRate,
82
- useGetCurrency: () => useGetCurrency,
83
- useGetCurrentCompany: () => useGetCurrentCompany,
84
- useGetDetail: () => useGetDetail,
85
- useGetExternalTabs: () => useGetExternalTabs,
86
- useGetFieldExport: () => useGetFieldExport,
87
- useGetFieldOnChange: () => useGetFieldOnChange,
88
- useGetFileExcel: () => useGetFileExcel,
89
- useGetFormView: () => useGetFormView,
90
- useGetGroups: () => useGetGroups,
91
- useGetList: () => useGetList,
92
- useGetListCompany: () => useGetListCompany,
93
- useGetListData: () => useGetListData,
94
- useGetListMyBankAccount: () => useGetListMyBankAccount,
95
- useGetMenu: () => useGetMenu,
96
- useGetOrderLine: () => useGetOrderLine,
97
- useGetPinCode: () => useGetPinCode,
98
- useGetPrintReport: () => useGetPrintReport,
99
- useGetProGressBar: () => useGetProGressBar,
100
- useGetProfile: () => useGetProfile,
101
- useGetProvider: () => useGetProvider,
102
- useGetResequence: () => useGetResequence,
103
- useGetRowIds: () => useGetRowIds,
104
- useGetSelection: () => useGetSelection,
105
- useGetSpecification: () => useGetSpecification,
106
- useGetUser: () => useGetUser,
107
- useGetView: () => useGetView,
108
- useGrantAccess: () => useGrantAccess,
109
- useIsValidToken: () => useIsValidToken,
110
- useListData: () => useListData,
111
- useLoadAction: () => useLoadAction,
112
- useLoadMessage: () => useLoadMessage,
113
- useLoginCredential: () => useLoginCredential,
114
- useLoginSocial: () => useLoginSocial,
115
- useLogout: () => useLogout,
116
- useMenu: () => useMenu,
117
- useModel: () => useModel,
118
- useOdooDataTransform: () => useOdooDataTransform,
119
- useOnChangeForm: () => useOnChangeForm,
120
- useParsePreview: () => useParsePreview,
121
- usePrint: () => usePrint,
122
- useProfile: () => useProfile,
123
- useReadGroup: () => useReadGroup,
124
- useRemoveRow: () => useRemoveRow,
125
- useRemoveTotpSetup: () => useRemoveTotpSetup,
126
- useRequestSetupTotp: () => useRequestSetupTotp,
127
- useResetPassword: () => useResetPassword,
128
- useResetPasswordSSO: () => useResetPasswordSSO,
129
- useRunAction: () => useRunAction,
130
- useSave: () => useSave,
131
- useSendComment: () => useSendComment,
132
- useSettingsWebRead2fa: () => useSettingsWebRead2fa,
133
- useSignInSSO: () => useSignInSSO,
134
- useStorageState: () => useStorageState,
135
- useSwitchLocale: () => useSwitchLocale,
136
- useUpdatePassword: () => useUpdatePassword,
137
- useUploadFile: () => useUploadFile,
138
- useUploadFileExcel: () => useUploadFileExcel,
139
- useUploadIdFile: () => useUploadIdFile,
140
- useUploadImage: () => useUploadImage,
141
- useUser: () => useUser,
142
- useValidateActionToken: () => useValidateActionToken,
143
- useVerify2FA: () => useVerify2FA,
144
- useVerifyTotp: () => useVerifyTotp,
145
- useViewV2: () => useViewV2,
146
- validateAndParseDate: () => validateAndParseDate
147
- });
148
-
149
- // src/hooks.ts
150
- import {
151
- useModel,
152
- useButton,
153
- useChangeStatus,
154
- useDelete,
155
- useDeleteComment,
156
- useDuplicateRecord,
157
- useExecuteImport,
158
- useExportExcel,
159
- useForgotPassword,
160
- useForgotPasswordSSO,
161
- useGet2FAMethods,
162
- useGetAccessByCode,
163
- useGetActionDetail,
164
- useGetAll,
165
- useGetCalendar,
166
- useGetComment,
167
- useGetCompanyInfo,
168
- useGetConversionRate,
169
- useGetCurrency,
170
- useGetCurrentCompany,
171
- useGetDetail,
172
- useGetFieldExport,
173
- useGetFieldOnChange,
174
- useGetFileExcel,
175
- useGetFormView,
176
- useGetGroups,
177
- useGetListCompany,
178
- useGetListData,
179
- useGetListMyBankAccount,
180
- useGetMenu,
181
- useGetPrintReport,
182
- useGetProGressBar,
183
- useGetProfile,
184
- useGetProvider,
185
- useGetResequence,
186
- useGetSelection,
187
- useGetUser,
188
- useGetView,
189
- useGrantAccess,
190
- useIsValidToken,
191
- useLoadAction,
192
- useLoadMessage,
193
- useLoginCredential,
194
- useLoginSocial,
195
- useLogout,
196
- useOdooDataTransform,
197
- useOnChangeForm,
198
- useParsePreview,
199
- usePrint,
200
- useRemoveRow,
201
- useRemoveTotpSetup,
202
- useRequestSetupTotp,
203
- useResetPassword,
204
- useResetPasswordSSO,
205
- useRunAction,
206
- useSave,
207
- useSendComment,
208
- useSettingsWebRead2fa,
209
- useSignInSSO,
210
- useSwitchLocale,
211
- useUpdatePassword,
212
- useUploadFile,
213
- useUploadFileExcel,
214
- useUploadIdFile,
215
- useUploadImage,
216
- useValidateActionToken,
217
- useVerify2FA,
218
- useVerifyTotp,
219
- useAddEntity,
220
- useChangeOrderPreparationState,
221
- useCheckPayment,
222
- useCreateEntity,
223
- useCreatePosConfig,
224
- useCreateSession,
225
- useDeleteEntity,
226
- useGenSerialNumber,
227
- useGeneratePaymentQrInfo,
228
- useGetASession,
229
- useGetExternalTabs,
230
- useGetList,
231
- useGetOrderLine,
232
- useReadGroup,
233
- useGetPinCode
234
- } from "@fctc/interface-logic/hooks";
235
-
236
- // src/hooks/core/use-app-provider.tsx
237
- import { createContext, useContext, useMemo as useMemo4 } from "react";
238
-
239
- // src/hooks/core/use-menu.ts
240
- import { useState as useState2 } from "react";
241
-
242
- // src/hooks/core/use-call-action.ts
243
- import { useCallback, useState } from "react";
244
-
245
- // src/provider.ts
246
- var provider_exports = {};
247
- __reExport(provider_exports, provider_star);
248
- import * as provider_star from "@fctc/interface-logic/provider";
249
-
250
- // src/hooks/core/use-call-action.ts
251
- var useCallAction = () => {
252
- const { env } = (0, provider_exports.useEnv)();
253
- const { useLoadAction: useLoadAction2, useRunAction: useRunAction2 } = (0, provider_exports.useService)();
254
- const queryLoadAction = useLoadAction2();
255
- const queryRunAction = useRunAction2();
256
- const [actionData, setActionData] = useState(
257
- void 0
258
- );
259
- const callAction = useCallback(
260
- async ({
261
- aid,
262
- service,
263
- xNode,
264
- context
265
- }) => {
266
- try {
267
- const menuContext = {
268
- ...env?.context,
269
- ...context
270
- };
271
- const loadRes = await queryLoadAction.mutateAsync({
272
- idAction: aid,
273
- context: menuContext,
274
- service,
275
- xNode
276
- });
277
- if (loadRes?.result?.type === "ir.actions.server") {
278
- const runRes = await queryRunAction.mutateAsync({
279
- idAction: aid,
280
- context: menuContext,
281
- service,
282
- xNode
283
- });
284
- setActionData(runRes?.result);
285
- return runRes?.result;
286
- } else {
287
- setActionData(loadRes?.result);
288
- return loadRes?.result;
289
- }
290
- } catch (err) {
291
- console.error("callAction error:", err);
292
- return void 0;
293
- }
294
- },
295
- [env?.context?.lang]
296
- );
297
- return [actionData, callAction];
298
- };
299
-
300
- // src/utils.ts
301
- var utils_exports = {};
302
- __export(utils_exports, {
303
- STORAGES: () => STORAGES,
304
- countSum: () => countSum,
305
- guessTypeFromUrl: () => guessTypeFromUrl,
306
- isObjectEmpty: () => isObjectEmpty,
307
- languages: () => languages,
308
- mergeButtons: () => mergeButtons,
309
- setStorageItemAsync: () => setStorageItemAsync,
310
- useStorageState: () => useStorageState,
311
- validateAndParseDate: () => validateAndParseDate
312
- });
313
-
314
- // src/utils/constants.ts
315
- var languages = [
316
- { id: "vi_VN", name: "VIE" },
317
- { id: "en_US", name: "ENG" }
318
- ];
319
- var isBlobUrl = (url) => url.startsWith("blob:");
320
-
321
- // src/utils/function.ts
322
- import { useCallback as useCallback2, useEffect, useReducer } from "react";
323
- var countSum = (data, field) => {
324
- if (!data || !field) return 0;
325
- return data.reduce(
326
- (total, item) => total + (item?.[`${field}_count`] || 0),
327
- 0
328
- );
329
- };
330
- var isObjectEmpty = (obj) => {
331
- return Object.keys(obj).length === 0;
332
- };
333
- function mergeButtons(fields) {
334
- const buttons = fields?.filter((f) => f.type_co === "button");
335
- const others = fields?.filter((f) => f.type_co !== "button");
336
- if (buttons?.length) {
337
- others.push({
338
- type_co: "buttons",
339
- buttons
340
- });
341
- }
342
- return others;
343
- }
344
- var STORAGES = {
345
- TOKEN: "accessToken",
346
- USER_INFO: "USER_INFO"
347
- };
348
- function useAsyncState(initialValue = [true, null]) {
349
- return useReducer(
350
- (_state, action = null) => [false, action],
351
- initialValue
352
- );
353
- }
354
- async function setStorageItemAsync(key, value) {
355
- try {
356
- if (value === null) {
357
- localStorage.removeItem(key);
358
- } else {
359
- localStorage.setItem(key, value);
360
- }
361
- } catch (e) {
362
- console.error("Local storage is unavailable:", e);
363
- }
364
- }
365
- function useStorageState(key) {
366
- const [state, setState] = useAsyncState();
367
- useEffect(() => {
368
- try {
369
- const storedValue = localStorage.getItem(key);
370
- setState(storedValue);
371
- } catch (e) {
372
- console.error("Local storage is unavailable:", e);
373
- }
374
- }, [key]);
375
- const setValue = useCallback2(
376
- (value) => {
377
- setState(value);
378
- setStorageItemAsync(key, value);
379
- },
380
- [key]
381
- );
382
- return [state, setValue];
383
- }
384
- var guessTypeFromUrl = (url) => {
385
- const ext = url.split(".").pop()?.toLowerCase();
386
- if (!ext) return null;
387
- const map = {
388
- jpg: "image/jpeg",
389
- jpeg: "image/jpeg",
390
- png: "image/png",
391
- webp: "image/webp",
392
- gif: "image/gif",
393
- svg: "image/svg+xml",
394
- bmp: "image/bmp",
395
- tiff: "image/tiff",
396
- pdf: "application/pdf",
397
- zip: "application/zip",
398
- rar: "application/x-rar-compressed",
399
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
400
- xls: "application/vnd.ms-excel",
401
- mp4: "video/mp4",
402
- mov: "video/quicktime"
403
- };
404
- return map[ext] || null;
405
- };
406
-
407
- // src/utils/format-date.ts
408
- import moment from "moment";
409
- var validateAndParseDate = (input, isDateTime = false) => {
410
- if (!input || typeof input !== "string") return null;
411
- const cleanInput = input.replace(/[^0-9-\/:\s]/g, "");
412
- const dateFormat = "YYYY-MM-DD";
413
- const dateTimeFormat = "YYYY-MM-DD HH:mm:ss";
414
- const currentDay = moment().format("DD");
415
- const currentMonth = moment().format("MM");
416
- const currentYear = moment().format("YYYY");
417
- const defaultTime = "00:00:00";
418
- const maxYear = parseInt(currentYear) + 10;
419
- const isValidDate = (day, month, year) => {
420
- const date = moment(`${day}-${month}-${year}`, "DD-MM-YYYY", true);
421
- return date.isValid();
422
- };
423
- const isValidTime = (hour, minute = "00", second = "00") => {
424
- const h = parseInt(hour, 10);
425
- const m = parseInt(minute, 10);
426
- const s = parseInt(second, 10);
427
- return h >= 0 && h <= 23 && m >= 0 && m <= 59 && s >= 0 && s <= 59;
428
- };
429
- const formatOutput = (day, month, year, time = defaultTime) => {
430
- let result = moment(
431
- `${day}-${month}-${year} ${time}`,
432
- "DD-MM-YYYY HH:mm:ss"
433
- );
434
- if (!result.isValid()) return null;
435
- if (isDateTime) {
436
- result = result.subtract(7, "hours");
437
- return result.format(dateTimeFormat);
438
- }
439
- return result.format(dateFormat);
440
- };
441
- if (isDateTime && input.match(
442
- /^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}\s+\d{1,2}(:\d{1,2}(:\d{1,2})?)?$/
443
- )) {
444
- const [datePart, timePart] = input.split(/\s+/);
445
- const dateParts = datePart.split(/[\/-]/);
446
- const timeParts = timePart.split(":");
447
- const day = dateParts[0].padStart(2, "0");
448
- const month = dateParts[1].padStart(2, "0");
449
- const year = dateParts[2].length <= 2 ? `20${dateParts[2].padStart(2, "0")}` : dateParts[2].padStart(4, "0");
450
- const hour = timeParts[0].padStart(2, "0");
451
- const minute = timeParts[1] ? timeParts[1].padStart(2, "0") : "00";
452
- const second = timeParts[2] ? timeParts[2].padStart(2, "0") : "00";
453
- if (isValidDate(day, month, year) && isValidTime(hour, minute, second)) {
454
- let result = moment(
455
- `${day}-${month}-${year} ${hour}:${minute}:${second}`,
456
- "DD-MM-YYYY HH:mm:ss"
457
- );
458
- if (!result.isValid()) return null;
459
- result = result.subtract(7, "hours");
460
- return result.format(dateTimeFormat);
461
- }
462
- return null;
463
- }
464
- if (cleanInput.match(/^\d{4}-\d{2}-\d{2}$/)) {
465
- const [year, month, day] = cleanInput.split("-");
466
- if (isValidDate(day, month, year)) {
467
- return formatOutput(day, month, year);
468
- }
469
- return null;
470
- }
471
- if (cleanInput.match(/^\d{1,2}\/\d{1,2}\/\d{2,4}$/)) {
472
- const [day, month, year] = cleanInput.split("/");
473
- const paddedDay = day.padStart(2, "0");
474
- const paddedMonth = month.padStart(2, "0");
475
- const fullYear = year.length <= 2 ? `20${year.padStart(2, "0")}` : year.padStart(4, "0");
476
- if (isValidDate(paddedDay, paddedMonth, fullYear)) {
477
- return formatOutput(paddedDay, paddedMonth, fullYear);
478
- }
479
- return null;
480
- }
481
- if (cleanInput.match(/^\d{1,2}-\d{1,2}-\d{2,4}$/)) {
482
- const [day, month, year] = cleanInput.split("-");
483
- const paddedDay = day.padStart(2, "0");
484
- const paddedMonth = month.padStart(2, "0");
485
- const fullYear = year.length <= 2 ? `20${year.padStart(2, "0")}` : year.padStart(4, "0");
486
- if (isValidDate(paddedDay, paddedMonth, fullYear)) {
487
- return formatOutput(paddedDay, paddedMonth, fullYear);
488
- }
489
- return null;
490
- }
491
- if (cleanInput.match(/^\d{1,2}[\/-]\d{1,2}$/)) {
492
- const [day, month] = cleanInput.split(/[\/-]/);
493
- const paddedDay = day.padStart(2, "0");
494
- const paddedMonth = month.padStart(2, "0");
495
- if (isValidDate(paddedDay, paddedMonth, currentYear)) {
496
- return formatOutput(paddedDay, paddedMonth, currentYear);
497
- }
498
- return null;
499
- }
500
- if (cleanInput.match(/^\d{4}$/)) {
501
- const num = parseInt(cleanInput, 10);
502
- if (num >= 2e3 && num <= maxYear) {
503
- if (isValidDate(currentDay, currentMonth, num.toString())) {
504
- return formatOutput(currentDay, currentMonth, num.toString());
505
- }
506
- return null;
507
- }
508
- const day = cleanInput.slice(0, 2);
509
- const month = cleanInput.slice(2, 4);
510
- if (isValidDate(day, month, currentYear)) {
511
- return formatOutput(day, month, currentYear);
512
- }
513
- return null;
514
- }
515
- if (cleanInput.startsWith("-") && /^\-\d+$/.test(cleanInput)) {
516
- const daysToSubtract = Math.abs(parseInt(cleanInput, 10));
517
- let result = moment().subtract(daysToSubtract, "days");
518
- if (isDateTime) {
519
- result = result.subtract(7, "hours");
520
- }
521
- if (result.isValid()) {
522
- return isDateTime ? result.format(dateTimeFormat) : result.format(dateFormat);
523
- }
524
- return null;
525
- }
526
- if (input.match(/^\d{1,2}[^0-9-\/]+\d{1,2}[^0-9-\/]+\d{2,4}.*$/)) {
527
- const parts = input.split(/[^0-9-\/]+/).filter(Boolean);
528
- const day = parts[0].padStart(2, "0");
529
- const month = parts[1].padStart(2, "0");
530
- let year = parts[2];
531
- year = year.length === 2 ? `20${year}` : year.padStart(4, "0");
532
- if (isValidDate(day, month, year)) {
533
- return formatOutput(day, month, year);
534
- }
535
- return null;
536
- }
537
- if (isDateTime) {
538
- if (cleanInput.length === 9) {
539
- const day = cleanInput.slice(0, 2);
540
- const month = cleanInput.slice(2, 4);
541
- const year = cleanInput.slice(4, 8);
542
- const hour = cleanInput.slice(8, 9).padStart(2, "0");
543
- if (isValidDate(day, month, year) && isValidTime(hour)) {
544
- let result = moment(
545
- `${day}-${month}-${year} ${hour}:00:00`,
546
- "DD-MM-YYYY HH:mm:ss"
547
- );
548
- if (!result.isValid()) return null;
549
- result = result.subtract(7, "hours");
550
- return result.format(dateTimeFormat);
551
- }
552
- return null;
553
- }
554
- if (cleanInput.length === 10) {
555
- const day = cleanInput.slice(0, 2);
556
- const month = cleanInput.slice(2, 4);
557
- const year = cleanInput.slice(4, 8);
558
- const hour = cleanInput.slice(8, 10);
559
- if (isValidDate(day, month, year) && isValidTime(hour)) {
560
- let result = moment(
561
- `${day}-${month}-${year} ${hour}:00:00`,
562
- "DD-MM-YYYY HH:mm:ss"
563
- );
564
- if (!result.isValid()) return null;
565
- result = result.subtract(7, "hours");
566
- return result.format(dateTimeFormat);
567
- }
568
- return null;
569
- }
570
- if (cleanInput.length === 11) {
571
- const day = cleanInput.slice(0, 2);
572
- const month = cleanInput.slice(2, 4);
573
- const year = cleanInput.slice(4, 8);
574
- const hour = cleanInput.slice(8, 10);
575
- const minute = cleanInput.slice(10, 11).padStart(2, "0");
576
- if (isValidDate(day, month, year) && isValidTime(hour, minute)) {
577
- let result = moment(
578
- `${day}-${month}-${year} ${hour}:${minute}:00`,
579
- "DD-MM-YYYY HH:mm:ss"
580
- );
581
- if (!result.isValid()) return null;
582
- result = result.subtract(7, "hours");
583
- return result.format(dateTimeFormat);
584
- }
585
- return null;
586
- }
587
- if (cleanInput.length === 12) {
588
- const day = cleanInput.slice(0, 2);
589
- const month = cleanInput.slice(2, 4);
590
- const year = cleanInput.slice(4, 8);
591
- const hour = cleanInput.slice(8, 10);
592
- const minute = cleanInput.slice(10, 12);
593
- if (isValidDate(day, month, year) && isValidTime(hour, minute)) {
594
- let result = moment(
595
- `${day}-${month}-${year} ${hour}:${minute}:00`,
596
- "DD-MM-YYYY HH:mm:ss"
597
- );
598
- if (!result.isValid()) return null;
599
- result = result.subtract(7, "hours");
600
- return result.format(dateTimeFormat);
601
- }
602
- return null;
603
- }
604
- if (cleanInput.length === 13) {
605
- const day = cleanInput.slice(0, 2);
606
- const month = cleanInput.slice(2, 4);
607
- const year = cleanInput.slice(4, 8);
608
- const hour = cleanInput.slice(8, 10);
609
- const minute = cleanInput.slice(10, 12);
610
- const second = cleanInput.slice(12, 13).padStart(2, "0");
611
- if (isValidDate(day, month, year) && isValidTime(hour, minute, second)) {
612
- let result = moment(
613
- `${day}-${month}-${year} ${hour}:${minute}:${second}`,
614
- "DD-MM-YYYY HH:mm:ss"
615
- );
616
- if (!result.isValid()) return null;
617
- result = result.subtract(7, "hours");
618
- return result.format(dateTimeFormat);
619
- }
620
- return null;
621
- }
622
- if (cleanInput.length === 14) {
623
- const day = cleanInput.slice(0, 2);
624
- const month = cleanInput.slice(2, 4);
625
- const year = cleanInput.slice(4, 8);
626
- const hour = cleanInput.slice(8, 10);
627
- const minute = cleanInput.slice(10, 12);
628
- const second = cleanInput.slice(12, 14);
629
- if (isValidDate(day, month, year) && isValidTime(hour, minute, second)) {
630
- let result = moment(
631
- `${day}-${month}-${year} ${hour}:${minute}:${second}`,
632
- "DD-MM-YYYY HH:mm:ss"
633
- );
634
- if (!result.isValid()) return null;
635
- result = result.subtract(7, "hours");
636
- return result.format(dateTimeFormat);
637
- }
638
- return null;
639
- }
640
- }
641
- const len = cleanInput.length;
642
- if (len === 1 || len === 2) {
643
- const paddedDay = cleanInput.padStart(2, "0");
644
- if (isValidDate(paddedDay, currentMonth, currentYear)) {
645
- return formatOutput(paddedDay, currentMonth, currentYear);
646
- }
647
- return null;
648
- }
649
- if (len === 3) {
650
- const day = cleanInput.slice(0, 2);
651
- const month = cleanInput.slice(2, 3).padStart(2, "0");
652
- if (isValidDate(day, month, currentYear)) {
653
- return formatOutput(day, month, currentYear);
654
- }
655
- return null;
656
- }
657
- if (len === 6) {
658
- const day = cleanInput.slice(0, 2);
659
- const month = cleanInput.slice(2, 4);
660
- let year = cleanInput.slice(4, 6);
661
- year = `20${year}`;
662
- if (parseInt(month) > 12) {
663
- if (isValidDate(day, currentMonth, currentYear)) {
664
- return formatOutput(day, currentMonth, currentYear);
665
- }
666
- return null;
667
- }
668
- if (isValidDate(day, month, year)) {
669
- return formatOutput(day, month, year);
670
- }
671
- return null;
672
- }
673
- if (len === 7) {
674
- return null;
675
- }
676
- if (len === 8) {
677
- const day = cleanInput.slice(0, 2);
678
- const month = cleanInput.slice(2, 4);
679
- const year = cleanInput.slice(4, 8);
680
- if (isValidDate(day, month, year)) {
681
- return formatOutput(day, month, year);
682
- }
683
- return null;
684
- }
685
- if (len > 8 && !isDateTime) {
686
- return null;
687
- }
688
- return null;
689
- };
690
-
691
- // src/utils.ts
692
- __reExport(utils_exports, utils_star);
693
- import * as utils_star from "@fctc/interface-logic/utils";
694
-
695
- // src/hooks/core/use-menu.ts
696
- var useMenu = ({
697
- context,
698
- specification,
699
- domain,
700
- defaultService
701
- }) => {
702
- const { useGetMenu: useGetMenu2 } = (0, provider_exports.useService)();
703
- const [action, callAction] = useCallAction();
704
- const [service, setService] = useState2("");
705
- const [xNode, setXNode] = useState2("");
706
- const menuData = useGetMenu2(
707
- context,
708
- specification,
709
- !!context && !isObjectEmpty(context) && !!context?.uid && !!context?.lang,
710
- domain,
711
- defaultService
712
- );
713
- const [menuId, setMenuId] = useState2(void 0);
714
- const handleChangeMenu = async ({
715
- menu,
716
- service: service2,
717
- xNode: xNode2,
718
- context: context2
719
- }) => {
720
- const aidMenu = menu?.action?.external_xml_id || menu?.action?.id?.id;
721
- if (menu) {
722
- setMenuId(menu.id?.toString() ?? "");
723
- }
724
- if (aidMenu) {
725
- const actionResponse = await callAction({
726
- aid: aidMenu,
727
- service: service2 ?? "",
728
- xNode: xNode2,
729
- context: context2
730
- });
731
- setService(service2 ?? "");
732
- setXNode(xNode2 ?? "");
733
- return actionResponse;
734
- }
735
- };
736
- return {
737
- ...menuData,
738
- service,
739
- xNode,
740
- data: menuData?.data,
741
- action: { handleChangeMenu },
742
- state: { menuId, action },
743
- context,
744
- isLoading: menuData.isLoading,
745
- isError: menuData.isError,
746
- error: menuData.error,
747
- refetch: menuData.refetch
748
- };
749
- };
750
-
751
- // src/hooks/core/use-detail.ts
752
- import { useQuery } from "@tanstack/react-query";
753
- import { useEffect as useEffect2 } from "react";
754
- var useDetail = (sub) => {
755
- const { setUserInfo, env } = (0, provider_exports.useEnv)();
756
- const { useGetDetail: useGetDetail2 } = (0, provider_exports.useService)();
757
- const fetchGetDetail = useGetDetail2();
758
- const userDetailQuery = useQuery({
759
- queryKey: ["userDetailQuery", sub],
760
- queryFn: () => {
761
- return fetchGetDetail.mutateAsync({
762
- model: "res.users",
763
- ids: [sub],
764
- specification: { image_256: {} },
765
- service: env?.default_service
766
- });
767
- },
768
- enabled: !!sub
769
- });
770
- useEffect2(() => {
771
- if (userDetailQuery.data) {
772
- const userPicture = userDetailQuery.data;
773
- setUserInfo({ ...env?.user, image: userPicture?.[0]?.image_256 });
774
- }
775
- }, [userDetailQuery.isFetched]);
776
- return { ...userDetailQuery };
777
- };
778
-
779
- // src/hooks/core/use-profile.ts
780
- import { useQuery as useQuery2 } from "@tanstack/react-query";
781
- import { useEffect as useEffect3, useMemo } from "react";
782
- var useProfile = ({
783
- service,
784
- i18n
785
- }) => {
786
- const { setUid, setLang, setUserInfo, env } = (0, provider_exports.useEnv)();
787
- const { useGetProfile: useGetProfile2 } = (0, provider_exports.useService)();
788
- const getProfile = useGetProfile2(service);
789
- const userInfoQuery = useQuery2({
790
- queryKey: ["userInfo"],
791
- queryFn: () => getProfile.mutateAsync(),
792
- enabled: isObjectEmpty(env?.user)
793
- });
794
- useEffect3(() => {
795
- if (userInfoQuery.data) {
796
- const userInfo = userInfoQuery.data;
797
- utils_exports.sessionStorageUtils.setXNode(userInfo?.x_node);
798
- setUid(userInfo?.sub);
799
- setUserInfo(userInfo);
800
- const userLocale = languages.find((lang) => lang?.id === userInfo?.locale);
801
- setLang(userLocale?.id);
802
- i18n.changeLanguage(userLocale?.id.split("_")[0]);
803
- }
804
- }, [userInfoQuery.isFetched]);
805
- const context = useMemo(() => {
806
- if (userInfoQuery.data?.sub && userInfoQuery.data?.locale) {
807
- return {
808
- uid: Number(userInfoQuery.data.sub),
809
- lang: String(userInfoQuery.data.locale),
810
- tz: "Asia/Saigon"
811
- };
812
- }
813
- return void 0;
814
- }, [userInfoQuery.isFetched]);
815
- if (userInfoQuery.isLoading || !userInfoQuery.data) {
816
- return null;
817
- }
818
- return {
819
- ...userInfoQuery,
820
- context
821
- };
822
- };
823
-
824
- // src/hooks/core/use-user.ts
825
- var useUser = ({ service, i18n }) => {
826
- const userProfile = useProfile({ service, i18n });
827
- const userDetail = useDetail(userProfile?.data?.sub);
828
- return { userProfile, userDetail, context: userProfile?.context };
829
- };
830
-
831
- // src/hooks/core/use-view-v2.ts
832
- import { useMemo as useMemo2 } from "react";
833
- var useViewV2 = ({
834
- action,
835
- context,
836
- aid,
837
- service,
838
- xNode
839
- }) => {
840
- const { useGetView: useGetView2 } = (0, provider_exports.useService)();
841
- const viewParams = useMemo2(() => {
842
- if (!action || !action?.res_model) {
843
- return void 0;
844
- }
845
- const actionResult = action;
846
- return {
847
- aid,
848
- model: String(actionResult?.res_model),
849
- views: [
850
- ...Array.isArray(actionResult?.views) ? actionResult?.views.map(
851
- (view2) => view2[1] === "list" ? [view2[0], "list"] : view2
852
- ) : [],
853
- [
854
- Array.isArray(actionResult?.search_view_id) ? actionResult?.search_view_id[0] : actionResult?.search_view_id,
855
- "search"
856
- ]
857
- ],
858
- context,
859
- id: isNaN(Number(aid)) ? action?.id : aid,
860
- service,
861
- xNode
862
- };
863
- }, [action, context, aid]);
864
- const view = useGetView2({
865
- viewParams: viewParams ?? {},
866
- enabled: !!viewParams
867
- });
868
- return {
869
- ...view,
870
- context
871
- };
872
- };
873
-
874
- // src/hooks/core/use-company.ts
875
- import { useQuery as useQuery3 } from "@tanstack/react-query";
876
- import { useEffect as useEffect4, useMemo as useMemo3 } from "react";
877
- var useCompany = ({ service }) => {
878
- const { setCompanies, setDefaultCompany, env } = (0, provider_exports.useEnv)();
879
- const { useGetCurrentCompany: useGetCurrentCompany2, useGetCompanyInfo: useGetCompanyInfo2 } = (0, provider_exports.useService)();
880
- const getCurrentCompany = useGetCurrentCompany2();
881
- const fetchCurrentCompany = async () => {
882
- return await getCurrentCompany.mutateAsync({
883
- service
884
- });
885
- };
886
- const currentCompany = useQuery3({
887
- queryKey: ["currentCompany"],
888
- queryFn: fetchCurrentCompany,
889
- enabled: !!env?.defaultCompany
890
- });
891
- const current_company_id = useMemo3(() => {
892
- return currentCompany.data?.current_company_id;
893
- }, [currentCompany.data]);
894
- useEffect4(() => {
895
- if (current_company_id) {
896
- const companyIDs = [current_company_id];
897
- setCompanies(companyIDs);
898
- }
899
- }, [current_company_id]);
900
- const getCompanyInfo = useGetCompanyInfo2();
901
- const companyInfo = useQuery3({
902
- queryKey: ["companyInfoQuery", current_company_id],
903
- queryFn: () => getCompanyInfo.mutateAsync({
904
- service,
905
- id: Number(current_company_id)
906
- }),
907
- enabled: !!current_company_id
908
- });
909
- useEffect4(() => {
910
- if (companyInfo.data) {
911
- const companyInfoData = companyInfo.data;
912
- if (companyInfoData?.length) {
913
- setDefaultCompany(companyInfoData[0]);
914
- }
915
- }
916
- }, [companyInfo.data]);
917
- if (!companyInfo?.data || !currentCompany?.data) return;
918
- return {
919
- currentCompany: { ...currentCompany },
920
- companyInfo: { ...companyInfo }
921
- };
922
- };
923
-
924
- // src/hooks/core/use-app-provider.tsx
925
- import { jsx } from "react/jsx-runtime";
926
- var AppProviderInitialValue = {
927
- user: {},
928
- company: {},
929
- action: {},
930
- menu: {},
931
- view: {}
932
- };
933
- var ReactContext = createContext(AppProviderInitialValue);
934
- var AppProvider = ({
935
- children,
936
- menuParams,
937
- aid,
938
- i18n
939
- }) => {
940
- const { env } = (0, provider_exports.useEnv)();
941
- const user = useUser({ service: env.default_service, i18n });
942
- const company = useCompany({ service: env.default_service });
943
- const menuContext = useMemo4(() => {
944
- return (0, utils_exports.combineContexts)([
945
- {
946
- ...user?.context,
947
- ...!isObjectEmpty(env?.user) ? { lang: env?.context?.lang } : {},
948
- ...menuParams?.context ?? {}
949
- }
950
- ]);
951
- }, [user?.context, company?.companyInfo?.isFetched, env?.context?.lang]);
952
- const menu = useMenu({
953
- context: {
954
- ...menuContext
955
- },
956
- specification: menuParams?.specification,
957
- domain: menuParams?.domain,
958
- defaultService: env.default_service
959
- });
960
- const action = useMemo4(() => {
961
- return menu?.state?.action;
962
- }, [menu?.state?.action, env?.context?.lang]);
963
- const viewContext = useMemo4(() => {
964
- return (0, utils_exports.combineContexts)([
965
- menuContext,
966
- { ...(0, utils_exports.evalJSONContext)(action?.context) }
967
- ]);
968
- }, [menuContext, action?.context, env?.context?.lang]);
969
- const view = useViewV2({
970
- action,
971
- context: viewContext,
972
- aid,
973
- service: menu?.service,
974
- xNode: menu?.xNode
975
- });
976
- return /* @__PURE__ */ jsx(
977
- ReactContext.Provider,
978
- {
979
- value: {
980
- user,
981
- company,
982
- menu,
983
- action,
984
- view
985
- },
986
- children
987
- }
988
- );
989
- };
990
- var useAppProvider = () => {
991
- const context = useContext(ReactContext);
992
- if (!context) {
993
- return AppProviderInitialValue;
994
- }
995
- return context;
996
- };
997
-
998
- // src/hooks/core/use-config.ts
999
- import { useEffect as useEffect5 } from "react";
1000
- var useConfig = ({
1001
- envConfig,
1002
- config,
1003
- localStorageUtils,
1004
- sessionStorageUtils: sessionStorageUtils2
1005
- }) => {
1006
- const { setupEnv, setEnvFile } = (0, provider_exports.useEnv)();
1007
- useEffect5(() => {
1008
- try {
1009
- setupEnv({
1010
- baseUrl: envConfig.baseUrl,
1011
- config: envConfig.config,
1012
- default_service: "",
1013
- localStorageUtils: localStorageUtils && localStorageUtils(),
1014
- sessionStorageUtils: localStorageUtils && sessionStorageUtils2()
1015
- });
1016
- setEnvFile(config);
1017
- } catch (error) {
1018
- console.error("Error loading env or config:", error);
1019
- }
1020
- }, [envConfig, config]);
1021
- return { envConfig, config };
1022
- };
1023
-
1024
- // src/hooks/core/use-get-action.ts
1025
- var useGetAction = ({
1026
- aid,
1027
- context
1028
- }) => {
1029
- const { useLoadAction: useLoadAction2, useRunAction: useRunAction2 } = (0, provider_exports.useService)();
1030
- const queryLoadAction = useLoadAction2();
1031
- const queryRunAction = useRunAction2();
1032
- const handleActionResult = (data) => {
1033
- if (data && data.result && data.result.views && Array.isArray(data.result.views) && data.result.views.length > 0) {
1034
- }
1035
- };
1036
- const onLoadAction = () => {
1037
- queryLoadAction.mutate(
1038
- {
1039
- idAction: aid,
1040
- context
1041
- },
1042
- {
1043
- onSuccess: (data) => {
1044
- if (data?.result?.type === "ir.actions.act_window") {
1045
- handleActionResult(data);
1046
- } else if (data?.result?.type === "ir.actions.server") {
1047
- queryRunAction.mutate(
1048
- {
1049
- idAction: aid,
1050
- context
1051
- },
1052
- {
1053
- onSuccess: handleActionResult
1054
- }
1055
- );
1056
- }
1057
- }
1058
- }
1059
- );
1060
- };
1061
- return {
1062
- onLoadAction
1063
- };
1064
- };
1065
-
1066
- // src/hooks/core/use-get-specification.ts
1067
- import { useMemo as useMemo5 } from "react";
1068
- var useGetSpecification = ({
1069
- model,
1070
- viewData,
1071
- fields
1072
- }) => {
1073
- const baseModel = useMemo5(
1074
- () => ({
1075
- name: String(model),
1076
- view: viewData,
1077
- fields
1078
- }),
1079
- [model, viewData, fields]
1080
- );
1081
- const initModel = useModel();
1082
- const modelInstance = useMemo5(() => {
1083
- if (viewData) {
1084
- return initModel.initModel(baseModel);
1085
- }
1086
- return null;
1087
- }, [baseModel, viewData, model]);
1088
- const specification = useMemo5(() => {
1089
- if (modelInstance) {
1090
- return modelInstance.getSpecification();
1091
- }
1092
- return null;
1093
- }, [modelInstance, model]);
1094
- return { specification };
1095
- };
1096
-
1097
- // src/hooks/core/use-list-data.ts
1098
- import { useMemo as useMemo6, useState as useState5 } from "react";
1099
- import {
1100
- evalJSONDomain,
1101
- formatSortingString
1102
- } from "@fctc/interface-logic/utils";
1103
-
1104
- // src/hooks/utils/use-debounce.ts
1105
- import { useEffect as useEffect6, useState as useState3 } from "react";
1106
- function useDebounce(value, delay) {
1107
- const [debouncedValue, setDebouncedValue] = useState3(value);
1108
- useEffect6(() => {
1109
- const handler = setTimeout(() => {
1110
- setDebouncedValue(value);
1111
- }, delay);
1112
- return () => {
1113
- clearTimeout(handler);
1114
- };
1115
- }, [value, delay]);
1116
- return [debouncedValue];
1117
- }
1118
-
1119
- // src/hooks/utils/use-get-rowids.ts
1120
- import { useCallback as useCallback3, useEffect as useEffect7, useRef, useState as useState4 } from "react";
1121
- var useGetRowIds = (tableRef) => {
1122
- function isElementVisible(el) {
1123
- const style = window.getComputedStyle(el);
1124
- return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
1125
- }
1126
- function arraysAreEqual(a, b) {
1127
- if (a.length !== b.length) return false;
1128
- if (a.length === 0 && b.length === 0) return true;
1129
- const setA = new Set(a);
1130
- const setB = new Set(b);
1131
- if (setA.size !== setB.size) return false;
1132
- for (const val of setA) {
1133
- if (!setB.has(val)) return false;
1134
- }
1135
- return true;
1136
- }
1137
- const [rowIds, setRowIds] = useState4([]);
1138
- const lastRowIdsRef = useRef([]);
1139
- const updateVisibleRowIds = useCallback3(() => {
1140
- const table = tableRef.current;
1141
- if (!table) return;
1142
- const rows = table.querySelectorAll("tr[data-row-id]");
1143
- const ids = [];
1144
- rows.forEach((row) => {
1145
- const el = row;
1146
- if (isElementVisible(el)) {
1147
- const id = el.getAttribute("data-row-id");
1148
- if (id) ids.push(id);
1149
- }
1150
- });
1151
- const uniqueIds = Array.from(new Set(ids));
1152
- if (!arraysAreEqual(lastRowIdsRef.current, uniqueIds)) {
1153
- lastRowIdsRef.current = uniqueIds;
1154
- setRowIds(uniqueIds);
1155
- }
1156
- }, [tableRef]);
1157
- useEffect7(() => {
1158
- const table = tableRef.current;
1159
- if (!table) return;
1160
- const mutationObserver = new MutationObserver(() => {
1161
- updateVisibleRowIds();
1162
- });
1163
- mutationObserver.observe(table, {
1164
- childList: true,
1165
- subtree: true,
1166
- attributes: true,
1167
- attributeFilter: ["style", "class"]
1168
- });
1169
- const resizeObserver = new ResizeObserver(() => {
1170
- updateVisibleRowIds();
1171
- });
1172
- resizeObserver.observe(table);
1173
- const handleScroll = () => updateVisibleRowIds();
1174
- table.addEventListener("scroll", handleScroll, true);
1175
- updateVisibleRowIds();
1176
- return () => {
1177
- mutationObserver.disconnect();
1178
- resizeObserver.disconnect();
1179
- table.removeEventListener("scroll", handleScroll, true);
1180
- };
1181
- }, [updateVisibleRowIds, tableRef?.current]);
1182
- return { rowIds, refresh: updateVisibleRowIds };
1183
- };
1184
-
1185
- // src/hooks/core/use-list-data.ts
1186
- var useListData = ({
1187
- action,
1188
- context,
1189
- viewData,
1190
- model,
1191
- service,
1192
- xNode,
1193
- mode,
1194
- limit = 10
1195
- }) => {
1196
- const { useGetListData: useGetListData2 } = (0, provider_exports.useService)();
1197
- const [page, setPage] = useState5(0);
1198
- const [pageLimit, setPageLimit] = useState5(limit);
1199
- const [groupByList, setGroupByList] = useState5(null);
1200
- const [domain, setDomain] = useState5(null);
1201
- const [order, setOrder] = useState5("");
1202
- const [selectedRowKeys, setSelectedRowKeys] = useState5([]);
1203
- const [debouncedPage] = useDebounce(page, 500);
1204
- const [debouncedDomain] = useDebounce(domain, 500);
1205
- const { specification } = useGetSpecification({
1206
- model,
1207
- viewData,
1208
- fields: mode === "kanban" ? viewData?.views?.kanban?.fields : viewData?.views?.list?.fields
1209
- });
1210
- const listDataProps = useMemo6(() => {
1211
- if (!viewData || !action || !context) {
1212
- return null;
1213
- }
1214
- const domainParse = domain ? [...domain] : action?.domain ? Array.isArray(action?.domain) ? [...action?.domain] : evalJSONDomain(action?.domain, context) : [];
1215
- const limit2 = pageLimit;
1216
- const offset = debouncedPage * pageLimit;
1217
- const fields = typeof groupByList === "object" ? groupByList?.fields : void 0;
1218
- const groupby = typeof groupByList === "object" ? [groupByList?.contexts?.[0]?.group_by] : [];
1219
- const sort = order ?? formatSortingString(
1220
- (mode === "kanban" ? viewData?.views?.kanban : viewData?.views?.list)?.default_order
1221
- ) ?? "";
1222
- return {
1223
- model: action?.res_model,
1224
- specification,
1225
- domain: domainParse,
1226
- limit: limit2,
1227
- offset,
1228
- fields,
1229
- groupby,
1230
- context,
1231
- sort,
1232
- mode
1233
- };
1234
- }, [
1235
- action,
1236
- groupByList,
1237
- order,
1238
- debouncedPage,
1239
- pageLimit,
1240
- debouncedDomain,
1241
- context,
1242
- model
1243
- ]);
1244
- const list = useGetListData2(
1245
- { ...listDataProps },
1246
- [
1247
- listDataProps?.domain,
1248
- listDataProps?.groupby,
1249
- listDataProps?.limit,
1250
- listDataProps?.offset,
1251
- listDataProps?.sort,
1252
- listDataProps?.context,
1253
- listDataProps?.specification,
1254
- listDataProps?.mode
1255
- ],
1256
- !!listDataProps && !!specification && !isObjectEmpty(specification) && !!domain,
1257
- service,
1258
- xNode
1259
- );
1260
- return {
1261
- ...list,
1262
- state: {
1263
- specification,
1264
- page,
1265
- order,
1266
- domain: listDataProps?.domain,
1267
- pageLimit,
1268
- groupByList,
1269
- selectedRowKeys,
1270
- setPage,
1271
- setOrder,
1272
- setDomain,
1273
- setPageLimit,
1274
- setGroupByList,
1275
- setSelectedRowKeys
1276
- }
1277
- };
1278
- };
1279
-
1280
- // src/config.ts
1281
- var config_exports = {};
1282
- __reExport(config_exports, configs_star);
1283
- import * as configs_star from "@fctc/interface-logic/configs";
1284
-
1285
- // src/index.ts
1286
- __reExport(index_exports, config_exports);
1287
-
1288
- // src/widget/basic/status-dropdown-field/controller.ts
1289
- import { useEffect as useEffect8, useRef as useRef2, useState as useState6 } from "react";
1290
- import { getEnv } from "@fctc/interface-logic/environment";
1291
- import { useSave as useSave2 } from "@fctc/interface-logic/hooks";
1292
- var statusDropdownController = (props) => {
1293
- const { selection, isForm, id, model, name, state, onRefetch } = props;
1294
- const env = getEnv();
1295
- const colors = {
1296
- normal: "bg-[#e9ecef]",
1297
- done: "bg-primary",
1298
- blocked: "bg-red-500"
1299
- };
1300
- const [isOpen, setIsOpen] = useState6(false);
1301
- const buttonRef = useRef2(null);
1302
- useEffect8(() => {
1303
- const handleClickOutside = (event) => {
1304
- if (buttonRef.current && !buttonRef.current.contains(event.target)) {
1305
- setIsOpen(false);
1306
- }
1307
- };
1308
- document.addEventListener("mousedown", handleClickOutside);
1309
- return () => {
1310
- document.removeEventListener("mousedown", handleClickOutside);
1311
- };
1312
- }, []);
1313
- const { mutate: onSave } = useSave2();
1314
- const handleClick = async (status) => {
1315
- setIsOpen(!isOpen);
1316
- onSave(
1317
- {
1318
- ids: id ? [id] : [],
1319
- model: model ?? "",
1320
- data: { [name ?? ""]: status },
1321
- context: env.context
1322
- },
1323
- {
1324
- onSuccess: () => {
1325
- onRefetch && onRefetch();
1326
- }
1327
- }
1328
- );
1329
- };
1330
- return {
1331
- handleClick,
1332
- buttonRef,
1333
- isForm,
1334
- setIsOpen,
1335
- isOpen,
1336
- selection,
1337
- state,
1338
- colors
1339
- };
1340
- };
1341
-
1342
- // src/widget/basic/many2one-field/controller.ts
1343
- import { useCallback as useCallback4, useEffect as useEffect9, useMemo as useMemo7, useState as useState7 } from "react";
1344
- var MANY2ONE_EXTERNAL = "many2one_external";
1345
- var many2oneFieldController = (props) => {
1346
- const {
1347
- methods,
1348
- relation,
1349
- domain,
1350
- formValues,
1351
- value: propValue,
1352
- onChange,
1353
- name,
1354
- context: fieldContext,
1355
- options: fieldOptions,
1356
- showDetail,
1357
- service,
1358
- xNode,
1359
- isForm,
1360
- widget,
1361
- in_list_view,
1362
- isEditTable
1363
- } = props;
1364
- const { env } = (0, provider_exports.useEnv)();
1365
- const { action } = useAppProvider();
1366
- const { useGetSelection: useGetSelection3, useGetDetail: useGetDetail2 } = (0, provider_exports.useService)();
1367
- const [listOptions, setListOptions] = useState7([]);
1368
- const [inputValue, setInputValue] = useState7("");
1369
- const [debouncedInputValue] = useDebounce(inputValue, 1e3);
1370
- const [isShowModalMany2Many, setIsShowModalMany2Many] = useState7(false);
1371
- const [tempSelectedOption, setTempSelectedOption] = useState7(null);
1372
- const [domainModal, setDomainModal] = useState7(null);
1373
- const [domainObject, setDomainObject] = useState7(null);
1374
- const initValue = methods?.getValues(name);
1375
- const contextObject = {
1376
- ...(typeof action?.context === "string" ? (0, utils_exports.evalJSONContext)(action?.context) : action?.context) || {},
1377
- ...fieldContext,
1378
- ...env?.context
1379
- };
1380
- const optionsObject = typeof fieldOptions === "string" ? (0, utils_exports.evalJSONContext)(fieldOptions, {
1381
- ...formValues,
1382
- ...contextObject,
1383
- context: contextObject,
1384
- parent: { ...formValues }
1385
- }) : fieldOptions;
1386
- const fetchGetDetail = useGetDetail2();
1387
- const data = {
1388
- model: widget === MANY2ONE_EXTERNAL ? optionsObject?.model : relation,
1389
- domain: widget === MANY2ONE_EXTERNAL ? optionsObject?.domain : domainObject,
1390
- context: {
1391
- ...contextObject,
1392
- ...optionsObject?.context
1393
- },
1394
- specification: widget === MANY2ONE_EXTERNAL ? optionsObject?.specification : {
1395
- id: {},
1396
- name: {},
1397
- display_name: {}
1398
- }
1399
- };
1400
- const {
1401
- data: dataOfSelection,
1402
- refetch,
1403
- isFetching
1404
- } = useGetSelection3({
1405
- data,
1406
- queryKey: [`data_${relation}`, domainObject],
1407
- enabled: false,
1408
- service: widget === MANY2ONE_EXTERNAL ? optionsObject?.service : service,
1409
- xNode
1410
- });
1411
- const selectOptions = useMemo7(() => {
1412
- return dataOfSelection?.records?.map((val) => ({
1413
- value: val?.id,
1414
- label: val?.display_name || val?.name,
1415
- ...widget === MANY2ONE_EXTERNAL ? val : {}
1416
- })) || [];
1417
- }, [dataOfSelection]);
1418
- useEffect9(() => {
1419
- setListOptions(selectOptions);
1420
- setDomainModal(domainObject);
1421
- }, [selectOptions]);
1422
- const parsedFormValues = useMemo7(
1423
- () => JSON.parse(
1424
- JSON.stringify({
1425
- ...formValues,
1426
- ...contextObject,
1427
- context: contextObject
1428
- })
1429
- ) ?? {},
1430
- [formValues, contextObject]
1431
- );
1432
- useEffect9(() => {
1433
- const newDomain = (0, utils_exports.evalJSONDomain)(domain, parsedFormValues);
1434
- const parsedDomain = typeof newDomain === "string" ? JSON.parse(
1435
- newDomain.replace(/\(/g, "[").replace(/\)/g, "]").replace(/'/g, '"')
1436
- ) : newDomain;
1437
- setDomainObject((prev) => {
1438
- const prevStr = JSON.stringify(prev);
1439
- const nextStr = JSON.stringify(parsedDomain);
1440
- return prevStr === nextStr ? prev : parsedDomain;
1441
- });
1442
- }, [domain, parsedFormValues]);
1443
- useEffect9(() => {
1444
- if (!propValue && tempSelectedOption) {
1445
- methods?.setValue(name, null, { shouldDirty: true });
1446
- setTempSelectedOption(null);
1447
- } else if (propValue) {
1448
- if (isForm && !isEditTable && optionsObject?.service && optionsObject?.model && !propValue?.display_name && !in_list_view) {
1449
- fetchGetDetail.mutate(
1450
- {
1451
- model: optionsObject?.model,
1452
- ids: propValue?.id ?? propValue,
1453
- specification: widget === MANY2ONE_EXTERNAL ? optionsObject?.specification : {
1454
- id: {},
1455
- display_name: {}
1456
- },
1457
- context: { ...env.context },
1458
- service: optionsObject ? optionsObject?.service : service,
1459
- xNode
1460
- },
1461
- {
1462
- onSuccess: (dataResponse) => {
1463
- const detailData = dataResponse?.[0];
1464
- setTempSelectedOption({
1465
- value: detailData?.id,
1466
- label: detailData?.display_name
1467
- });
1468
- if (widget === MANY2ONE_EXTERNAL && optionsObject?.values_included) {
1469
- Object.keys(optionsObject?.values_included)?.forEach(
1470
- (field) => {
1471
- methods?.setValue(
1472
- optionsObject?.values_included[field]?.name,
1473
- detailData?.[field]
1474
- );
1475
- }
1476
- );
1477
- methods?.setValue(name, detailData);
1478
- }
1479
- },
1480
- onError: (error) => {
1481
- console.log("error", error);
1482
- }
1483
- }
1484
- );
1485
- return;
1486
- }
1487
- setTempSelectedOption({
1488
- value: propValue?.id,
1489
- label: propValue?.display_name
1490
- });
1491
- }
1492
- }, [propValue]);
1493
- const fetchMoreOptions = useCallback4(() => {
1494
- refetch();
1495
- }, [refetch]);
1496
- useEffect9(() => {
1497
- if (debouncedInputValue) {
1498
- const filteredDomain = [...domainObject ?? []]?.filter(
1499
- (d) => !(Array.isArray(d) && d[0] === "name" && d[1] === "ilike")
1500
- ) || [];
1501
- const newDomain = [
1502
- ...filteredDomain,
1503
- ...debouncedInputValue ? [["name", "ilike", debouncedInputValue]] : []
1504
- ];
1505
- setDomainObject(newDomain);
1506
- setTimeout(() => {
1507
- fetchMoreOptions();
1508
- }, 50);
1509
- }
1510
- }, [debouncedInputValue]);
1511
- const handleChooseRecord = useCallback4(
1512
- (idRecord) => {
1513
- const newOption = listOptions?.find(
1514
- (option) => option.value === idRecord
1515
- );
1516
- const newValue = widget === MANY2ONE_EXTERNAL && optionsObject?.field_name ? newOption?.[optionsObject?.field_name] : newOption.value;
1517
- if (widget === MANY2ONE_EXTERNAL && optionsObject?.values_included) {
1518
- Object.keys(optionsObject?.values_included)?.forEach((field) => {
1519
- methods?.setValue(
1520
- optionsObject?.values_included[field]?.name,
1521
- newOption?.[field],
1522
- { shouldDirty: true }
1523
- );
1524
- });
1525
- }
1526
- if (newOption) {
1527
- methods?.setValue(
1528
- name,
1529
- {
1530
- ...newOption,
1531
- id: newValue,
1532
- display_name: newOption?.label
1533
- },
1534
- { shouldDirty: true }
1535
- );
1536
- setTempSelectedOption(newOption);
1537
- onChange && onChange(String(name), {
1538
- ...newOption,
1539
- id: newValue,
1540
- display_name: newOption?.label
1541
- });
1542
- methods.trigger(name);
1543
- }
1544
- setIsShowModalMany2Many(false);
1545
- },
1546
- [listOptions, methods, name, onChange]
1547
- );
1548
- const handleClose = useCallback4(() => setIsShowModalMany2Many(false), []);
1549
- const handleSelectChange = useCallback4(
1550
- (selectedOption) => {
1551
- if (!selectedOption) {
1552
- if (widget === MANY2ONE_EXTERNAL && optionsObject?.values_included) {
1553
- Object.keys(optionsObject?.values_included)?.forEach((field) => {
1554
- methods?.setValue(
1555
- optionsObject?.values_included[field]?.name,
1556
- null,
1557
- { shouldDirty: true }
1558
- );
1559
- });
1560
- }
1561
- methods.setValue(name, null, { shouldDirty: true });
1562
- setTempSelectedOption(null);
1563
- onChange && onChange(String(name), null);
1564
- methods.trigger(name);
1565
- return;
1566
- }
1567
- const newValue = widget === MANY2ONE_EXTERNAL && optionsObject?.field_name ? selectedOption?.[optionsObject?.field_name] : selectedOption.value;
1568
- if (widget === MANY2ONE_EXTERNAL && optionsObject?.values_included) {
1569
- Object.keys(optionsObject?.values_included)?.forEach((field) => {
1570
- methods?.setValue(
1571
- optionsObject?.values_included[field]?.name,
1572
- selectedOption?.[field],
1573
- { shouldDirty: true }
1574
- );
1575
- });
1576
- }
1577
- methods?.setValue(
1578
- name,
1579
- {
1580
- id: newValue,
1581
- display_name: selectedOption?.label
1582
- },
1583
- { shouldDirty: true }
1584
- );
1585
- setTempSelectedOption(selectedOption);
1586
- onChange && onChange(String(name), {
1587
- id: newValue,
1588
- display_name: selectedOption.label
1589
- });
1590
- methods.trigger(name);
1591
- },
1592
- [methods, name, onChange]
1593
- );
1594
- const allowShowDetail = showDetail && contextObject?.form_view_ref && (!optionsObject || !("no_open" in optionsObject) || optionsObject.no_open === false);
1595
- return {
1596
- isShowModalMany2Many,
1597
- isFetching,
1598
- initValue,
1599
- handleChooseRecord,
1600
- handleClose,
1601
- handleSelectChange,
1602
- domainModal,
1603
- setInputValue,
1604
- allowShowDetail,
1605
- contextObject: {
1606
- ...contextObject,
1607
- ...optionsObject?.context
1608
- },
1609
- tempSelectedOption,
1610
- listOptions,
1611
- fetchMoreOptions,
1612
- domainObject: widget === MANY2ONE_EXTERNAL ? optionsObject?.domain : domainObject,
1613
- setIsShowModalMany2Many,
1614
- setDomainObject,
1615
- options: optionsObject,
1616
- relation: widget === MANY2ONE_EXTERNAL ? optionsObject?.model : relation,
1617
- service: widget === MANY2ONE_EXTERNAL ? optionsObject?.service : service
1618
- };
1619
- };
1620
-
1621
- // src/widget/basic/many2one-button-field/controller.ts
1622
- import { getEnv as getEnv2 } from "@fctc/interface-logic/environment";
1623
- import { useGetSelection as useGetSelection2 } from "@fctc/interface-logic/hooks";
1624
- import { evalJSONDomain as evalJSONDomain3, evalJSONContext as evalJSONContext3 } from "@fctc/interface-logic/utils";
1625
- var many2oneButtonController = (props) => {
1626
- const { domain, methods, relation, service, xNode } = props;
1627
- const actionDataString = sessionStorage.getItem("actionData");
1628
- const env = getEnv2();
1629
- const domainObject = evalJSONDomain3(domain, methods?.getValues() || {});
1630
- const actionData = actionDataString && actionDataString !== "undefined" ? JSON.parse(actionDataString) : {};
1631
- const { data: dataOfSelection } = useGetSelection2({
1632
- data: {
1633
- model: relation ?? "",
1634
- domain: domainObject,
1635
- context: { ...env.context, ...evalJSONContext3(actionData?.context) }
1636
- },
1637
- queryKey: [`data_${relation}`, domainObject],
1638
- service,
1639
- xNode
1640
- });
1641
- const options = dataOfSelection?.records?.map((val) => ({
1642
- value: val.id,
1643
- label: val.name
1644
- })) || [];
1645
- return {
1646
- options
1647
- };
1648
- };
1649
-
1650
- // src/widget/basic/many2many-field/controller.ts
1651
- import { useEffect as useEffect10, useMemo as useMemo8 } from "react";
1652
- import { evalJSONContext as evalJSONContext4 } from "@fctc/interface-logic/utils";
1653
- var many2manyFieldController = (props) => {
1654
- const {
1655
- relation,
1656
- domain,
1657
- context,
1658
- options,
1659
- enabled: enabledCallAPI,
1660
- service
1661
- } = props;
1662
- const { env } = (0, provider_exports.useEnv)();
1663
- const { user } = useAppProvider();
1664
- const { useGetView: useGetView2 } = (0, provider_exports.useService)();
1665
- const dataUser = user?.userProfile?.data;
1666
- const contextObject = useMemo8(
1667
- () => ({
1668
- ...env.context,
1669
- ...context || {}
1670
- }),
1671
- [env?.context, context]
1672
- );
1673
- const viewParams = useMemo8(
1674
- () => ({
1675
- model: relation,
1676
- views: [
1677
- [false, "list"],
1678
- [false, "search"]
1679
- ],
1680
- context: contextObject,
1681
- service,
1682
- xNode: service == "wesap" && dataUser?.x_node
1683
- }),
1684
- [relation, contextObject, service, dataUser?.x_node]
1685
- );
1686
- const { data: viewResponse } = useGetView2({
1687
- viewParams,
1688
- enabled: enabledCallAPI
1689
- });
1690
- const default_order = viewResponse && viewResponse?.views?.list?.default_order;
1691
- const optionsObject = useMemo8(
1692
- () => (options && typeof options === "string" ? evalJSONContext4(options) : options) || {},
1693
- [options]
1694
- );
1695
- const {
1696
- data: dataResponse,
1697
- isFetched,
1698
- isLoading,
1699
- state,
1700
- isPlaceholderData
1701
- } = useListData({
1702
- action: {
1703
- domain,
1704
- res_model: relation
1705
- },
1706
- context: contextObject,
1707
- model: relation ?? "",
1708
- viewData: viewResponse,
1709
- service,
1710
- xNode: service == "wesap" && dataUser?.x_node
1711
- });
1712
- const {
1713
- selectedRowKeys,
1714
- groupByList,
1715
- domain: domainList,
1716
- page,
1717
- pageLimit,
1718
- setDomain,
1719
- setOrder,
1720
- setPage,
1721
- setSelectedRowKeys,
1722
- setGroupByList,
1723
- setPageLimit,
1724
- specification
1725
- } = state;
1726
- useEffect10(() => {
1727
- return () => {
1728
- setDomain(null);
1729
- setOrder("");
1730
- setGroupByList(null);
1731
- setPageLimit(10);
1732
- };
1733
- }, []);
1734
- const { rows, columns, typeTable, onToggleColumnOptional } = tableController({
1735
- data: {
1736
- fields: viewResponse?.views?.list?.fields,
1737
- records: dataResponse?.records ?? dataResponse?.groups,
1738
- dataModel: viewResponse?.models?.[String(relation)],
1739
- context: contextObject,
1740
- typeTable: dataResponse?.groups ? "group" : "list"
1741
- }
1742
- });
1743
- const searchControllers = searchController({
1744
- viewData: viewResponse,
1745
- model: relation ?? "",
1746
- context: contextObject,
1747
- domain,
1748
- fieldsList: [
1749
- ...columns?.filter(
1750
- (col) => col?.field?.type_co === "field" && col?.optional !== "hide"
1751
- )?.map((col) => ({ ...col.field })) ?? []
1752
- ]
1753
- });
1754
- const handleCreateNewOnPage = async () => {
1755
- };
1756
- return {
1757
- rows,
1758
- columns,
1759
- optionsObject,
1760
- viewData: viewResponse,
1761
- totalRows: dataResponse?.length ?? 0,
1762
- onToggleColumnOptional,
1763
- typeTable,
1764
- isLoading,
1765
- isFetched,
1766
- isPlaceholderData,
1767
- page,
1768
- pageLimit,
1769
- groupByList,
1770
- selectedRowKeys,
1771
- domain: domainList,
1772
- setPage,
1773
- setDomain,
1774
- setPageLimit,
1775
- setGroupByList,
1776
- setSelectedRowKeys,
1777
- searchController: searchControllers,
1778
- handleCreateNewOnPage,
1779
- specification
1780
- };
1781
- };
1782
-
1783
- // src/widget/basic/many2many-tags-field/controller.ts
1784
- import { useCallback as useCallback5, useEffect as useEffect11, useMemo as useMemo9, useState as useState8 } from "react";
1785
- import { WIDGETAVATAR, WIDGETCOLOR } from "@fctc/interface-logic/constants";
1786
- import { evalJSONContext as evalJSONContext5, evalJSONDomain as evalJSONDomain4 } from "@fctc/interface-logic/utils";
1787
- var many2manyTagsController = (props) => {
1788
- const {
1789
- relation,
1790
- domain,
1791
- options: optionsFields,
1792
- widget,
1793
- formValues,
1794
- service,
1795
- xNode,
1796
- context: fieldContext,
1797
- onChange,
1798
- methods,
1799
- name
1800
- } = props;
1801
- const isUser = relation === "res.users" || relation === "res.partner";
1802
- const { env } = (0, provider_exports.useEnv)();
1803
- const { action } = useAppProvider();
1804
- const { useGetSelection: useGetSelection3 } = (0, provider_exports.useService)();
1805
- const [options, setOptions] = useState8([]);
1806
- const [domainObject, setDomainObject] = useState8(null);
1807
- const [isShowModalMany2Many, setIsShowModalMany2Many] = useState8(false);
1808
- const addtionalFields = optionsFields ? evalJSONContext5(optionsFields) : null;
1809
- const contextObject = {
1810
- ...evalJSONContext5(action?.context) || {},
1811
- ...fieldContext ?? {},
1812
- ...env?.context
1813
- };
1814
- const parsedFormValues = useMemo9(
1815
- () => JSON.parse(
1816
- JSON.stringify({
1817
- ...formValues,
1818
- ...contextObject,
1819
- context: contextObject,
1820
- parent: { ...formValues }
1821
- })
1822
- ) ?? {},
1823
- [formValues, contextObject]
1824
- );
1825
- useEffect11(() => {
1826
- const newDomain = evalJSONDomain4(domain, parsedFormValues);
1827
- setDomainObject(
1828
- (prev) => JSON.stringify(prev) === JSON.stringify(newDomain) ? prev : newDomain
1829
- );
1830
- }, [domain, parsedFormValues]);
1831
- const data = {
1832
- model: relation ?? "",
1833
- domain: domainObject,
1834
- specification: {
1835
- id: {},
1836
- name: {},
1837
- display_name: {},
1838
- ...widget && WIDGETAVATAR[widget] ? { image_256: {} } : {},
1839
- ...widget && WIDGETCOLOR[widget] && addtionalFields?.color_field ? { color: {} } : {}
1840
- },
1841
- context: env.context
1842
- };
1843
- const queryKey = [`data_${relation}`, domainObject];
1844
- const {
1845
- data: dataOfSelection,
1846
- refetch,
1847
- isFetching
1848
- } = useGetSelection3({
1849
- data,
1850
- queryKey,
1851
- service,
1852
- xNode,
1853
- enabled: false
1854
- });
1855
- const selectOptions = useMemo9(() => {
1856
- return dataOfSelection?.records?.map((val) => ({
1857
- value: val.id,
1858
- label: val.name ?? val.display_name,
1859
- ...val
1860
- })) || [];
1861
- }, [dataOfSelection]);
1862
- useEffect11(() => {
1863
- setOptions(selectOptions);
1864
- }, [selectOptions]);
1865
- const fetchMoreOptions = useCallback5(() => {
1866
- refetch();
1867
- }, [refetch]);
1868
- const transfer = (data2) => {
1869
- return data2?.map((val) => ({
1870
- id: val.value,
1871
- display_name: val.label
1872
- })) || [];
1873
- };
1874
- const handleChooseRecord = useCallback5(
1875
- (idRecord) => {
1876
- const newOption = options.find(
1877
- (option) => option.value === idRecord
1878
- );
1879
- setIsShowModalMany2Many(false);
1880
- },
1881
- [options, methods, name, onChange]
1882
- );
1883
- const handleClose = useCallback5(() => setIsShowModalMany2Many(false), []);
1884
- return {
1885
- options,
1886
- transfer,
1887
- isUser,
1888
- isFetching,
1889
- fetchMoreOptions,
1890
- domainObject,
1891
- setDomainObject,
1892
- handleChooseRecord,
1893
- handleClose,
1894
- isShowModalMany2Many,
1895
- setIsShowModalMany2Many
1896
- };
1897
- };
1898
-
1899
- // src/widget/basic/status-bar-field/controller.ts
1900
- import { useState as useState9 } from "react";
1901
- import { evalJSONDomain as evalJSONDomain5 } from "@fctc/interface-logic/utils";
1902
- var durationController = (props) => {
1903
- const { relation, domain, formValues, name, id, model, onRefetch, enabled } = props;
1904
- const specification = {
1905
- id: 0,
1906
- name: "",
1907
- fold: ""
1908
- };
1909
- const { useGetListData: useGetListData2, useChangeStatus: useChangeStatus2 } = (0, provider_exports.useService)();
1910
- const { env } = (0, provider_exports.useEnv)();
1911
- const [disabled, setDisabled] = useState9(false);
1912
- const [modelStatus, setModalStatus] = useState9(false);
1913
- const queryKey = [`data-status-duration`, specification];
1914
- const listDataProps = {
1915
- model: relation,
1916
- specification,
1917
- domain: evalJSONDomain5(domain, JSON.parse(JSON.stringify(formValues))),
1918
- limit: 10,
1919
- offset: 0,
1920
- fields: "",
1921
- groupby: [],
1922
- context: {
1923
- lang: env.context.lang
1924
- },
1925
- sort: ""
1926
- };
1927
- const { data: dataResponse } = useGetListData2(
1928
- listDataProps,
1929
- queryKey,
1930
- enabled
1931
- );
1932
- const { mutate: fetchChangeStatus } = useChangeStatus2();
1933
- const handleClick = async (stage_id) => {
1934
- setDisabled(true);
1935
- if (stage_id) {
1936
- fetchChangeStatus(
1937
- {
1938
- data: {
1939
- stage_id,
1940
- name,
1941
- id,
1942
- model,
1943
- lang: env.context.lang
1944
- }
1945
- },
1946
- {
1947
- onSuccess: (res) => {
1948
- if (res) {
1949
- setDisabled(false);
1950
- onRefetch && onRefetch();
1951
- }
1952
- }
1953
- }
1954
- );
1955
- }
1956
- };
1957
- return {
1958
- dataResponse,
1959
- handleClick,
1960
- disabled,
1961
- modelStatus,
1962
- setModalStatus
1963
- };
1964
- };
1965
-
1966
- // src/widget/basic/priority-field/controller.ts
1967
- import { evalJSONContext as evalJSONContext6 } from "@fctc/interface-logic/utils";
1968
- var priorityFieldController = (props) => {
1969
- const { name, model, index, actionData, context, onChange, specification } = props;
1970
- const _context = { ...evalJSONContext6(actionData?.context) };
1971
- const contextObject = { ...context, ..._context };
1972
- const { useSave: useSave3 } = (0, provider_exports.useService)();
1973
- const { mutateAsync: fetchSave } = useSave3();
1974
- const savePriorities = async ({
1975
- value,
1976
- resetPriority
1977
- }) => {
1978
- const priorityValue = value <= 0 ? 0 : value - 1;
1979
- try {
1980
- fetchSave({
1981
- ids: index ? [index] : [],
1982
- data: { [String(name)]: String(priorityValue) },
1983
- model: String(model),
1984
- context: contextObject,
1985
- specification
1986
- });
1987
- if (typeof onChange === "function") {
1988
- onChange(String(name), String(priorityValue));
1989
- }
1990
- } catch (error) {
1991
- if (resetPriority) {
1992
- resetPriority();
1993
- }
1994
- }
1995
- };
1996
- return {
1997
- savePriorities
1998
- };
1999
- };
2000
-
2001
- // src/widget/basic/download-file-field/controller.ts
2002
- import { useId, useState as useState10 } from "react";
2003
- var downloadFileController = () => {
2004
- const inputId = useId();
2005
- const [file, setFile] = useState10(null);
2006
- const handleFileChange = (e) => {
2007
- setFile(e.target.files[0]);
2008
- };
2009
- const handleFileDownload = () => {
2010
- const url = URL.createObjectURL(file);
2011
- const link = document.createElement("a");
2012
- link.href = url;
2013
- link.download = file.name;
2014
- document.body.appendChild(link);
2015
- link.click();
2016
- document.body.removeChild(link);
2017
- };
2018
- return {
2019
- inputId,
2020
- file,
2021
- handleFileChange,
2022
- handleFileDownload
2023
- };
2024
- };
2025
-
2026
- // src/widget/basic/download-binary-field/controller.ts
2027
- var downLoadBinaryController = (props) => {
2028
- const { value, defaultValue, formValues } = props;
2029
- const downloadFile = async (url, filename) => {
2030
- try {
2031
- const response = await fetch(url);
2032
- if (!response.ok) throw new Error(`Failed to fetch ${url}`);
2033
- const contentType = response.headers.get("Content-Type") || "";
2034
- let ext = "";
2035
- if (contentType.includes("pdf")) ext = ".pdf";
2036
- else if (contentType.includes("png")) ext = ".png";
2037
- else if (contentType.includes("jpeg") || contentType.includes("jpg"))
2038
- ext = ".jpg";
2039
- else if (contentType.includes("zip")) ext = ".zip";
2040
- else if (contentType.includes("msword")) ext = ".doc";
2041
- else if (contentType.includes("spreadsheet")) ext = ".xls";
2042
- else if (contentType.includes("json")) ext = ".json";
2043
- else if (contentType.includes("text")) ext = ".txt";
2044
- else {
2045
- ext = "";
2046
- }
2047
- const blob = await response.blob();
2048
- const urlBlob = window.URL.createObjectURL(blob);
2049
- const link = document.createElement("a");
2050
- link.href = urlBlob;
2051
- link.download = (filename || "file") + ext;
2052
- document.body.appendChild(link);
2053
- link.click();
2054
- document.body.removeChild(link);
2055
- window.URL.revokeObjectURL(urlBlob);
2056
- } catch (error) {
2057
- console.error("File download failed:", error);
2058
- }
2059
- };
2060
- const handleFileDownload = async (e) => {
2061
- e.stopPropagation();
2062
- await downloadFile(value || defaultValue, formValues?.name);
2063
- };
2064
- return {
2065
- handleFileDownload
2066
- };
2067
- };
2068
-
2069
- // src/widget/basic/copy-link-button/controller.ts
2070
- import { useState as useState11 } from "react";
2071
- var copyTextToClipboard = async (text) => {
2072
- if ("clipboard" in navigator) {
2073
- return await navigator.clipboard.writeText(text);
2074
- } else {
2075
- const textArea = document.createElement("textarea");
2076
- textArea.value = text;
2077
- textArea.style.position = "fixed";
2078
- document.body.appendChild(textArea);
2079
- textArea.focus();
2080
- textArea.select();
2081
- try {
2082
- document.execCommand("copy");
2083
- } finally {
2084
- document.body.removeChild(textArea);
2085
- }
2086
- }
2087
- };
2088
- var copyLinkButtonController = (props) => {
2089
- const { value, defaultValue } = props;
2090
- const [isCopied, setIsCopied] = useState11(false);
2091
- const handleCopyToClipboard = async (value2) => {
2092
- await copyTextToClipboard(value2);
2093
- setIsCopied(true);
2094
- setTimeout(() => setIsCopied(false), 2e3);
2095
- };
2096
- const propValue = value || defaultValue;
2097
- return {
2098
- isCopied,
2099
- handleCopyToClipboard,
2100
- propValue
2101
- };
2102
- };
2103
-
2104
- // src/widget/basic/color-field/color-controller.ts
2105
- import { evalJSONContext as evalJSONContext7 } from "@fctc/interface-logic/utils";
2106
- var colorFieldController = (props) => {
2107
- const { value, isForm, name, formValues, idForm, model, actionData } = props;
2108
- const { env } = (0, provider_exports.useEnv)();
2109
- const { useSave: useSave3 } = (0, provider_exports.useService)();
2110
- const _context = { ...evalJSONContext7(actionData?.context) || {} };
2111
- const contextObject = { ...env.context, ..._context };
2112
- const idDefault = isForm ? idForm : formValues?.id;
2113
- const { mutate: onSave } = useSave3();
2114
- const savePickColor = async (colorObject) => {
2115
- const { id } = colorObject;
2116
- if (value === id) return;
2117
- try {
2118
- onSave({
2119
- ids: idDefault !== null ? [idDefault] : [],
2120
- model: String(model),
2121
- data: { [String(name)]: id },
2122
- specification: {
2123
- name: {},
2124
- color: {}
2125
- },
2126
- context: contextObject
2127
- });
2128
- } catch (error) {
2129
- console.log(error);
2130
- }
2131
- };
2132
- return {
2133
- savePickColor
2134
- };
2135
- };
2136
-
2137
- // src/widget/basic/binary-field/controller.ts
2138
- import { useEffect as useEffect12, useState as useState12 } from "react";
2139
- var binaryFieldController = (props) => {
2140
- const {
2141
- name,
2142
- methods,
2143
- readonly = false,
2144
- filename,
2145
- onChange: handleOnchange,
2146
- service,
2147
- xNode,
2148
- path,
2149
- rootField,
2150
- index,
2151
- value
2152
- } = props;
2153
- const { useUploadFile: useUploadFile2 } = (0, provider_exports.useService)();
2154
- const { mutateAsync } = useUploadFile2();
2155
- const [url, setUrl] = useState12(value || null);
2156
- const [fileInfo, setFileInfo] = useState12(null);
2157
- useEffect12(() => {
2158
- if (!value) {
2159
- setUrl(null);
2160
- setFileInfo(null);
2161
- return;
2162
- }
2163
- fetchFileMeta(value);
2164
- }, [value]);
2165
- const formatSize = (bytes) => {
2166
- if (bytes < 1024) return bytes + " B";
2167
- let kb = bytes / 1024;
2168
- if (kb < 1024) return kb.toFixed(2) + " KB";
2169
- let mb = kb / 1024;
2170
- if (mb < 1024) return mb.toFixed(2) + " MB";
2171
- return (mb / 1024).toFixed(2) + " GB";
2172
- };
2173
- const fetchFileMeta = async (url2) => {
2174
- try {
2175
- const res = await fetch(url2, { method: "HEAD" });
2176
- const size = res.headers.get("content-length") || "";
2177
- let type = res.headers.get("content-type") || "";
2178
- const date = res.headers.get("last-modified") || "";
2179
- const guessed = guessTypeFromUrl(url2);
2180
- if (guessed) type = guessed;
2181
- setFileInfo({
2182
- size: size ? formatSize(Number(size)) : "--",
2183
- type,
2184
- date: date ? new Date(date).toLocaleString() : "--"
2185
- });
2186
- setUrl(url2);
2187
- } catch (e) {
2188
- console.error(e);
2189
- }
2190
- };
2191
- const onUploadFile = async (formData) => {
2192
- const res = await mutateAsync({
2193
- formData,
2194
- service,
2195
- xNode,
2196
- path
2197
- });
2198
- const url2 = res?.url;
2199
- methods?.setValue(name, url2, { shouldDirty: true });
2200
- handleOnchange && handleOnchange(name ?? "", url2);
2201
- if (filename) {
2202
- methods?.setValue(
2203
- rootField ? `${rootField?.name}.${index}.${filename}` : filename,
2204
- url2?.split("/").pop(),
2205
- { shouldDirty: true }
2206
- );
2207
- handleOnchange && handleOnchange(
2208
- rootField ? `${rootField?.name}.${index}.${filename}` : filename,
2209
- url2?.split("/").pop()
2210
- );
2211
- }
2212
- setUrl(url2);
2213
- fetchFileMeta(url2);
2214
- return url2;
2215
- };
2216
- const onDeleteFile = () => {
2217
- if (filename) {
2218
- methods?.setValue(
2219
- rootField ? `${rootField?.name}.${index}.${filename}` : filename,
2220
- null,
2221
- { shouldDirty: true }
2222
- );
2223
- handleOnchange && handleOnchange(
2224
- rootField ? `${rootField?.name}.${index}.${filename}` : filename,
2225
- null
2226
- );
2227
- }
2228
- setUrl(null);
2229
- setFileInfo(null);
2230
- methods?.setValue(name, null, { shouldDirty: true });
2231
- handleOnchange && handleOnchange(name ?? "", null);
2232
- };
2233
- return {
2234
- onUploadFile,
2235
- onDeleteFile,
2236
- fileInfo,
2237
- url
2238
- };
2239
- };
2240
-
2241
- // src/widget/basic/many2many-binary-field/controller.tsx
2242
- import { useId as useId2, useRef as useRef3, useState as useState13 } from "react";
2243
- var many2manyBinaryController = (props) => {
2244
- const {
2245
- name,
2246
- methods,
2247
- value,
2248
- onChange: handleOnchange,
2249
- service,
2250
- xNode,
2251
- path
2252
- } = props;
2253
- const inputId = useId2();
2254
- const { useUploadFile: useUploadFile2 } = (0, provider_exports.useService)();
2255
- const { mutateAsync } = useUploadFile2();
2256
- const binaryRef = useRef3(null);
2257
- const [initialFiles, setInitialFiles] = useState13(
2258
- Array.isArray(value) ? value : value ? [value] : []
2259
- );
2260
- const checkIsImageLink = (url) => {
2261
- const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|webp|svg|tiff|ico)$/i;
2262
- return imageExtensions.test(url) || isBase64Image(url) || isBlobUrl(url);
2263
- };
2264
- const sanitizeForBE = (list) => list.filter((x) => x?.datas && !isBlobUrl(x.datas)).map((x) => ({ name: x.name, datas: x.datas, mimetype: x.mimetype }));
2265
- const isBase64Image = (str) => {
2266
- const base64Regex = /^data:image\/(png|jpeg|jpg|gif|webp);base64,/;
2267
- if (!base64Regex.test(str)) {
2268
- return false;
2269
- }
2270
- try {
2271
- const base64Data = str.split(",")[1];
2272
- return !!base64Data && atob(base64Data).length > 0;
2273
- } catch (error) {
2274
- return false;
2275
- }
2276
- };
2277
- const handleFileChange = async (files, e, oldValues) => {
2278
- try {
2279
- const uploadedUrls = await Promise.all(
2280
- files.map(async (f) => {
2281
- const formData = new FormData();
2282
- formData.append("file", f);
2283
- const res = await mutateAsync({ formData, service, xNode, path });
2284
- return res?.url;
2285
- })
2286
- );
2287
- const uploadedItems = files.map((f, i) => ({
2288
- name: f.name,
2289
- datas: uploadedUrls[i] ?? "",
2290
- mimetype: f.type
2291
- }));
2292
- const finalList = [...oldValues, ...uploadedItems];
2293
- methods?.setValue(name, finalList, { shouldDirty: true });
2294
- const payloadForBE = sanitizeForBE(finalList);
2295
- handleOnchange && handleOnchange(name ?? "", payloadForBE);
2296
- } catch (err) {
2297
- console.error(err);
2298
- } finally {
2299
- e.target.value = "";
2300
- }
2301
- };
2302
- const handleRemoveAt = (idx) => {
2303
- const current = methods?.getValues(name) || [];
2304
- const next = current.filter((_, i) => i !== idx);
2305
- setInitialFiles((p) => p.filter((_, i) => i !== idx));
2306
- methods?.setValue(name, next.length ? next : null, { shouldDirty: true });
2307
- const payloadForBE = next.length ? sanitizeForBE(next) : null;
2308
- handleOnchange && handleOnchange(name ?? "", payloadForBE);
2309
- };
2310
- const handleRemoveAll = () => {
2311
- setInitialFiles([]);
2312
- methods?.setValue(name, null, { shouldDirty: true });
2313
- handleOnchange && handleOnchange(name ?? "", null);
2314
- };
2315
- return {
2316
- inputId,
2317
- initialFiles,
2318
- binaryRef,
2319
- handleFileChange,
2320
- handleRemoveAt,
2321
- handleRemoveAll,
2322
- checkIsImageLink,
2323
- setInitialFiles
2324
- };
2325
- };
2326
-
2327
- // src/widget/basic/provider-einvoice-field/controller.ts
2328
- var providerEinvoiceFieldController = (props) => {
2329
- const { relation, formValues, options: fieldOptions, xNode } = props;
2330
- const { env } = (0, provider_exports.useEnv)();
2331
- const { action } = useAppProvider();
2332
- const { useGetSelection: useGetSelection3 } = (0, provider_exports.useService)();
2333
- const contextObject = {
2334
- ...(typeof action?.context === "string" ? (0, utils_exports.evalJSONContext)(action?.context) : action?.context) || {},
2335
- ...env?.context
2336
- };
2337
- const optionsObject = typeof fieldOptions === "string" ? (0, utils_exports.evalJSONContext)(fieldOptions, {
2338
- ...formValues,
2339
- ...contextObject,
2340
- context: contextObject,
2341
- parent: { ...formValues }
2342
- }) : fieldOptions;
2343
- const data = {
2344
- model: optionsObject?.model,
2345
- domain: optionsObject?.domain,
2346
- context: {
2347
- ...contextObject,
2348
- ...optionsObject?.context
2349
- },
2350
- specification: optionsObject?.specification
2351
- };
2352
- const { data: listDataCard } = useGetSelection3({
2353
- data,
2354
- queryKey: [`data_${relation}`],
2355
- enabled: true,
2356
- service: optionsObject?.service,
2357
- xNode
2358
- });
2359
- return {
2360
- listDataCard
2361
- };
2362
- };
2363
-
2364
- // src/widget/advance/table/table-head/controller.ts
2365
- import { useMemo as useMemo10, useRef as useRef4 } from "react";
2366
- var tableHeadController = (props) => {
2367
- const {
2368
- typeTable,
2369
- rows,
2370
- tableRef,
2371
- groupByList,
2372
- selectedRowKeys,
2373
- setSelectedRowKeys
2374
- } = props;
2375
- const { rowIds: recordIds } = useGetRowIds(tableRef);
2376
- const selectedRowKeysRef = useRef4(recordIds);
2377
- const isGroupTable = typeTable === "group";
2378
- const recordsCheckedGroup = useMemo10(() => {
2379
- if (!rows || !groupByList) return 0;
2380
- const groupBy = typeof groupByList === "object" ? groupByList?.contexts?.[0]?.group_by : void 0;
2381
- return countSum(rows, groupBy);
2382
- }, [rows, groupByList]);
2383
- const isAllGroupChecked = useMemo10(() => {
2384
- if (!isGroupTable || !selectedRowKeys?.length) return false;
2385
- const selectedLength = selectedRowKeys.filter((id) => id !== -1).length;
2386
- const allRecordsSelected = recordIds.length === selectedRowKeys.length ? recordIds.length === selectedLength : false;
2387
- const allGroupsSelected = recordsCheckedGroup === selectedRowKeys.length;
2388
- return allGroupsSelected || allRecordsSelected;
2389
- }, [isGroupTable, selectedRowKeys, recordIds, recordsCheckedGroup]);
2390
- const isAllNormalChecked = useMemo10(() => {
2391
- if (isGroupTable || !selectedRowKeys?.length || !rows?.length) return false;
2392
- return selectedRowKeys.length === rows.length && selectedRowKeys.every(
2393
- (id) => rows.some((record) => record.id === id)
2394
- );
2395
- }, [isGroupTable, selectedRowKeys, rows]);
2396
- const checkedAll = isAllGroupChecked || isAllNormalChecked;
2397
- const handleCheckBoxAll = (event) => {
2398
- if (event?.target?.checked && typeTable === "list") {
2399
- const allRowKeys = Array.isArray(rows) ? rows.map((record) => record?.id) : [];
2400
- setSelectedRowKeys(allRowKeys);
2401
- } else if (event?.target?.checked && typeTable === "group") {
2402
- const rowsIDs = document.querySelectorAll("tr[data-row-id]");
2403
- const ids = Array.from(rowsIDs)?.map(
2404
- (row) => Number(row?.getAttribute("data-row-id"))
2405
- );
2406
- if (ids?.length > 0) {
2407
- setSelectedRowKeys(ids);
2408
- } else {
2409
- const sum = countSum(
2410
- rows,
2411
- typeof groupByList === "object" ? groupByList?.contexts?.[0]?.group_by : void 0
2412
- );
2413
- const keys = Array.from({ length: sum }, (_) => void 0);
2414
- setSelectedRowKeys(keys);
2415
- }
2416
- if (selectedRowKeysRef) {
2417
- selectedRowKeysRef.current = [];
2418
- }
2419
- } else {
2420
- setSelectedRowKeys([]);
2421
- }
2422
- };
2423
- return {
2424
- handleCheckBoxAll,
2425
- checkedAll,
2426
- selectedRowKeysRef
2427
- };
2428
- };
2429
-
2430
- // src/widget/advance/table/table-view/controller.ts
2431
- import { useCallback as useCallback6, useEffect as useEffect13, useMemo as useMemo11, useState as useState14 } from "react";
2432
- import { domainHelper } from "@fctc/interface-logic/utils";
2433
- var tableController = ({ data }) => {
2434
- const [rows, setRows] = useState14([]);
2435
- const [columnVisibility, setColumnVisibility] = useState14({});
2436
- const dataModelFields = useMemo11(() => {
2437
- return data?.fields?.map((field) => ({
2438
- ...data.dataModel?.[field?.name],
2439
- ...field,
2440
- string: field?.string || data.dataModel?.[field?.name]?.string
2441
- })) ?? [];
2442
- }, [data?.fields, data?.dataModel]);
2443
- const mergeFields = useMemo11(
2444
- () => mergeButtons(dataModelFields),
2445
- [dataModelFields]
2446
- );
2447
- const transformData = useCallback6(
2448
- (dataList) => {
2449
- if (!dataList) return [];
2450
- return dataList.map((item) => {
2451
- const transformedItem = { ...item };
2452
- Object.keys(item).forEach((field) => {
2453
- if (field !== "__domain") {
2454
- if (item[field] && typeof item[field] === "object" && item[field].display_name) {
2455
- transformedItem[field] = item[field];
2456
- } else if (Array.isArray(item[field]) && item[field].length > 0) {
2457
- if (data.typeTable === "group" && item[field]?.length === 2 && typeof item[field]?.[1] === "string") {
2458
- transformedItem["string"] = item[field]?.[1];
2459
- }
2460
- transformedItem[field] = item[field];
2461
- }
2462
- }
2463
- });
2464
- return item.display_name ? { ...transformedItem, item: item.display_name } : transformedItem;
2465
- });
2466
- },
2467
- [data?.typeTable]
2468
- );
2469
- useEffect13(() => {
2470
- setRows(transformData(data?.records));
2471
- }, [data?.records, transformData]);
2472
- const columns = useMemo11(() => {
2473
- try {
2474
- return mergeFields?.filter((item) => {
2475
- return item?.widget !== "details_Receive_money" && !(item?.column_invisible ? domainHelper.matchDomains(
2476
- data.context,
2477
- item?.column_invisible
2478
- ) : item?.invisible ? domainHelper.matchDomains(data.context, item?.invisible) : false);
2479
- })?.map((field) => {
2480
- const overridden = columnVisibility[field?.name];
2481
- return {
2482
- name: field?.name,
2483
- optional: overridden ?? field?.optional,
2484
- title: field?.type_co === "button" ? "" : field?.string,
2485
- field: { ...field }
2486
- };
2487
- }) ?? [];
2488
- } catch (error) {
2489
- console.error("Error in useTable:", error);
2490
- return [];
2491
- }
2492
- }, [mergeFields, data?.context, columnVisibility]);
2493
- const onToggleColumnOptional = useCallback6((item) => {
2494
- setColumnVisibility((prev) => ({
2495
- ...prev,
2496
- [item?.name]: item?.optional === "show" ? "hide" : "show"
2497
- }));
2498
- }, []);
2499
- return {
2500
- rows,
2501
- columns,
2502
- onToggleColumnOptional,
2503
- typeTable: data?.typeTable
2504
- };
2505
- };
2506
-
2507
- // src/widget/advance/table/table-group/controller.ts
2508
- import { useMemo as useMemo12, useState as useState15 } from "react";
2509
- var tableGroupController = (props) => {
2510
- const { env } = (0, provider_exports.useEnv)();
2511
- const { useGetListData: useGetListData2 } = (0, provider_exports.useService)();
2512
- const {
2513
- columns,
2514
- row,
2515
- model,
2516
- viewData,
2517
- level,
2518
- specification,
2519
- context,
2520
- checkedAll,
2521
- groupByList,
2522
- setSelectedRowKeys
2523
- } = props;
2524
- const [pageGroup, setPageGroup] = useState15(0);
2525
- const [isShowGroup, setIsShowGroup] = useState15(false);
2526
- const [colEmptyGroup, setColEmptyGroup] = useState15({
2527
- fromStart: 1,
2528
- fromEnd: 1
2529
- });
2530
- const domain = row?.__domain;
2531
- const processedData = useMemo12(() => {
2532
- const calculateColSpanEmpty = () => {
2533
- const startIndex = columns.findIndex(
2534
- (col) => col.field.type === "monetary" && typeof row[col.key] === "number" || col.field.aggregator === "sum"
2535
- );
2536
- const endIndex = columns.findLastIndex(
2537
- (col) => col.field.type === "monetary" && typeof row[col.key] === "number" || col.field.aggregator !== "sum"
2538
- );
2539
- const fromStart = startIndex === -1 ? columns.length : startIndex;
2540
- const fromEnd = endIndex === -1 ? columns.length : columns.length - 1 - endIndex;
2541
- setColEmptyGroup({ fromStart: fromStart + 1, fromEnd: fromEnd + 1 });
2542
- return { fromStart: fromStart + 1, fromEnd: fromEnd + 1 };
2543
- };
2544
- return calculateColSpanEmpty();
2545
- }, [columns, row]);
2546
- const shouldFetchData = useMemo12(() => {
2547
- return !!isShowGroup;
2548
- }, [isShowGroup]);
2549
- const enabled = shouldFetchData && !!processedData;
2550
- const listDataProps = {
2551
- model,
2552
- specification,
2553
- domain,
2554
- context,
2555
- offset: pageGroup * 10,
2556
- fields: groupByList?.fields,
2557
- groupby: [groupByList?.contexts[level]?.group_by],
2558
- limit: 10
2559
- };
2560
- const queryKey = [
2561
- `data-${model}-level_${level}-row-${row?.id}`,
2562
- specification,
2563
- domain,
2564
- pageGroup
2565
- ];
2566
- const {
2567
- data: dataGroup,
2568
- isFetched: isDataGroupFetched,
2569
- isLoading,
2570
- isFetching,
2571
- isPlaceholderData: isDataPlaceHolder
2572
- } = useGetListData2(listDataProps, queryKey, enabled);
2573
- const {
2574
- columns: columnsGroup,
2575
- rows: rowsGroup,
2576
- typeTable: typeTableGroup
2577
- } = tableController({
2578
- data: {
2579
- fields: viewData?.views?.list?.fields,
2580
- records: dataGroup?.records ?? dataGroup?.groups,
2581
- dataModel: viewData?.models?.[model],
2582
- context: env.context,
2583
- typeTable: dataGroup?.groups ? "group" : "list"
2584
- }
2585
- });
2586
- const group_by_field_name = groupByList?.contexts[level - 1]?.group_by;
2587
- const nameGroup = Array.isArray(row[group_by_field_name]) ? row?.string ?? row[`${group_by_field_name}`][1] : viewData?.models?.[model]?.[group_by_field_name]?.selection ? viewData.models[model][group_by_field_name].selection.find(
2588
- (selectItem) => selectItem?.[0] === row[group_by_field_name]
2589
- )?.[1] : row[group_by_field_name];
2590
- const toggleShowGroup = () => setIsShowGroup((prev) => !prev);
2591
- return {
2592
- // onExpandChildGroup,
2593
- colEmptyGroup,
2594
- isShowGroup,
2595
- isDataGroupFetched,
2596
- isDataPlaceHolder,
2597
- // nameGroupWithCount,
2598
- columnsGroup,
2599
- rowsGroup,
2600
- dataGroup,
2601
- pageGroup,
2602
- setPageGroup,
2603
- typeTableGroup
2604
- };
2605
- };
2606
-
2607
- // src/widget/advance/search/controller.ts
2608
- import moment2 from "moment";
2609
- import { useCallback as useCallback7, useEffect as useEffect14, useState as useState16 } from "react";
2610
-
2611
- // src/constants.ts
2612
- var constants_exports = {};
2613
- __reExport(constants_exports, constants_star);
2614
- import * as constants_star from "@fctc/interface-logic/constants";
2615
-
2616
- // src/widget/advance/search/controller.ts
2617
- var searchController = ({
2618
- viewData,
2619
- model,
2620
- domain,
2621
- context,
2622
- fieldsList
2623
- }) => {
2624
- const { env } = (0, provider_exports.useEnv)();
2625
- const [filterBy, setFilterBy] = useState16(null);
2626
- const [searchBy, setSearchBy] = useState16(null);
2627
- const [groupBy, setGroupBy] = useState16(null);
2628
- const [selectedTags, setSelectedTags] = useState16(null);
2629
- const [searchString, setSearchString] = useState16("");
2630
- const [searchMap, setSearchMap] = useState16({});
2631
- const [hoveredIndex, setHoveredIndex] = useState16(0);
2632
- const [hoveredIndexSearchList, setHoveredIndexSearchList] = useState16(0);
2633
- const actionContext = typeof context === "string" ? (0, utils_exports.evalJSONContext)(context) : context;
2634
- const contextSearch = { ...env.context, ...actionContext };
2635
- const domainAction = domain ? Array.isArray(domain) ? [...domain] : (0, utils_exports.evalJSONDomain)(domain, contextSearch) : [];
2636
- const clearSearch = () => {
2637
- setFilterBy([]);
2638
- setGroupBy([]);
2639
- setSearchBy([]);
2640
- setSelectedTags(null);
2641
- setSearchString("");
2642
- setSearchMap({});
2643
- };
2644
- const fetchData = async () => {
2645
- if (viewData) {
2646
- try {
2647
- const dataModel = viewData?.models?.[model];
2648
- const searchViews = viewData?.views?.search;
2649
- const searchByItems = searchViews?.search_by?.filter(
2650
- (item) => !utils_exports.domainHelper.matchDomains(contextSearch, item.invisible)
2651
- )?.map(
2652
- ({ string, name, filter_domain, operator, widget }, index) => ({
2653
- dataIndex: index,
2654
- title: string ?? dataModel?.[name]?.string,
2655
- name: name ?? dataModel?.[name]?.name,
2656
- filter_domain,
2657
- operator,
2658
- widget,
2659
- type: dataModel?.[name]?.type
2660
- })
2661
- );
2662
- const filterByItems = searchViews?.filter_by.filter((item) => {
2663
- return !utils_exports.domainHelper.matchDomains(contextSearch, item?.invisible);
2664
- })?.map((item) => ({ ...item, active: false }));
2665
- const groupByItems = searchViews?.group_by.filter(
2666
- (item) => !utils_exports.domainHelper.matchDomains(contextSearch, item?.invisible)
2667
- ).map((item) => ({
2668
- ...item,
2669
- string: item.string ?? viewData?.models?.[model]?.[item?.name?.split("group_by_")?.[1]]?.string
2670
- }));
2671
- setSearchBy(searchByItems);
2672
- setFilterBy(filterByItems);
2673
- setGroupBy(groupByItems);
2674
- } catch (error) {
2675
- console.error("Error fetching data:", error);
2676
- }
2677
- }
2678
- };
2679
- useEffect14(() => {
2680
- fetchData();
2681
- }, [model, viewData]);
2682
- const onChangeSearchInput = (search_string) => {
2683
- setSearchString(search_string);
2684
- };
2685
- const removeKeyFromSearchMap = ({
2686
- key,
2687
- item
2688
- }) => {
2689
- const values = searchMap[key];
2690
- if (!values) return searchMap;
2691
- const newSearchMap = { ...searchMap };
2692
- if (item) {
2693
- const filtered = values.filter((value) => value.name !== item.name);
2694
- if (filtered.length > 0) {
2695
- newSearchMap[key] = filtered;
2696
- } else {
2697
- delete newSearchMap[key];
2698
- }
2699
- } else {
2700
- delete newSearchMap[key];
2701
- }
2702
- setSearchMap(newSearchMap);
2703
- };
2704
- const updateSearchMap = ({ key, item }) => {
2705
- const newSearchMap = { ...searchMap };
2706
- const currentValues = searchMap[key] ?? [];
2707
- newSearchMap[key] = [...currentValues, item];
2708
- setSearchMap(newSearchMap);
2709
- };
2710
- const removeSearchItems = (key, item) => {
2711
- removeKeyFromSearchMap({ key: String(key), item });
2712
- };
2713
- const addSearchItems = (key, newItem) => {
2714
- updateSearchMap({ key, item: newItem });
2715
- };
2716
- const formatDomain = () => {
2717
- if (domainAction) {
2718
- const domain2 = [];
2719
- if (Array.isArray(domainAction) && domainAction.length > 0) {
2720
- if (Object.keys(searchMap).some((key) => !key.includes(constants_exports.SearchType.GROUP))) {
2721
- domain2.push("&");
2722
- }
2723
- domainAction.forEach((domainItem) => {
2724
- domain2.push(domainItem);
2725
- });
2726
- }
2727
- Object.keys(searchMap).forEach((key, keyIndex, keys) => {
2728
- if (!key?.includes(constants_exports.SearchType.GROUP)) {
2729
- if (keys.length > 1 && keyIndex < keys.length - 1) {
2730
- domain2.push("&");
2731
- }
2732
- const valuesOfKey = searchMap[key];
2733
- valuesOfKey.forEach((value, index) => {
2734
- if (index < valuesOfKey.length - 1) {
2735
- domain2.push("|");
2736
- }
2737
- if (value.domain) {
2738
- domain2.push(...value.domain);
2739
- return;
2740
- }
2741
- let valueDomainItem = value?.value;
2742
- if (value?.modelType === "date") {
2743
- valueDomainItem = validateAndParseDate(value?.value);
2744
- } else if (value?.modelType === "datetime") {
2745
- if (value?.operator === "<=" || value?.operator === "<") {
2746
- const parsedDate = validateAndParseDate(value?.value, true);
2747
- const hasTime = moment2(value?.value).format("HH:mm:ss") !== "00:00:00";
2748
- valueDomainItem = hasTime ? moment2(parsedDate).format("YYYY-MM-DD HH:mm:ss") : moment2(parsedDate).add(1, "day").subtract(1, "second").format("YYYY-MM-DD HH:mm:ss");
2749
- } else {
2750
- valueDomainItem = validateAndParseDate(value?.value, true);
2751
- }
2752
- }
2753
- const operator = value?.modelType === "date" || value?.modelType === "datetime" || value?.modelType === "boolean" || value?.modelType === "integer" ? value?.operator ?? "=" : value.operator ?? "ilike";
2754
- domain2.push([value.name, operator, valueDomainItem]);
2755
- });
2756
- }
2757
- });
2758
- return [...domain2];
2759
- }
2760
- };
2761
- const setTagSearch = useCallback7(
2762
- (updatedMap) => {
2763
- if (!updatedMap) return;
2764
- const tagsSearch = Object.entries(updatedMap).map(
2765
- ([key, objValues]) => {
2766
- const {
2767
- title,
2768
- name,
2769
- groupIndex,
2770
- type,
2771
- widget,
2772
- modelType,
2773
- dataIndex
2774
- } = objValues[0];
2775
- if (!key?.includes(constants_exports.SearchType.GROUP)) {
2776
- const values = objValues?.map((objValue) => objValue.value);
2777
- return {
2778
- title,
2779
- name: type === constants_exports.SearchType.SEARCH ? `${constants_exports.SearchType.SEARCH}_${String(dataIndex)}` : groupIndex ?? name,
2780
- values,
2781
- type,
2782
- widget,
2783
- modelType
2784
- };
2785
- } else {
2786
- const contexts = [];
2787
- let groupValues = [];
2788
- objValues?.forEach((objValue) => {
2789
- const { context: context2, value, active, groupIndex: groupIndex2, isDefault } = objValue;
2790
- const indexAppend = groupIndex2 != null ? groupIndex2 : viewData?.views?.search?.filters_by?.length ?? 0;
2791
- contexts.push(
2792
- ...Array.isArray(context2?.group_by) ? context2.group_by.map((item) => ({ group_by: item })) : [context2]
2793
- );
2794
- groupValues[indexAppend] = {
2795
- contexts: [
2796
- ...Array.isArray(context2?.group_by) ? context2.group_by.map((item) => ({
2797
- group_by: item
2798
- })) : [context2]
2799
- ],
2800
- strings: isDefault ? [value] : [...groupValues[indexAppend]?.strings ?? [], value]
2801
- };
2802
- });
2803
- const fields = [
2804
- ...new Set(fieldsList?.map((item) => item?.name))
2805
- ];
2806
- const groupByTag = {
2807
- title,
2808
- values: groupValues?.filter(
2809
- (item) => item !== void 0
2810
- ),
2811
- type,
2812
- contexts,
2813
- fields
2814
- };
2815
- return groupByTag;
2816
- }
2817
- }
2818
- );
2819
- setSelectedTags(tagsSearch);
2820
- setSearchString("");
2821
- },
2822
- [searchMap]
2823
- );
2824
- useEffect14(() => {
2825
- setTagSearch(searchMap);
2826
- }, [searchMap]);
2827
- const handleAddTagSearch = (tag) => {
2828
- const { domain: domain2, groupIndex, value, type, context: context2, dataIndex } = tag;
2829
- const domainFormat = new utils_exports.domainHelper.Domain(domain2);
2830
- if (type === constants_exports.SearchType.FILTER) {
2831
- addSearchItems(`${constants_exports.SearchType.FILTER}_${groupIndex}`, {
2832
- ...tag,
2833
- domain: domain2 ? domainFormat.toList(context2) : null
2834
- });
2835
- } else if (type === constants_exports.SearchType.SEARCH) {
2836
- addSearchItems(`${constants_exports.SearchType.SEARCH}_${String(dataIndex)}`, {
2837
- ...tag,
2838
- domain: domain2 ? domainFormat.toList({
2839
- ...context2,
2840
- self: value
2841
- }) : null
2842
- });
2843
- } else if (type === constants_exports.SearchType.GROUP) {
2844
- addSearchItems(`${constants_exports.SearchType.GROUP}`, {
2845
- ...tag,
2846
- domain: domain2 ? domainFormat.toList({
2847
- context: context2,
2848
- self: value
2849
- }) : null
2850
- });
2851
- }
2852
- };
2853
- const onKeyDown = (e) => {
2854
- if (!searchBy || searchBy.length === 0) return;
2855
- switch (e.key) {
2856
- case "Backspace": {
2857
- if (!searchString && selectedTags && selectedTags.length > 0) {
2858
- const lastTag = selectedTags[selectedTags.length - 1];
2859
- if (!lastTag) return;
2860
- const key = lastTag.type === constants_exports.SearchType.GROUP ? constants_exports.SearchType.GROUP : lastTag.name;
2861
- removeKeyFromSearchMap({ key: String(key) });
2862
- }
2863
- break;
2864
- }
2865
- case "ArrowDown": {
2866
- e.preventDefault();
2867
- setHoveredIndex((prev) => {
2868
- const maxIndex = searchBy.length - 1;
2869
- const next = prev < maxIndex ? prev + 1 : prev;
2870
- setHoveredIndexSearchList(next);
2871
- return next;
2872
- });
2873
- break;
2874
- }
2875
- case "ArrowUp": {
2876
- e.preventDefault();
2877
- setHoveredIndex((prev) => {
2878
- const next = prev > 0 ? prev - 1 : prev;
2879
- setHoveredIndexSearchList(next);
2880
- return next;
2881
- });
2882
- break;
2883
- }
2884
- case "Enter": {
2885
- e.preventDefault();
2886
- if (!searchString.trim()) return;
2887
- const head = searchBy[hoveredIndex];
2888
- if (!head) return;
2889
- handleAddTagSearch({
2890
- title: head.title,
2891
- name: head.name,
2892
- value: searchString,
2893
- type: constants_exports.SearchType.SEARCH,
2894
- domain: head.filter_domain,
2895
- operator: head.operator,
2896
- dataIndex: head.dataIndex,
2897
- widget: head.widget,
2898
- modelType: head.type
2899
- });
2900
- break;
2901
- }
2902
- default:
2903
- break;
2904
- }
2905
- };
2906
- const handleMouseEnter = (index) => {
2907
- setHoveredIndexSearchList(index);
2908
- };
2909
- const handleMouseLeave = () => {
2910
- setHoveredIndexSearchList(null);
2911
- };
2912
- return {
2913
- groupBy,
2914
- searchBy,
2915
- filterBy,
2916
- selectedTags,
2917
- searchString,
2918
- setFilterBy,
2919
- setGroupBy,
2920
- setSearchBy,
2921
- clearSearch,
2922
- setSelectedTags,
2923
- removeSearchItems,
2924
- onSearchString: onChangeSearchInput,
2925
- handleAddTagSearch,
2926
- domain: formatDomain(),
2927
- context: contextSearch,
2928
- onKeyDown,
2929
- handleMouseEnter,
2930
- handleMouseLeave,
2931
- hoveredIndexSearchList
2932
- };
2933
- };
2934
-
2935
- // src/index.ts
2936
- __reExport(index_exports, utils_exports);
2937
- __reExport(index_exports, constants_exports);
2938
-
2939
- // src/environment.ts
2940
- var environment_exports = {};
2941
- __reExport(environment_exports, environment_star);
2942
- import * as environment_star from "@fctc/interface-logic/environment";
2943
-
2944
- // src/index.ts
2945
- __reExport(index_exports, environment_exports);
2946
- __reExport(index_exports, provider_exports);
2947
-
2948
- // src/services.ts
2949
- var services_exports = {};
2950
- __reExport(services_exports, services_star);
2951
- import * as services_star from "@fctc/interface-logic/services";
2952
-
2953
- // src/index.ts
2954
- __reExport(index_exports, services_exports);
2955
-
2956
- // src/types.ts
2957
- var types_exports = {};
2958
- __reExport(types_exports, types_star);
2959
- import * as types_star from "@fctc/interface-logic/types";
2960
-
2961
- // src/index.ts
2962
- __reExport(index_exports, types_exports);
2963
- export {
2964
- AppProvider,
2965
- STORAGES,
2966
- binaryFieldController,
2967
- colorFieldController,
2968
- copyLinkButtonController,
2969
- countSum,
2970
- downLoadBinaryController,
2971
- downloadFileController,
2972
- durationController,
2973
- guessTypeFromUrl,
2974
- isObjectEmpty,
2975
- languages,
2976
- many2manyBinaryController,
2977
- many2manyFieldController,
2978
- many2manyTagsController,
2979
- many2oneButtonController,
2980
- many2oneFieldController,
2981
- mergeButtons,
2982
- priorityFieldController,
2983
- providerEinvoiceFieldController,
2984
- searchController,
2985
- setStorageItemAsync,
2986
- statusDropdownController,
2987
- tableController,
2988
- tableGroupController,
2989
- tableHeadController,
2990
- useAddEntity,
2991
- useAppProvider,
2992
- useButton,
2993
- useCallAction,
2994
- useChangeOrderPreparationState,
2995
- useChangeStatus,
2996
- useCheckPayment,
2997
- useCompany,
2998
- useConfig,
2999
- useCreateEntity,
3000
- useCreatePosConfig,
3001
- useCreateSession,
3002
- useDebounce,
3003
- useDelete,
3004
- useDeleteComment,
3005
- useDeleteEntity,
3006
- useDetail,
3007
- useDuplicateRecord,
3008
- useExecuteImport,
3009
- useExportExcel,
3010
- useForgotPassword,
3011
- useForgotPasswordSSO,
3012
- useGenSerialNumber,
3013
- useGeneratePaymentQrInfo,
3014
- useGet2FAMethods,
3015
- useGetASession,
3016
- useGetAccessByCode,
3017
- useGetAction,
3018
- useGetActionDetail,
3019
- useGetAll,
3020
- useGetCalendar,
3021
- useGetComment,
3022
- useGetCompanyInfo,
3023
- useGetConversionRate,
3024
- useGetCurrency,
3025
- useGetCurrentCompany,
3026
- useGetDetail,
3027
- useGetExternalTabs,
3028
- useGetFieldExport,
3029
- useGetFieldOnChange,
3030
- useGetFileExcel,
3031
- useGetFormView,
3032
- useGetGroups,
3033
- useGetList,
3034
- useGetListCompany,
3035
- useGetListData,
3036
- useGetListMyBankAccount,
3037
- useGetMenu,
3038
- useGetOrderLine,
3039
- useGetPinCode,
3040
- useGetPrintReport,
3041
- useGetProGressBar,
3042
- useGetProfile,
3043
- useGetProvider,
3044
- useGetResequence,
3045
- useGetRowIds,
3046
- useGetSelection,
3047
- useGetSpecification,
3048
- useGetUser,
3049
- useGetView,
3050
- useGrantAccess,
3051
- useIsValidToken,
3052
- useListData,
3053
- useLoadAction,
3054
- useLoadMessage,
3055
- useLoginCredential,
3056
- useLoginSocial,
3057
- useLogout,
3058
- useMenu,
3059
- useModel,
3060
- useOdooDataTransform,
3061
- useOnChangeForm,
3062
- useParsePreview,
3063
- usePrint,
3064
- useProfile,
3065
- useReadGroup,
3066
- useRemoveRow,
3067
- useRemoveTotpSetup,
3068
- useRequestSetupTotp,
3069
- useResetPassword,
3070
- useResetPasswordSSO,
3071
- useRunAction,
3072
- useSave,
3073
- useSendComment,
3074
- useSettingsWebRead2fa,
3075
- useSignInSSO,
3076
- useStorageState,
3077
- useSwitchLocale,
3078
- useUpdatePassword,
3079
- useUploadFile,
3080
- useUploadFileExcel,
3081
- useUploadIdFile,
3082
- useUploadImage,
3083
- useUser,
3084
- useValidateActionToken,
3085
- useVerify2FA,
3086
- useVerifyTotp,
3087
- useViewV2,
3088
- validateAndParseDate
3089
- };