@sankhyalabs/sankhyablocks 8.15.0-dev.9 → 8.15.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/dist/cjs/{ISave-d68ce3cd.js → ISave-e91b70a7.js} +1 -0
  2. package/dist/cjs/{SnkMessageBuilder-7293d0ad.js → SnkMessageBuilder-e7dcf408.js} +13 -0
  3. package/dist/cjs/loader.cjs.js +1 -1
  4. package/dist/cjs/{dataunit-fetcher-353e4af2.js → pesquisa-fetcher-e4a7c4c3.js} +215 -26
  5. package/dist/cjs/sankhyablocks.cjs.js +1 -1
  6. package/dist/cjs/snk-actions-button_2.cjs.entry.js +5 -4
  7. package/dist/cjs/snk-application.cjs.entry.js +33 -4
  8. package/dist/cjs/snk-attach.cjs.entry.js +388 -57
  9. package/dist/cjs/snk-crud.cjs.entry.js +2 -3
  10. package/dist/cjs/snk-data-exporter.cjs.entry.js +3 -3
  11. package/dist/cjs/{snk-data-unit-1bc69073.js → snk-data-unit-82c08a8c.js} +1 -1
  12. package/dist/cjs/snk-data-unit.cjs.entry.js +2 -2
  13. package/dist/cjs/snk-detail-view.cjs.entry.js +4 -5
  14. package/dist/cjs/snk-filter-bar.cjs.entry.js +25 -3
  15. package/dist/cjs/snk-filter-item.cjs.entry.js +4 -47
  16. package/dist/cjs/snk-filter-modal.cjs.entry.js +2 -1
  17. package/dist/cjs/snk-filter-multi-select.cjs.entry.js +2 -1
  18. package/dist/cjs/{snk-guides-viewer-e60ccc5e.js → snk-guides-viewer-d32c096f.js} +2 -3
  19. package/dist/cjs/snk-guides-viewer.cjs.entry.js +3 -4
  20. package/dist/cjs/snk-pesquisa.cjs.entry.js +1 -1
  21. package/dist/cjs/snk-simple-crud.cjs.entry.js +17 -6
  22. package/dist/collection/components/snk-application/snk-application.js +52 -9
  23. package/dist/collection/components/snk-attach/snk-attach.js +188 -39
  24. package/dist/collection/components/snk-attach/structure/{crud-config-builder.js → builder/anexo-sistema-crud-config.builder.js} +1 -1
  25. package/dist/collection/components/snk-attach/structure/builder/attach-crud-config.builder.js +62 -0
  26. package/dist/collection/components/snk-attach/structure/{taskbar-builder.js → builder/taskbar-builder.js} +1 -1
  27. package/dist/collection/components/snk-attach/structure/fetcher/facade/fetcher.facade.js +1 -0
  28. package/dist/collection/components/snk-attach/structure/{data-unit-builder.js → fetcher/factory/anexo-sistema-data-unit.factory.js} +14 -11
  29. package/dist/collection/components/snk-attach/structure/fetcher/factory/attach-fetcher-data-unit.factory.js +111 -0
  30. package/dist/collection/components/snk-attach/structure/index.js +6 -3
  31. package/dist/collection/components/snk-data-exporter/snk-data-exporter.js +1 -1
  32. package/dist/collection/components/snk-filter-bar/filter-item/editors/snk-filter-multi-select.js +2 -1
  33. package/dist/collection/components/snk-filter-bar/filter-item/snk-filter-item.js +4 -47
  34. package/dist/collection/components/snk-filter-bar/filter-modal/snk-filter-modal.js +19 -1
  35. package/dist/collection/components/snk-filter-bar/snk-filter-bar.js +39 -2
  36. package/dist/collection/components/snk-filter-bar/utils/SnkFilterModalFactory.js +3 -1
  37. package/dist/collection/components/snk-pesquisa/snk-pesquisa.css +2 -4
  38. package/dist/collection/components/snk-simple-crud/snk-simple-crud.js +53 -1
  39. package/dist/collection/components/snk-taskbar/elements/taskbar-actions-button/taskbar-actions-button.js +3 -1
  40. package/dist/collection/lib/dataUnit/InMemoryLoader.js +1 -1
  41. package/dist/collection/lib/http/data-fetcher/fetchers/{attach-fetcher.js → AttachFetcher/anexo-sistema-fetcher.js} +16 -15
  42. package/dist/collection/lib/http/data-fetcher/fetchers/AttachFetcher/attach-fetcher.js +90 -0
  43. package/dist/collection/lib/http/data-fetcher/fetchers/AttachFetcher/facade/attach-fetcher.facade.js +1 -0
  44. package/dist/collection/lib/http/data-fetcher/fetchers/AttachFetcher/index.js +2 -0
  45. package/dist/collection/lib/http/data-fetcher/fetchers/AttachFetcher/interfaces/IDelete.js +1 -0
  46. package/dist/collection/lib/http/data-fetcher/fetchers/AttachFetcher/interfaces/IDownloadKey.js +1 -0
  47. package/dist/collection/lib/http/data-fetcher/fetchers/{fecthAttach → AttachFetcher}/interfaces/ISave.js +1 -0
  48. package/dist/collection/lib/http/data-fetcher/fetchers/data-unit/dataunit-fetcher.js +17 -3
  49. package/dist/collection/lib/http/data-fetcher/fetchers/data-unit/loadstrategy/DatasetStrategy.js +29 -22
  50. package/dist/collection/lib/http/data-fetcher/fetchers/parameters-fecher.js +21 -0
  51. package/dist/collection/lib/http/data-fetcher/fetchers/pesquisa-fetcher.js +7 -1
  52. package/dist/collection/lib/index.js +1 -1
  53. package/dist/collection/lib/message/resources/snk-attach.msg.js +13 -0
  54. package/dist/components/SnkMessageBuilder.js +13 -0
  55. package/dist/components/dataunit-fetcher.js +54 -27
  56. package/dist/components/snk-actions-button2.js +1 -0
  57. package/dist/components/snk-application2.js +32 -1
  58. package/dist/components/snk-attach2.js +394 -57
  59. package/dist/components/snk-data-exporter2.js +1 -1
  60. package/dist/components/snk-filter-bar2.js +26 -3
  61. package/dist/components/snk-filter-item2.js +4 -47
  62. package/dist/components/snk-filter-modal.js +4 -2
  63. package/dist/components/snk-filter-multi-select.js +2 -1
  64. package/dist/components/snk-pesquisa2.js +1 -1
  65. package/dist/components/snk-simple-crud2.js +15 -1
  66. package/dist/components/taskbar-actions-button2.js +3 -1
  67. package/dist/esm/{ISave-4412b20c.js → ISave-d8c8bc59.js} +1 -0
  68. package/dist/esm/{SnkMessageBuilder-ca843d1b.js → SnkMessageBuilder-0fb796b9.js} +13 -0
  69. package/dist/esm/loader.js +1 -1
  70. package/dist/esm/{dataunit-fetcher-0fc935a0.js → pesquisa-fetcher-fa0c2540.js} +215 -27
  71. package/dist/esm/sankhyablocks.js +1 -1
  72. package/dist/esm/snk-actions-button_2.entry.js +5 -4
  73. package/dist/esm/snk-application.entry.js +32 -3
  74. package/dist/esm/snk-attach.entry.js +389 -58
  75. package/dist/esm/snk-crud.entry.js +2 -3
  76. package/dist/esm/snk-data-exporter.entry.js +3 -3
  77. package/dist/esm/{snk-data-unit-6208ebf0.js → snk-data-unit-5d201fb3.js} +1 -1
  78. package/dist/esm/snk-data-unit.entry.js +2 -2
  79. package/dist/esm/snk-detail-view.entry.js +4 -5
  80. package/dist/esm/snk-filter-bar.entry.js +25 -3
  81. package/dist/esm/snk-filter-item.entry.js +4 -47
  82. package/dist/esm/snk-filter-modal.entry.js +2 -1
  83. package/dist/esm/snk-filter-multi-select.entry.js +2 -1
  84. package/dist/esm/{snk-guides-viewer-98a8e45e.js → snk-guides-viewer-f49613c6.js} +2 -3
  85. package/dist/esm/snk-guides-viewer.entry.js +3 -4
  86. package/dist/esm/snk-pesquisa.entry.js +1 -1
  87. package/dist/esm/snk-simple-crud.entry.js +15 -4
  88. package/dist/sankhyablocks/p-02e3a45b.entry.js +1 -0
  89. package/dist/sankhyablocks/{p-ff6064e7.js → p-05243555.js} +1 -1
  90. package/dist/sankhyablocks/p-0ec5b2e5.js +1 -0
  91. package/dist/sankhyablocks/{p-9e7d65a4.js → p-21749402.js} +1 -1
  92. package/dist/sankhyablocks/p-2582537c.entry.js +1 -0
  93. package/dist/sankhyablocks/p-282789a6.entry.js +1 -0
  94. package/dist/sankhyablocks/p-3b0e4e08.js +65 -0
  95. package/dist/sankhyablocks/{p-0874adb5.entry.js → p-40915359.entry.js} +1 -1
  96. package/dist/sankhyablocks/p-70a4af56.entry.js +1 -0
  97. package/dist/sankhyablocks/p-86801b08.entry.js +1 -0
  98. package/dist/sankhyablocks/p-96ef14f9.entry.js +1 -0
  99. package/dist/sankhyablocks/p-9b5944a4.entry.js +1 -0
  100. package/dist/sankhyablocks/p-9bdbc7d8.entry.js +1 -0
  101. package/dist/sankhyablocks/{p-90f9b4db.entry.js → p-a52b9254.entry.js} +3 -3
  102. package/dist/sankhyablocks/p-ac384baf.entry.js +1 -0
  103. package/dist/sankhyablocks/p-bf2acf72.entry.js +1 -0
  104. package/dist/sankhyablocks/p-c4874327.entry.js +1 -0
  105. package/dist/sankhyablocks/{p-247a8b36.entry.js → p-d1791da2.entry.js} +1 -1
  106. package/dist/sankhyablocks/{p-32f0935f.js → p-f3d1c48e.js} +1 -1
  107. package/dist/sankhyablocks/sankhyablocks.esm.js +1 -1
  108. package/dist/types/components/snk-actions-button/subcomponents/snk-actions-form.d.ts +1 -1
  109. package/dist/types/components/snk-application/snk-application.d.ts +7 -0
  110. package/dist/types/components/snk-attach/{structure/crud-config-builder.d.ts → interfaces/ICrudConfig.d.ts} +1 -2
  111. package/dist/types/components/snk-attach/interfaces/TFetcherType.d.ts +1 -0
  112. package/dist/types/components/snk-attach/snk-attach.d.ts +27 -6
  113. package/dist/types/components/snk-attach/structure/builder/anexo-sistema-crud-config.builder.d.ts +2 -0
  114. package/dist/types/components/snk-attach/structure/builder/attach-crud-config.builder.d.ts +31 -0
  115. package/dist/types/components/snk-attach/structure/{taskbar-builder.d.ts → builder/taskbar-builder.d.ts} +1 -1
  116. package/dist/types/components/snk-attach/structure/fetcher/facade/fetcher.facade.d.ts +11 -0
  117. package/dist/types/components/snk-attach/structure/fetcher/factory/anexo-sistema-data-unit.factory.d.ts +17 -0
  118. package/dist/types/components/snk-attach/structure/fetcher/factory/attach-fetcher-data-unit.factory.d.ts +15 -0
  119. package/dist/types/components/snk-attach/structure/index.d.ts +6 -3
  120. package/dist/types/components/snk-filter-bar/filter-item/snk-filter-item.d.ts +1 -2
  121. package/dist/types/components/snk-filter-bar/filter-modal/snk-filter-modal.d.ts +5 -0
  122. package/dist/types/components/snk-filter-bar/snk-filter-bar.d.ts +7 -0
  123. package/dist/types/components/snk-filter-bar/utils/SnkFilterModalFactory.d.ts +3 -1
  124. package/dist/types/components/snk-simple-crud/snk-simple-crud.d.ts +10 -1
  125. package/dist/types/components.d.ts +74 -2
  126. package/dist/types/lib/http/data-fetcher/DataFetcher.d.ts +1 -1
  127. package/dist/types/lib/http/data-fetcher/fetchers/{attach-fetcher.d.ts → AttachFetcher/anexo-sistema-fetcher.d.ts} +3 -2
  128. package/dist/types/lib/http/data-fetcher/fetchers/AttachFetcher/attach-fetcher.d.ts +11 -0
  129. package/dist/types/lib/http/data-fetcher/fetchers/AttachFetcher/facade/attach-fetcher.facade.d.ts +8 -0
  130. package/dist/types/lib/http/data-fetcher/fetchers/AttachFetcher/index.d.ts +3 -0
  131. package/dist/types/lib/http/data-fetcher/fetchers/{fecthAttach → AttachFetcher}/interfaces/ISave.d.ts +2 -1
  132. package/dist/types/lib/http/data-fetcher/fetchers/data-unit/dataunit-fetcher.d.ts +1 -0
  133. package/dist/types/lib/http/data-fetcher/fetchers/data-unit/loadstrategy/DatasetStrategy.d.ts +1 -0
  134. package/dist/types/lib/http/data-fetcher/fetchers/parameters-fecher.d.ts +1 -0
  135. package/dist/types/lib/index.d.ts +1 -1
  136. package/package.json +5 -5
  137. package/dist/cjs/pesquisa-fetcher-ef050a47.js +0 -167
  138. package/dist/esm/pesquisa-fetcher-dd3ca0a5.js +0 -165
  139. package/dist/sankhyablocks/p-20726710.entry.js +0 -1
  140. package/dist/sankhyablocks/p-41560fd8.entry.js +0 -1
  141. package/dist/sankhyablocks/p-4775a293.entry.js +0 -1
  142. package/dist/sankhyablocks/p-6678d5d4.entry.js +0 -1
  143. package/dist/sankhyablocks/p-71439fd9.entry.js +0 -1
  144. package/dist/sankhyablocks/p-7d8d7fe9.entry.js +0 -1
  145. package/dist/sankhyablocks/p-a91bb13d.js +0 -1
  146. package/dist/sankhyablocks/p-a9e5b094.entry.js +0 -1
  147. package/dist/sankhyablocks/p-abfa8101.entry.js +0 -1
  148. package/dist/sankhyablocks/p-b3020263.entry.js +0 -1
  149. package/dist/sankhyablocks/p-bf93a748.js +0 -60
  150. package/dist/sankhyablocks/p-c6f89389.entry.js +0 -1
  151. package/dist/sankhyablocks/p-cebae710.entry.js +0 -1
  152. package/dist/sankhyablocks/p-d9bb09b3.js +0 -6
  153. package/dist/types/components/snk-attach/structure/data-unit-builder.d.ts +0 -15
  154. /package/dist/collection/{lib/http/data-fetcher/fetchers/fecthAttach/interfaces/IDelete.js → components/snk-attach/interfaces/ICrudConfig.js} +0 -0
  155. /package/dist/collection/{lib/http/data-fetcher/fetchers/fecthAttach/interfaces/IDownloadKey.js → components/snk-attach/interfaces/TFetcherType.js} +0 -0
  156. /package/dist/collection/lib/http/data-fetcher/fetchers/{fecthAttach → AttachFetcher}/interfaces/index.js +0 -0
  157. /package/dist/types/lib/http/data-fetcher/fetchers/{fecthAttach → AttachFetcher}/interfaces/IDelete.d.ts +0 -0
  158. /package/dist/types/lib/http/data-fetcher/fetchers/{fecthAttach → AttachFetcher}/interfaces/IDownloadKey.d.ts +0 -0
  159. /package/dist/types/lib/http/data-fetcher/fetchers/{fecthAttach → AttachFetcher}/interfaces/index.d.ts +0 -0
