@sankhyalabs/core 6.1.1 → 6.2.0-ms.1

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 (106) hide show
  1. package/.docs/classes/Change.md +11 -11
  2. package/.docs/classes/ColumnFilterManager.md +6 -6
  3. package/.docs/classes/DataUnit.md +158 -158
  4. package/.docs/classes/DataUnitLoaderUtils.md +6 -6
  5. package/.docs/classes/LangUtils.md +195 -0
  6. package/.docs/classes/SelectionInfo.md +16 -16
  7. package/.docs/enumerations/ChangeOperation.md +4 -4
  8. package/.docs/enumerations/SelectionMode.md +2 -2
  9. package/.docs/functions/defaultDataLoader.md +1 -1
  10. package/.docs/globals.md +1 -0
  11. package/.docs/interfaces/DUActionInterceptor.md +1 -1
  12. package/.docs/interfaces/PageRequest.md +3 -3
  13. package/.docs/interfaces/PaginationInfoBuilderParams.md +3 -3
  14. package/.docs/interfaces/QuickFilter.md +3 -3
  15. package/.docs/interfaces/Record.md +4 -4
  16. package/.docs/interfaces/SavedRecord.md +5 -5
  17. package/.docs/interfaces/WaitingChange.md +3 -3
  18. package/.docs/type-aliases/DataUnitEventOptions.md +1 -1
  19. package/dist/dataunit/Changes.d.ts +52 -0
  20. package/dist/dataunit/Changes.js +64 -0
  21. package/dist/dataunit/Changes.js.map +1 -0
  22. package/dist/dataunit/DataUnit.d.ts +9 -129
  23. package/dist/dataunit/DataUnit.js +87 -177
  24. package/dist/dataunit/DataUnit.js.map +1 -1
  25. package/dist/dataunit/DataUnitHelper.d.ts +2 -1
  26. package/dist/dataunit/DataUnitHelper.js.map +1 -1
  27. package/dist/dataunit/SelectionInfo.d.ts +16 -0
  28. package/dist/dataunit/SelectionInfo.js +39 -0
  29. package/dist/dataunit/SelectionInfo.js.map +1 -0
  30. package/dist/dataunit/formatting/PrettyFormatter.js +5 -3
  31. package/dist/dataunit/formatting/PrettyFormatter.js.map +1 -1
  32. package/dist/dataunit/interfaces/dataUnit.d.ts +61 -0
  33. package/dist/dataunit/interfaces/dataUnit.js +13 -0
  34. package/dist/dataunit/interfaces/dataUnit.js.map +1 -0
  35. package/dist/dataunit/loader/utils/dataUnitLoaderUtils.d.ts +2 -1
  36. package/dist/dataunit/loader/utils/dataUnitLoaderUtils.js.map +1 -1
  37. package/dist/dataunit/loading/LoadDataRequest.d.ts +1 -1
  38. package/dist/dataunit/loading/LoadDataResponse.d.ts +1 -1
  39. package/dist/dataunit/sorting/FieldComparator.d.ts +1 -1
  40. package/dist/dataunit/state/slice/AddedRecordsSlice.d.ts +1 -1
  41. package/dist/dataunit/state/slice/ChangesSlice.d.ts +2 -1
  42. package/dist/dataunit/state/slice/ChangesSlice.js +2 -1
  43. package/dist/dataunit/state/slice/ChangesSlice.js.map +1 -1
  44. package/dist/dataunit/state/slice/LoadingControlSlice.js.map +1 -1
  45. package/dist/dataunit/state/slice/RecordsSlice.d.ts +1 -1
  46. package/dist/dataunit/state/slice/RecordsSlice.js +1 -1
  47. package/dist/dataunit/state/slice/RecordsSlice.js.map +1 -1
  48. package/dist/dataunit/state/slice/SelectionSlice.d.ts +2 -1
  49. package/dist/dataunit/state/slice/SelectionSlice.js +2 -1
  50. package/dist/dataunit/state/slice/SelectionSlice.js.map +1 -1
  51. package/dist/dataunit/state/slice/SnapshotSlice.d.ts +1 -1
  52. package/dist/dataunit/state/slice/WaitingChangesSlice.d.ts +1 -1
  53. package/dist/index.d.ts +6 -2
  54. package/dist/index.js +6 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/utils/ColumnFilterManager.d.ts +2 -1
  57. package/dist/utils/ColumnFilterManager.js.map +1 -1
  58. package/dist/utils/LangUtils.d.ts +83 -0
  59. package/dist/utils/LangUtils.js +121 -0
  60. package/dist/utils/LangUtils.js.map +1 -0
  61. package/dist/utils/SortingUtils.d.ts +1 -1
  62. package/package.json +2 -1
  63. package/reports/test-report.xml +657 -440
  64. package/src/dataunit/Changes.ts +77 -0
  65. package/src/dataunit/DataUnit.ts +242 -397
  66. package/src/dataunit/DataUnitHelper.ts +2 -1
  67. package/src/dataunit/SelectionInfo.ts +55 -0
  68. package/src/dataunit/formatting/PrettyFormatter.ts +4 -5
  69. package/src/dataunit/interfaces/dataUnit.ts +71 -0
  70. package/src/dataunit/loader/utils/dataUnitLoaderUtils.ts +2 -1
  71. package/src/dataunit/loading/LoadDataRequest.ts +1 -1
  72. package/src/dataunit/loading/LoadDataResponse.ts +1 -1
  73. package/src/dataunit/sorting/FieldComparator.ts +1 -1
  74. package/src/dataunit/state/slice/AddedRecordsSlice.ts +1 -1
  75. package/src/dataunit/state/slice/ChangesSlice.ts +2 -1
  76. package/src/dataunit/state/slice/LoadingControlSlice.ts +1 -2
  77. package/src/dataunit/state/slice/RecordsSlice.ts +3 -2
  78. package/src/dataunit/state/slice/SelectionSlice.ts +2 -1
  79. package/src/dataunit/state/slice/SnapshotSlice.ts +1 -1
  80. package/src/dataunit/state/slice/WaitingChangesSlice.ts +1 -1
  81. package/src/dataunit/state/slice/test/RecordsSlice.spec.ts +1 -1
  82. package/src/index.ts +6 -2
  83. package/src/utils/ColumnFilterManager.ts +2 -1
  84. package/src/utils/LangUtils.ts +129 -0
  85. package/src/utils/SortingUtils.ts +1 -1
  86. package/test/dataunit/AccessParentsDataUnit.spec.ts +69 -0
  87. package/test/dataunit/Actions.spec.ts +74 -0
  88. package/test/dataunit/Change.spec.ts +66 -0
  89. package/test/dataunit/FieldManager.spec.ts +286 -0
  90. package/test/dataunit/FilterSortsLockersAndObservers.spec.ts +339 -0
  91. package/test/dataunit/InfoManager.spec.ts +254 -0
  92. package/test/dataunit/LoadDataAndMetadata.spec.ts +269 -0
  93. package/test/dataunit/RecodsSelection.spec.ts +229 -0
  94. package/test/dataunit/RecordsManager.spec.ts +323 -0
  95. package/test/dataunit/SavingData.spec.ts +206 -0
  96. package/test/dataunit/SelectionInfo.spec.ts +143 -0
  97. package/test/dataunit/formatting/PrettyFormatter.spec.ts +1 -1
  98. package/test/dataunit/loader/dataUnitInMemoryLoader.spec.ts +2 -1
  99. package/test/dataunit/loader/utils/createDataUnitMock.ts +34 -0
  100. package/test/dataunit/loader/utils/dataUnitLoaderUtils.spec.ts +1 -1
  101. package/test/dataunit/resources/metadata.ts +39 -0
  102. package/test/dataunit/resources/records.ts +29 -0
  103. package/test/util/ColumnFilterManager.spec.ts +2 -1
  104. package/test/util/LangUtils.spec.ts +117 -0
  105. package/tsconfig.json +1 -0
  106. package/src/dataunit/test/DataUnit.spec.ts +0 -44
@@ -29,12 +29,15 @@ import { getLoadingProperties, LoadingPropertiesReducer } from "./state/slice/Lo
29
29
  import SortingUtils from "../utils/SortingUtils.js";
30
30
  import ServiceCanceledException from "../exceptions/ServiceCanceledException.js";
31
31
  import SilentException from "../exceptions/SilentException.js";
