@archbase/data 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +57 -0
  2. package/dist/archbase-data-3.0.0.tgz +0 -0
  3. package/dist/datasource/ArchbaseDataSource.d.ts +472 -0
  4. package/dist/datasource/ArchbaseLocalFilterDataSource.d.ts +27 -0
  5. package/dist/datasource/ArchbaseRemoteDataSource.d.ts +17 -0
  6. package/dist/datasource/ArchbaseRemoteFilterDataSource.d.ts +28 -0
  7. package/dist/datasource/ArchbaseV1V2CompatibilityPattern.d.ts +72 -0
  8. package/dist/datasource/IArchbaseDataSourceBase.d.ts +111 -0
  9. package/dist/datasource/index.d.ts +10 -0
  10. package/dist/datasource/v2/ArchbaseDataSourceV2.d.ts +128 -0
  11. package/dist/datasource/v2/ArchbaseQueryIntegration.d.ts +210 -0
  12. package/dist/datasource/v2/ArchbaseQueryProvider.d.ts +79 -0
  13. package/dist/datasource/v2/ArchbaseRemoteDataSourceV2.d.ts +182 -0
  14. package/dist/datasource/v2/ArchbaseTanStackQueryIntegration.d.ts +132 -0
  15. package/dist/datasource/v2/index.d.ts +11 -0
  16. package/dist/datasource/v2/useArchbaseDataSourceV2.d.ts +143 -0
  17. package/dist/datasource/v2/useArchbaseRemoteDataSourceV2.d.ts +210 -0
  18. package/dist/hooks/index.d.ts +14 -0
  19. package/dist/hooks/useArchbaseDataSource.d.ts +15 -0
  20. package/dist/hooks/useArchbaseDataSourceListener.d.ts +7 -0
  21. package/dist/hooks/useArchbaseDidMount.d.ts +5 -0
  22. package/dist/hooks/useArchbaseDidUpdate.d.ts +6 -0
  23. package/dist/hooks/useArchbaseEventListener.d.ts +1 -0
  24. package/dist/hooks/useArchbaseForceRerender.d.ts +5 -0
  25. package/dist/hooks/useArchbaseForceUpdate.d.ts +5 -0
  26. package/dist/hooks/useArchbaseLocalFilterDataSource.d.ts +13 -0
  27. package/dist/hooks/useArchbaseRemoteDataSource.d.ts +36 -0
  28. package/dist/hooks/useArchbaseRemoteFilterDataSource.d.ts +34 -0
  29. package/dist/hooks/useArchbaseRemoteServiceApi.d.ts +2 -0
  30. package/dist/hooks/useArchbaseStore.d.ts +3 -0
  31. package/dist/hooks/useArchbaseWillUnmount.d.ts +5 -0
  32. package/dist/index.d.ts +9 -0
  33. package/dist/index.js +3360 -0
  34. package/dist/service/ArchbaseRemoteApiService.d.ts +103 -0
  35. package/dist/service/index.d.ts +2 -0
  36. package/dist/types/ArchbaseStateValues.d.ts +9 -0
  37. package/dist/types/index.d.ts +1 -0
  38. package/package.json +64 -0