@@ -0,0 +1 @@
1
+ import{r as t,h as i,H as s,g as e,c as n}from"./p-d2d301a6.js";import{ApplicationContext as o,StringUtils as a,ErrorException as c,WarningException as r,ObjectUtils as l,DateUtils as h,ArrayUtils as d,ElementIDUtils as u}from"@sankhyalabs/core";import{D as p}from"./p-9695f78b.js";import{P as m}from"./p-eaad0aa8.js";import"./p-3b0e4e08.js";import"./p-38289a55.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-c22c1d8e.js";import"./p-ff1990ad.js";import"./p-0d7863ed.js";import{R as v}from"./p-688dcb4c.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";class b{execute(t){var i;const s={actionID:t.actionID,refreshType:null===(i=t.actionConfig.javaCall)||void 0===i?void 0:i.refreshType};return new Promise((t=>{t({execSource:s,callback:this.callExecJava})}))}async callExecJava(t){const i={requestBody:{javaCall:t}};await p.get().callServiceBroker("ActionButtonsSP.executeJava",JSON.stringify(i))}}class w{execute(t){var i;const s={actionID:t.actionID,refreshType:null===(i=t.actionConfig.runScript)||void 0===i?void 0:i.refreshType};return new Promise((t=>{t({execSource:s,callback:this.callExecScript})}))}async callExecScript(t){const i={runScript:t};await p.get().callServiceBroker("ActionButtonsSP.executeScript",i)}}class f{constructor(){this._application=o.getContextValue("__SNK__APPLICATION__")}async execute(t,i){const s=t.resourceID;if(!s)return;let e=await this.buildLaunchObject(t,i);return this._application.openApp(s,e),null}buildLaunchObject(t,i){return new Promise((s=>{let e=t.actionConfig.params.param;if(e&&e.length>0){let n={},o=[];e.forEach((s=>{const e=s.localField;let r=i.getFieldValue(e);if(!r){let s=i.getField(e).label;throw s=a.isEmpty(i.getField(e).label)?e:s,new c(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.launchScreen.emptyField",{description:t.description,localFieldLabel:s}))}r=a.isEmpty(r.toString())?void 0:r.toString(),n[s.targetField]=r,o.push({fieldName:s.targetField,value:r})})),n.ACTION_PARAMETERS=o,n.call_time=Date.now(),s(n)}s(null)}))}}class k{execute(t){var i,s,e;const n=null===(i=t.actionConfig.dbCall)||void 0===i?void 0:i.name,o=null===(s=t.actionConfig.dbCall)||void 0===s?void 0:s.rootEntity,a={actionID:t.actionID,refreshType:null===(e=t.actionConfig.dbCall)||void 0===e?void 0:e.refreshType,procName:n,rootEntity:o};return new Promise((t=>{t({execSource:a,callback:this.callExecProcedure})}))}async callExecProcedure(t){const i={requestBody:{stpCall:t}};await p.get().callServiceBroker("ActionButtonsSP.executeSTP",JSON.stringify(i))}}var _,y;!function(t){t.LAUNCH_SCREEN="LC",t.JAVASCRIPT="SC",t.JAVA="RJ",t.PROCEDURE="SP",t.EMBEDDED="EB"}(_||(_={}));class S{constructor(t){this.actionType=t,this._application=o.getContextValue("__SNK__APPLICATION__")}get executor(){switch(this.actionType){case _.LAUNCH_SCREEN:return new f;case _.JAVASCRIPT:return new w;case _.JAVA:return new b;case _.PROCEDURE:return new k;default:throw new c(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.action.nonExistentType",{actionType:this.actionType}))}}}!function(t){t.NONE="NONE",t.PARENT="PARENT",t.MASTER="MASTER",t.ALL="ALL"}(y||(y={}));const A="__MASTER_ROW__";class P{constructor(t,i,s){var e;this._lastValuesCache={},this._actionsExecuteInterface=t,this._dataUnit=i,this._selectedRows=(null===(e=null==i?void 0:i.getSelectionInfo())||void 0===e?void 0:e.isAllRecords())?[]:null==i?void 0:i.getSelectionInfo().records,this._application=o.getContextValue("__SNK__APPLICATION__"),this._appResourceId=s}apply(t,i){this._application.closePopUp(),this._actionsExecuteInterface.execute(t,this._dataUnit).then((({execSource:s,callback:e})=>{this.resolvePromptParams(t,s,i).then((()=>{this.actionExecute(s,e)}))}))}async execute(t){var i;if(!t.actionConfig)throw new r(this._application.messagesBuilder.getMessage("snkActionsButton.title.warning",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.action.incorrectAction",{description:t.description}));if(null===(i=t.actionConfig.params)||void 0===i?void 0:i.promptParam){const i=t.actionConfig.params.promptParam;let s=!1;for(let t=0;t<i.length;t++)if(!s&&"true"===i[t].saveLast){s=!0;break}s&&(t.actionConfig.params.promptParam=await this.loadSavedValuesIntoParams(t));const e=document.createElement("snk-actions-form");window.document.body.appendChild(e),e.action=l.copy(t),e.applyParameters=t=>{this.apply(t,s)},e.openPopup()}else t.type!=_.LAUNCH_SCREEN?this._actionsExecuteInterface.execute(t,this._dataUnit).then((({execSource:t,callback:i})=>{this.actionExecute(t,i)})):this._actionsExecuteInterface.execute(t,this._dataUnit)}loadSavedValuesIntoParams(t){return this.loadLastValues(t).then((i=>{let s=t.actionConfig.params.promptParam;return i&&i.param.forEach((t=>{s=s.map((i=>i.name!==t.paramName?i:Object.assign(Object.assign({},i),"B"===i.paramType?{value:"S"===t.$}:{value:t.$})))})),s}))}actionExecute(t,i){t.virtualPage=this.buildVirtualPage(),this.prepareAndExecute(t,i),this.recordsReloader(t.refreshType)}resolvePromptParams(t,i,s){return new Promise((e=>{let n=[];t.actionConfig.params.promptParam.forEach((t=>{n.push(this.buildPromptParam(t))})),this.putParamsOnExecSource(n,i),s&&this.saveLastValues(t,n),e()}))}buildPromptParam(t){let i,s,e=t.paramType,n=!1,o=t.value;switch(e){case m.DATE:e="D";break;case m.DATETIME:e="H";break;case m.DECIMAL:e="F",i={"sk-precision":Number(t.precision)};break;case m.BOOLEAN:e="S",n=!0,o=t.value?"S":"N";break;case m.ENTITY:i={"sk-entity-name":t.entityName,"sk-allow-show-hierarchical-mode":t.hierarchyEntity,"sk-data-type":"S"},t.hierarchyEntity&&t.entityPK&&(s=t.entityPK),o=t.value?Number(t.value):null;break;case m.OPTIONS:e="O";let a=t.options.split(";").map((function(t,i){let s,e;if(t.indexOf("=")>-1){let i=t.split("=");s=i[0],e=i[1]}else s=i+1,e=t;return{data:s,value:e}}));i={"sk-options":a}}return{description:t.label,required:"true"==t.required,fieldName:t.name,fieldNameOri:t.name,entityPK:s,paramType:t.paramType,type:e,isCheckbox:n,saveLast:t.saveLast,fieldProp:i,value:o,isGeneratedName:t.isGeneratedName}}putParamsOnExecSource(t,i){i.params={param:[]},t.forEach((t=>{if(t.isGeneratedName&&t.value)throw new c(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.action.emptyParamName",void 0));a.isEmpty(t.value)||i.params.param.push({type:this.getParamDataType(t.paramType),paramName:t.fieldName,$:this.getParamValue(t)})}))}getParamDataType(t){let i;switch(t){case"D":i="F";break;case"DT":case"DH":i="D";break;case"B":case"ENTITY":case"SO":i="S";break;default:i=t}return i}getParamValue(t){let i=t.value;return i?("DT"==t.paramType?i=h.formatDate(i):"DH"==t.paramType&&(i=h.formatDateTime(i)),i):i}async loadLastValues(t){const i=await this.buildResourceId(t.actionID);return new Promise(((t,s)=>{if(this._lastValuesCache[i])t(this._lastValuesCache[i]);else{const e={config:{chave:i,tipo:"T"}};p.get().callServiceBroker("SystemUtilsSP.getConf",e).then((s=>{var e,n;let o;(null===(n=null===(e=s.config)||void 0===e?void 0:e.data)||void 0===n?void 0:n.params)&&(o=s.config.data.params,Array.isArray(o.param)||(o.param=[o.param])),this._lastValuesCache[i]=o,t(o)})).catch((t=>{s(t)}))}}))}async saveLastValues(t,i){if(this._application){let s={params:{param:[]}};i.forEach((t=>{"true"==t.saveLast&&s.params.param.push({paramName:t.fieldName,$:t.value})}));const e=await this.buildResourceId(t.actionID);this._lastValuesCache[e]=s.params,this._application.saveConfig(e,s)}}async buildResourceId(t){return this._appResourceId+".actionconfig."+t}prepareAndExecute(t,i){this.addRows(t),i(t)}addRows(t){const i={row:[]},s=this._selectedRows;for(const t in s){const e=s[t],n={};e.hasOwnProperty(A)&&(n.master="S",n.entityName=e.__ENTITY_NAME__,delete e[A],delete e.__ENTITY_NAME__);for(const t in e)"NUFIN"===t&&(n.field||(n.field=[]),n.field.push({fieldName:t,$:e[t]}));i.row.push(n)}i.row.length>0&&(t.rows=i)}recordsReloader(t){switch(t){case y.NONE:break;case y.PARENT:case y.MASTER:case y.ALL:this._dataUnit.loadData();break;default:this._dataUnit.reloadCurrentRecord()}}buildVirtualPage(){var t,i,s,e;if(null===(i=null===(t=this._dataUnit)||void 0===t?void 0:t.getSelectionInfo())||void 0===i?void 0:i.isAllRecords())return{filters:{filters:null===(s=this._dataUnit)||void 0===s?void 0:s.getAppliedFilters()},orders:{orders:null===(e=this._dataUnit)||void 0===e?void 0:e.getSort()}}}}class N{async clientConfirm(t,i){return new Promise((s=>{const e=o.getContextValue("__SNK__APPLICATION__");let n="";t.content.event.hasOwnProperty("stpCall")?(i.requestBody=t.content.event.stpCall,n=_.PROCEDURE):t.content.event.hasOwnProperty("runScript")?(i.requestBody=t.content.event.runScript,n=_.JAVASCRIPT):t.content.event.hasOwnProperty("javaCall")&&(i.requestBody=t.content.event.javaCall,n=_.JAVA);let a={type:"S",sequence:t.content.event.sequence};i.requestBody.params?Array.isArray(i.requestBody.params.param)||(i.requestBody.params.param=[i.requestBody.params.param]):i.requestBody.params={param:[]},i.requestBody.params.param.push(a);const c=t.content.event.title.$,r=t.content.event.message.$;let l;switch(n){case _.JAVASCRIPT:l={runScript:i.requestBody};break;case _.PROCEDURE:l={requestBody:{stpCall:i.requestBody}};break;case _.JAVA:l={requestBody:{javaCall:i.requestBody}}}if("S"==t.content.event.showNoOption){a.paramName="__ESCOLHA_SIMNAO__";const t=document.createElement("snk-client-confirm");window.document.body.appendChild(t),t.titleMessage=c,t.message=r,t.accept=async()=>{a.$="S",await i.reCall(l),s()},t.cancel=async()=>{a.$="N",await i.reCall(l),s()},t.openPopup()}else e.confirm(c,r,null,"warn",{labelCancel:"Cancelar",labelConfirm:"Sim"}).then((async t=>{t&&(a.paramName="__CONFIRMACAO__",a.$="S",await i.reCall(l),s())}))}))}}const x=class{constructor(i){t(this,i),this.CLIENT_EVENT_CONFIRM_NAME="br.com.sankhya.actionbutton.clientconfirm",this.handleClick=t=>{const i=this._actions.find((i=>i.actionID==t.detail.id)),s=new S(i.type).executor;new P(s,this._dataUnit,this._resourceID).execute(Object.assign({},i)),this._showDropdown=!1},this._items=[],this._showDropdown=!1,this._actions=[],this._isOrderActions=!1}async getActions(){let t={param:{entityName:this._entityName,resourceID:this._resourceID}};return p.get().callServiceBroker("ActionButtonsSP.getActions",t).then((t=>{var i;(null===(i=t.actions)||void 0===i?void 0:i.action)&&(this._actions=this._isOrderActions?d.sortAlphabetically(t.actions.action,"description"):t.actions.action)}))}controlDropdown(){this._showDropdown=!this._showDropdown}canShowDropdown(){var t;return this._showDropdown&&(null===(t=this._items)||void 0===t?void 0:t.length)>0}positionDropdown(){var t;const i=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();i&&this._dropdownParent&&(this._dropdownParent.style.top=i.y+i.height+5+"px",this._dropdownParent.style.left=i.x+"px")}closeDropdown(t){const i=null==t?void 0:t.target;i&&(i.closest(".snk-actions-button")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}async componentWillLoad(){this._application=o.getContextValue("__SNK__APPLICATION__"),this._isOrderActions=await this._application.getBooleanParam("global.ordenar.acoes.personalizadas");const t=this._element.parentElement;this._dataUnit=null==t?void 0:t.dataUnit,this._resourceID=null==t?void 0:t.resourceID,this._entityName=this._dataUnit.name.split("/")[2],null==this._resourceID&&(this._resourceID=await v.getResourceID()),this.setEvents(),this.getActions().then((()=>{this.loadItems()}))}async componentDidLoad(){if(this._element&&(u.addIDInfo(this._element),this.positionDropdown(),!await this._application.hasClientEvent(this.CLIENT_EVENT_CONFIRM_NAME))){const t=new N;this._application.addClientEvent(this.CLIENT_EVENT_CONFIRM_NAME,t.clientConfirm)}}componentDidUpdate(){this.positionDropdown()}loadItems(){this._actions&&0!=this._actions.length&&this._actions.forEach((t=>{this._items.push({id:t.actionID,label:t.description})}))}getElementID(t){return{[u.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:u.getInternalIDInfo(t)}}render(){return i(s,null,this._actions&&this._actions.length>0&&i("div",{class:`ez-padding-left--medium snk-actions-button\n ${this.canShowDropdown()?" ez-elevation--16":""}\n `},i("ez-button",Object.assign({ref:t=>this._ezButton=t,iconName:"acao",size:"small",mode:"icon",title:this._application.messagesBuilder.getMessage("snkActionsButton.title.actions",void 0),onClick:()=>this.controlDropdown()},this.getElementID("button"))),i("div",Object.assign({ref:t=>this._dropdownParent=t,class:(this.canShowDropdown()?"snk-actions-button__dropdown--show":"snk-actions-button__dropdown")+"\n "},this.getElementID("dropdown")),this.canShowDropdown()&&i("ez-dropdown",Object.assign({items:this._items,onEzClick:t=>this.handleClick(t)},this.getElementID("dropdown"))))),this.canShowDropdown()&&i("div",Object.assign({class:"ez-scrim ez-scrim--light"},this.getElementID("ezScrim"))))}get _element(){return e(this)}};x.style=".sc-snk-actions-button-h{display:flex;width:fit-content;height:fit-content}.snk-actions-button.sc-snk-actions-button{display:flex;width:fit-content;height:fit-content}.snk-actions-button__dropdown--show.sc-snk-actions-button{display:flex;flex-direction:column;position:fixed}.snk-actions-button__dropdown.sc-snk-actions-button>ez-dropdown.sc-snk-actions-button{position:relative}.snk-actions-button__dropdown.sc-snk-actions-button{display:none}";const O=class{constructor(i){t(this,i),this.taskbarActionSelected=n(this,"taskbarActionSelected",7),this.taskbarActionsOpened=n(this,"taskbarActionsOpened",7),this.taskbarActionsButtonDisconnected=n(this,"taskbarActionsButtonDisconnected",7),this._showDropdown=!1,this.title=void 0,this.enabled=void 0,this.actions=void 0}async handleKeyDown(t){"Escape"!==t.key&&"Esc"!==t.key||await this.hideActions()}async handleClose(){await this.hideActions()}async showActions(){this._showDropdown=!0,requestAnimationFrame((()=>{this._element.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}))}async hideActions(){this._showDropdown=!1}async isOpened(){return this._showDropdown}controlDropdown(){this._showDropdown=!this._showDropdown}loadItems(){return this.actions.filter((t=>void 0!==t)).map((t=>{var i;return{id:t.value,label:t.label,value:t.value,type:null!==(i=t.type)&&void 0!==i?i:"item",children:t.children,iconName:t.iconName,subAction:t.subAction,group:t.group,disableCloseOnSelect:t.disableCloseOnSelect}}))}canShowDropdown(){var t;return this._showDropdown&&(null===(t=this.actions)||void 0===t?void 0:t.length)>0}onSelectAction(t){const i=this.actions.map((t=>Object.assign(Object.assign({},t),{id:t.value}))),s=this.getSelectedAction(t.id,i);this.taskbarActionSelected.emit(s),s.disableCloseOnSelect||(this._showDropdown=!1)}getSelectedAction(t,i){let s=null;for(const e of i){if(e.id===t){s=e;break}if((null==e?void 0:e.children)&&(s=this.getSelectedAction(t,e.children),s))break}return s}dropdownItemBuilder(t,s){const e=this.actions.find((i=>i.value===t.id));if(!e||!e.itemBuilder)return;const n=e.itemBuilder(this._element,e);return"string"==typeof n?i("div",{innerHTML:n}):n}initializeEagerItems(){var t;null===(t=this.actions)||void 0===t||t.forEach((t=>{var i;t&&t.eagerInitialize&&t.itemBuilder&&(null===(i=t.itemBuilder)||void 0===i||i.call(t,this._element,t))}))}componentDidLoad(){this.initializeEagerItems()}componentDidRender(){this._showDropdown&&this.taskbarActionsOpened.emit(this._element)}disconnectedCallback(){this.taskbarActionsButtonDisconnected.emit()}render(){return i(s,null,i("div",{class:"ez-padding-left--medium "+(this.canShowDropdown()?" ez-elevation--16":"")},i("ez-button",{title:this.title,mode:"icon",iconName:"dots-vertical",size:"small",enabled:this.enabled,onClick:()=>this.controlDropdown()}),this.canShowDropdown()&&i("ez-dropdown",{items:this.loadItems(),onEzClick:t=>this.onSelectAction(t.detail),onEzOutsideClick:()=>this._showDropdown=!1,itemBuilder:(t,i)=>this.dropdownItemBuilder(t,i)})))}get _element(){return e(this)}};O.style=".sc-taskbar-actions-button-h{display:flex;width:fit-content;height:fit-content}";export{x as snk_actions_button,O as taskbar_actions_button}
@@ -0,0 +1,65 @@
1
+ import{DataUnit as e,DataType as t,DateUtils as r,StringUtils as n,ChangeOperation as i,ApplicationContext as a,UserInterface as s,DataUnitStorage as o}from"@sankhyalabs/core";import{D as l,d as c}from"./p-9695f78b.js";import{DISTINCT_FILTER_NAME_PREFIX as u}from"@sankhyalabs/ezui/dist/collection/utils/constants";import{DataUnitTransient as d}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{P as h}from"./p-c22c1d8e.js";import{R as m}from"./p-688dcb4c.js";import{ColumnFilterManager as f}from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";class p{constructor(t,r){this.metadata=t,this.records=r,this._dataUnit=new e(p.IN_MEMORY_DATA_UNIT_NAME),this._dataUnit.metadataLoader=()=>this.metadaLoader(),this._dataUnit.dataLoader=(e,t)=>this.inMemoryLoader(e,t,this.getRecordsToLoad()),this._dataUnit.saveLoader=(e,t)=>this.saveLoader(e,t),this._dataUnit.removeLoader=(e,t)=>this.removeLoader(e,t),this.dataUnit.loadMetadata().then((()=>this.dataUnit.loadData()))}getRecordsToLoad(){return(null==this._initialRecords||this.dataUnit.records.length>0)&&(this._initialRecords=this.dataUnit.records),this._initialRecords}get dataUnit(){return this._dataUnit}get records(){return this.dataUnit.records}static getConvertedValue(e,n){return e.dataType===t.BOOLEAN?"S"===n:e.dataType===t.NUMBER?Number(n):e.dataType===t.DATE?r.strToDate(n,!0):e.dataType===t.OBJECT?JSON.parse(n):n}set records(e){const t=this._metadata?new Map(this._metadata.fields.map((e=>[e.name,e]))):void 0,r=null==e?void 0:e.map((e=>{if(e.__record__id__||(e.__record__id__=this.generateUniqueId()),null!=t)for(const r in e){const n=e[r];"string"==typeof n&&t.has(r)&&(e[r]=p.getConvertedValue(t.get(r),n))}return e}));this._initialRecords=r,this._dataUnit&&this._dataUnit.gotoPage(0)}get metadata(){return this._metadata}set metadata(e){this._metadata=e,this._dataUnit&&(this._dataUnit.metadata=this._metadata)}generateUniqueId(){return n.generateUUID()}inMemoryLoader(e,t,r){let n=this.applyFilter(r,e,t.filters);return n=this.applySorting(n,e,t.sort),Promise.resolve({records:n,paginationInfo:_(t,n)})}applyFilter(e,t,r){const n=f.getColumnFilters(r,"");if(null==n||0==n.size)return e;const i=f.getFilterFunction(t,Array.from(n.values()));return null==i?e:e.filter(i)}applySorting(e,t,r){if(null==r||0==r.length)return e;const n=h.getSortingFunction(t,r);return null==n?e:e.sort(n)}metadaLoader(){return Promise.resolve(this._metadata)}saveLoader(e,t){return new Promise((e=>{let r=[];t.forEach((e=>{let{record:t,updatingFields:n,operation:a}=e;const s=Object.assign(Object.assign({},t),n);if(a===i.INSERT||a===i.COPY)s.__old__id__=t.__record__id__,s.__record__id__=this.generateUniqueId(),this.records.push(s);else{const e=this.records.findIndex((e=>e.__record__id__==s.__record__id__));this.records[e]=s}r.push(s)})),e(r)}))}removeLoader(e,t){return new Promise((e=>{e(t)}))}}function _({offset:e,limit:t},r){if(void 0===e||void 0===t)return;const n=Math.min(e+t,r.length);return{currentPage:Math.ceil(e/t),firstRecord:e,lastRecord:n,total:r.length,hasMore:!!(r.length-n)}}p.IN_MEMORY_DATA_UNIT_NAME="InMemoryDataUnit";class g{canSlice(){return!1}processSortingSide(e,t,r){const n=[],i=[];if(null!=e.sort){if(0===r.length)return{localSorting:e.sort,serverSorting:[]};for(const r of e.sort){const e=t.getField(r.field);null!=e&&null!=e.properties&&"true"===e.properties.calculated?n.push(r):i.push(r)}}return{localSorting:n,serverSorting:i}}async load(e,t,r){var n,i;if(null==e.metadata)return Promise.resolve({records:[],loadingInfo:r});try{const a=null!==(i=null===(n=t.filters)||void 0===n?void 0:n.filter((e=>!e.name.startsWith("FILTRO_COLUNA_"))))&&void 0!==i?i:[],{localSorting:s,serverSorting:o}=this.processSortingSide(t,e,a),c=this.getFieldsList(e),u="DatasetSP.loadRecords",d=this.buildRequestBody(u,c,e,t,r,o,a),h=r.quiet?{urlParams:{quietMode:"true"}}:void 0,{result:m,pagerID:f}=await l.get().callServiceBroker(u,d,h),p=this.processRecords(e,c,m),_=null!=f,g=r.count+p.length,v=!_&&s.length>0;return Promise.resolve({records:p,loadingInfo:Object.assign(Object.assign({},r),{pagerId:f,loadingInProgress:_,total:_?void 0:g,count:g,needReload:v})})}catch(e){return console.error(e),Promise.reject(e)}}getFieldsList(e){let t=["__record__id__","__record__label__"];return e.metadata.fields.forEach((e=>{e.standAlone||(t=t.concat(this.getFieldNames(e)))})),t}getStandAloneFieldsList(e){let t={};return e.metadata.fields.forEach((e=>{e.standAlone&&(t=Object.assign(Object.assign({},t),{[e.name]:{fieldType:e.dataType,userType:e.userInterface}}))})),t}getFieldNames(e){const t=this.getSearchDescriptionField(e);return null==t?e.name:[e.name,t]}buildRequestBody(e,t,r,n,i,a,s){const o=r.dataUnitId,l=b.parseDataUnitName(r.name).entityName,c=!(!n.limit&&!n.offset),u={serviceName:e,requestBody:{dataSetID:o,fields:t,entityName:l,pageNumber:i.pageNumber,totalRecordsCount:i.count,pagerID:i.pagerId,standAlone:!1,standAloneFieldsMD:Object.assign({__record__id__:{fieldType:"S",userType:"P"},__record__label__:{fieldType:"S",userType:"P"}},this.getStandAloneFieldsList(r)),tryJoinedFields:!0,parallelLoader:c,crudListener:`br.com.sankhya.bff.${this.getModuleName()}.BFFDataUnitDatasetAdapter`,txProperties:this.getTxProperties(r,n,a,s),useDefaultRowsLimit:!1}};return JSON.stringify(u)}getModuleName(){return a.getContextValue("__SNK__APPLICATION__").getModuleName().replace("-bff","")}getTxProperties(e,t,r,n){const i={"__DATA_UNIT_ADAPTER__[dataUnitName]":e.name};0!==n.length&&(i["__DATA_UNIT_ADAPTER__[criteria]"]=JSON.stringify(n)),null!=r&&0!==r.length&&(i["__DATA_UNIT_ADAPTER__[sorting]"]=JSON.stringify(r)),null!=t.parentRecordId&&(i["__DATA_UNIT_ADAPTER__[parentRecordId]"]=t.parentRecordId);const a=e.getGlobalLoaderProps();return null==a||0===a.size||Array.from(a.entries()).forEach((([e,t])=>{i[e]=t})),i}processRecords(e,t,r){return r.map((r=>{const n={__record__id__:r[0],__record__label__:r[1]};return e.metadata.fields.forEach((e=>{n[e.name]=this.buildFieldValue(e,t,r)})),n}))}buildFieldValue(e,t,r){const i=t.indexOf(e.name);if(i<0)return null;const a=r[i];if(n.isEmpty(a))return null;const o=this.getSearchDescriptionField(e);if(null!=o){const e=t.indexOf(o);if(e>=0)return{value:a,label:r[e]}}return e.userInterface===s.SEARCH?isNaN(Number(a))?a:Number(a):p.getConvertedValue(e,a)}getSearchDescriptionField(e){if(e.userInterface===s.SEARCH){const{ENTITYNAME:t,mergedFrom:r,DESCRIPTIONFIELD:i}=e.properties;if(!n.isEmpty(i))return null!=r?`${r}.${t}.${i}`:`${t}.${i}`}}}class v{static async debounce(e,t){const r=e.name;v._debouncingTimeouts[r]&&(clearTimeout(v._debouncingTimeouts[r]),delete v._debouncingTimeouts[r]),v._debouncingTimeouts[r]=setTimeout((()=>{delete v._debouncingTimeouts[r],t()}),100)}static async loadData(e,t){return new Promise(((r,n)=>{v.debounce(e,(()=>{h.loadData(e,t,this.loadFromServer).then((e=>r(e))).catch((e=>n(e)))}))}))}static async loadFromServer(e,t,r){try{r=v.registryLoading(e,r);const n=await v.callLoader(e,t,r);if(null==n)return;const i=n.records,a=v.buildPaginationInfo(i.length,t,n.loadingInfo),s=null==a?i:i.slice(0,a.lastRecord);return Promise.resolve({records:s,paginationInfo:a})}catch(e){return console.error(e),Promise.reject(e)}}static async callLoader(e,t,r,n){null==n&&(n=new g);const i=await n.load(e,t,r),{records:a,loadingInfo:s}=i;if(v.isOldRequest(e,s))return Promise.resolve(void 0);const o=!n.canSlice()||0===s.count;if(h.cacheRecords(e,a,o,s.loadingInProgress),h.isCacheEnabled(e)&&s.loadingInProgress){const r=Object.assign(Object.assign({},t),{offset:s.count}),i=Object.assign(Object.assign({},s),{pageNumber:(s.pageNumber||0)+1,quiet:!0});this.callLoader(e,r,i,n).then((t=>v.afterLoadingPage(e,t.loadingInfo))).catch((e=>console.error(e)))}return Promise.resolve(i)}static afterLoadingPage(e,t){h.setLoadingStatus(e,t.loadingInProgress);const r=e.getPaginationInfo();if(null==r)return;const n=t.count;t.loadingInProgress?e.updatePagination(Object.assign(Object.assign({},r),{count:n})):t.needReload?e.gotoPage(0):e.updatePagination(Object.assign(Object.assign({},r),{total:n,count:n}))}static registryLoading(e,t){return null==t&&(t={requestTime:(new Date).getTime(),count:0}),v._requestTimeByDataUnit.set(e.name,t.requestTime),t}static isOldRequest(e,t){return v._requestTimeByDataUnit.get(e.name)>t.requestTime}static buildPaginationInfo(e,t,r){let{limit:n,offset:i}=t;if(!n)return;1===r.pageNumber&&(i=0);const{total:a,count:s,loadingInProgress:o}=r,l=0===s||0===e?0:i+1,c=i+Math.min(e,n);return{total:a,count:s,lastRecord:c,firstRecord:l,currentPage:i/n,hasMore:c<s||o}}}v._requestTimeByDataUnit=new Map,v._debouncingTimeouts={};const y=/dd:\/\/([^/]+)\/([^/?]+)/;class b{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",c.gql`query($name: String!) {
2
+ $queryAlias$: fetchDataUnit(name: $name){
3
+ name
4
+ fields{
5
+ name
6
+ defaultValue
7
+ label
8
+ visible
9
+ standAlone
10
+ readOnly
11
+ required
12
+ dataType
13
+ userInterface
14
+ calculated
15
+ group
16
+ order
17
+ properties{
18
+ name
19
+ value
20
+ }
21
+ dependencies{
22
+ masterFields
23
+ type
24
+ expression
25
+ }
26
+ }
27
+ children{
28
+ name
29
+ label
30
+ links{
31
+ source
32
+ target
33
+ }
34
+ }
35
+ }
36
+ }`),this.templateByQuery.set("saveData",c.gql`mutation($changes: [InputBatchChange!]!) {
37
+ $queryAlias$: batchOperationDataUnit(changes: $changes){
38
+ oldId
39
+ id
40
+ label
41
+ ownerDataUnitName
42
+ fields {
43
+ name
44
+ value
45
+ }
46
+ }
47
+ }`),this.templateByQuery.set("fetchDataRecord",c.gql`query($dataunit: String! $recordID: [String!]) {
48
+ $queryAlias$: fetchDataUnit(name: $dataunit){
49
+ record(id: $recordID){
50
+ id
51
+ label
52
+ fields {
53
+ name
54
+ value
55
+ }
56
+ }
57
+ }
58
+ }`),this.templateByQuery.set("fetchDistinctColumn",c.gql`query($dataUnit: String!, $fieldName: String!, $argument: String, $filters: [InputFilter], $parentRecordId: String) {
59
+ $queryAlias$: selectDistinct(dataUnit: $dataUnit, fieldName: $fieldName, argument: $argument, filters: $filters, parentRecordId: $parentRecordId)
60
+ }`)}static parseDataUnitName(e){if(null==e)return;const t=y.exec(e);return t?{entityName:t[1],resourceID:t[2]}:void 0}getDataUnit(t,r,n,i){null==h.applicationResourceID&&m.getResourceID().then((e=>h.applicationResourceID=e));const a=`dd://${t}/${r}${i?"/"+i:""}`,s=null!=n?n.getChildDataunit(a):new e(a);return s.metadataLoader=e=>this.loadMetadata(e),s.dataLoader=(e,t)=>v.loadData(e,t),s.saveLoader=(e,t)=>this.saveData(s,t),s.removeLoader=(e,t)=>this.removeRecords(e,t),s.recordLoader=(e,t)=>this.loadRecord(e,t),s}loadMetadata(e){return new Promise(((t,r)=>{l.get().callGraphQL({values:{name:e.name},query:this.templateByQuery.get("fetchDataUnit")}).then((e=>{var r;const n={name:e.name,label:e.name,children:[...e.children],fields:[]};null===(r=e.fields)||void 0===r||r.forEach((e=>{let t;Array.isArray(e.properties)&&(t={},e.calculated&&(t.gridHeaderTooltip="Campos calculados não podem ser ordenados"),e.properties.forEach((e=>t[e.name]=e.value))),n.fields.push(Object.assign(Object.assign({},e),{properties:t}))})),n.fields.sort(((e,t)=>e.order-t.order)),t(n)})).catch((e=>{r(e)}))}))}loadSelectDistinct(e,t,r){const{parentRecordId:n,filters:i}=e.getLastLoadRequest()||{},a=i.filter((e=>e.name!==`${u}${t}`)),s={dataUnit:e.name,argument:r,fieldName:t,parentRecordId:n,filters:a};return new Promise(((e,t)=>{l.get().callGraphQL({values:s,query:this.templateByQuery.get("fetchDistinctColumn")}).then((t=>{e(t)})).catch((e=>{t(e)}))}))}addTransientProperties(e,t){const r=e.getGlobalLoaderProps();return null==r||0===r.size||(null==t&&(t={}),Array.from(r.entries()).forEach((([e,r])=>{t[`transient.${e}`]=r}))),t}getUpdatingFields(e,t){if(null==t)return;const r=Object.assign({},t);return Object.keys(r).forEach((t=>{const n=e.getField(t);null!=n&&n.standAlone&&delete r[t]})),this.addTransientProperties(e,r)}saveData(e,r){const n=[],a=[],s=r.map((r=>{const{dataUnit:s,record:l,operation:c}=r,u=o.get(s),d=this.getUpdatingFields(u,r.updatingFields);let h;null!=d&&(h=Object.entries(d).map((([e,r])=>{const n=u.getField(e);return{fieldName:e,dataType:n?n.dataType:t.TEXT,value:u.valueToString(e,r)}}))),s===e.name&&(c===i.INSERT||c===i.COPY?a.push(l.__record__id__):n.push(l.__record__id__));const m={dataUnit:s,fields:h,operation:c,recordId:l.__record__id__};return r.sourceId&&(m.sourceId=r.sourceId),l.__parent__record__id__&&(m.parentRecordId=l.__parent__record__id__),m}));return new Promise(((t,r)=>{const i=s.map((e=>function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(e,[])));l.get().callGraphQL({values:{changes:i},query:this.templateByQuery.get("saveData")}).then((r=>{const i=[];null==r||r.forEach((t=>{const r={__record__id__:t.id,__record__label__:t.label,__owner__dataunit__name__:t.ownerDataUnitName},n=o.get(r.__owner__dataunit__name__)||e;t.oldId&&(r.__old__id__=t.oldId),t.fields.forEach((({name:e,value:t})=>{var i;const a=null===(i=null==n?void 0:n.valueFromString)||void 0===i?void 0:i.call(n,e,t);r[e]=void 0!==a?a:t})),i.push(r)})),this.updateCache(e,i,n,a),t(i)})).catch((e=>{r(e)}))}))}updateCache(e,t,r,n){const i=new Map(t.map((e=>[e.__old__id__||e.__record__id__,e]))),a=n.map((e=>{const t=Object.assign({},i.get(e));return delete t.__old__id__,t}));a.length>0&&h.insertRecords(e,e.records[0],a);const s=r.map((e=>Object.assign({},i.get(e))));h.updateRecords(e,s)}getTransientInfo(e,r){const{records:n}=e.getSelectionInfo();return Object.entries(n.filter((e=>e.__record__id__==r))[0]).filter((([e])=>e.startsWith(d.DATA_UNIT_TRANSIENT_PREFIX_NAME))).map((([e,r])=>({fieldName:e,value:r,dataType:t.TEXT})))}removeRecords(e,t){const r=t.map((t=>({dataUnit:e.name,operation:i.DELETE,recordId:t,fields:this.getTransientInfo(e,t)})));return new Promise(((n,i)=>{l.get().callGraphQL({values:{changes:r},query:this.templateByQuery.get("saveData")}).then((()=>{h.removeRecords(e,e.records.filter((e=>t.includes(e.__record__id__)))),n(t)})).catch((e=>{i(e)}))}))}loadRecord(e,t){return new Promise(((r,n)=>{l.get().callGraphQL({values:{recordID:t,dataunit:e.name},query:this.templateByQuery.get("fetchDataRecord")}).then((t=>{const n=[];t.record.forEach((t=>{const r={__record__id__:t.id,__record__label__:t.label};t.fields.forEach((({name:t,value:n})=>{r[t]=e.valueFromString(t,n)})),n.push(r)})),r(n)})).catch((e=>{n(e)}))}))}}class ${constructor(){this._defaultPageSize=100,this._templateByQuery=new Map,this._searchListenersByDataUnit=new Map,this.buldTemplates()}buldTemplates(){this._templateByQuery.set("search",c.gql`query($entityName: String! $argument: String $criteria: InputSearchCriteria $options: InputSearchOptions) {
61
+ $queryAlias$: search(entityName: $entityName argument: $argument criteria: $criteria options: $options){
62
+ value
63
+ label
64
+ }
65
+ }`)}loadSearchOptions(e,r,n,i){var a;const s=(null==r?void 0:r.toString().trim())||void 0;r=isNaN(Number(s))&&s?`%${s}`:s,null==n||n.params.forEach((e=>{e.dataType===t.OBJECT&&(e.value=JSON.stringify(e.value))}));const o=this.applySearchListener(S.beforeSearch,e,r,n,i),c={argument:(null==o?void 0:o.argument)||r,entityName:e,criteria:(null==o?void 0:o.criteria)||n,options:(null==o?void 0:o.searchOptions)||i};return c.options&&(null===(a=c.options)||void 0===a||delete a.dataUnitId),new Promise(((e,t)=>{l.get().callGraphQL({values:c,query:this._templateByQuery.get("search")}).then((t=>{e(t)})).catch((e=>{t(e)}))}))}loadAdvancedSearch(e,r,n,i){var s,o,c;const u=this.applySearchListener(S.beforeSearch,e,r,n,i),d={argument:(null==u?void 0:u.argument)||r,criteria:(null==u?void 0:u.criteria)||n,searchOptions:(null==u?void 0:u.searchOptions)||i},h={query:{$:null===(s=d.criteria)||void 0===s?void 0:s.expression}};(null===(o=d.criteria)||void 0===o?void 0:o.params.length)>0&&(h.params={param:d.criteria.params.map((e=>{let r=e.value;if("string"==typeof r){const e=/CTX\{([^}]+)\}/.exec(r);e&&(r=a.getContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${e[1]})__`))}let n=e.dataType;return n===t.OBJECT?(r=r.value,n="S"):n=function(e){switch(e){case t.NUMBER:return"I";case t.DATE:return"D";default:return"S"}}(e.dataType),{$:r,type:n}}))});const m={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:Object.assign({entityName:e,compacted:!1,ignoreEntityCriteria:!1,limit:this._defaultPageSize,query:{$:d.argument},orderByDesc:!1,externalCriteria:h,localEntityName:null===(c=d.searchOptions)||void 0===c?void 0:c.rootEntity},{options:null!=i?{pkFieldName:i.codeFieldName,label:i.descriptionFieldName,fieldName:i.codeFieldName,useDescriptionOptions:!1,enableRowsCounter:!0}:void 0}),clientEventList:{clientEvent:[]}}};return new Promise(((e,t)=>{l.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(m)).then((t=>e(t))).catch((e=>t(e)))}))}addSearchListener(e,t,r){var n;const i=this._searchListenersByDataUnit.get(t)||[],a=i.find((t=>t.entity===e));if(a){for(const e of Object.keys(r))if(e in a.listener){if((null===(n=a.listener[e])||void 0===n?void 0:n.toString())===r[e].toString())continue;a.listener[e]=r[e]}}else this._searchListenersByDataUnit.set(t,[...i,{entity:e,listener:r}]);return()=>{const r=i.filter((t=>t.entity!==e));r.length?this._searchListenersByDataUnit.set(t,r):this._searchListenersByDataUnit.delete(t)}}applySearchListener(e,t,r,n,i){var a;const s=null==i?void 0:i.dataUnitId;if(!s)return;const o=null===(a=this._searchListenersByDataUnit.get(s))||void 0===a?void 0:a.find((({entity:e})=>e===t));if(!o)return;const{listener:l}=o;return e in l?l[e]({argument:r,criteria:n,searchOptions:i}):void 0}}var S;!function(e){e.beforeSearch="beforeSearch"}(S||(S={}));export{b as D,p as I,$ as P}
@@ -1 +1 @@
1
- import{r as t,h as e,H as i,g as s}from"./p-d2d301a6.js";import{ApplicationContext as o,ObjectUtils as r,DataType as n,ElementIDUtils as l}from"@sankhyalabs/core";import{ApplicationUtils as a,DialogType as d}from"@sankhyalabs/ezui/dist/collection/utils";import{D as h,a as c,b as p}from"./p-38289a55.js";import{R as u}from"./p-b0ef4383.js";import{D as m}from"./p-9695f78b.js";import{S as v}from"./p-32f0935f.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-ff6064e7.js";class x{constructor(t,e){this._selectedNumber=0,this._getMessage=t,this._selectedNumber=e}setExportOption(t,e){const i=this.getExportGroupName();t===h.EXPORT_TO_PDF&&e.push(this.getExportToPDF(i)),t===h.EXPORT_TO_XLS&&e.push(this.getExportToXLS(i)),this.setExportCurrentPage(t,e),this.setExportByEmail(t,e)}setExportCurrentPage(t,e){var i;const s=[h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS];if(t===h.EXPORT_CURRENT_PAGE&&e.push(this.getCurrentPage()),s.includes(t)){let s=e.find((t=>t.id===h.EXPORT_CURRENT_PAGE));null==s&&(e.push(this.getCurrentPage()),s=e.find((t=>t.id===h.EXPORT_CURRENT_PAGE))),(null===(i=null==s?void 0:s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===h.EXPORT_PAGE_TO_PDF&&s.children.push(this.getExportPageToPDF()),t===h.EXPORT_PAGE_TO_XLS&&s.children.push(this.getExportPageToXLS())}}setExportByEmail(t,e){t===h.EXPORT_BY_EMAIL&&e.push(this.getExportByEmail())}getExportToPDF(t){return{id:h.EXPORT_TO_PDF,label:"PDF (.pdf)",group:t}}getExportToXLS(t){return{id:h.EXPORT_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`,group:t}}getCurrentPage(){return{id:h.EXPORT_CURRENT_PAGE,label:this._getMessage("snkDataExporter.label.currentPage"),group:this._getMessage("snkDataExporter.group.custom")}}getExportPageToPDF(){return{id:h.EXPORT_PAGE_TO_PDF,label:"PDF (.pdf)"}}getExportPageToXLS(){return{id:h.EXPORT_PAGE_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportByEmail(){return{id:h.EXPORT_BY_EMAIL,label:`${this._getMessage("snkDataExporter.label.sendByEmail")}...`}}getExportGroupName(){return 1===this._selectedNumber?this._getMessage("snkDataExporter.group.export.selectedLine"):this._selectedNumber>1?this._getMessage("snkDataExporter.group.export.multiSelected").replace("{0}",this._selectedNumber.toString()):this._getMessage("snkDataExporter.group.export.default")}}function f(t){var{methodName:e}=t,i=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(s=Object.getOwnPropertySymbols(t);o<s.length;o++)e.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(i[s[o]]=t[s[o]])}return i}(t,["methodName"]);const s=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.${e}`,n={serviceName:s,requestBody:i};return new Promise(((t,e)=>{m.get().callServiceBroker(s,r.objectToString(n)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return r.stringToObject(i)}(e)))).catch((t=>e(t)))}))}const E=5e3,b=class{constructor(e){t(this,e),this._selectedNumber=0,this._customPrefix="$custom$",this._items=[],this._showDropdown=!1,this._releasedToExport=[h.EXPORT_TO_PDF,h.EXPORT_TO_XLS,h.EXPORT_BY_EMAIL,h.EXPORT_PDF_TO_EMAIL,h.EXPORT_XLS_TO_EMAIL,h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS],this.provider=null,this.messagesBuilder=void 0}async exportByEmail(){const t=this._selectedNumber;this._snkEmailSender.open({type:t>0?"selection":"all",selectedRows:t,email:{attachments:[{name:this._appLabel}]},resolver:({type:t,format:e,email:{to:i,subject:s,message:o}})=>{var r;const n=null!==(r=c[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:c.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,titleGrid:this._appLabel},(()=>{this._snkEmailSender.close(),a.info(this.getMessage("snkDataExporter.message.emailSuccess"),{iconName:"check"})}))}})}getMessage(t,e){if(null==this.messagesBuilder){const t=v.getNearestInstance(this._element);t&&(this.messagesBuilder=t.messagesBuilder)}return this.messagesBuilder.getMessage(t,e)}positionDropdown(){var t;const e=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();null!=e&&null!=this._dropdownParent&&(this._dropdownParent.style.top=e.y+e.height+5+"px",this._dropdownParent.style.left=e.x+"px")}closeDropdown(t){const e=null==t?void 0:t.target;null!=e&&(e.closest(".snk-data-exporter")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}controlDropdown(){this._showDropdown=!this._showDropdown}async resolveExporter(t,e){if(null==this.provider||null==t||null==e)return;const i=this.provider.getFilters(),s=await this.provider.getColumnsMetadata(),o=this.provider.getOrders(),r=this.provider.getResourceURI(),n=this.provider.getSelectedIDs(),l=t.exportOption,d=[h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS];delete t.exportOption;let c=Object.assign({filters:i,columns:s,sort:o,resourceURI:r,selectedIDs:n.slice(0,E)},t);if(d.includes(l)||"page"==t.type){const t=this.provider.getOffset(),e=this.provider.getLimit();c=Object.assign(Object.assign({},c),{offset:t,limit:e,selectedIDs:[]})}else"all"==t.type&&(c=Object.assign(Object.assign({},c),{offset:0,limit:E,selectedIDs:[]}));f(c).then((t=>e(t))).catch((t=>a.error(this.getMessage("snkDataExporter.message.exportError"),t?t.statusMessage:this.getMessage("snkDataExporter.message.exportError"))))}getOptionKey(t){return Object.keys(h).find((e=>h[e]===t))}dispatchExporter(t){var e;const i=this.getOptionKey(t),s=null!==(e=p[i])&&void 0!==e?e:p.EXPORT_TO_PDF,r=p[i]===p.EXPORT_TO_XLS;this.resolveExporter({methodName:h[`EXPORT_TO_${s}`],fileName:this._appLabel,titleGrid:this._appLabel,exportOption:t,limit:E},(t=>{!function({fileSessionKey:t,isDownload:e}){const i=o.getContextValue("__SNK__APPLICATION__");window.open(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/mge/visualizadorArquivos.mge?chaveArquivo=${t}${e?"&download=S":""}`),a.info(function(t){var e;return null===(e=null==t?void 0:t.messagesBuilder)||void 0===e?void 0:e.getMessage("fileViewer.message.exportSuccess",void 0)}(i),{iconName:"check"})}(Object.assign(Object.assign({},t),{fileType:s,isDownload:r}))}))}async processExporter(t){var e,i,s,o;const r=null==t?void 0:t.detail,n=[h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS],l=null===(e=null==r?void 0:r.id)||void 0===e?void 0:e.includes(this._customPrefix);if((null==r?void 0:r.id)===h.EXPORT_CURRENT_PAGE)return;const c=null===(i=this.provider)||void 0===i?void 0:i.getSelectedIDs(),p=null===(s=this.provider)||void 0===s?void 0:s.getTotalRecords(),u=null===(o=this.provider)||void 0===o?void 0:o.getLimit();let m=!1;if(n.includes(null==r?void 0:r.id)&&u<=E||l?m=!1:(null==c?void 0:c.length)?m=c.length>E:p>E&&(m=!0),m){const t=E.toLocaleString("pt-BR",{minimumFractionDigits:0}),e={title:this.getMessage("snkDataExporter.limitExceeded.title"),description:`\n ${this.getMessage("snkDataExporter.limitExceeded.description",{limit:t})}\n <br/><br/>\n <b>\n ${this.getMessage("snkDataExporter.limitExceeded.subdescription")}\n </b>\n `,cancel:this.getMessage("snkDataExporter.limitExceeded.cancel"),confirm:this.getMessage("snkDataExporter.limitExceeded.continue")};if(!await a.confirm(e.title,e.description,null,d.WARN,{labelCancel:e.cancel,labelConfirm:e.confirm}))return}if(l)return this.openPersonalizedReports(r.id),void(this._showDropdown=!1);this._releasedToExport.includes(null==r?void 0:r.id)&&(r.id===h.EXPORT_BY_EMAIL?this.exportByEmail():this.dispatchExporter(r.id),this._showDropdown=!1)}loadItems(){const t=[];this._releasedToExport.forEach((e=>{var i;null===(i=this._itemBuilder)||void 0===i||i.setExportOption(e,t)})),this.loadPersonalizedItems(t)}async loadPersonalizedItems(t){var e;const i=null===(e=this.provider)||void 0===e?void 0:e.getRecordID();if(null==i)return void(this._items=t);const s=await function(t){const e=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.getPersonalizedReports`,i={serviceName:e,requestBody:t};return new Promise(((t,s)=>m.get().callServiceBroker(e,r.objectToString(i)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return r.stringToObject(i)}(e)))).catch((t=>s(t)))))}({recordID:i});null==s||s.forEach((e=>{t.push({id:`${this._customPrefix}_${e.ID}`,label:e.label,group:this.getMessage("snkDataExporter.group.custom")})})),this._items=t}openPersonalizedReports(t){var e;const i=[],s=(null==t?void 0:t.replace(this._customPrefix,""))||"";null===(e=this.provider)||void 0===e||e.getSelectedIDs().forEach((({name:t,type:e,value:s},o)=>{const r=[];r.fields=[],0===o&&(i[`PK_${t}`]={type:this.parseDataType(e),value:s},i.pks=[]),r.fields.push({nome:t,tipo:e,valor:s}),i.pks.push(r)})),this._application.openApp(`${u}${s}`,i)}parseDataType(t){switch(t){case n.NUMBER:return"I";case n.DATE:return"D";default:return"S"}}loadDropdown(){var t,e;this._selectedNumber=(null===(e=null===(t=this.provider)||void 0===t?void 0:t.getSelectedIDs())||void 0===e?void 0:e.length)||0,this._itemBuilder=new x(this.getMessage.bind(this),this._selectedNumber),this.loadItems()}getElementID(t){return{[l.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:l.getInternalIDInfo(t)}}canShowDropdown(){var t;return this._showDropdown&&(null===(t=this._items)||void 0===t?void 0:t.length)>0}componentWillLoad(){var t;this._application=o.getContextValue("__SNK__APPLICATION__"),null===(t=this._application)||void 0===t||t.getAppLabel().then((t=>this._appLabel=t)),this.setEvents()}componentDidLoad(){null!=this._element&&(l.addIDInfo(this._element),this.positionDropdown())}componentWillUpdate(){var t;this._showDropdown&&!(null===(t=this._items)||void 0===t?void 0:t.length)&&this.loadDropdown()}componentDidUpdate(){var t;this._showDropdown?this.positionDropdown():(null===(t=this._items)||void 0===t?void 0:t.length)>0&&(this._items=[])}render(){return e(i,null,e("div",{class:`snk-data-exporter\n ${this.canShowDropdown()?" ez-elevation--16":""}\n `},e("ez-button",Object.assign({ref:t=>this._ezButton=t,iconName:"file-download",size:"small",mode:"icon",title:this.getMessage("snkDataExporter.group.export.title"),onClick:()=>this.controlDropdown()},this.getElementID("button"))),e("div",Object.assign({ref:t=>this._dropdownParent=t,class:`snk-data-exporter__dropdown\n ${this.canShowDropdown()?"snk-data-exporter__dropdown--show":""}\n `},this.getElementID("dropdown")),this.canShowDropdown()&&e("ez-dropdown",Object.assign({items:this._items,onEzClick:t=>this.processExporter(t)},this.getElementID("dropdown"))))),this.canShowDropdown()&&e("div",Object.assign({class:"ez-scrim ez-scrim--light"},this.getElementID("ezScrim"))),e("snk-exporter-email-sender",Object.assign({ref:t=>this._snkEmailSender=t,getMessage:(t,e)=>this.getMessage(t,e)},this.getElementID("snkExporterEmailSender"))))}get _element(){return s(this)}};b.style=".sc-snk-data-exporter-h{display:flex;width:fit-content;height:fit-content}.snk-data-exporter.sc-snk-data-exporter{display:flex;width:fit-content;height:fit-content}.snk-data-exporter__dropdown.sc-snk-data-exporter{display:none}.snk-data-exporter__dropdown--show.sc-snk-data-exporter{display:flex;flex-direction:column;position:fixed}.snk-data-exporter__dropdown.sc-snk-data-exporter>ez-dropdown.sc-snk-data-exporter{position:relative}";export{b as snk_data_exporter}
1
+ import{r as t,h as e,H as i,g as s}from"./p-d2d301a6.js";import{ApplicationContext as o,ObjectUtils as r,DataType as n,ElementIDUtils as l}from"@sankhyalabs/core";import{ApplicationUtils as a,DialogType as d}from"@sankhyalabs/ezui/dist/collection/utils";import{D as h,a as c,b as p}from"./p-38289a55.js";import{R as u}from"./p-b0ef4383.js";import{D as m}from"./p-9695f78b.js";import{S as v}from"./p-f3d1c48e.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-05243555.js";class x{constructor(t,e){this._selectedNumber=0,this._getMessage=t,this._selectedNumber=e}setExportOption(t,e){const i=this.getExportGroupName();t===h.EXPORT_TO_PDF&&e.push(this.getExportToPDF(i)),t===h.EXPORT_TO_XLS&&e.push(this.getExportToXLS(i)),this.setExportCurrentPage(t,e),this.setExportByEmail(t,e)}setExportCurrentPage(t,e){var i;const s=[h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS];if(t===h.EXPORT_CURRENT_PAGE&&e.push(this.getCurrentPage()),s.includes(t)){let s=e.find((t=>t.id===h.EXPORT_CURRENT_PAGE));null==s&&(e.push(this.getCurrentPage()),s=e.find((t=>t.id===h.EXPORT_CURRENT_PAGE))),(null===(i=null==s?void 0:s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===h.EXPORT_PAGE_TO_PDF&&s.children.push(this.getExportPageToPDF()),t===h.EXPORT_PAGE_TO_XLS&&s.children.push(this.getExportPageToXLS())}}setExportByEmail(t,e){t===h.EXPORT_BY_EMAIL&&e.push(this.getExportByEmail())}getExportToPDF(t){return{id:h.EXPORT_TO_PDF,label:"PDF (.pdf)",group:t}}getExportToXLS(t){return{id:h.EXPORT_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`,group:t}}getCurrentPage(){return{id:h.EXPORT_CURRENT_PAGE,label:this._getMessage("snkDataExporter.label.currentPage"),group:this._getMessage("snkDataExporter.group.custom")}}getExportPageToPDF(){return{id:h.EXPORT_PAGE_TO_PDF,label:"PDF (.pdf)"}}getExportPageToXLS(){return{id:h.EXPORT_PAGE_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportByEmail(){return{id:h.EXPORT_BY_EMAIL,label:`${this._getMessage("snkDataExporter.label.sendByEmail")}...`}}getExportGroupName(){return 1===this._selectedNumber?this._getMessage("snkDataExporter.group.export.selectedLine"):this._selectedNumber>1?this._getMessage("snkDataExporter.group.export.multiSelected").replace("{0}",this._selectedNumber.toString()):this._getMessage("snkDataExporter.group.export.default")}}function f(t){var{methodName:e}=t,i=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(s=Object.getOwnPropertySymbols(t);o<s.length;o++)e.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(i[s[o]]=t[s[o]])}return i}(t,["methodName"]);const s=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.${e}`,n={serviceName:s,requestBody:i};return new Promise(((t,e)=>{m.get().callServiceBroker(s,r.objectToString(n)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return r.stringToObject(i)}(e)))).catch((t=>e(t)))}))}const E=5e3,b=class{constructor(e){t(this,e),this._selectedNumber=0,this._customPrefix="$custom$",this._items=[],this._showDropdown=!1,this._releasedToExport=[h.EXPORT_TO_PDF,h.EXPORT_TO_XLS,h.EXPORT_BY_EMAIL,h.EXPORT_PDF_TO_EMAIL,h.EXPORT_XLS_TO_EMAIL,h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS],this.provider=null,this.messagesBuilder=void 0}async exportByEmail(){const t=this._selectedNumber;this._snkEmailSender.open({type:t>0?"selection":"all",selectedRows:t,email:{attachments:[{name:this._appLabel}]},resolver:({type:t,format:e,email:{to:i,subject:s,message:o}})=>{var r;const n=null!==(r=c[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:c.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,titleGrid:this._appLabel},(()=>{this._snkEmailSender.close(),a.info(this.getMessage("snkDataExporter.message.emailSuccess"),{iconName:"check"})}))}})}getMessage(t,e){if(null==this.messagesBuilder){const t=v.getNearestInstance(this._element);t&&(this.messagesBuilder=t.messagesBuilder)}return this.messagesBuilder.getMessage(t,e)}positionDropdown(){var t;const e=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();null!=e&&null!=this._dropdownParent&&(this._dropdownParent.style.top=e.y+e.height+5+"px",this._dropdownParent.style.left=e.x+"px")}closeDropdown(t){const e=null==t?void 0:t.target;null!=e&&(e.closest(".snk-data-exporter")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}controlDropdown(){this._showDropdown=!this._showDropdown}async resolveExporter(t,e){if(null==this.provider||null==t||null==e)return;const i=this.provider.getFilters(),s=await this.provider.getColumnsMetadata(),o=this.provider.getOrders(),r=this.provider.getResourceURI(),n=this.provider.getSelectedIDs(),l=t.exportOption,d=[h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS];delete t.exportOption;let c=Object.assign({filters:i,columns:s,sort:o,resourceURI:r,selectedIDs:n.slice(0,E)},t);if(d.includes(l)||"page"==t.type){const t=this.provider.getOffset(),e=this.provider.getLimit();c=Object.assign(Object.assign({},c),{offset:t,limit:e,selectedIDs:[]})}else"all"==t.type&&(c=Object.assign(Object.assign({},c),{offset:0,limit:E,selectedIDs:[]}));f(c).then((t=>e(t))).catch((t=>a.error(this.getMessage("snkDataExporter.message.exportError"),t?t.statusMessage:this.getMessage("snkDataExporter.message.exportError"))))}getOptionKey(t){return Object.keys(h).find((e=>h[e]===t))}dispatchExporter(t){var e;const i=this.getOptionKey(t),s=null!==(e=p[i])&&void 0!==e?e:p.EXPORT_TO_PDF,r=p[i]===p.EXPORT_TO_XLS;this.resolveExporter({methodName:h[`EXPORT_TO_${s}`],fileName:this._appLabel,titleGrid:this._appLabel,exportOption:t,limit:E},(t=>{!function({fileSessionKey:t,isDownload:e}){const i=o.getContextValue("__SNK__APPLICATION__");window.open(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/mge/visualizadorArquivos.mge?chaveArquivo=${t}${e?"&download=S":""}`),a.info(function(t){var e;return null===(e=null==t?void 0:t.messagesBuilder)||void 0===e?void 0:e.getMessage("fileViewer.message.exportSuccess",void 0)}(i),{iconName:"check"})}(Object.assign(Object.assign({},t),{fileType:s,isDownload:r}))}))}async processExporter(t){var e,i,s,o;const r=null==t?void 0:t.detail,n=[h.EXPORT_PAGE_TO_PDF,h.EXPORT_PAGE_TO_XLS],l=null===(e=null==r?void 0:r.id)||void 0===e?void 0:e.includes(this._customPrefix);if((null==r?void 0:r.id)===h.EXPORT_CURRENT_PAGE)return;const c=null===(i=this.provider)||void 0===i?void 0:i.getSelectedIDs(),p=null===(s=this.provider)||void 0===s?void 0:s.getTotalRecords(),u=null===(o=this.provider)||void 0===o?void 0:o.getLimit();let m=!1;if(n.includes(null==r?void 0:r.id)&&u<=E||l?m=!1:(null==c?void 0:c.length)?m=c.length>E:p>E&&(m=!0),m){const t=E.toLocaleString("pt-BR",{minimumFractionDigits:0}),e={title:this.getMessage("snkDataExporter.limitExceeded.title"),description:`\n ${this.getMessage("snkDataExporter.limitExceeded.description",{limit:t})}\n <br/><br/>\n <b>\n ${this.getMessage("snkDataExporter.limitExceeded.subdescription")}\n </b>\n `,cancel:this.getMessage("snkDataExporter.limitExceeded.cancel"),confirm:this.getMessage("snkDataExporter.limitExceeded.continue")};if(!await a.confirm(e.title,e.description,null,d.WARN,{labelCancel:e.cancel,labelConfirm:e.confirm}))return}if(l)return this.openPersonalizedReports(r.id),void(this._showDropdown=!1);this._releasedToExport.includes(null==r?void 0:r.id)&&(r.id===h.EXPORT_BY_EMAIL?this.exportByEmail():this.dispatchExporter(r.id),this._showDropdown=!1)}loadItems(){const t=[];this._releasedToExport.forEach((e=>{var i;null===(i=this._itemBuilder)||void 0===i||i.setExportOption(e,t)})),this.loadPersonalizedItems(t)}async loadPersonalizedItems(t){var e;const i=null===(e=this.provider)||void 0===e?void 0:e.getRecordID();if(null==i)return void(this._items=t);const s=await function(t){const e=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.getPersonalizedReports`,i={serviceName:e,requestBody:t};return new Promise(((t,s)=>m.get().callServiceBroker(e,r.objectToString(i)).then((e=>t(function(t){var e;const i=null===(e=null==t?void 0:t.json)||void 0===e?void 0:e.$;if(null!=i)return r.stringToObject(i)}(e)))).catch((t=>s(t)))))}({recordID:i});null==s||s.forEach((e=>{t.push({id:`${this._customPrefix}_${e.ID}`,label:e.label,group:this.getMessage("snkDataExporter.group.custom")})})),this._items=t}openPersonalizedReports(t){var e;const i=[],s=(null==t?void 0:t.replace(this._customPrefix,""))||"";null===(e=this.provider)||void 0===e||e.getSelectedIDs().forEach((({name:t,type:e,value:s},o)=>{const r=[];r.fields=[],0===o&&(i[`PK_${t}`]={type:this.parseDataType(e),value:s},i.pks=[]);const n={nome:t,tipo:this.parseDataType(e),valor:s};r.fields.push(n),i.pks.push(r)})),this._application.openApp(`${u}${s}`,i)}parseDataType(t){switch(t){case n.NUMBER:return"I";case n.DATE:return"D";default:return"S"}}loadDropdown(){var t,e;this._selectedNumber=(null===(e=null===(t=this.provider)||void 0===t?void 0:t.getSelectedIDs())||void 0===e?void 0:e.length)||0,this._itemBuilder=new x(this.getMessage.bind(this),this._selectedNumber),this.loadItems()}getElementID(t){return{[l.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:l.getInternalIDInfo(t)}}canShowDropdown(){var t;return this._showDropdown&&(null===(t=this._items)||void 0===t?void 0:t.length)>0}componentWillLoad(){var t;this._application=o.getContextValue("__SNK__APPLICATION__"),null===(t=this._application)||void 0===t||t.getAppLabel().then((t=>this._appLabel=t)),this.setEvents()}componentDidLoad(){null!=this._element&&(l.addIDInfo(this._element),this.positionDropdown())}componentWillUpdate(){var t;this._showDropdown&&!(null===(t=this._items)||void 0===t?void 0:t.length)&&this.loadDropdown()}componentDidUpdate(){var t;this._showDropdown?this.positionDropdown():(null===(t=this._items)||void 0===t?void 0:t.length)>0&&(this._items=[])}render(){return e(i,null,e("div",{class:`snk-data-exporter\n ${this.canShowDropdown()?" ez-elevation--16":""}\n `},e("ez-button",Object.assign({ref:t=>this._ezButton=t,iconName:"file-download",size:"small",mode:"icon",title:this.getMessage("snkDataExporter.group.export.title"),onClick:()=>this.controlDropdown()},this.getElementID("button"))),e("div",Object.assign({ref:t=>this._dropdownParent=t,class:`snk-data-exporter__dropdown\n ${this.canShowDropdown()?"snk-data-exporter__dropdown--show":""}\n `},this.getElementID("dropdown")),this.canShowDropdown()&&e("ez-dropdown",Object.assign({items:this._items,onEzClick:t=>this.processExporter(t)},this.getElementID("dropdown"))))),this.canShowDropdown()&&e("div",Object.assign({class:"ez-scrim ez-scrim--light"},this.getElementID("ezScrim"))),e("snk-exporter-email-sender",Object.assign({ref:t=>this._snkEmailSender=t,getMessage:(t,e)=>this.getMessage(t,e)},this.getElementID("snkExporterEmailSender"))))}get _element(){return s(this)}};b.style=".sc-snk-data-exporter-h{display:flex;width:fit-content;height:fit-content}.snk-data-exporter.sc-snk-data-exporter{display:flex;width:fit-content;height:fit-content}.snk-data-exporter__dropdown.sc-snk-data-exporter{display:none}.snk-data-exporter__dropdown--show.sc-snk-data-exporter{display:flex;flex-direction:column;position:fixed}.snk-data-exporter__dropdown.sc-snk-data-exporter>ez-dropdown.sc-snk-data-exporter{position:relative}";export{b as snk_data_exporter}
@@ -0,0 +1 @@
1
+ import{r as t,h as i}from"./p-d2d301a6.js";import{ModalAction as e}from"@sankhyalabs/ezui/dist/collection/components/ez-modal-container";import{ApplicationUtils as s}from"@sankhyalabs/ezui/dist/collection/utils";import{F as l}from"./p-d9804798.js";import{F as r}from"./p-ff1990ad.js";import{ObjectUtils as o}from"@sankhyalabs/core";import{P as a}from"./p-057fad05.js";import{F as n}from"./p-fa80e546.js";import"./p-933c0c0b.js";const d=class{constructor(i){t(this,i),this.getMessage=void 0,this.configName=void 0,this.filters=void 0,this.applyFilters=void 0,this.closeModal=void 0,this.addPersonalizedFilter=void 0,this.editPersonalizedFilter=void 0,this.deletePersonalizedFilter=void 0,this.filtersToDelete=[],this.disablePersonalizedFilter=void 0}deletePersonalizedFilterListener(t){this.filtersToDelete.push(t.detail)}getCustomMessage(t,i){var e;return null===(e=this.getMessage)||void 0===e?void 0:e.call(this,`snkFilterBar.filterModal.${t}`,i)}handleClearAll(){const{customFilters:t,quickFilters:i,otherFilters:e,multiListFilters:s}=this.filters.reduce(((t,i)=>i.type===r.MULTI_LIST?(t.multiListFilters.push(i),t):i.filterType===l.QUICK_FILTER?(t.quickFilters.push(i),t):i.filterType===l.CUSTOM_FILTER?(t.customFilters.push(i),t):i.filterType===l.OTHER_FILTERS?(t.otherFilters.push(i),t):t),{quickFilters:[],customFilters:[],otherFilters:[],multiListFilters:[]});this.handleClearFilterList(i),this.handleClearCustomFilters(t),this.handleClearOthersFilters(e),s.forEach((t=>this.handleClearSigleFilter(t)))}handleClearOthersFilters(t){this.filters=this.filters.map((i=>t.includes(i)?Object.assign(Object.assign({},i),{value:void 0}):i))}handleClearCustomFilters(t){this.filters.forEach(((i,e)=>{i.filterType===l.CUSTOM_FILTER&&(this.filters[e]=this.clearAllCustomFilter(t).shift())}))}clearAllCustomFilter(t){return t.map((t=>{const i=Object.assign({},t);return delete i.value,i.visible=!1,i.groupedItems&&(i.groupedItems=this.clearAllCustomFilter(i.groupedItems)),i}))}handleClose(){if(o.objectToString(this.filters)!==o.objectToString(this._originalFilterConfig))return s.confirm(this.getCustomMessage("validations.notSaved.title"),this.getCustomMessage("validations.notSaved.message")).then((t=>{t&&this.closeModal()}));this.closeModal()}handleApplyFilters(){const t=this.filters.find((t=>t.filterType===l.CUSTOM_FILTER));this.isValidCustomFilter(t)&&this.applyFilters(this.filters),this.filtersToDelete.length>0&&(this.filtersToDelete.forEach((t=>{this.deletePersonalizedFilter(t,this.configName)})),this.filtersToDelete=[])}isValidCustomFilter(t){return!!a.validateVariableValues(t)||(s.alert(this.getCustomMessage("validations.notFullFilled.title"),this.getCustomMessage("validations.notFullFilled.message")),!1)}modalActionListener(t){switch(t.detail){case e.CANCEL:this.handleClearAll();break;case e.OK:this.handleApplyFilters();break;case e.CLOSE:this.handleClose()}}handleFilterChange(t){this.filters=this.filters.map((i=>i.id===t.id?t:i))}handleClearFilterList(t){this.filters=this.filters.map((i=>t.includes(i)?Object.assign(Object.assign({},i),{value:void 0}):i))}handleClearSigleFilter(t){if(r.MULTI_LIST===t.type){let i=o.copy(t);this.uncheckFilterValues(i.value);const e=o.copy(this.filters),s=e.findIndex((i=>i.id===t.id));return e.splice(s,1,i),void(this.filters=o.copy(e))}if(r.CHECK_BOX_LIST===t.type){const i=o.copy(this.filters);return i.find((i=>i.id===t.id)).value=void 0,void(this.filters=o.copy(i))}this.filters.find((i=>i.id===t.id)).value=void 0}uncheckFilterValues(t){return t.forEach((t=>{t&&(t.check=!1)})),t}renderFilterItem(t,e){return i("snk-filter-modal-item",{class:e?"ez-col ez-col--sd-12":"ez-col ez-col--sd-6 ez-padding--small",filterItem:t,configName:this.configName,onFilterChange:t=>this.handleFilterChange(t.detail),onEditPersonalizedFilter:t=>this.editPersonalizedFilter(t.detail),onAddPersonalizedFilter:()=>this.addPersonalizedFilter()})}isDefaultFilterNumberVariation(t){var i;return t.type===r.NUMBER&&(!t.props.variation||(null===(i=t.props)||void 0===i?void 0:i.variation)===n.DEFAULT)}mountFiltersLines(t){let i=0,e=!1;const s={};for(let l=0;l<t.length;l++){s[i]=s[i]||[];const o=t[l],a=l===t.length-1,n=o.type===r.TEXT||this.isDefaultFilterNumberVariation(o),d=!a&&(t[l+1].type===r.TEXT||this.isDefaultFilterNumberVariation(t[l+1]));n&&d||e?(s[i].push(o),e=s[i].length<2,2===s[i].length&&++i):(s[i]=s[i]||[],s[i].push(o),++i)}return Object.values(s)}renderFilterLine(t){const i=1===t.length;return t.map((t=>this.renderFilterItem(t,i)))}getIformedFiltersCount(t){let i=0;return t.forEach((t=>{var e,s,l,o,a,n;r.MULTI_LIST!==t.type?r.CHECK_BOX_LIST!==t.type?null==t.groupedItems?t.value&&i++:i=t.groupedItems.filter((t=>t.visible)).length:i+=Object.entries(null!==(n=t.value)&&void 0!==n?n:{}).filter((([t,i])=>!0===i)).map((([t,i])=>t)).length:i+=null!==(a=null===(o=null===(l=null!==(s=null===(e=t.value)||void 0===e?void 0:e.elements)&&void 0!==s?s:t.value)||void 0===l?void 0:l.filter((t=>null==t?void 0:t.check)))||void 0===o?void 0:o.length)&&void 0!==a?a:0})),i}renderCollapsibleFilterBox(t,e,s,l=!0){if(!e.length)return null;const r=this.getIformedFiltersCount(e),o=this.mountFiltersLines(e);return i("ez-collapsible-box",{class:"snk-filter-modal__collapsible-box",headerSize:"medium",value:!0,label:t},!!r&&i("ez-badge",{class:"ez-badge--primary-subtle",slot:"rightSlot",label:null==r?void 0:r.toString()}),i("div",{class:"ez-row snk-filter-modal__rendered-items"},o.map(this.renderFilterLine.bind(this))),l&&i("div",{class:"ez-flex ez-flex--justify-end grow"},i("ez-button",{class:"ez-button--tertiary",size:"medium",label:"Limpar",onClick:()=>s?this.handleClearSigleFilter(e[0]):this.handleClearFilterList(e)})))}componentWillRender(){this._modalTitle=this.getCustomMessage("title"),this._okButtonLabel=this.getCustomMessage("okButtonLabel"),this._cancelButtonLabel=this.getCustomMessage("cancelButtonLabel")}componentDidLoad(){this._originalFilterConfig||(this._originalFilterConfig=this.filters)}render(){const t=this.filters.filter((t=>t.filterType===l.CUSTOM_FILTER)),e=this.filters.filter((t=>t.filterType===l.QUICK_FILTER)),s=this.filters.filter((t=>t.filterType===l.OTHER_FILTERS));return i("ez-modal-container",{class:"snk-filter-modal__container",modalTitle:this._modalTitle,cancelButtonLabel:this._cancelButtonLabel,okButtonLabel:this._okButtonLabel,onEzModalAction:this.modalActionListener.bind(this)},i("div",{class:"snk-filter-modal__content ez-col--sd-12"},!this.disablePersonalizedFilter&&this.renderCollapsibleFilterBox(this.getCustomMessage("customFilters"),t,!1,!1),this.renderCollapsibleFilterBox(this.getCustomMessage("quickFilters"),e,!1),s.map((t=>this.renderCollapsibleFilterBox(t.label,[t],!0)))))}};d.style="ez-modal{--ez-modal-content-padding:24px 12px}.snk-filter-modal__container{width:344px;max-width:344px;min-width:344px;overflow:hidden}.snk-filter-modal__content{display:flex;flex-direction:column;gap:var(--space--medium, 12px);padding-right:var(--space--3xs, 4px)}.snk-filter-modal__collapsible-box{border:var(--border--small, 1px solid) var(--color--strokes, #DCE0E8);border-radius:var(--border--radius-medium);padding:var(--space--medium, 12px) var(--space--small, 6px)}.snk-filter-modal__rendered-items{max-height:760px;overflow-x:clip;overflow-y:auto}.snk-filter-modal__rendered-items::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}";export{d as snk_filter_modal}
@@ -0,0 +1 @@
1
+ import{r as t,c as i,h as e,H as s,g as r}from"./p-d2d301a6.js";import{FloatingManager as n,DateUtils as l,ElementIDUtils as o}from"@sankhyalabs/core";import{F as h}from"./p-ff1990ad.js";import{F as a}from"./p-fa80e546.js";const c=class{constructor(e){t(this,e),this.visibleChanged=i(this,"visibleChanged",7),this.filterChange=i(this,"filterChange",3),this.innerClickCheck=(t,i)=>i.id!=n.MODAL_ELEMENT_ID||(this.detailIsVisible=!1,!1),this.detailIsVisible=void 0,this.config=void 0,this.getMessage=void 0}observeDetailIsVisible(t){this.visibleChanged.emit(t)}async showUp(t=!1){return new Promise((i=>{this._filterItemElement.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"}),t&&(this._closeCallback=i,window.requestAnimationFrame((()=>{this._floatingID=n.float(this._popover,this._popoverContainer,this.getFloatOptions()),this._popover.show(),this.detailIsVisible=!0})))}))}updatePosition(){null!=this._floatingID&&n.updateFloatPosition(this._popover,this._popoverContainer,this.getFloatOptions())}getFloatOptions(){return{autoClose:!0,innerClickTest:this.innerClickCheck,backClickListener:()=>this.onDetailCloseCallback(),left:this.getScrollOffsetLeft(),top:this.getScrollOffsetTop(),useOverlay:!0,overlayClassName:"ez-scrim ez-scrim--light",isFixed:!0}}getScrollOffsetLeft(){const t=getComputedStyle(this._filterItemElement).getPropertyValue("padding-left");return`calc(${this._filterItemElement.getBoundingClientRect().x}px + ${t})`}getScrollOffsetTop(){const t=this._filterItemElement.getBoundingClientRect();return t.y+t.height+"px"}controlScrollPage(){window.removeEventListener("scroll",this.updatePosition.bind(this)),window.addEventListener("scroll",this.updatePosition.bind(this))}getConfigChanges(){var t;const i=this.config;(null===(t=i.groupedItems)||void 0===t?void 0:t.length)&&(i.visible=!1,i.groupedItems=i.groupedItems.map((t=>Object.assign(Object.assign({},t),{visible:!1}))));const e=i.type===h.MULTI_LIST&&Array.isArray(i.value)?i.value.map((t=>Object.assign(Object.assign({},t),{check:!1}))):void 0;return Object.assign(Object.assign({},i),{value:e})}async hideDetail(){this.detailIsVisible&&null!=this._floatingID&&n.close(this._floatingID)}onDetailCloseCallback(){this._floatingID=void 0,this.detailIsVisible=!1,this._closeCallback&&(this._closeCallback(),this._closeCallback=void 0)}clickListener(t){if([this._chipElement,this._leftIconElement,this._rightIconElement].includes(t.target)){if(t.target===this._rightIconElement&&this.canClearFilter()){const t=this.getConfigChanges();this.filterChange.emit(t)}else this.detailIsVisible?this.hideDetail():this.showUp(!0);t.preventDefault(),t.stopImmediatePropagation(),t.stopPropagation()}}mouseDownListener(t){this.detailIsVisible&&[this._chipElement,this._leftIconElement,this._rightIconElement].includes(t.target)&&(t.preventDefault(),t.stopImmediatePropagation(),t.stopPropagation())}getLabel(t=!1){var i,e;const{type:s,value:r,label:n,props:o,groupedItems:c=[]}=this.config;if(r||c.length){if(s===h.BINARY_SELECT){const[i,e]=o.options,s=this.getMessage("snkFilterBar.binarySelectTooltip");if(i.name===r)return t?`${s} ${String(i.label).toLowerCase()}`:i.label;if(e.name===r)return t?`${s} ${String(e.label).toLowerCase()}`:e.label}if(s===h.MULTI_SELECT)return`${n}: ${o.options.find((t=>t.value===r)).label}`;if(s===h.PERIOD){let{end:i,start:e}=r;"string"==typeof i&&(i=new Date(i),i.setMinutes(i.getMinutes()+i.getTimezoneOffset())),"string"==typeof e&&(e=new Date(e),e.setMinutes(e.getMinutes()+e.getTimezoneOffset()));const s=new Intl.DateTimeFormat("pt-BR");if(i&&e){const s=e.getFullYear()===i.getFullYear(),r=Object.assign({day:"2-digit",month:"2-digit"},(!s||t)&&{year:"2-digit"}),o=l.formatDate(e,r),h=l.formatDate(i,r);return t?this.getMessage("snkFilterBar.fullPeriodTooltip",{LABEL:n,START_LABEL:o,END_LABEL:h}):`${n}: ${o} → ${h}`}return e?`${n}: ${this.getMessage("snkFilterBar.onlyStartToltip")} ${s.format(e)}`:i?`${n}: ${this.getMessage("snkFilterBar.onlyEndToltip")} ${s.format(i)}`:n}if(s===h.SEARCH)return`${n}: ${r.value} - ${r.label}`;if(s===h.PERSONALIZED){const t=this.calculateActiveCount(c);return t<=0?n:`${n}: ${this.getMessage("snkFilterBar.personalizedCount",{activeCount:t})}`}if(s===h.MULTI_LIST){const e=(null!==(i=r.elements)&&void 0!==i?i:r).filter((t=>null==t?void 0:t.check));return this.getLabelFromCheckedOptions(e,n,t)}if(s===h.CHECK_BOX_LIST){const i=Object.entries(null!=r?r:{}).filter((([t,i])=>!0===i)).map((([t,i])=>t)),s=(null!==(e=o.options)&&void 0!==e?e:[]).filter((t=>i.includes(t.name)));return this.getLabelFromCheckedOptions(s,n,t)}if(s===h.NUMBER&&o.variation===a.INTERVAL){const{start:t,end:i}=r;if(t&&i)return this.getMessage("snkFilterBar.fullIntervalTooltip",{LABEL:n,START_LABEL:t,END_LABEL:i});if(t)return`${n}: ${this.getMessage("snkFilterBar.onlyStartToltip")} ${Number(t)}`;if(i)return`${n}: ${this.getMessage("snkFilterBar.onlyEndToltip")} ${Number(i)}`}return`${n}: ${r}`}return n}getLabelFromCheckedOptions(t,i,e){const s=t.length;return 0===s?`${i}`:s>1?e?`${i}: ${t.map((t=>t.label)).join(",")}`:`${i}: ${s} ${this.getMessage("snkFilterBar.multiListToltip")}`:`${i}: ${t[0].label}`}calculateActiveCount(t){return t.reduce(((t,i)=>i.visible?t+1:t),0)}componentDidLoad(){this._filterItemElement&&(o.addIDInfo(this._filterItemElement),this._idSnkFilterDetail=`filterDetail_${this.config.id}`),this.controlScrollPage()}componentDidRender(){null==this._floatingID&&this._popover&&this._popover.remove()}filterChangeListener(){this.hideDetail()}canClearFilter(){const{value:t,groupedItems:i=[]}=this.config;return null!=t&&this.config.type===h.MULTI_LIST?t.some((t=>t.check)):void 0!==t||i.some((t=>t.visible))}getRightIconName(){return this.canClearFilter()?"close":this.detailIsVisible?"chevron-up":"chevron-down"}getLeftIconName(){switch(this.config.type){case h.PERIOD:return"calendar";case h.PERSONALIZED:return"tune"}}hasActiveElements(t){var i,e,s;return(null===(s=null===(e=null!==(i=null==t?void 0:t.elements)&&void 0!==i?i:t)||void 0===e?void 0:e.filter((t=>null==t?void 0:t.check)))||void 0===s?void 0:s.length)>0}hasActiveValue(t){return t.type!==h.MULTI_LIST&&void 0!==t.value||this.hasActiveElements(t.value)}getEnabledChip(){if(this.config.type===h.PERSONALIZED){const{groupedItems:t=[]}=this.config;return t.some((t=>t.visible))}return this.hasActiveValue(this.config)}render(){const t=this.getLeftIconName();return e(s,null,e("ez-chip",{id:this.config.id,ref:t=>this._chipElement=t,label:this.getLabel(),value:this.getEnabledChip()},t?e("ez-icon",{ref:t=>this._leftIconElement=t,iconName:t,class:"ez-padding-right--small",slot:"leftIcon"}):void 0,e("ez-icon",{ref:t=>this._rightIconElement=t,iconName:this.getRightIconName(),class:"ez-padding-left--small",slot:"rightIcon",id:"removeFilter"})),e("section",{class:"ez-margin-top--small sc-snk-filter-bar snk-filter__popover-container",ref:t=>this._popoverContainer=t},e("snk-filter-detail",{config:this.config,getMessage:this.getMessage,class:"sc-snk-filter-bar snk-filter__popover ez-padding--small ez-elevation--16",ref:t=>this._popover=t,key:this.config.id,"data-element-id":this._idSnkFilterDetail})))}get _filterItemElement(){return r(this)}static get watchers(){return{detailIsVisible:["observeDetailIsVisible"]}}};export{c as snk_filter_item}
@@ -0,0 +1 @@
1
+ import{r as t,c as e,h as i,H as r,g as s}from"./p-d2d301a6.js";import{DataType as a,StringUtils as n,ObjectUtils as l,ElementIDUtils as o,ErrorException as d,ApplicationContext as h}from"@sankhyalabs/core";import{EzScrollDirection as c}from"@sankhyalabs/ezui/dist/collection/components/ez-scroller/EzScrollDirection";import{C as f}from"./p-aa95fb2c.js";import{toString as m}from"@sankhyalabs/core/dist/dataunit/metadata/DataType";import{F as u}from"./p-ff1990ad.js";import{F as p}from"./p-933c0c0b.js";import{F as b}from"./p-fa80e546.js";import{ApplicationUtils as v}from"@sankhyalabs/ezui/dist/collection/utils";import{P as k}from"./p-057fad05.js";import"./p-0d7863ed.js";import"./p-9695f78b.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";function g(t){let e="";return t.forEach(((t,i)=>{var r;e+=` ${i>0?null!==(r=t.operand)&&void 0!==r?r:"OR":""} ${t.expression}`})),e.trim()}class _{constructor({filterConfig:t,configName:e,onComplete:i,getMessage:r,disablePersonalizedFilter:s,onAddPersonalizedFilter:a,onEditPersonalizedFilter:n,onDeletePersonalizedFilter:l}){this._filterConfig=t,this._configName=e,this._onComplete=i,this._getMessage=r,this._disablePersonalizedFilter=s,this._addPersonalizedFilterFn=a,this._editPersonalizedFilterFn=n,this._onDeletePersonalizedFilter=l}applyFilters(t){this._onComplete(t),this._closeModal()}buildFilterModal(){const t=document.createElement("snk-filter-modal");return t.className="ez-size-height--full",t.filters=this._filterConfig,t.configName=this._configName,t.disablePersonalizedFilter=this._disablePersonalizedFilter,t.getMessage=this._getMessage.bind(this),t.applyFilters=this.applyFilters.bind(this),t.closeModal=()=>this._closeModal(),t.addPersonalizedFilter=()=>this._addPersonalizedFilterFn(),t.editPersonalizedFilter=t=>this._editPersonalizedFilterFn(t),t.deletePersonalizedFilter=(t,e)=>this._onDeletePersonalizedFilter(t,e),t}async showModal(){const t={content:this.buildFilterModal(),position:"left",heightMode:"full",closeOutsideClick:!1,useScrimLight:!0};this._closeModal=await v.showModal(t)}async closeModal(){this._closeModal()}}const x=class{constructor(i){t(this,i),this.configUpdated=e(this,"configUpdated",7),this._updateSequence=[],this._loadingPending=!1,this._configUpdated=!1,this._firstLoad=!0,this._pendingVariables=!1,this._customfiltersToBeUpdated=[],this._calculateSortIndex=t=>{let e=t.hardFixed?1e6:0;return t.hardFixed||(e+=t.fixed?1e5:0,e+=null==t.value?0:1e4,e+=this._updateSequence.lastIndexOf(t.id)+1),e},this._filtersComparator=(t,e)=>this._calculateSortIndex(e)-this._calculateSortIndex(t),this.dataUnit=void 0,this.configName=void 0,this.resourceID=void 0,this.filterConfig=void 0,this.messagesBuilder=void 0,this.disablePersonalizedFilter=void 0,this.allowDefault=void 0,this.scrollerLocked=!1,this.showPersonalizedFilter=!1,this.personalizedFilterId=void 0}observeFilterConfig(t,e){if(null!=e&&null==t)this._loadingPending=!0,this._configUpdated=!0;else{const i=new Map(e?e.map((t=>[t.id,t])):void 0);0===i.size&&t.length>0?(this._loadingPending=!0,this._configUpdated=!1):t.forEach((t=>{const e=i.get(t.id);if(null!=e){if(this._configUpdated=this._configUpdated||l.objectToString(e)!=l.objectToString(t),this._loadingPending=this._loadingPending||l.objectToString(e.value)!==l.objectToString(t.value),!this._loadingPending){const i=l.objectToString(e.groupedItems)!=l.objectToString(t.groupedItems);this._configUpdated=this._configUpdated||i,this._loadingPending=this._loadingPending||i}}else this._configUpdated=!0,this._loadingPending=this._loadingPending||null!=t.value}))}(this._loadingPending||this._configUpdated)&&this.configUpdated.emit(t),this.processAfterUpdateConfig()}async reload(){this.loadConfigFromStorage(!0)}async getFilterItem(t){const e=this.filterConfig.find((e=>e.id===t));return Promise.resolve(l.copy(e))}async updateFilterItem(t){return-1==this.filterConfig.findIndex((e=>e.id===t.id))?(console.warn("[SnkFilterBar.updateFilterItem] FilterItem não encontrado, o mesmo não será atualizado."),Promise.resolve()):(this._loadingPending=!0,this.updateFilter(t),Promise.resolve())}async addFilterItem(t){return this.filterConfig.findIndex((e=>e.id===t.id))>-1?(console.warn("[SnkFilterBar.addFilterItem] FilterItem já existe , o mesmo não será adicionado novamente."),Promise.resolve()):(this.filterConfig.push(t),this._loadingPending=!0,this.updateFilter(t),Promise.resolve())}async removeFilterItem(t){const e=this.filterConfig.findIndex((e=>e.id===t));if(-1==e)return console.warn("[SnkFilterBar.removeFilterItem] FilterItem não encontrado"),Promise.resolve(void 0);const i=this.filterConfig[e];return this.filterConfig=this.filterConfig.filter((e=>e.id!==t)),Promise.resolve(i)}componentDidLoad(){this._element&&o.addIDInfo(this._element,null,{dataUnit:this.dataUnit})}processPendingFilter(){if(this._pendingVariables){const t=this._element.querySelector("#filter-PERSONALIZED_FILTER_GROUP");t&&t.showUp(!0).then((()=>{this.processAfterUpdateConfig()}))}else this.processAfterUpdateConfig()}getPersonalizedFilterItem(){return this.filterConfig.find((t=>t.type===u.PERSONALIZED))}async processAfterUpdateConfig(){if(this._loadingPending){if(await this._application.isLoadedByPk()&&!this._configUpdated)return;const t=this.getPersonalizedFilterItem();if(this._pendingVariables=!k.validateVariableValues(t),this._pendingVariables)return;this._loadingPending=!1,this.doLoadData(null!=this.dataUnit.getLastLoadRequest())}this._configUpdated&&(this._configUpdated=!1,f.saveFilterBarConfig(this.filterConfig,this.configName,this.resourceID))}async doLoadData(t=!1){try{if(this._firstLoad&&!t&&!await this._application.getBooleanParam("global.carregar.registros.iniciar.tela"))return;this.dataUnit.loadData(void 0,void 0,!0)}finally{this._firstLoad=!1}}getMessage(t,e,i){var r;return null==this.messagesBuilder&&this._application&&(this.messagesBuilder=this._application.messagesBuilder),(null===(r=this.messagesBuilder)||void 0===r?void 0:r.getMessage(t,e))||i}getFilter(t){var e;const i=[];return null===(e=this.filterConfig)||void 0===e||e.filter((t=>this.isActiveFilter(t))).forEach((t=>{const e=(t=>{switch(t.type){case u.DEFAULT_FILTER:return function(t){return{name:t.id,expression:t.props.expression,params:[]}}(t);case u.BINARY_SELECT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.options.find((t=>t.name===i)).expression,params:[]}}(t);case u.MULTI_SELECT:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:a.TEXT,value:i}]}}(t);case u.MULTI_LIST:return function(t){const{id:e,value:i,props:r}=t,s=(null!==(o=null!==(l=null==(n=i)?void 0:n.elements)&&void 0!==l?l:null==n?void 0:n.members)&&void 0!==o?o:n).filter((t=>null==t?void 0:t.check)).map((({id:t})=>Number.isNaN(+t)?String(t):Number(t)));var n,l,o;if(s.length>0)return{name:e,expression:r.expression,params:[{name:e,dataType:a.TEXT,value:JSON.stringify(s)}]}}(t);case u.PERIOD:return function(t){const{id:e,value:i,props:r}=t;let{end:s,start:n}=i;"string"==typeof s&&(s=new Date(s)),"string"==typeof n&&(n=new Date(n));const l=[];let o;return s&&n?(o=r.expression.fullfill,l.push({name:`${e}.START`,dataType:a.DATE,value:m(a.DATE,n)},{name:`${e}.END`,dataType:a.DATE,value:m(a.DATE,s)})):n?(o=r.expression.onlystart,l.push({name:e,dataType:a.DATE,value:m(a.DATE,n)})):(o=r.expression.onlyend,l.push({name:e,dataType:a.DATE,value:m(a.DATE,s)})),{name:e,expression:o,params:l}}(t);case u.SEARCH:return function(t){const{id:e,value:i,props:r}=t;return{name:e,expression:r.expression,params:[{name:e,dataType:a.TEXT,value:m(a.TEXT,i.value)}]}}(t);case u.TEXT:return function(t){let{id:e,value:i,props:r}=t;const s=r.expression;var l,o;return n.isEmpty(r.likeAs)||(l=i,i="CONTANIS"===(o=r.likeAs)?`%${l}%`:"STARTS_WITH"===o?`${l}%`:"ENDS_WITH"===o?`%${l}`:l),{name:e,expression:s,params:[{name:e,dataType:a.TEXT,value:m(a.TEXT,i)}]}}(t);case u.NUMBER:return function(t){const{id:e,value:i,props:r}=t;if(r.variation===b.INTERVAL){const{start:t,end:s}=null!=i?i:{start:0,end:0};if(t&&s)return{name:e,expression:r.intervalExpression.fullfill,params:[{name:`${e}.START`,dataType:a.NUMBER,value:m(a.NUMBER,t)},{name:`${e}.END`,dataType:a.NUMBER,value:m(a.NUMBER,s)}]};if(t)return{name:e,expression:r.intervalExpression.onlystart,params:[{name:e,dataType:a.NUMBER,value:m(a.NUMBER,t)}]};if(s)return{name:e,expression:r.intervalExpression.onlyend,params:[{name:e,dataType:a.NUMBER,value:m(a.NUMBER,s)}]}}return{name:e,expression:r.expression,params:[{name:e,dataType:a.NUMBER,value:m(a.NUMBER,i)}]}}(t);case u.PERSONALIZED:return function(t){const{id:e,groupedItems:i=[]}=t,r=i.filter((t=>!!t.visible)).map((t=>{var e;const i=t.props.expression,r=((null===(e=t.props.personalizedFilter)||void 0===e?void 0:e.parameters)||[]).map(((e,i)=>{const r=Array.from(t.value||0),s=e.dataType;let n=i>=0&&i<r.length?r[i]:null;return null!=n&&"object"==typeof n&&"value"in n&&(n=n.value),null==n&&s===a.BOOLEAN&&(n=!1),{name:e.name,dataType:s,value:"string"==typeof n?n:m(s,n)}}));return{expression:i,name:t.id,params:r}}));return{name:e,expression:r.map((t=>`(${t.expression})`)).join(` ${p.AND} `),params:r.flatMap((t=>t.params))}}(t);case u.CHECK_BOX_LIST:return function(t){var e;const{id:i,value:r,props:s}=t,a=Object.entries(null!=r?r:{}).filter((([t,e])=>!0===e)).map((([t,e])=>t));return{name:i,expression:g(null===(e=s.options)||void 0===e?void 0:e.filter((t=>a.includes(t.name)))),params:[]}}(t);default:return}})(t);e&&i.push(e)})),i}isActiveFilter(t){return t.type===u.DEFAULT_FILTER||this.filterActiveFilter(t)&&(t.groupedItems||null!=t.value)}registryFilterProvider(){this.dataUnit.addFilterProvider(this),this.filterConfig&&this.doLoadData()}itemFocused(t){this._element.querySelectorAll("snk-filter-item,snk-filter-list").forEach((e=>{e.id===t?"snk-filter-item"===e.tagName.toLowerCase()&&e.getClientRects()[0].x<0&&e.scrollIntoView({behavior:"auto",inline:"nearest"}):e.hideDetail()}))}filterActiveFilter(t){return t.visible||t.removalBlocked}getFilterItems(){const t=[],e=[];this.filterConfig.filter(this.filterActiveFilter).forEach(((r,s)=>{const a=`filter-${(r=l.copy(r)).id}`,n=i("snk-filter-item",{onVisibleChanged:t=>this.scrollerLocked=t.detail,onFilterChange:t=>this.updateFilter(t.detail),onFocusin:()=>this.itemFocused(a),id:a,config:r,class:s>0?"ez-padding-left--medium":"",getMessage:(t,e)=>this.getMessage(t,e),key:r.id});return r.fixed||r.hardFixed?t.push(n):e.push(n),n}));const r=[];return r.push(...t),t.length>0&&e.length>0&&r.push(i("hr",{class:"ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-filter-bar__divider"})),r.push(...e),r}calculateUpdateSequence(t){t&&(this._updateSequence=this._updateSequence.filter((e=>t.id!==e)),this._updateSequence.push(t.id))}normalizeItem(t){const e=Object.assign({},t);return["props","value","hardFixed","fixed"].forEach((t=>{null==e[t]&&delete e[t]})),""===t.value&&delete t.value,e}updateFilter(t){this.filterConfig=this.filterConfig.map((e=>(t=this.normalizeItem(t),e.id===t.id?(l.objectToString(e)!=l.objectToString(t)&&this.calculateUpdateSequence(t),t):e))).sort(((t,e)=>this._filtersComparator(t,e)))}loadPermitions(){this._application.isUserSup().then((t=>this.allowDefault=t))}async loadConfigFromStorage(t){return t&&await f.deleteFilterBarConfigCache(this.configName,this.resourceID),new Promise((t=>{f.loadFilterBarConfig(this.configName,this.resourceID,{contextURI:this.dataUnit.name}).then((e=>{t(),this.filterConfig=e.map((t=>this.normalizeItem(t)))})).catch((t=>{throw new d(this.getMessage("snkFilterBar.failToLoadConfig"),t)}))}))}attachDataUnit(){if(null==this.dataUnit){let t=this._element.parentElement;for(;t;)if("SNK-DATA-UNIT"===t.tagName.toUpperCase()){const e=t;this.dataUnit=e.dataUnit,this.dataUnit?this.registryFilterProvider():e.addEventListener("dataUnitReady",(t=>{this.dataUnit=t.detail,this.registryFilterProvider()}));break}t=t.parentElement}else this.registryFilterProvider()}filterChangeListener(t){this.updateFilter(t.detail)}async showFilterModal(){let t=l.copy(this.filterConfig);t=t.sort(((t,e)=>t.originOrder-e.originOrder)),this._filterModalFactory=new _({filterConfig:t,configName:this.configName,onComplete:t=>{this.filterConfig=t.map(this.normalizeItem).sort(((t,e)=>this._filtersComparator(t,e)))},disablePersonalizedFilter:this.disablePersonalizedFilter,getMessage:(t,e)=>this.getMessage(t,e),onAddPersonalizedFilter:()=>this.addPersonalizedFilter(),onEditPersonalizedFilter:t=>this.editPersonalizedFilter(t),onDeletePersonalizedFilter:(t,e)=>this.deletePersonalizedFilter(t,u.PERSONALIZED,e)}),await this._filterModalFactory.showModal()}addPersonalizedFilter(){this._filterModalFactory.closeModal(),this.personalizedFilterId=void 0,this.showPersonalizedFilter=!0,window.requestAnimationFrame((()=>{this._elPersonalizedFilter.createPersonalizedFilter()}))}editPersonalizedFilter(t){this._filterModalFactory.closeModal(),this.showPersonalizedFilter=!0,this.personalizedFilterId=t}deletePersonalizedFilter(t,e,i){e===u.PERSONALIZED&&f.removePersonalizedFilter(t,this.resourceID,i)}handleHidePersonalizedFilter(t){t?this.loadConfigFromStorage().then((()=>{this.hidePersonalizedFilter()})):this.hidePersonalizedFilter()}hidePersonalizedFilter(){this.personalizedFilterId=void 0,this.showPersonalizedFilter=!1}componentWillLoad(){this._application=h.getContextValue("__SNK__APPLICATION__"),this._application&&(this.loadPermitions(),this.loadConfigFromStorage()),this.attachDataUnit()}componentDidRender(){this.processPendingFilter()}render(){if(this.dataUnit&&this.filterConfig&&0!==this.filterConfig.length)return this.showPersonalizedFilter?i("snk-personalized-filter",{class:"filter-bar__personalized-filter",filterId:this.personalizedFilterId,ref:t=>this._elPersonalizedFilter=t,onEzCancel:()=>this.handleHidePersonalizedFilter(!1),onEzAfterSave:()=>this.handleHidePersonalizedFilter(!0),entityUri:this.dataUnit.name,configName:this.configName,resourceID:this.resourceID}):i(r,null,i("ez-scroller",{class:"snk-filter-bar__scroller",direction:c.HORIZONTAL,activeShadow:!0,locked:this.scrollerLocked},i("section",{class:"snk-filter-bar__filter-item-container"},this.getFilterItems())),i("ez-button",{class:"ez-padding-left--medium",size:"small",label:this.getMessage("snkFilterBar.filters",void 0,"Filtros"),onClick:this.showFilterModal.bind(this)},i("ez-icon",{slot:"leftIcon",iconName:"plus",class:"ez-padding-right--small"})))}get _element(){return s(this)}static get watchers(){return{filterConfig:["observeFilterConfig"]}}};x.style='.sc-snk-filter-bar-h{display:grid;grid-template-columns:minmax(100px, 100%) 1fr 1fr;--snk-personalized-filter--z-index:var(--elevation--20, 20);--snk-personalized-filter--background-color:var(--background--xlight, #fff)}.snk-filter__popover-container.sc-snk-filter-bar{display:flex;cursor:auto}.filter-bar__personalized-filter.sc-snk-filter-bar{display:flex;flex-direction:column;position:fixed;top:0;left:0;width:100%;height:100%;overflow:auto;z-index:var(--snk-personalized-filter--z-index);background-color:var(--snk-personalized-filter--background-color)}.snk-filter__popover.sc-snk-filter-bar{display:flex;flex-direction:column;position:absolute;width:fit-content;height:fit-content;min-width:265px;background-color:var(--background--xlight, #fff);border-radius:var(--border--radius-medium, 12px);box-shadow:var(--shadow, 0px 0px 16px 0px #000)}.snk-filter-item__editor-header.sc-snk-filter-bar{flex-grow:1;font-weight:var(--text-weight--medium, 400);color:var(--color--title-primary, #2B3A54)}.snk-filter__popover-rule.sc-snk-filter-bar{border-style:solid;border-color:var(--color--disable-secondary, #F2F5F8);border-radius:1px;border-width:1px;width:100%}.editor__ez-check.sc-snk-filter-bar{--ez-check__label--padding-left:0}.snk-filter-item__editor-header-button.sc-snk-filter-bar{cursor:pointer;background-color:transparent;border:none;padding:3px;outline-color:var(--color--primary)}.snk-filter-bar__divider.sc-snk-filter-bar{margin-bottom:var(--space--small)}.snk-filter-bar__scroller.sc-snk-filter-bar{height:calc(100% + var(--space-extra-small, 3px))}.snk-filter-bar__filter-item-container.sc-snk-filter-bar{display:flex;align-self:center}.snk-filter-bar__scroller.sc-snk-filter-bar .sc-snk-filter-bar:first-child{margin-left:var(--space-extra-small, 3px)}.snk-filter-bar__filter-list-items-container.sc-snk-filter-bar{overflow-y:auto;max-height:360px;margin-top:var(--space--small, 6px)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar{cursor:pointer;border-radius:var(--border--radius-small, 6px);border:none;background-color:transparent}.snk-filter-bar__filter-list-item__label.sc-snk-filter-bar{color:var(--title--primary)}.snk-filter-bar__filter-list-item__label--secondary.sc-snk-filter-bar{color:var(--text--primary)}.snk-filter-bar__filter-list-item__icon.sc-snk-filter-bar{--ez-icon--color:var(--title--primary)}.snk-filter-bar__filter-list-item__icon--secondary.sc-snk-filter-bar{--ez-icon--color:var(--text--secondary)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:focus-visible{outline:none;background-color:var(--background--medium)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:hover{background-color:var(--background--medium)}.snk-filter-bar__filter-list-items-container--empty.sc-snk-filter-bar{width:100%;height:100px;display:flex;justify-content:center;align-self:center;align-items:center}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar{position:relative}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar::after{display:flex;position:absolute;content:"";width:8px;height:8px;top:7px;left:17px;background-color:var(--icon--alert--color, #008561);border-radius:50%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar{--modal-item-border-width:2px;display:flex;flex-direction:row;margin-left:var(--modal-item-border-width);border-radius:var(--border--radius-medium, 12px);background-color:var(--background--medium, #f0f3f7);border:none;width:100%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar:focus-visible{outline:var(--color--primary) solid var(--modal-item-border-width)}.snk-filter-bar__filter-modal-item__check.sc-snk-filter-bar{width:auto}.snk-filter-bar__filter-modal-item__label.sc-snk-filter-bar{font-weight:var(--text-weight--medium)}.snk-filter-bar__filter-modal-content.sc-snk-filter-bar{display:grid;grid-template-rows:auto auto 1fr auto;width:99%;height:100%}';export{x as snk_filter_bar}
@@ -0,0 +1 @@
1
+ import{r as i,c as t,h as s,g as e}from"./p-d2d301a6.js";import{ObjectUtils as a,ApplicationContext as n,DataType as o,UserInterface as r,StringUtils as l,JSUtils as d,FloatingManager as h}from"@sankhyalabs/core";import{d as u,S as c}from"./p-b0ef4383.js";import{T as m}from"./p-374d03f6.js";import"./p-9695f78b.js";import{I as p}from"./p-3b0e4e08.js";import{P as v}from"./p-38289a55.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-c22c1d8e.js";import"./p-ff1990ad.js";import"./p-0d7863ed.js";import{T as k,b,o as g}from"./p-c2495304.js";import{S as f}from"./p-094c30cb.js";import"./p-6dc031de.js";import"./p-8d884fab.js";import"./p-688dcb4c.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource";const S=class{constructor(s){i(this,s),this.dataStateChange=t(this,"dataStateChange",3),this.dataUnitReady=t(this,"dataUnitReady",3),this.actionClick=t(this,"actionClick",7),this.formItemsReady=t(this,"formItemsReady",7),this.REGULAR_DEFAULT_BTNS=["INSERT","REFRESH","PREVIOUS","NEXT","DIVIDER","MORE_OPTIONS"],this.REGULAR_SELECTED_BTNS=["INSERT","REFRESH","PREVIOUS","NEXT","DIVIDER","CLONE","REMOVE","DIVIDER","MORE_OPTIONS"],this._multiSelectionListDataSource=new f,this._keyDownHandler=i=>this.keyDownListener(i),this._taskbarProcessor=new k({"snkSimpleCrudTaskbar.form_regular":this.resolveInMemoryBtns(this.REGULAR_DEFAULT_BTNS).concat(m.GRID_MODE),"snkSimpleCrudTaskbar.grid_regular":this.resolveInMemoryBtns(this.REGULAR_DEFAULT_BTNS).concat(m.FORM_MODE),"snkSimpleCrudTaskbar.form_selected":this.resolveInMemoryBtns(this.REGULAR_SELECTED_BTNS).concat(m.GRID_MODE),"snkSimpleCrudTaskbar.grid_selected":this.resolveInMemoryBtns(this.REGULAR_SELECTED_BTNS).concat(m.FORM_MODE),"snkSimpleCrudTaskbar.finish_edition":["CANCEL","SAVE"]}),this._currentViewMode=u.GRID,this._config=void 0,this._fieldToGetFocus=void 0,this.dataState=void 0,this.dataUnit=void 0,this.mode=c.SERVER,this.gridConfig=void 0,this.formConfig=void 0,this._formFields=[],this.multipleSelection=void 0,this.useCancelConfirm=!0,this.taskbarManager=void 0,this.messagesBuilder=void 0,this.useEnterLikeTab=!1,this.actionsList=void 0,this.configName=void 0}resolveInMemoryBtns(i){const t=[...i];return this.mode===c.IN_MEMORY&&t.splice(1,1),t}async goToView(i){this._currentViewMode=i,this._viewStack&&this._viewStack.show(i)}actionClickListener(i){const t=i.detail;t===m.GRID_MODE?this.goToView(u.GRID):t===m.FORM_MODE&&this.goToView(u.FORM),i.stopPropagation()}onModeChange(){this.mode==c.IN_MEMORY&&this.initInMemoryDataUnit()}observeDataState(i,t){a.objectToString(t)!=a.objectToString(i)&&this.dataStateChange.emit(i)}componentWillRender(){this._taskbarProcessor.process(this.getTaskBarId(),this.taskbarManager,this.dataState,this.getTaskBarDisabledButtons())}componentWillLoad(){this.processMetadata(),this.onModeChange(),this.configDatasource()}configDatasource(){const i=n.getContextValue("__SNK__APPLICATION__");this._multiSelectionListDataSource.setApplication(i),this._multiSelectionListDataSource.setDataUnit(this.dataUnit)}getTaskBarId(){var i,t,s;return(null===(i=this.dataState)||void 0===i?void 0:i.isDirty)?"snkSimpleCrudTaskbar.finish_edition":(null===(t=this.dataState)||void 0===t?void 0:t.selectionInfo)&&!this.dataState.selectionInfo.isAllRecords()&&(null===(s=this.dataState.selectionInfo.records)||void 0===s?void 0:s.length)>0?this._currentViewMode===u.GRID?"snkSimpleCrudTaskbar.grid_selected":"snkSimpleCrudTaskbar.form_selected":this._currentViewMode===u.GRID?"snkSimpleCrudTaskbar.grid_regular":"snkSimpleCrudTaskbar.form_regular"}initInMemoryDataUnit(){this._inMemoryLoader=new p(this._metadata),this.dataUnit=this._inMemoryLoader.dataUnit,this.dataUnitReady.emit(this.dataUnit)}setMetadata(i){return this._inMemoryLoader?this._inMemoryLoader.metadata=i:this.dataUnit&&(this.dataUnit.metadata=i),Promise.resolve()}setRecords(i){return this._inMemoryLoader?this._inMemoryLoader.records=i:this.dataUnit&&(this.dataUnit.records=i),Promise.resolve()}getRecords(){return Promise.resolve(this.dataUnit.records)}processMetadata(){const i=this._element.querySelectorAll("snk-field-metadata"),t=[],s={fields:[],emptyConfig:!1};i.forEach((i=>{const e={name:i.getAttribute("name")||i.getAttribute("label"),label:i.getAttribute("label"),dataType:o[i.getAttribute("dataType")]||o.TEXT,userInterface:r[i.getAttribute("userInterface")]||r.SHORTTEXT,readOnly:"true"==i.getAttribute("readOnly"),required:"true"==i.getAttribute("required"),tab:i.getAttribute("tab")||void 0,visible:"false"!=i.getAttribute("visible")};s.fields.push({name:e.name,tab:e.tab,visible:e.visible}),t.push(e)})),t.length>0&&(this.formConfig||(this.formConfig=s),this._metadata={name:"SimpleCrud",label:"SimpleCrud",fields:t})}onDataStateChange(i){this.dataState=Object.assign({},i.detail)}getTaskBarDisabledButtons(){var i,t,s,e;const a=[];return(null===(i=this.dataState)||void 0===i?void 0:i.hasNext)||a.push(m.NEXT),(null===(t=this.dataState)||void 0===t?void 0:t.hasPrevious)||a.push(m.PREVIOUS),(null===(e=null===(s=this.dataState)||void 0===s?void 0:s.selectionInfo)||void 0===e?void 0:e.isEmpty())&&a.push(m.FORM_MODE),a}handleCancelEdit(){var i;(null===(i=this.dataState)||void 0===i?void 0:i.recordsIsEmpty)&&(this.goToView(u.GRID),this.dataUnit.clearSelection())}getColumnSearch(i,t){return null!=this._columnSearch||(this._moreOptions=i,this._columnSearch=b(t,(({argument:i})=>new Promise((t=>{this._grid.filterColumns(i).then((i=>{t(i.filter((i=>!i.hidden)).map((i=>({label:i.label,value:i.name}))))}))}))),(t=>{var s;null!=t&&(this._grid.locateColumn(t.value),null===(s=i.hideActions)||void 0===s||s.call(i))}))),this._columnSearch}onSelectField(i,t){null!=i&&(this._fieldToGetFocus=i.value,t.hideActions())}getFieldSearch(i,t){return null!=this._fieldSearch||(this._moreOptions=i,i.addEventListener("ezPopoverOpen",(()=>this.findField())),this._fieldSearch=b(t,(({argument:i})=>this.fieldsOptionLoader(i)),(t=>this.onSelectField(t,i)))),this._fieldSearch}getFormFields(){var i,t;return null!==(t=null===(i=this.formConfig)||void 0===i?void 0:i.fields)&&void 0!==t?t:this._formFields}handleFormSetFields(i){this._formFields=null!=i?i:[]}fieldsOptionLoader(i){const t=null==i?void 0:i.toLowerCase(),s=this.getFormFields().map((i=>{var t;return null===(t=this.dataUnit)||void 0===t?void 0:t.getField(i.name)})).filter((i=>{var s,e;return(null===(s=i.name)||void 0===s?void 0:s.toLowerCase().includes(t))||(null===(e=i.label)||void 0===e?void 0:e.toLowerCase().includes(t))})).map((i=>({value:i.name,label:i.label})));return Promise.resolve(s)}getActionsList(){var i,t;const s=[{value:l.generateUUID(),label:null!==(t=null===(i=this.messagesBuilder)||void 0===i?void 0:i.getMessage("snkSimpleCrud.findColumn",void 0))&&void 0!==t?t:"Buscar",disableCloseOnSelect:!0,eagerInitialize:!0,itemBuilder:(i,t)=>this._currentViewMode===u.GRID?this.getColumnSearch(i,t):this.getFieldSearch(i,t)}];if(null!=this.taskbarManager&&null!=this.taskbarManager.getMoreOptions){const i=this.getTopTaskBarId();return s.concat(this.taskbarManager.getMoreOptions(i,this.configName,this.dataState,this.actionsList))}return s.concat(this.actionsList)}getTopTaskBarId(){var i;return(null===(i=this.dataState)||void 0===i?void 0:i.isDirty)?`snkGridTopTaskbar.finish_edition${v.PRIMARY}`:`snkGridTopTaskbar.regular${v.PRIMARY}`}async keyDownListener(i){i.ctrlKey&&null!=i.key&&"F"===i.key.toUpperCase()&&null!=this._element&&(d.isHiddenElement(this._element)||(h.closeAll(),this._currentViewMode===u.GRID?await this.findColumn():await this.findField(),i.preventDefault()))}async findField(){await this.openSeach(this._fieldSearch)}async findColumn(){await this.openSeach(this._columnSearch)}async openSeach(i){await g(this._moreOptions,i)}clearFieldToFocusHandler(){this._fieldToGetFocus=void 0}connectedCallback(){window.addEventListener("keydown",this._keyDownHandler,{capture:!0})}disconnectedCallback(){window.removeEventListener("keydown",this._keyDownHandler)}render(){var i;return s("snk-data-unit",{class:"simple-crud__container",dataUnit:this.dataUnit,useCancelConfirm:this.useCancelConfirm,onDataStateChange:i=>this.onDataStateChange(i),onCancelEdition:this.handleCancelEdit.bind(this),onInsertionMode:()=>this.goToView(u.FORM),onDataUnitReady:i=>this.dataUnitReady.emit(i.detail),ignoreSaveMessage:this._currentViewMode===u.GRID,onMessagesBuilderUpdated:i=>this.messagesBuilder=i.detail},s("header",null,s("slot",{name:"snkSimpleCrudHeader"})),s("section",{class:"ez-box ez-box--shadow simple-crud__container-section"},s("snk-taskbar",{class:"ez-box ez-box--shadow ez-padding--medium ez-margin-bottom--large",dataUnit:this.dataUnit,primaryButton:(null===(i=this.dataState)||void 0===i?void 0:i.isDirty)?"SAVE":"INSERT","data-element-id":"grid_left",messagesBuilder:this.messagesBuilder,buttons:this._taskbarProcessor.buttons,actionsList:this.getActionsList(),disabledButtons:this._taskbarProcessor.disabledButtons,customButtons:this._taskbarProcessor.customButtons,slot:"leftButtons",presentationMode:v.SECONDARY},s("slot",{name:"TASKBAR_CUSTOM_ELEMENTS"})),s("ez-view-stack",{ref:i=>this._viewStack=i,"data-element-id":"simple-crud"},s("stack-item",null,s("ez-grid",{ref:i=>this._grid=i,dataUnit:this.dataUnit,config:this.gridConfig,"no-header":!0,multipleSelection:this.multipleSelection,onEzDoubleClick:()=>this.goToView(u.FORM),columnfilterDataSource:this.dataUnit.name.includes(p.IN_MEMORY_DATA_UNIT_NAME)?void 0:this._multiSelectionListDataSource,useEnterLikeTab:this.useEnterLikeTab},s("div",{slot:"footer"},s("slot",{name:"snkSimpleCrudFooter"})))),s("stack-item",null,s("ez-form",{dataUnit:this.dataUnit,config:this.formConfig,fieldToFocus:this._fieldToGetFocus,onEzFormSetFields:i=>this.handleFormSetFields(i.detail),onEzFormRequestClearFieldToFocus:this.clearFieldToFocusHandler.bind(this)})))))}get _element(){return e(this)}static get watchers(){return{mode:["onModeChange"],dataState:["observeDataState"]}}};S.style=".sc-snk-simple-crud-h{display:flex;height:100%;width:100%}.simple-crud__container.sc-snk-simple-crud{display:grid;grid-template-rows:max-content;row-gap:12px;height:100%;width:100%}.simple-crud__container-section.sc-snk-simple-crud{flex-wrap:unset;flex-direction:column}ez-grid.sc-snk-simple-crud{--ez-grid__container--shadow:none;min-height:300px}ez-form.sc-snk-simple-crud{min-height:300px}";export{S as snk_simple_crud}
@@ -0,0 +1 @@
1
+ export{S as snk_guides_viewer}from"./p-0ec5b2e5.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"./p-573a07c5.js";import"./p-aa95fb2c.js";import"./p-0d7863ed.js";import"./p-9695f78b.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-ff1990ad.js";import"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-c2495304.js";import"./p-374d03f6.js";import"./p-38289a55.js";import"./p-6dc031de.js";import"./p-b0ef4383.js";import"./p-3b0e4e08.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"./p-c22c1d8e.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"./p-688dcb4c.js";import"./p-21749402.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";
@@ -1,11 +1,11 @@
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 a,WaitingChangeException as o,WarningException as c,ErrorException as h,KeyboardManager as u,OnboardingUtils as l,DependencyType as p,ArrayUtils as d,SearchUtils as m,ElementIDUtils as w,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-aa95fb2c.js";import{d as A,D as _,U as I}from"./p-9695f78b.js";import{A as S,a as b}from"./p-e6380c60.js";import{D as N}from"./p-bf93a748.js";import{P as D}from"./p-d9bb09b3.js";import{S as C}from"./p-ff6064e7.js";import"./p-0d7863ed.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"./p-c22c1d8e.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"./p-688dcb4c.js";class k{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const E=L;function L(t,s){const e=T();return(L=function(t){return e[t-=378]})(t,s)}function T(){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(T=function(){return t})()}!function(){const t=L,s=T();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{[E(397)](t){const s=E;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new j("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 j{constructor(t){const s=E;this.isSup=t,this[s(384)]={}}[E(378)](t,s){this[E(384)][t]=s}[E(393)](t){const s=E;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 U{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",A.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 a,WaitingChangeException as o,WarningException as c,ErrorException as h,KeyboardManager as u,OnboardingUtils as l,DependencyType as p,ArrayUtils as d,SearchUtils as m,ElementIDUtils as w,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 _}from"./p-aa95fb2c.js";import{d as g,D as A,U as I}from"./p-9695f78b.js";import{A as S,a as b}from"./p-e6380c60.js";import{D as N,P as C}from"./p-3b0e4e08.js";import{S as T}from"./p-05243555.js";import"./p-0d7863ed.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"./p-c22c1d8e.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";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 E=L;function L(t,s){const e=k();return(L=function(t){return e[t-=378]})(t,s)}function k(){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(k=function(){return t})()}!function(){const t=L,s=k();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{[E(397)](t){const s=E;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=E;this.isSup=t,this[s(384)]={}}[E(378)](t,s){this[E(384)][t]=s}[E(393)](t){const s=E;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",g.gql`query($name: String!) {
2
2
  $queryAlias$: fetchResource(name: $name){
3
3
  name
4
4
  resource
5
5
  }
6
- }`)}async getParam(t){const s=`param://application?params=${t}`;return _.get().callGraphQL({values:{name:s},query:this.templateByQuery.get("fetchParam")})}async asString(t){const s=await this.getParam(t);return this.getValue(s)}async asInteger(t){const s=await this.getParam(t);return parseInt(this.getValue(s))}async asFloat(t){const s=await this.getParam(t);return parseFloat(this.getValue(s))}async asBoolean(t){const s=await this.getParam(t);return"S"===this.getValue(s)}async asDate(t){const s=await this.getParam(t);return n.strToDate(this.getValue(s))}async getBatchParams(t){const s=await this.getParam(t.join(",")),e={};return s.forEach((t=>e[t.name]=t.resource)),e}getValue(t={}){if(Array.isArray(t)&&t.length>0&&(t=t[0]),r.isEmpty(t.resource))return"";try{const s=a.stringToObject(t.resource),[e]=Object.keys(s);return s[e]}catch(t){console.warn("Erro ao converter string JSON.")}}}class M{constructor(){this.templateByQuery=new Map,this.cancel=[],this.buildTemplates()}buildTemplates(){this.templateByQuery.set("fetchTotals",A.gql`query($filters: [InputFilter!] $name: String!) {
6
+ }`)}async getParam(t){if(this._embeddedParams.has(t))return Promise.resolve(this._embeddedParams.get(t));const s=`param://application?params=${t}`;return A.get().callGraphQL({values:{name:s},query:this.templateByQuery.get("fetchParam")})}async asString(t){const s=await this.getParam(t);return this.getValue(s)}async asInteger(t){const s=await this.getParam(t);return parseInt(this.getValue(s))}async asFloat(t){const s=await this.getParam(t);return parseFloat(this.getValue(s))}async asBoolean(t){const s=await this.getParam(t);return"S"===this.getValue(s)}async asDate(t){const s=await this.getParam(t);return n.strToDate(this.getValue(s))}async getBatchParams(t){const s=await this.getParam(t.join(",")),e={};return s.forEach((t=>e[t.name]=t.resource)),e}getValue(t={}){if(Array.isArray(t)&&t.length>0&&(t=t[0]),"string"==typeof t)return t;if(r.isEmpty(t.resource))return"";try{const s=a.stringToObject(t.resource),[e]=Object.keys(s);return s[e]}catch(t){console.warn("Erro ao converter string JSON.")}}}class F{constructor(){this.templateByQuery=new Map,this.cancel=[],this.buildTemplates()}buildTemplates(){this.templateByQuery.set("fetchTotals",g.gql`query($filters: [InputFilter!] $name: String!) {
7
7
  $queryAlias$: fetchTotals(name: $name, filters: $filters ){
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)=>{_.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 F(){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(F=function(){return t})()}const $=R;function R(t,s){const e=F();return(R=function(t){return e[t-=392]})(t,s)}!function(){const t=R,s=F();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 q=$(396);var z;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===(z=window.workspace)||void 0===z?void 0:z.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 o||(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 o||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 "${a.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 u,this._waitingAppReady=new Array,this._duCache=new Map,this._duPromises=new Map,this._requestListener=new V,this._pendingActions=new Map,this._isLoadedByPk=!1,this.messagesBuilder=void 0,this.configName=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 U),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 H(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)}))}))}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 _.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){l.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){this.clearContent(this._popUp),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=s,this._popUp.useHeader=e,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}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)=>{_.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)=>{_.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=>{k.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,a)=>{const o=this.getDuPromissesStack(s),c=o.length>0;if(o.push(new H(r,a)),!c){const r=this.dataUnitFetcher.getDataUnit(t,n,e,i);r.loadMetadata().then((()=>{for(s&&this.updateDataunitCache(void 0,s,r);o.length>0;)o.pop().resolve(r)})).catch((t=>{for(;o.length>0;)o.pop().reject(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,a)=>{const o=this._duCache.get(s);o?r(o):this.createDataunit(t,s,e,i,n).then((t=>{r(t)})).catch((t=>a(t)))}))}async addClientEvent(t,s){return new Promise((e=>{_.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{_.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(_.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 M),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new D),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new b),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:a,DESCRIPTIONFIELD:o,ROOTENTITY:c,DESCRIPTIONENTITY:h}=i.properties,u=i.dependencies;let l;const d={rootEntity:c,descriptionFieldName:o,codeFieldName:a,showInactives:!1,dataUnitId:e.dataUnitId};return null==u||u.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===p.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(l={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:l,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 a;return{value:r.highlightValue(t,s.__matchFields,null===(a=s[n])||void 0===a?void 0:a.toString(),e,!0),label:i?r.highlightValue(t,s.__matchFields,s[i],e,!0):"",details:m.buildDetails(t,e,s)}}async executePreparedSearch(t,s,e){const i={},{entity:n,entityDescription:r,criteria:o,searchOptions:c}=e;return new Promise("ADVANCED"===t?t=>{const e=document.createElement("snk-pesquisa");e[w.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,e.argument=s,e.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,o,c),e.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(e)}:(t,e)=>{this.pesquisaFetcher.loadAdvancedSearch(n,s,o,c).then((e=>{let n=(e=a.stringToObject(e.json.$)).descriptionField,r=e.pkField;const o=[];e.data.forEach((t=>{let a=this.filterInvalidFields(e,t,i),c=this.filterMathFields(t.__matchFields,a,6,i);o.push(this.builOptionItem(s,t,c,n,r))})),t(o)})).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(_.get())}async whenApplicationReady(){return y.getContextValue("__SNK__APPLICATION__LOADING__")?Promise.resolve(this):new Promise((t=>{this._waitingAppReady.push((()=>t(this)))}))}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);if(null==e||s!==this.applicationResourceID)return;const i={pk:e};if(this._isLoadedByPk=!0,this.loadByPK)return this.loadByPK(i),void(this._currentPkParameter=t);this.defaultLoadByPK(i,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 C,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__",q),this.registerPkChangeListener(),P.init(),g.preload(this.applicationResourceID,this.configName),document.addEventListener("click",(()=>x.applicationClick())),this._waitingAppReady.forEach((t=>t()))}connectedCallback(){y.setContextValue("__SNK__APPLICATION__",this),_.addRequestListener(this._requestListener)}disconnectedCallback(){_.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()})),w.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)}};class V{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 H{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 R(t,s){const e=M();return(R=function(t){return e[t-=392]})(t,s)}!function(){const t=R,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 q=$(396);var z;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===(z=window.workspace)||void 0===z?void 0:z.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 o||(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 o||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 "${a.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 u,this._waitingAppReady=new Array,this._duCache=new Map,this._duPromises=new Map,this._requestListener=new V,this._pendingActions=new Map,this._isLoadedByPk=!1,this.messagesBuilder=void 0,this.configName=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 H(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)}))}))}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){l.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){this.clearContent(this._popUp),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=s,this._popUp.useHeader=e,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}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,a)=>{const o=this.getDuPromissesStack(s),c=o.length>0;if(o.push(new H(r,a)),!c){const r=this.dataUnitFetcher.getDataUnit(t,n,e,i);r.loadMetadata().then((()=>{for(s&&this.updateDataunitCache(void 0,s,r);o.length>0;)o.pop().resolve(r)})).catch((t=>{for(;o.length>0;)o.pop().reject(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,a)=>{const o=this._duCache.get(s);o?r(o):this.createDataunit(t,s,e,i,n).then((t=>{r(t)})).catch((t=>a(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 C),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new b),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:a,DESCRIPTIONFIELD:o,ROOTENTITY:c,DESCRIPTIONENTITY:h}=i.properties,u=i.dependencies;let l;const d={rootEntity:c,descriptionFieldName:o,codeFieldName:a,showInactives:!1,dataUnitId:e.dataUnitId};return null==u||u.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===p.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(l={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:l,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 a;return{value:r.highlightValue(t,s.__matchFields,null===(a=s[n])||void 0===a?void 0:a.toString(),e,!0),label:i?r.highlightValue(t,s.__matchFields,s[i],e,!0):"",details:m.buildDetails(t,e,s)}}async executePreparedSearch(t,s,e){const i={},{entity:n,entityDescription:r,criteria:o,searchOptions:c}=e;return new Promise("ADVANCED"===t?t=>{const e=document.createElement("snk-pesquisa");e[w.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,e.argument=s,e.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,o,c),e.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(e)}:(t,e)=>{this.pesquisaFetcher.loadAdvancedSearch(n,s,o,c).then((e=>{let n=(e=a.stringToObject(e.json.$)).descriptionField,r=e.pkField;const o=[];e.data.forEach((t=>{let a=this.filterInvalidFields(e,t,i),c=this.filterMathFields(t.__matchFields,a,6,i);o.push(this.builOptionItem(s,t,c,n,r))})),t(o)})).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);if(null==e||s!==this.applicationResourceID)return;const i={pk:e};if(this._isLoadedByPk=!0,this.loadByPK)return this.loadByPK(i),void(this._currentPkParameter=t);this.defaultLoadByPK(i,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 T,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__",q),this.registerPkChangeListener(),P.init(),_.preload(this.applicationResourceID,this.configName),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()})),w.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)}};class V{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 H{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}
@@ -0,0 +1 @@
1
+ import{r as t,c as i,f as s,h as e,H as a}from"./p-d2d301a6.js";import{Action as h}from"@sankhyalabs/core";import{S as o}from"./p-573a07c5.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-9695f78b.js";import"./p-3b0e4e08.js";import{P as d}from"./p-38289a55.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-c22c1d8e.js";import"./p-ff1990ad.js";import"./p-0d7863ed.js";import{T as l}from"./p-374d03f6.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-0ec5b2e5.js";import{S as u}from"./p-05243555.js";import"./p-aa95fb2c.js";import"./p-8d884fab.js";import"./p-688dcb4c.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"./p-6dc031de.js";import"./p-c2495304.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class p{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,h=null!=n.getDetailName(s.split("::").pop()),o=h&&e,r=this._parentGuide.id,d=h?`${r}::${s}`:`${r}__FORM:${s}`;return h&&t.has(d)&&!o?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:o,tooltip:o?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),h=a.shift();return h.label=e?"Novo Registro":s.__record__label__,h.children=a,i.children=[h],i}}const v=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}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,h=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==h?void 0:h.__record__id__)&&this.snkDetailGuidesChange.emit(new p(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const o=[];this.dataState.hasPrevious||o.push(l.PREVIOUS),this.dataState.hasNext||o.push(l.NEXT),this.dataState.insertionMode&&o.push(l.INSERT),this._disabledButtons=o}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(v.REGEX_FORM_ID,"")}loadMetadata(){var t;if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const i=this.formConfigManager.getConfig(null===(t=this.dataState)||void 0===t?void 0:t.insertionMode,this.dataUnit);this._formMetadata=r(null==i||0===i.fields.length?void 0:i,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){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 o(this._configName,this.resourceID,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async dataUnitActionHandler(t){t.type===h.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new p(this.branchGuide,this._formMetadata,this.dataUnit))}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"]}}};v.REGEX_FORM_ID=/__FORM:[^:]+/g,v.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{v as snk_detail_view}
@@ -0,0 +1 @@
1
+ import{r as t,c as s,h as i,g as e}from"./p-d2d301a6.js";import{ElementIDUtils as o}from"@sankhyalabs/core";import{F as h}from"./p-ff1990ad.js";const r=class{constructor(i){t(this,i),this.valueChanged=s(this,"valueChanged",7),this.value=void 0,this.config=void 0}ezChangeListener(t){var s;this.value=null===(s=t.detail)||void 0===s?void 0:s.value,this.valueChanged.emit(this.value)}async show(){this._comboElement.setFocus()}componentDidLoad(){this._element&&o.addIDInfo(this._element,"filterContentEditor")}render(){if(this.config&&this.config.type===h.MULTI_SELECT)return i("ez-combo-box",{id:this.config.id,ref:t=>this._comboElement=t,label:this.config.label,value:this.config.value,options:this.config.props.options})}get _element(){return e(this)}};export{r as snk_filter_multi_select}
@@ -0,0 +1 @@
1
+ export{S as snk_data_unit}from"./p-f3d1c48e.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"@sankhyalabs/ezui/dist/collection/utils";import"./p-05243555.js";
@@ -1 +1 @@
1
- import{r as s,h as e,H as i,g as t}from"./p-d2d301a6.js";import{ObjectUtils as r,StringUtils as a,ElementIDUtils as o}from"@sankhyalabs/core";const n=class{constructor(e){s(this,e),this._mdByName={},this._startHighlightTag="<span class='card-item__highlight'>",this._endHighlightTag="</span>",this._specialCharsRegex=/[[.\-\$\+\*,_\&\(\)%\/\\#@!:\|\=\'\"]/gim,this._charsWithAccentuation="ÁÉÍÓÚ_ÃÕ_ÂÊÎÔÛ_ÀÈÌÒÙ_Ü_Ç_áéíóú_ãõ_âêîôû_àèìòù_ü_ç",this._charsWithoutAccentuation="AEIOU_AO_AEIOU_AEIOU_U_C_aeiou_ao_aeiou_aeiou_u_c",this._changeDeboucingTimeout=null,this._limitCharsToSearch=3,this._deboucingTime=450,this._itemList=void 0,this._startLoading=!1,this.searchLoader=void 0,this.selectItem=void 0,this.argument=void 0}observeArgument(){this._textInput&&(this._textInput.value=this.argument)}clearSearch(){this.argument="",this._itemList=void 0}buildDetails(s,e){let i={};for(let t=0;t<s.length;t++){const r=s[t],a=e[r.fieldName];i[r.description]=this.highlightValue(e.__matchFields,r.options&&r.options[a]||a,s,!0)}return i}buildFirstFields(s,e,i=6){return s&&Array.isArray(s)&&s.forEach((s=>{let i=this.removeReference(e,this._mdByName[s]);i&&e.unshift(i)})),e=e.slice(0,i)}doSearch(s){this.searchLoader&&"function"==typeof this.searchLoader&&(this._startLoading=!0,this.searchLoader(s).then((s=>{if(this._startLoading=!1,s){let e=(s=r.stringToObject(s.json.$)).descriptionField,i=s.pkField;if(i){let t=[];s.data.forEach((r=>{var a;let o=this.filterFieldsMetadata(s,r),n=this.buildFirstFields(r.__matchFields,o),l={key:this.highlightValue(r.__matchFields,null===(a=r[i])||void 0===a?void 0:a.toString(),n,!0),title:e?this.highlightValue(r.__matchFields,r[e],n,!0):"",details:this.buildDetails(n,r)};t.push(l)})),this._itemList=t}}})).catch((s=>{this._startLoading=!1,this._itemList=[],console.warn(s)})))}filterFieldsMetadata(s,e){return s.fieldsMetadata.filter((i=>{let t=!a.isEmpty(e[i.fieldName])&&!1!==i.visible&&"B"!==i.type&&s.pkField!==i.fieldName&&s.descriptionField!==i.fieldName&&(i.isPrimaryKey||!i.isLinkField)&&!("S"===i.type&&"H"===i.presentationType);return t&&(this._mdByName[i.fieldName]=i),("string"!=typeof e[i.fieldName]||!(e[i.fieldName].indexOf("<img")>-1||e[i.fieldName].indexOf("<svg")>-1))&&t}))}removeAtIndex(s,e){if(e>=0&&e<s.length)return s.splice(e,1)[0]}removeReference(s,e){let i=this.indexOf(s,e);return this.removeAtIndex(s,i)}indexOf(s,e){let i=-1;return Array.isArray(s)&&this.find(s,((s,t)=>(i=t,this.equals(e,s)))),i}equals(s,e){return r.objectToString(s)===r.objectToString(e)}find(s,e){if(s)for(let i=0,t=s.length;i<t;i++)if(e(s[i],i,s))return s[i]}highlightValue(s,e,i,t){let r=this.replaceHtmlEntities(e);if(this.argument&&(t||this.isIn(s,i.fieldName))){const s=this.getArgumentNumber();let e=(isNaN(s)?this.argument:s.toString()).split(/%|,|\s+/),t=0,a=this.replaceAccentuatedChars(r);e.forEach((s=>{if(s){s=this.replaceAccentuatedChars(s);let e=this.getSpecialCharacters(s);null!=e&&e.length>0&&(s=this.removeSpecialCharacters(s)),(i.mask||"CGC_CPF"===i.uiType||"Phone"===i.uiType)&&(s=s.split("").join("\\.?\\-?\\/?\\(?\\)?"));let o=new RegExp(s,"ig");o.lastIndex=t;let n=o.exec(a);if(n&&n.length>0){t=n.index;let s=n[0].length,e=r.substring(t,t+s),i=(null==e?void 0:e.trim())?this._startHighlightTag+e+this._endHighlightTag:"",o=r.substring(0,t),l=r.substring(t+s);r=o+i+l,t+=i.length,a=this.replaceAccentuatedChars(r)}}}))}return r}replaceHtmlEntities(s){return null==s?s:String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}replaceAccentuatedChars(s){return null==s?s:this.replaceToSpace(s,["&amp;","&lt;","&gt;","&quot;"]).replace(/[^\w ]/g,(s=>{let e=this._charsWithAccentuation.indexOf(s);return e>-1&&(s=this._charsWithoutAccentuation.charAt(e)),s||""}))}replaceToSpace(s,e=[]){return null==s||e.forEach((e=>{const i=new RegExp(e,"g");let t="";for(let s=0;s<e.length;s++)t+=" ";s=String(s).replace(i,t)})),s}isIn(s,e){return this.indexOf(s,e)>-1}getSpecialCharacters(s){let e,i=[];for(;e=this._specialCharsRegex.exec(s);)i.push(s[e.index]);return i}removeSpecialCharacters(s){return this.getSpecialCharacters(s).forEach((e=>{s=this.replaceAll(s,e,"")})),s}replaceAll(s,e,i){let t=(null!=s?s:"").indexOf(e);for(;t>-1;)t=(s=s.replace(e,i)).indexOf(e);return s}getArgumentNumber(){return Number(this.argument||void 0)}createOption(s){let{key:e,title:i}=s;const t=new RegExp(this._startHighlightTag,"g"),r=new RegExp(this._endHighlightTag,"g");i=a.decodeHtmlEntities(i);const o={value:null==e?void 0:e.replace(t,"").replace(r,""),label:null==i?void 0:i.replace(t,"").replace(r,"")};this.selectItem(o)}onChangeValue(s){if(this.clearDeboucingTimeout(),this._startLoading)return void(this._changeDeboucingTimeout=setTimeout((()=>{this.onChangeValue(s)}),this._deboucingTime));this.argument=(s.detail||"").trim();const e=this.getArgumentNumber();this.argument&&(!isNaN(e)||this.argument.length>=this._limitCharsToSearch)?this._changeDeboucingTimeout=setTimeout((()=>{this.doSearch(isNaN(e)?this.argument:e.toString())}),this._deboucingTime):this._itemList=void 0}clearDeboucingTimeout(){this._changeDeboucingTimeout&&(clearTimeout(this._changeDeboucingTimeout),this._changeDeboucingTimeout=void 0)}onClickSearch(){this.doSearch((this.argument||"").trim())}getMessageView(){return this._startLoading?"Aguarde, buscando registros...":this._itemList?this._itemList.length>=1?`${this._itemList.length} ${this._itemList.length>1?"registros encontrados":"registro encontrado"}`:"Nenhum registro encontrado":"Os resultados de sua pesquisa aparecerão aqui..."}componentDidLoad(){o.addIDInfo(this._element)}render(){var s;return e(i,null,e("div",{class:"snk-pesquisa"},e("div",{class:"snk-pesquisa__input"},e("ez-text-input",{label:"Buscar",class:"ez-margin-right--medium",canShowError:!1,ref:s=>this._textInput=s,onEzChange:s=>this.onChangeValue(s),value:this.argument,"data-element-id":"searchInput"},e("ez-icon",{slot:"leftIcon",iconName:"search"}),this.argument&&(null===(s=this._textInput)||void 0===s?void 0:s.value)?e("button",{slot:"rightIcon",class:"snk-pesquisa__btn",onClick:()=>this.clearSearch()},e("ez-icon",{iconName:"close"})):void 0),e("ez-button",{class:"ez-button--primary",label:"Pesquisar",onClick:()=>this.onClickSearch()})),e("label",{class:"snk-pesquisa__records"},this.getMessageView()),e("div",{class:"snk-pesquisa__content"},this._itemList&&this._itemList.map((s=>e("ez-card-item",{onEzClick:s=>this.createOption(s.detail),item:s}))))))}get _element(){return t(this)}static get watchers(){return{argument:["observeArgument"]}}};n.style=".sc-snk-pesquisa-h{--snk-pesquisa--font-size:var(--text--medium, 14px);--snk-pesquisa--font-family:var(--font-pattern, Arial);--snk-pesquisa--font-weight:var(--text-weight--medium, 400);--snk-pesquisa__records--color:var(--text--primary, #626e82);--snk-pesquisa__records--padding-vertical:var(--space--medium, 12px);--snk-pesquisa__content--padding-right:var(--space--small, 6px);--snk-pesquisa__btn--color:var(--title--primary, #2B3A54);--snk-pesquisa__btn-disabled--color:var(--text--disable, #AFB6C0);--snk-pesquisa__btn-hover--color:var(--color--primary, #4e4e4e);--snk-pesquisa__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-pesquisa__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-pesquisa__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-pesquisa__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-pesquisa__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-pesquisa__scrollbar--width:var(--space--medium, 12px);max-height:100%;height:100%;display:flex;flex-direction:column;overflow-y:auto}.snk-pesquisa.sc-snk-pesquisa{display:flex;flex-direction:column;height:100%}.snk-pesquisa__input.sc-snk-pesquisa{display:flex;width:100%;box-sizing:border-box;padding-top:4px;padding-right:4px}.snk-pesquisa__input.sc-snk-pesquisa ez-icon.sc-snk-pesquisa{--ez-icon--color:inherit;font-weight:var(--text-weight--large, 600)}.snk-pesquisa__content.sc-snk-pesquisa{display:flex;flex-direction:column;height:100%;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--snk-pesquisa__scrollbar--color-clicked) var(--snk-pesquisa__scrollbar--color-background);padding-right:var(--snk-pesquisa__content--padding-right)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar{background-color:var(--snk-pesquisa__scrollbar--color-background);width:var(--snk-pesquisa__scrollbar--width);max-width:var(--snk-pesquisa__scrollbar--width);min-width:var(--snk-pesquisa__scrollbar--width)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-track{background-color:var(--snk-pesquisa__scrollbar--color-background);border-radius:var(--snk-pesquisa__scrollbar--border-radius)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb{background-color:var(--snk-pesquisa__scrollbar--color-default);border-radius:var(--snk-pesquisa__scrollbar--border-radius)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:vertical:hover,.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--snk-pesquisa__scrollbar--color-hover)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:vertical:active,.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--snk-pesquisa__scrollbar--color-clicked)}.snk-pesquisa__records.sc-snk-pesquisa{font-family:var(--snk-pesquisa--font-family);font-weight:var(--snk-pesquisa--font-weight);font-size:var(--snk-pesquisa--font-size);color:var(--snk-pesquisa__records--color);padding-bottom:var(--snk-pesquisa__records--padding-vertical);padding-top:var(--snk-pesquisa__records--padding-vertical)}.snk-pesquisa__btn.sc-snk-pesquisa{outline:none;border:none;background:none;cursor:pointer;color:var(--snk-pesquisa__btn--color)}.snk-pesquisa__btn.sc-snk-pesquisa:disabled{cursor:unset;color:var(--snk-pesquisa__btn-disabled--color)}.snk-pesquisa__btn.sc-snk-pesquisa:disabled:hover{cursor:unset;color:var(--snk-pesquisa__btn-disabled--color)}.snk-pesquisa__btn.sc-snk-pesquisa:hover{color:var(--snk-pesquisa__btn-hover--color)}";export{n as snk_pesquisa}
1
+ import{r as s,h as e,H as i,g as t}from"./p-d2d301a6.js";import{ObjectUtils as r,StringUtils as a,ElementIDUtils as o}from"@sankhyalabs/core";const n=class{constructor(e){s(this,e),this._mdByName={},this._startHighlightTag="<span class='card-item__highlight'>",this._endHighlightTag="</span>",this._specialCharsRegex=/[[.\-\$\+\*,_\&\(\)%\/\\#@!:\|\=\'\"]/gim,this._charsWithAccentuation="ÁÉÍÓÚ_ÃÕ_ÂÊÎÔÛ_ÀÈÌÒÙ_Ü_Ç_áéíóú_ãõ_âêîôû_àèìòù_ü_ç",this._charsWithoutAccentuation="AEIOU_AO_AEIOU_AEIOU_U_C_aeiou_ao_aeiou_aeiou_u_c",this._changeDeboucingTimeout=null,this._limitCharsToSearch=3,this._deboucingTime=450,this._itemList=void 0,this._startLoading=!1,this.searchLoader=void 0,this.selectItem=void 0,this.argument=void 0}observeArgument(){this._textInput&&(this._textInput.value=this.argument)}clearSearch(){this.argument="",this._itemList=void 0}buildDetails(s,e){let i={};for(let t=0;t<s.length;t++){const r=s[t],a=e[r.fieldName];i[r.description]=this.highlightValue(e.__matchFields,r.options&&r.options[a]||a,s,!0)}return i}buildFirstFields(s,e,i=6){return s&&Array.isArray(s)&&s.forEach((s=>{let i=this.removeReference(e,this._mdByName[s]);i&&e.unshift(i)})),e=e.slice(0,i)}doSearch(s){this.searchLoader&&"function"==typeof this.searchLoader&&(this._startLoading=!0,this.searchLoader(s).then((s=>{if(this._startLoading=!1,s){let e=(s=r.stringToObject(s.json.$)).descriptionField,i=s.pkField;if(i){let t=[];s.data.forEach((r=>{var a;let o=this.filterFieldsMetadata(s,r),n=this.buildFirstFields(r.__matchFields,o),l={key:this.highlightValue(r.__matchFields,null===(a=r[i])||void 0===a?void 0:a.toString(),n,!0),title:e?this.highlightValue(r.__matchFields,r[e],n,!0):"",details:this.buildDetails(n,r)};t.push(l)})),this._itemList=t}}})).catch((s=>{this._startLoading=!1,this._itemList=[],console.warn(s)})))}filterFieldsMetadata(s,e){return s.fieldsMetadata.filter((i=>{let t=!a.isEmpty(e[i.fieldName])&&!1!==i.visible&&"B"!==i.type&&s.pkField!==i.fieldName&&s.descriptionField!==i.fieldName&&(i.isPrimaryKey||!i.isLinkField)&&!("S"===i.type&&"H"===i.presentationType);return t&&(this._mdByName[i.fieldName]=i),("string"!=typeof e[i.fieldName]||!(e[i.fieldName].indexOf("<img")>-1||e[i.fieldName].indexOf("<svg")>-1))&&t}))}removeAtIndex(s,e){if(e>=0&&e<s.length)return s.splice(e,1)[0]}removeReference(s,e){let i=this.indexOf(s,e);return this.removeAtIndex(s,i)}indexOf(s,e){let i=-1;return Array.isArray(s)&&this.find(s,((s,t)=>(i=t,this.equals(e,s)))),i}equals(s,e){return r.objectToString(s)===r.objectToString(e)}find(s,e){if(s)for(let i=0,t=s.length;i<t;i++)if(e(s[i],i,s))return s[i]}highlightValue(s,e,i,t){let r=this.replaceHtmlEntities(e);if(this.argument&&(t||this.isIn(s,i.fieldName))){const s=this.getArgumentNumber();let e=(isNaN(s)?this.argument:s.toString()).split(/%|,|\s+/),t=0,a=this.replaceAccentuatedChars(r);e.forEach((s=>{if(s){s=this.replaceAccentuatedChars(s);let e=this.getSpecialCharacters(s);null!=e&&e.length>0&&(s=this.removeSpecialCharacters(s)),(i.mask||"CGC_CPF"===i.uiType||"Phone"===i.uiType)&&(s=s.split("").join("\\.?\\-?\\/?\\(?\\)?"));let o=new RegExp(s,"ig");o.lastIndex=t;let n=o.exec(a);if(n&&n.length>0){t=n.index;let s=n[0].length,e=r.substring(t,t+s),i=(null==e?void 0:e.trim())?this._startHighlightTag+e+this._endHighlightTag:"",o=r.substring(0,t),l=r.substring(t+s);r=o+i+l,t+=i.length,a=this.replaceAccentuatedChars(r)}}}))}return r}replaceHtmlEntities(s){return null==s?s:String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}replaceAccentuatedChars(s){return null==s?s:this.replaceToSpace(s,["&amp;","&lt;","&gt;","&quot;"]).replace(/[^\w ]/g,(s=>{let e=this._charsWithAccentuation.indexOf(s);return e>-1&&(s=this._charsWithoutAccentuation.charAt(e)),s||""}))}replaceToSpace(s,e=[]){return null==s||e.forEach((e=>{const i=new RegExp(e,"g");let t="";for(let s=0;s<e.length;s++)t+=" ";s=String(s).replace(i,t)})),s}isIn(s,e){return this.indexOf(s,e)>-1}getSpecialCharacters(s){let e,i=[];for(;e=this._specialCharsRegex.exec(s);)i.push(s[e.index]);return i}removeSpecialCharacters(s){return this.getSpecialCharacters(s).forEach((e=>{s=this.replaceAll(s,e,"")})),s}replaceAll(s,e,i){let t=(null!=s?s:"").indexOf(e);for(;t>-1;)t=(s=s.replace(e,i)).indexOf(e);return s}getArgumentNumber(){return Number(this.argument||void 0)}createOption(s){let{key:e,title:i}=s;const t=new RegExp(this._startHighlightTag,"g"),r=new RegExp(this._endHighlightTag,"g");i=a.decodeHtmlEntities(i);const o={value:null==e?void 0:e.replace(t,"").replace(r,""),label:null==i?void 0:i.replace(t,"").replace(r,"")};this.selectItem(o)}onChangeValue(s){if(this.clearDeboucingTimeout(),this._startLoading)return void(this._changeDeboucingTimeout=setTimeout((()=>{this.onChangeValue(s)}),this._deboucingTime));this.argument=(s.detail||"").trim();const e=this.getArgumentNumber();this.argument&&(!isNaN(e)||this.argument.length>=this._limitCharsToSearch)?this._changeDeboucingTimeout=setTimeout((()=>{this.doSearch(isNaN(e)?this.argument:e.toString())}),this._deboucingTime):this._itemList=void 0}clearDeboucingTimeout(){this._changeDeboucingTimeout&&(clearTimeout(this._changeDeboucingTimeout),this._changeDeboucingTimeout=void 0)}onClickSearch(){this.doSearch((this.argument||"").trim())}getMessageView(){return this._startLoading?"Aguarde, buscando registros...":this._itemList?this._itemList.length>=1?`${this._itemList.length} ${this._itemList.length>1?"registros encontrados":"registro encontrado"}`:"Nenhum registro encontrado":"Os resultados de sua pesquisa aparecerão aqui..."}componentDidLoad(){o.addIDInfo(this._element)}render(){var s;return e(i,null,e("div",{class:"snk-pesquisa"},e("div",{class:"snk-pesquisa__input"},e("ez-text-input",{label:"Buscar",class:"ez-margin-right--medium",canShowError:!1,ref:s=>this._textInput=s,onEzChange:s=>this.onChangeValue(s),value:this.argument,"data-element-id":"searchInput"},e("ez-icon",{slot:"leftIcon",iconName:"search"}),this.argument&&(null===(s=this._textInput)||void 0===s?void 0:s.value)?e("button",{slot:"rightIcon",class:"snk-pesquisa__btn",onClick:()=>this.clearSearch()},e("ez-icon",{iconName:"close"})):void 0),e("ez-button",{class:"ez-button--primary",label:"Pesquisar",onClick:()=>this.onClickSearch()})),e("label",{class:"snk-pesquisa__records"},this.getMessageView()),e("div",{class:"snk-pesquisa__content"},this._itemList&&this._itemList.map((s=>e("ez-card-item",{onEzClick:s=>this.createOption(s.detail),item:s}))))))}get _element(){return t(this)}static get watchers(){return{argument:["observeArgument"]}}};n.style=".sc-snk-pesquisa-h{--snk-pesquisa--font-size:var(--text--medium, 14px);--snk-pesquisa--font-family:var(--font-pattern, Arial);--snk-pesquisa--font-weight:var(--text-weight--medium, 400);--snk-pesquisa__records--color:var(--text--primary, #626e82);--snk-pesquisa__records--padding-vertical:var(--space--medium, 12px);--snk-pesquisa__content--padding-right:var(--space--small, 6px);--snk-pesquisa__btn--color:var(--title--primary, #2B3A54);--snk-pesquisa__btn-disabled--color:var(--text--disable, #AFB6C0);--snk-pesquisa__btn-hover--color:var(--color--primary, #4e4e4e);--snk-pesquisa__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-pesquisa__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-pesquisa__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-pesquisa__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-pesquisa__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-pesquisa__scrollbar--width:var(--space--medium, 12px);height:100%;display:flex;flex-direction:column;overflow-y:auto}.snk-pesquisa.sc-snk-pesquisa{display:flex;flex-direction:column;height:100%}.snk-pesquisa__input.sc-snk-pesquisa{display:flex;width:100%;box-sizing:border-box;padding-top:4px;padding-right:4px}.snk-pesquisa__input.sc-snk-pesquisa ez-icon.sc-snk-pesquisa{--ez-icon--color:inherit;font-weight:var(--text-weight--large, 600)}.snk-pesquisa__content.sc-snk-pesquisa{display:flex;flex-direction:column;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--snk-pesquisa__scrollbar--color-clicked) var(--snk-pesquisa__scrollbar--color-background);padding-right:var(--snk-pesquisa__content--padding-right)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar{background-color:var(--snk-pesquisa__scrollbar--color-background);width:var(--snk-pesquisa__scrollbar--width);max-width:var(--snk-pesquisa__scrollbar--width);min-width:var(--snk-pesquisa__scrollbar--width)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-track{background-color:var(--snk-pesquisa__scrollbar--color-background);border-radius:var(--snk-pesquisa__scrollbar--border-radius)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb{background-color:var(--snk-pesquisa__scrollbar--color-default);border-radius:var(--snk-pesquisa__scrollbar--border-radius)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:vertical:hover,.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--snk-pesquisa__scrollbar--color-hover)}.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:vertical:active,.snk-pesquisa__content.sc-snk-pesquisa::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--snk-pesquisa__scrollbar--color-clicked)}.snk-pesquisa__records.sc-snk-pesquisa{font-family:var(--snk-pesquisa--font-family);font-weight:var(--snk-pesquisa--font-weight);font-size:var(--snk-pesquisa--font-size);color:var(--snk-pesquisa__records--color);padding-bottom:var(--snk-pesquisa__records--padding-vertical);padding-top:var(--snk-pesquisa__records--padding-vertical)}.snk-pesquisa__btn.sc-snk-pesquisa{outline:none;border:none;background:none;cursor:pointer;color:var(--snk-pesquisa__btn--color)}.snk-pesquisa__btn.sc-snk-pesquisa:disabled{cursor:unset;color:var(--snk-pesquisa__btn-disabled--color)}.snk-pesquisa__btn.sc-snk-pesquisa:disabled:hover{cursor:unset;color:var(--snk-pesquisa__btn-disabled--color)}.snk-pesquisa__btn.sc-snk-pesquisa:hover{color:var(--snk-pesquisa__btn-hover--color)}";export{n as snk_pesquisa}