@sankhyalabs/sankhyablocks 5.7.0 → 5.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/cjs/{SnkMessageBuilder-056d1c24.js → SnkMessageBuilder-1760d2c9.js} +7 -0
  2. package/dist/cjs/loader.cjs.js +1 -1
  3. package/dist/cjs/sankhyablocks.cjs.js +1 -1
  4. package/dist/cjs/snk-application.cjs.entry.js +1 -1
  5. package/dist/cjs/snk-data-exporter.cjs.entry.js +2 -2
  6. package/dist/cjs/{snk-data-unit-289081c4.js → snk-data-unit-f27603c9.js} +1 -1
  7. package/dist/cjs/snk-data-unit.cjs.entry.js +2 -2
  8. package/dist/cjs/snk-detail-view.cjs.entry.js +1 -1
  9. package/dist/cjs/snk-filter-bar.cjs.entry.js +1 -1
  10. package/dist/cjs/snk-filter-binary-select.cjs.entry.js +19 -15
  11. package/dist/cjs/snk-filter-detail.cjs.entry.js +4 -9
  12. package/dist/cjs/snk-filter-item.cjs.entry.js +35 -7
  13. package/dist/cjs/snk-filter-modal-item.cjs.entry.js +4 -3
  14. package/dist/cjs/snk-filter-modal.cjs.entry.js +2 -2
  15. package/dist/cjs/snk-filter-period.cjs.entry.js +8 -1
  16. package/dist/cjs/snk-grid.cjs.entry.js +8 -1
  17. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-binary-select.js +19 -35
  18. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-period.js +23 -1
  19. package/dist/collection/components/snk-filter-bar/filter-item/snk-filter-detail.js +5 -10
  20. package/dist/collection/components/snk-filter-bar/filter-item/snk-filter-item.js +36 -8
  21. package/dist/collection/components/snk-filter-bar/filter-modal/snk-filter-modal.css +1 -0
  22. package/dist/collection/components/snk-filter-bar/filter-modal/snk-filter-modal.js +1 -1
  23. package/dist/collection/components/snk-filter-bar/filter-modal/subcomponents/snk-filter-modal-item.css +5 -1
  24. package/dist/collection/components/snk-filter-bar/filter-modal/subcomponents/snk-filter-modal-item.js +3 -2
  25. package/dist/collection/components/snk-filter-bar/snk-filter-bar.js +1 -1
  26. package/dist/collection/components/snk-grid/snk-grid.js +8 -1
  27. package/dist/collection/lib/message/resources/snk-filter-bar.msg.js +7 -0
  28. package/dist/components/SnkMessageBuilder.js +7 -0
  29. package/dist/components/snk-filter-bar2.js +1 -1
  30. package/dist/components/snk-filter-binary-select.js +20 -17
  31. package/dist/components/snk-filter-detail2.js +5 -10
  32. package/dist/components/snk-filter-item2.js +36 -8
  33. package/dist/components/snk-filter-modal-item2.js +4 -3
  34. package/dist/components/snk-filter-modal.js +2 -2
  35. package/dist/components/snk-filter-period.js +9 -1
  36. package/dist/components/snk-grid2.js +8 -1
  37. package/dist/esm/{SnkMessageBuilder-23272e07.js → SnkMessageBuilder-4caf8b4f.js} +7 -0
  38. package/dist/esm/loader.js +1 -1
  39. package/dist/esm/sankhyablocks.js +1 -1
  40. package/dist/esm/snk-application.entry.js +1 -1
  41. package/dist/esm/snk-data-exporter.entry.js +2 -2
  42. package/dist/esm/{snk-data-unit-34dc5371.js → snk-data-unit-640399b3.js} +1 -1
  43. package/dist/esm/snk-data-unit.entry.js +2 -2
  44. package/dist/esm/snk-detail-view.entry.js +1 -1
  45. package/dist/esm/snk-filter-bar.entry.js +1 -1
  46. package/dist/esm/snk-filter-binary-select.entry.js +19 -15
  47. package/dist/esm/snk-filter-detail.entry.js +5 -10
  48. package/dist/esm/snk-filter-item.entry.js +36 -8
  49. package/dist/esm/snk-filter-modal-item.entry.js +4 -3
  50. package/dist/esm/snk-filter-modal.entry.js +2 -2
  51. package/dist/esm/snk-filter-period.entry.js +8 -1
  52. package/dist/esm/snk-grid.entry.js +8 -1
  53. package/dist/sankhyablocks/p-08779202.entry.js +1 -0
  54. package/dist/sankhyablocks/{p-7695c404.entry.js → p-1465f132.entry.js} +1 -1
  55. package/dist/sankhyablocks/{p-0110b7da.entry.js → p-21c2b733.entry.js} +1 -1
  56. package/dist/sankhyablocks/p-29c1889f.js +1 -0
  57. package/dist/sankhyablocks/p-355e7ab0.entry.js +1 -0
  58. package/dist/sankhyablocks/p-3794686e.entry.js +1 -0
  59. package/dist/sankhyablocks/{p-64b03506.entry.js → p-4181c36d.entry.js} +1 -1
  60. package/dist/sankhyablocks/{p-c1ab16d0.entry.js → p-57b74971.entry.js} +2 -2
  61. package/dist/sankhyablocks/p-59705471.entry.js +1 -0
  62. package/dist/sankhyablocks/{p-3db1d3de.js → p-6981c03e.js} +1 -1
  63. package/dist/sankhyablocks/p-80e52e85.entry.js +1 -0
  64. package/dist/sankhyablocks/{p-df8f13b4.entry.js → p-9c3f0caf.entry.js} +1 -1
  65. package/dist/sankhyablocks/p-9cbc3925.entry.js +1 -0
  66. package/dist/sankhyablocks/p-b9fb86fe.entry.js +1 -0
  67. package/dist/sankhyablocks/sankhyablocks.esm.js +1 -1
  68. package/dist/types/components/snk-filter-bar/filter-item/snk-filter-item.d.ts +8 -1
  69. package/dist/types/components.d.ts +8 -4
  70. package/package.json +1 -1
  71. package/dist/sankhyablocks/p-45ee8b22.entry.js +0 -1
  72. package/dist/sankhyablocks/p-82bc97da.entry.js +0 -1
  73. package/dist/sankhyablocks/p-a1c58536.entry.js +0 -1
  74. package/dist/sankhyablocks/p-bdbb2672.entry.js +0 -1
  75. package/dist/sankhyablocks/p-ed3d6ab4.entry.js +0 -1
  76. package/dist/sankhyablocks/p-ee1381f4.entry.js +0 -1
  77. package/dist/sankhyablocks/p-f5f36fbb.js +0 -1
  78. package/dist/sankhyablocks/p-ffac37d5.entry.js +0 -1
@@ -1,5 +1,5 @@
1
1
  import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-cfd4bb13.js';
2
- import { FloatingManager, ElementIDUtils } from '@sankhyalabs/core';
2
+ import { FloatingManager, DateUtils, ElementIDUtils } from '@sankhyalabs/core';
3
3
  import { F as FilterItemType } from './filter-item-type.enum-5028ed3f.js';
4
4
 
5
5
  const SnkFilterItem = class {
@@ -114,16 +114,17 @@ const SnkFilterItem = class {
114
114
  evt.stopPropagation();
115
115
  }
116
116
  }