package/dist/index.js ADDED
@@ -0,0 +1,3360 @@
1
+ import { isDate as we, parseISO as Ee } from "date-fns";
2
+ import { EventEmitter as Le } from "events";
3
+ import { uniqueId as Be, cloneDeep as $e } from "lodash";
4
+ import { archbaseI18next as m, ArchbaseDataSourceError as g, ArchbaseObjectHelper as ye, processErrorMessage as k, QUICK as Se, NORMAL as Fe, ADVANCED as Ae, ArchbaseFilterDSL as xe, QueryFilterEntity as ue, detectDataSourceVersion as ve, MigrationMetrics as Ne, ARCHBASE_IOC_API_TYPE as He, ArchbaseJacksonParser as ie } from "@archbase/core";
5
+ import { ADVANCED as Mt, ARCHBASE_IOC_API_TYPE as jt, FILTER_TYPE as Ut, NORMAL as Gt, QUICK as kt, useArchbaseBool as qt } from "@archbase/core";
6
+ import { useState as C, useCallback as l, useRef as le, useMemo as H, useEffect as J, useReducer as We } from "react";
7
+ import { produce as _ } from "immer";
8
+ import "reflect-metadata";
9
+ import ee from "axios";
10
+ import * as ne from "inversify";
11
+ import { useContainer as ze } from "inversify-react";
12
+ import { create as Me } from "zustand";
13
+ import { createTrackedSelector as je } from "react-tracked";
14
+ var d = /* @__PURE__ */ ((n) => (n[n.dataChanged = 0] = "dataChanged", n[n.recordChanged = 1] = "recordChanged", n[n.refreshData = 2] = "refreshData", n[n.fieldChanged = 3] = "fieldChanged", n[n.beforeClose = 4] = "beforeClose", n[n.afterClose = 5] = "afterClose", n[n.beforeOpen = 6] = "beforeOpen", n[n.afterOpen = 7] = "afterOpen", n[n.beforeAppend = 8] = "beforeAppend", n[n.afterAppend = 9] = "afterAppend", n[n.beforeRemove = 10] = "beforeRemove", n[n.afterRemove = 11] = "afterRemove", n[n.beforeInsert = 12] = "beforeInsert", n[n.afterInsert = 13] = "afterInsert", n[n.beforeEdit = 14] = "beforeEdit", n[n.afterEdit = 15] = "afterEdit", n[n.beforeSave = 16] = "beforeSave", n[n.afterSave = 17] = "afterSave", n[n.beforeCancel = 18] = "beforeCancel", n[n.afterCancel = 19] = "afterCancel", n[n.afterScroll = 20] = "afterScroll", n[n.onError = 21] = "onError", n[n.onFieldError = 22] = "onFieldError", n))(d || {});
15
+ class Ue {
16
+ eventEmitter;
17
+ listenersDisable = !1;
18
+ constructor() {
19
+ this.eventEmitter = new Le();
20
+ }
21
+ disabledAllListeners() {
22
+ return this.listenersDisable = !0, this;
23
+ }
24
+ enableAllListeners() {
25
+ return this.listenersDisable = !1, this;
26
+ }
27
+ emit(e, ...t) {
28
+ return this.listenersDisable ? !1 : this.eventEmitter.emit(e, t);
29
+ }
30
+ addListener(e, t) {
31
+ return this.eventEmitter.addListener(e, t), this;
32
+ }
33
+ on(e, t) {
34
+ return this.eventEmitter.on(e, t), this;
35
+ }
36
+ once(e, t) {
37
+ return this.eventEmitter.once(e, t), this;
38
+ }
39
+ removeListener(e, t) {
40
+ return this.eventEmitter.removeListener(e, t), this;
41
+ }
42
+ off(e, t) {
43
+ return this.eventEmitter.off(e, t), this;
44
+ }
45
+ removeAllListeners(e) {
46
+ return this.eventEmitter.removeAllListeners(e), this;
47
+ }
48
+ }
49
+ class Ie {
50
+ fieldEventListeners;
51
+ records;
52
+ filteredRecords;
53
+ filters;
54
+ grandTotalRecords = 0;
55
+ currentPageIndex = 0;
56
+ totalPages = 0;
57
+ pageSize = 0;
58
+ currentRecordIndex = -1;
59
+ currentRecord;
60
+ oldRecord;
61
+ oldRecordIndex = -1;
62
+ emitter;
63
+ listeners = /* @__PURE__ */ new Set();
64
+ listenersDisable = !1;
65
+ inserting = !1;
66
+ active = !1;
67
+ editing = !1;
68
+ name;
69
+ label;
70
+ uuid;
71
+ lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
72
+ lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime();
73
+ filter;
74
+ sort;
75
+ originFilter;
76
+ originSort;
77
+ originGlobalFilter;
78
+ defaultSortFields = [];
79
+ validator;
80
+ getIdentity;
81
+ constructor(e, t, r) {
82
+ this.name = e, this.label = r || e, this.records = [], this.filteredRecords = [], this.loadOptions(t), this.fieldEventListeners = {}, this.emitter = new Ue(), this.uuid = Be(), this.validator = t.validator, this.getIdentity = t.getIdentity;
83
+ }
84
+ loadOptions(e) {
85
+ this.records = e.records, this.filters = [], e.filters && (this.filters = e.filters), this.currentRecord = void 0, this.currentRecordIndex = -1, this.filteredRecords = this.applyFilters(), this.filteredRecords.length > 0 && (this.currentRecordIndex = 0, this.currentRecord = this.filteredRecords[this.currentRecordIndex]), this.grandTotalRecords = e.grandTotalRecords, this.currentPageIndex = e.currentPage, this.totalPages = e.totalPages, this.pageSize = e.pageSize, this.active = !0, this.filter = e.filter, this.sort = e.sort, this.originFilter = e.originFilter, this.originSort = e.originSort, this.originGlobalFilter = e.originGlobalFilter, this.defaultSortFields = e.defaultSortFields ? e.defaultSortFields : [];
86
+ }
87
+ validateDataSourceActive(e) {
88
+ if (!this.isActive()) {
89
+ const t = m.t("archbase:operationNotAllowed", { dataSourceName: this.name, operation: e });
90
+ throw this.publishEventError(t, {}), new g(t);
91
+ }
92
+ }
93
+ getName() {
94
+ return this.name;
95
+ }
96
+ /**
97
+ * Limpa os dados do DataSource. Ao usar este método os seguintes eventos serão gerados:
98
+ * beforeClose, afterOpen, dataChanged, afterScroll
99
+ */
100
+ clear() {
101
+ if (!this.isActive()) {
102
+ const e = m.t("archbase:operationNotAllowed", { dataSourceName: this.name, operation: "clear" });
103
+ throw this.publishEventError(e, {}), new g(e);
104
+ }
105
+ this.emitter.emit("beforeClose"), this.emit({
106
+ type: 4
107
+ /* beforeClose */
108
+ }), this.loadOptions({
109
+ records: [],
110
+ totalPages: 0,
111
+ grandTotalRecords: 0,
112
+ currentPage: 0,
113
+ pageSize: 0
114
+ }), this.active = !0, this.editing = !1, this.inserting = !1, this.emitter.emit("afterOpen"), this.emit({
115
+ type: 7
116
+ /* afterOpen */
117
+ }), this.emitter.emit("dataChanged", this.records), this.emit({ type: 0, data: this.records }), this.emitter.emit("afterScroll"), this.emit({
118
+ type: 20
119
+ /* afterScroll */
120
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
121
+ }
122
+ open(e) {
123
+ this.active = !1, this.emitter.emit("beforeClose"), this.emit({
124
+ type: 4
125
+ /* beforeClose */
126
+ }), this.loadOptions(e), this.active = !0, this.emitter.emit("afterOpen"), this.emit({
127
+ type: 7
128
+ /* afterOpen */
129
+ }), this.emitter.emit("dataChanged", this.records), this.emit({ type: 0, data: this.records }), this.emitter.emit("afterScroll"), this.emit({
130
+ type: 20
131
+ /* afterScroll */
132
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
133
+ }
134
+ close() {
135
+ this.validateDataSourceActive("close"), this.emitter.emit("beforeClose"), this.emit({
136
+ type: 4
137
+ /* beforeClose */
138
+ }), this.active = !1, this.emitter.emit("afterClose"), this.emit({
139
+ type: 5
140
+ /* afterClose */
141
+ }), this.emitter.emit("afterScroll"), this.emit({
142
+ type: 20
143
+ /* afterScroll */
144
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
145
+ }
146
+ setData(e) {
147
+ this.validateDataSourceActive("setData"), this.loadOptions(e), this.emitter.emit("dataChanged", this.records), this.emit({ type: 0, data: this.records }), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
148
+ }
149
+ goToPage(e) {
150
+ return this.validateDataSourceActive("goToPage"), this;
151
+ }
152
+ goToRecord(e) {
153
+ if (this.validateDataSourceActive("goToRecord"), this.inserting || this.editing || this.isBOF() || this.isEOF()) {
154
+ const t = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
155
+ throw this.publishEventError(t, {}), new g(t);
156
+ }
157
+ e <= this.getTotalRecords() - 1 && (this.currentRecordIndex = e, this.emitter.emit("afterScroll"), this.emit({
158
+ type: 20
159
+ /* afterScroll */
160
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime());
161
+ }
162
+ disabledAllListeners() {
163
+ return this.listenersDisable = !0, this.emitter.disabledAllListeners(), this;
164
+ }
165
+ enableAllListeners() {
166
+ return this.listenersDisable = !1, this.emitter.enableAllListeners(), this;
167
+ }
168
+ addFilter(e) {
169
+ return this.filters?.push(e), this;
170
+ }
171
+ removeFilter(e) {
172
+ const t = this.filters?.indexOf(e);
173
+ return t && t >= 0 && this.filters?.splice(t, 1), this;
174
+ }
175
+ clearFilters() {
176
+ return this.filters = [], this;
177
+ }
178
+ applyFilters() {
179
+ if (!this.filters || this.filters.length === 0)
180
+ return this.records;
181
+ let e = [...this.records];
182
+ return this.filters?.forEach((t) => {
183
+ e = e.filter(t);
184
+ }), e;
185
+ }
186
+ emit(e) {
187
+ if (!this.listenersDisable)
188
+ for (const t of this.listeners)
189
+ t(e);
190
+ }
191
+ append(e) {
192
+ if (this.validateDataSourceActive("append"), this.inserting || this.editing) {
193
+ const t = m.t("archbase:insertRecordIsNotAllowed", { dataSourceName: this.name });
194
+ throw this.publishEventError(t, {}), new g(t);
195
+ }
196
+ return this.emitter.emit("beforeAppend", e), this.emit({ type: 8, record: e }), this.records.push(e), this.filteredRecords = this.applyFilters(), this.grandTotalRecords++, this.filteredRecords.forEach((t, r) => {
197
+ e === t && (this.currentRecordIndex = r, this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.emitter.emit("afterScroll"), this.emit({
198
+ type: 20
199
+ /* afterScroll */
200
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime());
201
+ }), this.emitter.emit("afterAppend", e, this.currentRecordIndex), this.emit({
202
+ type: 9,
203
+ record: e,
204
+ index: this.currentRecordIndex
205
+ }), this.emitter.emit("afterScroll"), this.emit({
206
+ type: 20
207
+ /* afterScroll */
208
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.currentRecordIndex;
209
+ }
210
+ insert(e) {
211
+ if (this.validateDataSourceActive("insert"), this.inserting || this.editing) {
212
+ const r = m.t("archbase:insertRecordIsNotAllowed", { dataSourceName: this.name });
213
+ throw this.publishEventError(r, {}), new g(r);
214
+ }
215
+ this.emitter.emit("beforeInsert"), this.emit({
216
+ type: 12
217
+ /* beforeInsert */
218
+ }), this.oldRecord = this.getCurrentRecord(), this.oldRecordIndex = this.currentRecordIndex, this.grandTotalRecords++;
219
+ const t = this.getTotalRecords();
220
+ return this.filteredRecords = [...this.filteredRecords, e], this.currentRecordIndex = t, this.currentRecord = e, this.inserting = !0, this.emitter.emit("afterInsert", e, this.currentRecordIndex), this.emit({
221
+ type: 13,
222
+ record: e,
223
+ index: this.currentRecordIndex
224
+ }), this.emitter.emit("afterScroll"), this.emit({
225
+ type: 20
226
+ /* afterScroll */
227
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this;
228
+ }
229
+ edit() {
230
+ if (this.validateDataSourceActive("edit"), this.inserting || this.editing) {
231
+ const e = m.t("archbase:editRecordIsNotAllowed", { dataSourceName: this.name });
232
+ throw this.publishEventError(e, {}), new g(e);
233
+ }
234
+ if (this.isEmpty() || !this.currentRecord) {
235
+ const e = m.t("archbase:noRecordsToEdit", { dataSourceName: this.name });
236
+ throw this.publishEventError(e, {}), new g(e);
237
+ }
238
+ if (this.isBOF()) {
239
+ const e = m.t("archbase:BOFDataSource", { dataSourceName: this.name });
240
+ throw this.publishEventError(e, {}), new g(e);
241
+ }
242
+ if (this.isEOF()) {
243
+ const e = m.t("archbase:EOFDataSource", { dataSourceName: this.name });
244
+ throw this.publishEventError(e, {}), new g(e);
245
+ }
246
+ return this.emitter.emit("beforeEdit", this.currentRecord, this.currentRecordIndex), this.emit({
247
+ type: 14,
248
+ record: this.currentRecord,
249
+ index: this.getCurrentIndex()
250
+ }), this.editing = !0, this.currentRecord = $e(this.currentRecord), this.emitter.emit("afterEdit", this.currentRecord, this.getCurrentIndex()), this.emit({
251
+ type: 15,
252
+ record: this.currentRecord,
253
+ index: this.getCurrentIndex()
254
+ }), this;
255
+ }
256
+ async remove(e) {
257
+ if (this.validateDataSourceActive("remove"), this.inserting || this.editing) {
258
+ const s = m.t("archbase:removingRecordIsNotAllowed", { dataSourceName: this.name });
259
+ throw this.publishEventError(s, {}), new g(s);
260
+ }
261
+ if (this.isEmpty() || !this.currentRecord) {
262
+ const s = m.t("archbase:noRecordsToEdit", { dataSourceName: this.name });
263
+ throw this.publishEventError(s, {}), new g(s);
264
+ }
265
+ if (this.isBOF()) {
266
+ const s = m.t("archbase:BOFDataSource", { dataSourceName: this.name });
267
+ throw this.publishEventError(s, {}), new g(s);
268
+ }
269
+ if (this.isEOF()) {
270
+ const s = m.t("archbase:EOFDataSource", { dataSourceName: this.name });
271
+ throw this.publishEventError(s, {}), new g(s);
272
+ }
273
+ this.emitter.emit("beforeRemove", this.currentRecord, this.currentRecordIndex), this.emit({
274
+ type: 10,
275
+ record: this.currentRecord,
276
+ index: this.getCurrentIndex()
277
+ });
278
+ let t = -1;
279
+ const r = this.currentRecord, i = this.currentRecordIndex;
280
+ return this.records.forEach((s, o) => {
281
+ this.currentRecord === s && (t = o);
282
+ }), t >= 0 && this.records.splice(t, 1), this.records !== this.filteredRecords && this.filteredRecords.splice(this.getCurrentIndex(), 1), this.grandTotalRecords--, this.filteredRecords.length === 0 ? (this.currentRecord = void 0, this.currentRecordIndex = -1) : (this.currentRecordIndex > this.filteredRecords.length - 1 && this.currentRecordIndex--, this.currentRecord = this.filteredRecords[this.currentRecordIndex]), this.editing = !1, this.inserting = !1, this.emitter.emit("afterScroll"), this.emit({
283
+ type: 20
284
+ /* afterScroll */
285
+ }), this.emitter.emit("afterRemove", r, i), this.emit({
286
+ type: 11,
287
+ record: r,
288
+ index: i
289
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), e && e(), r;
290
+ }
291
+ isBrowsing() {
292
+ return !this.isEditing() && !this.isInserting() && this.isActive();
293
+ }
294
+ isEditing() {
295
+ return this.editing;
296
+ }
297
+ isInserting() {
298
+ return this.inserting;
299
+ }
300
+ isActive() {
301
+ return this.active;
302
+ }
303
+ getPageSize() {
304
+ return this.pageSize;
305
+ }
306
+ publishEventErrors = (e) => {
307
+ e.forEach((t) => {
308
+ if (t.fieldName) {
309
+ const r = m.t(t.errorMessage, { keySeparator: !1 });
310
+ this.emitter.emit("onFieldError", t.fieldName, r), this.emit({
311
+ type: 22,
312
+ fieldName: t.fieldName,
313
+ error: r,
314
+ originalError: t
315
+ });
316
+ } else
317
+ this.publishEventError(m.t(t.errorMessage, { keySeparator: !1 }), t);
318
+ });
319
+ };
320
+ publishEventError = (e, t) => {
321
+ this.emitter.emit("onError", e), this.emit({
322
+ type: 21,
323
+ error: e,
324
+ originalError: t
325
+ });
326
+ };
327
+ validate() {
328
+ if (this.validator && this.currentRecord) {
329
+ const e = this.validator.validateEntity(this.currentRecord);
330
+ if (e && e.length > 0)
331
+ if (this.publishEventErrors(e), e[0].fieldName) {
332
+ const t = m.t("archbase:errorSavingRecord", { dataSourceName: this.label });
333
+ throw new g(t);
334
+ } else
335
+ throw new g(e[0].errorMessage);
336
+ }
337
+ return !0;
338
+ }
339
+ async save(e) {
340
+ if (this.validateDataSourceActive("save"), !this.inserting && !this.editing) {
341
+ const r = m.t("archbase:saveRecordIsNotAllowed", { dataSourceName: this.name });
342
+ throw this.publishEventError(r, {}), new g(r);
343
+ }
344
+ if (!this.currentRecord) {
345
+ const r = m.t("archbase:noRecordToSave", { dataSourceName: this.name });
346
+ throw this.publishEventError(r, {}), new g(r);
347
+ }
348
+ if (this.emitter.emit("beforeSave", this.currentRecord, this.getCurrentIndex()), this.emit({
349
+ type: 16,
350
+ record: this.currentRecord,
351
+ index: this.getCurrentIndex()
352
+ }), this.validator) {
353
+ const r = this.validator.validateEntity(this.currentRecord);
354
+ if (r && r.length > 0)
355
+ if (this.publishEventErrors(r), r[0].fieldName) {
356
+ const i = m.t("archbase:errorSavingRecord", { dataSourceName: this.label });
357
+ throw new g(i);
358
+ } else
359
+ throw new g(r[0].errorMessage);
360
+ }
361
+ this.editing && (this.filteredRecords[this.getCurrentIndex()] = this.currentRecord);
362
+ let t = -1;
363
+ return this.records.forEach((r, i) => {
364
+ const s = this.getIdentity ? this.getIdentity(r) : r.id, o = this.getIdentity ? this.getIdentity(this.currentRecord) : this.currentRecord.id;
365
+ (r === this.currentRecord || s !== void 0 && s === o) && (t = i);
366
+ }), t >= 0 ? this.records[t] = this.currentRecord : this.records.push(this.currentRecord), this.editing = !1, this.inserting = !1, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.emitter.emit("afterSave", this.currentRecord, this.getCurrentIndex()), this.emit({
367
+ type: 17,
368
+ record: this.currentRecord,
369
+ index: this.getCurrentIndex()
370
+ }), e && e(), this.currentRecord;
371
+ }
372
+ cancel() {
373
+ if (this.validateDataSourceActive("cancel"), !this.inserting && !this.editing) {
374
+ const e = m.t("archbase:notAllowCancelRecord", { dataSourceName: this.name });
375
+ throw this.publishEventError(e, {}), new g(e);
376
+ }
377
+ return this.emitter.emit("beforeCancel", this.currentRecord, this.currentRecordIndex), this.emit({
378
+ type: 18,
379
+ record: this.currentRecord,
380
+ index: this.getCurrentIndex()
381
+ }), this.inserting ? (this.filteredRecords.splice(this.currentRecordIndex, 1), this.currentRecord = this.oldRecord, this.currentRecordIndex = this.oldRecordIndex, this.grandTotalRecords--, this.emitter.emit("afterScroll"), this.emit({
382
+ type: 20
383
+ /* afterScroll */
384
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime()) : this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.inserting = !1, this.editing = !1, this.emitter.emit("afterCancel", this.currentRecord, this.currentRecordIndex), this.emit({
385
+ type: 19,
386
+ record: this.currentRecord,
387
+ index: this.getCurrentIndex()
388
+ }), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this;
389
+ }
390
+ getCurrentPage() {
391
+ return this.currentPageIndex;
392
+ }
393
+ getTotalPages() {
394
+ return this.totalPages;
395
+ }
396
+ getTotalRecords() {
397
+ return this.filteredRecords.length;
398
+ }
399
+ getGrandTotalRecords() {
400
+ return this.grandTotalRecords;
401
+ }
402
+ getFieldValue(e, t = "") {
403
+ if (this.validateDataSourceActive("getFieldValue"), !e) {
404
+ const s = m.t("archbase:invalidFieldName", { dataSourceName: this.name });
405
+ throw this.publishEventError(s, {}), new g(s);
406
+ }
407
+ if (this.isEmpty() || this.isBOF() || this.isEOF() && !this.inserting)
408
+ return;
409
+ let r = this.filteredRecords[this.currentRecordIndex];
410
+ this.editing && (r = this.currentRecord);
411
+ let i = this.fieldValueByName(r, e);
412
+ return i === void 0 && t !== void 0 && (i = t), i;
413
+ }
414
+ fieldValueByName(e, t) {
415
+ if (e === void 0)
416
+ return;
417
+ const r = ye.getNestedProperty(e, t);
418
+ if (r !== void 0)
419
+ return we(r) ? Ee(r) : r;
420
+ }
421
+ setFieldValue(e, t) {
422
+ if (this.validateDataSourceActive("setFieldValue"), this.isEmpty() || !this.currentRecord)
423
+ return this;
424
+ if (!(this.inserting || this.editing || this.isBOF() || this.isEOF())) {
425
+ const o = m.t("archbase:recordNotBeingEdited", { dataSourceName: this.name });
426
+ throw this.publishEventError(o, {}), new g(o);
427
+ }
428
+ let r = t;
429
+ const i = ye.getNestedProperty(this.currentRecord, e);
430
+ return we(t) && (r = Ee(t)), e.split(".").length > 1 ? ye.setNestedProperty(this.currentRecord, e, r) : this.currentRecord[e] = r, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.emitFieldChangeEvent(e, i, r), this.emitter.emit("fieldChanged", this.currentRecord, this.getCurrentIndex(), e, i, r), this.emit({
431
+ type: 3,
432
+ record: this.currentRecord,
433
+ index: this.getCurrentIndex(),
434
+ fieldName: e,
435
+ oldValue: i,
436
+ newValue: r
437
+ }), this;
438
+ }
439
+ isEmptyField(e) {
440
+ return this.validateDataSourceActive("isEmptyField"), this.getFieldValue(e) === void 0 || this.getFieldValue(e, "") === "";
441
+ }
442
+ getOptions() {
443
+ return {
444
+ pageSize: this.getPageSize(),
445
+ currentPage: this.getCurrentPage(),
446
+ records: this.records,
447
+ filters: this.filters,
448
+ grandTotalRecords: this.getGrandTotalRecords(),
449
+ totalPages: this.getTotalPages(),
450
+ filter: this.filter,
451
+ sort: this.sort,
452
+ originFilter: this.originFilter,
453
+ originSort: this.originSort,
454
+ originGlobalFilter: this.originGlobalFilter
455
+ };
456
+ }
457
+ refreshData(e) {
458
+ if (e)
459
+ this.emitter.emit("refreshData", e), this.emit({ type: 2, options: e });
460
+ else {
461
+ const t = this.getOptions();
462
+ this.emitter.emit("refreshData", t), this.emit({ type: 2, options: t });
463
+ }
464
+ this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
465
+ }
466
+ browseRecords() {
467
+ return this.filteredRecords;
468
+ }
469
+ getCurrentIndex() {
470
+ return this.currentRecordIndex;
471
+ }
472
+ getCurrentRecord() {
473
+ return this.currentRecord;
474
+ }
475
+ isEOF() {
476
+ return this.currentRecordIndex > this.getTotalRecords() - 1 || this.isEmpty();
477
+ }
478
+ isBOF() {
479
+ return this.currentRecordIndex === -1;
480
+ }
481
+ isEmpty() {
482
+ return this.getTotalRecords() === 0;
483
+ }
484
+ isFirst() {
485
+ return this.currentRecordIndex === 0;
486
+ }
487
+ isLast() {
488
+ return this.currentRecordIndex === this.getTotalRecords() - 1;
489
+ }
490
+ next() {
491
+ if (this.validateDataSourceActive("next"), this.inserting || this.editing || this.isBOF() || this.isEOF()) {
492
+ const e = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
493
+ throw this.publishEventError(e, {}), new g(e);
494
+ }
495
+ return this.currentRecordIndex + 1 > this.getTotalRecords() - 1 ? (this.currentRecordIndex++, this.currentRecord = void 0) : (this.currentRecordIndex++, this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.emitter.emit("afterScroll"), this.emit({
496
+ type: 20
497
+ /* afterScroll */
498
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime()), this;
499
+ }
500
+ prior() {
501
+ if (this.validateDataSourceActive("prior"), this.inserting || this.editing || this.isBOF() || this.isEOF()) {
502
+ const e = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
503
+ throw this.publishEventError(e, {}), new g(e);
504
+ }
505
+ return this.currentRecordIndex - 1 < 0 ? (this.currentRecordIndex = -1, this.currentRecord = void 0) : (this.currentRecordIndex--, this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.emitter.emit("afterScroll"), this.emit({
506
+ type: 20
507
+ /* afterScroll */
508
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime()), this;
509
+ }
510
+ first() {
511
+ if (this.validateDataSourceActive("first"), this.inserting || this.editing) {
512
+ const e = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
513
+ throw this.publishEventError(e, {}), new g(e);
514
+ }
515
+ return this.getTotalRecords() === 0 ? (this.currentRecordIndex = -1, this.currentRecord = void 0) : (this.currentRecordIndex = 0, this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.emitter.emit("afterScroll"), this.emit({
516
+ type: 20
517
+ /* afterScroll */
518
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime()), this;
519
+ }
520
+ last() {
521
+ if (this.validateDataSourceActive("last"), this.inserting || this.editing) {
522
+ const e = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
523
+ throw this.publishEventError(e, {}), new g(e);
524
+ }
525
+ return this.getTotalRecords() === 0 ? (this.currentRecordIndex = -1, this.currentRecord = void 0) : (this.currentRecordIndex = this.getTotalRecords() - 1, this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.emitter.emit("afterScroll"), this.emit({
526
+ type: 20
527
+ /* afterScroll */
528
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime()), this;
529
+ }
530
+ gotoRecord(e) {
531
+ if (e === this.currentRecordIndex)
532
+ return this.currentRecord;
533
+ if (this.validateDataSourceActive("gotoRecord"), this.inserting || this.editing || this.isBOF() || this.isEOF()) {
534
+ const t = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
535
+ throw this.publishEventError(t, {}), new g(t);
536
+ }
537
+ if (e < 0 || e >= this.filteredRecords.length) {
538
+ const t = "Indice fora da faixa.";
539
+ throw this.publishEventError(t, {}), new g(t);
540
+ }
541
+ return this.currentRecordIndex = e, this.currentRecord = this.filteredRecords[this.currentRecordIndex], this.emitter.emit("afterScroll"), this.emit({
542
+ type: 20
543
+ /* afterScroll */
544
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.currentRecord;
545
+ }
546
+ gotoRecordByData(e) {
547
+ if (this.validateDataSourceActive("gotoRecordByData"), this.inserting || this.editing || this.isBOF() || this.isEOF()) {
548
+ const r = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
549
+ throw this.publishEventError(r, {}), new g(r);
550
+ }
551
+ if (this.isEmpty())
552
+ return !1;
553
+ if (this.currentRecord === e)
554
+ return this.emitter.emit("afterScroll"), this.emit({
555
+ type: 20
556
+ /* afterScroll */
557
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), !0;
558
+ let t = !1;
559
+ return this.filteredRecords.forEach((r, i) => {
560
+ e === r && (this.currentRecordIndex = i, this.currentRecord = r, this.emitter.emit("afterScroll"), this.emit({
561
+ type: 20
562
+ /* afterScroll */
563
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), t = !0);
564
+ }), t;
565
+ }
566
+ locate(e) {
567
+ if (!this.isBrowsing()) {
568
+ const i = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
569
+ throw this.publishEventError(i, {}), new g(i);
570
+ }
571
+ if (this.isEmpty())
572
+ return !1;
573
+ let t = -1, r = -1;
574
+ return this.records.forEach((i) => {
575
+ r++;
576
+ for (const s in e)
577
+ this.fieldValueByName(i, s) === e[s] && (t = r);
578
+ }), t >= 0 && this.gotoRecord(t), t >= 0;
579
+ }
580
+ locateByFilter(e) {
581
+ if (this.validateDataSourceActive("locate"), this.inserting || this.editing) {
582
+ const r = m.t("archbase:notAllowedBrowseRecords", { dataSourceName: this.name });
583
+ throw this.publishEventError(r, {}), new g(r);
584
+ }
585
+ if (this.isEmpty())
586
+ return !1;
587
+ const t = this.filteredRecords.findIndex(e);
588
+ return t !== -1 && this.gotoRecord(t), t >= 0;
589
+ }
590
+ addListener(e) {
591
+ return this.listeners.has(e) || this.listeners.add(e), this;
592
+ }
593
+ removeListener(e) {
594
+ return this.listeners.has(e) && this.listeners.delete(e), this;
595
+ }
596
+ on(e, t) {
597
+ this.emitter.on(e, t);
598
+ }
599
+ off(e, t) {
600
+ this.emitter.off(e, t);
601
+ }
602
+ addFieldChangeListener(e, t) {
603
+ const r = e.split(".");
604
+ let i = "";
605
+ return r.forEach((s, o) => {
606
+ i = o === 0 ? s : `${i}.${s}`, this.fieldEventListeners[`field:${i}`] || (this.fieldEventListeners[`field:${i}`] = []), this.fieldEventListeners[`field:${i}`].includes(t) || this.fieldEventListeners[`field:${i}`].push(t);
607
+ }), this;
608
+ }
609
+ removeFieldChangeListener(e, t) {
610
+ const r = e.split(".");
611
+ let i = "";
612
+ return r.forEach((s, o) => {
613
+ i = o === 0 ? s : `${i}.${s}`;
614
+ const c = this.fieldEventListeners[`field:${i}`];
615
+ if (c) {
616
+ const f = c.indexOf(t);
617
+ f !== -1 && c.splice(f, 1);
618
+ }
619
+ }), this;
620
+ }
621
+ emitFieldChangeEvent(e, t, r) {
622
+ const i = e.split(".");
623
+ let s = "";
624
+ for (const o of i) {
625
+ s = s ? `${s}.${o}` : o;
626
+ const c = this.fieldEventListeners[`field:${s}`];
627
+ c && c.forEach((f) => f(s, t, r));
628
+ }
629
+ }
630
+ /**
631
+ * Define um erro para um campo específico
632
+ * @param fieldName Nome do campo
633
+ * @param errors Array de mensagens de erro
634
+ */
635
+ setFieldError(e, t) {
636
+ t && t.length > 0 && (this.emitter.emit("onFieldError", e, t[0]), this.emit({
637
+ type: 22,
638
+ fieldName: e,
639
+ error: t[0],
640
+ originalError: t
641
+ }));
642
+ }
643
+ }
644
+ class Ce extends Ie {
645
+ service;
646
+ constructor(e, t, r, i) {
647
+ super(t, r, i), this.service = e;
648
+ }
649
+ async save(e) {
650
+ if (this.validateDataSourceActive("save"), !this.inserting && !this.editing) {
651
+ const t = m.t("archbase:saveRecordIsNotAllowed", { dataSourceName: this.name });
652
+ throw this.publishEventError(t, {}), new g(t);
653
+ }
654
+ if (!this.currentRecord) {
655
+ const t = m.t("archbase:noRecordToSave", { dataSourceName: this.name });
656
+ throw this.publishEventError(t, {}), new g(t);
657
+ }
658
+ if (this.emitter.emit("beforeSave", this.currentRecord), this.emit({
659
+ type: d.beforeSave,
660
+ record: this.currentRecord,
661
+ index: this.getCurrentIndex()
662
+ }), this.validator) {
663
+ const t = this.validator.validateEntity(this.currentRecord);
664
+ if (t && t.length > 0)
665
+ if (this.publishEventErrors(t), t[0].fieldName) {
666
+ const r = m.t("archbase:errorSavingRecord", { dataSourceName: this.label });
667
+ throw new g(r);
668
+ } else
669
+ throw new g(t[0].errorMessage);
670
+ }
671
+ try {
672
+ let t = -1;
673
+ this.records.forEach((r, i) => {
674
+ const s = this.getIdentity ? this.getIdentity(r) : r.id, o = this.getIdentity ? this.getIdentity(this.currentRecord) : this.currentRecord.id;
675
+ (r === this.currentRecord || s !== void 0 && s === o) && (t = i);
676
+ }), this.currentRecord = await this.service.save(this.currentRecord), this.editing && (this.filteredRecords = [...this.filteredRecords], this.filteredRecords[this.getCurrentIndex()] = this.currentRecord), this.records = [...this.records], t >= 0 ? this.records[t] = this.currentRecord : this.records.push(this.currentRecord), this.editing = !1, this.inserting = !1, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.emitter.emit("afterSave", this.currentRecord), this.emit({
677
+ type: d.afterSave,
678
+ record: this.currentRecord,
679
+ index: this.getCurrentIndex()
680
+ }), e && e();
681
+ } catch (t) {
682
+ t.response && t.response.data && t.response.data.apierror && t.response.data.apierror.subErrors && t.response.data.apierror.subErrors.forEach((i) => {
683
+ if (i.field) {
684
+ const s = m.t(i.message, { defaultValue: i.message });
685
+ this.emitter.emit("onFieldError", i.field, s), this.emit({
686
+ type: d.onFieldError,
687
+ fieldName: i.field,
688
+ error: s,
689
+ originalError: i.message
690
+ });
691
+ }
692
+ });
693
+ const r = k(t);
694
+ throw this.emitter.emit("onError", r, t), this.emit({
695
+ type: d.onError,
696
+ error: r,
697
+ originalError: t
698
+ }), e && e(r), new g(r);
699
+ }
700
+ return this.currentRecord;
701
+ }
702
+ async remove(e) {
703
+ if (this.validateDataSourceActive("remove"), this.inserting || this.editing) {
704
+ const t = m.t("archbase:removingRecordIsNotAllowed", { dataSourceName: this.name });
705
+ throw this.publishEventError(t, {}), new g(
706
+ t
707
+ );
708
+ }
709
+ if (this.isEmpty() || !this.currentRecord) {
710
+ const t = m.t("archbase:noRecordsToEdit", { dataSourceName: this.name });
711
+ throw this.publishEventError(t, {}), new g(t);
712
+ }
713
+ if (this.isBOF()) {
714
+ const t = m.t("archbase:BOFDataSource", { dataSourceName: this.name });
715
+ throw this.publishEventError(t, {}), new g(t);
716
+ }
717
+ if (this.isEOF()) {
718
+ const t = m.t("archbase:EOFDataSource", { dataSourceName: this.name });
719
+ throw this.publishEventError(t, {}), new g(t);
720
+ }
721
+ this.emitter.emit("beforeRemove", this.currentRecord, this.currentRecordIndex), this.emit({
722
+ type: d.beforeRemove,
723
+ record: this.currentRecord,
724
+ index: this.getCurrentIndex()
725
+ });
726
+ try {
727
+ await this.service.delete(this.service.getId(this.currentRecord));
728
+ let t = -1;
729
+ const r = this.currentRecord, i = this.currentRecordIndex;
730
+ return this.records = [...this.records], this.filteredRecords = [...this.filteredRecords], this.records.forEach((s, o) => {
731
+ this.currentRecord === s && (t = o);
732
+ }), t >= 0 && this.records.splice(t, 1), this.records !== this.filteredRecords && this.filteredRecords.splice(this.getCurrentIndex(), 1), this.grandTotalRecords--, this.filteredRecords.length === 0 ? (this.currentRecord = void 0, this.currentRecordIndex = -1) : (this.currentRecordIndex > this.filteredRecords.length - 1 && this.currentRecordIndex--, this.currentRecord = this.filteredRecords[this.currentRecordIndex]), this.editing = !1, this.inserting = !1, this.emitter.emit("afterScroll"), this.emit({ type: d.afterScroll }), this.emitter.emit("afterRemove", r, i), this.emit({
733
+ type: d.afterRemove,
734
+ record: r,
735
+ index: i
736
+ }), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), e && e(), r;
737
+ } catch (t) {
738
+ const r = k(t);
739
+ throw this.emitter.emit("onError", r, t), this.emit({
740
+ type: d.onError,
741
+ error: r,
742
+ originalError: t
743
+ }), e && e(r), new g(r);
744
+ }
745
+ }
746
+ applyRemoteFilter(e, t, r) {
747
+ return e && e.filter.filterType === Se && e.filter.quickFilterText && e.filter.quickFilterText !== "" ? this.getDataWithQuickFilter(e, t) : e && (e.filter.filterType === Fe || e.filter.filterType === Ae) ? this.getDataWithFilter(e, t) : this.getDataWithoutFilter(t);
748
+ }
749
+ async getDataWithFilter(e, t) {
750
+ const r = new xe();
751
+ r.buildFrom(e.filter, e.sort);
752
+ const i = r.toJSON();
753
+ let s;
754
+ return i ? s = await this.service.findAllWithFilter(i, t, this.getPageSize()) : s = this.getDataWithoutFilter(t), s;
755
+ }
756
+ getDataWithoutFilter(e) {
757
+ let t;
758
+ return this.defaultSortFields.length > 0 ? t = this.service.findAllWithSort(e, this.getPageSize(), this.defaultSortFields) : t = this.service.findAll(e, this.getPageSize()), t;
759
+ }
760
+ getDataWithQuickFilter(e, t) {
761
+ return this.service.findAllMultipleFields(
762
+ e.filter.quickFilterText,
763
+ e.filter.quickFilterFieldsText,
764
+ t,
765
+ this.getPageSize(),
766
+ this.getSortFields(e)
767
+ );
768
+ }
769
+ getSortFields(e) {
770
+ return e && e.sort ? e.sort.quickFilterSort : this.defaultSortFields;
771
+ }
772
+ }
773
+ class Ge {
774
+ id;
775
+ companyId;
776
+ filter;
777
+ name;
778
+ description;
779
+ viewName;
780
+ componentName;
781
+ componentId;
782
+ userName;
783
+ userOwner;
784
+ shared;
785
+ readOnly;
786
+ code;
787
+ constructor(e = {}) {
788
+ Object.assign(this, e);
789
+ }
790
+ }
791
+ class ke extends Ie {
792
+ getFilterById(e) {
793
+ if (this.locate({ id: e }))
794
+ return this.convertCurrentRecordToFilter();
795
+ }
796
+ convertCurrentRecordToFilter() {
797
+ return new ue({
798
+ id: this.getFieldValue("id"),
799
+ name: this.getFieldValue("name"),
800
+ description: this.getFieldValue("description"),
801
+ companyId: this.getFieldValue("companyId"),
802
+ componentId: this.getFieldValue("componentId") || this.getFieldValue("componentName"),
803
+ userOwner: this.getFieldValue("userOwner") || this.getFieldValue("userName"),
804
+ shared: this.getFieldValue("shared"),
805
+ readOnly: this.getFieldValue("readOnly"),
806
+ filter: this.getFieldValue("filter") ? atob(this.getFieldValue("filter")) : void 0
807
+ });
808
+ }
809
+ async addNewFilter(e, t) {
810
+ this.insert(
811
+ new Ge({
812
+ id: e.id,
813
+ name: e.name,
814
+ description: e.description,
815
+ companyId: e.companyId,
816
+ componentId: e.componentId,
817
+ componentName: e.componentId,
818
+ userOwner: e.userOwner,
819
+ userName: e.userOwner,
820
+ filter: e.filter ? btoa(JSON.stringify(e.filter)) : void 0,
821
+ shared: e.shared,
822
+ readOnly: e.readOnly
823
+ })
824
+ );
825
+ const r = await this.save();
826
+ t(null, r.id);
827
+ }
828
+ async saveFilter(e, t) {
829
+ if (this.locate({ id: e.id })) {
830
+ this.edit(), this.setFieldValue("filter", btoa(JSON.stringify(e.filter)));
831
+ const r = await this.save();
832
+ t(null, r.id);
833
+ } else
834
+ t("Filtro não encontrado.");
835
+ }
836
+ async removeFilterBy(e, t) {
837
+ this.locate({ id: e.id }) ? (await this.remove(), t(null, e.id)) : t("Filtro não encontrado.");
838
+ }
839
+ getFirstFilter() {
840
+ if (this.getTotalRecords() > 0)
841
+ return this.first(), this.convertCurrentRecordToFilter();
842
+ }
843
+ getFilters() {
844
+ return this.getTotalRecords() > 0 ? this.browseRecords().map(
845
+ (e) => new ue({
846
+ id: e.id,
847
+ name: e.name,
848
+ description: e.description,
849
+ companyId: e.companyId,
850
+ componentId: e.componentId || e.componentName,
851
+ userOwner: e.userOwner || e.userName,
852
+ shared: e.shared,
853
+ readOnly: e.readOnly,
854
+ filter: e.filter ? atob(e.filter) : void 0
855
+ })
856
+ ) : [];
857
+ }
858
+ }
859
+ class qe {
860
+ id;
861
+ companyId;
862
+ filter;
863
+ name;
864
+ description;
865
+ viewName;
866
+ componentName;
867
+ componentId;
868
+ userName;
869
+ userOwner;
870
+ shared;
871
+ readOnly;
872
+ code;
873
+ isNewFilter;
874
+ constructor(e = {}) {
875
+ Object.assign(this, e);
876
+ }
877
+ }
878
+ class _e extends Ce {
879
+ getFilterById(e) {
880
+ if (this.locate({ id: e }))
881
+ return this.convertCurrentRecordToFilter();
882
+ }
883
+ convertCurrentRecordToFilter() {
884
+ return new ue({
885
+ id: this.getFieldValue("id"),
886
+ name: this.getFieldValue("name"),
887
+ description: this.getFieldValue("description"),
888
+ companyId: this.getFieldValue("companyId"),
889
+ componentId: this.getFieldValue("componentId") || this.getFieldValue("componentName"),
890
+ userOwner: this.getFieldValue("userOwner") || this.getFieldValue("userName"),
891
+ shared: this.getFieldValue("shared"),
892
+ readOnly: this.getFieldValue("readOnly"),
893
+ filter: this.getFieldValue("filter") ? atob(this.getFieldValue("filter")) : void 0
894
+ });
895
+ }
896
+ async addNewFilter(e, t) {
897
+ this.insert(
898
+ new qe({
899
+ id: e.id,
900
+ name: e.name,
901
+ description: e.description,
902
+ companyId: e.companyId,
903
+ componentId: e.componentId,
904
+ componentName: e.componentId,
905
+ userOwner: e.userOwner,
906
+ userName: e.userOwner,
907
+ filter: e.filter ? btoa(JSON.stringify(e.filter)) : void 0,
908
+ shared: e.shared,
909
+ readOnly: e.readOnly
910
+ })
911
+ );
912
+ const r = await this.save();
913
+ t(null, r.id);
914
+ }
915
+ async saveFilter(e, t) {
916
+ if (this.locate({ id: e.id })) {
917
+ this.edit(), this.setFieldValue("filter", btoa(JSON.stringify(e.filter)));
918
+ const r = await this.save((i) => {
919
+ t(i, r.id);
920
+ });
921
+ } else
922
+ t("Filtro não encontrado.");
923
+ }
924
+ async removeFilterBy(e, t) {
925
+ this.locate({ id: e.id }) ? await this.remove((r) => {
926
+ t(r, e.id);
927
+ }) : t("Filtro não encontrado.");
928
+ }
929
+ getFirstFilter() {
930
+ if (this.getTotalRecords() > 0)
931
+ return this.first(), this.convertCurrentRecordToFilter();
932
+ }
933
+ getFilters() {
934
+ return this.getTotalRecords() > 0 ? this.browseRecords().map(
935
+ (e) => new ue({
936
+ id: e.id,
937
+ name: e.name,
938
+ description: e.description,
939
+ companyId: e.companyId,
940
+ componentId: e.componentId || e.componentName,
941
+ userOwner: e.userOwner || e.userName,
942
+ shared: e.shared,
943
+ readOnly: e.readOnly,
944
+ filter: e.filter ? atob(e.filter) : void 0
945
+ })
946
+ ) : [];
947
+ }
948
+ }
949
+ function pt(n, e, t, r) {
950
+ const i = e && ("appendToFieldArray" in e || "updateFieldArrayItem" in e), [s, o] = C(r), [, c] = C(0), f = l(() => {
951
+ c((u) => u + 1);
952
+ }, []), [R, b] = C(r), [N, W] = C(0), T = l(() => {
953
+ let u = r;
954
+ e && t && (u = e.getFieldValue(t), u == null && (u = r)), i ? (b(u), W((a) => a + 1)) : o(u);
955
+ }, [e, t, r, i]), O = l((u) => {
956
+ e && t && ((u.type === d.dataChanged || u.type === d.recordChanged || u.type === d.afterScroll || u.type === d.afterCancel || u.type === d.afterEdit) && (T(), i || f()), u.type === d.onFieldError && u.fieldName === t && console.warn(`[${n}] Field error:`, u.error));
957
+ }, [e, t, T, f, i, n]), $ = l((u, a) => {
958
+ i ? (b(u), e && !e.isBrowsing() && t && e.getFieldValue(t) !== u && e.setFieldValue(t, u)) : (o(u), e && !e.isBrowsing() && t && e.getFieldValue(t) !== u && e.setFieldValue(t, u));
959
+ }, [e, t, i]), z = l(() => {
960
+ const u = ve(e);
961
+ Ne.trackV2Usage(n, u);
962
+ }, [n, e]);
963
+ return le(() => {
964
+ process.env.NODE_ENV === "production" && z();
965
+ }).current, {
966
+ // Detecção de versão
967
+ isDataSourceV2: i,
968
+ dataSourceVersion: ve(e),
969
+ // Estados
970
+ currentValue: i ? R : s,
971
+ v1State: { currentValue: s, setCurrentValue: o, forceUpdate: f },
972
+ v2State: { v2Value: R, setV2Value: b, v2ShouldUpdate: N },
973
+ // Funções
974
+ loadDataSourceFieldValue: T,
975
+ dataSourceEvent: O,
976
+ handleValueChange: $,
977
+ // Utilitários
978
+ isReadOnly: e ? e.isBrowsing() : !1,
979
+ isEditing: e ? e.isEditing() : !1,
980
+ trackUsage: z
981
+ };
982
+ }
983
+ const yt = {
984
+ /**
985
+ * Valida se o componente está seguindo o padrão corretamente
986
+ */
987
+ validatePattern: (n, e) => {
988
+ const t = [];
989
+ return e.dataSourceVersion === "NONE" && e.isDataSourceV2 && t.push("DataSource version detection inconsistent"), e.isDataSourceV2 && e.v1State.currentValue === e.currentValue && t.push("V2 should use v2Value, not v1 currentValue"), !e.isDataSourceV2 && e.v2State.v2Value === e.currentValue && t.push("V1 should use currentValue, not v2Value"), t.length > 0 ? (console.error(`[${n}] Migration pattern validation failed:`, t), !1) : !0;
990
+ },
991
+ /**
992
+ * Testa se o comportamento V1 está preservado
993
+ */
994
+ testV1Compatibility: (n, e) => !e || ve(e) !== "V1" || [
995
+ "isBrowsing",
996
+ "isEditing",
997
+ "getFieldValue",
998
+ "setFieldValue"
999
+ ].every((r) => typeof e[r] == "function") ? !0 : (console.error(`[${n}] V1 DataSource missing required methods`), !1)
1000
+ }, vt = `
1001
+ // Em qualquer componente que use DataSource:
1002
+
1003
+ import { useArchbaseV1V2Compatibility } from '../core/patterns/ArchbaseV1V2CompatibilityPattern';
1004
+
1005
+ export function MyComponent<T, ID>({ dataSource, dataField, value, onChangeValue, ...props }) {
1006
+ // 1. USAR HOOK DE COMPATIBILIDADE (OBRIGATÓRIO)
1007
+ const {
1008
+ isDataSourceV2,
1009
+ currentValue,
1010
+ handleValueChange,
1011
+ dataSourceEvent,
1012
+ loadDataSourceFieldValue,
1013
+ isReadOnly
1014
+ } = useArchbaseV1V2Compatibility<T>(
1015
+ 'MyComponent',
1016
+ dataSource,
1017
+ dataField,
1018
+ value
1019
+ );
1020
+
1021
+ // 2. SETUP DOS LISTENERS (OBRIGATÓRIO)
1022
+ useArchbaseDataSourceListener({
1023
+ dataSource,
1024
+ listener: dataSourceEvent
1025
+ });
1026
+
1027
+ // 3. CARREGAMENTO INICIAL (OBRIGATÓRIO)
1028
+ useEffect(() => {
1029
+ loadDataSourceFieldValue();
1030
+ }, [loadDataSourceFieldValue]);
1031
+
1032
+ // 4. HANDLER DE MUDANÇA (OBRIGATÓRIO)
1033
+ const handleChange = useCallback((newValue: T, event: any) => {
1034
+ handleValueChange(newValue, event);
1035
+
1036
+ // Callback externo preservado
1037
+ if (onChangeValue) {
1038
+ onChangeValue(newValue, event);
1039
+ }
1040
+ }, [handleValueChange, onChangeValue]);
1041
+
1042
+ // 5. RENDERIZAÇÃO CONDICIONAL (OBRIGATÓRIO)
1043
+ return (
1044
+ <SomeInput
1045
+ value={currentValue} // Usa valor correto baseado na versão
1046
+ onChange={handleChange}
1047
+ readOnly={isReadOnly}
1048
+ {...props}
1049
+ />
1050
+ );
1051
+ }
1052
+ `;
1053
+ class U {
1054
+ name;
1055
+ label;
1056
+ records = [];
1057
+ currentIndex = -1;
1058
+ state = "browse";
1059
+ listeners = /* @__PURE__ */ new Set();
1060
+ originalRecord = null;
1061
+ validator;
1062
+ lastDataChangedAt = 0;
1063
+ active = !0;
1064
+ // Callbacks V2
1065
+ onStateChange;
1066
+ onFieldError;
1067
+ onError;
1068
+ constructor(e) {
1069
+ this.name = e.name, this.label = e.label || e.name, this.validator = e.validator, this.onStateChange = e.onStateChange, this.onFieldError = e.onFieldError, this.onError = e.onError, e.records && (this.records = [...e.records], this.records.length > 0 && (this.currentIndex = 0)), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime();
1070
+ }
1071
+ // =================== Basic Properties ===================
1072
+ getName() {
1073
+ return this.name;
1074
+ }
1075
+ getLabel() {
1076
+ return this.label;
1077
+ }
1078
+ isActive() {
1079
+ return this.active;
1080
+ }
1081
+ close() {
1082
+ this.active = !1, this.listeners.clear();
1083
+ }
1084
+ // =================== Record Management ===================
1085
+ getCurrentRecord() {
1086
+ if (this.currentIndex >= 0 && this.currentIndex < this.records.length)
1087
+ return this.records[this.currentIndex];
1088
+ }
1089
+ getCurrentIndex() {
1090
+ return this.currentIndex;
1091
+ }
1092
+ getTotalRecords() {
1093
+ return this.records.length;
1094
+ }
1095
+ isEmpty() {
1096
+ return this.records.length === 0;
1097
+ }
1098
+ // =================== Navigation ===================
1099
+ first() {
1100
+ return this.records.length > 0 && (this.currentIndex = 0, this.emit({
1101
+ type: d.afterScroll
1102
+ })), this;
1103
+ }
1104
+ last() {
1105
+ return this.records.length > 0 && (this.currentIndex = this.records.length - 1, this.emit({
1106
+ type: d.afterScroll
1107
+ })), this;
1108
+ }
1109
+ next() {
1110
+ return this.currentIndex < this.records.length - 1 && (this.currentIndex++, this.emit({
1111
+ type: d.recordChanged,
1112
+ record: this.getCurrentRecord(),
1113
+ index: this.currentIndex
1114
+ })), this;
1115
+ }
1116
+ prior() {
1117
+ return this.currentIndex > 0 && (this.currentIndex--, this.emit({
1118
+ type: d.recordChanged,
1119
+ record: this.getCurrentRecord(),
1120
+ index: this.currentIndex
1121
+ })), this;
1122
+ }
1123
+ goToRecord(e) {
1124
+ if (e >= 0 && e < this.records.length)
1125
+ return this.currentIndex = e, this.emit({
1126
+ type: d.recordChanged,
1127
+ record: this.getCurrentRecord(),
1128
+ index: this.currentIndex
1129
+ }), this.getCurrentRecord();
1130
+ }
1131
+ isFirst() {
1132
+ return this.currentIndex === 0;
1133
+ }
1134
+ isLast() {
1135
+ return this.currentIndex === this.records.length - 1;
1136
+ }
1137
+ isBOF() {
1138
+ return this.currentIndex < 0;
1139
+ }
1140
+ isEOF() {
1141
+ return this.currentIndex >= this.records.length;
1142
+ }
1143
+ // =================== State Management ===================
1144
+ isBrowsing() {
1145
+ return this.state === "browse";
1146
+ }
1147
+ isEditing() {
1148
+ return this.state === "edit";
1149
+ }
1150
+ isInserting() {
1151
+ return this.state === "insert";
1152
+ }
1153
+ edit() {
1154
+ if (this.validateDataSourceActive("edit"), this.isEmpty() || !this.getCurrentRecord())
1155
+ throw new Error(`No records to edit in DataSource ${this.name}`);
1156
+ return this.state = "edit", this.originalRecord = JSON.parse(JSON.stringify(this.getCurrentRecord())), this.emit({
1157
+ type: d.beforeEdit,
1158
+ record: this.getCurrentRecord(),
1159
+ index: this.currentIndex
1160
+ }), this.emit({
1161
+ type: d.afterEdit,
1162
+ record: this.getCurrentRecord(),
1163
+ index: this.currentIndex
1164
+ }), this;
1165
+ }
1166
+ cancel() {
1167
+ return this.validateDataSourceActive("cancel"), this.state === "edit" && this.originalRecord ? (this.records = [...this.records], this.records[this.currentIndex] = { ...this.originalRecord }) : this.state === "insert" && (this.records = this.records.slice(0, -1), this.records.length > 0 ? this.currentIndex = Math.min(this.currentIndex, this.records.length - 1) : this.currentIndex = -1), this.state = "browse", this.originalRecord = null, this.emit({
1168
+ type: d.afterCancel,
1169
+ record: this.getCurrentRecord(),
1170
+ index: this.currentIndex
1171
+ }), this;
1172
+ }
1173
+ insert(e) {
1174
+ return this.validateDataSourceActive("insert"), this.state = "insert", this.emit({
1175
+ type: d.beforeInsert
1176
+ }), this.records = [...this.records, e], this.currentIndex = this.records.length - 1, this.notifyStateChange(), this.emit({
1177
+ type: d.afterInsert,
1178
+ record: e,
1179
+ index: this.currentIndex
1180
+ }), this;
1181
+ }
1182
+ async save(e) {
1183
+ if (this.validateDataSourceActive("save"), !this.isInserting() && !this.isEditing())
1184
+ throw new Error(`Save not allowed in current state for DataSource ${this.name}`);
1185
+ if (!this.getCurrentRecord())
1186
+ throw new Error(`No record to save in DataSource ${this.name}`);
1187
+ const t = this.getCurrentRecord();
1188
+ if (this.emit({
1189
+ type: d.beforeSave,
1190
+ record: t,
1191
+ index: this.getCurrentIndex()
1192
+ }), this.validator) {
1193
+ const r = this.validator.validateEntity(t);
1194
+ if (r && r.length > 0)
1195
+ throw new Error(r[0].errorMessage);
1196
+ }
1197
+ return this.state = "browse", this.originalRecord = null, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.notifyStateChange(), this.emit({
1198
+ type: d.afterSave,
1199
+ record: t,
1200
+ index: this.getCurrentIndex()
1201
+ }), e && e(), t;
1202
+ }
1203
+ async remove(e) {
1204
+ if (this.validateDataSourceActive("remove"), this.isInserting() || this.isEditing())
1205
+ throw new Error(`Remove not allowed in current state for DataSource ${this.name}`);
1206
+ if (this.isEmpty() || !this.getCurrentRecord())
1207
+ throw new Error(`No records to remove in DataSource ${this.name}`);
1208
+ const t = this.getCurrentRecord(), r = this.currentIndex;
1209
+ return this.emit({
1210
+ type: d.beforeRemove,
1211
+ record: t,
1212
+ index: r
1213
+ }), this.records = this.records.filter((i, s) => s !== this.currentIndex), this.records.length === 0 ? this.currentIndex = -1 : this.currentIndex >= this.records.length && (this.currentIndex = this.records.length - 1), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.notifyStateChange(), this.emit({ type: d.afterScroll }), this.emit({
1214
+ type: d.afterRemove,
1215
+ record: t,
1216
+ index: r
1217
+ }), e && e(), t;
1218
+ }
1219
+ // =================== Field Operations ===================
1220
+ setFieldValue(e, t) {
1221
+ if (this.validateDataSourceActive("setFieldValue"), !this.getCurrentRecord())
1222
+ return this;
1223
+ const r = this.getFieldValue(e);
1224
+ if (r === t)
1225
+ return this;
1226
+ const i = [...this.records];
1227
+ return this.records = _(this.records, (s) => {
1228
+ const o = s[this.currentIndex];
1229
+ o && this.setNestedValue(o, e, t);
1230
+ }), this.notifyStateChange(i), this.emit({
1231
+ type: d.fieldChanged,
1232
+ fieldName: e,
1233
+ oldValue: r,
1234
+ newValue: t,
1235
+ record: this.getCurrentRecord(),
1236
+ index: this.currentIndex
1237
+ }), this.emit({
1238
+ type: d.dataChanged,
1239
+ data: this.records
1240
+ }), this;
1241
+ }
1242
+ getFieldValue(e) {
1243
+ const t = this.getCurrentRecord();
1244
+ if (t)
1245
+ return this.getNestedValue(t, e);
1246
+ }
1247
+ // =================== Array Field Operations (V2) ===================
1248
+ appendToFieldArray(e, t) {
1249
+ if (this.validateDataSourceActive("appendToFieldArray"), !this.getCurrentRecord())
1250
+ return;
1251
+ const r = this.getFieldValue(e);
1252
+ if (r == null) {
1253
+ console.warn(`appendToFieldArray: Field ${String(e)} is undefined/null. Initialize the array in your DTO before using appendToFieldArray.`);
1254
+ return;
1255
+ }
1256
+ if (!Array.isArray(r))
1257
+ throw new Error(`Field ${String(e)} is not an array (found: ${typeof r})`);
1258
+ const i = [...this.records];
1259
+ this.records = _(this.records, (s) => {
1260
+ const o = s[this.currentIndex];
1261
+ if (o) {
1262
+ const c = this.getNestedValue(o, e);
1263
+ c && c.push(t);
1264
+ }
1265
+ }), this.notifyStateChange(i), this.emit({
1266
+ type: d.fieldChanged,
1267
+ fieldName: e,
1268
+ oldValue: r,
1269
+ newValue: [...r, t],
1270
+ record: this.getCurrentRecord(),
1271
+ index: this.currentIndex
1272
+ });
1273
+ }
1274
+ updateFieldArrayItem(e, t, r) {
1275
+ if (this.validateDataSourceActive("updateFieldArrayItem"), !this.getCurrentRecord())
1276
+ return;
1277
+ const i = this.getFieldValue(e);
1278
+ if (!Array.isArray(i) || t < 0 || t >= i.length)
1279
+ return;
1280
+ const s = [...this.records];
1281
+ this.records = _(this.records, (o) => {
1282
+ const c = o[this.currentIndex];
1283
+ if (c) {
1284
+ const f = this.getNestedValue(c, e);
1285
+ f[t] !== void 0 && r(f[t]);
1286
+ }
1287
+ }), this.notifyStateChange(s), this.emit({
1288
+ type: d.fieldChanged,
1289
+ fieldName: e,
1290
+ oldValue: i,
1291
+ newValue: this.getFieldValue(e),
1292
+ record: this.getCurrentRecord(),
1293
+ index: this.currentIndex
1294
+ });
1295
+ }
1296
+ removeFromFieldArray(e, t) {
1297
+ if (this.validateDataSourceActive("removeFromFieldArray"), !this.getCurrentRecord())
1298
+ return;
1299
+ const r = this.getFieldValue(e);
1300
+ if (!Array.isArray(r))
1301
+ throw new Error(`Field ${String(e)} is not an array`);
1302
+ if (t < 0 || t >= r.length)
1303
+ return;
1304
+ const i = [...this.records];
1305
+ this.records = _(this.records, (s) => {
1306
+ const o = s[this.currentIndex];
1307
+ o && this.getNestedValue(o, e).splice(t, 1);
1308
+ }), this.notifyStateChange(i), this.emit({
1309
+ type: d.fieldChanged,
1310
+ fieldName: e,
1311
+ oldValue: r,
1312
+ newValue: this.getFieldValue(e),
1313
+ record: this.getCurrentRecord(),
1314
+ index: this.currentIndex
1315
+ });
1316
+ }
1317
+ insertIntoFieldArray(e, t, r) {
1318
+ if (this.validateDataSourceActive("insertIntoFieldArray"), !this.getCurrentRecord())
1319
+ return;
1320
+ const i = this.getFieldValue(e);
1321
+ if (!Array.isArray(i))
1322
+ throw new Error(`Field ${String(e)} is not an array`);
1323
+ const s = [...this.records];
1324
+ this.records = _(this.records, (o) => {
1325
+ const c = o[this.currentIndex];
1326
+ c && this.getNestedValue(c, e).splice(t, 0, r);
1327
+ }), this.notifyStateChange(s), this.emit({
1328
+ type: d.fieldChanged,
1329
+ fieldName: e,
1330
+ oldValue: i,
1331
+ newValue: this.getFieldValue(e),
1332
+ record: this.getCurrentRecord(),
1333
+ index: this.currentIndex
1334
+ });
1335
+ }
1336
+ getFieldArray(e) {
1337
+ const t = this.getFieldValue(e);
1338
+ return t == null ? [] : Array.isArray(t) ? t : (console.warn(`Field ${String(e)} is not an array (found: ${typeof t}), returning empty array`), []);
1339
+ }
1340
+ isFieldArray(e) {
1341
+ const t = this.getFieldValue(e);
1342
+ return Array.isArray(t);
1343
+ }
1344
+ // =================== Interface Compatibility Methods ===================
1345
+ /**
1346
+ * Abre o DataSource com os dados fornecidos.
1347
+ * Aceita tanto o formato completo DataSourceOptions quanto um formato simplificado { records: T[] }
1348
+ */
1349
+ open(e) {
1350
+ this.setData(e);
1351
+ }
1352
+ clear() {
1353
+ this.records = [], this.currentIndex = -1, this.state = "browse", this.originalRecord = null, this.emit({
1354
+ type: d.dataChanged,
1355
+ data: this.records
1356
+ });
1357
+ }
1358
+ /**
1359
+ * Define os dados do DataSource.
1360
+ * Quando apenas records é informado, os valores de paginação são derivados automaticamente.
1361
+ */
1362
+ setData(e) {
1363
+ this.records = [...e.records || []], this.currentIndex = this.records.length > 0 ? 0 : -1, this.state = "browse", this.originalRecord = null, this.emit({
1364
+ type: d.dataChanged,
1365
+ data: this.records
1366
+ });
1367
+ }
1368
+ getOptions() {
1369
+ return {
1370
+ records: [...this.records],
1371
+ grandTotalRecords: this.records.length,
1372
+ currentPage: 0,
1373
+ totalPages: 1,
1374
+ pageSize: this.records.length || 10
1375
+ };
1376
+ }
1377
+ refreshData(e) {
1378
+ e && this.setData(e);
1379
+ }
1380
+ browseRecords() {
1381
+ return [...this.records];
1382
+ }
1383
+ getGrandTotalRecords() {
1384
+ return this.records.length;
1385
+ }
1386
+ getCurrentPage() {
1387
+ return 0;
1388
+ }
1389
+ getTotalPages() {
1390
+ return 1;
1391
+ }
1392
+ isEmptyField(e) {
1393
+ const t = this.getFieldValue(e);
1394
+ return t == null || t === "";
1395
+ }
1396
+ goToPage(e) {
1397
+ return this;
1398
+ }
1399
+ gotoRecordByData(e) {
1400
+ const t = this.records.findIndex((r) => r === e);
1401
+ return t >= 0 ? (this.currentIndex = t, this.emit({
1402
+ type: d.recordChanged,
1403
+ record: this.getCurrentRecord(),
1404
+ index: this.currentIndex
1405
+ }), !0) : !1;
1406
+ }
1407
+ disabledAllListeners() {
1408
+ return this;
1409
+ }
1410
+ enableAllListeners() {
1411
+ return this;
1412
+ }
1413
+ addFieldChangeListener(e, t) {
1414
+ const r = (i) => {
1415
+ i.type === d.fieldChanged && "fieldName" in i && i.fieldName === e && t(e, i.oldValue, i.newValue);
1416
+ };
1417
+ return this.addListener(r), this;
1418
+ }
1419
+ removeFieldChangeListener(e, t) {
1420
+ return this;
1421
+ }
1422
+ addFilter(e) {
1423
+ return this;
1424
+ }
1425
+ removeFilter(e) {
1426
+ return this;
1427
+ }
1428
+ clearFilters() {
1429
+ return this;
1430
+ }
1431
+ locate(e) {
1432
+ for (let t = 0; t < this.records.length; t++) {
1433
+ const r = this.records[t];
1434
+ let i = !0;
1435
+ for (const [s, o] of Object.entries(e))
1436
+ if (this.getNestedValue(r, s) !== o) {
1437
+ i = !1;
1438
+ break;
1439
+ }
1440
+ if (i)
1441
+ return this.currentIndex = t, this.emit({
1442
+ type: d.recordChanged,
1443
+ record: this.getCurrentRecord(),
1444
+ index: this.currentIndex
1445
+ }), !0;
1446
+ }
1447
+ return !1;
1448
+ }
1449
+ locateByFilter(e) {
1450
+ for (let t = 0; t < this.records.length; t++)
1451
+ if (e(this.records[t]))
1452
+ return this.currentIndex = t, this.emit({
1453
+ type: d.recordChanged,
1454
+ record: this.getCurrentRecord(),
1455
+ index: this.currentIndex
1456
+ }), !0;
1457
+ return !1;
1458
+ }
1459
+ validate() {
1460
+ return !0;
1461
+ }
1462
+ // =================== Event Management ===================
1463
+ addListener(...e) {
1464
+ return e.forEach((t) => this.listeners.add(t)), this;
1465
+ }
1466
+ removeListener(...e) {
1467
+ return e.forEach((t) => this.listeners.delete(t)), this;
1468
+ }
1469
+ emit(e) {
1470
+ this.listeners.forEach((t) => {
1471
+ try {
1472
+ t(e);
1473
+ } catch (r) {
1474
+ console.error("Error in DataSource listener:", r);
1475
+ }
1476
+ });
1477
+ }
1478
+ // =================== Utility Methods ===================
1479
+ getRecords() {
1480
+ return [...this.records];
1481
+ }
1482
+ setRecords(e) {
1483
+ const t = [...this.records];
1484
+ this.records = [...e], e.length > 0 ? this.currentIndex = 0 : this.currentIndex = -1, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.notifyStateChange(t), this.emit({
1485
+ type: d.dataChanged,
1486
+ data: this.records
1487
+ });
1488
+ }
1489
+ // =================== Debug Support ===================
1490
+ getDebugSnapshot() {
1491
+ return {
1492
+ name: this.name,
1493
+ recordCount: this.records.length,
1494
+ currentIndex: this.currentIndex,
1495
+ currentRecord: this.getCurrentRecord(),
1496
+ state: this.state,
1497
+ listeners: this.listeners.size
1498
+ };
1499
+ }
1500
+ // =================== Private Helper Methods ===================
1501
+ validateDataSourceActive(e) {
1502
+ if (!this.active)
1503
+ throw new Error(`DataSource ${this.name} is not active. Cannot perform ${e}`);
1504
+ }
1505
+ notifyStateChange(e) {
1506
+ this.onStateChange && e && this.onStateChange(e, [...this.records]);
1507
+ }
1508
+ setNestedValue(e, t, r) {
1509
+ const i = t.split(".");
1510
+ let s = e;
1511
+ for (let o = 0; o < i.length - 1; o++) {
1512
+ const c = i[o];
1513
+ c in s || (s[c] = {}), s = s[c];
1514
+ }
1515
+ s[i[i.length - 1]] = r;
1516
+ }
1517
+ getNestedValue(e, t) {
1518
+ const r = t.split(".");
1519
+ let i = e;
1520
+ for (const s of r) {
1521
+ if (i == null)
1522
+ return;
1523
+ i = i[s];
1524
+ }
1525
+ return i;
1526
+ }
1527
+ }
1528
+ class Je {
1529
+ name;
1530
+ label;
1531
+ service;
1532
+ records = [];
1533
+ filteredRecords = [];
1534
+ currentIndex = -1;
1535
+ state = "browse";
1536
+ listeners = /* @__PURE__ */ new Set();
1537
+ originalRecord = null;
1538
+ validator;
1539
+ lastDataChangedAt = 0;
1540
+ lastDataBrowsingOn = 0;
1541
+ grandTotalRecords = 0;
1542
+ defaultSortFields = [];
1543
+ pageSize = 20;
1544
+ active = !0;
1545
+ // Callbacks V2
1546
+ onStateChange;
1547
+ onFieldError;
1548
+ onError;
1549
+ constructor(e) {
1550
+ this.name = e.name, this.label = e.label || e.name, this.service = e.service, this.validator = e.validator, this.defaultSortFields = e.defaultSortFields || [], this.pageSize = e.pageSize || 20, this.onStateChange = e.onStateChange, this.onFieldError = e.onFieldError, this.onError = e.onError, e.records && (this.records = [...e.records], this.filteredRecords = [...this.records], this.grandTotalRecords = this.records.length, this.records.length > 0 && (this.currentIndex = 0)), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime();
1551
+ }
1552
+ // =================== Basic Properties ===================
1553
+ getName() {
1554
+ return this.name;
1555
+ }
1556
+ getLabel() {
1557
+ return this.label;
1558
+ }
1559
+ isActive() {
1560
+ return this.active;
1561
+ }
1562
+ close() {
1563
+ this.active = !1, this.listeners.clear();
1564
+ }
1565
+ // =================== Record Management ===================
1566
+ getCurrentRecord() {
1567
+ if (this.currentIndex >= 0 && this.currentIndex < this.filteredRecords.length)
1568
+ return this.filteredRecords[this.currentIndex];
1569
+ }
1570
+ getCurrentIndex() {
1571
+ return this.currentIndex;
1572
+ }
1573
+ getTotalRecords() {
1574
+ return this.filteredRecords.length;
1575
+ }
1576
+ isEmpty() {
1577
+ return this.filteredRecords.length === 0;
1578
+ }
1579
+ // =================== Navigation ===================
1580
+ first() {
1581
+ this.filteredRecords.length > 0 && (this.currentIndex = 0, this.emit({
1582
+ type: d.afterScroll
1583
+ }));
1584
+ }
1585
+ last() {
1586
+ this.filteredRecords.length > 0 && (this.currentIndex = this.filteredRecords.length - 1, this.emit({
1587
+ type: d.afterScroll
1588
+ }));
1589
+ }
1590
+ next() {
1591
+ this.currentIndex < this.filteredRecords.length - 1 && (this.currentIndex++, this.emit({
1592
+ type: d.afterScroll
1593
+ }));
1594
+ }
1595
+ prior() {
1596
+ this.currentIndex > 0 && (this.currentIndex--, this.emit({
1597
+ type: d.afterScroll
1598
+ }));
1599
+ }
1600
+ goToRecord(e) {
1601
+ e >= 0 && e < this.filteredRecords.length && (this.currentIndex = e, this.emit({
1602
+ type: d.afterScroll
1603
+ }));
1604
+ }
1605
+ isFirst() {
1606
+ return this.currentIndex === 0;
1607
+ }
1608
+ isLast() {
1609
+ return this.currentIndex === this.filteredRecords.length - 1;
1610
+ }
1611
+ isBOF() {
1612
+ return this.currentIndex < 0;
1613
+ }
1614
+ isEOF() {
1615
+ return this.currentIndex >= this.filteredRecords.length;
1616
+ }
1617
+ // =================== State Management ===================
1618
+ isBrowsing() {
1619
+ return this.state === "browse";
1620
+ }
1621
+ isEditing() {
1622
+ return this.state === "edit";
1623
+ }
1624
+ isInserting() {
1625
+ return this.state === "insert";
1626
+ }
1627
+ edit() {
1628
+ if (this.validateDataSourceActive("edit"), this.isEmpty() || !this.getCurrentRecord()) {
1629
+ const e = m.t("archbase:noRecordsToEdit", { dataSourceName: this.name });
1630
+ throw this.publishEventError(e, {}), new g(e);
1631
+ }
1632
+ this.state = "edit", this.originalRecord = JSON.parse(JSON.stringify(this.getCurrentRecord())), this.emit({
1633
+ type: d.beforeEdit,
1634
+ record: this.getCurrentRecord(),
1635
+ index: this.currentIndex
1636
+ }), this.emit({
1637
+ type: d.afterEdit,
1638
+ record: this.getCurrentRecord(),
1639
+ index: this.currentIndex
1640
+ });
1641
+ }
1642
+ cancel() {
1643
+ if (this.validateDataSourceActive("cancel"), this.state === "edit" && this.originalRecord) {
1644
+ this.filteredRecords = [...this.filteredRecords], this.filteredRecords[this.currentIndex] = { ...this.originalRecord };
1645
+ const e = this.service.getId(this.originalRecord), t = this.records.findIndex(
1646
+ (r) => this.service.getId(r) === e
1647
+ );
1648
+ t >= 0 && (this.records = [...this.records], this.records[t] = { ...this.originalRecord });
1649
+ } else
1650
+ this.state === "insert" && (this.filteredRecords = this.filteredRecords.slice(0, -1), this.records = this.records.slice(0, -1), this.grandTotalRecords--, this.filteredRecords.length > 0 ? this.currentIndex = Math.min(this.currentIndex, this.filteredRecords.length - 1) : this.currentIndex = -1);
1651
+ this.state = "browse", this.originalRecord = null, this.emit({
1652
+ type: d.afterCancel,
1653
+ record: this.getCurrentRecord(),
1654
+ index: this.currentIndex
1655
+ });
1656
+ }
1657
+ insert(e) {
1658
+ this.validateDataSourceActive("insert"), this.state = "insert", this.emit({
1659
+ type: d.beforeInsert
1660
+ }), this.filteredRecords = [...this.filteredRecords, e], this.records = [...this.records, e], this.currentIndex = this.filteredRecords.length - 1, this.grandTotalRecords++, this.notifyStateChange(), this.emit({
1661
+ type: d.afterInsert,
1662
+ record: e,
1663
+ index: this.currentIndex
1664
+ });
1665
+ }
1666
+ // =================== Remote CRUD Operations ===================
1667
+ async save(e) {
1668
+ if (this.validateDataSourceActive("save"), !this.isInserting() && !this.isEditing()) {
1669
+ const r = m.t("archbase:saveRecordIsNotAllowed", { dataSourceName: this.name });
1670
+ throw this.publishEventError(r, {}), new g(r);
1671
+ }
1672
+ if (!this.getCurrentRecord()) {
1673
+ const r = m.t("archbase:noRecordToSave", { dataSourceName: this.name });
1674
+ throw this.publishEventError(r, {}), new g(r);
1675
+ }
1676
+ const t = this.getCurrentRecord();
1677
+ if (this.emit({
1678
+ type: d.beforeSave,
1679
+ record: t,
1680
+ index: this.getCurrentIndex()
1681
+ }), this.validator) {
1682
+ const r = this.validator.validateEntity(t);
1683
+ if (r && r.length > 0)
1684
+ if (this.publishEventErrors(r), r[0].fieldName) {
1685
+ const i = m.t("archbase:errorSavingRecord", { dataSourceName: this.label });
1686
+ throw new g(i);
1687
+ } else
1688
+ throw new g(r[0].errorMessage);
1689
+ }
1690
+ try {
1691
+ const r = await this.service.save(t);
1692
+ this.filteredRecords = _(this.filteredRecords, (s) => {
1693
+ s[this.currentIndex] = r;
1694
+ });
1695
+ let i = -1;
1696
+ return this.records.forEach((s, o) => {
1697
+ const c = this.service.getId(s), f = this.service.getId(t);
1698
+ (s === t || c !== void 0 && c === f) && (i = o);
1699
+ }), this.records = _(this.records, (s) => {
1700
+ i >= 0 ? s[i] = r : s.push(r);
1701
+ }), this.state = "browse", this.originalRecord = null, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.notifyStateChange(), this.emit({
1702
+ type: d.afterSave,
1703
+ record: r,
1704
+ index: this.getCurrentIndex()
1705
+ }), e && e(), r;
1706
+ } catch (r) {
1707
+ throw this.handleSaveError(r, e), new g(k(r));
1708
+ }
1709
+ }
1710
+ async remove(e) {
1711
+ if (this.validateDataSourceActive("remove"), this.isInserting() || this.isEditing()) {
1712
+ const i = m.t("archbase:removingRecordIsNotAllowed", { dataSourceName: this.name });
1713
+ throw this.publishEventError(i, {}), new g(i);
1714
+ }
1715
+ if (this.isEmpty() || !this.getCurrentRecord()) {
1716
+ const i = m.t("archbase:noRecordsToEdit", { dataSourceName: this.name });
1717
+ throw this.publishEventError(i, {}), new g(i);
1718
+ }
1719
+ const t = this.getCurrentRecord(), r = this.currentIndex;
1720
+ this.emit({
1721
+ type: d.beforeRemove,
1722
+ record: t,
1723
+ index: r
1724
+ });
1725
+ try {
1726
+ await this.service.delete(this.service.getId(t)), this.filteredRecords = this.filteredRecords.filter((s, o) => o !== this.currentIndex);
1727
+ const i = this.records.findIndex(
1728
+ (s) => this.service.getId(s) === this.service.getId(t)
1729
+ );
1730
+ return i >= 0 && (this.records = this.records.filter((s, o) => o !== i)), this.grandTotalRecords--, this.filteredRecords.length === 0 ? this.currentIndex = -1 : this.currentIndex >= this.filteredRecords.length && (this.currentIndex = this.filteredRecords.length - 1), this.lastDataBrowsingOn = (/* @__PURE__ */ new Date()).getTime(), this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.notifyStateChange(), this.emit({ type: d.afterScroll }), this.emit({
1731
+ type: d.afterRemove,
1732
+ record: t,
1733
+ index: r
1734
+ }), e && e(), t;
1735
+ } catch (i) {
1736
+ const s = k(i);
1737
+ throw this.emit({
1738
+ type: d.onError,
1739
+ error: s,
1740
+ originalError: i
1741
+ }), e && e(s), new g(s);
1742
+ }
1743
+ }
1744
+ // =================== Field Operations ===================
1745
+ setFieldValue(e, t) {
1746
+ if (this.validateDataSourceActive("setFieldValue"), !this.getCurrentRecord())
1747
+ return;
1748
+ const r = this.getFieldValue(e);
1749
+ if (r === t)
1750
+ return;
1751
+ const i = [...this.filteredRecords];
1752
+ if (this.filteredRecords = _(this.filteredRecords, (s) => {
1753
+ const o = s[this.currentIndex];
1754
+ o && this.setNestedValue(o, e, t);
1755
+ }), this.state === "edit" || this.state === "insert") {
1756
+ const s = this.getCurrentRecord() ? this.service.getId(this.getCurrentRecord()) : null;
1757
+ if (s !== void 0) {
1758
+ const o = this.records.findIndex(
1759
+ (c) => this.service.getId(c) === s
1760
+ );
1761
+ o >= 0 && (this.records = _(this.records, (c) => {
1762
+ this.setNestedValue(c[o], e, t);
1763
+ }));
1764
+ }
1765
+ }
1766
+ this.notifyStateChange(i), this.emit({
1767
+ type: d.fieldChanged,
1768
+ fieldName: e,
1769
+ oldValue: r,
1770
+ newValue: t,
1771
+ record: this.getCurrentRecord(),
1772
+ index: this.currentIndex
1773
+ }), this.emit({
1774
+ type: d.dataChanged,
1775
+ data: this.filteredRecords
1776
+ });
1777
+ }
1778
+ getFieldValue(e) {
1779
+ const t = this.getCurrentRecord();
1780
+ if (t)
1781
+ return this.getNestedValue(t, e);
1782
+ }
1783
+ // =================== Array Field Operations (V2) ===================
1784
+ appendToFieldArray(e, t) {
1785
+ if (this.validateDataSourceActive("appendToFieldArray"), !this.getCurrentRecord())
1786
+ return;
1787
+ const r = this.getFieldValue(e);
1788
+ if (r == null) {
1789
+ console.warn(`appendToFieldArray: Field ${String(e)} is undefined/null. Initialize the array in your DTO before using appendToFieldArray.`);
1790
+ return;
1791
+ }
1792
+ if (!Array.isArray(r))
1793
+ throw new Error(`Field ${String(e)} is not an array (found: ${typeof r})`);
1794
+ const i = [...this.filteredRecords];
1795
+ this.filteredRecords = _(this.filteredRecords, (s) => {
1796
+ const o = s[this.currentIndex];
1797
+ if (o) {
1798
+ const c = this.getNestedValue(o, e);
1799
+ c && c.push(t);
1800
+ }
1801
+ }), this.notifyStateChange(i), this.emit({
1802
+ type: d.fieldChanged,
1803
+ fieldName: e,
1804
+ oldValue: r,
1805
+ newValue: [...r, t],
1806
+ record: this.getCurrentRecord(),
1807
+ index: this.currentIndex
1808
+ });
1809
+ }
1810
+ updateFieldArrayItem(e, t, r) {
1811
+ if (this.validateDataSourceActive("updateFieldArrayItem"), !this.getCurrentRecord())
1812
+ return;
1813
+ const i = this.getFieldValue(e);
1814
+ if (!Array.isArray(i) || t < 0 || t >= i.length)
1815
+ return;
1816
+ const s = [...this.filteredRecords];
1817
+ this.filteredRecords = _(this.filteredRecords, (o) => {
1818
+ const c = o[this.currentIndex];
1819
+ if (c) {
1820
+ const f = this.getNestedValue(c, e);
1821
+ f[t] !== void 0 && r(f[t]);
1822
+ }
1823
+ }), this.notifyStateChange(s), this.emit({
1824
+ type: d.fieldChanged,
1825
+ fieldName: e,
1826
+ oldValue: i,
1827
+ newValue: this.getFieldValue(e),
1828
+ record: this.getCurrentRecord(),
1829
+ index: this.currentIndex
1830
+ });
1831
+ }
1832
+ removeFromFieldArray(e, t) {
1833
+ if (this.validateDataSourceActive("removeFromFieldArray"), !this.getCurrentRecord())
1834
+ return;
1835
+ const r = this.getFieldValue(e);
1836
+ if (!Array.isArray(r))
1837
+ throw new Error(`Field ${String(e)} is not an array`);
1838
+ if (t < 0 || t >= r.length)
1839
+ return;
1840
+ const i = [...this.filteredRecords];
1841
+ this.filteredRecords = _(this.filteredRecords, (s) => {
1842
+ const o = s[this.currentIndex];
1843
+ o && this.getNestedValue(o, e).splice(t, 1);
1844
+ }), this.notifyStateChange(i), this.emit({
1845
+ type: d.fieldChanged,
1846
+ fieldName: e,
1847
+ oldValue: r,
1848
+ newValue: this.getFieldValue(e),
1849
+ record: this.getCurrentRecord(),
1850
+ index: this.currentIndex
1851
+ });
1852
+ }
1853
+ insertIntoFieldArray(e, t, r) {
1854
+ if (this.validateDataSourceActive("insertIntoFieldArray"), !this.getCurrentRecord())
1855
+ return;
1856
+ const i = this.getFieldValue(e);
1857
+ if (!Array.isArray(i))
1858
+ throw new Error(`Field ${String(e)} is not an array`);
1859
+ const s = [...this.filteredRecords];
1860
+ this.filteredRecords = _(this.filteredRecords, (o) => {
1861
+ const c = o[this.currentIndex];
1862
+ c && this.getNestedValue(c, e).splice(t, 0, r);
1863
+ }), this.notifyStateChange(s), this.emit({
1864
+ type: d.fieldChanged,
1865
+ fieldName: e,
1866
+ oldValue: i,
1867
+ newValue: this.getFieldValue(e),
1868
+ record: this.getCurrentRecord(),
1869
+ index: this.currentIndex
1870
+ });
1871
+ }
1872
+ getFieldArray(e) {
1873
+ const t = this.getFieldValue(e);
1874
+ return t == null ? [] : Array.isArray(t) ? t : (console.warn(`Field ${String(e)} is not an array (found: ${typeof t}), returning empty array`), []);
1875
+ }
1876
+ isFieldArray(e) {
1877
+ const t = this.getFieldValue(e);
1878
+ return Array.isArray(t);
1879
+ }
1880
+ // =================== Remote Filter Operations ===================
1881
+ /**
1882
+ * Interface de opções para refreshData - compatibilidade com V1
1883
+ */
1884
+ currentPage = 0;
1885
+ currentFilter;
1886
+ currentSort;
1887
+ /**
1888
+ * Atualiza os dados do DataSource com as opções fornecidas.
1889
+ * Compatível com a interface do DataSource V1.
1890
+ *
1891
+ * @param options Opções de refresh incluindo página, filtro e ordenação
1892
+ */
1893
+ refreshData(e) {
1894
+ console.log("[V2 refreshData] Chamado com options:", e), e?.pageSize !== void 0 && (this.pageSize = e.pageSize);
1895
+ const t = e?.currentPage ?? this.currentPage;
1896
+ if (this.currentPage = t, console.log("[V2 refreshData] Página atual definida:", this.currentPage), "filter" in (e || {}) && (this.currentFilter = e?.filter, console.log("[V2 refreshData] Filtro definido:", this.currentFilter)), e?.sort !== void 0 && (this.currentSort = e.sort, this.defaultSortFields = e.sort.map((r) => r.split(":")[0])), this.currentFilter && this.currentFilter.trim() !== "") {
1897
+ console.log("[V2 refreshData] Chamando getDataWithRsqlFilter para página:", t), this.getDataWithRsqlFilter(t);
1898
+ return;
1899
+ }
1900
+ console.log("[V2 refreshData] Chamando getDataWithoutFilter para página:", t), this.getDataWithoutFilter(t);
1901
+ }
1902
+ /**
1903
+ * Carrega dados com filtro RSQL
1904
+ */
1905
+ async getDataWithRsqlFilter(e, t) {
1906
+ try {
1907
+ let r;
1908
+ return this.currentSort && this.currentSort.length > 0 ? r = await this.service.findAllWithFilterAndSort(
1909
+ this.currentFilter,
1910
+ e,
1911
+ this.getPageSize(),
1912
+ this.currentSort
1913
+ ) : this.defaultSortFields.length > 0 ? r = await this.service.findAllWithFilterAndSort(
1914
+ this.currentFilter,
1915
+ e,
1916
+ this.getPageSize(),
1917
+ this.defaultSortFields
1918
+ ) : r = await this.service.findAllWithFilter(
1919
+ this.currentFilter,
1920
+ e,
1921
+ this.getPageSize()
1922
+ ), r && r.content && (this.grandTotalRecords = r.totalElements || r.content.length, this.setRecords(r.content)), t && t(), r;
1923
+ } catch (r) {
1924
+ throw this.handleRemoteError(r, t), r;
1925
+ }
1926
+ }
1927
+ /**
1928
+ * Retorna as opções atuais do DataSource - compatibilidade com V1
1929
+ */
1930
+ getOptions() {
1931
+ return {
1932
+ currentPage: this.currentPage,
1933
+ pageSize: this.pageSize,
1934
+ filter: this.currentFilter,
1935
+ sort: this.currentSort || this.defaultSortFields,
1936
+ grandTotalRecords: this.grandTotalRecords
1937
+ };
1938
+ }
1939
+ applyRemoteFilter(e, t, r) {
1940
+ if (this.currentPage = t, !(e && e.filter)) {
1941
+ this.getDataWithoutFilter(t, r);
1942
+ return;
1943
+ }
1944
+ const s = e.filter.filterType, o = e.filter.quickFilterText;
1945
+ s === Se && o && o !== "" ? this.getDataWithQuickFilter(e, t, r) : s === Fe || s === Ae ? this.getDataWithFilter(e, t, r) : this.getDataWithoutFilter(t, r);
1946
+ }
1947
+ // =================== Event Management ===================
1948
+ addListener(e) {
1949
+ this.listeners.add(e);
1950
+ }
1951
+ removeListener(e) {
1952
+ this.listeners.delete(e);
1953
+ }
1954
+ emit(e) {
1955
+ this.listeners.forEach((t) => {
1956
+ try {
1957
+ t(e);
1958
+ } catch (r) {
1959
+ console.error("Error in DataSource listener:", r);
1960
+ }
1961
+ });
1962
+ }
1963
+ // =================== Utility Methods ===================
1964
+ getGrandTotalRecords() {
1965
+ return this.grandTotalRecords;
1966
+ }
1967
+ getPageSize() {
1968
+ return this.pageSize;
1969
+ }
1970
+ setPageSize(e) {
1971
+ this.pageSize = e;
1972
+ }
1973
+ /**
1974
+ * Retorna a página atual (0-indexed)
1975
+ */
1976
+ getCurrentPage() {
1977
+ return this.currentPage;
1978
+ }
1979
+ /**
1980
+ * Alias para getRecords - compatibilidade com V1
1981
+ */
1982
+ browseRecords() {
1983
+ return [...this.filteredRecords];
1984
+ }
1985
+ getRecords() {
1986
+ return [...this.filteredRecords];
1987
+ }
1988
+ /**
1989
+ * Localiza um registro por valores de campos e navega para ele
1990
+ * @param values Objeto com campos/valores para busca
1991
+ * @returns true se encontrou, false caso contrário
1992
+ */
1993
+ locate(e) {
1994
+ const t = Object.keys(e), r = this.filteredRecords.findIndex((i) => t.every((s) => {
1995
+ const o = i[s], c = e[s];
1996
+ return o === c;
1997
+ }));
1998
+ return r >= 0 ? (this.currentIndex = r, this.emit({
1999
+ type: d.afterScroll
2000
+ }), !0) : !1;
2001
+ }
2002
+ /**
2003
+ * Vai para um registro pelo seu índice (alias para goToRecord)
2004
+ * @param index Índice do registro
2005
+ */
2006
+ gotoRecord(e) {
2007
+ this.goToRecord(e);
2008
+ }
2009
+ /**
2010
+ * Vai para um registro pelo seu dado
2011
+ * @param record Dados do registro para navegar
2012
+ * @returns true se encontrou, false caso contrário
2013
+ */
2014
+ gotoRecordByData(e) {
2015
+ const t = this.service.getId(e), r = this.filteredRecords.findIndex(
2016
+ (i) => this.service.getId(i) === t
2017
+ );
2018
+ return r >= 0 ? (this.currentIndex = r, this.emit({
2019
+ type: d.afterScroll
2020
+ }), !0) : !1;
2021
+ }
2022
+ setRecords(e, t) {
2023
+ const r = [...this.filteredRecords];
2024
+ this.records = [...e], this.filteredRecords = [...e], t !== void 0 ? this.grandTotalRecords = t : this.grandTotalRecords < e.length && (this.grandTotalRecords = e.length), e.length > 0 ? this.currentIndex = 0 : this.currentIndex = -1, this.lastDataChangedAt = (/* @__PURE__ */ new Date()).getTime(), this.notifyStateChange(r), this.emit({
2025
+ type: d.dataChanged,
2026
+ data: this.filteredRecords
2027
+ });
2028
+ }
2029
+ // =================== Debug Support ===================
2030
+ getDebugSnapshot() {
2031
+ return {
2032
+ name: this.name,
2033
+ label: this.label,
2034
+ recordCount: this.filteredRecords.length,
2035
+ currentIndex: this.currentIndex,
2036
+ currentRecord: this.getCurrentRecord(),
2037
+ state: this.state,
2038
+ listeners: this.listeners.size,
2039
+ totalRecords: this.grandTotalRecords,
2040
+ pageSize: this.pageSize
2041
+ };
2042
+ }
2043
+ // =================== Private Helper Methods ===================
2044
+ validateDataSourceActive(e) {
2045
+ if (!this.active)
2046
+ throw new g(`DataSource ${this.name} is not active. Cannot perform ${e}`);
2047
+ }
2048
+ publishEventError(e, t) {
2049
+ this.emit({
2050
+ type: d.onError,
2051
+ error: e,
2052
+ originalError: t
2053
+ }), this.onError && this.onError(e, t);
2054
+ }
2055
+ publishEventErrors(e) {
2056
+ e.forEach((t) => {
2057
+ t.fieldName && (this.emit({
2058
+ type: d.onFieldError,
2059
+ fieldName: t.fieldName,
2060
+ error: t.errorMessage,
2061
+ originalError: t
2062
+ }), this.onFieldError && this.onFieldError(t.fieldName, t.errorMessage));
2063
+ });
2064
+ }
2065
+ handleSaveError(e, t) {
2066
+ e.response && e.response.data && e.response.data.apierror && e.response.data.apierror.subErrors && e.response.data.apierror.subErrors.forEach((i) => {
2067
+ i.field && (this.emit({
2068
+ type: d.onFieldError,
2069
+ fieldName: i.field,
2070
+ error: i.message,
2071
+ originalError: i.message
2072
+ }), this.onFieldError && this.onFieldError(i.field, i.message));
2073
+ });
2074
+ const r = k(e);
2075
+ this.emit({
2076
+ type: d.onError,
2077
+ error: r,
2078
+ originalError: e
2079
+ }), this.onError && this.onError(r, e), t && t(r);
2080
+ }
2081
+ notifyStateChange(e) {
2082
+ this.onStateChange && e && this.onStateChange(e, [...this.filteredRecords]);
2083
+ }
2084
+ setNestedValue(e, t, r) {
2085
+ const i = t.split(".");
2086
+ let s = e;
2087
+ for (let o = 0; o < i.length - 1; o++) {
2088
+ const c = i[o];
2089
+ c in s || (s[c] = {}), s = s[c];
2090
+ }
2091
+ s[i[i.length - 1]] = r;
2092
+ }
2093
+ getNestedValue(e, t) {
2094
+ const r = t.split(".");
2095
+ let i = e;
2096
+ for (const s of r) {
2097
+ if (i == null)
2098
+ return;
2099
+ i = i[s];
2100
+ }
2101
+ return i;
2102
+ }
2103
+ // =================== Remote Data Loading ===================
2104
+ async getDataWithFilter(e, t, r) {
2105
+ try {
2106
+ const i = new xe();
2107
+ i.buildFrom(e.filter, e.sort);
2108
+ const s = i.toJSON();
2109
+ let o;
2110
+ return s ? o = await this.service.findAllWithFilter(s, t, this.getPageSize()) : o = await this.getDataWithoutFilter(t), o && o.content && (this.grandTotalRecords = o.totalElements || o.content.length, this.setRecords(o.content)), r && r(), o;
2111
+ } catch (i) {
2112
+ throw this.handleRemoteError(i, r), i;
2113
+ }
2114
+ }
2115
+ async getDataWithoutFilter(e, t) {
2116
+ try {
2117
+ console.log("[V2 getDataWithoutFilter] Buscando página:", e, "pageSize:", this.getPageSize(), "sort:", this.defaultSortFields);
2118
+ let r;
2119
+ return this.defaultSortFields.length > 0 ? r = await this.service.findAllWithSort(e, this.getPageSize(), this.defaultSortFields) : r = await this.service.findAll(e, this.getPageSize()), console.log("[V2 getDataWithoutFilter] Resultado:", r?.totalElements, "registros totais,", r?.content?.length, "na página"), r && r.content && (this.grandTotalRecords = r.totalElements || r.content.length, this.setRecords(r.content), console.log("[V2 getDataWithoutFilter] Após setRecords - currentPage:", this.currentPage, "grandTotal:", this.grandTotalRecords)), t && t(), r;
2120
+ } catch (r) {
2121
+ throw this.handleRemoteError(r, t), r;
2122
+ }
2123
+ }
2124
+ async getDataWithQuickFilter(e, t, r) {
2125
+ try {
2126
+ const i = Array.isArray(e.filter.quickFilterFieldsText) ? e.filter.quickFilterFieldsText.join(",") : e.filter.quickFilterFieldsText, s = this.getSortFields(e).join(","), o = await this.service.findAllMultipleFields(
2127
+ e.filter.quickFilterText,
2128
+ i,
2129
+ t,
2130
+ this.getPageSize(),
2131
+ s
2132
+ );
2133
+ return o && o.content && (this.grandTotalRecords = o.totalElements || o.content.length, this.setRecords(o.content)), r && r(), o;
2134
+ } catch (i) {
2135
+ throw this.handleRemoteError(i, r), i;
2136
+ }
2137
+ }
2138
+ getSortFields(e) {
2139
+ if (e && e.sort) {
2140
+ const t = e.sort.quickFilterSort;
2141
+ if (Array.isArray(t))
2142
+ return t;
2143
+ if (typeof t == "string")
2144
+ return [t];
2145
+ }
2146
+ return this.defaultSortFields;
2147
+ }
2148
+ handleRemoteError(e, t) {
2149
+ const r = k(e);
2150
+ this.emit({
2151
+ type: d.onError,
2152
+ error: r,
2153
+ originalError: e
2154
+ }), this.onError && this.onError(r, e), t && t();
2155
+ }
2156
+ }
2157
+ function be(n) {
2158
+ const e = le(null), [t, r] = C(null), [i, s] = C(-1), [o, c] = C(0), [f, R] = C(!0), [b, N] = C(!1), [W, T] = C(!1), [O, $] = C(!1), [, z] = C({}), u = l(() => z({}), []), a = H(() => (e.current || (e.current = new U(n)), e.current), []), V = l((F) => {
2159
+ switch (F.type) {
2160
+ case d.dataChanged:
2161
+ case d.recordChanged:
2162
+ r(a.getCurrentRecord()), s(a.getCurrentIndex()), c(a.getTotalRecords()), R(a.isBrowsing()), N(a.isEditing()), T(a.isInserting());
2163
+ break;
2164
+ case d.fieldChanged:
2165
+ r(a.getCurrentRecord()), u();
2166
+ break;
2167
+ case d.afterScroll:
2168
+ r(a.getCurrentRecord()), s(a.getCurrentIndex());
2169
+ break;
2170
+ case d.beforeEdit:
2171
+ case d.beforeInsert:
2172
+ $(!0);
2173
+ break;
2174
+ case d.afterEdit:
2175
+ case d.afterInsert:
2176
+ case d.afterSave:
2177
+ case d.afterCancel:
2178
+ $(!1), R(a.isBrowsing()), N(a.isEditing()), T(a.isInserting());
2179
+ break;
2180
+ case d.onError:
2181
+ case d.onFieldError:
2182
+ $(!1);
2183
+ break;
2184
+ }
2185
+ }, [a, u]);
2186
+ J(() => (a.addListener(V), r(a.getCurrentRecord()), s(a.getCurrentIndex()), c(a.getTotalRecords()), R(a.isBrowsing()), N(a.isEditing()), T(a.isInserting()), () => {
2187
+ a.removeListener(V);
2188
+ }), [a, V]);
2189
+ const Y = l((F, j) => {
2190
+ a.setFieldValue(F, j);
2191
+ }, [a]), S = l((F) => a.getFieldValue(F), [a]), h = l(() => {
2192
+ a instanceof U, a.edit();
2193
+ }, [a]), Q = l(async () => await a.save(), [a]), X = l(() => {
2194
+ a instanceof U, a.cancel();
2195
+ }, [a]), I = l((F) => {
2196
+ a instanceof U, a.insert(F);
2197
+ }, [a]), G = l(async (F) => await a.remove(F), [a]), Z = l(() => {
2198
+ a instanceof U, a.first();
2199
+ }, [a]), D = l(() => {
2200
+ a instanceof U, a.last();
2201
+ }, [a]), E = l(() => {
2202
+ a instanceof U, a.next();
2203
+ }, [a]), A = l(() => {
2204
+ a instanceof U, a.prior();
2205
+ }, [a]), P = l((F) => {
2206
+ a instanceof U, a.goToRecord(F);
2207
+ }, [a]), p = l((F, j) => {
2208
+ a instanceof U && a.appendToFieldArray(F, j);
2209
+ }, [a]), v = l((F, j, he) => {
2210
+ a instanceof U && a.updateFieldArrayItem(F, j, he);
2211
+ }, [a]), x = l((F, j) => {
2212
+ a instanceof U && a.removeFromFieldArray(F, j);
2213
+ }, [a]), L = l((F, j, he) => {
2214
+ a instanceof U && a.insertIntoFieldArray(F, j, he);
2215
+ }, [a]), y = l((F) => {
2216
+ if (a instanceof U)
2217
+ return a.getFieldArray(F);
2218
+ const j = a.getFieldValue(F);
2219
+ return Array.isArray(j) ? j : [];
2220
+ }, [a]), q = l((F) => {
2221
+ if (a instanceof U)
2222
+ return a.isFieldArray(F);
2223
+ const j = a.getFieldValue(F);
2224
+ return Array.isArray(j);
2225
+ }, [a]), te = H(() => i < o - 1, [i, o]), oe = H(() => i > 0, [i]), ae = H(() => o === 0, [o]), B = H(() => i === 0, [i]), K = H(() => i === o - 1, [i, o]), re = H(() => f, [f]), de = H(() => b, [b]), ce = H(() => W, [W]), fe = l(() => process.env.NODE_ENV === "development" ? {
2226
+ ...a.getDebugSnapshot(),
2227
+ hookState: {
2228
+ currentRecord: t,
2229
+ currentIndex: i,
2230
+ totalRecords: o,
2231
+ isBrowsing: re,
2232
+ isEditing: de,
2233
+ isInserting: ce,
2234
+ isLoading: O
2235
+ }
2236
+ } : null, [a, t, i, o, re, de, ce, O]);
2237
+ return {
2238
+ // DataSource instance (para casos onde acesso direto é necessário)
2239
+ dataSource: a,
2240
+ // Estado reativo
2241
+ currentRecord: t,
2242
+ currentIndex: i,
2243
+ totalRecords: o,
2244
+ isLoading: O,
2245
+ // Estado derivado
2246
+ canNext: te,
2247
+ canPrior: oe,
2248
+ isEmpty: ae,
2249
+ isFirst: B,
2250
+ isLast: K,
2251
+ isBrowsing: re,
2252
+ isEditing: de,
2253
+ isInserting: ce,
2254
+ // Operações básicas
2255
+ setFieldValue: Y,
2256
+ getFieldValue: S,
2257
+ edit: h,
2258
+ save: Q,
2259
+ cancel: X,
2260
+ insert: I,
2261
+ remove: G,
2262
+ // Navegação
2263
+ first: Z,
2264
+ last: D,
2265
+ next: E,
2266
+ prior: A,
2267
+ goToRecord: P,
2268
+ // Operações de array (V2)
2269
+ appendToFieldArray: p,
2270
+ updateFieldArrayItem: v,
2271
+ removeFromFieldArray: x,
2272
+ insertIntoFieldArray: L,
2273
+ getFieldArray: y,
2274
+ isFieldArray: q,
2275
+ // Debug
2276
+ getDebugInfo: fe
2277
+ };
2278
+ }
2279
+ function It(n) {
2280
+ const {
2281
+ dataSource: e,
2282
+ currentRecord: t,
2283
+ currentIndex: r,
2284
+ totalRecords: i,
2285
+ canNext: s,
2286
+ canPrior: o,
2287
+ isEmpty: c,
2288
+ isFirst: f,
2289
+ isLast: R,
2290
+ isBrowsing: b,
2291
+ first: N,
2292
+ last: W,
2293
+ next: T,
2294
+ prior: O,
2295
+ goToRecord: $,
2296
+ getFieldValue: z,
2297
+ getFieldArray: u,
2298
+ isFieldArray: a
2299
+ } = be(n);
2300
+ return {
2301
+ dataSource: e,
2302
+ currentRecord: t,
2303
+ currentIndex: r,
2304
+ totalRecords: i,
2305
+ canNext: s,
2306
+ canPrior: o,
2307
+ isEmpty: c,
2308
+ isFirst: f,
2309
+ isLast: R,
2310
+ isBrowsing: b,
2311
+ first: N,
2312
+ last: W,
2313
+ next: T,
2314
+ prior: O,
2315
+ goToRecord: $,
2316
+ getFieldValue: z,
2317
+ getFieldArray: u,
2318
+ isFieldArray: a
2319
+ };
2320
+ }
2321
+ function wt(n) {
2322
+ return be(n);
2323
+ }
2324
+ function De(n) {
2325
+ const e = le(null), [t, r] = C(void 0), [i, s] = C(-1), [o, c] = C(0), [f, R] = C(0), [b, N] = C(!0), [W, T] = C(!1), [O, $] = C(!1), [z, u] = C(!1), [a, V] = C(null), [, Y] = C({}), S = l(() => Y({}), []), h = H(() => (e.current || (e.current = new Je(n)), e.current), []), Q = l((w) => {
2326
+ switch (w.type) {
2327
+ case d.dataChanged:
2328
+ case d.recordChanged:
2329
+ case d.refreshData:
2330
+ r(h.getCurrentRecord()), s(h.getCurrentIndex()), c(h.getTotalRecords()), R(h.getGrandTotalRecords()), N(h.isBrowsing()), T(h.isEditing()), $(h.isInserting()), u(!1), V(null);
2331
+ break;
2332
+ case d.fieldChanged:
2333
+ r(h.getCurrentRecord()), S();
2334
+ break;
2335
+ case d.afterScroll:
2336
+ r(h.getCurrentRecord()), s(h.getCurrentIndex());
2337
+ break;
2338
+ case d.beforeEdit:
2339
+ case d.beforeInsert:
2340
+ case d.beforeSave:
2341
+ case d.beforeRemove:
2342
+ u(!0), V(null);
2343
+ break;
2344
+ case d.afterEdit:
2345
+ case d.afterInsert:
2346
+ case d.afterSave:
2347
+ case d.afterCancel:
2348
+ case d.afterRemove:
2349
+ u(!1), N(h.isBrowsing()), T(h.isEditing()), $(h.isInserting()), V(null);
2350
+ break;
2351
+ case d.onError:
2352
+ u(!1), V(w.error);
2353
+ break;
2354
+ case d.onFieldError:
2355
+ u(!1);
2356
+ break;
2357
+ }
2358
+ }, [h, S]);
2359
+ J(() => (h.addListener(Q), r(h.getCurrentRecord()), s(h.getCurrentIndex()), c(h.getTotalRecords()), R(h.getGrandTotalRecords()), N(h.isBrowsing()), T(h.isEditing()), $(h.isInserting()), () => {
2360
+ h.removeListener(Q);
2361
+ }), [h, Q]);
2362
+ const X = l((w, M) => {
2363
+ h.setFieldValue(w, M);
2364
+ }, [h]), I = l((w) => h.getFieldValue(w), [h]), G = l(() => {
2365
+ h.edit();
2366
+ }, [h]), Z = l(async () => {
2367
+ try {
2368
+ return V(null), await h.save();
2369
+ } catch (w) {
2370
+ throw V(w.message || "Erro ao salvar"), w;
2371
+ }
2372
+ }, [h]), D = l(() => {
2373
+ h.cancel();
2374
+ }, [h]), E = l((w) => {
2375
+ h.insert(w);
2376
+ }, [h]), A = l(async (w) => {
2377
+ try {
2378
+ return V(null), await h.remove(w);
2379
+ } catch (M) {
2380
+ throw V(M.message || "Erro ao remover"), M;
2381
+ }
2382
+ }, [h]), P = l(() => {
2383
+ h.first();
2384
+ }, [h]), p = l(() => {
2385
+ h.last();
2386
+ }, [h]), v = l(() => {
2387
+ h.next();
2388
+ }, [h]), x = l(() => {
2389
+ h.prior();
2390
+ }, [h]), L = l((w) => {
2391
+ h.goToRecord(w);
2392
+ }, [h]), y = l((w, M) => {
2393
+ h.appendToFieldArray(w, M);
2394
+ }, [h]), q = l((w, M, se) => {
2395
+ h.updateFieldArrayItem(w, M, se);
2396
+ }, [h]), te = l((w, M) => {
2397
+ h.removeFromFieldArray(w, M);
2398
+ }, [h]), oe = l((w, M, se) => {
2399
+ h.insertIntoFieldArray(w, M, se);
2400
+ }, [h]), ae = l((w) => h.getFieldArray(w), [h]), B = l((w) => h.isFieldArray(w), [h]), K = l((w, M, se) => {
2401
+ u(!0), V(null);
2402
+ try {
2403
+ h.applyRemoteFilter(w, M, () => {
2404
+ u(!1), se && se();
2405
+ });
2406
+ } catch (Pe) {
2407
+ u(!1), V(Pe.message || "Erro ao aplicar filtro");
2408
+ }
2409
+ }, [h]), re = l(async (w) => {
2410
+ try {
2411
+ u(!0), V(null), h.refreshData(w);
2412
+ } catch (M) {
2413
+ throw u(!1), V(M.message || "Erro ao atualizar dados"), M;
2414
+ }
2415
+ }, [h]), de = l((w) => {
2416
+ h.setPageSize(w);
2417
+ }, [h]), ce = l(() => h.getPageSize(), [h]), fe = H(() => i < o - 1, [i, o]), F = H(() => i > 0, [i]), j = H(() => o === 0, [o]), he = H(() => i === 0, [i]), Te = H(() => i === o - 1, [i, o]), me = H(() => b, [b]), Re = H(() => W, [W]), pe = H(() => O, [O]), Oe = l(() => process.env.NODE_ENV === "development" ? {
2418
+ ...h.getDebugSnapshot(),
2419
+ hookState: {
2420
+ currentRecord: t,
2421
+ currentIndex: i,
2422
+ totalRecords: o,
2423
+ grandTotalRecords: f,
2424
+ isBrowsing: me,
2425
+ isEditing: Re,
2426
+ isInserting: pe,
2427
+ isLoading: z,
2428
+ error: a
2429
+ }
2430
+ } : null, [h, t, i, o, f, me, Re, pe, z, a]);
2431
+ return {
2432
+ // DataSource instance (para casos onde acesso direto é necessário)
2433
+ dataSource: h,
2434
+ // Estado reativo
2435
+ currentRecord: t,
2436
+ currentIndex: i,
2437
+ totalRecords: o,
2438
+ grandTotalRecords: f,
2439
+ isLoading: z,
2440
+ error: a,
2441
+ // Estado derivado
2442
+ canNext: fe,
2443
+ canPrior: F,
2444
+ isEmpty: j,
2445
+ isFirst: he,
2446
+ isLast: Te,
2447
+ isBrowsing: me,
2448
+ isEditing: Re,
2449
+ isInserting: pe,
2450
+ // Operações básicas
2451
+ setFieldValue: X,
2452
+ getFieldValue: I,
2453
+ edit: G,
2454
+ save: Z,
2455
+ cancel: D,
2456
+ insert: E,
2457
+ remove: A,
2458
+ // Navegação
2459
+ first: P,
2460
+ last: p,
2461
+ next: v,
2462
+ prior: x,
2463
+ goToRecord: L,
2464
+ // Operações de array (V2)
2465
+ appendToFieldArray: y,
2466
+ updateFieldArrayItem: q,
2467
+ removeFromFieldArray: te,
2468
+ insertIntoFieldArray: oe,
2469
+ getFieldArray: ae,
2470
+ isFieldArray: B,
2471
+ // Operações remotas
2472
+ applyRemoteFilter: K,
2473
+ refreshData: re,
2474
+ setPageSize: de,
2475
+ getPageSize: ce,
2476
+ // Debug
2477
+ getDebugInfo: Oe
2478
+ };
2479
+ }
2480
+ function Et(n) {
2481
+ const {
2482
+ dataSource: e,
2483
+ currentRecord: t,
2484
+ currentIndex: r,
2485
+ totalRecords: i,
2486
+ grandTotalRecords: s,
2487
+ isLoading: o,
2488
+ error: c,
2489
+ canNext: f,
2490
+ canPrior: R,
2491
+ isEmpty: b,
2492
+ isFirst: N,
2493
+ isLast: W,
2494
+ isBrowsing: T,
2495
+ first: O,
2496
+ last: $,
2497
+ next: z,
2498
+ prior: u,
2499
+ goToRecord: a,
2500
+ getFieldValue: V,
2501
+ getFieldArray: Y,
2502
+ isFieldArray: S,
2503
+ applyRemoteFilter: h,
2504
+ refreshData: Q,
2505
+ getPageSize: X,
2506
+ getDebugInfo: I
2507
+ } = De(n);
2508
+ return {
2509
+ dataSource: e,
2510
+ currentRecord: t,
2511
+ currentIndex: r,
2512
+ totalRecords: i,
2513
+ grandTotalRecords: s,
2514
+ isLoading: o,
2515
+ error: c,
2516
+ canNext: f,
2517
+ canPrior: R,
2518
+ isEmpty: b,
2519
+ isFirst: N,
2520
+ isLast: W,
2521
+ isBrowsing: T,
2522
+ first: O,
2523
+ last: $,
2524
+ next: z,
2525
+ prior: u,
2526
+ goToRecord: a,
2527
+ getFieldValue: V,
2528
+ getFieldArray: Y,
2529
+ isFieldArray: S,
2530
+ applyRemoteFilter: h,
2531
+ refreshData: Q,
2532
+ getPageSize: X,
2533
+ getDebugInfo: I
2534
+ };
2535
+ }
2536
+ function St(n) {
2537
+ return De(n);
2538
+ }
2539
+ class Ft {
2540
+ /**
2541
+ * Gera chave de query baseada no DataSource e filtros
2542
+ */
2543
+ static generateQueryKey(e, t, r, i) {
2544
+ const s = ["archbase-datasource", e];
2545
+ return t && s.push("filter", JSON.stringify(t)), r && s.push("sort", JSON.stringify(r)), i !== void 0 && s.push("page", i.toString()), s;
2546
+ }
2547
+ /**
2548
+ * Determina se os dados precisam ser refetch baseado em critérios
2549
+ */
2550
+ static shouldRefetch(e, t, r = !1) {
2551
+ const i = Date.now(), s = i - e > t;
2552
+ return !!(r && s || i - e > t * 2);
2553
+ }
2554
+ /**
2555
+ * Merge optimistic updates com dados em cache
2556
+ */
2557
+ static mergeOptimisticUpdate(e, t, r) {
2558
+ return e.map(
2559
+ (i) => i[r] === t[r] ? { ...i, ...t } : i
2560
+ );
2561
+ }
2562
+ }
2563
+ const At = {
2564
+ /** Configuração para dados que mudam raramente */
2565
+ STATIC_DATA: {
2566
+ staleTime: 30 * 60 * 1e3,
2567
+ // 30 minutos
2568
+ cacheTime: 60 * 60 * 1e3,
2569
+ // 1 hora
2570
+ refetchOnWindowFocus: !1,
2571
+ retry: 1
2572
+ },
2573
+ /** Configuração para dados dinâmicos */
2574
+ DYNAMIC_DATA: {
2575
+ staleTime: 5 * 60 * 1e3,
2576
+ // 5 minutos
2577
+ cacheTime: 15 * 60 * 1e3,
2578
+ // 15 minutos
2579
+ refetchOnWindowFocus: !0,
2580
+ retry: 3
2581
+ },
2582
+ /** Configuração para dados em tempo real */
2583
+ REALTIME_DATA: {
2584
+ staleTime: 30 * 1e3,
2585
+ // 30 segundos
2586
+ cacheTime: 5 * 60 * 1e3,
2587
+ // 5 minutos
2588
+ refetchOnWindowFocus: !0,
2589
+ refetchInterval: 60 * 1e3,
2590
+ // 1 minuto
2591
+ retry: 5
2592
+ }
2593
+ }, xt = (n) => {
2594
+ const { initialData: e, name: t, label: r, initialDataSource: i, onLoadComplete: s, store: o, validator: c } = n, f = () => o && o.existsValue(t) ? o.getValue(t) : i || new Ie(t, {
2595
+ records: e,
2596
+ grandTotalRecords: e.length,
2597
+ currentPage: 0,
2598
+ totalPages: 0,
2599
+ pageSize: 0,
2600
+ validator: c
2601
+ }, r), [R, b] = C(
2602
+ f()
2603
+ );
2604
+ return J(() => {
2605
+ o && o.setValue(t, R), s && s(R);
2606
+ }, [t]), { dataSource: R };
2607
+ }, Ct = (n) => {
2608
+ const e = (r) => {
2609
+ r.addListener(n.listener);
2610
+ }, t = (r) => {
2611
+ r.removeListener(n.listener);
2612
+ };
2613
+ J(() => (n.dataSource && (t(n.dataSource), e(n.dataSource)), () => {
2614
+ n.dataSource && t(n.dataSource);
2615
+ }), [n.dataSource?.uuid || n.dataSource?.getName()]);
2616
+ }, bt = (n) => {
2617
+ const { initialData: e, name: t, initialDataSource: r, onLoadComplete: i, validator: s } = n, [o, c] = C(
2618
+ r ?? new ke(t, {
2619
+ records: e,
2620
+ grandTotalRecords: e.length,
2621
+ currentPage: 0,
2622
+ totalPages: 0,
2623
+ pageSize: 0,
2624
+ validator: s
2625
+ })
2626
+ );
2627
+ return J(() => {
2628
+ c((f) => {
2629
+ const R = {
2630
+ records: e,
2631
+ grandTotalRecords: e.length,
2632
+ totalPages: 0,
2633
+ currentPage: 0,
2634
+ pageSize: 0,
2635
+ validator: s
2636
+ };
2637
+ return f.isActive() ? f.setData(R) : f.open(R), f;
2638
+ }), i && i(o);
2639
+ }, [e, t]), { dataSource: o };
2640
+ };
2641
+ class Ve {
2642
+ tokenManager;
2643
+ constructor(e) {
2644
+ this.tokenManager = e;
2645
+ }
2646
+ prepareHeaders(e = {}, t = !1) {
2647
+ let r = { "Content-Type": "application/json; charset=utf-8", ...e };
2648
+ if (!t) {
2649
+ const i = this.tokenManager.getToken();
2650
+ i && (r.Authorization = `Bearer ${i.access_token}`);
2651
+ }
2652
+ return r;
2653
+ }
2654
+ async get(e, t, r, i) {
2655
+ try {
2656
+ const s = this.prepareHeaders(t, r), o = await ee.get(e, { headers: s, ...i });
2657
+ return ie.convertJsonToObject(o.data);
2658
+ } catch (s) {
2659
+ return Promise.reject(s);
2660
+ }
2661
+ }
2662
+ async post(e, t, r, i, s) {
2663
+ try {
2664
+ const o = this.prepareHeaders(r, i), c = await ee.post(
2665
+ e,
2666
+ ie.convertObjectToJson(t),
2667
+ {
2668
+ headers: o,
2669
+ ...s
2670
+ }
2671
+ );
2672
+ return ie.convertJsonToObject(c.data);
2673
+ } catch (o) {
2674
+ return Promise.reject(o);
2675
+ }
2676
+ }
2677
+ async postNoConvertId(e, t, r, i, s) {
2678
+ try {
2679
+ const o = this.prepareHeaders(r, i);
2680
+ return (await ee.post(
2681
+ e,
2682
+ t,
2683
+ {
2684
+ headers: o,
2685
+ ...s
2686
+ }
2687
+ )).data;
2688
+ } catch (o) {
2689
+ return Promise.reject(o);
2690
+ }
2691
+ }
2692
+ async put(e, t, r, i, s) {
2693
+ try {
2694
+ const o = this.prepareHeaders(r, i), c = await ee.put(e, ie.convertObjectToJson(t), {
2695
+ headers: o,
2696
+ ...s
2697
+ });
2698
+ return ie.convertJsonToObject(c.data);
2699
+ } catch (o) {
2700
+ return Promise.reject(o);
2701
+ }
2702
+ }
2703
+ async putNoConvertId(e, t, r, i, s) {
2704
+ try {
2705
+ const o = this.prepareHeaders(r, i);
2706
+ return (await ee.put(e, t, {
2707
+ headers: o,
2708
+ ...s
2709
+ })).data;
2710
+ } catch (o) {
2711
+ return Promise.reject(o);
2712
+ }
2713
+ }
2714
+ async binaryPut(e, t, r = {}, i, s) {
2715
+ try {
2716
+ const o = this.prepareHeaders(r, i);
2717
+ return s = s || {}, (await ee.put(e, t, {
2718
+ headers: o,
2719
+ ...s
2720
+ })).data;
2721
+ } catch (o) {
2722
+ return Promise.reject(o);
2723
+ }
2724
+ }
2725
+ async delete(e, t, r, i) {
2726
+ try {
2727
+ const s = this.prepareHeaders(t, r), o = await ee.delete(e, { headers: s, ...i });
2728
+ return ie.convertJsonToObject(o.data);
2729
+ } catch (s) {
2730
+ return Promise.reject(s);
2731
+ }
2732
+ }
2733
+ async patch(e, t, r, i, s) {
2734
+ try {
2735
+ const o = this.prepareHeaders(r, i), c = await ee.patch(e, ie.convertObjectToJson(t), {
2736
+ headers: o,
2737
+ ...s
2738
+ });
2739
+ return ie.convertJsonToObject(c.data);
2740
+ } catch (o) {
2741
+ return Promise.reject(o);
2742
+ }
2743
+ }
2744
+ async patchNoConvertId(e, t, r, i, s) {
2745
+ try {
2746
+ const o = this.prepareHeaders(r, i);
2747
+ return (await ee.patch(e, t, {
2748
+ headers: o,
2749
+ ...s
2750
+ })).data;
2751
+ } catch (o) {
2752
+ return Promise.reject(o);
2753
+ }
2754
+ }
2755
+ }
2756
+ ne.decorate(ne.inject(He.TokenManager), Ve, 0);
2757
+ ne.decorate(ne.injectable(), Ve);
2758
+ class Qe {
2759
+ client;
2760
+ constructor(e) {
2761
+ this.client = e;
2762
+ }
2763
+ transformPage(e) {
2764
+ if (e.content && e.content.length > 0)
2765
+ for (let t = 0; t < e.content.length; t++) {
2766
+ const r = e.content[t];
2767
+ this.isTransformable() && (e.content[t] = this.transform(r));
2768
+ }
2769
+ }
2770
+ transformList(e) {
2771
+ if (e && e.length > 0)
2772
+ for (let t = 0; t < e.length; t++) {
2773
+ const r = e[t];
2774
+ this.isTransformable() && (e[t] = this.transform(r));
2775
+ }
2776
+ }
2777
+ isTransformable() {
2778
+ return typeof this.transform == "function";
2779
+ }
2780
+ async validate(e) {
2781
+ const t = this.configureHeaders();
2782
+ return this.client.post(`${this.getEndpoint()}/validate`, e, t, !1);
2783
+ }
2784
+ async validateGroup(e, t) {
2785
+ const r = { groups: JSON.stringify(t) }, i = this.configureHeaders(), s = { ...r, ...i };
2786
+ return this.client.post(`${this.getEndpoint()}/validateGroup`, e, s, !1);
2787
+ }
2788
+ async exists(e) {
2789
+ const t = this.configureHeaders();
2790
+ return this.client.get(`${this.getEndpoint()}/exists/${e}`, t, !1);
2791
+ }
2792
+ async findAll(e, t) {
2793
+ const r = this.configureHeaders(), i = await this.client.get(`${this.getEndpoint()}/findAll?page=${e}&size=${t}`, r, !1);
2794
+ return this.transformPage(i), i;
2795
+ }
2796
+ async findAllWithSort(e, t, r) {
2797
+ const i = this.configureHeaders(), s = await this.client.get(
2798
+ `${this.getEndpoint()}/findAll?page=${e}&size=${t}&sort=${r}`,
2799
+ i,
2800
+ !1
2801
+ );
2802
+ return this.transformPage(s), s;
2803
+ }
2804
+ async findAllByIds(e) {
2805
+ const t = this.configureHeaders(), r = await this.client.get(`${this.getEndpoint()}/findAll?ids=${e}`, t, !1);
2806
+ return this.transformList(r), r;
2807
+ }
2808
+ async findAllWithFilter(e, t, r) {
2809
+ const i = this.configureHeaders(), s = await this.client.get(
2810
+ `${this.getEndpoint()}/findWithFilter?page=${t}&size=${r}&filter=${encodeURIComponent(
2811
+ e
2812
+ )}`,
2813
+ i,
2814
+ !1
2815
+ );
2816
+ return this.transformPage(s), s;
2817
+ }
2818
+ async findAllMultipleFields(e, t, r, i, s) {
2819
+ const o = this.configureHeaders(), c = await this.client.get(
2820
+ `${this.getEndpoint()}/findMultipleFields?page=${r}&size=${i}&fields=${encodeURIComponent(
2821
+ t
2822
+ )}&filter=${encodeURIComponent(e)}&sort=${encodeURIComponent(s)}`,
2823
+ o,
2824
+ !1
2825
+ );
2826
+ return this.transformPage(c), c;
2827
+ }
2828
+ async findAllWithFilterAndSort(e, t, r, i) {
2829
+ const s = this.configureHeaders(), o = `${this.getEndpoint()}/findWithFilterAndSort?page=${t}&size=${r}&filter=${encodeURIComponent(
2830
+ e
2831
+ )}&sort=${i}`;
2832
+ console.log("[findAllWithFilterAndSort] URL:", o), console.log("[findAllWithFilterAndSort] filter original:", e);
2833
+ const c = await this.client.get(o, s, !1);
2834
+ return this.transformPage(c), c;
2835
+ }
2836
+ async findOne(e) {
2837
+ const t = this.configureHeaders(), r = await this.client.get(`${this.getEndpoint()}/${e}`, t, !1);
2838
+ return this.isTransformable() ? this.transform(r) : r;
2839
+ }
2840
+ async findByComplexId(e) {
2841
+ const t = this.configureHeaders();
2842
+ return this.client.post(`${this.getEndpoint()}`, e, t, !1);
2843
+ }
2844
+ async existsByComplexId(e) {
2845
+ const t = this.configureHeaders();
2846
+ return this.client.post(`${this.getEndpoint()}`, e, t, !1);
2847
+ }
2848
+ async save(e) {
2849
+ const t = this.configureHeaders();
2850
+ let r;
2851
+ return this.isNewRecord(e) ? r = await this.client.post(this.getEndpoint(), e, t, !1) : r = await this.client.put(`${this.getEndpoint()}/${e.id}`, e, t, !1), this.isTransformable() ? this.transform(r) : r;
2852
+ }
2853
+ async delete(e) {
2854
+ const t = this.configureHeaders();
2855
+ return this.client.delete(`${this.getEndpoint()}/${e}`, t, !1);
2856
+ }
2857
+ }
2858
+ ne.decorate(ne.injectable(), Qe);
2859
+ class ge {
2860
+ content;
2861
+ pageable;
2862
+ totalElements;
2863
+ totalPages;
2864
+ last;
2865
+ sort;
2866
+ number;
2867
+ size;
2868
+ first;
2869
+ numberOfElements;
2870
+ empty;
2871
+ constructor(e, t, r, i, s, o, c, f, R, b) {
2872
+ this.content = e, this.totalElements = t, this.totalPages = r, this.number = i, this.size = s, this.sort = o || { sorted: !1, unsorted: !0, empty: !0 }, this.last = c !== void 0 ? c : i === r - 1, this.first = f !== void 0 ? f : i === 0, this.numberOfElements = R !== void 0 ? R : e.length, this.empty = b !== void 0 ? b : e.length === 0, this.pageable = {
2873
+ sort: this.sort,
2874
+ offset: i * s,
2875
+ pageSize: s,
2876
+ pageNumber: i,
2877
+ unpaged: !1,
2878
+ paged: !0
2879
+ };
2880
+ }
2881
+ static createFromValues(e, t, r, i, s) {
2882
+ return new ge(e, t, r, i, s);
2883
+ }
2884
+ }
2885
+ function Ke(n) {
2886
+ return n.totalElements || n.totalElements === 0 ? n.totalElements : n.page.totalElements;
2887
+ }
2888
+ function Ye(n) {
2889
+ return n.totalPages || n.totalPages === 0 ? n.totalPages : n.page.totalPages;
2890
+ }
2891
+ function Xe(n) {
2892
+ return n.pageable ? n.pageable.pageNumber : n.page.number;
2893
+ }
2894
+ function Dt(n) {
2895
+ const {
2896
+ name: e,
2897
+ label: t,
2898
+ service: r,
2899
+ filter: i,
2900
+ sort: s,
2901
+ transformData: o,
2902
+ onLoadComplete: c,
2903
+ onDestroy: f,
2904
+ filterData: R,
2905
+ findAll: b,
2906
+ findAllWithSort: N,
2907
+ findAllWithFilter: W,
2908
+ findAllWithFilterAndSort: T,
2909
+ initialDataSource: O,
2910
+ pageSize: $ = 50,
2911
+ currentPage: z = 0,
2912
+ loadOnStart: u = !0,
2913
+ store: a,
2914
+ id: V,
2915
+ validator: Y
2916
+ } = n, S = le(!1), h = () => !!(a && a.existsValue(e) || O), Q = () => a && a.existsValue(e) ? a.getValue(e) : O || new Ce(r, e, {
2917
+ records: [],
2918
+ grandTotalRecords: 0,
2919
+ currentPage: z,
2920
+ totalPages: 0,
2921
+ pageSize: $,
2922
+ validator: Y
2923
+ }, t), X = () => a && a.existsValue(e) ? a.getValue(e).getCurrentPage() : O ? O.getCurrentPage() : 0, [I, G] = C({
2924
+ dataSource: Q(),
2925
+ isLoading: !1,
2926
+ isError: !1,
2927
+ error: "",
2928
+ name: e,
2929
+ label: t,
2930
+ filter: i,
2931
+ sort: s,
2932
+ id: V,
2933
+ currentPage: X(),
2934
+ pageSize: $,
2935
+ loadDataCount: h() ? 1 : 0
2936
+ }), Z = async (p, v, x, L, y, q, te, oe, ae) => {
2937
+ let B;
2938
+ if (q) {
2939
+ const K = await r.findOne(q);
2940
+ K ? B = ge.createFromValues([K], 1, 0, 0, 0) : B = ge.createFromValues([], 0, 0, 0, 0);
2941
+ } else
2942
+ T && L && y && y.length > 0 ? B = await T(L, v, x, y) : W && L ? B = await W(L, v, x) : N && y && y.length > 0 ? B = await N(v, x, y) : b ? B = await b(v, x) : L && y && y.length > 0 ? B = await r.findAllWithFilterAndSort(L, v, x, y) : L ? B = await r.findAllWithFilter(L, v, x) : y && y.length > 0 ? B = await r.findAllWithSort(v, x, y) : B = await r.findAll(v, x);
2943
+ R && (B = R(B)), o && (B = o(B)), G((K) => {
2944
+ const re = {
2945
+ records: B.content,
2946
+ grandTotalRecords: Ke(B),
2947
+ totalPages: Ye(B),
2948
+ currentPage: Xe(B),
2949
+ pageSize: x,
2950
+ filter: L,
2951
+ sort: y,
2952
+ originFilter: te,
2953
+ originGlobalFilter: ae,
2954
+ originSort: oe,
2955
+ validator: Y
2956
+ };
2957
+ return K.dataSource.isActive() ? K.dataSource.setData(re) : K.dataSource.open(re), {
2958
+ ...K,
2959
+ currentPage: v,
2960
+ pageSize: x,
2961
+ filter: L,
2962
+ sort: y,
2963
+ id: q,
2964
+ isLoading: !1,
2965
+ isError: !1,
2966
+ error: "",
2967
+ loadDataCount: K.loadDataCount + 1
2968
+ };
2969
+ }), a && a.setValue(e, I.dataSource);
2970
+ };
2971
+ J(() => {
2972
+ c && I.loadDataCount > 0 && c(I.dataSource);
2973
+ }, [I.loadDataCount]);
2974
+ const D = l((p) => {
2975
+ if (p.type === d.refreshData) {
2976
+ const v = p.options;
2977
+ try {
2978
+ G((x) => ({
2979
+ ...x,
2980
+ isLoading: !0,
2981
+ filter: v.filter,
2982
+ sort: v.sort,
2983
+ currentPage: v.currentPage,
2984
+ id: v.id
2985
+ })), Z(
2986
+ I.name,
2987
+ v.currentPage,
2988
+ v.pageSize,
2989
+ v.filter,
2990
+ v.sort,
2991
+ v.id,
2992
+ v.originFilter,
2993
+ v.originSort,
2994
+ v.originGlobalFilter
2995
+ ).catch((x) => {
2996
+ const L = k(x);
2997
+ G((y) => ({
2998
+ ...y,
2999
+ isError: !0,
3000
+ isLoading: !1,
3001
+ error: L
3002
+ })), n.onError && n.onError(L, x);
3003
+ });
3004
+ } catch (x) {
3005
+ const L = k(x);
3006
+ G((y) => ({
3007
+ ...y,
3008
+ isError: !0,
3009
+ isLoading: !1,
3010
+ error: L
3011
+ })), n.onError && n.onError(L, x);
3012
+ }
3013
+ }
3014
+ }, [Z, I.name, n.onError]), E = l((p) => {
3015
+ S.current || (p.addListener(D), S.current = !0);
3016
+ }, [D]), A = l((p) => {
3017
+ S.current && (p.removeListener(D), S.current = !1);
3018
+ }, [D]);
3019
+ J(() => {
3020
+ try {
3021
+ return E(I.dataSource), u && I.loadDataCount === 0 ? (G((p) => ({ ...p, isLoading: !0 })), Z(
3022
+ I.name,
3023
+ z,
3024
+ $,
3025
+ I.filter,
3026
+ I.sort,
3027
+ I.id
3028
+ ).catch((p) => {
3029
+ const v = k(p);
3030
+ G((x) => ({
3031
+ ...x,
3032
+ isError: !0,
3033
+ isLoading: !1,
3034
+ error: v
3035
+ })), n.onError && n.onError(v, p);
3036
+ })) : c && c(I.dataSource), () => {
3037
+ f && (A(I.dataSource), f(I.dataSource));
3038
+ };
3039
+ } catch (p) {
3040
+ const v = k(p);
3041
+ G((x) => ({
3042
+ ...x,
3043
+ isError: !0,
3044
+ isLoading: !1,
3045
+ error: v
3046
+ })), n.onError && n.onError(v, p);
3047
+ }
3048
+ }, [
3049
+ I.name,
3050
+ I.sort,
3051
+ I.filter,
3052
+ I.id,
3053
+ I.currentPage,
3054
+ I.pageSize
3055
+ ]);
3056
+ const P = () => {
3057
+ G((p) => ({
3058
+ ...p,
3059
+ isError: !1,
3060
+ isLoading: !1,
3061
+ error: ""
3062
+ }));
3063
+ };
3064
+ return {
3065
+ isLoading: I.isLoading,
3066
+ isError: I.isError,
3067
+ error: I.error,
3068
+ dataSource: I.dataSource,
3069
+ clearError: P
3070
+ };
3071
+ }
3072
+ function Ze(n) {
3073
+ return n.totalElements || n.totalElements === 0 ? n.totalElements : n.page.totalElements;
3074
+ }
3075
+ function et(n) {
3076
+ return n.totalPages || n.totalPages === 0 ? n.totalPages : n.page.totalPages;
3077
+ }
3078
+ function tt(n) {
3079
+ return n.pageable ? n.pageable.pageNumber : n.page.number;
3080
+ }
3081
+ function Vt(n) {
3082
+ const {
3083
+ name: e,
3084
+ service: t,
3085
+ filter: r,
3086
+ sort: i,
3087
+ transformData: s,
3088
+ onLoadComplete: o,
3089
+ onDestroy: c,
3090
+ filterData: f,
3091
+ findAll: R,
3092
+ findAllWithSort: b,
3093
+ findAllWithFilter: N,
3094
+ findAllWithFilterAndSort: W,
3095
+ initialDataSource: T,
3096
+ pageSize: O = 50,
3097
+ currentPage: $ = 0,
3098
+ loadOnStart: z = !0,
3099
+ store: u,
3100
+ validator: a
3101
+ } = n, V = () => !!(u && u.existsValue(e) || T), Y = () => u && u.existsValue(e) ? u.getValue(e) : T || new _e(t, e, {
3102
+ records: [],
3103
+ grandTotalRecords: 0,
3104
+ currentPage: $,
3105
+ totalPages: 0,
3106
+ pageSize: O,
3107
+ validator: a
3108
+ }), [S, h] = C({
3109
+ dataSource: Y(),
3110
+ isLoading: !1,
3111
+ isError: !1,
3112
+ error: "",
3113
+ name: e,
3114
+ filter: r,
3115
+ sort: i,
3116
+ currentPage: $,
3117
+ pageSize: O,
3118
+ loadDataCount: V() ? 1 : 0
3119
+ }), Q = async (D, E, A, P, p, v, x, L) => {
3120
+ let y;
3121
+ W && P && p && p.length > 0 ? y = await W(P, E, A, p) : N && P ? y = await N(P, E, A) : b && p && p.length > 0 ? y = await b(E, A, p) : R ? y = await R(E, A) : P && p && p.length > 0 ? y = await t.findAllWithFilterAndSort(P, E, A, p) : P ? y = await t.findAllWithFilter(P, E, A) : p && p.length > 0 ? y = await t.findAllWithSort(E, A, p) : y = await t.findAll(E, A), f && (y = f(y)), s && (y = s(y)), h((q) => {
3122
+ const te = {
3123
+ records: y.content,
3124
+ grandTotalRecords: Ze(y),
3125
+ totalPages: et(y),
3126
+ currentPage: tt(y),
3127
+ pageSize: A,
3128
+ filter: P,
3129
+ sort: p,
3130
+ originFilter: v,
3131
+ originGlobalFilter: L,
3132
+ originSort: x,
3133
+ validator: a
3134
+ };
3135
+ return q.dataSource.isActive() ? q.dataSource.setData(te) : q.dataSource.open(te), {
3136
+ ...q,
3137
+ currentPage: E,
3138
+ pageSize: A,
3139
+ filter: P,
3140
+ sort: p,
3141
+ isLoading: !1,
3142
+ isError: !1,
3143
+ error: "",
3144
+ loadDataCount: q.loadDataCount + 1
3145
+ };
3146
+ }), u && u.setValue(e, S.dataSource), o && o(S.dataSource);
3147
+ }, X = (D) => {
3148
+ if (D.type === d.refreshData) {
3149
+ const E = D.options;
3150
+ try {
3151
+ h((A) => ({
3152
+ ...A,
3153
+ isLoading: !0,
3154
+ filter: E.filter,
3155
+ sort: E.sort,
3156
+ currentPage: E.currentPage
3157
+ })), Q(
3158
+ S.name,
3159
+ E.currentPage,
3160
+ E.pageSize,
3161
+ E.filter,
3162
+ E.sort,
3163
+ E.originFilter,
3164
+ E.originSort,
3165
+ E.originGlobalFilter
3166
+ ).catch((A) => {
3167
+ const P = k(A);
3168
+ h((p) => ({
3169
+ ...p,
3170
+ isError: !0,
3171
+ isLoading: !1,
3172
+ error: P
3173
+ })), n.onError && n.onError(P, A);
3174
+ });
3175
+ } catch (A) {
3176
+ const P = k(A);
3177
+ h((p) => ({
3178
+ ...p,
3179
+ isError: !0,
3180
+ isLoading: !1,
3181
+ error: P
3182
+ })), n.onError && n.onError(P, A);
3183
+ }
3184
+ }
3185
+ }, I = (D) => {
3186
+ D.addListener(X);
3187
+ }, G = (D) => {
3188
+ D.removeListener(X);
3189
+ };
3190
+ J(() => {
3191
+ try {
3192
+ return I(S.dataSource), z && S.loadDataCount === 0 && (h((D) => ({ ...D, isLoading: !0 })), Q(
3193
+ S.name,
3194
+ $,
3195
+ O,
3196
+ S.filter,
3197
+ S.sort
3198
+ ).catch((D) => {
3199
+ const E = k(D);
3200
+ h((A) => ({
3201
+ ...A,
3202
+ isError: !0,
3203
+ isLoading: !1,
3204
+ error: E
3205
+ })), n.onError && n.onError(E, D);
3206
+ })), () => {
3207
+ c && (G(S.dataSource), c(S.dataSource));
3208
+ };
3209
+ } catch (D) {
3210
+ const E = k(D);
3211
+ h((A) => ({
3212
+ ...A,
3213
+ isError: !0,
3214
+ isLoading: !1,
3215
+ error: E
3216
+ })), n.onError && n.onError(E, D);
3217
+ }
3218
+ }, [
3219
+ S.name,
3220
+ S.sort,
3221
+ S.filter,
3222
+ S.currentPage,
3223
+ S.pageSize
3224
+ ]);
3225
+ const Z = () => {
3226
+ h((D) => ({
3227
+ ...D,
3228
+ isError: !1,
3229
+ isLoading: !1,
3230
+ error: ""
3231
+ }));
3232
+ };
3233
+ return {
3234
+ isLoading: S.isLoading,
3235
+ isError: S.isError,
3236
+ error: S.error,
3237
+ dataSource: S.dataSource,
3238
+ clearError: Z
3239
+ };
3240
+ }
3241
+ function Tt(n) {
3242
+ return ze((e) => e.get(n));
3243
+ }
3244
+ function Ot(n) {
3245
+ J(() => {
3246
+ n();
3247
+ }, []);
3248
+ }
3249
+ function Pt(n, e) {
3250
+ J(() => {
3251
+ n();
3252
+ }, e);
3253
+ }
3254
+ function Lt(n) {
3255
+ J(() => () => {
3256
+ n();
3257
+ }, []);
3258
+ }
3259
+ function Bt() {
3260
+ const [, n] = C(0);
3261
+ return l(() => {
3262
+ n((t) => t + 1);
3263
+ }, []);
3264
+ }
3265
+ const rt = (n) => (n + 1) % 1e6;
3266
+ function it() {
3267
+ const [, n] = We(rt, 0);
3268
+ return n;
3269
+ }
3270
+ function $t() {
3271
+ return it();
3272
+ }
3273
+ const st = Me((n, e) => ({
3274
+ values: /* @__PURE__ */ new Map(),
3275
+ setValue: (t, r) => n((i) => {
3276
+ const s = new Map(i.values);
3277
+ return s.set(t, r), { values: s };
3278
+ }),
3279
+ getValue: (t) => e().values.get(t),
3280
+ existsValue: (t) => e().values.has(t),
3281
+ clearValue: (t) => n((r) => {
3282
+ const i = new Map(r.values);
3283
+ return i.delete(t), { values: i };
3284
+ }),
3285
+ clearAllValues: () => n((t) => ({ values: /* @__PURE__ */ new Map() })),
3286
+ reset: () => n((t) => ({ values: /* @__PURE__ */ new Map() }))
3287
+ })), nt = je(st), Nt = (n = "default") => {
3288
+ const e = nt();
3289
+ return { setValue: (R, b) => {
3290
+ e.setValue(`${n}.${R}`, b);
3291
+ }, getValue: (R) => e.getValue(`${n}.${R}`), clearValue: (R) => {
3292
+ e.clearValue(`${n}.${R}`);
3293
+ }, existsValue: (R) => e.existsValue(`${n}.${R}`), clearAllValues: () => {
3294
+ for (const [R, b] of e.values.entries())
3295
+ R.startsWith(`${n}.`) && e.clearValue(R);
3296
+ }, reset: () => {
3297
+ e.clearAllValues();
3298
+ }, values: e.values };
3299
+ };
3300
+ function Ht(n, e, t = window) {
3301
+ const r = le(e);
3302
+ J(() => {
3303
+ r.current = e;
3304
+ }, [e]), J(
3305
+ () => {
3306
+ if (t && t.addEventListener && r.current) {
3307
+ const s = (o) => r.current(o);
3308
+ return t.addEventListener(n, s), () => {
3309
+ t.removeEventListener(n, s);
3310
+ };
3311
+ }
3312
+ },
3313
+ [n, t]
3314
+ // Executa novamente se eventName ou elemento mudar
3315
+ );
3316
+ }
3317
+ export {
3318
+ Mt as ADVANCED,
3319
+ jt as ARCHBASE_IOC_API_TYPE,
3320
+ At as ARCHBASE_QUERY_DEFAULTS,
3321
+ Ve as ArchbaseAxiosRemoteApiClient,
3322
+ Ie as ArchbaseDataSource,
3323
+ U as ArchbaseDataSourceV2,
3324
+ ke as ArchbaseLocalFilterDataSource,
3325
+ Ft as ArchbaseQueryUtils,
3326
+ Qe as ArchbaseRemoteApiService,
3327
+ Ce as ArchbaseRemoteDataSource,
3328
+ Je as ArchbaseRemoteDataSourceV2,
3329
+ _e as ArchbaseRemoteFilterDataSource,
3330
+ d as DataSourceEventNames,
3331
+ ge as DefaultPage,
3332
+ Ut as FILTER_TYPE,
3333
+ Ge as LocalFilter,
3334
+ yt as MigrationValidation,
3335
+ Gt as NORMAL,
3336
+ kt as QUICK,
3337
+ qe as RemoteFilter,
3338
+ vt as USAGE_EXAMPLE,
3339
+ qt as useArchbaseBool,
3340
+ xt as useArchbaseDataSource,
3341
+ Ct as useArchbaseDataSourceListener,
3342
+ be as useArchbaseDataSourceV2,
3343
+ wt as useArchbaseDataSourceV2Editor,
3344
+ It as useArchbaseDataSourceV2ReadOnly,
3345
+ Ot as useArchbaseDidMount,
3346
+ Pt as useArchbaseDidUpdate,
3347
+ Ht as useArchbaseEventListener,
3348
+ Bt as useArchbaseForceRerender,
3349
+ $t as useArchbaseForceUpdate,
3350
+ bt as useArchbaseLocalFilterDataSource,
3351
+ Dt as useArchbaseRemoteDataSource,
3352
+ De as useArchbaseRemoteDataSourceV2,
3353
+ St as useArchbaseRemoteDataSourceV2Editor,
3354
+ Et as useArchbaseRemoteDataSourceV2ReadOnly,
3355
+ Vt as useArchbaseRemoteFilterDataSource,
3356
+ Tt as useArchbaseRemoteServiceApi,
3357
+ Nt as useArchbaseStore,
3358
+ pt as useArchbaseV1V2Compatibility,
3359
+ Lt as useArchbaseWillUnmount
3360
+ };