@apia/api 3.0.10 → 3.0.12

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.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- import * as React from 'react';
1
+ import * as React$1 from 'react';
2
2
  import React__default from 'react';
3
3
  import { AxiosResponse, AxiosRequestConfig } from 'axios';
4
- import { TApiaFilter, TModify, TApiaLoad, TApiaFormElement } from '@apia/util';
4
+ import * as _apia_util from '@apia/util';
5
+ import { TApiaFilter, TModify, TApiaLoad, TApiaFormElement, TApiaFilterOption, TApiaFunction, TApiaFunctionPageInfo } from '@apia/util';
5
6
  import { TNotificationMessage, notify } from '@apia/notifications';
6
- import { TModal } from '@apia/components';
7
+ import { TModal, TOpenModal, ApiaUtilModalHandler } from '@apia/components';
7
8
  import QueryString from 'qs';
8
- import { TResponsiveTableColumn } from '@apia/table';
9
+ import { TResponsiveTableColumn, TResponsiveTableContextProps, TResponsiveTableRow, TResponsiveTableRowsSelectionEvent, TResponsiveTableSortChangeEvent } from '@apia/table';
10
+ import * as lodash from 'lodash';
11
+ import * as theme_ui from 'theme-ui';
9
12
 
10
13
  declare function getConfig<LoadType>(outerBehaveConfig?: IApiaApiRequestConfig<LoadType>): IApiaApiRequestConfig<unknown> & IApiaApiRequestConfig<LoadType> & Partial<IApiaApiRequestConfig<unknown>>;
