@sankhyalabs/core 0.0.0-bugfix-dev-KB-6165.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 (283) hide show
  1. package/.docs/.nojekyll +1 -0
  2. package/.docs/README.md +63 -0
  3. package/.docs/classes/ApplicationContext.md +90 -0
  4. package/.docs/classes/ArrayUtils.md +99 -0
  5. package/.docs/classes/AuthorizedServiceCaller.md +76 -0
  6. package/.docs/classes/Change.md +190 -0
  7. package/.docs/classes/DataUnit.md +2453 -0
  8. package/.docs/classes/DataUnitAction.md +96 -0
  9. package/.docs/classes/DataUnitStorage.md +116 -0
  10. package/.docs/classes/DateUtils.md +327 -0
  11. package/.docs/classes/ElementIDUtils.md +308 -0
  12. package/.docs/classes/ErrorException.md +214 -0
  13. package/.docs/classes/ErrorTracking.md +62 -0
  14. package/.docs/classes/FloatingManager.md +530 -0
  15. package/.docs/classes/HTMLBuilder.md +45 -0
  16. package/.docs/classes/HttpProvider.md +96 -0
  17. package/.docs/classes/JSUtils.md +115 -0
  18. package/.docs/classes/MaskFormatter-1.md +347 -0
  19. package/.docs/classes/NumberUtils.md +335 -0
  20. package/.docs/classes/ObjectUtils.md +160 -0
  21. package/.docs/classes/OnboardingUtils.md +126 -0
  22. package/.docs/classes/PromiseSync.md +91 -0
  23. package/.docs/classes/ReadyUtil.md +115 -0
  24. package/.docs/classes/RequestMetadata.md +84 -0
  25. package/.docs/classes/SelectionInfo.md +168 -0
  26. package/.docs/classes/SkwHttpProvider.md +109 -0
  27. package/.docs/classes/StringUtils.md +562 -0
  28. package/.docs/classes/TimeFormatter.md +98 -0
  29. package/.docs/classes/UserAgentUtils.md +58 -0
  30. package/.docs/classes/VersionUtils.md +42 -0
  31. package/.docs/classes/WaitingChangeException.md +200 -0
  32. package/.docs/classes/WarningException.md +214 -0
  33. package/.docs/enums/Action.md +294 -0
  34. package/.docs/enums/ChangeOperation.md +52 -0
  35. package/.docs/enums/DataType.md +63 -0
  36. package/.docs/enums/DependencyType.md +41 -0
  37. package/.docs/enums/SelectionMode.md +30 -0
  38. package/.docs/enums/SortMode.md +30 -0
  39. package/.docs/enums/UserInterface.md +195 -0
  40. package/.docs/interfaces/ChildDescriptor.md +41 -0
  41. package/.docs/interfaces/ChildLink.md +30 -0
  42. package/.docs/interfaces/DUActionInterceptor.md +29 -0
  43. package/.docs/interfaces/ExecutionContext.md +58 -0
  44. package/.docs/interfaces/FieldDescriptor.md +140 -0
  45. package/.docs/interfaces/Filter.md +41 -0
  46. package/.docs/interfaces/IElementIDInfo.md +30 -0
  47. package/.docs/interfaces/LoadDataRequest.md +101 -0
  48. package/.docs/interfaces/LoadDataResponse.md +36 -0
  49. package/.docs/interfaces/PageRequest.md +41 -0
  50. package/.docs/interfaces/PaginationInfo.md +75 -0
  51. package/.docs/interfaces/PromiseSyncCallback.md +39 -0
  52. package/.docs/interfaces/QuickFilter.md +41 -0
  53. package/.docs/interfaces/Record.md +62 -0
  54. package/.docs/interfaces/SavedRecord.md +85 -0
  55. package/.docs/interfaces/Sort.md +41 -0
  56. package/.docs/interfaces/SortingProvider.md +29 -0
  57. package/.docs/interfaces/UnitMetadata.md +52 -0
  58. package/.docs/interfaces/WaitingChange.md +41 -0
  59. package/.docs/modules/MaskFormatter.md +37 -0
  60. package/.docs/modules.md +74 -0
  61. package/.docs/package.json +15 -0
  62. package/.eslintignore +2 -0
  63. package/.eslintrc.cjs +35 -0
  64. package/.husky/commit-msg +4 -0
  65. package/.releaserc +58 -0
  66. package/README.md +62 -0
  67. package/commitlint.config.cjs +14 -0
  68. package/dist/async/PromiseSync.d.ts +29 -0
  69. package/dist/async/PromiseSync.js +31 -0
  70. package/dist/async/PromiseSync.js.map +1 -0
  71. package/dist/dataunit/DataUnit.d.ts +924 -0
  72. package/dist/dataunit/DataUnit.js +1621 -0
  73. package/dist/dataunit/DataUnit.js.map +1 -0
  74. package/dist/dataunit/DataUnitStorage.d.ts +24 -0
  75. package/dist/dataunit/DataUnitStorage.js +39 -0
  76. package/dist/dataunit/DataUnitStorage.js.map +1 -0
  77. package/dist/dataunit/formatting/PrettyFormatter.d.ts +2 -0
  78. package/dist/dataunit/formatting/PrettyFormatter.js +94 -0
  79. package/dist/dataunit/formatting/PrettyFormatter.js.map +1 -0
  80. package/dist/dataunit/loading/LoadDataRequest.d.ts +19 -0
  81. package/dist/dataunit/loading/LoadDataRequest.js +2 -0
  82. package/dist/dataunit/loading/LoadDataRequest.js.map +1 -0
  83. package/dist/dataunit/loading/LoadDataResponse.d.ts +9 -0
  84. package/dist/dataunit/loading/LoadDataResponse.js +2 -0
  85. package/dist/dataunit/loading/LoadDataResponse.js.map +1 -0
  86. package/dist/dataunit/loading/PaginationInfo.d.ts +13 -0
  87. package/dist/dataunit/loading/PaginationInfo.js +2 -0
  88. package/dist/dataunit/loading/PaginationInfo.js.map +1 -0
  89. package/dist/dataunit/metadata/DataType.d.ts +54 -0
  90. package/dist/dataunit/metadata/DataType.js +124 -0
  91. package/dist/dataunit/metadata/DataType.js.map +1 -0
  92. package/dist/dataunit/metadata/UnitMetadata.d.ts +88 -0
  93. package/dist/dataunit/metadata/UnitMetadata.js +36 -0
  94. package/dist/dataunit/metadata/UnitMetadata.js.map +1 -0
  95. package/dist/dataunit/state/HistReducer.d.ts +10 -0
  96. package/dist/dataunit/state/HistReducer.js +28 -0
  97. package/dist/dataunit/state/HistReducer.js.map +1 -0
  98. package/dist/dataunit/state/StateManager.d.ts +57 -0
  99. package/dist/dataunit/state/StateManager.js +97 -0
  100. package/dist/dataunit/state/StateManager.js.map +1 -0
  101. package/dist/dataunit/state/action/DataUnitAction.d.ts +40 -0
  102. package/dist/dataunit/state/action/DataUnitAction.js +42 -0
  103. package/dist/dataunit/state/action/DataUnitAction.js.map +1 -0
  104. package/dist/dataunit/state/slice/AddedRecordsSlice.d.ts +12 -0
  105. package/dist/dataunit/state/slice/AddedRecordsSlice.js +30 -0
  106. package/dist/dataunit/state/slice/AddedRecordsSlice.js.map +1 -0
  107. package/dist/dataunit/state/slice/ChangesSlice.d.ts +13 -0
  108. package/dist/dataunit/state/slice/ChangesSlice.js +105 -0
  109. package/dist/dataunit/state/slice/ChangesSlice.js.map +1 -0
  110. package/dist/dataunit/state/slice/InvalidFieldsSlice.d.ts +10 -0
  111. package/dist/dataunit/state/slice/InvalidFieldsSlice.js +66 -0
  112. package/dist/dataunit/state/slice/InvalidFieldsSlice.js.map +1 -0
  113. package/dist/dataunit/state/slice/LoadingControlSlice.d.ts +19 -0
  114. package/dist/dataunit/state/slice/LoadingControlSlice.js +45 -0
  115. package/dist/dataunit/state/slice/LoadingControlSlice.js.map +1 -0
  116. package/dist/dataunit/state/slice/RecordsSlice.d.ts +11 -0
  117. package/dist/dataunit/state/slice/RecordsSlice.js +62 -0
  118. package/dist/dataunit/state/slice/RecordsSlice.js.map +1 -0
  119. package/dist/dataunit/state/slice/RemovedRecordsSlice.d.ts +9 -0
  120. package/dist/dataunit/state/slice/RemovedRecordsSlice.js +25 -0
  121. package/dist/dataunit/state/slice/RemovedRecordsSlice.js.map +1 -0
  122. package/dist/dataunit/state/slice/SelectionSlice.d.ts +19 -0
  123. package/dist/dataunit/state/slice/SelectionSlice.js +155 -0
  124. package/dist/dataunit/state/slice/SelectionSlice.js.map +1 -0
  125. package/dist/dataunit/state/slice/SnapshotSlice.d.ts +19 -0
  126. package/dist/dataunit/state/slice/SnapshotSlice.js +106 -0
  127. package/dist/dataunit/state/slice/SnapshotSlice.js.map +1 -0
  128. package/dist/dataunit/state/slice/UnitMetadataSlice.d.ts +11 -0
  129. package/dist/dataunit/state/slice/UnitMetadataSlice.js +21 -0
  130. package/dist/dataunit/state/slice/UnitMetadataSlice.js.map +1 -0
  131. package/dist/dataunit/state/slice/WaitingChangesSlice.d.ts +12 -0
  132. package/dist/dataunit/state/slice/WaitingChangesSlice.js +56 -0
  133. package/dist/dataunit/state/slice/WaitingChangesSlice.js.map +1 -0
  134. package/dist/exceptions/ErrorException.d.ts +14 -0
  135. package/dist/exceptions/ErrorException.js +13 -0
  136. package/dist/exceptions/ErrorException.js.map +1 -0
  137. package/dist/exceptions/WaitingChangeException.d.ts +12 -0
  138. package/dist/exceptions/WaitingChangeException.js +12 -0
  139. package/dist/exceptions/WaitingChangeException.js.map +1 -0
  140. package/dist/exceptions/WarningException.d.ts +14 -0
  141. package/dist/exceptions/WarningException.js +13 -0
  142. package/dist/exceptions/WarningException.js.map +1 -0
  143. package/dist/html/HTMLBuilder.d.ts +3 -0
  144. package/dist/html/HTMLBuilder.js +9 -0
  145. package/dist/html/HTMLBuilder.js.map +1 -0
  146. package/dist/http/AuthorizedServiceCaller.d.ts +11 -0
  147. package/dist/http/AuthorizedServiceCaller.js +54 -0
  148. package/dist/http/AuthorizedServiceCaller.js.map +1 -0
  149. package/dist/http/HttpProvider.d.ts +25 -0
  150. package/dist/http/HttpProvider.js +74 -0
  151. package/dist/http/HttpProvider.js.map +1 -0
  152. package/dist/http/RequestMetadata.d.ts +30 -0
  153. package/dist/http/RequestMetadata.js +25 -0
  154. package/dist/http/RequestMetadata.js.map +1 -0
  155. package/dist/http/SkwHttpProvider.d.ts +9 -0
  156. package/dist/http/SkwHttpProvider.js +67 -0
  157. package/dist/http/SkwHttpProvider.js.map +1 -0
  158. package/dist/index.d.ts +34 -0
  159. package/dist/index.js +33 -0
  160. package/dist/index.js.map +1 -0
  161. package/dist/traking/ErrorTraking.d.ts +19 -0
  162. package/dist/traking/ErrorTraking.js +34 -0
  163. package/dist/traking/ErrorTraking.js.map +1 -0
  164. package/dist/ui/FloatingManager.d.ts +164 -0
  165. package/dist/ui/FloatingManager.js +358 -0
  166. package/dist/ui/FloatingManager.js.map +1 -0
  167. package/dist/utils/ApplicationContext.d.ts +26 -0
  168. package/dist/utils/ApplicationContext.js +38 -0
  169. package/dist/utils/ApplicationContext.js.map +1 -0
  170. package/dist/utils/ArrayUtils.d.ts +29 -0
  171. package/dist/utils/ArrayUtils.js +57 -0
  172. package/dist/utils/ArrayUtils.js.map +1 -0
  173. package/dist/utils/CriteriaModel.d.ts +107 -0
  174. package/dist/utils/CriteriaModel.js +172 -0
  175. package/dist/utils/CriteriaModel.js.map +1 -0
  176. package/dist/utils/CriteriaParameter.d.ts +69 -0
  177. package/dist/utils/CriteriaParameter.js +83 -0
  178. package/dist/utils/CriteriaParameter.js.map +1 -0
  179. package/dist/utils/DateUtils.d.ts +97 -0
  180. package/dist/utils/DateUtils.js +171 -0
  181. package/dist/utils/DateUtils.js.map +1 -0
  182. package/dist/utils/ElementIDUtils.d.ts +72 -0
  183. package/dist/utils/ElementIDUtils.js +161 -0
  184. package/dist/utils/ElementIDUtils.js.map +1 -0
  185. package/dist/utils/JSUtils.d.ts +36 -0
  186. package/dist/utils/JSUtils.js +66 -0
  187. package/dist/utils/JSUtils.js.map +1 -0
  188. package/dist/utils/MaskFormatter.d.ts +148 -0
  189. package/dist/utils/MaskFormatter.js +356 -0
  190. package/dist/utils/MaskFormatter.js.map +1 -0
  191. package/dist/utils/NumberUtils.d.ts +127 -0
  192. package/dist/utils/NumberUtils.js +245 -0
  193. package/dist/utils/NumberUtils.js.map +1 -0
  194. package/dist/utils/ObjectUtils.d.ts +47 -0
  195. package/dist/utils/ObjectUtils.js +68 -0
  196. package/dist/utils/ObjectUtils.js.map +1 -0
  197. package/dist/utils/OnboardingUtils.d.ts +17 -0
  198. package/dist/utils/OnboardingUtils.js +41 -0
  199. package/dist/utils/OnboardingUtils.js.map +1 -0
  200. package/dist/utils/ReadyUtil.d.ts +24 -0
  201. package/dist/utils/ReadyUtil.js +41 -0
  202. package/dist/utils/ReadyUtil.js.map +1 -0
  203. package/dist/utils/StringUtils.d.ts +167 -0
  204. package/dist/utils/StringUtils.js +328 -0
  205. package/dist/utils/StringUtils.js.map +1 -0
  206. package/dist/utils/TimeFormatter.d.ts +33 -0
  207. package/dist/utils/TimeFormatter.js +98 -0
  208. package/dist/utils/TimeFormatter.js.map +1 -0
  209. package/dist/utils/UserAgentUtils/index.d.ts +15 -0
  210. package/dist/utils/UserAgentUtils/index.js +48 -0
  211. package/dist/utils/UserAgentUtils/index.js.map +1 -0
  212. package/dist/utils/UserAgentUtils/navigatorAgentList.d.ts +17 -0
  213. package/dist/utils/UserAgentUtils/navigatorAgentList.js +40 -0
  214. package/dist/utils/UserAgentUtils/navigatorAgentList.js.map +1 -0
  215. package/dist/utils/VersionUtils.d.ts +7 -0
  216. package/dist/utils/VersionUtils.js +31 -0
  217. package/dist/utils/VersionUtils.js.map +1 -0
  218. package/jest.config.ts +17 -0
  219. package/mock/http/XMLHttpRequest-mock.js +26 -0
  220. package/package.json +52 -0
  221. package/scripts/runlink.bat +1 -0
  222. package/scripts/runlink.sh +1 -0
  223. package/src/async/PromiseSync.ts +49 -0
  224. package/src/dataunit/DataUnit.ts +1835 -0
  225. package/src/dataunit/DataUnitStorage.ts +43 -0
  226. package/src/dataunit/formatting/PrettyFormatter.ts +113 -0
  227. package/src/dataunit/loading/LoadDataRequest.ts +26 -0
  228. package/src/dataunit/loading/LoadDataResponse.ts +11 -0
  229. package/src/dataunit/loading/PaginationInfo.ts +18 -0
  230. package/src/dataunit/metadata/DataType.ts +127 -0
  231. package/src/dataunit/metadata/UnitMetadata.ts +102 -0
  232. package/src/dataunit/state/HistReducer.ts +34 -0
  233. package/src/dataunit/state/StateManager.ts +142 -0
  234. package/src/dataunit/state/action/DataUnitAction.ts +67 -0
  235. package/src/dataunit/state/slice/AddedRecordsSlice.ts +48 -0
  236. package/src/dataunit/state/slice/ChangesSlice.ts +125 -0
  237. package/src/dataunit/state/slice/InvalidFieldsSlice.ts +85 -0
  238. package/src/dataunit/state/slice/LoadingControlSlice.ts +60 -0
  239. package/src/dataunit/state/slice/RecordsSlice.ts +74 -0
  240. package/src/dataunit/state/slice/RemovedRecordsSlice.ts +30 -0
  241. package/src/dataunit/state/slice/SelectionSlice.ts +193 -0
  242. package/src/dataunit/state/slice/SnapshotSlice.ts +139 -0
  243. package/src/dataunit/state/slice/UnitMetadataSlice.ts +30 -0
  244. package/src/dataunit/state/slice/WaitingChangesSlice.ts +74 -0
  245. package/src/exceptions/ErrorException.ts +25 -0
  246. package/src/exceptions/WaitingChangeException.ts +21 -0
  247. package/src/exceptions/WarningException.ts +26 -0
  248. package/src/html/HTMLBuilder.ts +8 -0
  249. package/src/http/AuthorizedServiceCaller.ts +58 -0
  250. package/src/http/HttpProvider.ts +94 -0
  251. package/src/http/RequestMetadata.ts +42 -0
  252. package/src/http/SkwHttpProvider.ts +78 -0
  253. package/src/index.ts +93 -0
  254. package/src/traking/ErrorTraking.ts +37 -0
  255. package/src/ui/FloatingManager.ts +417 -0
  256. package/src/utils/ApplicationContext.ts +42 -0
  257. package/src/utils/ArrayUtils.ts +61 -0
  258. package/src/utils/CriteriaModel.ts +205 -0
  259. package/src/utils/CriteriaParameter.ts +108 -0
  260. package/src/utils/DateUtils.ts +195 -0
  261. package/src/utils/ElementIDUtils.ts +184 -0
  262. package/src/utils/JSUtils.ts +69 -0
  263. package/src/utils/MaskFormatter.ts +407 -0
  264. package/src/utils/NumberUtils.ts +283 -0
  265. package/src/utils/ObjectUtils.ts +76 -0
  266. package/src/utils/OnboardingUtils.ts +46 -0
  267. package/src/utils/ReadyUtil.ts +45 -0
  268. package/src/utils/StringUtils.ts +359 -0
  269. package/src/utils/TimeFormatter.ts +98 -0
  270. package/src/utils/UserAgentUtils/index.ts +62 -0
  271. package/src/utils/UserAgentUtils/navigatorAgentList.ts +39 -0
  272. package/src/utils/VersionUtils.ts +37 -0
  273. package/test/http/HttpProvider.spec.ts +35 -0
  274. package/test/http/SkwHttpProvider.ts.spec.ts +34 -0
  275. package/test/util/CriteriaModel.spec.ts +232 -0
  276. package/test/util/CriteriaParameter.spec.ts +52 -0
  277. package/test/util/DataUnitStorage.spec.ts +63 -0
  278. package/test/util/ElementIDUtils.spec.ts +272 -0
  279. package/test/util/MaskFormatter.spec.ts +138 -0
  280. package/test/util/NumberUtils.spec.ts +182 -0
  281. package/test/util/StringUtils.spec.ts +51 -0
  282. package/test/util/TimeFormatter.spec.ts +26 -0
  283. package/tsconfig.json +16 -0
