@sankhyalabs/sankhyablocks 8.16.0-dev.99 → 8.16.0-ms.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (157) hide show
  1. package/dist/cjs/{ClientSideExporterProvider-cc82b68a.js → ClientSideExporterProvider-2f5f350c.js} +21 -55
  2. package/dist/cjs/{ConfigStorage-2235f35e.js → ConfigStorage-d024aec8.js} +2 -2
  3. package/dist/cjs/{DataFetcher-875371e9.js → DataFetcher-65879b2c.js} +1 -1
  4. package/dist/cjs/ISave-e91b70a7.js +9 -0
  5. package/dist/cjs/{SnkFormConfigManager-6637cd6b.js → SnkFormConfigManager-c11d8468.js} +2 -2
  6. package/dist/cjs/{auth-fetcher-abad589f.js → auth-fetcher-8480751c.js} +1 -1
  7. package/dist/cjs/{dataunit-fetcher-b95768e8.js → dataunit-fetcher-449d51a3.js} +1 -1
  8. package/dist/cjs/{form-config-fetcher-db332748.js → form-config-fetcher-90126e4c.js} +1 -15
  9. package/dist/cjs/index-f9e81701.js +2 -2
  10. package/dist/cjs/loader.cjs.js +1 -1
  11. package/dist/cjs/{ISave-62fbb1dd.js → pesquisa-fetcher-5c583c93.js} +1 -9
  12. package/dist/cjs/pesquisa-grid_2.cjs.entry.js +6 -5
  13. package/dist/cjs/sankhyablocks.cjs.js +1 -1
  14. package/dist/cjs/{snk-actions-button_7.cjs.entry.js → snk-actions-button_5.cjs.entry.js} +6 -65
  15. package/dist/cjs/snk-application.cjs.entry.js +7 -50
  16. package/dist/cjs/snk-attach.cjs.entry.js +6 -5
  17. package/dist/cjs/snk-config-options_3.cjs.entry.js +4 -4
  18. package/dist/cjs/snk-configurator.cjs.entry.js +1 -8
  19. package/dist/cjs/snk-crud.cjs.entry.js +7 -7
  20. package/dist/cjs/snk-data-exporter.cjs.entry.js +7 -6
  21. package/dist/cjs/{snk-data-unit-33937ffe.js → snk-data-unit-bbd384bf.js} +1 -1
  22. package/dist/cjs/snk-data-unit.cjs.entry.js +3 -3
  23. package/dist/cjs/snk-detail-view.cjs.entry.js +10 -10
  24. package/dist/cjs/snk-filter-bar_4.cjs.entry.js +3 -3
  25. package/dist/cjs/snk-filter-modal-item.cjs.entry.js +3 -3
  26. package/dist/cjs/snk-grid.cjs.entry.js +7 -6
  27. package/dist/cjs/{snk-guides-viewer-0e4f3b1a.js → snk-guides-viewer-5396062f.js} +7 -6
  28. package/dist/cjs/snk-guides-viewer.cjs.entry.js +8 -7
  29. package/dist/cjs/snk-personalized-filter.cjs.entry.js +3 -3
  30. package/dist/cjs/snk-pesquisa.cjs.entry.js +12 -11
  31. package/dist/cjs/snk-simple-crud.cjs.entry.js +9 -9
  32. package/dist/collection/collection-manifest.json +0 -2
  33. package/dist/collection/components/snk-application/snk-application.js +0 -41
  34. package/dist/collection/components/snk-configurator/snk-configurator.js +1 -26
  35. package/dist/collection/components/snk-crud/snk-crud.js +1 -20
  36. package/dist/collection/components/snk-crud/subcomponents/snk-detail-view/snk-detail-view.css +1 -10
  37. package/dist/collection/components/snk-crud/subcomponents/snk-detail-view/snk-detail-view.js +1 -25
  38. package/dist/collection/components/snk-crud/subcomponents/snk-guides-viewer.js +1 -1
  39. package/dist/collection/components/snk-data-exporter/interfaces/IExporterProvider.js +16 -51
  40. package/dist/collection/components/snk-data-exporter/utils/ParserExport.js +1 -1
  41. package/dist/collection/components/snk-simple-crud/snk-simple-crud.js +1 -20
  42. package/dist/collection/lib/http/data-fetcher/DataFetcher.js +1 -1
  43. package/dist/collection/lib/http/data-fetcher/fetchers/form-config-fetcher.js +0 -14
  44. package/dist/components/ContinuousInsertUtils.js +16 -51
  45. package/dist/components/DataFetcher.js +1 -1
  46. package/dist/components/form-config-fetcher.js +0 -14
  47. package/dist/components/index.d.ts +0 -2
  48. package/dist/components/index.js +0 -2
  49. package/dist/components/snk-application2.js +0 -45
  50. package/dist/components/snk-attach2.js +22 -34
  51. package/dist/components/snk-configurator2.js +2 -22
  52. package/dist/components/snk-crud.js +62 -76
  53. package/dist/components/snk-data-exporter2.js +1 -1
  54. package/dist/components/snk-detail-view2.js +86 -110
  55. package/dist/components/snk-simple-crud2.js +19 -33
  56. package/dist/esm/{ClientSideExporterProvider-8191676b.js → ClientSideExporterProvider-3537805a.js} +21 -55
  57. package/dist/esm/{ConfigStorage-9bd805d6.js → ConfigStorage-373bb440.js} +2 -2
  58. package/dist/esm/{DataFetcher-ecf5f903.js → DataFetcher-5221b992.js} +1 -1
  59. package/dist/esm/ISave-d8c8bc59.js +9 -0
  60. package/dist/esm/{SnkFormConfigManager-fbc6a9a8.js → SnkFormConfigManager-5022f87f.js} +2 -2
  61. package/dist/esm/{auth-fetcher-07d33333.js → auth-fetcher-e32fe8a4.js} +1 -1
  62. package/dist/esm/{dataunit-fetcher-ed6e65ef.js → dataunit-fetcher-91b094f2.js} +1 -1
  63. package/dist/esm/{form-config-fetcher-ac17cff4.js → form-config-fetcher-126e2471.js} +1 -15
  64. package/dist/esm/index-a7d3d3f1.js +2 -2
  65. package/dist/esm/loader.js +1 -1
  66. package/dist/esm/{ISave-7d546dce.js → pesquisa-fetcher-4284f2a3.js} +2 -10
  67. package/dist/esm/pesquisa-grid_2.entry.js +5 -4
  68. package/dist/esm/sankhyablocks.js +1 -1
  69. package/dist/esm/{snk-actions-button_7.entry.js → snk-actions-button_5.entry.js} +8 -65
  70. package/dist/esm/snk-application.entry.js +6 -49
  71. package/dist/esm/snk-attach.entry.js +6 -5
  72. package/dist/esm/snk-config-options_3.entry.js +4 -4
  73. package/dist/esm/snk-configurator.entry.js +1 -8
  74. package/dist/esm/snk-crud.entry.js +7 -7
  75. package/dist/esm/snk-data-exporter.entry.js +7 -6
  76. package/dist/esm/{snk-data-unit-6258b8ae.js → snk-data-unit-b03bb5cf.js} +1 -1
  77. package/dist/esm/snk-data-unit.entry.js +3 -3
  78. package/dist/esm/snk-detail-view.entry.js +10 -10
  79. package/dist/esm/snk-filter-bar_4.entry.js +3 -3
  80. package/dist/esm/snk-filter-modal-item.entry.js +3 -3
  81. package/dist/esm/snk-grid.entry.js +7 -6
  82. package/dist/esm/{snk-guides-viewer-80a8709c.js → snk-guides-viewer-749d027c.js} +7 -6
  83. package/dist/esm/snk-guides-viewer.entry.js +8 -7
  84. package/dist/esm/snk-personalized-filter.entry.js +3 -3
  85. package/dist/esm/snk-pesquisa.entry.js +5 -4
  86. package/dist/esm/snk-simple-crud.entry.js +9 -9
  87. package/dist/sankhyablocks/p-13391b3d.entry.js +1 -0
  88. package/dist/sankhyablocks/p-1435701f.js +26 -0
  89. package/dist/sankhyablocks/{p-13f17dab.js → p-19dc71e9.js} +1 -1
  90. package/dist/sankhyablocks/{p-340e2447.entry.js → p-1cf39cfd.entry.js} +1 -1
  91. package/dist/sankhyablocks/p-21749402.js +1 -0
  92. package/dist/sankhyablocks/{p-abd9681c.js → p-23b47a92.js} +1 -1
  93. package/dist/sankhyablocks/{p-7e0a0aae.js → p-3653374d.js} +1 -1
  94. package/dist/sankhyablocks/p-389ba782.entry.js +1 -0
  95. package/dist/sankhyablocks/p-3ba431c9.js +1 -0
  96. package/dist/sankhyablocks/{p-108fee57.js → p-41c3bee5.js} +2 -2
  97. package/dist/sankhyablocks/{p-2746d606.entry.js → p-44efbeed.entry.js} +1 -1
  98. package/dist/sankhyablocks/p-4be6e0e7.entry.js +1 -0
  99. package/dist/sankhyablocks/p-4c9adf1c.entry.js +1 -0
  100. package/dist/sankhyablocks/p-4d87cd45.entry.js +1 -0
  101. package/dist/sankhyablocks/p-4fa79d68.entry.js +1 -0
  102. package/dist/sankhyablocks/p-5dd7f4c7.js +1 -0
  103. package/dist/sankhyablocks/p-6234bda8.entry.js +1 -0
  104. package/dist/sankhyablocks/p-647f9830.entry.js +11 -0
  105. package/dist/sankhyablocks/p-7b87d1a8.js +1 -0
  106. package/dist/sankhyablocks/{p-0bcd4757.entry.js → p-82ee6dc3.entry.js} +1 -1
  107. package/dist/sankhyablocks/{p-5fea0816.entry.js → p-974fdba6.entry.js} +1 -1
  108. package/dist/sankhyablocks/p-ad5e4f9d.entry.js +1 -0
  109. package/dist/sankhyablocks/p-b2de1bcc.entry.js +1 -0
  110. package/dist/sankhyablocks/{p-f467153c.entry.js → p-c021a3a9.entry.js} +1 -1
  111. package/dist/sankhyablocks/p-ca316523.entry.js +1 -0
  112. package/dist/sankhyablocks/{p-5a7e18f4.js → p-d62228fb.js} +1 -1
  113. package/dist/sankhyablocks/p-ee53b000.entry.js +1 -0
  114. package/dist/sankhyablocks/{p-48729c8c.js → p-f0b9303b.js} +1 -1
  115. package/dist/sankhyablocks/sankhyablocks.esm.js +1 -1
  116. package/dist/types/components/snk-application/snk-application.d.ts +0 -10
  117. package/dist/types/components/snk-configurator/snk-configurator.d.ts +0 -6
  118. package/dist/types/components/snk-crud/snk-crud.d.ts +0 -4
  119. package/dist/types/components/snk-crud/subcomponents/snk-detail-view/snk-detail-view.d.ts +0 -5
  120. package/dist/types/components/snk-data-exporter/interfaces/IExporterProvider.d.ts +0 -7
  121. package/dist/types/components/snk-simple-crud/snk-simple-crud.d.ts +0 -4
  122. package/dist/types/components.d.ts +1 -77
  123. package/dist/types/lib/http/data-fetcher/fetchers/form-config-fetcher.d.ts +0 -6
  124. package/package.json +1 -1
  125. package/react/components.d.ts +0 -2
  126. package/react/components.js +0 -2
  127. package/react/components.js.map +1 -1
  128. package/dist/collection/components/snk-layout-form-config/snk-layout-form-config.css +0 -3
  129. package/dist/collection/components/snk-layout-form-config/snk-layout-form-config.js +0 -73
  130. package/dist/collection/components/snk-layout-form-config/snk-view-representation/snk-view-representation.css +0 -78
  131. package/dist/collection/components/snk-layout-form-config/snk-view-representation/snk-view-representation.js +0 -57
  132. package/dist/collection/lib/configs/LayoutFormConfig.js +0 -25
  133. package/dist/components/snk-layout-form-config.d.ts +0 -11
  134. package/dist/components/snk-layout-form-config.js +0 -6
  135. package/dist/components/snk-layout-form-config2.js +0 -73
  136. package/dist/components/snk-view-representation.d.ts +0 -11
  137. package/dist/components/snk-view-representation.js +0 -6
  138. package/dist/components/snk-view-representation2.js +0 -41
  139. package/dist/sankhyablocks/p-01512409.js +0 -26
  140. package/dist/sankhyablocks/p-02c6dc9f.entry.js +0 -1
  141. package/dist/sankhyablocks/p-35fcf37e.js +0 -1
  142. package/dist/sankhyablocks/p-3a36d4b3.entry.js +0 -1
  143. package/dist/sankhyablocks/p-513af002.entry.js +0 -1
  144. package/dist/sankhyablocks/p-950e3cbe.entry.js +0 -1
  145. package/dist/sankhyablocks/p-9907cf67.entry.js +0 -1
  146. package/dist/sankhyablocks/p-af58c9d7.entry.js +0 -1
  147. package/dist/sankhyablocks/p-c5acb7ba.entry.js +0 -11
  148. package/dist/sankhyablocks/p-c7c6eab7.entry.js +0 -1
  149. package/dist/sankhyablocks/p-cb9d725a.js +0 -1
  150. package/dist/sankhyablocks/p-d1f04e2c.js +0 -1
  151. package/dist/sankhyablocks/p-d2065bb4.entry.js +0 -1
  152. package/dist/sankhyablocks/p-dc617b0c.entry.js +0 -1
  153. package/dist/sankhyablocks/p-e5d8891d.entry.js +0 -1
  154. package/dist/sankhyablocks/p-f861bfcb.entry.js +0 -1
  155. package/dist/types/components/snk-layout-form-config/snk-layout-form-config.d.ts +0 -15
  156. package/dist/types/components/snk-layout-form-config/snk-view-representation/snk-view-representation.d.ts +0 -10
  157. package/dist/types/lib/configs/LayoutFormConfig.d.ts +0 -11
@@ -1,13 +1,14 @@
1
1
  import { r as registerInstance, h, H as Host, g as getElement } from './index-a7d3d3f1.js';
2
2
  import { ObjectUtils, StringUtils, ElementIDUtils } from '@sankhyalabs/core';
3
- import { P as PesquisaFetcher, b as buildGridMetadata, a as PESQUISA_VIEW_MODE } from './ISave-7d546dce.js';
4
- import './DataFetcher-ecf5f903.js';
3
+ import { P as PesquisaFetcher, b as buildGridMetadata, a as PESQUISA_VIEW_MODE } from './pesquisa-fetcher-4284f2a3.js';
4
+ import './DataFetcher-5221b992.js';
5
5
  import './index-b40568ff.js';
6
+ import './ISave-d8c8bc59.js';
6
7
  import '@sankhyalabs/ezui/dist/collection/utils/constants';
7
8
  import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
8
- import './dataunit-fetcher-ed6e65ef.js';
9
+ import './dataunit-fetcher-91b094f2.js';
9
10
  import './filter-item-type.enum-d45e026f.js';
10
- import './form-config-fetcher-ac17cff4.js';
11
+ import './form-config-fetcher-126e2471.js';
11
12
  import './constants-75abb876.js';
12
13
  import './PrintUtils-3e4ff0f5.js';
13
14
  import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils';
@@ -3,18 +3,19 @@ import { StringUtils, ApplicationContext, ObjectUtils, DataType, UserInterface,
3
3
  import { CSSVarsUtils } from '@sankhyalabs/ezui/dist/collection/utils';
4
4
  import { V as VIEW_MODE, S as SIMPLE_CRUD_MODE } from './constants-75abb876.js';
5
5
  import { T as TaskbarElement } from './taskbar-elements-d2353c64.js';
6
- import './DataFetcher-ecf5f903.js';
7
- import './ISave-7d546dce.js';
8
- import { S as SnkMultiSelectionListDataSource, R as RmPrecisionCustomValueFormatter, b as ContinuousInsertUtils, a as CrudUtils, c as ClientSideExporterProvider } from './ClientSideExporterProvider-8191676b.js';
6
+ import './DataFetcher-5221b992.js';
7
+ import './pesquisa-fetcher-4284f2a3.js';
8
+ import { S as SnkMultiSelectionListDataSource, R as RmPrecisionCustomValueFormatter, b as ContinuousInsertUtils, a as CrudUtils, c as ClientSideExporterProvider } from './ClientSideExporterProvider-3537805a.js';
9
9
  import { P as PresentationMode } from './index-b40568ff.js';
10
+ import './ISave-d8c8bc59.js';
10
11
  import '@sankhyalabs/ezui/dist/collection/utils/constants';
11
12
  import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
12
- import { I as InMemoryLoader } from './dataunit-fetcher-ed6e65ef.js';
13
+ import { I as InMemoryLoader } from './dataunit-fetcher-91b094f2.js';
13
14
  import './filter-item-type.enum-d45e026f.js';
14
- import { F as FormConfigFetcher } from './form-config-fetcher-ac17cff4.js';
15
+ import { F as FormConfigFetcher } from './form-config-fetcher-126e2471.js';
15
16
  import { T as TaskbarProcessor, b as buildFieldSearch, o as openFieldSearch } from './field-search-f8b1d91e.js';
16
- import { C as ConfigStorage } from './ConfigStorage-9bd805d6.js';
17
- import { S as SnkFormConfigManager } from './SnkFormConfigManager-fbc6a9a8.js';
17
+ import { C as ConfigStorage } from './ConfigStorage-373bb440.js';
18
+ import { S as SnkFormConfigManager } from './SnkFormConfigManager-5022f87f.js';
18
19
  import { s as store } from './index-bdf75557.js';
19
20
  import './PrintUtils-3e4ff0f5.js';
20
21
  import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource';
@@ -82,7 +83,6 @@ const SnkSimpleCrud = class {
82
83
  this.ignoreReadOnlyFormFields = false;
83
84
  this.autoFocus = true;
84
85
  this.domainMessagesBuilder = undefined;
85
- this.layoutFormConfig = false;
86
86
  this.autoLoad = undefined;
87
87
  this.outlineMode = false;
88
88
  }
@@ -775,7 +775,7 @@ const SnkSimpleCrud = class {
775
775
  }
776
776
  return (h("snk-data-unit", { ref: ref => this._snkDataUnit = ref, class: "simple-crud__container", dataUnit: this.dataUnit, useCancelConfirm: this.useCancelConfirm, onDataStateChange: evt => this.onDataStateChange(evt), onCancelEdition: this.handleCancelEdit.bind(this), pageSize: this.getPageSize(), onInsertionMode: this.handleDataUnitOnInsertionMode.bind(this), onDataUnitReady: (evt) => this.dataUnitReady.emit(evt.detail), ignoreSaveMessage: this._currentViewMode === VIEW_MODE.GRID, onMessagesBuilderUpdated: evt => this.messagesBuilder = evt.detail, onDataUnitFieldsHidded: this.updateFormConfig.bind(this), domainMessagesBuilder: this.domainMessagesBuilder }, h("header", null, h("slot", { name: "snkSimpleCrudHeader" })), h("section", { class: `ez-box ${this.outlineMode ? 'ez-box--outline' : 'ez-box--shadow'} simple-crud__container-section` }, h("ez-view-stack", { ref: (ref) => this._viewStack = ref, "data-element-id": "simple-crud" }, h("stack-item", null, h("ez-grid", { class: "ez-margin-bottom--large", ref: ref => this._grid = ref, dataUnit: this.dataUnit, config: this.gridConfig, "no-header": true, multipleSelection: this.multipleSelection, onEzDoubleClick: () => this.goToView(VIEW_MODE.FORM), onConfigChange: evt => this.gridConfigChangeHandler(evt), columnfilterDataSource: this.dataUnit.name && this.dataUnit.name.includes(InMemoryLoader.IN_MEMORY_DATA_UNIT_NAME)
777
777
  ? undefined
778
- : this._multiSelectionListDataSource, useEnterLikeTab: this.useEnterLikeTab, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableContinuousInsert: this.enableContinuousInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, outlineMode: this.outlineMode }, this.renderTaskbarContent(), h("div", { slot: "footer" }, h("slot", { name: "snkSimpleCrudFooter" })))), h("stack-item", null, this.renderTaskbarContent(), h("ez-form", { ref: (ref) => this._form = ref, class: `ez-margin-top--large`, dataUnit: this.dataUnit, config: this.getFormConfig(), fieldToFocus: this._fieldToGetFocus, onEzFormSetFields: (evt) => this.handleFormSetFields(evt.detail), onEzFormRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this) }), h("snk-simple-form-config", { ref: (ref) => this._snkSimpleFormConfig = ref, dataUnit: this.dataUnit, onSnkConfigSaved: this.handleFormConfigSaved.bind(this), configName: (_a = this.formLegacyConfigName) !== null && _a !== void 0 ? _a : this.configName })), this.messagesBuilder && h("snk-configurator", { ref: (ref) => this._snkConfigurator = ref, viewMode: this._currentViewMode, messagesBuilder: this.messagesBuilder, onConfigSelected: (evt) => this.goToView(evt.detail), onOpenConfig: (evt) => this.openConfig(evt.detail), showActionButtons: this.showConfiguratorButtons, onSave: evt => this.handleConfiguratorEvent(evt, 'SAVE'), onCancel: evt => this.handleConfiguratorEvent(evt, 'CANCEL'), resourceID: this.resolveResourceID(), customContainerId: this._customContainerId, layoutFormConfig: this.layoutFormConfig })), h("div", { id: `${this._customContainerId}` }, h("slot", { name: "SnkConfigContainerSlot" }))), h("ez-modal", { modalSize: "small", closeEsc: false, closeOutsideClick: false, opened: this._showPopUpGridConfig, onEzCloseModal: () => this.closeGridConfig() }, h("snk-grid-config", { ref: ref => this._snkGridConfig = ref, config: this.gridConfig, "data-element-id": this._element.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME), selectedIndex: 0, configName: this.configName, onConfigChange: (evt) => this.modalConfigChangeHandler(evt), onConfigCancel: () => this.closeGridConfig(), resourceID: this.resolveResourceID() }))));
778
+ : this._multiSelectionListDataSource, useEnterLikeTab: this.useEnterLikeTab, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableContinuousInsert: this.enableContinuousInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, outlineMode: this.outlineMode }, this.renderTaskbarContent(), h("div", { slot: "footer" }, h("slot", { name: "snkSimpleCrudFooter" })))), h("stack-item", null, this.renderTaskbarContent(), h("ez-form", { ref: (ref) => this._form = ref, class: `ez-margin-top--large`, dataUnit: this.dataUnit, config: this.getFormConfig(), fieldToFocus: this._fieldToGetFocus, onEzFormSetFields: (evt) => this.handleFormSetFields(evt.detail), onEzFormRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this) }), h("snk-simple-form-config", { ref: (ref) => this._snkSimpleFormConfig = ref, dataUnit: this.dataUnit, onSnkConfigSaved: this.handleFormConfigSaved.bind(this), configName: (_a = this.formLegacyConfigName) !== null && _a !== void 0 ? _a : this.configName })), this.messagesBuilder && h("snk-configurator", { ref: (ref) => this._snkConfigurator = ref, viewMode: this._currentViewMode, messagesBuilder: this.messagesBuilder, onConfigSelected: (evt) => this.goToView(evt.detail), onOpenConfig: (evt) => this.openConfig(evt.detail), showActionButtons: this.showConfiguratorButtons, onSave: evt => this.handleConfiguratorEvent(evt, 'SAVE'), onCancel: evt => this.handleConfiguratorEvent(evt, 'CANCEL'), resourceID: this.resolveResourceID(), customContainerId: this._customContainerId })), h("div", { id: `${this._customContainerId}` }, h("slot", { name: "SnkConfigContainerSlot" }))), h("ez-modal", { modalSize: "small", closeEsc: false, closeOutsideClick: false, opened: this._showPopUpGridConfig, onEzCloseModal: () => this.closeGridConfig() }, h("snk-grid-config", { ref: ref => this._snkGridConfig = ref, config: this.gridConfig, "data-element-id": this._element.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME), selectedIndex: 0, configName: this.configName, onConfigChange: (evt) => this.modalConfigChangeHandler(evt), onConfigCancel: () => this.closeGridConfig(), resourceID: this.resolveResourceID() }))));
779
779
  }
780
780
  get _element() { return getElement(this); }
