@sankhyalabs/sankhyablocks 1.3.31-beta.2 → 1.3.31-beta.20

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 (218) hide show
  1. package/dist/cjs/SnkMessageBuilder-7717f1e4.js +326 -0
  2. package/dist/cjs/app-globals-3a1e7e63.js +5 -0
  3. package/dist/cjs/css-shim-b8158822.js +6 -0
  4. package/dist/cjs/dom-36862b77.js +75 -0
  5. package/dist/cjs/filter-item-type.enum-e2e1bc5b.js +14 -0
  6. package/dist/cjs/index-02201bc9.js +2397 -0
  7. package/dist/cjs/index-b0b676c5.js +3298 -0
  8. package/dist/cjs/loader.cjs.js +19 -3
  9. package/dist/cjs/sankhyablocks.cjs.js +117 -5
  10. package/dist/cjs/shadow-css-346c0795.js +389 -0
  11. package/dist/cjs/snk-application.cjs.entry.js +1041 -177
  12. package/dist/cjs/snk-crud.cjs.entry.js +65 -0
  13. package/dist/cjs/snk-data-unit.cjs.entry.js +276 -0
  14. package/dist/cjs/snk-filter-bar.cjs.entry.js +265 -0
  15. package/dist/cjs/snk-filter-binary-select.cjs.entry.js +47 -0
  16. package/dist/cjs/snk-filter-detail.cjs.entry.js +49 -0
  17. package/dist/cjs/snk-filter-item.cjs.entry.js +143 -0
  18. package/dist/cjs/snk-filter-list.cjs.entry.js +91 -0
  19. package/dist/cjs/snk-filter-multi-select.cjs.entry.js +23 -0
  20. package/dist/cjs/snk-filter-number.cjs.entry.js +24 -0
  21. package/dist/cjs/snk-filter-period.cjs.entry.js +26 -0
  22. package/dist/cjs/snk-filter-search.cjs.entry.js +44 -0
  23. package/dist/cjs/snk-filter-text.cjs.entry.js +22 -0
  24. package/dist/cjs/snk-form.cjs.entry.js +133 -0
  25. package/dist/cjs/snk-grid.cjs.entry.js +79 -0
  26. package/dist/cjs/snk-pesquisa.cjs.entry.js +10 -7
  27. package/dist/cjs/snk-taskbar.cjs.entry.js +160 -0
  28. package/dist/cjs/taskbar-elements-283c737e.js +93 -0
  29. package/dist/cjs/taskbar-processor-6bd0d35c.js +47 -0
  30. package/dist/cjs/teste-pesquisa.cjs.entry.js +5 -5
  31. package/dist/collection/collection-manifest.json +17 -2
  32. package/dist/collection/components/snk-application/errorhandler/snk-error-handler.js +9 -2
  33. package/dist/collection/components/snk-application/snk-application.js +1061 -629
  34. package/dist/collection/components/snk-crud/snk-crud.css +6 -0
  35. package/dist/collection/components/snk-crud/snk-crud.js +176 -0
  36. package/dist/collection/components/snk-data-unit/snk-data-unit.css +6 -0
  37. package/dist/collection/components/snk-data-unit/snk-data-unit.js +540 -0
  38. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-binary-select.js +88 -0
  39. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-multi-select.js +64 -0
  40. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-number.js +65 -0
  41. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-period.js +69 -0
  42. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-search.js +118 -0
  43. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-text.js +63 -0
  44. package/dist/collection/components/snk-filter-bar/filter-item/filter-item-type.enum.js +10 -0
  45. package/dist/collection/components/snk-filter-bar/filter-item/snk-filter-detail.js +118 -0
  46. package/dist/collection/components/snk-filter-bar/filter-item/snk-filter-item.js +244 -0
  47. package/dist/collection/components/snk-filter-bar/filter-list/snk-filter-list.js +233 -0
  48. package/dist/collection/components/snk-filter-bar/snk-filter-bar.css +114 -0
  49. package/dist/collection/components/snk-filter-bar/snk-filter-bar.js +323 -0
  50. package/dist/collection/components/snk-form/snk-form.css +34 -0
  51. package/dist/collection/components/snk-form/snk-form.js +258 -0
  52. package/dist/collection/components/snk-grid/snk-grid.css +18 -0
  53. package/dist/collection/components/snk-grid/snk-grid.js +183 -0
  54. package/dist/collection/components/snk-pesquisa/snk-pesquisa.css +56 -13
  55. package/dist/collection/components/snk-pesquisa/snk-pesquisa.js +81 -76
  56. package/dist/collection/components/snk-taskbar/elements/taskbar-elements.js +86 -0
  57. package/dist/collection/components/snk-taskbar/processor/taskbar-processor.js +43 -0
  58. package/dist/collection/components/snk-taskbar/snk-taskbar.css +3 -0
  59. package/dist/collection/components/snk-taskbar/snk-taskbar.js +307 -0
  60. package/dist/collection/components/teste-pesquisa/teste-pesquisa.js +12 -9
  61. package/dist/collection/lib/http/data-fetcher/DataFetcher.js +38 -13
  62. package/dist/collection/lib/http/data-fetcher/fetchers/dataunit-fetcher.js +52 -21
  63. package/dist/collection/lib/http/data-fetcher/fetchers/filter-bar-config-fetcher.js +388 -0
  64. package/dist/collection/lib/http/data-fetcher/fetchers/grid-config-fetcher.js +4 -3
  65. package/dist/collection/lib/http/data-fetcher/fetchers/pesquisa-fetcher.js +2 -0
  66. package/dist/collection/lib/http/data-fetcher/fetchers/totals-fetcher.js +47 -0
  67. package/dist/collection/lib/index.js +1 -0
  68. package/dist/collection/lib/message/SnkMessageBuilder.js +121 -0
  69. package/dist/collection/lib/message/resources/snk-data-unit.msg.js +23 -0
  70. package/dist/collection/lib/message/resources/snk-filter-bar.msg.js +18 -0
  71. package/dist/collection/lib/message/resources/snk-form.msg.js +10 -0
  72. package/dist/collection/lib/message/resources/snk-taskbar.msg.js +17 -0
  73. package/dist/components/SnkMessageBuilder.js +303 -0
  74. package/dist/components/filter-item-type.enum.js +12 -0
  75. package/dist/components/index.d.ts +18 -5
  76. package/dist/components/index.js +22 -0
  77. package/dist/components/index2.js +2384 -0
  78. package/dist/components/snk-application2.js +1019 -148
  79. package/dist/components/snk-crud.d.ts +11 -0
  80. package/dist/components/snk-crud.js +127 -0
  81. package/dist/components/snk-data-unit.d.ts +11 -0
  82. package/dist/components/snk-data-unit.js +299 -0
  83. package/dist/components/snk-filter-bar.d.ts +11 -0
  84. package/dist/components/snk-filter-bar.js +6 -0
  85. package/dist/components/snk-filter-bar2.js +296 -0
  86. package/dist/components/snk-filter-binary-select.d.ts +11 -0
  87. package/dist/components/snk-filter-binary-select.js +63 -0
  88. package/dist/components/snk-filter-detail.d.ts +11 -0
  89. package/dist/components/snk-filter-detail.js +6 -0
  90. package/dist/components/snk-filter-detail2.js +63 -0
  91. package/dist/components/snk-filter-item.d.ts +11 -0
  92. package/dist/components/snk-filter-item.js +6 -0
  93. package/dist/components/snk-filter-item2.js +164 -0
  94. package/dist/components/snk-filter-list.d.ts +11 -0
  95. package/dist/components/snk-filter-list.js +6 -0
  96. package/dist/components/snk-filter-list2.js +111 -0
  97. package/dist/components/snk-filter-multi-select.d.ts +11 -0
  98. package/dist/components/snk-filter-multi-select.js +39 -0
  99. package/dist/components/snk-filter-number.d.ts +11 -0
  100. package/dist/components/snk-filter-number.js +40 -0
  101. package/dist/components/snk-filter-period.d.ts +11 -0
  102. package/dist/components/snk-filter-period.js +42 -0
  103. package/dist/components/snk-filter-search.d.ts +11 -0
  104. package/dist/components/snk-filter-search.js +62 -0
  105. package/dist/components/snk-filter-text.d.ts +11 -0
  106. package/dist/components/snk-filter-text.js +38 -0
  107. package/dist/components/snk-form.d.ts +11 -0
  108. package/dist/components/snk-form.js +6 -0
  109. package/dist/components/snk-form2.js +159 -0
  110. package/dist/components/snk-grid.d.ts +11 -0
  111. package/dist/components/snk-grid.js +6 -0
  112. package/dist/components/snk-grid2.js +126 -0
  113. package/dist/components/snk-pesquisa2.js +6 -3
  114. package/dist/components/snk-taskbar.d.ts +11 -0
  115. package/dist/components/snk-taskbar.js +6 -0
  116. package/dist/components/snk-taskbar2.js +264 -0
  117. package/dist/components/taskbar-processor.js +45 -0
  118. package/dist/components/teste-pesquisa.js +1 -1
  119. package/dist/esm/SnkMessageBuilder-a7da466b.js +303 -0
  120. package/dist/esm/app-globals-0f993ce5.js +3 -0
  121. package/dist/esm/css-shim-b3f2ee8d.js +4 -0
  122. package/dist/esm/dom-665d6011.js +73 -0
  123. package/dist/esm/filter-item-type.enum-61fbf80a.js +12 -0
  124. package/dist/esm/index-2b4d2d14.js +3262 -0
  125. package/dist/esm/index-e5b61043.js +2384 -0
  126. package/dist/esm/loader.js +19 -3
  127. package/dist/esm/polyfills/css-shim.js +1 -1
  128. package/dist/esm/sankhyablocks.js +117 -5
  129. package/dist/esm/shadow-css-b18e99d7.js +387 -0
  130. package/dist/esm/snk-application.entry.js +1013 -149
  131. package/dist/esm/snk-crud.entry.js +61 -0
  132. package/dist/esm/snk-data-unit.entry.js +272 -0
  133. package/dist/esm/snk-filter-bar.entry.js +261 -0
  134. package/dist/esm/snk-filter-binary-select.entry.js +43 -0
  135. package/dist/esm/snk-filter-detail.entry.js +45 -0
  136. package/dist/esm/snk-filter-item.entry.js +139 -0
  137. package/dist/esm/snk-filter-list.entry.js +87 -0
  138. package/dist/esm/snk-filter-multi-select.entry.js +19 -0
  139. package/dist/esm/snk-filter-number.entry.js +20 -0
  140. package/dist/esm/snk-filter-period.entry.js +22 -0
  141. package/dist/esm/snk-filter-search.entry.js +40 -0
  142. package/dist/esm/snk-filter-text.entry.js +18 -0
  143. package/dist/esm/snk-form.entry.js +129 -0
  144. package/dist/esm/snk-grid.entry.js +75 -0
  145. package/dist/esm/snk-pesquisa.entry.js +7 -4
  146. package/dist/esm/snk-taskbar.entry.js +156 -0
  147. package/dist/esm/taskbar-elements-35d64ff9.js +90 -0
  148. package/dist/esm/taskbar-processor-aa6772c9.js +45 -0
  149. package/dist/esm/teste-pesquisa.entry.js +2 -2
  150. package/dist/sankhyablocks/SnkMessageBuilder-a7da466b.js +303 -0
  151. package/dist/sankhyablocks/app-globals-0f993ce5.js +3 -0
  152. package/dist/sankhyablocks/css-shim-b3f2ee8d.js +4 -0
  153. package/dist/sankhyablocks/dom-665d6011.js +73 -0
  154. package/dist/sankhyablocks/filter-item-type.enum-61fbf80a.js +12 -0
  155. package/dist/sankhyablocks/index-2b4d2d14.js +3262 -0
  156. package/dist/sankhyablocks/index-e5b61043.js +2384 -0
  157. package/dist/sankhyablocks/index.esm.js +1 -0
  158. package/dist/sankhyablocks/sankhyablocks.esm.js +129 -1
  159. package/dist/sankhyablocks/shadow-css-b18e99d7.js +387 -0
  160. package/dist/sankhyablocks/snk-application.entry.js +8452 -0
  161. package/dist/sankhyablocks/snk-crud.entry.js +61 -0
  162. package/dist/sankhyablocks/snk-data-unit.entry.js +272 -0
  163. package/dist/sankhyablocks/snk-filter-bar.entry.js +261 -0
  164. package/dist/sankhyablocks/snk-filter-binary-select.entry.js +43 -0
  165. package/dist/sankhyablocks/snk-filter-detail.entry.js +45 -0
  166. package/dist/sankhyablocks/snk-filter-item.entry.js +139 -0
  167. package/dist/sankhyablocks/snk-filter-list.entry.js +87 -0
  168. package/dist/sankhyablocks/snk-filter-multi-select.entry.js +19 -0
  169. package/dist/sankhyablocks/snk-filter-number.entry.js +20 -0
  170. package/dist/sankhyablocks/snk-filter-period.entry.js +22 -0
  171. package/dist/sankhyablocks/snk-filter-search.entry.js +40 -0
  172. package/dist/sankhyablocks/snk-filter-text.entry.js +18 -0
  173. package/dist/sankhyablocks/snk-form.entry.js +129 -0
  174. package/dist/sankhyablocks/snk-grid.entry.js +75 -0
  175. package/dist/sankhyablocks/snk-pesquisa.entry.js +311 -0
  176. package/dist/sankhyablocks/snk-taskbar.entry.js +156 -0
  177. package/dist/sankhyablocks/taskbar-elements-35d64ff9.js +90 -0
  178. package/dist/sankhyablocks/taskbar-processor-aa6772c9.js +45 -0
  179. package/dist/sankhyablocks/teste-pesquisa.entry.js +33 -0
  180. package/dist/types/components/snk-application/errorhandler/snk-error-handler.d.ts +1 -0
  181. package/dist/types/components/snk-application/snk-application.d.ts +141 -20
  182. package/dist/types/components/snk-filter-bar/filter-item/editors/snk-filter-binary-select.d.ts +12 -0
  183. package/dist/types/components/snk-filter-bar/filter-item/editors/snk-filter-multi-select.d.ts +7 -0
  184. package/dist/types/components/snk-filter-bar/filter-item/editors/snk-filter-number.d.ts +7 -0
  185. package/dist/types/components/snk-filter-bar/filter-item/editors/snk-filter-period.d.ts +13 -0
  186. package/dist/types/components/snk-filter-bar/filter-item/editors/snk-filter-search.d.ts +12 -0
  187. package/dist/types/components/snk-filter-bar/filter-item/editors/snk-filter-text.d.ts +7 -0
  188. package/dist/types/components/snk-filter-bar/filter-item/filter-item-type.enum.d.ts +9 -0
  189. package/dist/types/components/snk-filter-bar/filter-item/snk-filter-detail.d.ts +14 -0
  190. package/dist/types/components/snk-filter-bar/filter-list/snk-filter-list.d.ts +40 -0
  191. package/dist/types/components/snk-filter-bar/snk-filter-bar.d.ts +46 -0
  192. package/dist/types/components/snk-taskbar/elements/taskbar-elements.d.ts +29 -0
  193. package/dist/types/components/snk-taskbar/processor/taskbar-processor.d.ts +12 -0
  194. package/dist/types/components/snk-taskbar/snk-taskbar.d.ts +84 -0
  195. package/dist/types/components.d.ts +662 -9
  196. package/dist/types/lib/http/data-fetcher/DataFetcher.d.ts +7 -6
  197. package/dist/types/lib/http/data-fetcher/fetchers/dataunit-fetcher.d.ts +2 -0
  198. package/dist/types/lib/http/data-fetcher/fetchers/filter-bar-config-fetcher.d.ts +5 -0
  199. package/dist/types/lib/http/data-fetcher/fetchers/grid-config-fetcher.d.ts +3 -3
  200. package/dist/types/lib/http/data-fetcher/fetchers/totals-fetcher.d.ts +8 -0
  201. package/dist/types/lib/index.d.ts +1 -0
  202. package/dist/types/lib/message/SnkMessageBuilder.d.ts +42 -0
  203. package/dist/types/lib/message/resources/snk-data-unit.msg.d.ts +2 -0
  204. package/dist/types/lib/message/resources/snk-filter-bar.msg.d.ts +2 -0
  205. package/dist/types/lib/message/resources/snk-form.msg.d.ts +2 -0
  206. package/dist/types/lib/message/resources/snk-taskbar.msg.d.ts +2 -0
  207. package/dist/types/stencil-public-runtime.d.ts +15 -4
  208. package/loader/package.json +1 -0
  209. package/package.json +5 -5
  210. package/react/components.d.ts +0 -2
  211. package/react/components.js +0 -2
  212. package/react/components.js.map +1 -1
  213. package/dist/cjs/index-1133bc2a.js +0 -1235
  214. package/dist/esm/index-ffda6382.js +0 -1208
  215. package/dist/sankhyablocks/p-2a7b4cb3.entry.js +0 -1
  216. package/dist/sankhyablocks/p-d62412bb.entry.js +0 -1
  217. package/dist/sankhyablocks/p-e6e91d5f.entry.js +0 -69
  218. package/dist/sankhyablocks/p-edcb9d8e.js +0 -2