@@ -0,0 +1,1621 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { convertType, DataType, toString } from "./metadata/DataType.js";
11
+ import { Action, DataUnitAction } from "./state/action/DataUnitAction.js";
12
+ import StateManager from "./state/StateManager.js";
13
+ import ErrorException from "../exceptions/ErrorException.js";
14
+ import WaitingChangeException from "../exceptions/WaitingChangeException.js";
15
+ import { StringUtils } from "../utils/StringUtils.js";
16
+ import ObjectUtils from "../utils/ObjectUtils.js";
17
+ import { AddedRecordsReducer, getAddedRecords, prepareAddedRecordId, prepareCopiedRecord } from "./state/slice/AddedRecordsSlice.js";
18
+ import { ChangesReducer, getChangesToSave, isDirty, hasDirtyRecords } from "./state/slice/ChangesSlice.js";
19
+ import { SnapshotReducer, getCurrentRecords, getFieldValue, getModifiedRecords, getSelectionRecords, } from './state/slice/SnapshotSlice.js';
20
+ import { getCurrentPage, getLastPage, getPaginationInfo, getCurrentRequest, LoadingControlReducer, hasMorePages, hasPreviousPages } from "./state/slice/LoadingControlSlice.js";
21
+ import { getRecords, RecordsReducer } from "./state/slice/RecordsSlice.js";
22
+ import { RemovedRecordsReducer } from "./state/slice/RemovedRecordsSlice.js";
23
+ import { getSelection, getSelectionInfo, hasNext, hasPrevious, SelectionReducer } from "./state/slice/SelectionSlice.js";
24
+ import { getField, getMetadata, UnitMetadataReducer } from "./state/slice/UnitMetadataSlice.js";
25
+ import { getBlockingWaitingChanges, getWaitingChangePromisses, getWaitingChanges, isWaiting, WaitingChangesReducer } from "./state/slice/WaitingChangesSlice.js";
26
+ import { canRedo, canUndo, HistReducer } from "./state/HistReducer.js";
27
+ import { getFormattedValue } from "./formatting/PrettyFormatter.js";
28
+ import { v4 as uuid } from "uuid";
29
+ import { DataUnitStorage } from "./DataUnitStorage.js";
30
+ import { getInvalidFieldMessage, InvalidFieldsReducer } from "./state/slice/InvalidFieldsSlice.js";
31
+ const DEFAULT_DATAUNIT_NAME = "dataunit";
32
+ /***
33
+ * `DataUnit`: Atua como uma camada de abstração entre o back-end e a interface do usuário.
34
+ */
35
+ export default class DataUnit {
36
+ constructor(name = DEFAULT_DATAUNIT_NAME, parentDataUnit) {
37
+ var _a;
38
+ this._childByName = new Map();
39
+ this._savingLockers = [];
40
+ /**
41
+ *
42
+ * Trata as Actions do DataUnit Parent
43
+ *
44
+ *
45
+ */
46
+ this.onDataUnitParentEvent = (action) => {
47
+ var _a;
48
+ switch (action.type) {
49
+ case Action.SELECTION_CHANGED:
50
+ case Action.NEXT_SELECTED:
51
+ case Action.PREVIOUS_SELECTED:
52
+ case Action.DATA_LOADED:
53
+ this.clearDataUnit();
54
+ const selectedRecord = (_a = this._parentDataUnit) === null || _a === void 0 ? void 0 : _a.getSelectedRecord();
55
+ if (selectedRecord != undefined && !this.isNewRecord(selectedRecord.__record__id__)) {
56
+ this.loadData();
57
+ }
58
+ break;
59
+ }
60
+ };
61
+ this._uuid = uuid();
62
+ this._name = `${name}?uuid=${this._uuid}`;
63
+ this._pageSize = 0;
64
+ this._stateManager = new StateManager([
65
+ HistReducer,
66
+ UnitMetadataReducer,
67
+ LoadingControlReducer,
68
+ RecordsReducer,
69
+ RemovedRecordsReducer,
70
+ AddedRecordsReducer,
71
+ SelectionReducer,
72
+ ChangesReducer,
73
+ WaitingChangesReducer,
74
+ InvalidFieldsReducer,
75
+ SnapshotReducer
76
+ ]);
77
+ this._observers = [];
78
+ this._filterProviders = new Map();
79
+ this._sortingProvider = undefined;
80
+ this._interceptors = [];
81
+ this._parentDataUnit = parentDataUnit;
82
+ (_a = this._parentDataUnit) === null || _a === void 0 ? void 0 : _a.subscribe(this.onDataUnitParentEvent);
83
+ this._loadingLockers = [];
84
+ DataUnitStorage.put(this);
85
+ }
86
+ /**
87
+ * Desfaz vinculos do DataUnit. Chamado quando o DU não é mais necessário.
88
+ */
89
+ release() {
90
+ DataUnitStorage.remove(this._name);
91
+ if (this._parentDataUnit) {
92
+ this._parentDataUnit.unsubscribe(this.onDataUnitParentEvent);
93
+ this._parentDataUnit.removeChildDataunit(this._name);
94
+ }
95
+ }
96
+ get dataUnitId() {
97
+ return this._uuid;
98
+ }
99
+ /**
100
+ *
101
+ * Obtém o nome de identificação do DataUnit (geralmente em formato de URI - Uniform Resource Identifier).
102
+ *
103
+ * @returns - Nome de identificação do DataUnit.
104
+ *
105
+ */
106
+ get name() {
107
+ return this._name;
108
+ }
109
+ /**
110
+ *
111
+ * Obtém o valor convertido de acordo com o tipo do campo.
112
+ *
113
+ * @param fieldName - Identificador do campo.
114
+ * @param newValue - Novo valor que será atribuído ao campo pós validação.
115
+ *
116
+ * @returns - Novo valor convertido em um tipo valido.
117
+ *
118
+ */
119
+ validateAndTypeValue(fieldName, newValue) {
120
+ const descriptor = this.getField(fieldName);
121
+ return descriptor ? convertType(descriptor.dataType, newValue) : newValue;
122
+ }
123
+ /**
124
+ *
125
+ * Obtém chave única para identificação do FilterProvider.
126
+ *
127
+ * @param provider - Interface FilterProvider na qual será retornada uma chave correspondente.
128
+ *
129
+ * @returns - A chave do provider.
130
+ *
131
+ */
132
+ getFielterProviderKey(provider) {
133
+ if (provider.getKey) {
134
+ return provider.getKey();
135
+ }
136
+ return StringUtils.hashCode(provider.getFilter.toString());
137
+ }
138
+ /**
139
+ *
140
+ * Executa o carregamento dos registros.
141
+ *
142
+ * @param request - Dados da requisição para carregamento dos registros.
143
+ * @param executionCtx - Contexto de execução do carregamento dos registros do DataUnit.
144
+ * @param checkLastFilter - Habilita a verificação da última requisição, evitando carga desnecessária.
145
+ *
146
+ * @returns - Registros do DataUnit.
147
+ *
148
+ */
149
+ executeLoadData(request, executionCtx, checkLastFilter) {
150
+ if (checkLastFilter && this.isSameRequest(request)) {
151
+ const paginationInfo = getPaginationInfo(this._stateManager);
152
+ if (paginationInfo) {
153
+ const response = {
154
+ records: getRecords(this._stateManager),
155
+ paginationInfo
156
+ };
157
+ return Promise.resolve(response);
158
+ }
159
+ }
160
+ return new Promise((resolve, fail) => __awaiter(this, void 0, void 0, function* () {
161
+ if (yield this.dispatchAction(Action.LOADING_DATA, request, executionCtx)) {
162
+ if (this.dataLoader) {
163
+ this.dataLoader(this, request).then(response => {
164
+ this.dispatchAction(Action.DATA_LOADED, Object.assign(Object.assign({}, response), { keepSelection: request.keepSelection }), executionCtx);
165
+ resolve(response);
166
+ }).catch(error => {
167
+ const { errorCode } = error;
168
+ fail(new ErrorException("Erro ao carregar registros", error, errorCode));
169
+ });
170
+ }
171
+ }
172
+ }));
173
+ }
174
+ isSameRequest(request) {
175
+ const lastRequest = getCurrentRequest(this._stateManager);
176
+ return ObjectUtils.objectToString(request) === ObjectUtils.objectToString(lastRequest || {});
177
+ }
178
+ // Loaders
179
+ /**
180
+ *
181
+ * Carrega os metadados do DataUnit.
182
+ *
183
+ * @param executionCtx - Contexto de execução do carregamento dos metadados do DataUnit.
184
+ *
185
+ * @returns - Metadados carregados.
186
+ *
187
+ */
188
+ loadMetadata(executionCtx) {
189
+ return __awaiter(this, void 0, void 0, function* () {
190
+ if (yield this.dispatchAction(Action.LOADING_METADATA, undefined, executionCtx)) {
191
+ return new Promise((resolve, fail) => {
192
+ if (this.metadataLoader) {
193
+ this.metadataLoader(this).then(metadata => {
194
+ this.metadata = metadata;
195
+ resolve(this.metadata);
196
+ }).catch(error => {
197
+ const { errorCode } = error;
198
+ fail(new ErrorException("Erro ao carregar metadados", error, errorCode));
199
+ });
200
+ }
201
+ });
202
+ }
203
+ });
204
+ }
205
+ /**
206
+ *
207
+ * Carrega os registros do DataUnit.
208
+ *
209
+ * @param quickFilter - Filtros a serem aplicados.
210
+ * @param executionCtx - Contexto de execução do carregamento dos registros.
211
+ * @param checkLastFilter - Habilita a verificação da última requisição, evitando carga desnecessária.
212
+ *
213
+ * @returns - Registros requisitados.
214
+ *
215
+ */
216
+ loadData(quickFilter, executionCtx, checkLastFilter) {
217
+ return __awaiter(this, void 0, void 0, function* () {
218
+ yield this.processLoadingLockers();
219
+ if (this._parentDataUnit && !this._parentDataUnit.getSelectedRecord()) {
220
+ if (this.records) {
221
+ this.clearDataUnit();
222
+ }
223
+ return Promise.resolve({
224
+ records: []
225
+ });
226
+ }
227
+ const loadDataRequest = this.getLoadDataRequest(quickFilter);
228
+ return this.executeLoadData(loadDataRequest, executionCtx, checkLastFilter);
229
+ });
230
+ }
231
+ /**
232
+ *
233
+ * Alterna entre os registros por número de página.
234
+ *
235
+ * @param page - Número da página desejada.
236
+ * @param executionCtx - Contexto de execução do carregamento dos registros do DataUnit.
237
+ *
238
+ * @returns - Registros da página desejada.
239
+ *
240
+ */
241
+ gotoPage(page, executionCtx) {
242
+ return __awaiter(this, void 0, void 0, function* () {
243
+ let request = getCurrentRequest(this._stateManager);
244
+ if (!request) {
245
+ request = {
246
+ filters: this.getFilters(),
247
+ sort: this.getSort()
248
+ };
249
+ }
250
+ if (page >= 0 && page <= getLastPage(this._stateManager, this._pageSize)) {
251
+ return this.executeLoadData(Object.assign(Object.assign({}, request), { limit: this._pageSize, offset: page * this._pageSize, keepSelection: true }), executionCtx);
252
+ }
253
+ });
254
+ }
255
+ /**
256
+ *
257
+ * Vai para os registros da página seguinte.
258
+ *
259
+ * @param executionCtx - Contexto de execução do carregamento dos registros do DataUnit.
260
+ *
261
+ * @returns - Registros da página seguinte.
262
+ *
263
+ */
264
+ nextPage(executionCtx) {
265
+ return __awaiter(this, void 0, void 0, function* () {
266
+ return this.gotoPage(getCurrentPage(this._stateManager) + 1, executionCtx);
267
+ });
268
+ }
269
+ /**
270
+ *
271
+ * Vai para os registros da página anterior.
272
+ *
273
+ * @param executionCtx - Contexto de execução do carregamento dos registros do DataUnit.
274
+ *
275
+ * @returns - Registros da página anterior.
276
+ *
277
+ */
278
+ previousPage(executionCtx) {
279
+ return __awaiter(this, void 0, void 0, function* () {
280
+ return this.gotoPage(getCurrentPage(this._stateManager) - 1, executionCtx);
281
+ });
282
+ }
283
+ getLoadDataRequest(quickFilter) {
284
+ const request = {
285
+ filters: (quickFilter === null || quickFilter === void 0 ? void 0 : quickFilter.filter) ? [quickFilter.filter] : this.getFilters(),
286
+ sort: this.getSort(),
287
+ parentRecordId: this.getParentRecordId()
288
+ };
289
+ if (quickFilter) {
290
+ request.quickFilter = quickFilter;
291
+ }
292
+ if (this._pageSize > 0) {
293
+ request.limit = this._pageSize;
294
+ request.offset = 0;
295
+ }
296
+ return request;
297
+ }
298
+ notifySavingData(executionCtx) {
299
+ return __awaiter(this, void 0, void 0, function* () {
300
+ const notifyPromises = [];
301
+ Array.from(this._childByName.values()).forEach(child => notifyPromises.push(child.notifySavingData(executionCtx)));
302
+ if (isDirty(this._stateManager)) {
303
+ notifyPromises.push(this.dispatchAction(Action.SAVING_DATA, undefined, executionCtx));
304
+ }
305
+ return new Promise(accept => Promise.all(notifyPromises).then(responses => {
306
+ accept(responses.reduce((previous, current) => previous && current, true));
307
+ }));
308
+ });
309
+ }
310
+ getBeforeSavePromisses() {
311
+ let promises = getWaitingChangePromisses(this._stateManager) || [];
312
+ promises = promises.concat(this._savingLockers);
313
+ return promises;
314
+ }
315
+ /**
316
+ *
317
+ * Salva o estado do registro do DataUnit.
318
+ *
319
+ * @param executionCtx - Contexto de execução da persistencia do registro do DataUnit.
320
+ *
321
+ * @returns - Resposta da solicitação.
322
+ *
323
+ */
324
+ saveData(executionCtx) {
325
+ return __awaiter(this, void 0, void 0, function* () {
326
+ const blockingWaitingChanges = getBlockingWaitingChanges(this._stateManager);
327
+ if (blockingWaitingChanges && blockingWaitingChanges.size > 0) {
328
+ const [_, waitingChange] = blockingWaitingChanges.entries().next().value;
329
+ return Promise.reject(new WaitingChangeException("Aguardando alteração de campo", waitingChange.waitmessage));
330
+ }
331
+ else {
332
+ if (this.isDirty()) {
333
+ if (yield this.notifySavingData(executionCtx)) {
334
+ const promisses = this.getBeforeSavePromisses();
335
+ return new Promise((resolve, fail) => {
336
+ Promise.all(promisses || []).then(() => {
337
+ this._savingLockers = [];
338
+ if (this.saveLoader) {
339
+ const changes = this.getAllChangesToSave();
340
+ this.saveLoader(this, changes).then((records) => {
341
+ const recordsByDataUnit = this.getRecordsByDataUnit(records);
342
+ const dispatchPromisses = [];
343
+ for (const [ownerDataUnitName, splittedRecords] of recordsByDataUnit) {
344
+ const ownerDataUnit = DataUnitStorage.get(ownerDataUnitName);
345
+ const changesByDataUnit = changes.filter(change => change.dataUnit === ownerDataUnitName);
346
+ if (ownerDataUnit) {
347
+ dispatchPromisses.push(ownerDataUnit.dispatchAction(Action.DATA_SAVED, { changes: changesByDataUnit, records: splittedRecords }, executionCtx));
348
+ }
349
+ }
350
+ Promise.all(dispatchPromisses).then(() => resolve());
351
+ }).catch(cause => {
352
+ const { errorCode } = cause;
353
+ fail(new ErrorException("Erro ao salvar alterações", cause, errorCode));
354
+ });
355
+ }
356
+ else {
357
+ resolve();
358
+ }
359
+ });
360
+ });
361
+ }
362
+ }
363
+ }
364
+ return Promise.resolve();
365
+ });
366
+ }
367
+ /**
368
+ *
369
+ * Retorna as alterações a serem salvas no DataUnit atual.
370
+ *
371
+ *
372
+ *
373
+ * @returns - Mudanças realizadas no DataUnit atual
374
+ *
375
+ */
376
+ buildChangesToSave() {
377
+ return getChangesToSave(this._name, this._stateManager);
378
+ }
379
+ buildChangesToSaveFromChild(allChanges, dataUnit) {
380
+ var _a;
381
+ (_a = dataUnit._childByName) === null || _a === void 0 ? void 0 : _a.forEach((dataUnitChild) => {
382
+ if (dataUnitChild.isDirty()) {
383
+ allChanges.push(...getChangesToSave(dataUnitChild.name, dataUnitChild._stateManager));
384
+ this.buildChangesToSaveFromChild(allChanges, dataUnitChild);
385
+ }
386
+ });
387
+ }
388
+ /**
389
+ *
390
+ * Retorna todas as alterações do DataUnit a serem salvas, incluindo no nível Master e Detail.
391
+ *
392
+ *
393
+ *
394
+ * @returns - Todas as mudanças realizadas no DataUnit, tanto Master quanto Detail;
395
+ *
396
+ */
397
+ getAllChangesToSave() {
398
+ const allChanges = [];
399
+ allChanges.push(...this.buildChangesToSave());
400
+ this.buildChangesToSaveFromChild(allChanges, this);
401
+ return allChanges;
402
+ }
403
+ /**
404
+ *
405
+ * Remove o registro selecionado.
406
+ *
407
+ * @param buffered - Se será utilizado buffer na solicitação.
408
+ * @param silent - Define se haverá mensagem de confirmação da remoção
409
+ *
410
+ * @returns - ID's dos registros removidos.
411
+ *
412
+ */
413
+ removeSelectedRecords(buffered = false, silent = false) {
414
+ return __awaiter(this, void 0, void 0, function* () {
415
+ const selection = this.getSelectionInfo();
416
+ if (selection) {
417
+ if (selection.isAllRecords()) {
418
+ throw new Error("Exclusão remota não implementada.");
419
+ }
420
+ const records = (selection === null || selection === void 0 ? void 0 : selection.records) || [];
421
+ const recordIds = (selection === null || selection === void 0 ? void 0 : selection.recordIds) || [];
422
+ return this.removeRecords(recordIds, records, buffered, undefined, silent);
423
+ }
424
+ return Promise.resolve([]);
425
+ });
426
+ }
427
+ /**
428
+ *
429
+ * Efetua requisição para remoção dos registros.
430
+ *
431
+ * @param recordIds - Lista de IDs dos registros que serão removidos.
432
+ * @param cachedRecords - Dados dos registros que serão removidos.
433
+ * @param buffered - Se será utilizado buffer na solicitação.
434
+ * @param executionCtx - Contexto de execução da remoção do registro do DataUnit.
435
+ * @param silent - Define se haverá mensagem de confirmação da remoção
436
+ *
437
+ * @returns - ID's dos registros removidos.
438
+ *
439
+ */
440
+ removeRecords(recordIds, cachedRecords, buffered = false, executionCtx, silent = false) {
441
+ return __awaiter(this, void 0, void 0, function* () {
442
+ if (recordIds) {
443
+ if (buffered || !this.removeLoader) {
444
+ this.dispatchAction(Action.RECORDS_REMOVED, { records: recordIds, cachedRecords, buffered: true }, executionCtx);
445
+ }
446
+ else {
447
+ if (yield this.dispatchAction(Action.REMOVING_RECORDS, { silent }, executionCtx)) {
448
+ return new Promise((resolve, fail) => {
449
+ if (this.removeLoader) {
450
+ this.removeLoader(this, recordIds).then(removedIds => {
451
+ let currentIndex = 0;
452
+ const removedIndex = [];
453
+ const currentRecords = getCurrentRecords(this._stateManager);
454
+ currentRecords.forEach((value, key) => {
455
+ if (removedIds.includes(key)) {
456
+ removedIndex.push(currentIndex);
457
+ }
458
+ currentIndex++;
459
+ });
460
+ this.dispatchAction(Action.RECORDS_REMOVED, { records: removedIds, cachedRecords, removedIndex, buffered: false }, executionCtx);
461
+ resolve(removedIds);
462
+ }).catch(error => {
463
+ const { errorCode } = error;
464
+ fail(new ErrorException("Erro ao remover registros", error, errorCode));
465
+ });
466
+ }
467
+ });
468
+ }
469
+ }
470
+ }
471
+ return Promise.resolve(recordIds);
472
+ });
473
+ }
474
+ // API
475
+ /**
476
+ *
477
+ * Obtém o valor do campo em seu formato/tipo correto a partir de uma string.
478
+ *
479
+ * @param fieldName - Nome do campo que terá o tipo identificado para conversão.
480
+ * @param value - Texto que será convertido de acordo com o tipo identificado no campo.
481
+ *
482
+ * @returns - Valor convertido ou ele mesmo.
483
+ *
484
+ */
485
+ valueFromString(fieldName, value) {
486
+ const descriptor = this.getField(fieldName);
487
+ return descriptor ? convertType(descriptor.dataType, value) : value;
488
+ }
489
+ /**
490
+ *
491
+ * Converte o valor informado para texto de acordo com o tipo do campo informado.
492
+ *
493
+ * @param fieldName - Nome do campo utilizado para buscar o tipo de dado com o padrão de conversão para string.
494
+ * @param value - Valor a ser convertido.
495
+ *
496
+ * @returns - Valor informado convertido.
497
+ *
498
+ */
499
+ valueToString(fieldName, value) {
500
+ const descriptor = this.getField(fieldName);
501
+ return toString(descriptor === null || descriptor === void 0 ? void 0 : descriptor.dataType, value);
502
+ }
503
+ /**
504
+ *
505
+ * Formata o valor do campo considerando as informações do descriptor.
506
+ * Diferente do método "valueToString" que retorna o dado em valor textual,
507
+ * getFormattedValue retorna uma informação amigável ao usuário, geralmente
508
+ * usada na interface.
509
+ *
510
+ * @param fieldName - Nome do campo utilizado do qual se quer obter valor.
511
+ * @param value (opcional) - O valor a ser convertido. Caso omitido pega do registro selecionado.
512
+ *
513
+ * @returns - Valor formatado.
514
+ *
515
+ */
516
+ getFormattedValue(fieldName, value) {
517
+ const descriptor = this.getField(fieldName);
518
+ if (value == undefined) {
519
+ value = this.getFieldValue(fieldName);
520
+ }
521
+ else if (typeof value === "string" && (descriptor === null || descriptor === void 0 ? void 0 : descriptor.dataType) != DataType.TEXT) {
522
+ value = this.valueFromString(fieldName, value);
523
+ }
524
+ if (value == undefined) {
525
+ return "";
526
+ }
527
+ return getFormattedValue(value, descriptor);
528
+ }
529
+ /**
530
+ *
531
+ * Adiciona um interceptor correspondente a uma ação do DataUnit para fazer um processamento customizado.
532
+ *
533
+ * @param interceptor - Interceptor a ser adicionado.
534
+ *
535
+ */
536
+ addInterceptor(interceptor) {
537
+ this._interceptors.push(interceptor);
538
+ }
539
+ /**
540
+ *
541
+ * Remove um interceptor da lista de interceptors.
542
+ *
543
+ * @param interceptor - Interceptor a ser removido.
544
+ *
545
+ */
546
+ removeInterceptor(interceptor) {
547
+ this._interceptors = this._interceptors.filter(i => i !== interceptor);
548
+ }
549
+ /**
550
+ *
551
+ * Adiciona um FilterProvider.
552
+ *
553
+ * @param provider - FilterProvider que será adicionado.
554
+ *
555
+ */
556
+ addFilterProvider(provider) {
557
+ this._filterProviders.set(this.getFielterProviderKey(provider), provider);
558
+ }
559
+ /**
560
+ *
561
+ * Obtém informações de paginação dos registros.
562
+ *
563
+ * @returns - Informações da paginação de registros.
564
+ */
565
+ getPaginationInfo() {
566
+ return getPaginationInfo(this._stateManager);
567
+ }
568
+ /**
569
+ *
570
+ * Define a lógica de ordenação dos registros.
571
+ *
572
+ * @param provider - Objeto usado para definir a propriedade sortingProvider da instância da classe.
573
+ *
574
+ */
575
+ set sortingProvider(provider) {
576
+ this._sortingProvider = provider;
577
+ }
578
+ /**
579
+ *
580
+ * Define a propriedade metadata da instância da classe com um novo valor e chama o método dispatchAction para notificar os observers da aplicação sobre a mudança.
581
+ *
582
+ */
583
+ set metadata(md) {
584
+ this.dispatchAction(Action.METADATA_LOADED, md, undefined);
585
+ }
586
+ /**
587
+ *
588
+ * Obtém os metadados do DataUnit.
589
+ *
590
+ */
591
+ get metadata() {
592
+ return getMetadata(this._stateManager);
593
+ }
594
+ /**
595
+ *
596
+ * Obtém informações da ligação para um DataUnit filho.
597
+ *
598
+ * @param name - Nome do DataUnit que se deseja.
599
+ *
600
+ * @returns - As informações sobre a ligação solicitada. Pode retornar undefined.
601
+ *
602
+ */
603
+ getChildInfo(name) {
604
+ var _a;
605
+ const children = (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.children;
606
+ if (children == undefined) {
607
+ return;
608
+ }
609
+ return children.find(child => child.name === name);
610
+ }
611
+ /**
612
+ *
613
+ * Define a propriedade records da instância da classe com um novo valor e chama o método dispatchAction para notificar os observers da aplicação sobre a mudança.
614
+ *
615
+ */
616
+ set records(records) {
617
+ this.dispatchAction(Action.DATA_LOADED, { records }, undefined);
618
+ }
619
+ /**
620
+ *
621
+ * Obtém todos os registros atuais.
622
+ *
623
+ * @returns - Todos os registros atuais.
624
+ *
625
+ */
626
+ get records() {
627
+ const records = getCurrentRecords(this._stateManager);
628
+ return records ? Array.from(records.values()) : [];
629
+ }
630
+ /**
631
+ *
632
+ * Define a quantidade de registros que será exibido por página.
633
+ *
634
+ * @param size - Quantidade de registros que será exibido por página.
635
+ *
636
+ */
637
+ set pageSize(size) {
638
+ this._pageSize = size;
639
+ }
640
+ /**
641
+ *
642
+ * Obtém a quantidade de registros que está sendo exibido por página.
643
+ *
644
+ * @returns - Quantidade de registros exibidos por página.
645
+ *
646
+ */
647
+ get pageSize() {
648
+ return this._pageSize;
649
+ }
650
+ /**
651
+ *
652
+ * Obtém os registros modificados e ainda não salvos no DataUnit.
653
+ *
654
+ * @returns - Lista dos registros em edição.
655
+ *
656
+ */
657
+ getModifiedRecords() {
658
+ const modified = getModifiedRecords(this._stateManager);
659
+ return modified || [];
660
+ }
661
+ /**
662
+ *
663
+ * Obtém os registros adicionados no DataUnit.
664
+ *
665
+ * @returns - Lista dos registros adicionados.
666
+ *
667
+ */
668
+ getAddedRecords() {
669
+ return getAddedRecords(this._stateManager);
670
+ }
671
+ /**
672
+ *
673
+ * Obtém metadados de um campo específico.
674
+ *
675
+ * @param fieldName - Identificador do campo.
676
+ *
677
+ * @returns - Metadados do campo informado.
678
+ */
679
+ getField(fieldName) {
680
+ return getField(this._stateManager, fieldName);
681
+ }
682
+ /**
683
+ *
684
+ * Adiciona um novo registro.
685
+ *
686
+ * @param executionCtx - Contexto de execução da inserção do dado no DataUnit.
687
+ *
688
+ */
689
+ addRecord(executionCtx) {
690
+ return __awaiter(this, void 0, void 0, function* () {
691
+ return this.dispatchAction(Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}], this.getParentRecordId()), executionCtx);
692
+ });
693
+ }
694
+ /**
695
+ *
696
+ * Efetua a cópia do registro selecionado.
697
+ *
698
+ * @param executionCtx - Contexto de execução da cópia do dado do DataUnit.
699
+ *
700
+ */
701
+ copySelected(executionCtx) {
702
+ const selectionInfo = this.getSelectionInfo();
703
+ if (selectionInfo) {
704
+ const selectedRecords = selectionInfo.records;
705
+ if (selectedRecords) {
706
+ this.dispatchAction(Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords, this.getParentRecordId()), executionCtx);
707
+ }
708
+ }
709
+ }
710
+ getRecordsByDataUnit(records) {
711
+ const recordsMap = new Map();
712
+ records.forEach(record => {
713
+ let { __owner__dataunit__name__: ownerDataUnitName } = record;
714
+ if (!ownerDataUnitName) {
715
+ ownerDataUnitName = this.name;
716
+ }
717
+ let changes = recordsMap.get(ownerDataUnitName);
718
+ if (!changes) {
719
+ changes = [];
720
+ recordsMap.set(ownerDataUnitName, changes);
721
+ }
722
+ changes.push(record);
723
+ });
724
+ return recordsMap;
725
+ }
726
+ getParentRecordId() {
727
+ var _a;
728
+ const parentRecord = (_a = this._parentDataUnit) === null || _a === void 0 ? void 0 : _a.getSelectedRecord();
729
+ return parentRecord === null || parentRecord === void 0 ? void 0 : parentRecord.__record__id__;
730
+ }
731
+ /**
732
+ *
733
+ * Retorna se a alteração no campo já foi concluída ou se ainda está incompleta.
734
+ *
735
+ * @param fieldName - Identificador do campo a ser verificado.
736
+ *
737
+ * @returns - Verdadeiro se ainda está pendente.
738
+ *
739
+ */
740
+ waitingForChange(fieldName) {
741
+ return isWaiting(this._stateManager, fieldName);
742
+ }
743
+ /**
744
+ *
745
+ * Obtém valor do campo desejado.
746
+ *
747
+ * @param fieldName - Identificador do campo a ser buscado.
748
+ *
749
+ * @returns - Valor do campo.
750
+ *
751
+ */
752
+ getFieldValue(fieldName) {
753
+ return getFieldValue(this._stateManager, fieldName);
754
+ }
755
+ /**
756
+ *
757
+ * Insere valor no campo desejado.
758
+ *
759
+ * @param fieldName -Identificador do campo a ser modificado.
760
+ * @param newValue - Valor a ser inserido no campo.
761
+ * @param records - Indica quais registros foram afetados pela alteração no valor do campo.
762
+ * @returns - Promise que será resolvida quando o novo valor for persistido no state.
763
+ *
764
+ */
765
+ setFieldValue(fieldName, newValue, records) {
766
+ return __awaiter(this, void 0, void 0, function* () {
767
+ if (!this.hasNewRecord() && !this.getSelectedRecord())
768
+ yield this.addRecord();
769
+ const typedValue = this.validateAndTypeValue(fieldName, newValue);
770
+ const currentValue = this.getFieldValue(fieldName);
771
+ if (newValue instanceof Promise) {
772
+ const promise = new Promise(accept => {
773
+ newValue.then(resolvedValue => {
774
+ this.dispatchAction(Action.DATA_RESOLVED, { [fieldName]: resolvedValue, records }, undefined);
775
+ accept(this.setFieldValue(fieldName, resolvedValue, records));
776
+ });
777
+ });
778
+ this._savingLockers.push(promise);
779
+ return promise;
780
+ }
781
+ if (currentValue !== typedValue) {
782
+ const promise = this.dispatchAction(Action.DATA_CHANGED, { [fieldName]: typedValue, records }, undefined);
783
+ this._savingLockers.push(promise);
784
+ return promise;
785
+ }
786
+ return Promise.resolve(false);
787
+ });
788
+ }
789
+ /**
790
+ *
791
+ * Marca campos como inválidos.
792
+ *
793
+ * @param fieldName - Nome do campo inválido.
794
+ * @param message - Mensagem descrevendo o motivo da invalidade.
795
+ * @param recordId - Indica qual registro está com o campo inválido.
796
+ *
797
+ */
798
+ setInvalidField(fieldName, message, recordId) {
799
+ this.dispatchAction(Action.FIELD_INVALIDATED, { fieldName, message, recordId }, undefined);
800
+ }
801
+ /**
802
+ *
803
+ * Limpa campos inválidos.
804
+ *
805
+ * @param recordId - Indica em qual registro o campo não está mais inválido.
806
+ * @param fieldName - Nome do campo. Caso omitido, todos os campos serão limpos.
807
+ *
808
+ */
809
+ clearInvalid(recordId, fieldName) {
810
+ this.dispatchAction(Action.INVALIDATE_CLEAN, { fieldName, recordId }, undefined);
811
+ }
812
+ /**
813
+ *
814
+ * Obtém a mensagem de campo inválido para determinado registro.
815
+ *
816
+ * @param recordId - Identificador do registro.
817
+ * @param fieldName - Nome do campo.
818
+ *
819
+ */
820
+ getInvalidMessage(recordId, fieldName) {
821
+ return getInvalidFieldMessage(this._stateManager, fieldName, recordId);
822
+ }
823
+ /**
824
+ *
825
+ * Inicia alteração no campo.
826
+ *
827
+ * @param fieldName - Identificador do campo a ser modificado.
828
+ * @param waitingChange - Informa que uma mudança irá iniciar.
829
+ *
830
+ */
831
+ startChange(fieldName, waitingChange) {
832
+ this.dispatchAction(Action.CHANGING_DATA, { [fieldName]: waitingChange }, undefined);
833
+ }
834
+ /**
835
+ *
836
+ * Cancela o início de uma alteração no campo.
837
+ *
838
+ * @param fieldName - Identificador do campo.
839
+ *
840
+ */
841
+ cancelWaitingChange(fieldName) {
842
+ this.dispatchAction(Action.WAITING_CHANGE_CANCELED, { fieldName }, undefined);
843
+ }
844
+ /**
845
+ * Retorna se existe alterações pendentes.
846
+ * @returns Verdadeiro se existir pendências de modificações.
847
+ */
848
+ hasWaitingChanges() {
849
+ const waitingChanges = getWaitingChanges(this._stateManager);
850
+ return waitingChanges ? !!waitingChanges.size : false;
851
+ }
852
+ /**
853
+ *
854
+ * Seleciona o primeiro registro.
855
+ *
856
+ * @param executionCtx - Contexto de execução da seleção do registro do DataUnit.
857
+ *
858
+ */
859
+ selectFirst(executionCtx) {
860
+ if (this.records.length > 0) {
861
+ this.setSelectionByIndex([0], executionCtx);
862
+ }
863
+ }
864
+ /**
865
+ *
866
+ * Seleciona o último registro.
867
+ *
868
+ * @param executionCtx - Contexto de execução da seleção do registro do DataUnit.
869
+ *
870
+ */
871
+ selectLast(executionCtx) {
872
+ if (this.records.length > 0) {
873
+ this.setSelectionByIndex([this.records.length - 1], executionCtx);
874
+ }
875
+ }
876
+ /**
877
+ *
878
+ * Seleciona múltiplos registros por índice.
879
+ *
880
+ * @param selection - Índices desejados para a seleção.
881
+ * @param executionCtx - Contexto de execução da seleção do registro do DataUnit.
882
+ *
883
+ */
884
+ setSelectionByIndex(selection, executionCtx) {
885
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "index", selection }, executionCtx);
886
+ }
887
+ /**
888
+ *
889
+ * Seleciona múltiplos registros por ID ou todos os registros (multipágina) .
890
+ *
891
+ * @param selection - IDs para selecionar ou o modo de seleção completo.
892
+ * @param executionCtx - Contexto de execução da seleção dos registros do DataUnit.
893
+ *
894
+ *
895
+ */
896
+ setSelection(selection, executionCtx) {
897
+ return new Promise(resolve => {
898
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection }, executionCtx)
899
+ .then(() => resolve(getSelectionInfo(this._stateManager)));
900
+ });
901
+ }
902
+ /**
903
+ *
904
+ * Limpa a seleção.
905
+ *
906
+ * @param executionCtx - Contexto de execução da seleção dos registros do DataUnit.
907
+ *
908
+ */
909
+ clearSelection(executionCtx) {
910
+ this.setSelection([], executionCtx);
911
+ }
912
+ /**
913
+ *
914
+ * Atualiza a seleção dos registros atuais.
915
+ *
916
+ * @param selection - IDs dos registros selecionados no snapshot atual
917
+ * @param executionCtx - Contexto de execução da seleção dos registros do DataUnit.
918
+ *
919
+ * @returns - Informações sobre a seleção.
920
+ */
921
+ updatePageSelection(selection, executionCtx) {
922
+ if (!selection) {
923
+ return Promise.resolve(this.getSelectionInfo());
924
+ }
925
+ return new Promise(resolve => {
926
+ const newSelection = new Set(getSelection(this._stateManager));
927
+ const currentRecords = getCurrentRecords(this._stateManager) || new Map();
928
+ Array.from(currentRecords.keys()).forEach(recordId => {
929
+ if (selection.includes(recordId)) {
930
+ newSelection.add(recordId);
931
+ }
932
+ else {
933
+ newSelection.delete(recordId);
934
+ }
935
+ });
936
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection: Array.from(newSelection) }, executionCtx)
937
+ .then(() => {
938
+ resolve(this.getSelectionInfo());
939
+ });
940
+ });
941
+ }
942
+ /**
943
+ *
944
+ * Obtém informações sobre a seleção atual.
945
+ *
946
+ * @returns - Objeto com informações como registros selecionados e seleção por critério.
947
+ *
948
+ **/
949
+ getSelectionInfo() {
950
+ return getSelectionInfo(this._stateManager);
951
+ }
952
+ /**
953
+ *
954
+ * Retorna apenas um registro selecionado no Dataunit
955
+ *
956
+ * @returns - Registro selecionado.
957
+ *
958
+ */
959
+ getSelectedRecord() {
960
+ const selection = getSelectionRecords(this._stateManager);
961
+ if (!selection || selection.length == 0)
962
+ return;
963
+ return selection[0];
964
+ }
965
+ /**
966
+ *
967
+ * Limpa todos os registros do DataUnit
968
+ *
969
+ *
970
+ */
971
+ clearDataUnit() {
972
+ this.records = [];
973
+ }
974
+ /**
975
+ *
976
+ * Seleciona o próximo registro.
977
+ *
978
+ * @param executionCtx - Contexto de execução da seleção do registro do DataUnit.
979
+ *
980
+ *
981
+ */
982
+ nextRecord(executionCtx) {
983
+ if (!hasNext(this._stateManager)) {
984
+ if (hasMorePages(this._stateManager)) {
985
+ this.nextPage({
986
+ before: act => {
987
+ if (executionCtx && executionCtx.before) {
988
+ act = executionCtx.before(act);
989
+ }
990
+ return act;
991
+ },
992
+ after: act => {
993
+ this.selectFirst(executionCtx);
994
+ }
995
+ });
996
+ }
997
+ }
998
+ else {
999
+ this.dispatchAction(Action.NEXT_SELECTED, undefined, executionCtx);
1000
+ }
1001
+ }
1002
+ /**
1003
+ *
1004
+ * Seleciona o registro anterior.
1005
+ *
1006
+ * @param executionCtx - Contexto de execução da seleção do registro do DataUnit.
1007
+ *
1008
+ */
1009
+ previousRecord(executionCtx) {
1010
+ if (!hasPrevious(this._stateManager)) {
1011
+ if (hasPreviousPages(this._stateManager)) {
1012
+ this.previousPage({
1013
+ before: act => {
1014
+ if (executionCtx && executionCtx.before) {
1015
+ act = executionCtx.before(act);
1016
+ }
1017
+ return act;
1018
+ },
1019
+ after: act => {
1020
+ this.selectLast(executionCtx);
1021
+ }
1022
+ });
1023
+ }
1024
+ }
1025
+ else {
1026
+ this.dispatchAction(Action.PREVIOUS_SELECTED, undefined, executionCtx);
1027
+ }
1028
+ }
1029
+ /**
1030
+ *
1031
+ * Cancela edição do registro atual.
1032
+ *
1033
+ * @param executionCtx - Contexto de execução do cancelamento da seleção dos registros.
1034
+ * @param silent: Define se haverá mensagem de confirmação do cancelamento
1035
+ *
1036
+ */
1037
+ cancelEdition(executionCtx, fromParent, silent = false) {
1038
+ return __awaiter(this, void 0, void 0, function* () {
1039
+ const cancelledAction = yield this.dispatchAction(Action.EDITION_CANCELED, { fromParent, silent }, executionCtx);
1040
+ for (const [, dataUnit] of this._childByName) {
1041
+ if (dataUnit.isDirty()) {
1042
+ dataUnit.cancelEdition(undefined, true, silent);
1043
+ }
1044
+ }
1045
+ return Promise.resolve(cancelledAction);
1046
+ });
1047
+ }
1048
+ /**
1049
+ *
1050
+ * Retorna se existe algum tipo de alteração pendente.
1051
+ *
1052
+ * @returns Verdadeiro se existir alterações pendentes.
1053
+ *
1054
+ */
1055
+ isDirty() {
1056
+ return isDirty(this._stateManager) || this.childrenIsDirty();
1057
+ }
1058
+ /**
1059
+ *
1060
+ * Retorna se existe algum DataUnit detail com alterações pendentes.
1061
+ *
1062
+ * @returns Verdadeiro se existir alterações pendentes em algum DataUnit detail.
1063
+ *
1064
+ */
1065
+ childrenIsDirty() {
1066
+ for (let [key, dataUnitChild] of this._childByName) {
1067
+ if (dataUnitChild.isDirty())
1068
+ return true;
1069
+ }
1070
+ return false;
1071
+ }
1072
+ /**
1073
+ *
1074
+ * Retorna se existe algum registro em modo de edição.
1075
+ *
1076
+ * @returns Verdadeiro se existir alterações de registros pendentes.
1077
+ *
1078
+ */
1079
+ hasDirtyRecords() {
1080
+ return hasDirtyRecords(this._stateManager);
1081
+ }
1082
+ /**
1083
+ *
1084
+ * Retorna se existir uma pagina seguinte a atual na paginação.
1085
+ *
1086
+ * @returns Verdadeiro se existir uma próxima página.
1087
+ *
1088
+ */
1089
+ hasNext() {
1090
+ let result = hasNext(this._stateManager);
1091
+ if (!result) {
1092
+ result = hasMorePages(this._stateManager);
1093
+ }
1094
+ return result;
1095
+ }
1096
+ /**
1097
+ *
1098
+ * Retorna se existe uma página anterior a atual na paginação.
1099
+ *
1100
+ * @returns Verdadeiro se existir uma página anterior.
1101
+ *
1102
+ */
1103
+ hasPrevious() {
1104
+ let result = hasPrevious(this._stateManager);
1105
+ if (!result) {
1106
+ result = hasPreviousPages(this._stateManager);
1107
+ }
1108
+ return result;
1109
+ }
1110
+ /**
1111
+ *
1112
+ * Verifica se um registro é proveniente de inclusão.
1113
+ *
1114
+ * @param recordId - O id do registro a ser verificado.
1115
+ * @returns Verdadeiro se o id solicitado é de um registro novo.
1116
+ *
1117
+ */
1118
+ isNewRecord(recordId) {
1119
+ const newRecords = getAddedRecords(this._stateManager);
1120
+ if (newRecords && newRecords.length > 0) {
1121
+ const record = newRecords.find(newRecord => newRecord.__record__id__ === recordId);
1122
+ return record != undefined;
1123
+ }
1124
+ return false;
1125
+ }
1126
+ /**
1127
+ *
1128
+ * Retorna se existe pelo menos um registro novo.
1129
+ *
1130
+ * @returns Verdadeiro se algum registro foi adicionado.
1131
+ *
1132
+ */
1133
+ hasNewRecord() {
1134
+ const newRecords = getAddedRecords(this._stateManager);
1135
+ return newRecords && newRecords.length > 0;
1136
+ }
1137
+ /**
1138
+ *
1139
+ * Retorna se existe pelo menos um registro novo.
1140
+ *
1141
+ * @returns Verdadeiro se algum registro foi adicionado.
1142
+ *
1143
+ */
1144
+ hasCopiedRecord() {
1145
+ const newRecords = getAddedRecords(this._stateManager);
1146
+ if (newRecords == undefined) {
1147
+ return false;
1148
+ }
1149
+ for (let record of newRecords) {
1150
+ if (record['__record__source__id__'] != undefined) {
1151
+ return true;
1152
+ }
1153
+ }
1154
+ return false;
1155
+ }
1156
+ /**
1157
+ *
1158
+ * Retorna se a informação do estado anterior está salva, permitindo desfazer a ação.
1159
+ *
1160
+ * @returns Verdadeiro se for possível desfazer a ação.
1161
+ *
1162
+ */
1163
+ canUndo() {
1164
+ return canUndo(this._stateManager);
1165
+ }
1166
+ /**
1167
+ *
1168
+ * Retorna se a informação do estado futuro está salva, permitindo refazer a ação.
1169
+ *
1170
+ * @returns Verdadeiro se for possível refazer a ação.
1171
+ *
1172
+ */
1173
+ canRedo() {
1174
+ return canRedo(this._stateManager);
1175
+ }
1176
+ /**
1177
+ *
1178
+ * Desfaz a última ação.
1179
+ *
1180
+ * @param executionCtx - Contexto de execução de desfazer a última ação.
1181
+ *
1182
+ *
1183
+ */
1184
+ undo(executionCtx) {
1185
+ this.dispatchAction(Action.CHANGE_UNDONE, undefined, executionCtx);
1186
+ }
1187
+ /**
1188
+ *
1189
+ * Refaz a última ação.
1190
+ *
1191
+ * @param executionCtx - Contexto de execução de refazer a última ação.
1192
+ *
1193
+ */
1194
+ redo(executionCtx) {
1195
+ this.dispatchAction(Action.CHANGE_REDONE, undefined, executionCtx);
1196
+ }
1197
+ /**
1198
+ *
1199
+ * Obtém a representação textual do DataUnit, nesse caso, o nome do DataUnit.
1200
+ *
1201
+ * @returns - Valor contido na propriedade name.
1202
+ *
1203
+ */
1204
+ toString() {
1205
+ return this.name;
1206
+ }
1207
+ // Actions / State manager
1208
+ /**
1209
+ *
1210
+ * Lança ação do DataUnit para que sejam processadas.
1211
+ *
1212
+ * @param actionType - Tipo de ação que será executada.
1213
+ * @param payload - Dados que serão processados na ação.
1214
+ * @param executionCtx - Contexto de execução de lançar a ação que será executada.
1215
+ *
1216
+ * @returns - Verdadeiro se ação iniciada.
1217
+ *
1218
+ */
1219
+ dispatchAction(actionType, payload, executionCtx) {
1220
+ return __awaiter(this, void 0, void 0, function* () {
1221
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1222
+ let action = new DataUnitAction(actionType, payload);
1223
+ if (executionCtx && executionCtx.before) {
1224
+ action = executionCtx.before(action);
1225
+ }
1226
+ if (action && this._interceptors && this._interceptors.length > 0) {
1227
+ action = yield this.intercept(action, this._interceptors.values());
1228
+ }
1229
+ if (action) {
1230
+ this.doDispatchAction(action);
1231
+ if (executionCtx && executionCtx.after) {
1232
+ executionCtx.after(action);
1233
+ }
1234
+ resolve(true);
1235
+ }
1236
+ else {
1237
+ resolve(false);
1238
+ }
1239
+ }));
1240
+ });
1241
+ }
1242
+ /**
1243
+ *
1244
+ * Notifica os interceptors de que uma ação foi executada, para que cada interceptor possa fazer sua respectiva tratativa dos dados.
1245
+ *
1246
+ * @param action - Ação que foi executada.
1247
+ * @param interceptors - Interceptors que serão notificados.
1248
+ *
1249
+ * @returns - Ação executada no DataUnit.
1250
+ *
1251
+ */
1252
+ intercept(action, interceptors) {
1253
+ return __awaiter(this, void 0, void 0, function* () {
1254
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1255
+ let ite;
1256
+ while (action && !(ite = interceptors.next()).done) {
1257
+ action = yield ite.value.interceptAction(action);
1258
+ }
1259
+ resolve(action);
1260
+ }));
1261
+ });
1262
+ }
1263
+ /**
1264
+ *
1265
+ * Processa as ações no DataUnit e notifica os observers.
1266
+ *
1267
+ * @param action - Ações em execução no DataUnit.
1268
+ *
1269
+ */
1270
+ doDispatchAction(action) {
1271
+ var _a;
1272
+ this._stateManager.process(action);
1273
+ (_a = this === null || this === void 0 ? void 0 : this._parentDataUnit) === null || _a === void 0 ? void 0 : _a.dispatchAction(Action.CHILD_CHANGED, { srcAction: action, srcDataUnit: this });
1274
+ this._observers.forEach(f => {
1275
+ /*
1276
+ if some observer throws exceptions,
1277
+ should be continued
1278
+ */
1279
+ try {
1280
+ f(action);
1281
+ }
1282
+ catch (e) {
1283
+ console.warn("[DataUnit] error while call observer", e);
1284
+ }
1285
+ });
1286
+ }
1287
+ /**
1288
+ *
1289
+ * Cria um dataunit filho.
1290
+ *
1291
+ * @param name - Nome do dataunit filho.
1292
+ *
1293
+ */
1294
+ getChildDataunit(name) {
1295
+ const detail = new DataUnit(name, this);
1296
+ this._childByName.set(name, detail);
1297
+ return detail;
1298
+ }
1299
+ /**
1300
+ *
1301
+ * Remove um dataunit filho.
1302
+ *
1303
+ * @param name - Nome do dataunit filho.
1304
+ *
1305
+ */
1306
+ removeChildDataunit(name) {
1307
+ this._childByName.delete(name);
1308
+ }
1309
+ /**
1310
+ *
1311
+ * Adiciona um novo observer no DataUnit.
1312
+ * Ela vai ser chamada sempre que uma ação for despachada (dispatchAction()).
1313
+ *
1314
+ * @param observer - Função que recebe como parâmetro as ações que serão monitoradas.
1315
+ *
1316
+ */
1317
+ subscribe(observer) {
1318
+ this._observers.push(observer);
1319
+ }
1320
+ /**
1321
+ *
1322
+ * Remove um observer existente.
1323
+ *
1324
+ * @param observer - Observer que se deseja remover.
1325
+ *
1326
+ */
1327
+ unsubscribe(observer) {
1328
+ this._observers = this._observers.filter(f => f !== observer);
1329
+ }
1330
+ /**
1331
+ *
1332
+ * Recarrega registro selecionado com dados atualizados do servidor.
1333
+ *
1334
+ * @returns - Dados atualizados do registro selecionado.
1335
+ *
1336
+ */
1337
+ reloadCurrentRecord() {
1338
+ return new Promise((resolve, fail) => __awaiter(this, void 0, void 0, function* () {
1339
+ const selection = getSelection(this._stateManager);
1340
+ this.dispatchAction(Action.LOADING_RECORD, selection);
1341
+ if (!this.dataLoader)
1342
+ return;
1343
+ if (!this.recordLoader)
1344
+ return;
1345
+ this.recordLoader(this, selection).then(response => {
1346
+ this.dispatchAction(Action.RECORD_LOADED, response);
1347
+ }).catch(cause => {
1348
+ const { errorCode } = cause;
1349
+ fail(new ErrorException("Erro ao recarregar registro", cause, errorCode));
1350
+ });
1351
+ }));
1352
+ }
1353
+ /**
1354
+ *
1355
+ * Obtém a estrutura de ordenação das colunas dos dados.
1356
+ *
1357
+ * @returns - Lista dos ordenáveis por prioridade.
1358
+ *
1359
+ */
1360
+ getSort() {
1361
+ return this._sortingProvider ? this._sortingProvider.getSort(this._name) : undefined;
1362
+ }
1363
+ /**
1364
+ *
1365
+ * Obtém todos os filtros de dados.
1366
+ *
1367
+ * @returns - Lista de filtros.
1368
+ *
1369
+ */
1370
+ getFilters() {
1371
+ let filters = undefined;
1372
+ this._filterProviders.forEach(p => {
1373
+ const f = p.getFilter(this.name);
1374
+ if (f) {
1375
+ filters = (filters || []).concat(f);
1376
+ }
1377
+ });
1378
+ return filters;
1379
+ }
1380
+ /**
1381
+ *
1382
+ * Obtém as informações da última carga de dados.
1383
+ *
1384
+ * @returns - As informações de filtro e paginação.
1385
+ *
1386
+ */
1387
+ getLastLoadRequest() {
1388
+ return getCurrentRequest(this._stateManager);
1389
+ }
1390
+ /**
1391
+ *
1392
+ * Obtém os filtros aplicados.
1393
+ *
1394
+ * @returns - Lista de filtros.
1395
+ *
1396
+ */
1397
+ getAppliedFilters() {
1398
+ const { filters } = getCurrentRequest(this._stateManager) || {};
1399
+ return filters;
1400
+ }
1401
+ /**
1402
+ *
1403
+ * Habilita um campo do DataUnit
1404
+ * @param fieldName - nome do campo para ser habilitado.
1405
+ *
1406
+ */
1407
+ enableField(fieldName) {
1408
+ const fieldDescriptor = this.getField(fieldName);
1409
+ if ((fieldDescriptor === null || fieldDescriptor === void 0 ? void 0 : fieldDescriptor.readOnly) === true) {
1410
+ fieldDescriptor.readOnly = false;
1411
+ this.metadata = Object.assign({}, this.metadata);
1412
+ }
1413
+ }
1414
+ /**
1415
+ *
1416
+ * Desabilita um campo do DataUnit
1417
+ * @param fieldName - nome do campo para ficar desabilitado.
1418
+ *
1419
+ */
1420
+ disableField(fieldName) {
1421
+ const fieldDescriptor = this.getField(fieldName);
1422
+ if ((fieldDescriptor === null || fieldDescriptor === void 0 ? void 0 : fieldDescriptor.readOnly) === false) {
1423
+ fieldDescriptor.readOnly = true;
1424
+ this.metadata = Object.assign({}, this.metadata);
1425
+ }
1426
+ }
1427
+ /**
1428
+ *
1429
+ * Deixa um campo do DataUnit invisível
1430
+ * @param fieldName - nome do campo para ficar invisível.
1431
+ *
1432
+ */
1433
+ hideField(fieldName) {
1434
+ const fieldDescriptor = this.getField(fieldName);
1435
+ if ((fieldDescriptor === null || fieldDescriptor === void 0 ? void 0 : fieldDescriptor.visible) === true) {
1436
+ fieldDescriptor.visible = false;
1437
+ this.metadata = Object.assign({}, this.metadata);
1438
+ }
1439
+ }
1440
+ /**
1441
+ *
1442
+ * Deixa um campo do DataUnit visível
1443
+ * @param fieldName - nome do campo para ficar visível.
1444
+ *
1445
+ */
1446
+ showField(fieldName) {
1447
+ const fieldDescriptor = this.getField(fieldName);
1448
+ if ((fieldDescriptor === null || fieldDescriptor === void 0 ? void 0 : fieldDescriptor.visible) === false) {
1449
+ fieldDescriptor.visible = true;
1450
+ this.metadata = Object.assign({}, this.metadata);
1451
+ }
1452
+ }
1453
+ /**
1454
+ *
1455
+ * Obtém todos os registros selecionados.
1456
+ *
1457
+ * @returns - Lista de registros selecionados.
1458
+ *
1459
+ * @deprecated - Utilize o método `getSelectionInfo()` para obter os registros selecionados.
1460
+ * Devido a seleção virtual baseada em critérios e ordenação (ALL_RECORDS), esse
1461
+ * método foi descontinuado e pode retornar erros no caso da seleção virtual.
1462
+ *
1463
+ */
1464
+ getSelectedRecords() {
1465
+ console.warn("DataUnit: O método `getSelectedRecords` foi descontinuado. Use o método `getSelectionInfo`.");
1466
+ const selection = this.getSelectionInfo();
1467
+ if (selection != undefined && selection.isAllRecords()) {
1468
+ throw new Error("Erro interno: Impossível retornar os registros selecionados. A seleção atual é virtual. Use o método `getSelectionInfo`.");
1469
+ }
1470
+ if (selection) {
1471
+ return selection.records;
1472
+ }
1473
+ }
1474
+ /**
1475
+ *
1476
+ * Obtém ids dos registros selecionados.
1477
+ *
1478
+ * @returns - Lista com id de todos os registros selecionados.
1479
+ *
1480
+ * @deprecated - Utilize o método `getSelectionInfo()` para obter os registros selecionados.
1481
+ * Devido a seleção virtual baseada em critérios e ordenação (ALL_RECORDS), esse
1482
+ * método foi descontinuado e pode retornar erros no caso da seleção virtual.
1483
+ *
1484
+ */
1485
+ getSelection() {
1486
+ console.warn("DataUnit: O método `getSelection` foi descontinuado. Use o método `getSelectionInfo`.");
1487
+ const selection = this.getSelectionInfo();
1488
+ if (selection != undefined && selection.isAllRecords()) {
1489
+ throw new Error("Erro interno: Impossível retornar os registros selecionados. A seleção atual é virtual. Use o método `getSelectionInfo`.");
1490
+ }
1491
+ return (selection === null || selection === void 0 ? void 0 : selection.recordIds) || [];
1492
+ }
1493
+ /**
1494
+ * Adiciona um locker para impedir o carregamento dos registros do dataUnit.
1495
+ * @returns Retorna uma função responsável por liberar o lock adicionado.
1496
+ */
1497
+ addLoadingLocker() {
1498
+ let loadingLockerResolver;
1499
+ this._loadingLockers.push(new Promise((resolve) => {
1500
+ loadingLockerResolver = resolve;
1501
+ }));
1502
+ return loadingLockerResolver || Promise.resolve;
1503
+ }
1504
+ processLoadingLockers() {
1505
+ return __awaiter(this, void 0, void 0, function* () {
1506
+ if (this._loadingLockers.length) {
1507
+ yield Promise.all(this._loadingLockers);
1508
+ this._loadingLockers = [];
1509
+ }
1510
+ });
1511
+ }
1512
+ }
1513
+ export var ChangeOperation;
1514
+ (function (ChangeOperation) {
1515
+ ChangeOperation["INSERT"] = "INSERT";
1516
+ ChangeOperation["COPY"] = "COPY";
1517
+ ChangeOperation["UPDATE"] = "UPDATE";
1518
+ ChangeOperation["DELETE"] = "DELETE";
1519
+ })(ChangeOperation || (ChangeOperation = {}));
1520
+ /***
1521
+ * `Change`: Dados que representam uma alteração.
1522
+ */
1523
+ export class Change {
1524
+ constructor(dataUnit, record, updates, operation, sourceId) {
1525
+ this.dataUnit = dataUnit;
1526
+ this.record = record;
1527
+ this.sourceId = sourceId;
1528
+ this.updatingFields = updates;
1529
+ this._operation = operation;
1530
+ }
1531
+ /**
1532
+ *
1533
+ * Obtém o tipo de operação que está sendo realizada.
1534
+ *
1535
+ * @returns - Ação que está sendo executada.
1536
+ *
1537
+ */
1538
+ get operation() {
1539
+ return this._operation.toString();
1540
+ }
1541
+ /**
1542
+ *
1543
+ * Retorna se o DataUnit está em uma operação de inserção.
1544
+ *
1545
+ * @returns - Verdadeiro se a operação for de inserção.
1546
+ *
1547
+ */
1548
+ isInsert() {
1549
+ return this._operation === ChangeOperation.INSERT;
1550
+ }
1551
+ /**
1552
+ *
1553
+ * Retorna se o DataUnit está em uma operação de cópia.
1554
+ *
1555
+ * @returns - Verdadeiro se a operação for de cópia.
1556
+ *
1557
+ */
1558
+ isCopy() {
1559
+ return this._operation === ChangeOperation.COPY;
1560
+ }
1561
+ /**
1562
+ *
1563
+ * Retorna se o DataUnit está em uma operação de deleção.
1564
+ *
1565
+ * @returns - Verdadeiro se a operação for de deleção.
1566
+ *
1567
+ */
1568
+ isDelete() {
1569
+ return this._operation === ChangeOperation.DELETE;
1570
+ }
1571
+ /**
1572
+ *
1573
+ * Retorna se o DataUnit está em uma operação de atualização.
1574
+ *
1575
+ * @returns - Verdadeiro se a operação for de atualização.
1576
+ *
1577
+ */
1578
+ isUpdate() {
1579
+ return this._operation === ChangeOperation.UPDATE;
1580
+ }
1581
+ }
1582
+ export var SelectionMode;
1583
+ (function (SelectionMode) {
1584
+ SelectionMode["ALL_RECORDS"] = "ALL_RECORDS";
1585
+ SelectionMode["SOME_RECORDS"] = "SOME_RECORDS";
1586
+ })(SelectionMode || (SelectionMode = {}));
1587
+ export class SelectionInfo {
1588
+ constructor(records, mode = SelectionMode.SOME_RECORDS, total, filters, sort) {
1589
+ this._records = records;
1590
+ this._total = total;
1591
+ this.mode = mode;
1592
+ this.filters = filters;
1593
+ this.sort = sort;
1594
+ }
1595
+ get records() {
1596
+ if (this.isAllRecords()) {
1597
+ throw new Error("Erro interno: [ALL_RECORDS] - Impossível retornar os registros selecionados numa seleção virtual.");
1598
+ }
1599
+ return this._records;
1600
+ }
1601
+ get recordIds() {
1602
+ const records = this.records;
1603
+ if (records == undefined) {
1604
+ return undefined;
1605
+ }
1606
+ return records.map(record => record.__record__id__);
1607
+ }
1608
+ get length() {
1609
+ if (this.isAllRecords()) {
1610
+ return this._total || 0;
1611
+ }
1612
+ return this.records == undefined ? 0 : this.records.length;
1613
+ }
1614
+ isAllRecords() {
1615
+ return this.mode === SelectionMode.ALL_RECORDS;
1616
+ }
1617
+ isEmpty() {
1618
+ return this.length === 0;
1619
+ }
1620
+ }
1621
+ //# sourceMappingURL=DataUnit.js.map