781
781
  static get watchers() { return {
@@ -0,0 +1 @@
1
+ import{r as s,h as i,H as t,g as e}from"./p-d2d301a6.js";import{ObjectUtils as r,StringUtils as a,ElementIDUtils as o}from"@sankhyalabs/core";import{P as n,b as l,a as c}from"./p-41c3bee5.js";import"./p-d62228fb.js";import"./p-0f3698af.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-3653374d.js";import"./p-ff1990ad.js";import"./p-1435701f.js";import"./p-1d19a5b0.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";const u=class{constructor(i){s(this,i),this._mdByName={},this._startHighlightTag="<span class='card-item__highlight'>",this._endHighlightTag="</span>",this._specialCharsRegex=/[[.\-\$\+\*,_\&\(\)%\/\\#@!:\|\=\'\"]/gim,this._charsWithAccentuation="ÁÉÍÓÚ_ÃÕ_ÂÊÎÔÛ_ÀÈÌÒÙ_Ü_Ç_áéíóú_ãõ_âêîôû_àèìòù_ü_ç",this._charsWithoutAccentuation="AEIOU_AO_AEIOU_AEIOU_U_C_aeiou_ao_aeiou_aeiou_u_c",this._changeDeboucingTimeout=null,this._limitCharsToSearch=3,this._deboucingTime=450,this._gridDataSource=[],this.pesquisaFetcher=new n,this._itemList=void 0,this._startLoading=!1,this._presentationMode="list",this._currentView=void 0,this.searchLoader=void 0,this.treeLoader=void 0,this.selectItem=void 0,this.entityName=void 0,this.argument=void 0,this.isHierarchyEntity=!1,this.allowsNonAnalytic=!1}observeArgument(){this._textInput&&(this._textInput.value=this.argument)}clearSearch(){this.argument="",this._itemList=void 0}buildDetails(s,i){let t={};for(let e=0;e<s.length;e++){const r=s[e],a=i[r.fieldName];t[r.description]=this.highlightValue(i.__matchFields,r.options&&r.options[a]||a,s,!0)}return t}buildFirstFields(s,i,t=6){return s&&Array.isArray(s)&&s.forEach((s=>{let t=this.removeReference(i,this._mdByName[s]);t&&i.unshift(t)})),i=i.slice(0,t)}doSearch(s){this.searchLoader&&"function"==typeof this.searchLoader&&(this._startLoading=!0,this.searchLoader(s).then((s=>{s&&this.processSearchResponse(s)})).finally((()=>{this._startLoading=!1})))}processSearchResponse(s){let i=(s=r.stringToObject(s.json.$)).descriptionField,t=s.pkField;t&&(this._gridMetadata=l(s),this._gridDataSource=[...s.data],this._pkField=t,this._descriptionField=i,this._itemList=this.buildCardItemList(s,t,i))}buildCardItemList(s,i,t){var e;return null===(e=s.data)||void 0===e?void 0:e.map((e=>{var r;let a=this.filterFieldsMetadata(s,e),o=this.buildFirstFields(e.__matchFields,a);return{key:this.highlightValue(e.__matchFields,null===(r=e[i])||void 0===r?void 0:r.toString(),o,!0),title:t?this.highlightValue(e.__matchFields,e[t],o,!0):"",details:this.buildDetails(o,e)}}))}filterFieldsMetadata(s,i){return s.fieldsMetadata.filter((t=>{let e=!a.isEmpty(i[t.fieldName])&&!1!==t.visible&&"B"!==t.type&&s.pkField!==t.fieldName&&s.descriptionField!==t.fieldName&&(t.isPrimaryKey||!t.isLinkField)&&!("S"===t.type&&"H"===t.presentationType);return e&&(this._mdByName[t.fieldName]=t),("string"!=typeof i[t.fieldName]||!(i[t.fieldName].indexOf("<img")>-1||i[t.fieldName].indexOf("<svg")>-1))&&e}))}removeAtIndex(s,i){if(i>=0&&i<s.length)return s.splice(i,1)[0]}removeReference(s,i){let t=this.indexOf(s,i);return this.removeAtIndex(s,t)}indexOf(s,i){let t=-1;return Array.isArray(s)&&this.find(s,((s,e)=>(t=e,this.equals(i,s)))),t}equals(s,i){return r.objectToString(s)===r.objectToString(i)}find(s,i){if(s)for(let t=0,e=s.length;t<e;t++)if(i(s[t],t,s))return s[t]}highlightValue(s,i,t,e){let r=this.replaceHtmlEntities(i);if(this.argument&&(e||this.isIn(s,t.fieldName))){const s=this.getArgumentNumber();let i=(isNaN(s)?this.argument:s.toString()).split(/%|,|\s+/),e=0,a=this.replaceAccentuatedChars(r);i.forEach((s=>{if(s){s=this.replaceAccentuatedChars(s);let i=this.getSpecialCharacters(s);null!=i&&i.length>0&&(s=this.removeSpecialCharacters(s)),(t.mask||"CGC_CPF"===t.uiType||"Phone"===t.uiType)&&(s=s.split("").join("\\.?\\-?\\/?\\(?\\)?"));let o=new RegExp(s,"ig");o.lastIndex=e;let n=o.exec(a);if(n&&n.length>0){e=n.index;let s=n[0].length,i=r.substring(e,e+s),t=(null==i?void 0:i.trim())?this._startHighlightTag+i+this._endHighlightTag:"",o=r.substring(0,e),l=r.substring(e+s);r=o+t+l,e+=t.length,a=this.replaceAccentuatedChars(r)}}}))}return r}replaceHtmlEntities(s){return null==s?s:String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}replaceAccentuatedChars(s){return null==s?s:this.replaceToSpace(s,["&amp;","&lt;","&gt;","&quot;"]).replace(/[^\w ]/g,(s=>{let i=this._charsWithAccentuation.indexOf(s);return i>-1&&(s=this._charsWithoutAccentuation.charAt(i)),s||""}))}replaceToSpace(s,i=[]){return null==s||i.forEach((i=>{const t=new RegExp(i,"g");let e="";for(let s=0;s<i.length;s++)e+=" ";s=String(s).replace(t,e)})),s}isIn(s,i){return this.indexOf(s,i)>-1}getSpecialCharacters(s){let i,t=[];for(;i=this._specialCharsRegex.exec(s);)t.push(s[i.index]);return t}removeSpecialCharacters(s){return this.getSpecialCharacters(s).forEach((i=>{s=this.replaceAll(s,i,"")})),s}replaceAll(s,i,t){let e=(null!=s?s:"").indexOf(i);for(;e>-1;)e=(s=s.replace(i,t)).indexOf(i);return s}getArgumentNumber(){return Number(this.argument||void 0)}createOption(s){let{key:i,title:t}=s;const e=new RegExp(this._startHighlightTag,"g"),r=new RegExp(this._endHighlightTag,"g");t=a.decodeHtmlEntities(t);const o={value:null==i?void 0:i.replace(e,"").replace(r,""),label:null==t?void 0:t.replace(e,"").replace(r,"")};this.selectItem(o)}onChangeValue(s){var i;if(this.clearDeboucingTimeout(),this._startLoading)return void(this._changeDeboucingTimeout=setTimeout((()=>{this.onChangeValue(s)}),this._deboucingTime));if(this.argument=(s.detail||"").trim(),this.isHierarchyEntity&&"list"===this._presentationMode)return void(null===(i=this._pesquisaTree)||void 0===i||i.applyFilter());const t=this.getArgumentNumber();this.argument&&(!isNaN(t)||this.argument.length>=this._limitCharsToSearch)?this._changeDeboucingTimeout=setTimeout((()=>{this.doSearch(isNaN(t)?this.argument:t.toString())}),this._deboucingTime):this._itemList=void 0}clearDeboucingTimeout(){this._changeDeboucingTimeout&&(clearTimeout(this._changeDeboucingTimeout),this._changeDeboucingTimeout=void 0)}onClickSearch(){this.doSearch((this.argument||"").trim())}getMessageView(){return this._startLoading?"Aguarde, buscando registros...":this._itemList?this._itemList.length>=1?`${this._itemList.length} ${this._itemList.length>1?"registros encontrados":"registro encontrado"}`:"Nenhum registro encontrado":"Os resultados de sua pesquisa aparecerão aqui..."}async componentWillLoad(){const s=await this.pesquisaFetcher.loadPresentationConfig(this.entityName);this._presentationMode="list"===s?"list":"table"}async componentDidLoad(){o.addIDInfo(this._element),await this.chooseViewMode()}async handleChangeViewMode(){this._presentationMode="list"===this._presentationMode?"table":"list",await this.chooseViewMode(),await this.pesquisaFetcher.savePresentationConfig(this.entityName,this._presentationMode)}async chooseViewMode(){var s,i;if("list"!==this._presentationMode)return await(null===(s=this._viewStack)||void 0===s?void 0:s.show(c.GRID)),void(this._currentView=c.GRID);const t=this.isHierarchyEntity?c.TREE:c.CARDS;await(null===(i=this._viewStack)||void 0===i?void 0:i.show(t)),this._currentView=t}hideLimitMessage(){return!this._itemList||this._itemList.length<100}hideRecordsMessage(){return"list"===this._presentationMode&&this.isHierarchyEntity}getButtonModeInfo(){return"list"===this._presentationMode?{iconName:"table",title:"Modo grade"}:this.isHierarchyEntity?{iconName:"hierarchical-tree",title:"Modo árvore hierárquica"}:{iconName:"list",title:"Modo lista"}}render(){var s,e;return i(t,null,i("div",{class:"snk-pesquisa"},i("div",{class:"snk-pesquisa__input"},i("ez-text-input",{label:"Buscar",class:"ez-margin-right--medium",canShowError:!1,ref:s=>this._textInput=s,onEzChange:s=>this.onChangeValue(s),value:this.argument,"data-element-id":"searchInput"},i("ez-icon",{slot:"leftIcon",iconName:"search"}),this.argument&&(null===(s=this._textInput)||void 0===s?void 0:s.value)?i("button",{slot:"rightIcon",class:"snk-pesquisa__btn",onClick:()=>this.clearSearch()},i("ez-icon",{iconName:"close"})):void 0),i("ez-button",{class:"ez-button--primary",label:"Pesquisar",onClick:()=>this.onClickSearch()}),i("ez-button",{class:"ez-margin-left--medium",mode:"icon",iconName:this.getButtonModeInfo().iconName,title:this.getButtonModeInfo().title,onClick:async()=>await this.handleChangeViewMode()})),i("div",{class:"snk-pesquisa__records-label "+(this._currentView===c.TREE?"hidden":"")},i("label",{class:"snk-pesquisa__records "+(this.hideRecordsMessage()?"hidden":"")},this.getMessageView()),i("label",{class:"snk-pesquisa__records-limit "+(this.hideLimitMessage()?"hidden":"")},"Essa pesquisa foi limitada, existem mais resultados.")),i("div",{class:"snk-pesquisa__content"},i("ez-view-stack",{ref:s=>this._viewStack=s,"data-element-id":"simple-crud"},i("stack-item",null,i("pesquisa-grid",{metadata:this._gridMetadata,dataSource:this._gridDataSource,pkField:this._pkField,descriptionField:this._descriptionField,entityName:this.entityName,shouldLoadConfig:this._currentView===c.GRID,onPesquisaGridSelectItem:({detail:s})=>this.selectItem(s)})),i("stack-item",null,i("div",{class:"snk-pesquisa__cards-container"},null===(e=this._itemList)||void 0===e?void 0:e.map((s=>i("ez-card-item",{onEzClick:s=>this.createOption(s.detail),item:s}))))),i("stack-item",null,i("pesquisa-tree",{ref:s=>this._pesquisaTree=s,argument:this.argument,treeLoader:this.treeLoader,allowsNonAnalytic:this.allowsNonAnalytic,shouldLoadTree:this._currentView===c.TREE,onPesquisaTreeSelectItem:({detail:s})=>this.selectItem(s)}))))))}get _element(){return e(this)}static get watchers(){return{argument:["observeArgument"]}}};u.style=".sc-snk-pesquisa-h{--snk-pesquisa--font-size:var(--text--medium, 14px);--snk-pesquisa--font-family:var(--font-pattern, Arial);--snk-pesquisa--font-weight:var(--text-weight--medium, 400);--snk-pesquisa__records--color:var(--text--primary, #626e82);--snk-pesquisa__records--color-secondary:var(--text--secondary, #626e82);--snk-pesquisa__records--padding-vertical:var(--space--medium, 12px);--snk-pesquisa__content--padding-right:var(--space--small, 6px);--snk-pesquisa__btn--color:var(--title--primary, #2B3A54);--snk-pesquisa__btn-disabled--color:var(--text--disable, #AFB6C0);--snk-pesquisa__btn-hover--color:var(--color--primary, #4e4e4e);--snk-pesquisa__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-pesquisa__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-pesquisa__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-pesquisa__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-pesquisa__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-pesquisa__scrollbar--width:var(--space--small, 6px);height:100%;display:flex;flex-direction:column;overflow-y:auto}.snk-pesquisa.sc-snk-pesquisa{display:flex;flex-direction:column;height:100%}.snk-pesquisa__input.sc-snk-pesquisa{display:flex;width:100%;box-sizing:border-box;padding-top:4px;padding-right:4px}.snk-pesquisa__input.sc-snk-pesquisa ez-icon.sc-snk-pesquisa{--ez-icon--color:inherit;font-weight:var(--text-weight--large, 600)}.snk-pesquisa__content.sc-snk-pesquisa{display:flex;flex-direction:column;overflow-y:hidden;scrollbar-width:thin;scrollbar-color:var(--snk-pesquisa__scrollbar--color-clicked) var(--snk-pesquisa__scrollbar--color-background);padding-right:var(--snk-pesquisa__content--padding-right);height:100vh}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar{background-color:var(--snk-pesquisa__scrollbar--color-background);width:var(--snk-pesquisa__scrollbar--width);max-width:var(--snk-pesquisa__scrollbar--width);min-width:var(--snk-pesquisa__scrollbar--width)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-track{background-color:var(--snk-pesquisa__scrollbar--color-background);border-radius:var(--snk-pesquisa__scrollbar--border-radius)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb{background-color:var(--snk-pesquisa__scrollbar--color-default);border-radius:var(--snk-pesquisa__scrollbar--border-radius)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:vertical:hover,.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--snk-pesquisa__scrollbar--color-hover)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:vertical:active,.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--snk-pesquisa__scrollbar--color-clicked)}.snk-pesquisa__records-label.sc-snk-pesquisa{display:flex;flex-direction:row;justify-content:space-between;font-family:var(--snk-pesquisa--font-family);font-weight:var(--snk-pesquisa--font-weight);font-size:var(--snk-pesquisa--font-size);padding-bottom:var(--snk-pesquisa__records--padding-vertical);padding-top:var(--snk-pesquisa__records--padding-vertical)}.snk-pesquisa__records-label.hidden.sc-snk-pesquisa{display:none}.snk-pesquisa__records.sc-snk-pesquisa{color:var(--snk-pesquisa__records--color)}.snk-pesquisa__records-limit.sc-snk-pesquisa{color:var(--snk-pesquisa__records--color-secondary)}.snk-pesquisa__records-limit.hidden.sc-snk-pesquisa,.snk-pesquisa__records.hidden.sc-snk-pesquisa{visibility:hidden}.snk-pesquisa__btn.sc-snk-pesquisa{outline:none;border:none;background:none;cursor:pointer;color:var(--snk-pesquisa__btn--color)}.snk-pesquisa__btn.sc-snk-pesquisa:disabled{cursor:unset;color:var(--snk-pesquisa__btn-disabled--color)}.snk-pesquisa__btn.sc-snk-pesquisa:disabled:hover{cursor:unset;color:var(--snk-pesquisa__btn-disabled--color)}.snk-pesquisa__btn.sc-snk-pesquisa:hover{color:var(--snk-pesquisa__btn-hover--color)}.snk-pesquisa__cards-container.sc-snk-pesquisa{height:100%;overflow-y:auto}";export{u as snk_pesquisa}
@@ -0,0 +1,26 @@
1
+ import{d as e,D as r}from"./p-d62228fb.js";import{ObjectUtils as n}from"@sankhyalabs/core";class t{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchResource",e.gql`query($name: String!) {
2
+ $queryAlias$: fetchResource(name: $name){
3
+ resource
4
+ }
5
+ }`),this.templateByQuery.set("saveResource",e.gql`mutation($resource: InputResource!) {
6
+ $queryAlias$: saveResource(resource: $resource){
7
+ name
8
+ resource
9
+ }
10
+ }`)}loadResource(e){if(t._loadingResource.has(e))return t._loadingResource.get(e);const n=new Promise(((n,o)=>{r.get().callGraphQL({values:{name:e},query:this.templateByQuery.get("fetchResource")}).then((r=>{n(null==r?void 0:r.resource),t._loadingResource.delete(e)})).catch((r=>{o(r),t._loadingResource.delete(e)}))}));return t._loadingResource.set(e,n),n}saveResource(e,n){return new Promise(((t,o)=>{r.get().callGraphQL({values:{resource:{name:n,resource:JSON.stringify(e)}},query:this.templateByQuery.get("saveResource")}).then((e=>{t(e)})).catch((e=>{o(e)}))}))}}t._loadingResource=new Map;class o extends t{constructor(){super(),this.queryConfig=new Map,this.buildTemplatesConfig()}buildTemplatesConfig(){this.queryConfig.set("fetchUserAvailableConfigs",e.gql`query($name: String!) {
11
+ $queryAlias$: fetchUserAvailableConfigs(name: $name){
12
+ name
13
+ origin
14
+ key
15
+ }
16
+ }`),this.queryConfig.set("fetchLegacyConfig",e.gql`query($name: String!) {
17
+ $queryAlias$: fetchLegacyConfig(name: $name){
18
+ name
19
+ resource
20
+ }
21
+ }`),this.queryConfig.set("fetchDefaultConfig",e.gql`query($name: String!) {
22
+ $queryAlias$: fetchDefaultConfig(name: $name){
23
+ name
24
+ resource
25
+ }
26
+ }`)}loadFormConfig(e,r){return new Promise(((n,t)=>{Promise.all([this.loadResource(this.getPath(r,e)),this.loadResource(this.getPath(`FormCardState:${r}`,e,"form-card")),this.loadResource(this.getPath(r,e,"summary")),this.loadResource(this.getPath(r,e,"defaultValues"))]).then((([e,r,t,o])=>{let i;if(null!=e){i=Object.assign(Object.assign({},JSON.parse(e)),{emptyConfig:!1});const{tabs:r,fields:n}=i;if(r){const e=new Map(r.map((e=>[e.label,e])));null==n||n.forEach((r=>{var n;return r.tab=(null===(n=e.get(this.getTabName(r.tab)))||void 0===n?void 0:n.label)||e.get(this.getTabName(r.tab))}))}i.fields=null==n?void 0:n.map((e=>{if("readonly"in e){const r=!0===e.readonly;delete e.readonly,e.readOnly=r}return e}))}null!=r&&(null==i&&(i={emptyConfig:!0,fields:[]}),i.cardsState=new Map(JSON.parse(r))),null!=t&&(null==i&&(i={emptyConfig:!0,fields:[]}),i.summary=new Map(Object.entries(JSON.parse(t)))),null!=o&&(null==i&&(i={emptyConfig:!0,fields:[]}),i.defaultVars=new Map(Object.entries(JSON.parse(o)))),n(i)})).catch((e=>{t(e)}))}))}getTabName(e){return"object"==typeof e?e.label:e}saveCardState(e,r,n){const t=this.getPath(`FormCardState:${n}`,r,"form-card");return new Promise(((r,n)=>{this.saveResource(Array.from(e.entries()),t).then((e=>{r(new Map(JSON.parse(e.resource)))})).catch((e=>{n(e)}))}))}saveConfig(e,r,n){delete e.cardsState,delete e.defaultVars,delete e.summary;const t=this.getPath(n,r);return new Promise(((r,n)=>{this.saveResource(e,t).then((e=>{r(JSON.parse(e.resource))})).catch((e=>{n(e)}))}))}fetchUserAvailableConfigs(e,n){const t=this.getPath(n,e);return new Promise(((e,n)=>{r.get().callGraphQL({values:{name:t},query:this.queryConfig.get("fetchUserAvailableConfigs")}).then((r=>{e(r)})).catch((e=>{n(e)}))}))}fetchLegacyConfig(e,t){const o=this.getPath(t,e);return new Promise(((e,t)=>{r.get().callGraphQL({values:{name:o},query:this.queryConfig.get("fetchLegacyConfig")}).then((r=>{e(n.stringToObject((null==r?void 0:r.resource)||""))})).catch((e=>{t(e)}))}))}fetchDefaultConfig(e,t){const o=this.getPath(t,e);return new Promise(((e,t)=>{r.get().callGraphQL({values:{name:o},query:this.queryConfig.get("fetchDefaultConfig")}).then((r=>{(null==r?void 0:r.resource)||e(null),e(n.stringToObject(null==r?void 0:r.resource))})).catch((e=>{t(e)}))}))}getPath(e,r,n="form"){return r?`cfg://${n}/${e}/${r}`:`cfg://${n}/${e}`}async fetchLegacyConfigurableForm(e){const t={requestBody:{config:{chave:e,tipo:"T"}}},o=await r.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(t));if(!n.isEmpty(o))return this.buildLegacyConfigurableForm(o)}async fetchSimpleFormConfig(e){const n={requestBody:{formConfig:{configName:e}}},t=await r.get().callServiceBroker("FormConfig.getFormConfig",JSON.stringify(n));return this.processConfig(t)}async saveSimpleFormConfig(e,n){const t=this.buildSaveSimpleFormConfigPayload(e,n),o=await r.get().callServiceBroker("FormConfig.saveFormConfig",JSON.stringify(t));this.processConfig(o)}processConfig(e){return n.isEmpty(e)?[]:this.getResponseAsArray(e).map((e=>e.name))}getResponseAsArray(e){var r,n,t;const o=null!==(t=null===(n=null===(r=null==e?void 0:e.formConfig)||void 0===r?void 0:r.layout)||void 0===n?void 0:n.field)&&void 0!==t?t:[];return Array.isArray(o)?o:[o]}buildSaveSimpleFormConfigPayload(e,r){return{formConfig:{configName:e,layout:{field:r.map((e=>({name:e})))},metadata:{field:[]}}}}async restoreFormConfig(e){const n={requestBody:{formConfig:{configName:e}}};await r.get().callServiceBroker("FormConfig.restoreFormConfig",JSON.stringify(n))}buildLegacyConfigurableForm(e){var r,n,t;const o=null!==(t=null===(n=null===(r=null==e?void 0:e.formConfig)||void 0===r?void 0:r.layout)||void 0===n?void 0:n.field)&&void 0!==t?t:[];return{emptyConfig:!1,fields:Array.isArray(o)?o:[o]}}}var i;!function(e){e.USER="USER",e.DEFAULT="DEFAULT",e.SHARED="SHARED"}(i||(i={}));export{o as F,t as R,i as U}
@@ -1,4 +1,4 @@
1
- import{R as e,F as t}from"./p-01512409.js";import{F as i}from"./p-ff1990ad.js";import{ObjectUtils as s}from"@sankhyalabs/core";import{d as r,D as a}from"./p-5a7e18f4.js";var n;function l(e,t){if(null==e)return e;if(e instanceof Date)return e.toISOString();if("object"==typeof e){if(e instanceof Array)return e.map((e=>l(i.MULTI_LIST===t?function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(i[s[r]]=e[s[r]])}return i}(e,["label"]):e)));{const i=Object.assign({},e);return Object.keys(e).forEach((s=>{void 0!==e[s]?i[s]=l(e[s],t):delete i[s]})),i}}return e}class o{constructor(){this.templateByQuery=new Map,this.buildTemplates()}resolveURI(e,t){let i="filter-assistent-config://"+e;return t&&(i+="."+t),i}buildTemplates(){this.templateByQuery.set("fetchFilterFields",r.gql`
1
+ import{R as e,F as t}from"./p-1435701f.js";import{F as i}from"./p-ff1990ad.js";import{ObjectUtils as s}from"@sankhyalabs/core";import{d as r,D as a}from"./p-d62228fb.js";var n;function l(e,t){if(null==e)return e;if(e instanceof Date)return e.toISOString();if("object"==typeof e){if(e instanceof Array)return e.map((e=>l(i.MULTI_LIST===t?function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(i[s[r]]=e[s[r]])}return i}(e,["label"]):e)));{const i=Object.assign({},e);return Object.keys(e).forEach((s=>{void 0!==e[s]?i[s]=l(e[s],t):delete i[s]})),i}}return e}class o{constructor(){this.templateByQuery=new Map,this.buildTemplates()}resolveURI(e,t){let i="filter-assistent-config://"+e;return t&&(i+="."+t),i}buildTemplates(){this.templateByQuery.set("fetchFilterFields",r.gql`
2
2
  query($name: String!) {
3
3
  $queryAlias$: fetchFilterFields(name: $name){
4
4
  currentLink {
@@ -1 +1 @@
1
- import{r as t,c as i,h as e,H as s,g as r}from"./p-d2d301a6.js";import{ElementIDUtils as o,ObjectUtils as l}from"@sankhyalabs/core";import{F as a}from"./p-ff1990ad.js";import{E as n}from"./p-1a68fb59.js";import{C as d}from"./p-13f17dab.js";import{F as h}from"./p-d9804798.js";import"./p-01512409.js";import"./p-5a7e18f4.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const p=class{constructor(e){t(this,e),this.filterChange=i(this,"filterChange",7),this.editPersonalizedFilter=i(this,"editPersonalizedFilter",7),this.addPersonalizedFilter=i(this,"addPersonalizedFilter",7),this.filterItem=void 0,this.configName=void 0,this.resourceID=void 0}observeFilterItem(t){var i,e;this._editor&&(this._editor.config=t),null===(e=null===(i=this._editor)||void 0===i?void 0:i.reloadList)||void 0===e||e.call(i),this.filterChange.emit(t)}getContentEditorConfig(){const t={presentationMode:n.MODAL};switch(this.filterItem.type){case a.BINARY_SELECT:return{tag:"snk-filter-binary-select",props:t};case a.MULTI_SELECT:return{tag:"snk-filter-multi-select"};case a.PERIOD:return{tag:"snk-filter-period",props:t};case a.SEARCH:return{tag:"snk-filter-search"};case a.NUMBER:return{tag:"snk-filter-number",props:t};case a.PERSONALIZED:return this.buildSnkFilterPersonalizedProps();case a.CHECK_BOX_LIST:return{tag:"snk-filter-checkbox-list",props:t};case a.MULTI_LIST:return{tag:"snk-entity-list",props:{maxHeightList:"640px",rightListSlotBuilder:t=>this.buildRightSlot(t)}}}return{tag:"snk-filter-text"}}buildSnkFilterPersonalizedProps(){return{tag:"snk-personalized-filter-editor",props:{onEditFilter:t=>this.editPersonalizedFilter.emit(t.detail),onAddFilter:()=>this.addPersonalizedFilter.emit()}}}isVisible(t){return!!this.filterItem.visible||void 0!==t}updateFilterValue(t){const i=void 0!==(null==t?void 0:t.value)?t.value:t;this.filterItem=Object.assign(Object.assign({},this.filterItem),null!=this.filterItem.groupedItems?{visible:i>0,value:i,groupedItems:t.items}:{value:this.filterItem.type===(a.SEARCH||a.CHECK_BOX_LIST)?t:i,visible:this.isVisible(i)})}handleDeleteFilter(t,i){i===a.PERSONALIZED&&d.removePersonalizedFilter(t,this.resourceID,this.configName)}componentDidLoad(){if(this._element){o.addIDInfo(this._element);const t=this._element.getAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME);this._idContentEditor=`${t}_${this.filterItem.id}`}}buildRightSlot(t){return e("ez-icon",{iconName:"delete",onClick:()=>this.removeValueFromConfig(t)})}removeValueFromConfig(t){var i,e,s;const r=null===(e=null===(i=this.filterItem)||void 0===i?void 0:i.value)||void 0===e?void 0:e.findIndex((({id:i})=>i===t.id)),o=l.copy(this.filterItem);null===(s=null==o?void 0:o.value)||void 0===s||s.splice(r,1),this.updateFilterValue(o.value)}canShowDetailModal(){const{CUSTOM_FILTER:t,OTHER_FILTERS:i}=h;return![t,i].includes(this.filterItem.filterType)&&this.filterItem.type!==a.BINARY_SELECT}render(){const{tag:t,props:i}=this.getContentEditorConfig();return e(s,null,e("div",{class:"ez-flex ez-flex--column grow"},this.canShowDetailModal()&&e("div",{class:"col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center"},e("div",{class:"ez-title ez-title--small ez-title--primary grow"},this.filterItem.detailModal)),e(t,Object.assign({ref:t=>this._editor=t,config:this.filterItem,value:this.filterItem.value,onValueChanged:t=>this.updateFilterValue(t.detail),"data-element-id":this._idContentEditor},i))))}get _element(){return r(this)}static get watchers(){return{filterItem:["observeFilterItem"]}}};p.style=".grow{flex-grow:1}.gap{gap:4px}";export{p as snk_filter_modal_item}
1
+ import{r as t,c as i,h as e,H as s,g as r}from"./p-d2d301a6.js";import{ElementIDUtils as o,ObjectUtils as l}from"@sankhyalabs/core";import{F as a}from"./p-ff1990ad.js";import{E as n}from"./p-1a68fb59.js";import{C as d}from"./p-19dc71e9.js";import{F as h}from"./p-d9804798.js";import"./p-1435701f.js";import"./p-d62228fb.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const c=class{constructor(e){t(this,e),this.filterChange=i(this,"filterChange",7),this.editPersonalizedFilter=i(this,"editPersonalizedFilter",7),this.addPersonalizedFilter=i(this,"addPersonalizedFilter",7),this.filterItem=void 0,this.configName=void 0,this.resourceID=void 0}observeFilterItem(t){var i,e;this._editor&&(this._editor.config=t),null===(e=null===(i=this._editor)||void 0===i?void 0:i.reloadList)||void 0===e||e.call(i),this.filterChange.emit(t)}getContentEditorConfig(){const t={presentationMode:n.MODAL};switch(this.filterItem.type){case a.BINARY_SELECT:return{tag:"snk-filter-binary-select",props:t};case a.MULTI_SELECT:return{tag:"snk-filter-multi-select"};case a.PERIOD:return{tag:"snk-filter-period",props:t};case a.SEARCH:return{tag:"snk-filter-search"};case a.NUMBER:return{tag:"snk-filter-number",props:t};case a.PERSONALIZED:return this.buildSnkFilterPersonalizedProps();case a.CHECK_BOX_LIST:return{tag:"snk-filter-checkbox-list",props:t};case a.MULTI_LIST:return{tag:"snk-entity-list",props:{maxHeightList:"640px",rightListSlotBuilder:t=>this.buildRightSlot(t)}}}return{tag:"snk-filter-text"}}buildSnkFilterPersonalizedProps(){return{tag:"snk-personalized-filter-editor",props:{onEditFilter:t=>this.editPersonalizedFilter.emit(t.detail),onAddFilter:()=>this.addPersonalizedFilter.emit()}}}isVisible(t){return!!this.filterItem.visible||void 0!==t}updateFilterValue(t){const i=void 0!==(null==t?void 0:t.value)?t.value:t;this.filterItem=Object.assign(Object.assign({},this.filterItem),null!=this.filterItem.groupedItems?{visible:i>0,value:i,groupedItems:t.items}:{value:this.filterItem.type===(a.SEARCH||a.CHECK_BOX_LIST)?t:i,visible:this.isVisible(i)})}handleDeleteFilter(t,i){i===a.PERSONALIZED&&d.removePersonalizedFilter(t,this.resourceID,this.configName)}componentDidLoad(){if(this._element){o.addIDInfo(this._element);const t=this._element.getAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME);this._idContentEditor=`${t}_${this.filterItem.id}`}}buildRightSlot(t){return e("ez-icon",{iconName:"delete",onClick:()=>this.removeValueFromConfig(t)})}removeValueFromConfig(t){var i,e,s;const r=null===(e=null===(i=this.filterItem)||void 0===i?void 0:i.value)||void 0===e?void 0:e.findIndex((({id:i})=>i===t.id)),o=l.copy(this.filterItem);null===(s=null==o?void 0:o.value)||void 0===s||s.splice(r,1),this.updateFilterValue(o.value)}canShowDetailModal(){const{CUSTOM_FILTER:t,OTHER_FILTERS:i}=h;return![t,i].includes(this.filterItem.filterType)&&this.filterItem.type!==a.BINARY_SELECT}render(){const{tag:t,props:i}=this.getContentEditorConfig();return e(s,null,e("div",{class:"ez-flex ez-flex--column grow"},this.canShowDetailModal()&&e("div",{class:"col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center"},e("div",{class:"ez-title ez-title--small ez-title--primary grow"},this.filterItem.detailModal)),e(t,Object.assign({ref:t=>this._editor=t,config:this.filterItem,value:this.filterItem.value,onValueChanged:t=>this.updateFilterValue(t.detail),"data-element-id":this._idContentEditor},i))))}get _element(){return r(this)}static get watchers(){return{filterItem:["observeFilterItem"]}}};c.style=".grow{flex-grow:1}.gap{gap:4px}";export{c as snk_filter_modal_item}
@@ -0,0 +1 @@
1
+ var _;!function(_){_.LINK_AND_FILE_AT_THE_SAME_TIME="LINK_AND_FILE_AT_THE_SAME_TIME",_.ANY_LINK_OR_FILE_FILLED="ANY_LINK_OR_FILE_FILLED",_.UNKNOWN="UNKNOWN",_.DESCRIPTION_CANNOT_BE_CHANGED="DESCRIPTION_CANNOT_BE_CHANGED"}(_||(_={}));export{_ as S}
@@ -1 +1 @@
1
- import{r as t,c as i,h as s,g as e,H as a}from"./p-d2d301a6.js";import{Action as n,ObjectUtils as h,DataUnitAction as r,StringUtils as o,ApplicationContext as d}from"@sankhyalabs/core";import{ApplicationUtils as l,DialogType as c}from"@sankhyalabs/ezui/dist/collection/utils";import{O as u,S as v}from"./p-17425c72.js";import{g as f,a as m}from"./p-7e0a0aae.js";import{convertType as p}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";import{g as b}from"./p-7dd49d15.js";const w=class{constructor(s){t(this,s),this.dataStateChange=i(this,"dataStateChange",3),this.dataUnitReady=i(this,"dataUnitReady",3),this.messagesBuilderUpdated=i(this,"messagesBuilderUpdated",3),this.dataUnitFieldsHidded=i(this,"dataUnitFieldsHidded",7),this.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this._openedAlert=!1,this._fieldsWithRmp=[],this._fieldsWithRmPrecision=[],this._metadataByRow=new Map,this._rowMetadataCache=new Map,this.REGEX_DATAUNIT_NAME=/dd:\/\/(.+?)\//,this._dataUnitObserver=async t=>{const i=await this.buildDataState(t.type);switch(this.dataState=i,this.messagesBuilder.currentOperation=this.getMessageOperation(),t.type){case n.DATA_SAVED:await this.handleDataSaved(t);break;case n.RECORDS_ADDED:case n.RECORDS_COPIED:this.insertionMode.emit();break;case n.EDITION_CANCELED:this.cancelEdition.emit();break;case n.RECORDS_REMOVED:this.handleRecordsRemoved(t);break;case n.METADATA_LOADED:this.fillFieldsWithRmp(this.dataUnit.metadata),this.fillFieldsWithRmPrecision(this.dataUnit.metadata)}},this.fieldsToLink=[],this.dataState=void 0,this.messagesBuilder=void 0,this.dataUnitName=void 0,this.entityName=void 0,this.pageSize=150,this.dataUnit=void 0,this.beforeSave=void 0,this.afterSave=void 0,this.useCancelConfirm=!0,this.ignoreSaveMessage=void 0,this.configName=void 0,this.resourceID=void 0,this.domainMessagesBuilder=void 0}observePageSize(){this.dataUnit&&(this.dataUnit.pageSize=this.pageSize)}observeDataUnitName(t,i){i!=t&&(this.dataUnit?this._application.updateDataunitCache(i,this.dataUnitName,this.dataUnit):this.loadDataUnit())}observeEntityName(t,i){i!=t&&(this.dataUnit=void 0,this.entityName=t,this.loadDataUnit())}observeDataState(t,i){h.objectToString(i)!=h.objectToString(t)&&this.dataStateChange.emit(t)}observeDataUnit(){this.handlerLinkFields(),this.dataUnitReady.emit(this.dataUnit)}observeMessagesBuilder(t){t&&this.messagesBuilderUpdated.emit(t)}async getDataUnit(){return new Promise((t=>{this.dataUnit?t(this.dataUnit):this._onDataUnitResolve.push(t)}))}async getSelectedRecordsIDsInfo(){return b(this.dataUnit)}async getFieldsWithRmp(){return this._fieldsWithRmp}async getFieldsWithRmPrecision(){return this._fieldsWithRmPrecision}async getRowMetadata(t){return this.doGetRowMetadata(t)}async doGetRowMetadata(t){const i=this.dataUnit.getSelectedRecord();if(!t&&!i)return;const s=t||i,e="string"==typeof s?s:s.__record__id__;let a=this._metadataByRow.get(e);return this.dataUnit.isNewRecord(e)&&!a&&(a=await this.handleLoadRowMetadata(i)),a?(a.getProp=this.buildGetPropRowMetadata(a),Object.assign({},a)):void 0}buildGetPropRowMetadata(t){return(i,s)=>("rm_precision"===i&&(i=this.resolvePrecisionFromMetadata(s)),h.getProp(t,i))}resolvePrecisionFromMetadata(t){var i,s;if(!t)return void l.error(this.getMessage("snkDataUnit.fieldNameRequired"));const e=null===(s=null===(i=this.dataUnit.getField(t))||void 0===i?void 0:i.properties)||void 0===s?void 0:s.rm_precision;return e?e.split(".").filter(((t,i)=>1!==i)).join("."):""}getCleanOnCopyFields(){var t;return null===(t=this.dataUnit.metadata)||void 0===t?void 0:t.fields.filter((t=>{var i;return null===(i=t.properties)||void 0===i?void 0:i.cleanOnCopy})).map((t=>t.name))}fillFieldsWithRmp(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rmp)&&!this._fieldsWithRmp.includes(t.name)&&this._fieldsWithRmp.push(t.name)}))}fillFieldsWithRmPrecision(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rm_precision)&&!this._fieldsWithRmPrecision.includes(t.name)&&this._fieldsWithRmPrecision.push(t.name)}))}getCacheName(t,i,s){return[t,i,s].join("_")}updateDataStateRmp(t){const i=Object.assign({},t);this.dataState.rowMetadata=i}saveCacheRmd(t){const i=t.__record__metadata__,s=Object.keys(i);s.shift(),s.forEach((s=>{const e=f(t,s),a=this.getCacheName(s,i.provider,e);this._rowMetadataCache.set(a,Object.assign({},i))}))}getMetadataByRow(t){var i;if(!(null===(i=t.records)||void 0===i?void 0:i.length))return t;if(!this._fieldsWithRmp.length){const i=t.records.map((t=>(delete t.__record__metadata__,t)));return Object.assign(Object.assign({},t),{records:i})}const s=t.records.map((t=>{if(!t.__record__metadata__)return t;this.saveCacheRmd(t);const i=Object.assign({},t.__record__metadata__);return i.getProp=this.buildGetPropRowMetadata(i),this._metadataByRow.set(t.__record__id__,i),delete t.__record__metadata__,t}));return Object.assign(Object.assign({},t),{records:s})}interceptRecordsAdded(t){if(this.isAllowed("INSERT"))return new r(n.RECORDS_ADDED,this.handleLinksWithParent(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenInsert"))}interceptRecordsCopied(t){if(this.isAllowed("CLONE"))return new r(n.RECORDS_COPIED,this.handleRecordsCopied(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenClone"))}async interceptDataChange(t){var i;const s=null===(i=this.dataUnit.getSelectedRecord())||void 0===i?void 0:i.__record__id__;if(this.isAllowed("UPDATE")||this.dataUnit.isNewRecord(s))return t;this._openedAlert?await this.dataUnit.cancelEdition():(this._openedAlert=!0,await this.dataUnit.cancelEdition(),await l.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")),this._openedAlert=!1)}async interceptSavingData(t){if(!this.beforeSave)return t;const i=this.beforeSave(this.dataUnit);return i instanceof Promise?await i?t:void 0:i?t:void 0}interceptDataSaved(t){if(!this.afterSave)return t;this.afterSave(this.dataUnit)}async interceptEditionCanceled(t){var i,s;if(!this.useCancelConfirm||!this.dataState.hasDirtyRecords||(null===(i=t.payload)||void 0===i?void 0:i.fromParent)||(null===(s=t.payload)||void 0===s?void 0:s.silent))return t;const e=this.getMessage("snkDataUnit.cancelConfirmation");if(null==e)return this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),t;const a=this.getMessage("snkDataUnit.cancelConfirmationTitle"),n=await l.confirm(a,e);return n&&this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),n?t:void 0}async interceptRemovingRecords(t){var i,s,e;if(!this.isAllowed("REMOVE"))return void l.info(this.getMessage("snkDataUnit.forbiddenRemove"));let a=!1,n=!(null===(i=t.payload)||void 0===i?void 0:i.silent)&&this.getMessage("snkDataUnit.removeConfirmation");const h=null===(s=this.dataUnit)||void 0===s?void 0:s.getSelectionInfo();if(!(null===(e=t.payload)||void 0===e?void 0:e.silent)&&(null==h?void 0:h.length)>1&&(n=this.getMessage("snkDataUnit.removeAllConfirmation",{size:h.length}),a=!0),!n)return t;const r={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm."+(a?"no":"cancel")),labelConfirm:this.getMessage("snkDataUnit.confirm."+(a?"yes":"delete")),btnConfirmDanger:!1},o=this.getMessage("snkDataUnit.removeConfirmationTitle");return await l.confirm(o,n,null,c.WARN,r)?t:void 0}interceptDataLoaded(t){const i=this.getMetadataByRow(t.payload);return new r(n.DATA_LOADED,i)}interceptMetadataLoaded(t){return this.fillFieldsWithRmp(t.payload),this.fillFieldsWithRmPrecision(t.payload),new r(n.METADATA_LOADED,this.handleDULinksOnMetadataLoaded(t.payload))}async interceptAction(t){switch(t.type){case n.RECORDS_ADDED:return this.interceptRecordsAdded(t);case n.RECORDS_COPIED:return this.interceptRecordsCopied(t);case n.DATA_CHANGED:return await this.handleLoadRowMetadata(t.payload),await this.interceptDataChange(t);case n.CHANGING_DATA:return await this.interceptDataChange(t);case n.SAVING_DATA:return await this.interceptSavingData(t);case n.DATA_SAVED:return this.interceptDataSaved(t);case n.EDITION_CANCELED:return await this.interceptEditionCanceled(t);case n.REMOVING_RECORDS:return await this.interceptRemovingRecords(t);case n.DATA_LOADED:return this.interceptDataLoaded(t);case n.METADATA_LOADED:return this.interceptMetadataLoaded(t);default:return t}}async handleLoadRowMetadata(t){if(!t)return;const i=Object.keys(t).find((t=>this._fieldsWithRmp.includes(t)));if(i){const s=this.dataUnit.getField(i).properties.rmp,e=f(t,i);return await this.updateRowMetadata({fieldName:i,fieldValue:e,metadataName:s,updatedFields:t})}}async updateRowMetadata({fieldName:t,fieldValue:i,metadataName:s,updatedFields:e}){const a=this.getCacheName(t,s,i),n=this._rowMetadataCache.get(a);if(n)return this.updateDataStateRmp(n),n;{const i=new m,n=await i.loadRowMetadata(this,t,s,e);return this.updateDataStateRmp(n._rmd),this._rowMetadataCache.set(a,Object.assign({},n._rmd)),Object.assign({},n._rmd)}}handleDULinksOnMetadataLoaded(t){const i=Object.assign({},t);return this.processLinks(i),i}handleRecordsCopied(t){let i=[...t];return i=this.handleCleanOnCopy(i),this.handleLinksWithParent(i)}handleLinksWithParent(t){var i,s;const e=null!==(i=this._parentDataUnit)&&void 0!==i?i:null===(s=this.dataUnit)||void 0===s?void 0:s.getParentDataUnit();if(!e)return t;const a=e.getSelectedRecord(),n=null==e?void 0:e.getChildInfo(this.getCleanDataUnitName()),{links:h}=n;return h&&0!==h.length?t.map((t=>this.buildRecordWithLinkedFields(t,h,a))):t}buildRecordWithLinkedFields(t,i,s){const e=Object.assign({},t);return i.forEach((t=>{const i=p(this.dataUnit.getField(t.target).dataType,s[t.source]);e[t.target]=i})),e}handleCleanOnCopy(t){const i=this.getCleanOnCopyFields();return i.length>0&&(t=t.map((t=>this.buildCopyWithCleanedFields(t,i)))),t}buildCopyWithCleanedFields(t,i){const s=Object.assign({},t);return i.forEach((t=>delete s[t])),s}showSuccessMessage(t){l.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}async buildDataState(t){var i;const s=this.dataUnit.getSelectionInfo(),e=(this.dataUnit.hasDirtyRecords()||this.dataUnit.hasWaitingChanges())&&(null==s?void 0:s.isEmpty()),a=this.dataUnit.getSelectedRecord();let h=null===(i=this.dataState)||void 0===i?void 0:i.rowMetadata;return!a||h&&![n.SELECTION_CHANGED,n.EDITION_CANCELED,n.NEXT_SELECTED,n.PREVIOUS_SELECTED].includes(t)?h&&(h.getProp=this.buildGetPropRowMetadata(h)):h=await this.doGetRowMetadata(a),new D({insertionMode:this.dataUnit.hasNewRecord(),isStartingInsertionMode:e,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:this.dataUnit.hasCopiedRecord(),isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:void 0,selectionInfo:s,selectedRecord:a,recordsIsEmpty:0===this.dataUnit.records.length,metadataByRow:this._metadataByRow,rowMetadata:h})}async handleDataSaved(t){var i,s,e;const a=await this.handleLoadRowMetadata(null===(e=null===(s=null===(i=null==t?void 0:t.payload)||void 0===i?void 0:i.changes)||void 0===s?void 0:s[0])||void 0===e?void 0:e.record);a&&(a.getProp=this.buildGetPropRowMetadata(a)),this._metadataByRow.set(t.payload.records[0].__record__id__,a),this.dataState=await this.buildDataState();let n=t.payload.changes[0]._operation.toLowerCase();if("copy"==n&&(n=u.CLONE),this.ignoreSaveMessage&&![u.CLONE,u.INSERT].includes(n))return;const h=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0],n);null!=h&&this.showSuccessMessage(h)}handleRecordsRemoved(t){var i,s;let e=this.buildRemoveFinishMessage(t);null!=e&&this.showSuccessMessage(e);const a=null!==(s=null===(i=this.dataUnit.records)||void 0===i?void 0:i.length)&&void 0!==s?s:0,n=this.dataUnit.getPaginationInfo();n&&this.dataUnit.gotoPage(a>0||n.hasMore?n.currentPage:0)}buildRemoveFinishMessage(t){const i=t.payload.records;if(i&&i.length)return(null==i?void 0:i.length)>1?this.getMessage("snkDataUnit.removeAllInfo",{size:i.length}):this.getMessage("snkDataUnit.removeInfo",i)}getMessage(t,i,s){return i||(i=this.getMessageParams()),s&&(this.messagesBuilder.currentOperation=s),this.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecord}getMessageOperation(){return this.dataState.copyMode?u.CLONE:this.dataState.insertionMode||this.dataState.isStartingInsertionMode?u.INSERT:this.dataState.isDirty?u.UPDATE:u.CLEAN}async getDataUnitParentOrChild(){var t;const i=this.dataUnitName?this.dataUnitName:this.entityName;return this._parentSnkDataUnit?(this._parentDataUnit=await(null===(t=this._parentSnkDataUnit)||void 0===t?void 0:t.getDataUnit()),await this._application.getDataUnit(this.entityName,i,this._parentDataUnit,this.configName,this.resourceID)):await this._application.getDataUnit(this.entityName,i,null,this.configName,this.resourceID)}updateMetadataWithRMP(){this.fillFieldsWithRmp(this.dataUnit.metadata),this.fillFieldsWithRmPrecision(this.dataUnit.metadata);const t=this.handleDULinksOnMetadataLoaded(this.dataUnit.metadata);this.dataUnit.metadata=t}async loadDataUnit(){var t,i;if(null==this.dataUnit&&this._application&&this.entityName&&(this.dataUnit=await this.getDataUnitParentOrChild()),this.dataUnit){if(this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.subscribe(this._dataUnitObserver),(null===(t=this.dataUnit)||void 0===t?void 0:t.metadata)&&this.updateMetadataWithRMP(),this.dataUnit.addInterceptor(this),null===(i=this.dataUnit.records)||void 0===i?void 0:i.length){const{records:t}=this.getMetadataByRow(this.dataUnit);this.dataUnit.records=t}let s;for(this.dataState=await this.buildDataState();s=this._onDataUnitResolve.pop();)s(this.dataUnit)}}getParentSnkDataUnit(){let t=this.element;for(;t.parentNode;){if("SNK-DATA-UNIT"===t.parentNode.nodeName)return t.parentNode;t=t.parentNode}}handlerLinkFields(){var t,i,s,e;const a=null!==(t=this._parentDataUnit)&&void 0!==t?t:null===(i=this.dataUnit)||void 0===i?void 0:i.getParentDataUnit();if(!a)return;const n=null!==(s=this.entityName)&&void 0!==s?s:this.getCleanDataUnitName(),h=a.getChildInfo(n);if(!h)return;const r=null===(e=null==h?void 0:h.links)||void 0===e?void 0:e.map((t=>t.target));this.handleDUWithLinks(r)}handleDUWithLinks(t){this.fieldsToLink=t;const i=Object.assign({},this.dataUnit.metadata);this.processLinks(i),this.dataUnit.metadata=i,this.dataUnitFieldsHidded.emit()}processLinks(t){var i;null===(i=null==t?void 0:t.fields)||void 0===i||i.forEach((t=>{var i;(null===(i=this.fieldsToLink)||void 0===i?void 0:i.includes(t.name))&&(t.visible=!1)}))}getCleanDataUnitName(){var t;const i=this.dataUnit.name;if(o.isEmpty(i))return i;const s=this.REGEX_DATAUNIT_NAME.exec(i);return null!==(t=null==s?void 0:s[1])&&void 0!==t?t:i}static getNearestInstance(t){let i=t.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase())return i;i=i.parentElement}}instanceMessagesBuilder(){var t;this.messagesBuilder||(this.messagesBuilder=new v(null!==(t=this.domainMessagesBuilder)&&void 0!==t?t:this.entityName))}componentWillLoad(){this._application=d.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess(this.resourceID).then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit(),this.instanceMessagesBuilder()}disconnectedCallback(){this.dataUnit&&this.dataUnit.releaseCallbacks()}async componentDidLoad(){await this.loadDataUnit(),this.handlerLinkFields()}render(){return s(a,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"],messagesBuilder:["observeMessagesBuilder"]}}};class D{constructor(t){this.copyMode=t.copyMode,this.insertionMode=t.insertionMode,this.isStartingInsertionMode=t.isStartingInsertionMode,this.isDirty=t.isDirty,this.hasDirtyRecords=t.hasDirtyRecords,this.hasNext=t.hasNext,this.hasPrevious=t.hasPrevious,this.selectionInfo=t.selectionInfo,this.selectedRecord=t.selectedRecord,this.recordsIsEmpty=t.recordsIsEmpty,this.metadataByRow=t.metadataByRow,this.rowMetadata=t.rowMetadata}get selectedRecords(){var t;if(console.warn("SnkDataUnit: O método `selectedRecords` foi descontinuado. Use o método `selectionInfo`."),null===(t=this.selectionInfo)||void 0===t?void 0:t.isAllRecords())throw new Error("Erro interno: Impossível obter os registros selecionados. A seleção atual é virtual. Use o atributo `selectionInfo`.");return this.selectionInfo.records}}export{w as S}
1
+ import{r as t,c as i,h as s,g as e,H as a}from"./p-d2d301a6.js";import{Action as n,ObjectUtils as h,DataUnitAction as r,StringUtils as o,ApplicationContext as d}from"@sankhyalabs/core";import{ApplicationUtils as l,DialogType as c}from"@sankhyalabs/ezui/dist/collection/utils";import{O as u,S as v}from"./p-17425c72.js";import{g as f,a as m}from"./p-3653374d.js";import{convertType as p}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";import{g as b}from"./p-7dd49d15.js";const w=class{constructor(s){t(this,s),this.dataStateChange=i(this,"dataStateChange",3),this.dataUnitReady=i(this,"dataUnitReady",3),this.messagesBuilderUpdated=i(this,"messagesBuilderUpdated",3),this.dataUnitFieldsHidded=i(this,"dataUnitFieldsHidded",7),this.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this._openedAlert=!1,this._fieldsWithRmp=[],this._fieldsWithRmPrecision=[],this._metadataByRow=new Map,this._rowMetadataCache=new Map,this.REGEX_DATAUNIT_NAME=/dd:\/\/(.+?)\//,this._dataUnitObserver=async t=>{const i=await this.buildDataState(t.type);switch(this.dataState=i,this.messagesBuilder.currentOperation=this.getMessageOperation(),t.type){case n.DATA_SAVED:await this.handleDataSaved(t);break;case n.RECORDS_ADDED:case n.RECORDS_COPIED:this.insertionMode.emit();break;case n.EDITION_CANCELED:this.cancelEdition.emit();break;case n.RECORDS_REMOVED:this.handleRecordsRemoved(t);break;case n.METADATA_LOADED:this.fillFieldsWithRmp(this.dataUnit.metadata),this.fillFieldsWithRmPrecision(this.dataUnit.metadata)}},this.fieldsToLink=[],this.dataState=void 0,this.messagesBuilder=void 0,this.dataUnitName=void 0,this.entityName=void 0,this.pageSize=150,this.dataUnit=void 0,this.beforeSave=void 0,this.afterSave=void 0,this.useCancelConfirm=!0,this.ignoreSaveMessage=void 0,this.configName=void 0,this.resourceID=void 0,this.domainMessagesBuilder=void 0}observePageSize(){this.dataUnit&&(this.dataUnit.pageSize=this.pageSize)}observeDataUnitName(t,i){i!=t&&(this.dataUnit?this._application.updateDataunitCache(i,this.dataUnitName,this.dataUnit):this.loadDataUnit())}observeEntityName(t,i){i!=t&&(this.dataUnit=void 0,this.entityName=t,this.loadDataUnit())}observeDataState(t,i){h.objectToString(i)!=h.objectToString(t)&&this.dataStateChange.emit(t)}observeDataUnit(){this.handlerLinkFields(),this.dataUnitReady.emit(this.dataUnit)}observeMessagesBuilder(t){t&&this.messagesBuilderUpdated.emit(t)}async getDataUnit(){return new Promise((t=>{this.dataUnit?t(this.dataUnit):this._onDataUnitResolve.push(t)}))}async getSelectedRecordsIDsInfo(){return b(this.dataUnit)}async getFieldsWithRmp(){return this._fieldsWithRmp}async getFieldsWithRmPrecision(){return this._fieldsWithRmPrecision}async getRowMetadata(t){return this.doGetRowMetadata(t)}async doGetRowMetadata(t){const i=this.dataUnit.getSelectedRecord();if(!t&&!i)return;const s=t||i,e="string"==typeof s?s:s.__record__id__;let a=this._metadataByRow.get(e);return this.dataUnit.isNewRecord(e)&&!a&&(a=await this.handleLoadRowMetadata(i)),a?(a.getProp=this.buildGetPropRowMetadata(a),Object.assign({},a)):void 0}buildGetPropRowMetadata(t){return(i,s)=>("rm_precision"===i&&(i=this.resolvePrecisionFromMetadata(s)),h.getProp(t,i))}resolvePrecisionFromMetadata(t){var i,s;if(!t)return void l.error(this.getMessage("snkDataUnit.fieldNameRequired"));const e=null===(s=null===(i=this.dataUnit.getField(t))||void 0===i?void 0:i.properties)||void 0===s?void 0:s.rm_precision;return e?e.split(".").filter(((t,i)=>1!==i)).join("."):""}getCleanOnCopyFields(){var t;return null===(t=this.dataUnit.metadata)||void 0===t?void 0:t.fields.filter((t=>{var i;return null===(i=t.properties)||void 0===i?void 0:i.cleanOnCopy})).map((t=>t.name))}fillFieldsWithRmp(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rmp)&&!this._fieldsWithRmp.includes(t.name)&&this._fieldsWithRmp.push(t.name)}))}fillFieldsWithRmPrecision(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rm_precision)&&!this._fieldsWithRmPrecision.includes(t.name)&&this._fieldsWithRmPrecision.push(t.name)}))}getCacheName(t,i,s){return[t,i,s].join("_")}updateDataStateRmp(t){const i=Object.assign({},t);this.dataState.rowMetadata=i}saveCacheRmd(t){const i=t.__record__metadata__,s=Object.keys(i);s.shift(),s.forEach((s=>{const e=f(t,s),a=this.getCacheName(s,i.provider,e);this._rowMetadataCache.set(a,Object.assign({},i))}))}getMetadataByRow(t){var i;if(!(null===(i=t.records)||void 0===i?void 0:i.length))return t;if(!this._fieldsWithRmp.length){const i=t.records.map((t=>(delete t.__record__metadata__,t)));return Object.assign(Object.assign({},t),{records:i})}const s=t.records.map((t=>{if(!t.__record__metadata__)return t;this.saveCacheRmd(t);const i=Object.assign({},t.__record__metadata__);return i.getProp=this.buildGetPropRowMetadata(i),this._metadataByRow.set(t.__record__id__,i),delete t.__record__metadata__,t}));return Object.assign(Object.assign({},t),{records:s})}interceptRecordsAdded(t){if(this.isAllowed("INSERT"))return new r(n.RECORDS_ADDED,this.handleLinksWithParent(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenInsert"))}interceptRecordsCopied(t){if(this.isAllowed("CLONE"))return new r(n.RECORDS_COPIED,this.handleRecordsCopied(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenClone"))}async interceptDataChange(t){var i;const s=null===(i=this.dataUnit.getSelectedRecord())||void 0===i?void 0:i.__record__id__;if(this.isAllowed("UPDATE")||this.dataUnit.isNewRecord(s))return t;this._openedAlert?await this.dataUnit.cancelEdition():(this._openedAlert=!0,await this.dataUnit.cancelEdition(),await l.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")),this._openedAlert=!1)}async interceptSavingData(t){if(!this.beforeSave)return t;const i=this.beforeSave(this.dataUnit);return i instanceof Promise?await i?t:void 0:i?t:void 0}interceptDataSaved(t){if(!this.afterSave)return t;this.afterSave(this.dataUnit)}async interceptEditionCanceled(t){var i,s;if(!this.useCancelConfirm||!this.dataState.hasDirtyRecords||(null===(i=t.payload)||void 0===i?void 0:i.fromParent)||(null===(s=t.payload)||void 0===s?void 0:s.silent))return t;const e=this.getMessage("snkDataUnit.cancelConfirmation");if(null==e)return this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),t;const a=this.getMessage("snkDataUnit.cancelConfirmationTitle"),n=await l.confirm(a,e);return n&&this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),n?t:void 0}async interceptRemovingRecords(t){var i,s,e;if(!this.isAllowed("REMOVE"))return void l.info(this.getMessage("snkDataUnit.forbiddenRemove"));let a=!1,n=!(null===(i=t.payload)||void 0===i?void 0:i.silent)&&this.getMessage("snkDataUnit.removeConfirmation");const h=null===(s=this.dataUnit)||void 0===s?void 0:s.getSelectionInfo();if(!(null===(e=t.payload)||void 0===e?void 0:e.silent)&&(null==h?void 0:h.length)>1&&(n=this.getMessage("snkDataUnit.removeAllConfirmation",{size:h.length}),a=!0),!n)return t;const r={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm."+(a?"no":"cancel")),labelConfirm:this.getMessage("snkDataUnit.confirm."+(a?"yes":"delete")),btnConfirmDanger:!1},o=this.getMessage("snkDataUnit.removeConfirmationTitle");return await l.confirm(o,n,null,c.WARN,r)?t:void 0}interceptDataLoaded(t){const i=this.getMetadataByRow(t.payload);return new r(n.DATA_LOADED,i)}interceptMetadataLoaded(t){return this.fillFieldsWithRmp(t.payload),this.fillFieldsWithRmPrecision(t.payload),new r(n.METADATA_LOADED,this.handleDULinksOnMetadataLoaded(t.payload))}async interceptAction(t){switch(t.type){case n.RECORDS_ADDED:return this.interceptRecordsAdded(t);case n.RECORDS_COPIED:return this.interceptRecordsCopied(t);case n.DATA_CHANGED:return await this.handleLoadRowMetadata(t.payload),await this.interceptDataChange(t);case n.CHANGING_DATA:return await this.interceptDataChange(t);case n.SAVING_DATA:return await this.interceptSavingData(t);case n.DATA_SAVED:return this.interceptDataSaved(t);case n.EDITION_CANCELED:return await this.interceptEditionCanceled(t);case n.REMOVING_RECORDS:return await this.interceptRemovingRecords(t);case n.DATA_LOADED:return this.interceptDataLoaded(t);case n.METADATA_LOADED:return this.interceptMetadataLoaded(t);default:return t}}async handleLoadRowMetadata(t){if(!t)return;const i=Object.keys(t).find((t=>this._fieldsWithRmp.includes(t)));if(i){const s=this.dataUnit.getField(i).properties.rmp,e=f(t,i);return await this.updateRowMetadata({fieldName:i,fieldValue:e,metadataName:s,updatedFields:t})}}async updateRowMetadata({fieldName:t,fieldValue:i,metadataName:s,updatedFields:e}){const a=this.getCacheName(t,s,i),n=this._rowMetadataCache.get(a);if(n)return this.updateDataStateRmp(n),n;{const i=new m,n=await i.loadRowMetadata(this,t,s,e);return this.updateDataStateRmp(n._rmd),this._rowMetadataCache.set(a,Object.assign({},n._rmd)),Object.assign({},n._rmd)}}handleDULinksOnMetadataLoaded(t){const i=Object.assign({},t);return this.processLinks(i),i}handleRecordsCopied(t){let i=[...t];return i=this.handleCleanOnCopy(i),this.handleLinksWithParent(i)}handleLinksWithParent(t){var i,s;const e=null!==(i=this._parentDataUnit)&&void 0!==i?i:null===(s=this.dataUnit)||void 0===s?void 0:s.getParentDataUnit();if(!e)return t;const a=e.getSelectedRecord(),n=null==e?void 0:e.getChildInfo(this.getCleanDataUnitName()),{links:h}=n;return h&&0!==h.length?t.map((t=>this.buildRecordWithLinkedFields(t,h,a))):t}buildRecordWithLinkedFields(t,i,s){const e=Object.assign({},t);return i.forEach((t=>{const i=p(this.dataUnit.getField(t.target).dataType,s[t.source]);e[t.target]=i})),e}handleCleanOnCopy(t){const i=this.getCleanOnCopyFields();return i.length>0&&(t=t.map((t=>this.buildCopyWithCleanedFields(t,i)))),t}buildCopyWithCleanedFields(t,i){const s=Object.assign({},t);return i.forEach((t=>delete s[t])),s}showSuccessMessage(t){l.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}async buildDataState(t){var i;const s=this.dataUnit.getSelectionInfo(),e=(this.dataUnit.hasDirtyRecords()||this.dataUnit.hasWaitingChanges())&&(null==s?void 0:s.isEmpty()),a=this.dataUnit.getSelectedRecord();let h=null===(i=this.dataState)||void 0===i?void 0:i.rowMetadata;return!a||h&&![n.SELECTION_CHANGED,n.EDITION_CANCELED,n.NEXT_SELECTED,n.PREVIOUS_SELECTED].includes(t)?h&&(h.getProp=this.buildGetPropRowMetadata(h)):h=await this.doGetRowMetadata(a),new D({insertionMode:this.dataUnit.hasNewRecord(),isStartingInsertionMode:e,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:this.dataUnit.hasCopiedRecord(),isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:void 0,selectionInfo:s,selectedRecord:a,recordsIsEmpty:0===this.dataUnit.records.length,metadataByRow:this._metadataByRow,rowMetadata:h})}async handleDataSaved(t){var i,s,e;const a=await this.handleLoadRowMetadata(null===(e=null===(s=null===(i=null==t?void 0:t.payload)||void 0===i?void 0:i.changes)||void 0===s?void 0:s[0])||void 0===e?void 0:e.record);a&&(a.getProp=this.buildGetPropRowMetadata(a)),this._metadataByRow.set(t.payload.records[0].__record__id__,a),this.dataState=await this.buildDataState();let n=t.payload.changes[0]._operation.toLowerCase();if("copy"==n&&(n=u.CLONE),this.ignoreSaveMessage&&![u.CLONE,u.INSERT].includes(n))return;const h=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0],n);null!=h&&this.showSuccessMessage(h)}handleRecordsRemoved(t){var i,s;let e=this.buildRemoveFinishMessage(t);null!=e&&this.showSuccessMessage(e);const a=null!==(s=null===(i=this.dataUnit.records)||void 0===i?void 0:i.length)&&void 0!==s?s:0,n=this.dataUnit.getPaginationInfo();n&&this.dataUnit.gotoPage(a>0||n.hasMore?n.currentPage:0)}buildRemoveFinishMessage(t){const i=t.payload.records;if(i&&i.length)return(null==i?void 0:i.length)>1?this.getMessage("snkDataUnit.removeAllInfo",{size:i.length}):this.getMessage("snkDataUnit.removeInfo",i)}getMessage(t,i,s){return i||(i=this.getMessageParams()),s&&(this.messagesBuilder.currentOperation=s),this.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecord}getMessageOperation(){return this.dataState.copyMode?u.CLONE:this.dataState.insertionMode||this.dataState.isStartingInsertionMode?u.INSERT:this.dataState.isDirty?u.UPDATE:u.CLEAN}async getDataUnitParentOrChild(){var t;const i=this.dataUnitName?this.dataUnitName:this.entityName;return this._parentSnkDataUnit?(this._parentDataUnit=await(null===(t=this._parentSnkDataUnit)||void 0===t?void 0:t.getDataUnit()),await this._application.getDataUnit(this.entityName,i,this._parentDataUnit,this.configName,this.resourceID)):await this._application.getDataUnit(this.entityName,i,null,this.configName,this.resourceID)}updateMetadataWithRMP(){this.fillFieldsWithRmp(this.dataUnit.metadata),this.fillFieldsWithRmPrecision(this.dataUnit.metadata);const t=this.handleDULinksOnMetadataLoaded(this.dataUnit.metadata);this.dataUnit.metadata=t}async loadDataUnit(){var t,i;if(null==this.dataUnit&&this._application&&this.entityName&&(this.dataUnit=await this.getDataUnitParentOrChild()),this.dataUnit){if(this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.subscribe(this._dataUnitObserver),(null===(t=this.dataUnit)||void 0===t?void 0:t.metadata)&&this.updateMetadataWithRMP(),this.dataUnit.addInterceptor(this),null===(i=this.dataUnit.records)||void 0===i?void 0:i.length){const{records:t}=this.getMetadataByRow(this.dataUnit);this.dataUnit.records=t}let s;for(this.dataState=await this.buildDataState();s=this._onDataUnitResolve.pop();)s(this.dataUnit)}}getParentSnkDataUnit(){let t=this.element;for(;t.parentNode;){if("SNK-DATA-UNIT"===t.parentNode.nodeName)return t.parentNode;t=t.parentNode}}handlerLinkFields(){var t,i,s,e;const a=null!==(t=this._parentDataUnit)&&void 0!==t?t:null===(i=this.dataUnit)||void 0===i?void 0:i.getParentDataUnit();if(!a)return;const n=null!==(s=this.entityName)&&void 0!==s?s:this.getCleanDataUnitName(),h=a.getChildInfo(n);if(!h)return;const r=null===(e=null==h?void 0:h.links)||void 0===e?void 0:e.map((t=>t.target));this.handleDUWithLinks(r)}handleDUWithLinks(t){this.fieldsToLink=t;const i=Object.assign({},this.dataUnit.metadata);this.processLinks(i),this.dataUnit.metadata=i,this.dataUnitFieldsHidded.emit()}processLinks(t){var i;null===(i=null==t?void 0:t.fields)||void 0===i||i.forEach((t=>{var i;(null===(i=this.fieldsToLink)||void 0===i?void 0:i.includes(t.name))&&(t.visible=!1)}))}getCleanDataUnitName(){var t;const i=this.dataUnit.name;if(o.isEmpty(i))return i;const s=this.REGEX_DATAUNIT_NAME.exec(i);return null!==(t=null==s?void 0:s[1])&&void 0!==t?t:i}static getNearestInstance(t){let i=t.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase())return i;i=i.parentElement}}instanceMessagesBuilder(){var t;this.messagesBuilder||(this.messagesBuilder=new v(null!==(t=this.domainMessagesBuilder)&&void 0!==t?t:this.entityName))}componentWillLoad(){this._application=d.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess(this.resourceID).then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit(),this.instanceMessagesBuilder()}disconnectedCallback(){this.dataUnit&&this.dataUnit.releaseCallbacks()}async componentDidLoad(){await this.loadDataUnit(),this.handlerLinkFields()}render(){return s(a,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"],messagesBuilder:["observeMessagesBuilder"]}}};class D{constructor(t){this.copyMode=t.copyMode,this.insertionMode=t.insertionMode,this.isStartingInsertionMode=t.isStartingInsertionMode,this.isDirty=t.isDirty,this.hasDirtyRecords=t.hasDirtyRecords,this.hasNext=t.hasNext,this.hasPrevious=t.hasPrevious,this.selectionInfo=t.selectionInfo,this.selectedRecord=t.selectedRecord,this.recordsIsEmpty=t.recordsIsEmpty,this.metadataByRow=t.metadataByRow,this.rowMetadata=t.rowMetadata}get selectedRecords(){var t;if(console.warn("SnkDataUnit: O método `selectedRecords` foi descontinuado. Use o método `selectionInfo`."),null===(t=this.selectionInfo)||void 0===t?void 0:t.isAllRecords())throw new Error("Erro interno: Impossível obter os registros selecionados. A seleção atual é virtual. Use o atributo `selectionInfo`.");return this.selectionInfo.records}}export{w as S}
@@ -1,4 +1,4 @@
1
- import{ObjectUtils as t,DataUnit as e,DataUnitInMemoryLoader as n,ApplicationContext as r,StringUtils as a,UserInterface as s,DataUnitStorage as o,DataType as i,ChangeOperation as c}from"@sankhyalabs/core";import{D as l,d as u}from"./p-5a7e18f4.js";import{DISTINCT_FILTER_NAME_PREFIX as d}from"@sankhyalabs/ezui/dist/collection/utils/constants";import{DataUnitTransient as m}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{ColumnFilterManager as h}from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import f from"@sankhyalabs/core/dist/utils/SortingUtils";import{R as p}from"./p-688dcb4c.js";class g{constructor(t){this._list=[],this._listCopy=[],this._listLastUpdate=0,this._listCopyLastUpdate=0,this._equalsFunction=t}async load(t,e,n,r){let a=[].concat(this._list);null!=t&&(a=this._list.filter((e=>t(e)))),null!=e&&(a=a.sort(e));const s=a.length;if(null!=r){const t=n||0;a=a.slice(t,r?t+r:a.length)}return Promise.resolve({result:a,count:s})}async distict(t){const e=[];let n=!1;for(const r of this._list){const a=t(r);null!=a&&(null!=a.value?e.push(a):n=!0)}return n&&e.push({key:"",value:null}),Promise.resolve(new Map(e.map((t=>[t.key,t.value]))))}async push(t){this.updateList([...this._list,...t])}async clear(){this.updateList([])}async delete(t){const e=this._list.filter((e=>{for(const n of t)if(this._equalsFunction(e,n))return!1;return!0}));this.updateList(e)}async update(t){const e=this._list.map((e=>{const n=t.find((t=>this._equalsFunction(e,t)));return null==n?e:n}));this.updateList(e)}async insert(t,e){const n=this._list.indexOf(t);if(-1==n)return void this.push(e);const r=this._list.slice(0,n).concat(e).concat(this._list.slice(n));this.updateList(r)}isOperating(){return!0}async isEmpty(){return Promise.resolve(0===this._list.length)}async count(){return Promise.resolve(this._list.length)}getFromCache(){return this._listLastUpdate>this._listCopyLastUpdate&&(this._listCopyLastUpdate=this._listLastUpdate,this._listCopy=t.copy(this._list)),this._listCopy}updateList(t){this._list=t,this._listLastUpdate=Date.now()}}class _{static setLoadingStatus(t,e){this._loadingStatus.set(t.name,e)}static isCacheEnabled(t){return!0}static cacheRecords(t,e,n,r){_.setLoadingStatus(t,r),_.isCacheEnabled(t)?this.getRepository(t).push(e):n&&this._repositories.delete(t.name)}static getSortingFunction(t,e){return f.getSortingFunction(t,e)}static async getDistinct(t,e){if(!_.isCacheEnabled(t))return Promise.resolve(h.compileDistinct(e,t));let n;const r=t.getLastLoadRequest();if(null!=r){const a=h.getColumnFilters(r.filters,e);n=h.getFilterFunction(t,Array.from(a.values()))}return new Promise(((r,a)=>{_.getRepository(t).distict((r=>{if(null!=n&&!n(r))return;const a=r[e];if(null==a)return{key:null,value:null};const s=null!=a.value?a.value:a;return{key:t.getFormattedValue(e,a),value:s}})).then((t=>{r(null!=t?Array.from(t.entries()).map((([t,e])=>({label:t,value:e,check:!0}))):void 0)})).catch((t=>a(t)))}))}static async loadData(t,n,r){try{if(_.isCacheEnabled(t)){if(["EZ_GRID_LOADING_SOURCE",e.CHANGING_PAGE_LOADING_SOURCE,e.ALL_RECORDS_SELECTION_SOURCE].includes(n.source)&&!await _.getRepository(t).isEmpty())return _.loadFromCache(t,n);_.getRepository(t).clear().catch((()=>{}))}return r(t,n)}catch(t){return console.error(t),Promise.reject(t)}}static insertRecords(t,e,n){_.isCacheEnabled(t)&&_.getRepository(t).insert(e,n)}static updateRecords(t,e){_.isCacheEnabled(t)&&_.getRepository(t).update(e)}static removeRecords(t,e){_.isCacheEnabled(t)&&_.getRepository(t).delete(e)}static async countRecords(t){return _.isCacheEnabled(t)?_.getRepository(t).count():Promise.resolve(0)}static getRepository(t){const e=t.name;return _._repositories.has(e)||_._repositories.set(e,new g(((t,e)=>t.__record__id__===e.__record__id__))),_._repositories.get(e)}static async loadFromCache(t,e){return new Promise(((n,r)=>{const a=h.getColumnFilters(e.filters,""),{limit:s,offset:o,sort:i}=e;_.getRepository(t).load(h.getFilterFunction(t,Array.from(a.values())),_.getSortingFunction(t,i),o,s).then((e=>{const r=_._loadingStatus.get(t.name),{count:a,result:i}=e,c=0==a?0:o+1,l=o+Math.min(i.length,s);n({records:i,paginationInfo:{count:a,currentPage:o/s,firstRecord:c,lastRecord:l,hasMore:r||l<a,total:r?void 0:a}})})).catch((t=>r(t)))}))}static getCachedRecords(t){return _.getRepository(t).getFromCache()}}_._repositories=new Map,_._loadingStatus=new Map;class b{constructor(t,e,r){this._dataUnitInMemoryLoader=new n(t,e,r)}get dataUnit(){return this._dataUnitInMemoryLoader.dataUnit}get records(){return this._dataUnitInMemoryLoader.records}set records(t){this._dataUnitInMemoryLoader.records=t}get metadata(){return this._dataUnitInMemoryLoader.metadata}set metadata(t){this._dataUnitInMemoryLoader.metadata=t}removeLoader(t,e){return this._dataUnitInMemoryLoader.removeLoader(t,e)}static getConvertedValue(t,e,r){return n.getConvertedValue(t,e,r)}}function v(t,e){var n,r;return void 0!==(null===(n=t[e])||void 0===n?void 0:n.value)?null===(r=t[e])||void 0===r?void 0:r.value:t[e]}b.IN_MEMORY_DATA_UNIT_NAME=n.IN_MEMORY_DATA_UNIT_NAME;class y{canSlice(){return!1}processSortingSide(t,e,n){var r;const a=[],o=[];if(null!=t.sort){if(0===n.length)return{localSorting:t.sort,serverSorting:[]};for(const n of t.sort){const t=e.getField(n.field);"true"===(null===(r=null==t?void 0:t.properties)||void 0===r?void 0:r.calculated)||(null==t?void 0:t.userInterface)===s.LONGTEXT?a.push(n):o.push(n)}}return{localSorting:a,serverSorting:o}}async load(t,e,n){var r,a;if(null==t.metadata)return Promise.resolve({records:[],loadingInfo:n});try{const s=null!==(a=null===(r=e.filters)||void 0===r?void 0:r.filter((t=>!t.name.startsWith("FILTRO_COLUNA_"))))&&void 0!==a?a:[],{localSorting:o,serverSorting:i}=this.processSortingSide(e,t,s),c=this.getFieldsList(t),u="DatasetSP.loadRecords",d=this.buildRequestBody(u,c,t,e,n,i,s),m=n.quiet?{urlParams:{quietMode:"true"}}:void 0,{result:h,pagerID:f,askRowsLimit:p}=await l.get().callServiceBroker(u,d,m),g=this.processRecords(t,c,h),_=null!=f,b=n.count+g.length,v=t.hasNewRecord(),y=o.length>0,P=!_&&y;return P&&v&&t.setWaitingToReload(!0),Promise.resolve({records:g,loadingInfo:Object.assign(Object.assign({},n),{pagerId:f,loadingInProgress:_,total:_?void 0:b,count:b,needReload:P&&!v,askRowsLimit:p,hasLocalSorting:y})})}catch(t){return console.error(t),Promise.reject(t)}}async loadRowMetadata(t,e,n,r={}){try{const a="DatasetSP.loadRowMetadata",s=await this.buildRequestBodyLoadRowMetadata({snkDataUnit:t,fieldName:e,metadataName:n,serviceName:a,updatedFields:r});return await l.get().callServiceBroker(a,s)}catch(t){return console.error(t),Promise.reject(t)}}async buildRequestBodyLoadRowMetadata({snkDataUnit:t,serviceName:e,fieldName:n,metadataName:r,updatedFields:a}){const s=t.dataUnit,o=N.parseDataUnitName(s.name).entityName,i=(await t.getSelectedRecordsIDsInfo()).reduce(((t,e)=>(t[e.name]=e.value,t)),{}),c=s.getSelectedRecord(),l=s.metadata.fields.filter((({standAlone:t,name:e})=>!t&&!e.includes("."))).map((({name:t})=>t)),u=l.reduce(((t,e,n)=>{const r=v(c,e),s=v(a,e);return t[n]=void 0!==s?s:r,t}),{});return JSON.stringify({serviceName:e,requestBody:{dataSetID:s.dataUnitId,entityName:o,standAlone:!1,metadataName:r,fieldName:n,fields:l,record:{pk:i,oldPk:i,values:u}}})}getFieldsList(t){let e=["__record__id__","__record__label__"];return t.metadata.fields.forEach((t=>{t.standAlone||(e=e.concat(this.getFieldNames(t)))})),e}getStandAloneFieldsList(t){let e={};return t.metadata.fields.forEach((t=>{t.standAlone&&(e=Object.assign(Object.assign({},e),{[t.name]:{fieldType:t.dataType,userType:t.userInterface}}))})),e}getFieldNames(t){const e=this.getSearchDescriptionField(t);return null==e?t.name:[t.name,e]}buildRequestBody(t,e,n,r,a,s,o){const i=n.dataUnitId,c=N.parseDataUnitName(n.name).entityName,l=!(!r.limit&&!r.offset),u={serviceName:t,requestBody:{dataSetID:i,fields:e,entityName:c,pageNumber:a.pageNumber,totalRecordsCount:a.count,pagerID:a.pagerId,standAlone:!1,standAloneFieldsMD:Object.assign({__record__id__:{fieldType:"S",userType:"P"},__record__label__:{fieldType:"S",userType:"P"}},this.getStandAloneFieldsList(n)),tryJoinedFields:!0,parallelLoader:l,crudListener:`br.com.sankhya.bff.${this.getModuleName()}.BFFDataUnitDatasetAdapter`,txProperties:this.getTxProperties(n,r,s,o),useDefaultRowsLimit:!1}};return JSON.stringify(u)}getModuleName(){return r.getContextValue("__SNK__APPLICATION__").getModuleName().replace("-bff","")}getTxProperties(t,e,n,r){const a={"__DATA_UNIT_ADAPTER__[dataUnitName]":t.name};0!==r.length&&(a["__DATA_UNIT_ADAPTER__[criteria]"]=JSON.stringify(r)),null!=n&&0!==n.length&&(a["__DATA_UNIT_ADAPTER__[sorting]"]=JSON.stringify(n)),null!=e.parentRecordId&&(a["__DATA_UNIT_ADAPTER__[parentRecordId]"]=e.parentRecordId);const s=t.getGlobalLoaderProps();return null==s||0===s.size||Array.from(s.entries()).forEach((([t,e])=>{a[t]=e})),a}processRecords(t,e,n){return n.map((n=>{const r={__record__id__:n[0],__record__label__:n[1],__record__metadata__:n[n.length-1]._rmd};return t.metadata.fields.forEach((t=>{r[t.name]=this.buildFieldValue(t,e,n)})),r}))}buildFieldValue(t,e,n){const r=e.indexOf(t.name);if(r<0)return null;const o=n[r];if(a.isEmpty(o))return null;const i=this.getSearchDescriptionField(t);if(null!=i){const t=e.indexOf(i);if(t>=0)return{value:o,label:n[t]}}return t.userInterface===s.SEARCH?isNaN(Number(o))?o:Number(o):b.getConvertedValue(t,o)}getSearchDescriptionField(t){if(t.userInterface===s.SEARCH){const{ENTITYNAME:e,mergedFrom:n,DESCRIPTIONFIELD:r}=t.properties;if(!a.isEmpty(r))return null!=n?`${n}.${e}.${r}`:`${e}.${r}`}}}var P;!function(t){t.CANCEL="CANCEL",t.CONTINUE="CONTINUE",t.LOAD_ALL="LOAD_ALL"}(P||(P={}));class D{constructor(){}static async debounce(t,e){const n=t.name;D._debouncingTimeouts[n]&&(clearTimeout(D._debouncingTimeouts[n]),delete D._debouncingTimeouts[n]),D._debouncingTimeouts[n]=setTimeout((()=>{delete D._debouncingTimeouts[n],e()}),100)}static async loadData(t,e){return new Promise(((n,r)=>{D.debounce(t,(()=>{_.loadData(t,e,this.loadFromServer).then((t=>n(t))).catch((t=>r(t)))}))}))}static getCachedRecords(t){return _.getCachedRecords(t)}static async loadFromServer(t,e,n){try{n=D.registryLoading(t,n);const r=await D.callLoader(t,e,n);if(null==r)return;const a=r.records,s=D.buildPaginationInfo(a.length,e,r.loadingInfo),o=null==s?a:a.slice(0,s.lastRecord);return Promise.resolve({records:o,paginationInfo:s})}catch(t){return console.error(t),Promise.reject(t)}}static async callLoader(t,e,n,r){null==r&&(r=new y);const a=await r.load(t,e,n),s=a.loadingInfo;if(D.isOldRequest(t,s))return Promise.resolve(void 0);if(this.handleCache(r,s,t,a.records),t.cancelPagination)return this.handlePaginationCanceled(t,a);if(this.canFinishPagination(t,s))return Promise.resolve(a);const o=Object.assign(Object.assign({},e),{offset:s.count});let i=this.buildNewLoadingInfo(s);if(this.canProceedPagination(s))return this.recallLoader(t,o,i,r,a);const c=await async function(){return new Promise((t=>{const{checkboxContainer:e,checkbox:n}=function(){const t=document.createElement("div");t.style.marginBottom="14px",t.style.display="flex",t.style.alignItems="center";const{checkbox:e,checkboxLabel:n}=function(){const t=document.createElement("input");t.type="checkbox",t.id="loadAll";const e=document.createElement("label");return e.htmlFor="loadAll",e.textContent="Carregar tudo",e.style.marginLeft="5px",{checkbox:t,checkboxLabel:e}}();return t.appendChild(e),t.appendChild(n),{checkboxContainer:t,checkbox:e}}(),r=function(t,e){const n=document.createElement("ez-popup");return n.opened=!0,n.size="x-small",n.ezTitle="Aviso",n.heightMode="auto",n.addEventListener("ezClosePopup",(()=>{document.body.removeChild(n),t(e.checked?P.LOAD_ALL:P.CONTINUE)}),{once:!0}),n.addEventListener("ezPopupAction",(()=>{document.body.removeChild(n),t(P.CANCEL)}),{once:!0}),n}(t,n),a=function(){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.fontFamily="var(--font-pattern, Roboto)",t.style.fontSize="var(--text--medium)",t}();a.appendChild(function(){const t=document.createElement("div"),e=document.createElement("p"),n=document.createElement("p"),r=document.createElement("p");return r.style.fontWeight="var(--text-weight--large, 600)",e.textContent="Uma quantidade de registros muito grande está sendo carregada.",n.textContent="Recomendamos que a paginação seja cancelada e que seja criado um filtro para os registros.",r.textContent="Deseja cancelar o carregamento?",t.appendChild(e),t.appendChild(n),t.appendChild(r),t}()),a.appendChild(e);const s=function(){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="row",t.style.justifyContent="end",t.style.gap="5px",t}();s.appendChild(function(t,e,n){const r=document.createElement("ez-button");return r.label="Continuar",r.size="medium",r.onclick=()=>{document.body.removeChild(t),n(e.checked?P.LOAD_ALL:P.CONTINUE)},r}(r,n,t)),s.appendChild(function(t,e){const n=document.createElement("ez-button");return n.label="Cancelar paginação",n.size="medium",n.classList.add("ez-button--primary"),n.onclick=()=>{document.body.removeChild(t),e(P.CANCEL)},n}(r,t)),a.appendChild(s),r.appendChild(a),document.body.appendChild(r)}))}();return c===P.CANCEL?this.handlePaginationCanceled(t,a):(c===P.LOAD_ALL&&(i=Object.assign(Object.assign({},i),{loadAllRecords:!0})),i=Object.assign(Object.assign({},i),{lastRowLimitAsked:i.count}),this.recallLoader(t,o,i,r,a))}static buildNewLoadingInfo(t){return Object.assign(Object.assign({},t),{pageNumber:(t.pageNumber||0)+1,quiet:!0})}static handleCache(t,e,n,r){const a=!t.canSlice()||0===e.count;_.cacheRecords(n,r,a,e.loadingInProgress)}static recallLoader(t,e,n,r,a){return this.callLoader(t,e,n,r).then((e=>D.afterLoadingPage(t,e.loadingInfo))).catch((t=>console.error(t))),Promise.resolve(a)}static canFinishPagination(t,e){return!_.isCacheEnabled(t)||!e.loadingInProgress}static canProceedPagination(t){const{count:e,askRowsLimit:n,loadAllRecords:r,lastRowLimitAsked:a}=t;if(r)return!0;if(!e||!n)return!0;const s=Number(n);return e<s||e<s+(a||0)}static handlePaginationCanceled(t,e){t.cancelPagination=!1;let n=e.loadingInfo;return n=Object.assign(Object.assign({},n),{total:n.count,loadingInProgress:!1,pagerId:void 0,needReload:n.hasLocalSorting}),Promise.resolve({records:e.records,loadingInfo:n})}static afterLoadingPage(t,e){_.setLoadingStatus(t,e.loadingInProgress);const n=t.getPaginationInfo();if(null==n)return;const r=e.count;e.loadingInProgress?t.updatePagination(Object.assign(Object.assign({},n),{count:r,loadingInProgress:!0})):e.needReload?t.gotoPage(0):t.updatePagination(Object.assign(Object.assign({},n),{total:r,count:r,loadingInProgress:!1}))}static registryLoading(t,e){return null==e&&(e={requestTime:(new Date).getTime(),count:0}),D._requestTimeByDataUnit.set(t.name,e.requestTime),e}static isOldRequest(t,e){return D._requestTimeByDataUnit.get(t.name)>e.requestTime}static buildPaginationInfo(t,e,n){let{limit:r,offset:a}=e;if(!r)return;1===n.pageNumber&&(a=0);const{total:s,count:o,loadingInProgress:i,askRowsLimit:c}=n,l=0===o||0===t?0:a+1,u=a+Math.min(t,r);return{total:s,count:o,lastRecord:u,firstRecord:l,currentPage:a/r,hasMore:u<o||i,askRowsLimit:c}}}D._requestTimeByDataUnit=new Map,D._debouncingTimeouts={};const R=/dd:\/\/([^/]+)\/([^/?]+)/;class N{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",u.gql`query($name: String!) {
1
+ import{ObjectUtils as t,DataUnit as e,DataUnitInMemoryLoader as n,ApplicationContext as r,StringUtils as a,UserInterface as s,DataUnitStorage as o,DataType as i,ChangeOperation as c}from"@sankhyalabs/core";import{D as l,d as u}from"./p-d62228fb.js";import{DISTINCT_FILTER_NAME_PREFIX as d}from"@sankhyalabs/ezui/dist/collection/utils/constants";import{DataUnitTransient as m}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{ColumnFilterManager as h}from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import f from"@sankhyalabs/core/dist/utils/SortingUtils";import{R as p}from"./p-688dcb4c.js";class g{constructor(t){this._list=[],this._listCopy=[],this._listLastUpdate=0,this._listCopyLastUpdate=0,this._equalsFunction=t}async load(t,e,n,r){let a=[].concat(this._list);null!=t&&(a=this._list.filter((e=>t(e)))),null!=e&&(a=a.sort(e));const s=a.length;if(null!=r){const t=n||0;a=a.slice(t,r?t+r:a.length)}return Promise.resolve({result:a,count:s})}async distict(t){const e=[];let n=!1;for(const r of this._list){const a=t(r);null!=a&&(null!=a.value?e.push(a):n=!0)}return n&&e.push({key:"",value:null}),Promise.resolve(new Map(e.map((t=>[t.key,t.value]))))}async push(t){this.updateList([...this._list,...t])}async clear(){this.updateList([])}async delete(t){const e=this._list.filter((e=>{for(const n of t)if(this._equalsFunction(e,n))return!1;return!0}));this.updateList(e)}async update(t){const e=this._list.map((e=>{const n=t.find((t=>this._equalsFunction(e,t)));return null==n?e:n}));this.updateList(e)}async insert(t,e){const n=this._list.indexOf(t);if(-1==n)return void this.push(e);const r=this._list.slice(0,n).concat(e).concat(this._list.slice(n));this.updateList(r)}isOperating(){return!0}async isEmpty(){return Promise.resolve(0===this._list.length)}async count(){return Promise.resolve(this._list.length)}getFromCache(){return this._listLastUpdate>this._listCopyLastUpdate&&(this._listCopyLastUpdate=this._listLastUpdate,this._listCopy=t.copy(this._list)),this._listCopy}updateList(t){this._list=t,this._listLastUpdate=Date.now()}}class _{static setLoadingStatus(t,e){this._loadingStatus.set(t.name,e)}static isCacheEnabled(t){return!0}static cacheRecords(t,e,n,r){_.setLoadingStatus(t,r),_.isCacheEnabled(t)?this.getRepository(t).push(e):n&&this._repositories.delete(t.name)}static getSortingFunction(t,e){return f.getSortingFunction(t,e)}static async getDistinct(t,e){if(!_.isCacheEnabled(t))return Promise.resolve(h.compileDistinct(e,t));let n;const r=t.getLastLoadRequest();if(null!=r){const a=h.getColumnFilters(r.filters,e);n=h.getFilterFunction(t,Array.from(a.values()))}return new Promise(((r,a)=>{_.getRepository(t).distict((r=>{if(null!=n&&!n(r))return;const a=r[e];if(null==a)return{key:null,value:null};const s=null!=a.value?a.value:a;return{key:t.getFormattedValue(e,a),value:s}})).then((t=>{r(null!=t?Array.from(t.entries()).map((([t,e])=>({label:t,value:e,check:!0}))):void 0)})).catch((t=>a(t)))}))}static async loadData(t,n,r){try{if(_.isCacheEnabled(t)){if(["EZ_GRID_LOADING_SOURCE",e.CHANGING_PAGE_LOADING_SOURCE,e.ALL_RECORDS_SELECTION_SOURCE].includes(n.source)&&!await _.getRepository(t).isEmpty())return _.loadFromCache(t,n);_.getRepository(t).clear().catch((()=>{}))}return r(t,n)}catch(t){return console.error(t),Promise.reject(t)}}static insertRecords(t,e,n){_.isCacheEnabled(t)&&_.getRepository(t).insert(e,n)}static updateRecords(t,e){_.isCacheEnabled(t)&&_.getRepository(t).update(e)}static removeRecords(t,e){_.isCacheEnabled(t)&&_.getRepository(t).delete(e)}static async countRecords(t){return _.isCacheEnabled(t)?_.getRepository(t).count():Promise.resolve(0)}static getRepository(t){const e=t.name;return _._repositories.has(e)||_._repositories.set(e,new g(((t,e)=>t.__record__id__===e.__record__id__))),_._repositories.get(e)}static async loadFromCache(t,e){return new Promise(((n,r)=>{const a=h.getColumnFilters(e.filters,""),{limit:s,offset:o,sort:i}=e;_.getRepository(t).load(h.getFilterFunction(t,Array.from(a.values())),_.getSortingFunction(t,i),o,s).then((e=>{const r=_._loadingStatus.get(t.name),{count:a,result:i}=e,c=0==a?0:o+1,l=o+Math.min(i.length,s);n({records:i,paginationInfo:{count:a,currentPage:o/s,firstRecord:c,lastRecord:l,hasMore:r||l<a,total:r?void 0:a}})})).catch((t=>r(t)))}))}static getCachedRecords(t){return _.getRepository(t).getFromCache()}}_._repositories=new Map,_._loadingStatus=new Map;class b{constructor(t,e,r){this._dataUnitInMemoryLoader=new n(t,e,r)}get dataUnit(){return this._dataUnitInMemoryLoader.dataUnit}get records(){return this._dataUnitInMemoryLoader.records}set records(t){this._dataUnitInMemoryLoader.records=t}get metadata(){return this._dataUnitInMemoryLoader.metadata}set metadata(t){this._dataUnitInMemoryLoader.metadata=t}removeLoader(t,e){return this._dataUnitInMemoryLoader.removeLoader(t,e)}static getConvertedValue(t,e,r){return n.getConvertedValue(t,e,r)}}function v(t,e){var n,r;return void 0!==(null===(n=t[e])||void 0===n?void 0:n.value)?null===(r=t[e])||void 0===r?void 0:r.value:t[e]}b.IN_MEMORY_DATA_UNIT_NAME=n.IN_MEMORY_DATA_UNIT_NAME;class y{canSlice(){return!1}processSortingSide(t,e,n){var r;const a=[],o=[];if(null!=t.sort){if(0===n.length)return{localSorting:t.sort,serverSorting:[]};for(const n of t.sort){const t=e.getField(n.field);"true"===(null===(r=null==t?void 0:t.properties)||void 0===r?void 0:r.calculated)||(null==t?void 0:t.userInterface)===s.LONGTEXT?a.push(n):o.push(n)}}return{localSorting:a,serverSorting:o}}async load(t,e,n){var r,a;if(null==t.metadata)return Promise.resolve({records:[],loadingInfo:n});try{const s=null!==(a=null===(r=e.filters)||void 0===r?void 0:r.filter((t=>!t.name.startsWith("FILTRO_COLUNA_"))))&&void 0!==a?a:[],{localSorting:o,serverSorting:i}=this.processSortingSide(e,t,s),c=this.getFieldsList(t),u="DatasetSP.loadRecords",d=this.buildRequestBody(u,c,t,e,n,i,s),m=n.quiet?{urlParams:{quietMode:"true"}}:void 0,{result:h,pagerID:f,askRowsLimit:p}=await l.get().callServiceBroker(u,d,m),g=this.processRecords(t,c,h),_=null!=f,b=n.count+g.length,v=t.hasNewRecord(),y=o.length>0,P=!_&&y;return P&&v&&t.setWaitingToReload(!0),Promise.resolve({records:g,loadingInfo:Object.assign(Object.assign({},n),{pagerId:f,loadingInProgress:_,total:_?void 0:b,count:b,needReload:P&&!v,askRowsLimit:p,hasLocalSorting:y})})}catch(t){return console.error(t),Promise.reject(t)}}async loadRowMetadata(t,e,n,r={}){try{const a="DatasetSP.loadRowMetadata",s=await this.buildRequestBodyLoadRowMetadata({snkDataUnit:t,fieldName:e,metadataName:n,serviceName:a,updatedFields:r});return await l.get().callServiceBroker(a,s)}catch(t){return console.error(t),Promise.reject(t)}}async buildRequestBodyLoadRowMetadata({snkDataUnit:t,serviceName:e,fieldName:n,metadataName:r,updatedFields:a}){const s=t.dataUnit,o=N.parseDataUnitName(s.name).entityName,i=(await t.getSelectedRecordsIDsInfo()).reduce(((t,e)=>(t[e.name]=e.value,t)),{}),c=s.getSelectedRecord(),l=s.metadata.fields.filter((({standAlone:t,name:e})=>!t&&!e.includes("."))).map((({name:t})=>t)),u=l.reduce(((t,e,n)=>{const r=v(c,e),s=v(a,e);return t[n]=void 0!==s?s:r,t}),{});return JSON.stringify({serviceName:e,requestBody:{dataSetID:s.dataUnitId,entityName:o,standAlone:!1,metadataName:r,fieldName:n,fields:l,record:{pk:i,oldPk:i,values:u}}})}getFieldsList(t){let e=["__record__id__","__record__label__"];return t.metadata.fields.forEach((t=>{t.standAlone||(e=e.concat(this.getFieldNames(t)))})),e}getStandAloneFieldsList(t){let e={};return t.metadata.fields.forEach((t=>{t.standAlone&&(e=Object.assign(Object.assign({},e),{[t.name]:{fieldType:t.dataType,userType:t.userInterface}}))})),e}getFieldNames(t){const e=this.getSearchDescriptionField(t);return null==e?t.name:[t.name,e]}buildRequestBody(t,e,n,r,a,s,o){const i=n.dataUnitId,c=N.parseDataUnitName(n.name).entityName,l=!(!r.limit&&!r.offset),u={serviceName:t,requestBody:{dataSetID:i,fields:e,entityName:c,pageNumber:a.pageNumber,totalRecordsCount:a.count,pagerID:a.pagerId,standAlone:!1,standAloneFieldsMD:Object.assign({__record__id__:{fieldType:"S",userType:"P"},__record__label__:{fieldType:"S",userType:"P"}},this.getStandAloneFieldsList(n)),tryJoinedFields:!0,parallelLoader:l,crudListener:`br.com.sankhya.bff.${this.getModuleName()}.BFFDataUnitDatasetAdapter`,txProperties:this.getTxProperties(n,r,s,o),useDefaultRowsLimit:!1}};return JSON.stringify(u)}getModuleName(){return r.getContextValue("__SNK__APPLICATION__").getModuleName().replace("-bff","")}getTxProperties(t,e,n,r){const a={"__DATA_UNIT_ADAPTER__[dataUnitName]":t.name};0!==r.length&&(a["__DATA_UNIT_ADAPTER__[criteria]"]=JSON.stringify(r)),null!=n&&0!==n.length&&(a["__DATA_UNIT_ADAPTER__[sorting]"]=JSON.stringify(n)),null!=e.parentRecordId&&(a["__DATA_UNIT_ADAPTER__[parentRecordId]"]=e.parentRecordId);const s=t.getGlobalLoaderProps();return null==s||0===s.size||Array.from(s.entries()).forEach((([t,e])=>{a[t]=e})),a}processRecords(t,e,n){return n.map((n=>{const r={__record__id__:n[0],__record__label__:n[1],__record__metadata__:n[n.length-1]._rmd};return t.metadata.fields.forEach((t=>{r[t.name]=this.buildFieldValue(t,e,n)})),r}))}buildFieldValue(t,e,n){const r=e.indexOf(t.name);if(r<0)return null;const o=n[r];if(a.isEmpty(o))return null;const i=this.getSearchDescriptionField(t);if(null!=i){const t=e.indexOf(i);if(t>=0)return{value:o,label:n[t]}}return t.userInterface===s.SEARCH?isNaN(Number(o))?o:Number(o):b.getConvertedValue(t,o)}getSearchDescriptionField(t){if(t.userInterface===s.SEARCH){const{ENTITYNAME:e,mergedFrom:n,DESCRIPTIONFIELD:r}=t.properties;if(!a.isEmpty(r))return null!=n?`${n}.${e}.${r}`:`${e}.${r}`}}}var P;!function(t){t.CANCEL="CANCEL",t.CONTINUE="CONTINUE",t.LOAD_ALL="LOAD_ALL"}(P||(P={}));class D{constructor(){}static async debounce(t,e){const n=t.name;D._debouncingTimeouts[n]&&(clearTimeout(D._debouncingTimeouts[n]),delete D._debouncingTimeouts[n]),D._debouncingTimeouts[n]=setTimeout((()=>{delete D._debouncingTimeouts[n],e()}),100)}static async loadData(t,e){return new Promise(((n,r)=>{D.debounce(t,(()=>{_.loadData(t,e,this.loadFromServer).then((t=>n(t))).catch((t=>r(t)))}))}))}static getCachedRecords(t){return _.getCachedRecords(t)}static async loadFromServer(t,e,n){try{n=D.registryLoading(t,n);const r=await D.callLoader(t,e,n);if(null==r)return;const a=r.records,s=D.buildPaginationInfo(a.length,e,r.loadingInfo),o=null==s?a:a.slice(0,s.lastRecord);return Promise.resolve({records:o,paginationInfo:s})}catch(t){return console.error(t),Promise.reject(t)}}static async callLoader(t,e,n,r){null==r&&(r=new y);const a=await r.load(t,e,n),s=a.loadingInfo;if(D.isOldRequest(t,s))return Promise.resolve(void 0);if(this.handleCache(r,s,t,a.records),t.cancelPagination)return this.handlePaginationCanceled(t,a);if(this.canFinishPagination(t,s))return Promise.resolve(a);const o=Object.assign(Object.assign({},e),{offset:s.count});let i=this.buildNewLoadingInfo(s);if(this.canProceedPagination(s))return this.recallLoader(t,o,i,r,a);const c=await async function(){return new Promise((t=>{const{checkboxContainer:e,checkbox:n}=function(){const t=document.createElement("div");t.style.marginBottom="14px",t.style.display="flex",t.style.alignItems="center";const{checkbox:e,checkboxLabel:n}=function(){const t=document.createElement("input");t.type="checkbox",t.id="loadAll";const e=document.createElement("label");return e.htmlFor="loadAll",e.textContent="Carregar tudo",e.style.marginLeft="5px",{checkbox:t,checkboxLabel:e}}();return t.appendChild(e),t.appendChild(n),{checkboxContainer:t,checkbox:e}}(),r=function(t,e){const n=document.createElement("ez-popup");return n.opened=!0,n.size="x-small",n.ezTitle="Aviso",n.heightMode="auto",n.addEventListener("ezClosePopup",(()=>{document.body.removeChild(n),t(e.checked?P.LOAD_ALL:P.CONTINUE)}),{once:!0}),n.addEventListener("ezPopupAction",(()=>{document.body.removeChild(n),t(P.CANCEL)}),{once:!0}),n}(t,n),a=function(){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.fontFamily="var(--font-pattern, Roboto)",t.style.fontSize="var(--text--medium)",t}();a.appendChild(function(){const t=document.createElement("div"),e=document.createElement("p"),n=document.createElement("p"),r=document.createElement("p");return r.style.fontWeight="var(--text-weight--large, 600)",e.textContent="Uma quantidade de registros muito grande está sendo carregada.",n.textContent="Recomendamos que a paginação seja cancelada e que seja criado um filtro para os registros.",r.textContent="Deseja cancelar o carregamento?",t.appendChild(e),t.appendChild(n),t.appendChild(r),t}()),a.appendChild(e);const s=function(){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="row",t.style.justifyContent="end",t.style.gap="5px",t}();s.appendChild(function(t,e,n){const r=document.createElement("ez-button");return r.label="Continuar",r.size="medium",r.onclick=()=>{document.body.removeChild(t),n(e.checked?P.LOAD_ALL:P.CONTINUE)},r}(r,n,t)),s.appendChild(function(t,e){const n=document.createElement("ez-button");return n.label="Cancelar paginação",n.size="medium",n.classList.add("ez-button--primary"),n.onclick=()=>{document.body.removeChild(t),e(P.CANCEL)},n}(r,t)),a.appendChild(s),r.appendChild(a),document.body.appendChild(r)}))}();return c===P.CANCEL?this.handlePaginationCanceled(t,a):(c===P.LOAD_ALL&&(i=Object.assign(Object.assign({},i),{loadAllRecords:!0})),i=Object.assign(Object.assign({},i),{lastRowLimitAsked:i.count}),this.recallLoader(t,o,i,r,a))}static buildNewLoadingInfo(t){return Object.assign(Object.assign({},t),{pageNumber:(t.pageNumber||0)+1,quiet:!0})}static handleCache(t,e,n,r){const a=!t.canSlice()||0===e.count;_.cacheRecords(n,r,a,e.loadingInProgress)}static recallLoader(t,e,n,r,a){return this.callLoader(t,e,n,r).then((e=>D.afterLoadingPage(t,e.loadingInfo))).catch((t=>console.error(t))),Promise.resolve(a)}static canFinishPagination(t,e){return!_.isCacheEnabled(t)||!e.loadingInProgress}static canProceedPagination(t){const{count:e,askRowsLimit:n,loadAllRecords:r,lastRowLimitAsked:a}=t;if(r)return!0;if(!e||!n)return!0;const s=Number(n);return e<s||e<s+(a||0)}static handlePaginationCanceled(t,e){t.cancelPagination=!1;let n=e.loadingInfo;return n=Object.assign(Object.assign({},n),{total:n.count,loadingInProgress:!1,pagerId:void 0,needReload:n.hasLocalSorting}),Promise.resolve({records:e.records,loadingInfo:n})}static afterLoadingPage(t,e){_.setLoadingStatus(t,e.loadingInProgress);const n=t.getPaginationInfo();if(null==n)return;const r=e.count;e.loadingInProgress?t.updatePagination(Object.assign(Object.assign({},n),{count:r,loadingInProgress:!0})):e.needReload?t.gotoPage(0):t.updatePagination(Object.assign(Object.assign({},n),{total:r,count:r,loadingInProgress:!1}))}static registryLoading(t,e){return null==e&&(e={requestTime:(new Date).getTime(),count:0}),D._requestTimeByDataUnit.set(t.name,e.requestTime),e}static isOldRequest(t,e){return D._requestTimeByDataUnit.get(t.name)>e.requestTime}static buildPaginationInfo(t,e,n){let{limit:r,offset:a}=e;if(!r)return;1===n.pageNumber&&(a=0);const{total:s,count:o,loadingInProgress:i,askRowsLimit:c}=n,l=0===o||0===t?0:a+1,u=a+Math.min(t,r);return{total:s,count:o,lastRecord:u,firstRecord:l,currentPage:a/r,hasMore:u<o||i,askRowsLimit:c}}}D._requestTimeByDataUnit=new Map,D._debouncingTimeouts={};const R=/dd:\/\/([^/]+)\/([^/?]+)/;class N{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",u.gql`query($name: String!) {
2
2
  $queryAlias$: fetchDataUnit(name: $name){
3
3
  name
4
4
  fields{
@@ -0,0 +1 @@
1
+ import{r as i,c as t,h as s,H as e,F as a}from"./p-d2d301a6.js";import{I as o}from"./p-3653374d.js";import"./p-d62228fb.js";import{P as r}from"./p-41c3bee5.js";import"@sankhyalabs/core";import"./p-0f3698af.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-ff1990ad.js";import"./p-1435701f.js";import"./p-1d19a5b0.js";import{ApplicationUtils as n}from"@sankhyalabs/ezui/dist/collection/utils";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-8d884fab.js";const h=class{constructor(s){i(this,s),this.pesquisaGridSelectItem=t(this,"pesquisaGridSelectItem",7),this._pesquisaFetcher=new r,this.metadata=void 0,this.dataSource=[],this.pkField=void 0,this.descriptionField=void 0,this.entityName=void 0,this.shouldLoadConfig=!1,this._gridConfig=void 0,this._inMemoryLoader=void 0,this._dataunit=void 0}observeDataSource(i){this._inMemoryLoader&&this._dataunit&&i&&(this._inMemoryLoader.records=[...i])}observeMetadata(){this.initializeDataUnit()}async observeShouldLoadConfig(i){i&&!this._gridConfig&&await this.loadGridConfig()}async loadGridConfig(){this._gridConfig=await this._pesquisaFetcher.loadPesquisaGridConfig(this.entityName)}initializeDataUnit(){var i;this.metadata&&(this._inMemoryLoader=new o(this.metadata,null!==(i=this.dataSource)&&void 0!==i?i:[]),this._dataunit=this._inMemoryLoader.dataUnit,this._dataunit.pageSize=0)}handleDbClick(i){this.pesquisaGridSelectItem.emit({value:i[this.pkField],label:i[this.descriptionField]})}async handleConfigChanged({detail:i}){var t;const s=null!==(t=null==i?void 0:i.columns)&&void 0!==t?t:[];await this._pesquisaFetcher.savePesquisaGridConfig(this.entityName,s)}render(){if(this.metadata&&this._dataunit)return s(e,null,s("ez-grid",{dataUnit:this._dataunit,config:this._gridConfig,canEdit:!1,suppressCheckboxColumn:!0,compact:!0,autoFocus:!1,onEzDoubleClick:({detail:i})=>this.handleDbClick(i),onConfigChange:async i=>this.handleConfigChanged(i)}))}static get watchers(){return{dataSource:["observeDataSource"],metadata:["observeMetadata"],shouldLoadConfig:["observeShouldLoadConfig"]}}};h.style=".sc-pesquisa-grid-h{background:var(--background--xlight, #FFF);overflow-x:auto}ez-grid.sc-pesquisa-grid{--ez-grid__container--shadow:none;--ez-grid__header--shadow:none}";const l=class{constructor(s){i(this,s),this.pesquisaTreeSelectItem=t(this,"pesquisaTreeSelectItem",7),this.treeLoader=void 0,this.argument=void 0,this.allowsNonAnalytic=!1,this.shouldLoadTree=!1,this.items=[]}async applyFilter(){await this._tree.applyFilter(this.argument)}async observeShouldLoadTree(i){!i||this.items.length>0||await this.loadTree()}async loadTree(){if(!this.shouldLoadTree)return;if(!this.treeLoader||"function"!=typeof this.treeLoader)return;const i=await this.treeLoader((this.argument||"").trim());this.items=[...i]}expandOrCloseAllItems(i,t){return i.map((i=>Object.assign(Object.assign({},i),{expanded:t,children:i.children?this.expandOrCloseAllItems(i.children,t):void 0})))}handleExpandAll(){this.items=[...this.expandOrCloseAllItems(this.items,!0)]}handleCloseAll(){this.items=[...this.expandOrCloseAllItems(this.items,!1)]}handleDbClick(i){var t;this.allowsNonAnalytic||(null===(t=i.props)||void 0===t?void 0:t.analitico)?this.pesquisaTreeSelectItem.emit({value:i.id,label:i.label}):n.error("Erro","Há pelo menos um registro inválido selecionado. Você deve selecionar itens do tipo 'analítico'.")}renderEmptyMessage(){return s("div",{class:"ez-flex ez-flex--justify-center ez-flex--align-items-center ez-margin--large ez-text ez-text--xlarge ez-text--secondary"},s("span",null,"Nenhum registro encontrado..."))}render(){var i;return s(e,null,(null===(i=this.items)||void 0===i?void 0:i.length)?s(a,null,s("div",{class:"actions-container"},s("ez-button",{size:"small",mode:"icon",class:"ez-margin-right--small",iconName:"show-list",title:"Expandir",onClick:()=>this.handleExpandAll()}),s("ez-button",{size:"small",mode:"icon",iconName:"hide-list",title:"Recolher",onClick:()=>this.handleCloseAll()})),s("ez-tree",{ref:i=>this._tree=i,onEzDbClickItem:({detail:i})=>this.handleDbClick(i),items:this.items})):this.renderEmptyMessage())}static get watchers(){return{shouldLoadTree:["observeShouldLoadTree"]}}};l.style=".sc-pesquisa-tree-h{--snk-pesquisa--tree__action-container--top:var(--space--sm);--snk-pesquisa--tree__action-container--right:var(--space--small);--snk-pesquisa--tree__min-height:var(--space--extra-large);background:var(--background--xlight, #FFF);position:relative;min-height:var(--snk-pesquisa--tree__min-height);height:100%;display:block;overflow-y:auto}.sc-pesquisa-tree-h:hover .actions-container.sc-pesquisa-tree{display:flex}.actions-container.sc-pesquisa-tree{flex-direction:row;position:absolute;top:var(--snk-pesquisa--tree__action-container--top);right:var(--snk-pesquisa--tree__action-container--right);display:none}";export{h as pesquisa_grid,l as pesquisa_tree}
@@ -0,0 +1 @@
1
+ import{C as t}from"./p-19dc71e9.js";import{ObjectUtils as e,StringUtils as i}from"@sankhyalabs/core";import{F as s}from"./p-1435701f.js";import{c as r}from"./p-1d19a5b0.js";class n{constructor(t,e,i,s){this._resourceID=e,this._configName=t,this._onConfigChange=i,this._dataUnit=s}addFormLegacyConfig(e){this._configName&&t.addFormLegacyConfig(this._configName,e)}async loadConfig(){return new Promise((e=>{t.loadFormConfig(this._configName,this._resourceID).then((t=>{t=this.buildFormMetadataUITabs(t),this.setConfig(t),e(t)})).catch((t=>{console.warn(t)}))}))}getEmptyConfig(){return this.buildFormMetadataUITabs({fields:[],emptyConfig:!0},!0)}saveConfig(i){const s=e.copy(i);return new Promise((e=>{t.saveFormConfig(i,this._configName,this._resourceID).then((t=>{this.setConfig(Object.assign(Object.assign({},s),t)),e(Object.assign(Object.assign({},s),t))}))}))}saveCardState(e,i,s){return new Promise((r=>{var n;const l=(null===(n=this._config)||void 0===n?void 0:n.cardsState)||new Map,o=l.get(e);l.set(e,"fixed"===s?this.updateFixSequence(Object.assign(Object.assign({},o),{fixed:i.fixed}),l):Object.assign(Object.assign({},o),{[s]:i[s]})),t.saveCardState(l,this._configName,this._resourceID).then((t=>{this._config=Object.assign(Object.assign({},this._config),{cardsState:l}),r(t)}))}))}updateFixSequence(t,e){let i=-1;return Array.from(e.values()).forEach((e=>{e.fixed||delete t.fixSequence,null!=e.fixSequence&&(i=Math.max(i,e.fixSequence))})),t.fixed?t.fixSequence=i+1:delete t.fixSequence,t}hasConfig(t){var e;const i=null!=t?t:this._config;return!(!i||!(null===(e=i.fields)||void 0===e?void 0:e.length))}getFieldsList(t,e=!1){var i;const s=null===(i=this._config)||void 0===i?void 0:i.fields;return this.hasConfig()&&!e?s.map((({label:t,name:e,readOnly:i,visible:s,required:r,tab:n,group:l})=>{var o;if(null==t){const t=null===(o=this._dataUnit)||void 0===o?void 0:o.getField(e);if(!t)return;return Object.assign(Object.assign({},t),{name:null!=e?e:t.name,readOnly:null!=i?i:t.readOnly,visible:null!=s?s:t.visible,required:null!=r?r:t.required,tab:n,group:l})}return{name:e,label:t,readOnly:i,visible:s,required:r,tab:n,group:l}})).filter((e=>this.isFieldVisible(e,t))):this._dataUnit?this._dataUnit.metadata.fields.filter((e=>this.isFieldVisible(e,t))).map((({label:t,name:e,readOnly:i,visible:s,required:r,properties:n})=>({label:t,name:e,readOnly:i,visible:s,required:r,tab:null==n?void 0:n.UITabName}))):[]}isFieldVisible(t,e){if(void 0===t||!1===t.visible)return!1;if(null==e)return!0;const s=i.replaceAccentuatedCharsLower((t.label||t.name).toLocaleLowerCase()),r=i.replaceAccentuatedCharsLower(e.toLocaleLowerCase());return s.includes(r)}getFormConfig(t,e,i=!1){let s=this.getFieldsList(void 0,i);return e&&(s=s.filter((e=>{if(t){const i=t.getField(e.name);if(i&&i.readOnly)return!1}return!e.readOnly}))),Object.assign(Object.assign({},this._config),{fields:s})}setConfig(t){this.isLoaded=!0;const{cardsState:e,summary:i,defaultVars:s}=this._config||{};this._config=Object.assign({},t),e&&(this._config.cardsState=e),i&&(this._config.summary=i),s&&(this._config.defaultVars=s),this._onConfigChange&&this._onConfigChange(Object.assign({},this._config))}getConfig(t,e){return this.getFormConfig(t,null==e||e)}getFormConfigFetcher(){return null==this._formConfigFetcher&&(this._formConfigFetcher=new s),this._formConfigFetcher}async fetchUserAvailableConfigs(){return null!=this._configName?Promise.resolve(void 0):this.getFormConfigFetcher().fetchUserAvailableConfigs(this._configName,this._resourceID)}async fetchLegacyConfig(){return this.getFormConfigFetcher().fetchLegacyConfig(this._configName,this._resourceID)}async fetchDefaultConfig(){return this.getFormConfigFetcher().fetchDefaultConfig(this._configName,this._resourceID)}parseObjectList(t){return t?Array.isArray(t)?t:[t]:[]}buildFormMetadataUITabs(t,e=!1){var i;const s=this.hasConfig(t);if(!e&&(!this._dataUnit||s))return t;(t=this.getFormConfig(this._dataUnit,!1,!0)).tabs=this.parseObjectList(t.tabs),t.emptyConfig=!1,t.defaultConfiguration=!0;const n=this._dataUnit.metadata.fields;for(const e of n){const s=t.fields.find((t=>t.name===e.name)),n=null===(i=e.properties)||void 0===i?void 0:i.UITabName;n&&n!==r.main&&(t.tabs.some((t=>t.label===n))||t.tabs.push({label:n,name:n,order:0,visible:!0}),s&&(s.tab=n))}return t}}export{n as S}
@@ -1,6 +1,6 @@
1
- import{UserInterface as e,DataType as t,ApplicationContext as n,ErrorException as i}from"@sankhyalabs/core";import{d as o,D as r}from"./p-5a7e18f4.js";function a(e){const t=(n=e.fieldsMetadata)&&n.length?n.map((e=>({name:e.fieldName,label:e.description,dataType:u(e.type),userInterface:l(e),properties:s(e)}))):[];var n;return{label:e.entityDescription,name:e.descriptionField,fields:t}}function s(e){const t={};return t.options=function(e){const t=e.options;if(!t)return;const n=[];return Object.keys(t).forEach((e=>{n.push({label:e,value:t[e]})})),n}(e),t.mask=function(e){const t=e.uiType;return t?String(t).toLowerCase():void 0}(e),t}function l(t){const n=t.options;return n&&Object.keys(n).length>0?e.OPTIONSELECTOR:"D"===t.type?e.DATE:"H"===t.type?e.DATETIME:"T"===t.type?e.TIME:"I"===t.type?e.INTEGERNUMBER:void 0}function u(e){switch(e){case"F":case"I":return t.NUMBER;case"D":case"H":return t.DATE;case"B":return t.OBJECT;default:return t.TEXT}}function c(e){return Object.assign({id:e.codigo,label:`${e.caminho} - ${e.descricao}`,bold:"N"===e.analitico,props:{analitico:"S"===e.analitico}},e.no&&{children:e.no.map(c)})}var d,v,f;!function(e){e[e.GRID=0]="GRID",e[e.CARDS=1]="CARDS",e[e.TREE=2]="TREE"}(d||(d={}));class m{constructor(){this._defaultPageSize=100,this._templateByQuery=new Map,this._searchListenersByDataUnit=new Map,this.buldTemplates()}buldTemplates(){this._templateByQuery.set("search",o.gql`query($entityName: String! $argument: String $criteria: InputSearchCriteria $options: InputSearchOptions) {
1
+ import{UserInterface as e,DataType as t,ApplicationContext as n,ErrorException as i}from"@sankhyalabs/core";import{d as o,D as r}from"./p-d62228fb.js";function a(e){const t=(n=e.fieldsMetadata)&&n.length?n.map((e=>({name:e.fieldName,label:e.description,dataType:u(e.type),userInterface:l(e),properties:s(e)}))):[];var n;return{label:e.entityDescription,name:e.descriptionField,fields:t}}function s(e){const t={};return t.options=function(e){const t=e.options;if(!t)return;const n=[];return Object.keys(t).forEach((e=>{n.push({label:e,value:t[e]})})),n}(e),t.mask=function(e){const t=e.uiType;return t?String(t).toLowerCase():void 0}(e),t}function l(t){const n=t.options;return n&&Object.keys(n).length>0?e.OPTIONSELECTOR:"D"===t.type?e.DATE:"H"===t.type?e.DATETIME:"T"===t.type?e.TIME:"I"===t.type?e.INTEGERNUMBER:void 0}function u(e){switch(e){case"F":case"I":return t.NUMBER;case"D":case"H":return t.DATE;case"B":return t.OBJECT;default:return t.TEXT}}function c(e){return Object.assign({id:e.codigo,label:`${e.caminho} - ${e.descricao}`,bold:"N"===e.analitico,props:{analitico:"S"===e.analitico}},e.no&&{children:e.no.map(c)})}var d,v;!function(e){e[e.GRID=0]="GRID",e[e.CARDS=1]="CARDS",e[e.TREE=2]="TREE"}(d||(d={}));class f{constructor(){this._defaultPageSize=100,this._templateByQuery=new Map,this._searchListenersByDataUnit=new Map,this.buldTemplates()}buldTemplates(){this._templateByQuery.set("search",o.gql`query($entityName: String! $argument: String $criteria: InputSearchCriteria $options: InputSearchOptions) {
2
2
  $queryAlias$: search(entityName: $entityName argument: $argument criteria: $criteria options: $options){
3
3
  value
4
4
  label
5
5
  }
6
- }`)}loadSearchOptions(e,n,i,o){var a;const s=(null==n?void 0:n.toString().trim())||void 0;n=isNaN(Number(s))&&s?`%${s}`:s,null==i||i.params.forEach((e=>{e.dataType===t.OBJECT&&(e.value=JSON.stringify(e.value))}));const l=this.applySearchListener(v.beforeSearch,e,n,i,o),u={argument:(null==l?void 0:l.argument)||n,entityName:e,criteria:(null==l?void 0:l.criteria)||i,options:(null==l?void 0:l.searchOptions)||o};return u.options&&(null===(a=u.options)||void 0===a||delete a.dataUnitId),new Promise(((e,t)=>{r.get().callGraphQL({values:u,query:this._templateByQuery.get("search")}).then((t=>{e(t)})).catch((e=>{t(e)}))}))}loadAdvancedSearch(e,o,a,s){var l,u,c,d,f;const m=this.applySearchListener(v.beforeSearch,e,o,a,s),p={argument:(null==m?void 0:m.argument)||o,criteria:(null==m?void 0:m.criteria)||a,searchOptions:Object.assign(Object.assign({},s),null==m?void 0:m.searchOptions)},N={query:{$:null===(l=p.criteria)||void 0===l?void 0:l.expression}};(null===(c=null===(u=p.criteria)||void 0===u?void 0:u.params)||void 0===c?void 0:c.length)>0&&(N.params={param:p.criteria.params.map((e=>{let o=e.value;if("string"==typeof o){const e=/CTX\{([^}]+)\}/.exec(o);e&&(o=n.getContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${e[1]})__`))}if(e.dataType===t.NUMBER&&void 0===o)throw new i("Falha detectada",`O campo ${e.name} deve ser informado.`);let r=e.dataType;return r===t.OBJECT?(o=o.value,r="S"):r=g(e.dataType),{$:o,type:r}}))});const h=null!=s?Object.assign(Object.assign({},null==p?void 0:p.searchOptions),{pkFieldName:s.codeFieldName,label:s.descriptionFieldName,fieldName:s.codeFieldName,useDescriptionOptions:!1,enableRowsCounter:!0}):void 0,S={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:Object.assign({entityName:e,compacted:!1,ignoreEntityCriteria:null!==(d=null==h?void 0:h.ignoreEntityCriteria)&&void 0!==d&&d,limit:this._defaultPageSize,query:{$:p.argument},orderByDesc:!1,externalCriteria:N,localEntityName:null===(f=p.searchOptions)||void 0===f?void 0:f.rootEntity},{options:h}),clientEventList:{clientEvent:[]}}},O={urlParams:{quietMode:!0}};return new Promise(((e,t)=>{r.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(S),O).then((t=>e(t))).catch((e=>t(e)))}))}addSearchListener(e,t,n){var i;const o=this._searchListenersByDataUnit.get(t)||[],r=o.find((t=>t.entity===e));if(r){for(const e of Object.keys(n))if(e in r.listener){if((null===(i=r.listener[e])||void 0===i?void 0:i.toString())===n[e].toString())continue;r.listener[e]=n[e]}}else this._searchListenersByDataUnit.set(t,[...o,{entity:e,listener:n}]);return()=>{const n=o.filter((t=>t.entity!==e));n.length?this._searchListenersByDataUnit.set(t,n):this._searchListenersByDataUnit.delete(t)}}applySearchListener(e,t,n,i,o){var r;const a=null==o?void 0:o.dataUnitId;if(!a)return;const s=null===(r=this._searchListenersByDataUnit.get(a))||void 0===r?void 0:r.find((({entity:e})=>e===t));if(!s)return;const{listener:l}=s;return e in l?l[e]({argument:n,criteria:i,searchOptions:o}):void 0}async loadPresentationConfig(e){var t,n;let i=function(e){return{config:{chave:`PesquisaContent:${e}`,tipo:"T"}}}(e);const o=await r.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(i));return null!==(n=null===(t=null==o?void 0:o.config)||void 0===t?void 0:t.lastUsedMode)&&void 0!==n?n:"list"}async savePresentationConfig(e,t){let n=function(e,t){return{config:{lastUsedMode:t,chave:`PesquisaContent:${e}`,tipo:"T"}}}(e,t);await r.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(n))}async loadPesquisaGridConfig(e){const t=function(e){return{gridConfig:{configName:`GrdCfgHtml5:grdcfg.dynaform.pesquisa.${e}`}}}(e);return function(e){var t,n;const i=[],o=null!==(n=null===(t=null==e?void 0:e.gridConfig)||void 0===t?void 0:t.field)&&void 0!==n?n:{};if(Object.keys(o).forEach((e=>i.push(o[e]))),i.length)return{columns:i}}(await r.get().callServiceBroker("GridConfig.getGridConfigFromJson",JSON.stringify(t)))}async savePesquisaGridConfig(e,t){const n=function(e,t){const n={};return null==t||t.forEach(((e,t)=>n[`field${t}`]=e)),{gridConfig:{compactMode:!0,configName:`GrdCfgHtml5:grdcfg.dynaform.pesquisa.${e}`,field:n}}}(e,t);await r.get().callServiceBroker("GridConfig.saveGridConfigFromJSON",JSON.stringify(n))}async loadTree(e,t,n,i){const o=this.buildLoadTreeRequestBody(e,t,n,i);return(null!==(s=null===(a=(await r.get().callServiceBroker("Pesquisa.getStructuredData",JSON.stringify(o))).arvore)||void 0===a?void 0:a.no)&&void 0!==s?s:[]).map(c);var a,s}buildLoadTreeRequestBody(e,t,n,i){var o,r;const a=this.applySearchListener(v.beforeSearch,e,t,n,i),s=null!==(o=null==a?void 0:a.searchOptions)&&void 0!==o?o:i,l=null==s?void 0:s.rootEntity,u=null==s?void 0:s.codeFieldName,c=null===(r=null==a?void 0:a.criteria)||void 0===r?void 0:r.expression,d=this.buildParams(a),f={nome:e,nomeInstanciaLocal:l,codeFieldName:u};return c&&(f.criterioLiteral={expressao:{$:c},parametro:d}),{instancia:f}}buildParams(e){var t,n;let i=null!==(n=null===(t=null==e?void 0:e.criteria)||void 0===t?void 0:t.params)&&void 0!==n?n:[];return i=i.map((e=>Object.assign(Object.assign({},e),{tipo:g(e.dataType),$:e.value}))),i}}function g(e){switch(e){case t.NUMBER:return"I";case t.DATE:return"D";default:return"S"}}!function(e){e.beforeSearch="beforeSearch"}(v||(v={})),function(e){e.LINK_AND_FILE_AT_THE_SAME_TIME="LINK_AND_FILE_AT_THE_SAME_TIME",e.ANY_LINK_OR_FILE_FILLED="ANY_LINK_OR_FILE_FILLED",e.UNKNOWN="UNKNOWN",e.DESCRIPTION_CANNOT_BE_CHANGED="DESCRIPTION_CANNOT_BE_CHANGED"}(f||(f={}));export{m as P,f as S,d as a,a as b}
6
+ }`)}loadSearchOptions(e,n,i,o){var a;const s=(null==n?void 0:n.toString().trim())||void 0;n=isNaN(Number(s))&&s?`%${s}`:s,null==i||i.params.forEach((e=>{e.dataType===t.OBJECT&&(e.value=JSON.stringify(e.value))}));const l=this.applySearchListener(v.beforeSearch,e,n,i,o),u={argument:(null==l?void 0:l.argument)||n,entityName:e,criteria:(null==l?void 0:l.criteria)||i,options:(null==l?void 0:l.searchOptions)||o};return u.options&&(null===(a=u.options)||void 0===a||delete a.dataUnitId),new Promise(((e,t)=>{r.get().callGraphQL({values:u,query:this._templateByQuery.get("search")}).then((t=>{e(t)})).catch((e=>{t(e)}))}))}loadAdvancedSearch(e,o,a,s){var l,u,c,d,f;const g=this.applySearchListener(v.beforeSearch,e,o,a,s),p={argument:(null==g?void 0:g.argument)||o,criteria:(null==g?void 0:g.criteria)||a,searchOptions:Object.assign(Object.assign({},s),null==g?void 0:g.searchOptions)},h={query:{$:null===(l=p.criteria)||void 0===l?void 0:l.expression}};(null===(c=null===(u=p.criteria)||void 0===u?void 0:u.params)||void 0===c?void 0:c.length)>0&&(h.params={param:p.criteria.params.map((e=>{let o=e.value;if("string"==typeof o){const e=/CTX\{([^}]+)\}/.exec(o);e&&(o=n.getContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${e[1]})__`))}if(e.dataType===t.NUMBER&&void 0===o)throw new i("Falha detectada",`O campo ${e.name} deve ser informado.`);let r=e.dataType;return r===t.OBJECT?(o=o.value,r="S"):r=m(e.dataType),{$:o,type:r}}))});const S=null!=s?Object.assign(Object.assign({},null==p?void 0:p.searchOptions),{pkFieldName:s.codeFieldName,label:s.descriptionFieldName,fieldName:s.codeFieldName,useDescriptionOptions:!1,enableRowsCounter:!0}):void 0,y={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:Object.assign({entityName:e,compacted:!1,ignoreEntityCriteria:null!==(d=null==S?void 0:S.ignoreEntityCriteria)&&void 0!==d&&d,limit:this._defaultPageSize,query:{$:p.argument},orderByDesc:!1,externalCriteria:h,localEntityName:null===(f=p.searchOptions)||void 0===f?void 0:f.rootEntity},{options:S}),clientEventList:{clientEvent:[]}}},b={urlParams:{quietMode:!0}};return new Promise(((e,t)=>{r.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(y),b).then((t=>e(t))).catch((e=>t(e)))}))}addSearchListener(e,t,n){var i;const o=this._searchListenersByDataUnit.get(t)||[],r=o.find((t=>t.entity===e));if(r){for(const e of Object.keys(n))if(e in r.listener){if((null===(i=r.listener[e])||void 0===i?void 0:i.toString())===n[e].toString())continue;r.listener[e]=n[e]}}else this._searchListenersByDataUnit.set(t,[...o,{entity:e,listener:n}]);return()=>{const n=o.filter((t=>t.entity!==e));n.length?this._searchListenersByDataUnit.set(t,n):this._searchListenersByDataUnit.delete(t)}}applySearchListener(e,t,n,i,o){var r;const a=null==o?void 0:o.dataUnitId;if(!a)return;const s=null===(r=this._searchListenersByDataUnit.get(a))||void 0===r?void 0:r.find((({entity:e})=>e===t));if(!s)return;const{listener:l}=s;return e in l?l[e]({argument:n,criteria:i,searchOptions:o}):void 0}async loadPresentationConfig(e){var t,n;let i=function(e){return{config:{chave:`PesquisaContent:${e}`,tipo:"T"}}}(e);const o=await r.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(i));return null!==(n=null===(t=null==o?void 0:o.config)||void 0===t?void 0:t.lastUsedMode)&&void 0!==n?n:"list"}async savePresentationConfig(e,t){let n=function(e,t){return{config:{lastUsedMode:t,chave:`PesquisaContent:${e}`,tipo:"T"}}}(e,t);await r.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(n))}async loadPesquisaGridConfig(e){const t=function(e){return{gridConfig:{configName:`GrdCfgHtml5:grdcfg.dynaform.pesquisa.${e}`}}}(e);return function(e){var t,n;const i=[],o=null!==(n=null===(t=null==e?void 0:e.gridConfig)||void 0===t?void 0:t.field)&&void 0!==n?n:{};if(Object.keys(o).forEach((e=>i.push(o[e]))),i.length)return{columns:i}}(await r.get().callServiceBroker("GridConfig.getGridConfigFromJson",JSON.stringify(t)))}async savePesquisaGridConfig(e,t){const n=function(e,t){const n={};return null==t||t.forEach(((e,t)=>n[`field${t}`]=e)),{gridConfig:{compactMode:!0,configName:`GrdCfgHtml5:grdcfg.dynaform.pesquisa.${e}`,field:n}}}(e,t);await r.get().callServiceBroker("GridConfig.saveGridConfigFromJSON",JSON.stringify(n))}async loadTree(e,t,n,i){const o=this.buildLoadTreeRequestBody(e,t,n,i);return(null!==(s=null===(a=(await r.get().callServiceBroker("Pesquisa.getStructuredData",JSON.stringify(o))).arvore)||void 0===a?void 0:a.no)&&void 0!==s?s:[]).map(c);var a,s}buildLoadTreeRequestBody(e,t,n,i){var o,r;const a=this.applySearchListener(v.beforeSearch,e,t,n,i),s=null!==(o=null==a?void 0:a.searchOptions)&&void 0!==o?o:i,l=null==s?void 0:s.rootEntity,u=null==s?void 0:s.codeFieldName,c=null===(r=null==a?void 0:a.criteria)||void 0===r?void 0:r.expression,d=this.buildParams(a),f={nome:e,nomeInstanciaLocal:l,codeFieldName:u};return c&&(f.criterioLiteral={expressao:{$:c},parametro:d}),{instancia:f}}buildParams(e){var t,n;let i=null!==(n=null===(t=null==e?void 0:e.criteria)||void 0===t?void 0:t.params)&&void 0!==n?n:[];return i=i.map((e=>Object.assign(Object.assign({},e),{tipo:m(e.dataType),$:e.value}))),i}}function m(e){switch(e){case t.NUMBER:return"I";case t.DATE:return"D";default:return"S"}}!function(e){e.beforeSearch="beforeSearch"}(v||(v={}));export{f as P,d as a,a as b}
@@ -1 +1 @@
1
- export{S as snk_data_unit}from"./p-abd9681c.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"@sankhyalabs/ezui/dist/collection/utils";import"./p-17425c72.js";import"./p-7e0a0aae.js";import"./p-5a7e18f4.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"./p-7dd49d15.js";
1
+ export{S as snk_data_unit}from"./p-23b47a92.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"@sankhyalabs/ezui/dist/collection/utils";import"./p-17425c72.js";import"./p-3653374d.js";import"./p-d62228fb.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"./p-7dd49d15.js";
@@ -0,0 +1 @@
1
+ import{r as t,c as i,f as s,h as e,H as a}from"./p-d2d301a6.js";import{Action as o}from"@sankhyalabs/core";import{S as h}from"./p-3ba431c9.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-d62228fb.js";import"./p-41c3bee5.js";import{P as d}from"./p-0f3698af.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-3653374d.js";import"./p-ff1990ad.js";import"./p-1435701f.js";import{V as l}from"./p-1d19a5b0.js";import{T as c}from"./p-3fc82614.js";import{S as m}from"./p-7b87d1a8.js";import{S as u}from"./p-17425c72.js";import"./p-19dc71e9.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-23736d75.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(l.FORM)}),0),e&&this.changeViewMode(l.GRID);const h=[];this.dataState.hasPrevious||h.push(c.PREVIOUS),this.dataState.hasNext||h.push(c.NEXT),this.dataState.insertionMode&&h.push(c.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const t=this.formConfigManager.getConfig(this.dataUnit);this._formMetadata=r(null==t||0===t.fields.length?void 0:t,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){var i,s;this._viewStack=t,this._currentView=this.selectedForm?1:0,null===(s=null===(i=this._viewStack)||void 0===i?void 0:i.show)||void 0===s||s.call(i,this._currentView)}getFormFields(){return this.selectedForm&&this._formMetadata?this._formMetadata.getSheet(this.selectedForm).fields:[]}emitSwitchEvent(t){const i=t===l.GRID?this.stripFormPattern(this.branchGuide.id):this.getFormGuideId();i&&this.snkSwitchGuide.emit(i)}handleAttachBack(){this._viewStack.show(l.GRID)}executeActionHandler(t){t.detail===c.GRID_MODE&&(this.emitSwitchEvent(l.GRID),t.stopPropagation()),t.detail!==c.FORM_MODE&&t.detail!==c.UPDATE||(this.emitSwitchEvent(l.FORM),t.stopPropagation()),t.detail===c.ATTACH&&(this._viewStack.show(l.ATTACHMENT),t.stopPropagation())}async getAttachmentRegisterKey(){if(this._snkDataUnit)return(await this._snkDataUnit.getSelectedRecordsIDsInfo()).map((({value:t})=>t)).join("_")}async handleDataStateChange({detail:t}){this.dataState=t,void 0!==t.selectedRecord&&this._snkDataUnit&&(this.attachmentRegisterKey=await this.getAttachmentRegisterKey())}componentWillLoad(){this._configName=`dynaform.${this.entityName}`,this.formConfigManager=new h(this._configName,this.resourceID,(()=>this.loadMetadata()),this.dataUnit),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===l.GRID,messagesBuilder:this.messagesBuilder,configName:this._configName},e("ez-view-stack",{ref:t=>this.updateViewStack(t)},e("stack-item",null,e("div",{class:"ez-box ez-box--shadow grid-container"},e("div",{class:"ez-flex ez-title--primary ez-size-width--full ez-padding--large detail-header"},e("div",{class:"ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center"},this._levelPath?e("span",{class:"level-path"},this._levelPath+" /"):void 0,this.label)),e("snk-grid",{class:"ez-size-width--full ez-size-height--full",ref:t=>this._snkGrid=t,configName:this._configName,messagesBuilder:this.messagesBuilder,onGridDoubleClick:()=>this.emitSwitchEvent(l.FORM),onActionClick:t=>this.executeActionHandler(t),presentationMode:d.SECONDARY,canEdit:this.canEdit,isDetail:!0,taskbarCustomContainerId:this.taskbarCustomContainerId,gridHeaderCustomSlotId:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS",topTaskbarCustomSlotId:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS",outlineMode:!1}))),e("stack-item",null,e("snk-form-view",{ref:t=>this._snkFormView=t,canExpand:!1,canFix:!1,name:this.selectedForm,formMetadata:this._formMetadata,dataUnit:this.dataUnit,fields:this.getFormFields(),label:this.label,levelPath:this._levelPath,onFormItemsReady:({detail:t})=>this.formItemsReady.emit(t)},e("snk-taskbar",{key:"guideViewerTaskbar",class:"form-taskbar","data-element-id":"guideViewer",configName:this._configName,messagesBuilder:this.messagesBuilder,disabledButtons:this._disabledButtons,buttons:"INSERT,PREVIOUS,NEXT,DIVIDER,CLONE,REMOVE,MORE_OPTIONS,DIVIDER,GRID_MODE,CONFIGURATOR",primaryButton:"INSERT",presentationMode:d.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit,resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"},e("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))),e("stack-item",null,e("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this.entityName,onBack:this.handleAttachBack.bind(this)})))))}static get watchers(){return{dataUnit:["observeDataUnit"],dataState:["observerDataState"],customEditors:["observerPropsCustomEditor"],customRenders:["observeCustomRenders"]}}};p.REGEX_FORM_ID=/__FORM:[^:]+/g,p.style=".sc-snk-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%}.level-path.sc-snk-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.form-taskbar.sc-snk-detail-view{padding-bottom:var(--space--medium)}.grid-container.sc-snk-detail-view{background-color:#FFF;min-height:100px}.detail-header.sc-snk-detail-view{padding-bottom:0}";export{p as snk_detail_view}
@@ -0,0 +1 @@
1
+ import{r as o,c as r,h as t,g as i}from"./p-d2d301a6.js";import{ApplicationContext as n}from"@sankhyalabs/core";import{V as a}from"./p-1d19a5b0.js";import{A as s}from"./p-dc36cfbf.js";const l=class{constructor(t){o(this,t),this.configSelected=r(this,"configSelected",7),this.openConfig=r(this,"openConfig",7),this.save=r(this,"save",7),this.cancel=r(this,"cancel",7),this._opened=!1,this._permissions=void 0,this.showActionButtons=!1,this.configName=void 0,this.resourceID=void 0,this.viewMode=a.GRID,this.customContainerId=void 0,this.messagesBuilder=void 0}async open(){this._opened=!0,this.configSelected.emit(this.getViewModeValue()),this.modal.heightMode="full"}async close(){this.closeConfig()}closeConfig(){this._opened=!1}onViewModeChanged(o){this.viewMode=null==o?void 0:o.detail,this.configSelected.emit(this.viewMode)}onClickOpenConfig(){this.openConfig.emit(this.viewMode)}isAllowed(o){return!s[o]||!!this._permissions&&(this._permissions.isSup||this._permissions[o])}enableModeConfig(){return!(!this.isAllowed(s.CONFIG_GRID)||!this.isAllowed(s.CONFIG))}getViewModeValue(){return null!=this._permissions&&(this.isAllowed(s.CONFIG_GRID)?this.isAllowed(s.CONFIG)||(this.viewMode=a.GRID):this.viewMode=a.FORM),this.viewMode}getMessage(o){var r;return null===(r=this.messagesBuilder)||void 0===r?void 0:r.getMessage(o,{})}componentWillLoad(){this._application=n.getContextValue("__SNK__APPLICATION__"),this._application?this._application.getAllAccess(this.resourceID).then((o=>this._permissions=o)):this._permissions={}}componentDidRender(){if(!this.customContainerId)return;const o=document.querySelector(`#${this.customContainerId}`),r=null==o?void 0:o.querySelector("#SnkConfigContainerSlot");if(!r)return;const t=r.firstElementChild;if(!t)return;const i=this._element.querySelector("#slotContainer");null==i||i.appendChild(t)}render(){return t("ez-modal",{ref:o=>this.modal=o,opened:this._opened,"close-esc":!1,"close-outside-click":!1,"modal-size":"small",scrim:"light"},t("div",{class:"snk-configurator"},t("div",{class:"snk-configurator__header"},t("label",{class:"snk-configurator__title"},this.getMessage("snkConfigurator.titleConfigurations")),t("div",{class:"snk-configurator__button-close"},t("ez-button",{mode:"icon",iconName:"close",size:"medium",onClick:()=>this.closeConfig()}))),t("div",{class:"snk-configurator__main"},t("ez-collapsible-box",{boxBordered:!0,label:"Modo de visualização ",headerSize:"medium",class:"snk-configurator__collapsable-box"},t("ez-radio-button",{value:this.getViewModeValue().toString(),onEzChange:o=>this.onViewModeChanged(o),enabled:this.enableModeConfig()},t("ez-radio-button-option",{label:this.getMessage("snkConfigurator.labelGrid"),value:a.GRID}),t("ez-radio-button-option",{label:this.getMessage("snkConfigurator.labelForm"),value:a.FORM})),t("div",{class:"snk-configurator__collsable-box-action"},t("ez-button",{label:this.getMessage(this.viewMode===a.GRID?"snkConfigurator.labelConfigGrid":"snkConfigurator.labelConfigForm"),class:"snk-configurator__button-config ez-button--secondary",onClick:()=>this.onClickOpenConfig(),id:"openConfigurator"}))),t("div",{id:"slotContainer",class:"snk-configurator__outline"})),this.showActionButtons&&t("div",{class:"snk-configurator__action-buttons"},t("ez-button",{label:"Cancelar",onClick:()=>this.cancel.emit()}),t("ez-button",{label:"Salvar",onClick:()=>this.save.emit(),class:"ez-button--primary"}))))}get _element(){return i(this)}};l.style='.sc-snk-configurator-h{--snk-configurator__button-close--padding-left:var(--space--medium, 12px);--snk-configurator__title--color:var(--title--primary, #2B3A54);--snk-configurator__title--font-family:var(--font-pattern, "Roboto");--snk-configurator__title--font-size:var(--title--large, 20px);--snk-configurator__title--font-weight:var(--text-weight--extra-large, 700);--snk-configurator__subtitle--color:var(--title--primary, #2B3A54);--snk-configurator__subtitle--font-family:var(--font-pattern, "Roboto");--snk-configurator__subtitle--font-size:var(--text--medium, 14px);--snk-configurator__subtitle--font-weight:var(--text-weight--large, 600);--snk-configurator__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-configurator__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-configurator__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-configurator__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-configurator__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-configurator__scrollbar--width:var(--space--small, 6px)}.snk-configurator.sc-snk-configurator{display:grid;grid-template-rows:auto 1fr auto;max-height:100%;width:100%}.snk-configurator__collsable-box-action.sc-snk-configurator{width:100%}.snk-configurator__action-buttons.sc-snk-configurator{display:flex;flex-direction:row;justify-content:flex-end;gap:var(--space--medium)}.snk-configurator__outline.sc-snk-configurator{display:flex;flex-direction:column;gap:var(--space--small);margin-top:var(--space--small);margin-bottom:var(--space--large)}@media screen and (min-width: 480px){.snk-configurator.sc-snk-configurator{width:359px;max-width:359px}}.snk-configurator__button-config.sc-snk-configurator{--ez-button--min-width:100%}.snk-configurator__header.sc-snk-configurator{display:flex;justify-content:space-between;align-items:center;width:100%}.snk-configurator__title.sc-snk-configurator{display:flex;margin:0;line-height:normal;letter-spacing:0em;text-align:left;color:var(--snk-configurator__title--color);font-size:var(--snk-configurator__title--font-size);font-family:var(--snk-configurator__title--font-family);font-weight:var(--snk-configurator__title--font-weight)}.snk-configurator__subtitle.sc-snk-configurator{display:flex;margin:0;padding-top:var(--space--medium);padding-bottom:var(--space--small);color:var(--snk-configurator__subtitle--color);font-size:var(--snk-configurator__subtitle--font-size);font-family:var(--snk-configurator__subtitle--font-family);font-weight:var(--snk-configurator__subtitle--font-weight)}.snk-configurator__button-close.sc-snk-configurator{padding-left:var(--snk-configurator__button-close--padding-left)}.snk-configurator__main.sc-snk-configurator{overflow-y:auto;scrollbar-width:thin;margin:var(--space--medium) 0;scrollbar-color:var(--snk-configurator__scrollbar--color-clicked) var(--snk-configurator__scrollbar--color-background)}.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar{background-color:var(--snk-configurator__scrollbar--color-background);width:var(--snk-configurator__scrollbar--width);max-width:var(--snk-configurator__scrollbar--width);min-width:var(--snk-configurator__scrollbar--width)}.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar-track{background-color:var(--snk-configurator__scrollbar--color-background);border-radius:var(--snk-configurator__scrollbar--border-radius)}.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar-thumb{background-color:var(--snk-configurator__scrollbar--color-default);border-radius:var(--snk-configurator__scrollbar--border-radius)}.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar-thumb:vertical:hover,.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--snk-configurator__scrollbar--color-hover)}.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar-thumb:vertical:active,.snk-configurator__main.sc-snk-configurator::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--snk-configurator__scrollbar--color-clicked)}';export{l as snk_configurator}
@@ -0,0 +1 @@
1
+ import{r as t,c as i,h as e}from"./p-d2d301a6.js";import{ApplicationContext as a,DataType as s,Action as n,UserInterface as o,StringUtils as r,DataUnitLoaderUtils as h,DataUnit as l}from"@sankhyalabs/core";import{D as d}from"./p-d62228fb.js";import"./p-41c3bee5.js";import"./p-0f3698af.js";import{S as c}from"./p-21749402.js";import{P as u,D as m,I as v}from"./p-3653374d.js";import"./p-ff1990ad.js";import"./p-1435701f.js";import{V as A}from"./p-1d19a5b0.js";import{A as O}from"./p-f0b9303b.js";import{T as p}from"./p-3fc82614.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";class w{constructor(t){this.dataUnitName=t}async save({dataUnit:t,record:i,updatingFields:e,operation:a}){var s,n;const o="INSERT"==a,r=o?e:i;if(!o&&(null==e?void 0:e.DESCRICAO)&&(null==e?void 0:e.DESCRICAO)!==(null==i?void 0:i.DESCRICAO))throw new Error(c.DESCRIPTION_CANNOT_BE_CHANGED);const h={anexo:{codata:o?null==e?void 0:e.REGISTER_KEY:null==i?void 0:i.CODATA,sequencia:(null==r?void 0:r.SEQUENCIA)||"0",tipo:(null==r?void 0:r.TIPO)||"N",descricao:null==r?void 0:r.DESCRICAO,arquivo:null===(n=null===(s=e.CAMINHO_ARQUIVO)||void 0===s?void 0:s[0])||void 0===n?void 0:n.name,ehInclusao:o?"S":"N",ehArquivoRepositorio:"N"}};return new Promise(((i,a)=>{d.get().callServiceBroker("Attach.save",JSON.stringify(h)).then((a=>{var s;return i([Object.assign(Object.assign(Object.assign({},a),e),{__owner__dataunit__name__:null!==(s=this.dataUnitName)&&void 0!==s?s:t})])})).catch((t=>a(t)))}))}async edit(t){throw new Error("Method not implemented.")}async delete(t){var i={anexo:{codata:t.CODATA,tipo:t.TIPO,descricao:t.DESCRICAO}};const e=await d.get().callServiceBroker("Attach.remove",JSON.stringify(i));return Promise.resolve(e)}async getDownloadKey(t){var i,e,a;if("S"==t.EHARQUIVOREPOSITORIO){const a={config:{path:t.ARQUIVO,tipoconteudo:t.TIPOCONTEUDO}},s=await d.get().callServiceBroker("RepositorioArquivoSP.abreArquivo",JSON.stringify(a));return Promise.resolve({chave:{valor:null===(e=null===(i=null==s?void 0:s.responseBody)||void 0===i?void 0:i.chave)||void 0===e?void 0:e.valor}})}const s={anexo:{codata:t.CODATA,codemp:t.CODEMP,sequencia:t.SEQUENCIA,tipo:t.TIPO,descricao:t.DESCRICAO,tipoConteudo:t.TIPOCONTEUDO}},n=await d.get().callServiceBroker("Attach.view",JSON.stringify(s));return(null==n?void 0:n.chaveAnexo)?Promise.resolve({chave:{valor:null===(a=null==n?void 0:n.chaveAnexo)||void 0===a?void 0:a.idChaveAnexo}}):Promise.reject(new Error("File not found."))}}const I="AnexoSistemaSP.salvar",_="AnexoSistemaSP.excluir",S="AnexoSistemaSP.baixar";class k{constructor(t,i){var e;this.entityName=t,this.dataUnitName=i,this.validateFields=t=>{if(t.LINK&&t.NOMEARQUIVO)throw new Error(c.LINK_AND_FILE_AT_THE_SAME_TIME);if(!t.LINK&&!t.NOMEARQUIVO)throw new Error(c.ANY_LINK_OR_FILE_FILLED);if(!this._registerKey)throw new Error("Register key can not be null")},this.resourceID=window.resourceID||(null===(e=window.workspace)||void 0===e?void 0:e.resourceID)}set registerKey(t){this._registerKey=t}async save(t){var i,e;let{updatingFields:a}=t;a=Object.assign(Object.assign({},a),{NOMEARQUIVO:null===(i=a.NOMEARQUIVO)||void 0===i?void 0:i[0]});try{this.validateFields(a);const t=a.LINK?null:a.NOMEARQUIVO,i={serviceName:I,requestBody:{params:{resourceID:this.resourceID,description:a.DESCRICAO,fileSelect:t?1:0,keySession:null===(e=null==t?void 0:t.properties)||void 0===e?void 0:e.fileNameTmp,nameAttach:null==t?void 0:t.name,link:a.LINK,nameEntity:this.entityName,pkEntity:this._registerKey,typeAcess:a.TIPOACESSO,typeApres:a.TIPOAPRES}}},s=await d.get().callServiceBroker(I,JSON.stringify(i));return Promise.resolve([Object.assign(Object.assign(Object.assign({},s),a),{ARQUIVOOULINK:a.LINK?a.LINK:null==t?void 0:t.name,__owner__dataunit__name__:this.dataUnitName})])}catch(t){return Promise.reject(t)}}async edit(t){var i,e,a;let{updatingFields:s,record:n}=t;const o=t=>void 0!==s[t]?s[t]:n[t],r=o("NOMEARQUIVO"),h=null===(e=null===(i=s.NOMEARQUIVO)||void 0===i?void 0:i[0])||void 0===e?void 0:e.downloadURL;s=Object.assign(Object.assign({},s),{DESCRICAO:o("DESCRICAO"),LINK:o("LINK"),TIPOACESSO:o("TIPOACESSO"),TIPOAPRES:o("TIPOAPRES"),CHAVEARQUIVO:n.CHAVEARQUIVO,NOMEARQUIVO:null==r?void 0:r[0]});const l=s.LINK?null:s.NOMEARQUIVO;try{this.validateFields(s);const t={serviceName:I,requestBody:{params:{resourceID:this.resourceID,nuAttach:null==n?void 0:n.NUATTACH,description:s.DESCRICAO,fileSelect:h?1:0,keySession:null===(a=null==l?void 0:l.properties)||void 0===a?void 0:a.fileNameTmp,keyAttach:s.CHAVEARQUIVO,nameAttach:null==l?void 0:l.name,link:s.LINK,nameEntity:this.entityName,pkEntity:this._registerKey,typeAcess:s.TIPOACESSO,typeApres:s.TIPOAPRES}}},i=await d.get().callServiceBroker(I,JSON.stringify(t));return Promise.resolve([Object.assign(Object.assign(Object.assign({},i),s),{ARQUIVOOULINK:s.LINK?s.LINK:null==l?void 0:l.name,__owner__dataunit__name__:this.dataUnitName})])}catch(t){return Promise.reject(t)}}delete(t){var i;const e=(null===(i=t.NOMEARQUIVO)||void 0===i?void 0:i[0])||{},a={serviceName:_,requestBody:{paramsDelete:{keyAttach:t.CHAVEARQUIVO,nameAttach:null==e?void 0:e.name,nameEntity:t.NOMEINSTANCIA,nuAttach:t.NUATTACH,pkEntity:t.PKREGISTRO}}};return new Promise(((t,i)=>{d.get().callServiceBroker(_,JSON.stringify(a)).then((i=>t(i))).catch((t=>i(t)))}))}getDownloadKey(t){var i;const e=(null===(i=t.NOMEARQUIVO)||void 0===i?void 0:i[0])||{},a={serviceName:S,requestBody:{paramsDown:{nameAttach:null==e?void 0:e.name,nameEntity:t.NOMEINSTANCIA,nuAttach:t.NUATTACH,pkEntity:t.PKREGISTRO,keyAttach:t.CHAVEARQUIVO}}};return new Promise(((t,i)=>{d.get().callServiceBroker(S,JSON.stringify(a)).then((i=>t(i))).catch((t=>i(t)))}))}}class b{constructor(t,i){this.entityName=t,this.getMessage=i,this._application=a.getContextValue("__SNK__APPLICATION__")}initLoaders(t,i,e){this.loader||(this.loader=t.dataLoader),t.dataLoader=(t,i)=>this.dataLoader(t,i),t.saveLoader=(t,a)=>this.saveLoader(a,i).then((t=>(t.length&&e(),t))),t.removeLoader=(t,a)=>this.removeLoader(t,a,i).then((t=>(t.length&&e(),t)))}metadataLoader(t){throw new Error("Method not implemented.")}dataLoader(t,i){return new Promise((e=>{this.loader(t,i).then((t=>{const i=((null==t?void 0:t.records)||[]).map((t=>{let i;return t.LINK||(i=[{name:t.NOMEARQUIVO}]),Object.assign(Object.assign({},t),{ARQUIVOOULINK:t.LINK?t.LINK:t.NOMEARQUIVO,NOMEARQUIVO:i})}));e(Object.assign(Object.assign({},t),{records:i}))}))}))}saveLoader(t,i){return new Promise((e=>{var a;const s=Array.isArray(t)?t[0]:{};((null===(a=null==s?void 0:s.record)||void 0===a?void 0:a.NUATTACH)>=0?i.edit.bind(i):i.save.bind(i))(s).then((t=>{e(t)})).catch((t=>t.message===c.LINK_AND_FILE_AT_THE_SAME_TIME?(this._application.alert(this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.title"),this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.message")),e([])):t.message===c.ANY_LINK_OR_FILE_FILLED?(this._application.alert(this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.title"),this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.message")),e([])):t.message?(this._application.error(t.title||t.name,t.message),e([])):void e([])))}))}removeLoader(t,i,e){return new Promise((a=>{const{records:s}=t.getSelectionInfo(),n=s[0];e.delete(n).then((()=>(u.removeRecords(t,[n]),a(i))))}))}getFilters(t){return[{name:"AttachmentsByPK",expression:"this.PKREGISTRO = :PKREGISTRO",params:[{name:"PKREGISTRO",dataType:s.TEXT,value:`${t}_${this.entityName}`}]}]}getInterceptions(t,i,e){return new Promise((a=>i.type===n.EDITION_CANCELED?t.isDirty()?this._application.confirm(this.getMessage("snkAttach.cancelConfirmation.title"),this.getMessage("snkAttach.cancelConfirmation.message")).then((t=>t?(e.goToView(A.GRID),a(i)):a(void 0))):a(i):i.type===n.DATA_SAVED?(t.loadData(),a(i)):void a(i)))}}const y=a.getContextValue("__SNK__APPLICATION__"),f=t=>{var i,e;return null===(e=null===(i=null==y?void 0:y.messagesBuilder)||void 0===i?void 0:i.getMessage)||void 0===e?void 0:e.call(i,t,null)},E={grid:{columns:[{name:"CODATA",orderIndex:0,width:0},{name:"DESCRICAO",orderIndex:1,width:0},{name:"ARQUIVO",orderIndex:2,width:0},{name:"DTALTER",orderIndex:3,width:0},{name:"USUARIO",orderIndex:4,width:0}]},form:{emptyConfig:!1,fields:[{name:"DESCRICAO",label:f("snkAttach.attachMetadata.lblDescription"),visible:!0,readOnly:!1,required:!0},{name:"CAMINHO_ARQUIVO",label:f("snkAttach.attachMetadata.lblFile"),visible:!0,readOnly:!1,required:!0}]}},N={name:"Attach",label:"Attach List",fields:[{name:"CODATA",label:f("snkAttach.attachMetadata.lblCode"),dataType:s.TEXT},{name:"DESCRICAO",label:f("snkAttach.attachMetadata.lblDescription"),dataType:s.TEXT,readOnly:!1},{name:"ARQUIVO",label:f("snkAttach.attachMetadata.lblFileOrLink"),dataType:s.TEXT},{name:"USUARIO",label:f("snkAttach.attachMetadata.lblUser"),dataType:s.TEXT},{name:"DTALTER",label:f("snkAttach.attachMetadata.lblDate"),dataType:s.TEXT},{name:"CAMINHO_ARQUIVO",label:f("snkAttach.attachMetadata.lblFileUpload"),dataType:s.OBJECT,userInterface:o.FILE,readOnly:!1,required:!0,visible:!0,properties:{subTitle:f("snkAttach.attachMetadata.lblSubTitle"),MAX_FILES:1,STORAGESTRATEGY:"SESSION",INTERNAL_FILENAME:"Attach.upload"}}]};class g{constructor(t){this.getMessage=t,this._records=[],this._application=a.getContextValue("__SNK__APPLICATION__")}initLoaders(t,i,e){t.metadataLoader=t=>this.metadataLoader(t),t.dataLoader=(t,i)=>this.dataLoader(t,i),t.saveLoader=(t,a)=>this.saveLoader(a,i).then((t=>(t.length&&e(),t))),t.removeLoader=(t,a)=>this.removeLoader(t,a,i).then((t=>(t.length&&e(),t)))}metadataLoader(t){return Promise.resolve(N)}async dataLoader(t,i){if(!i.source)return Promise.resolve({records:this._records});if(!Number.isNaN(Number(i.source))){const t={criteria:{codata:i.source,tipoAnexo:"N"}},e=await this._application.getDataFetcher(),{anexos:{anexo:a=[]}}=await e.callServiceBroker("Attach.load",JSON.stringify(t)),s=[];a.forEach((t=>{s.push(Object.assign({__record__id__:r.generateUUID(),CAMINHO_ARQUIVO:[{name:null==t?void 0:t.ARQUIVO}]},t))})),this._records=s}return h.buildLoadDataResponse(this._records,t,i)}saveLoader(t,i){return new Promise((e=>{const a=Array.isArray(t)?t[0]:{};i.save(a).then(e).catch((t=>t.message===c.DESCRIPTION_CANNOT_BE_CHANGED?(this._application.alert(this.getMessage("snkAttach.alertValidation.descriptionCannotBeChanged.title"),this.getMessage("snkAttach.alertValidation.descriptionCannotBeChanged.message")),e([])):t.message===c.LINK_AND_FILE_AT_THE_SAME_TIME?(this._application.alert(this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.title"),this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.message")),e([])):t.message===c.ANY_LINK_OR_FILE_FILLED?(this._application.alert(this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.title"),this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.message")),e([])):t.message?(this._application.error(t.title||t.name,t.message),e([])):void e([])))}))}removeLoader(t,i,e){return new Promise((a=>{t.getSelectionInfo().records.forEach((async t=>{this._application.hasAccess(O.REMOVE).then((async s=>{s&&(await e.delete(t),a(i))}))}))}))}getFilters(){throw new Error("Method not implemented.")}getInterceptions(t,i,e){return new Promise((a=>i.type===n.EDITION_CANCELED?t.isDirty()?this._application.confirm(this.getMessage("snkAttach.cancelConfirmation.title"),this.getMessage("snkAttach.cancelConfirmation.message")).then((t=>t?(e.goToView(A.GRID),a(i)):a(void 0))):a(i):i.type===n.DATA_SAVED?(t.loadData(),a(i)):void a(i)))}}const C=a.getContextValue("__SNK__APPLICATION__"),P=t=>{var i,e;return null===(e=null===(i=null==C?void 0:C.messagesBuilder)||void 0===i?void 0:i.getMessage)||void 0===e?void 0:e.call(i,t,null)},T={DOWNLOAD:{hint:P("snkAttach.taskbar.titleDownload"),name:"DOWNLOAD",iconName:"file-download"},LINK:{hint:P("snkAttach.taskbar.titleLink"),name:"LINK",iconName:"launch"}},L=()=>{const t=[p.REMOVE,"DOWNLOAD","LINK"];return{getButtons:(t,i,e)=>{const a=e.indexOf(p.REFRESH);if((null==i?void 0:i.insertionMode)||(null==i?void 0:i.isDirty))return e.reverse();-1!==a&&e.splice(a,1);const{selectedRecord:s}=i||{},n=(null==s?void 0:s.LINK)?T.LINK:T.DOWNLOAD;e.splice(e.indexOf(p.DIVIDER)+1,0,p.REMOVE,n,p.DIVIDER);const o=[p.CLONE,p.DATA_EXPORTER],r=Array.from(new Set(e.filter((t=>!o.includes(t)))));return r.splice(r.indexOf(n)+1,0,p.DIVIDER),r},isEnabled:(i,e,a)=>{const s=void 0!==(null==e?void 0:e.selectedRecord);return!(t.includes(a)&&!s)}}},R={grid:{columns:[{name:"ARQUIVOOULINK",orderIndex:0,width:0},{name:"DESCRICAO",orderIndex:1,width:0},{name:"DHCAD",orderIndex:2,width:0},{name:"DHALTER",orderIndex:3,width:0},{name:"TIPOAPRES",orderIndex:4,width:0},{name:"TIPOACESSO",orderIndex:5,width:0},{name:"CODUSU",orderIndex:6,width:0},{name:"CODUSUALT",orderIndex:7,width:0}]},form:{emptyConfig:!1,fields:[{name:"DESCRICAO",required:!0},{name:"TIPOAPRES",required:!0},{name:"TIPOACESSO",required:!0},{name:"LINK"},{name:"NOMEARQUIVO"}]}},x=class{constructor(e){t(this,e),this.back=i(this,"back",7),this.handleTaskbarClick=async({detail:t})=>{if(["DOWNLOAD","LINK"].includes(t))return this.downloadAttachment(this._currentDataUnit.getSelectedRecord());"Attach"===this.fetcherType&&["SAVE"].includes(t)&&this._currentDataUnit.isDirty()&&await this._currentDataUnit.setFieldValue("REGISTER_KEY",this.registerKey)},this.handleBack=()=>{this._currentDataUnit.cancelEdition().then((t=>{t&&this.back.emit()}))},this.handleFinish=()=>{if(!this._currentDataUnit.isDirty())return this.back.emit();this._currentDataUnit.saveData().then((()=>{this.showFinishedToast(),this.back.emit()}))},this.fetcherType=void 0,this.fetcher=void 0,this.dataUnit=void 0,this.dataUnitBuilder=void 0,this.registerKey=void 0,this.entityName=void 0,this.messagesBuilder=void 0,this._currentFetcher=void 0,this._currentDataUnit=void 0,this.crudConfig=void 0}async registerKeyWatcher(t,i){var e;null==this._currentDataUnit&&this.loadAttachmentDataUnit(),i!==t&&(this._currentFetcher instanceof k&&(this._currentFetcher.registerKey=t),await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData()))}getAnexoSistemaFetcherInstance(){var t;const i=new k(this.entityName,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name);return i.registerKey=this.registerKey,i}async initAttach(){var t,i,e,a,s;if(this.fetcherType||this.registerKey){if(this.fetcherType||(this.fetcherType="AnexoSistema"),this.returnToGridMode(),"AnexoSistema"===this.fetcherType)return this._currentFetcher=this.getAnexoSistemaFetcherInstance(),null===(t=this._currentDataUnitBuilder)||void 0===t||t.initLoaders(this._currentDataUnit,this._currentFetcher,this.returnToGridMode.bind(this)),void await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadData());if("Attach"===this.fetcherType&&(null===(e=this.registerKey)||void 0===e?void 0:e.split("_").length)>1)return;await(null===(a=this._currentDataUnit)||void 0===a?void 0:a.loadMetadata()),await(null===(s=this._currentDataUnit)||void 0===s?void 0:s.loadData(void 0,void 0,!0,this.registerKey))}}getMessage(t,i){if(this.messagesBuilder)return this.messagesBuilder.getMessage(t,i)}showFinishedToast(){this._application.info(this.getMessage("snkAttach.finishedMessage"),{iconName:"check"})}downloadAttachment(t){if(!t)throw new Error("Nenhum registro selecionado");t.LINK?window.open(`${t.LINK}`):this._currentFetcher.getDownloadKey(t).then((({chave:i})=>{var e;let a=!1;(null===(e=null==t?void 0:t.ARQUIVO)||void 0===e?void 0:e.endsWith(".pdf"))||(a=!0),window.open(`/mge/visualizadorArquivos.mge?chaveArquivo=${i.valor}${a?"&forcarDownload=S":""}`)}))}returnToGridMode(){var t;null===(t=this._currentDataUnit)||void 0===t||t.clearSelection(),this._crudElement&&this._crudElement.goToView(A.GRID)}async loadAttachmentDataUnit(){try{switch(this.fetcherType){case"AnexoSistema":await this.loadAnexoSistema();break;case"Attach":await this.loadAttach();break;default:this._currentFetcher=this.fetcher,this._currentDataUnit=this.dataUnit,this._currentDataUnitBuilder=this.dataUnitBuilder}}catch(t){throw new Error("There was an error while creating the data unit")}}async loadAnexoSistema(){var t,i;this._currentDataUnit=(new m).getDataUnit("AnexoSistema","br.com.sankhya.core.v3.anexoSistema"),this._currentFetcher=this.getAnexoSistemaFetcherInstance(),this._currentDataUnit.metadata||(await(null===(t=this._currentDataUnit)||void 0===t?void 0:t.loadMetadata()),this.crudConfig=Object.assign({},R)),this.initDataUnitLoaders(),this._currentDataUnit.addFilterProvider({getFilter:()=>this._currentDataUnitBuilder.getFilters(this.registerKey)}),this._currentDataUnit.addInterceptor({interceptAction:t=>this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit,t,this._crudElement)}),await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadData()),this.disableEditFieldsNotInForm()}async loadAttach(){var t,i;this._currentFetcher=new w,this._currentDataUnit=new l(v.IN_MEMORY_DATA_UNIT_NAME),this.initDataUnitLoaders(),this._currentDataUnit.addInterceptor({interceptAction:t=>{var i;return t.type===n.METADATA_LOADED&&(this.crudConfig=Object.assign({},E),null===(i=this._crudElement)||void 0===i||i.updateConfig()),this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit,t,this._crudElement)}}),this._currentDataUnit.metadata||(await(null===(t=this._currentDataUnit)||void 0===t?void 0:t.loadMetadata()),this.crudConfig=Object.assign({},E),await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadData(void 0,void 0,!0,this.registerKey)),this.disableEditFieldsNotInForm())}initDataUnitLoaders(){var t,i;"AnexoSistema"===this.fetcherType&&(this._currentFetcher=this.getAnexoSistemaFetcherInstance(),this._currentDataUnitBuilder=new b(this.entityName,this.getMessage.bind(this)),null===(t=this._currentDataUnitBuilder)||void 0===t||t.initLoaders(this._currentDataUnit,this._currentFetcher,this.returnToGridMode.bind(this))),"Attach"===this.fetcherType&&(this._currentFetcher=new w,this._currentDataUnitBuilder=new g(this.getMessage.bind(this)),null===(i=this._currentDataUnitBuilder)||void 0===i||i.initLoaders(this._currentDataUnit,this._currentFetcher,(async()=>{this.returnToGridMode(),await this._currentDataUnit.loadData(void 0,void 0,!0,this.registerKey)})))}disableEditFieldsNotInForm(){var t;null===(t=this.crudConfig)||void 0===t||t.grid.columns.forEach((t=>{var i;const e=t.name;(null===(i=this.crudConfig)||void 0===i?void 0:i.form.fields.some((t=>t.name===e)))||this._currentDataUnit.disableField(e)}))}async componentWillLoad(){this._application=a.getContextValue("__SNK__APPLICATION__"),await this.initAttach()}componentWillRender(){this.fetcherType||(this.fetcherType="AnexoSistema"),null==this._currentDataUnit&&this.loadAttachmentDataUnit()}async handleOnDataStateChange({detail:t}){"Attach"===this.fetcherType&&(t.insertionMode?this._currentDataUnit.enableField("DESCRICAO"):this._currentDataUnit.disableField("DESCRICAO"),await this._currentDataUnit.loadMetadata())}render(){var t,i;return this._currentDataUnit?e("main",{class:"snk-attach__main"},e("header",{class:"snk-attach__header"},e("snk-simple-bar",{onExit:this.handleBack,messagesBuilder:this.messagesBuilder},e("div",{slot:"rightSlot"},e("ez-button",{class:"ez-button--primary",label:this.getMessage("snkAttach.finish"),onClick:this.handleFinish})))),e("div",{class:"snk-attach__crud-section ez-size-height--full ez-size-width--full ez-flex ez-flex--column"},e("div",{class:"ez-box__container"},e("snk-simple-crud",{ref:t=>this._crudElement=t,dataUnit:this._currentDataUnit,taskbarManager:L(),gridConfig:null===(t=this.crudConfig)||void 0===t?void 0:t.grid,formConfig:null===(i=this.crudConfig)||void 0===i?void 0:i.form,useCancelConfirm:!1,onActionClick:this.handleTaskbarClick,messagesBuilder:this.messagesBuilder,onDataStateChange:this.handleOnDataStateChange.bind(this)},e("div",{slot:"snkSimpleCrudHeader"},e("div",{class:"ez-flex ez-flex--column"},e("span",{class:"ez-title--primary ez-text ez-text--large ez-text--bold ez-padding-bottom--medium"},this.getMessage("snkAttach.title")),e("span",{class:"ez-text ez-text--medium ez-text--secondary ez-padding-bottom--medium"},this.getMessage("snkAttach.description")))))))):null}static get watchers(){return{registerKey:["registerKeyWatcher"]}}};x.style=".snk-attach__header.sc-snk-attach,.snk-attach__crud-section.sc-snk-attach{padding:0 var(--space--lg)}.snk-attach__file-info.sc-snk-attach{padding:var(--space--small);max-width:50%}.snk-attach__main.sc-snk-attach{height:85%}.ez-box__container.sc-snk-attach{height:100%}";export{x as snk_attach}