11
14
  type TApiaApiAxiosResponse<LoadType> = AxiosResponse<LoadType | null> & {
@@ -245,14 +248,14 @@ type TApiaApiMethodHandler = {
245
248
  reset: () => void;
246
249
  setError: typeof notify;
247
250
  setMessage: (message: Record<string, unknown>) => unknown;
248
- setState: React.Dispatch<React.SetStateAction<IApiaApiHandlerState>>;
251
+ setState: React$1.Dispatch<React$1.SetStateAction<IApiaApiHandlerState>>;
249
252
  state: IApiaApiHandlerState;
250
253
  setValue: (name: string, value: string) => void;
251
254
  };
252
255
  type TApiaApiMethod = (handler: TApiaApiMethodHandler, props: TMethod['props']) => Promise<void> | void;
253
256
  type TApiaApiField = TApiaApiMethodHandler & {
254
257
  element: TModify<TApiaFormElement, {
255
- onChange: React.ChangeEventHandler;
258
+ onChange: React$1.ChangeEventHandler;
256
259
  }>;
257
260
  };
258
261
  type TStoredApiaApiMethod = (props?: TMethod['props']) => unknown;
@@ -277,7 +280,7 @@ interface IApiaApiHandlerState {
277
280
  errors: Record<string, string>;
278
281
  windowIndex: number;
279
282
  }
280
- declare const ApiaApiHandler: React.MemoExoticComponent<() => React.JSX.Element>;
283
+ declare const ApiaApiHandler: React$1.MemoExoticComponent<() => React$1.JSX.Element>;
281
284
 
282
285
  declare global {
283
286
  interface Window {
@@ -294,5 +297,129 @@ declare global {
294
297
  * */
295
298
  declare const getModal: (path: string) => React__default.LazyExoticComponent<React__default.ComponentType<TApiaApiField>>;
296
299
 
297
- export { ApiaApi, ApiaApiHandler, type IApiaApiRequestConfig, type TApiaApiAxiosResponse, type TApiaApiMethod, type TApiaApiResult, getFunction, getModal, makeApiaUrl };
300
+ type TFilter = {
301
+ avoidLabel?: boolean;
302
+ column?: string;
303
+ errorMessage?: string;
304
+ id: string;
305
+ isAdditional?: boolean;
306
+ isHidden?: boolean;
307
+ onChange?: (queryController: QueryController) => unknown;
308
+ options?: TApiaFilterOption[];
309
+ placeholder?: string;
310
+ readonly?: boolean;
311
+ required?: boolean;
312
+ runAutomatically?: boolean;
313
+ title?: string;
314
+ tooltip?: string;
315
+ type?: 'date' | 'D' | 'S' | 'number' | 'N' | 'apiaNumber' | 'triple' | 'dateHour';
316
+ value: any;
317
+ };
318
+
319
+ type FilterState = TFilter;
320
+ declare class Filter {
321
+ filterState: FilterState;
322
+ constructor(properties: TFilter);
323
+ Component: (({ filter }: {
324
+ filter: TApiaFilter;
325
+ }) => React$1.JSX.Element) & {
326
+ displayName: string;
327
+ };
328
+ }
329
+
330
+ type TableControllerState = {
331
+ columns: Map<string, TResponsiveTableColumn>;
332
+ filters: Map<string | number, Filter>;
333
+ pagination: {
334
+ currentPage: number;
335
+ totalPages: number;
336
+ totalRecords: number;
337
+ };
338
+ props: Omit<TResponsiveTableContextProps, 'FiltersRenderer' | 'SelectionHandler' | 'filters' | 'columns' | 'rows' | keyof TableControllerEvents>;
339
+ rows: TResponsiveTableRow[];
340
+ };
341
+ type TableControllerEvents = {
342
+ onChangeSelection: TResponsiveTableRowsSelectionEvent;
343
+ onFilterBlur: TApiaFilter;
344
+ onFilterChange: TApiaFilter;
345
+ onFilterPressEnter: TApiaFilter;
346
+ onPage: number;
347
+ onRefresh: null;
348
+ onRowClick: TResponsiveTableRowsSelectionEvent[number];
349
+ onSelectRows: TResponsiveTableRowsSelectionEvent;
350
+ onSortChange: TResponsiveTableSortChangeEvent;
351
+ };
352
+
353
+ declare class TableController {
354
+ private emitter;
355
+ private tableName;
356
+ private tableSelectionController;
357
+ private controllerComponent;
358
+ state: TableControllerState;
359
+ constructor(initialState?: Partial<TableControllerState>);
360
+ Context: (({ children }: {
361
+ children: React.ReactNode;
362
+ }) => React$1.JSX.Element) & {
363
+ displayName: string;
364
+ };
365
+ getTableName(): string;
366
+ Pagination: (() => React$1.JSX.Element) & {
367
+ displayName: string;
368
+ };
369
+ Table: React$1.MemoExoticComponent<React$1.ForwardRefExoticComponent<theme_ui.BoxProps & React$1.RefAttributes<HTMLDivElement>>>;
370
+ on<K extends keyof TableControllerEvents>(ev: K, cb: (e: TableControllerEvents[K]) => unknown): _apia_util.UnSubscriber;
371
+ updateState(newState: Partial<TableControllerState> | ((currentState: TableControllerState) => void)): void;
372
+ }
373
+
374
+ type QueryControllerStructure = {
375
+ columns: TResponsiveTableColumn[];
376
+ description: string;
377
+ filters: TFilter[];
378
+ hasAdditionalInformation: boolean;
379
+ isDynamic: boolean;
380
+ openFiltersAutomatically: boolean;
381
+ runFiltersAutomatically: boolean;
382
+ title: string;
383
+ };
384
+ declare abstract class QueryController {
385
+ ajaxUrl: string;
386
+ private hasInited;
387
+ private initializing;
388
+ structure: QueryControllerStructure | null;
389
+ tableController: TableController;
390
+ constructor(ajaxUrl: string);
391
+ private initEvents;
392
+ protected getLoadStructureParameters(): Record<string, unknown>;
393
+ protected getPageParameters(): Record<string, unknown>;
394
+ protected getRefreshParameters(): Record<string, unknown>;
395
+ protected getSortParameters(): Record<string, unknown>;
396
+ protected parseLoadStructureResponse(response: Record<string, unknown>): QueryControllerStructure;
397
+ protected parseRefreshResponse(response?: TApiaFunction | null): void;
398
+ protected getStructure(): Promise<QueryControllerStructure>;
399
+ protected parseStructure(structure: QueryControllerStructure): void;
400
+ protected updatePageState(pageInfo?: TApiaFunctionPageInfo): void;
401
+ protected updateRows(rows: TResponsiveTableRow[]): void;
402
+ initialLoad(): Promise<void>;
403
+ page(num: number): Promise<void>;
404
+ protected executeRefresh: lodash.DebouncedFunc<() => Promise<void>>;
405
+ refresh(): Promise<void | undefined>;
406
+ sort(column: string): Promise<void>;
407
+ }
408
+
409
+ type QueryModalControllerEvents = Pick<TableControllerEvents, 'onSelectRows'>;
410
+ declare class QueryModalController {
411
+ private emitter;
412
+ protected queryController: QueryController;
413
+ private modalHandler;
414
+ private currentSelection;
415
+ private additionalFiltersController;
416
+ constructor(queryController: QueryController);
417
+ protected getModalDefinition(): TOpenModal;
418
+ getQueryController(): QueryController;
419
+ on<K extends keyof QueryModalControllerEvents>(ev: K, cb: (e: QueryModalControllerEvents[K]) => unknown): _apia_util.UnSubscriber;
420
+ openModal: (properties?: TOpenModal) => Promise<void>;
421
+ getModalHandler(): ApiaUtilModalHandler | null;
422
+ }
423
+
424
+ export { ApiaApi, ApiaApiHandler, type IApiaApiRequestConfig, QueryController, type QueryControllerStructure, QueryModalController, type TApiaApiAxiosResponse, type TApiaApiMethod, type TApiaApiResult, type TFilter, getFunction, getModal, makeApiaUrl };
298
425
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { jsx, jsxs, Fragment } from '@apia/theme/jsx-runtime';
2
2
  import * as React from 'react';
3
3
  import React__default, { createContext, useState, useCallback, useEffect, useId } from 'react';
4
- import { Box, Label, spacing, getVariant } from '@apia/theme';
4
+ import { Box, Label, spacing, getVariant, Input as Input$1 } from '@apia/theme';
5
5
  import { debugDispatcher, parseXmlAsync, EventEmitter, arrayOrArray, useMount, encrypt, noNaN, getIndex, getLabel, StatefulEmitter, focus, focusSelector, useLatest } from '@apia/util';
6
6
  import { notify, getNotificationMessageObj, dispatchNotifications } from '@apia/notifications';
7
7
  import { classToValidate, Checkbox, FileInput, classToValidationFunction, Input, Radio, Select, Textarea, useFormContext, validationsStore, hasSucceedFormValidation, Form } from '@apia/validations';
@@ -11,7 +11,10 @@ import merge from 'lodash-es/merge';
11
11
  import QueryString from 'qs';
12
12
  import { session } from '@apia/session';
13
13
  import uniqueId from 'lodash-es/uniqueId';
14
- import { ResponsiveTableContext, ResponsiveTable, Pagination, Sort, Responsive, Additional, responsiveTableStore } from '@apia/table';
14
+ import { ResponsiveTableContext, ResponsiveTable, Pagination, Sort, Responsive, Additional, responsiveTableStore, TableContextReproducer, makeController2, useResponsiveTableContext } from '@apia/table';
15
+ import { toJS, makeObservable, observable, action } from 'mobx';
16
+ import { observer } from 'mobx-react-lite';
17
+ import { throttle } from 'lodash-es';
15
18
 
16
19
  const ApiaApiId = createContext("apiaApi");
17
20
  const ApiaApiContext = ({
@@ -3217,5 +3220,504 @@ const ApiaApiHandlerNonMemoized = () => {
3217
3220
  };
3218
3221
  const ApiaApiHandler = React.memo(ApiaApiHandlerNonMemoized);
3219
3222
 
3220
- export { ApiaApi$1 as ApiaApi, ApiaApiHandler, getFunction, getModal, makeApiaUrl };
3223
+ const AdditionalFiltersComponent = ({
3224
+ tableController
3225
+ }) => {
3226
+ const filterTitle = getLabel("sbtFilters").text;
3227
+ const sortTitle = getLabel("titOrderBy").text;
3228
+ const filterTypes = getLabel("btnFilterType").text;
3229
+ return /* @__PURE__ */ jsx(TableContextReproducer, { tableName: tableController.getTableName(), children: /* @__PURE__ */ jsx(Box, { className: "additionalFiltersContent", children: /* @__PURE__ */ jsxs(Accordion, { children: [
3230
+ /* @__PURE__ */ jsx(
3231
+ AccordionItem,
3232
+ {
3233
+ id: "Responsive",
3234
+ buttonProps: { ariaLabel: filterTitle, label: filterTitle },
3235
+ children: /* @__PURE__ */ jsx(Responsive, {})
3236
+ }
3237
+ ),
3238
+ /* @__PURE__ */ jsx(
3239
+ AccordionItem,
3240
+ {
3241
+ id: "Additional",
3242
+ buttonProps: { ariaLabel: sortTitle, label: sortTitle },
3243
+ children: /* @__PURE__ */ jsx(Additional, {})
3244
+ }
3245
+ ),
3246
+ /* @__PURE__ */ jsx(
3247
+ AccordionItem,
3248
+ {
3249
+ id: "Sort",
3250
+ buttonProps: { ariaLabel: filterTypes, label: filterTypes },
3251
+ children: /* @__PURE__ */ jsx(Sort, {})
3252
+ }
3253
+ )
3254
+ ] }) }) });
3255
+ };
3256
+
3257
+ var __defProp$4 = Object.defineProperty;
3258
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3259
+ var __publicField$4 = (obj, key, value) => {
3260
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
3261
+ return value;
3262
+ };
3263
+ class AdditionalFiltersModalController {
3264
+ constructor(tableController) {
3265
+ this.tableController = tableController;
3266
+ __publicField$4(this, "modalHandler", null);
3267
+ }
3268
+ getModalDefinition() {
3269
+ return {
3270
+ children: /* @__PURE__ */ jsx(AdditionalFiltersComponent, { tableController: this.tableController }),
3271
+ onConfirm: () => {
3272
+ },
3273
+ confirmProps: {
3274
+ hideConfirmButton: true,
3275
+ hideCancelButton: true,
3276
+ additionalButtons: /* @__PURE__ */ jsxs(Fragment, { children: [
3277
+ /* @__PURE__ */ jsx(SimpleButton, { children: "TODO:BUSCAR" }),
3278
+ ",",
3279
+ /* @__PURE__ */ jsx(SimpleButton, { variant: "outline", children: "TODO:FILTER" })
3280
+ ] })
3281
+ },
3282
+ draggable: true,
3283
+ size: "lg"
3284
+ };
3285
+ }
3286
+ async openModal(properties) {
3287
+ this.modalHandler = ApiaUtil.instance.modals.open({
3288
+ ...this.getModalDefinition(),
3289
+ ...properties
3290
+ });
3291
+ }
3292
+ closeModal() {
3293
+ this.modalHandler?.close();
3294
+ }
3295
+ }
3296
+
3297
+ var __defProp$3 = Object.defineProperty;
3298
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3299
+ var __publicField$3 = (obj, key, value) => {
3300
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
3301
+ return value;
3302
+ };
3303
+ class QueryModalController {
3304
+ constructor(queryController) {
3305
+ __publicField$3(this, "emitter", new EventEmitter());
3306
+ __publicField$3(this, "queryController");
3307
+ __publicField$3(this, "modalHandler", null);
3308
+ __publicField$3(this, "currentSelection", null);
3309
+ __publicField$3(this, "additionalFiltersController");
3310
+ __publicField$3(this, "openModal", async (properties) => {
3311
+ await this.queryController.initialLoad();
3312
+ this.modalHandler = ApiaUtil.instance.modals.open({
3313
+ ...this.getModalDefinition(),
3314
+ ...properties
3315
+ });
3316
+ });
3317
+ if (!queryController) {
3318
+ throw new Error("QueryController instance is required");
3319
+ }
3320
+ this.queryController = queryController;
3321
+ this.additionalFiltersController = new AdditionalFiltersModalController(
3322
+ this.queryController.tableController
3323
+ );
3324
+ this.queryController.tableController.state.props = {
3325
+ isMultiple: false
3326
+ };
3327
+ this.queryController.tableController.on("onSelectRows", (ev) => {
3328
+ this.emitter.emit("onSelectRows", ev);
3329
+ this.modalHandler?.close();
3330
+ });
3331
+ this.queryController.tableController.on("onChangeSelection", (ev) => {
3332
+ this.currentSelection = ev;
3333
+ });
3334
+ }
3335
+ getModalDefinition() {
3336
+ const tableController = this.queryController.tableController;
3337
+ const structure = this.queryController.structure;
3338
+ return {
3339
+ children: /* @__PURE__ */ jsxs(tableController.Context, { children: [
3340
+ /* @__PURE__ */ jsx(tableController.Table, {}),
3341
+ /* @__PURE__ */ jsx(tableController.Pagination, {})
3342
+ ] }),
3343
+ title: structure?.title,
3344
+ onConfirm: () => {
3345
+ this.emitter.emit("onSelectRows", this.currentSelection || []);
3346
+ },
3347
+ onCancel: () => {
3348
+ this.additionalFiltersController.closeModal();
3349
+ },
3350
+ confirmProps: {
3351
+ confirmButtonText: getLabel("btnCon").text,
3352
+ cancelButtonText: getLabel("btnCan").text
3353
+ },
3354
+ NavBar: /* @__PURE__ */ jsx(
3355
+ SimpleButton,
3356
+ {
3357
+ size: "sm",
3358
+ variant: "outline",
3359
+ onClick: () => this.additionalFiltersController.openModal(),
3360
+ children: "Additional filters"
3361
+ }
3362
+ ),
3363
+ size: "finder"
3364
+ };
3365
+ }
3366
+ getQueryController() {
3367
+ return this.queryController;
3368
+ }
3369
+ on(ev, cb) {
3370
+ return this.emitter.on(ev, cb);
3371
+ }
3372
+ getModalHandler() {
3373
+ return this.modalHandler;
3374
+ }
3375
+ }
3376
+
3377
+ var __defProp$2 = Object.defineProperty;
3378
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3379
+ var __publicField$2 = (obj, key, value) => {
3380
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
3381
+ return value;
3382
+ };
3383
+ let controllerCount = 0;
3384
+ class TableController {
3385
+ constructor(initialState) {
3386
+ __publicField$2(this, "emitter", new EventEmitter());
3387
+ __publicField$2(this, "tableName", `TableController${controllerCount++}`);
3388
+ __publicField$2(this, "tableSelectionController");
3389
+ __publicField$2(this, "controllerComponent", () => null);
3390
+ __publicField$2(this, "state", {
3391
+ columns: /* @__PURE__ */ new Map(),
3392
+ filters: /* @__PURE__ */ new Map(),
3393
+ pagination: { currentPage: 0, totalPages: 0, totalRecords: 0 },
3394
+ props: {},
3395
+ rows: []
3396
+ });
3397
+ __publicField$2(this, "Context", observer(({ children }) => {
3398
+ const props = toJS(this.state.props);
3399
+ return /* @__PURE__ */ jsx(
3400
+ ResponsiveTableContext,
3401
+ {
3402
+ ...props,
3403
+ columns: [...toJS(this.state.columns).values()],
3404
+ rows: toJS(this.state.rows),
3405
+ filters: [...toJS(this.state.filters).values()].map((c) => {
3406
+ return {
3407
+ id: c.filterState.id,
3408
+ column: c.filterState.column,
3409
+ asAdditional: c.filterState.isAdditional || this.state.columns.get(c.filterState.column || "")?.hidden
3410
+ };
3411
+ }),
3412
+ FiltersRenderer: (filterId) => this.state.filters.get(filterId).Component,
3413
+ name: this.tableName,
3414
+ SelectionHandler: this.controllerComponent,
3415
+ onSortChange: () => {
3416
+ this.emitter.emit.bind(this.emitter, "onSortChange");
3417
+ },
3418
+ onChangeSelection: this.emitter.emit.bind(
3419
+ this.emitter,
3420
+ "onChangeSelection"
3421
+ ),
3422
+ onFilterBlur: this.emitter.emit.bind(this.emitter, "onFilterBlur"),
3423
+ onFilterChange: this.emitter.emit.bind(this.emitter, "onFilterChange"),
3424
+ onFilterPressEnter: this.emitter.emit.bind(
3425
+ this.emitter,
3426
+ "onFilterPressEnter"
3427
+ ),
3428
+ onRowClick: this.emitter.emit.bind(this.emitter, "onRowClick"),
3429
+ onSelectRows: this.emitter.emit.bind(this.emitter, "onSelectRows"),
3430
+ children
3431
+ }
3432
+ );
3433
+ }));
3434
+ __publicField$2(this, "Pagination", observer(() => {
3435
+ return /* @__PURE__ */ jsx(
3436
+ Pagination,
3437
+ {
3438
+ currentPage: this.state.pagination.currentPage,
3439
+ pageCount: this.state.pagination.totalPages,
3440
+ recordsCount: this.state.pagination.totalRecords,
3441
+ onPageChange: this.emitter.emit.bind(this.emitter, "onPage"),
3442
+ onRefresh: this.emitter.emit.bind(this.emitter, "onRefresh", null)
3443
+ }
3444
+ );
3445
+ }));
3446
+ __publicField$2(this, "Table", ResponsiveTable);
3447
+ makeObservable(this, {
3448
+ state: observable,
3449
+ updateState: action
3450
+ });
3451
+ const [controller, controllerComponent] = makeController2(this.tableName);
3452
+ this.tableSelectionController = controller;
3453
+ this.controllerComponent = controllerComponent;
3454
+ if (initialState) {
3455
+ Object.assign(this.state, initialState);
3456
+ }
3457
+ }
3458
+ getTableName() {
3459
+ return this.tableName;
3460
+ }
3461
+ on(ev, cb) {
3462
+ return this.emitter.on(ev, cb);
3463
+ }
3464
+ updateState(newState) {
3465
+ if (newState instanceof Function) {
3466
+ newState(this.state);
3467
+ } else {
3468
+ Object.assign(this.state, newState);
3469
+ }
3470
+ }
3471
+ }
3472
+
3473
+ var __defProp$1 = Object.defineProperty;
3474
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3475
+ var __publicField$1 = (obj, key, value) => {
3476
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
3477
+ return value;
3478
+ };
3479
+ class Filter {
3480
+ constructor(properties) {
3481
+ __publicField$1(this, "filterState", {
3482
+ runAutomatically: false,
3483
+ value: ""
3484
+ });
3485
+ __publicField$1(this, "Component", observer(({ filter }) => {
3486
+ const { onFilterBlur, onFilterChange, onFilterPressEnter } = useResponsiveTableContext();
3487
+ return /* @__PURE__ */ jsx(
3488
+ Input$1,
3489
+ {
3490
+ value: this.filterState.value,
3491
+ onChange: (ev) => {
3492
+ this.filterState.value = ev.target.value;
3493
+ onFilterChange?.(filter);
3494
+ },
3495
+ onKeyDown: (ev) => {
3496
+ if (ev.code === "Enter") {
3497
+ onFilterPressEnter?.(filter);
3498
+ }
3499
+ },
3500
+ onBlur: () => {
3501
+ onFilterBlur?.(filter);
3502
+ }
3503
+ }
3504
+ );
3505
+ }));
3506
+ Object.assign(this.filterState, properties);
3507
+ makeObservable(this, { filterState: observable });
3508
+ }
3509
+ }
3510
+
3511
+ var __defProp = Object.defineProperty;
3512
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3513
+ var __publicField = (obj, key, value) => {
3514
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
3515
+ return value;
3516
+ };
3517
+ class QueryController {
3518
+ constructor(ajaxUrl) {
3519
+ this.ajaxUrl = ajaxUrl;
3520
+ __publicField(this, "hasInited", false);
3521
+ __publicField(this, "initializing", false);
3522
+ __publicField(this, "structure", null);
3523
+ __publicField(this, "tableController", new TableController());
3524
+ __publicField(this, "executeRefresh", throttle(
3525
+ async () => {
3526
+ const refresh = await ApiaApi$1.post(
3527
+ makeApiaUrl(this.getRefreshParameters())
3528
+ );
3529
+ this.parseRefreshResponse(refresh?.data);
3530
+ },
3531
+ 300,
3532
+ { leading: false, trailing: true }
3533
+ ));
3534
+ this.initEvents();
3535
+ }
3536
+ initEvents() {
3537
+ this.tableController.on("onChangeSelection", (ev) => {
3538
+ });
3539
+ this.tableController.on("onFilterBlur", (ev) => {
3540
+ });
3541
+ this.tableController.on("onFilterChange", (ev) => {
3542
+ const filter = this.tableController.state.filters.get(ev.id);
3543
+ if (filter?.filterState.runAutomatically) {
3544
+ this.refresh();
3545
+ }
3546
+ });
3547
+ this.tableController.on("onFilterPressEnter", this.refresh.bind(this));
3548
+ this.tableController.on("onRowClick", (ev) => {
3549
+ });
3550
+ this.tableController.on("onSelectRows", (ev) => {
3551
+ });
3552
+ this.tableController.on("onSortChange", (ev) => {
3553
+ this.sort(ev.column.name);
3554
+ });
3555
+ this.tableController.on("onPage", this.page.bind(this));
3556
+ this.tableController.on("onRefresh", this.refresh.bind(this));
3557
+ }
3558
+ getLoadStructureParameters() {
3559
+ return {
3560
+ ajaxUrl: this.ajaxUrl,
3561
+ action: "init",
3562
+ react: true,
3563
+ //Importante para forzar paginacion en querys de modal ya que no existe parametro aún
3564
+ forcePagination: true
3565
+ };
3566
+ }
3567
+ getPageParameters() {
3568
+ return {
3569
+ ajaxUrl: this.ajaxUrl,
3570
+ action: "page"
3571
+ };
3572
+ }
3573
+ getRefreshParameters() {
3574
+ return {
3575
+ ajaxUrl: this.ajaxUrl,
3576
+ action: "refresh",
3577
+ react: true
3578
+ };
3579
+ }
3580
+ getSortParameters() {
3581
+ return {
3582
+ ajaxUrl: this.ajaxUrl,
3583
+ action: "sort",
3584
+ react: true,
3585
+ orderJustThisColumn: true
3586
+ };
3587
+ }
3588
+ parseLoadStructureResponse(response) {
3589
+ const typedResponse = response;
3590
+ const retrievedColumns = arrayOrArray(typedResponse.columns.column);
3591
+ return {
3592
+ columns: retrievedColumns.map((c) => {
3593
+ const column = {
3594
+ label: c.title,
3595
+ name: c.name,
3596
+ additionalData: c,
3597
+ allowSorting: c.enableOrder === "1",
3598
+ ariaLabel: c.title,
3599
+ currentSorting: c.order,
3600
+ hidden: c.hide === "1",
3601
+ hideFromAccordion: c.hide === "1",
3602
+ id: c.name,
3603
+ showAsAdditional: c.asMoreInformation,
3604
+ title: c.title,
3605
+ width: c.width
3606
+ };
3607
+ return column;
3608
+ }),
3609
+ description: typedResponse.queryData.description,
3610
+ filters: arrayOrArray(typedResponse.filters.filter).filter((f) => !!f.column).map((f, i) => {
3611
+ const filter = {
3612
+ id: `filter${String(i + 1)}`,
3613
+ // Id generado en APIA
3614
+ value: f.currentValue,
3615
+ avoidLabel: false,
3616
+ column: f.column,
3617
+ isAdditional: f.asAdditional,
3618
+ isHidden: f.hideFilterOption,
3619
+ title: f.title,
3620
+ tooltip: f.toolTip,
3621
+ type: f.type,
3622
+ onChange: () => {
3623
+ },
3624
+ options: [],
3625
+ placeholder: f.title,
3626
+ readonly: f.readonly,
3627
+ required: f.required === "true",
3628
+ runAutomatically: typedResponse?.filters.runFiltersAutomatically || f.detectOnChange
3629
+ };
3630
+ return filter;
3631
+ }),
3632
+ hasAdditionalInformation: !!retrievedColumns.find(
3633
+ (c) => c.asMoreInformation
3634
+ ),
3635
+ isDynamic: false,
3636
+ title: typedResponse.queryData.title,
3637
+ openFiltersAutomatically: typedResponse.filters.openFiltersAutomatically,
3638
+ runFiltersAutomatically: typedResponse.filters.runFiltersAutomatically
3639
+ };
3640
+ }
3641
+ parseRefreshResponse(response) {
3642
+ const columns = [...this.tableController.state.columns.values()];
3643
+ const rows = response?.function?.messages?.result?.table?.row;
3644
+ const pageState = response?.function.messages.result.pageInfo;
3645
+ this.updatePageState(pageState);
3646
+ this.updateRows([
3647
+ ...arrayOrArray(rows).map((r) => {
3648
+ return {
3649
+ forbidSelection: r.unselectableTR,
3650
+ initiallySelected: r.selected,
3651
+ isLocked: r.isLocked,
3652
+ rowProps: r,
3653
+ cells: [
3654
+ columns.find((c) => c.showAsAdditional) ? {} : void 0,
3655
+ ...columns.filter((c) => c.hidden).map(() => ({})),
3656
+ ...arrayOrArray(r.cell).map((c) => ({ children: c }))
3657
+ ].filter(Boolean),
3658
+ className: r.classToAdd,
3659
+ id: r.id
3660
+ };
3661
+ })
3662
+ ]);
3663
+ }
3664
+ async getStructure() {
3665
+ const result = await ApiaApi$1.post(
3666
+ makeApiaUrl(this.getLoadStructureParameters())
3667
+ );
3668
+ if (!result?.data) {
3669
+ throw new Error("Cannot load Input query structure");
3670
+ }
3671
+ return this.parseLoadStructureResponse(result.data);
3672
+ }
3673
+ parseStructure(structure) {
3674
+ const columns = new Map(
3675
+ arrayOrArray(structure.columns).map((c) => [c.name, c])
3676
+ );
3677
+ const filters = new Map(
3678
+ arrayOrArray(structure.filters).map((f) => [f.id, new Filter(f)])
3679
+ );
3680
+ this.tableController.updateState({ columns, filters });
3681
+ }
3682
+ updatePageState(pageInfo) {
3683
+ const currentPage = Number(pageInfo?.currentPage ?? 0);
3684
+ const totalPages = Number(pageInfo?.pageCount ?? 0);
3685
+ const totalRecords = Number(pageInfo?.totalRecords ?? 0);
3686
+ this.tableController.updateState({
3687
+ pagination: { currentPage, totalPages, totalRecords }
3688
+ });
3689
+ }
3690
+ updateRows(rows) {
3691
+ this.tableController.state.rows = rows;
3692
+ }
3693
+ async initialLoad() {
3694
+ if (this.initializing && !this.hasInited) {
3695
+ throw new Error("Cannot initialize the query twice");
3696
+ }
3697
+ this.initializing = true;
3698
+ if (!this.hasInited) {
3699
+ this.structure = await this.getStructure();
3700
+ this.parseStructure(this.structure);
3701
+ this.hasInited = true;
3702
+ this.initializing = false;
3703
+ }
3704
+ }
3705
+ async page(num) {
3706
+ const page = await ApiaApi$1.post(
3707
+ makeApiaUrl({ ...this.getPageParameters(), pageNumber: num })
3708
+ );
3709
+ this.parseRefreshResponse(page?.data);
3710
+ }
3711
+ async refresh() {
3712
+ return this.executeRefresh();
3713
+ }
3714
+ async sort(column) {
3715
+ await ApiaApi$1.post(
3716
+ makeApiaUrl({ ...this.getSortParameters(), orderBy: column })
3717
+ );
3718
+ this.refresh();
3719
+ }
3720
+ }
3721
+
3722
+ export { ApiaApi$1 as ApiaApi, ApiaApiHandler, QueryController, QueryModalController, getFunction, getModal, makeApiaUrl };
3221
3723
  //# sourceMappingURL=index.js.map