32
+ import { DataUnitEventOptions, DUActionInterceptor, HideFieldOptions, LoadDataParams, QuickFilter, Record, SavedRecord, SelectionMode, WaitingChange } from "./interfaces/dataUnit.js";
33
+ import { Change } from "./Changes.js";
34
+ import { SelectionInfo } from "./SelectionInfo.js";
32
35
 
33
36
  /***
34
37
  * `DataUnit`: Atua como uma camada de abstração entre o back-end e a interface do usuário.
35
38
  */
36
39
  export default class DataUnit {
37
-
40
+
38
41
  public static CHANGING_PAGE_LOADING_SOURCE = "CHANGING_PAGE_LOADING_SOURCE";
39
42
  public static ALL_RECORDS_SELECTION_SOURCE = "ALL_RECORDS_SELECTION_SOURCE";
40
43
  public static DEFAULT_DATAUNIT_NAME = "dataunit";
@@ -57,7 +60,7 @@ export default class DataUnit {
57
60
  private _cancelPagination: boolean = false;
58
61
  private _isMultipleEdition: boolean = false;
59
62
  private _fieldSourceValue: Map<string, string> = new Map<string, string>();
60
-
63
+
61
64
  public metadataLoader?: (dataUnit: DataUnit) => Promise<UnitMetadata>;
62
65
  public dataLoader?: (dataUnit: DataUnit, request: LoadDataRequest) => Promise<LoadDataResponse>;
63
66
  public saveLoader?: (dataUnit: DataUnit, changes: Array<Change>) => Promise<Array<SavedRecord>>;
@@ -100,9 +103,9 @@ export default class DataUnit {
100
103
  /**
101
104
  * Desfaz vinculos do DataUnit. Chamado quando o DU não é mais necessário.
102
105
  */
103
- public release(){
106
+ public release() {
104
107
  DataUnitStorage.remove(this._name);
105
- if(this._parentDataUnit){
108
+ if (this._parentDataUnit) {
106
109
  this._parentDataUnit.unsubscribe(this.onDataUnitParentEvent);
107
110
  this._parentDataUnit.removeChildDataunit(this._name);
108
111
  }
@@ -120,8 +123,8 @@ export default class DataUnit {
120
123
  * - Observers
121
124
  * - Sorting Providers
122
125
  */
123
- public releaseCallbacks(){
124
- if(!this._allowReleaseCallbacks) return;
126
+ public releaseCallbacks() {
127
+ if (!this._allowReleaseCallbacks) return;
125
128
 
126
129
  this._observers = new Map();
127
130
  this._filterProviders = new Map<string, FilterProvider>();
@@ -138,8 +141,8 @@ export default class DataUnit {
138
141
  * @param value - Valor da propriedade
139
142
  *
140
143
  */
141
- public addGlobalLoaderProp(name: string, value: string):void{
142
- this.dispatchAction(Action.LOADING_PROPERTY_ADDED, {[name]: value});
144
+ public addGlobalLoaderProp(name: string, value: string): void {
145
+ this.dispatchAction(Action.LOADING_PROPERTY_ADDED, { [name]: value });
143
146
  }
144
147
 
145
148
  /**
@@ -147,11 +150,11 @@ export default class DataUnit {
147
150
  *
148
151
  * @returns - Todas as propriedades desde o final do último loader.
149
152
  */
150
- public getGlobalLoaderProps(): Map<string, string>{
153
+ public getGlobalLoaderProps(): Map<string, string> {
151
154
  return getLoadingProperties(this._stateManager) || new Map();
152
155
  }
153
156
 
154
- public get dataUnitId(): string{
157
+ public get dataUnitId(): string {
155
158
  return this._uuid;
156
159
  }
157
160
 
@@ -167,7 +170,7 @@ export default class DataUnit {
167
170
  * Define se o dataUnit tem um recarregamento pendente.
168
171
  * @param isWaiting
169
172
  */
170
- public setWaitingToReload(isWaiting: boolean){
173
+ public setWaitingToReload(isWaiting: boolean) {
171
174
  this._waitingToReload = isWaiting;
172
175
  }
173
176
 
@@ -197,7 +200,7 @@ export default class DataUnit {
197
200
  */
198
201
  public set isMultipleEdition(isMultipleEdition) {
199
202
  this._isMultipleEdition = isMultipleEdition;
200
- this.dispatchAction(Action.MULTIPLE_EDITION_CHANGED, {isMultipleEdition});
203
+ this.dispatchAction(Action.MULTIPLE_EDITION_CHANGED, { isMultipleEdition });
201
204
  }
202
205
 
203
206
  /**
@@ -233,7 +236,7 @@ export default class DataUnit {
233
236
  *
234
237
  */
235
238
  private onDataUnitParentEvent = (action: DataUnitAction) => {
236
- switch(action.type){
239
+ switch (action.type) {
237
240
  case Action.SELECTION_CHANGED:
238
241
  case Action.NEXT_SELECTED:
239
242
  case Action.PREVIOUS_SELECTED:
@@ -242,7 +245,7 @@ export default class DataUnit {
242
245
  case Action.EDITION_CANCELED:
243
246
  this.clearDataUnit();
244
247
  const selectedRecord = this._parentDataUnit?.getSelectedRecord();
245
- if(selectedRecord != undefined && !this.isNewRecord(selectedRecord.__record__id__)){
248
+ if (selectedRecord != undefined && !this.isNewRecord(selectedRecord.__record__id__)) {
246
249
  this.loadData();
247
250
  }
248
251
  break;
@@ -278,15 +281,15 @@ export default class DataUnit {
278
281
  */
279
282
  private executeLoadData(request: LoadDataRequest, executionCtx?: ExecutionContext, checkLastFilter?: boolean, selectFirstRecord?: boolean): Promise<LoadDataResponse> {
280
283
 
281
- if(checkLastFilter && this.isSameRequest(request)){
282
- const paginationInfo = getPaginationInfo(this._stateManager);
283
- if(paginationInfo){
284
+ if (checkLastFilter && this.isSameRequest(request)) {
285
+ const paginationInfo = this.getPaginationInfo();
286
+ if (paginationInfo) {
284
287
  const response: LoadDataResponse = {
285
288
  records: getRecords(this._stateManager),
286
- paginationInfo
289
+ paginationInfo
287
290
  };
288
291
 
289
- if(selectFirstRecord){
292
+ if (selectFirstRecord) {
290
293
  this.requestSelectFirst(executionCtx);
291
294
  }
292
295
 
@@ -300,21 +303,21 @@ export default class DataUnit {
300
303
  this.dataLoader(this, request).then(
301
304
  async response => {
302
305
  await this.dispatchAction(
303
- Action.DATA_LOADED,
304
- {...response, keepSelection: request.keepSelection, filters: request.filters, selectFirstRecord},
306
+ Action.DATA_LOADED,
307
+ { ...response, keepSelection: request.keepSelection, filters: request.filters, selectFirstRecord },
305
308
  executionCtx
306
309
  );
307
310
 
308
311
  await this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
309
312
 
310
- if(selectFirstRecord){
313
+ if (selectFirstRecord) {
311
314
  this.requestSelectFirst(executionCtx);
312
315
  }
313
316
  resolve(response);
314
317
  }
315
318
  ).catch(error => {
316
319
  console.error(error);
317
- const {errorCode} = error;
320
+ const { errorCode } = error;
318
321
  this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
319
322
  fail(new ErrorException("Erro ao carregar registros", error, errorCode))
320
323
  });
@@ -323,13 +326,13 @@ export default class DataUnit {
323
326
  });
324
327
  }
325
328
 
326
- private requestSelectFirst(executionCtx?: ExecutionContext){
329
+ private requestSelectFirst(executionCtx?: ExecutionContext) {
327
330
  window.requestAnimationFrame(() => {
328
331
  this.selectFirst(executionCtx);
329
332
  })
330
333
  }
331
334
 
332
- private isSameRequest(request: LoadDataRequest): boolean{
335
+ private isSameRequest(request: LoadDataRequest): boolean {
333
336
  const lastRequest = getCurrentRequest(this._stateManager);
334
337
  return ObjectUtils.objectToString(request) === ObjectUtils.objectToString(lastRequest || {});
335
338
  }
@@ -354,7 +357,7 @@ export default class DataUnit {
354
357
  resolve(this.metadata);
355
358
  }
356
359
  ).catch(error => {
357
- const {errorCode} = error;
360
+ const { errorCode } = error;
358
361
  fail(new ErrorException("Erro ao carregar metadados", error, errorCode))
359
362
  });
360
363
  }
@@ -362,7 +365,7 @@ export default class DataUnit {
362
365
  }
363
366
  }
364
367
 
365
- public async loadDataWithParams({source, keepSelection, selectFirstRecord, executionCtx, checkLastFilter, quickFilter}: LoadDataParams): Promise<LoadDataResponse> {
368
+ public async loadDataWithParams({ source, keepSelection, selectFirstRecord, executionCtx, checkLastFilter, quickFilter }: LoadDataParams): Promise<LoadDataResponse> {
366
369
  return await this.loadData(quickFilter, executionCtx, checkLastFilter, source, selectFirstRecord, keepSelection);
367
370
  }
368
371
 
@@ -378,13 +381,13 @@ export default class DataUnit {
378
381
  *
379
382
  */
380
383
  public async loadData(quickFilter?: QuickFilter, executionCtx?: ExecutionContext, checkLastFilter?: boolean, source?: string, selectFirstRecord?: boolean, keepSelection?: boolean): Promise<LoadDataResponse> {
381
-
384
+
382
385
  await this.processLoadingLockers();
383
386
 
384
387
  if (this._parentDataUnit) {
385
388
  const parentRecord = this._parentDataUnit.getSelectedRecord();
386
- if(parentRecord == undefined || this._parentDataUnit.isNewRecord(parentRecord.__record__id__)){
387
- if(this.records){
389
+ if (parentRecord == undefined || this._parentDataUnit.isNewRecord(parentRecord.__record__id__)) {
390
+ if (this.records) {
388
391
  this.clearDataUnit();
389
392
  }
390
393
  return Promise.resolve({
@@ -408,7 +411,7 @@ export default class DataUnit {
408
411
  *
409
412
  */
410
413
  public async gotoPage(page: number, executionCtx?: ExecutionContext): Promise<LoadDataResponse | void> {
411
- if(this._pageSize === 0) {
414
+ if (this._pageSize === 0) {
412
415
  return;
413
416
  }
414
417
 
@@ -479,13 +482,13 @@ export default class DataUnit {
479
482
  return request;
480
483
  }
481
484
 
482
- private async notifySavingData(executionCtx?: ExecutionContext): Promise<boolean>{
485
+ private async notifySavingData(executionCtx?: ExecutionContext): Promise<boolean> {
483
486
  const notifyPromises: Array<Promise<boolean>> = [];
484
487
  Array.from(this._childByName.values()).forEach(
485
488
  child => notifyPromises.push(child.notifySavingData(executionCtx))
486
489
  );
487
-
488
- if(isDirty(this._stateManager)){
490
+
491
+ if (isDirty(this._stateManager)) {
489
492
  notifyPromises.push(this.dispatchAction(Action.SAVING_DATA, undefined, executionCtx));
490
493
  }
491
494
 
@@ -494,8 +497,8 @@ export default class DataUnit {
494
497
  }));
495
498
  }
496
499
 
497
- private getBeforeSavePromisses(): Array<Promise<any>|undefined>{
498
- let promises = getWaitingChangePromisses(this._stateManager)||[];
500
+ private getBeforeSavePromisses(): Array<Promise<any> | undefined> {
501
+ let promises = getWaitingChangePromisses(this._stateManager) || [];
499
502
  promises = promises.concat(this._savingLockers);
500
503
  return promises;
501
504
  }
@@ -513,15 +516,18 @@ export default class DataUnit {
513
516
  const blockingWaitingChanges = getBlockingWaitingChanges(this._stateManager);
514
517
 
515
518
  if (blockingWaitingChanges && blockingWaitingChanges.size > 0) {
516
- const [_, waitingChange] = blockingWaitingChanges.entries().next().value;
517
- return Promise.reject(new WaitingChangeException("Aguardando alteração de campo", (waitingChange as WaitingChange).waitmessage));
519
+ const entry = blockingWaitingChanges.entries().next().value;
520
+ if (entry) {
521
+ const [_, waitingChange] = entry;
522
+ return Promise.reject(new WaitingChangeException("Aguardando alteração de campo", waitingChange.waitmessage));
523
+ }
518
524
  } else {
519
525
  if (this.isDirty()) {
520
526
 
521
527
  if (await this.notifySavingData(executionCtx)) {
522
528
  const promisses = this.getBeforeSavePromisses();
523
529
  return new Promise((resolve, fail) => {
524
- Promise.all(promisses || []).then(() => {
530
+ Promise.all(promisses).then(() => {
525
531
  this._savingLockers = [];
526
532
  if (this.saveLoader) {
527
533
  const changes: Array<Change> = this.getAllChangesToSave();
@@ -534,21 +540,21 @@ export default class DataUnit {
534
540
  for (const [ownerDataUnitName, splittedRecords] of recordsByDataUnit) {
535
541
  const ownerDataUnit = DataUnitStorage.get(ownerDataUnitName);
536
542
  const changesByDataUnit = changes.filter(change => change.dataUnit === ownerDataUnitName);
537
-
538
- if(ownerDataUnit){
543
+
544
+ if (ownerDataUnit) {
539
545
  dispatchPromisses.push(ownerDataUnit.dispatchAction(Action.DATA_SAVED, { changes: changesByDataUnit, records: splittedRecords }, executionCtx));
540
546
  }
541
547
  }
542
548
  Promise.all(dispatchPromisses).then(() => resolve());
543
549
  }).catch(cause => {
544
- const {errorCode} = cause;
550
+ const { errorCode } = cause;
545
551
  this.dispatchAction(Action.SAVING_ERROR);
546
552
  this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
547
- if(cause instanceof ServiceCanceledException){
553
+ if (cause instanceof ServiceCanceledException) {
548
554
  console.debug("Service canceled: " + cause.message);
549
555
  resolve();
550
- }
551
- if(cause instanceof SilentException){
556
+ }
557
+ if (cause instanceof SilentException) {
552
558
  fail(cause);
553
559
  return;
554
560
  }
@@ -576,17 +582,17 @@ export default class DataUnit {
576
582
  * @returns - Mudanças realizadas no DataUnit atual
577
583
  *
578
584
  */
579
- public buildChangesToSave(): Array<Change>{
585
+ public buildChangesToSave(): Array<Change> {
580
586
  return getChangesToSave(this._name, this._stateManager);
581
587
  }
582
588
 
583
589
  public buildChangesToSaveFromChild(allChanges: Array<Change>, dataUnit: DataUnit): void {
584
- dataUnit._childByName?.forEach((dataUnitChild: DataUnit) => {
590
+ dataUnit._childByName.forEach((dataUnitChild: DataUnit) => {
585
591
  if (dataUnitChild.isDirty()) {
586
- allChanges.push(...getChangesToSave(dataUnitChild.name, dataUnitChild._stateManager));
587
- this.buildChangesToSaveFromChild(allChanges, dataUnitChild);
592
+ allChanges.push(...getChangesToSave(dataUnitChild.name, dataUnitChild._stateManager));
593
+ this.buildChangesToSaveFromChild(allChanges, dataUnitChild);
588
594
  }
589
- });
595
+ });
590
596
  }
591
597
 
592
598
  /**
@@ -617,15 +623,18 @@ export default class DataUnit {
617
623
  */
618
624
  public async removeSelectedRecords(buffered: boolean = false, silent: boolean = false): Promise<Array<string>> {
619
625
  const selection = this.getSelectionInfo();
620
- if (selection) {
621
- if(selection.isAllRecords()){
622
- throw new Error("Exclusão remota não implementada.");
623
- }
624
- const records = selection?.records as Array<Record> || [];
625
- const recordIds = selection?.recordIds as Array<string> || [];
626
- return this.removeRecords(recordIds, records, buffered, undefined, silent);
626
+
627
+ if (selection.isAllRecords()) {
628
+ throw new Error("Exclusão remota não implementada.");
627
629
  }
628
- return Promise.resolve([]);
630
+
631
+ if (!selection.records || !selection.records.length) {
632
+ return Promise.resolve([]);
633
+ }
634
+
635
+ const records = selection.records;
636
+ const recordIds = selection.recordIds as Array<string>;
637
+ return this.removeRecords(recordIds, records, buffered, undefined, silent);
629
638
  }
630
639
 
631
640
  /**
@@ -647,7 +656,7 @@ export default class DataUnit {
647
656
  this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
648
657
  this.dispatchAction(Action.RECORDS_REMOVED, { records: recordIds, cachedRecords, buffered: true }, executionCtx);
649
658
  } else {
650
- if (await this.dispatchAction(Action.REMOVING_RECORDS, {silent}, executionCtx)) {
659
+ if (await this.dispatchAction(Action.REMOVING_RECORDS, { silent }, executionCtx)) {
651
660
 
652
661
  return new Promise((resolve, fail) => {
653
662
  if (this.removeLoader) {
@@ -668,7 +677,7 @@ export default class DataUnit {
668
677
  }
669
678
  ).catch(error => {
670
679
  this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
671
- const {errorCode} = error;
680
+ const { errorCode } = error;
672
681
  fail(new ErrorException("Erro ao remover registros", error, errorCode))
673
682
  });
674
683
  }
@@ -727,11 +736,11 @@ export default class DataUnit {
727
736
  const descriptor = this.getField(fieldName);
728
737
  if (value == undefined) {
729
738
  value = this.getFieldValue(fieldName);
730
- } else if (typeof value === "string" && descriptor?.dataType != DataType.TEXT){
739
+ } else if (typeof value === "string" && descriptor?.dataType != DataType.TEXT) {
731
740
  value = this.valueFromString(fieldName, value);
732
741
  }
733
742
 
734
- if(value == undefined){
743
+ if (value == undefined) {
735
744
  return "";
736
745
  }
737
746
 
@@ -778,7 +787,7 @@ export default class DataUnit {
778
787
  * @param provider - FilterProvider que será removido.
779
788
  *
780
789
  */
781
- public removeFilterProvider(provider: FilterProvider): boolean {
790
+ public removeFilterProvider(provider: FilterProvider): boolean {
782
791
  return this._filterProviders.delete(this.getFielterProviderKey(provider));
783
792
  }
784
793
 
@@ -843,18 +852,18 @@ export default class DataUnit {
843
852
  return getMetadata(this._stateManager);
844
853
  }
845
854
 
846
- /**
847
- *
848
- * Obtém informações da ligação para um DataUnit filho.
849
- *
850
- * @param name - Nome do DataUnit que se deseja.
851
- *
852
- * @returns - As informações sobre a ligação solicitada. Pode retornar undefined.
853
- *
854
- */
855
- public getChildInfo(name: string): ChildDescriptor|undefined {
855
+ /**
856
+ *
857
+ * Obtém informações da ligação para um DataUnit filho.
858
+ *
859
+ * @param name - Nome do DataUnit que se deseja.
860
+ *
861
+ * @returns - As informações sobre a ligação solicitada. Pode retornar undefined.
862
+ *
863
+ */
864
+ public getChildInfo(name: string): ChildDescriptor | undefined {
856
865
  const children = this.metadata?.children;
857
- if(children == undefined){
866
+ if (children == undefined) {
858
867
  return;
859
868
  }
860
869
 
@@ -971,41 +980,41 @@ export default class DataUnit {
971
980
  */
972
981
  public copySelected(executionCtx?: ExecutionContext): void {
973
982
  const selectionInfo = this.getSelectionInfo();
974
- if (selectionInfo) {
975
- if(selectionInfo.isAllRecords()){
976
- throw new Error("Erro interno: Impossível copiar os registros selecionados pois a seleção atual é virtual.");
977
- }
978
- const selectedRecords = selectionInfo.records as Array<Record>;
979
- if(selectedRecords){
980
-
981
- this.dispatchAction(Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords, this.getParentRecordId()), executionCtx);
982
- }
983
+
984
+ if (selectionInfo.isAllRecords()) {
985
+ throw new Error("Erro interno: Impossível copiar os registros selecionados pois a seleção atual é virtual.");
986
+ }
987
+
988
+ const selectedRecords = selectionInfo.records;
989
+
990
+ if (selectedRecords.length) {
991
+ this.dispatchAction(Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords, this.getParentRecordId()), executionCtx);
983
992
  }
984
993
  }
985
-
994
+
986
995
  private getRecordsByDataUnit(records: Array<Record>): Map<string, Array<Record>> {
987
996
  const recordsMap = new Map<string, Array<Record>>();
988
-
997
+
989
998
  records.forEach(record => {
990
999
  let { __owner__dataunit__name__: ownerDataUnitName } = record;
991
-
992
- if(!ownerDataUnitName){
1000
+
1001
+ if (!ownerDataUnitName) {
993
1002
  ownerDataUnitName = this.name;
994
1003
  }
995
1004
  let changes = recordsMap.get(ownerDataUnitName);
996
-
997
- if(!changes){
1005
+
1006
+ if (!changes) {
998
1007
  changes = [];
999
1008
  recordsMap.set(ownerDataUnitName, changes);
1000
1009
  }
1001
1010
 
1002
1011
  changes.push(record);
1003
1012
  });
1004
-
1013
+
1005
1014
  return recordsMap;
1006
1015
  }
1007
1016
 
1008
- private getParentRecordId(){
1017
+ private getParentRecordId() {
1009
1018
  const parentRecord = this._parentDataUnit?.getSelectedRecord();
1010
1019
  return parentRecord?.__record__id__;
1011
1020
  }
@@ -1047,27 +1056,27 @@ export default class DataUnit {
1047
1056
  * @returns - Promise que será resolvida quando o novo valor for persistido no state.
1048
1057
  *
1049
1058
  */
1050
- public async setFieldValue(fieldName: string, newValue: any, records?: Array<string>, options?:DataUnitEventOptions): Promise<boolean> {
1059
+ public async setFieldValue(fieldName: string, newValue: any, records?: Array<string>, options?: DataUnitEventOptions): Promise<boolean> {
1051
1060
  const noRecordSelected = !this.hasNewRecord() && !this.getSelectedRecord();
1052
1061
 
1053
1062
  const suppressCreateNewRecord = options?.suppressCreateNewRecord;
1054
1063
 
1055
- if(noRecordSelected && suppressCreateNewRecord) return Promise.resolve(false);
1064
+ if (noRecordSelected && suppressCreateNewRecord) return Promise.resolve(false);
1056
1065
 
1057
- if(noRecordSelected) await this.addRecord();
1066
+ if (noRecordSelected) await this.addRecord();
1058
1067
 
1059
1068
  const typedValue = this.validateAndTypeValue(fieldName, newValue);
1060
1069
  const currentValue = this.getFieldValue(fieldName);
1061
1070
 
1062
- if(this.areEquivalentValues(newValue, currentValue, typedValue)) {
1071
+ if (this.areEquivalentValues(newValue, currentValue, typedValue)) {
1063
1072
  return Promise.resolve(false);
1064
1073
  }
1065
1074
 
1066
- if(newValue instanceof Promise){
1067
- const promise:Promise<boolean> = new Promise(accept => {
1075
+ if (newValue instanceof Promise) {
1076
+ const promise: Promise<boolean> = new Promise(accept => {
1068
1077
  newValue.then(resolvedValue => {
1069
1078
  this.dispatchAction(Action.DATA_RESOLVED, { [fieldName]: resolvedValue, records }, undefined);
1070
- accept(this.setFieldValue(fieldName, resolvedValue, records, options));
1079
+ accept(this.setFieldValue(fieldName, resolvedValue, records, options));
1071
1080
  });
1072
1081
  });
1073
1082
  this._savingLockers.push(promise);
@@ -1085,8 +1094,8 @@ export default class DataUnit {
1085
1094
 
1086
1095
  private areEquivalentValues(newValue: any, currentValue: any, typedValue: any) {
1087
1096
  return !(newValue instanceof Promise)
1088
- && ObjectUtils.hasEquivalentProps(currentValue, typedValue)
1089
- && !this.isMultipleEdition;
1097
+ && ObjectUtils.hasEquivalentProps(currentValue, typedValue)
1098
+ && !this.isMultipleEdition;
1090
1099
  }
1091
1100
 
1092
1101
  /**
@@ -1110,7 +1119,7 @@ export default class DataUnit {
1110
1119
  * @param recordId - Indica qual registro está com os campos inválido.
1111
1120
  *
1112
1121
  */
1113
- public savingCanceled(fields: Array<{name: string, message: string}>, recordId: string): void {
1122
+ public savingCanceled(fields: Array<{ name: string, message: string }>, recordId: string): void {
1114
1123
  this.dispatchAction(Action.SAVING_CANCELED, { fields, recordId }, undefined);
1115
1124
  }
1116
1125
 
@@ -1134,7 +1143,7 @@ export default class DataUnit {
1134
1143
  * @param fieldName - Nome do campo.
1135
1144
  *
1136
1145
  */
1137
- public getInvalidMessage(recordId: string, fieldName: string): string|undefined {
1146
+ public getInvalidMessage(recordId: string, fieldName: string): string | undefined {
1138
1147
  return getInvalidFieldMessage(this._stateManager, fieldName, recordId);
1139
1148
  }
1140
1149
 
@@ -1168,7 +1177,6 @@ export default class DataUnit {
1168
1177
  public hasWaitingChanges(): boolean {
1169
1178
  const waitingChanges = getWaitingChanges(this._stateManager);
1170
1179
  return waitingChanges ? !!waitingChanges.size : false;
1171
-
1172
1180
  }
1173
1181
 
1174
1182
  /**
@@ -1221,7 +1229,7 @@ export default class DataUnit {
1221
1229
  public setSelection(selection: Array<string> | SelectionMode.ALL_RECORDS, executionCtx?: ExecutionContext): Promise<SelectionInfo> {
1222
1230
  return new Promise(resolve => {
1223
1231
  this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection }, executionCtx)
1224
- .then(()=>resolve(this.getSelectionInfo()));
1232
+ .then(() => resolve(this.getSelectionInfo()));
1225
1233
  });
1226
1234
  }
1227
1235
 
@@ -1232,7 +1240,7 @@ export default class DataUnit {
1232
1240
  * @param executionCtx - Contexto de execução da seleção dos registros do DataUnit.
1233
1241
  *
1234
1242
  */
1235
- public clearSelection(executionCtx?: ExecutionContext){
1243
+ public clearSelection(executionCtx?: ExecutionContext) {
1236
1244
  this.setSelection([], executionCtx);
1237
1245
  }
1238
1246
 
@@ -1244,19 +1252,19 @@ export default class DataUnit {
1244
1252
  * @param executionCtx - Contexto de execução da seleção dos registros do DataUnit.
1245
1253
  * @returns - Informações sobre a seleção.
1246
1254
  */
1247
- public updatePageSelection(selection: Array<string>, executionCtx?: ExecutionContext): Promise<SelectionInfo|undefined>{
1248
- if(!selection) return Promise.resolve(this.getSelectionInfo());
1255
+ public updatePageSelection(selection?: Array<string>, executionCtx?: ExecutionContext): Promise<SelectionInfo | undefined> {
1256
+ if (!selection) return Promise.resolve(this.getSelectionInfo());
1249
1257
 
1250
1258
  return new Promise(resolve => {
1251
1259
  const newSelection: Set<string> = new Set(selection);
1252
1260
 
1253
1261
  this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection: Array.from(newSelection) }, executionCtx)
1254
- .then(()=> resolve(this.getSelectionInfo()));
1262
+ .then(() => resolve(this.getSelectionInfo()));
1255
1263
  });
1256
1264
  }
1257
1265
 
1258
1266
 
1259
- private updatePageSelectionAll(addRecords: boolean): Promise<SelectionInfo|undefined>{
1267
+ private updatePageSelectionAll(addRecords: boolean): Promise<SelectionInfo | undefined> {
1260
1268
  return new Promise(resolve => {
1261
1269
  const newSelection: Set<string> = new Set<string>();
1262
1270
 
@@ -1264,10 +1272,10 @@ export default class DataUnit {
1264
1272
  cachedSelection.forEach(item => newSelection.add(item));
1265
1273
 
1266
1274
  const recordsIds = this.records.map(r => r.__record__id__);
1267
- recordsIds.forEach(id => addRecords ? newSelection.add(id): newSelection.delete(id));
1275
+ recordsIds.forEach(id => addRecords ? newSelection.add(id) : newSelection.delete(id));
1268
1276
 
1269
1277
  this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection: Array.from(newSelection) })
1270
- .then(()=> resolve(this.getSelectionInfo()));
1278
+ .then(() => resolve(this.getSelectionInfo()));
1271
1279
  });
1272
1280
  }
1273
1281
 
@@ -1276,8 +1284,8 @@ export default class DataUnit {
1276
1284
  *
1277
1285
  * @returns - Informações sobre a seleção.
1278
1286
  */
1279
- public selectAllRecords(): Promise<SelectionInfo|undefined>{
1280
- return this.updatePageSelectionAll(true);
1287
+ public selectAllRecords(): Promise<SelectionInfo | undefined> {
1288
+ return this.updatePageSelectionAll(true);
1281
1289
  }
1282
1290
 
1283
1291
  /**
@@ -1285,9 +1293,9 @@ export default class DataUnit {
1285
1293
  *
1286
1294
  * @returns - Informações sobre a seleção.
1287
1295
  */
1288
- public unSelectAllRecords(): Promise<SelectionInfo|undefined>{
1296
+ public unSelectAllRecords(): Promise<SelectionInfo | undefined> {
1289
1297
  return this.updatePageSelectionAll(false);
1290
- }
1298
+ }
1291
1299
 
1292
1300
  /**
1293
1301
  *
@@ -1295,13 +1303,13 @@ export default class DataUnit {
1295
1303
  *
1296
1304
  * @returns - Objeto com informações como registros selecionados e seleção por critério.
1297
1305
  *
1298
- **/
1299
- public getSelectionInfo(): SelectionInfo{
1306
+ **/
1307
+ public getSelectionInfo(): SelectionInfo {
1300
1308
  const selectionInfo: SelectionInfo = getSelectionInfo(this._stateManager);
1301
1309
  selectionInfo.getAllRecords = () => {
1302
-
1310
+
1303
1311
  let records = this.allRecordsLoader?.(this) ?? [];
1304
-
1312
+
1305
1313
  if (selectionInfo.sort != undefined && selectionInfo.sort.length > 0) {
1306
1314
  const sortingFunction = SortingUtils.getSortingFunction(this, selectionInfo.sort)
1307
1315
  records = [...records].sort(sortingFunction);
@@ -1312,7 +1320,7 @@ export default class DataUnit {
1312
1320
 
1313
1321
  if (selectionInfo.sort != undefined && selectionInfo.sort.length > 0) {
1314
1322
  const sortingFunction = SortingUtils.getSortingFunction(this, selectionInfo.sort)
1315
- selectionInfo.records?.sort(sortingFunction)
1323
+ selectionInfo.records.sort(sortingFunction)
1316
1324
  }
1317
1325
 
1318
1326
  return selectionInfo;
@@ -1326,7 +1334,7 @@ export default class DataUnit {
1326
1334
  *
1327
1335
  */
1328
1336
  public getSelectedRecord(): Record | undefined {
1329
- return getSelectedRecord(this._stateManager);
1337
+ return getSelectedRecord(this._stateManager);
1330
1338
  }
1331
1339
 
1332
1340
  /**
@@ -1356,17 +1364,17 @@ export default class DataUnit {
1356
1364
  *
1357
1365
  *
1358
1366
  */
1359
- public nextRecord(executionCtx?: ExecutionContext): void {
1360
- if(!hasNext(this._stateManager)){
1361
- if(hasMorePages(this._stateManager)){
1362
- this.nextPage({
1363
- before: act =>{
1364
- if(executionCtx && executionCtx.before){
1367
+ public async nextRecord(executionCtx?: ExecutionContext): Promise<void> {
1368
+ if (!hasNext(this._stateManager)) {
1369
+ if (hasMorePages(this._stateManager)) {
1370
+ await this.nextPage({
1371
+ before: (act) => {
1372
+ if (executionCtx && executionCtx.before) {
1365
1373
  act = executionCtx.before(act);
1366
1374
  }
1367
1375
  return act;
1368
1376
  },
1369
- after: act => {
1377
+ after: () => {
1370
1378
  this.selectFirst(executionCtx);
1371
1379
  }
1372
1380
  });
@@ -1383,17 +1391,17 @@ export default class DataUnit {
1383
1391
  * @param executionCtx - Contexto de execução da seleção do registro do DataUnit.
1384
1392
  *
1385
1393
  */
1386
- public previousRecord(executionCtx?: ExecutionContext): void {
1387
- if(!hasPrevious(this._stateManager)){
1388
- if(hasPreviousPages(this._stateManager)){
1389
- this.previousPage({
1390
- before: act =>{
1391
- if(executionCtx && executionCtx.before){
1394
+ public async previousRecord(executionCtx?: ExecutionContext): Promise<void> {
1395
+ if (!hasPrevious(this._stateManager)) {
1396
+ if (hasPreviousPages(this._stateManager)) {
1397
+ await this.previousPage({
1398
+ before: (act) => {
1399
+ if (executionCtx && executionCtx.before) {
1392
1400
  act = executionCtx.before(act);
1393
1401
  }
1394
1402
  return act;
1395
1403
  },
1396
- after: act => {
1404
+ after: () => {
1397
1405
  this.selectLast(executionCtx);
1398
1406
  }
1399
1407
  });
@@ -1412,14 +1420,14 @@ export default class DataUnit {
1412
1420
  *
1413
1421
  */
1414
1422
  public async cancelEdition(executionCtx?: ExecutionContext, fromParent?: boolean, silent: boolean = false): Promise<boolean> {
1415
- const cancelledAction = await this.dispatchAction(Action.EDITION_CANCELED, {fromParent, silent}, executionCtx);
1416
- for (const [, dataUnit] of this._childByName) {
1417
- if(dataUnit.isDirty()){
1418
- dataUnit.cancelEdition(undefined, true, silent);
1419
- }
1423
+ const cancelledAction = await this.dispatchAction(Action.EDITION_CANCELED, { fromParent, silent }, executionCtx);
1424
+ for (const [, dataUnit] of this._childByName) {
1425
+ if (dataUnit.isDirty()) {
1426
+ dataUnit.cancelEdition(undefined, true, silent);
1420
1427
  }
1421
- return Promise.resolve(cancelledAction);
1422
-
1428
+ }
1429
+ return Promise.resolve(cancelledAction);
1430
+
1423
1431
  }
1424
1432
 
1425
1433
  /**
@@ -1429,9 +1437,9 @@ export default class DataUnit {
1429
1437
  * @param ignoreChildren: Define se deverá ignorar alterações pendentes no DataUnit filho.
1430
1438
  * @returns Verdadeiro se existir alterações pendentes.
1431
1439
  *
1432
- */
1440
+ */
1433
1441
  public isDirty(ignoreChildren?: boolean): boolean {
1434
- if(ignoreChildren) return isDirty(this._stateManager);
1442
+ if (ignoreChildren) return isDirty(this._stateManager);
1435
1443
 
1436
1444
  return isDirty(this._stateManager) || this.childrenIsDirty();
1437
1445
  }
@@ -1453,10 +1461,10 @@ export default class DataUnit {
1453
1461
  *
1454
1462
  * @returns Verdadeiro se existir alterações pendentes em algum DataUnit detail.
1455
1463
  *
1456
- */
1457
- private childrenIsDirty():boolean {
1458
- for (let [key, dataUnitChild] of this._childByName) {
1459
- if(dataUnitChild.isDirty()) return true;
1464
+ */
1465
+ private childrenIsDirty(): boolean {
1466
+ for (let [_, dataUnitChild] of this._childByName) {
1467
+ if (dataUnitChild.isDirty()) return true;
1460
1468
  }
1461
1469
  return false;
1462
1470
  }
@@ -1481,7 +1489,7 @@ export default class DataUnit {
1481
1489
  */
1482
1490
  public hasNext(): boolean {
1483
1491
  let result = hasNext(this._stateManager);
1484
- if(!result){
1492
+ if (!result) {
1485
1493
  result = hasMorePages(this._stateManager);
1486
1494
  }
1487
1495
  return result;
@@ -1496,7 +1504,7 @@ export default class DataUnit {
1496
1504
  */
1497
1505
  public hasPrevious(): boolean {
1498
1506
  let result = hasPrevious(this._stateManager);
1499
- if(!result){
1507
+ if (!result) {
1500
1508
  result = hasPreviousPages(this._stateManager);
1501
1509
  }
1502
1510
  return result;
@@ -1512,7 +1520,7 @@ export default class DataUnit {
1512
1520
  */
1513
1521
  public isNewRecord(recordId: string): boolean {
1514
1522
  const newRecords = getAddedRecords(this._stateManager);
1515
- if(newRecords && newRecords.length > 0){
1523
+ if (newRecords && newRecords.length > 0) {
1516
1524
  const record = newRecords.find(newRecord => newRecord.__record__id__ === recordId);
1517
1525
  return record != undefined;
1518
1526
  }
@@ -1540,10 +1548,11 @@ export default class DataUnit {
1540
1548
  */
1541
1549
  public hasCopiedRecord(): boolean {
1542
1550
  const newRecords = getAddedRecords(this._stateManager);
1543
- if(newRecords == undefined){
1551
+
1552
+ if (newRecords == undefined) {
1544
1553
  return false;
1545
1554
  }
1546
- for(let record of newRecords){
1555
+ for (let record of newRecords) {
1547
1556
  if (record['__record__source__id__'] != undefined) {
1548
1557
  return true
1549
1558
  }
@@ -1619,7 +1628,7 @@ export default class DataUnit {
1619
1628
  * @returns - Verdadeiro se ação iniciada.
1620
1629
  *
1621
1630
  */
1622
- private async dispatchAction(actionType: Action, payload?: any, executionCtx?: ExecutionContext, options?:DataUnitEventOptions): Promise<boolean> {
1631
+ private async dispatchAction(actionType: Action, payload?: any, executionCtx?: ExecutionContext, options?: DataUnitEventOptions): Promise<boolean> {
1623
1632
  return new Promise(async resolve => {
1624
1633
  let action = new DataUnitAction(actionType, payload);
1625
1634
  if (executionCtx && executionCtx.before) {
@@ -1667,7 +1676,7 @@ export default class DataUnit {
1667
1676
  * @param action - Ações em execução no DataUnit.
1668
1677
  *
1669
1678
  */
1670
- private doDispatchAction(action: DataUnitAction, options:DataUnitEventOptions = {}): void {
1679
+ private doDispatchAction(action: DataUnitAction, options: DataUnitEventOptions = {}): void {
1671
1680
  this._stateManager.process(action);
1672
1681
  this?._parentDataUnit?.dispatchAction(Action.CHILD_CHANGED, { srcAction: action, srcDataUnit: this });
1673
1682
  this._observers.forEach(f => {
@@ -1687,7 +1696,7 @@ export default class DataUnit {
1687
1696
  * @param name - Nome do dataunit filho.
1688
1697
  *
1689
1698
  */
1690
- public getChildDataunit(name:string){
1699
+ public getChildDataunit(name: string) {
1691
1700
  const detail: DataUnit = new DataUnit(name, this);
1692
1701
  this._childByName.set(name, detail);
1693
1702
  return detail;
@@ -1700,10 +1709,10 @@ export default class DataUnit {
1700
1709
  * @param name - Nome do dataunit filho.
1701
1710
  *
1702
1711
  */
1703
- public removeChildDataunit(name:string){
1712
+ public removeChildDataunit(name: string) {
1704
1713
  this._childByName.delete(name);
1705
1714
  }
1706
-
1715
+
1707
1716
  /**
1708
1717
  *
1709
1718
  * Adiciona um novo observer no DataUnit.
@@ -1749,17 +1758,17 @@ export default class DataUnit {
1749
1758
  * @returns - Dados atualizados do registro selecionado.
1750
1759
  *
1751
1760
  */
1752
- public reloadCurrentRecord(): Promise<Array<Record>>{
1761
+ public reloadCurrentRecord(): Promise<Array<Record>> {
1753
1762
  return new Promise(async (resolve, fail) => {
1754
1763
  const selection = getSelection(this._stateManager);
1755
1764
  await this.dispatchAction(Action.LOADING_RECORD, selection);
1756
-
1757
- if(!this.recordLoader || !this.dataLoader) {
1765
+
1766
+ if (!this.recordLoader || !this.dataLoader) {
1758
1767
  await this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
1759
1768
  resolve([]);
1760
1769
  return;
1761
1770
  }
1762
-
1771
+
1763
1772
  this.recordLoader(this, selection).then(async response => {
1764
1773
  await this.dispatchAction(Action.RECORD_LOADED, response)
1765
1774
  await this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
@@ -1767,7 +1776,7 @@ export default class DataUnit {
1767
1776
  resolve(response);
1768
1777
  }).catch(async cause => {
1769
1778
  await this.dispatchAction(Action.LOADING_PROPERTIES_CLEANED);
1770
- const {errorCode} = cause;
1779
+ const { errorCode } = cause;
1771
1780
  fail(new ErrorException("Erro ao recarregar registro", cause, errorCode));
1772
1781
  });
1773
1782
  });
@@ -1791,7 +1800,7 @@ export default class DataUnit {
1791
1800
  * @returns - Lista de filtros.
1792
1801
  *
1793
1802
  */
1794
- public getFilters(): Array<Filter> | undefined {
1803
+ public getFilters(): Array<Filter> | undefined {
1795
1804
  let filters: Array<Filter> | undefined = undefined;
1796
1805
  this._filterProviders.forEach(p => {
1797
1806
  const f = p.getFilter(this.name);
@@ -1808,18 +1817,18 @@ export default class DataUnit {
1808
1817
  *
1809
1818
  * @returns - As informações de filtro e paginação.
1810
1819
  *
1811
- */
1820
+ */
1812
1821
  public getLastLoadRequest(): LoadDataRequest | undefined {
1813
1822
  return getCurrentRequest(this._stateManager);
1814
1823
  }
1815
-
1824
+
1816
1825
  /**
1817
1826
  *
1818
1827
  * Obtém os filtros aplicados.
1819
1828
  *
1820
1829
  * @returns - Lista de filtros.
1821
1830
  *
1822
- */
1831
+ */
1823
1832
  public getAppliedFilters(): Array<Filter> | undefined {
1824
1833
  const { filters }: LoadDataRequest = getCurrentRequest(this._stateManager) || {};
1825
1834
  return filters
@@ -1831,12 +1840,16 @@ export default class DataUnit {
1831
1840
  * @param fieldName - nome do campo para ser habilitado.
1832
1841
  *
1833
1842
  */
1834
- public enableField(fieldName:string) {
1843
+ public enableField(fieldName: string) {
1835
1844
  const fieldDescriptor = this.getField(fieldName);
1836
1845
 
1837
- if(fieldDescriptor?.readOnly === true){
1846
+ if (!fieldDescriptor) {
1847
+ return;
1848
+ }
1849
+
1850
+ if (fieldDescriptor.readOnly) {
1838
1851
  fieldDescriptor.readOnly = false;
1839
- this.metadata = {...this.metadata};
1852
+ this.metadata = { ...this.metadata };
1840
1853
  }
1841
1854
  }
1842
1855
 
@@ -1846,12 +1859,16 @@ export default class DataUnit {
1846
1859
  * @param fieldName - nome do campo para ficar desabilitado.
1847
1860
  *
1848
1861
  */
1849
- public disableField(fieldName:string) {
1862
+ public disableField(fieldName: string) {
1850
1863
  const fieldDescriptor = this.getField(fieldName);
1851
1864
 
1852
- if(fieldDescriptor?.readOnly === false){
1865
+ if (!fieldDescriptor) {
1866
+ return;
1867
+ }
1868
+
1869
+ if (!fieldDescriptor.readOnly) {
1853
1870
  fieldDescriptor.readOnly = true;
1854
- this.metadata = {...this.metadata};
1871
+ this.metadata = { ...this.metadata };
1855
1872
  }
1856
1873
  }
1857
1874
 
@@ -1861,13 +1878,21 @@ export default class DataUnit {
1861
1878
  * @param fieldName - nome do campo para ficar invisível.
1862
1879
  *
1863
1880
  */
1864
- public hideField(fieldName:string, options:HideFieldOptions) {
1881
+ public hideField(fieldName: string, options?: HideFieldOptions) {
1865
1882
  const fieldDescriptor = this.getField(fieldName);
1866
1883
 
1867
- if(fieldDescriptor?.visible === true){
1884
+ if (!fieldDescriptor) {
1885
+ return;
1886
+ }
1887
+
1888
+ if (fieldDescriptor.visible) {
1868
1889
  fieldDescriptor.visible = false;
1869
- fieldDescriptor.properties = {...fieldDescriptor.properties, visibleOnConfig: options?.visibleOnConfig };
1870
- this.metadata = {...this.metadata};
1890
+
1891
+ if (options) {
1892
+ fieldDescriptor.properties = { ...fieldDescriptor.properties, visibleOnConfig: options.visibleOnConfig };
1893
+ }
1894
+
1895
+ this.metadata = { ...this.metadata };
1871
1896
  }
1872
1897
  }
1873
1898
 
@@ -1877,15 +1902,19 @@ export default class DataUnit {
1877
1902
  * @param fieldName - nome do campo para ficar visível.
1878
1903
  *
1879
1904
  */
1880
- public showField(fieldName:string) {
1905
+ public showField(fieldName: string) {
1881
1906
  const fieldDescriptor = this.getField(fieldName);
1882
1907
 
1883
- if(fieldDescriptor?.visible === false){
1908
+ if (!fieldDescriptor) {
1909
+ return;
1910
+ }
1911
+
1912
+ if (!fieldDescriptor.visible) {
1884
1913
  fieldDescriptor.visible = true;
1885
- this.metadata = {...this.metadata};
1914
+ this.metadata = { ...this.metadata };
1886
1915
  }
1887
1916
  }
1888
-
1917
+
1889
1918
  /**
1890
1919
  *
1891
1920
  * Obtém todos os registros selecionados.
@@ -1901,7 +1930,7 @@ export default class DataUnit {
1901
1930
  console.warn("DataUnit: O método `getSelectedRecords` foi descontinuado. Use o método `getSelectionInfo`.");
1902
1931
  const selection = this.getSelectionInfo();
1903
1932
 
1904
- if(selection != undefined && selection.isAllRecords()){
1933
+ if (selection != undefined && selection.isAllRecords()) {
1905
1934
  throw new Error("Erro interno: Impossível retornar os registros selecionados. A seleção atual é virtual. Use o método `getSelectionInfo`.");
1906
1935
  }
1907
1936
 
@@ -1924,11 +1953,11 @@ export default class DataUnit {
1924
1953
  public getSelection(): Array<string> {
1925
1954
  console.warn("DataUnit: O método `getSelection` foi descontinuado. Use o método `getSelectionInfo`.");
1926
1955
  const selection = this.getSelectionInfo();
1927
- if(selection == undefined){
1956
+ if (selection == undefined) {
1928
1957
  return [];
1929
1958
  }
1930
1959
 
1931
- if(selection.isAllRecords()){
1960
+ if (selection.isAllRecords()) {
1932
1961
  throw new Error("Erro interno: Impossível retornar os registros selecionados. A seleção atual é virtual. Use o método `getSelectionInfo`.");
1933
1962
  }
1934
1963
 
@@ -1940,7 +1969,7 @@ export default class DataUnit {
1940
1969
  *
1941
1970
  * @deprecated - metodo depreciado, utilizar o metodo addField
1942
1971
  */
1943
- public addStandAloneField() : void {
1972
+ public addStandAloneField(): void {
1944
1973
  console.warn("metodo depreciado, para adicionar um campo standAlone, utilizar o metodo addField")
1945
1974
  }
1946
1975
 
@@ -1949,9 +1978,9 @@ export default class DataUnit {
1949
1978
  *
1950
1979
  * @param field - Campo a ser adicionado.
1951
1980
  */
1952
- public addField(field: Omit<FieldDescriptor, 'standAlone'>) : void {
1953
- const standAloneField = {...field, standAlone: true};
1954
- this.metadata = {...this.metadata, fields: [...this.metadata.fields, standAloneField]};
1981
+ public addField(field: Omit<FieldDescriptor, 'standAlone'>): void {
1982
+ const standAloneField = { ...field, standAlone: true };
1983
+ this.metadata = { ...this.metadata, fields: [...this.metadata.fields, standAloneField] };
1955
1984
  }
1956
1985
 
1957
1986
  /**
@@ -1959,16 +1988,16 @@ export default class DataUnit {
1959
1988
  * @returns Retorna uma função responsável por liberar o lock adicionado.
1960
1989
  */
1961
1990
  public addLoadingLocker(): Function {
1962
- let loadingLockerResolver;
1991
+ let loadingLockerResolver = () => {};
1963
1992
 
1964
1993
  this._loadingLockers.push(new Promise((resolve) => {
1965
1994
  loadingLockerResolver = resolve;
1966
1995
  }));
1967
-
1968
- return loadingLockerResolver || Promise.resolve;
1996
+
1997
+ return loadingLockerResolver;
1969
1998
  }
1970
1999
 
1971
- public set allowReleaseCallbacks(allow: boolean){
2000
+ public set allowReleaseCallbacks(allow: boolean) {
1972
2001
  this._allowReleaseCallbacks = allow;
1973
2002
  }
1974
2003
 
@@ -1976,19 +2005,19 @@ export default class DataUnit {
1976
2005
  /**
1977
2006
  * Adiciona um mapeamento de origem dos dados de um determinado campo
1978
2007
  */
1979
- public addSourceFieldValue(sourceFieldName:string, targetFieldName:string): void{
2008
+ public addSourceFieldValue(sourceFieldName: string, targetFieldName: string): void {
1980
2009
  this._fieldSourceValue.set(sourceFieldName, targetFieldName);
1981
2010
  }
1982
2011
 
1983
- /**
1984
- * Retornar o campo de origem dos dados caso exista mapeamento
1985
- */
1986
- public getSourceFieldValue(targetFieldName:string): string | undefined{
1987
- return this._fieldSourceValue.get(targetFieldName);
2012
+ /**
2013
+ * Retornar o campo de origem dos dados caso exista mapeamento
2014
+ */
2015
+ public getSourceFieldValue(sourceFieldName: string): string | undefined {
2016
+ return this._fieldSourceValue.get(sourceFieldName);
1988
2017
  }
1989
2018
 
1990
- private async processLoadingLockers(){
1991
- if(this._loadingLockers.length) {
2019
+ private async processLoadingLockers() {
2020
+ if (this._loadingLockers.length) {
1992
2021
  await Promise.all(this._loadingLockers);
1993
2022
  this._loadingLockers = [];
1994
2023
  }
@@ -1996,200 +2025,16 @@ export default class DataUnit {
1996
2025
 
1997
2026
  }
1998
2027
 
1999
- export interface LoadDataParams {
2000
- quickFilter?: QuickFilter;
2001
- executionCtx?: ExecutionContext;
2002
- checkLastFilter?: boolean;
2003
- source?: string;
2004
- selectFirstRecord?: boolean;
2005
- keepSelection?: boolean
2006
- }
2007
-
2008
- export interface DUActionInterceptor {
2009
- interceptAction(action: DataUnitAction): DataUnitAction | Promise<DataUnitAction>;
2010
- }
2011
-
2012
- export interface Record {
2013
- __record__id__: string;
2014
- __record__label__?: string;
2015
- __parent__record__id__?: string;
2016
- __owner__dataunit__name__?: string;
2017
- [key: string]: any;
2018
- }
2019
-
2020
- export interface SavedRecord extends Record {
2021
- __old__id__?: string;
2022
- }
2023
-
2024
- export enum ChangeOperation {
2025
- INSERT = "INSERT",
2026
- COPY = "COPY",
2027
- UPDATE = "UPDATE",
2028
- DELETE = "DELETE",
2029
- }
2030
-
2031
- /***
2032
- * `Change`: Dados que representam uma alteração.
2033
- */
2034
- export class Change {
2035
-
2036
- public dataUnit: string;
2037
- public record: Record;
2038
- public sourceId: string | undefined;
2039
- public updatingFields: any;
2040
-
2041
- private _operation: ChangeOperation;
2042
-
2043
- constructor(dataUnit: string, record: Record, updates: any, operation: ChangeOperation, sourceId?: string) {
2044
- this.dataUnit = dataUnit;
2045
- this.record = record;
2046
- this.sourceId = sourceId;
2047
- this.updatingFields = updates;
2048
- this._operation = operation;
2049
- }
2050
-
2051
- /**
2052
- *
2053
- * Obtém o tipo de operação que está sendo realizada.
2054
- *
2055
- * @returns - Ação que está sendo executada.
2056
- *
2057
- */
2058
- public get operation(): string {
2059
- return this._operation.toString();
2060
- }
2061
-
2062
- /**
2063
- *
2064
- * Retorna se o DataUnit está em uma operação de inserção.
2065
- *
2066
- * @returns - Verdadeiro se a operação for de inserção.
2067
- *
2068
- */
2069
- public isInsert(): boolean {
2070
- return this._operation === ChangeOperation.INSERT;
2071
- }
2072
-
2073
- /**
2074
- *
2075
- * Retorna se o DataUnit está em uma operação de cópia.
2076
- *
2077
- * @returns - Verdadeiro se a operação for de cópia.
2078
- *
2079
- */
2080
- public isCopy(): boolean {
2081
- return this._operation === ChangeOperation.COPY;
2082
- }
2083
-
2084
- /**
2085
- *
2086
- * Retorna se o DataUnit está em uma operação de deleção.
2087
- *
2088
- * @returns - Verdadeiro se a operação for de deleção.
2089
- *
2090
- */
2091
- public isDelete(): boolean {
2092
- return this._operation === ChangeOperation.DELETE;
2093
- }
2094
-
2095
- /**
2096
- *
2097
- * Retorna se o DataUnit está em uma operação de atualização.
2098
- *
2099
- * @returns - Verdadeiro se a operação for de atualização.
2100
- *
2101
- */
2102
- public isUpdate(): boolean {
2103
- return this._operation === ChangeOperation.UPDATE;
2104
- }
2105
- }
2106
-
2107
- export interface WaitingChange {
2108
- waitmessage: string;
2109
- blocking: boolean;
2110
- promise?: Promise<any>;
2111
- }
2112
-
2113
- export interface PageRequest {
2114
- limit: number;
2115
- offset: number;
2116
- quickFilter?: QuickFilter;
2117
- }
2118
-
2119
- export interface QuickFilter {
2120
- term: string;
2121
- fields?: Array<string>;
2122
- filter?: Filter;
2123
- }
2124
-
2125
- export interface PageResponse {
2126
- limit: number;
2127
- offset: number;
2128
- total: number;
2129
- hasMore: boolean;
2130
- records: Array<Record>;
2131
- }
2132
-
2133
- export enum SelectionMode{
2134
- ALL_RECORDS = "ALL_RECORDS",
2135
- SOME_RECORDS = "SOME_RECORDS"
2136
- }
2137
-
2138
- export class SelectionInfo{
2139
-
2140
- public mode: SelectionMode;
2141
- public filters?: Array<Filter>;
2142
- public sort?: Array<Sort>;
2143
- public getAllRecords?: () => Array<Record> | undefined;
2144
- private _records: Array<Record>;
2145
- private _total?: number;
2146
-
2147
- constructor(records: Array<Record>, mode: SelectionMode = SelectionMode.SOME_RECORDS, total?:number, filters?: Array<Filter>, sort?: Array<Sort>){
2148
- this._records = records;
2149
- this._total = total;
2150
- this.mode = mode;
2151
- this.filters = filters;
2152
- this.sort = sort;
2153
- }
2154
-
2155
- public get records(): Array<Record> | undefined{
2156
- if(this.isAllRecords()){
2157
- if(this.getAllRecords != undefined){
2158
- return this.getAllRecords();
2159
- }
2160
- throw new Error("Erro interno: Impossível retornar os registros selecionados numa seleção virtual.");
2161
- }
2162
- return this._records;
2163
- }
2164
-
2165
- public get recordIds(): Array<string> | undefined{
2166
-
2167
- const records = this.records;
2168
-
2169
- if(records == undefined){
2170
- return undefined;
2171
- }
2172
- return records.map(record => record.__record__id__);
2173
- }
2174
-
2175
- public get length(): number{
2176
- if(this.isAllRecords()){
2177
- return this._total || 0;
2178
- }
2179
- return this.records == undefined ? 0 : (this.records as Array<Record>).length;
2180
- }
2181
-
2182
- public isAllRecords(): boolean{
2183
- return this.mode === SelectionMode.ALL_RECORDS;
2184
- }
2185
-
2186
- public isEmpty(): boolean{
2187
- return this.length === 0;
2188
- }
2189
- }
2190
-
2191
- export type DataUnitEventOptions = {[key:string]: any};
2192
-
2193
- export type HideFieldOptions = {
2194
- visibleOnConfig: boolean
2195
- };
2028
+ export {
2029
+ Record,
2030
+ Change,
2031
+ SelectionInfo,
2032
+ SelectionMode,
2033
+ LoadDataParams,
2034
+ DUActionInterceptor,
2035
+ SavedRecord,
2036
+ WaitingChange,
2037
+ QuickFilter,
2038
+ DataUnitEventOptions,
2039
+ HideFieldOptions
2040
+ }