@@ -0,0 +1,2384 @@
1
+ /**
2
+ * Classe com utiliários comuns para Strings.
3
+ */
4
+ class StringUtils {
5
+ /**
6
+ * Verifica se a string está vazia.
7
+ * Valores null e undefined são considerados como vazio.
8
+ *
9
+ * @param value String para ser validada.
10
+ */
11
+ static isEmpty(value) {
12
+ if (value == undefined || value === null) {
13
+ return true;
14
+ }
15
+ value = value.toString();
16
+ value = value.trim();
17
+ if (value.length === 0) {
18
+ return true;
19
+ }
20
+ return false;
21
+ }
22
+ /**
23
+ * Remove acentos de vogais, substitui Ç por c e retorna a string em caixa alta.
24
+ *
25
+ * @param value String para ser transformada.
26
+ */
27
+ static replaceAccentuatedChars(text) {
28
+ text = text.toUpperCase();
29
+ text = text.replace(/[À]/, "A");
30
+ text = text.replace(/[Á]/, "A");
31
+ text = text.replace(/[Â]/, "A");
32
+ text = text.replace(/[Ã]/, "A");
33
+ text = text.replace(/[Ä]/, "A");
34
+ text = text.replace(/[È]/, "E");
35
+ text = text.replace(/[É]/, "E");
36
+ text = text.replace(/[Ê]/, "E");
37
+ text = text.replace(/[Ë]/, "E");
38
+ text = text.replace(/[Ì]/, "I");
39
+ text = text.replace(/[Í]/, "I");
40
+ text = text.replace(/[Î]/, "I");
41
+ text = text.replace(/[Ï]/, "I");
42
+ text = text.replace(/[Ò]/, "O");
43
+ text = text.replace(/[Ó]/, "O");
44
+ text = text.replace(/[Ô]/, "O");
45
+ text = text.replace(/[Ö]/, "O");
46
+ text = text.replace(/[Ù]/, "U");
47
+ text = text.replace(/[Ú]/, "U");
48
+ text = text.replace(/[Û]/, "U");
49
+ text = text.replace(/[Ü]/, "U");
50
+ text = text.replace(/[Ç]/, "C");
51
+ return text.replace(/[^a-z0-9]/gi, "");
52
+ }
53
+ /**
54
+ * Remove acentos de vogais, substitui Ç por c e retorna a string em caixa alta mantendo espaços e símbolos.
55
+ * @param text String para ser transformada.
56
+ */
57
+ static replaceAccentuatedCharsKeepSymbols(text) {
58
+ return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toUpperCase();
59
+ }
60
+ /**
61
+ * Calcula um código hash para uma string.
62
+ * @param value String que será gerado o hash code.
63
+ */
64
+ static hashCode(value) {
65
+ let hash = 0, i, chr;
66
+ if (value.length === 0)
67
+ return hash.toString();
68
+ for (i = 0; i < value.length; i++) {
69
+ chr = value.charCodeAt(i);
70
+ hash = ((hash << 5) - hash) + chr;
71
+ hash |= 0; // Convert to 32bit integer
72
+ }
73
+ return hash.toString();
74
+ }
75
+ /**
76
+ * Converte um valor em string para booleano
77
+ * @param value Valor a ser convertido
78
+ * @param defaultValue Será retornado esse caso seja passado valores diferentes do esperado(true, false, "true", "false", "S", "N")
79
+ */
80
+ static getBooleanValue(value, defaultValue = false) {
81
+ if ([true, "true", "S"].includes(value)) {
82
+ return true;
83
+ }
84
+ else if ([false, "false", "N"].includes(value)) {
85
+ return false;
86
+ }
87
+ else {
88
+ return defaultValue;
89
+ }
90
+ }
91
+ static padStart(str, len, pad = " ") {
92
+ str = str != undefined ? str : "";
93
+ while (str.length < len) {
94
+ str = pad + str;
95
+ }
96
+ return str;
97
+ }
98
+ static padEnd(str, len, pad = " ") {
99
+ str = str != undefined ? str : "";
100
+ while (str.length < len) {
101
+ str = str + pad;
102
+ }
103
+ return str;
104
+ }
105
+ /**
106
+ * Utilitário para determinar a ordem de strings. Geralmente usado no método "sort" de um array.
107
+ * Retorna um número negativo se o primeiro argumento é menor que o segundo, zero se os dois são iguais
108
+ * e um número positivo quando o primeiro é maior que o segundo.if they're equal, and a positive value otherwise.
109
+ * @param a - Primeira string para comparação
110
+ * @param b - Segunda string para comparação
111
+ * @returns Um valor maior, menor ou igual a zero para determinar se a ordem precisa ser alterada.
112
+ */
113
+ static compare(a, b) {
114
+ if (a === undefined) {
115
+ return b === undefined ? 0 : 1;
116
+ }
117
+ else if (b === undefined) {
118
+ return -1;
119
+ }
120
+ if (a === null) {
121
+ return b === null ? 0 : 1;
122
+ }
123
+ else if (b === null) {
124
+ return -1;
125
+ }
126
+ return a.localeCompare(b);
127
+ }
128
+ }
129
+
130
+ const NUMBERINPUTS_REGEX_SCIENTIFIC_PARTS = /^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/;
131
+ /**
132
+ * `NumberUtils` é uma biblioteca para manipulação de números
133
+ *
134
+ * `Métodos`:
135
+ *
136
+ * @stringToNumber: converte um número em formato de string em um valor numérico nativo do javascript
137
+ * @format: arredonda um número em formato de string baseado nos parâmetros "presision" e "prettyPrecision";
138
+ */
139
+ class NumberUtils {
140
+ }
141
+ /**
142
+ * @stringToNumber: converte um numero em formato de string em numero
143
+ *
144
+ * @param value numero em formato de string a ser convertido (Importante: formato PT-BR ou já em formato numérico: ######.##)
145
+ *
146
+ * @returns string based number
147
+ *
148
+ * @Exemples
149
+ * @"100,12" | 100.12
150
+ * @"100.12" | 100.12
151
+ * @"-100,12" | -100.12
152
+ * @"R$100,12" | 100.12
153
+ * @"-R$100,12" | -100.12
154
+ * @"string" | NaN
155
+ */
156
+ NumberUtils.stringToNumber = (value) => {
157
+ if (value === '' || value === null || value === undefined) {
158
+ return NaN;
159
+ }
160
+ if (value) {
161
+ value = value.toString();
162
+ const negative = (value.charAt(0) === '-');
163
+ if (!NUMBERINPUTS_REGEX_SCIENTIFIC_PARTS.test(value)) {
164
+ value = value.replace(/[^\d.,]/g, '');
165
+ }
166
+ else {
167
+ value = value.replace(/^-/g, '');
168
+ }
169
+ //In case of simple string such as: "@@@@@@@"
170
+ if (value === '') {
171
+ return Number(NaN);
172
+ }
173
+ const indexV = value.indexOf(',');
174
+ const indexP = value.indexOf('.');
175
+ if (indexP > indexV) {
176
+ value = value.replace(',', '');
177
+ }
178
+ else if (indexP < indexV) {
179
+ value = value.replace(/\./g, '@').replace(',', '.').replace(/@/g, '');
180
+ }
181
+ if (negative) {
182
+ value = '-' + value;
183
+ }
184
+ }
185
+ return Number(value);
186
+ };
187
+ /**
188
+ * @format: converte um numero em formato de string em um numero em formato de string formatado de acordo com os parametros de "precision" e "prettyPrecision"
189
+ *
190
+ * @param value numero em formato de string a ser convertido (Importante: formato PT-BR ou já em formato numérico<sem separadors de milhares>: ######.##)
191
+ * @param precision (numero de decimais)
192
+ * @param prettyPrecision (numero de zeros nos decimais)
193
+ *
194
+ * @returns numero em formato de string formatado em PT-BR
195
+ */
196
+ NumberUtils.format = (value, precision, prettyPrecision = NaN) => {
197
+ if (value === '' || value === undefined || value === "NaN") {
198
+ return NaN.toString();
199
+ }
200
+ const newValue = NumberUtils.stringToNumber(value);
201
+ if (isNaN(newValue)) {
202
+ return NaN.toString();
203
+ }
204
+ //Validation "precision":
205
+ // Case1: precision < 0 => does not use precision
206
+ // Case2: presicion not int => does not use precision
207
+ if (precision < 0 || Math.abs(Math.round(precision * 1) / 1) !== precision) {
208
+ //Once stringToNumber returns number format, we need to change to pt-br
209
+ return NumberUtils.changeFormat(newValue.toString());
210
+ }
211
+ //Validation "prettyPrecision"
212
+ let prettyPrecisionInternal = 0;
213
+ // Case1: prettyPrecision < 0 => prettyPrecision does not change de format that means: prettyPrecisionInternal = precision;
214
+ // Case2: prettyPrecision not int => prettyPrecision does not change de format that means: prettyPrecisionInternal = precision;
215
+ if (isNaN(prettyPrecision) || Math.abs(Math.round(prettyPrecision * 1) / 1) !== prettyPrecision) {
216
+ prettyPrecisionInternal = precision;
217
+ }
218
+ else {
219
+ prettyPrecisionInternal = prettyPrecision;
220
+ }
221
+ let newValueStr;
222
+ newValueStr = (Math.round(newValue * Math.pow(10, precision)) / Math.pow(10, precision)).toLocaleString('pt-br', { minimumFractionDigits: precision });
223
+ //prettyPrecision
224
+ const varSettingPP = precision - prettyPrecisionInternal;
225
+ if (varSettingPP > 0) {
226
+ for (let i = 0; i < varSettingPP; i++) {
227
+ if (newValueStr.substring(newValueStr.length - 1) == "0" && precision > 0) {
228
+ newValueStr = newValueStr.substring(0, newValueStr.length - 1);
229
+ }
230
+ }
231
+ }
232
+ //in Case "." or "," in the end of the string
233
+ if (newValueStr.substring(newValueStr.length - 1) == "." || newValueStr.substring(newValueStr.length - 1) == ",") {
234
+ newValueStr = newValueStr.substring(0, newValueStr.length - 1);
235
+ }
236
+ return newValueStr;
237
+ };
238
+ /**
239
+ * @keepOnlyDecimalSeparator: retira os separadores de milhar de um número em formato de string
240
+ *
241
+ * @param value numero em formato de string a ser convertido
242
+ * @param formatnumber (formatação de ENTRADA e SAÍDA do utilitário: pt-BR="###.###,##" en-US="###,###.##"; Default: "pt-BR")
243
+ *
244
+ * @returns numero em formato de string formatado apenas com separador decimal
245
+ */
246
+ NumberUtils.keepOnlyDecimalSeparator = (value, formatnumber = 'pt-BR') => {
247
+ //Formatting formatnumber to be able to get lowercases
248
+ formatnumber = formatnumber.toUpperCase();
249
+ //Formatting value following formatnumber parameter
250
+ //keep only decimal character in order to correct format the string
251
+ //This transformation is due the "stringtoNumber" method is a general method that tries to convert all formated strings
252
+ if (formatnumber === 'EN-US') {
253
+ value = value.replace(/\,/g, '');
254
+ }
255
+ else {
256
+ value = value.replace(/\./g, '');
257
+ }
258
+ return value;
259
+ };
260
+ /**
261
+ * @changeFormat: troca o formato do numero string de "PT-BR" para "EN-US" e vice-versa
262
+ *
263
+ * @param value numero em formato de string a ser convertido
264
+ *
265
+ * @returns numero em formato de string formatado de "PT-BR" para "EN-US" e vice-versa
266
+ */
267
+ NumberUtils.changeFormat = (value) => {
268
+ //Formatting output following formatnumber
269
+ return value.replace(/\./g, '_').replace(/\,/g, '.').replace(/\_/g, ',');
270
+ };
271
+
272
+ /**
273
+ * `MaskFormatter` é usado para formatar strings. Seu comportamento
274
+ * é controlado pela formato do atributo `mask` que especifica quais
275
+ * caracteres são válidos e onde devem estar posicionados, intercalando-os
276
+ * com eventuais caracteres literais expressados no padrão informado.
277
+ * Sua implementação é inspirada pela implementação em Java do [MaskFormatter](https://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html).
278
+ *
279
+ * Para o padrão da máscara podem ser usados os seguintes caracteres especiais:
280
+ *
281
+ * | Caractere | Comportamento |
282
+ * |:---------:|-------------------------------------------------------------------------------------------------------------|
283
+ * | # | Qualquer número |
284
+ * | ' | "Escapa" o caractere que vem na sequência. Útil quando desejamos converter um caractere especial em literal.|
285
+ * | U | Qualquer letra. Transforma letras maiúsculas em maiúsculas. |
286
+ * | L | Qualquer letra. Transforma letras maiúsculas em minúsculas. |
287
+ * | A | Qualquer letra ou número. |
288
+ * | ? | Qualquer letra. Preserva maiúsculas e minúsculas. |
289
+ * | * | Qualquer caractere. |
290
+ *
291
+ * Os demais caracteres presentes no padrão serão tratados como literais, isto é,
292
+ * serão apenas inseridos naquela posição.
293
+ *
294
+ * Quando o o valor a ser formatado é menor que a máscara um 'placeHolder'
295
+ * será inserido em cada posição ausente, completando a formatação.
296
+ * Por padrão será usado um espaço em branco como 'placeHolder' mas
297
+ * esse valor pode ser alterado.
298
+ *
299
+ * For por exemplo:
300
+ * '''
301
+ * const formatter: MaskFormatter = new MaskFormatter("###-####");
302
+ * formatter.placeholder = '_';
303
+ * console.log(formatter.format("123"));
304
+ * '''
305
+ * resultaria na string '123-____'.
306
+ *
307
+ * ##Veja mais alguns exemplos:
308
+ * |Padrão |Máscara |Entrada |Saída |
309
+ * |----------------|------------------|--------------|------------------|
310
+ * |Telefone |(##) ####-#### |3432192515 |(34) 3219-2515 |
311
+ * |CPF |###.###.###-## |12345678901 |123.456.789-01 |
312
+ * |CNPJ |##.###.###/####-##|12345678901234|12.345.678/9012-34|
313
+ * |CEP |##.###-### |12345678 |12.345-678 |
314
+ * |PLACA (veículo) |UUU-#### |abc1234 |ABC-1234 |
315
+ * |Cor RGB |'#AAAAAA |00000F0 |#0000F0 |
316
+ *
317
+ */
318
+ class MaskFormatter {
319
+ constructor(mask) {
320
+ this._mask = '';
321
+ this._maskChars = new Array();
322
+ /**
323
+ * Determina qual caractere será usado dos caracteres não presentes no valor
324
+ * ou seja, aqueles que o usuário ainda não informou. Por padrão usamos um espaço
325
+ */
326
+ this.placeholder = ' ';
327
+ this.mask = mask;
328
+ }
329
+ /**
330
+ * Setter para mask. Trata-se do padrão que se espera ao formatar o texto.
331
+ */
332
+ set mask(mask) {
333
+ this._mask = mask;
334
+ this.updateInternalMask();
335
+ }
336
+ /**
337
+ * Getter para mask
338
+ *
339
+ * @return A última máscara informada.
340
+ */
341
+ get mask() {
342
+ return this._mask;
343
+ }
344
+ /**
345
+ * Formata a string passada baseada na máscara definda pelo atributo mask.
346
+ *
347
+ * @param value Valor a ser formatado
348
+ * @return O valor processado de acordo com o padrão
349
+ */
350
+ format(value) {
351
+ let result = '';
352
+ const index = [0];
353
+ let counter = 0;
354
+ const maxCounter = this._maskChars.length;
355
+ while (counter < maxCounter) {
356
+ result = this._maskChars[counter].append(result, value, index);
357
+ counter++;
358
+ }
359
+ return result;
360
+ }
361
+ /**
362
+ * Preparamos a formatação internamente de acordo com o padrão.
363
+ */
364
+ updateInternalMask() {
365
+ this._maskChars.length = 0;
366
+ if (this.mask != null) {
367
+ let counter = 0;
368
+ const maxCounter = this.mask.length;
369
+ while (counter < maxCounter) {
370
+ let maskChar = this.mask.charAt(counter);
371
+ switch (maskChar) {
372
+ case MaskFormatter.DIGIT_KEY:
373
+ this._maskChars.push(new MaskFormatter.DigitMaskCharacter(this, maskChar));
374
+ break;
375
+ case MaskFormatter.LITERAL_KEY:
376
+ if (++counter < maxCounter) {
377
+ maskChar = this.mask.charAt(counter);
378
+ this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
379
+ }
380
+ break;
381
+ case MaskFormatter.UPPERCASE_KEY:
382
+ this._maskChars.push(new MaskFormatter.UpperCaseCharacter(this, maskChar));
383
+ break;
384
+ case MaskFormatter.LOWERCASE_KEY:
385
+ this._maskChars.push(new MaskFormatter.LowerCaseCharacter(this, maskChar));
386
+ break;
387
+ case MaskFormatter.ALPHA_NUMERIC_KEY:
388
+ this._maskChars.push(new MaskFormatter.AlphaNumericCharacter(this, maskChar));
389
+ break;
390
+ case MaskFormatter.CHARACTER_KEY:
391
+ this._maskChars.push(new MaskFormatter.CharCharacter(this, maskChar));
392
+ break;
393
+ case MaskFormatter.ANYTHING_KEY:
394
+ this._maskChars.push(new MaskFormatter.MaskCharacter(this, maskChar));
395
+ break;
396
+ default:
397
+ this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
398
+ break;
399
+ }
400
+ counter++;
401
+ }
402
+ }
403
+ }
404
+ }
405
+ MaskFormatter.DIGIT_KEY = "#";
406
+ MaskFormatter.LITERAL_KEY = "'";
407
+ MaskFormatter.UPPERCASE_KEY = "U";
408
+ MaskFormatter.LOWERCASE_KEY = "L";
409
+ MaskFormatter.ALPHA_NUMERIC_KEY = "A";
410
+ MaskFormatter.CHARACTER_KEY = "?";
411
+ MaskFormatter.ANYTHING_KEY = "*";
412
+ //
413
+ // Classes internas usadas para representar a máscara.
414
+ //
415
+ MaskFormatter.MaskCharacter = class {
416
+ constructor(maskFormatter, type) {
417
+ this.maskFormatter = maskFormatter;
418
+ this.type = type;
419
+ }
420
+ /**
421
+ * Cada subclasse deve sobrescrever o retornando true, caso represente
422
+ * um caractere literal. Por padrão o retorno é false.
423
+ */
424
+ isLiteral() {
425
+ return false;
426
+ }
427
+ /**
428
+ * Returns true if <code>aChar</code> is a valid reprensentation of
429
+ * the receiver. The default implementation returns true if the
430
+ * receiver represents a literal character and <code>getChar</code>
431
+ * == aChar. Otherwise, this will return true is <code>aChar</code>
432
+ * is contained in the valid characters and not contained
433
+ * in the invalid characters.
434
+ */
435
+ isValidCharacter(aChar) {
436
+ if (this.isLiteral()) {
437
+ return (this.getChar(aChar) == aChar);
438
+ }
439
+ aChar = this.getChar(aChar);
440
+ return true;
441
+ }
442
+ /**
443
+ * Returns the character to insert for <code>aChar</code>. The
444
+ * default implementation returns <code>aChar</code>. Subclasses
445
+ * that wish to do some sort of mapping, perhaps lower case to upper
446
+ * case should override this and do the necessary mapping.
447
+ */
448
+ getChar(aChar) {
449
+ return aChar;
450
+ }
451
+ /**
452
+ * Appends the necessary character in <code>formatting</code> at
453
+ * <code>index</code> to <code>buff</code>.
454
+ */
455
+ append(result, formatting, index) {
456
+ const inString = index[0] < formatting.length;
457
+ const aChar = inString ? formatting.charAt(index[0]) : '';
458
+ if (this.isLiteral()) {
459
+ const literal = this.getChar(aChar);
460
+ result += literal;
461
+ if (literal === aChar) {
462
+ index[0] = index[0] + 1;
463
+ }
464
+ }
465
+ else if (index[0] >= formatting.length) {
466
+ result += this.maskFormatter.placeholder;
467
+ index[0] = index[0] + 1;
468
+ }
469
+ else if (this.isValidCharacter(aChar)) {
470
+ result += this.getChar(aChar);
471
+ index[0] = index[0] + 1;
472
+ }
473
+ else {
474
+ throw new Error(`Valor inválido: "${aChar}". Na posição ${index[0] + 1} espera-se ${this.getFormatMessage()}.`);
475
+ }
476
+ return result;
477
+ }
478
+ getFormatMessage() {
479
+ let message;
480
+ switch (this.type) {
481
+ case MaskFormatter.UPPERCASE_KEY:
482
+ case MaskFormatter.LOWERCASE_KEY:
483
+ case MaskFormatter.CHARACTER_KEY:
484
+ message = 'uma letra';
485
+ break;
486
+ case MaskFormatter.DIGIT_KEY:
487
+ message = 'um número';
488
+ break;
489
+ case MaskFormatter.ALPHA_NUMERIC_KEY:
490
+ message = 'uma letra ou um número';
491
+ break;
492
+ default:
493
+ message = '';
494
+ }
495
+ return message;
496
+ }
497
+ };
498
+ MaskFormatter.LiteralCharacter = class extends MaskFormatter.MaskCharacter {
499
+ constructor(maskFormatter, fixedChar) {
500
+ super(maskFormatter, fixedChar);
501
+ this._fixedChar = fixedChar;
502
+ }
503
+ isLiteral() {
504
+ return true;
505
+ }
506
+ getChar(aChar) {
507
+ aChar;
508
+ return this._fixedChar;
509
+ }
510
+ };
511
+ MaskFormatter.DigitMaskCharacter = class extends MaskFormatter.MaskCharacter {
512
+ isValidCharacter(aChar) {
513
+ return (this.isDigit(aChar) && super.isValidCharacter(aChar));
514
+ }
515
+ isDigit(char) {
516
+ return char >= '0' && char <= '9';
517
+ }
518
+ };
519
+ MaskFormatter.UpperCaseCharacter = class extends MaskFormatter.MaskCharacter {
520
+ isValidCharacter(aChar) {
521
+ return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
522
+ }
523
+ getChar(aChar) {
524
+ return aChar.toUpperCase();
525
+ }
526
+ };
527
+ MaskFormatter.LowerCaseCharacter = class extends MaskFormatter.MaskCharacter {
528
+ isValidCharacter(aChar) {
529
+ return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
530
+ }
531
+ getChar(aChar) {
532
+ return aChar.toLocaleLowerCase();
533
+ }
534
+ };
535
+ MaskFormatter.AlphaNumericCharacter = class extends MaskFormatter.MaskCharacter {
536
+ isValidCharacter(aChar) {
537
+ //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
538
+ return (/[a-z0-9]/i.test(aChar)) && super.isValidCharacter(aChar);
539
+ }
540
+ };
541
+ MaskFormatter.CharCharacter = class extends MaskFormatter.MaskCharacter {
542
+ isValidCharacter(aChar) {
543
+ //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
544
+ return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
545
+ }
546
+ };
547
+
548
+ class FloatingEntry {
549
+ constructor(parent, content, opts) {
550
+ try {
551
+ this.weakRefParent = new WeakRef(parent);
552
+ this.weakRefContent = new WeakRef(content);
553
+ }
554
+ catch (error) {
555
+ this.strongRefParent = parent;
556
+ this.strongRefContent = content;
557
+ }
558
+ this.options = opts;
559
+ }
560
+ get parent() {
561
+ if (this.weakRefParent) {
562
+ return this.weakRefParent.deref();
563
+ }
564
+ return this.strongRefParent;
565
+ }
566
+ get content() {
567
+ if (this.weakRefContent) {
568
+ return this.weakRefContent.deref();
569
+ }
570
+ return this.strongRefContent;
571
+ }
572
+ }
573
+ class FloatingManager {
574
+ static init() {
575
+ FloatingManager.entries = [];
576
+ document.addEventListener('mousedown', FloatingManager.handleDocumentEvent);
577
+ document.addEventListener('keydown', FloatingManager.handleKeyboardEvent);
578
+ FloatingManager.initialized = true;
579
+ }
580
+ static innerClick(container, node) {
581
+ if (container.contains(node)) {
582
+ return true;
583
+ }
584
+ if (container.shadowRoot && container.shadowRoot.contains(node)) {
585
+ return true;
586
+ }
587
+ return false;
588
+ }
589
+ static doClose(id, entry, target, event) {
590
+ if (!target || entry.options.autoClose) {
591
+ const parent = entry.parent;
592
+ const content = entry.content;
593
+ if (parent && content) {
594
+ const innerClickFunction = entry.options.innerClickTest ? entry.options.innerClickTest : FloatingManager.innerClick;
595
+ const backClickFunction = entry.options.backClickListener ? entry.options.backClickListener : () => { };
596
+ if (!target || !innerClickFunction(content, target, event)) {
597
+ content.remove();
598
+ delete FloatingManager.entries[id];
599
+ backClickFunction();
600
+ }
601
+ }
602
+ else {
603
+ delete FloatingManager.entries[id];
604
+ }
605
+ }
606
+ }
607
+ static handleDocumentEvent(event) {
608
+ FloatingManager.entries.forEach((entry, index) => {
609
+ FloatingManager.doClose(index, entry, event.composedPath()[0], event);
610
+ });
611
+ }
612
+ static handleKeyboardEvent(event) {
613
+ if (event.key === 'Escape') {
614
+ for (let index = FloatingManager.entries.length; index >= 0; index--) {
615
+ const entry = FloatingManager.entries[index];
616
+ if (entry) {
617
+ FloatingManager.close(index);
618
+ break;
619
+ }
620
+ }
621
+ }
622
+ }
623
+ static applyStyle(element, propertyName, value) {
624
+ if (value) {
625
+ element.style.setProperty(propertyName, value);
626
+ }
627
+ }
628
+ static getFloatIndex(content, parent) {
629
+ for (let index = 0; index < FloatingManager.entries.length; index++) {
630
+ const entry = FloatingManager.entries[index];
631
+ if (entry && content === entry.content && parent === entry.parent) {
632
+ return index;
633
+ }
634
+ }
635
+ return -1;
636
+ }
637
+ static isFloating(id) {
638
+ return FloatingManager.entries[id] !== undefined;
639
+ }
640
+ static float(content, parent, options = { autoClose: true }) {
641
+ if (!FloatingManager.initialized) {
642
+ FloatingManager.init();
643
+ }
644
+ const alreadyFloatingIndex = FloatingManager.getFloatIndex(content, parent);
645
+ if (alreadyFloatingIndex > -1) {
646
+ return alreadyFloatingIndex;
647
+ }
648
+ content.style.position = options.isFixed ? 'fixed' : 'absolute';
649
+ FloatingManager.applyStyle(content, "top", options.top);
650
+ FloatingManager.applyStyle(content, "left", options.left);
651
+ FloatingManager.applyStyle(content, "right", options.right);
652
+ FloatingManager.applyStyle(content, "bottom", options.bottom);
653
+ parent.appendChild(content);
654
+ FloatingManager.entries.push(new FloatingEntry(parent, content, options));
655
+ return FloatingManager.entries.length - 1;
656
+ }
657
+ static updateFloatPosition(content, parent, options = { autoClose: true }) {
658
+ const alreadyFloatingIndex = FloatingManager.getFloatIndex(content, parent);
659
+ if (alreadyFloatingIndex > -1) {
660
+ FloatingManager.applyStyle(content, "top", options.top);
661
+ FloatingManager.applyStyle(content, "left", options.left);
662
+ FloatingManager.applyStyle(content, "right", options.right);
663
+ FloatingManager.applyStyle(content, "bottom", options.bottom);
664
+ }
665
+ }
666
+ static close(id) {
667
+ if (FloatingManager.entries[id]) {
668
+ FloatingManager.doClose(id, FloatingManager.entries[id], undefined);
669
+ }
670
+ }
671
+ }
672
+
673
+ class DateUtils {
674
+ static clearTime(date, adjustDayLightSavingTime = true) {
675
+ const newDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
676
+ return adjustDayLightSavingTime ? DateUtils.adjustDLST(newDate) : newDate;
677
+ }
678
+ static strToDate(strValue, adjustDayLightSavingTime = true, monthYearMode = false) {
679
+ /** monthYearMode é um booleano para usar o formato MM/YYYY.
680
+ * Quando ativado, é retornado o primeiro dia do mês apenas para construir a data.
681
+ * Não há necessidade de verificar o horário de verão quando utilizado esse modo. */
682
+ let parts;
683
+ if (monthYearMode) {
684
+ parts = /^(1[0-2]|0[1-9]|[1-9])[^\d]?(\d{2}|\d{4})(?:\s(\d{1,2}):(\d{1,2}):?(\d{0,2}))?$/.exec(strValue);
685
+ }
686
+ else {
687
+ parts = /^(3[01]|[1-2]\d|0[1-9]|[1-9])[^\d]?(1[0-2]|0[1-9]|[1-9])[^\d]?(\d{2}|\d{4})(?:\s(\d{1,2}):(\d{1,2}):?(\d{0,2}))?$/.exec(strValue);
688
+ }
689
+ if (!parts) {
690
+ return undefined;
691
+ }
692
+ const day = monthYearMode ? 1 : Number(parts[1]);
693
+ const month = Number(parts[(monthYearMode ? 1 : 2)]);
694
+ let year = Number(parts[(monthYearMode ? 2 : 3)]);
695
+ const hour = Number(parts[(monthYearMode ? 3 : 4)] || 0);
696
+ const min = Number(parts[(monthYearMode ? 4 : 5)] || 0);
697
+ const sec = Number(parts[(monthYearMode ? 5 : 6)] || 0);
698
+ if (year < 100) {
699
+ year += year < 30 ? 2000 : 1900;
700
+ }
701
+ let date = new Date(year, month - 1, day, hour, min, sec, 0);
702
+ if (adjustDayLightSavingTime === true && !monthYearMode && hour == 0) {
703
+ date = DateUtils.adjustDLST(date);
704
+ }
705
+ return date;
706
+ }
707
+ static adjustDLST(date) {
708
+ //Work around para corrigir o Bug do horário de verão.
709
+ if (date.getHours() == 23) {
710
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 1, 0, 0, 0);
711
+ }
712
+ return date;
713
+ }
714
+ }
715
+
716
+ class ArrayUtils {
717
+ /**
718
+ * Filtra um array a partir de um critério textual.
719
+ *
720
+ * @param argument - Texto a ser usado no filtro
721
+ * @param originalArray - Array no formato original
722
+ * @param alphabeticalSorting - Determina se o resultado deve ser ordenado ou mantido na ordem original. Por padrão ordena.
723
+ * @param fieldName - Caso o objeto deva ser filtrado por um campo diferente de "label", pode-se usar esse parâmetro
724
+ * @returns Um array filtrado e ordenado conforme necessidade. Se "argument" for omitido, ou nulo, o array original é retornado.
725
+ */
726
+ static applyStringFilter(argument, originalArray, alphabeticalSorting = true, fieldName = "label") {
727
+ if (!argument) {
728
+ return originalArray;
729
+ }
730
+ const normalizedArgument = ArrayUtils.normalizeSearchString(argument);
731
+ const filteredArray = originalArray.filter(item => {
732
+ const itemValue = ArrayUtils.normalizeSearchString(item[fieldName]);
733
+ return itemValue.includes(normalizedArgument);
734
+ });
735
+ return alphabeticalSorting ? filteredArray.sort((a, b) => StringUtils.compare(a[fieldName], b[fieldName])) : filteredArray;
736
+ }
737
+ static normalizeSearchString(original) {
738
+ return StringUtils.replaceAccentuatedCharsKeepSymbols(original.toUpperCase());
739
+ }
740
+ }
741
+
742
+ /**
743
+ * `TimeFormatter` é um utilitário para formatação de strings desformatadas em strings válidas de horários
744
+ */
745
+ class TimeFormatter {
746
+ /**
747
+ * @prepareValue: converts an unformated time string into a formatted time.
748
+ *
749
+ * @param value unformated time string to convert
750
+ *
751
+ * @returns formatted time string
752
+ *
753
+ * @Exemples
754
+ * @"1012" | "10:12"
755
+ * @"10:12" | "10:12:00"
756
+ * @"100112" | "10:01:12"
757
+ */
758
+ static prepareValue(value, showSeconds) {
759
+ if (value && value.length > 0 && value != "NaN") {
760
+ let validationValue = value.replace(/:/g, "");
761
+ if (showSeconds) {
762
+ this._maskFormatter.mask = "##:##:##";
763
+ if (validationValue.length < 6) {
764
+ while (validationValue.length < 6) {
765
+ validationValue = "0".concat(validationValue);
766
+ }
767
+ }
768
+ }
769
+ else {
770
+ this._maskFormatter.mask = "##:##";
771
+ if (validationValue.length < 4) {
772
+ while (validationValue.length < 4) {
773
+ validationValue = "0".concat(validationValue);
774
+ }
775
+ }
776
+ }
777
+ if (this._maskFormatter) {
778
+ try {
779
+ value = this._maskFormatter.format(validationValue);
780
+ return value;
781
+ }
782
+ catch (e) {
783
+ throw new Error(e.message);
784
+ }
785
+ }
786
+ }
787
+ return '';
788
+ }
789
+ /**
790
+ * @validateTime: validates if an input string has the corect time format.
791
+ *
792
+ * @param value input string to validate
793
+ *
794
+ * @returns true or false
795
+ *
796
+ * @Exemples
797
+ * @"1012" | true
798
+ * @"14e4" | false
799
+ * @"2624" | false
800
+ */
801
+ static validateTime(value, showSeconds) {
802
+ let isValid = true;
803
+ if (value) {
804
+ let validationValue = value.replace(/:/g, "");
805
+ if (showSeconds) {
806
+ if (!["1", "2", "0"].includes(validationValue[0])) {
807
+ isValid = false;
808
+ }
809
+ if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) {
810
+ isValid = false;
811
+ }
812
+ if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[4])) {
813
+ isValid = false;
814
+ }
815
+ if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) {
816
+ isValid = false;
817
+ }
818
+ }
819
+ else {
820
+ if (!["1", "2", "0"].includes(validationValue[0])) {
821
+ isValid = false;
822
+ }
823
+ if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) {
824
+ isValid = false;
825
+ }
826
+ if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) {
827
+ isValid = false;
828
+ }
829
+ }
830
+ }
831
+ else {
832
+ isValid = false;
833
+ }
834
+ return isValid;
835
+ }
836
+ }
837
+ TimeFormatter._maskFormatter = new MaskFormatter("##:##");
838
+
839
+ /**
840
+ * Representa as propriedades necessárias para se executar uma requisição.
841
+ */
842
+ class RequestMetadata {
843
+ /**
844
+ * @param {string} url A URL que deve ser chamada.
845
+ * @param {Method} method O Método da requisição (GET, PUT, POST ou DELETE).
846
+ */
847
+ constructor(url, method, headers) {
848
+ /** Tempo limite de espera pela resposta */
849
+ this.timeout = 30000;
850
+ this.url = url;
851
+ this.method = method;
852
+ this.headers = headers || [];
853
+ }
854
+ }
855
+ /** Representa os verbos HTTP suportados */
856
+ var Method;
857
+ (function (Method) {
858
+ Method[Method["GET"] = 0] = "GET";
859
+ Method[Method["PUT"] = 1] = "PUT";
860
+ Method[Method["POST"] = 2] = "POST";
861
+ Method[Method["DELETE"] = 3] = "DELETE";
862
+ })(Method || (Method = {}));
863
+
864
+ /**
865
+ * Abstração do XMLHttpRequest. Este serviço é responsável por realizar as requisições
866
+ * ao backend. Todos os métodos são estáticos.
867
+ */
868
+ class HttpProvider {
869
+ /**
870
+ * Faz uma requisição usando o método GET do HTTP para uma URL específica.
871
+ *
872
+ * @param {string} url A URL que deve ser chamada.
873
+ * @param {Array<Header>} headers [Opcional] Cabeçalhos HTTP.
874
+ * @returns {Promise<Object>} Uma promessa de que a requisição será preenchida.
875
+ */
876
+ static get(url, headers) {
877
+ return this.dispatch(new RequestMetadata(url, Method.GET, headers));
878
+ }
879
+ /**
880
+ * Faz uma requisição usando o método POST do HTTP para uma URL específica.
881
+ *
882
+ * @param {string} url A URL que deve ser chamada.
883
+ * @param {Object} payload Informações a serem enviadas.
884
+ * @param {Array<Header>} headers [Opcional] Cabeçalhos HTTP.
885
+ * @returns {Promise<Object>} Uma promessa de que a requisição será preenchida.
886
+ */
887
+ static post(url, payload, headers) {
888
+ return this.dispatch(new RequestMetadata(url, Method.POST, headers), payload);
889
+ }
890
+ static dispatch(requestMetadata, payload) {
891
+ return new Promise((resolve, reject) => {
892
+ const request = new XMLHttpRequest();
893
+ request.timeout = requestMetadata.timeout;
894
+ request.onerror = function handleError() {
895
+ reject({
896
+ status: 404,
897
+ statusText: 'Not Found'
898
+ });
899
+ };
900
+ request.ontimeout = function handleTimeout() {
901
+ reject({
902
+ status: 408,
903
+ statusText: 'Request Timeout'
904
+ });
905
+ };
906
+ request.onreadystatechange = () => {
907
+ // While readState isn't done, there's nothing to do...
908
+ if (request.readyState != 4) {
909
+ return;
910
+ }
911
+ const status = request.status;
912
+ // The request has failed so we'll handled by onerror instead
913
+ if (status === 0) {
914
+ return;
915
+ }
916
+ const response = {
917
+ status,
918
+ statusText: request.statusText,
919
+ };
920
+ // Anything out of this range is an error, so we just send the status and statusText.
921
+ if (status >= 200 && status < 300) {
922
+ resolve(Object.assign(Object.assign({}, response), { data: request.response, dataAsString: request.responseText }));
923
+ }
924
+ else {
925
+ reject(response);
926
+ }
927
+ };
928
+ request.open(requestMetadata.method.toString(), requestMetadata.url, true);
929
+ requestMetadata.headers.map((h) => request.setRequestHeader(h.name, h.value));
930
+ if (payload != null) {
931
+ request.send(JSON.stringify(payload));
932
+ }
933
+ });
934
+ }
935
+ }
936
+
937
+ class SkwHttpProvider {
938
+ static callService(serviceName, content) {
939
+ return new Promise((resolve, reject) => {
940
+ let host = "http://192.168.1.218:8503/mge/";
941
+ let appName = "ListaTarefa";
942
+ let module = 'mge';
943
+ this._counter++;
944
+ if (serviceName.indexOf("@") > -1) {
945
+ let s = serviceName.split("@");
946
+ module = s[0];
947
+ serviceName = s[1];
948
+ }
949
+ let url = `${host}/${module}/service.sbr?serviceName=${serviceName}&counter=${this._counter}&application=${appName}&outputType=json&preventTransform=false`;
950
+ let requestContent = {
951
+ serviceName: serviceName,
952
+ requestBody: content
953
+ };
954
+ let headers = new Headers();
955
+ headers.append("Content-Type", "application/json");
956
+ //headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
957
+ //headers.append("Access-Control-Allow-Origin", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
958
+ fetch(url, {
959
+ body: JSON.stringify(requestContent),
960
+ method: 'POST',
961
+ headers: headers
962
+ })
963
+ .then(res => res.json())
964
+ .then((data) => {
965
+ console.log(data);
966
+ });
967
+ /*HttpProvider.post(url, requestContent, headers)
968
+ .then(res => {
969
+ if (!res.hasOwnProperty('status') ||
970
+ res.status == this.STATUS_ERROR ||
971
+ res.status == this.STATUS_TIMEOUT) {
972
+
973
+ let statusMessage = res.statusMessage;
974
+
975
+ if (!statusMessage) {
976
+ statusMessage = 'Erro não identificado.'
977
+ }
978
+ //TODO: No futuro, exibir mensagens de erro. (MessageUtils.showError)
979
+ reject(new Error(statusMessage));
980
+ }else if (res.status == this.STATUS_CANCELED) {
981
+ if (res.statusMessage){
982
+ console.warn(res.statusMessage);
983
+ }
984
+ }else{
985
+ resolve(res);
986
+ }
987
+
988
+ if (res.status == this.STATUS_INFO) {
989
+ //TODO: No futuro, exibir mensagens de erro. (MessageUtils.showAlert)
990
+ console.info(res.statusMessage);
991
+ }
992
+ })
993
+ .catch((e)=>{reject(e)});*/
994
+ });
995
+ }
996
+ }
997
+ SkwHttpProvider._counter = 0;
998
+ SkwHttpProvider.STATUS_ERROR = 0;
999
+ SkwHttpProvider.STATUS_OK = 1;
1000
+ SkwHttpProvider.STATUS_INFO = 2;
1001
+ SkwHttpProvider.STATUS_TIMEOUT = 3;
1002
+ SkwHttpProvider.STATUS_CANCELED = 4;
1003
+
1004
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1005
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1006
+ return new (P || (P = Promise))(function (resolve, reject) {
1007
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1008
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1009
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1010
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1011
+ });
1012
+ };
1013
+ class AuthorizedServiceCaller {
1014
+ constructor(serverURL, unauthorizedPath) {
1015
+ this.serverURL = "http://192.168.1.218:8503"; //todo request deve fazer replace de ${serverURL} pelo conteúdo da variável
1016
+ this.unauthorizedPath = "/";
1017
+ this.serverURL = serverURL;
1018
+ this.unauthorizedPath = unauthorizedPath;
1019
+ }
1020
+ requestService(request, callback) {
1021
+ return __awaiter$1(this, void 0, void 0, function* () {
1022
+ const token = localStorage.getItem('token');
1023
+ const body = request === null || request === void 0 ? void 0 : request.body;
1024
+ const method = request === null || request === void 0 ? void 0 : request.method;
1025
+ let headers;
1026
+ if (!token) {
1027
+ window.location.pathname = this.unauthorizedPath;
1028
+ }
1029
+ else {
1030
+ headers = {
1031
+ 'Authorization': `${token}`,
1032
+ 'Content-Type': 'application/json',
1033
+ 'Customer-Host': 'http://localhost:8080/sankhyaw'
1034
+ };
1035
+ }
1036
+ const response = yield yield fetch(this.serverURL, {
1037
+ method: method,
1038
+ headers: headers,
1039
+ body: body
1040
+ })
1041
+ .catch(e => {
1042
+ console.log(e);
1043
+ });
1044
+ if (response instanceof Response && response.status === 401) {
1045
+ localStorage.removeItem('token');
1046
+ window.location.pathname = this.unauthorizedPath;
1047
+ }
1048
+ if (callback && response instanceof Response) {
1049
+ callback(response.json().then());
1050
+ }
1051
+ else {
1052
+ return response;
1053
+ }
1054
+ });
1055
+ }
1056
+ }
1057
+
1058
+ var DataType;
1059
+ (function (DataType) {
1060
+ DataType["NUMBER"] = "NUMBER";
1061
+ DataType["DATE"] = "DATE";
1062
+ DataType["TEXT"] = "TEXT";
1063
+ DataType["BOOLEAN"] = "BOOLEAN";
1064
+ DataType["OBJECT"] = "OBJECT";
1065
+ })(DataType || (DataType = {}));
1066
+ const convertType = (dataType, value) => {
1067
+ if (value === undefined || value === null) {
1068
+ return value;
1069
+ }
1070
+ if (typeof value === "object" && dataType !== DataType.OBJECT && "value" in value) {
1071
+ value = value.value;
1072
+ }
1073
+ switch (dataType) {
1074
+ case DataType.NUMBER:
1075
+ return value === "" || isNaN(value) ? null : Number(value);
1076
+ case DataType.OBJECT:
1077
+ return typeof value === "string" ? JSON.parse(value) : value;
1078
+ case DataType.BOOLEAN:
1079
+ if (typeof value == 'string') {
1080
+ return Boolean(value === 'true');
1081
+ }
1082
+ return Boolean(value);
1083
+ case DataType.DATE:
1084
+ return new Date(value.toString());
1085
+ default:
1086
+ return value;
1087
+ }
1088
+ };
1089
+ const toString = (dataType, value) => {
1090
+ if (value === undefined || value === null) {
1091
+ return value;
1092
+ }
1093
+ if (dataType) {
1094
+ if (dataType === DataType.OBJECT) {
1095
+ return JSON.stringify(value);
1096
+ }
1097
+ else if (dataType === DataType.DATE) {
1098
+ return value.toISOString();
1099
+ }
1100
+ else {
1101
+ return value.toString();
1102
+ }
1103
+ }
1104
+ else {
1105
+ if (typeof value === "string") {
1106
+ return value;
1107
+ }
1108
+ else if (value instanceof Date) {
1109
+ return value.toISOString();
1110
+ }
1111
+ else {
1112
+ try {
1113
+ return JSON.stringify(value);
1114
+ }
1115
+ catch (_a) {
1116
+ value = value.toString();
1117
+ }
1118
+ return value;
1119
+ }
1120
+ }
1121
+ };
1122
+
1123
+ class DataUnitAction {
1124
+ constructor(type, payload) {
1125
+ this._type = type;
1126
+ this._payload = payload;
1127
+ }
1128
+ get type() {
1129
+ return this._type;
1130
+ }
1131
+ get payload() {
1132
+ return this._payload;
1133
+ }
1134
+ }
1135
+ var Action;
1136
+ (function (Action) {
1137
+ Action["LOADING_METADATA"] = "loadingMetadata";
1138
+ Action["METADATA_LOADED"] = "metadataLoaded";
1139
+ Action["LOADING_DATA"] = "loadingData";
1140
+ Action["DATA_LOADED"] = "dataLoaded";
1141
+ Action["SAVING_DATA"] = "savingData";
1142
+ Action["DATA_SAVED"] = "dataSaved";
1143
+ Action["REMOVING_RECORDS"] = "removingRecords";
1144
+ Action["RECORDS_REMOVED"] = "recordsRemoved";
1145
+ Action["RECORDS_ADDED"] = "recordsAdded";
1146
+ Action["RECORDS_COPIED"] = "recordsCopied";
1147
+ Action["CHANGING_DATA"] = "changingData";
1148
+ Action["WAITING_CHANGE_CANCELED"] = "waitingChangeCanceled";
1149
+ Action["DATA_CHANGED"] = "dataChanged";
1150
+ Action["EDITION_CANCELED"] = "editionCanceled";
1151
+ Action["CHANGE_UNDONE"] = "changeUndone";
1152
+ Action["CHANGE_REDONE"] = "changeRedone";
1153
+ Action["SELECTION_CHANGED"] = "selectionChanged";
1154
+ Action["NEXT_SELECTED"] = "nextSelected";
1155
+ Action["PREVIOUS_SELECTED"] = "previousSelected";
1156
+ Action["STATE_CHANGED"] = "stateChanged";
1157
+ })(Action || (Action = {}));
1158
+
1159
+ /**
1160
+ * Essa classe representa uma interpretação do padrão de projetos Flux.
1161
+ * No padrão Flux os dados da aplicação são chamados de "estado" e existem
1162
+ * algumas regras para gerenciamento/manipulação desse estado:
1163
+ *
1164
+ * 1 - O estado é imutável.
1165
+ * 2 - Toda modificação de estado é representada por uma "ação".
1166
+ * 3 - Quando "ações" acontecem a "store" cria um novo estado e notifica a todos interessados.
1167
+ *
1168
+ * Nessa interpretação desse design pattern, o StateManager faz o papel da store,
1169
+ * notificando os manipuladores de estado (handlers), que são responsáveis por pedaços
1170
+ * do estado (slices).
1171
+ *
1172
+ * O StateManager mantém dois tipos de estados: "Histórico" e "Não Histórico". No estado
1173
+ * "Histórico", sempre que uma alteração de estado acontece, o estado anterior é guardado em
1174
+ * uma pilha, o que permite que possamos voltar no tempo, desfazendo algumas ações
1175
+ */
1176
+ class StateManager {
1177
+ constructor(reducers) {
1178
+ this._past = [];
1179
+ this._future = [];
1180
+ this._present = {};
1181
+ this._nonHist = {};
1182
+ this._histClean = false;
1183
+ this._reducers = reducers;
1184
+ }
1185
+ process(action) {
1186
+ const oldPresent = this._present;
1187
+ let hasHistChange = false;
1188
+ this._histClean = false;
1189
+ this._reducers.forEach(reducer => {
1190
+ const sliceName = reducer.sliceName;
1191
+ const isHistoric = this.isHistoric(sliceName);
1192
+ const oldSlice = this.getSlice(sliceName, isHistoric);
1193
+ const newSlice = reducer.reduce(this, oldSlice, action);
1194
+ if (newSlice !== oldSlice) {
1195
+ this.updateSlice(sliceName, newSlice, isHistoric);
1196
+ hasHistChange || (hasHistChange = isHistoric);
1197
+ }
1198
+ });
1199
+ if (hasHistChange && !this._histClean) {
1200
+ this._past.push(oldPresent);
1201
+ this._future = [];
1202
+ document.dispatchEvent(new CustomEvent("undoableAction", { detail: this }));
1203
+ }
1204
+ }
1205
+ select(sliceName, selector) {
1206
+ const isHistoric = this.isHistoric(sliceName);
1207
+ return selector(this.getSlice(sliceName, isHistoric));
1208
+ }
1209
+ isHistoric(slice) {
1210
+ return slice.startsWith("hist::");
1211
+ }
1212
+ updateSlice(name, slice, isHistoric) {
1213
+ if (isHistoric) {
1214
+ this._present = Object.assign(Object.assign({}, this._present), { [name]: slice });
1215
+ if (slice === undefined) {
1216
+ delete this._present[name];
1217
+ }
1218
+ }
1219
+ else {
1220
+ this._nonHist = Object.assign(Object.assign({}, this._nonHist), { [name]: slice });
1221
+ if (slice === undefined) {
1222
+ delete this._nonHist[name];
1223
+ }
1224
+ }
1225
+ }
1226
+ getSlice(name, isHistoric) {
1227
+ return isHistoric ? this._present[name] : this._nonHist[name];
1228
+ }
1229
+ canUndo() {
1230
+ return this._past.length > 0;
1231
+ }
1232
+ canRedo() {
1233
+ return this._future.length > 0;
1234
+ }
1235
+ undo() {
1236
+ if (this.canUndo()) {
1237
+ this._future.push(this._present);
1238
+ this._present = this._past.pop();
1239
+ }
1240
+ }
1241
+ redo() {
1242
+ if (this.canRedo()) {
1243
+ this._past.push(this._present);
1244
+ this._present = this._future.pop();
1245
+ }
1246
+ }
1247
+ clearUndo() {
1248
+ this._histClean = true;
1249
+ this._past = [];
1250
+ this._future = [];
1251
+ }
1252
+ persist() {
1253
+ }
1254
+ }
1255
+
1256
+ class ErrorException extends Error {
1257
+ constructor(title, message, errorCode = "") {
1258
+ super(message);
1259
+ this.title = title;
1260
+ this.message = message;
1261
+ this.errorCode = errorCode;
1262
+ }
1263
+ }
1264
+
1265
+ class WaitingChangeException extends Error {
1266
+ constructor(title, message) {
1267
+ super(message);
1268
+ this.title = title;
1269
+ this.message = message;
1270
+ }
1271
+ }
1272
+
1273
+ class AddedRecordsReducerImpl {
1274
+ constructor() {
1275
+ this.sliceName = "hist::addedRecords";
1276
+ }
1277
+ reduce(_stateManager, currentState, action) {
1278
+ switch (action.type) {
1279
+ case Action.RECORDS_ADDED:
1280
+ case Action.RECORDS_COPIED:
1281
+ return (currentState || []).concat(action.payload);
1282
+ case Action.DATA_SAVED:
1283
+ case Action.EDITION_CANCELED:
1284
+ return undefined;
1285
+ }
1286
+ return currentState;
1287
+ }
1288
+ }
1289
+ const AddedRecordsReducer = new AddedRecordsReducerImpl();
1290
+ const getAddedRecords = (stateManager) => {
1291
+ return stateManager.select(AddedRecordsReducer.sliceName, (state) => state);
1292
+ };
1293
+ const prepareAddedRecordId = (stateManager, source) => {
1294
+ let index = (getAddedRecords(stateManager) || []).length;
1295
+ return source.map(item => { return Object.assign(Object.assign({}, item), { __record__id__: "NEW_" + (index++) }); });
1296
+ };
1297
+ const prepareCopiedRecord = (stateManager, source) => {
1298
+ let index = (getAddedRecords(stateManager) || []).length;
1299
+ return source.map(item => { return Object.assign(Object.assign({}, item), { __record__id__: "NEW_" + (index++), __record__source__id__: item.__record__id__, __copy__: true }); });
1300
+ };
1301
+
1302
+ class RemovedRecordsReducerImpl {
1303
+ constructor() {
1304
+ this.sliceName = "hist::removedRecords";
1305
+ }
1306
+ reduce(_stateManager, currentState, action) {
1307
+ switch (action.type) {
1308
+ case Action.RECORDS_REMOVED:
1309
+ const { records, buffered } = action.payload;
1310
+ if (buffered) {
1311
+ return (currentState || []).concat(records);
1312
+ }
1313
+ return currentState;
1314
+ case Action.EDITION_CANCELED:
1315
+ case Action.DATA_SAVED:
1316
+ return undefined;
1317
+ }
1318
+ return currentState;
1319
+ }
1320
+ }
1321
+ const RemovedRecordsReducer = new RemovedRecordsReducerImpl();
1322
+ const getRemovedRecords = (stateManager) => {
1323
+ return stateManager.select(RemovedRecordsReducer.sliceName, (state) => state);
1324
+ };
1325
+
1326
+ class RecordsReducerImpl {
1327
+ constructor() {
1328
+ this.sliceName = "records";
1329
+ }
1330
+ reduce(stateManager, currentState, action) {
1331
+ switch (action.type) {
1332
+ case Action.DATA_LOADED:
1333
+ return action.payload ? action.payload.records : undefined;
1334
+ case Action.RECORDS_REMOVED:
1335
+ const { records, buffered } = action.payload;
1336
+ if (!buffered) {
1337
+ return currentState.filter(r => !records.includes(r.__record__id__));
1338
+ }
1339
+ return currentState;
1340
+ case Action.DATA_SAVED:
1341
+ const recordsMap = new Map();
1342
+ const currentRecords = getRecords(stateManager);
1343
+ if (currentRecords) {
1344
+ const removed = getRemovedRecords(stateManager) || [];
1345
+ currentRecords.forEach(r => {
1346
+ if (!removed.includes(r.__record__id__)) {
1347
+ recordsMap.set(r.__record__id__, r);
1348
+ }
1349
+ });
1350
+ }
1351
+ const newRecords = [];
1352
+ const savedRecords = action.payload.records;
1353
+ savedRecords.forEach(sr => {
1354
+ const recordId = sr.__old__id__ || sr.__record__id__;
1355
+ const newRecord = Object.assign({}, sr);
1356
+ delete newRecord["__old__id__"];
1357
+ if (recordsMap.has(recordId)) {
1358
+ recordsMap.set(recordId, newRecord);
1359
+ }
1360
+ else {
1361
+ newRecords.push(newRecord);
1362
+ }
1363
+ });
1364
+ return newRecords.concat(Array.from(recordsMap.values()));
1365
+ }
1366
+ return currentState;
1367
+ }
1368
+ }
1369
+ const RecordsReducer = new RecordsReducerImpl();
1370
+ const getRecords = (stateManager) => {
1371
+ return stateManager.select(RecordsReducer.sliceName, (state) => state);
1372
+ };
1373
+
1374
+ class CurrentRecordsReducerImpl {
1375
+ constructor() {
1376
+ this.sliceName = "currentRecords";
1377
+ }
1378
+ reduce(stateManager) {
1379
+ let records = getRecords(stateManager);
1380
+ const added = getAddedRecords(stateManager);
1381
+ if (!records && !added) {
1382
+ return undefined;
1383
+ }
1384
+ if (added) {
1385
+ records = (added || []).concat(records || []);
1386
+ }
1387
+ const removedRecords = getRemovedRecords(stateManager);
1388
+ if (removedRecords) {
1389
+ records = records.filter(r => !removedRecords.includes(r.__record__id__));
1390
+ }
1391
+ const changes = getChanges(stateManager);
1392
+ return new Map(records.map(r => {
1393
+ const recordId = r.__record__id__;
1394
+ const record = Object.assign(Object.assign({}, r), changes === null || changes === void 0 ? void 0 : changes.get(recordId));
1395
+ return [recordId, record];
1396
+ }));
1397
+ }
1398
+ }
1399
+ const CurrentRecordsReducer = new CurrentRecordsReducerImpl();
1400
+ const getCurrentRecords = (stateManager) => {
1401
+ return stateManager.select(CurrentRecordsReducer.sliceName, (state) => state);
1402
+ };
1403
+ const getModifiedRecords = (stateManager) => {
1404
+ const currentRecords = getCurrentRecords(stateManager);
1405
+ if (!currentRecords) {
1406
+ return undefined;
1407
+ }
1408
+ const changes = getChanges(stateManager);
1409
+ const added = getAddedRecords(stateManager);
1410
+ if (!changes && !added) {
1411
+ return undefined;
1412
+ }
1413
+ let modifiedIDs = changes ? Array.from(changes.keys()) : [];
1414
+ if (added) {
1415
+ modifiedIDs = modifiedIDs.concat(added.map(r => r.__record__id__));
1416
+ }
1417
+ return Array.from(currentRecords.values()).filter(r => modifiedIDs.includes(r.__record__id__));
1418
+ };
1419
+ const getFieldValue = (stateManager, fieldName) => {
1420
+ const selection = getSelection(stateManager);
1421
+ if (selection && selection.length > 0) {
1422
+ const currentRecords = getCurrentRecords(stateManager);
1423
+ if (currentRecords) {
1424
+ const record = currentRecords.get(selection[0]);
1425
+ return record ? record[fieldName] : undefined;
1426
+ }
1427
+ }
1428
+ return undefined;
1429
+ };
1430
+
1431
+ class SelectionReducerImpl {
1432
+ constructor() {
1433
+ this.sliceName = "hist::selection";
1434
+ }
1435
+ reduce(stateManager, currentState, action) {
1436
+ switch (action.type) {
1437
+ case Action.RECORDS_ADDED:
1438
+ case Action.RECORDS_COPIED:
1439
+ return { currentSelection: action.payload.map((r) => r.__record__id__), lastSelection: currentState === null || currentState === void 0 ? void 0 : currentState.currentSelection };
1440
+ case Action.DATA_SAVED:
1441
+ return { currentSelection: updateSavedIds(stateManager, action.payload.records) };
1442
+ case Action.RECORDS_REMOVED:
1443
+ const removed = action.payload.records;
1444
+ if (currentState && removed) {
1445
+ const currentSelection = currentState.currentSelection;
1446
+ const record = currentSelection.filter(recordId => !removed.includes(recordId));
1447
+ if (record.length === 0) {
1448
+ const currentRecords = getCurrentRecords(stateManager);
1449
+ let removedIndex = action.payload.removedIndex.slice(-1)[0];
1450
+ let currentIndex = 0;
1451
+ if (removedIndex >= currentRecords.size - 1) {
1452
+ removedIndex--;
1453
+ }
1454
+ else {
1455
+ removedIndex++;
1456
+ }
1457
+ currentRecords.forEach((value, key) => {
1458
+ if (currentIndex === removedIndex) {
1459
+ record.push(key);
1460
+ }
1461
+ currentIndex++;
1462
+ });
1463
+ }
1464
+ return { currentSelection: record };
1465
+ }
1466
+ return currentState;
1467
+ case Action.NEXT_SELECTED:
1468
+ case Action.PREVIOUS_SELECTED:
1469
+ const currentRecords = getCurrentRecords(stateManager);
1470
+ const currentSelection = currentState === null || currentState === void 0 ? void 0 : currentState.currentSelection;
1471
+ if (currentRecords && currentRecords.size > 0) {
1472
+ let index;
1473
+ if (!currentState || currentSelection.length === 0) {
1474
+ index = action.type === Action.PREVIOUS_SELECTED ? 0 : Math.min(1, currentRecords.size);
1475
+ }
1476
+ else {
1477
+ index = getItemIndex(currentSelection[0], currentRecords) + (action.type === Action.PREVIOUS_SELECTED ? -1 : 1);
1478
+ }
1479
+ if (index < currentRecords.size && index >= 0) {
1480
+ return { currentSelection: [Array.from(currentRecords.values())[index].__record__id__] };
1481
+ }
1482
+ }
1483
+ return undefined;
1484
+ case Action.SELECTION_CHANGED:
1485
+ const { type, selection: selectionSource } = action.payload;
1486
+ if (selectionSource && type === "index") {
1487
+ const currentRecords = getCurrentRecords(stateManager);
1488
+ if (currentRecords) {
1489
+ const records = Array.from(currentRecords.values());
1490
+ const selectionById = [];
1491
+ selectionSource.forEach((i) => {
1492
+ if (i >= 0 && i < currentRecords.size) {
1493
+ selectionById.push(records[i].__record__id__);
1494
+ }
1495
+ });
1496
+ return { currentSelection: selectionById };
1497
+ }
1498
+ }
1499
+ return { currentSelection: selectionSource };
1500
+ case Action.EDITION_CANCELED:
1501
+ if (currentState === null || currentState === void 0 ? void 0 : currentState.lastSelection) {
1502
+ return { currentSelection: currentState.lastSelection };
1503
+ }
1504
+ }
1505
+ return currentState;
1506
+ }
1507
+ }
1508
+ const SelectionReducer = new SelectionReducerImpl();
1509
+ const getSelection = (stateManager) => {
1510
+ let selection = getCurrentSelection(stateManager);
1511
+ if (!selection || selection.length === 0) {
1512
+ return [];
1513
+ }
1514
+ return selection;
1515
+ };
1516
+ const hasNext = (stateManager) => {
1517
+ const records = getCurrentRecords(stateManager);
1518
+ if (records) {
1519
+ const selection = getCurrentSelection(stateManager);
1520
+ if (!selection || selection.length === 0) {
1521
+ return records.size > 0;
1522
+ }
1523
+ return records.size > (getItemIndex(selection[0], records) + 1);
1524
+ }
1525
+ return false;
1526
+ };
1527
+ const hasPrevious = (stateManager) => {
1528
+ const records = getCurrentRecords(stateManager);
1529
+ if (records) {
1530
+ const selection = getCurrentSelection(stateManager);
1531
+ if (!selection || selection.length === 0) {
1532
+ return false;
1533
+ }
1534
+ return getItemIndex(selection[0], records) > 0;
1535
+ }
1536
+ return false;
1537
+ };
1538
+ function getItemIndex(key, map) {
1539
+ return Array.from(map.keys()).indexOf(key);
1540
+ }
1541
+ function updateSavedIds(stateManager, savedRecords) {
1542
+ const currentSelection = getSelection(stateManager);
1543
+ if (currentSelection) {
1544
+ const newSelection = [];
1545
+ currentSelection.forEach(id => {
1546
+ const record = savedRecords.find(r => r.__old__id__ === id);
1547
+ if (record) {
1548
+ newSelection.push(record.__record__id__);
1549
+ }
1550
+ else {
1551
+ newSelection.push(id);
1552
+ }
1553
+ });
1554
+ return newSelection;
1555
+ }
1556
+ return currentSelection;
1557
+ }
1558
+ function getCurrentSelection(stateManager) {
1559
+ var _a;
1560
+ return (_a = stateManager.select(SelectionReducer.sliceName, (state) => state)) === null || _a === void 0 ? void 0 : _a.currentSelection;
1561
+ }
1562
+
1563
+ class WaitingCheangesReducerImpl {
1564
+ constructor() {
1565
+ this.sliceName = "waitingChanges";
1566
+ }
1567
+ reduce(stateManager, currentState, action) {
1568
+ let newState;
1569
+ switch (action.type) {
1570
+ case Action.CHANGING_DATA:
1571
+ newState = new Map(currentState);
1572
+ Object.entries(action.payload).forEach(([key, value]) => {
1573
+ newState.set(key, value);
1574
+ });
1575
+ return newState;
1576
+ case Action.WAITING_CHANGE_CANCELED:
1577
+ newState = new Map(currentState);
1578
+ newState.delete(action.payload.fieldName);
1579
+ return newState.size === 0 ? undefined : newState;
1580
+ case Action.DATA_CHANGED:
1581
+ newState = new Map(currentState);
1582
+ Object.entries(action.payload).forEach(([key]) => {
1583
+ newState.delete(key);
1584
+ });
1585
+ return newState.size === 0 ? undefined : newState;
1586
+ case Action.DATA_SAVED:
1587
+ case Action.EDITION_CANCELED:
1588
+ return undefined;
1589
+ }
1590
+ return currentState;
1591
+ }
1592
+ }
1593
+ const WaitingChangesReducer = new WaitingCheangesReducerImpl();
1594
+ const getWaitingChanges = (stateManager) => {
1595
+ return stateManager.select(WaitingChangesReducer.sliceName, (state) => state);
1596
+ };
1597
+ const isWaiting = (stateManager, fieldName) => {
1598
+ const allWC = getWaitingChanges(stateManager);
1599
+ return allWC ? allWC.has(fieldName) : false;
1600
+ };
1601
+ const getBlockingWaitingChanges = (stateManager) => {
1602
+ const allWC = getWaitingChanges(stateManager);
1603
+ if (allWC) {
1604
+ return new Map(Array.from(allWC.entries())
1605
+ .filter(entry => entry[1].blocking)
1606
+ .map(entry => [entry[0], entry[1]]));
1607
+ }
1608
+ };
1609
+ const getWaitingChangePromisses = (stateManager) => {
1610
+ const allWC = getWaitingChanges(stateManager);
1611
+ if (allWC) {
1612
+ return Array.from(allWC.values())
1613
+ .filter(wc => !wc.blocking)
1614
+ .map(wc => wc.promise);
1615
+ }
1616
+ };
1617
+
1618
+ class ChangesReducerImpl {
1619
+ constructor() {
1620
+ this.sliceName = "hist::changes";
1621
+ }
1622
+ reduce(stateManager, currentState, action) {
1623
+ switch (action.type) {
1624
+ case Action.RECORDS_COPIED:
1625
+ const records = action.payload;
1626
+ const changes = new Map(getChanges(stateManager));
1627
+ records.forEach(r => {
1628
+ const rChanges = Object.assign(Object.assign({}, changes.get(r.__record__id__)), r);
1629
+ delete rChanges.__old__id__;
1630
+ delete rChanges.__record__id__;
1631
+ delete rChanges.__parent__record__id__;
1632
+ delete rChanges.__record__source__id__;
1633
+ delete rChanges.__copy__;
1634
+ changes.set(r.__record__id__, rChanges);
1635
+ });
1636
+ return changes;
1637
+ case Action.DATA_CHANGED:
1638
+ const selection = action.payload.records || getSelection(stateManager);
1639
+ if (selection) {
1640
+ const newState = new Map(currentState);
1641
+ selection.forEach(recordId => {
1642
+ const newChanges = Object.assign(Object.assign({}, newState.get(recordId)), action.payload);
1643
+ delete newChanges.records;
1644
+ newState.set(recordId, newChanges);
1645
+ });
1646
+ return newState;
1647
+ }
1648
+ return currentState;
1649
+ case Action.DATA_SAVED:
1650
+ case Action.EDITION_CANCELED:
1651
+ return undefined;
1652
+ }
1653
+ return currentState;
1654
+ }
1655
+ }
1656
+ const ChangesReducer = new ChangesReducerImpl();
1657
+ const getChanges = (stateManager) => {
1658
+ return stateManager.select(ChangesReducer.sliceName, (state) => state);
1659
+ };
1660
+ const isDirty = (stateManager) => {
1661
+ if (getAddedRecords(stateManager) !== undefined) {
1662
+ return true;
1663
+ }
1664
+ if (getRemovedRecords(stateManager) !== undefined) {
1665
+ return true;
1666
+ }
1667
+ return hasDirtyRecords(stateManager);
1668
+ };
1669
+ const hasDirtyRecords = (stateManager) => {
1670
+ if (getWaitingChanges(stateManager) !== undefined) {
1671
+ return true;
1672
+ }
1673
+ return getChanges(stateManager) !== undefined;
1674
+ };
1675
+ const getChangesToSave = (dataUnit, stateManager) => {
1676
+ const result = [];
1677
+ const changes = getChanges(stateManager);
1678
+ const records = getRecords(stateManager);
1679
+ records === null || records === void 0 ? void 0 : records.forEach(r => {
1680
+ if (changes) {
1681
+ const c = changes.get(r.__record__id__);
1682
+ if (c) {
1683
+ result.push(new Change(dataUnit, r, c, ChangeOperation.UPDATE));
1684
+ }
1685
+ }
1686
+ });
1687
+ const addedRecords = getAddedRecords(stateManager);
1688
+ if (addedRecords) {
1689
+ addedRecords.forEach(r => {
1690
+ const operation = r.__copy__ ? ChangeOperation.COPY : ChangeOperation.INSERT;
1691
+ result.push(new Change(dataUnit, r, changes === null || changes === void 0 ? void 0 : changes.get(r.__record__id__), operation, r.__record__source__id__));
1692
+ });
1693
+ }
1694
+ const removedRecords = getRemovedRecords(stateManager);
1695
+ const recordsById = {};
1696
+ records === null || records === void 0 ? void 0 : records.forEach(r => recordsById[r.__record__id__] = r);
1697
+ if (removedRecords) {
1698
+ removedRecords.forEach(id => {
1699
+ result.push(new Change(dataUnit, recordsById[id], undefined, ChangeOperation.DELETE));
1700
+ });
1701
+ }
1702
+ return result;
1703
+ };
1704
+
1705
+ class LoadingControlReducerImpl {
1706
+ constructor() {
1707
+ this.sliceName = "loadingControl";
1708
+ }
1709
+ reduce(stateManager, currentState, action) {
1710
+ var _a;
1711
+ switch (action.type) {
1712
+ case Action.LOADING_DATA:
1713
+ return Object.assign(Object.assign({}, currentState), { lastRequest: action.payload });
1714
+ case Action.DATA_LOADED:
1715
+ return Object.assign(Object.assign({}, currentState), { paginationInfo: (_a = action.payload) === null || _a === void 0 ? void 0 : _a.paginationInfo });
1716
+ }
1717
+ return currentState;
1718
+ }
1719
+ }
1720
+ const LoadingControlReducer = new LoadingControlReducerImpl();
1721
+ const getPaginationInfo = (stateManager) => {
1722
+ const state = stateManager.select(LoadingControlReducer.sliceName, (state) => state);
1723
+ return state ? state.paginationInfo : undefined;
1724
+ };
1725
+ const getCurrentRequest = (stateManager) => {
1726
+ const state = stateManager.select(LoadingControlReducer.sliceName, (state) => state);
1727
+ return state ? state.lastRequest : undefined;
1728
+ };
1729
+ const getCurrentPage = (stateManager) => {
1730
+ const paginationInfo = getPaginationInfo(stateManager);
1731
+ return paginationInfo ? paginationInfo.currentPage : 0;
1732
+ };
1733
+ const getLastPage = (stateManager, pageSize) => {
1734
+ const paginationInfo = getPaginationInfo(stateManager);
1735
+ return paginationInfo ? Math.ceil(paginationInfo.total / pageSize) : 0;
1736
+ };
1737
+ const hasMorePages = (stateManager) => {
1738
+ const paginationInfo = getPaginationInfo(stateManager);
1739
+ if (paginationInfo && paginationInfo.hasMore) {
1740
+ return true;
1741
+ }
1742
+ return false;
1743
+ };
1744
+ const hasPreviousPages = (stateManager) => {
1745
+ const paginationInfo = getPaginationInfo(stateManager);
1746
+ return paginationInfo ? paginationInfo.currentPage > 0 : false;
1747
+ };
1748
+
1749
+ class UnitMetadataReducerImpl {
1750
+ constructor() {
1751
+ this.sliceName = "unitMetadata";
1752
+ }
1753
+ reduce(_stateManager, currentState, action) {
1754
+ if (action.type === Action.METADATA_LOADED) {
1755
+ return action.payload;
1756
+ }
1757
+ return currentState;
1758
+ }
1759
+ }
1760
+ const UnitMetadataReducer = new UnitMetadataReducerImpl();
1761
+ const getMetadata = (stateManager) => {
1762
+ return stateManager.select(UnitMetadataReducer.sliceName, (state) => state);
1763
+ };
1764
+ const getField = (stateManager, fieldName) => {
1765
+ const md = getMetadata(stateManager);
1766
+ return md ? md.fields.find(fmd => fmd.name === fieldName) : undefined;
1767
+ };
1768
+
1769
+ class HistReducerImpl {
1770
+ constructor() {
1771
+ this.sliceName = "";
1772
+ }
1773
+ reduce(stateManager, _currentState, action) {
1774
+ switch (action.type) {
1775
+ case Action.DATA_SAVED:
1776
+ case Action.EDITION_CANCELED:
1777
+ stateManager.clearUndo();
1778
+ break;
1779
+ case Action.CHANGE_UNDONE:
1780
+ stateManager.undo();
1781
+ break;
1782
+ case Action.CHANGE_REDONE:
1783
+ stateManager.redo();
1784
+ break;
1785
+ }
1786
+ }
1787
+ }
1788
+ const HistReducer = new HistReducerImpl();
1789
+ const canUndo = (stateManager) => {
1790
+ return stateManager.canUndo();
1791
+ };
1792
+ const canRedo = (stateManager) => {
1793
+ return stateManager.canRedo();
1794
+ };
1795
+
1796
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1797
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1798
+ return new (P || (P = Promise))(function (resolve, reject) {
1799
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1800
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1801
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1802
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1803
+ });
1804
+ };
1805
+ class DataUnit {
1806
+ constructor(name) {
1807
+ this._name = name;
1808
+ this._pageSize = 0;
1809
+ this._stateManager = new StateManager([
1810
+ HistReducer,
1811
+ UnitMetadataReducer,
1812
+ LoadingControlReducer,
1813
+ RecordsReducer,
1814
+ RemovedRecordsReducer,
1815
+ AddedRecordsReducer,
1816
+ SelectionReducer,
1817
+ ChangesReducer,
1818
+ WaitingChangesReducer,
1819
+ CurrentRecordsReducer
1820
+ ]);
1821
+ this._observers = [];
1822
+ this._filterProviders = new Map();
1823
+ this._sortingProvider = undefined;
1824
+ this._interceptors = [];
1825
+ }
1826
+ get name() {
1827
+ return this._name;
1828
+ }
1829
+ // Métodos privados
1830
+ validateAndTypeValue(fieldName, newValue) {
1831
+ const descriptor = this.getField(fieldName);
1832
+ return descriptor ? convertType(descriptor.dataType, newValue) : newValue;
1833
+ }
1834
+ getFilters() {
1835
+ let filters = undefined;
1836
+ this._filterProviders.forEach(p => {
1837
+ const f = p.getFilter(this.name);
1838
+ if (f) {
1839
+ filters = (filters || []).concat(f);
1840
+ }
1841
+ });
1842
+ return filters;
1843
+ }
1844
+ getSort() {
1845
+ return this._sortingProvider ? this._sortingProvider.getSort(this._name) : undefined;
1846
+ }
1847
+ getFielterProviderKey(provider) {
1848
+ if (provider.getKey) {
1849
+ return provider.getKey();
1850
+ }
1851
+ return StringUtils.hashCode(provider.getFilter.toString());
1852
+ }
1853
+ executeLoadData(request, executionCtx) {
1854
+ return new Promise((resolve, fail) => __awaiter(this, void 0, void 0, function* () {
1855
+ if (yield this.dispatchAction(Action.LOADING_DATA, request, executionCtx)) {
1856
+ if (this.dataLoader) {
1857
+ this.dataLoader(this, request).then(response => {
1858
+ this.dispatchAction(Action.DATA_LOADED, response, executionCtx);
1859
+ resolve(response);
1860
+ }).catch(error => {
1861
+ const { errorCode } = error;
1862
+ fail(new ErrorException("Problema carregando registros", error, errorCode));
1863
+ });
1864
+ }
1865
+ }
1866
+ }));
1867
+ }
1868
+ // Loaders
1869
+ loadMetadata(executionCtx) {
1870
+ return __awaiter(this, void 0, void 0, function* () {
1871
+ if (yield this.dispatchAction(Action.LOADING_METADATA, undefined, executionCtx)) {
1872
+ return new Promise((resolve, fail) => {
1873
+ if (this.metadataLoader) {
1874
+ this.metadataLoader(this).then(metadata => {
1875
+ this.metadata = metadata;
1876
+ resolve(this.metadata);
1877
+ }).catch(error => {
1878
+ const { errorCode } = error;
1879
+ fail(new ErrorException("Problema carregando metadados", error, errorCode));
1880
+ });
1881
+ }
1882
+ });
1883
+ }
1884
+ });
1885
+ }
1886
+ loadData(quickFilter, executionCtx) {
1887
+ return __awaiter(this, void 0, void 0, function* () {
1888
+ const loadDataRequest = {
1889
+ quickFilter,
1890
+ filters: this.getFilters(),
1891
+ sort: this.getSort()
1892
+ };
1893
+ if (this._pageSize > 0) {
1894
+ loadDataRequest.limit = this._pageSize;
1895
+ loadDataRequest.offset = 0;
1896
+ }
1897
+ return this.executeLoadData(loadDataRequest, executionCtx);
1898
+ });
1899
+ }
1900
+ gotoPage(page, executionCtx) {
1901
+ return __awaiter(this, void 0, void 0, function* () {
1902
+ let request = getCurrentRequest(this._stateManager);
1903
+ if (!request) {
1904
+ request = {
1905
+ filters: this.getFilters(),
1906
+ sort: this.getSort()
1907
+ };
1908
+ }
1909
+ if (page >= 0 && page <= getLastPage(this._stateManager, this._pageSize)) {
1910
+ return this.executeLoadData(Object.assign(Object.assign({}, request), { limit: this._pageSize, offset: page * this._pageSize }), executionCtx);
1911
+ }
1912
+ });
1913
+ }
1914
+ nextPage(executionCtx) {
1915
+ return __awaiter(this, void 0, void 0, function* () {
1916
+ return this.gotoPage(getCurrentPage(this._stateManager) + 1, executionCtx);
1917
+ });
1918
+ }
1919
+ previousPage(executionCtx) {
1920
+ return __awaiter(this, void 0, void 0, function* () {
1921
+ return this.gotoPage(getCurrentPage(this._stateManager) - 1, executionCtx);
1922
+ });
1923
+ }
1924
+ saveData(executionCtx) {
1925
+ return __awaiter(this, void 0, void 0, function* () {
1926
+ const blockingWaitingChanges = getBlockingWaitingChanges(this._stateManager);
1927
+ if (blockingWaitingChanges && blockingWaitingChanges.size > 0) {
1928
+ const [field, waitingChange] = blockingWaitingChanges.entries().next().value;
1929
+ return Promise.reject(new WaitingChangeException("Aguardando alteração de campo", waitingChange.waitmessage));
1930
+ }
1931
+ else {
1932
+ if (isDirty(this._stateManager)) {
1933
+ if (yield this.dispatchAction(Action.SAVING_DATA, undefined, executionCtx)) {
1934
+ const promisses = getWaitingChangePromisses(this._stateManager);
1935
+ return new Promise((resolve, fail) => {
1936
+ Promise.all(promisses || []).then(() => {
1937
+ if (this.saveLoader) {
1938
+ const changes = getChangesToSave(this._name, this._stateManager);
1939
+ this.saveLoader(this, changes).then(records => {
1940
+ this.dispatchAction(Action.DATA_SAVED, { changes, records }, executionCtx);
1941
+ resolve();
1942
+ }).catch(cause => {
1943
+ const { errorCode } = cause;
1944
+ fail(new ErrorException("Erro salvando alterações", cause, errorCode));
1945
+ });
1946
+ }
1947
+ else {
1948
+ resolve();
1949
+ }
1950
+ });
1951
+ });
1952
+ }
1953
+ }
1954
+ }
1955
+ return Promise.resolve();
1956
+ });
1957
+ }
1958
+ removeSelectedRecords(buffered = false) {
1959
+ return __awaiter(this, void 0, void 0, function* () {
1960
+ const selection = getSelection(this._stateManager);
1961
+ if (selection) {
1962
+ const records = this.getSelectedRecords() || [];
1963
+ return this.removeRecords(selection, records, buffered);
1964
+ }
1965
+ return Promise.resolve(selection);
1966
+ });
1967
+ }
1968
+ removeRecords(recordIds, cachedRecords, buffered = false, executionCtx) {
1969
+ return __awaiter(this, void 0, void 0, function* () {
1970
+ if (recordIds) {
1971
+ if (buffered || !this.removeLoader) {
1972
+ this.dispatchAction(Action.RECORDS_REMOVED, { records: recordIds, cachedRecords, buffered: true }, executionCtx);
1973
+ }
1974
+ else {
1975
+ if (yield this.dispatchAction(Action.REMOVING_RECORDS, undefined, executionCtx)) {
1976
+ return new Promise((resolve, fail) => {
1977
+ if (this.removeLoader) {
1978
+ this.removeLoader(this, recordIds).then(removedIds => {
1979
+ let currentIndex = 0;
1980
+ const removedIndex = [];
1981
+ const currentRecords = getCurrentRecords(this._stateManager);
1982
+ currentRecords.forEach((value, key) => {
1983
+ if (removedIds.includes(key)) {
1984
+ removedIndex.push(currentIndex);
1985
+ }
1986
+ currentIndex++;
1987
+ });
1988
+ this.dispatchAction(Action.RECORDS_REMOVED, { records: removedIds, cachedRecords, removedIndex, buffered: false }, executionCtx);
1989
+ resolve(removedIds);
1990
+ }).catch(error => {
1991
+ const { errorCode } = error;
1992
+ fail(new ErrorException("Problema removendo registros", error, errorCode));
1993
+ });
1994
+ }
1995
+ });
1996
+ }
1997
+ }
1998
+ }
1999
+ return Promise.resolve(recordIds);
2000
+ });
2001
+ }
2002
+ // API
2003
+ valueFromString(fieldName, value) {
2004
+ const descriptor = this.getField(fieldName);
2005
+ return descriptor ? convertType(descriptor.dataType, value) : value;
2006
+ }
2007
+ valueToString(fieldName, value) {
2008
+ const descriptor = this.getField(fieldName);
2009
+ return toString(descriptor === null || descriptor === void 0 ? void 0 : descriptor.dataType, value);
2010
+ }
2011
+ addInterceptor(interceptor) {
2012
+ this._interceptors.push(interceptor);
2013
+ }
2014
+ removeInterceptor(interceptor) {
2015
+ this._interceptors = this._interceptors.filter(i => i !== interceptor);
2016
+ }
2017
+ addFilterProvider(provider) {
2018
+ this._filterProviders.set(this.getFielterProviderKey(provider), provider);
2019
+ }
2020
+ getPaginationInfo() {
2021
+ return getPaginationInfo(this._stateManager);
2022
+ }
2023
+ set sortingProvider(provider) {
2024
+ this._sortingProvider = provider;
2025
+ }
2026
+ set metadata(md) {
2027
+ this.dispatchAction(Action.METADATA_LOADED, md, undefined);
2028
+ }
2029
+ get metadata() {
2030
+ return getMetadata(this._stateManager);
2031
+ }
2032
+ set records(r) {
2033
+ this.dispatchAction(Action.DATA_LOADED, { records: this.records }, undefined);
2034
+ }
2035
+ get records() {
2036
+ const records = getCurrentRecords(this._stateManager);
2037
+ return records ? Array.from(records.values()) : [];
2038
+ }
2039
+ set pageSize(size) {
2040
+ this._pageSize = size;
2041
+ }
2042
+ get pageSize() {
2043
+ return this._pageSize;
2044
+ }
2045
+ getModifiedRecords() {
2046
+ const modified = getModifiedRecords(this._stateManager);
2047
+ return modified || [];
2048
+ }
2049
+ getField(fieldName) {
2050
+ return getField(this._stateManager, fieldName);
2051
+ }
2052
+ addRecord(executionCtx) {
2053
+ this.dispatchAction(Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}]), executionCtx);
2054
+ }
2055
+ copySelected(executionCtx) {
2056
+ const selectedRecords = this.getSelectedRecords();
2057
+ if (selectedRecords) {
2058
+ this.dispatchAction(Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords), executionCtx);
2059
+ }
2060
+ }
2061
+ waitingForChange(fieldName) {
2062
+ return isWaiting(this._stateManager, fieldName);
2063
+ }
2064
+ getFieldValue(fieldName) {
2065
+ return getFieldValue(this._stateManager, fieldName);
2066
+ }
2067
+ setFieldValue(fieldName, newValue, records) {
2068
+ const typedValue = this.validateAndTypeValue(fieldName, newValue);
2069
+ const currentValue = this.getFieldValue(fieldName);
2070
+ if (currentValue !== typedValue) {
2071
+ this.dispatchAction(Action.DATA_CHANGED, { [fieldName]: typedValue, records }, undefined);
2072
+ }
2073
+ }
2074
+ startChange(fieldName, waitingChange) {
2075
+ this.dispatchAction(Action.CHANGING_DATA, { [fieldName]: waitingChange }, undefined);
2076
+ }
2077
+ cancelWaitingChange(fieldName) {
2078
+ this.dispatchAction(Action.WAITING_CHANGE_CANCELED, { fieldName }, undefined);
2079
+ }
2080
+ getSelection() {
2081
+ return getSelection(this._stateManager);
2082
+ }
2083
+ setSelection(selection, executionCtx) {
2084
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection }, executionCtx);
2085
+ }
2086
+ selectFirst(executionCtx) {
2087
+ if (this.records.length > 0) {
2088
+ this.setSelectionByIndex([0], executionCtx);
2089
+ }
2090
+ }
2091
+ selectLast(executionCtx) {
2092
+ if (this.records.length > 0) {
2093
+ this.setSelectionByIndex([this.records.length - 1], executionCtx);
2094
+ }
2095
+ }
2096
+ setSelectionByIndex(selection, executionCtx) {
2097
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "index", selection }, executionCtx);
2098
+ }
2099
+ getSelectedRecords() {
2100
+ const selection = this.getSelection();
2101
+ if (selection) {
2102
+ const currentRecords = this.records;
2103
+ return currentRecords === null || currentRecords === void 0 ? void 0 : currentRecords.filter(r => selection.includes(r.__record__id__));
2104
+ }
2105
+ }
2106
+ nextRecord(executionCtx) {
2107
+ if (!hasNext(this._stateManager)) {
2108
+ if (hasMorePages(this._stateManager)) {
2109
+ this.nextPage({
2110
+ before: act => {
2111
+ if (executionCtx && executionCtx.before) {
2112
+ act = executionCtx.before(act);
2113
+ }
2114
+ return act;
2115
+ },
2116
+ after: act => {
2117
+ this.selectFirst(executionCtx);
2118
+ }
2119
+ });
2120
+ }
2121
+ }
2122
+ else {
2123
+ this.dispatchAction(Action.NEXT_SELECTED, undefined, executionCtx);
2124
+ }
2125
+ }
2126
+ previousRecord(executionCtx) {
2127
+ if (!hasPrevious(this._stateManager)) {
2128
+ if (hasPreviousPages(this._stateManager)) {
2129
+ this.previousPage({
2130
+ before: act => {
2131
+ if (executionCtx && executionCtx.before) {
2132
+ act = executionCtx.before(act);
2133
+ }
2134
+ return act;
2135
+ },
2136
+ after: act => {
2137
+ this.selectLast(executionCtx);
2138
+ }
2139
+ });
2140
+ }
2141
+ }
2142
+ else {
2143
+ this.dispatchAction(Action.PREVIOUS_SELECTED, undefined, executionCtx);
2144
+ }
2145
+ }
2146
+ cancelEdition(executionCtx) {
2147
+ this.dispatchAction(Action.EDITION_CANCELED, undefined, executionCtx);
2148
+ }
2149
+ isDirty() {
2150
+ return isDirty(this._stateManager);
2151
+ }
2152
+ hasDirtyRecords() {
2153
+ return hasDirtyRecords(this._stateManager);
2154
+ }
2155
+ hasNext() {
2156
+ let result = hasNext(this._stateManager);
2157
+ if (!result) {
2158
+ result = hasMorePages(this._stateManager);
2159
+ }
2160
+ return result;
2161
+ }
2162
+ hasPrevious() {
2163
+ let result = hasPrevious(this._stateManager);
2164
+ if (!result) {
2165
+ result = hasPreviousPages(this._stateManager);
2166
+ }
2167
+ return result;
2168
+ }
2169
+ canUndo() {
2170
+ return canUndo(this._stateManager);
2171
+ }
2172
+ canRedo() {
2173
+ return canRedo(this._stateManager);
2174
+ }
2175
+ undo(executionCtx) {
2176
+ this.dispatchAction(Action.CHANGE_UNDONE, undefined, executionCtx);
2177
+ }
2178
+ redo(executionCtx) {
2179
+ this.dispatchAction(Action.CHANGE_REDONE, undefined, executionCtx);
2180
+ }
2181
+ toString() {
2182
+ return this.name;
2183
+ }
2184
+ // Actions / State manager
2185
+ dispatchAction(actionType, payload, executionCtx) {
2186
+ return __awaiter(this, void 0, void 0, function* () {
2187
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
2188
+ let action = new DataUnitAction(actionType, payload);
2189
+ if (executionCtx && executionCtx.before) {
2190
+ action = executionCtx.before(action);
2191
+ }
2192
+ if (action && this._interceptors && this._interceptors.length > 0) {
2193
+ action = yield this.intercept(action, this._interceptors.values());
2194
+ }
2195
+ if (action) {
2196
+ this.doDispatchAction(action);
2197
+ if (executionCtx && executionCtx.after) {
2198
+ executionCtx.after(action);
2199
+ }
2200
+ resolve(true);
2201
+ }
2202
+ else {
2203
+ resolve(false);
2204
+ }
2205
+ }));
2206
+ });
2207
+ }
2208
+ intercept(action, interceptors) {
2209
+ return __awaiter(this, void 0, void 0, function* () {
2210
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
2211
+ let ite;
2212
+ while (action && !(ite = interceptors.next()).done) {
2213
+ action = yield ite.value.interceptAction(action);
2214
+ }
2215
+ resolve(action);
2216
+ }));
2217
+ });
2218
+ }
2219
+ doDispatchAction(action) {
2220
+ this._stateManager.process(action);
2221
+ this._observers.forEach(f => {
2222
+ /*
2223
+ if some observer throws exceptions,
2224
+ should be continued
2225
+ */
2226
+ try {
2227
+ f(action);
2228
+ }
2229
+ catch (e) {
2230
+ console.warn("[DataUnit] error while call observer", e);
2231
+ }
2232
+ });
2233
+ }
2234
+ subscribe(observer) {
2235
+ this._observers.push(observer);
2236
+ }
2237
+ unsubscribe(observer) {
2238
+ this._observers = this._observers.filter(f => f !== observer);
2239
+ }
2240
+ }
2241
+ var ChangeOperation;
2242
+ (function (ChangeOperation) {
2243
+ ChangeOperation["INSERT"] = "INSERT";
2244
+ ChangeOperation["COPY"] = "COPY";
2245
+ ChangeOperation["UPDATE"] = "UPDATE";
2246
+ ChangeOperation["DELETE"] = "DELETE";
2247
+ })(ChangeOperation || (ChangeOperation = {}));
2248
+ class Change {
2249
+ constructor(dataUnit, record, updates, operation, sourceId) {
2250
+ this.dataUnit = dataUnit;
2251
+ this.record = record;
2252
+ this.sourceId = sourceId;
2253
+ this.updatingFields = updates;
2254
+ this._operation = operation;
2255
+ }
2256
+ get operation() {
2257
+ return this._operation.toString();
2258
+ }
2259
+ isInsert() {
2260
+ return this._operation === ChangeOperation.INSERT;
2261
+ }
2262
+ isCopy() {
2263
+ return this._operation === ChangeOperation.COPY;
2264
+ }
2265
+ isDelete() {
2266
+ return this._operation === ChangeOperation.DELETE;
2267
+ }
2268
+ isUpdate() {
2269
+ return this._operation === ChangeOperation.UPDATE;
2270
+ }
2271
+ }
2272
+
2273
+ var SortMode;
2274
+ (function (SortMode) {
2275
+ SortMode["ASC"] = "ASC";
2276
+ SortMode["DESC"] = "DESC";
2277
+ })(SortMode || (SortMode = {}));
2278
+ var DependencyType;
2279
+ (function (DependencyType) {
2280
+ DependencyType["SEARCHING"] = "SEARCHING";
2281
+ DependencyType["REQUIREMENT"] = "REQUIREMENT";
2282
+ DependencyType["VISIBILITY"] = "REQUIREMENT";
2283
+ })(DependencyType || (DependencyType = {}));
2284
+ var UserInterface;
2285
+ (function (UserInterface) {
2286
+ UserInterface["FILE"] = "FILE";
2287
+ UserInterface["IMAGE"] = "IMAGE";
2288
+ UserInterface["DATE"] = "DATE";
2289
+ UserInterface["DATETIME"] = "DATETIME";
2290
+ UserInterface["TIME"] = "TIME";
2291
+ UserInterface["ELAPSEDTIME"] = "ELAPSEDTIME";
2292
+ UserInterface["CHECKBOX"] = "CHECKBOX";
2293
+ UserInterface["SWITCH"] = "SWITCH";
2294
+ UserInterface["OPTIONSELECTOR"] = "OPTIONSELECTOR";
2295
+ UserInterface["DECIMALNUMBER"] = "DECIMALNUMBER";
2296
+ UserInterface["INTEGERNUMBER"] = "INTEGERNUMBER";
2297
+ UserInterface["SEARCH"] = "SEARCH";
2298
+ UserInterface["SHORTTEXT"] = "SHORTTEXT";
2299
+ UserInterface["PASSWORD"] = "PASSWORD";
2300
+ UserInterface["MASKEDTEXT"] = "MASKEDTEXT";
2301
+ UserInterface["LONGTEXT"] = "LONGTEXT";
2302
+ UserInterface["HTML"] = "HTML";
2303
+ })(UserInterface || (UserInterface = {}));
2304
+
2305
+ class ApplicationContext {
2306
+ static getContextValue(key) {
2307
+ return ApplicationContext.getCtx()[key];
2308
+ }
2309
+ static setContextValue(key, value) {
2310
+ ApplicationContext.getCtx()[key] = value;
2311
+ }
2312
+ static getCtx() {
2313
+ let ctx = window.___snkcore___ctx___;
2314
+ if (!ctx) {
2315
+ ctx = {};
2316
+ window.___snkcore___ctx___ = ctx;
2317
+ }
2318
+ return ctx;
2319
+ }
2320
+ }
2321
+
2322
+ class ReadyUtil {
2323
+ clean() {
2324
+ this.resolve = undefined;
2325
+ this.promise = undefined;
2326
+ }
2327
+ start() {
2328
+ if (!this.promise)
2329
+ this.promise = new Promise((accept) => {
2330
+ this.resolve = () => accept(true);
2331
+ });
2332
+ }
2333
+ end() {
2334
+ this.resolve && this.resolve();
2335
+ }
2336
+ whenReady() {
2337
+ this.start();
2338
+ return new Promise((accept) => {
2339
+ this.promise.then(() => {
2340
+ accept(true);
2341
+ this.clean();
2342
+ });
2343
+ });
2344
+ }
2345
+ }
2346
+
2347
+ class ObjectUtils {
2348
+ static copy(data) {
2349
+ return this.stringToObject(this.objectToString(data));
2350
+ }
2351
+ static objectToString(data) {
2352
+ return JSON.stringify(data);
2353
+ }
2354
+ static stringToObject(data) {
2355
+ return JSON.parse(data);
2356
+ }
2357
+ }
2358
+
2359
+ class WarningException extends Error {
2360
+ constructor(title, message, errorCode = "") {
2361
+ super(message);
2362
+ this.title = title;
2363
+ this.message = message;
2364
+ this.errorCode = errorCode;
2365
+ }
2366
+ }
2367
+
2368
+ class ErrorTracking {
2369
+ static init() {
2370
+ const rollbar = window.Rollbar;
2371
+ if (rollbar) {
2372
+ rollbar.configure({
2373
+ checkIgnore: function (isUncaught, args, payload) {
2374
+ return args[1] ? ErrorTracking.isInternalException(args[1]) : false;
2375
+ }
2376
+ });
2377
+ }
2378
+ }
2379
+ static isInternalException(error) {
2380
+ return (error instanceof ErrorException || error instanceof WaitingChangeException || error instanceof WarningException);
2381
+ }
2382
+ }
2383
+
2384
+ export { Action as A, ChangeOperation as C, DataUnit as D, ErrorException as E, FloatingManager as F, ObjectUtils as O, StringUtils as S, UserInterface as U, WarningException as W, ApplicationContext as a, DataType as b, DateUtils as c, WaitingChangeException as d, DependencyType as e, ErrorTracking as f, ArrayUtils as g, toString as t };