@sankhyalabs/sankhyablocks 8.16.0-rc.3 → 8.16.0-rc.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (81) hide show
  1. package/dist/cjs/{ConfigStorage-a343e418.js → ConfigStorage-e49214c6.js} +2 -2
  2. package/dist/cjs/{DataFetcher-313debd8.js → DataFetcher-77729a93.js} +7 -2
  3. package/dist/cjs/{IExporterProvider-597949f9.js → IExporterProvider-10b7fed5.js} +4 -4
  4. package/dist/cjs/{SnkFormConfigManager-166cbd1f.js → SnkFormConfigManager-beebf47a.js} +2 -2
  5. package/dist/cjs/{auth-fetcher-54f5ff9d.js → auth-fetcher-29bb791c.js} +1 -1
  6. package/dist/cjs/{dataunit-fetcher-688d3f05.js → dataunit-fetcher-d4873076.js} +1 -1
  7. package/dist/cjs/{form-config-fetcher-2dd00e5b.js → form-config-fetcher-feb08214.js} +1 -1
  8. package/dist/cjs/{pesquisa-fetcher-680e198f.js → pesquisa-fetcher-a1d0353f.js} +1 -1
  9. package/dist/cjs/snk-actions-button_4.cjs.entry.js +5 -5
  10. package/dist/cjs/snk-application.cjs.entry.js +6 -6
  11. package/dist/cjs/snk-attach.cjs.entry.js +5 -5
  12. package/dist/cjs/snk-crud.cjs.entry.js +5 -5
  13. package/dist/cjs/snk-data-exporter.cjs.entry.js +5 -5
  14. package/dist/cjs/{snk-data-unit-8fa7917a.js → snk-data-unit-ece44c4a.js} +1 -1
  15. package/dist/cjs/snk-data-unit.cjs.entry.js +3 -3
  16. package/dist/cjs/snk-detail-view.cjs.entry.js +7 -7
  17. package/dist/cjs/snk-filter-bar.cjs.entry.js +3 -3
  18. package/dist/cjs/snk-filter-modal-item.cjs.entry.js +3 -3
  19. package/dist/cjs/snk-form-config.cjs.entry.js +2 -2
  20. package/dist/cjs/snk-form.cjs.entry.js +4 -4
  21. package/dist/cjs/snk-grid.cjs.entry.js +6 -6
  22. package/dist/cjs/{snk-guides-viewer-bdc41281.js → snk-guides-viewer-69ec61af.js} +5 -5
  23. package/dist/cjs/snk-guides-viewer.cjs.entry.js +7 -7
  24. package/dist/cjs/snk-personalized-filter.cjs.entry.js +3 -3
  25. package/dist/cjs/snk-simple-crud.cjs.entry.js +7 -7
  26. package/dist/collection/lib/http/data-fetcher/DataFetcher.js +8 -3
  27. package/dist/components/DataFetcher.js +8 -3
  28. package/dist/esm/{ConfigStorage-3806514e.js → ConfigStorage-e476378d.js} +2 -2
  29. package/dist/esm/{DataFetcher-c1baf61d.js → DataFetcher-773a3e4b.js} +8 -3
  30. package/dist/esm/{IExporterProvider-63a188b6.js → IExporterProvider-d597f27d.js} +4 -4
  31. package/dist/esm/{SnkFormConfigManager-31b24066.js → SnkFormConfigManager-298cd647.js} +2 -2
  32. package/dist/esm/{auth-fetcher-039abba3.js → auth-fetcher-a411f73c.js} +1 -1
  33. package/dist/esm/{dataunit-fetcher-264191b2.js → dataunit-fetcher-3d2ec959.js} +1 -1
  34. package/dist/esm/{form-config-fetcher-30fb808f.js → form-config-fetcher-e0382e5a.js} +1 -1
  35. package/dist/esm/{pesquisa-fetcher-03c8f919.js → pesquisa-fetcher-a87445a0.js} +1 -1
  36. package/dist/esm/snk-actions-button_4.entry.js +5 -5
  37. package/dist/esm/snk-application.entry.js +6 -6
  38. package/dist/esm/snk-attach.entry.js +5 -5
  39. package/dist/esm/snk-crud.entry.js +5 -5
  40. package/dist/esm/snk-data-exporter.entry.js +5 -5
  41. package/dist/esm/{snk-data-unit-f5cbe64b.js → snk-data-unit-2a1d5d09.js} +1 -1
  42. package/dist/esm/snk-data-unit.entry.js +3 -3
  43. package/dist/esm/snk-detail-view.entry.js +7 -7
  44. package/dist/esm/snk-filter-bar.entry.js +3 -3
  45. package/dist/esm/snk-filter-modal-item.entry.js +3 -3
  46. package/dist/esm/snk-form-config.entry.js +2 -2
  47. package/dist/esm/snk-form.entry.js +4 -4
  48. package/dist/esm/snk-grid.entry.js +6 -6
  49. package/dist/esm/{snk-guides-viewer-dda0fede.js → snk-guides-viewer-43f21b03.js} +5 -5
  50. package/dist/esm/snk-guides-viewer.entry.js +7 -7
  51. package/dist/esm/snk-personalized-filter.entry.js +3 -3
  52. package/dist/esm/snk-simple-crud.entry.js +7 -7
  53. package/dist/sankhyablocks/{p-fe79f83a.js → p-091ce761.js} +1 -1
  54. package/dist/sankhyablocks/{p-913a9979.js → p-0cd3c0a9.js} +1 -1
  55. package/dist/sankhyablocks/{p-df5451c7.js → p-181975f1.js} +1 -1
  56. package/dist/sankhyablocks/{p-8c59edd7.entry.js → p-1e971cb0.entry.js} +1 -1
  57. package/dist/sankhyablocks/{p-fa4d8cb4.js → p-1f35c795.js} +1 -1
  58. package/dist/sankhyablocks/{p-af8efd95.js → p-25f1fc39.js} +1 -1
  59. package/dist/sankhyablocks/{p-62ba211a.entry.js → p-2e9c764c.entry.js} +1 -1
  60. package/dist/sankhyablocks/{p-52920496.js → p-3287a6cc.js} +1 -1
  61. package/dist/sankhyablocks/{p-4e5e1313.entry.js → p-421bec84.entry.js} +1 -1
  62. package/dist/sankhyablocks/{p-7505da04.entry.js → p-42f7b05d.entry.js} +1 -1
  63. package/dist/sankhyablocks/{p-b05d8893.entry.js → p-53412c1d.entry.js} +1 -1
  64. package/dist/sankhyablocks/p-594bc21d.js +1 -0
  65. package/dist/sankhyablocks/{p-2a408684.js → p-5f016aed.js} +1 -1
  66. package/dist/sankhyablocks/{p-d6e26ea8.entry.js → p-62f34e6f.entry.js} +1 -1
  67. package/dist/sankhyablocks/{p-6bb2f3e9.entry.js → p-631954eb.entry.js} +1 -1
  68. package/dist/sankhyablocks/{p-7a85fd49.entry.js → p-65f8c11c.entry.js} +1 -1
  69. package/dist/sankhyablocks/{p-80042dc6.entry.js → p-684a2590.entry.js} +1 -1
  70. package/dist/sankhyablocks/{p-3a212712.js → p-76a65660.js} +1 -1
  71. package/dist/sankhyablocks/p-7b8f7242.entry.js +1 -0
  72. package/dist/sankhyablocks/{p-450c60e4.entry.js → p-939e15d3.entry.js} +1 -1
  73. package/dist/sankhyablocks/{p-47db7e88.entry.js → p-9dfda04a.entry.js} +1 -1
  74. package/dist/sankhyablocks/{p-871aa14e.entry.js → p-ba25555b.entry.js} +1 -1
  75. package/dist/sankhyablocks/{p-2c68b3ae.entry.js → p-bd008859.entry.js} +1 -1
  76. package/dist/sankhyablocks/{p-7619bdb1.entry.js → p-d6610d11.entry.js} +2 -2
  77. package/dist/sankhyablocks/{p-17def7cd.js → p-ffa5e4ff.js} +1 -1
  78. package/dist/sankhyablocks/sankhyablocks.esm.js +1 -1
  79. package/package.json +1 -1
  80. package/dist/sankhyablocks/p-75e674ed.entry.js +0 -1
  81. package/dist/sankhyablocks/p-dc7c9047.js +0 -1
