@apia/api 2.0.11 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,3213 @@
1
- export { ApiaApiHandler, getFunction } from './ApiaApiHandler.js';
2
- export { default as ApiaApi, makeApiaUrl } from './apiaApi.js';
3
- export { getModal } from './fields/ApiaApiInput.js';
1
+ import { jsx, jsxs, Fragment } from '@apia/theme/jsx-runtime';
2
+ import * as React from 'react';
3
+ import React__default, { createContext, useState, useCallback, useEffect, useId } from 'react';
4
+ import { Box, Label, spacing, getVariant } from '@apia/theme';
5
+ import { debugDispatcher, parseXmlAsync, EventEmitter, arrayOrArray, useMount, encrypt, noNaN, getIndex, getLabel, StatefulEmitter, focus, focusSelector, useLatest } from '@apia/util';
6
+ import { notify, getNotificationMessageObj, dispatchNotifications } from '@apia/notifications';
7
+ import { classToValidate, Checkbox, FileInput, classToValidationFunction, Input, Radio, Select, Textarea, useFormContext, validationsStore, hasSucceedFormValidation, Form } from '@apia/validations';
8
+ import { Accordion, AccordionItem, useModal, LabelBox, SimpleButton, ApiaUtil, Modal, ProgressBar } from '@apia/components';
9
+ import axios from 'axios';
10
+ import merge from 'lodash-es/merge';
11
+ import QueryString from 'qs';
12
+ import { session } from '@apia/session';
13
+ import uniqueId from 'lodash-es/uniqueId';
14
+ import { ResponsiveTableContext, ResponsiveTable, Pagination, Sort, Responsive, Additional, responsiveTableStore } from '@apia/table';
15
+
16
+ const ApiaApiId = createContext("apiaApi");
17
+ const ApiaApiContext = ({
18
+ children,
19
+ id
20
+ }) => {
21
+ return /* @__PURE__ */ jsx(ApiaApiId.Provider, { value: id, children });
22
+ };
23
+ var ApiaApiContext$1 = React.memo(ApiaApiContext);
24
+
25
+ debugDispatcher.on(
26
+ "parseXml",
27
+ async ([text]) => {
28
+ const result = await parseXmlAsync(text);
29
+ console.info(result);
30
+ },
31
+ "Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript."
32
+ );
33
+ const defaultConfig = {
34
+ debug: false,
35
+ colors: {
36
+ exception: "red",
37
+ alert: "yellow",
38
+ message: "lightgreen"
39
+ },
40
+ handleLoad: false
41
+ };
42
+ const STORED_CONFIG = "ApiaApiConfig";
43
+ let forcedConfig = {};
44
+ const storedConfig = localStorage.getItem(STORED_CONFIG);
45
+ if (storedConfig)
46
+ forcedConfig = JSON.parse(storedConfig);
47
+ function getConfig(outerBehaveConfig) {
48
+ return merge({}, defaultConfig, outerBehaveConfig, forcedConfig);
49
+ }
50
+ function makeUrl(url, queryData, stringifyOptions) {
51
+ let finalUrl = url;
52
+ const questionMarkIndex = finalUrl.indexOf("?");
53
+ if (questionMarkIndex === -1)
54
+ finalUrl += "?";
55
+ else if (questionMarkIndex !== finalUrl.length - 1 && !finalUrl.endsWith("&"))
56
+ finalUrl += "&";
57
+ let parsedUrl = `${finalUrl}${queryData ? QueryString.stringify(queryData, stringifyOptions) : ""}`;
58
+ if (parsedUrl.endsWith("&") || parsedUrl.endsWith("?")) {
59
+ parsedUrl = parsedUrl.slice(0, parsedUrl.length - 1);
60
+ }
61
+ return parsedUrl;
62
+ }
63
+ const getURLActionName = (url) => {
64
+ const actionIdx = url.match(/action=(\w+)/)?.[1];
65
+ return actionIdx ?? "noAction";
66
+ };
67
+ class ApiaActionsClass extends EventEmitter {
68
+ }
69
+ const ApiaActions = new ApiaActionsClass();
70
+ function getColor(color, colors = defaultConfig.colors ?? {
71
+ exception: "red",
72
+ alert: "yellow",
73
+ message: "green"
74
+ }) {
75
+ return colors[color];
76
+ }
77
+ const handleWrongResponse = (error) => {
78
+ let errorMessage;
79
+ if (typeof error !== "string") {
80
+ if (error.message)
81
+ errorMessage = error.message;
82
+ else
83
+ errorMessage = error.toString();
84
+ } else
85
+ errorMessage = error;
86
+ notify({
87
+ type: "danger",
88
+ message: error.message.replaceAll("AxiosError", "Error")
89
+ });
90
+ console.log("%c ", "font-size:10vh");
91
+ console.log("%cError in ApiaApi", "color:red;font-size:2em;font-weight:bold");
92
+ console.log(`red/${errorMessage}`, { error });
93
+ console.log("%c ", "font-size:10vh");
94
+ };
95
+ function isJsonResponse(response) {
96
+ return response.headers["content-type"].match("application/json");
97
+ }
98
+ function isXmlResponse(response) {
99
+ return response.headers["content-type"].match(
100
+ /(?:application|text)?\/xml/
101
+ );
102
+ }
103
+ function isHtmlResponse(response) {
104
+ return response.headers["content-type"].match(
105
+ /(?:application|text)?\/html/
106
+ );
107
+ }
108
+ function handleActions(actions) {
109
+ if (actions) {
110
+ if (getConfig().debug)
111
+ console.log(
112
+ "%cHandled actions: ",
113
+ `color: ${getConfig().colors?.message ?? "green"}`,
114
+ { actions }
115
+ );
116
+ const actionsArray = arrayOrArray(actions.action);
117
+ actionsArray.forEach((action) => {
118
+ ApiaActions.emit("action", {
119
+ ...action,
120
+ param: arrayOrArray(action.param)
121
+ });
122
+ });
123
+ }
124
+ }
125
+ function handleOnClose({
126
+ exceptions,
127
+ onClose,
128
+ sysExceptions,
129
+ sysMessages
130
+ }) {
131
+ try {
132
+ import(
133
+ /* webpackChunkName: "api-[request]" */
134
+ `/api/onClose/${onClose}.ts`
135
+ ).then(
136
+ (func) => {
137
+ if (exceptions || sysExceptions || sysMessages) {
138
+ const notificationsObject = getNotificationMessageObj({
139
+ exceptions,
140
+ onClose,
141
+ sysExceptions,
142
+ sysMessages
143
+ });
144
+ if (notificationsObject)
145
+ notificationsObject.forEach((notification) => {
146
+ notify({
147
+ ...notification,
148
+ onClose: func.default
149
+ });
150
+ });
151
+ else
152
+ func.default();
153
+ } else
154
+ func.default();
155
+ },
156
+ (e) => {
157
+ notify({
158
+ message: `onClose action not found: ${String(e)}`,
159
+ type: "danger"
160
+ });
161
+ }
162
+ );
163
+ } catch (e) {
164
+ parseMessages({ exceptions, sysExceptions, sysMessages });
165
+ console.error("Error while handling onClose");
166
+ console.error(e);
167
+ }
168
+ }
169
+ function parseMessages(response) {
170
+ if (!response)
171
+ return;
172
+ const { exceptions, sysMessages, sysExceptions } = response;
173
+ if (exceptions || sysExceptions || sysMessages) {
174
+ try {
175
+ dispatchNotifications({
176
+ exceptions,
177
+ sysExceptions,
178
+ sysMessages
179
+ });
180
+ } catch (e) {
181
+ handleWrongResponse(new Error(e));
182
+ }
183
+ }
184
+ }
185
+ const parseSuccessfulResponse = async (response, currentUrl, outerBehaveConfig = defaultConfig) => {
186
+ const behaveConfig = getConfig(outerBehaveConfig);
187
+ let parsedObj = void 0;
188
+ if (isJsonResponse(response)) {
189
+ if (typeof response.data === "string")
190
+ parsedObj = JSON.parse(
191
+ response.data.trim()
192
+ );
193
+ else if (typeof response.data === "object" && response.data)
194
+ parsedObj = response.data;
195
+ } else if (isXmlResponse(response)) {
196
+ parsedObj = await parseXmlAsync(response.data).catch(
197
+ (e) => {
198
+ handleWrongResponse(new Error(e));
199
+ }
200
+ );
201
+ } else if (isHtmlResponse(response)) {
202
+ console.error(
203
+ "El contenido devuelto es Html, no se esperaba esa respuesta"
204
+ );
205
+ return null;
206
+ }
207
+ if (behaveConfig.validateResponse) {
208
+ const validateResult = await behaveConfig.validateResponse({
209
+ ...response,
210
+ data: parsedObj?.load ?? parsedObj
211
+ });
212
+ if (typeof validateResult === "string")
213
+ throw new Error(`Validation error: ${validateResult}`);
214
+ else if (!validateResult) {
215
+ throw new Error("Error");
216
+ }
217
+ }
218
+ if (parsedObj) {
219
+ const {
220
+ actions,
221
+ onClose,
222
+ exceptions,
223
+ sysExceptions,
224
+ sysMessages,
225
+ load,
226
+ ...rest
227
+ } = parsedObj;
228
+ if (rest.code === "-1" && exceptions) {
229
+ session.invalidate();
230
+ return null;
231
+ }
232
+ if (exceptions && behaveConfig.debug) {
233
+ console.log(
234
+ `%cparseSuccessfulResponse`,
235
+ `color: ${getColor("exception", behaveConfig.colors)}`,
236
+ {
237
+ exceptions
238
+ }
239
+ );
240
+ }
241
+ if (sysExceptions && behaveConfig.debug) {
242
+ console.log(
243
+ `%cparseSuccessfulResponse`,
244
+ `color: ${getColor("exception", behaveConfig.colors)}`,
245
+ {
246
+ sysExceptions
247
+ }
248
+ );
249
+ }
250
+ if (sysMessages && behaveConfig.debug) {
251
+ console.log(
252
+ `%cparseSuccessfulResponse`,
253
+ `color: ${getColor("alert", behaveConfig.colors)}`,
254
+ {
255
+ sysMessages
256
+ }
257
+ );
258
+ }
259
+ handleActions(actions);
260
+ if (behaveConfig.handleLoad && onClose)
261
+ handleOnClose({
262
+ exceptions,
263
+ onClose,
264
+ sysExceptions,
265
+ sysMessages
266
+ });
267
+ else
268
+ parseMessages({ exceptions, sysExceptions, sysMessages });
269
+ if (load) {
270
+ if (behaveConfig.handleLoad) {
271
+ console.log(
272
+ `%chandleLoad`,
273
+ `color: ${getColor("message", behaveConfig.colors)}`,
274
+ {
275
+ load
276
+ }
277
+ );
278
+ if (!handle(load, currentUrl, {
279
+ methodsPath: outerBehaveConfig.methodsPath,
280
+ modalConfiguration: {
281
+ ...behaveConfig.modalConfiguration,
282
+ onClose: () => {
283
+ if (onClose)
284
+ handleOnClose({
285
+ exceptions,
286
+ onClose,
287
+ sysExceptions,
288
+ sysMessages
289
+ });
290
+ if (behaveConfig.modalConfiguration?.onClose)
291
+ behaveConfig.modalConfiguration?.onClose();
292
+ }
293
+ }
294
+ })) {
295
+ console.log(
296
+ `%cunhandledLoad -> There is no handler defined`,
297
+ `color: ${getColor("exception", behaveConfig.colors)}`,
298
+ {
299
+ load
300
+ }
301
+ );
302
+ }
303
+ }
304
+ return { ...load, sysMessages, exceptions, sysExceptions };
305
+ }
306
+ return { ...rest, sysMessages, exceptions, sysExceptions };
307
+ }
308
+ return null;
309
+ };
310
+ async function handleResponse(result, currentUrl, outerBehaveConfig = defaultConfig) {
311
+ const behaveConfig = getConfig(outerBehaveConfig);
312
+ try {
313
+ if (!result || result.data === void 0) {
314
+ if (behaveConfig.debug)
315
+ console.log(
316
+ `%cApiaApi wrong response`,
317
+ `color: ${getColor("alert", behaveConfig.colors)}`
318
+ );
319
+ } else {
320
+ const parsedResponse = await parseSuccessfulResponse(
321
+ result,
322
+ currentUrl,
323
+ behaveConfig
324
+ );
325
+ const action = getURLActionName(currentUrl);
326
+ if (behaveConfig.debug)
327
+ console.log(
328
+ `%c <- ApiaApi.${result.config.method ?? ""} ${action} `,
329
+ `color: ${getColor("message", behaveConfig.colors)}`,
330
+ {
331
+ data: parsedResponse
332
+ }
333
+ );
334
+ return {
335
+ ...result,
336
+ data: parsedResponse,
337
+ hasError: !!parsedResponse?.exceptions || !!parsedResponse?.sysExceptions,
338
+ hasMessages: !!parsedResponse?.sysMessages
339
+ };
340
+ }
341
+ } catch (e) {
342
+ handleWrongResponse(new Error(e));
343
+ return null;
344
+ }
345
+ return null;
346
+ }
347
+ async function post(par1, par2) {
348
+ const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
349
+ const configParameter = typeof par1 === "string" ? par2 ?? defaultConfig : par1;
350
+ const behaveConfig = {
351
+ ...getConfig(configParameter),
352
+ postData: configParameter.postDataTreatement === "stringify" ? QueryString.stringify(
353
+ configParameter.postData,
354
+ configParameter.stringifyOptions
355
+ ) : configParameter.postData
356
+ };
357
+ const parsedUrl = makeUrl(
358
+ actualUrl,
359
+ behaveConfig.queryData,
360
+ behaveConfig.stringifyOptions
361
+ );
362
+ if (behaveConfig.debug) {
363
+ const queryString = actualUrl.split("&");
364
+ const action = getURLActionName(actualUrl);
365
+ console.log(
366
+ `%cApiaApi.post ${action}`,
367
+ `color: ${getColor("message", behaveConfig.colors)}`,
368
+ {
369
+ url: parsedUrl,
370
+ queryDataInURL: [...queryString],
371
+ queryData: behaveConfig.queryData,
372
+ formData: behaveConfig.postData,
373
+ stringifyOptiopns: behaveConfig.stringifyOptions
374
+ }
375
+ );
376
+ }
377
+ const response = await axios.post(parsedUrl, behaveConfig.postData, behaveConfig.axiosConfig).catch((e) => {
378
+ handleWrongResponse(new Error(e));
379
+ });
380
+ if (response) {
381
+ const result = handleResponse(response, actualUrl, behaveConfig);
382
+ return result;
383
+ }
384
+ return null;
385
+ }
386
+ async function get(par1, par2) {
387
+ const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
388
+ const behaveConfig = getConfig(
389
+ typeof par1 === "string" ? par2 ?? defaultConfig : par1
390
+ );
391
+ const parsedUrl = makeUrl(
392
+ actualUrl,
393
+ behaveConfig.queryData,
394
+ behaveConfig.stringifyOptions
395
+ );
396
+ if (behaveConfig.debug)
397
+ console.log(
398
+ `%cApiaApi.get`,
399
+ `color: ${getColor("message", behaveConfig.colors)}`,
400
+ {
401
+ url: parsedUrl
402
+ }
403
+ );
404
+ const response = await axios.get(parsedUrl, behaveConfig.axiosConfig).catch((e) => {
405
+ handleWrongResponse(new Error(e));
406
+ });
407
+ if (response) {
408
+ const result = await handleResponse(
409
+ response,
410
+ actualUrl,
411
+ behaveConfig
412
+ );
413
+ return result;
414
+ }
415
+ return null;
416
+ }
417
+ const ApiaApi = {
418
+ get,
419
+ getConfig,
420
+ post
421
+ };
422
+ function makeApiaUrl(props) {
423
+ let actualQueryData = {};
424
+ if (props) {
425
+ const {
426
+ ajaxUrl,
427
+ queryString: queryString2,
428
+ stringifyOptions,
429
+ shouldAvoidTabId,
430
+ preventAsXmlParameter,
431
+ avoidTabId,
432
+ tabId: outerTabId,
433
+ ...rest
434
+ } = props;
435
+ actualQueryData = { ...rest };
436
+ }
437
+ const queryString = QueryString.stringify(
438
+ actualQueryData,
439
+ props?.stringifyOptions ?? {
440
+ arrayFormat: "repeat",
441
+ encodeValuesOnly: false
442
+ }
443
+ );
444
+ let actualAjaxUrl = props?.ajaxUrl ?? window.URL_REQUEST_AJAX;
445
+ if (actualAjaxUrl.indexOf("?") === actualAjaxUrl.length - 1) {
446
+ actualAjaxUrl = actualAjaxUrl.slice(0, actualAjaxUrl.length - 1);
447
+ }
448
+ if (!actualAjaxUrl.startsWith("/")) {
449
+ actualAjaxUrl = `/${actualAjaxUrl}`;
450
+ }
451
+ const match = window.TAB_ID_REQUEST.match(/tokenId=(\w+)/);
452
+ const currentTokenId = (match ?? [])[1];
453
+ let tabId = (props?.tabId ? `&tabId=${props.tabId}&tokenId=${currentTokenId}` : window.TAB_ID_REQUEST).slice(1);
454
+ if (props?.avoidTabId) {
455
+ tabId = "";
456
+ }
457
+ let { CONTEXT } = window;
458
+ if (CONTEXT?.endsWith("/")) {
459
+ CONTEXT += CONTEXT.slice(0, CONTEXT.length - 1);
460
+ }
461
+ let timestamp = `timestamp=${Date.now()}&`;
462
+ if (props?.queryString && props.queryString.includes("timestamp=") || queryString?.includes("timestamp=")) {
463
+ timestamp = "";
464
+ }
465
+ const contextWord = CONTEXT.replaceAll("/", "");
466
+ actualAjaxUrl = actualAjaxUrl.match(
467
+ new RegExp(`^(?:(?:/?${contextWord})?/)?(.+)$`)
468
+ )?.[1];
469
+ return `${contextWord ? "/" : ""}${contextWord}/${actualAjaxUrl}?${timestamp}${!props?.preventAsXmlParameter ? "asXml=true&" : ""}${props?.queryString ? `${props.queryString}&` : ""}${queryString ? `${queryString}&` : ""}${tabId}`;
470
+ }
471
+ var ApiaApi$1 = ApiaApi;
472
+
473
+ const ApiaApiCheckbox = (props) => {
474
+ const element = React__default.useMemo(() => props.element, [props.element]);
475
+ const className = React__default.useMemo(
476
+ () => element.class ? `handler__checkbox ${element.class}` : "handler__checkbox",
477
+ [element.class]
478
+ );
479
+ const validationRules = React__default.useMemo(
480
+ () => ({
481
+ required: element.mandatory,
482
+ ...classToValidate(element.class)
483
+ }),
484
+ [element.class, element.mandatory]
485
+ );
486
+ const submitValueParser = React__default.useCallback(
487
+ (value) => value === "on" || value === true,
488
+ []
489
+ );
490
+ return /* @__PURE__ */ jsx(
491
+ Checkbox,
492
+ {
493
+ className,
494
+ name: element.id || element.name,
495
+ label: element.text,
496
+ title: element.title || element.text,
497
+ initialValue: String(element.selected) === "true",
498
+ disabled: element.readonly || element.disabled,
499
+ validationRules,
500
+ onChange: element.onChange,
501
+ submitValueParser
502
+ }
503
+ );
504
+ };
505
+
506
+ const ApiaApiFileInput = (props) => {
507
+ const element = React__default.useMemo(() => props.element, [props.element]);
508
+ const className = React__default.useMemo(
509
+ () => element.class ? `handler__file ${element.class}` : "handler__file",
510
+ [element.class]
511
+ );
512
+ const validationRules = React__default.useMemo(
513
+ () => ({
514
+ required: element.mandatory,
515
+ ...classToValidate(element.class)
516
+ }),
517
+ [element.class, element.mandatory]
518
+ );
519
+ return /* @__PURE__ */ jsx(
520
+ FileInput,
521
+ {
522
+ className,
523
+ name: element.id || element.name,
524
+ label: element.text,
525
+ title: element.title || element.text,
526
+ readOnly: element.readonly,
527
+ disabled: element.disabled,
528
+ validationRules
529
+ }
530
+ );
531
+ };
532
+ ApiaApiFileInput.displayName = "ApiaApiFileInput";
533
+
534
+ const getModal = (path) => {
535
+ return React__default.lazy(() => {
536
+ return new Promise((resolve) => {
537
+ import(
538
+ /* webpackChunkName: "handlerModal" */
539
+ /* webpackInclude: /\.tsx?$/ */
540
+ `/api/modals/${path}`
541
+ ).then((result) => {
542
+ resolve(
543
+ result
544
+ );
545
+ }).catch((error) => {
546
+ resolve({
547
+ default: () => {
548
+ console.error(error);
549
+ throw new Error(
550
+ `The above error ocurred at component ApiaApiHandler/${path}, does it exist?`
551
+ );
552
+ }
553
+ });
554
+ });
555
+ });
556
+ });
557
+ };
558
+ const ApiaApiInput = (props) => {
559
+ const element = React__default.useMemo(() => props.element, [props.element]);
560
+ const [Submodal, setSubmodal] = React__default.useState(null);
561
+ useMount(() => {
562
+ if (element.modalFunction) {
563
+ const found = element.modalFunction.match(/(?:fnc)?(\w+)\(?\)?$/);
564
+ if (found) {
565
+ const modalName = found[found.length - 1];
566
+ setSubmodal(getModal(modalName));
567
+ }
568
+ }
569
+ });
570
+ const className = React__default.useMemo(
571
+ () => element.class ? `handler__${element.type} ${element.class}` : `handler__${element.type}`,
572
+ [element.class, element.type]
573
+ );
574
+ const validationRules = React__default.useMemo(
575
+ () => ({
576
+ required: element.mandatory,
577
+ maxLength: element.maxlength ? Number(element.maxlength) : void 0,
578
+ pattern: element.regExp,
579
+ patternMessage: element.regExpMessage,
580
+ ...classToValidate(element.class)
581
+ }),
582
+ [
583
+ element.class,
584
+ element.mandatory,
585
+ element.maxlength,
586
+ element.regExp,
587
+ element.regExpMessage
588
+ ]
589
+ );
590
+ const validationFunction = React__default.useMemo(
591
+ () => classToValidationFunction(element.class),
592
+ [element.class]
593
+ );
594
+ const submitValueParser = React__default.useCallback(
595
+ (value) => {
596
+ if (element.type === "password") {
597
+ return encrypt(
598
+ window.SALT,
599
+ window.IV,
600
+ window.PASSPHRASE,
601
+ value,
602
+ Number(window.KEY_SIZE),
603
+ Number(window.ITERATION_COUNT)
604
+ );
605
+ }
606
+ return value;
607
+ },
608
+ [element.type]
609
+ );
610
+ if (element.modalFunction) {
611
+ if (Submodal) {
612
+ return /* @__PURE__ */ jsx(React__default.Suspense, { children: /* @__PURE__ */ jsx(Submodal, { ...props, element }) });
613
+ }
614
+ return null;
615
+ }
616
+ return /* @__PURE__ */ jsx(
617
+ Input,
618
+ {
619
+ type: element.isADate ? "date" : element.type,
620
+ className,
621
+ name: element.id || element.name,
622
+ label: element.text,
623
+ title: element.title || element.text,
624
+ value: element.value,
625
+ readOnly: element.readonly,
626
+ disabled: element.disabled,
627
+ validationFunction,
628
+ validationRules,
629
+ submitValueParser,
630
+ onChange: element.onChange,
631
+ autoComplete: element.type === "password" ? "new-password" : void 0
632
+ }
633
+ );
634
+ };
635
+ ApiaApiInput.displayName = "ApiaApiInput";
636
+
637
+ const ApiaApiRadio = (props) => {
638
+ const element = React__default.useMemo(() => props.element, [props.element]);
639
+ const className = React__default.useMemo(
640
+ () => element.class ? `handler__radio ${element.class}` : "handler__radio",
641
+ [element.class]
642
+ );
643
+ const options = React__default.useMemo(
644
+ () => arrayOrArray(element.options?.option).map((currOption) => {
645
+ return { value: currOption.value, label: currOption.content };
646
+ }),
647
+ [element.options?.option]
648
+ );
649
+ const validationRules = React__default.useMemo(
650
+ () => ({
651
+ required: element.mandatory,
652
+ ...classToValidate(element.class)
653
+ }),
654
+ [element.class, element.mandatory]
655
+ );
656
+ return /* @__PURE__ */ jsx(
657
+ Radio,
658
+ {
659
+ className,
660
+ name: element.id || element.name,
661
+ label: element.text,
662
+ title: element.title || element.text,
663
+ initialValue: element.value,
664
+ disabled: element.readonly || element.disabled,
665
+ validationRules,
666
+ options,
667
+ onChange: element.onChange
668
+ }
669
+ );
670
+ };
671
+ ApiaApiRadio.displayName = "ApiaApiRadio";
672
+
673
+ class ApiaApiSelectOptions extends EventEmitter {
674
+ }
675
+ const apiaApiSelectOptions = new ApiaApiSelectOptions();
676
+ const ApiaApiSelect = (props) => {
677
+ const element = React__default.useMemo(() => props.element, [props.element]);
678
+ const className = React__default.useMemo(
679
+ () => element.class ? `handler__select ${element.class}` : "handler__select",
680
+ [element.class]
681
+ );
682
+ const [options, setOptions] = React__default.useState(
683
+ arrayOrArray(element.options?.option).map((currOption) => {
684
+ return { value: currOption.value, label: currOption.content };
685
+ })
686
+ );
687
+ const validationRules = React__default.useMemo(
688
+ () => ({
689
+ required: element.mandatory,
690
+ ...classToValidate(element.class)
691
+ }),
692
+ [element.class, element.mandatory]
693
+ );
694
+ React__default.useEffect(() => {
695
+ const unsuscribe = apiaApiSelectOptions.on("setOptions", (ev) => {
696
+ if (ev.fieldName === element.name) {
697
+ setOptions(
698
+ ev.options.map((currOption) => ({
699
+ value: currOption.value,
700
+ label: currOption.content
701
+ }))
702
+ );
703
+ }
704
+ });
705
+ return () => {
706
+ unsuscribe();
707
+ };
708
+ }, [element.name]);
709
+ const initialValue = React__default.useMemo(
710
+ () => options.find((current) => current.value === props.element.value)?.value ?? options[0]?.value ?? "",
711
+ [options, props.element.value]
712
+ );
713
+ return /* @__PURE__ */ jsx(
714
+ Select,
715
+ {
716
+ className,
717
+ name: element.id || element.name,
718
+ label: element.text,
719
+ title: element.title || element.text,
720
+ initialValue,
721
+ disabled: element.readonly || element.disabled,
722
+ validationRules,
723
+ options,
724
+ onChange: element.onChange
725
+ }
726
+ );
727
+ };
728
+ ApiaApiSelect.displayName = "ApiaApiSelect";
729
+
730
+ const ApiaApiTextArea = (props) => {
731
+ const element = React__default.useMemo(() => props.element, [props.element]);
732
+ const className = React__default.useMemo(
733
+ () => element.class ? `handler__textarea ${element.class}` : "handler__textarea",
734
+ [element.class]
735
+ );
736
+ const validationRules = React__default.useMemo(
737
+ () => ({
738
+ required: element.mandatory,
739
+ maxLength: element.maxlength ? Number(element.maxlength) : void 0,
740
+ pattern: element.regExp,
741
+ patternMessage: element.regExpMessage,
742
+ ...classToValidate(element.class)
743
+ }),
744
+ [
745
+ element.class,
746
+ element.mandatory,
747
+ element.maxlength,
748
+ element.regExp,
749
+ element.regExpMessage
750
+ ]
751
+ );
752
+ const validationFunction = React__default.useMemo(
753
+ () => classToValidationFunction(element.class),
754
+ [element.class]
755
+ );
756
+ return /* @__PURE__ */ jsx(
757
+ Textarea,
758
+ {
759
+ className,
760
+ name: element.id || element.name,
761
+ label: element.text,
762
+ title: element.title || element.text,
763
+ value: element.value,
764
+ readOnly: element.readonly,
765
+ disabled: element.disabled,
766
+ validationFunction,
767
+ validationRules,
768
+ onChange: element.onChange
769
+ }
770
+ );
771
+ };
772
+ ApiaApiTextArea.displayName = "ApiaApiTextArea";
773
+
774
+ function parseResult(result) {
775
+ if (result) {
776
+ const { pageInfo } = result.function.messages.result;
777
+ const { table } = result.function.messages.result;
778
+ if (table) {
779
+ table.row = arrayOrArray(table.row);
780
+ const returnRows = table.row.map((currentRow) => {
781
+ const returnRow = {
782
+ id: currentRow.id,
783
+ cells: arrayOrArray(currentRow.cell).map((currentCell) => {
784
+ const children = typeof currentCell === "string" ? currentCell : currentCell.label;
785
+ const returnCell = {
786
+ children
787
+ };
788
+ return returnCell;
789
+ }),
790
+ className: `${currentRow.classToAdd ?? ""} ${currentRow.unselectableTR ? "locked" : ""}`
791
+ };
792
+ return returnRow;
793
+ });
794
+ return {
795
+ currentPage: Number.parseInt(pageInfo.currentPage, 10),
796
+ pageCount: Number.parseInt(pageInfo.pageCount, 10),
797
+ reachedMax: pageInfo.reachedMax,
798
+ rows: returnRows,
799
+ recordsCount: noNaN(pageInfo.totalRecords)
800
+ };
801
+ }
802
+ }
803
+ return {
804
+ currentPage: 0,
805
+ pageCount: 0,
806
+ reachedMax: true,
807
+ rows: [],
808
+ recordsCount: 0
809
+ };
810
+ }
811
+ const defaultFetcher = {
812
+ async filter({ filters, parameters, path, requestConfig }) {
813
+ const filterValues = {
814
+ selectOnlyOne: false
815
+ };
816
+ (filters ?? []).forEach((currentFilter) => {
817
+ filterValues[currentFilter.id] = currentFilter.currentValue;
818
+ });
819
+ const result = await ApiaApi$1.post(
820
+ makeApiaUrl({
821
+ react: true,
822
+ action: "filter",
823
+ ajaxUrl: `/${path}`,
824
+ isAjax: true,
825
+ timestamp: Date.now(),
826
+ stringifyOptions: requestConfig?.stringifyOptions
827
+ }),
828
+ {
829
+ ...requestConfig,
830
+ postDataTreatement: "stringify",
831
+ postData: { ...parameters, ...filterValues }
832
+ }
833
+ );
834
+ return parseResult(result?.data);
835
+ },
836
+ async page({ page, path, requestConfig }) {
837
+ const result = await ApiaApi$1.post(
838
+ makeApiaUrl({
839
+ react: true,
840
+ action: "page",
841
+ ajaxUrl: `/${path}`,
842
+ pageNumber: page,
843
+ isAjax: true,
844
+ stringifyOptions: requestConfig?.stringifyOptions
845
+ }),
846
+ {
847
+ ...requestConfig
848
+ }
849
+ );
850
+ return parseResult(result?.data);
851
+ },
852
+ async refresh({ path, requestConfig }) {
853
+ const result = await ApiaApi$1.post(
854
+ makeApiaUrl({
855
+ react: true,
856
+ action: "refresh",
857
+ ajaxUrl: `/${path}`,
858
+ isAjax: true,
859
+ stringifyOptions: requestConfig?.stringifyOptions
860
+ }),
861
+ {
862
+ ...requestConfig
863
+ }
864
+ );
865
+ return parseResult(result?.data);
866
+ },
867
+ async sort({ path, requestConfig, sort }) {
868
+ const result = await ApiaApi$1.post(
869
+ makeApiaUrl({
870
+ react: true,
871
+ action: "sort",
872
+ ajaxUrl: `/${path}`,
873
+ isAjax: true,
874
+ stringifyOptions: requestConfig?.stringifyOptions
875
+ }),
876
+ {
877
+ ...requestConfig,
878
+ postData: {
879
+ orderBy: sort
880
+ },
881
+ postDataTreatement: "stringify"
882
+ }
883
+ );
884
+ return parseResult(result?.data);
885
+ }
886
+ };
887
+ function useFetcher(fetcher = defaultFetcher) {
888
+ const [isLoading, setIsLoading] = React__default.useState(0);
889
+ const proxy = React__default.useMemo(() => {
890
+ return new Proxy(fetcher, {
891
+ get(obj, prop) {
892
+ if (prop in obj) {
893
+ const method = obj[prop];
894
+ return (args) => {
895
+ return new Promise((resolve, reject) => {
896
+ setIsLoading((currentIndex) => currentIndex + 1);
897
+ method(args).then((result) => {
898
+ setIsLoading((currentIndex) => currentIndex - 1);
899
+ resolve(result);
900
+ }, reject);
901
+ });
902
+ };
903
+ }
904
+ return void 0;
905
+ }
906
+ });
907
+ }, [fetcher]);
908
+ return { fetcher: proxy, isLoading: isLoading > 0 };
909
+ }
910
+
911
+ const ApiaEnvironmentsModal = (props) => {
912
+ const [actualColumns, setColumns] = useState(
913
+ environmentsModal.columns.map((current) => ({
914
+ ...current,
915
+ currentSorting: getIndex(
916
+ ["A", "D", null],
917
+ [
918
+ ["A", "Up"].includes(current.currentSorting || ""),
919
+ ["D", "Down"].includes(current.currentSorting || ""),
920
+ true
921
+ ]
922
+ )
923
+ }))
924
+ );
925
+ const [filters, setFilters] = useState(environmentsModal.filters);
926
+ const [state, setState] = useState(null);
927
+ const { fetcher } = useFetcher();
928
+ const filter = useCallback(
929
+ (newFilters = filters) => {
930
+ if (newFilters) {
931
+ fetcher.filter({
932
+ filters: newFilters,
933
+ parameters: {
934
+ txtName: props.initialProps.name,
935
+ txtTitle: props.initialProps.title,
936
+ txtDesc: props.initialProps.title,
937
+ selectOnlyOne: false,
938
+ txtAdtSql: props.initialProps.adtInfo ?? "",
939
+ fromGlobalDescAdm: false,
940
+ usrToUpdate: ""
941
+ },
942
+ path: environmentsModal.path,
943
+ requestConfig: {}
944
+ }).then((result) => {
945
+ if (result) {
946
+ setState(result);
947
+ }
948
+ }).catch(console.error);
949
+ }
950
+ },
951
+ [
952
+ fetcher,
953
+ filters,
954
+ props.initialProps.adtInfo,
955
+ props.initialProps.name,
956
+ props.initialProps.title
957
+ ]
958
+ );
959
+ useEffect(() => {
960
+ filter();
961
+ }, []);
962
+ useEffect(() => {
963
+ ApiaEnvironmentsModalEmitter.on("deleteFilters", filter);
964
+ }, [filter]);
965
+ const handleFilterChange = useCallback(
966
+ (ev) => {
967
+ const newFilters = filters?.map((currentFilter) => {
968
+ if (currentFilter.column === ev.column) {
969
+ return { ...ev };
970
+ }
971
+ return currentFilter;
972
+ });
973
+ setFilters(newFilters);
974
+ if (ev.runAutomatically)
975
+ filter(newFilters);
976
+ },
977
+ [filters, filter]
978
+ );
979
+ const handleSort = useCallback(
980
+ (ev) => {
981
+ fetcher.sort({
982
+ sort: ev.columnIndex,
983
+ parameters: {},
984
+ path: environmentsModal.path,
985
+ requestConfig: {}
986
+ }).then((result) => {
987
+ if (result) {
988
+ setColumns(
989
+ (currentColumns) => currentColumns.map((column) => {
990
+ if (column.name === ev.name)
991
+ return {
992
+ ...column,
993
+ currentSorting: column.currentSorting === "Down" || column.currentSorting === "D" || !column.currentSorting ? "A" : "D"
994
+ };
995
+ return { ...column, currentSorting: null };
996
+ })
997
+ );
998
+ setState(result);
999
+ }
1000
+ }).catch(console.error);
1001
+ },
1002
+ [fetcher]
1003
+ );
1004
+ const handleFilterPressEnter = useCallback(() => filter(), [filter]);
1005
+ const handleFilterBlur = useCallback(() => filter(), [filter]);
1006
+ const handlePageChange = useCallback(
1007
+ (page) => {
1008
+ fetcher.page({
1009
+ page,
1010
+ parameters: {},
1011
+ path: environmentsModal.path
1012
+ }).then((result) => {
1013
+ if (result) {
1014
+ setState(result);
1015
+ }
1016
+ }).catch(console.error);
1017
+ },
1018
+ [fetcher]
1019
+ );
1020
+ const handleRefresh = useCallback(() => {
1021
+ fetcher.refresh({
1022
+ parameters: {},
1023
+ path: environmentsModal.path
1024
+ }).then((result) => {
1025
+ if (result) {
1026
+ setState(result);
1027
+ }
1028
+ }).catch(console.error);
1029
+ }, [fetcher]);
1030
+ return state?.rows && /* @__PURE__ */ jsxs(
1031
+ ResponsiveTableContext,
1032
+ {
1033
+ columns: actualColumns,
1034
+ rows: state?.rows,
1035
+ filters,
1036
+ name: props.tableName ?? environmentsModal.label,
1037
+ variant: "layout.common.modals.table",
1038
+ onFilterChange: handleFilterChange,
1039
+ onSortChange: handleSort,
1040
+ onFilterBlur: handleFilterBlur,
1041
+ onFilterPressEnter: handleFilterPressEnter,
1042
+ isMultiple: true,
1043
+ children: [
1044
+ /* @__PURE__ */ jsx(ResponsiveTable, {}),
1045
+ /* @__PURE__ */ jsx(Box, { className: "pagination__wrapper", children: /* @__PURE__ */ jsx(
1046
+ Pagination,
1047
+ {
1048
+ currentPage: state.currentPage,
1049
+ onPageChange: handlePageChange,
1050
+ onRefresh: handleRefresh,
1051
+ pageCount: state.pageCount,
1052
+ reachedMax: state.reachedMax,
1053
+ recordsCount: state.recordsCount
1054
+ }
1055
+ ) })
1056
+ ]
1057
+ }
1058
+ );
1059
+ };
1060
+
1061
+ const FiltersModal = ({ tableName }) => {
1062
+ return /* @__PURE__ */ jsx(Box, { className: "additionalFiltersContent", children: /* @__PURE__ */ jsxs(Accordion, { className: "filtersModals__accordion", singleExpand: true, children: [
1063
+ /* @__PURE__ */ jsx(
1064
+ AccordionItem,
1065
+ {
1066
+ id: "Sortpanel",
1067
+ buttonProps: {
1068
+ ariaLabel: window.FINDER_ORDER_BY,
1069
+ label: window.FINDER_ORDER_BY
1070
+ },
1071
+ defaultExpanded: true,
1072
+ children: /* @__PURE__ */ jsx(Sort, { tableName })
1073
+ }
1074
+ ),
1075
+ /* @__PURE__ */ jsx(
1076
+ AccordionItem,
1077
+ {
1078
+ id: "Filters",
1079
+ buttonProps: {
1080
+ ariaLabel: window.FINDER_FILTERS,
1081
+ label: window.FINDER_FILTERS
1082
+ },
1083
+ children: /* @__PURE__ */ jsx(Responsive, { tableName })
1084
+ }
1085
+ ),
1086
+ /* @__PURE__ */ jsx(
1087
+ AccordionItem,
1088
+ {
1089
+ id: "Additional",
1090
+ buttonProps: {
1091
+ ariaLabel: window.ADDITIONAL_FILTERS_LABEL,
1092
+ label: window.ADDITIONAL_FILTERS_LABEL
1093
+ },
1094
+ children: /* @__PURE__ */ jsx(Additional, { tableName })
1095
+ }
1096
+ )
1097
+ ] }) });
1098
+ };
1099
+
1100
+ const ApiaEnvironmentsModalEmitter = new EventEmitter();
1101
+ const ApiaApiEnvironmentsModalField = (props) => {
1102
+ const { name } = useFormContext();
1103
+ const [selectedRows, setSelectedRows] = useState(
1104
+ props.element.value.split("#").filter((env) => env !== "").map((envData) => {
1105
+ const id2 = envData.split("_$_")[0];
1106
+ const title = envData.split("_$_")[1];
1107
+ return {
1108
+ id: id2,
1109
+ title
1110
+ };
1111
+ })
1112
+ );
1113
+ const {
1114
+ isLoading: isFiltersModalLoading,
1115
+ show: showFiltersModal,
1116
+ ...filtersModalProps
1117
+ } = useModal();
1118
+ const id = useId();
1119
+ const deleteFilters = useCallback(() => {
1120
+ const newFilters = environmentsModal.filters?.map(
1121
+ (currentFilter) => {
1122
+ return {
1123
+ ...currentFilter,
1124
+ currentValue: "",
1125
+ deleteFiltersTimestamp: Date.now()
1126
+ };
1127
+ }
1128
+ );
1129
+ ApiaEnvironmentsModalEmitter.emit("deleteFilters", newFilters);
1130
+ }, []);
1131
+ useEffect(() => {
1132
+ validationsStore.setFieldValue(
1133
+ name,
1134
+ props.element.name,
1135
+ selectedRows.map((e) => e.id).join("#")
1136
+ );
1137
+ }, [name, props.element.name, selectedRows]);
1138
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1139
+ /* @__PURE__ */ jsx(Label, { children: getLabel(props.element.text).text }),
1140
+ /* @__PURE__ */ jsxs(
1141
+ Box,
1142
+ {
1143
+ sx: {
1144
+ display: "flex",
1145
+ flexDirection: "column",
1146
+ gap: spacing(3)
1147
+ },
1148
+ children: [
1149
+ /* @__PURE__ */ jsx(
1150
+ Box,
1151
+ {
1152
+ sx: {
1153
+ maxHeight: "200px",
1154
+ overflow: "auto",
1155
+ width: "100%",
1156
+ display: "flex",
1157
+ flexWrap: "wrap"
1158
+ },
1159
+ children: selectedRows.map((row) => {
1160
+ return /* @__PURE__ */ jsx(
1161
+ LabelBox,
1162
+ {
1163
+ label: row.title,
1164
+ onClose: () => {
1165
+ setSelectedRows((prev) => {
1166
+ return prev.filter((prevRow) => {
1167
+ return prevRow.id !== row.id;
1168
+ });
1169
+ });
1170
+ }
1171
+ },
1172
+ row.id
1173
+ );
1174
+ })
1175
+ }
1176
+ ),
1177
+ /* @__PURE__ */ jsx(
1178
+ SimpleButton,
1179
+ {
1180
+ onClick: () => {
1181
+ ApiaUtil.instance.modals.open({
1182
+ onConfirm: () => {
1183
+ const rows = responsiveTableStore.getState().responsiveTableSlice[id].rows;
1184
+ const selectedIndex = responsiveTableStore.getState().responsiveTableSlice[id].selectedRows;
1185
+ const selectedRows2 = [];
1186
+ selectedIndex.forEach((i) => {
1187
+ if (rows[i]) {
1188
+ selectedRows2.push({
1189
+ id: rows[i].id,
1190
+ title: rows[i].cells[1].children
1191
+ });
1192
+ }
1193
+ });
1194
+ setSelectedRows((prev) => [
1195
+ ...prev,
1196
+ ...selectedRows2.filter((newEnv) => {
1197
+ return !prev.find((prevEnv) => prevEnv.id === newEnv.id);
1198
+ })
1199
+ ]);
1200
+ },
1201
+ confirmProps: { confirmButtonText: getLabel("btnCon").text },
1202
+ children: /* @__PURE__ */ jsx(
1203
+ ApiaEnvironmentsModal,
1204
+ {
1205
+ ...filtersModalProps,
1206
+ initialProps: props.element,
1207
+ tableName: id
1208
+ }
1209
+ ),
1210
+ size: "xxl",
1211
+ title: environmentsModal.label,
1212
+ NavBar: /* @__PURE__ */ jsxs(Fragment, { children: [
1213
+ /* @__PURE__ */ jsx(
1214
+ SimpleButton,
1215
+ {
1216
+ variant: "outline-sm",
1217
+ title: window.FILTERS_LABEL,
1218
+ onClick: () => {
1219
+ ApiaUtil.instance.modals.open({
1220
+ children: /* @__PURE__ */ jsx(FiltersModal, { tableName: id }),
1221
+ variant: "layout.common.modals.tableModal.additionalFiltersModal",
1222
+ size: "xl",
1223
+ noHeader: true,
1224
+ initialFocusGetter(modalInnerRef) {
1225
+ return modalInnerRef.querySelector(
1226
+ "select"
1227
+ );
1228
+ }
1229
+ });
1230
+ },
1231
+ isLoading: isFiltersModalLoading,
1232
+ children: window.FILTERS_LABEL
1233
+ }
1234
+ ),
1235
+ /* @__PURE__ */ jsx(
1236
+ SimpleButton,
1237
+ {
1238
+ variant: "outline-sm",
1239
+ onClick: deleteFilters,
1240
+ title: window.BTN_DELETE_FILTERS,
1241
+ children: window.BTN_DELETE_FILTERS
1242
+ }
1243
+ )
1244
+ ] })
1245
+ });
1246
+ },
1247
+ sx: {
1248
+ width: "fit-content !important"
1249
+ },
1250
+ children: getLabel("lblAdd").text
1251
+ }
1252
+ )
1253
+ ]
1254
+ }
1255
+ )
1256
+ ] });
1257
+ };
1258
+
1259
+ const ApiaTasksModal = (props) => {
1260
+ const [actualColumns, setColumns] = useState(
1261
+ tasksModal.columns.map((current) => ({
1262
+ ...current,
1263
+ currentSorting: getIndex(
1264
+ ["A", "D", null],
1265
+ [
1266
+ ["A", "Up"].includes(current.currentSorting || ""),
1267
+ ["D", "Down"].includes(current.currentSorting || ""),
1268
+ true
1269
+ ]
1270
+ )
1271
+ }))
1272
+ );
1273
+ const [filters, setFilters] = useState(tasksModal.filters);
1274
+ const [state, setState] = useState(null);
1275
+ const { fetcher } = useFetcher();
1276
+ const filter = useCallback(
1277
+ (newFilters = filters) => {
1278
+ if (newFilters) {
1279
+ fetcher.filter({
1280
+ filters: newFilters,
1281
+ parameters: {
1282
+ txtName: props.initialProps.name,
1283
+ txtTitle: props.initialProps.title,
1284
+ txtDesc: props.initialProps.title,
1285
+ selectOnlyOne: false,
1286
+ txtAdtSql: props.initialProps.adtInfo ?? "",
1287
+ usrToUpdate: ""
1288
+ },
1289
+ path: tasksModal.path,
1290
+ requestConfig: {}
1291
+ }).then((result) => {
1292
+ if (result) {
1293
+ setState(result);
1294
+ }
1295
+ }).catch(console.error);
1296
+ }
1297
+ },
1298
+ [
1299
+ fetcher,
1300
+ filters,
1301
+ props.initialProps.adtInfo,
1302
+ props.initialProps.name,
1303
+ props.initialProps.title
1304
+ ]
1305
+ );
1306
+ useEffect(() => {
1307
+ filter();
1308
+ }, []);
1309
+ useEffect(() => {
1310
+ ApiaTasksModalEmitter.on("deleteFilters", filter);
1311
+ }, [filter]);
1312
+ const handleFilterChange = useCallback(
1313
+ (ev) => {
1314
+ const newFilters = filters?.map((currentFilter) => {
1315
+ if (currentFilter.column === ev.column) {
1316
+ return { ...ev };
1317
+ }
1318
+ return currentFilter;
1319
+ });
1320
+ setFilters(newFilters);
1321
+ if (ev.runAutomatically)
1322
+ filter(newFilters);
1323
+ },
1324
+ [filters, filter]
1325
+ );
1326
+ const handleSort = useCallback(
1327
+ (ev) => {
1328
+ fetcher.sort({
1329
+ sort: ev.columnIndex,
1330
+ parameters: {},
1331
+ path: tasksModal.path,
1332
+ requestConfig: {}
1333
+ }).then((result) => {
1334
+ if (result) {
1335
+ setColumns(
1336
+ (currentColumns) => currentColumns.map((column) => {
1337
+ if (column.name === ev.name)
1338
+ return {
1339
+ ...column,
1340
+ currentSorting: column.currentSorting === "Down" || column.currentSorting === "D" || !column.currentSorting ? "A" : "D"
1341
+ };
1342
+ return { ...column, currentSorting: null };
1343
+ })
1344
+ );
1345
+ setState(result);
1346
+ }
1347
+ }).catch(console.error);
1348
+ },
1349
+ [fetcher]
1350
+ );
1351
+ const handleFilterPressEnter = useCallback(() => filter(), [filter]);
1352
+ const handleFilterBlur = useCallback(() => filter(), [filter]);
1353
+ const handlePageChange = useCallback(
1354
+ (page) => {
1355
+ fetcher.page({
1356
+ page,
1357
+ parameters: {},
1358
+ path: tasksModal.path
1359
+ }).then((result) => {
1360
+ if (result) {
1361
+ setState(result);
1362
+ }
1363
+ }).catch(console.error);
1364
+ },
1365
+ [fetcher]
1366
+ );
1367
+ const handleRefresh = useCallback(() => {
1368
+ fetcher.refresh({
1369
+ parameters: {},
1370
+ path: tasksModal.path
1371
+ }).then((result) => {
1372
+ if (result) {
1373
+ setState(result);
1374
+ }
1375
+ }).catch(console.error);
1376
+ }, [fetcher]);
1377
+ return state?.rows && /* @__PURE__ */ jsxs(
1378
+ ResponsiveTableContext,
1379
+ {
1380
+ columns: actualColumns,
1381
+ rows: state?.rows,
1382
+ filters,
1383
+ name: props.tableName ?? tasksModal.label,
1384
+ variant: "layout.common.modals.table",
1385
+ onFilterChange: handleFilterChange,
1386
+ onSortChange: handleSort,
1387
+ onFilterBlur: handleFilterBlur,
1388
+ onFilterPressEnter: handleFilterPressEnter,
1389
+ isMultiple: true,
1390
+ children: [
1391
+ /* @__PURE__ */ jsx(ResponsiveTable, {}),
1392
+ /* @__PURE__ */ jsx(Box, { className: "pagination__wrapper", children: /* @__PURE__ */ jsx(
1393
+ Pagination,
1394
+ {
1395
+ currentPage: state.currentPage,
1396
+ onPageChange: handlePageChange,
1397
+ onRefresh: handleRefresh,
1398
+ pageCount: state.pageCount,
1399
+ reachedMax: state.reachedMax,
1400
+ recordsCount: state.recordsCount
1401
+ }
1402
+ ) })
1403
+ ]
1404
+ }
1405
+ );
1406
+ };
1407
+
1408
+ const ApiaTasksModalEmitter = new EventEmitter();
1409
+ const ApiaApiTasksModalField = (props) => {
1410
+ const { name } = useFormContext();
1411
+ const [selectedRows, setSelectedRows] = useState(
1412
+ props.element.value.split("#").filter((tsk) => tsk !== "").map((tskData) => {
1413
+ const id2 = tskData.split("_$_")[0];
1414
+ const title = tskData.split("_$_")[1];
1415
+ return {
1416
+ id: id2,
1417
+ title
1418
+ };
1419
+ })
1420
+ );
1421
+ const {
1422
+ isLoading: isFiltersModalLoading,
1423
+ show: showFiltersModal,
1424
+ ...filtersModalProps
1425
+ } = useModal();
1426
+ const id = useId();
1427
+ const deleteFilters = useCallback(() => {
1428
+ const newFilters = tasksModal.filters?.map(
1429
+ (currentFilter) => {
1430
+ return {
1431
+ ...currentFilter,
1432
+ currentValue: "",
1433
+ deleteFiltersTimestamp: Date.now()
1434
+ };
1435
+ }
1436
+ );
1437
+ ApiaTasksModalEmitter.emit("deleteFilters", newFilters);
1438
+ }, []);
1439
+ useEffect(() => {
1440
+ validationsStore.setFieldValue(
1441
+ name,
1442
+ props.element.name,
1443
+ selectedRows.map((e) => e.id).join("#")
1444
+ );
1445
+ }, [name, props.element.name, selectedRows]);
1446
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1447
+ /* @__PURE__ */ jsx(Label, { children: getLabel(props.element.text).text }),
1448
+ /* @__PURE__ */ jsxs(
1449
+ Box,
1450
+ {
1451
+ sx: {
1452
+ display: "flex",
1453
+ flexDirection: "column",
1454
+ gap: spacing(3)
1455
+ },
1456
+ children: [
1457
+ /* @__PURE__ */ jsx(
1458
+ Box,
1459
+ {
1460
+ sx: {
1461
+ maxHeight: "200px",
1462
+ overflow: "auto",
1463
+ width: "100%",
1464
+ display: "flex",
1465
+ flexWrap: "wrap"
1466
+ },
1467
+ children: selectedRows.map((row) => {
1468
+ return /* @__PURE__ */ jsx(
1469
+ LabelBox,
1470
+ {
1471
+ label: row.title,
1472
+ onClose: () => {
1473
+ setSelectedRows((prev) => {
1474
+ return prev.filter((prevRow) => {
1475
+ return prevRow.id !== row.id;
1476
+ });
1477
+ });
1478
+ }
1479
+ },
1480
+ row.id
1481
+ );
1482
+ })
1483
+ }
1484
+ ),
1485
+ /* @__PURE__ */ jsx(
1486
+ SimpleButton,
1487
+ {
1488
+ onClick: () => {
1489
+ ApiaUtil.instance.modals.open({
1490
+ onConfirm: () => {
1491
+ const rows = responsiveTableStore.getState().responsiveTableSlice[id].rows;
1492
+ const selectedIndex = responsiveTableStore.getState().responsiveTableSlice[id].selectedRows;
1493
+ const selectedRows2 = [];
1494
+ selectedIndex.forEach((i) => {
1495
+ if (rows[i]) {
1496
+ selectedRows2.push({
1497
+ id: rows[i].id,
1498
+ title: rows[i].cells[1].children
1499
+ });
1500
+ }
1501
+ });
1502
+ setSelectedRows((prev) => [
1503
+ ...prev,
1504
+ ...selectedRows2.filter((newEnv) => {
1505
+ return !prev.find((prevEnv) => prevEnv.id === newEnv.id);
1506
+ })
1507
+ ]);
1508
+ },
1509
+ confirmProps: { confirmButtonText: getLabel("btnCon").text },
1510
+ children: /* @__PURE__ */ jsx(
1511
+ ApiaTasksModal,
1512
+ {
1513
+ ...filtersModalProps,
1514
+ initialProps: props.element,
1515
+ tableName: id
1516
+ }
1517
+ ),
1518
+ size: "xxl",
1519
+ title: environmentsModal.label,
1520
+ NavBar: /* @__PURE__ */ jsxs(Fragment, { children: [
1521
+ /* @__PURE__ */ jsx(
1522
+ SimpleButton,
1523
+ {
1524
+ variant: "outline-sm",
1525
+ title: window.FILTERS_LABEL,
1526
+ onClick: () => {
1527
+ ApiaUtil.instance.modals.open({
1528
+ children: /* @__PURE__ */ jsx(FiltersModal, { tableName: id }),
1529
+ variant: "layout.common.modals.tableModal.additionalFiltersModal",
1530
+ size: "xl",
1531
+ noHeader: true,
1532
+ initialFocusGetter(modalInnerRef) {
1533
+ return modalInnerRef.querySelector(
1534
+ "select"
1535
+ );
1536
+ }
1537
+ });
1538
+ },
1539
+ isLoading: isFiltersModalLoading,
1540
+ children: window.FILTERS_LABEL
1541
+ }
1542
+ ),
1543
+ /* @__PURE__ */ jsx(
1544
+ SimpleButton,
1545
+ {
1546
+ variant: "outline-sm",
1547
+ onClick: deleteFilters,
1548
+ title: window.BTN_DELETE_FILTERS,
1549
+ children: window.BTN_DELETE_FILTERS
1550
+ }
1551
+ )
1552
+ ] })
1553
+ });
1554
+ },
1555
+ sx: {
1556
+ width: "fit-content !important"
1557
+ },
1558
+ children: getLabel("lblAdd").text
1559
+ }
1560
+ )
1561
+ ]
1562
+ }
1563
+ )
1564
+ ] });
1565
+ };
1566
+
1567
+ const ApiaProcessesModal = (props) => {
1568
+ const [actualColumns, setColumns] = useState(
1569
+ processesModal.columns.map((current) => ({
1570
+ ...current,
1571
+ currentSorting: getIndex(
1572
+ ["A", "D", null],
1573
+ [
1574
+ ["A", "Up"].includes(current.currentSorting || ""),
1575
+ ["D", "Down"].includes(current.currentSorting || ""),
1576
+ true
1577
+ ]
1578
+ )
1579
+ }))
1580
+ );
1581
+ const [filters, setFilters] = useState(processesModal.filters);
1582
+ const [state, setState] = useState(null);
1583
+ const { fetcher } = useFetcher();
1584
+ const filter = useCallback(
1585
+ (newFilters = filters) => {
1586
+ if (newFilters) {
1587
+ fetcher.filter({
1588
+ filters: newFilters,
1589
+ parameters: {
1590
+ txtName: props.initialProps.name,
1591
+ txtTitle: props.initialProps.title,
1592
+ txtDesc: props.initialProps.title,
1593
+ selectOnlyOne: false,
1594
+ showGlobal: false,
1595
+ isScenario: false,
1596
+ showAll: false,
1597
+ txtAdtSql: props.initialProps.adtInfo ?? "",
1598
+ usrToUpdate: ""
1599
+ },
1600
+ path: processesModal.path,
1601
+ requestConfig: {}
1602
+ }).then((result) => {
1603
+ if (result) {
1604
+ setState(result);
1605
+ }
1606
+ }).catch(console.error);
1607
+ }
1608
+ },
1609
+ [
1610
+ fetcher,
1611
+ filters,
1612
+ props.initialProps.adtInfo,
1613
+ props.initialProps.name,
1614
+ props.initialProps.title
1615
+ ]
1616
+ );
1617
+ useEffect(() => {
1618
+ filter();
1619
+ }, []);
1620
+ useEffect(() => {
1621
+ ApiaProcessesModalEmitter.on("deleteFilters", filter);
1622
+ }, [filter]);
1623
+ const handleFilterChange = useCallback(
1624
+ (ev) => {
1625
+ const newFilters = filters?.map((currentFilter) => {
1626
+ if (currentFilter.column === ev.column) {
1627
+ return { ...ev };
1628
+ }
1629
+ return currentFilter;
1630
+ });
1631
+ setFilters(newFilters);
1632
+ if (ev.runAutomatically)
1633
+ filter(newFilters);
1634
+ },
1635
+ [filters, filter]
1636
+ );
1637
+ const handleSort = useCallback(
1638
+ (ev) => {
1639
+ fetcher.sort({
1640
+ sort: ev.columnIndex,
1641
+ parameters: {},
1642
+ path: processesModal.path,
1643
+ requestConfig: {}
1644
+ }).then((result) => {
1645
+ if (result) {
1646
+ setColumns(
1647
+ (currentColumns) => currentColumns.map((column) => {
1648
+ if (column.name === ev.name)
1649
+ return {
1650
+ ...column,
1651
+ currentSorting: column.currentSorting === "Down" || column.currentSorting === "D" || !column.currentSorting ? "A" : "D"
1652
+ };
1653
+ return { ...column, currentSorting: null };
1654
+ })
1655
+ );
1656
+ setState(result);
1657
+ }
1658
+ }).catch(console.error);
1659
+ },
1660
+ [fetcher]
1661
+ );
1662
+ const handleFilterPressEnter = useCallback(() => filter(), [filter]);
1663
+ const handleFilterBlur = useCallback(() => filter(), [filter]);
1664
+ const handlePageChange = useCallback(
1665
+ (page) => {
1666
+ fetcher.page({
1667
+ page,
1668
+ parameters: {},
1669
+ path: processesModal.path
1670
+ }).then((result) => {
1671
+ if (result) {
1672
+ setState(result);
1673
+ }
1674
+ }).catch(console.error);
1675
+ },
1676
+ [fetcher]
1677
+ );
1678
+ const handleRefresh = useCallback(() => {
1679
+ fetcher.refresh({
1680
+ parameters: {},
1681
+ path: processesModal.path
1682
+ }).then((result) => {
1683
+ if (result) {
1684
+ setState(result);
1685
+ }
1686
+ }).catch(console.error);
1687
+ }, [fetcher]);
1688
+ return state?.rows && /* @__PURE__ */ jsxs(
1689
+ ResponsiveTableContext,
1690
+ {
1691
+ columns: actualColumns,
1692
+ rows: state?.rows,
1693
+ filters,
1694
+ name: props.tableName ?? processesModal.label,
1695
+ variant: "layout.common.modals.table",
1696
+ onFilterChange: handleFilterChange,
1697
+ onSortChange: handleSort,
1698
+ onFilterBlur: handleFilterBlur,
1699
+ onFilterPressEnter: handleFilterPressEnter,
1700
+ isMultiple: true,
1701
+ children: [
1702
+ /* @__PURE__ */ jsx(ResponsiveTable, {}),
1703
+ /* @__PURE__ */ jsx(Box, { className: "pagination__wrapper", children: /* @__PURE__ */ jsx(
1704
+ Pagination,
1705
+ {
1706
+ currentPage: state.currentPage,
1707
+ onPageChange: handlePageChange,
1708
+ onRefresh: handleRefresh,
1709
+ pageCount: state.pageCount,
1710
+ reachedMax: state.reachedMax,
1711
+ recordsCount: state.recordsCount
1712
+ }
1713
+ ) })
1714
+ ]
1715
+ }
1716
+ );
1717
+ };
1718
+
1719
+ const ApiaProcessesModalEmitter = new EventEmitter();
1720
+ const ApiaApiProcessesModalField = (props) => {
1721
+ const { name } = useFormContext();
1722
+ const [selectedRows, setSelectedRows] = useState(
1723
+ props.element.value.split("#").filter((env) => env !== "").map((proData) => {
1724
+ const id2 = proData.split("_$_")[0];
1725
+ const title = proData.split("_$_")[1];
1726
+ return {
1727
+ id: id2,
1728
+ title
1729
+ };
1730
+ })
1731
+ );
1732
+ const {
1733
+ isLoading: isFiltersModalLoading,
1734
+ show: showFiltersModal,
1735
+ ...filtersModalProps
1736
+ } = useModal();
1737
+ const id = useId();
1738
+ const deleteFilters = useCallback(() => {
1739
+ const newFilters = processesModal.filters?.map(
1740
+ (currentFilter) => {
1741
+ return {
1742
+ ...currentFilter,
1743
+ currentValue: "",
1744
+ deleteFiltersTimestamp: Date.now()
1745
+ };
1746
+ }
1747
+ );
1748
+ ApiaProcessesModalEmitter.emit("deleteFilters", newFilters);
1749
+ }, []);
1750
+ useEffect(() => {
1751
+ validationsStore.setFieldValue(
1752
+ name,
1753
+ props.element.name,
1754
+ selectedRows.map((e) => e.id).join("#")
1755
+ );
1756
+ }, [name, props.element.name, selectedRows]);
1757
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1758
+ /* @__PURE__ */ jsx(Label, { children: getLabel(props.element.text).text }),
1759
+ /* @__PURE__ */ jsxs(
1760
+ Box,
1761
+ {
1762
+ sx: {
1763
+ display: "flex",
1764
+ flexDirection: "column",
1765
+ gap: spacing(3)
1766
+ },
1767
+ children: [
1768
+ /* @__PURE__ */ jsx(
1769
+ Box,
1770
+ {
1771
+ sx: {
1772
+ maxHeight: "200px",
1773
+ overflow: "auto",
1774
+ width: "100%",
1775
+ display: "flex",
1776
+ flexWrap: "wrap"
1777
+ },
1778
+ children: selectedRows.map((row) => {
1779
+ return /* @__PURE__ */ jsx(
1780
+ LabelBox,
1781
+ {
1782
+ label: row.title,
1783
+ onClose: () => {
1784
+ setSelectedRows((prev) => {
1785
+ return prev.filter((prevRow) => {
1786
+ return prevRow.id !== row.id;
1787
+ });
1788
+ });
1789
+ }
1790
+ },
1791
+ row.id
1792
+ );
1793
+ })
1794
+ }
1795
+ ),
1796
+ /* @__PURE__ */ jsx(
1797
+ SimpleButton,
1798
+ {
1799
+ onClick: () => {
1800
+ ApiaUtil.instance.modals.open({
1801
+ onConfirm: () => {
1802
+ const rows = responsiveTableStore.getState().responsiveTableSlice[id].rows;
1803
+ const selectedIndex = responsiveTableStore.getState().responsiveTableSlice[id].selectedRows;
1804
+ const selectedRows2 = [];
1805
+ selectedIndex.forEach((i) => {
1806
+ if (rows[i]) {
1807
+ selectedRows2.push({
1808
+ id: rows[i].id,
1809
+ title: rows[i].cells[0].children
1810
+ });
1811
+ }
1812
+ });
1813
+ setSelectedRows((prev) => [
1814
+ ...prev,
1815
+ ...selectedRows2.filter((newEnv) => {
1816
+ return !prev.find((prevEnv) => prevEnv.id === newEnv.id);
1817
+ })
1818
+ ]);
1819
+ },
1820
+ confirmProps: { confirmButtonText: getLabel("btnCon").text },
1821
+ children: /* @__PURE__ */ jsx(
1822
+ ApiaProcessesModal,
1823
+ {
1824
+ ...filtersModalProps,
1825
+ initialProps: props.element,
1826
+ tableName: id
1827
+ }
1828
+ ),
1829
+ size: "xxl",
1830
+ title: processesModal.label,
1831
+ NavBar: /* @__PURE__ */ jsxs(Fragment, { children: [
1832
+ /* @__PURE__ */ jsx(
1833
+ SimpleButton,
1834
+ {
1835
+ variant: "outline-sm",
1836
+ title: window.FILTERS_LABEL,
1837
+ onClick: () => {
1838
+ ApiaUtil.instance.modals.open({
1839
+ children: /* @__PURE__ */ jsx(FiltersModal, { tableName: id }),
1840
+ variant: "layout.common.modals.tableModal.additionalFiltersModal",
1841
+ size: "xl",
1842
+ noHeader: true,
1843
+ initialFocusGetter(modalInnerRef) {
1844
+ return modalInnerRef.querySelector(
1845
+ "select"
1846
+ );
1847
+ }
1848
+ });
1849
+ },
1850
+ isLoading: isFiltersModalLoading,
1851
+ children: window.FILTERS_LABEL
1852
+ }
1853
+ ),
1854
+ /* @__PURE__ */ jsx(
1855
+ SimpleButton,
1856
+ {
1857
+ variant: "outline-sm",
1858
+ onClick: deleteFilters,
1859
+ title: window.BTN_DELETE_FILTERS,
1860
+ children: window.BTN_DELETE_FILTERS
1861
+ }
1862
+ )
1863
+ ] })
1864
+ });
1865
+ },
1866
+ sx: {
1867
+ width: "fit-content !important"
1868
+ },
1869
+ children: getLabel("lblAdd").text
1870
+ }
1871
+ )
1872
+ ]
1873
+ }
1874
+ )
1875
+ ] });
1876
+ };
1877
+
1878
+ const ApiaPoolsModal = (props) => {
1879
+ const [actualColumns, setColumns] = useState(
1880
+ poolsModal.columns.map((current) => ({
1881
+ ...current,
1882
+ currentSorting: getIndex(
1883
+ ["A", "D", null],
1884
+ [
1885
+ ["A", "Up"].includes(current.currentSorting || ""),
1886
+ ["D", "Down"].includes(current.currentSorting || ""),
1887
+ true
1888
+ ]
1889
+ )
1890
+ }))
1891
+ );
1892
+ const [filters, setFilters] = useState(poolsModal.filters);
1893
+ const [state, setState] = useState(null);
1894
+ const { fetcher } = useFetcher();
1895
+ const filter = useCallback(
1896
+ (newFilters = filters) => {
1897
+ if (newFilters) {
1898
+ fetcher.filter({
1899
+ filters: newFilters,
1900
+ parameters: {
1901
+ txtName: props.initialProps.name,
1902
+ txtTitle: props.initialProps.title,
1903
+ txtDesc: props.initialProps.title,
1904
+ selectOnlyOne: false,
1905
+ showAutogenerated: false,
1906
+ showNotAutogenerated: false,
1907
+ showCurrentEnv: false,
1908
+ showGlobal: false,
1909
+ fromEnvs: "",
1910
+ exactMatch: "",
1911
+ showOnlyPoolsInHierarchy: false,
1912
+ forHierarchy: false,
1913
+ showOnlyPoolsOutsideHierarchy: false,
1914
+ refreshParameters: false,
1915
+ fetchAllInHierarchy: false,
1916
+ usrToUpdate: ""
1917
+ },
1918
+ path: poolsModal.path,
1919
+ requestConfig: {}
1920
+ }).then((result) => {
1921
+ if (result) {
1922
+ setState(result);
1923
+ }
1924
+ }).catch(console.error);
1925
+ }
1926
+ },
1927
+ [fetcher, filters, props.initialProps.name, props.initialProps.title]
1928
+ );
1929
+ useEffect(() => {
1930
+ filter();
1931
+ }, []);
1932
+ useEffect(() => {
1933
+ ApiaPoolsModalEmitter.on("deleteFilters", filter);
1934
+ }, [filter]);
1935
+ const handleFilterChange = useCallback(
1936
+ (ev) => {
1937
+ const newFilters = filters?.map((currentFilter) => {
1938
+ if (currentFilter.column === ev.column) {
1939
+ return { ...ev };
1940
+ }
1941
+ return currentFilter;
1942
+ });
1943
+ setFilters(newFilters);
1944
+ if (ev.runAutomatically)
1945
+ filter(newFilters);
1946
+ },
1947
+ [filters, filter]
1948
+ );
1949
+ const handleSort = useCallback(
1950
+ (ev) => {
1951
+ fetcher.sort({
1952
+ sort: ev.columnIndex,
1953
+ parameters: {},
1954
+ path: poolsModal.path,
1955
+ requestConfig: {}
1956
+ }).then((result) => {
1957
+ if (result) {
1958
+ setColumns(
1959
+ (currentColumns) => currentColumns.map((column) => {
1960
+ if (column.name === ev.name)
1961
+ return {
1962
+ ...column,
1963
+ currentSorting: column.currentSorting === "Down" || column.currentSorting === "D" || !column.currentSorting ? "A" : "D"
1964
+ };
1965
+ return { ...column, currentSorting: null };
1966
+ })
1967
+ );
1968
+ setState(result);
1969
+ }
1970
+ }).catch(console.error);
1971
+ },
1972
+ [fetcher]
1973
+ );
1974
+ const handleFilterPressEnter = useCallback(() => filter(), [filter]);
1975
+ const handleFilterBlur = useCallback(() => filter(), [filter]);
1976
+ const handlePageChange = useCallback(
1977
+ (page) => {
1978
+ fetcher.page({
1979
+ page,
1980
+ parameters: {},
1981
+ path: poolsModal.path
1982
+ }).then((result) => {
1983
+ if (result) {
1984
+ setState(result);
1985
+ }
1986
+ }).catch(console.error);
1987
+ },
1988
+ [fetcher]
1989
+ );
1990
+ const handleRefresh = useCallback(() => {
1991
+ fetcher.refresh({
1992
+ parameters: {},
1993
+ path: poolsModal.path
1994
+ }).then((result) => {
1995
+ if (result) {
1996
+ setState(result);
1997
+ }
1998
+ }).catch(console.error);
1999
+ }, [fetcher]);
2000
+ return state?.rows && /* @__PURE__ */ jsxs(
2001
+ ResponsiveTableContext,
2002
+ {
2003
+ columns: actualColumns,
2004
+ rows: state?.rows,
2005
+ filters,
2006
+ name: props.tableName ?? poolsModal.label,
2007
+ variant: "layout.common.modals.table",
2008
+ onFilterChange: handleFilterChange,
2009
+ onSortChange: handleSort,
2010
+ onFilterBlur: handleFilterBlur,
2011
+ onFilterPressEnter: handleFilterPressEnter,
2012
+ isMultiple: true,
2013
+ children: [
2014
+ /* @__PURE__ */ jsx(ResponsiveTable, {}),
2015
+ /* @__PURE__ */ jsx(Box, { className: "pagination__wrapper", children: /* @__PURE__ */ jsx(
2016
+ Pagination,
2017
+ {
2018
+ currentPage: state.currentPage,
2019
+ onPageChange: handlePageChange,
2020
+ onRefresh: handleRefresh,
2021
+ pageCount: state.pageCount,
2022
+ reachedMax: state.reachedMax,
2023
+ recordsCount: state.recordsCount
2024
+ }
2025
+ ) })
2026
+ ]
2027
+ }
2028
+ );
2029
+ };
2030
+
2031
+ const ApiaPoolsModalEmitter = new EventEmitter();
2032
+ const ApiaApiPoolsModalField = (props) => {
2033
+ const { name } = useFormContext();
2034
+ const [selectedRows, setSelectedRows] = useState(
2035
+ props.element.value.split("#").filter((env) => env !== "").map((envData) => {
2036
+ const id2 = envData.split("_$_")[0];
2037
+ const title = envData.split("_$_")[1];
2038
+ return {
2039
+ id: id2,
2040
+ title
2041
+ };
2042
+ })
2043
+ );
2044
+ const {
2045
+ isLoading: isFiltersModalLoading,
2046
+ show: showFiltersModal,
2047
+ ...filtersModalProps
2048
+ } = useModal();
2049
+ const id = useId();
2050
+ const deleteFilters = useCallback(() => {
2051
+ const newFilters = poolsModal.filters?.map(
2052
+ (currentFilter) => {
2053
+ return {
2054
+ ...currentFilter,
2055
+ currentValue: "",
2056
+ deleteFiltersTimestamp: Date.now()
2057
+ };
2058
+ }
2059
+ );
2060
+ ApiaPoolsModalEmitter.emit("deleteFilters", newFilters);
2061
+ }, []);
2062
+ useEffect(() => {
2063
+ validationsStore.setFieldValue(
2064
+ name,
2065
+ props.element.name,
2066
+ selectedRows.map((e) => e.id).join("#")
2067
+ );
2068
+ }, [name, props.element.name, selectedRows]);
2069
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2070
+ /* @__PURE__ */ jsx(Label, { children: getLabel(props.element.text).text }),
2071
+ /* @__PURE__ */ jsxs(
2072
+ Box,
2073
+ {
2074
+ sx: {
2075
+ display: "flex",
2076
+ flexDirection: "column",
2077
+ gap: spacing(3)
2078
+ },
2079
+ children: [
2080
+ /* @__PURE__ */ jsx(
2081
+ Box,
2082
+ {
2083
+ sx: {
2084
+ maxHeight: "200px",
2085
+ overflow: "auto",
2086
+ width: "100%",
2087
+ display: "flex",
2088
+ flexWrap: "wrap"
2089
+ },
2090
+ children: selectedRows.map((row) => {
2091
+ return /* @__PURE__ */ jsx(
2092
+ LabelBox,
2093
+ {
2094
+ label: row.title,
2095
+ onClose: () => {
2096
+ setSelectedRows((prev) => {
2097
+ return prev.filter((prevRow) => {
2098
+ return prevRow.id !== row.id;
2099
+ });
2100
+ });
2101
+ }
2102
+ },
2103
+ row.id
2104
+ );
2105
+ })
2106
+ }
2107
+ ),
2108
+ /* @__PURE__ */ jsx(
2109
+ SimpleButton,
2110
+ {
2111
+ onClick: () => {
2112
+ ApiaUtil.instance.modals.open({
2113
+ onConfirm: () => {
2114
+ const rows = responsiveTableStore.getState().responsiveTableSlice[id].rows;
2115
+ const selectedIndex = responsiveTableStore.getState().responsiveTableSlice[id].selectedRows;
2116
+ const selectedRows2 = [];
2117
+ selectedIndex.forEach((i) => {
2118
+ if (rows[i]) {
2119
+ selectedRows2.push({
2120
+ id: rows[i].id,
2121
+ title: rows[i].cells[0].children
2122
+ });
2123
+ }
2124
+ });
2125
+ setSelectedRows((prev) => [
2126
+ ...prev,
2127
+ ...selectedRows2.filter((newEnv) => {
2128
+ return !prev.find((prevEnv) => prevEnv.id === newEnv.id);
2129
+ })
2130
+ ]);
2131
+ },
2132
+ confirmProps: { confirmButtonText: getLabel("btnCon").text },
2133
+ children: /* @__PURE__ */ jsx(
2134
+ ApiaPoolsModal,
2135
+ {
2136
+ ...filtersModalProps,
2137
+ initialProps: props.element,
2138
+ tableName: id
2139
+ }
2140
+ ),
2141
+ size: "xxl",
2142
+ title: poolsModal.label,
2143
+ NavBar: /* @__PURE__ */ jsxs(Fragment, { children: [
2144
+ /* @__PURE__ */ jsx(
2145
+ SimpleButton,
2146
+ {
2147
+ variant: "outline-sm",
2148
+ title: window.FILTERS_LABEL,
2149
+ onClick: () => {
2150
+ ApiaUtil.instance.modals.open({
2151
+ children: /* @__PURE__ */ jsx(FiltersModal, { tableName: id }),
2152
+ variant: "layout.common.modals.tableModal.additionalFiltersModal",
2153
+ size: "xl",
2154
+ noHeader: true,
2155
+ initialFocusGetter(modalInnerRef) {
2156
+ return modalInnerRef.querySelector(
2157
+ "select"
2158
+ );
2159
+ }
2160
+ });
2161
+ },
2162
+ isLoading: isFiltersModalLoading,
2163
+ children: window.FILTERS_LABEL
2164
+ }
2165
+ ),
2166
+ /* @__PURE__ */ jsx(
2167
+ SimpleButton,
2168
+ {
2169
+ variant: "outline-sm",
2170
+ onClick: deleteFilters,
2171
+ title: window.BTN_DELETE_FILTERS,
2172
+ children: window.BTN_DELETE_FILTERS
2173
+ }
2174
+ )
2175
+ ] })
2176
+ });
2177
+ },
2178
+ sx: {
2179
+ width: "fit-content !important"
2180
+ },
2181
+ children: getLabel("lblAdd").text
2182
+ }
2183
+ )
2184
+ ]
2185
+ }
2186
+ )
2187
+ ] });
2188
+ };
2189
+
2190
+ const ApiaUsersModal = (props) => {
2191
+ const [actualColumns, setColumns] = useState(
2192
+ usersModal.columns.map((current) => ({
2193
+ ...current,
2194
+ currentSorting: getIndex(
2195
+ ["A", "D", null],
2196
+ [
2197
+ ["A", "Up"].includes(current.currentSorting || ""),
2198
+ ["D", "Down"].includes(current.currentSorting || ""),
2199
+ true
2200
+ ]
2201
+ )
2202
+ }))
2203
+ );
2204
+ const [filters, setFilters] = useState(usersModal.filters);
2205
+ const [state, setState] = useState(null);
2206
+ const { fetcher } = useFetcher();
2207
+ const filter = useCallback(
2208
+ (newFilters = filters) => {
2209
+ if (newFilters) {
2210
+ fetcher.filter({
2211
+ filters: newFilters,
2212
+ parameters: {
2213
+ txtName: props.initialProps.name,
2214
+ txtLogin: props.initialProps.title,
2215
+ txtDesc: props.initialProps.title,
2216
+ externalUser: false,
2217
+ selectOnlyOne: false,
2218
+ globalAndEnv: true,
2219
+ hierarchy: false,
2220
+ forOrgUnit: false,
2221
+ forCurrentEnv: false
2222
+ },
2223
+ path: usersModal.path,
2224
+ requestConfig: {}
2225
+ }).then((result) => {
2226
+ if (result) {
2227
+ setState(result);
2228
+ }
2229
+ }).catch(console.error);
2230
+ }
2231
+ },
2232
+ [fetcher, filters, props.initialProps.name, props.initialProps.title]
2233
+ );
2234
+ useEffect(() => {
2235
+ filter();
2236
+ }, []);
2237
+ useEffect(() => {
2238
+ ApiaUsersModalEmitter.on("deleteFilters", filter);
2239
+ }, [filter]);
2240
+ const handleFilterChange = useCallback(
2241
+ (ev) => {
2242
+ const newFilters = filters?.map((currentFilter) => {
2243
+ if (currentFilter.column === ev.column) {
2244
+ return { ...ev };
2245
+ }
2246
+ return currentFilter;
2247
+ });
2248
+ setFilters(newFilters);
2249
+ if (ev.runAutomatically)
2250
+ filter(newFilters);
2251
+ },
2252
+ [filters, filter]
2253
+ );
2254
+ const handleSort = useCallback(
2255
+ (ev) => {
2256
+ fetcher.sort({
2257
+ sort: ev.columnIndex,
2258
+ parameters: {},
2259
+ path: usersModal.path,
2260
+ requestConfig: {}
2261
+ }).then((result) => {
2262
+ if (result) {
2263
+ setColumns(
2264
+ (currentColumns) => currentColumns.map((column) => {
2265
+ if (column.name === ev.name)
2266
+ return {
2267
+ ...column,
2268
+ currentSorting: column.currentSorting === "Down" || column.currentSorting === "D" || !column.currentSorting ? "A" : "D"
2269
+ };
2270
+ return { ...column, currentSorting: null };
2271
+ })
2272
+ );
2273
+ setState(result);
2274
+ }
2275
+ }).catch(console.error);
2276
+ },
2277
+ [fetcher]
2278
+ );
2279
+ const handleFilterPressEnter = useCallback(() => filter(), [filter]);
2280
+ const handleFilterBlur = useCallback(() => filter(), [filter]);
2281
+ const handlePageChange = useCallback(
2282
+ (page) => {
2283
+ fetcher.page({
2284
+ page,
2285
+ parameters: {},
2286
+ path: usersModal.path
2287
+ }).then((result) => {
2288
+ if (result) {
2289
+ setState(result);
2290
+ }
2291
+ }).catch(console.error);
2292
+ },
2293
+ [fetcher]
2294
+ );
2295
+ const handleRefresh = useCallback(() => {
2296
+ fetcher.refresh({
2297
+ parameters: {},
2298
+ path: usersModal.path
2299
+ }).then((result) => {
2300
+ if (result) {
2301
+ setState(result);
2302
+ }
2303
+ }).catch(console.error);
2304
+ }, [fetcher]);
2305
+ return state?.rows && /* @__PURE__ */ jsxs(
2306
+ ResponsiveTableContext,
2307
+ {
2308
+ columns: actualColumns,
2309
+ rows: state?.rows,
2310
+ filters,
2311
+ name: props.tableName ?? usersModal.label,
2312
+ variant: "layout.common.modals.table",
2313
+ onFilterChange: handleFilterChange,
2314
+ onSortChange: handleSort,
2315
+ onFilterBlur: handleFilterBlur,
2316
+ onFilterPressEnter: handleFilterPressEnter,
2317
+ isMultiple: true,
2318
+ children: [
2319
+ /* @__PURE__ */ jsx(ResponsiveTable, {}),
2320
+ /* @__PURE__ */ jsx(Box, { className: "pagination__wrapper", children: /* @__PURE__ */ jsx(
2321
+ Pagination,
2322
+ {
2323
+ currentPage: state.currentPage,
2324
+ onPageChange: handlePageChange,
2325
+ onRefresh: handleRefresh,
2326
+ pageCount: state.pageCount,
2327
+ reachedMax: state.reachedMax,
2328
+ recordsCount: state.recordsCount
2329
+ }
2330
+ ) })
2331
+ ]
2332
+ }
2333
+ );
2334
+ };
2335
+
2336
+ const ApiaUsersModalEmitter = new EventEmitter();
2337
+ const ApiaApiUsersModalField = (props) => {
2338
+ const { name } = useFormContext();
2339
+ const [selectedRows, setSelectedRows] = useState(
2340
+ props.element.value.split("#").filter((env) => env !== "").map((envData) => {
2341
+ const id2 = envData;
2342
+ return {
2343
+ id: id2
2344
+ };
2345
+ })
2346
+ );
2347
+ const {
2348
+ isLoading: isFiltersModalLoading,
2349
+ show: showFiltersModal,
2350
+ ...filtersModalProps
2351
+ } = useModal();
2352
+ const id = useId();
2353
+ const deleteFilters = useCallback(() => {
2354
+ const newFilters = usersModal.filters?.map(
2355
+ (currentFilter) => {
2356
+ return {
2357
+ ...currentFilter,
2358
+ currentValue: "",
2359
+ deleteFiltersTimestamp: Date.now()
2360
+ };
2361
+ }
2362
+ );
2363
+ ApiaUsersModalEmitter.emit("deleteFilters", newFilters);
2364
+ }, []);
2365
+ useEffect(() => {
2366
+ validationsStore.setFieldValue(
2367
+ name,
2368
+ props.element.name,
2369
+ selectedRows.map((e) => e.id).join("#")
2370
+ );
2371
+ }, [name, props.element.name, selectedRows]);
2372
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2373
+ /* @__PURE__ */ jsx(Label, { children: getLabel(props.element.text).text }),
2374
+ /* @__PURE__ */ jsxs(
2375
+ Box,
2376
+ {
2377
+ sx: {
2378
+ display: "flex",
2379
+ flexDirection: "column",
2380
+ gap: spacing(3)
2381
+ },
2382
+ children: [
2383
+ /* @__PURE__ */ jsx(
2384
+ Box,
2385
+ {
2386
+ sx: {
2387
+ maxHeight: "200px",
2388
+ overflow: "auto",
2389
+ width: "100%",
2390
+ display: "flex",
2391
+ flexWrap: "wrap"
2392
+ },
2393
+ children: selectedRows.map((row) => {
2394
+ return /* @__PURE__ */ jsx(
2395
+ LabelBox,
2396
+ {
2397
+ label: row.id,
2398
+ onClose: () => {
2399
+ setSelectedRows((prev) => {
2400
+ return prev.filter((prevRow) => {
2401
+ return prevRow.id !== row.id;
2402
+ });
2403
+ });
2404
+ }
2405
+ },
2406
+ row.id
2407
+ );
2408
+ })
2409
+ }
2410
+ ),
2411
+ /* @__PURE__ */ jsx(
2412
+ SimpleButton,
2413
+ {
2414
+ onClick: () => {
2415
+ ApiaUtil.instance.modals.open({
2416
+ onConfirm: () => {
2417
+ const rows = responsiveTableStore.getState().responsiveTableSlice[id].rows;
2418
+ const selectedIndex = responsiveTableStore.getState().responsiveTableSlice[id].selectedRows;
2419
+ const selectedRows2 = [];
2420
+ selectedIndex.forEach((i) => {
2421
+ if (rows[i]) {
2422
+ selectedRows2.push({
2423
+ id: rows[i].id
2424
+ });
2425
+ }
2426
+ });
2427
+ setSelectedRows((prev) => [
2428
+ ...prev,
2429
+ ...selectedRows2.filter((newEnv) => {
2430
+ return !prev.find((prevEnv) => prevEnv.id === newEnv.id);
2431
+ })
2432
+ ]);
2433
+ },
2434
+ // TODO LABEL
2435
+ confirmProps: { confirmButtonText: getLabel("btnCon").text },
2436
+ children: /* @__PURE__ */ jsx(
2437
+ ApiaUsersModal,
2438
+ {
2439
+ ...filtersModalProps,
2440
+ initialProps: props.element,
2441
+ tableName: id
2442
+ }
2443
+ ),
2444
+ size: "xxl",
2445
+ title: usersModal.label,
2446
+ NavBar: /* @__PURE__ */ jsxs(Fragment, { children: [
2447
+ /* @__PURE__ */ jsx(
2448
+ SimpleButton,
2449
+ {
2450
+ variant: "outline-sm",
2451
+ title: window.FILTERS_LABEL,
2452
+ onClick: () => {
2453
+ ApiaUtil.instance.modals.open({
2454
+ children: /* @__PURE__ */ jsx(FiltersModal, { tableName: id }),
2455
+ variant: "layout.common.modals.tableModal.additionalFiltersModal",
2456
+ size: "xl",
2457
+ noHeader: true,
2458
+ initialFocusGetter(modalInnerRef) {
2459
+ return modalInnerRef.querySelector(
2460
+ "select"
2461
+ );
2462
+ }
2463
+ });
2464
+ },
2465
+ isLoading: isFiltersModalLoading,
2466
+ children: window.FILTERS_LABEL
2467
+ }
2468
+ ),
2469
+ /* @__PURE__ */ jsx(
2470
+ SimpleButton,
2471
+ {
2472
+ variant: "outline-sm",
2473
+ onClick: deleteFilters,
2474
+ title: window.BTN_DELETE_FILTERS,
2475
+ children: window.BTN_DELETE_FILTERS
2476
+ }
2477
+ )
2478
+ ] })
2479
+ });
2480
+ },
2481
+ sx: {
2482
+ width: "fit-content !important"
2483
+ },
2484
+ children: getLabel("lblAdd").text
2485
+ }
2486
+ )
2487
+ ]
2488
+ }
2489
+ )
2490
+ ] });
2491
+ };
2492
+
2493
+ const parseApiaApiSections = (elements) => {
2494
+ const removeEndingSpacers = (sectionElements) => {
2495
+ if (sectionElements.length > 1) {
2496
+ for (let i = sectionElements.length - 1; i >= 0; i--) {
2497
+ if (sectionElements[i].type === "empty") {
2498
+ sectionElements.pop();
2499
+ } else {
2500
+ return sectionElements;
2501
+ }
2502
+ }
2503
+ }
2504
+ return sectionElements;
2505
+ };
2506
+ const sectionIndexes = [];
2507
+ if (elements[0]?.type !== "2columnTitle") {
2508
+ sectionIndexes.push(-1);
2509
+ }
2510
+ elements.forEach((element, index) => {
2511
+ if (element.type === "2columnTitle") {
2512
+ sectionIndexes.push(index);
2513
+ }
2514
+ });
2515
+ const sections = [];
2516
+ sectionIndexes.forEach((sectionIndex, arrayIndex) => {
2517
+ const start = sectionIndex + 1 < elements.length ? sectionIndex + 1 : elements.length - 1;
2518
+ const end = arrayIndex + 1 < sectionIndexes.length ? sectionIndexes[arrayIndex + 1] : void 0;
2519
+ sections.push({
2520
+ sectionId: `ApiaApiSection_${arrayIndex}`,
2521
+ sectionHeader: sectionIndex !== -1 ? {
2522
+ ...elements[sectionIndex],
2523
+ sectionElementId: `sectionHeader_${arrayIndex}`
2524
+ } : void 0,
2525
+ sectionElements: removeEndingSpacers(elements.slice(start, end)).map(
2526
+ (currentElement) => ({
2527
+ ...currentElement,
2528
+ sectionElementId: `sectionElement_${currentElement.id || currentElement.name || uniqueId()}`
2529
+ })
2530
+ )
2531
+ });
2532
+ });
2533
+ return sections;
2534
+ };
2535
+ const NonMemoizedApiaApiFieldsContainer = (props) => {
2536
+ const elements = React__default.useMemo(
2537
+ () => arrayOrArray(props?.definition?.form.elements?.element ?? []),
2538
+ [props?.definition?.form.elements?.element]
2539
+ );
2540
+ const sections = React__default.useMemo(
2541
+ () => parseApiaApiSections(elements),
2542
+ [elements]
2543
+ );
2544
+ const renderSectionContent = React__default.useCallback(
2545
+ (sectionId, sectionElements) => {
2546
+ const isVisible = sectionElements.findIndex((element) => element.type !== "hidden") !== -1;
2547
+ return /* @__PURE__ */ jsx(
2548
+ Box,
2549
+ {
2550
+ className: isVisible ? "handler__form__elements__section__content" : `handler__form__elements__section__content handler__hidden`,
2551
+ children: sectionElements.map((current) => {
2552
+ const element = {
2553
+ ...current,
2554
+ onChange() {
2555
+ getFunction(current.onChange, props).then((onChangeMethod) => {
2556
+ if (onChangeMethod) {
2557
+ onChangeMethod();
2558
+ }
2559
+ }).catch(console.error);
2560
+ }
2561
+ };
2562
+ switch (element.type) {
2563
+ case "table": {
2564
+ const data = JSON.parse(element.text);
2565
+ return /* @__PURE__ */ jsx(
2566
+ Box,
2567
+ {
2568
+ ...getVariant("layout.common.tables.information"),
2569
+ children: /* @__PURE__ */ jsxs("table", { sx: { width: "100%" }, children: [
2570
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: data.columns.map((column) => {
2571
+ return /* @__PURE__ */ jsx("th", { children: column }, column);
2572
+ }) }) }),
2573
+ /* @__PURE__ */ jsx("tbody", { children: data.rows.map((row) => {
2574
+ return /* @__PURE__ */ jsx("tr", { children: row.cells.map((cell, i) => {
2575
+ return /* @__PURE__ */ jsx("td", { children: cell }, `${cell}_${data.columns[i]}`);
2576
+ }) }, row.cells.join("-"));
2577
+ }) })
2578
+ ] })
2579
+ },
2580
+ element.sectionElementId
2581
+ );
2582
+ }
2583
+ case "2columnSubTitle":
2584
+ return /* @__PURE__ */ jsx(
2585
+ Box,
2586
+ {
2587
+ className: element.class,
2588
+ as: "h6",
2589
+ children: element.value || element.text
2590
+ },
2591
+ element.sectionElementId
2592
+ );
2593
+ case "2column":
2594
+ return /* @__PURE__ */ jsx(
2595
+ Box,
2596
+ {
2597
+ dangerouslySetInnerHTML: {
2598
+ __html: element.value || element.text
2599
+ },
2600
+ className: element.class
2601
+ },
2602
+ element.sectionElementId
2603
+ );
2604
+ case "checkbox":
2605
+ return /* @__PURE__ */ jsx(
2606
+ ApiaApiCheckbox,
2607
+ {
2608
+ ...props,
2609
+ element
2610
+ },
2611
+ element.sectionElementId
2612
+ );
2613
+ case "file":
2614
+ return /* @__PURE__ */ jsx(
2615
+ ApiaApiFileInput,
2616
+ {
2617
+ ...props,
2618
+ element
2619
+ },
2620
+ element.sectionElementId
2621
+ );
2622
+ case "hidden":
2623
+ case "password":
2624
+ case "text":
2625
+ return /* @__PURE__ */ jsx(
2626
+ ApiaApiInput,
2627
+ {
2628
+ ...props,
2629
+ element
2630
+ },
2631
+ element.sectionElementId
2632
+ );
2633
+ case "select":
2634
+ return /* @__PURE__ */ jsx(
2635
+ ApiaApiSelect,
2636
+ {
2637
+ ...props,
2638
+ element
2639
+ },
2640
+ element.sectionElementId
2641
+ );
2642
+ case "radio":
2643
+ return /* @__PURE__ */ jsx(
2644
+ ApiaApiRadio,
2645
+ {
2646
+ ...props,
2647
+ element
2648
+ },
2649
+ element.sectionElementId
2650
+ );
2651
+ case "textarea":
2652
+ return /* @__PURE__ */ jsx(
2653
+ ApiaApiTextArea,
2654
+ {
2655
+ ...props,
2656
+ element
2657
+ },
2658
+ element.sectionElementId
2659
+ );
2660
+ case "empty":
2661
+ return /* @__PURE__ */ jsx(Box, { className: "spacer" }, element.sectionElementId);
2662
+ case "envsModal":
2663
+ return /* @__PURE__ */ jsx(
2664
+ ApiaApiEnvironmentsModalField,
2665
+ {
2666
+ ...props,
2667
+ element
2668
+ },
2669
+ element.sectionElementId
2670
+ );
2671
+ case "tsksModal":
2672
+ return /* @__PURE__ */ jsx(
2673
+ ApiaApiTasksModalField,
2674
+ {
2675
+ ...props,
2676
+ element
2677
+ },
2678
+ element.sectionElementId
2679
+ );
2680
+ case "procModal":
2681
+ return /* @__PURE__ */ jsx(
2682
+ ApiaApiProcessesModalField,
2683
+ {
2684
+ ...props,
2685
+ element
2686
+ },
2687
+ element.sectionElementId
2688
+ );
2689
+ case "poolModal":
2690
+ return /* @__PURE__ */ jsx(
2691
+ ApiaApiPoolsModalField,
2692
+ {
2693
+ ...props,
2694
+ element
2695
+ },
2696
+ element.sectionElementId
2697
+ );
2698
+ case "userModal":
2699
+ return /* @__PURE__ */ jsx(
2700
+ ApiaApiUsersModalField,
2701
+ {
2702
+ ...props,
2703
+ element
2704
+ },
2705
+ element.sectionElementId
2706
+ );
2707
+ default:
2708
+ console.warn(
2709
+ `Unhandled element type: ${element.type}`,
2710
+ element
2711
+ );
2712
+ return null;
2713
+ }
2714
+ })
2715
+ },
2716
+ sectionId
2717
+ );
2718
+ },
2719
+ [props]
2720
+ );
2721
+ return /* @__PURE__ */ jsx(Box, { className: "handler__form__elements", children: sections.map((section) => {
2722
+ if (section.sectionHeader) {
2723
+ return renderSectionContent(
2724
+ section.sectionId,
2725
+ section.sectionElements
2726
+ );
2727
+ }
2728
+ return renderSectionContent(section.sectionId, section.sectionElements);
2729
+ }) });
2730
+ };
2731
+ const ApiaApiFieldsContainer = React__default.memo(
2732
+ NonMemoizedApiaApiFieldsContainer
2733
+ );
2734
+ ApiaApiFieldsContainer.displayName = "ApiaApiFieldsContainer";
2735
+
2736
+ const parseButtons = (buttons) => {
2737
+ return buttons.map((currentButton) => ({
2738
+ ...currentButton,
2739
+ buttonKey: uniqueId(),
2740
+ type: ["submitAjax", "submit"].includes(currentButton.type) ? "submit" : "button"
2741
+ }));
2742
+ };
2743
+ const NonMemoizedApiaApiButtonsContainer = (props) => {
2744
+ const buttonElements = React__default.useMemo(
2745
+ () => arrayOrArray(props.definition?.form.buttons?.button ?? []),
2746
+ [props.definition?.form.buttons?.button]
2747
+ );
2748
+ const buttons = React__default.useMemo(
2749
+ () => parseButtons(buttonElements),
2750
+ [buttonElements]
2751
+ );
2752
+ const modalConfiguration = React__default.useMemo(
2753
+ () => props.configuration?.modalConfiguration,
2754
+ [props.configuration?.modalConfiguration]
2755
+ );
2756
+ const methodsPath = React__default.useMemo(
2757
+ () => props.configuration?.methodsPath,
2758
+ [props.configuration?.methodsPath]
2759
+ );
2760
+ const { name: apiaApiForm } = useFormContext();
2761
+ const renderButton = React__default.useCallback(
2762
+ (currentButton) => {
2763
+ const key = currentButton.buttonKey;
2764
+ const className = `handler__${currentButton.type ?? ""}`;
2765
+ const onClick = () => {
2766
+ void async function submitForm() {
2767
+ const validationResult = await validationsStore.validateForm(apiaApiForm);
2768
+ if (!hasSucceedFormValidation(validationResult)) {
2769
+ return;
2770
+ }
2771
+ const { submitValues } = validationResult;
2772
+ function runButtonMethod() {
2773
+ void (async () => {
2774
+ if (currentButton.onclick) {
2775
+ const actions = currentButton.onclick.split(";");
2776
+ for await (const action of actions) {
2777
+ const method = await getFunction(action, {
2778
+ ...props
2779
+ });
2780
+ if (method) {
2781
+ method({
2782
+ currentUrl: props.definition?.form.action ?? "noUrl"
2783
+ });
2784
+ } else {
2785
+ throw new Error(
2786
+ `The requested action is not defined: "${props.definition?.form.action ?? ""}"`
2787
+ );
2788
+ }
2789
+ }
2790
+ }
2791
+ })();
2792
+ }
2793
+ if (props?.definition && currentButton.type === "submit") {
2794
+ const formData = new FormData();
2795
+ Object.entries(submitValues).forEach(([name, value]) => {
2796
+ formData.append(name, value ?? "");
2797
+ });
2798
+ const hasContext = props?.definition.form.action.match(
2799
+ new RegExp(`^${window.CONTEXT}/`)
2800
+ );
2801
+ const url = `${hasContext ? "" : window.CONTEXT}${!props?.definition.form.action.startsWith("/") ? "/" : ""}${props?.definition.form.action}`;
2802
+ props.setState((current) => ({
2803
+ ...current,
2804
+ isLoading: true
2805
+ }));
2806
+ void ApiaApi$1.post(url, {
2807
+ postData: props.state.isMultipart ? formData : QueryString.stringify(
2808
+ [...formData.entries(), ["isAjax", true]].reduce((accumulated, [name, value]) => {
2809
+ const retValue = { ...accumulated };
2810
+ retValue[name.toString()] = value.toString();
2811
+ return retValue;
2812
+ }, {})
2813
+ ),
2814
+ handleLoad: true,
2815
+ notificationsCategory: "apiaApiHandler",
2816
+ modalConfiguration,
2817
+ methodsPath
2818
+ }).finally(() => {
2819
+ runButtonMethod();
2820
+ if (props?.definition?.form.closeOnSubmit) {
2821
+ props.close();
2822
+ }
2823
+ });
2824
+ } else {
2825
+ runButtonMethod();
2826
+ }
2827
+ }();
2828
+ };
2829
+ return /* @__PURE__ */ jsx(
2830
+ SimpleButton,
2831
+ {
2832
+ className,
2833
+ disabled: props.state.disabled,
2834
+ id: currentButton.id || currentButton.text,
2835
+ isLoading: props.state.isLoading,
2836
+ title: currentButton.text,
2837
+ type: currentButton.type,
2838
+ onClick,
2839
+ children: currentButton.text
2840
+ },
2841
+ key
2842
+ );
2843
+ },
2844
+ [apiaApiForm, methodsPath, modalConfiguration, props]
2845
+ );
2846
+ return buttons.length > 0 && /* @__PURE__ */ jsx(Box, { className: "handler__form__buttons", children: buttons.map((currentButton) => renderButton(currentButton)) });
2847
+ };
2848
+ const ApiaApiButtonsContainer = React__default.memo(
2849
+ NonMemoizedApiaApiButtonsContainer
2850
+ );
2851
+
2852
+ const ApiaApiMessenger = new class extends EventEmitter {
2853
+ }();
2854
+ const FunctionsDispatcher = new class extends EventEmitter {
2855
+ }();
2856
+ const apiaApiForm = "ApiaApiForm";
2857
+ const methods = {};
2858
+ async function getFunction(name, handler) {
2859
+ return new Promise((resolve) => {
2860
+ try {
2861
+ const separateNameFromParametersRegex = /^\/?([\w\d_-]+)\/?(?:\(([^)]*)\))?$/;
2862
+ const match = name.match(separateNameFromParametersRegex);
2863
+ if (match) {
2864
+ const functionName = match[1];
2865
+ const parameters = match[2];
2866
+ const path = [
2867
+ ...handler.configuration?.methodsPath?.split("/").filter((current) => !!current) ?? [],
2868
+ functionName
2869
+ ].join("/");
2870
+ const storeMethodAndResolve = (result) => {
2871
+ if (typeof result.default.default !== "function")
2872
+ notFound();
2873
+ const method = result.default.default;
2874
+ methods[functionName] = (props) => {
2875
+ return method(handler, {
2876
+ ...props,
2877
+ inlineArguments: parameters?.split(",").map((argument) => {
2878
+ if (argument.startsWith("'") || argument.startsWith('"'))
2879
+ return argument.slice(1, argument.length - 1);
2880
+ return argument;
2881
+ }) ?? []
2882
+ });
2883
+ };
2884
+ resolve(methods[functionName]);
2885
+ };
2886
+ const notFound = () => {
2887
+ throw new Error(
2888
+ `${functionName}.ts not found at ${path}.ts nor ./${functionName}.ts`
2889
+ );
2890
+ };
2891
+ import(
2892
+ /* webpackChunkName: "api-methods-[request]" */
2893
+ `/api/methods/${path}.ts`
2894
+ ).then(storeMethodAndResolve).catch(() => {
2895
+ if (handler.configuration?.methodsPath !== void 0)
2896
+ import(
2897
+ /* webpackChunkName: "api-methods-[request]" */
2898
+ `/api/methods/${functionName}.ts`
2899
+ ).then(storeMethodAndResolve).catch(notFound);
2900
+ else {
2901
+ notFound();
2902
+ }
2903
+ });
2904
+ }
2905
+ } catch (e) {
2906
+ console.error(e);
2907
+ handler.reset();
2908
+ handler.setError({
2909
+ type: "danger",
2910
+ message: "Error while loading current method."
2911
+ });
2912
+ }
2913
+ });
2914
+ }
2915
+ function isForm(responseObject) {
2916
+ return responseObject.form !== void 0 && typeof responseObject.form === "object" && !!responseObject.form;
2917
+ }
2918
+ function isFunction(responseObject) {
2919
+ return typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && !!responseObject.function;
2920
+ }
2921
+ function isMessage(responseObject) {
2922
+ if (typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && typeof responseObject.text === "object" && responseObject.text && typeof responseObject.text.label === "string") {
2923
+ return true;
2924
+ }
2925
+ return false;
2926
+ }
2927
+ const modalConfigurationHandler = new StatefulEmitter();
2928
+ function useModalConfiguration() {
2929
+ const value = modalConfigurationHandler.useState("value");
2930
+ const latestValue = useLatest(value);
2931
+ return latestValue;
2932
+ }
2933
+ const currentFormDispatcher = new class currentFormDispatcher2 extends EventEmitter {
2934
+ emit(eventName, params) {
2935
+ super.emit(eventName, params);
2936
+ }
2937
+ }();
2938
+ function handle(responseObject, currentUrl, configuration) {
2939
+ modalConfigurationHandler.setState("value", configuration);
2940
+ if (isForm(responseObject)) {
2941
+ currentFormDispatcher.emit("form", responseObject);
2942
+ return true;
2943
+ }
2944
+ if (isFunction(responseObject)) {
2945
+ FunctionsDispatcher.emit("method", {
2946
+ name: responseObject.function.name,
2947
+ props: {
2948
+ messages: responseObject.function.messages,
2949
+ attributes: responseObject.function,
2950
+ currentUrl
2951
+ }
2952
+ });
2953
+ return true;
2954
+ }
2955
+ if (isMessage(responseObject)) {
2956
+ ApiaApiMessenger.emit("message", {
2957
+ predicate: responseObject.text.content,
2958
+ title: responseObject.text.title
2959
+ });
2960
+ return true;
2961
+ }
2962
+ return false;
2963
+ }
2964
+ const initialState = {
2965
+ disabled: false,
2966
+ isLoading: false,
2967
+ isMultipart: false,
2968
+ progress: 0,
2969
+ errors: {}
2970
+ };
2971
+ const ApiaApiHandlerNonMemoized = () => {
2972
+ const configuration = useModalConfiguration();
2973
+ const [state, setState] = React.useState({
2974
+ ...initialState,
2975
+ windowIndex: -1
2976
+ });
2977
+ const [currentForm2, setCurrentForm] = React.useState(
2978
+ void 0
2979
+ );
2980
+ React.useEffect(() => {
2981
+ return currentFormDispatcher.on("form", setCurrentForm);
2982
+ }, []);
2983
+ const setValue = React.useCallback((name, value) => {
2984
+ return validationsStore.setFieldValue(apiaApiForm, name, value);
2985
+ }, []);
2986
+ React.useEffect(() => {
2987
+ if (!currentForm2)
2988
+ return;
2989
+ const elements = arrayOrArray(currentForm2?.form?.elements?.element ?? []);
2990
+ let isMultipart = false;
2991
+ const elementsValues = Object.values(elements);
2992
+ let i = 0;
2993
+ while (i < elementsValues.length && !isMultipart) {
2994
+ if (elementsValues[i++].type === "file") {
2995
+ isMultipart = true;
2996
+ }
2997
+ }
2998
+ setState((currentState) => {
2999
+ return {
3000
+ ...currentState,
3001
+ ...initialState,
3002
+ isMultipart
3003
+ };
3004
+ });
3005
+ }, [currentForm2]);
3006
+ const { show, onClose, ...modalHookProps } = useModal();
3007
+ const close = React.useCallback(() => {
3008
+ onClose();
3009
+ currentFormDispatcher.emit("form", void 0);
3010
+ setState((currentState) => {
3011
+ return { ...currentState, ...initialState };
3012
+ });
3013
+ configuration.current?.modalConfiguration?.onClose?.();
3014
+ validationsStore.unregisterForm(apiaApiForm);
3015
+ }, [onClose, configuration]);
3016
+ const modalRef = React.useRef(null);
3017
+ React.useEffect(() => {
3018
+ const elements = modalRef.current?.querySelectorAll(
3019
+ "a,input,textarea,button"
3020
+ );
3021
+ if (elements?.length === 1)
3022
+ void focus.on([...elements][0]);
3023
+ });
3024
+ const setError = React.useCallback(
3025
+ (notification) => {
3026
+ notify({ ...notification });
3027
+ },
3028
+ []
3029
+ );
3030
+ const initialFocusGetter = React.useCallback((ref) => {
3031
+ return ref?.querySelector(focusSelector);
3032
+ }, []);
3033
+ const defaultModalProps = React.useMemo(
3034
+ () => ({
3035
+ onClose: close,
3036
+ id: apiaApiForm,
3037
+ title: configuration.current?.modalConfiguration?.modalTitle ?? currentForm2?.form.title,
3038
+ size: "md-fixed",
3039
+ shouldCloseOnEsc: !state.disabled,
3040
+ shouldCloseOnOverlayClick: !state.disabled,
3041
+ initialFocusGetter
3042
+ }),
3043
+ [
3044
+ close,
3045
+ configuration,
3046
+ currentForm2?.form.title,
3047
+ initialFocusGetter,
3048
+ state.disabled
3049
+ ]
3050
+ );
3051
+ const getModalProps = React.useCallback(
3052
+ (innerHandler) => {
3053
+ if (innerHandler.setModalProps) {
3054
+ const overrideProps = innerHandler.setModalProps?.(
3055
+ {
3056
+ methodsPath: innerHandler.configuration?.methodsPath,
3057
+ modalConfiguration: innerHandler.configuration?.modalConfiguration
3058
+ },
3059
+ innerHandler.formDefinition
3060
+ );
3061
+ if (overrideProps) {
3062
+ const currentOnClose = () => {
3063
+ overrideProps?.onClose?.();
3064
+ defaultModalProps.onClose?.();
3065
+ };
3066
+ const currentOnExited = () => {
3067
+ overrideProps?.onExited?.();
3068
+ modalHookProps?.onExited?.();
3069
+ };
3070
+ return {
3071
+ ...defaultModalProps,
3072
+ ...overrideProps,
3073
+ ...modalHookProps,
3074
+ onClose: currentOnClose,
3075
+ onExited: currentOnExited
3076
+ };
3077
+ }
3078
+ }
3079
+ return { ...defaultModalProps, ...modalHookProps };
3080
+ },
3081
+ [defaultModalProps, modalHookProps]
3082
+ );
3083
+ const getHandler = React.useCallback(() => {
3084
+ const newHandler = {
3085
+ alert,
3086
+ close,
3087
+ configuration: configuration.current,
3088
+ formDefinition: currentForm2,
3089
+ reset: () => {
3090
+ return setState((currentState) => {
3091
+ return {
3092
+ ...currentState,
3093
+ ...initialState
3094
+ };
3095
+ });
3096
+ },
3097
+ setError,
3098
+ setMessage: (message) => {
3099
+ if (configuration.current?.modalConfiguration?.onMessage)
3100
+ configuration.current.modalConfiguration.onMessage(message);
3101
+ },
3102
+ setState,
3103
+ state,
3104
+ setValue
3105
+ };
3106
+ return newHandler;
3107
+ }, [close, configuration, currentForm2, setError, state, setValue]);
3108
+ const handler = getHandler();
3109
+ const modalProps = getModalProps(handler);
3110
+ const handleAction = React.useCallback(
3111
+ async (action) => {
3112
+ const innerHandler = getHandler();
3113
+ if (action.toDo === "ajaxHiddeAll") {
3114
+ close();
3115
+ }
3116
+ if (action.toDo === "functionTimedCall") {
3117
+ const method = await getFunction(
3118
+ arrayOrArray(action.param)[1],
3119
+ innerHandler
3120
+ );
3121
+ if (method) {
3122
+ setTimeout(
3123
+ () => method({
3124
+ currentUrl: innerHandler.formDefinition?.form.action ?? "noUrl"
3125
+ }),
3126
+ Number(action.param[0])
3127
+ );
3128
+ }
3129
+ }
3130
+ },
3131
+ [close, getHandler]
3132
+ );
3133
+ const handleFunction = React.useCallback(
3134
+ async ({ name, props: { messages, attributes, currentUrl } }) => {
3135
+ const innerHandler = getHandler();
3136
+ const method = await getFunction(`${name}`, innerHandler);
3137
+ if (method) {
3138
+ method({ messages, attributes, currentUrl });
3139
+ }
3140
+ },
3141
+ [getHandler]
3142
+ );
3143
+ const handleMessage = React.useCallback(
3144
+ (ev) => {
3145
+ const innerHandler = getHandler();
3146
+ notify({
3147
+ message: ev.predicate,
3148
+ type: "warning",
3149
+ onClose: innerHandler.configuration?.modalConfiguration?.onMessageClose
3150
+ });
3151
+ const onMessage = innerHandler.configuration?.modalConfiguration?.onMessage;
3152
+ if (onMessage) {
3153
+ onMessage(ev);
3154
+ }
3155
+ },
3156
+ [getHandler]
3157
+ );
3158
+ React.useEffect(() => {
3159
+ const u1 = ApiaApiMessenger.on("message", handleMessage);
3160
+ const u2 = FunctionsDispatcher.on("method", handleFunction);
3161
+ const u3 = ApiaActions.on("action", handleAction);
3162
+ return () => {
3163
+ u1();
3164
+ u2();
3165
+ u3();
3166
+ };
3167
+ }, [handleAction, handleFunction, handleMessage, state.windowIndex]);
3168
+ React.useEffect(() => {
3169
+ if (currentForm2) {
3170
+ show();
3171
+ }
3172
+ }, [currentForm2]);
3173
+ const formRef = React.useCallback(
3174
+ async (el) => {
3175
+ if (el && currentForm2?.form.onLoad) {
3176
+ const method = await getFunction(
3177
+ `${currentForm2?.form.onLoad}`,
3178
+ getHandler()
3179
+ );
3180
+ if (method) {
3181
+ method();
3182
+ }
3183
+ }
3184
+ },
3185
+ [currentForm2?.form.onLoad, getHandler]
3186
+ );
3187
+ return /* @__PURE__ */ jsx(ApiaApiContext$1, { id: apiaApiForm, children: /* @__PURE__ */ jsx(Modal, { ...modalProps, ref: modalRef, children: currentForm2 && /* @__PURE__ */ jsx(Box, { ...getVariant("layout.common.modals.apiaApi"), children: /* @__PURE__ */ jsxs(
3188
+ Form,
3189
+ {
3190
+ name: apiaApiForm,
3191
+ unregisterOnUnmount: true,
3192
+ avoidFieldsOverride: true,
3193
+ className: "handler__form",
3194
+ children: [
3195
+ /* @__PURE__ */ jsx(ApiaApiFieldsContainer, { definition: currentForm2, ...handler }),
3196
+ state.isMultipart && state.progress > 0 && /* @__PURE__ */ jsx(Box, { className: "progressBox", children: /* @__PURE__ */ jsx(
3197
+ ProgressBar,
3198
+ {
3199
+ id: "ApiaApiHandler progress",
3200
+ progress: state.progress,
3201
+ loading: true
3202
+ }
3203
+ ) }),
3204
+ /* @__PURE__ */ jsx(ApiaApiButtonsContainer, { definition: currentForm2, ...handler }),
3205
+ /* @__PURE__ */ jsx(Box, { ref: formRef, sx: { display: "none" } })
3206
+ ]
3207
+ }
3208
+ ) }) }) });
3209
+ };
3210
+ const ApiaApiHandler = React.memo(ApiaApiHandlerNonMemoized);
3211
+
3212
+ export { ApiaApi$1 as ApiaApi, ApiaApiHandler, getFunction, getModal, makeApiaUrl };
4
3213
  //# sourceMappingURL=index.js.map