117
- getLabel() {
117
+ getLabel(isTooltipLabel = false) {
118
118
  const { type, value, label, props } = this.config;
119
119
  if (value) {
120
120
  if (type === FilterItemType.BINARY_SELECT) {
121
121
  const [optOne, optTwo] = props.options;
122
+ const tooltip = this.getMessage('snkFilterBar.binarySelectTooltip');
122
123
  if (optOne.name === value) {
123
- return optOne.label;
124
+ return isTooltipLabel ? `${tooltip} ${String(optOne.label).toLowerCase()}` : optOne.label;
124
125
  }
125
126
  if (optTwo.name === value) {
126
- return optTwo.label;
127
+ return isTooltipLabel ? `${tooltip} ${String(optTwo.label).toLowerCase()}` : optTwo.label;
127
128
  }
128
129
  }
129
130
  if (type === FilterItemType.MULTI_SELECT) {
@@ -142,14 +143,21 @@ const SnkFilterItem = class {
142
143
  }
143
144
  const dateFormater = new Intl.DateTimeFormat("pt-BR");
144
145
  if (end && start) {
145
- return `${label}: ${dateFormater.format(start)} a ${dateFormater.format(end)}`;
146
+ const isSameYear = start.getFullYear() === end.getFullYear();
147
+ const formatOptions = Object.assign({ day: '2-digit', month: '2-digit' }, ((!isSameYear || isTooltipLabel) && { year: '2-digit' }));
148
+ const startLabel = DateUtils.formatDate(start, formatOptions);
149
+ const endLabel = DateUtils.formatDate(end, formatOptions);
150
+ if (isTooltipLabel) {
151
+ return this.getMessage('snkFilterBar.fullPeriodTooltip', { LABEL: label, START_LABEL: startLabel, END_LABEL: endLabel });
152
+ }
153
+ return `${label}: ${startLabel} \u2192 ${endLabel}`;
146
154
  }
147
155
  else {
148
156
  if (start) {
149
- return `${label}: A partir de ${dateFormater.format(start)}`;
157
+ return `${label}: ${this.getMessage('snkFilterBar.onlyStartPeriodToltip')} ${dateFormater.format(start)}`;
150
158
  }
151
159
  else if (end) {
152
- return `${label}: Até ${dateFormater.format(end)}`;
160
+ return `${label}: ${this.getMessage('snkFilterBar.onlyEndPeriodToltip')} ${dateFormater.format(end)}`;
153
161
  }
154
162
  else {
155
163
  return label;
@@ -162,10 +170,30 @@ const SnkFilterItem = class {
162
170
  if (type === FilterItemType.PERSONALIZED) {
163
171
  return label;
164
172
  }
173
+ if (type === FilterItemType.MULTI_LIST) {
174
+ const selectedOptions = value.filter(item => item.check);
175
+ const checkedAmount = selectedOptions.length;
176
+ if (checkedAmount > 1) {
177
+ if (isTooltipLabel) {
178
+ const selectedOptionsDescrptions = selectedOptions.map(item => item.description);
179
+ return `${label}: ${selectedOptionsDescrptions.join(',')}`;
180
+ }
181
+ return `${label}: ${checkedAmount} ${this.getMessage('snkFilterBar.multiListToltip')}`;
182
+ }
183
+ return `${label}: ${value.description}`;
184
+ }
165
185
  return `${label}: ${value}`;
166
186
  }
167
187
  return label;
168
188
  }
189
+ applyTooltip() {
190
+ if (!this.config.value)
191
+ return undefined;
192
+ return {
193
+ 'data-tooltip': this.getLabel(true),
194
+ 'data-flow': 'bottom'
195
+ };
196
+ }
169
197
  componentDidLoad() {
170
198
  if (this._filterItemElement) {
171
199
  ElementIDUtils.addIDInfo(this._filterItemElement);
@@ -203,7 +231,7 @@ const SnkFilterItem = class {
203
231
  }
204
232
  render() {
205
233
  const leftIcon = this.getLeftIconName();
206
- return (h(Host, null, h("ez-chip", { ref: ref => this._chipElement = ref, label: this.getLabel(), value: this.config.value != undefined, id: this.config.id }, leftIcon ? h("ez-icon", { ref: ref => this._leftIconElement = ref, iconName: leftIcon, class: "ez-padding-right--small", slot: "leftIcon" }) : undefined, h("ez-icon", { ref: ref => this._rightIconElement = ref, iconName: this.getRightIconName(), class: "ez-padding-left--small", slot: "rightIcon", id: "removeFilter" })), h("section", { class: "ez-margin-top--small sc-snk-filter-bar snk-filter__popover-container", ref: elem => this._popoverContainer = elem }, h("snk-filter-detail", { config: this.config, getMessage: this.getMessage, class: "sc-snk-filter-bar snk-filter__popover ez-padding--small", ref: elem => this._popover = elem, key: this.config.id, "data-element-id": this._idSnkFilterDetail }))));
234
+ return (h(Host, Object.assign({}, this.applyTooltip()), h("ez-chip", { id: this.config.id, ref: ref => this._chipElement = ref, label: this.getLabel(), value: this.config.value != undefined }, leftIcon ? h("ez-icon", { ref: ref => this._leftIconElement = ref, iconName: leftIcon, class: "ez-padding-right--small", slot: "leftIcon" }) : undefined, h("ez-icon", { ref: ref => this._rightIconElement = ref, iconName: this.getRightIconName(), class: "ez-padding-left--small", slot: "rightIcon", id: "removeFilter" })), h("section", { class: "ez-margin-top--small sc-snk-filter-bar snk-filter__popover-container", ref: elem => this._popoverContainer = elem }, h("snk-filter-detail", { config: this.config, getMessage: this.getMessage, class: "sc-snk-filter-bar snk-filter__popover ez-padding--small", ref: elem => this._popover = elem, key: this.config.id, "data-element-id": this._idSnkFilterDetail }))));
207
235
  }
208
236
  get _filterItemElement() { return getElement(this); }
209
237
  static get watchers() { return {
@@ -4,7 +4,7 @@ import { F as FilterItemType } from './filter-item-type.enum-5028ed3f.js';
4
4
  import { F as FilterType } from './filter-type.enum-a80c1b6b.js';
5
5
  import { E as EPresentationMode } from './presentationMode-783bbf9d.js';
6
6
 
7
- const snkFilterModalItemCss = ".grow{flex-grow:1}";
7
+ const snkFilterModalItemCss = ".grow{flex-grow:1}.gap{gap:4px}";
8
8
 
9
9
  const SnkFilterModalItem = class {
10
10
  constructor(hostRef) {
@@ -36,7 +36,8 @@ const SnkFilterModalItem = class {
36
36
  return { tag: "snk-filter-text" };
37
37
  }
38
38
  updateFilterValue(newValue) {
39
- this.filterItem = Object.assign(Object.assign({}, this.filterItem), { value: newValue });
39
+ const isVisble = !this.filterItem.visible ? newValue !== undefined : true;
40
+ this.filterItem = Object.assign(Object.assign({}, this.filterItem), { value: newValue, visible: isVisble });
40
41
  }
41
42
  canShowDetailModal() {
42
43
  return this.filterItem.filterType !== FilterType.OTHER_FILTERS && this.filterItem.type !== FilterItemType.BINARY_SELECT;
@@ -50,7 +51,7 @@ const SnkFilterModalItem = class {
50
51
  }
51
52
  render() {
52
53
  const { tag: ContentEditor, variations } = this.getContentEditorConfig();
53
- return (h(Host, null, h("div", { class: "ez-flex ez-flex--column grow" }, this.canShowDetailModal() && (h("div", { class: "col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center" }, h("div", { class: "ez-text ez-title ez-title--small ez-padding--small sc-snk-filter-bar snk-filter-item__editor-header" }, this.filterItem.detailModal))), h(ContentEditor, Object.assign({ config: this.filterItem, value: this.filterItem.value, onValueChanged: (event) => this.updateFilterValue(event.detail), "data-element-id": this._idContentEditor }, variations)))));
54
+ return (h(Host, null, h("div", { class: "ez-flex ez-flex--column grow" }, this.canShowDetailModal() && (h("div", { class: "col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center" }, h("div", { class: "ez-title ez-title--small ez-title--primary grow" }, this.filterItem.detailModal))), h(ContentEditor, Object.assign({ config: this.filterItem, value: this.filterItem.value, onValueChanged: (event) => this.updateFilterValue(event.detail), "data-element-id": this._idContentEditor }, variations)))));
54
55
  }
55
56
  get _element() { return getElement(this); }
56
57
  static get watchers() { return {
@@ -3,7 +3,7 @@ import { ModalAction } from '@sankhyalabs/ezui/dist/collection/components/ez-mod
3
3
  import { F as FilterType } from './filter-type.enum-a80c1b6b.js';
4
4
  import { F as FilterItemType } from './filter-item-type.enum-5028ed3f.js';
5
5
 
6
- const snkFilterModalCss = "ez-modal{--ez-modal-content-padding:24px 12px}.snk-filter__modal-container{width:344px;max-width:344px;overflow:hidden}.snk-filter__modal-content{display:flex;flex-direction:column;gap:12px;max-height:760px;overflow-x:clip;overflow-y:auto;padding-right:4px}.snk-filter__modal-content::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}.snk-filter__modal-collapsible-box{border:1px solid #DCE0E8;border-radius:var(--border--radius-medium)}";
6
+ const snkFilterModalCss = "ez-modal{--ez-modal-content-padding:24px 12px}.snk-filter__modal-container{width:344px;max-width:344px;overflow:hidden}.snk-filter__modal-content{display:flex;flex-direction:column;gap:12px;max-height:760px;overflow-x:clip;overflow-y:auto;padding-right:4px}.snk-filter__modal-content::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}.snk-filter__modal-collapsible-box{border:1px solid #DCE0E8;border-radius:var(--border--radius-medium);padding:12px 6px}";
7
7
 
8
8
  const SnkFilterModal = class {
9
9
  constructor(hostRef) {
@@ -76,7 +76,7 @@ const SnkFilterModal = class {
76
76
  return null;
77
77
  const appliedFilters = listItems.filter(filterItem => !!filterItem.value).length;
78
78
  const lines = this.mountFiltersLines(listItems);
79
- return (h("ez-collapsible-box", { className: "snk-filter__modal-collapsible-box ez-padding--medium", headerSize: "medium", value: true, label: label }, !!appliedFilters && (h("ez-badge", { className: "ez-badge--primary-subtle", slot: "rightSlot", label: appliedFilters })), lines.map(this.renderFilterLine.bind(this)), h("div", { class: "ez-flex ez-flex--justify-end grow" }, h("ez-button", { className: "ez-button--tertiary", size: "medium", label: "Limpar", onClick: () => this.handleClearFilters(listItems) }))));
79
+ return (h("ez-collapsible-box", { className: "snk-filter__modal-collapsible-box", headerSize: "medium", value: true, label: label }, !!appliedFilters && (h("ez-badge", { className: "ez-badge--primary-subtle", slot: "rightSlot", label: appliedFilters })), lines.map(this.renderFilterLine.bind(this)), h("div", { class: "ez-flex ez-flex--justify-end grow" }, h("ez-button", { className: "ez-button--tertiary", size: "medium", label: "Limpar", onClick: () => this.handleClearFilters(listItems) }))));
80
80
  }
81
81
  componentWillRender() {
82
82
  this._modalTitle = this.getCustomMessage('title');
@@ -7,7 +7,10 @@ const SnkFilterPeriod = class {
7
7
  constructor(hostRef) {
8
8
  registerInstance(this, hostRef);
9
9
  this.valueChanged = createEvent(this, "valueChanged", 7);
10
+ this._startDateLabel = 'Inicial';
11
+ this._endDateLabel = 'Final';
10
12
  this.config = undefined;
13
+ this.getMessage = undefined;
11
14
  this.value = undefined;
12
15
  this.presentationMode = EPresentationMode.CHIP;
13
16
  }
@@ -48,11 +51,15 @@ const SnkFilterPeriod = class {
48
51
  return h("label", { class: "ez-text ez-text--medium ez-text--primary ez-margin--medium" }, "at\u00E9");
49
52
  }
50
53
  }
54
+ componentWillLoad() {
55
+ this._startDateLabel = this.getMessage('snkFilterBar.labelStartDatePeriod');
56
+ this._endDateLabel = this.getMessage('snkFilterBar.labelEndDatePeriod');
57
+ }
51
58
  render() {
52
59
  if (!this.config || this.config.type !== FilterItemType.PERIOD) {
53
60
  return undefined;
54
61
  }
55
- return (h("div", { class: "ez-col ez-col--nowrap" }, h("ez-date-input", { id: `${this.config.id}_start`, class: this.presentationMode === EPresentationMode.MODAL ? 'ez-padding--small' : '', label: this.config.label, ref: ref => this._startDate = ref, value: this.getDate("start") }), this.buildLabel(), h("ez-date-input", { id: `${this.config.id}_end`, class: this.presentationMode === EPresentationMode.MODAL ? 'ez-padding--small' : '', label: this.config.label, ref: ref => this._endDate = ref, value: this.getDate("end") })));
62
+ return (h("div", { class: "ez-col ez-col--nowrap" }, h("ez-date-input", { id: `${this.config.id}_start`, class: this.presentationMode === EPresentationMode.MODAL ? 'ez-padding--small' : '', label: this._startDateLabel, ref: ref => this._startDate = ref, value: this.getDate("start") }), this.buildLabel(), h("ez-date-input", { id: `${this.config.id}_end`, class: this.presentationMode === EPresentationMode.MODAL ? 'ez-padding--small' : '', label: this._endDateLabel, ref: ref => this._endDate = ref, value: this.getDate("end") })));
56
63
  }
57
64
  get _element() { return getElement(this); }
58
65
  };
@@ -222,10 +222,12 @@ const SnkGrid = class {
222
222
  if (!this._dataUnit) {
223
223
  this._snkDataUnit.addEventListener("dataUnitReady", (evt) => {
224
224
  this._dataUnit = evt.detail;
225
+ this._dataUnitLoadLockerResolver = this._dataUnit.addLoadingLocker();
225
226
  this.addElementID();
226
227
  });
227
228
  }
228
229
  else {
230
+ this._dataUnitLoadLockerResolver = this._dataUnit.addLoadingLocker();
229
231
  this.addElementID();
230
232
  }
231
233
  this._snkDataUnit.addEventListener("dataStateChange", (evt) => {
@@ -275,13 +277,18 @@ const SnkGrid = class {
275
277
  getPrimaryButton() {
276
278
  return this.presentationMode === PresentationMode.PRIMARY ? "INSERT" : "";
277
279
  }
280
+ onEzGridReady() {
281
+ var _a;
282
+ (_a = this._dataUnitLoadLockerResolver) === null || _a === void 0 ? void 0 : _a.call(this);
283
+ this._dataUnitLoadLockerResolver = undefined;
284
+ }
278
285
  render() {
279
286
  var _a, _b;
280
287
  if (!this._dataUnit) {
281
288
  return undefined;
282
289
  }
283
290
  return (h("div", { class: "snk-grid__container ez-flex ez-flex--column ez-flex-item--auto ez-padding--large" }, h("div", { class: "snk-grid__header ez-margin-bottom--medium" }, h("snk-filter-bar", { ref: (ref) => this._snkFilterBar = ref, dataUnit: this._dataUnit, "data-element-id": "gridFilter", class: "snk-grid__filter-bar ez-align--top", configName: this.configName, messagesBuilder: this.messagesBuilder }), ((_b = (_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.filterConfig) === null || _b === void 0 ? void 0 : _b.length) > 0 &&
284
- h("hr", { class: "ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-grid__header-divider" }), h("snk-taskbar", { class: "ez-padding-left--medium", "data-element-id": "grid_top", key: "topTaskbar", configName: this.configName, dataUnit: this._dataUnit, messagesBuilder: this.messagesBuilder, buttons: this._topTaskbarProcessor.buttons, disabledButtons: this._topTaskbarProcessor.disabledButtons, customButtons: this._topTaskbarProcessor.customButtons, primaryButton: this.getPrimaryButton() })), h("ez-grid", { ref: ref => this._grid = ref, class: (this.presentationMode === PresentationMode.SECONDARY ? "snk-grid-container__without-shadow " : "") + "snk-grid__table", "data-element-id": "embedded", dataUnit: this._dataUnit, key: "grid-" + this._snkDataUnit.entityName, config: this._gridConfig, onConfigChange: (evt) => { this.gridConfigChangeHandler(evt); }, onEzDoubleClick: () => this.gridDoubleClick.emit(), statusResolver: this.statusResolver, multipleSelection: this.multipleSelection }, h("snk-taskbar", { dataUnit: this._dataUnit, configName: this.configName, messagesBuilder: this.messagesBuilder, "data-element-id": "grid_left", buttons: this._headerTaskbarProcessor.buttons, disabledButtons: this._headerTaskbarProcessor.disabledButtons, customButtons: this._headerTaskbarProcessor.customButtons, slot: "leftButtons", actionsList: this.actionsList })), h("div", { class: "ez-col ez-col--sd-12" }, h("slot", { name: "SnkGridFooter" })), h("ez-modal", { modalSize: "small", closeEsc: false, closeOutsideClick: false, opened: this._popUpGridConfig, 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), application: this._application, selectedIndex: 0, configName: this.configName, onConfigChange: (evt) => this.modalConfigChangeHandler(evt), onConfigCancel: () => this.closeGridConfig() }))));
291
+ h("hr", { class: "ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-grid__header-divider" }), h("snk-taskbar", { class: "ez-padding-left--medium", "data-element-id": "grid_top", key: "topTaskbar", configName: this.configName, dataUnit: this._dataUnit, messagesBuilder: this.messagesBuilder, buttons: this._topTaskbarProcessor.buttons, disabledButtons: this._topTaskbarProcessor.disabledButtons, customButtons: this._topTaskbarProcessor.customButtons, primaryButton: this.getPrimaryButton() })), h("ez-grid", { ref: ref => this._grid = ref, class: (this.presentationMode === PresentationMode.SECONDARY ? "snk-grid-container__without-shadow " : "") + "snk-grid__table", "data-element-id": "embedded", dataUnit: this._dataUnit, key: "grid-" + this._snkDataUnit.entityName, config: this._gridConfig, onConfigChange: (evt) => { this.gridConfigChangeHandler(evt); }, onEzDoubleClick: () => this.gridDoubleClick.emit(), statusResolver: this.statusResolver, multipleSelection: this.multipleSelection, onComponentReady: () => this.onEzGridReady() }, h("snk-taskbar", { dataUnit: this._dataUnit, configName: this.configName, messagesBuilder: this.messagesBuilder, "data-element-id": "grid_left", buttons: this._headerTaskbarProcessor.buttons, disabledButtons: this._headerTaskbarProcessor.disabledButtons, customButtons: this._headerTaskbarProcessor.customButtons, slot: "leftButtons", actionsList: this.actionsList })), h("div", { class: "ez-col ez-col--sd-12" }, h("slot", { name: "SnkGridFooter" })), h("ez-modal", { modalSize: "small", closeEsc: false, closeOutsideClick: false, opened: this._popUpGridConfig, 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), application: this._application, selectedIndex: 0, configName: this.configName, onConfigChange: (evt) => this.modalConfigChangeHandler(evt), onConfigCancel: () => this.closeGridConfig() }))));
285
292
  }
286
293
  get _element() { return getElement(this); }
287
294
  };
@@ -0,0 +1 @@
1
+ import{r as t,c as i,h as s,H as e,g as r}from"./p-b9667fbe.js";import{FloatingManager as n,DateUtils as l,ElementIDUtils as h}from"@sankhyalabs/core";import{F as o}from"./p-584d7212.js";const a=class{constructor(s){t(this,s),this.visibleChanged=i(this,"visibleChanged",7),this.filterChange=i(this,"filterChange",7),this.innerClickCheck=(t,i)=>i.id!=n.MODAL_ELEMENT_ID||(this.detailIsVisible=!1,!1),this.detailIsVisible=void 0,this.config=void 0,this.getMessage=void 0}observeDetailIsVisible(t){this.visibleChanged.emit(t)}async showUp(t=!1){return new Promise((i=>{this._filterItemElement.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"}),t&&(this._closeCallback=i,window.requestAnimationFrame((()=>{this._floatingID=n.float(this._popover,this._popoverContainer,this.getFloatOptions()),this._popover.show(),this.detailIsVisible=!0})))}))}updatePosition(){null!=this._floatingID&&n.updateFloatPosition(this._popover,this._popoverContainer,this.getFloatOptions())}getFloatOptions(){return{autoClose:!0,innerClickTest:this.innerClickCheck,backClickListener:()=>this.onDetailCloseCallback(),left:this.getScrollOffsetLeft(),top:this.getScrollOffsetTop(),useOverlay:!0,overlayClassName:"ez-scrim ez-scrim--light",isFixed:!0}}getScrollOffsetLeft(){const t=getComputedStyle(this._filterItemElement).getPropertyValue("padding-left");return`calc(${this._filterItemElement.getBoundingClientRect().x}px + ${t})`}getScrollOffsetTop(){const t=this._filterItemElement.getBoundingClientRect();return t.y+t.height+"px"}controlScrollPage(){window.removeEventListener("scroll",this.updatePosition.bind(this)),window.addEventListener("scroll",this.updatePosition.bind(this))}async hideDetail(){this.detailIsVisible&&null!=this._floatingID&&n.close(this._floatingID)}onDetailCloseCallback(){this._floatingID=void 0,this.detailIsVisible=!1,this._closeCallback&&(this._closeCallback(),this._closeCallback=void 0)}clickListener(t){[this._chipElement,this._leftIconElement,this._rightIconElement].includes(t.target)&&(t.target===this._rightIconElement&&null!=this.config.value?this.filterChange.emit(Object.assign(Object.assign({},this.config),{value:void 0})):this.detailIsVisible?this.hideDetail():this.showUp(!0),t.preventDefault(),t.stopImmediatePropagation(),t.stopPropagation())}mouseDownListener(t){this.detailIsVisible&&[this._chipElement,this._leftIconElement,this._rightIconElement].includes(t.target)&&(t.preventDefault(),t.stopImmediatePropagation(),t.stopPropagation())}getLabel(t=!1){const{type:i,value:s,label:e,props:r}=this.config;if(s){if(i===o.BINARY_SELECT){const[i,e]=r.options,n=this.getMessage("snkFilterBar.binarySelectTooltip");if(i.name===s)return t?`${n} ${String(i.label).toLowerCase()}`:i.label;if(e.name===s)return t?`${n} ${String(e.label).toLowerCase()}`:e.label}if(i===o.MULTI_SELECT)return`${e}: ${r.options.find((t=>t.value===s)).label}`;if(i===o.PERIOD){let{end:i,start:r}=s;"string"==typeof i&&(i=new Date(i),i.setMinutes(i.getMinutes()+i.getTimezoneOffset())),"string"==typeof r&&(r=new Date(r),r.setMinutes(r.getMinutes()+r.getTimezoneOffset()));const n=new Intl.DateTimeFormat("pt-BR");if(i&&r){const s=r.getFullYear()===i.getFullYear(),n=Object.assign({day:"2-digit",month:"2-digit"},(!s||t)&&{year:"2-digit"}),h=l.formatDate(r,n),o=l.formatDate(i,n);return t?this.getMessage("snkFilterBar.fullPeriodTooltip",{LABEL:e,START_LABEL:h,END_LABEL:o}):`${e}: ${h} → ${o}`}return r?`${e}: ${this.getMessage("snkFilterBar.onlyStartPeriodToltip")} ${n.format(r)}`:i?`${e}: ${this.getMessage("snkFilterBar.onlyEndPeriodToltip")} ${n.format(i)}`:e}if(i===o.SEARCH)return`${e}: ${s.value} - ${s.label}`;if(i===o.PERSONALIZED)return e;if(i===o.MULTI_LIST){const i=s.filter((t=>t.check)),r=i.length;return r>1?t?`${e}: ${i.map((t=>t.description)).join(",")}`:`${e}: ${r} ${this.getMessage("snkFilterBar.multiListToltip")}`:`${e}: ${s.description}`}return`${e}: ${s}`}return e}applyTooltip(){if(this.config.value)return{"data-tooltip":this.getLabel(!0),"data-flow":"bottom"}}componentDidLoad(){this._filterItemElement&&(h.addIDInfo(this._filterItemElement),this._idSnkFilterDetail=`filterDetail_${this.config.id}`),this.controlScrollPage()}componentDidRender(){null==this._floatingID&&this._popover&&this._popover.remove()}filterChangeListener(){this.hideDetail()}getRightIconName(){return null!=this.config.value?"close":this.detailIsVisible?"chevron-up":"chevron-down"}getLeftIconName(){switch(this.config.type){case o.PERIOD:return"calendar";case o.PERSONALIZED:return"tune"}}render(){const t=this.getLeftIconName();return s(e,Object.assign({},this.applyTooltip()),s("ez-chip",{id:this.config.id,ref:t=>this._chipElement=t,label:this.getLabel(),value:null!=this.config.value},t?s("ez-icon",{ref:t=>this._leftIconElement=t,iconName:t,class:"ez-padding-right--small",slot:"leftIcon"}):void 0,s("ez-icon",{ref:t=>this._rightIconElement=t,iconName:this.getRightIconName(),class:"ez-padding-left--small",slot:"rightIcon",id:"removeFilter"})),s("section",{class:"ez-margin-top--small sc-snk-filter-bar snk-filter__popover-container",ref:t=>this._popoverContainer=t},s("snk-filter-detail",{config:this.config,getMessage:this.getMessage,class:"sc-snk-filter-bar snk-filter__popover ez-padding--small",ref:t=>this._popover=t,key:this.config.id,"data-element-id":this._idSnkFilterDetail})))}get _filterItemElement(){return r(this)}static get watchers(){return{detailIsVisible:["observeDetailIsVisible"]}}};export{a as snk_filter_item}
@@ -1 +1 @@
1
- import{r as t,h as e,H as i,g as r}from"./p-b9667fbe.js";import{DataType as s,ObjectUtils as a,ElementIDUtils as n,ErrorException as o,ApplicationContext as l}from"@sankhyalabs/core";import{EzScrollDirection as d}from"@sankhyalabs/ezui/dist/collection/components/ez-scroller/EzScrollDirection";import{C as c}from"./p-52ed2a18.js";import{toString as h}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";import{F as f}from"./p-584d7212.js";import{ApplicationUtils as u}from"@sankhyalabs/ezui/dist/collection/utils";import"./p-0d81236c.js";import"./p-41d92871.js";import"./p-112455b1.js";class m{constructor({filterConfig:t,onComplete:e,getMessage:i}){this._filterConfig=t,this._onComplete=e,this._getMessage=i}applyFilters(t){this._onComplete(t),this._closeModal()}clearAll(t){return t.map((t=>Object.assign(Object.assign({},t),{value:void 0})))}buildFilterModal(){const t=document.createElement("snk-filter-modal");return t.filters=this._filterConfig,t.getMessage=this._getMessage.bind(this),t.applyFilters=this.applyFilters.bind(this),t.clearAll=this.clearAll.bind(this),t.closeModal=()=>this._closeModal(),t}async showModal(){const t={content:this.buildFilterModal(),position:"left",heightMode:"full",closeOutsideClick:!1,useScrimLight:!0};this._closeModal=await u.showModal(t)}}const p=class{constructor(e){t(this,e),this._updateSequence=[],this._loadingPending=!1,this._configUpdated=!1,this._pendingFilters=[],this._calculateSortIndex=t=>{let e=t.hardFixed?1e6:0;return t.hardFixed||(e+=t.fixed?1e5:0,e+=null==t.value?0:1e4,e+=this._updateSequence.lastIndexOf(t.id)+1),e},this._filtersComparator=(t,e)=>this._calculateSortIndex(e)-this._calculateSortIndex(t),this.dataUnit=void 0,this.configName=void 0,this.filterConfig=void 0,this.messagesBuilder=void 0,this.allowDefault=void 0,this.scrollerLocked=!1}observeFilterConfig(t,e){if(null!=e&&null==t)this._loadingPending=!0,this._configUpdated=!0;else{const i=new Map(e?e.map((t=>[t.id,t])):void 0);t.forEach((t=>{const e=i.get(t.id);null!=e?(this._configUpdated=this._configUpdated||a.objectToString(e)!=a.objectToString(t),this._loadingPending=this._loadingPending||a.objectToString(e.value)!==a.objectToString(t.value)):(this._configUpdated=!0,this._loadingPending=this._loadingPending||null!=t.value)}))}this.processAfterUpdateConfig()}componentDidLoad(){this._element&&n.addIDInfo(this._element,null,{dataUnit:this.dataUnit})}processPendingFilter(){this._pendingFilters.length>0&&null==this._currentPendingFilter&&(this._currentPendingFilter=this._element.querySelector("#filter-"+this._pendingFilters.pop()),this._currentPendingFilter&&this._currentPendingFilter.showUp(!0).then((()=>{this._currentPendingFilter=void 0,this.processPendingFilter()}))),null==this._currentPendingFilter&&this.processAfterUpdateConfig()}processAfterUpdateConfig(){this._pendingFilters.length>0||(this._loadingPending&&(this._loadingPending=!1,this.dataUnit.loadData()),this._configUpdated&&(this._configUpdated=!1,c.saveFilterBarConfig(this.filterConfig,this.configName)))}getMessage(t,e,i){var r;return(null===(r=this.messagesBuilder)||void 0===r?void 0:r.getMessage(t,e))||i}getFilter(t){var e;const i=[];return null===(e=this.filterConfig)||void 0===e||e.filter((t=>this.isActiveFilter(t))).forEach((t=>{const e=(t=>{switch(t.type){case f.DEFAULT_FILTER:return function(t){return{name:t.id,expression:t.props.expression,params:[]}}(t);case f.BINARY_SELECT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.options.find((t=>t.name===i)).expression,params:[]}}(t);case f.MULTI_SELECT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.TEXT,value:i}]}}(t);case f.PERIOD:return function(t){const{id:e,value:i,props:r}=t;let{end:a,start:n}=i;"string"==typeof a&&(a=new Date(a)),"string"==typeof n&&(n=new Date(n));const o=[];let l;return a&&n?(l=r.expression.fullfill,o.push({name:`${e}.START`,dataType:s.DATE,value:h(s.DATE,n)},{name:`${e}.END`,dataType:s.DATE,value:h(s.DATE,a)})):n?(l=r.expression.onlystart,o.push({name:e,dataType:s.DATE,value:h(s.DATE,n)})):(l=r.expression.onlyend,o.push({name:e,dataType:s.DATE,value:h(s.DATE,a)})),{name:e,expression:l,params:o}}(t);case f.SEARCH:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.TEXT,value:h(s.TEXT,i.value)}]}}(t);case f.TEXT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.TEXT,value:h(s.TEXT,i)}]}}(t);case f.NUMBER:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.NUMBER,value:h(s.NUMBER,i)}]}}(t);case f.PERSONALIZED:return function(t){var e;const{id:i,value:r,props:a}=t;return{name:i,expression:a.expression,params:((null===(e=a.personalizedFilter)||void 0===e?void 0:e.parameters)||[]).map(((t,e)=>{const i=Array.from(r),a=t.dataType;let n=e>=0&&e<i.length?i[e]:null;return null!=n&&"object"==typeof n&&"value"in n&&(n=n.value),null==n&&a===s.BOOLEAN&&(n=!1),{name:t.name,dataType:a,value:"string"==typeof n?n:h(a,n)}}))}}(t);default:return}})(t);e&&i.push(e)})),i}isActiveFilter(t){return t.visible&&null!=t.value||t.type===f.DEFAULT_FILTER}registryFilterProvider(){this.dataUnit.addFilterProvider(this),this.filterConfig&&this.dataUnit.loadData()}itemFocused(t){this._element.querySelectorAll("snk-filter-item,snk-filter-list").forEach((e=>{e.id===t?"snk-filter-item"===e.tagName.toLowerCase()&&e.getClientRects()[0].x<0&&e.scrollIntoView({behavior:"auto",inline:"nearest"}):e.hideDetail()}))}getFilterItems(){const t=[],i=[];this.filterConfig.filter((t=>t.visible)).forEach(((r,s)=>{const a=`filter-${r.id}`,n=e("snk-filter-item",{onVisibleChanged:t=>this.scrollerLocked=t.detail,onFocusin:()=>this.itemFocused(a),id:a,config:r,class:s>0?"ez-padding-left--medium":"",getMessage:(t,e)=>this.getMessage(t,e),key:r.id});return r.fixed||r.hardFixed?t.push(n):i.push(n),n}));const r=[];return r.push(...t),t.length>0&&i.length>0&&r.push(e("hr",{class:"ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-filter-bar__divider"})),r.push(...i),r}calculateUpdateSequence(t){t&&(this._updateSequence=this._updateSequence.filter((e=>t.id!==e)),this._updateSequence.push(t.id))}normalizeItem(t){const e=Object.assign({},t);return["props","value","hardFixed","fixed"].forEach((t=>{null==e[t]&&delete e[t]})),""===t.value&&delete t.value,e}updateFilter(t){this.filterConfig=this.filterConfig.map((e=>(t=this.normalizeItem(t),e.id===t.id?(a.objectToString(e)!=a.objectToString(t)&&this.calculateUpdateSequence(t),t):e))).sort(((t,e)=>this._filtersComparator(t,e)))}loadPermitions(){this._application.isUserSup().then((t=>this.allowDefault=t))}loadConfigFromStorage(){c.get().then((t=>{t.loadFilterBarConfig(this.configName).then((t=>{this.filterConfig=t.map((t=>this.normalizeItem(t))),this.dataUnit&&this.dataUnit.loadData(void 0,void 0,!0)})).catch((t=>{throw new o(this.getMessage("snkFilterBar.failToLoadConfig"),t)}))}))}attachDataUnit(){if(null==this.dataUnit){let t=this._element.parentElement;for(;t;)if("SNK-DATA-UNIT"===t.tagName.toUpperCase()){const e=t;this.dataUnit=e.dataUnit,this.dataUnit?this.registryFilterProvider():e.addEventListener("dataUnitReady",(t=>{this.dataUnit=t.detail,this.registryFilterProvider()}));break}t=t.parentElement}else this.registryFilterProvider()}filterChangeListener(t){this.updateFilter(t.detail)}async showFilterModal(){const t=new m({filterConfig:this.filterConfig,onComplete:t=>{this.filterConfig=t.map(this.normalizeItem)},getMessage:(t,e)=>this.getMessage(t,e)});await t.showModal()}componentWillLoad(){this._application=l.getContextValue("__SNK__APPLICATION__"),this._application&&(this.loadPermitions(),this.loadConfigFromStorage()),this.attachDataUnit()}componentDidRender(){this.processPendingFilter()}render(){if(this.dataUnit&&this.filterConfig&&0!==this.filterConfig.length)return e(i,null,e("ez-scroller",{direction:d.HORIZONTAL,activeShadow:!0,locked:this.scrollerLocked},this.getFilterItems()),e("ez-button",{class:"ez-padding-left--medium",size:"small",label:this.getMessage("snkFilterBar.filters",void 0,"Filtros"),onClick:this.showFilterModal.bind(this)},e("ez-icon",{slot:"leftIcon",iconName:"plus",class:"ez-padding-right--small"})))}get _element(){return r(this)}static get watchers(){return{filterConfig:["observeFilterConfig"]}}};p.style='.sc-snk-filter-bar-h{display:grid;grid-template-columns:minmax(100px, 100%) 1fr 1fr}.snk-filter__popover-container.sc-snk-filter-bar{display:flex;cursor:auto}.snk-filter__popover.sc-snk-filter-bar{display:flex;flex-direction:column;position:absolute;width:fit-content;height:fit-content;min-width:265px;z-index:var(--most-visible, 3);background-color:var(--background--xlight, #fff);border-radius:var(--border--radius-medium, 12px);box-shadow:var(--shadow, 0px 0px 16px 0px #000)}.snk-filter-item__editor-header.sc-snk-filter-bar{flex-grow:1;font-weight:var(--text-weight--medium, 400);color:var(--color--title-primary, #2B3A54)}.snk-filter__popover-rule.sc-snk-filter-bar{border-style:solid;border-color:var(--color--disable-secondary, #F2F5F8);border-radius:1px;border-width:1px;width:100%}.editor__ez-check.sc-snk-filter-bar{--ez-check__label--padding-left:0}.snk-filter-item__editor-header-button.sc-snk-filter-bar{cursor:pointer;background-color:transparent;border:none;padding:3px;outline-color:var(--color--primary)}.snk-filter-bar__divider.sc-snk-filter-bar{margin-bottom:var(--space--small)}.snk-filter-bar__filter-list-items-container.sc-snk-filter-bar{overflow-y:auto;max-height:360px;margin-top:var(--space--small, 6px)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar{cursor:pointer;border-radius:var(--border--radius-small, 6px);border:none;background-color:transparent}.snk-filter-bar__filter-list-item__label.sc-snk-filter-bar{color:var(--title--primary)}.snk-filter-bar__filter-list-item__label--secondary.sc-snk-filter-bar{color:var(--text--primary)}.snk-filter-bar__filter-list-item__icon.sc-snk-filter-bar{--ez-icon--color:var(--title--primary)}.snk-filter-bar__filter-list-item__icon--secondary.sc-snk-filter-bar{--ez-icon--color:var(--text--secondary)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:focus-visible{outline:none;background-color:var(--background--medium)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:hover{background-color:var(--background--medium)}.snk-filter-bar__filter-list-items-container--empty.sc-snk-filter-bar{width:100%;height:100px;display:flex;justify-content:center;align-self:center;align-items:center}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar{position:relative}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar::after{display:flex;position:absolute;content:"";width:8px;height:8px;top:7px;left:17px;background-color:var(--icon--alert--color, #008561);border-radius:50%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar{--modal-item-border-width:2px;display:flex;flex-direction:row;margin-left:var(--modal-item-border-width);border-radius:var(--border--radius-medium, 12px);background-color:var(--background--medium, #f0f3f7);border:none;width:100%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar:focus-visible{outline:var(--color--primary) solid var(--modal-item-border-width)}.snk-filter-bar__filter-modal-item__check.sc-snk-filter-bar{width:auto}.snk-filter-bar__filter-modal-item__label.sc-snk-filter-bar{font-weight:var(--text-weight--medium)}.snk-filter-bar__filter-modal-content.sc-snk-filter-bar{display:grid;grid-template-rows:auto auto 1fr auto;width:99%;height:100%}';export{p as snk_filter_bar}
1
+ import{r as t,h as e,H as i,g as r}from"./p-b9667fbe.js";import{DataType as s,ObjectUtils as a,ElementIDUtils as n,ErrorException as o,ApplicationContext as l}from"@sankhyalabs/core";import{EzScrollDirection as d}from"@sankhyalabs/ezui/dist/collection/components/ez-scroller/EzScrollDirection";import{C as c}from"./p-52ed2a18.js";import{toString as h}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";import{F as f}from"./p-584d7212.js";import{ApplicationUtils as u}from"@sankhyalabs/ezui/dist/collection/utils";import"./p-0d81236c.js";import"./p-41d92871.js";import"./p-112455b1.js";class m{constructor({filterConfig:t,onComplete:e,getMessage:i}){this._filterConfig=t,this._onComplete=e,this._getMessage=i}applyFilters(t){this._onComplete(t),this._closeModal()}clearAll(t){return t.map((t=>Object.assign(Object.assign({},t),{value:void 0})))}buildFilterModal(){const t=document.createElement("snk-filter-modal");return t.filters=this._filterConfig,t.getMessage=this._getMessage.bind(this),t.applyFilters=this.applyFilters.bind(this),t.clearAll=this.clearAll.bind(this),t.closeModal=()=>this._closeModal(),t}async showModal(){const t={content:this.buildFilterModal(),position:"left",heightMode:"full",closeOutsideClick:!1,useScrimLight:!0};this._closeModal=await u.showModal(t)}}const p=class{constructor(e){t(this,e),this._updateSequence=[],this._loadingPending=!1,this._configUpdated=!1,this._pendingFilters=[],this._calculateSortIndex=t=>{let e=t.hardFixed?1e6:0;return t.hardFixed||(e+=t.fixed?1e5:0,e+=null==t.value?0:1e4,e+=this._updateSequence.lastIndexOf(t.id)+1),e},this._filtersComparator=(t,e)=>this._calculateSortIndex(e)-this._calculateSortIndex(t),this.dataUnit=void 0,this.configName=void 0,this.filterConfig=void 0,this.messagesBuilder=void 0,this.allowDefault=void 0,this.scrollerLocked=!1}observeFilterConfig(t,e){if(null!=e&&null==t)this._loadingPending=!0,this._configUpdated=!0;else{const i=new Map(e?e.map((t=>[t.id,t])):void 0);t.forEach((t=>{const e=i.get(t.id);null!=e?(this._configUpdated=this._configUpdated||a.objectToString(e)!=a.objectToString(t),this._loadingPending=this._loadingPending||a.objectToString(e.value)!==a.objectToString(t.value)):(this._configUpdated=!0,this._loadingPending=this._loadingPending||null!=t.value)}))}this.processAfterUpdateConfig()}componentDidLoad(){this._element&&n.addIDInfo(this._element,null,{dataUnit:this.dataUnit})}processPendingFilter(){this._pendingFilters.length>0&&null==this._currentPendingFilter&&(this._currentPendingFilter=this._element.querySelector("#filter-"+this._pendingFilters.pop()),this._currentPendingFilter&&this._currentPendingFilter.showUp(!0).then((()=>{this._currentPendingFilter=void 0,this.processPendingFilter()}))),null==this._currentPendingFilter&&this.processAfterUpdateConfig()}processAfterUpdateConfig(){this._pendingFilters.length>0||(this._loadingPending&&(this._loadingPending=!1,this.dataUnit.loadData()),this._configUpdated&&(this._configUpdated=!1,c.saveFilterBarConfig(this.filterConfig,this.configName)))}getMessage(t,e,i){var r;return(null===(r=this.messagesBuilder)||void 0===r?void 0:r.getMessage(t,e))||i}getFilter(t){var e;const i=[];return null===(e=this.filterConfig)||void 0===e||e.filter((t=>this.isActiveFilter(t))).forEach((t=>{const e=(t=>{switch(t.type){case f.DEFAULT_FILTER:return function(t){return{name:t.id,expression:t.props.expression,params:[]}}(t);case f.BINARY_SELECT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.options.find((t=>t.name===i)).expression,params:[]}}(t);case f.MULTI_SELECT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.TEXT,value:i}]}}(t);case f.PERIOD:return function(t){const{id:e,value:i,props:r}=t;let{end:a,start:n}=i;"string"==typeof a&&(a=new Date(a)),"string"==typeof n&&(n=new Date(n));const o=[];let l;return a&&n?(l=r.expression.fullfill,o.push({name:`${e}.START`,dataType:s.DATE,value:h(s.DATE,n)},{name:`${e}.END`,dataType:s.DATE,value:h(s.DATE,a)})):n?(l=r.expression.onlystart,o.push({name:e,dataType:s.DATE,value:h(s.DATE,n)})):(l=r.expression.onlyend,o.push({name:e,dataType:s.DATE,value:h(s.DATE,a)})),{name:e,expression:l,params:o}}(t);case f.SEARCH:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.TEXT,value:h(s.TEXT,i.value)}]}}(t);case f.TEXT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.TEXT,value:h(s.TEXT,i)}]}}(t);case f.NUMBER:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:s.NUMBER,value:h(s.NUMBER,i)}]}}(t);case f.PERSONALIZED:return function(t){var e;const{id:i,value:r,props:a}=t;return{name:i,expression:a.expression,params:((null===(e=a.personalizedFilter)||void 0===e?void 0:e.parameters)||[]).map(((t,e)=>{const i=Array.from(r),a=t.dataType;let n=e>=0&&e<i.length?i[e]:null;return null!=n&&"object"==typeof n&&"value"in n&&(n=n.value),null==n&&a===s.BOOLEAN&&(n=!1),{name:t.name,dataType:a,value:"string"==typeof n?n:h(a,n)}}))}}(t);default:return}})(t);e&&i.push(e)})),i}isActiveFilter(t){return t.visible&&null!=t.value||t.type===f.DEFAULT_FILTER}registryFilterProvider(){this.dataUnit.addFilterProvider(this),this.filterConfig&&this.dataUnit.loadData()}itemFocused(t){this._element.querySelectorAll("snk-filter-item,snk-filter-list").forEach((e=>{e.id===t?"snk-filter-item"===e.tagName.toLowerCase()&&e.getClientRects()[0].x<0&&e.scrollIntoView({behavior:"auto",inline:"nearest"}):e.hideDetail()}))}getFilterItems(){const t=[],i=[];this.filterConfig.filter((t=>t.visible)).forEach(((r,s)=>{const a=`filter-${r.id}`,n=e("snk-filter-item",{onVisibleChanged:t=>this.scrollerLocked=t.detail,onFocusin:()=>this.itemFocused(a),id:a,config:r,class:s>0?"ez-padding-left--medium":"",getMessage:(t,e)=>this.getMessage(t,e),key:r.id});return r.fixed||r.hardFixed?t.push(n):i.push(n),n}));const r=[];return r.push(...t),t.length>0&&i.length>0&&r.push(e("hr",{class:"ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-filter-bar__divider"})),r.push(...i),r}calculateUpdateSequence(t){t&&(this._updateSequence=this._updateSequence.filter((e=>t.id!==e)),this._updateSequence.push(t.id))}normalizeItem(t){const e=Object.assign({},t);return["props","value","hardFixed","fixed"].forEach((t=>{null==e[t]&&delete e[t]})),""===t.value&&delete t.value,e}updateFilter(t){this.filterConfig=this.filterConfig.map((e=>(t=this.normalizeItem(t),e.id===t.id?(a.objectToString(e)!=a.objectToString(t)&&this.calculateUpdateSequence(t),t):e))).sort(((t,e)=>this._filtersComparator(t,e)))}loadPermitions(){this._application.isUserSup().then((t=>this.allowDefault=t))}loadConfigFromStorage(){c.get().then((t=>{t.loadFilterBarConfig(this.configName).then((t=>{this.filterConfig=t.map((t=>this.normalizeItem(t))),this.dataUnit&&this.dataUnit.loadData(void 0,void 0,!0)})).catch((t=>{throw new o(this.getMessage("snkFilterBar.failToLoadConfig"),t)}))}))}attachDataUnit(){if(null==this.dataUnit){let t=this._element.parentElement;for(;t;)if("SNK-DATA-UNIT"===t.tagName.toUpperCase()){const e=t;this.dataUnit=e.dataUnit,this.dataUnit?this.registryFilterProvider():e.addEventListener("dataUnitReady",(t=>{this.dataUnit=t.detail,this.registryFilterProvider()}));break}t=t.parentElement}else this.registryFilterProvider()}filterChangeListener(t){this.updateFilter(t.detail)}async showFilterModal(){const t=new m({filterConfig:this.filterConfig,onComplete:t=>{this.filterConfig=t.map(this.normalizeItem).sort(((t,e)=>this._filtersComparator(t,e)))},getMessage:(t,e)=>this.getMessage(t,e)});await t.showModal()}componentWillLoad(){this._application=l.getContextValue("__SNK__APPLICATION__"),this._application&&(this.loadPermitions(),this.loadConfigFromStorage()),this.attachDataUnit()}componentDidRender(){this.processPendingFilter()}render(){if(this.dataUnit&&this.filterConfig&&0!==this.filterConfig.length)return e(i,null,e("ez-scroller",{direction:d.HORIZONTAL,activeShadow:!0,locked:this.scrollerLocked},this.getFilterItems()),e("ez-button",{class:"ez-padding-left--medium",size:"small",label:this.getMessage("snkFilterBar.filters",void 0,"Filtros"),onClick:this.showFilterModal.bind(this)},e("ez-icon",{slot:"leftIcon",iconName:"plus",class:"ez-padding-right--small"})))}get _element(){return r(this)}static get watchers(){return{filterConfig:["observeFilterConfig"]}}};p.style='.sc-snk-filter-bar-h{display:grid;grid-template-columns:minmax(100px, 100%) 1fr 1fr}.snk-filter__popover-container.sc-snk-filter-bar{display:flex;cursor:auto}.snk-filter__popover.sc-snk-filter-bar{display:flex;flex-direction:column;position:absolute;width:fit-content;height:fit-content;min-width:265px;z-index:var(--most-visible, 3);background-color:var(--background--xlight, #fff);border-radius:var(--border--radius-medium, 12px);box-shadow:var(--shadow, 0px 0px 16px 0px #000)}.snk-filter-item__editor-header.sc-snk-filter-bar{flex-grow:1;font-weight:var(--text-weight--medium, 400);color:var(--color--title-primary, #2B3A54)}.snk-filter__popover-rule.sc-snk-filter-bar{border-style:solid;border-color:var(--color--disable-secondary, #F2F5F8);border-radius:1px;border-width:1px;width:100%}.editor__ez-check.sc-snk-filter-bar{--ez-check__label--padding-left:0}.snk-filter-item__editor-header-button.sc-snk-filter-bar{cursor:pointer;background-color:transparent;border:none;padding:3px;outline-color:var(--color--primary)}.snk-filter-bar__divider.sc-snk-filter-bar{margin-bottom:var(--space--small)}.snk-filter-bar__filter-list-items-container.sc-snk-filter-bar{overflow-y:auto;max-height:360px;margin-top:var(--space--small, 6px)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar{cursor:pointer;border-radius:var(--border--radius-small, 6px);border:none;background-color:transparent}.snk-filter-bar__filter-list-item__label.sc-snk-filter-bar{color:var(--title--primary)}.snk-filter-bar__filter-list-item__label--secondary.sc-snk-filter-bar{color:var(--text--primary)}.snk-filter-bar__filter-list-item__icon.sc-snk-filter-bar{--ez-icon--color:var(--title--primary)}.snk-filter-bar__filter-list-item__icon--secondary.sc-snk-filter-bar{--ez-icon--color:var(--text--secondary)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:focus-visible{outline:none;background-color:var(--background--medium)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:hover{background-color:var(--background--medium)}.snk-filter-bar__filter-list-items-container--empty.sc-snk-filter-bar{width:100%;height:100px;display:flex;justify-content:center;align-self:center;align-items:center}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar{position:relative}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar::after{display:flex;position:absolute;content:"";width:8px;height:8px;top:7px;left:17px;background-color:var(--icon--alert--color, #008561);border-radius:50%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar{--modal-item-border-width:2px;display:flex;flex-direction:row;margin-left:var(--modal-item-border-width);border-radius:var(--border--radius-medium, 12px);background-color:var(--background--medium, #f0f3f7);border:none;width:100%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar:focus-visible{outline:var(--color--primary) solid var(--modal-item-border-width)}.snk-filter-bar__filter-modal-item__check.sc-snk-filter-bar{width:auto}.snk-filter-bar__filter-modal-item__label.sc-snk-filter-bar{font-weight:var(--text-weight--medium)}.snk-filter-bar__filter-modal-content.sc-snk-filter-bar{display:grid;grid-template-rows:auto auto 1fr auto;width:99%;height:100%}';export{p as snk_filter_bar}
@@ -1 +1 @@
1
- import{r as t,c as i,f as s,h as e,H as a}from"./p-b9667fbe.js";import{S as o}from"./p-e0aa5838.js";import{FormMetadata as h,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-41d92871.js";import"./p-11028eba.js";import"@sankhyalabs/core";import{P as n}from"./p-4c2015a9.js";import{T as d}from"./p-d410f45a.js";import{c as l}from"./p-17375123.js";import{S as c}from"./p-ccd26e3a.js";import{S as u}from"./p-f5f36fbb.js";import"./p-52ed2a18.js";import"./p-0d81236c.js";import"./p-112455b1.js";import"./p-6a02e236.js";import"./p-c2beb95c.js";class m{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!=h.getDetailName(s.split("::").pop()),r=o&&e,n=this._parentGuide.id,d=o?`${n}::${s}`:`${n}__FORM:${s}`;return o&&t.has(d)&&!r?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:r,tooltip:r?"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._disabledButtons=void 0,this.formConfigManager=void 0,this.dataUnitName=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}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 m(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(d.PREVIOUS),this.dataState.hasNext||h.push(d.NEXT),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"})}onContentCardChanged(t){c.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}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(){var t;if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const i=this.formConfigManager.getConfig(null===(t=this.dataState)||void 0===t?void 0:t.insertionMode,this.dataUnit);this._formMetadata=r(null==i||0===i.fields.length?void 0:i,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){t.show(this.selectedForm?1:0)}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)}executeActionHandler(t){t.detail===d.GRID_MODE&&(this.emitSwitchEvent(l.GRID),t.stopPropagation()),t.detail===d.FORM_MODE&&(this.emitSwitchEvent(l.FORM),t.stopPropagation())}componentWillLoad(){this._configName=`dynaform.${this.entityName}`,this.formConfigManager=new o(this._configName,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:t=>this.dataState=t.detail,messagesBuilder:this.messagesBuilder},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-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:n.SECONDARY,isDetail:!0}))),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},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:n.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit}))))))}static get watchers(){return{dataState:["observerDataState"]}}};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}
1
+ import{r as t,c as i,f as s,h as e,H as a}from"./p-b9667fbe.js";import{S as o}from"./p-e0aa5838.js";import{FormMetadata as h,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-41d92871.js";import"./p-11028eba.js";import"@sankhyalabs/core";import{P as n}from"./p-4c2015a9.js";import{T as d}from"./p-d410f45a.js";import{c as l}from"./p-17375123.js";import{S as c}from"./p-ccd26e3a.js";import{S as u}from"./p-29c1889f.js";import"./p-52ed2a18.js";import"./p-0d81236c.js";import"./p-112455b1.js";import"./p-6a02e236.js";import"./p-c2beb95c.js";class m{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!=h.getDetailName(s.split("::").pop()),r=o&&e,n=this._parentGuide.id,d=o?`${n}::${s}`:`${n}__FORM:${s}`;return o&&t.has(d)&&!r?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:r,tooltip:r?"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._disabledButtons=void 0,this.formConfigManager=void 0,this.dataUnitName=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}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 m(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(d.PREVIOUS),this.dataState.hasNext||h.push(d.NEXT),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"})}onContentCardChanged(t){c.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}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(){var t;if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const i=this.formConfigManager.getConfig(null===(t=this.dataState)||void 0===t?void 0:t.insertionMode,this.dataUnit);this._formMetadata=r(null==i||0===i.fields.length?void 0:i,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){t.show(this.selectedForm?1:0)}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)}executeActionHandler(t){t.detail===d.GRID_MODE&&(this.emitSwitchEvent(l.GRID),t.stopPropagation()),t.detail===d.FORM_MODE&&(this.emitSwitchEvent(l.FORM),t.stopPropagation())}componentWillLoad(){this._configName=`dynaform.${this.entityName}`,this.formConfigManager=new o(this._configName,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:t=>this.dataState=t.detail,messagesBuilder:this.messagesBuilder},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-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:n.SECONDARY,isDetail:!0}))),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},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:n.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit}))))))}static get watchers(){return{dataState:["observerDataState"]}}};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
+ const e={saveInfo:{clone:"Duplicação realizada!",insert:"Inclusão realizada!",update:"Alteração realizada!"},cancelInfo:{clone:"Duplicação descartada!",insert:"A inclusão descartada!",update:"A edição foi descartada!"},confirm:{cancel:"Cancelar",delete:"Excluir",yes:"Sim",no:"Não"},removeInfo:"Registro removido com sucesso!",cancelConfirmationTitle:"Aviso",cancelConfirmation:"As alterações realizadas serão descartadas<br/><br/><b>Você realmente gostaria de cancelar?",removeConfirmationTitle:"Aviso",removeConfirmation:"Deseja realmente excluir o registro atual?",forbidden:"Sem permissão",forbiddenUpdate:"Não é possível fazer alterações. Verifique as permissões de acesso.",forbiddenInsert:"Não é possível incluir. Verifique as permissões de acesso.",forbiddenClone:"Não é possível duplicar. Verifique as permissões de acesso.",forbiddenRemove:"Não é possível remover. Verifique as permissões de acesso.",removeAllConfirmation:"Os <strong>{{size}} registros selecionados</strong> serão excluídos.<br/><br/><strong>Você realmente gostaria de continuar?</strong>",removeAllInfo:"Os {{size}} registros foram removidos com sucesso!"},a={addFilter:"Adicionar filtro",pinFilter:"Fixar filtro",unpinFilter:"Desfixar filtro",removeFilter:"Remover filtro",cleanFilter:"Limpar",applyFilter:"Aplicar",findFilter:"Buscar filtros...",findField:"Buscar filtros...",modalFindFilter:"Buscar filtro",emptyFiltersList:"Não há filtros disponíveis",emptyAppliedFiltersList:"Não há filtros aplicados",customFilter:"Filtro personalizado",defaultFilter:"Filtro padrão",failToLoadConfig:"Falha ao buscar configuração de filtros",clearAllFilters:"Limpar todos os filtros",successfullyCleaned:"Filtro limpo com sucesso!",activeFilter:"{{ACTIVE_FILTERS}} filtro aplicado",activeFilters:"{{ACTIVE_FILTERS}} filtros aplicados",noActiveFilters:"Nenhum filtro aplicado",modalDefaultFilterTitle:"Filtro padrão",modalInfoTextEditDefault:"Use o layout antigo para editar o seu filtro padrão, em breve traremos uma nova experiência.",modalInfoTextCreateDefault:"Use o layout antigo para criar o seu filtro padrão, em breve traremos uma nova experiência.",modalPersonalizedFilterTitle:"Filtro personalizado",modalPersonalizedFilterSubTitle:"Gerencie seus filtros",modalInfoTextCreateEditPersonalized:"Use o layout antigo para criar ou editar filtros, em breve traremos uma nova experiência",modalOkButtonLabel:"Aplicar",modalCancelButtonLabel:"Limpar",binarySelectTooltip:"Exibindo registros",multiListToltip:"selecionado(a)s",onlyStartPeriodToltip:"A partir de",onlyEndPeriodToltip:"Até",fullPeriodTooltip:"Data de {{LABEL}}: {{START_LABEL}} até {{END_LABEL}}",labelStartDatePeriod:"Inicial",labelEndDatePeriod:"Final",filters:"Filtros",filterModal:{title:"Filtros",okButtonLabel:"Aplicar",cancelButtonLabel:"Limpar tudo",customFilters:"Filtros personalizados",quickFilters:"Filtros rápidos"}},o={titleUpdate:"Editar",titlePrevious:"Anterior",titleNext:"Próximo",titleRefresh:"Atualizar",titleClone:"Duplicar",titleRemove:"Excluir",titleMoreOptions:"Mais Opções",titleInsert:"Cadastrar",titleCancel:"Cancelar",titleSave:"Salvar",titleGridMode:"Modo Grade",titleFormMode:"Modo Formulário",titleConfigurator:"Configurações",titleAttach:"Anexar",forbidden:"Permissão não liberada"},i={errorArray:"CrudUtils.find deve receber um array de fields, ou uma lista separada por virgula."},r={emailSenderTitle:"Enviar por email",emailSenderBackButton:"Voltar",emailSenderNextButton:"Avançar",emailSenderCancelButton:"Cancelar",emailSenderSendButton:"Enviar",emailSenderOptStep_subtitle:"Primeiro, escolha o formato do arquivo",emailSenderOptStep_lblFormat:"Formato:",emailSenderOptStep_formatPDF:"PDF (.pdf)",emailSenderOptStep_formatXLSX:"Planilha (.xlsx)",emailSenderOptStep_export:"Exportar:",emailSenderOptStep_allData:"Toda a grade",emailSenderOptStep_currentPage:"Somente a página atual",emailSenderOptStep_someRecords:"{{SELECTION_COUNT}} linhas selecionadas",emailSenderOptStep_oneRecord:"Somente a linha selecionada",emailSenderInfoStep_subtitle:"Informações de email",emailSenderInfoStep_sendTo:"Enviar para",emailSenderInfoStep_subject:"Assunto",emailSenderInfoStep_message:"Mensagem"},l={title:{clone:"Duplicar registro",insert:"Cadastrar registro",update:"Alterar registro",clean:"{{ENTITY_NAME}}"},goBackTitle:"Voltar"},s={error:{title:"Erro na Exportação",message:"O usuário não possui permissão para exportar o arquivo."},message:{exportSuccess:"Exportado com sucesso!"}},t={label:{nameField:"Nome do Campo *",typeValueDefault:"Tipo de valor padrão *",valueDefault:"Valor Padrão",clearDuplicate:"Limpar ao Duplicar",requiredField:"Campo Obrigatório",protectedField:"Campo Protegido"},options:{valueFixed:"Valor Fixo",variable:"Variável"}},n={title:"Configuração do formulário",goBackTitle:"Voltar",applyConfig:"Aplicar configuração",availableFields:{title:"Campos disponíveis",labelNoFields:"Nenhum campo disponível",labelOneField:"1 campo disponível",labelAvailableFields:"Campos disponíveis",labelSearchField:"Procurar campo"},form:{subTitleInfo:"Inclua estes campos nos grupos ou deixe-os separados no topo do formulário!",labelDropField:"Arraste e solte um campo aqui",labelNewGroup:"Adicionar novo grupo",mainArea:"Área principal",tabGeneral:"Geral"},confirm:{title:"Aviso",deleteTab:"Você realmente deseja excluir a aba",cancel:"As alterações realizadas serão descartadas.<br/><br/><b>Gostaria de continuar?</b>",exit:"Ao sair as alterações serão descartadas.<br/><br/><b>Você realmente gostaria de sair?</b>",apply:"A <b>{0}</b> irá substituir a sua configuração {1}!<br/><br/><b>Deseja continuar?</b>",group:"Não é possível salvar as configurações com um grupo vazio!",labelCancel:"Cancelar",labelDelete:"Excluir"},alert:{titleGroupExists:"Já existe um grupo com título",infoValidTitle:"Por favor, digite um título válido.",inTab:"na aba"},info:{successfullyConfigSaved:"As configurações foram salvas com sucesso!"}},d={titleRemove:"Remover",titleConfigurations:"Configurações",titleAdd:"Adicionar"},c={labelRename:"Renomear",labelHide:"Ocultar",labelShow:"Exibir",labelDelete:"Excluir"},u={titleConfigurations:"Configurações",subTitleModeConfig:"Modo de visualização",labelConfigGrid:"Configurar grade",labelConfigForm:"Configurar formulário",labelGrid:"Grade",labelForm:"Formulário"},m={},p={gridConfiguration:"Configuração da Grade",columnVisibilityOrder:"Defina visibilidade e ordem das colunas.",sortingSequence:"Sequência da ordenação",findColumn:"Localizar coluna",cancel:"Cancelar",complete:"Concluir",tab:{columns:"Colunas",lineOrdering:"Ordenação das linhas"},info:{successfullyConfigSaved:"As configurações foram salvas com sucesso!"},confirm:{cancel:"Descartar",save:"Salvar",alert:"Aviso",msgCancel:"As alterações realizadas serão descartadas. Gostaria de salvar antes de sair?"},group:{visible:"Visíveis",hidden:"Ocultas"}},f={group:{export:{default:"Exportar para",multiSelected:"Exportar {0} linhas selecionadas",selectedLine:"Exportar somente 1 linha selecionada",title:"Exportar"},custom:"Personalizado"},label:{currentPage:"Somente a página atual",spreadsheet:"Planilha",cube:"Cubo",sendByEmail:"Enviar por email"},message:{emailSuccess:"E-mail enviado com sucesso",exportError:"Usuário sem permissão",exportPermission:"O usuário não possui permissão para exportar o arquivo."},title:{error:"Erro"},limitExceeded:{title:"Atenção",description:"Apenas os {{limit}} primeiros registros serão exportados. Deseja continuar?",subdescription:"Caso seja necessária uma quantidade maior de registros exportados, utilize o Extrator de Dados através de um Relatório Personalizado.",cancel:"Cancelar",continue:"Continuar"}},b={modalTitle:"Configuração de valor variável",labelSystemConfig:"Usar definições do sistema",labelUserConfig:"Usar definições personalizadas",labelInstance:"Categoria",labelField:"Campo",labelDescription:"Descrição (obrigatório) *",labelType:"Tipo (obrigatório) *",labelTypeValues:{date:"Data",text:"Texto",integer:"Número Inteiro",decimal:"Número com Decimal"},labelExpression:"Expressão",labelCancel:"Cancelar",labelSave:"Salvar"},g={searchLabel:"Buscar campo",fieldLabel:"Campos de {{link}}",linkLabel:"Categorias de {{link}}"},v={backTitle:"Voltar"},C={title:"Anexar arquivos",description:"Faça o upload dos arquivos ou informe links que deseja anexar ao título",attachHint:"Fazer download do arquivo",breadcrumbTitle:"Anexar",finishedMessage:"O anexo foi finalizado com sucesso",finish:"Finalizar",cancelConfirmation:{title:"Atenção",message:"As alterações realizadas não serão aplicadas.<br/><br/><b>Deseja mesmo continuar?</b>"},alertValidation:{fileAndLinkAtTheSameTime:{title:"Atenção",message:"Não é permitido inserir o arquivo e o link ao mesmo tempo."},anyLinkOrFileFilled:{title:"Atenção",message:'É necessário preencher o campo "Link" ou anexar um arquivo.'}},taskbar:{titleDownload:"Fazer download",titleLink:"Abrir link"}},F={info:{labelSearchField:"Buscar campo",labelOperator:"Operador",labelValueVarible:"Valor variável",titleTooltip:"Ao ativar um valor variável, é possível inserir um valor diferente sempre que o filtro for aplicado"},confirm:{title:"Aviso",description:"As informações da condição serão descartadas.</br></br><b>Gostaria de continuar?</b>"}};class S{constructor(S){this._defaults={snkDataUnit:e,snkFormConfig:n,snkConfigOptions:t,snkTaskbar:o,snkFieldConfig:d,snkFilterBar:a,snkConfigurator:u,snkTabConfig:c,crudUtils:i,snkGrid:m,snkGridConfig:p,snkExporter:r,snkDataExporter:f,snkCrud:l,fileViewer:s,snkFilterParamConfig:b,snkFilterFieldSearch:g,snkSimpleBar:v,snkAttach:C,snkPersonalizedFilter:F},this._currentOperation=A.CLEAN,this._domainName=S,this.loadAppMessages().then((e=>{this._appMessages=e}),(e=>{console.info("O arquivo de mensagens personalizadas não foi encontrado no caminho /messages/appmessages.js",e)}))}set currentOperation(e){this._currentOperation=e}getMessage(e,a){if(null==e)return;var o=e.split(".");let i=this.resolveMessage(o,this.getDomainMessages());if(null==i&&(i=this.resolveMessage(o,this._defaults)),this.customMessageBuilder){const o=this.customMessageBuilder(e,i,a);i=o.message,a=o.params}return this.postProcess(i,a)}getDomainMessages(){return null==this._domainName?this._appMessages.Global||this._appMessages:null==this._appMessages?void 0:this._appMessages[this._domainName]}resolveMessage(e,a){if(null==a)return;const o=a[e[0]];return o?this.isOperationSensitive(o)?o[this._currentOperation]:1===e.length||null==o||"string"==typeof o?o:this.resolveMessage(e.slice(1),o):void 0}isOperationSensitive(e){return null!=e[A.CLONE]||null!=e[A.INSERT]||null!=e[A.UPDATE]||null!=e[A.CLEAN]}postProcess(e,a){if(e){const o=/(.*?)\{\{(.+?)\}\}/g;let i,r="",l=e;for(;null!==(i=o.exec(e));){const[o,s,t]=i,n=i.index+o.length;l=n<e.length?e.substring(n):"";let d=a?a[t]:void 0;null==d&&(d=""),r+=s+d}return r+l}return e}loadAppMessages(){return new Promise(((e,a)=>{const o="dev"!==window.applicationenv?`/${window.MGE_MODULE_NAME}/labsApps/${window.APPLICATION_NAME}/build/messages/appmessages.js`:"/messages/appmessages.js";import(o).then((a=>{e(a.default)})).catch((e=>{a(e)}))}))}}var A;!function(e){e.CLONE="clone",e.INSERT="insert",e.UPDATE="update",e.CLEAN="clean"}(A||(A={}));export{A as O,S}
@@ -0,0 +1 @@
1
+ import{r as t,c as e,h as i,F as s,H as l,g as r}from"./p-b9667fbe.js";import{ApplicationUtils as n}from"@sankhyalabs/ezui/dist/collection/utils";import{F as a}from"./p-584d7212.js";import{ElementIDUtils as o,DataType as h}from"@sankhyalabs/core";const c=class{constructor(i){t(this,i),this.filterChange=e(this,"filterChange",7),this.config=void 0,this.getMessage=void 0}async show(){var t,e;null===(e=(t=this._editor).show)||void 0===e||e.call(t)}componentDidLoad(){if(this._element){o.addIDInfo(this._element);const t=this._element.getAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME);this._idContentEditor=`${t}_${this.config.id}`}}changeConfig(t){this.filterChange.emit(t)}getContentEditor(){switch(this.config.type){case a.BINARY_SELECT:return"snk-filter-binary-select";case a.MULTI_SELECT:return"snk-filter-multi-select";case a.PERIOD:return"snk-filter-period";case a.SEARCH:return"snk-filter-search";case a.NUMBER:return"snk-filter-number";case a.PERSONALIZED:return"snk-filter-personalized"}return"snk-filter-text"}removeItem(){this.changeConfig(Object.assign(Object.assign({},this.config),{visible:!1,fixed:!1,value:void 0}))}getPopUpHeaderButtons(){return i(s,null,!this.config.removalBlocked&&this.buildIcon(this.getMessage("snkFilterBar.removeFilter"),"delete",(()=>this.removeItem())),!this.config.hardFixed&&this.buildIcon(this.getMessage(this.config.fixed?"snkFilterBar.unpinFilter":"snkFilterBar.pinFilter"),this.config.fixed?"un-pin":"push-pin",(()=>this.changeConfig(Object.assign(Object.assign({},this.config),{fixed:!this.config.fixed})))))}buildIcon(t,e,s){return i("button",{onClick:()=>s(),class:"sc-snk-filter-bar snk-filter-item__editor-header-button",ref:e=>e&&this.buildIdButton(e,t)},i("ez-icon",Object.assign({title:t,iconName:e},{[o.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:`${o.getInternalIDInfo(`_${t}`)}`})))}buildIdButton(t,e){if(!t)return;const i={id:e};t.removeAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME),o.addIDInfoIfNotExists(t,"button",i)}getNormalizedValue(t,e){return t.reduce(((t,e,i)=>(e.dataType!==h.BOOLEAN||null!=t&&null!=t[i]||((t=t||[])[i]=!1),t)),e)}apply(){var t;let e=this._editor.value,i=!0;if(this.config.type===a.PERSONALIZED){const s=(null===(t=this.config.props.personalizedFilter)||void 0===t?void 0:t.parameters)||[];e=this.getNormalizedValue(s,e);const l=s.length;0===l?e=[]:i=this.validateAllFilled(l,e)}i&&this.changeConfig(Object.assign(Object.assign({},this.config),{value:e}))}validateAllFilled(t,e){let i=!0;return null!=e&&t>1&&(t>e.length?i=!1:e.forEach((t=>{null==t&&(i=!1)}))),i||n.alert("Filtro parcialmente preenchido","Favor completar todas as informações do filtro."),i}clear(){this.changeConfig(Object.assign(Object.assign({},this.config),{value:void 0}))}onKeyDonwListener(t){"Enter"===t.key&&this._applyButton.setFocus().then((()=>this.apply()))}render(){const t=this.getContentEditor();return i(l,null,i("div",{class:"col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center"},i("div",{class:"ez-text ez-title ez-title--small ez-padding--small sc-snk-filter-bar snk-filter-item__editor-header"},this.config.detailTitle),this.getPopUpHeaderButtons()),i(t,{ref:t=>this._editor=t,value:this.config.value,config:this.config,onKeyDown:t=>this.onKeyDonwListener(t),"data-element-id":this._idContentEditor,getMessage:this.getMessage}),i("hr",{class:"sc-snk-filter-bar snk-filter__popover-rule"}),i("div",{class:"ez-col ez-col--sd-12 ez-align--right"},i("ez-button",{label:this.getMessage("snkFilterBar.cleanFilter"),onClick:()=>this.clear(),size:"small"}),i("ez-button",{ref:t=>this._applyButton=t,label:this.getMessage("snkFilterBar.applyFilter"),onClick:()=>this.apply(),size:"small",class:"ez-button--primary ez-padding-left--medium"})))}get _element(){return r(this)}};export{c as snk_filter_detail}
@@ -0,0 +1 @@
1
+ import{r as t,h as e}from"./p-b9667fbe.js";import{ModalAction as i}from"@sankhyalabs/ezui/dist/collection/components/ez-modal-container";import{F as s}from"./p-d9804798.js";import{F as l}from"./p-584d7212.js";const o=class{constructor(e){t(this,e),this.getMessage=void 0,this.filters=void 0,this.applyFilters=void 0,this.clearAll=void 0,this.closeModal=void 0}getCustomMessage(t,e){var i;return null===(i=this.getMessage)||void 0===i?void 0:i.call(this,`snkFilterBar.filterModal.${t}`,e)}handleClearAll(){const t=this.clearAll(this.filters);this.filters=t}modalActionListener(t){switch(t.detail){case i.CANCEL:this.handleClearAll();break;case i.OK:this.applyFilters(this.filters);case i.CLOSE:this.closeModal()}}handleFilterChange(t){this.filters=this.filters.map((e=>e.id===t.id?t:e))}handleClearFilters(t){this.filters=this.filters.map((e=>t.includes(e)?Object.assign(Object.assign({},e),{value:void 0}):e))}renderFilterItem(t,i){return e("snk-filter-modal-item",{class:i?"ez-col ez-col--sd-12":"ez-col ez-col--sd-6 ez-padding--small",filterItem:t,onFilterChange:t=>this.handleFilterChange(t.detail)})}mountFiltersLines(t){let e=0,i=!1;const s={};for(let o=0;o<t.length;o++){s[e]=s[e]||[];const a=t[o],r=o===t.length-1,n=[l.TEXT,l.NUMBER].includes(a.type),d=!r&&[l.TEXT,l.NUMBER].includes(t[o+1].type);n&&d||i?(s[e].push(a),i=s[e].length<2,2===s[e].length&&++e):(s[e]=s[e]||[],s[e].push(a),++e)}return Object.values(s)}renderFilterLine(t){const i=1===t.length;return e("div",{class:"ez-row"},t.map((t=>this.renderFilterItem(t,i))))}renderCollapsibleFilterBox(t,i){if(!i.length)return null;const s=i.filter((t=>!!t.value)).length,l=this.mountFiltersLines(i);return e("ez-collapsible-box",{className:"snk-filter__modal-collapsible-box",headerSize:"medium",value:!0,label:t},!!s&&e("ez-badge",{className:"ez-badge--primary-subtle",slot:"rightSlot",label:s}),l.map(this.renderFilterLine.bind(this)),e("div",{class:"ez-flex ez-flex--justify-end grow"},e("ez-button",{className:"ez-button--tertiary",size:"medium",label:"Limpar",onClick:()=>this.handleClearFilters(i)})))}componentWillRender(){this._modalTitle=this.getCustomMessage("title"),this._okButtonLabel=this.getCustomMessage("okButtonLabel"),this._cancelButtonLabel=this.getCustomMessage("cancelButtonLabel")}render(){const t=this.filters.filter((t=>t.filterType===s.CUSTOM_FILTER)),i=this.filters.filter((t=>t.filterType===s.QUICK_FILTER)),l=this.filters.filter((t=>t.filterType===s.OTHER_FILTERS));return e("ez-modal-container",{class:"snk-filter__modal-container",modalTitle:this._modalTitle,cancelButtonLabel:this._cancelButtonLabel,okButtonLabel:this._okButtonLabel,onEzModalAction:this.modalActionListener.bind(this)},e("div",{class:"snk-filter__modal-content"},this.renderCollapsibleFilterBox(this.getCustomMessage("customFilters"),t),this.renderCollapsibleFilterBox(this.getCustomMessage("quickFilters"),i),l.map((t=>this.renderCollapsibleFilterBox(t.label,[t])))))}};o.style="ez-modal{--ez-modal-content-padding:24px 12px}.snk-filter__modal-container{width:344px;max-width:344px;overflow:hidden}.snk-filter__modal-content{display:flex;flex-direction:column;gap:12px;max-height:760px;overflow-x:clip;overflow-y:auto;padding-right:4px}.snk-filter__modal-content::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}.snk-filter__modal-collapsible-box{border:1px solid #DCE0E8;border-radius:var(--border--radius-medium);padding:12px 6px}";export{o as snk_filter_modal}
@@ -1 +1 @@
1
- import{r as t,h as e,H as i,g as s}from"./p-b9667fbe.js";import{ObjectUtils as o,ApplicationContext as r,ElementIDUtils as n}from"@sankhyalabs/core";import{ApplicationUtils as l,DialogType as a}from"@sankhyalabs/ezui/dist/collection/utils";import{D as d,a as h,b as c}from"./p-4c2015a9.js";import{d as p,W as u,R as m}from"./p-17375123.js";import{D as v}from"./p-41d92871.js";import{S as x}from"./p-3db1d3de.js";import"./p-112455b1.js";import"./p-f5f36fbb.js";class f{constructor(t,e){this._selectedNumber=0,this._getMessage=t,this._selectedNumber=e}setExportOption(t,e){const i=this.getExportGroupName();t===d.EXPORT_TO_PDF&&e.push(this.getExportToPDF(i)),t===d.EXPORT_TO_XLS&&e.push(this.getExportToXLS(i)),this.setExportCurrentPage(t,e),this.setExportByEmail(t,e)}setExportCurrentPage(t,e){var i;const s=[d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS];if(t===d.EXPORT_CURRENT_PAGE&&e.push(this.getCurrentPage()),s.includes(t)){let s=e.find((t=>t.id===d.EXPORT_CURRENT_PAGE));null==s&&(e.push(this.getCurrentPage()),s=e.find((t=>t.id===d.EXPORT_CURRENT_PAGE))),(null===(i=null==s?void 0:s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===d.EXPORT_PAGE_TO_PDF&&s.children.push(this.getExportPageToPDF()),t===d.EXPORT_PAGE_TO_XLS&&s.children.push(this.getExportPageToXLS())}}setExportByEmail(t,e){t===d.EXPORT_BY_EMAIL&&e.push(this.getExportByEmail())}getExportToPDF(t){return{id:d.EXPORT_TO_PDF,label:"PDF (.pdf)",group:t}}getExportToXLS(t){return{id:d.EXPORT_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`,group:t}}getCurrentPage(){return{id:d.EXPORT_CURRENT_PAGE,label:this._getMessage("snkDataExporter.label.currentPage"),group:this._getMessage("snkDataExporter.group.custom")}}getExportPageToPDF(){return{id:d.EXPORT_PAGE_TO_PDF,label:"PDF (.pdf)"}}getExportPageToXLS(){return{id:d.EXPORT_PAGE_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportByEmail(){return{id:d.EXPORT_BY_EMAIL,label:`${this._getMessage("snkDataExporter.label.sendByEmail")}...`}}getExportGroupName(){return 1===this._selectedNumber?this._getMessage("snkDataExporter.group.export.selectedLine"):this._selectedNumber>1?this._getMessage("snkDataExporter.group.export.multiSelected").replace("{0}",this._selectedNumber.toString()):this._getMessage("snkDataExporter.group.export.default")}}function b(t){var{methodName:e}=t,i=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(s=Object.getOwnPropertySymbols(t);o<s.length;o++)e.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(i[s[o]]=t[s[o]])}return i}(t,["methodName"]);const s=`mgefin-bff@DataExporterSPBean.${e}`,r={serviceName:s,requestBody:i};return new Promise(((t,e)=>{v.get().callServiceBroker(s,o.objectToString(r)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return o.stringToObject(i)}(e)))).catch((t=>e(t)))}))}const E=5e3,k=class{constructor(e){t(this,e),this._selectedNumber=0,this._customPrefix="$custom$",this._items=[],this._showDropdown=!1,this._releasedToExport=[d.EXPORT_TO_PDF,d.EXPORT_TO_XLS,d.EXPORT_BY_EMAIL,d.EXPORT_PDF_TO_EMAIL,d.EXPORT_XLS_TO_EMAIL,d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS],this.provider=null,this.messagesBuilder=void 0}async exportByEmail(){const t=this._selectedNumber;this._snkEmailSender.open({type:t>0?"selection":"all",selectedRows:t,email:{attachments:[{name:this._appLabel}]},resolver:({type:t,format:e,email:{to:i,subject:s,message:o}})=>{var r;const n=null!==(r=h[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:h.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,titleGrid:this._appLabel},(()=>{this._snkEmailSender.close(),l.info(this.getMessage("snkDataExporter.message.emailSuccess"),{iconName:"check"})}))}})}getMessage(t,e){if(null==this.messagesBuilder){const t=x.getNearestInstance(this._element);t&&(this.messagesBuilder=t.messagesBuilder)}return this.messagesBuilder.getMessage(t,e)}positionDropdown(){var t;const e=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();null!=e&&null!=this._dropdownParent&&(this._dropdownParent.style.top=e.y+e.height+5+"px",this._dropdownParent.style.left=e.x+"px")}closeDropdown(t){const e=null==t?void 0:t.target;null!=e&&(e.closest(".snk-data-exporter")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}controlDropdown(){this._showDropdown=!this._showDropdown}resolveExporter(t,e){if(null==this.provider||null==t||null==e)return;const i=this.provider.getFilters(),s=this.provider.getColumnsMetadata(),o=this.provider.getOrders(),r=this.provider.getResourceURI(),n=this.provider.getSelectedIDs(),a=t.exportOption,h=[d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS];delete t.exportOption;let c=Object.assign({filters:i,columns:s,sort:o,resourceURI:r,selectedIDs:n.slice(0,E)},t);if(h.includes(a)||"page"==t.type){const t=this.provider.getOffset(),e=this.provider.getLimit();c=Object.assign(Object.assign({},c),{offset:t,limit:e,selectedIDs:[]})}else"all"==t.type&&(c=Object.assign(Object.assign({},c),{offset:0,limit:E,selectedIDs:[]}));b(c).then((t=>e(t))).catch((t=>l.error(this.getMessage("snkDataExporter.message.exportError"),t?t.statusMessage:this.getMessage("snkDataExporter.message.exportError"))))}getOptionKey(t){return Object.keys(d).find((e=>d[e]===t))}dispatchExporter(t){var e;const i=this.getOptionKey(t),s=null!==(e=c[i])&&void 0!==e?e:c.EXPORT_TO_PDF,o=c[i]===c.EXPORT_TO_XLS;this.resolveExporter({methodName:d[`EXPORT_TO_${s}`],fileName:this._appLabel,titleGrid:this._appLabel,exportOption:t,limit:E},(t=>{!function({fileSessionKey:t,canPrint:e,canExport:i,useAppPrint:s,isDownload:o}){const n=r.getContextValue("__SNK__APPLICATION__");if(s&&!o)return function(t,e,i,s){null==s||s.webConnection(p,u.methods.PDF_VIEWER,{chaveArquivo:t,permiteImprimir:e?"S":"N",permiteExportar:i?"S":"N",contentType:"S"})}(t,e,i,n);window.open(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/mge/visualizadorArquivos.mge?chaveArquivo=${t}${o?"&download=S":""}`),l.info(function(t){var e;return null===(e=null==t?void 0:t.messagesBuilder)||void 0===e?void 0:e.getMessage("fileViewer.message.exportSuccess",void 0)}(n),{iconName:"check"})}(Object.assign(Object.assign({},t),{fileType:s,isDownload:o}))}))}async processExporter(t){var e,i,s,o;const r=null==t?void 0:t.detail,n=[d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS],h=null===(e=null==r?void 0:r.id)||void 0===e?void 0:e.includes(this._customPrefix);if((null==r?void 0:r.id)===d.EXPORT_CURRENT_PAGE)return;const c=null===(i=this.provider)||void 0===i?void 0:i.getSelectedIDs(),p=null===(s=this.provider)||void 0===s?void 0:s.getTotalRecords(),u=null===(o=this.provider)||void 0===o?void 0:o.getLimit();let m=!1;if(n.includes(null==r?void 0:r.id)&&u<=E||h?m=!1:(null==c?void 0:c.length)?m=c.length>E:p>E&&(m=!0),m){const t=E.toLocaleString("pt-BR",{minimumFractionDigits:0}),e={title:this.getMessage("snkDataExporter.limitExceeded.title"),description:`\n ${this.getMessage("snkDataExporter.limitExceeded.description",{limit:t})}\n <br/><br/>\n <b>\n ${this.getMessage("snkDataExporter.limitExceeded.subdescription")}\n </b>\n `,cancel:this.getMessage("snkDataExporter.limitExceeded.cancel"),confirm:this.getMessage("snkDataExporter.limitExceeded.continue")};if(!await l.confirm(e.title,e.description,null,a.WARN,{labelCancel:e.cancel,labelConfirm:e.confirm}))return}if(h)return this.openPersonalizedReports(r.id),void(this._showDropdown=!1);this._releasedToExport.includes(null==r?void 0:r.id)&&(r.id===d.EXPORT_BY_EMAIL?this.exportByEmail():this.dispatchExporter(r.id),this._showDropdown=!1)}loadItems(){const t=[];this._releasedToExport.forEach((e=>{var i;null===(i=this._itemBuilder)||void 0===i||i.setExportOption(e,t)})),this.loadPersonalizedItems(t)}async loadPersonalizedItems(t){var e;const i=null===(e=this.provider)||void 0===e?void 0:e.getRecordID();if(null==i)return void(this._items=t);const s=await function(t){const e="mgefin-bff@DataExporterSPBean.getPersonalizedReports",i={serviceName:e,requestBody:t};return new Promise(((t,s)=>v.get().callServiceBroker(e,o.objectToString(i)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return o.stringToObject(i)}(e)))).catch((t=>s(t)))))}({recordID:i});null==s||s.forEach((e=>{t.push({id:`${this._customPrefix}_${e.ID}`,label:e.label,group:this.getMessage("snkDataExporter.group.custom")})})),this._items=t}openPersonalizedReports(t){var e;const i=[],s=(null==t?void 0:t.replace(this._customPrefix,""))||"";null===(e=this.provider)||void 0===e||e.getSelectedIDs().forEach((({name:t,type:e,value:s},o)=>{const r=[];r.fields=[],0===o&&(i[`PK_${t}`]={type:e,value:s},i.pks=[]),r.fields.push({nome:t,tipo:e,valor:s}),i.pks.push(r)})),this._application.openApp(`${m}${s}`,i)}loadDropdown(){var t,e;this._selectedNumber=(null===(e=null===(t=this.provider)||void 0===t?void 0:t.getSelectedIDs())||void 0===e?void 0:e.length)||0,this._itemBuilder=new f(this.getMessage.bind(this),this._selectedNumber),this.loadItems()}getElementID(t){return{[n.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:n.getInternalIDInfo(t)}}canShowDropdown(){var t;return this._showDropdown&&(null===(t=this._items)||void 0===t?void 0:t.length)>0}componentWillLoad(){var t;this._application=r.getContextValue("__SNK__APPLICATION__"),null===(t=this._application)||void 0===t||t.getAppLabel().then((t=>this._appLabel=t)),this.setEvents()}componentDidLoad(){null!=this._element&&(n.addIDInfo(this._element),this.positionDropdown())}componentWillUpdate(){var t;this._showDropdown&&!(null===(t=this._items)||void 0===t?void 0:t.length)&&this.loadDropdown()}componentDidUpdate(){var t;this._showDropdown?this.positionDropdown():(null===(t=this._items)||void 0===t?void 0:t.length)>0&&(this._items=[])}render(){return e(i,null,e("div",{class:`snk-data-exporter\n ${this.canShowDropdown()?" snk-data-exporter--overlap":""}\n `},e("ez-button",Object.assign({ref:t=>this._ezButton=t,iconName:"file-download",size:"small",mode:"icon",title:this.getMessage("snkDataExporter.group.export.title"),onClick:()=>this.controlDropdown()},this.getElementID("button"))),e("div",Object.assign({ref:t=>this._dropdownParent=t,class:`snk-data-exporter__dropdown\n ${this.canShowDropdown()?"snk-data-exporter__dropdown--show":""}\n `},this.getElementID("dropdown")),this.canShowDropdown()&&e("ez-dropdown",Object.assign({items:this._items,onEzClick:t=>this.processExporter(t)},this.getElementID("dropdown"))))),this.canShowDropdown()&&e("div",Object.assign({class:"ez-scrim ez-scrim--light"},this.getElementID("ezScrim"))),e("snk-exporter-email-sender",Object.assign({ref:t=>this._snkEmailSender=t,getMessage:(t,e)=>this.getMessage(t,e)},this.getElementID("snkExporterEmailSender"))))}get _element(){return s(this)}};k.style=".sc-snk-data-exporter-h{--snk-data-exporter--z-index:var(--most-visible, 3);display:flex;width:fit-content;height:fit-content}.snk-data-exporter.sc-snk-data-exporter{display:flex;width:fit-content;height:fit-content}.snk-data-exporter--overlap.sc-snk-data-exporter{z-index:var(--snk-data-exporter--z-index)}.snk-data-exporter__dropdown.sc-snk-data-exporter{display:none}.snk-data-exporter__dropdown--show.sc-snk-data-exporter{display:flex;flex-direction:column;position:fixed}.snk-data-exporter__dropdown.sc-snk-data-exporter>ez-dropdown.sc-snk-data-exporter{position:relative}";export{k as snk_data_exporter}
1
+ import{r as t,h as e,H as i,g as s}from"./p-b9667fbe.js";import{ObjectUtils as o,ApplicationContext as r,ElementIDUtils as n}from"@sankhyalabs/core";import{ApplicationUtils as l,DialogType as a}from"@sankhyalabs/ezui/dist/collection/utils";import{D as d,a as h,b as c}from"./p-4c2015a9.js";import{d as p,W as u,R as m}from"./p-17375123.js";import{D as v}from"./p-41d92871.js";import{S as x}from"./p-6981c03e.js";import"./p-112455b1.js";import"./p-29c1889f.js";class f{constructor(t,e){this._selectedNumber=0,this._getMessage=t,this._selectedNumber=e}setExportOption(t,e){const i=this.getExportGroupName();t===d.EXPORT_TO_PDF&&e.push(this.getExportToPDF(i)),t===d.EXPORT_TO_XLS&&e.push(this.getExportToXLS(i)),this.setExportCurrentPage(t,e),this.setExportByEmail(t,e)}setExportCurrentPage(t,e){var i;const s=[d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS];if(t===d.EXPORT_CURRENT_PAGE&&e.push(this.getCurrentPage()),s.includes(t)){let s=e.find((t=>t.id===d.EXPORT_CURRENT_PAGE));null==s&&(e.push(this.getCurrentPage()),s=e.find((t=>t.id===d.EXPORT_CURRENT_PAGE))),(null===(i=null==s?void 0:s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===d.EXPORT_PAGE_TO_PDF&&s.children.push(this.getExportPageToPDF()),t===d.EXPORT_PAGE_TO_XLS&&s.children.push(this.getExportPageToXLS())}}setExportByEmail(t,e){t===d.EXPORT_BY_EMAIL&&e.push(this.getExportByEmail())}getExportToPDF(t){return{id:d.EXPORT_TO_PDF,label:"PDF (.pdf)",group:t}}getExportToXLS(t){return{id:d.EXPORT_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`,group:t}}getCurrentPage(){return{id:d.EXPORT_CURRENT_PAGE,label:this._getMessage("snkDataExporter.label.currentPage"),group:this._getMessage("snkDataExporter.group.custom")}}getExportPageToPDF(){return{id:d.EXPORT_PAGE_TO_PDF,label:"PDF (.pdf)"}}getExportPageToXLS(){return{id:d.EXPORT_PAGE_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportByEmail(){return{id:d.EXPORT_BY_EMAIL,label:`${this._getMessage("snkDataExporter.label.sendByEmail")}...`}}getExportGroupName(){return 1===this._selectedNumber?this._getMessage("snkDataExporter.group.export.selectedLine"):this._selectedNumber>1?this._getMessage("snkDataExporter.group.export.multiSelected").replace("{0}",this._selectedNumber.toString()):this._getMessage("snkDataExporter.group.export.default")}}function E(t){var{methodName:e}=t,i=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(s=Object.getOwnPropertySymbols(t);o<s.length;o++)e.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(i[s[o]]=t[s[o]])}return i}(t,["methodName"]);const s=`mgefin-bff@DataExporterSPBean.${e}`,r={serviceName:s,requestBody:i};return new Promise(((t,e)=>{v.get().callServiceBroker(s,o.objectToString(r)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return o.stringToObject(i)}(e)))).catch((t=>e(t)))}))}const b=5e3,k=class{constructor(e){t(this,e),this._selectedNumber=0,this._customPrefix="$custom$",this._items=[],this._showDropdown=!1,this._releasedToExport=[d.EXPORT_TO_PDF,d.EXPORT_TO_XLS,d.EXPORT_BY_EMAIL,d.EXPORT_PDF_TO_EMAIL,d.EXPORT_XLS_TO_EMAIL,d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS],this.provider=null,this.messagesBuilder=void 0}async exportByEmail(){const t=this._selectedNumber;this._snkEmailSender.open({type:t>0?"selection":"all",selectedRows:t,email:{attachments:[{name:this._appLabel}]},resolver:({type:t,format:e,email:{to:i,subject:s,message:o}})=>{var r;const n=null!==(r=h[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:h.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,titleGrid:this._appLabel},(()=>{this._snkEmailSender.close(),l.info(this.getMessage("snkDataExporter.message.emailSuccess"),{iconName:"check"})}))}})}getMessage(t,e){if(null==this.messagesBuilder){const t=x.getNearestInstance(this._element);t&&(this.messagesBuilder=t.messagesBuilder)}return this.messagesBuilder.getMessage(t,e)}positionDropdown(){var t;const e=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();null!=e&&null!=this._dropdownParent&&(this._dropdownParent.style.top=e.y+e.height+5+"px",this._dropdownParent.style.left=e.x+"px")}closeDropdown(t){const e=null==t?void 0:t.target;null!=e&&(e.closest(".snk-data-exporter")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}controlDropdown(){this._showDropdown=!this._showDropdown}resolveExporter(t,e){if(null==this.provider||null==t||null==e)return;const i=this.provider.getFilters(),s=this.provider.getColumnsMetadata(),o=this.provider.getOrders(),r=this.provider.getResourceURI(),n=this.provider.getSelectedIDs(),a=t.exportOption,h=[d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS];delete t.exportOption;let c=Object.assign({filters:i,columns:s,sort:o,resourceURI:r,selectedIDs:n.slice(0,b)},t);if(h.includes(a)||"page"==t.type){const t=this.provider.getOffset(),e=this.provider.getLimit();c=Object.assign(Object.assign({},c),{offset:t,limit:e,selectedIDs:[]})}else"all"==t.type&&(c=Object.assign(Object.assign({},c),{offset:0,limit:b,selectedIDs:[]}));E(c).then((t=>e(t))).catch((t=>l.error(this.getMessage("snkDataExporter.message.exportError"),t?t.statusMessage:this.getMessage("snkDataExporter.message.exportError"))))}getOptionKey(t){return Object.keys(d).find((e=>d[e]===t))}dispatchExporter(t){var e;const i=this.getOptionKey(t),s=null!==(e=c[i])&&void 0!==e?e:c.EXPORT_TO_PDF,o=c[i]===c.EXPORT_TO_XLS;this.resolveExporter({methodName:d[`EXPORT_TO_${s}`],fileName:this._appLabel,titleGrid:this._appLabel,exportOption:t,limit:b},(t=>{!function({fileSessionKey:t,canPrint:e,canExport:i,useAppPrint:s,isDownload:o}){const n=r.getContextValue("__SNK__APPLICATION__");if(s&&!o)return function(t,e,i,s){null==s||s.webConnection(p,u.methods.PDF_VIEWER,{chaveArquivo:t,permiteImprimir:e?"S":"N",permiteExportar:i?"S":"N",contentType:"S"})}(t,e,i,n);window.open(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/mge/visualizadorArquivos.mge?chaveArquivo=${t}${o?"&download=S":""}`),l.info(function(t){var e;return null===(e=null==t?void 0:t.messagesBuilder)||void 0===e?void 0:e.getMessage("fileViewer.message.exportSuccess",void 0)}(n),{iconName:"check"})}(Object.assign(Object.assign({},t),{fileType:s,isDownload:o}))}))}async processExporter(t){var e,i,s,o;const r=null==t?void 0:t.detail,n=[d.EXPORT_PAGE_TO_PDF,d.EXPORT_PAGE_TO_XLS],h=null===(e=null==r?void 0:r.id)||void 0===e?void 0:e.includes(this._customPrefix);if((null==r?void 0:r.id)===d.EXPORT_CURRENT_PAGE)return;const c=null===(i=this.provider)||void 0===i?void 0:i.getSelectedIDs(),p=null===(s=this.provider)||void 0===s?void 0:s.getTotalRecords(),u=null===(o=this.provider)||void 0===o?void 0:o.getLimit();let m=!1;if(n.includes(null==r?void 0:r.id)&&u<=b||h?m=!1:(null==c?void 0:c.length)?m=c.length>b:p>b&&(m=!0),m){const t=b.toLocaleString("pt-BR",{minimumFractionDigits:0}),e={title:this.getMessage("snkDataExporter.limitExceeded.title"),description:`\n ${this.getMessage("snkDataExporter.limitExceeded.description",{limit:t})}\n <br/><br/>\n <b>\n ${this.getMessage("snkDataExporter.limitExceeded.subdescription")}\n </b>\n `,cancel:this.getMessage("snkDataExporter.limitExceeded.cancel"),confirm:this.getMessage("snkDataExporter.limitExceeded.continue")};if(!await l.confirm(e.title,e.description,null,a.WARN,{labelCancel:e.cancel,labelConfirm:e.confirm}))return}if(h)return this.openPersonalizedReports(r.id),void(this._showDropdown=!1);this._releasedToExport.includes(null==r?void 0:r.id)&&(r.id===d.EXPORT_BY_EMAIL?this.exportByEmail():this.dispatchExporter(r.id),this._showDropdown=!1)}loadItems(){const t=[];this._releasedToExport.forEach((e=>{var i;null===(i=this._itemBuilder)||void 0===i||i.setExportOption(e,t)})),this.loadPersonalizedItems(t)}async loadPersonalizedItems(t){var e;const i=null===(e=this.provider)||void 0===e?void 0:e.getRecordID();if(null==i)return void(this._items=t);const s=await function(t){const e="mgefin-bff@DataExporterSPBean.getPersonalizedReports",i={serviceName:e,requestBody:t};return new Promise(((t,s)=>v.get().callServiceBroker(e,o.objectToString(i)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return o.stringToObject(i)}(e)))).catch((t=>s(t)))))}({recordID:i});null==s||s.forEach((e=>{t.push({id:`${this._customPrefix}_${e.ID}`,label:e.label,group:this.getMessage("snkDataExporter.group.custom")})})),this._items=t}openPersonalizedReports(t){var e;const i=[],s=(null==t?void 0:t.replace(this._customPrefix,""))||"";null===(e=this.provider)||void 0===e||e.getSelectedIDs().forEach((({name:t,type:e,value:s},o)=>{const r=[];r.fields=[],0===o&&(i[`PK_${t}`]={type:e,value:s},i.pks=[]),r.fields.push({nome:t,tipo:e,valor:s}),i.pks.push(r)})),this._application.openApp(`${m}${s}`,i)}loadDropdown(){var t,e;this._selectedNumber=(null===(e=null===(t=this.provider)||void 0===t?void 0:t.getSelectedIDs())||void 0===e?void 0:e.length)||0,this._itemBuilder=new f(this.getMessage.bind(this),this._selectedNumber),this.loadItems()}getElementID(t){return{[n.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:n.getInternalIDInfo(t)}}canShowDropdown(){var t;return this._showDropdown&&(null===(t=this._items)||void 0===t?void 0:t.length)>0}componentWillLoad(){var t;this._application=r.getContextValue("__SNK__APPLICATION__"),null===(t=this._application)||void 0===t||t.getAppLabel().then((t=>this._appLabel=t)),this.setEvents()}componentDidLoad(){null!=this._element&&(n.addIDInfo(this._element),this.positionDropdown())}componentWillUpdate(){var t;this._showDropdown&&!(null===(t=this._items)||void 0===t?void 0:t.length)&&this.loadDropdown()}componentDidUpdate(){var t;this._showDropdown?this.positionDropdown():(null===(t=this._items)||void 0===t?void 0:t.length)>0&&(this._items=[])}render(){return e(i,null,e("div",{class:`snk-data-exporter\n ${this.canShowDropdown()?" snk-data-exporter--overlap":""}\n `},e("ez-button",Object.assign({ref:t=>this._ezButton=t,iconName:"file-download",size:"small",mode:"icon",title:this.getMessage("snkDataExporter.group.export.title"),onClick:()=>this.controlDropdown()},this.getElementID("button"))),e("div",Object.assign({ref:t=>this._dropdownParent=t,class:`snk-data-exporter__dropdown\n ${this.canShowDropdown()?"snk-data-exporter__dropdown--show":""}\n `},this.getElementID("dropdown")),this.canShowDropdown()&&e("ez-dropdown",Object.assign({items:this._items,onEzClick:t=>this.processExporter(t)},this.getElementID("dropdown"))))),this.canShowDropdown()&&e("div",Object.assign({class:"ez-scrim ez-scrim--light"},this.getElementID("ezScrim"))),e("snk-exporter-email-sender",Object.assign({ref:t=>this._snkEmailSender=t,getMessage:(t,e)=>this.getMessage(t,e)},this.getElementID("snkExporterEmailSender"))))}get _element(){return s(this)}};k.style=".sc-snk-data-exporter-h{--snk-data-exporter--z-index:var(--most-visible, 3);display:flex;width:fit-content;height:fit-content}.snk-data-exporter.sc-snk-data-exporter{display:flex;width:fit-content;height:fit-content}.snk-data-exporter--overlap.sc-snk-data-exporter{z-index:var(--snk-data-exporter--z-index)}.snk-data-exporter__dropdown.sc-snk-data-exporter{display:none}.snk-data-exporter__dropdown--show.sc-snk-data-exporter{display:flex;flex-direction:column;position:fixed}.snk-data-exporter__dropdown.sc-snk-data-exporter>ez-dropdown.sc-snk-data-exporter{position:relative}";export{k as snk_data_exporter}
@@ -1,4 +1,4 @@
1
- import{r as t,c as s,h as e,g as n}from"./p-b9667fbe.js";import{WaitingChangeException as i,WarningException as r,ErrorException as a,ObjectUtils as o,DateUtils as c,StringUtils as h,DependencyType as u,ElementIDUtils as l,ApplicationContext as p,ErrorTracking as d,DataType as m}from"@sankhyalabs/core";import{d as f,D as w,U as y}from"./p-41d92871.js";import{ApplicationUtils as g}from"@sankhyalabs/ezui/dist/collection/utils";import{P as I}from"./p-11028eba.js";import{G as P,C as v}from"./p-52ed2a18.js";import{D as _}from"./p-f821768b.js";import{R as A}from"./p-0d81236c.js";import{S as E}from"./p-f5f36fbb.js";import"./p-112455b1.js";class C{constructor(t){this._app=t,window.addEventListener("error",(t=>this.errorHandler(t))),window.addEventListener("unhandledrejection",(t=>this.rejectionHandler(t)))}rejectionHandler(t){const s=t.reason;s instanceof i||(s?this.processException(s):this._app.isDebugMode().then((t=>{t&&this._app.error("Promise rejeitada","Erro interno: Uma promise foi rejeitada sem razão determinada.")})))}errorHandler(t){this.processException(t.error)}buildErrorCodeHTML(t){return'<br><a href="#" onclick="try{window.workspace.openHelp(\'_tbcode:'+t+"')} catch(e){alert('Não é possível abrir a ajuda fora do workspace Sankhya');}\">Código: "+t+"</a>"}processException(t){t.errorCode&&(t.message+=this.buildErrorCodeHTML(t.errorCode)),t instanceof i||t instanceof r?this._app.alert(t.title,t.message):t instanceof a?this._app.error(t.title,t.message):this._app.isDebugMode().then((s=>{if(s)if(t instanceof Error)this._app.error(t.name,t.message);else{const s=(null==t?void 0:t.title)||"Erro detectado",e="string"==typeof t?t:t.message||`Erro interno "${o.objectToString(t)}"`;this._app.error(s,e)}}))}}function S(){const t=["2909523kXwted","CompanyName=Sankhya Jiva Tecnologia e Inovao Ltda,LicensedApplication=Sankhya Gestao,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=2,LicensedProductionInstancesCount=0,AssetReference=AG-019460,ExpiryDate=9_November_2022_[v2]_MTY2Nzk1MjAwMDAwMA==10487151e296ee4360f80961ca960869","1131048CARoeW","502909mLEPmu","447255iQEXuN","428UHbJwW","270AFTxAV","194369jhGqTI","1540nWuTrj","2044062GicUQI","30CkXPWg"];return(S=function(){return t})()}const T=D;function D(t,s){const e=S();return(D=function(t){return e[t-=392]})(t,s)}!function(){const t=D,s=S();for(;;)try{if(951926==-parseInt(t(398))/1+-parseInt(t(393))/2+parseInt(t(395))/3+-parseInt(t(400))/4*(parseInt(t(392))/5)+-parseInt(t(401))/6*(-parseInt(t(402))/7)+parseInt(t(397))/8+-parseInt(t(399))/9*(-parseInt(t(394))/10))break;s.push(s.shift())}catch(t){s.push(s.shift())}}();const b=T(396);class N{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchTotals",f.gql`query($filters: [InputFilter!] $name: String!) {
1
+ import{r as t,c as s,h as e,g as n}from"./p-b9667fbe.js";import{WaitingChangeException as i,WarningException as r,ErrorException as a,ObjectUtils as o,DateUtils as c,StringUtils as h,DependencyType as u,ElementIDUtils as l,ApplicationContext as p,ErrorTracking as d,DataType as m}from"@sankhyalabs/core";import{d as f,D as w,U as y}from"./p-41d92871.js";import{ApplicationUtils as g}from"@sankhyalabs/ezui/dist/collection/utils";import{P as I}from"./p-11028eba.js";import{G as P,C as v}from"./p-52ed2a18.js";import{D as _}from"./p-f821768b.js";import{R as A}from"./p-0d81236c.js";import{S as E}from"./p-29c1889f.js";import"./p-112455b1.js";class C{constructor(t){this._app=t,window.addEventListener("error",(t=>this.errorHandler(t))),window.addEventListener("unhandledrejection",(t=>this.rejectionHandler(t)))}rejectionHandler(t){const s=t.reason;s instanceof i||(s?this.processException(s):this._app.isDebugMode().then((t=>{t&&this._app.error("Promise rejeitada","Erro interno: Uma promise foi rejeitada sem razão determinada.")})))}errorHandler(t){this.processException(t.error)}buildErrorCodeHTML(t){return'<br><a href="#" onclick="try{window.workspace.openHelp(\'_tbcode:'+t+"')} catch(e){alert('Não é possível abrir a ajuda fora do workspace Sankhya');}\">Código: "+t+"</a>"}processException(t){t.errorCode&&(t.message+=this.buildErrorCodeHTML(t.errorCode)),t instanceof i||t instanceof r?this._app.alert(t.title,t.message):t instanceof a?this._app.error(t.title,t.message):this._app.isDebugMode().then((s=>{if(s)if(t instanceof Error)this._app.error(t.name,t.message);else{const s=(null==t?void 0:t.title)||"Erro detectado",e="string"==typeof t?t:t.message||`Erro interno "${o.objectToString(t)}"`;this._app.error(s,e)}}))}}function S(){const t=["2909523kXwted","CompanyName=Sankhya Jiva Tecnologia e Inovao Ltda,LicensedApplication=Sankhya Gestao,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=2,LicensedProductionInstancesCount=0,AssetReference=AG-019460,ExpiryDate=9_November_2022_[v2]_MTY2Nzk1MjAwMDAwMA==10487151e296ee4360f80961ca960869","1131048CARoeW","502909mLEPmu","447255iQEXuN","428UHbJwW","270AFTxAV","194369jhGqTI","1540nWuTrj","2044062GicUQI","30CkXPWg"];return(S=function(){return t})()}const T=D;function D(t,s){const e=S();return(D=function(t){return e[t-=392]})(t,s)}!function(){const t=D,s=S();for(;;)try{if(951926==-parseInt(t(398))/1+-parseInt(t(393))/2+parseInt(t(395))/3+-parseInt(t(400))/4*(parseInt(t(392))/5)+-parseInt(t(401))/6*(-parseInt(t(402))/7)+parseInt(t(397))/8+-parseInt(t(399))/9*(-parseInt(t(394))/10))break;s.push(s.shift())}catch(t){s.push(s.shift())}}();const N=T(396);class b{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchTotals",f.gql`query($filters: [InputFilter!] $name: String!) {
2
2
  $queryAlias$: fetchTotals(name: $name, filters: $filters ){
3
3
  name
4
4
  value
@@ -8,4 +8,4 @@ import{r as t,c as s,h as e,g as n}from"./p-b9667fbe.js";import{WaitingChangeExc
8
8
  name
9
9
  resource
10
10
  }
11
- }`)}async getParam(t){const s=`param://application?params=${t}`;return w.get().callGraphQL({values:{name:s},query:this.templateByQuery.get("fetchParam")})}async asString(t){const s=await this.getParam(t);return this.getValue(s)}async asInteger(t){const s=await this.getParam(t);return parseInt(this.getValue(s))}async asFloat(t){const s=await this.getParam(t);return parseFloat(this.getValue(s))}async asBoolean(t){const s=await this.getParam(t);return"S"===this.getValue(s)}async asDate(t){const s=await this.getParam(t);return c.strToDate(this.getValue(s))}async getBatchParams(t){const s=await this.getParam(t.join(",")),e={};return s.forEach((t=>e[t.name]=t.resource)),e}getValue(t={}){if(Array.isArray(t)&&t.length>0&&(t=t[0]),h.isEmpty(t.resource))return"";try{const s=o.stringToObject(t.resource),[e]=Object.keys(s);return s[e]}catch(t){console.warn("Erro ao converter string JSON.")}}}const k=R;function R(t,s){const e=$();return(R=function(t){return e[t-=378]})(t,s)}function $(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return($=function(){return t})()}!function(){const t=R,s=$();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;s.push(s.shift())}catch(t){s.push(s.shift())}}();class F{[k(397)](t){const s=k;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new M("S"===t[s(402)]||!0===t[s(402)]);return Array[s(394)](t[s(391)])&&t[s(391)][s(385)]((t=>e.putAccess(t[s(382)],String(t.status)==s(398)))),e}}class M{constructor(t){const s=k;this.isSup=t,this[s(384)]={}}[k(378)](t,s){this[k(384)][t]=s}[k(393)](t){const s=k;if(this[s(402)])return!0;let e=!0;return this[s(384)][s(380)](t)&&(e=this.actions[t]),e}isUserSup(){return this.isSup}}class q extends A{getData(t){const s=`cfg://auth/${t}`;return new Promise(((t,e)=>{this.loadResource(s).then((s=>{let e=o.stringToObject(s);e&&"object"==typeof e&&t(e)})).catch((t=>{e(t)}))}))}}var x;!function(t){t.INSERT="I",t.UPDATE="A",t.REMOVE="E",t.SHOW="C",t.CONFIG="F",t.CONFIG_NUMBER="N",t.CLONE="D",t.CONFIG_GRID="G"}(x||(x={}));const z=class{constructor(e){t(this,e),this.applicationLoaded=s(this,"applicationLoaded",7),this.applicationLoading=s(this,"applicationLoading",7),this._authPromises=[],this._duCache=new Map,this._duPromises=new Map,this._requestListener=new G,this.messagesBuilder=void 0,this.configName=void 0}get parameters(){return this._parameters||(this._parameters=new U),this._parameters}get resourceID(){return this._resourceID||(this._resourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||O.resourceID||"unknown.resource.id"),this._resourceID}get auth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,s)=>{const e=this._authPromises.length>0;this._authPromises.push(new H(t,s)),e||this.authFetcher.getData(this.resourceID).then((t=>{for(this._auth=t;this._authPromises.length>0;)this._authPromises.pop().resolve(this._auth)})).catch((t=>{for(;this._authPromises.length>0;)this._authPromises.pop().reject(t)}))}))}async isUserSup(){return new Promise(((t,s)=>{this.auth.then((e=>{this.getAuthList(e).then((s=>{t(s.isSup)})).catch((t=>s(t)))}))}))}async hasAccess(t){return new Promise(((s,e)=>{this.auth.then((n=>{this.getAuthList(n).then((e=>{s(e.isSup||e.actions[t])})).catch((t=>e(t)))}))}))}async getAllAccess(){return new Promise(((t,s)=>{this.auth.then((e=>{this.getAuthList(e).then((s=>{const e={};e.isSup=s.isSup,Object.entries(x).forEach((t=>{e[t[0]]=s.actions[t[1]]||!1})),t(e)})).catch((t=>s(t)))}))}))}async getStringParam(t){return this.parameters.asString(t)}async getIntParam(t){return this.parameters.asInteger(t)}async getFloatParam(t){return this.parameters.asFloat(t)}async getBooleanParam(t){return this.parameters.asBoolean(t)}async getDateParam(t){return this.parameters.asDate(t)}async showPopUp(t,s="full",e=!0){this.clearContent(this._popUp),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=s,this._popUp.useHeader=e,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}async closeModal(){this.clearContent(this._rightModal),this._rightModal.opened=!1}async closePopUp(){this.clearContent(this._popUp),this._popUp.opened=!1,this._popUp.useHeader=!0,this._popUp.heightMode="full"}async temOpcional(t){const s=t.split(",");return new Promise(((t,e)=>{this.getAttributeFromHTMLWrapper("opc0009").then((n=>{"1"===n?t(!0):Promise.all(s.map((t=>this.getAttributeFromHTMLWrapper("opc"+t)))).then((s=>{t(s.includes("1"))})).catch((t=>{e(t)}))})).catch((t=>{e(t)}))}))}async getConfig(t){let s={serviceName:"SystemUtilsSP.getConf",requestBody:{config:{chave:t,tipo:"T"}}};return new Promise(((t,e)=>{w.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(s)).then((s=>{var e;return t(null===(e=s.config)||void 0===e?void 0:e.data)})).catch((t=>e(t)))}))}async saveConfig(t,s){let e={serviceName:"SystemUtilsSP.saveConf",requestBody:{config:{chave:t,tipo:"T",data:s}}};return new Promise(((t,s)=>{w.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(e)).then((s=>t(s))).catch((t=>s(t)))}))}async getAttributeFromHTMLWrapper(t){return Promise.resolve(window[t])}async openApp(t,s){O.openAppActivity(t,s)}async webConnection(t,s,e){this.getStringParam(t).then((t=>{j.webConnectionCaller(t,s,e)}))}getDuPromissesStack(t){let s;return t&&(s=this._duPromises.get(t),s||(s=[],this._duPromises.set(t,s))),s||[]}async createDataunit(t,s,e){return new Promise(((n,i)=>{const r=this.getDuPromissesStack(s),a=r.length>0;if(r.push(new H(n,i)),!a){const n=this.dataUnitFetcher.getDataUnit(t,this.resourceID,e);n.loadMetadata().then((()=>{for(s&&this.updateDataunitCache(void 0,s,n);r.length>0;)r.pop().resolve(n)})).catch((t=>{for(;r.length>0;)r.pop().reject(t)}))}}))}async updateDataunitCache(t,s,e){t&&this._duCache.delete(t),this._duCache.set(s,e)}async getDataUnit(t,s,e){return new Promise(((n,i)=>{const r=this._duCache.get(s);r?n(r):this.createDataunit(t,s,e).then((t=>{n(t)})).catch((t=>i(t)))}))}async addClientEvent(t,s){return new Promise((e=>{w.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{w.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(w.hasClientEvent(t))}))}async getResourceID(){return Promise.resolve(this.resourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,s,e,n){return g.alert(t,s,e,n)}async error(t,s,e,n){return g.error(t,s,e,n)}async success(t,s,e,n){return g.success(t,s,e,n)}async message(t,s,e,n){return g.message(t,s,e,n)}async confirm(t,s,e,n,i){return g.confirm(t,s,e,n,i)}async info(t,s){return g.info(t,s)}async loadGridConfig(t){return this.gridConfigFetcher.getConfig(t,this.resourceID)}async loadTotals(t,s,e){return this.totalsFetcher.fetchTotals(t,s,e)}async getAuthList(t){return await(new F).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=y.getQueryParams(location.search)),this._urlParams}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new _),this._dataUnitFetcher}get gridConfigFetcher(){return this._gridConfigFetcher||(this._gridConfigFetcher=new P),this._gridConfigFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new N),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new I),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new q),this._authFetcher}async executeSearch(t,s,e){const n=null==e?void 0:e.getField(s);if(n){const{mode:s,argument:i}=t,{ENTITYNAME:r,CODEFIELD:a,DESCRIPTIONFIELD:o,ROOTENTITY:c,DESCRIPTIONENTITY:h}=n.properties,l=n.dependencies;let p;const d={rootEntity:c,descriptionFieldName:o,codeFieldName:a,showInactives:!1,dataUnitId:e.dataUnitId};return null==l||l.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===u.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(p={expression:t.expression,params:t.masterFields.map((t=>{const s=e.getField(t),n=(null==s?void 0:s.dataType)||m.TEXT,i=e.getFieldValue(t);if(null==i)throw this.alert("Erro ao pesquisar",`É necessario informar o campo ${s.label} para executar a pesquisa.`),new Error(`É necessario informar o campo ${s.label} para executar a pesquisa.`);return{name:t,value:i,dataType:n}}))})})),this.executePreparedSearch(s,i,{entity:r,entityDescription:h,criteria:p,searchOptions:d})}}async executePreparedSearch(t,s,e){const{entity:n,entityDescription:i,criteria:r,searchOptions:a}=e;return"ADVANCED"===t?new Promise((t=>{const e=document.createElement("snk-pesquisa");e[l.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,e.argument=s,e.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,r,a),e.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(i),this.showPopUp(e)})):this.pesquisaFetcher.loadSearchOptions(n,s,r,a)}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){return O.getAppLabel(this._resourceID)}addSearchListener(t,s,e){return new Promise((n=>{n(this.pesquisaFetcher.addSearchListener(t,s.dataUnitId,e))}))}clearContent(t){t&&Array.from(t.children).forEach((s=>{t.removeChild(s)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}componentWillLoad(){this._errorHandler=new C(this),this.messagesBuilder=new E,p.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${y.getUrlBase()}/mge/upload/file`),p.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,s,e)=>this.executeSearch(t,s,e))),p.setContextValue("__EZUI__GRID_LICENSE__",b),d.init(),v.get()}connectedCallback(){p.setContextValue("__SNK__APPLICATION__",this),w.addRequestListener(this._requestListener)}disconnectedCallback(){w.removeRequestListener(this._requestListener)}componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{this.applicationLoaded.emit(!0)})),l.addIDInfo(this._element,`resource_${this._resourceID}`)}render(){return e("div",null,e("ez-loading-bar",{ref:t=>this._requestListener.loadingBar=t}),e("ez-popup",{opened:!1,ref:t=>this._popUp=t,onEzClosePopup:()=>this.closePopUp()}),e("ez-modal",{opened:!1,ref:t=>this._rightModal=t,"modal-size":"small",closeOutsideClick:!0,closeEsc:!0}))}get _element(){return n(this)}};class G{constructor(){this._debounceTime=1e3,this._ignoredNameTypes=["totals"],this._countRequest=0}onRequestStart(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest++,this.loadingBar.show(),this._timerLoading&&clearTimeout(this._timerLoading))}onRequestEnd(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest--,this._timerLoading=setTimeout((()=>{this._countRequest<=0&&this.loadingBar.hide()}),this._debounceTime))}isIgnoreLoadingOnRequest(t){var s;if(1==(null===(s=null==t?void 0:t.requestBody)||void 0===s?void 0:s.length)){const{name:s}=t.requestBody[0].variables;if(s){const t=s.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class H{constructor(t,s){this.resolve=t,this.reject=s}}z.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{z as snk_application}
11
+ }`)}async getParam(t){const s=`param://application?params=${t}`;return w.get().callGraphQL({values:{name:s},query:this.templateByQuery.get("fetchParam")})}async asString(t){const s=await this.getParam(t);return this.getValue(s)}async asInteger(t){const s=await this.getParam(t);return parseInt(this.getValue(s))}async asFloat(t){const s=await this.getParam(t);return parseFloat(this.getValue(s))}async asBoolean(t){const s=await this.getParam(t);return"S"===this.getValue(s)}async asDate(t){const s=await this.getParam(t);return c.strToDate(this.getValue(s))}async getBatchParams(t){const s=await this.getParam(t.join(",")),e={};return s.forEach((t=>e[t.name]=t.resource)),e}getValue(t={}){if(Array.isArray(t)&&t.length>0&&(t=t[0]),h.isEmpty(t.resource))return"";try{const s=o.stringToObject(t.resource),[e]=Object.keys(s);return s[e]}catch(t){console.warn("Erro ao converter string JSON.")}}}const k=R;function R(t,s){const e=$();return(R=function(t){return e[t-=378]})(t,s)}function $(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return($=function(){return t})()}!function(){const t=R,s=$();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;s.push(s.shift())}catch(t){s.push(s.shift())}}();class F{[k(397)](t){const s=k;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new M("S"===t[s(402)]||!0===t[s(402)]);return Array[s(394)](t[s(391)])&&t[s(391)][s(385)]((t=>e.putAccess(t[s(382)],String(t.status)==s(398)))),e}}class M{constructor(t){const s=k;this.isSup=t,this[s(384)]={}}[k(378)](t,s){this[k(384)][t]=s}[k(393)](t){const s=k;if(this[s(402)])return!0;let e=!0;return this[s(384)][s(380)](t)&&(e=this.actions[t]),e}isUserSup(){return this.isSup}}class q extends A{getData(t){const s=`cfg://auth/${t}`;return new Promise(((t,e)=>{this.loadResource(s).then((s=>{let e=o.stringToObject(s);e&&"object"==typeof e&&t(e)})).catch((t=>{e(t)}))}))}}var x;!function(t){t.INSERT="I",t.UPDATE="A",t.REMOVE="E",t.SHOW="C",t.CONFIG="F",t.CONFIG_NUMBER="N",t.CLONE="D",t.CONFIG_GRID="G"}(x||(x={}));const z=class{constructor(e){t(this,e),this.applicationLoaded=s(this,"applicationLoaded",7),this.applicationLoading=s(this,"applicationLoading",7),this._authPromises=[],this._duCache=new Map,this._duPromises=new Map,this._requestListener=new G,this.messagesBuilder=void 0,this.configName=void 0}get parameters(){return this._parameters||(this._parameters=new U),this._parameters}get resourceID(){return this._resourceID||(this._resourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||O.resourceID||"unknown.resource.id"),this._resourceID}get auth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,s)=>{const e=this._authPromises.length>0;this._authPromises.push(new H(t,s)),e||this.authFetcher.getData(this.resourceID).then((t=>{for(this._auth=t;this._authPromises.length>0;)this._authPromises.pop().resolve(this._auth)})).catch((t=>{for(;this._authPromises.length>0;)this._authPromises.pop().reject(t)}))}))}async isUserSup(){return new Promise(((t,s)=>{this.auth.then((e=>{this.getAuthList(e).then((s=>{t(s.isSup)})).catch((t=>s(t)))}))}))}async hasAccess(t){return new Promise(((s,e)=>{this.auth.then((n=>{this.getAuthList(n).then((e=>{s(e.isSup||e.actions[t])})).catch((t=>e(t)))}))}))}async getAllAccess(){return new Promise(((t,s)=>{this.auth.then((e=>{this.getAuthList(e).then((s=>{const e={};e.isSup=s.isSup,Object.entries(x).forEach((t=>{e[t[0]]=s.actions[t[1]]||!1})),t(e)})).catch((t=>s(t)))}))}))}async getStringParam(t){return this.parameters.asString(t)}async getIntParam(t){return this.parameters.asInteger(t)}async getFloatParam(t){return this.parameters.asFloat(t)}async getBooleanParam(t){return this.parameters.asBoolean(t)}async getDateParam(t){return this.parameters.asDate(t)}async showPopUp(t,s="full",e=!0){this.clearContent(this._popUp),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=s,this._popUp.useHeader=e,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}async closeModal(){this.clearContent(this._rightModal),this._rightModal.opened=!1}async closePopUp(){this.clearContent(this._popUp),this._popUp.opened=!1,this._popUp.useHeader=!0,this._popUp.heightMode="full"}async temOpcional(t){const s=t.split(",");return new Promise(((t,e)=>{this.getAttributeFromHTMLWrapper("opc0009").then((n=>{"1"===n?t(!0):Promise.all(s.map((t=>this.getAttributeFromHTMLWrapper("opc"+t)))).then((s=>{t(s.includes("1"))})).catch((t=>{e(t)}))})).catch((t=>{e(t)}))}))}async getConfig(t){let s={serviceName:"SystemUtilsSP.getConf",requestBody:{config:{chave:t,tipo:"T"}}};return new Promise(((t,e)=>{w.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(s)).then((s=>{var e;return t(null===(e=s.config)||void 0===e?void 0:e.data)})).catch((t=>e(t)))}))}async saveConfig(t,s){let e={serviceName:"SystemUtilsSP.saveConf",requestBody:{config:{chave:t,tipo:"T",data:s}}};return new Promise(((t,s)=>{w.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(e)).then((s=>t(s))).catch((t=>s(t)))}))}async getAttributeFromHTMLWrapper(t){return Promise.resolve(window[t])}async openApp(t,s){O.openAppActivity(t,s)}async webConnection(t,s,e){this.getStringParam(t).then((t=>{j.webConnectionCaller(t,s,e)}))}getDuPromissesStack(t){let s;return t&&(s=this._duPromises.get(t),s||(s=[],this._duPromises.set(t,s))),s||[]}async createDataunit(t,s,e){return new Promise(((n,i)=>{const r=this.getDuPromissesStack(s),a=r.length>0;if(r.push(new H(n,i)),!a){const n=this.dataUnitFetcher.getDataUnit(t,this.resourceID,e);n.loadMetadata().then((()=>{for(s&&this.updateDataunitCache(void 0,s,n);r.length>0;)r.pop().resolve(n)})).catch((t=>{for(;r.length>0;)r.pop().reject(t)}))}}))}async updateDataunitCache(t,s,e){t&&this._duCache.delete(t),this._duCache.set(s,e)}async getDataUnit(t,s,e){return new Promise(((n,i)=>{const r=this._duCache.get(s);r?n(r):this.createDataunit(t,s,e).then((t=>{n(t)})).catch((t=>i(t)))}))}async addClientEvent(t,s){return new Promise((e=>{w.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{w.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(w.hasClientEvent(t))}))}async getResourceID(){return Promise.resolve(this.resourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,s,e,n){return g.alert(t,s,e,n)}async error(t,s,e,n){return g.error(t,s,e,n)}async success(t,s,e,n){return g.success(t,s,e,n)}async message(t,s,e,n){return g.message(t,s,e,n)}async confirm(t,s,e,n,i){return g.confirm(t,s,e,n,i)}async info(t,s){return g.info(t,s)}async loadGridConfig(t){return this.gridConfigFetcher.getConfig(t,this.resourceID)}async loadTotals(t,s,e){return this.totalsFetcher.fetchTotals(t,s,e)}async getAuthList(t){return await(new F).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=y.getQueryParams(location.search)),this._urlParams}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new _),this._dataUnitFetcher}get gridConfigFetcher(){return this._gridConfigFetcher||(this._gridConfigFetcher=new P),this._gridConfigFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new b),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new I),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new q),this._authFetcher}async executeSearch(t,s,e){const n=null==e?void 0:e.getField(s);if(n){const{mode:s,argument:i}=t,{ENTITYNAME:r,CODEFIELD:a,DESCRIPTIONFIELD:o,ROOTENTITY:c,DESCRIPTIONENTITY:h}=n.properties,l=n.dependencies;let p;const d={rootEntity:c,descriptionFieldName:o,codeFieldName:a,showInactives:!1,dataUnitId:e.dataUnitId};return null==l||l.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===u.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(p={expression:t.expression,params:t.masterFields.map((t=>{const s=e.getField(t),n=(null==s?void 0:s.dataType)||m.TEXT,i=e.getFieldValue(t);if(null==i)throw this.alert("Erro ao pesquisar",`É necessario informar o campo ${s.label} para executar a pesquisa.`),new Error(`É necessario informar o campo ${s.label} para executar a pesquisa.`);return{name:t,value:i,dataType:n}}))})})),this.executePreparedSearch(s,i,{entity:r,entityDescription:h,criteria:p,searchOptions:d})}}async executePreparedSearch(t,s,e){const{entity:n,entityDescription:i,criteria:r,searchOptions:a}=e;return"ADVANCED"===t?new Promise((t=>{const e=document.createElement("snk-pesquisa");e[l.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,e.argument=s,e.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,r,a),e.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(i),this.showPopUp(e)})):this.pesquisaFetcher.loadSearchOptions(n,s,r,a)}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){return O.getAppLabel(this._resourceID)}addSearchListener(t,s,e){return new Promise((n=>{n(this.pesquisaFetcher.addSearchListener(t,s.dataUnitId,e))}))}clearContent(t){t&&Array.from(t.children).forEach((s=>{t.removeChild(s)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}componentWillLoad(){this._errorHandler=new C(this),this.messagesBuilder=new E,p.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${y.getUrlBase()}/mge/upload/file`),p.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,s,e)=>this.executeSearch(t,s,e))),p.setContextValue("__EZUI__GRID_LICENSE__",N),d.init(),v.get()}connectedCallback(){p.setContextValue("__SNK__APPLICATION__",this),w.addRequestListener(this._requestListener)}disconnectedCallback(){w.removeRequestListener(this._requestListener)}componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{this.applicationLoaded.emit(!0)})),l.addIDInfo(this._element,`resource_${this._resourceID}`)}render(){return e("div",null,e("ez-loading-bar",{ref:t=>this._requestListener.loadingBar=t}),e("ez-popup",{opened:!1,ref:t=>this._popUp=t,onEzClosePopup:()=>this.closePopUp()}),e("ez-modal",{opened:!1,ref:t=>this._rightModal=t,"modal-size":"small",closeOutsideClick:!0,closeEsc:!0}))}get _element(){return n(this)}};class G{constructor(){this._debounceTime=1e3,this._ignoredNameTypes=["totals"],this._countRequest=0}onRequestStart(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest++,this.loadingBar.show(),this._timerLoading&&clearTimeout(this._timerLoading))}onRequestEnd(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest--,this._timerLoading=setTimeout((()=>{this._countRequest<=0&&this.loadingBar.hide()}),this._debounceTime))}isIgnoreLoadingOnRequest(t){var s;if(1==(null===(s=null==t?void 0:t.requestBody)||void 0===s?void 0:s.length)){const{name:s}=t.requestBody[0].variables;if(s){const t=s.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class H{constructor(t,s){this.resolve=t,this.reject=s}}z.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{z as snk_application}
@@ -0,0 +1 @@
1
+ import{r as t,c as e,h as s,H as i,g as r}from"./p-b9667fbe.js";import{ElementIDUtils as a}from"@sankhyalabs/core";import{F as n}from"./p-584d7212.js";import{F as l}from"./p-d9804798.js";import{E as o}from"./p-1a68fb59.js";const c=class{constructor(s){t(this,s),this.filterChange=e(this,"filterChange",7),this.filterItem=void 0}observeFilterItem(t){this.filterChange.emit(t)}getContentEditorConfig(){const t={presentationMode:o.MODAL};switch(this.filterItem.type){case n.BINARY_SELECT:return{tag:"snk-filter-binary-select",variations:t};case n.MULTI_SELECT:return{tag:"snk-filter-multi-select"};case n.PERIOD:return{tag:"snk-filter-period",variations:t};case n.SEARCH:return{tag:"snk-filter-search"};case n.NUMBER:return{tag:"snk-filter-number"};case n.PERSONALIZED:return{tag:"snk-filter-personalized"};case n.MULTI_LIST:return{tag:"snk-entity-list"}}return{tag:"snk-filter-text"}}updateFilterValue(t){const e=!!this.filterItem.visible||void 0!==t;this.filterItem=Object.assign(Object.assign({},this.filterItem),{value:t,visible:e})}canShowDetailModal(){return this.filterItem.filterType!==l.OTHER_FILTERS&&this.filterItem.type!==n.BINARY_SELECT}componentDidLoad(){if(this._element){a.addIDInfo(this._element);const t=this._element.getAttribute(a.DATA_ELEMENT_ID_ATTRIBUTE_NAME);this._idContentEditor=`${t}_${this.filterItem.id}`}}render(){const{tag:t,variations:e}=this.getContentEditorConfig();return s(i,null,s("div",{class:"ez-flex ez-flex--column grow"},this.canShowDetailModal()&&s("div",{class:"col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center"},s("div",{class:"ez-title ez-title--small ez-title--primary grow"},this.filterItem.detailModal)),s(t,Object.assign({config:this.filterItem,value:this.filterItem.value,onValueChanged:t=>this.updateFilterValue(t.detail),"data-element-id":this._idContentEditor},e))))}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}
@@ -1 +1 @@
1
- import{r as t,c as i,h as s,g as e,H as n}from"./p-b9667fbe.js";import{Action as a,ObjectUtils as o,JSUtils as h,ApplicationContext as r,DataType as l}from"@sankhyalabs/core";import{ApplicationUtils as d,DialogType as c}from"@sankhyalabs/ezui/dist/collection/utils";import{O as v,S as u}from"./p-f5f36fbb.js";const f=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.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this._openedAlert=!1,this._dataUnitObserver=t=>{var i,s;const e=this.buildDataState();if(this.dataState=e,t.type===a.DATA_SAVED){const i=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0]);null!=i&&this.showSuccessMessage(i)}if(t.type!==a.RECORDS_ADDED&&t.type!==a.RECORDS_COPIED||this.insertionMode.emit(),t.type===a.EDITION_CANCELED&&this.cancelEdition.emit(),t.type===a.RECORDS_REMOVED){const e=t.payload.cachedRecords;let n;n=(null==e?void 0:e.length)>1?this.getMessage("snkDataUnit.removeAllInfo",{size:e.length}):this.getMessage("snkDataUnit.removeInfo",t.payload.cachedRecords[0]),null!=n&&this.showSuccessMessage(n);const a=null!==(s=null===(i=this.dataUnit.records)||void 0===i?void 0:i.length)&&void 0!==s?s:0,o=this.dataUnit.getPaginationInfo();o&&this.dataUnit.gotoPage(a>0||o.hasMore?o.currentPage:0)}this.messagesBuilder.currentOperation=this.getMessageOperation()},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}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){o.objectToString(i)!=o.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(){var t;const i=null===(t=this.dataUnit)||void 0===t?void 0:t.getSelectionInfo();if(null==i?void 0:i.isAllRecords())return[];const s=[],e=null==i?void 0:i.records;return(null==e?void 0:e.length)>0&&e.forEach((({__record__id__:t})=>{if(!this.dataUnit.isNewRecord(t)){if(!h.isBase64(t))return void s.push({name:"__record__id__",type:l.TEXT,value:t});const i=JSON.parse(window.atob(t));Object.entries(i).forEach((([t,i])=>{var e;const n=null===(e=this.dataUnit)||void 0===e?void 0:e.getField(t);null!=n&&s.push(Object.assign({name:t,type:n.dataType},i))}))}})),s}async interceptAction(t){return new Promise((i=>{var s,e;switch(t.type){case a.RECORDS_ADDED:this.isAllowed("INSERT")?i(t):d.info(this.getMessage("snkDataUnit.forbiddenInsert"));break;case a.RECORDS_COPIED:this.isAllowed("CLONE")?i(t):d.info(this.getMessage("snkDataUnit.forbiddenClone"));break;case a.DATA_CHANGED:case a.CHANGING_DATA:if(this.isAllowed("UPDATE"))return i(t);if(this._openedAlert)return this.dataUnit.cancelEdition();this._openedAlert=!0,this.dataUnit.cancelEdition(),d.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")).then((()=>{this._openedAlert=!1}));break;case a.SAVING_DATA:if(this.beforeSave){const s=this.beforeSave(this.dataUnit);s instanceof Promise?s.then((s=>i(s?t:void 0))):i(s?t:void 0)}else i(t);break;case a.DATA_SAVED:this.afterSave?this.afterSave(this.dataUnit):i(t);break;case a.EDITION_CANCELED:if(!this.useCancelConfirm)return i(t);if(this.dataState.hasDirtyRecords){const e=this.getMessage("snkDataUnit.cancelConfirmation");if(null===(s=t.payload)||void 0===s?void 0:s.fromParent)return void i(t);if(null==e)this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),i(t);else{const s=this.getMessage("snkDataUnit.cancelConfirmationTitle");d.confirm(s,e).then((s=>{s&&this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),i(s?t:void 0)}))}}else i(t);break;case a.REMOVING_RECORDS:if(this.isAllowed("REMOVE")){let s=!1,n=this.getMessage("snkDataUnit.removeConfirmation");const a=null===(e=this.dataUnit)||void 0===e?void 0:e.getSelectionInfo();if((null==a?void 0:a.length)>1&&(n=this.getMessage("snkDataUnit.removeAllConfirmation",{size:a.length}),s=!0),null==n)i(t);else{const e={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm."+(s?"no":"cancel")),labelConfirm:this.getMessage("snkDataUnit.confirm."+(s?"yes":"delete")),btnConfirmDanger:!1},a=this.getMessage("snkDataUnit.removeConfirmationTitle");d.confirm(a,n,null,c.WARN,e).then((s=>i(s?t:void 0)))}}else d.info(this.getMessage("snkDataUnit.forbiddenRemove"));break;default:i(t)}}))}showSuccessMessage(t){d.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}buildDataState(){const t=this.dataUnit.getSelectionInfo(),i=(this.dataUnit.hasDirtyRecords()||this.dataUnit.hasWaitingChanges())&&(null==t?void 0:t.isEmpty());return new m({insertionMode:this.dataUnit.hasNewRecord(),isStartingInsertionMode:i,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:this.dataUnit.hasCopiedRecord(),isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:void 0,selectionInfo:t,selectedRecord:this.dataUnit.getSelectedRecord()})}getMessage(t,i){return i||(i=this.getMessageParams()),this.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecord}getMessageOperation(){return this.dataState.copyMode?v.CLONE:this.dataState.insertionMode||this.dataState.isStartingInsertionMode?v.INSERT:this.dataState.isDirty?v.UPDATE:v.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)):await this._application.getDataUnit(this.entityName,i)}async loadDataUnit(){if(null==this.dataUnit&&this._application&&this.entityName&&(this.dataUnit=await this.getDataUnitParentOrChild()),this.dataUnit){let t;for(this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.addInterceptor(this),this.dataUnit.subscribe(this._dataUnitObserver),this.dataState=this.buildDataState();t=this._onDataUnitResolve.pop();)t(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;const s=Object.assign({},this.dataUnit.metadata);if(!this._parentDataUnit)return;const e=this._parentDataUnit.getChildInfo(this.entityName);if(!e)return;const n=null===(t=null==e?void 0:e.links)||void 0===t?void 0:t.map((t=>t.target));null===(i=null==s?void 0:s.fields)||void 0===i||i.forEach((t=>{(null==n?void 0:n.includes(t.name))&&(t.visible=!1)})),this.dataUnit.metadata=s}static getNearestInstance(t){let i=t.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase())return i;i=i.parentElement}}componentWillLoad(){this._application=r.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess().then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}disconnectedCallback(){this.dataUnit&&(this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.removeInterceptor(this))}componentDidLoad(){this.loadDataUnit()}render(){return s(n,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"],messagesBuilder:["observeMessagesBuilder"]}}};class m{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}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}}f.style=".sc-snk-data-unit-h{display:flex;flex-direction:column;height:100%;width:100%}";export{f as S}
1
+ import{r as t,c as i,h as s,g as e,H as n}from"./p-b9667fbe.js";import{Action as a,ObjectUtils as o,JSUtils as h,ApplicationContext as r,DataType as l}from"@sankhyalabs/core";import{ApplicationUtils as d,DialogType as c}from"@sankhyalabs/ezui/dist/collection/utils";import{O as v,S as u}from"./p-29c1889f.js";const f=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.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this._openedAlert=!1,this._dataUnitObserver=t=>{var i,s;const e=this.buildDataState();if(this.dataState=e,t.type===a.DATA_SAVED){const i=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0]);null!=i&&this.showSuccessMessage(i)}if(t.type!==a.RECORDS_ADDED&&t.type!==a.RECORDS_COPIED||this.insertionMode.emit(),t.type===a.EDITION_CANCELED&&this.cancelEdition.emit(),t.type===a.RECORDS_REMOVED){const e=t.payload.cachedRecords;let n;n=(null==e?void 0:e.length)>1?this.getMessage("snkDataUnit.removeAllInfo",{size:e.length}):this.getMessage("snkDataUnit.removeInfo",t.payload.cachedRecords[0]),null!=n&&this.showSuccessMessage(n);const a=null!==(s=null===(i=this.dataUnit.records)||void 0===i?void 0:i.length)&&void 0!==s?s:0,o=this.dataUnit.getPaginationInfo();o&&this.dataUnit.gotoPage(a>0||o.hasMore?o.currentPage:0)}this.messagesBuilder.currentOperation=this.getMessageOperation()},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}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){o.objectToString(i)!=o.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(){var t;const i=null===(t=this.dataUnit)||void 0===t?void 0:t.getSelectionInfo();if(null==i?void 0:i.isAllRecords())return[];const s=[],e=null==i?void 0:i.records;return(null==e?void 0:e.length)>0&&e.forEach((({__record__id__:t})=>{if(!this.dataUnit.isNewRecord(t)){if(!h.isBase64(t))return void s.push({name:"__record__id__",type:l.TEXT,value:t});const i=JSON.parse(window.atob(t));Object.entries(i).forEach((([t,i])=>{var e;const n=null===(e=this.dataUnit)||void 0===e?void 0:e.getField(t);null!=n&&s.push(Object.assign({name:t,type:n.dataType},i))}))}})),s}async interceptAction(t){return new Promise((i=>{var s,e;switch(t.type){case a.RECORDS_ADDED:this.isAllowed("INSERT")?i(t):d.info(this.getMessage("snkDataUnit.forbiddenInsert"));break;case a.RECORDS_COPIED:this.isAllowed("CLONE")?i(t):d.info(this.getMessage("snkDataUnit.forbiddenClone"));break;case a.DATA_CHANGED:case a.CHANGING_DATA:if(this.isAllowed("UPDATE"))return i(t);if(this._openedAlert)return this.dataUnit.cancelEdition();this._openedAlert=!0,this.dataUnit.cancelEdition(),d.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")).then((()=>{this._openedAlert=!1}));break;case a.SAVING_DATA:if(this.beforeSave){const s=this.beforeSave(this.dataUnit);s instanceof Promise?s.then((s=>i(s?t:void 0))):i(s?t:void 0)}else i(t);break;case a.DATA_SAVED:this.afterSave?this.afterSave(this.dataUnit):i(t);break;case a.EDITION_CANCELED:if(!this.useCancelConfirm)return i(t);if(this.dataState.hasDirtyRecords){const e=this.getMessage("snkDataUnit.cancelConfirmation");if(null===(s=t.payload)||void 0===s?void 0:s.fromParent)return void i(t);if(null==e)this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),i(t);else{const s=this.getMessage("snkDataUnit.cancelConfirmationTitle");d.confirm(s,e).then((s=>{s&&this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),i(s?t:void 0)}))}}else i(t);break;case a.REMOVING_RECORDS:if(this.isAllowed("REMOVE")){let s=!1,n=this.getMessage("snkDataUnit.removeConfirmation");const a=null===(e=this.dataUnit)||void 0===e?void 0:e.getSelectionInfo();if((null==a?void 0:a.length)>1&&(n=this.getMessage("snkDataUnit.removeAllConfirmation",{size:a.length}),s=!0),null==n)i(t);else{const e={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm."+(s?"no":"cancel")),labelConfirm:this.getMessage("snkDataUnit.confirm."+(s?"yes":"delete")),btnConfirmDanger:!1},a=this.getMessage("snkDataUnit.removeConfirmationTitle");d.confirm(a,n,null,c.WARN,e).then((s=>i(s?t:void 0)))}}else d.info(this.getMessage("snkDataUnit.forbiddenRemove"));break;default:i(t)}}))}showSuccessMessage(t){d.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}buildDataState(){const t=this.dataUnit.getSelectionInfo(),i=(this.dataUnit.hasDirtyRecords()||this.dataUnit.hasWaitingChanges())&&(null==t?void 0:t.isEmpty());return new m({insertionMode:this.dataUnit.hasNewRecord(),isStartingInsertionMode:i,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:this.dataUnit.hasCopiedRecord(),isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:void 0,selectionInfo:t,selectedRecord:this.dataUnit.getSelectedRecord()})}getMessage(t,i){return i||(i=this.getMessageParams()),this.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecord}getMessageOperation(){return this.dataState.copyMode?v.CLONE:this.dataState.insertionMode||this.dataState.isStartingInsertionMode?v.INSERT:this.dataState.isDirty?v.UPDATE:v.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)):await this._application.getDataUnit(this.entityName,i)}async loadDataUnit(){if(null==this.dataUnit&&this._application&&this.entityName&&(this.dataUnit=await this.getDataUnitParentOrChild()),this.dataUnit){let t;for(this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.addInterceptor(this),this.dataUnit.subscribe(this._dataUnitObserver),this.dataState=this.buildDataState();t=this._onDataUnitResolve.pop();)t(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;const s=Object.assign({},this.dataUnit.metadata);if(!this._parentDataUnit)return;const e=this._parentDataUnit.getChildInfo(this.entityName);if(!e)return;const n=null===(t=null==e?void 0:e.links)||void 0===t?void 0:t.map((t=>t.target));null===(i=null==s?void 0:s.fields)||void 0===i||i.forEach((t=>{(null==n?void 0:n.includes(t.name))&&(t.visible=!1)})),this.dataUnit.metadata=s}static getNearestInstance(t){let i=t.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase())return i;i=i.parentElement}}componentWillLoad(){this._application=r.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess().then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}disconnectedCallback(){this.dataUnit&&(this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.removeInterceptor(this))}componentDidLoad(){this.loadDataUnit()}render(){return s(n,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"],messagesBuilder:["observeMessagesBuilder"]}}};class m{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}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}}f.style=".sc-snk-data-unit-h{display:flex;flex-direction:column;height:100%;width:100%}";export{f as S}