@@ -1 +1 @@
1
- import{r as i,c as o,h as n,H as t,g as s}from"./p-d2d301a6.js";import{S as e}from"./p-fa816fb2.js";import{ObjectUtils as l,ElementIDUtils as r,ArrayUtils as a,ApplicationContext as d}from"@sankhyalabs/core";import{ApplicationUtils as c,DialogType as f}from"@sankhyalabs/ezui/dist/collection/utils";import{C as h,a as g,T as u,A as m,D as v}from"./p-b0ef4383.js";import{U as b}from"./p-df5451c7.js";import{buildFormConfigFromDataUnit as p}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-dc7c9047.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const _="EZ-COLLAPSIBLE-BOX",z="fieldsWithoutGroupContainer",k="fieldsAvailableContainer",C="addNewGroupContainer",x=class{constructor(n){i(this,n),this.configChange=o(this,"configChange",7),this.configClose=o(this,"configClose",7),this._listEnabledFields=[],this._renderTimer=500,this._tabSelected=1,this._labelNewGroup="Novo grupo",this._mouseOnFieldConfig=!1,this._mouseOnConfigOptions=!1,this._editingTitleGroup=!1,this._newGroupBoxes=[],this._currentGroupBoxes=[],this._formFieldsStyle="ez-col ez-col--sd-12 ez-col--tb-4 ez-padding-right--small ez-padding-bottom--medium sc-snk-form-config",this._fieldsAvailableStyle="ez-col ez-col--sd-12 ez-col--tb-12 ez-margin-bottom--medium ez-margin-right--medium sc-snk-form-config",this._fieldFloatingStyle="form-config__field-config--dragged",this._sortableTimer=100,this._formConfigOptions=[],this._fieldConfigSelected=void 0,this._layoutFormConfig=void 0,this._fieldsAvailable=void 0,this._formConfig={},this._formConfigChanged=!1,this._optionFormConfigSelected=void 0,this._optionFormConfigChanged=!1,this._tempGroups=[],this.dataUnit=void 0,this.configManager=void 0,this.messagesBuilder=void 0}observeConfigManager(){this.loadConfig(this._sortableTimer)}loadFields(i=0){this._layoutFormConfig=[],i>0?setTimeout((()=>{this.buildFields()}),i):this.buildFields()}buildFields(){this.buildFormConfig(),this.buildAvailableFields()}loadFormConfig(i){var o;this._formConfig=this.getConfig(),this.loadFields(i),this.controlFieldConfig(),null!=(null===(o=this._filterFieldsAvailable)||void 0===o?void 0:o.value)&&(this._filterFieldsAvailable.value="")}getConfig(){let i=this.configManager.getConfig(this.dataUnit);return i.fields&&0===i.fields.length&&(i=void 0),null==i&&(i=p(this.dataUnit)),l.copy(i)}cancelChangeConfig(){!0===this._formConfigChanged?this.openConfirmDialog(this.getMessage("snkFormConfig.confirm.cancel")).then((i=>{i&&(this._formConfigChanged=!1,this.resetChangeConfig())})):this.resetChangeConfig()}cancelChangeOptionConfig(){!0===this._optionFormConfigChanged?this.openConfirmDialog(this.getMessage("snkFormConfig.confirm.cancel")).then((i=>{i&&(this._optionFormConfigChanged=!1,this.resetChangeOptionConfig())})):this.resetChangeOptionConfig()}resetChangeConfig(){this.loadFormConfig(this._sortableTimer),this.clearTempGroups()}resetChangeOptionConfig(){this._formConfigChanged=!1,this.loadConfig(this._sortableTimer),this.clearTempGroups()}getTabsToSave(){return this._layoutFormConfig.map(((i,o)=>({label:i.tab,order:o,visible:i.visible})))}getFieldsToSave(){const i=[];return this._formContainer.querySelectorAll("snk-field-config").forEach((o=>{const n=o.fieldConfig;if(null==n)return;const t={cleanOnCopy:n.cleanOnCopy||!1,group:n.group,label:n.label,name:n.name,required:n.required,readOnly:n.readOnly,tab:n.tab};null!=n.defaultValue&&(t.defaultValue=null==n.defaultValue.type?{type:v.fixed,value:n.defaultValue}:n.defaultValue),i.push(t)})),i}isDefaultConfiguration(){var i;return(null===(i=this._optionFormConfigSelected)||void 0===i?void 0:i.origin)===b.DEFAULT&&!0===this._optionFormConfigChanged&&!1===this._formConfigChanged}buildConfigToSave(){let i={};const o=this.isDefaultConfiguration();if(i=o?this.getConfig():l.copy(this._formConfig),!1===o){const o=this.getTabsToSave();(null==o?void 0:o.length)>0&&(i.tabs=o);const n=this.getFieldsToSave();(null==n?void 0:n.length)>0&&(i.fields=n)}return i.defaultConfiguration=o,i}saveConfig(){var i;(null===(i=this._tempGroups)||void 0===i?void 0:i.length)>0?c.alert(this.getMessage("snkFormConfig.confirm.title"),this.getMessage("snkFormConfig.confirm.group")):(this._formConfigChanged=!1,this._optionFormConfigChanged=!1,this.configManager.saveConfig(this.buildConfigToSave()).then((i=>{c.info(this.getMessage("snkFormConfig.info.successfullyConfigSaved"),{iconName:"check"}),this.configChange.emit(i)})))}applyOptionConfig(){if(!0===this._optionFormConfigChanged&&null!=this._optionFormConfigSelected){const i=this._optionFormConfigSelected.name||"configuração selecionada",o=this._optionFormConfigSelected.origin===b.DEFAULT?"pessoal":"padrão",n=this.getMessage("snkFormConfig.confirm.apply").replace("{0}",i).replace("{1}",o);this.openConfirmDialog(n).then((i=>{i&&this.saveConfig()}))}else this.saveConfig()}controlFieldConfig(i){var o;this._fieldConfigSelected=null!=i?(null===(o=this._fieldConfigSelected)||void 0===o?void 0:o.name)===(null==i?void 0:i.name)?void 0:i:void 0}getFieldConfigStyle(i){var o;return this._formFieldsStyle+((null===(o=this._fieldConfigSelected)||void 0===o?void 0:o.name)===i.name?" form-config__field-config--selected":"")}getFieldsByGroup(i){var o;return(null===(o=i.fields)||void 0===o?void 0:o.length)?i.fields.map((i=>{var o,t;return n("div",{key:i.name,class:this.getFieldConfigStyle(i),"data-draggable-element":"field",onMouseDown:i=>this.controlMoveField(i)},n("snk-field-config",{messagesBuilder:this.messagesBuilder,onEzClickIcon:i=>{this.handleFieldConfigChange(i)},modeInsertion:!1,fieldConfig:i,dataUnit:this.dataUnit,isConfigActive:(null===(o=this._fieldConfigSelected)||void 0===o?void 0:o.name)===i.name,id:i.name,key:i.name}),(null===(t=this._fieldConfigSelected)||void 0===t?void 0:t.name)===i.name&&n("div",{class:"ez-flex form-config__config-options"},n("snk-config-options",{idConfig:i.name,messagesBuilder:this.messagesBuilder,dataUnit:this.dataUnit,fieldConfig:this._fieldConfigSelected,"data-element-id":this._element.getAttribute(r.DATA_ELEMENT_ID_ATTRIBUTE_NAME),onConfigOptionsChanged:i=>this.handleconfigOptionsChanged(i.detail)})))})):n("div",{class:"form-config__add-group-container"},n("div",{class:"form-config__add-group-content"},n("div",{class:"form-config__add-group-label"},n("label",{class:"ez-text ez-text--center ez-text--medium ez-text--primary ez-text--bold"},this.getMessage("snkFormConfig.form.labelDropField")))))}handleconfigOptionsChanged(i){var o;null===(o=this._formConfig.fields)||void 0===o||o.forEach((()=>{})),this._formConfigChanged=!0}closeFormConfig(){!0===this._formConfigChanged||!0===this._optionFormConfigChanged?this.openConfirmDialog(this.getMessage("snkFormConfig.confirm.exit")).then((i=>{i&&(this._formConfigChanged=!1,this.configClose.emit())})):this.configClose.emit()}openConfirmDialog(i="",o=this.getMessage("snkFormConfig.confirm.title")){return c.confirm(o,i)}controlMoveField(i){const o=null==i?void 0:i.target;null!=(null==o?void 0:o.closest('[data-draggable-element="field"]'))&&(this._mouseOnFieldConfig=!0,null!=(null==o?void 0:o.closest(".form-config__config-options"))||null!=(null==o?void 0:o.closest(".field-config__options"))?this._mouseOnConfigOptions=!0:!1===["minus","settings-inverted","chevron-up"].includes(null==o?void 0:o.iconName)&&this.controlFieldConfig())}controlStartDraggingField(i){var o,n,t;if(this._mouseOnConfigOptions)null==i||i.cancel(),this._mouseOnConfigOptions=!1;else{const s=null===(t=null===(n=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.dragEvent)||void 0===n?void 0:n.data)||void 0===t?void 0:t.sourceContainer;null!=s&&s.classList.add(this._fieldFloatingStyle)}}controlSortedDraggingField(i){var o,n,t,s,e,l,r,a;const d=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.oldContainer,c=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.newContainer,f=null===(e=null===(s=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.dragEvent)||void 0===s?void 0:s.data)||void 0===e?void 0:e.source,h=null===(a=null===(r=null===(l=null==i?void 0:i.data)||void 0===l?void 0:l.dragEvent)||void 0===r?void 0:r.data)||void 0===a?void 0:a.originalSource;null!=d&&null!=c&&null!=f&&null!=h&&(c.tagName!==_&&c.id!==z||d.id!==k?d.tagName!==_&&d.id!==z||c.id!==k||(f.className=this._fieldsAvailableStyle,f.querySelector("snk-field-config").modeInsertion=!0,h.className=this._fieldsAvailableStyle,h.querySelector("snk-field-config").modeInsertion=!0):(f.className=this._formFieldsStyle,f.querySelector("snk-field-config").modeInsertion=!1,h.className=this._formFieldsStyle,h.querySelector("snk-field-config").modeInsertion=!1))}isCancelDragAvailableField(i,o,n){var t,s;return null!=i&&null!=o&&null!=n&&(null===(t=n.data)||void 0===t?void 0:t.newIndex)!==(null===(s=n.data)||void 0===s?void 0:s.oldIndex)&&i.id===k&&o.id===i.id&&(n.cancel(),this._fieldsAvailable=[],setTimeout((()=>{this.buildAvailableFields()}),this._sortableTimer),!0)}isRemoveField(i,o,n){if(null==i||null==o||null==n)return!1;if((o.tagName===_||o.id===z)&&i.id===k){const i={detail:{field:n,type:m.remove}};return setTimeout((()=>{this.handleFieldConfigChange(i)}),this._renderTimer),!0}return!1}isAddOrMoveField(i,o,n,t){var s;return null!=i&&null!=o&&null!=n&&null!=t&&(t.newIndex!==t.oldIndex||o.dataset.groupName!==i.dataset.groupName||i.id===z&&o.id===k)&&(this.isFieldAvailable(i,o)&&(n.tab=null===(s=this._tabConfig)||void 0===s?void 0:s.selectedTab),n.group=i.dataset.groupName,setTimeout((()=>{i.id.includes(C)&&this.clearTempGroups(!0),this.updateFieldsToSave(o.dataset.groupName!==i.dataset.groupName||i.id===z&&o.id===k?this._sortableTimer:0)}),this._renderTimer),!0)}isFieldAvailable(i,o){return null!=i&&null!=o&&(i.tagName===_||i.id===z)&&o.id===k}controlStopDraggingField(i){var o,n,t,s,e,l;const r=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.oldContainer,a=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.newContainer;if(this.isCancelDragAvailableField(a,r,i))return;const d=null===(e=null===(s=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.dragEvent)||void 0===s?void 0:s.data)||void 0===e?void 0:e.originalSource,c=null===(l=null==d?void 0:d.querySelector("snk-field-config"))||void 0===l?void 0:l.fieldConfig;this.isRemoveField(a,r,c)||this.isAddOrMoveField(a,r,c,null==i?void 0:i.data)}updateFieldsToSave(i=0){const o=this.getFieldsToSave();(null==o?void 0:o.length)>0&&(this._formConfig.fields=o),this.loadFields(i),this._formConfigChanged=!0}controlSortableField(){null!=this._sortableContainer&&(this._sortableField&&this._sortableField.destroy(),this._sortableField=new e(this._sortableContainer.querySelectorAll('[data-draggable-parent="field"]'),{draggable:'[data-draggable-element="field"]',mirror:{constrainDimensions:!0},distance:h.dragStartDistance}),this._sortableField.on(g.dragStart,(i=>this.controlStartDraggingField(i))),this._sortableField.on(g.dragSorted,(i=>this.controlSortedDraggingField(i))),this._sortableField.on(g.dragStop,(i=>this.controlStopDraggingField(i))))}controlStartDraggingGroup(i){(this._mouseOnFieldConfig||this._editingTitleGroup)&&(null==i||i.cancel(),this._mouseOnFieldConfig=!1)}controlStopDraggingGroup(i){i.data.newIndex!==i.data.oldIndex&&setTimeout((()=>{this.updateFieldsToSave(this._sortableTimer)}),this._renderTimer)}controlSortableGroup(){null!=this._sortableContainer&&(this._sortableGroup&&this._sortableGroup.destroy(),this._sortableGroup=new e(this._sortableContainer.querySelectorAll('[data-draggable-parent="group"]'),{draggable:'[data-draggable-element="group"]',mirror:{constrainDimensions:!0},distance:h.dragStartDistance}),this._sortableGroup.on(g.dragStart,(i=>this.controlStartDraggingGroup(i))),this._sortableGroup.on(g.dragStop,(i=>this.controlStopDraggingGroup(i))))}loadUserConfig(){null!=this.configManager&&this.configManager.fetchUserAvailableConfigs().then((i=>{if(this._formConfigOptions=i,null==this._formConfigOptions)return;let o=null==this._formConfig||this._formConfig.defaultConfiguration;const n=i.find((i=>i.origin===(o?b.DEFAULT:b.USER)));this.setFormConfig(n)}))}setFormConfig(i){this._optionFormConfigSelected=i}controlSelectFormConfig(i){const o=null==i?void 0:i.detail,n=this._formConfigOptions.find((i=>i.origin===(null==o?void 0:o.value)));this.setFormConfig(n),this._optionFormConfigChanged=!0,this.loadConfigByUser()}changeTabOrder(i){const o=[],n=this._tabConfig.querySelectorAll(".tab-config__tab");this._tabSelected=i,n.forEach(((i,n)=>{var t;if(n){const s=null===(t=i.querySelector(".tab-config__tab-label"))||void 0===t?void 0:t.getAttribute("title");o.push({label:s,order:n-1})}})),this._layoutFormConfig.map((i=>{o.forEach((o=>{o.label===i.tab&&(o.visible=i.visible)}))})),o.length>0&&(this._formConfig.tabs=o,this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0)}async loadConfigByUser(){if(null==this.configManager)return;if(null==this._optionFormConfigSelected)return;let i;switch(this._optionFormConfigSelected.origin){case b.DEFAULT:case b.DEFAULT:i=await this.configManager.fetchDefaultConfig()}null!=i&&(this._formConfig=i,this._tabSelected=1,this.loadFields(this._sortableTimer),this.controlFieldConfig(),this.clearTempGroups())}loadConfig(i=0){this.loadFormConfig(i),this.loadUserConfig()}addNewGroup(){var i,o;const n=null===(i=this._tabConfig)||void 0===i?void 0:i.selectedTab;null==(null===(o=this._tempGroups)||void 0===o?void 0:o.find((i=>i.tab===n&&i.group.includes(this._labelNewGroup))))&&(this._tempGroups.push({tab:n,group:this.handleDuplicateGroups(this._labelNewGroup,this._tabConfig.selectedTab)}),this.loadFields(),this.controlFieldConfig(),this._formConfigChanged=!0)}clearTempGroups(i=!1){var o;(null===(o=this._tempGroups)||void 0===o?void 0:o.length)>0&&(this._tempGroups=i?this._tempGroups.filter((i=>i.tab!==this._tabConfig.selectedTab)):[])}removeGroup(i){null!=i?this._tempGroups=this._tempGroups.filter(((o,n)=>n!==i&&o.tab===this._tabConfig.selectedTab||o.tab!==this._tabConfig.selectedTab)):this.updateFieldsToSave(this._sortableTimer)}checkGroupExists(i,o,n=!1){var t,s,e;const l=null===(t=this._tabConfig)||void 0===t?void 0:t.selectedTab,r=null===(s=this._layoutFormConfig)||void 0===s?void 0:s.find((i=>i.tab===l)),a=null===(e=null==r?void 0:r.groups)||void 0===e?void 0:e.map((i=>{var o;return null===(o=i.group)||void 0===o?void 0:o.toLowerCase()}));if(null==a?void 0:a.includes(null==i?void 0:i.toLowerCase())){const t=this.getMessage("snkFormConfig.confirm.title"),s=`\n ${this.getMessage("snkFormConfig.alert.titleGroupExists")}\n <b>${i}</b>\n ${this.getMessage("snkFormConfig.alert.inTab")}\n <b>${l===u.main?this.getMessage("snkFormConfig.form.mainArea"):l}</b>.\n <br/><br/>\n ${this.getMessage("snkFormConfig.alert.infoValidTitle")}\n `;return c.alert(t,s).then((()=>{var i,t;n?null===(i=this._newGroupBoxes[o])||void 0===i||i.applyFocusTextEdit():null===(t=this._currentGroupBoxes[l][o])||void 0===t||t.applyFocusTextEdit()})),!1}return!0}saveEditLabelTempGroup(i,o){const{newValue:n}=i.detail;null!=this._newGroupBoxes&&null!=this._newGroupBoxes[o]&&(this._newGroupBoxes[o].dataset.groupName=n)}saveEditLabelGroup(i){var o;const{value:n,newValue:t}=i.detail;null===(o=this._formConfig.fields)||void 0===o||o.forEach((i=>{i.group===n&&(i.group=t)})),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0}renderTempGroupByTab(i){return this._tempGroups.map(((o,t)=>{if(o.tab===i)return n("ez-collapsible-box",{ref:i=>this._newGroupBoxes[t]=i,id:`${C}-${t}`,editable:!0,removable:!0,"header-size":"large",label:o.group,"icon-placement":"left","data-group-name":o.group,"data-draggable-parent":"field",class:"form-config__add-group",onEzRemove:()=>this.removeGroup(t),onEzSaveEditLabel:i=>this.saveEditLabelTempGroup(i,t),onEzEditLabelMode:i=>this._editingTitleGroup=i.detail,conditionalSave:i=>this.checkGroupExists(i,t,!0)},this.getFieldsByGroup(o))}))}handleDuplicateGroups(i,o){var n;const t=this._layoutFormConfig[this._tabConfig.selectedIndex].groups.map((i=>i.group));return null!=t&&(null===(n=this._layoutFormConfig)||void 0===n||n.map((n=>{n.tab===o&&n.groups.some((o=>o.group===i))&&(i+=`${this.captureHighestValueTitle(t)}`)}))),i}captureHighestValueTitle(i){let o=[];return null==i||i.map((i=>{null!=i&&o.push(i.replace(/[^0-9]/g,""))})),Math.max.apply(null,o)>0?` (${Math.max.apply(null,o)+1})`:" (1)"}getLayoutFormConfig(){var i,o;if(null==(null===(i=this._formConfig)||void 0===i?void 0:i.fields))return;let n=[],t=[];for(const i of this._formConfig.fields)if(null==t.find((o=>i.name===o.name&&i.tab===o.tab))){t.push(i);const s=this.dataUnit.getField(i.name);if(null==s?void 0:s.visible){null!=i.label&&""!==i.label||(i.label=s.label),null!=i.tab&&""!==i.tab||(i.tab=this.getMessage("snkFormConfig.form.tabGeneral"));let t=n.find((o=>o.tab===i.tab));if(null==t){let s=null;if(null!=this._formConfig.tabs){const o=this._formConfig.tabs.filter((o=>o.label===i.tab));o.length>0&&(s=o[0].visible)}const e=(null===(o=i.tab)||void 0===o?void 0:o.label)||i.tab;t=null!==s?{tab:e,groups:[],visible:s}:{tab:e,groups:[],visible:!0},n.push(t)}const e=t.groups.find((o=>o.group===i.group));if(e)e.fields.push(i);else{const o={group:i.group,fields:[i]};void 0===i.group?t.groups.unshift(o):t.groups.push(o)}}}return n}configureTabs(i){var o;return null==(null===(o=this._formConfig)||void 0===o?void 0:o.tabs)?i:(null==i&&(i=[]),this._formConfig.tabs.map((o=>i.find((i=>{var n,t;return(null===(n=o.label)||void 0===n?void 0:n.toLowerCase())===(null===(t=i.tab)||void 0===t?void 0:t.toLowerCase())}))||{tab:o.label,groups:[],visible:o.visible})))}configureTabMain(i){return null==i&&(i=[]),null==i.find((i=>i.tab===u.main))&&i.unshift({tab:u.main,groups:[],visible:!0}),i}updateTabs(){const i=this.getTabsToSave();(null==i?void 0:i.length)>0&&(this._formConfig.tabs=i,1===i.length&&(this._tabSelected=0))}buildFormConfig(){var i;if(null==(null===(i=this._formConfig)||void 0===i?void 0:i.fields))return;let o=this.getLayoutFormConfig();o=this.configureTabs(o),o=this.configureTabMain(o),this._layoutFormConfig=o,this.updateTabs()}buildAvailableFields(){var i,o;if(null==(null===(i=this._formConfig)||void 0===i?void 0:i.fields))return;let n=[],t=this.dataUnit.metadata.fields;for(const i of this._formConfig.fields)n.push(i);const s=t.filter((({name:i,visible:o})=>!0===o&&!1===n.some((({name:o})=>o===i))));this._fieldsAvailable=s,this._listEnabledFields=s,null!=(null===(o=this._filterFieldsAvailable)||void 0===o?void 0:o.value)&&this.onFilterChange(this._filterFieldsAvailable.value)}changeTabSelected(i){this._tabSelected=i.index;const o=this._formContainer.querySelector("div#tab"+i.index);this._formContainer.querySelectorAll(".form-config__tab-content").forEach((i=>i.className="form-config__hide-content sc-snk-form-config")),o&&(o.className="form-config__tab-content ez-flex ez-flex--column ez-size-width--full ez-padding--medium sc-snk-form-config")}onFilterChange(i){this._fieldsAvailable=a.applyStringFilter(i,this._listEnabledFields,!0,"label")}orderFieldsAvailable(i){return a.sortAlphabetically(i)}handleLabelCounter(i){const o=[this.getMessage("snkFormConfig.availableFields.labelNoFields"),this.getMessage("snkFormConfig.availableFields.labelOneField")];return i>1?`${i} ${this.getMessage("snkFormConfig.availableFields.labelAvailableFields")}`:o[i]}controlAddFieldConfig(i){var o;if(this._formConfigChanged=!1,null==i)return;null==this._formConfig.fields&&(this._formConfig.fields=[]);const n=this._formConfig.fields.filter((o=>o.name===i.name&&o.tab&&i.tab));n.length>0?n.forEach((o=>{o.name=i.name,o.label=i.label,o.required=i.required,o.readOnly=i.readOnly,o.group=i.group})):this._formConfig.fields.push({name:i.name,label:i.label,required:i.required,readOnly:i.readOnly,group:i.group,tab:null===(o=this._tabConfig)||void 0===o?void 0:o.selectedTab}),this.loadFields(),this.controlFieldConfig(),this._formConfigChanged=!0,this.resetSortables()}controlRemoveFieldConfig(i,o){var n;this._formConfigChanged=!1,null!=i&&(this._formConfig.fields=null===(n=this._formConfig.fields)||void 0===n?void 0:n.filter((o=>o.name!==i.name)),this.loadFields(o),this.controlFieldConfig(),this._formConfigChanged=!0,this.resetSortables())}resetSortables(){this.controlSortableField(),this.controlSortableGroup()}handleFieldConfigChange(i,o=0){const{field:n,type:t}=i.detail;t!==m.configuration?t!==m.remove?t!==m.add||this.controlAddFieldConfig(n):this.controlRemoveFieldConfig(n,o):this.controlFieldConfig(n)}changeTabLabel(i){var o,n;const{value:t,newValue:s}=i.detail.detail;null===(o=this._formConfig.fields)||void 0===o||o.forEach((i=>{i.tab===t&&(i.tab=s)})),null===(n=this._formConfig.tabs)||void 0===n||n.forEach((i=>{i.label===t&&(i.label=s)})),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0}handleDeleteTab(i){let o={canClose:!1,labelCancel:this.getMessage("snkFormConfig.confirm.labelCancel"),labelConfirm:this.getMessage("snkFormConfig.confirm.labelDelete"),btnConfirmDanger:!1};const n=this.getMessage("snkFormConfig.confirm.title"),t=this.getMessage("snkFormConfig.confirm.deleteTab")+` <b>${i.detail.label}</b>?`;c.confirm(n,t,null,f.WARN,o).then((o=>{var n;o&&(this._formConfig.tabs=null===(n=this._formConfig.tabs)||void 0===n?void 0:n.filter((o=>o.label!==i.detail.label)),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0)}))}changeHideTab(i){var o;null===(o=this._formConfig.tabs)||void 0===o||o.forEach((o=>{o.label===i.detail.label&&(o.visible=!o.visible)})),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0}handleCanStartDragTab(){var i,o;const n=this._layoutFormConfig.map((i=>i.tab));for(const o of n)null===(i=this._currentGroupBoxes[o])||void 0===i||i.map((i=>null==i?void 0:i.cancelEdition()));null===(o=this._newGroupBoxes)||void 0===o||o.map((i=>null==i?void 0:i.cancelEdition()))}getMessage(i,o){return this.messagesBuilder.getMessage(i,o)}componentDidRender(){this.controlSortableField(),this.controlSortableGroup()}async componentWillRender(){if(null==this.messagesBuilder){const i=d.getContextValue("__SNK__APPLICATION__");this.messagesBuilder=i.messagesBuilder}}componentWillLoad(){this.loadConfig()}componentDidLoad(){r.addIDInfo(this._element,null,{dataUnit:this.dataUnit})}render(){var i,o,s,e;return n(t,null,n("div",{class:"ez-row ez-padding--medium"},n("div",{class:"ez-col ez-col--sd-7 ez-col--tb-9 ez-align--middle"},n("ez-button",{mode:"icon",title:this.getMessage("snkFormConfig.goBackTitle"),iconName:"arrow_back",class:"ez-padding--small",size:"small",onClick:()=>this.closeFormConfig(),id:"formConfigToBack"}),n("h1",{class:"ez-title ez-title--primary ez-title--extra-large ez-padding--small"},this.getMessage("snkFormConfig.title")),this._formConfigOptions&&n("ez-actions-button",{class:"form-config__actions-button ez-margin-left--medium",value:null===(i=this._optionFormConfigSelected)||void 0===i?void 0:i.origin,showLabel:!0,displayIcon:"chevron-down",checkOption:!0,size:"small",actions:this._formConfigOptions.map((i=>({value:i.origin,label:i.name}))),onEzAction:i=>this.controlSelectFormConfig(i),id:"selectConfig"})),n("div",{class:"ez-col ez-col--sd-5 ez-col--tb-3 ez-align--middle ez-align--right"},!0===this._formConfigChanged&&!1===this._optionFormConfigChanged&&n("div",{class:"ez-row ez-align--middle ez-align--right"},n("ez-button",{label:"Cancelar",class:"ez-padding-left--medium",size:"small",onClick:()=>this.cancelChangeConfig()}),n("ez-button",{label:"Salvar",class:"ez-button--primary ez-padding-left--medium",size:"small",onClick:()=>this.saveConfig()},n("ez-icon",{class:"ez-margin-right--small",slot:"leftIcon",iconName:"save"}))),!0===this._optionFormConfigChanged&&n("div",{class:"ez-row ez-align--middle ez-align--right"},n("ez-button",{label:"Cancelar",class:"ez-padding-left--medium",size:"small",onClick:()=>this.cancelChangeOptionConfig()}),n("ez-button",{label:this.getMessage("snkFormConfig.applyConfig"),class:"ez-button--primary ez-padding-left--medium",size:"small",onClick:()=>this.applyOptionConfig()})))),n("div",{class:"ez-row ez-padding--medium",ref:i=>this._sortableContainer=i},n("div",{class:"form-config__tab-container ez-col ez-col--sd-9 ez-col--tb-9 ez-padding-right--medium"},(null===(o=this._layoutFormConfig)||void 0===o?void 0:o.length)>0&&n("section",{class:"ez-box__container",ref:i=>this._formContainer=i},n("snk-tab-config",{ref:i=>this._tabConfig=i,selectedIndex:this._tabSelected,messagesBuilder:this.messagesBuilder,onEzTabChange:i=>this.changeTabSelected(i.detail),onEzOrderChange:i=>this.changeTabOrder(i.detail),onEditionTitleTab:i=>this.changeTabLabel(i),onDeleteTab:i=>this.handleDeleteTab(i),onHideTab:i=>this.changeHideTab(i),onCanStartDrag:()=>this.handleCanStartDragTab(),tabItems:this._layoutFormConfig.map((i=>({tabKey:i.tab,label:i.tab,visible:i.visible})))}),this._layoutFormConfig.map(((i,o)=>n("div",{id:"tab"+o,"data-draggable-parent":"group",class:this._tabSelected===o?"form-config__tab-content ez-flex ez-flex--column ez-size-width--full ez-padding--medium":"form-config__hide-content"},i.groups.map(((o,t)=>o.group?(null==this._currentGroupBoxes[i.tab]&&(this._currentGroupBoxes[i.tab]=[]),n("ez-collapsible-box",{ref:o=>this._currentGroupBoxes[i.tab][t]=o,editable:!0,removable:!0,"header-size":"large",label:o.group,"icon-placement":"left","data-group-name":o.group,"data-draggable-parent":"field","data-draggable-element":"group",onEzRemove:()=>this.removeGroup(),onEzSaveEditLabel:i=>this.saveEditLabelGroup(i),onEzEditLabelMode:i=>this._editingTitleGroup=i.detail,conditionalSave:i=>this.checkGroupExists(i,t)},this.getFieldsByGroup(o))):n("div",{class:"ez-flex ez-flex--column ez-size-width--full"},n("label",{class:"ez-text ez-text--secondary ez-margin-vertical--small"},this.getMessage("snkFormConfig.form.subTitleInfo")),n("div",{id:z,class:"ez-row","data-draggable-parent":"field"},this.getFieldsByGroup(o)),n("hr",{class:"ez-divider-horizontal ez-margin-vertical--medium"})))),this.renderTempGroupByTab(i.tab)))),n("div",{class:"form-config__btn-add-group ez-row"},n("div",{class:"form-config__btn-add-group-container ez-col ez-col--sd-12 ez-col--tb-12 ez-align--center"},n("ez-button",{label:this.getMessage("snkFormConfig.form.labelNewGroup"),class:"ez-padding-horizontal--small ez-button--primary",size:"small",onClick:()=>this.addNewGroup()},n("ez-icon",{class:"ez-margin-right--small",slot:"leftIcon",iconName:"plus"})))))),n("div",{class:"form-config__fields-available ez-col ez-col--sd-3 ez-col--tb-3"},n("section",{class:"ez-box__container ez-col ez-col--pn-12"},n("h1",{class:"ez-title ez-title--large ez-title--primary ez-padding-bottom--medium"},this.getMessage("snkFormConfig.availableFields.title")),n("ez-filter-input",{id:"searchFields",ref:i=>this._filterFieldsAvailable=i,label:this.getMessage("snkFormConfig.availableFields.labelSearchField"),onEzChange:i=>this.onFilterChange(i.detail)}),n("span",{class:"ez-box__label-counter ez-text ez-text--medium ez-text--primary ez-margin-bottom--medium"},this.handleLabelCounter(null===(s=this._fieldsAvailable)||void 0===s?void 0:s.length)),(null===(e=this._layoutFormConfig)||void 0===e?void 0:e.length)>0&&n("div",{id:k,class:"ez-row","data-draggable-parent":"field"},this.orderFieldsAvailable(this._fieldsAvailable).map((i=>n("div",{key:i.name,class:this._fieldsAvailableStyle,"data-draggable-element":"field",onMouseDown:i=>this.controlMoveField(i)},n("snk-field-config",{messagesBuilder:this.messagesBuilder,onEzClickIcon:i=>{this.handleFieldConfigChange(i)},dataUnit:this.dataUnit,fieldConfig:i,id:i.name})))))))))}get _element(){return s(this)}static get watchers(){return{configManager:["observeConfigManager"]}}};x.style=".sc-snk-form-config-h{--snk-form-config--z-index:var(--more-visible, 2);--snk-form-config--background-color:var(--background--xlight, #fff);--snk-form-config__icon--color:var(--text--disable, #AFB6C0);--snk-form-config__label-counter--font-weight:var(--text-weight--extra-small, 200);--snk-form-config__add-group-container--border-radius:var(--border--radius-medium, 12px);--snk-form-config__add-group-container--background-color:var(--background--medium, #d2dce9);--snk-form-config__add-group-container--padding:var(--space--small, 6px);--snk-form-config__add-group-content--border:2px dashed var(--color-strokes, #DCE0E8);--snk-form-config__add-group-content--border-radius:var(--border--radius-small, 6px);--snk-form-config__add-group-label--padding:var(--space--large, 24px);--snk-form-config__btn-add-group--padding:var(--space--large, 24px) var(--space--medium, 12px) 0;--snk-form-config__btn-add-group-container--padding:var(--space--medium, 12px);--snk-form-config__btn-add-group-container--border-radius:var(--border--radius-medium, 12px);--snk-form-config__btn-add-group-container--border:2px solid var(--color-strokes, #DCE0E8);--snk-form-config__btn-add-group-container--background-color:var(--background--body, #fafcff);display:flex;flex-direction:column;position:fixed;top:0;left:0;width:100%;height:100%;z-index:var(--snk-form-config--z-index);background-color:var(--snk-form-config--background-color)}.form-config__header-container.sc-snk-form-config{display:flex}.form-config__field-container.sc-snk-form-config{width:32%;padding:6px}.form-config__hide-content.sc-snk-form-config{display:none}ez-icon.sc-snk-form-config .left-icon.sc-snk-form-config{--ez-icon--color:var(--snk-form-config__icon--color)}.ez-box__label-counter.sc-snk-form-config{margin-top:-7px;font-weight:var(--snk-form-config__label-counter--font-weight)}.form-config__btn-options.sc-snk-form-config{--ez-button--min-width:300px;--ez-button--background-color:var(--snk-form-config--background-color)}[data-draggable-parent].sc-snk-form-config{position:relative}.form-config__field-config--selected.sc-snk-form-config{position:static}.form-config__field-config--dragged.sc-snk-form-config .draggable-mirror.sc-snk-form-config{z-index:var(--snk-form-config--z-index)}.form-config__config-options.sc-snk-form-config{position:relative;margin-top:-3px;min-width:100%;z-index:1}.form-config__tab-container.sc-snk-form-config,.form-config__fields-available.sc-snk-form-config{position:relative;height:100%;max-height:calc(100vh - 92px)}.form-config__tab-container.sc-snk-form-config .ez-box__container.sc-snk-form-config,.form-config__fields-available.sc-snk-form-config .ez-box__container.sc-snk-form-config{align-content:flex-start;height:100%}.form-config__fields-available.sc-snk-form-config [data-draggable-parent].sc-snk-form-config{align-content:flex-start;overflow-y:auto;height:100%;max-height:calc(100% - 122px)}.form-config__tab-content.sc-snk-form-config{align-content:flex-start;overflow-y:auto;height:auto;max-height:calc(100% - 128px)}[data-draggable-element].sc-snk-form-config{cursor:grab}.form-config__actions-button.sc-snk-form-config{--ez-actions-button__btn-action--min-width:235px}.form-config__add-group.sc-snk-form-config{position:relative;min-height:120px;margin-bottom:10px}.form-config__add-group-container.sc-snk-form-config{position:absolute;display:flex;flex-wrap:wrap;width:100%;box-sizing:border-box;border-radius:var(--snk-form-config__add-group-container--border-radius);background-color:var(--snk-form-config__add-group-container--background-color);padding:var(--snk-form-config__add-group-container--padding)}.form-config__add-group-content.sc-snk-form-config{width:100%;display:flex;flex-wrap:wrap;justify-content:center;align-items:center;box-sizing:border-box;border:var(--snk-form-config__add-group-content--border);border-radius:var(--snk-form-config__add-group-content--border-radius)}.form-config__add-group-label.sc-snk-form-config{display:flex;justify-content:center;box-sizing:border-box;padding:var(--snk-form-config__add-group-label--padding)}.form-config__btn-add-group.sc-snk-form-config{position:relative;padding:var(--snk-form-config__btn-add-group--padding)}.form-config__btn-add-group-container.sc-snk-form-config{padding:var(--snk-form-config__btn-add-group-container--padding);border-radius:var(--snk-form-config__btn-add-group-container--border-radius);border:var(--snk-form-config__btn-add-group-container--border);background-color:var(--snk-form-config__btn-add-group-container--background-color)}ez-collapsible-box.draggable-mirror.sc-snk-form-config{display:table;background-color:var(--snk-form-config--background-color)}ez-collapsible-box.sc-snk-form-config{margin-bottom:10px}@media screen and (min-width: 480px){.form-config__field-config--selected.sc-snk-form-config .ez-flex.form-config__config-options.sc-snk-form-config{min-width:calc(300% + 12px)}.form-config__field-config--selected.sc-snk-form-config:nth-child(3n+2) .ez-flex.form-config__config-options.sc-snk-form-config{left:calc(100% / 1 * -1)}.form-config__field-config--selected.sc-snk-form-config:nth-child(3n+3) .ez-flex.form-config__config-options.sc-snk-form-config{left:calc(100% / 1 * -2)}}";export{x as snk_form_config}
1
+ import{r as i,c as o,h as n,H as t,g as s}from"./p-d2d301a6.js";import{S as e}from"./p-fa816fb2.js";import{ObjectUtils as l,ElementIDUtils as r,ArrayUtils as a,ApplicationContext as d}from"@sankhyalabs/core";import{ApplicationUtils as c,DialogType as f}from"@sankhyalabs/ezui/dist/collection/utils";import{C as h,a as g,T as u,A as m,D as v}from"./p-b0ef4383.js";import{U as b}from"./p-181975f1.js";import{buildFormConfigFromDataUnit as p}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-594bc21d.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const _="EZ-COLLAPSIBLE-BOX",z="fieldsWithoutGroupContainer",k="fieldsAvailableContainer",C="addNewGroupContainer",x=class{constructor(n){i(this,n),this.configChange=o(this,"configChange",7),this.configClose=o(this,"configClose",7),this._listEnabledFields=[],this._renderTimer=500,this._tabSelected=1,this._labelNewGroup="Novo grupo",this._mouseOnFieldConfig=!1,this._mouseOnConfigOptions=!1,this._editingTitleGroup=!1,this._newGroupBoxes=[],this._currentGroupBoxes=[],this._formFieldsStyle="ez-col ez-col--sd-12 ez-col--tb-4 ez-padding-right--small ez-padding-bottom--medium sc-snk-form-config",this._fieldsAvailableStyle="ez-col ez-col--sd-12 ez-col--tb-12 ez-margin-bottom--medium ez-margin-right--medium sc-snk-form-config",this._fieldFloatingStyle="form-config__field-config--dragged",this._sortableTimer=100,this._formConfigOptions=[],this._fieldConfigSelected=void 0,this._layoutFormConfig=void 0,this._fieldsAvailable=void 0,this._formConfig={},this._formConfigChanged=!1,this._optionFormConfigSelected=void 0,this._optionFormConfigChanged=!1,this._tempGroups=[],this.dataUnit=void 0,this.configManager=void 0,this.messagesBuilder=void 0}observeConfigManager(){this.loadConfig(this._sortableTimer)}loadFields(i=0){this._layoutFormConfig=[],i>0?setTimeout((()=>{this.buildFields()}),i):this.buildFields()}buildFields(){this.buildFormConfig(),this.buildAvailableFields()}loadFormConfig(i){var o;this._formConfig=this.getConfig(),this.loadFields(i),this.controlFieldConfig(),null!=(null===(o=this._filterFieldsAvailable)||void 0===o?void 0:o.value)&&(this._filterFieldsAvailable.value="")}getConfig(){let i=this.configManager.getConfig(this.dataUnit);return i.fields&&0===i.fields.length&&(i=void 0),null==i&&(i=p(this.dataUnit)),l.copy(i)}cancelChangeConfig(){!0===this._formConfigChanged?this.openConfirmDialog(this.getMessage("snkFormConfig.confirm.cancel")).then((i=>{i&&(this._formConfigChanged=!1,this.resetChangeConfig())})):this.resetChangeConfig()}cancelChangeOptionConfig(){!0===this._optionFormConfigChanged?this.openConfirmDialog(this.getMessage("snkFormConfig.confirm.cancel")).then((i=>{i&&(this._optionFormConfigChanged=!1,this.resetChangeOptionConfig())})):this.resetChangeOptionConfig()}resetChangeConfig(){this.loadFormConfig(this._sortableTimer),this.clearTempGroups()}resetChangeOptionConfig(){this._formConfigChanged=!1,this.loadConfig(this._sortableTimer),this.clearTempGroups()}getTabsToSave(){return this._layoutFormConfig.map(((i,o)=>({label:i.tab,order:o,visible:i.visible})))}getFieldsToSave(){const i=[];return this._formContainer.querySelectorAll("snk-field-config").forEach((o=>{const n=o.fieldConfig;if(null==n)return;const t={cleanOnCopy:n.cleanOnCopy||!1,group:n.group,label:n.label,name:n.name,required:n.required,readOnly:n.readOnly,tab:n.tab};null!=n.defaultValue&&(t.defaultValue=null==n.defaultValue.type?{type:v.fixed,value:n.defaultValue}:n.defaultValue),i.push(t)})),i}isDefaultConfiguration(){var i;return(null===(i=this._optionFormConfigSelected)||void 0===i?void 0:i.origin)===b.DEFAULT&&!0===this._optionFormConfigChanged&&!1===this._formConfigChanged}buildConfigToSave(){let i={};const o=this.isDefaultConfiguration();if(i=o?this.getConfig():l.copy(this._formConfig),!1===o){const o=this.getTabsToSave();(null==o?void 0:o.length)>0&&(i.tabs=o);const n=this.getFieldsToSave();(null==n?void 0:n.length)>0&&(i.fields=n)}return i.defaultConfiguration=o,i}saveConfig(){var i;(null===(i=this._tempGroups)||void 0===i?void 0:i.length)>0?c.alert(this.getMessage("snkFormConfig.confirm.title"),this.getMessage("snkFormConfig.confirm.group")):(this._formConfigChanged=!1,this._optionFormConfigChanged=!1,this.configManager.saveConfig(this.buildConfigToSave()).then((i=>{c.info(this.getMessage("snkFormConfig.info.successfullyConfigSaved"),{iconName:"check"}),this.configChange.emit(i)})))}applyOptionConfig(){if(!0===this._optionFormConfigChanged&&null!=this._optionFormConfigSelected){const i=this._optionFormConfigSelected.name||"configuração selecionada",o=this._optionFormConfigSelected.origin===b.DEFAULT?"pessoal":"padrão",n=this.getMessage("snkFormConfig.confirm.apply").replace("{0}",i).replace("{1}",o);this.openConfirmDialog(n).then((i=>{i&&this.saveConfig()}))}else this.saveConfig()}controlFieldConfig(i){var o;this._fieldConfigSelected=null!=i?(null===(o=this._fieldConfigSelected)||void 0===o?void 0:o.name)===(null==i?void 0:i.name)?void 0:i:void 0}getFieldConfigStyle(i){var o;return this._formFieldsStyle+((null===(o=this._fieldConfigSelected)||void 0===o?void 0:o.name)===i.name?" form-config__field-config--selected":"")}getFieldsByGroup(i){var o;return(null===(o=i.fields)||void 0===o?void 0:o.length)?i.fields.map((i=>{var o,t;return n("div",{key:i.name,class:this.getFieldConfigStyle(i),"data-draggable-element":"field",onMouseDown:i=>this.controlMoveField(i)},n("snk-field-config",{messagesBuilder:this.messagesBuilder,onEzClickIcon:i=>{this.handleFieldConfigChange(i)},modeInsertion:!1,fieldConfig:i,dataUnit:this.dataUnit,isConfigActive:(null===(o=this._fieldConfigSelected)||void 0===o?void 0:o.name)===i.name,id:i.name,key:i.name}),(null===(t=this._fieldConfigSelected)||void 0===t?void 0:t.name)===i.name&&n("div",{class:"ez-flex form-config__config-options"},n("snk-config-options",{idConfig:i.name,messagesBuilder:this.messagesBuilder,dataUnit:this.dataUnit,fieldConfig:this._fieldConfigSelected,"data-element-id":this._element.getAttribute(r.DATA_ELEMENT_ID_ATTRIBUTE_NAME),onConfigOptionsChanged:i=>this.handleconfigOptionsChanged(i.detail)})))})):n("div",{class:"form-config__add-group-container"},n("div",{class:"form-config__add-group-content"},n("div",{class:"form-config__add-group-label"},n("label",{class:"ez-text ez-text--center ez-text--medium ez-text--primary ez-text--bold"},this.getMessage("snkFormConfig.form.labelDropField")))))}handleconfigOptionsChanged(i){var o;null===(o=this._formConfig.fields)||void 0===o||o.forEach((()=>{})),this._formConfigChanged=!0}closeFormConfig(){!0===this._formConfigChanged||!0===this._optionFormConfigChanged?this.openConfirmDialog(this.getMessage("snkFormConfig.confirm.exit")).then((i=>{i&&(this._formConfigChanged=!1,this.configClose.emit())})):this.configClose.emit()}openConfirmDialog(i="",o=this.getMessage("snkFormConfig.confirm.title")){return c.confirm(o,i)}controlMoveField(i){const o=null==i?void 0:i.target;null!=(null==o?void 0:o.closest('[data-draggable-element="field"]'))&&(this._mouseOnFieldConfig=!0,null!=(null==o?void 0:o.closest(".form-config__config-options"))||null!=(null==o?void 0:o.closest(".field-config__options"))?this._mouseOnConfigOptions=!0:!1===["minus","settings-inverted","chevron-up"].includes(null==o?void 0:o.iconName)&&this.controlFieldConfig())}controlStartDraggingField(i){var o,n,t;if(this._mouseOnConfigOptions)null==i||i.cancel(),this._mouseOnConfigOptions=!1;else{const s=null===(t=null===(n=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.dragEvent)||void 0===n?void 0:n.data)||void 0===t?void 0:t.sourceContainer;null!=s&&s.classList.add(this._fieldFloatingStyle)}}controlSortedDraggingField(i){var o,n,t,s,e,l,r,a;const d=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.oldContainer,c=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.newContainer,f=null===(e=null===(s=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.dragEvent)||void 0===s?void 0:s.data)||void 0===e?void 0:e.source,h=null===(a=null===(r=null===(l=null==i?void 0:i.data)||void 0===l?void 0:l.dragEvent)||void 0===r?void 0:r.data)||void 0===a?void 0:a.originalSource;null!=d&&null!=c&&null!=f&&null!=h&&(c.tagName!==_&&c.id!==z||d.id!==k?d.tagName!==_&&d.id!==z||c.id!==k||(f.className=this._fieldsAvailableStyle,f.querySelector("snk-field-config").modeInsertion=!0,h.className=this._fieldsAvailableStyle,h.querySelector("snk-field-config").modeInsertion=!0):(f.className=this._formFieldsStyle,f.querySelector("snk-field-config").modeInsertion=!1,h.className=this._formFieldsStyle,h.querySelector("snk-field-config").modeInsertion=!1))}isCancelDragAvailableField(i,o,n){var t,s;return null!=i&&null!=o&&null!=n&&(null===(t=n.data)||void 0===t?void 0:t.newIndex)!==(null===(s=n.data)||void 0===s?void 0:s.oldIndex)&&i.id===k&&o.id===i.id&&(n.cancel(),this._fieldsAvailable=[],setTimeout((()=>{this.buildAvailableFields()}),this._sortableTimer),!0)}isRemoveField(i,o,n){if(null==i||null==o||null==n)return!1;if((o.tagName===_||o.id===z)&&i.id===k){const i={detail:{field:n,type:m.remove}};return setTimeout((()=>{this.handleFieldConfigChange(i)}),this._renderTimer),!0}return!1}isAddOrMoveField(i,o,n,t){var s;return null!=i&&null!=o&&null!=n&&null!=t&&(t.newIndex!==t.oldIndex||o.dataset.groupName!==i.dataset.groupName||i.id===z&&o.id===k)&&(this.isFieldAvailable(i,o)&&(n.tab=null===(s=this._tabConfig)||void 0===s?void 0:s.selectedTab),n.group=i.dataset.groupName,setTimeout((()=>{i.id.includes(C)&&this.clearTempGroups(!0),this.updateFieldsToSave(o.dataset.groupName!==i.dataset.groupName||i.id===z&&o.id===k?this._sortableTimer:0)}),this._renderTimer),!0)}isFieldAvailable(i,o){return null!=i&&null!=o&&(i.tagName===_||i.id===z)&&o.id===k}controlStopDraggingField(i){var o,n,t,s,e,l;const r=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.oldContainer,a=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.newContainer;if(this.isCancelDragAvailableField(a,r,i))return;const d=null===(e=null===(s=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.dragEvent)||void 0===s?void 0:s.data)||void 0===e?void 0:e.originalSource,c=null===(l=null==d?void 0:d.querySelector("snk-field-config"))||void 0===l?void 0:l.fieldConfig;this.isRemoveField(a,r,c)||this.isAddOrMoveField(a,r,c,null==i?void 0:i.data)}updateFieldsToSave(i=0){const o=this.getFieldsToSave();(null==o?void 0:o.length)>0&&(this._formConfig.fields=o),this.loadFields(i),this._formConfigChanged=!0}controlSortableField(){null!=this._sortableContainer&&(this._sortableField&&this._sortableField.destroy(),this._sortableField=new e(this._sortableContainer.querySelectorAll('[data-draggable-parent="field"]'),{draggable:'[data-draggable-element="field"]',mirror:{constrainDimensions:!0},distance:h.dragStartDistance}),this._sortableField.on(g.dragStart,(i=>this.controlStartDraggingField(i))),this._sortableField.on(g.dragSorted,(i=>this.controlSortedDraggingField(i))),this._sortableField.on(g.dragStop,(i=>this.controlStopDraggingField(i))))}controlStartDraggingGroup(i){(this._mouseOnFieldConfig||this._editingTitleGroup)&&(null==i||i.cancel(),this._mouseOnFieldConfig=!1)}controlStopDraggingGroup(i){i.data.newIndex!==i.data.oldIndex&&setTimeout((()=>{this.updateFieldsToSave(this._sortableTimer)}),this._renderTimer)}controlSortableGroup(){null!=this._sortableContainer&&(this._sortableGroup&&this._sortableGroup.destroy(),this._sortableGroup=new e(this._sortableContainer.querySelectorAll('[data-draggable-parent="group"]'),{draggable:'[data-draggable-element="group"]',mirror:{constrainDimensions:!0},distance:h.dragStartDistance}),this._sortableGroup.on(g.dragStart,(i=>this.controlStartDraggingGroup(i))),this._sortableGroup.on(g.dragStop,(i=>this.controlStopDraggingGroup(i))))}loadUserConfig(){null!=this.configManager&&this.configManager.fetchUserAvailableConfigs().then((i=>{if(this._formConfigOptions=i,null==this._formConfigOptions)return;let o=null==this._formConfig||this._formConfig.defaultConfiguration;const n=i.find((i=>i.origin===(o?b.DEFAULT:b.USER)));this.setFormConfig(n)}))}setFormConfig(i){this._optionFormConfigSelected=i}controlSelectFormConfig(i){const o=null==i?void 0:i.detail,n=this._formConfigOptions.find((i=>i.origin===(null==o?void 0:o.value)));this.setFormConfig(n),this._optionFormConfigChanged=!0,this.loadConfigByUser()}changeTabOrder(i){const o=[],n=this._tabConfig.querySelectorAll(".tab-config__tab");this._tabSelected=i,n.forEach(((i,n)=>{var t;if(n){const s=null===(t=i.querySelector(".tab-config__tab-label"))||void 0===t?void 0:t.getAttribute("title");o.push({label:s,order:n-1})}})),this._layoutFormConfig.map((i=>{o.forEach((o=>{o.label===i.tab&&(o.visible=i.visible)}))})),o.length>0&&(this._formConfig.tabs=o,this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0)}async loadConfigByUser(){if(null==this.configManager)return;if(null==this._optionFormConfigSelected)return;let i;switch(this._optionFormConfigSelected.origin){case b.DEFAULT:case b.DEFAULT:i=await this.configManager.fetchDefaultConfig()}null!=i&&(this._formConfig=i,this._tabSelected=1,this.loadFields(this._sortableTimer),this.controlFieldConfig(),this.clearTempGroups())}loadConfig(i=0){this.loadFormConfig(i),this.loadUserConfig()}addNewGroup(){var i,o;const n=null===(i=this._tabConfig)||void 0===i?void 0:i.selectedTab;null==(null===(o=this._tempGroups)||void 0===o?void 0:o.find((i=>i.tab===n&&i.group.includes(this._labelNewGroup))))&&(this._tempGroups.push({tab:n,group:this.handleDuplicateGroups(this._labelNewGroup,this._tabConfig.selectedTab)}),this.loadFields(),this.controlFieldConfig(),this._formConfigChanged=!0)}clearTempGroups(i=!1){var o;(null===(o=this._tempGroups)||void 0===o?void 0:o.length)>0&&(this._tempGroups=i?this._tempGroups.filter((i=>i.tab!==this._tabConfig.selectedTab)):[])}removeGroup(i){null!=i?this._tempGroups=this._tempGroups.filter(((o,n)=>n!==i&&o.tab===this._tabConfig.selectedTab||o.tab!==this._tabConfig.selectedTab)):this.updateFieldsToSave(this._sortableTimer)}checkGroupExists(i,o,n=!1){var t,s,e;const l=null===(t=this._tabConfig)||void 0===t?void 0:t.selectedTab,r=null===(s=this._layoutFormConfig)||void 0===s?void 0:s.find((i=>i.tab===l)),a=null===(e=null==r?void 0:r.groups)||void 0===e?void 0:e.map((i=>{var o;return null===(o=i.group)||void 0===o?void 0:o.toLowerCase()}));if(null==a?void 0:a.includes(null==i?void 0:i.toLowerCase())){const t=this.getMessage("snkFormConfig.confirm.title"),s=`\n ${this.getMessage("snkFormConfig.alert.titleGroupExists")}\n <b>${i}</b>\n ${this.getMessage("snkFormConfig.alert.inTab")}\n <b>${l===u.main?this.getMessage("snkFormConfig.form.mainArea"):l}</b>.\n <br/><br/>\n ${this.getMessage("snkFormConfig.alert.infoValidTitle")}\n `;return c.alert(t,s).then((()=>{var i,t;n?null===(i=this._newGroupBoxes[o])||void 0===i||i.applyFocusTextEdit():null===(t=this._currentGroupBoxes[l][o])||void 0===t||t.applyFocusTextEdit()})),!1}return!0}saveEditLabelTempGroup(i,o){const{newValue:n}=i.detail;null!=this._newGroupBoxes&&null!=this._newGroupBoxes[o]&&(this._newGroupBoxes[o].dataset.groupName=n)}saveEditLabelGroup(i){var o;const{value:n,newValue:t}=i.detail;null===(o=this._formConfig.fields)||void 0===o||o.forEach((i=>{i.group===n&&(i.group=t)})),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0}renderTempGroupByTab(i){return this._tempGroups.map(((o,t)=>{if(o.tab===i)return n("ez-collapsible-box",{ref:i=>this._newGroupBoxes[t]=i,id:`${C}-${t}`,editable:!0,removable:!0,"header-size":"large",label:o.group,"icon-placement":"left","data-group-name":o.group,"data-draggable-parent":"field",class:"form-config__add-group",onEzRemove:()=>this.removeGroup(t),onEzSaveEditLabel:i=>this.saveEditLabelTempGroup(i,t),onEzEditLabelMode:i=>this._editingTitleGroup=i.detail,conditionalSave:i=>this.checkGroupExists(i,t,!0)},this.getFieldsByGroup(o))}))}handleDuplicateGroups(i,o){var n;const t=this._layoutFormConfig[this._tabConfig.selectedIndex].groups.map((i=>i.group));return null!=t&&(null===(n=this._layoutFormConfig)||void 0===n||n.map((n=>{n.tab===o&&n.groups.some((o=>o.group===i))&&(i+=`${this.captureHighestValueTitle(t)}`)}))),i}captureHighestValueTitle(i){let o=[];return null==i||i.map((i=>{null!=i&&o.push(i.replace(/[^0-9]/g,""))})),Math.max.apply(null,o)>0?` (${Math.max.apply(null,o)+1})`:" (1)"}getLayoutFormConfig(){var i,o;if(null==(null===(i=this._formConfig)||void 0===i?void 0:i.fields))return;let n=[],t=[];for(const i of this._formConfig.fields)if(null==t.find((o=>i.name===o.name&&i.tab===o.tab))){t.push(i);const s=this.dataUnit.getField(i.name);if(null==s?void 0:s.visible){null!=i.label&&""!==i.label||(i.label=s.label),null!=i.tab&&""!==i.tab||(i.tab=this.getMessage("snkFormConfig.form.tabGeneral"));let t=n.find((o=>o.tab===i.tab));if(null==t){let s=null;if(null!=this._formConfig.tabs){const o=this._formConfig.tabs.filter((o=>o.label===i.tab));o.length>0&&(s=o[0].visible)}const e=(null===(o=i.tab)||void 0===o?void 0:o.label)||i.tab;t=null!==s?{tab:e,groups:[],visible:s}:{tab:e,groups:[],visible:!0},n.push(t)}const e=t.groups.find((o=>o.group===i.group));if(e)e.fields.push(i);else{const o={group:i.group,fields:[i]};void 0===i.group?t.groups.unshift(o):t.groups.push(o)}}}return n}configureTabs(i){var o;return null==(null===(o=this._formConfig)||void 0===o?void 0:o.tabs)?i:(null==i&&(i=[]),this._formConfig.tabs.map((o=>i.find((i=>{var n,t;return(null===(n=o.label)||void 0===n?void 0:n.toLowerCase())===(null===(t=i.tab)||void 0===t?void 0:t.toLowerCase())}))||{tab:o.label,groups:[],visible:o.visible})))}configureTabMain(i){return null==i&&(i=[]),null==i.find((i=>i.tab===u.main))&&i.unshift({tab:u.main,groups:[],visible:!0}),i}updateTabs(){const i=this.getTabsToSave();(null==i?void 0:i.length)>0&&(this._formConfig.tabs=i,1===i.length&&(this._tabSelected=0))}buildFormConfig(){var i;if(null==(null===(i=this._formConfig)||void 0===i?void 0:i.fields))return;let o=this.getLayoutFormConfig();o=this.configureTabs(o),o=this.configureTabMain(o),this._layoutFormConfig=o,this.updateTabs()}buildAvailableFields(){var i,o;if(null==(null===(i=this._formConfig)||void 0===i?void 0:i.fields))return;let n=[],t=this.dataUnit.metadata.fields;for(const i of this._formConfig.fields)n.push(i);const s=t.filter((({name:i,visible:o})=>!0===o&&!1===n.some((({name:o})=>o===i))));this._fieldsAvailable=s,this._listEnabledFields=s,null!=(null===(o=this._filterFieldsAvailable)||void 0===o?void 0:o.value)&&this.onFilterChange(this._filterFieldsAvailable.value)}changeTabSelected(i){this._tabSelected=i.index;const o=this._formContainer.querySelector("div#tab"+i.index);this._formContainer.querySelectorAll(".form-config__tab-content").forEach((i=>i.className="form-config__hide-content sc-snk-form-config")),o&&(o.className="form-config__tab-content ez-flex ez-flex--column ez-size-width--full ez-padding--medium sc-snk-form-config")}onFilterChange(i){this._fieldsAvailable=a.applyStringFilter(i,this._listEnabledFields,!0,"label")}orderFieldsAvailable(i){return a.sortAlphabetically(i)}handleLabelCounter(i){const o=[this.getMessage("snkFormConfig.availableFields.labelNoFields"),this.getMessage("snkFormConfig.availableFields.labelOneField")];return i>1?`${i} ${this.getMessage("snkFormConfig.availableFields.labelAvailableFields")}`:o[i]}controlAddFieldConfig(i){var o;if(this._formConfigChanged=!1,null==i)return;null==this._formConfig.fields&&(this._formConfig.fields=[]);const n=this._formConfig.fields.filter((o=>o.name===i.name&&o.tab&&i.tab));n.length>0?n.forEach((o=>{o.name=i.name,o.label=i.label,o.required=i.required,o.readOnly=i.readOnly,o.group=i.group})):this._formConfig.fields.push({name:i.name,label:i.label,required:i.required,readOnly:i.readOnly,group:i.group,tab:null===(o=this._tabConfig)||void 0===o?void 0:o.selectedTab}),this.loadFields(),this.controlFieldConfig(),this._formConfigChanged=!0,this.resetSortables()}controlRemoveFieldConfig(i,o){var n;this._formConfigChanged=!1,null!=i&&(this._formConfig.fields=null===(n=this._formConfig.fields)||void 0===n?void 0:n.filter((o=>o.name!==i.name)),this.loadFields(o),this.controlFieldConfig(),this._formConfigChanged=!0,this.resetSortables())}resetSortables(){this.controlSortableField(),this.controlSortableGroup()}handleFieldConfigChange(i,o=0){const{field:n,type:t}=i.detail;t!==m.configuration?t!==m.remove?t!==m.add||this.controlAddFieldConfig(n):this.controlRemoveFieldConfig(n,o):this.controlFieldConfig(n)}changeTabLabel(i){var o,n;const{value:t,newValue:s}=i.detail.detail;null===(o=this._formConfig.fields)||void 0===o||o.forEach((i=>{i.tab===t&&(i.tab=s)})),null===(n=this._formConfig.tabs)||void 0===n||n.forEach((i=>{i.label===t&&(i.label=s)})),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0}handleDeleteTab(i){let o={canClose:!1,labelCancel:this.getMessage("snkFormConfig.confirm.labelCancel"),labelConfirm:this.getMessage("snkFormConfig.confirm.labelDelete"),btnConfirmDanger:!1};const n=this.getMessage("snkFormConfig.confirm.title"),t=this.getMessage("snkFormConfig.confirm.deleteTab")+` <b>${i.detail.label}</b>?`;c.confirm(n,t,null,f.WARN,o).then((o=>{var n;o&&(this._formConfig.tabs=null===(n=this._formConfig.tabs)||void 0===n?void 0:n.filter((o=>o.label!==i.detail.label)),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0)}))}changeHideTab(i){var o;null===(o=this._formConfig.tabs)||void 0===o||o.forEach((o=>{o.label===i.detail.label&&(o.visible=!o.visible)})),this.loadFields(this._sortableTimer),this.controlFieldConfig(),this._formConfigChanged=!0}handleCanStartDragTab(){var i,o;const n=this._layoutFormConfig.map((i=>i.tab));for(const o of n)null===(i=this._currentGroupBoxes[o])||void 0===i||i.map((i=>null==i?void 0:i.cancelEdition()));null===(o=this._newGroupBoxes)||void 0===o||o.map((i=>null==i?void 0:i.cancelEdition()))}getMessage(i,o){return this.messagesBuilder.getMessage(i,o)}componentDidRender(){this.controlSortableField(),this.controlSortableGroup()}async componentWillRender(){if(null==this.messagesBuilder){const i=d.getContextValue("__SNK__APPLICATION__");this.messagesBuilder=i.messagesBuilder}}componentWillLoad(){this.loadConfig()}componentDidLoad(){r.addIDInfo(this._element,null,{dataUnit:this.dataUnit})}render(){var i,o,s,e;return n(t,null,n("div",{class:"ez-row ez-padding--medium"},n("div",{class:"ez-col ez-col--sd-7 ez-col--tb-9 ez-align--middle"},n("ez-button",{mode:"icon",title:this.getMessage("snkFormConfig.goBackTitle"),iconName:"arrow_back",class:"ez-padding--small",size:"small",onClick:()=>this.closeFormConfig(),id:"formConfigToBack"}),n("h1",{class:"ez-title ez-title--primary ez-title--extra-large ez-padding--small"},this.getMessage("snkFormConfig.title")),this._formConfigOptions&&n("ez-actions-button",{class:"form-config__actions-button ez-margin-left--medium",value:null===(i=this._optionFormConfigSelected)||void 0===i?void 0:i.origin,showLabel:!0,displayIcon:"chevron-down",checkOption:!0,size:"small",actions:this._formConfigOptions.map((i=>({value:i.origin,label:i.name}))),onEzAction:i=>this.controlSelectFormConfig(i),id:"selectConfig"})),n("div",{class:"ez-col ez-col--sd-5 ez-col--tb-3 ez-align--middle ez-align--right"},!0===this._formConfigChanged&&!1===this._optionFormConfigChanged&&n("div",{class:"ez-row ez-align--middle ez-align--right"},n("ez-button",{label:"Cancelar",class:"ez-padding-left--medium",size:"small",onClick:()=>this.cancelChangeConfig()}),n("ez-button",{label:"Salvar",class:"ez-button--primary ez-padding-left--medium",size:"small",onClick:()=>this.saveConfig()},n("ez-icon",{class:"ez-margin-right--small",slot:"leftIcon",iconName:"save"}))),!0===this._optionFormConfigChanged&&n("div",{class:"ez-row ez-align--middle ez-align--right"},n("ez-button",{label:"Cancelar",class:"ez-padding-left--medium",size:"small",onClick:()=>this.cancelChangeOptionConfig()}),n("ez-button",{label:this.getMessage("snkFormConfig.applyConfig"),class:"ez-button--primary ez-padding-left--medium",size:"small",onClick:()=>this.applyOptionConfig()})))),n("div",{class:"ez-row ez-padding--medium",ref:i=>this._sortableContainer=i},n("div",{class:"form-config__tab-container ez-col ez-col--sd-9 ez-col--tb-9 ez-padding-right--medium"},(null===(o=this._layoutFormConfig)||void 0===o?void 0:o.length)>0&&n("section",{class:"ez-box__container",ref:i=>this._formContainer=i},n("snk-tab-config",{ref:i=>this._tabConfig=i,selectedIndex:this._tabSelected,messagesBuilder:this.messagesBuilder,onEzTabChange:i=>this.changeTabSelected(i.detail),onEzOrderChange:i=>this.changeTabOrder(i.detail),onEditionTitleTab:i=>this.changeTabLabel(i),onDeleteTab:i=>this.handleDeleteTab(i),onHideTab:i=>this.changeHideTab(i),onCanStartDrag:()=>this.handleCanStartDragTab(),tabItems:this._layoutFormConfig.map((i=>({tabKey:i.tab,label:i.tab,visible:i.visible})))}),this._layoutFormConfig.map(((i,o)=>n("div",{id:"tab"+o,"data-draggable-parent":"group",class:this._tabSelected===o?"form-config__tab-content ez-flex ez-flex--column ez-size-width--full ez-padding--medium":"form-config__hide-content"},i.groups.map(((o,t)=>o.group?(null==this._currentGroupBoxes[i.tab]&&(this._currentGroupBoxes[i.tab]=[]),n("ez-collapsible-box",{ref:o=>this._currentGroupBoxes[i.tab][t]=o,editable:!0,removable:!0,"header-size":"large",label:o.group,"icon-placement":"left","data-group-name":o.group,"data-draggable-parent":"field","data-draggable-element":"group",onEzRemove:()=>this.removeGroup(),onEzSaveEditLabel:i=>this.saveEditLabelGroup(i),onEzEditLabelMode:i=>this._editingTitleGroup=i.detail,conditionalSave:i=>this.checkGroupExists(i,t)},this.getFieldsByGroup(o))):n("div",{class:"ez-flex ez-flex--column ez-size-width--full"},n("label",{class:"ez-text ez-text--secondary ez-margin-vertical--small"},this.getMessage("snkFormConfig.form.subTitleInfo")),n("div",{id:z,class:"ez-row","data-draggable-parent":"field"},this.getFieldsByGroup(o)),n("hr",{class:"ez-divider-horizontal ez-margin-vertical--medium"})))),this.renderTempGroupByTab(i.tab)))),n("div",{class:"form-config__btn-add-group ez-row"},n("div",{class:"form-config__btn-add-group-container ez-col ez-col--sd-12 ez-col--tb-12 ez-align--center"},n("ez-button",{label:this.getMessage("snkFormConfig.form.labelNewGroup"),class:"ez-padding-horizontal--small ez-button--primary",size:"small",onClick:()=>this.addNewGroup()},n("ez-icon",{class:"ez-margin-right--small",slot:"leftIcon",iconName:"plus"})))))),n("div",{class:"form-config__fields-available ez-col ez-col--sd-3 ez-col--tb-3"},n("section",{class:"ez-box__container ez-col ez-col--pn-12"},n("h1",{class:"ez-title ez-title--large ez-title--primary ez-padding-bottom--medium"},this.getMessage("snkFormConfig.availableFields.title")),n("ez-filter-input",{id:"searchFields",ref:i=>this._filterFieldsAvailable=i,label:this.getMessage("snkFormConfig.availableFields.labelSearchField"),onEzChange:i=>this.onFilterChange(i.detail)}),n("span",{class:"ez-box__label-counter ez-text ez-text--medium ez-text--primary ez-margin-bottom--medium"},this.handleLabelCounter(null===(s=this._fieldsAvailable)||void 0===s?void 0:s.length)),(null===(e=this._layoutFormConfig)||void 0===e?void 0:e.length)>0&&n("div",{id:k,class:"ez-row","data-draggable-parent":"field"},this.orderFieldsAvailable(this._fieldsAvailable).map((i=>n("div",{key:i.name,class:this._fieldsAvailableStyle,"data-draggable-element":"field",onMouseDown:i=>this.controlMoveField(i)},n("snk-field-config",{messagesBuilder:this.messagesBuilder,onEzClickIcon:i=>{this.handleFieldConfigChange(i)},dataUnit:this.dataUnit,fieldConfig:i,id:i.name})))))))))}get _element(){return s(this)}static get watchers(){return{configManager:["observeConfigManager"]}}};x.style=".sc-snk-form-config-h{--snk-form-config--z-index:var(--more-visible, 2);--snk-form-config--background-color:var(--background--xlight, #fff);--snk-form-config__icon--color:var(--text--disable, #AFB6C0);--snk-form-config__label-counter--font-weight:var(--text-weight--extra-small, 200);--snk-form-config__add-group-container--border-radius:var(--border--radius-medium, 12px);--snk-form-config__add-group-container--background-color:var(--background--medium, #d2dce9);--snk-form-config__add-group-container--padding:var(--space--small, 6px);--snk-form-config__add-group-content--border:2px dashed var(--color-strokes, #DCE0E8);--snk-form-config__add-group-content--border-radius:var(--border--radius-small, 6px);--snk-form-config__add-group-label--padding:var(--space--large, 24px);--snk-form-config__btn-add-group--padding:var(--space--large, 24px) var(--space--medium, 12px) 0;--snk-form-config__btn-add-group-container--padding:var(--space--medium, 12px);--snk-form-config__btn-add-group-container--border-radius:var(--border--radius-medium, 12px);--snk-form-config__btn-add-group-container--border:2px solid var(--color-strokes, #DCE0E8);--snk-form-config__btn-add-group-container--background-color:var(--background--body, #fafcff);display:flex;flex-direction:column;position:fixed;top:0;left:0;width:100%;height:100%;z-index:var(--snk-form-config--z-index);background-color:var(--snk-form-config--background-color)}.form-config__header-container.sc-snk-form-config{display:flex}.form-config__field-container.sc-snk-form-config{width:32%;padding:6px}.form-config__hide-content.sc-snk-form-config{display:none}ez-icon.sc-snk-form-config .left-icon.sc-snk-form-config{--ez-icon--color:var(--snk-form-config__icon--color)}.ez-box__label-counter.sc-snk-form-config{margin-top:-7px;font-weight:var(--snk-form-config__label-counter--font-weight)}.form-config__btn-options.sc-snk-form-config{--ez-button--min-width:300px;--ez-button--background-color:var(--snk-form-config--background-color)}[data-draggable-parent].sc-snk-form-config{position:relative}.form-config__field-config--selected.sc-snk-form-config{position:static}.form-config__field-config--dragged.sc-snk-form-config .draggable-mirror.sc-snk-form-config{z-index:var(--snk-form-config--z-index)}.form-config__config-options.sc-snk-form-config{position:relative;margin-top:-3px;min-width:100%;z-index:1}.form-config__tab-container.sc-snk-form-config,.form-config__fields-available.sc-snk-form-config{position:relative;height:100%;max-height:calc(100vh - 92px)}.form-config__tab-container.sc-snk-form-config .ez-box__container.sc-snk-form-config,.form-config__fields-available.sc-snk-form-config .ez-box__container.sc-snk-form-config{align-content:flex-start;height:100%}.form-config__fields-available.sc-snk-form-config [data-draggable-parent].sc-snk-form-config{align-content:flex-start;overflow-y:auto;height:100%;max-height:calc(100% - 122px)}.form-config__tab-content.sc-snk-form-config{align-content:flex-start;overflow-y:auto;height:auto;max-height:calc(100% - 128px)}[data-draggable-element].sc-snk-form-config{cursor:grab}.form-config__actions-button.sc-snk-form-config{--ez-actions-button__btn-action--min-width:235px}.form-config__add-group.sc-snk-form-config{position:relative;min-height:120px;margin-bottom:10px}.form-config__add-group-container.sc-snk-form-config{position:absolute;display:flex;flex-wrap:wrap;width:100%;box-sizing:border-box;border-radius:var(--snk-form-config__add-group-container--border-radius);background-color:var(--snk-form-config__add-group-container--background-color);padding:var(--snk-form-config__add-group-container--padding)}.form-config__add-group-content.sc-snk-form-config{width:100%;display:flex;flex-wrap:wrap;justify-content:center;align-items:center;box-sizing:border-box;border:var(--snk-form-config__add-group-content--border);border-radius:var(--snk-form-config__add-group-content--border-radius)}.form-config__add-group-label.sc-snk-form-config{display:flex;justify-content:center;box-sizing:border-box;padding:var(--snk-form-config__add-group-label--padding)}.form-config__btn-add-group.sc-snk-form-config{position:relative;padding:var(--snk-form-config__btn-add-group--padding)}.form-config__btn-add-group-container.sc-snk-form-config{padding:var(--snk-form-config__btn-add-group-container--padding);border-radius:var(--snk-form-config__btn-add-group-container--border-radius);border:var(--snk-form-config__btn-add-group-container--border);background-color:var(--snk-form-config__btn-add-group-container--background-color)}ez-collapsible-box.draggable-mirror.sc-snk-form-config{display:table;background-color:var(--snk-form-config--background-color)}ez-collapsible-box.sc-snk-form-config{margin-bottom:10px}@media screen and (min-width: 480px){.form-config__field-config--selected.sc-snk-form-config .ez-flex.form-config__config-options.sc-snk-form-config{min-width:calc(300% + 12px)}.form-config__field-config--selected.sc-snk-form-config:nth-child(3n+2) .ez-flex.form-config__config-options.sc-snk-form-config{left:calc(100% / 1 * -1)}.form-config__field-config--selected.sc-snk-form-config:nth-child(3n+3) .ez-flex.form-config__config-options.sc-snk-form-config{left:calc(100% / 1 * -2)}}";export{x as snk_form_config}
@@ -1 +1 @@
1
- import{r as t,c as i,h as e,H as s,g as r}from"./p-d2d301a6.js";import{ElementIDUtils as o,ObjectUtils as l}from"@sankhyalabs/core";import{F as a}from"./p-ff1990ad.js";import{E as n}from"./p-1a68fb59.js";import{C as d}from"./p-52920496.js";import{F as h}from"./p-d9804798.js";import"./p-df5451c7.js";import"./p-dc7c9047.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const c=class{constructor(e){t(this,e),this.filterChange=i(this,"filterChange",7),this.editPersonalizedFilter=i(this,"editPersonalizedFilter",7),this.addPersonalizedFilter=i(this,"addPersonalizedFilter",7),this.filterItem=void 0,this.configName=void 0,this.resourceID=void 0}observeFilterItem(t){var i,e;this._editor&&(this._editor.config=t),null===(e=null===(i=this._editor)||void 0===i?void 0:i.reloadList)||void 0===e||e.call(i),this.filterChange.emit(t)}getContentEditorConfig(){const t={presentationMode:n.MODAL};switch(this.filterItem.type){case a.BINARY_SELECT:return{tag:"snk-filter-binary-select",props:t};case a.MULTI_SELECT:return{tag:"snk-filter-multi-select"};case a.PERIOD:return{tag:"snk-filter-period",props:t};case a.SEARCH:return{tag:"snk-filter-search"};case a.NUMBER:return{tag:"snk-filter-number",props:t};case a.PERSONALIZED:return this.buildSnkFilterPersonalizedProps();case a.CHECK_BOX_LIST:return{tag:"snk-filter-checkbox-list",props:t};case a.MULTI_LIST:return{tag:"snk-entity-list",props:{maxHeightList:"640px",rightListSlotBuilder:t=>this.buildRightSlot(t)}}}return{tag:"snk-filter-text"}}buildSnkFilterPersonalizedProps(){return{tag:"snk-personalized-filter-editor",props:{onEditFilter:t=>this.editPersonalizedFilter.emit(t.detail),onAddFilter:()=>this.addPersonalizedFilter.emit()}}}isVisible(t){return!!this.filterItem.visible||void 0!==t}updateFilterValue(t){const i=void 0!==(null==t?void 0:t.value)?t.value:t;this.filterItem=Object.assign(Object.assign({},this.filterItem),null!=this.filterItem.groupedItems?{visible:i>0,value:i,groupedItems:t.items}:{value:this.filterItem.type===(a.SEARCH||a.CHECK_BOX_LIST)?t:i,visible:this.isVisible(i)})}handleDeleteFilter(t,i){i===a.PERSONALIZED&&d.removePersonalizedFilter(t,this.resourceID,this.configName)}componentDidLoad(){if(this._element){o.addIDInfo(this._element);const t=this._element.getAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME);this._idContentEditor=`${t}_${this.filterItem.id}`}}buildRightSlot(t){return e("ez-icon",{iconName:"delete",onClick:()=>this.removeValueFromConfig(t)})}removeValueFromConfig(t){var i,e,s;const r=null===(e=null===(i=this.filterItem)||void 0===i?void 0:i.value)||void 0===e?void 0:e.findIndex((({id:i})=>i===t.id)),o=l.copy(this.filterItem);null===(s=null==o?void 0:o.value)||void 0===s||s.splice(r,1),this.updateFilterValue(o.value)}canShowDetailModal(){const{CUSTOM_FILTER:t,OTHER_FILTERS:i}=h;return![t,i].includes(this.filterItem.filterType)&&this.filterItem.type!==a.BINARY_SELECT}render(){const{tag:t,props:i}=this.getContentEditorConfig();return e(s,null,e("div",{class:"ez-flex ez-flex--column grow"},this.canShowDetailModal()&&e("div",{class:"col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center"},e("div",{class:"ez-title ez-title--small ez-title--primary grow"},this.filterItem.detailModal)),e(t,Object.assign({ref:t=>this._editor=t,config:this.filterItem,value:this.filterItem.value,onValueChanged:t=>this.updateFilterValue(t.detail),"data-element-id":this._idContentEditor},i))))}get _element(){return r(this)}static get watchers(){return{filterItem:["observeFilterItem"]}}};c.style=".grow{flex-grow:1}.gap{gap:4px}";export{c as snk_filter_modal_item}
1
+ import{r as t,c as i,h as e,H as s,g as r}from"./p-d2d301a6.js";import{ElementIDUtils as o,ObjectUtils as l}from"@sankhyalabs/core";import{F as a}from"./p-ff1990ad.js";import{E as n}from"./p-1a68fb59.js";import{C as d}from"./p-3287a6cc.js";import{F as h}from"./p-d9804798.js";import"./p-181975f1.js";import"./p-594bc21d.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const c=class{constructor(e){t(this,e),this.filterChange=i(this,"filterChange",7),this.editPersonalizedFilter=i(this,"editPersonalizedFilter",7),this.addPersonalizedFilter=i(this,"addPersonalizedFilter",7),this.filterItem=void 0,this.configName=void 0,this.resourceID=void 0}observeFilterItem(t){var i,e;this._editor&&(this._editor.config=t),null===(e=null===(i=this._editor)||void 0===i?void 0:i.reloadList)||void 0===e||e.call(i),this.filterChange.emit(t)}getContentEditorConfig(){const t={presentationMode:n.MODAL};switch(this.filterItem.type){case a.BINARY_SELECT:return{tag:"snk-filter-binary-select",props:t};case a.MULTI_SELECT:return{tag:"snk-filter-multi-select"};case a.PERIOD:return{tag:"snk-filter-period",props:t};case a.SEARCH:return{tag:"snk-filter-search"};case a.NUMBER:return{tag:"snk-filter-number",props:t};case a.PERSONALIZED:return this.buildSnkFilterPersonalizedProps();case a.CHECK_BOX_LIST:return{tag:"snk-filter-checkbox-list",props:t};case a.MULTI_LIST:return{tag:"snk-entity-list",props:{maxHeightList:"640px",rightListSlotBuilder:t=>this.buildRightSlot(t)}}}return{tag:"snk-filter-text"}}buildSnkFilterPersonalizedProps(){return{tag:"snk-personalized-filter-editor",props:{onEditFilter:t=>this.editPersonalizedFilter.emit(t.detail),onAddFilter:()=>this.addPersonalizedFilter.emit()}}}isVisible(t){return!!this.filterItem.visible||void 0!==t}updateFilterValue(t){const i=void 0!==(null==t?void 0:t.value)?t.value:t;this.filterItem=Object.assign(Object.assign({},this.filterItem),null!=this.filterItem.groupedItems?{visible:i>0,value:i,groupedItems:t.items}:{value:this.filterItem.type===(a.SEARCH||a.CHECK_BOX_LIST)?t:i,visible:this.isVisible(i)})}handleDeleteFilter(t,i){i===a.PERSONALIZED&&d.removePersonalizedFilter(t,this.resourceID,this.configName)}componentDidLoad(){if(this._element){o.addIDInfo(this._element);const t=this._element.getAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME);this._idContentEditor=`${t}_${this.filterItem.id}`}}buildRightSlot(t){return e("ez-icon",{iconName:"delete",onClick:()=>this.removeValueFromConfig(t)})}removeValueFromConfig(t){var i,e,s;const r=null===(e=null===(i=this.filterItem)||void 0===i?void 0:i.value)||void 0===e?void 0:e.findIndex((({id:i})=>i===t.id)),o=l.copy(this.filterItem);null===(s=null==o?void 0:o.value)||void 0===s||s.splice(r,1),this.updateFilterValue(o.value)}canShowDetailModal(){const{CUSTOM_FILTER:t,OTHER_FILTERS:i}=h;return![t,i].includes(this.filterItem.filterType)&&this.filterItem.type!==a.BINARY_SELECT}render(){const{tag:t,props:i}=this.getContentEditorConfig();return e(s,null,e("div",{class:"ez-flex ez-flex--column grow"},this.canShowDetailModal()&&e("div",{class:"col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center"},e("div",{class:"ez-title ez-title--small ez-title--primary grow"},this.filterItem.detailModal)),e(t,Object.assign({ref:t=>this._editor=t,config:this.filterItem,value:this.filterItem.value,onValueChanged:t=>this.updateFilterValue(t.detail),"data-element-id":this._idContentEditor},i))))}get _element(){return r(this)}static get watchers(){return{filterItem:["observeFilterItem"]}}};c.style=".grow{flex-grow:1}.gap{gap:4px}";export{c as snk_filter_modal_item}
@@ -1 +1 @@
1
- import{r as t,c as i,f as s,h as e,H as a}from"./p-d2d301a6.js";import{Action as o}from"@sankhyalabs/core";import{S as h}from"./p-2a408684.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-dc7c9047.js";import"./p-af8efd95.js";import{P as d}from"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-fe79f83a.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{T as l}from"./p-7e7a7473.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-fa4d8cb4.js";import{S as u}from"./p-7ef9c55c.js";import"./p-52920496.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-c2495304.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const h=[];this.dataState.hasPrevious||h.push(l.PREVIOUS),this.dataState.hasNext||h.push(l.NEXT),this.dataState.insertionMode&&h.push(l.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const t=this.formConfigManager.getConfig(this.dataUnit);this._formMetadata=r(null==t||0===t.fields.length?void 0:t,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){var i,s;this._viewStack=t,this._currentView=this.selectedForm?1:0,null===(s=null===(i=this._viewStack)||void 0===i?void 0:i.show)||void 0===s||s.call(i,this._currentView)}getFormFields(){return this.selectedForm&&this._formMetadata?this._formMetadata.getSheet(this.selectedForm).fields:[]}emitSwitchEvent(t){const i=t===c.GRID?this.stripFormPattern(this.branchGuide.id):this.getFormGuideId();i&&this.snkSwitchGuide.emit(i)}handleAttachBack(){this._viewStack.show(c.GRID)}executeActionHandler(t){t.detail===l.GRID_MODE&&(this.emitSwitchEvent(c.GRID),t.stopPropagation()),t.detail===l.FORM_MODE&&(this.emitSwitchEvent(c.FORM),t.stopPropagation()),t.detail===l.ATTACH&&(this._viewStack.show(c.ATTACHMENT),t.stopPropagation())}async getAttachmentRegisterKey(){if(this._snkDataUnit)return(await this._snkDataUnit.getSelectedRecordsIDsInfo()).map((({value:t})=>t)).join("_")}async handleDataStateChange({detail:t}){this.dataState=t,void 0!==t.selectedRecord&&this._snkDataUnit&&(this.attachmentRegisterKey=await this.getAttachmentRegisterKey())}componentWillLoad(){this._configName=`dynaform.${this.entityName}`,this.formConfigManager=new h(this._configName,this.resourceID,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===c.GRID,messagesBuilder:this.messagesBuilder,configName:this._configName},e("ez-view-stack",{ref:t=>this.updateViewStack(t)},e("stack-item",null,e("div",{class:"ez-box ez-box--shadow grid-container"},e("div",{class:"ez-flex ez-title--primary ez-size-width--full ez-padding--large detail-header"},e("div",{class:"ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center"},this._levelPath?e("span",{class:"level-path"},this._levelPath+" /"):void 0,this.label)),e("snk-grid",{class:"ez-size-width--full ez-size-height--full",ref:t=>this._snkGrid=t,configName:this._configName,messagesBuilder:this.messagesBuilder,onGridDoubleClick:()=>this.emitSwitchEvent(c.FORM),onActionClick:t=>this.executeActionHandler(t),presentationMode:d.SECONDARY,canEdit:this.canEdit,isDetail:!0,taskbarCustomContainerId:this.taskbarCustomContainerId,gridHeaderCustomSlotId:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS",topTaskbarCustomSlotId:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS"}))),e("stack-item",null,e("snk-form-view",{ref:t=>this._snkFormView=t,canExpand:!1,canFix:!1,name:this.selectedForm,formMetadata:this._formMetadata,dataUnit:this.dataUnit,fields:this.getFormFields(),label:this.label,levelPath:this._levelPath,onFormItemsReady:({detail:t})=>this.formItemsReady.emit(t)},e("snk-taskbar",{key:"guideViewerTaskbar",class:"form-taskbar","data-element-id":"guideViewer",configName:this._configName,messagesBuilder:this.messagesBuilder,disabledButtons:this._disabledButtons,buttons:"INSERT,PREVIOUS,NEXT,DIVIDER,CLONE,REMOVE,MORE_OPTIONS,DIVIDER,GRID_MODE,CONFIGURATOR",primaryButton:"INSERT",presentationMode:d.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit,resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"},e("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))),e("stack-item",null,e("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this.entityName,onBack:this.handleAttachBack.bind(this)})))))}static get watchers(){return{dataUnit:["observeDataUnit"],dataState:["observerDataState"],customEditors:["observerPropsCustomEditor"],customRenders:["observeCustomRenders"]}}};p.REGEX_FORM_ID=/__FORM:[^:]+/g,p.style=".sc-snk-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%}.level-path.sc-snk-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.form-taskbar.sc-snk-detail-view{padding-bottom:var(--space--medium)}.grid-container.sc-snk-detail-view{background-color:#FFF;min-height:100px}.detail-header.sc-snk-detail-view{padding-bottom:0}";export{p as snk_detail_view}
1
+ import{r as t,c as i,f as s,h as e,H as a}from"./p-d2d301a6.js";import{Action as o}from"@sankhyalabs/core";import{S as h}from"./p-5f016aed.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-594bc21d.js";import"./p-25f1fc39.js";import{P as d}from"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-091ce761.js";import"./p-ff1990ad.js";import"./p-181975f1.js";import{T as l}from"./p-7e7a7473.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-1f35c795.js";import{S as u}from"./p-7ef9c55c.js";import"./p-3287a6cc.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-c2495304.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const h=[];this.dataState.hasPrevious||h.push(l.PREVIOUS),this.dataState.hasNext||h.push(l.NEXT),this.dataState.insertionMode&&h.push(l.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const t=this.formConfigManager.getConfig(this.dataUnit);this._formMetadata=r(null==t||0===t.fields.length?void 0:t,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){var i,s;this._viewStack=t,this._currentView=this.selectedForm?1:0,null===(s=null===(i=this._viewStack)||void 0===i?void 0:i.show)||void 0===s||s.call(i,this._currentView)}getFormFields(){return this.selectedForm&&this._formMetadata?this._formMetadata.getSheet(this.selectedForm).fields:[]}emitSwitchEvent(t){const i=t===c.GRID?this.stripFormPattern(this.branchGuide.id):this.getFormGuideId();i&&this.snkSwitchGuide.emit(i)}handleAttachBack(){this._viewStack.show(c.GRID)}executeActionHandler(t){t.detail===l.GRID_MODE&&(this.emitSwitchEvent(c.GRID),t.stopPropagation()),t.detail===l.FORM_MODE&&(this.emitSwitchEvent(c.FORM),t.stopPropagation()),t.detail===l.ATTACH&&(this._viewStack.show(c.ATTACHMENT),t.stopPropagation())}async getAttachmentRegisterKey(){if(this._snkDataUnit)return(await this._snkDataUnit.getSelectedRecordsIDsInfo()).map((({value:t})=>t)).join("_")}async handleDataStateChange({detail:t}){this.dataState=t,void 0!==t.selectedRecord&&this._snkDataUnit&&(this.attachmentRegisterKey=await this.getAttachmentRegisterKey())}componentWillLoad(){this._configName=`dynaform.${this.entityName}`,this.formConfigManager=new h(this._configName,this.resourceID,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===c.GRID,messagesBuilder:this.messagesBuilder,configName:this._configName},e("ez-view-stack",{ref:t=>this.updateViewStack(t)},e("stack-item",null,e("div",{class:"ez-box ez-box--shadow grid-container"},e("div",{class:"ez-flex ez-title--primary ez-size-width--full ez-padding--large detail-header"},e("div",{class:"ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center"},this._levelPath?e("span",{class:"level-path"},this._levelPath+" /"):void 0,this.label)),e("snk-grid",{class:"ez-size-width--full ez-size-height--full",ref:t=>this._snkGrid=t,configName:this._configName,messagesBuilder:this.messagesBuilder,onGridDoubleClick:()=>this.emitSwitchEvent(c.FORM),onActionClick:t=>this.executeActionHandler(t),presentationMode:d.SECONDARY,canEdit:this.canEdit,isDetail:!0,taskbarCustomContainerId:this.taskbarCustomContainerId,gridHeaderCustomSlotId:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS",topTaskbarCustomSlotId:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS"}))),e("stack-item",null,e("snk-form-view",{ref:t=>this._snkFormView=t,canExpand:!1,canFix:!1,name:this.selectedForm,formMetadata:this._formMetadata,dataUnit:this.dataUnit,fields:this.getFormFields(),label:this.label,levelPath:this._levelPath,onFormItemsReady:({detail:t})=>this.formItemsReady.emit(t)},e("snk-taskbar",{key:"guideViewerTaskbar",class:"form-taskbar","data-element-id":"guideViewer",configName:this._configName,messagesBuilder:this.messagesBuilder,disabledButtons:this._disabledButtons,buttons:"INSERT,PREVIOUS,NEXT,DIVIDER,CLONE,REMOVE,MORE_OPTIONS,DIVIDER,GRID_MODE,CONFIGURATOR",primaryButton:"INSERT",presentationMode:d.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit,resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"},e("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))),e("stack-item",null,e("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this.entityName,onBack:this.handleAttachBack.bind(this)})))))}static get watchers(){return{dataUnit:["observeDataUnit"],dataState:["observerDataState"],customEditors:["observerPropsCustomEditor"],customRenders:["observeCustomRenders"]}}};p.REGEX_FORM_ID=/__FORM:[^:]+/g,p.style=".sc-snk-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%}.level-path.sc-snk-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.form-taskbar.sc-snk-detail-view{padding-bottom:var(--space--medium)}.grid-container.sc-snk-detail-view{background-color:#FFF;min-height:100px}.detail-header.sc-snk-detail-view{padding-bottom:0}";export{p as snk_detail_view}
@@ -1 +1 @@
1
- import{r as i,c as e,h as s,F as t,H as n}from"./p-d2d301a6.js";import{StringUtils as l,ObjectUtils as r,ApplicationContext as a,ElementIDUtils as o}from"@sankhyalabs/core";import{P as h}from"./p-057fad05.js";import{P as d,C as c}from"./p-52920496.js";import{ApplicationUtils as f}from"@sankhyalabs/ezui/dist/collection/utils";import{a as p}from"./p-933c0c0b.js";import{s as z}from"./p-6dc031de.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import"./p-dc7c9047.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const m=class{constructor(s){i(this,s),this.ezCancel=e(this,"ezCancel",7),this.ezSave=e(this,"ezSave",7),this.ezAfterSave=e(this,"ezAfterSave",7),this._personalizedFilterFetcher=new d,this._filterMetadataStorage=new Map,this._dataSourceFetcher={fetchData:async i=>{let e=null==i?void 0:i.uri;if(l.isEmpty(e)&&(e=this.entityUri),!this._filterMetadataStorage.has(e)){const i=await this._personalizedFilterFetcher.loadFields(e);this._filterMetadataStorage.set(e,i)}return this._filterMetadataStorage.get(e)}},this._filterAssistentMode=!0,this._filterAssistent=void 0,this.messagesBuilder=void 0,this.entityUri=void 0,this.filterId=void 0,this.configName=void 0,this.resourceID=void 0}async createPersonalizedFilter(){const i={name:"",active:!0,expression:"",parameters:[],assistent:{id:l.generateUUID(),items:[{id:l.generateUUID(),entityName:"",fieldName:"",description:"",fieldLabel:"Valor",type:void 0,expression:void 0,operand:void 0,paramVariable:!1,value:void 0,systemConfig:null,userConfig:null}],childrenGroups:[],operand:p.AND}};this._originalFilterAssistent=r.copy(i),this._filterAssistent=r.copy(i)}loadFilter(i,e){null!=i&&e!=i&&null!=this.resourceID&&c.loadPersonalizedFilter(i,this.resourceID,this.configName).then((i=>{const e=this.applyDefaultValues(i);this._filterAssistent=e,this._originalFilterAssistent=r.copy(e),this._filterAssistentMode=this._filterAssistent.hasOwnProperty("assistent")&&null!=this._filterAssistent.assistent}))}componentWillLoad(){var i;null==z.get(`filterFieldsDataSource.${this.entityUri}`)&&z.set(`filterFieldsDataSource.${this.entityUri}`,this._dataSourceFetcher),this.messagesBuilder||(this._application=a.getContextValue("__SNK__APPLICATION__"),this.messagesBuilder=null===(i=this._application)||void 0===i?void 0:i.messagesBuilder),this.loadFilter(this.filterId,void 0)}componentDidRender(){var i;null===(i=this._viewStackRef)||void 0===i||i.show(this._filterAssistentMode?0:1),this._elButtonMode&&this._elButtonMode.setAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME,o.getInternalIDInfo(this._filterAssistentMode?"advancedMode_ezButton":"assistentMode_ezButton"))}getMessage(i,e){return this._application.messagesBuilder.getMessage(i,e)}saveFilter(){c.savePersonalizedFilter(this._filterAssistent,this.resourceID,this.configName).then((i=>{this._elButtonSave.enabled=!1,f.info(this.getMessage(`snkPersonalizedFilter.${this._filterAssistent.id?"confirmEdit":"confirmSave"}.title`),{iconName:"check"});const e=Object.assign(Object.assign({},i),this._filterAssistent);e.parameters=h.buildVariableParameters(this._filterAssistent.assistent),this._originalFilterAssistent=r.copy(e),this._filterAssistent=r.copy(e),this.ezAfterSave.emit()}))}removeFilter(){c.removePersonalizedFilter(this._filterAssistent,this.resourceID,this.configName)}hasChangesToSave(){return JSON.stringify(this._filterAssistent)===JSON.stringify(this._originalFilterAssistent)}async handleSave(){if(this._filterAssistentMode){if(!h.validateFields(this._filterAssistent.assistent)||!this._filterAssistent.name)return this._application.error(this.getMessage("snkPersonalizedFilter.error.title"),this.getMessage("snkPersonalizedFilter.error.description"));this.saveAssistentMode()}else{if(!this._filterAssistent.expression||!this._filterAssistent.name)return this._application.error(this.getMessage("snkPersonalizedFilter.error.title"),this.getMessage("snkPersonalizedFilter.error.description"));if(!await this.validateExpressionBeforeSaving())return;this.saveAdvancedMode()}}saveAssistentMode(){const{assistent:i,expression:e}=this._filterAssistent,s=i?h.buildGroupExpression(i):e;this._filterAssistent.expression=s,this.ezSave.emit(s),this.saveFilter()}saveAdvancedMode(){this._originalFilterAssistent.expression!==this._filterAssistent.expression&&this._filterAssistent.assistent?f.confirm(this.getMessage("snkPersonalizedFilter.confirmSaveModeAdvanced.title"),this.getMessage("snkPersonalizedFilter.confirmSaveModeAdvanced.description")).then((i=>{i&&this.saveAndTransformToAdvancedMode()})):this._filterAssistent.assistent?this.saveAssistentMode():this.saveAndTransformToAdvancedMode()}saveAndTransformToAdvancedMode(){this._filterAssistent.assistent=void 0,this.ezSave.emit(this._filterAssistent.expression),this.saveFilter()}async validateExpressionBeforeSaving(){const{valid:i,message:e=""}=await this._personalizedFilterFetcher.validatePersonalizedFilter(this.entityUri,this._filterAssistent.expression);return i||this._application.error(this.getMessage("snkPersonalizedFilter.errorValidation.title"),e.replace(/.*Exception: /,"")),i}handleCancel(){if(this.hasChangesToSave())return this.ezCancel.emit();f.confirm(this.getMessage("snkPersonalizedFilter.confirmCancel.title"),this.getMessage("snkPersonalizedFilter.confirmCancel.description")).then((i=>{var e;i&&(this._filterAssistent=r.copy(null!==(e=this._originalFilterAssistent)&&void 0!==e?e:{}),this.ezCancel.emit(),this._elButtonSave.enabled=!1)}))}handleTitleChange(i){this._filterAssistent=Object.assign(Object.assign({},this._filterAssistent),{name:i}),this._elButtonSave.enabled=!this.hasChangesToSave()}applyDefaultValues(i){return this.addLabelToItems(i),this.addFilterGroupCondition(i),i}addFilterGroupCondition(i){i.assistent&&!i.assistent.operand&&(i.assistent.operand=p.AND)}addLabelToItems(i){i.assistent&&i.assistent.items&&i.assistent.items.length>0&&i.assistent.items.forEach((e=>{if(null==e.fieldLabel){const s=(i.parameters||[]).find((i=>i.fieldName===e.fieldName));s&&(e.fieldLabel=s.label)}}))}handleExpressionChangeAdvancedMode(i){this._filterAssistent=Object.assign(Object.assign({},this._filterAssistent),{expression:i}),this._elButtonSave.enabled=!this.hasChangesToSave()}handleChangeFilterAssistentMode(i){this._elButtonSave.enabled=!this.hasChangesToSave(),this._filterAssistent=Object.assign({},i)}selectField(i){if(!("name"in i))return;const e=this.buildExpression(i.entityName,i.name,i.entityPath);this._elAdvancedMode.querySelector("ez-text-area").appendTextToSelection(e)}buildExpression(i,e,s){return s.length>0&&s.shift(),s.length>0?`${s.join("->")}->${e}`:`${i}.${e}`}onAddField(i){this._elAdvancedMode.querySelector("ez-text-area").setFocus(),i.setBlur(),this._elFilterFieldSearch&&this._elFilterFieldSearch.show(i,{horizontalGap:0,verticalGap:12,fromRight:!0})}renderButtonAddField(){if(!this._filterAssistentMode)return s(t,null,s("ez-button",{class:"snk-personalized-filter__button-mode",label:this.getMessage("snkPersonalizedFilter.info.addField"),enabled:!0,onClick:i=>this.onAddField(i.target)},s("ez-icon",{class:"ez-padding-right--small",slot:"leftIcon",iconName:"plus"})),s("snk-filter-field-search",{class:"ez-padding-left--medium",ref:i=>this._elFilterFieldSearch=i,onEzSelectFilterItem:i=>this.selectField(i.detail),fieldsDataSource:this._dataSourceFetcher}))}buildContainerPersonalizedFilter(){return s("ez-view-stack",{ref:i=>this._viewStackRef=i},s("stack-item",null,this._filterAssistentMode&&s("snk-filter-assistent-mode",{filterAssistent:this._filterAssistent,messagesBuilder:this.messagesBuilder,filterId:this.filterId,entityUri:this.entityUri,application:this._application,onEzChangeFilter:i=>this.handleChangeFilterAssistentMode(i.detail)})),s("stack-item",null,s("snk-filter-advanced-mode",{ref:i=>this._elAdvancedMode=i,filterAssistent:this._filterAssistent,application:this._application,onEzExpressionChange:i=>this.handleExpressionChangeAdvancedMode(i.detail)})))}handleModeChange(){var i,e;if(this._filterAssistentMode)f.confirm(this.getMessage("snkPersonalizedFilter.confirmChangeModeAssistent.title"),this.getMessage("snkPersonalizedFilter.confirmChangeModeAssistent.description")).then((i=>{if(i&&(this._filterAssistentMode=!this._filterAssistentMode,!this.hasChangesToSave())){const i=h.buildGroupExpression(this._filterAssistent.assistent);this._filterAssistent.expression=i,this._elButtonSave.enabled=!this.hasChangesToSave()}}));else if((null===(i=this._filterAssistent)||void 0===i?void 0:i.expression)===(null===(e=this._originalFilterAssistent)||void 0===e?void 0:e.expression))this._filterAssistentMode=!this._filterAssistentMode;else{const i=this._filterAssistent.expression,e=h.buildGroupExpression(this._filterAssistent.assistent);i!==e?f.confirm(this.getMessage("snkPersonalizedFilter.confirmChangeModeAdvanced.title"),this.getMessage("snkPersonalizedFilter.confirmChangeModeAdvanced.description")).then((i=>{i&&(this._filterAssistent=Object.assign(Object.assign({},this._filterAssistent),{expression:e}),this._filterAssistentMode=!this._filterAssistentMode)})):this._filterAssistentMode=!this._filterAssistentMode}}render(){var i,e,t,l;if((null===(i=this._filterAssistent)||void 0===i?void 0:i.assistent)||!this._filterAssistentMode)return s(n,null,s("div",{class:"snk-personalized-filter"},s("div",null,s("snk-simple-bar",{label:this.getMessage(this.filterId?"snkPersonalizedFilter.info.titleEdit":"snkPersonalizedFilter.info.titleAdd"),onExit:()=>this.handleCancel()},s("div",{class:"snk-personalized-filter__header-actions",slot:"rightSlot"},s("ez-button",{size:"small",label:this.getMessage("snkPersonalizedFilter.info.labelCancel"),onClick:()=>this.handleCancel()}),s("ez-button",{size:"small",ref:i=>this._elButtonSave=i,enabled:!1,class:"ez-button--primary",label:this.getMessage("snkPersonalizedFilter.info.labelSave"),onClick:this.handleSave.bind(this)})))),s("div",{class:"ez-box ez-margin-bottom--medium ez-box__main"},s("div",{class:"ez-box__container"},s("div",{class:"ez-flex ez-flex--column ez-size-width--full"},s("div",{class:"ez-flex"},s("ez-text-input",{class:"ez-padding-right--medium",label:this.getMessage("snkPersonalizedFilter.info.labelNameFilter"),value:null===(e=this._filterAssistent)||void 0===e?void 0:e.name,onEzChange:i=>this.handleTitleChange(i.detail)}),this.renderButtonAddField(),s("ez-button",{ref:i=>this._elButtonMode=i,class:"snk-personalized-filter__button-mode",label:this.getMessage(this._filterAssistentMode?"snkPersonalizedFilter.info.activeModeAdvanced":"snkPersonalizedFilter.info.activeModeAssistent"),onClick:()=>this.handleModeChange(),"data-tooltip":this._filterAssistentMode||(null===(t=this._filterAssistent)||void 0===t?void 0:t.assistent)?void 0:this.getMessage("snkPersonalizedFilter.info.tooltipDisabledAssistentMode"),"data-flow":"bottom",enabled:!this._filterAssistent.name||Boolean(this._filterAssistentMode||(null===(l=this._filterAssistent)||void 0===l?void 0:l.assistent))})),this.buildContainerPersonalizedFilter())))))}static get watchers(){return{filterId:["loadFilter"]}}};m.style=".sc-snk-personalized-filter-h{display:flex;height:100%;padding:var(--space--large, 24px);--snk-personalized-filter--width:100%;--snk-personalized-filter--height:100%;--snk-personalized-filter--background-color-line:var(--color--disable-secondary);--snk-personalized-filter--margin-line:var(--border--radius-medium, 12px)}.snk-personalized-filter.sc-snk-personalized-filter{height:var(--snk-personalized-filter--width);width:var(--snk-personalized-filter--height)}.snk-personalized-filter__header-actions.sc-snk-personalized-filter{display:flex;gap:var(--space--medium)}.snk-personalized-filter__group.sc-snk-personalized-filter{flex:1}.snk-personalized-filter__expression-input--line.sc-snk-personalized-filter{width:100%;height:2px;background-color:var(--snk-personalized-filter--background-color-line);margin-top:var(--snk-personalized-filter--margin-line);margin-bottom:var(--snk-personalized-filter--margin-line)}.ez-box__main.sc-snk-personalized-filter{height:90%}.snk-personalized-filter__button-mode.sc-snk-personalized-filter{height:35px}";export{m as snk_personalized_filter}
1
+ import{r as i,c as e,h as s,F as t,H as n}from"./p-d2d301a6.js";import{StringUtils as l,ObjectUtils as r,ApplicationContext as a,ElementIDUtils as o}from"@sankhyalabs/core";import{P as h}from"./p-057fad05.js";import{P as d,C as c}from"./p-3287a6cc.js";import{ApplicationUtils as f}from"@sankhyalabs/ezui/dist/collection/utils";import{a as p}from"./p-933c0c0b.js";import{s as z}from"./p-6dc031de.js";import"./p-ff1990ad.js";import"./p-181975f1.js";import"./p-594bc21d.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";const m=class{constructor(s){i(this,s),this.ezCancel=e(this,"ezCancel",7),this.ezSave=e(this,"ezSave",7),this.ezAfterSave=e(this,"ezAfterSave",7),this._personalizedFilterFetcher=new d,this._filterMetadataStorage=new Map,this._dataSourceFetcher={fetchData:async i=>{let e=null==i?void 0:i.uri;if(l.isEmpty(e)&&(e=this.entityUri),!this._filterMetadataStorage.has(e)){const i=await this._personalizedFilterFetcher.loadFields(e);this._filterMetadataStorage.set(e,i)}return this._filterMetadataStorage.get(e)}},this._filterAssistentMode=!0,this._filterAssistent=void 0,this.messagesBuilder=void 0,this.entityUri=void 0,this.filterId=void 0,this.configName=void 0,this.resourceID=void 0}async createPersonalizedFilter(){const i={name:"",active:!0,expression:"",parameters:[],assistent:{id:l.generateUUID(),items:[{id:l.generateUUID(),entityName:"",fieldName:"",description:"",fieldLabel:"Valor",type:void 0,expression:void 0,operand:void 0,paramVariable:!1,value:void 0,systemConfig:null,userConfig:null}],childrenGroups:[],operand:p.AND}};this._originalFilterAssistent=r.copy(i),this._filterAssistent=r.copy(i)}loadFilter(i,e){null!=i&&e!=i&&null!=this.resourceID&&c.loadPersonalizedFilter(i,this.resourceID,this.configName).then((i=>{const e=this.applyDefaultValues(i);this._filterAssistent=e,this._originalFilterAssistent=r.copy(e),this._filterAssistentMode=this._filterAssistent.hasOwnProperty("assistent")&&null!=this._filterAssistent.assistent}))}componentWillLoad(){var i;null==z.get(`filterFieldsDataSource.${this.entityUri}`)&&z.set(`filterFieldsDataSource.${this.entityUri}`,this._dataSourceFetcher),this.messagesBuilder||(this._application=a.getContextValue("__SNK__APPLICATION__"),this.messagesBuilder=null===(i=this._application)||void 0===i?void 0:i.messagesBuilder),this.loadFilter(this.filterId,void 0)}componentDidRender(){var i;null===(i=this._viewStackRef)||void 0===i||i.show(this._filterAssistentMode?0:1),this._elButtonMode&&this._elButtonMode.setAttribute(o.DATA_ELEMENT_ID_ATTRIBUTE_NAME,o.getInternalIDInfo(this._filterAssistentMode?"advancedMode_ezButton":"assistentMode_ezButton"))}getMessage(i,e){return this._application.messagesBuilder.getMessage(i,e)}saveFilter(){c.savePersonalizedFilter(this._filterAssistent,this.resourceID,this.configName).then((i=>{this._elButtonSave.enabled=!1,f.info(this.getMessage(`snkPersonalizedFilter.${this._filterAssistent.id?"confirmEdit":"confirmSave"}.title`),{iconName:"check"});const e=Object.assign(Object.assign({},i),this._filterAssistent);e.parameters=h.buildVariableParameters(this._filterAssistent.assistent),this._originalFilterAssistent=r.copy(e),this._filterAssistent=r.copy(e),this.ezAfterSave.emit()}))}removeFilter(){c.removePersonalizedFilter(this._filterAssistent,this.resourceID,this.configName)}hasChangesToSave(){return JSON.stringify(this._filterAssistent)===JSON.stringify(this._originalFilterAssistent)}async handleSave(){if(this._filterAssistentMode){if(!h.validateFields(this._filterAssistent.assistent)||!this._filterAssistent.name)return this._application.error(this.getMessage("snkPersonalizedFilter.error.title"),this.getMessage("snkPersonalizedFilter.error.description"));this.saveAssistentMode()}else{if(!this._filterAssistent.expression||!this._filterAssistent.name)return this._application.error(this.getMessage("snkPersonalizedFilter.error.title"),this.getMessage("snkPersonalizedFilter.error.description"));if(!await this.validateExpressionBeforeSaving())return;this.saveAdvancedMode()}}saveAssistentMode(){const{assistent:i,expression:e}=this._filterAssistent,s=i?h.buildGroupExpression(i):e;this._filterAssistent.expression=s,this.ezSave.emit(s),this.saveFilter()}saveAdvancedMode(){this._originalFilterAssistent.expression!==this._filterAssistent.expression&&this._filterAssistent.assistent?f.confirm(this.getMessage("snkPersonalizedFilter.confirmSaveModeAdvanced.title"),this.getMessage("snkPersonalizedFilter.confirmSaveModeAdvanced.description")).then((i=>{i&&this.saveAndTransformToAdvancedMode()})):this._filterAssistent.assistent?this.saveAssistentMode():this.saveAndTransformToAdvancedMode()}saveAndTransformToAdvancedMode(){this._filterAssistent.assistent=void 0,this.ezSave.emit(this._filterAssistent.expression),this.saveFilter()}async validateExpressionBeforeSaving(){const{valid:i,message:e=""}=await this._personalizedFilterFetcher.validatePersonalizedFilter(this.entityUri,this._filterAssistent.expression);return i||this._application.error(this.getMessage("snkPersonalizedFilter.errorValidation.title"),e.replace(/.*Exception: /,"")),i}handleCancel(){if(this.hasChangesToSave())return this.ezCancel.emit();f.confirm(this.getMessage("snkPersonalizedFilter.confirmCancel.title"),this.getMessage("snkPersonalizedFilter.confirmCancel.description")).then((i=>{var e;i&&(this._filterAssistent=r.copy(null!==(e=this._originalFilterAssistent)&&void 0!==e?e:{}),this.ezCancel.emit(),this._elButtonSave.enabled=!1)}))}handleTitleChange(i){this._filterAssistent=Object.assign(Object.assign({},this._filterAssistent),{name:i}),this._elButtonSave.enabled=!this.hasChangesToSave()}applyDefaultValues(i){return this.addLabelToItems(i),this.addFilterGroupCondition(i),i}addFilterGroupCondition(i){i.assistent&&!i.assistent.operand&&(i.assistent.operand=p.AND)}addLabelToItems(i){i.assistent&&i.assistent.items&&i.assistent.items.length>0&&i.assistent.items.forEach((e=>{if(null==e.fieldLabel){const s=(i.parameters||[]).find((i=>i.fieldName===e.fieldName));s&&(e.fieldLabel=s.label)}}))}handleExpressionChangeAdvancedMode(i){this._filterAssistent=Object.assign(Object.assign({},this._filterAssistent),{expression:i}),this._elButtonSave.enabled=!this.hasChangesToSave()}handleChangeFilterAssistentMode(i){this._elButtonSave.enabled=!this.hasChangesToSave(),this._filterAssistent=Object.assign({},i)}selectField(i){if(!("name"in i))return;const e=this.buildExpression(i.entityName,i.name,i.entityPath);this._elAdvancedMode.querySelector("ez-text-area").appendTextToSelection(e)}buildExpression(i,e,s){return s.length>0&&s.shift(),s.length>0?`${s.join("->")}->${e}`:`${i}.${e}`}onAddField(i){this._elAdvancedMode.querySelector("ez-text-area").setFocus(),i.setBlur(),this._elFilterFieldSearch&&this._elFilterFieldSearch.show(i,{horizontalGap:0,verticalGap:12,fromRight:!0})}renderButtonAddField(){if(!this._filterAssistentMode)return s(t,null,s("ez-button",{class:"snk-personalized-filter__button-mode",label:this.getMessage("snkPersonalizedFilter.info.addField"),enabled:!0,onClick:i=>this.onAddField(i.target)},s("ez-icon",{class:"ez-padding-right--small",slot:"leftIcon",iconName:"plus"})),s("snk-filter-field-search",{class:"ez-padding-left--medium",ref:i=>this._elFilterFieldSearch=i,onEzSelectFilterItem:i=>this.selectField(i.detail),fieldsDataSource:this._dataSourceFetcher}))}buildContainerPersonalizedFilter(){return s("ez-view-stack",{ref:i=>this._viewStackRef=i},s("stack-item",null,this._filterAssistentMode&&s("snk-filter-assistent-mode",{filterAssistent:this._filterAssistent,messagesBuilder:this.messagesBuilder,filterId:this.filterId,entityUri:this.entityUri,application:this._application,onEzChangeFilter:i=>this.handleChangeFilterAssistentMode(i.detail)})),s("stack-item",null,s("snk-filter-advanced-mode",{ref:i=>this._elAdvancedMode=i,filterAssistent:this._filterAssistent,application:this._application,onEzExpressionChange:i=>this.handleExpressionChangeAdvancedMode(i.detail)})))}handleModeChange(){var i,e;if(this._filterAssistentMode)f.confirm(this.getMessage("snkPersonalizedFilter.confirmChangeModeAssistent.title"),this.getMessage("snkPersonalizedFilter.confirmChangeModeAssistent.description")).then((i=>{if(i&&(this._filterAssistentMode=!this._filterAssistentMode,!this.hasChangesToSave())){const i=h.buildGroupExpression(this._filterAssistent.assistent);this._filterAssistent.expression=i,this._elButtonSave.enabled=!this.hasChangesToSave()}}));else if((null===(i=this._filterAssistent)||void 0===i?void 0:i.expression)===(null===(e=this._originalFilterAssistent)||void 0===e?void 0:e.expression))this._filterAssistentMode=!this._filterAssistentMode;else{const i=this._filterAssistent.expression,e=h.buildGroupExpression(this._filterAssistent.assistent);i!==e?f.confirm(this.getMessage("snkPersonalizedFilter.confirmChangeModeAdvanced.title"),this.getMessage("snkPersonalizedFilter.confirmChangeModeAdvanced.description")).then((i=>{i&&(this._filterAssistent=Object.assign(Object.assign({},this._filterAssistent),{expression:e}),this._filterAssistentMode=!this._filterAssistentMode)})):this._filterAssistentMode=!this._filterAssistentMode}}render(){var i,e,t,l;if((null===(i=this._filterAssistent)||void 0===i?void 0:i.assistent)||!this._filterAssistentMode)return s(n,null,s("div",{class:"snk-personalized-filter"},s("div",null,s("snk-simple-bar",{label:this.getMessage(this.filterId?"snkPersonalizedFilter.info.titleEdit":"snkPersonalizedFilter.info.titleAdd"),onExit:()=>this.handleCancel()},s("div",{class:"snk-personalized-filter__header-actions",slot:"rightSlot"},s("ez-button",{size:"small",label:this.getMessage("snkPersonalizedFilter.info.labelCancel"),onClick:()=>this.handleCancel()}),s("ez-button",{size:"small",ref:i=>this._elButtonSave=i,enabled:!1,class:"ez-button--primary",label:this.getMessage("snkPersonalizedFilter.info.labelSave"),onClick:this.handleSave.bind(this)})))),s("div",{class:"ez-box ez-margin-bottom--medium ez-box__main"},s("div",{class:"ez-box__container"},s("div",{class:"ez-flex ez-flex--column ez-size-width--full"},s("div",{class:"ez-flex"},s("ez-text-input",{class:"ez-padding-right--medium",label:this.getMessage("snkPersonalizedFilter.info.labelNameFilter"),value:null===(e=this._filterAssistent)||void 0===e?void 0:e.name,onEzChange:i=>this.handleTitleChange(i.detail)}),this.renderButtonAddField(),s("ez-button",{ref:i=>this._elButtonMode=i,class:"snk-personalized-filter__button-mode",label:this.getMessage(this._filterAssistentMode?"snkPersonalizedFilter.info.activeModeAdvanced":"snkPersonalizedFilter.info.activeModeAssistent"),onClick:()=>this.handleModeChange(),"data-tooltip":this._filterAssistentMode||(null===(t=this._filterAssistent)||void 0===t?void 0:t.assistent)?void 0:this.getMessage("snkPersonalizedFilter.info.tooltipDisabledAssistentMode"),"data-flow":"bottom",enabled:!this._filterAssistent.name||Boolean(this._filterAssistentMode||(null===(l=this._filterAssistent)||void 0===l?void 0:l.assistent))})),this.buildContainerPersonalizedFilter())))))}static get watchers(){return{filterId:["loadFilter"]}}};m.style=".sc-snk-personalized-filter-h{display:flex;height:100%;padding:var(--space--large, 24px);--snk-personalized-filter--width:100%;--snk-personalized-filter--height:100%;--snk-personalized-filter--background-color-line:var(--color--disable-secondary);--snk-personalized-filter--margin-line:var(--border--radius-medium, 12px)}.snk-personalized-filter.sc-snk-personalized-filter{height:var(--snk-personalized-filter--width);width:var(--snk-personalized-filter--height)}.snk-personalized-filter__header-actions.sc-snk-personalized-filter{display:flex;gap:var(--space--medium)}.snk-personalized-filter__group.sc-snk-personalized-filter{flex:1}.snk-personalized-filter__expression-input--line.sc-snk-personalized-filter{width:100%;height:2px;background-color:var(--snk-personalized-filter--background-color-line);margin-top:var(--snk-personalized-filter--margin-line);margin-bottom:var(--snk-personalized-filter--margin-line)}.ez-box__main.sc-snk-personalized-filter{height:90%}.snk-personalized-filter__button-mode.sc-snk-personalized-filter{height:35px}";export{m as snk_personalized_filter}
@@ -1,4 +1,4 @@
1
- import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,StringUtils as r,ObjectUtils as o,WaitingChangeException as a,WarningException as c,ErrorException as h,KeyboardManager as l,OnboardingUtils as u,DependencyType as p,ArrayUtils as d,SearchUtils as w,ElementIDUtils as m,ApplicationContext as f,DataType as y,ErrorTracking as P}from"@sankhyalabs/core";import{ApplicationUtils as v}from"@sankhyalabs/ezui/dist/collection/utils";import{C as g}from"./p-52920496.js";import{d as _,D as A,U as I}from"./p-dc7c9047.js";import{A as S,a as C}from"./p-913a9979.js";import{D as N}from"./p-fe79f83a.js";import{P as b}from"./p-af8efd95.js";import{S as L}from"./p-7ef9c55c.js";import"./p-df5451c7.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class D{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const T=k;function k(t,s){const e=E();return(k=function(t){return e[t-=378]})(t,s)}function E(){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(E=function(){return t})()}!function(){const t=k,s=E();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 O{[T(397)](t){const s=T;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new U("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 U{constructor(t){const s=T;this.isSup=t,this[s(384)]={}}[T(378)](t,s){this[T(384)][t]=s}[T(393)](t){const s=T;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 j{constructor(){this._embeddedParams=new Map,this.templateByQuery=new Map;try{if(null!=window.MGE_PARAMS){atob(window.MGE_PARAMS).split("__;__").forEach((t=>{const[s,e]=t.split("__=__");this._embeddedParams.set(s,e)}))}}catch(t){console.error("Problemas ao obter parâmetros embarcados"),console.error(t)}this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",_.gql`query($name: String!) {
1
+ import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,StringUtils as r,ObjectUtils as o,WaitingChangeException as a,WarningException as c,ErrorException as h,KeyboardManager as l,OnboardingUtils as u,DependencyType as p,ArrayUtils as d,SearchUtils as w,ElementIDUtils as m,ApplicationContext as y,DataType as f,ErrorTracking as P}from"@sankhyalabs/core";import{ApplicationUtils as v}from"@sankhyalabs/ezui/dist/collection/utils";import{C as g}from"./p-3287a6cc.js";import{d as _,D as A,U as I}from"./p-594bc21d.js";import{A as S,a as C}from"./p-0cd3c0a9.js";import{D as b}from"./p-091ce761.js";import{P as N}from"./p-25f1fc39.js";import{S as L}from"./p-7ef9c55c.js";import"./p-181975f1.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class D{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const T=k;function k(t,s){const e=E();return(k=function(t){return e[t-=378]})(t,s)}function E(){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(E=function(){return t})()}!function(){const t=k,s=E();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 O{[T(397)](t){const s=T;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new U("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 U{constructor(t){const s=T;this.isSup=t,this[s(384)]={}}[T(378)](t,s){this[T(384)][t]=s}[T(393)](t){const s=T;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 j{constructor(){this._embeddedParams=new Map,this.templateByQuery=new Map;try{if(null!=window.MGE_PARAMS){atob(window.MGE_PARAMS).split("__;__").forEach((t=>{const[s,e]=t.split("__=__");this._embeddedParams.set(s,e)}))}}catch(t){console.error("Problemas ao obter parâmetros embarcados"),console.error(t)}this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",_.gql`query($name: String!) {
2
2
  $queryAlias$: fetchResource(name: $name){
3
3
  name
4
4
  resource
@@ -8,4 +8,4 @@ import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,S
8
8
  name
9
9
  value
10
10
  }
11
- }`)}fetchTotals(t,s,e=[]){const i=`${t}_${s}`,n=this.cancel.findIndex((t=>t[i]));return n>=0&&(this.cancel[n][i](),this.cancel.splice(n,1)),Promise.race([new Promise((t=>this.cancel.push({[i]:t}))),this.getTotals(t,s,e)]).then((t=>{let s=new Map;if(t){s=t;const e=this.cancel.findIndex((t=>t[i]));e>=0&&this.cancel.splice(e,1)}return s}))}getTotals(t,s,e=[]){return new Promise(((i,n)=>{A.get().callGraphQL({query:this.templateByQuery.get("fetchTotals"),values:{name:`totals://${t}/${s}`,filters:e}}).then((t=>{if(t.length>0){const s=new Map;return t.forEach((t=>s.set(t.name,parseFloat(t.value)))),i(s)}return n("Não foi possível recuperar os totalizadores")})).catch(n)}))}}function M(){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(M=function(){return t})()}const R=$;function $(t,s){const e=M();return($=function(t){return e[t-=392]})(t,s)}!function(){const t=$,s=M();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 z=R(396);var q;class x{static openAppActivity(t,s){var e;null===(e=window.workspace)||void 0===e||e.openAppActivity(t,s)}static getAppLabel(t){if(null!=(null===window||void 0===window?void 0:window.workspace))return null==window.workspace.getAppLabel&&(window.workspace.getAppLabel=t=>(t||"").split(".").pop()),window.workspace.getAppLabel(t)}static setScreenToUseV3Layout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseV3Layout()}static setScreenToUseOldLayout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseOldLayout()}static showDesktop(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.showDesktop)||void 0===s||s.call(t)}static searchApp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.searchApp)||void 0===s||s.call(t)}static openHelp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.openHelp)||void 0===s||s.call(t)}static applicationClick(){var t,s;(null===(t=window.workspace)||void 0===t?void 0:t.applicationClick)&&(null===(s=window.workspace)||void 0===s||s.applicationClick())}}x.resourceID=null===(q=window.workspace)||void 0===q?void 0:q.resourceID;class B{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 a||(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 a||t instanceof c?this._app.alert(t.title,t.message):t instanceof h?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)}}))}}const K=class{constructor(e){t(this,e),this.applicationLoaded=s(this,"applicationLoaded",7),this.applicationLoading=s(this,"applicationLoading",7),this.NEW_VERSION_POPUP_LOCKER="NEW_VERSION_POPUP_LOCKER",this._authPromises=[],this._keyboardManager=new l,this._waitingAppReady=new Array,this._duCache=new Map,this._duPromises=new Map,this._requestListener=new H,this._pendingActions=new Map,this._loadPkParameter=null,this._isLoadedByPk=!1,this.messagesBuilder=void 0,this.configName=void 0,this.gridLegacyConfigName=void 0,this.formLegacyConfigName=void 0,this.loadByPK=void 0}async processPendingActions(t){const s=this._pendingActions.get(t);s&&s.length&&(s.forEach((t=>t())),this._pendingActions.set(t,[]))}get parameters(){return this._parameters||(this._parameters=new j),this._parameters}async getAuth(t){return null==t?this.getApplicationAuth():new Promise(((s,e)=>{this.authFetcher.getData(t).then((t=>{s(t)})).catch((t=>{e(t)}))}))}async getApplicationAuth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,s)=>{const e=this._authPromises.length>0;this._authPromises.push(new V(t,s)),e||this.authFetcher.getData(this.applicationResourceID).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)}))}))}watchPropHandler(t,s){t&&this._loadPkParameter&&(this.loadByPK(this._loadPkParameter.pk,this._loadPkParameter.redirect),this._loadPkParameter=null)}async getKeyboardManager(){return Promise.resolve(this._keyboardManager)}async isUserSup(){return new Promise(((t,s)=>{this.getAuth().then((e=>{this.getAuthList(e).then((s=>{t(s.isSup)})).catch((t=>s(t)))}))}))}async addPendingAction(t,s){var e;const i=null!==(e=this._pendingActions.get(t))&&void 0!==e?e:[];this._pendingActions.set(t,[...i,s])}async callServiceBroker(t,s,e){return A.get().callServiceBroker(t,s,e)}async initOnboarding(t){this.hasToShowNewVersionPopup()?await this.addPendingAction(this.NEW_VERSION_POPUP_LOCKER,(()=>this.doInitOnboarding(t))):this.doInitOnboarding(t)}doInitOnboarding(t){u.getInstance().init(t,window.envContext)}async hasAccess(t,s){return new Promise(((e,i)=>{this.getAuth(s).then((s=>{this.getAuthList(s).then((s=>{e(s.isSup||s.actions[t])})).catch((t=>i(t)))}))}))}async getAllAccess(t){return new Promise(((s,e)=>{this.getAuth(t).then((t=>{this.getAuthList(t).then((t=>{const e={};e.isSup=t.isSup,Object.entries(S).forEach((s=>{e[s[0]]=t.actions[s[1]]||!1})),s(e)})).catch((t=>e(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,i){this.clearContent(this._popUp),this._popUp.addEventListener("ezClosePopup",(()=>{i()}),{once:!0}),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}showAlerts(t){return v.showAlerts({alerts:t})}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((i=>{"1"===i?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)=>{A.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)=>{A.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){x.openAppActivity(t,s)}async webConnection(t,s,e){this.getStringParam(t).then((t=>{D.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,i,n){return null==n&&(n=this.applicationResourceID),new Promise(((r,o)=>{const a=this.getDuPromissesStack(s),c=a.length>0;if(a.push(new V(r,o)),!c){const r=this.dataUnitFetcher.getDataUnit(t,n,e,i);r.loadMetadata().then((()=>{this.processResolveDataUnit(r,s,a)})).catch((t=>{for(;a.length>0;)a.pop().reject(t)}))}}))}processResolveDataUnit(t,s,e){for(s&&this.updateDataunitCache(void 0,s,t);e.length>0;)e.pop().resolve(t)}async updateDataunitCache(t,s,e){t&&this._duCache.delete(t),this._duCache.set(s,e)}async getDataUnit(t,s,e,i,n){return new Promise(((r,o)=>{const a=this._duCache.get(s);a?r(a):this.createDataunit(t,s,e,i,n).then((t=>{r(t)})).catch((t=>o(t)))}))}async addClientEvent(t,s){return new Promise((e=>{A.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{A.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(A.hasClientEvent(t))}))}get applicationResourceID(){return this._applicationResourceID||(this._applicationResourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||x.resourceID||"unknown.resource.id"),this._applicationResourceID}async getResourceID(){return Promise.resolve(this.applicationResourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,s,e,i){return v.alert(t,s,e,i)}async error(t,s,e,i){return v.error(t,s,e,i)}async success(t,s,e,i){return v.success(t,s,e,i)}async message(t,s,e,i){return v.message(t,s,e,i)}async confirm(t,s,e,i,n){return v.confirm(t,s,e,i,n)}async info(t,s){return v.info(t,s)}async loadTotals(t,s,e){return this.totalsFetcher.fetchTotals(t,s,e)}async isLoadedByPk(){return Promise.resolve(this._isLoadedByPk)}async getAuthList(t){return await(new O).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=I.getQueryParams(location.search)),this._urlParams}getMessage(t,s){var e;return null===(e=this.messagesBuilder)||void 0===e?void 0:e.getMessage(t,s)}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new N),this._dataUnitFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new F),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new b),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new C),this._authFetcher}async executeSearch(t,s,e){const i=null==e?void 0:e.getField(s);if(i){const{mode:s,argument:n}=t,{ENTITYNAME:r,CODEFIELD:o,DESCRIPTIONFIELD:a,ROOTENTITY:c,DESCRIPTIONENTITY:h}=i.properties,l=i.dependencies;let u;const d={rootEntity:c,descriptionFieldName:a,codeFieldName:o,showInactives:!1,dataUnitId:e.dataUnitId};return null==l||l.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===p.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(u={expression:t.expression,params:t.masterFields.map((t=>{const s=e.getField(t),i=(null==s?void 0:s.dataType)||y.TEXT,n=e.getFieldValue(t);if(null==n)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:n,dataType:i}}))})})),this.executePreparedSearch(s,n,{entity:r,entityDescription:h,criteria:u,searchOptions:d})}}filterInvalidFields(t,s,e){return t.fieldsMetadata.filter((i=>{let n=!r.isEmpty(s[i.fieldName])&&!1!==i.visible&&"B"!==i.type&&t.pkField!==i.fieldName&&t.descriptionField!==i.fieldName&&(i.isPrimaryKey||!i.isLinkField)&&!("S"===i.type&&"H"===i.presentationType);return n&&(e[i.fieldName]=i),("string"!=typeof s[i.fieldName]||!(s[i.fieldName].indexOf("<img")>-1||s[i.fieldName].indexOf("<svg")>-1))&&n}))}filterMathFields(t,s,e,i){return t&&Array.isArray(t)&&t.forEach((t=>{let e=d.removeReference(s,i[t]);e&&s.unshift(e)})),s=s.slice(0,e)}builOptionItem(t,s,e,i,n){var o;return{value:r.highlightValue(t,s.__matchFields,null===(o=s[n])||void 0===o?void 0:o.toString(),e,!0),label:i?r.highlightValue(t,s.__matchFields,s[i],e,!0):"",details:w.buildDetails(t,e,s)}}async executePreparedSearch(t,s,e){const i={},{entity:n,entityDescription:r,criteria:a,searchOptions:c}=e;return new Promise("ADVANCED"===t?(t,e)=>{const i=document.createElement("snk-pesquisa");i[m.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,i.argument=s,i.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,a,c),i.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(i,void 0,void 0,e)}:(t,e)=>{this.pesquisaFetcher.loadAdvancedSearch(n,s,a,c).then((e=>{let n=(e=o.stringToObject(e.json.$)).descriptionField,r=e.pkField;const a=[];e.data.forEach((t=>{let o=this.filterInvalidFields(e,t,i),c=this.filterMathFields(t.__matchFields,o,6,i);a.push(this.builOptionItem(s,t,c,n,r))})),t(a)})).catch((t=>{e(t)}))})}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){return x.getAppLabel(this.applicationResourceID)}addSearchListener(t,s,e){return new Promise((i=>{i(this.pesquisaFetcher.addSearchListener(t,s.dataUnitId,e))}))}importScript(t){return new Promise((s=>{this.getApplicationPath().then((e=>{let i=[];Array.isArray(t)||(i=[t]),i.forEach((t=>{const s=document.createElement("script");s.src=`${e}/${t}`,s.async=!0,document.body.appendChild(s)})),s()}))}))}async getApplicationPath(){return new Promise((t=>{"dev"===window.applicationenv?t(""):t(`/${this.getModuleName()}/labsApps/${window.APPLICATION_NAME}/build`)}))}getModuleName(){return window.MGE_MODULE_NAME||"mgefin-bff"}executeSelectDistinct(t,s,e){return this.dataUnitFetcher.loadSelectDistinct(t,s,e)}getDataFetcher(){return Promise.resolve(A.get())}async whenApplicationReady(){return f.getContextValue("__SNK__APPLICATION__LOADING__")?Promise.resolve(this):new Promise((t=>{this._waitingAppReady.push((()=>t(this)))}))}async setSearchFilterContext(t,s){f.setContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${t})__`,s)}clearContent(t){t&&Array.from(t.children).forEach((s=>{t.removeChild(s)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}async pkChangeListener(){const t=top.window.location.hash.split("/")[2];if(this._currentPkParameter===t)return;const s=this.getResourceIdFromToken(),e=I.getPkObjectFromUrlToken(top.window.location.hash),i=window.redirectFrom;if(void 0===e)return;if((!i||-1===i.split("_")[0].indexOf(s.split("_")[0]))&&s!==this.applicationResourceID)return;const n={pk:e};if(this._isLoadedByPk=!0,this.loadByPK)return this.loadByPK(n,i),void(this._currentPkParameter=t);this._loadPkParameter={pk:n,redirect:i},this.defaultLoadByPK(n,t)}getResourceIdFromToken(){return top.window.location.pathname.indexOf("tabContent.jsp")>-1?I.getResourceIdFromUrlToken(window.location.generateHash(window.location.hash)):I.getResourceIdFromUrlToken(top.window.location.hash)}defaultLoadByPK(t,s){if(!(null==t?void 0:t.pk))return;const e=this.getFirstDataUnitFromDOM(),i=e.dataUnit;if(!i)return console.warn("Dataunit não inicializado"),void e.addEventListener("dataUnitReady",(e=>{this.loadDataWithPKFilter(t,e.detail),this._currentPkParameter=s}));this.loadDataWithPKFilter(t,i),this._currentPkParameter=s}loadDataWithPKFilter(t,s){const e={term:"",filter:{name:"LOAD_BY_PK_FILTER",expression:this.buildFilterExpressionByPkObject(t),params:this.getFilterParamsFromPkObject(t,s)}};s.loadData(e)}getFirstDataUnitFromDOM(){let t=this._element.querySelector("snk-data-unit[data-load-by-pk]");if(t||(t=this._element.querySelector("snk-data-unit")),t)return t}getFilterParamsFromPkObject(t,s){var e;const i=[];for(const n in t.pk)t.pk.hasOwnProperty(n)&&!Array.isArray(t.pk[n])&&i.push({name:n,dataType:(null===(e=s.getField(n))||void 0===e?void 0:e.dataType)||this.getDefaultDataTypeLoadByPK(t.pk[n]),value:t.pk[n]});return i}getDefaultDataTypeLoadByPK(t){return"number"==typeof t||t instanceof Number?y.NUMBER:"boolean"==typeof t||t instanceof Boolean?y.BOOLEAN:t instanceof Date?y.DATE:y.TEXT}buildFilterExpressionByPkObject(t){let s="";for(const e in t.pk)r.isEmpty(s)||(s+=" AND "),Array.isArray(t.pk[e])?s+=`${e} IN (${t.pk[e].toString()})`:s+=`${e} = :${e}`;return s}async showNewVersionPopup(){const t=document.createElement("ez-modal-container"),s=await this.getAppLabel();t.modalTitle=this.getMessage("snkApplication.newVersionPopup.title",{screenName:s}),t.okButtonLabel=this.getMessage("snkApplication.newVersionPopup.okButton"),t.cancelButtonLabel=this.getMessage("snkApplication.newVersionPopup.cancelButton");const e=document.createElement("p");e.innerText=this.getMessage("snkApplication.newVersionPopup.info"),e.className="ez-text",t.appendChild(e),t.addEventListener("ezModalAction",this.newVersionPopupEventListener.bind(this));const i=await v.showPopup({content:t});this._removeVersionLayoutPopup=async()=>{await i(),await this.processPendingActions(this.NEW_VERSION_POPUP_LOCKER)}}async newVersionPopupEventListener(t){"LOAD"!==t.detail&&("OK"===t.detail&&x.setScreenToUseV3Layout(),"CANCEL"===t.detail&&x.setScreenToUseOldLayout(),this._popUp.opened=!1,this._removeVersionLayoutPopup&&await this._removeVersionLayoutPopup())}async handleShowNewVersionPopup(){this.hasToShowNewVersionPopup()&&await this.showNewVersionPopup()}hasToShowNewVersionPopup(){const t=new URLSearchParams(window.location.search).get("firstLoadConv");return t&&"S"===t}registerPkChangeListener(){window.hasOwnProperty("onhashchange")?window.onhashchange=this.pkChangeListener.bind(this):setInterval(this.pkChangeListener.bind(this),100)}componentWillLoad(){f.setContextValue("__SNK__APPLICATION__LOADING__",!0),this._errorHandler=new B(this),this.messagesBuilder=new L,f.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${I.getUrlBase()}/mge/upload/file`),f.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,s,e)=>this.executeSearch(t,s,e))),f.setContextValue("__EZUI__GRID_LICENSE__",z),this.registerPkChangeListener(),P.init(),g.preload(this.applicationResourceID,this.configName,{gridLegacyConfig:this.gridLegacyConfigName,formLegacyConfig:this.formLegacyConfigName}),document.addEventListener("click",(()=>x.applicationClick())),this._waitingAppReady.forEach((t=>t()))}connectedCallback(){f.setContextValue("__SNK__APPLICATION__",this),A.addRequestListener(this._requestListener)}disconnectedCallback(){A.removeRequestListener(this._requestListener),this.removeShortcuts()}async componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{f.setContextValue("__SNK__APPLICATION__LOADING__",!1),this.applicationLoaded.emit(!0),this.pkChangeListener()})),m.addIDInfo(this._element,`resource_${this.applicationResourceID}`),await this.handleShowNewVersionPopup(),this.initKeyboardManager()}initKeyboardManager(){this._keyboardManager.bind("ctrl + g",x.searchApp.bind(this),{description:"Pesquisar por telas"}).bind("ctrl + d",x.showDesktop.bind(this),{description:"Mostrar o desktop"}).bind("F1",x.openHelp.bind(this),{description:"Abrir ajuda"})}removeShortcuts(){this._keyboardManager.unbind("ctrl + g").unbind("ctrl + d").unbind("F1")}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 i(this)}static get watchers(){return{loadByPK:["watchPropHandler"]}}};class H{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){if(null==t)return!1;if(t.url.includes("quietMode=true"))return!0;if(null==t.requestBody)return!1;if(1==t.requestBody.length){const{name:s}=t.requestBody[0].variables;if(s){const t=s.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class V{constructor(t,s){this.resolve=t,this.reject=s}}K.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{K as snk_application}
11
+ }`)}fetchTotals(t,s,e=[]){const i=`${t}_${s}`,n=this.cancel.findIndex((t=>t[i]));return n>=0&&(this.cancel[n][i](),this.cancel.splice(n,1)),Promise.race([new Promise((t=>this.cancel.push({[i]:t}))),this.getTotals(t,s,e)]).then((t=>{let s=new Map;if(t){s=t;const e=this.cancel.findIndex((t=>t[i]));e>=0&&this.cancel.splice(e,1)}return s}))}getTotals(t,s,e=[]){return new Promise(((i,n)=>{A.get().callGraphQL({query:this.templateByQuery.get("fetchTotals"),values:{name:`totals://${t}/${s}`,filters:e}}).then((t=>{if(t.length>0){const s=new Map;return t.forEach((t=>s.set(t.name,parseFloat(t.value)))),i(s)}return n("Não foi possível recuperar os totalizadores")})).catch(n)}))}}function M(){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(M=function(){return t})()}const R=$;function $(t,s){const e=M();return($=function(t){return e[t-=392]})(t,s)}!function(){const t=$,s=M();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 z=R(396);var q;class x{static openAppActivity(t,s){var e;null===(e=window.workspace)||void 0===e||e.openAppActivity(t,s)}static getAppLabel(t){if(null!=(null===window||void 0===window?void 0:window.workspace))return null==window.workspace.getAppLabel&&(window.workspace.getAppLabel=t=>(t||"").split(".").pop()),window.workspace.getAppLabel(t)}static setScreenToUseV3Layout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseV3Layout()}static setScreenToUseOldLayout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseOldLayout()}static showDesktop(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.showDesktop)||void 0===s||s.call(t)}static searchApp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.searchApp)||void 0===s||s.call(t)}static openHelp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.openHelp)||void 0===s||s.call(t)}static applicationClick(){var t,s;(null===(t=window.workspace)||void 0===t?void 0:t.applicationClick)&&(null===(s=window.workspace)||void 0===s||s.applicationClick())}}x.resourceID=null===(q=window.workspace)||void 0===q?void 0:q.resourceID;class B{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 a||(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 a||t instanceof c?this._app.alert(t.title,t.message):t instanceof h?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)}}))}}const K=class{constructor(e){t(this,e),this.applicationLoaded=s(this,"applicationLoaded",7),this.applicationLoading=s(this,"applicationLoading",7),this.NEW_VERSION_POPUP_LOCKER="NEW_VERSION_POPUP_LOCKER",this._authPromises=[],this._keyboardManager=new l,this._waitingAppReady=new Array,this._duCache=new Map,this._duPromises=new Map,this._requestListener=new H,this._pendingActions=new Map,this._loadPkParameter=null,this._isLoadedByPk=!1,this.messagesBuilder=void 0,this.configName=void 0,this.gridLegacyConfigName=void 0,this.formLegacyConfigName=void 0,this.loadByPK=void 0}async processPendingActions(t){const s=this._pendingActions.get(t);s&&s.length&&(s.forEach((t=>t())),this._pendingActions.set(t,[]))}get parameters(){return this._parameters||(this._parameters=new j),this._parameters}async getAuth(t){return null==t?this.getApplicationAuth():new Promise(((s,e)=>{this.authFetcher.getData(t).then((t=>{s(t)})).catch((t=>{e(t)}))}))}async getApplicationAuth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,s)=>{const e=this._authPromises.length>0;this._authPromises.push(new V(t,s)),e||this.authFetcher.getData(this.applicationResourceID).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)}))}))}watchPropHandler(t,s){t&&this._loadPkParameter&&(this.loadByPK(this._loadPkParameter.pk,this._loadPkParameter.redirect),this._loadPkParameter=null)}async getKeyboardManager(){return Promise.resolve(this._keyboardManager)}async isUserSup(){return new Promise(((t,s)=>{this.getAuth().then((e=>{this.getAuthList(e).then((s=>{t(s.isSup)})).catch((t=>s(t)))}))}))}async addPendingAction(t,s){var e;const i=null!==(e=this._pendingActions.get(t))&&void 0!==e?e:[];this._pendingActions.set(t,[...i,s])}async callServiceBroker(t,s,e){return A.get().callServiceBroker(t,s,e)}async initOnboarding(t){this.hasToShowNewVersionPopup()?await this.addPendingAction(this.NEW_VERSION_POPUP_LOCKER,(()=>this.doInitOnboarding(t))):this.doInitOnboarding(t)}doInitOnboarding(t){u.getInstance().init(t,window.envContext)}async hasAccess(t,s){return new Promise(((e,i)=>{this.getAuth(s).then((s=>{this.getAuthList(s).then((s=>{e(s.isSup||s.actions[t])})).catch((t=>i(t)))}))}))}async getAllAccess(t){return new Promise(((s,e)=>{this.getAuth(t).then((t=>{this.getAuthList(t).then((t=>{const e={};e.isSup=t.isSup,Object.entries(S).forEach((s=>{e[s[0]]=t.actions[s[1]]||!1})),s(e)})).catch((t=>e(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,i){this.clearContent(this._popUp),this._popUp.addEventListener("ezClosePopup",(()=>{i()}),{once:!0}),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}showAlerts(t){return v.showAlerts({alerts:t})}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((i=>{"1"===i?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)=>{A.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)=>{A.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){x.openAppActivity(t,s)}async webConnection(t,s,e){this.getStringParam(t).then((t=>{D.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,i,n){return null==n&&(n=this.applicationResourceID),new Promise(((r,o)=>{const a=this.getDuPromissesStack(s),c=a.length>0;if(a.push(new V(r,o)),!c){const r=this.dataUnitFetcher.getDataUnit(t,n,e,i);r.loadMetadata().then((()=>{this.processResolveDataUnit(r,s,a)})).catch((t=>{for(;a.length>0;)a.pop().reject(t)}))}}))}processResolveDataUnit(t,s,e){for(s&&this.updateDataunitCache(void 0,s,t);e.length>0;)e.pop().resolve(t)}async updateDataunitCache(t,s,e){t&&this._duCache.delete(t),this._duCache.set(s,e)}async getDataUnit(t,s,e,i,n){return new Promise(((r,o)=>{const a=this._duCache.get(s);a?r(a):this.createDataunit(t,s,e,i,n).then((t=>{r(t)})).catch((t=>o(t)))}))}async addClientEvent(t,s){return new Promise((e=>{A.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{A.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(A.hasClientEvent(t))}))}get applicationResourceID(){return this._applicationResourceID||(this._applicationResourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||x.resourceID||"unknown.resource.id"),this._applicationResourceID}async getResourceID(){return Promise.resolve(this.applicationResourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,s,e,i){return v.alert(t,s,e,i)}async error(t,s,e,i){return v.error(t,s,e,i)}async success(t,s,e,i){return v.success(t,s,e,i)}async message(t,s,e,i){return v.message(t,s,e,i)}async confirm(t,s,e,i,n){return v.confirm(t,s,e,i,n)}async info(t,s){return v.info(t,s)}async loadTotals(t,s,e){return this.totalsFetcher.fetchTotals(t,s,e)}async isLoadedByPk(){return Promise.resolve(this._isLoadedByPk)}async getAuthList(t){return await(new O).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=I.getQueryParams(location.search)),this._urlParams}getMessage(t,s){var e;return null===(e=this.messagesBuilder)||void 0===e?void 0:e.getMessage(t,s)}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new b),this._dataUnitFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new F),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new N),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new C),this._authFetcher}async executeSearch(t,s,e){const i=null==e?void 0:e.getField(s);if(i){const{mode:s,argument:n}=t,{ENTITYNAME:r,CODEFIELD:o,DESCRIPTIONFIELD:a,ROOTENTITY:c,DESCRIPTIONENTITY:h}=i.properties,l=i.dependencies;let u;const d={rootEntity:c,descriptionFieldName:a,codeFieldName:o,showInactives:!1,dataUnitId:e.dataUnitId};return null==l||l.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===p.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(u={expression:t.expression,params:t.masterFields.map((t=>{const s=e.getField(t),i=(null==s?void 0:s.dataType)||f.TEXT,n=e.getFieldValue(t);if(null==n)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:n,dataType:i}}))})})),this.executePreparedSearch(s,n,{entity:r,entityDescription:h,criteria:u,searchOptions:d})}}filterInvalidFields(t,s,e){return t.fieldsMetadata.filter((i=>{let n=!r.isEmpty(s[i.fieldName])&&!1!==i.visible&&"B"!==i.type&&t.pkField!==i.fieldName&&t.descriptionField!==i.fieldName&&(i.isPrimaryKey||!i.isLinkField)&&!("S"===i.type&&"H"===i.presentationType);return n&&(e[i.fieldName]=i),("string"!=typeof s[i.fieldName]||!(s[i.fieldName].indexOf("<img")>-1||s[i.fieldName].indexOf("<svg")>-1))&&n}))}filterMathFields(t,s,e,i){return t&&Array.isArray(t)&&t.forEach((t=>{let e=d.removeReference(s,i[t]);e&&s.unshift(e)})),s=s.slice(0,e)}builOptionItem(t,s,e,i,n){var o;return{value:r.highlightValue(t,s.__matchFields,null===(o=s[n])||void 0===o?void 0:o.toString(),e,!0),label:i?r.highlightValue(t,s.__matchFields,s[i],e,!0):"",details:w.buildDetails(t,e,s)}}async executePreparedSearch(t,s,e){const i={},{entity:n,entityDescription:r,criteria:a,searchOptions:c}=e;return new Promise("ADVANCED"===t?(t,e)=>{const i=document.createElement("snk-pesquisa");i[m.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,i.argument=s,i.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,a,c),i.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(i,void 0,void 0,e)}:(t,e)=>{this.pesquisaFetcher.loadAdvancedSearch(n,s,a,c).then((e=>{let n=(e=o.stringToObject(e.json.$)).descriptionField,r=e.pkField;const a=[];e.data.forEach((t=>{let o=this.filterInvalidFields(e,t,i),c=this.filterMathFields(t.__matchFields,o,6,i);a.push(this.builOptionItem(s,t,c,n,r))})),t(a)})).catch((t=>{e(t)}))})}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){return x.getAppLabel(this.applicationResourceID)}addSearchListener(t,s,e){return new Promise((i=>{i(this.pesquisaFetcher.addSearchListener(t,s.dataUnitId,e))}))}importScript(t){return new Promise((s=>{this.getApplicationPath().then((e=>{let i=[];Array.isArray(t)||(i=[t]),i.forEach((t=>{const s=document.createElement("script");s.src=`${e}/${t}`,s.async=!0,document.body.appendChild(s)})),s()}))}))}async getApplicationPath(){return new Promise((t=>{"dev"===window.applicationenv?t(""):t(`/${this.getModuleName()}/labsApps/${window.APPLICATION_NAME}/build`)}))}getModuleName(){return window.MGE_MODULE_NAME||"mgefin-bff"}executeSelectDistinct(t,s,e){return this.dataUnitFetcher.loadSelectDistinct(t,s,e)}getDataFetcher(){return Promise.resolve(A.get())}async whenApplicationReady(){return y.getContextValue("__SNK__APPLICATION__LOADING__")?Promise.resolve(this):new Promise((t=>{this._waitingAppReady.push((()=>t(this)))}))}async setSearchFilterContext(t,s){y.setContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${t})__`,s)}clearContent(t){t&&Array.from(t.children).forEach((s=>{t.removeChild(s)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}async pkChangeListener(){const t=top.window.location.hash.split("/")[2];if(this._currentPkParameter===t)return;const s=this.getResourceIdFromToken(),e=I.getPkObjectFromUrlToken(top.window.location.hash),i=window.redirectFrom;if(void 0===e)return;if((!i||-1===i.split("_")[0].indexOf(s.split("_")[0]))&&s!==this.applicationResourceID)return;const n={pk:e};if(this._isLoadedByPk=!0,this.loadByPK)return this.loadByPK(n,i),void(this._currentPkParameter=t);this._loadPkParameter={pk:n,redirect:i},this.defaultLoadByPK(n,t)}getResourceIdFromToken(){return top.window.location.pathname.indexOf("tabContent.jsp")>-1?I.getResourceIdFromUrlToken(window.location.generateHash(window.location.hash)):I.getResourceIdFromUrlToken(top.window.location.hash)}defaultLoadByPK(t,s){if(!(null==t?void 0:t.pk))return;const e=this.getFirstDataUnitFromDOM(),i=e.dataUnit;if(!i)return console.warn("Dataunit não inicializado"),void e.addEventListener("dataUnitReady",(e=>{this.loadDataWithPKFilter(t,e.detail),this._currentPkParameter=s}));this.loadDataWithPKFilter(t,i),this._currentPkParameter=s}loadDataWithPKFilter(t,s){const e={term:"",filter:{name:"LOAD_BY_PK_FILTER",expression:this.buildFilterExpressionByPkObject(t),params:this.getFilterParamsFromPkObject(t,s)}};s.loadData(e)}getFirstDataUnitFromDOM(){let t=this._element.querySelector("snk-data-unit[data-load-by-pk]");if(t||(t=this._element.querySelector("snk-data-unit")),t)return t}getFilterParamsFromPkObject(t,s){var e;const i=[];for(const n in t.pk)t.pk.hasOwnProperty(n)&&!Array.isArray(t.pk[n])&&i.push({name:n,dataType:(null===(e=s.getField(n))||void 0===e?void 0:e.dataType)||this.getDefaultDataTypeLoadByPK(t.pk[n]),value:t.pk[n]});return i}getDefaultDataTypeLoadByPK(t){return"number"==typeof t||t instanceof Number?f.NUMBER:"boolean"==typeof t||t instanceof Boolean?f.BOOLEAN:t instanceof Date?f.DATE:f.TEXT}buildFilterExpressionByPkObject(t){let s="";for(const e in t.pk)r.isEmpty(s)||(s+=" AND "),Array.isArray(t.pk[e])?s+=`${e} IN (${t.pk[e].toString()})`:s+=`${e} = :${e}`;return s}async showNewVersionPopup(){const t=document.createElement("ez-modal-container"),s=await this.getAppLabel();t.modalTitle=this.getMessage("snkApplication.newVersionPopup.title",{screenName:s}),t.okButtonLabel=this.getMessage("snkApplication.newVersionPopup.okButton"),t.cancelButtonLabel=this.getMessage("snkApplication.newVersionPopup.cancelButton");const e=document.createElement("p");e.innerText=this.getMessage("snkApplication.newVersionPopup.info"),e.className="ez-text",t.appendChild(e),t.addEventListener("ezModalAction",this.newVersionPopupEventListener.bind(this));const i=await v.showPopup({content:t});this._removeVersionLayoutPopup=async()=>{await i(),await this.processPendingActions(this.NEW_VERSION_POPUP_LOCKER)}}async newVersionPopupEventListener(t){"LOAD"!==t.detail&&("OK"===t.detail&&x.setScreenToUseV3Layout(),"CANCEL"===t.detail&&x.setScreenToUseOldLayout(),this._popUp.opened=!1,this._removeVersionLayoutPopup&&await this._removeVersionLayoutPopup())}async handleShowNewVersionPopup(){this.hasToShowNewVersionPopup()&&await this.showNewVersionPopup()}hasToShowNewVersionPopup(){const t=new URLSearchParams(window.location.search).get("firstLoadConv");return t&&"S"===t}registerPkChangeListener(){window.hasOwnProperty("onhashchange")?window.onhashchange=this.pkChangeListener.bind(this):setInterval(this.pkChangeListener.bind(this),100)}componentWillLoad(){y.setContextValue("__SNK__APPLICATION__LOADING__",!0),this._errorHandler=new B(this),this.messagesBuilder=new L,y.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${I.getUrlBase()}/mge/upload/file`),y.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,s,e)=>this.executeSearch(t,s,e))),y.setContextValue("__EZUI__GRID_LICENSE__",z),this.registerPkChangeListener(),P.init(),g.preload(this.applicationResourceID,this.configName,{gridLegacyConfig:this.gridLegacyConfigName,formLegacyConfig:this.formLegacyConfigName}),document.addEventListener("click",(()=>x.applicationClick())),this._waitingAppReady.forEach((t=>t()))}connectedCallback(){y.setContextValue("__SNK__APPLICATION__",this),A.addRequestListener(this._requestListener)}disconnectedCallback(){A.removeRequestListener(this._requestListener),this.removeShortcuts()}async componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{y.setContextValue("__SNK__APPLICATION__LOADING__",!1),this.applicationLoaded.emit(!0),this.pkChangeListener()})),m.addIDInfo(this._element,`resource_${this.applicationResourceID}`),await this.handleShowNewVersionPopup(),this.initKeyboardManager()}initKeyboardManager(){this._keyboardManager.bind("ctrl + g",x.searchApp.bind(this),{description:"Pesquisar por telas"}).bind("ctrl + d",x.showDesktop.bind(this),{description:"Mostrar o desktop"}).bind("F1",x.openHelp.bind(this),{description:"Abrir ajuda"})}removeShortcuts(){this._keyboardManager.unbind("ctrl + g").unbind("ctrl + d").unbind("F1")}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 i(this)}static get watchers(){return{loadByPK:["watchPropHandler"]}}};class H{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){if(null==t)return!1;if(t.url.includes("quietMode=true"))return!0;if(null==t.requestBody)return!1;if(1==t.requestBody.length){const{name:s}=t.requestBody[0].variables;if(s){const t=s.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class V{constructor(t,s){this.resolve=t,this.reject=s}}K.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{K as snk_application}
@@ -1 +1 @@
1
- import{r as t,c as i,h as s,g as e,H as a}from"./p-d2d301a6.js";import{Action as n,ObjectUtils as h,DataUnitAction as r,StringUtils as o,ApplicationContext as d}from"@sankhyalabs/core";import{ApplicationUtils as l,DialogType as c}from"@sankhyalabs/ezui/dist/collection/utils";import{O as u,S as v}from"./p-7ef9c55c.js";import{g as f,a as m}from"./p-fe79f83a.js";import{g as b}from"./p-9863d682.js";import{convertType as p}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";const D=class{constructor(s){t(this,s),this.dataStateChange=i(this,"dataStateChange",3),this.dataUnitReady=i(this,"dataUnitReady",3),this.messagesBuilderUpdated=i(this,"messagesBuilderUpdated",3),this.dataUnitFieldsHidded=i(this,"dataUnitFieldsHidded",7),this.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this._openedAlert=!1,this._fieldsWithRmp=[],this._fieldsWithRmPrecision=[],this._metadataByRow=new Map,this._rowMetadataCache=new Map,this.REGEX_DATAUNIT_NAME=/dd:\/\/(.+?)\//,this._dataUnitObserver=async t=>{const i=this.buildDataState(t.type);switch(this.dataState=i,this.messagesBuilder.currentOperation=this.getMessageOperation(),t.type){case n.DATA_SAVED:await this.handleDataSaved(t);break;case n.RECORDS_ADDED:case n.RECORDS_COPIED:this.insertionMode.emit();break;case n.EDITION_CANCELED:this.cancelEdition.emit();break;case n.RECORDS_REMOVED:this.handleRecordsRemoved(t);break;case n.METADATA_LOADED:this.fillFieldsWithRmp(this.dataUnit.metadata),this.fillFieldsWithRmPrecision(this.dataUnit.metadata)}},this.fieldsToLink=[],this.dataState=void 0,this.messagesBuilder=void 0,this.dataUnitName=void 0,this.entityName=void 0,this.pageSize=150,this.dataUnit=void 0,this.beforeSave=void 0,this.afterSave=void 0,this.useCancelConfirm=!0,this.ignoreSaveMessage=void 0,this.configName=void 0,this.resourceID=void 0,this.domainMessagesBuilder=void 0}observePageSize(){this.dataUnit&&(this.dataUnit.pageSize=this.pageSize)}observeDataUnitName(t,i){i!=t&&(this.dataUnit?this._application.updateDataunitCache(i,this.dataUnitName,this.dataUnit):this.loadDataUnit())}observeEntityName(t,i){i!=t&&(this.dataUnit=void 0,this.entityName=t,this.loadDataUnit())}observeDataState(t,i){h.objectToString(i)!=h.objectToString(t)&&this.dataStateChange.emit(t)}observeDataUnit(){this.handlerLinkFields(),this.dataUnitReady.emit(this.dataUnit)}observeMessagesBuilder(t){t&&this.messagesBuilderUpdated.emit(t)}async getDataUnit(){return new Promise((t=>{this.dataUnit?t(this.dataUnit):this._onDataUnitResolve.push(t)}))}async getSelectedRecordsIDsInfo(){return Promise.resolve(b(this.dataUnit))}async getFieldsWithRmp(){return this._fieldsWithRmp}async getFieldsWithRmPrecision(){return this._fieldsWithRmPrecision}async getRowMetadata(t){return this.doGetRowMetadata(t)}doGetRowMetadata(t){const i=this.dataUnit.getSelectedRecord();if(!t&&!i)return;const s=t||i,e=this._metadataByRow.get("string"==typeof s?s:s.__record__id__);return e?(e.getProp=this.buildGetPropRowMetadata(e),Object.assign({},e)):void 0}buildGetPropRowMetadata(t){return(i,s)=>("rm_precision"===i&&(i=this.resolvePrecisionFromMetadata(s)),h.getProp(t,i))}resolvePrecisionFromMetadata(t){var i,s;if(!t)return void l.error(this.getMessage("snkDataUnit.fieldNameRequired"));const e=null===(s=null===(i=this.dataUnit.getField(t))||void 0===i?void 0:i.properties)||void 0===s?void 0:s.rm_precision;return e?e.split(".").filter(((t,i)=>1!==i)).join("."):""}getCleanOnCopyFields(){var t;return null===(t=this.dataUnit.metadata)||void 0===t?void 0:t.fields.filter((t=>{var i;return null===(i=t.properties)||void 0===i?void 0:i.cleanOnCopy})).map((t=>t.name))}fillFieldsWithRmp(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rmp)&&!this._fieldsWithRmp.includes(t.name)&&this._fieldsWithRmp.push(t.name)}))}fillFieldsWithRmPrecision(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rm_precision)&&!this._fieldsWithRmPrecision.includes(t.name)&&this._fieldsWithRmPrecision.push(t.name)}))}getCacheName(t,i,s){return[t,i,s].join("_")}updateDataStateRmp(t){const i=Object.assign({},t);this.dataState.rowMetadata=i}saveCacheRmd(t){const i=t.__record__metadata__,s=Object.keys(i);s.shift(),s.forEach((s=>{const e=f(t,s),a=this.getCacheName(s,i.provider,e);this._rowMetadataCache.set(a,Object.assign({},i))}))}getMetadataByRow(t){var i;if(!(null===(i=t.records)||void 0===i?void 0:i.length))return t;if(!this._fieldsWithRmp.length){const i=t.records.map((t=>(delete t.__record__metadata__,t)));return Object.assign(Object.assign({},t),{records:i})}const s=t.records.map((t=>{if(!t.__record__metadata__)return t;this.saveCacheRmd(t);const i=Object.assign({},t.__record__metadata__);return i.getProp=this.buildGetPropRowMetadata(i),this._metadataByRow.set(t.__record__id__,i),delete t.__record__metadata__,t}));return Object.assign(Object.assign({},t),{records:s})}interceptRecordsAdded(t){if(this.isAllowed("INSERT"))return new r(n.RECORDS_ADDED,this.handleLinksWithParent(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenInsert"))}interceptRecordsCopied(t){if(this.isAllowed("CLONE"))return new r(n.RECORDS_COPIED,this.handleRecordsCopied(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenClone"))}async interceptDataChange(t){if(this.isAllowed("UPDATE"))return t;this._openedAlert?await this.dataUnit.cancelEdition():(this._openedAlert=!0,await this.dataUnit.cancelEdition(),await l.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")),this._openedAlert=!1)}async interceptSavingData(t){if(!this.beforeSave)return t;const i=this.beforeSave(this.dataUnit);return i instanceof Promise?await i?t:void 0:i?t:void 0}interceptDataSaved(t){if(!this.afterSave)return t;this.afterSave(this.dataUnit)}async interceptEditionCanceled(t){var i,s;if(!this.useCancelConfirm||!this.dataState.hasDirtyRecords||(null===(i=t.payload)||void 0===i?void 0:i.fromParent)||(null===(s=t.payload)||void 0===s?void 0:s.silent))return t;const e=this.getMessage("snkDataUnit.cancelConfirmation");if(null==e)return this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),t;const a=this.getMessage("snkDataUnit.cancelConfirmationTitle"),n=await l.confirm(a,e);return n&&this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),n?t:void 0}async interceptRemovingRecords(t){var i,s,e;if(!this.isAllowed("REMOVE"))return void l.info(this.getMessage("snkDataUnit.forbiddenRemove"));let a=!1,n=!(null===(i=t.payload)||void 0===i?void 0:i.silent)&&this.getMessage("snkDataUnit.removeConfirmation");const h=null===(s=this.dataUnit)||void 0===s?void 0:s.getSelectionInfo();if(!(null===(e=t.payload)||void 0===e?void 0:e.silent)&&(null==h?void 0:h.length)>1&&(n=this.getMessage("snkDataUnit.removeAllConfirmation",{size:h.length}),a=!0),!n)return t;const r={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm."+(a?"no":"cancel")),labelConfirm:this.getMessage("snkDataUnit.confirm."+(a?"yes":"delete")),btnConfirmDanger:!1},o=this.getMessage("snkDataUnit.removeConfirmationTitle");return await l.confirm(o,n,null,c.WARN,r)?t:void 0}interceptDataLoaded(t){const i=this.getMetadataByRow(t.payload);return new r(n.DATA_LOADED,i)}interceptMetadataLoaded(t){return this.fillFieldsWithRmp(t.payload),this.fillFieldsWithRmPrecision(t.payload),new r(n.METADATA_LOADED,this.handleDULinksOnMetadataLoaded(t.payload))}async interceptAction(t){switch(t.type){case n.RECORDS_ADDED:return this.interceptRecordsAdded(t);case n.RECORDS_COPIED:return this.interceptRecordsCopied(t);case n.DATA_CHANGED:return await this.handleLoadRowMetadata(t),await this.interceptDataChange(t);case n.CHANGING_DATA:return await this.interceptDataChange(t);case n.SAVING_DATA:return await this.interceptSavingData(t);case n.DATA_SAVED:return this.interceptDataSaved(t);case n.EDITION_CANCELED:return await this.interceptEditionCanceled(t);case n.REMOVING_RECORDS:return await this.interceptRemovingRecords(t);case n.DATA_LOADED:return this.interceptDataLoaded(t);case n.METADATA_LOADED:return this.interceptMetadataLoaded(t);default:return t}}async handleLoadRowMetadata(t){const i=t.type===n.DATA_CHANGED?t.payload:t.payload.changes[0].record,s=Object.keys(i).find((t=>this._fieldsWithRmp.includes(t)));if(s){const t=this.dataUnit.getField(s).properties.rmp,e=f(i,s);return await this.updateRowMetadata({fieldName:s,fieldValue:e,metadataName:t,updatedFields:i})}}async updateRowMetadata({fieldName:t,fieldValue:i,metadataName:s,updatedFields:e}){const a=this.getCacheName(t,s,i),n=this._rowMetadataCache.get(a);if(n)return this.updateDataStateRmp(n),n;{const i=new m,n=await i.loadRowMetadata(this,t,s,e);return this.updateDataStateRmp(n._rmd),this._rowMetadataCache.set(a,Object.assign({},n._rmd)),Object.assign({},n._rmd)}}handleDULinksOnMetadataLoaded(t){const i=Object.assign({},t);return this.processLinks(i),i}handleRecordsCopied(t){let i=[...t];return i=this.handleCleanOnCopy(i),this.handleLinksWithParent(i)}handleLinksWithParent(t){var i,s;const e=null!==(i=this._parentDataUnit)&&void 0!==i?i:null===(s=this.dataUnit)||void 0===s?void 0:s.getParentDataUnit();if(!e)return t;const a=e.getSelectedRecord(),n=null==e?void 0:e.getChildInfo(this.getCleanDataUnitName()),{links:h}=n;return h&&0!==h.length?t.map((t=>this.buildRecordWithLinkedFields(t,h,a))):t}buildRecordWithLinkedFields(t,i,s){const e=Object.assign({},t);return i.forEach((t=>{const i=p(this.dataUnit.getField(t.target).dataType,s[t.source]);e[t.target]=i})),e}handleCleanOnCopy(t){const i=this.getCleanOnCopyFields();return i.length>0&&(t=t.map((t=>this.buildCopyWithCleanedFields(t,i)))),t}buildCopyWithCleanedFields(t,i){const s=Object.assign({},t);return i.forEach((t=>delete s[t])),s}showSuccessMessage(t){l.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}buildDataState(t){var i;const s=this.dataUnit.getSelectionInfo(),e=(this.dataUnit.hasDirtyRecords()||this.dataUnit.hasWaitingChanges())&&(null==s?void 0:s.isEmpty()),a=this.dataUnit.getSelectedRecord();let h=null===(i=this.dataState)||void 0===i?void 0:i.rowMetadata;return!a||h&&![n.SELECTION_CHANGED,n.EDITION_CANCELED,n.NEXT_SELECTED,n.PREVIOUS_SELECTED].includes(t)?h&&(h.getProp=this.buildGetPropRowMetadata(h)):h=this.doGetRowMetadata(a),new w({insertionMode:this.dataUnit.hasNewRecord(),isStartingInsertionMode:e,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:this.dataUnit.hasCopiedRecord(),isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:void 0,selectionInfo:s,selectedRecord:a,recordsIsEmpty:0===this.dataUnit.records.length,metadataByRow:this._metadataByRow,rowMetadata:h})}async handleDataSaved(t){const i=await this.handleLoadRowMetadata(t);if(i&&(i.getProp=this.buildGetPropRowMetadata(i)),this._metadataByRow.set(t.payload.records[0].__record__id__,i),this.dataState=this.buildDataState(),this.ignoreSaveMessage)return;const s=t.payload.changes[0]._operation.toLowerCase(),e=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0],s);null!=e&&this.showSuccessMessage(e)}handleRecordsRemoved(t){var i,s;const e=t.payload.cachedRecords;let a;a=(null==e?void 0:e.length)>1?this.getMessage("snkDataUnit.removeAllInfo",{size:e.length}):this.getMessage("snkDataUnit.removeInfo",t.payload.cachedRecords[0]),null!=a&&this.showSuccessMessage(a);const n=null!==(s=null===(i=this.dataUnit.records)||void 0===i?void 0:i.length)&&void 0!==s?s:0,h=this.dataUnit.getPaginationInfo();h&&this.dataUnit.gotoPage(n>0||h.hasMore?h.currentPage:0)}getMessage(t,i,s){return i||(i=this.getMessageParams()),s&&(this.messagesBuilder.currentOperation=s),this.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecord}getMessageOperation(){return this.dataState.copyMode?u.CLONE:this.dataState.insertionMode||this.dataState.isStartingInsertionMode?u.INSERT:this.dataState.isDirty?u.UPDATE:u.CLEAN}async getDataUnitParentOrChild(){var t;const i=this.dataUnitName?this.dataUnitName:this.entityName;return this._parentSnkDataUnit?(this._parentDataUnit=await(null===(t=this._parentSnkDataUnit)||void 0===t?void 0:t.getDataUnit()),await this._application.getDataUnit(this.entityName,i,this._parentDataUnit,this.configName,this.resourceID)):await this._application.getDataUnit(this.entityName,i,null,this.configName,this.resourceID)}async loadDataUnit(){var t;if(null==this.dataUnit&&this._application&&this.entityName&&(this.dataUnit=await this.getDataUnitParentOrChild()),this.dataUnit){let i;for(this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.addInterceptor(this),this.dataUnit.subscribe(this._dataUnitObserver),await this.dataUnit.loadMetadata(),(null===(t=this.dataUnit.records)||void 0===t?void 0:t.length)&&this.getMetadataByRow(this.dataUnit),this.dataState=this.buildDataState();i=this._onDataUnitResolve.pop();)i(this.dataUnit)}}getParentSnkDataUnit(){let t=this.element;for(;t.parentNode;){if("SNK-DATA-UNIT"===t.parentNode.nodeName)return t.parentNode;t=t.parentNode}}handlerLinkFields(){var t,i,s,e;const a=null!==(t=this._parentDataUnit)&&void 0!==t?t:null===(i=this.dataUnit)||void 0===i?void 0:i.getParentDataUnit();if(!a)return;const n=null!==(s=this.entityName)&&void 0!==s?s:this.getCleanDataUnitName(),h=a.getChildInfo(n);if(!h)return;const r=null===(e=null==h?void 0:h.links)||void 0===e?void 0:e.map((t=>t.target));this.handleDUWithLinks(r)}handleDUWithLinks(t){this.fieldsToLink=t;const i=Object.assign({},this.dataUnit.metadata);this.processLinks(i),this.dataUnit.metadata=i,this.dataUnitFieldsHidded.emit()}processLinks(t){var i;null===(i=null==t?void 0:t.fields)||void 0===i||i.forEach((t=>{var i;(null===(i=this.fieldsToLink)||void 0===i?void 0:i.includes(t.name))&&(t.visible=!1)}))}getCleanDataUnitName(){var t;const i=this.dataUnit.name;if(o.isEmpty(i))return i;const s=this.REGEX_DATAUNIT_NAME.exec(i);return null!==(t=null==s?void 0:s[1])&&void 0!==t?t:i}static getNearestInstance(t){let i=t.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase())return i;i=i.parentElement}}instanceMessagesBuilder(){var t;this.messagesBuilder||(this.messagesBuilder=new v(null!==(t=this.domainMessagesBuilder)&&void 0!==t?t:this.entityName))}componentWillLoad(){this._application=d.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess(this.resourceID).then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit(),this.instanceMessagesBuilder()}disconnectedCallback(){this.dataUnit&&this.dataUnit.releaseCallbacks()}async componentDidLoad(){await this.loadDataUnit(),this.handlerLinkFields()}render(){return s(a,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"],messagesBuilder:["observeMessagesBuilder"]}}};class w{constructor(t){this.copyMode=t.copyMode,this.insertionMode=t.insertionMode,this.isStartingInsertionMode=t.isStartingInsertionMode,this.isDirty=t.isDirty,this.hasDirtyRecords=t.hasDirtyRecords,this.hasNext=t.hasNext,this.hasPrevious=t.hasPrevious,this.selectionInfo=t.selectionInfo,this.selectedRecord=t.selectedRecord,this.recordsIsEmpty=t.recordsIsEmpty,this.metadataByRow=t.metadataByRow,this.rowMetadata=t.rowMetadata}get selectedRecords(){var t;if(console.warn("SnkDataUnit: O método `selectedRecords` foi descontinuado. Use o método `selectionInfo`."),null===(t=this.selectionInfo)||void 0===t?void 0:t.isAllRecords())throw new Error("Erro interno: Impossível obter os registros selecionados. A seleção atual é virtual. Use o atributo `selectionInfo`.");return this.selectionInfo.records}}export{D as S}
1
+ import{r as t,c as i,h as s,g as e,H as a}from"./p-d2d301a6.js";import{Action as n,ObjectUtils as h,DataUnitAction as r,StringUtils as o,ApplicationContext as d}from"@sankhyalabs/core";import{ApplicationUtils as l,DialogType as c}from"@sankhyalabs/ezui/dist/collection/utils";import{O as u,S as v}from"./p-7ef9c55c.js";import{g as f,a as m}from"./p-091ce761.js";import{g as b}from"./p-9863d682.js";import{convertType as p}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";const D=class{constructor(s){t(this,s),this.dataStateChange=i(this,"dataStateChange",3),this.dataUnitReady=i(this,"dataUnitReady",3),this.messagesBuilderUpdated=i(this,"messagesBuilderUpdated",3),this.dataUnitFieldsHidded=i(this,"dataUnitFieldsHidded",7),this.insertionMode=i(this,"insertionMode",3),this.cancelEdition=i(this,"cancelEdition",3),this._onDataUnitResolve=[],this._openedAlert=!1,this._fieldsWithRmp=[],this._fieldsWithRmPrecision=[],this._metadataByRow=new Map,this._rowMetadataCache=new Map,this.REGEX_DATAUNIT_NAME=/dd:\/\/(.+?)\//,this._dataUnitObserver=async t=>{const i=this.buildDataState(t.type);switch(this.dataState=i,this.messagesBuilder.currentOperation=this.getMessageOperation(),t.type){case n.DATA_SAVED:await this.handleDataSaved(t);break;case n.RECORDS_ADDED:case n.RECORDS_COPIED:this.insertionMode.emit();break;case n.EDITION_CANCELED:this.cancelEdition.emit();break;case n.RECORDS_REMOVED:this.handleRecordsRemoved(t);break;case n.METADATA_LOADED:this.fillFieldsWithRmp(this.dataUnit.metadata),this.fillFieldsWithRmPrecision(this.dataUnit.metadata)}},this.fieldsToLink=[],this.dataState=void 0,this.messagesBuilder=void 0,this.dataUnitName=void 0,this.entityName=void 0,this.pageSize=150,this.dataUnit=void 0,this.beforeSave=void 0,this.afterSave=void 0,this.useCancelConfirm=!0,this.ignoreSaveMessage=void 0,this.configName=void 0,this.resourceID=void 0,this.domainMessagesBuilder=void 0}observePageSize(){this.dataUnit&&(this.dataUnit.pageSize=this.pageSize)}observeDataUnitName(t,i){i!=t&&(this.dataUnit?this._application.updateDataunitCache(i,this.dataUnitName,this.dataUnit):this.loadDataUnit())}observeEntityName(t,i){i!=t&&(this.dataUnit=void 0,this.entityName=t,this.loadDataUnit())}observeDataState(t,i){h.objectToString(i)!=h.objectToString(t)&&this.dataStateChange.emit(t)}observeDataUnit(){this.handlerLinkFields(),this.dataUnitReady.emit(this.dataUnit)}observeMessagesBuilder(t){t&&this.messagesBuilderUpdated.emit(t)}async getDataUnit(){return new Promise((t=>{this.dataUnit?t(this.dataUnit):this._onDataUnitResolve.push(t)}))}async getSelectedRecordsIDsInfo(){return Promise.resolve(b(this.dataUnit))}async getFieldsWithRmp(){return this._fieldsWithRmp}async getFieldsWithRmPrecision(){return this._fieldsWithRmPrecision}async getRowMetadata(t){return this.doGetRowMetadata(t)}doGetRowMetadata(t){const i=this.dataUnit.getSelectedRecord();if(!t&&!i)return;const s=t||i,e=this._metadataByRow.get("string"==typeof s?s:s.__record__id__);return e?(e.getProp=this.buildGetPropRowMetadata(e),Object.assign({},e)):void 0}buildGetPropRowMetadata(t){return(i,s)=>("rm_precision"===i&&(i=this.resolvePrecisionFromMetadata(s)),h.getProp(t,i))}resolvePrecisionFromMetadata(t){var i,s;if(!t)return void l.error(this.getMessage("snkDataUnit.fieldNameRequired"));const e=null===(s=null===(i=this.dataUnit.getField(t))||void 0===i?void 0:i.properties)||void 0===s?void 0:s.rm_precision;return e?e.split(".").filter(((t,i)=>1!==i)).join("."):""}getCleanOnCopyFields(){var t;return null===(t=this.dataUnit.metadata)||void 0===t?void 0:t.fields.filter((t=>{var i;return null===(i=t.properties)||void 0===i?void 0:i.cleanOnCopy})).map((t=>t.name))}fillFieldsWithRmp(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rmp)&&!this._fieldsWithRmp.includes(t.name)&&this._fieldsWithRmp.push(t.name)}))}fillFieldsWithRmPrecision(t){t.fields.forEach((t=>{var i;(null===(i=t.properties)||void 0===i?void 0:i.rm_precision)&&!this._fieldsWithRmPrecision.includes(t.name)&&this._fieldsWithRmPrecision.push(t.name)}))}getCacheName(t,i,s){return[t,i,s].join("_")}updateDataStateRmp(t){const i=Object.assign({},t);this.dataState.rowMetadata=i}saveCacheRmd(t){const i=t.__record__metadata__,s=Object.keys(i);s.shift(),s.forEach((s=>{const e=f(t,s),a=this.getCacheName(s,i.provider,e);this._rowMetadataCache.set(a,Object.assign({},i))}))}getMetadataByRow(t){var i;if(!(null===(i=t.records)||void 0===i?void 0:i.length))return t;if(!this._fieldsWithRmp.length){const i=t.records.map((t=>(delete t.__record__metadata__,t)));return Object.assign(Object.assign({},t),{records:i})}const s=t.records.map((t=>{if(!t.__record__metadata__)return t;this.saveCacheRmd(t);const i=Object.assign({},t.__record__metadata__);return i.getProp=this.buildGetPropRowMetadata(i),this._metadataByRow.set(t.__record__id__,i),delete t.__record__metadata__,t}));return Object.assign(Object.assign({},t),{records:s})}interceptRecordsAdded(t){if(this.isAllowed("INSERT"))return new r(n.RECORDS_ADDED,this.handleLinksWithParent(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenInsert"))}interceptRecordsCopied(t){if(this.isAllowed("CLONE"))return new r(n.RECORDS_COPIED,this.handleRecordsCopied(t.payload));l.info(this.getMessage("snkDataUnit.forbiddenClone"))}async interceptDataChange(t){if(this.isAllowed("UPDATE"))return t;this._openedAlert?await this.dataUnit.cancelEdition():(this._openedAlert=!0,await this.dataUnit.cancelEdition(),await l.alert(this.getMessage("snkDataUnit.forbidden"),this.getMessage("snkDataUnit.forbiddenUpdate")),this._openedAlert=!1)}async interceptSavingData(t){if(!this.beforeSave)return t;const i=this.beforeSave(this.dataUnit);return i instanceof Promise?await i?t:void 0:i?t:void 0}interceptDataSaved(t){if(!this.afterSave)return t;this.afterSave(this.dataUnit)}async interceptEditionCanceled(t){var i,s;if(!this.useCancelConfirm||!this.dataState.hasDirtyRecords||(null===(i=t.payload)||void 0===i?void 0:i.fromParent)||(null===(s=t.payload)||void 0===s?void 0:s.silent))return t;const e=this.getMessage("snkDataUnit.cancelConfirmation");if(null==e)return this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),t;const a=this.getMessage("snkDataUnit.cancelConfirmationTitle"),n=await l.confirm(a,e);return n&&this.showSuccessMessage(this.getMessage("snkDataUnit.cancelInfo")),n?t:void 0}async interceptRemovingRecords(t){var i,s,e;if(!this.isAllowed("REMOVE"))return void l.info(this.getMessage("snkDataUnit.forbiddenRemove"));let a=!1,n=!(null===(i=t.payload)||void 0===i?void 0:i.silent)&&this.getMessage("snkDataUnit.removeConfirmation");const h=null===(s=this.dataUnit)||void 0===s?void 0:s.getSelectionInfo();if(!(null===(e=t.payload)||void 0===e?void 0:e.silent)&&(null==h?void 0:h.length)>1&&(n=this.getMessage("snkDataUnit.removeAllConfirmation",{size:h.length}),a=!0),!n)return t;const r={canClose:!1,labelCancel:this.getMessage("snkDataUnit.confirm."+(a?"no":"cancel")),labelConfirm:this.getMessage("snkDataUnit.confirm."+(a?"yes":"delete")),btnConfirmDanger:!1},o=this.getMessage("snkDataUnit.removeConfirmationTitle");return await l.confirm(o,n,null,c.WARN,r)?t:void 0}interceptDataLoaded(t){const i=this.getMetadataByRow(t.payload);return new r(n.DATA_LOADED,i)}interceptMetadataLoaded(t){return this.fillFieldsWithRmp(t.payload),this.fillFieldsWithRmPrecision(t.payload),new r(n.METADATA_LOADED,this.handleDULinksOnMetadataLoaded(t.payload))}async interceptAction(t){switch(t.type){case n.RECORDS_ADDED:return this.interceptRecordsAdded(t);case n.RECORDS_COPIED:return this.interceptRecordsCopied(t);case n.DATA_CHANGED:return await this.handleLoadRowMetadata(t),await this.interceptDataChange(t);case n.CHANGING_DATA:return await this.interceptDataChange(t);case n.SAVING_DATA:return await this.interceptSavingData(t);case n.DATA_SAVED:return this.interceptDataSaved(t);case n.EDITION_CANCELED:return await this.interceptEditionCanceled(t);case n.REMOVING_RECORDS:return await this.interceptRemovingRecords(t);case n.DATA_LOADED:return this.interceptDataLoaded(t);case n.METADATA_LOADED:return this.interceptMetadataLoaded(t);default:return t}}async handleLoadRowMetadata(t){const i=t.type===n.DATA_CHANGED?t.payload:t.payload.changes[0].record,s=Object.keys(i).find((t=>this._fieldsWithRmp.includes(t)));if(s){const t=this.dataUnit.getField(s).properties.rmp,e=f(i,s);return await this.updateRowMetadata({fieldName:s,fieldValue:e,metadataName:t,updatedFields:i})}}async updateRowMetadata({fieldName:t,fieldValue:i,metadataName:s,updatedFields:e}){const a=this.getCacheName(t,s,i),n=this._rowMetadataCache.get(a);if(n)return this.updateDataStateRmp(n),n;{const i=new m,n=await i.loadRowMetadata(this,t,s,e);return this.updateDataStateRmp(n._rmd),this._rowMetadataCache.set(a,Object.assign({},n._rmd)),Object.assign({},n._rmd)}}handleDULinksOnMetadataLoaded(t){const i=Object.assign({},t);return this.processLinks(i),i}handleRecordsCopied(t){let i=[...t];return i=this.handleCleanOnCopy(i),this.handleLinksWithParent(i)}handleLinksWithParent(t){var i,s;const e=null!==(i=this._parentDataUnit)&&void 0!==i?i:null===(s=this.dataUnit)||void 0===s?void 0:s.getParentDataUnit();if(!e)return t;const a=e.getSelectedRecord(),n=null==e?void 0:e.getChildInfo(this.getCleanDataUnitName()),{links:h}=n;return h&&0!==h.length?t.map((t=>this.buildRecordWithLinkedFields(t,h,a))):t}buildRecordWithLinkedFields(t,i,s){const e=Object.assign({},t);return i.forEach((t=>{const i=p(this.dataUnit.getField(t.target).dataType,s[t.source]);e[t.target]=i})),e}handleCleanOnCopy(t){const i=this.getCleanOnCopyFields();return i.length>0&&(t=t.map((t=>this.buildCopyWithCleanedFields(t,i)))),t}buildCopyWithCleanedFields(t,i){const s=Object.assign({},t);return i.forEach((t=>delete s[t])),s}showSuccessMessage(t){l.info(t,{iconName:"check"})}isAllowed(t){return!!this._permissions&&(this._permissions.isSup||this._permissions[t])}buildDataState(t){var i;const s=this.dataUnit.getSelectionInfo(),e=(this.dataUnit.hasDirtyRecords()||this.dataUnit.hasWaitingChanges())&&(null==s?void 0:s.isEmpty()),a=this.dataUnit.getSelectedRecord();let h=null===(i=this.dataState)||void 0===i?void 0:i.rowMetadata;return!a||h&&![n.SELECTION_CHANGED,n.EDITION_CANCELED,n.NEXT_SELECTED,n.PREVIOUS_SELECTED].includes(t)?h&&(h.getProp=this.buildGetPropRowMetadata(h)):h=this.doGetRowMetadata(a),new w({insertionMode:this.dataUnit.hasNewRecord(),isStartingInsertionMode:e,hasNext:this.dataUnit.hasNext(),hasPrevious:this.dataUnit.hasPrevious(),copyMode:this.dataUnit.hasCopiedRecord(),isDirty:this.dataUnit.isDirty(),hasDirtyRecords:this.dataUnit.hasDirtyRecords(),selectedRecords:void 0,selectionInfo:s,selectedRecord:a,recordsIsEmpty:0===this.dataUnit.records.length,metadataByRow:this._metadataByRow,rowMetadata:h})}async handleDataSaved(t){const i=await this.handleLoadRowMetadata(t);if(i&&(i.getProp=this.buildGetPropRowMetadata(i)),this._metadataByRow.set(t.payload.records[0].__record__id__,i),this.dataState=this.buildDataState(),this.ignoreSaveMessage)return;const s=t.payload.changes[0]._operation.toLowerCase(),e=this.getMessage("snkDataUnit.saveInfo",t.payload.records[0],s);null!=e&&this.showSuccessMessage(e)}handleRecordsRemoved(t){var i,s;const e=t.payload.cachedRecords;let a;a=(null==e?void 0:e.length)>1?this.getMessage("snkDataUnit.removeAllInfo",{size:e.length}):this.getMessage("snkDataUnit.removeInfo",t.payload.cachedRecords[0]),null!=a&&this.showSuccessMessage(a);const n=null!==(s=null===(i=this.dataUnit.records)||void 0===i?void 0:i.length)&&void 0!==s?s:0,h=this.dataUnit.getPaginationInfo();h&&this.dataUnit.gotoPage(n>0||h.hasMore?h.currentPage:0)}getMessage(t,i,s){return i||(i=this.getMessageParams()),s&&(this.messagesBuilder.currentOperation=s),this.messagesBuilder.getMessage(t,i)}getMessageParams(){return this.dataState.selectedRecord}getMessageOperation(){return this.dataState.copyMode?u.CLONE:this.dataState.insertionMode||this.dataState.isStartingInsertionMode?u.INSERT:this.dataState.isDirty?u.UPDATE:u.CLEAN}async getDataUnitParentOrChild(){var t;const i=this.dataUnitName?this.dataUnitName:this.entityName;return this._parentSnkDataUnit?(this._parentDataUnit=await(null===(t=this._parentSnkDataUnit)||void 0===t?void 0:t.getDataUnit()),await this._application.getDataUnit(this.entityName,i,this._parentDataUnit,this.configName,this.resourceID)):await this._application.getDataUnit(this.entityName,i,null,this.configName,this.resourceID)}async loadDataUnit(){var t;if(null==this.dataUnit&&this._application&&this.entityName&&(this.dataUnit=await this.getDataUnitParentOrChild()),this.dataUnit){let i;for(this.dataUnit.pageSize=this.pageSize,this.dataUnit.unsubscribe(this._dataUnitObserver),this.dataUnit.addInterceptor(this),this.dataUnit.subscribe(this._dataUnitObserver),await this.dataUnit.loadMetadata(),(null===(t=this.dataUnit.records)||void 0===t?void 0:t.length)&&this.getMetadataByRow(this.dataUnit),this.dataState=this.buildDataState();i=this._onDataUnitResolve.pop();)i(this.dataUnit)}}getParentSnkDataUnit(){let t=this.element;for(;t.parentNode;){if("SNK-DATA-UNIT"===t.parentNode.nodeName)return t.parentNode;t=t.parentNode}}handlerLinkFields(){var t,i,s,e;const a=null!==(t=this._parentDataUnit)&&void 0!==t?t:null===(i=this.dataUnit)||void 0===i?void 0:i.getParentDataUnit();if(!a)return;const n=null!==(s=this.entityName)&&void 0!==s?s:this.getCleanDataUnitName(),h=a.getChildInfo(n);if(!h)return;const r=null===(e=null==h?void 0:h.links)||void 0===e?void 0:e.map((t=>t.target));this.handleDUWithLinks(r)}handleDUWithLinks(t){this.fieldsToLink=t;const i=Object.assign({},this.dataUnit.metadata);this.processLinks(i),this.dataUnit.metadata=i,this.dataUnitFieldsHidded.emit()}processLinks(t){var i;null===(i=null==t?void 0:t.fields)||void 0===i||i.forEach((t=>{var i;(null===(i=this.fieldsToLink)||void 0===i?void 0:i.includes(t.name))&&(t.visible=!1)}))}getCleanDataUnitName(){var t;const i=this.dataUnit.name;if(o.isEmpty(i))return i;const s=this.REGEX_DATAUNIT_NAME.exec(i);return null!==(t=null==s?void 0:s[1])&&void 0!==t?t:i}static getNearestInstance(t){let i=t.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase())return i;i=i.parentElement}}instanceMessagesBuilder(){var t;this.messagesBuilder||(this.messagesBuilder=new v(null!==(t=this.domainMessagesBuilder)&&void 0!==t?t:this.entityName))}componentWillLoad(){this._application=d.getContextValue("__SNK__APPLICATION__"),this._application.getAllAccess(this.resourceID).then((t=>this._permissions=t)),this._parentSnkDataUnit=this.getParentSnkDataUnit(),this.instanceMessagesBuilder()}disconnectedCallback(){this.dataUnit&&this.dataUnit.releaseCallbacks()}async componentDidLoad(){await this.loadDataUnit(),this.handlerLinkFields()}render(){return s(a,null)}get element(){return e(this)}static get watchers(){return{pageSize:["observePageSize"],dataUnitName:["observeDataUnitName"],entityName:["observeEntityName"],dataState:["observeDataState"],dataUnit:["observeDataUnit"],messagesBuilder:["observeMessagesBuilder"]}}};class w{constructor(t){this.copyMode=t.copyMode,this.insertionMode=t.insertionMode,this.isStartingInsertionMode=t.isStartingInsertionMode,this.isDirty=t.isDirty,this.hasDirtyRecords=t.hasDirtyRecords,this.hasNext=t.hasNext,this.hasPrevious=t.hasPrevious,this.selectionInfo=t.selectionInfo,this.selectedRecord=t.selectedRecord,this.recordsIsEmpty=t.recordsIsEmpty,this.metadataByRow=t.metadataByRow,this.rowMetadata=t.rowMetadata}get selectedRecords(){var t;if(console.warn("SnkDataUnit: O método `selectedRecords` foi descontinuado. Use o método `selectionInfo`."),null===(t=this.selectionInfo)||void 0===t?void 0:t.isAllRecords())throw new Error("Erro interno: Impossível obter os registros selecionados. A seleção atual é virtual. Use o atributo `selectionInfo`.");return this.selectionInfo.records}}export{D as S}