@sankhyalabs/sankhyablocks 8.16.0-dev.2 → 8.16.0-dev.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (46) hide show
  1. package/dist/cjs/{IExporterProvider-9479f618.js → IExporterProvider-597949f9.js} +1 -1
  2. package/dist/cjs/{dataunit-fetcher-0c7106a0.js → dataunit-fetcher-688d3f05.js} +7 -3
  3. package/dist/cjs/snk-actions-button_4.cjs.entry.js +1 -1
  4. package/dist/cjs/snk-application.cjs.entry.js +1 -1
  5. package/dist/cjs/snk-attach.cjs.entry.js +1 -1
  6. package/dist/cjs/snk-crud.cjs.entry.js +1 -1
  7. package/dist/cjs/snk-data-exporter.cjs.entry.js +2 -2
  8. package/dist/cjs/{snk-data-unit-16791a2f.js → snk-data-unit-685272e7.js} +1 -1
  9. package/dist/cjs/snk-data-unit.cjs.entry.js +2 -2
  10. package/dist/cjs/snk-detail-view.cjs.entry.js +2 -2
  11. package/dist/cjs/snk-grid.cjs.entry.js +2 -2
  12. package/dist/cjs/{snk-guides-viewer-d82746e8.js → snk-guides-viewer-67605336.js} +1 -1
  13. package/dist/cjs/snk-guides-viewer.cjs.entry.js +2 -2
  14. package/dist/cjs/snk-simple-crud.cjs.entry.js +2 -2
  15. package/dist/collection/lib/dataUnit/dataUnitInMemoryUtils.js +7 -3
  16. package/dist/components/dataunit-fetcher.js +7 -3
  17. package/dist/esm/{IExporterProvider-5a858363.js → IExporterProvider-63a188b6.js} +1 -1
  18. package/dist/esm/{dataunit-fetcher-f7e0ffc0.js → dataunit-fetcher-264191b2.js} +7 -3
  19. package/dist/esm/snk-actions-button_4.entry.js +1 -1
  20. package/dist/esm/snk-application.entry.js +1 -1
  21. package/dist/esm/snk-attach.entry.js +1 -1
  22. package/dist/esm/snk-crud.entry.js +1 -1
  23. package/dist/esm/snk-data-exporter.entry.js +2 -2
  24. package/dist/esm/{snk-data-unit-a327d22c.js → snk-data-unit-63f83504.js} +1 -1
  25. package/dist/esm/snk-data-unit.entry.js +2 -2
  26. package/dist/esm/snk-detail-view.entry.js +2 -2
  27. package/dist/esm/snk-grid.entry.js +2 -2
  28. package/dist/esm/{snk-guides-viewer-874da66f.js → snk-guides-viewer-151f6091.js} +1 -1
  29. package/dist/esm/snk-guides-viewer.entry.js +2 -2
  30. package/dist/esm/snk-simple-crud.entry.js +2 -2
  31. package/dist/sankhyablocks/{p-6ded2076.entry.js → p-14b9f964.entry.js} +1 -1
  32. package/dist/sankhyablocks/{p-e6210aec.js → p-3a212712.js} +1 -1
  33. package/dist/sankhyablocks/{p-b8cde0d8.entry.js → p-3a216b81.entry.js} +1 -1
  34. package/dist/sankhyablocks/{p-e0b9f59a.entry.js → p-7505da04.entry.js} +1 -1
  35. package/dist/sankhyablocks/{p-e9bbc3d5.entry.js → p-75f83d1d.entry.js} +1 -1
  36. package/dist/sankhyablocks/{p-60e46675.entry.js → p-82a0bfb0.entry.js} +1 -1
  37. package/dist/sankhyablocks/{p-0e11ee18.entry.js → p-941bf3ef.entry.js} +1 -1
  38. package/dist/sankhyablocks/{p-0046959e.entry.js → p-b4b21558.entry.js} +1 -1
  39. package/dist/sankhyablocks/{p-b7c4feeb.entry.js → p-bad55caa.entry.js} +1 -1
  40. package/dist/sankhyablocks/{p-8c6b44ea.entry.js → p-c053256c.entry.js} +1 -1
  41. package/dist/sankhyablocks/{p-7d9baaf4.entry.js → p-c5268346.entry.js} +1 -1
  42. package/dist/sankhyablocks/{p-a4b1f1eb.js → p-cefba299.js} +1 -1
  43. package/dist/sankhyablocks/{p-c7cbad38.js → p-fcac4dfc.js} +1 -1
  44. package/dist/sankhyablocks/{p-6d4f4614.js → p-fe79f83a.js} +1 -1
  45. package/dist/sankhyablocks/sankhyablocks.esm.js +1 -1
  46. package/package.json +1 -1
@@ -1 +1 @@
1
- import{r as t,c as i,h as e}from"./p-d2d301a6.js";import{ApplicationContext as a,DataType as s,Action as n,UserInterface as o,StringUtils as r,DataUnit as l}from"@sankhyalabs/core";import{D as h}from"./p-dc7c9047.js";import"./p-af8efd95.js";import"./p-30cf616e.js";import{S as d}from"./p-21749402.js";import{P as c,b as u,c as v,d as m,D as A,I as O}from"./p-6d4f4614.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{d as p}from"./p-b0ef4383.js";import{A as w}from"./p-913a9979.js";import{T as I}from"./p-7e7a7473.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";class _{constructor(t){this.dataUnitName=t}async save({dataUnit:t,record:i,updatingFields:e,operation:a}){var s,n;const o="INSERT"==a,r=o?e:i;if(!o&&(null==e?void 0:e.DESCRICAO)&&(null==e?void 0:e.DESCRICAO)!==(null==i?void 0:i.DESCRICAO))throw new Error(d.DESCRIPTION_CANNOT_BE_CHANGED);const l={anexo:{codata:o?null==e?void 0:e.REGISTER_KEY:null==i?void 0:i.CODATA,sequencia:(null==r?void 0:r.SEQUENCIA)||"0",tipo:(null==r?void 0:r.TIPO)||"N",descricao:null==r?void 0:r.DESCRICAO,arquivo:null===(n=null===(s=e.CAMINHO_ARQUIVO)||void 0===s?void 0:s[0])||void 0===n?void 0:n.name,ehInclusao:o?"S":"N",ehArquivoRepositorio:"N"}};return new Promise(((i,a)=>{h.get().callServiceBroker("Attach.save",JSON.stringify(l)).then((a=>{var s;return i([Object.assign(Object.assign(Object.assign({},a),e),{__owner__dataunit__name__:null!==(s=this.dataUnitName)&&void 0!==s?s:t})])})).catch((t=>a(t)))}))}async edit(t){throw new Error("Method not implemented.")}async delete(t){var i={anexo:{codata:t.CODATA,tipo:t.TIPO,descricao:t.DESCRICAO}};const e=await h.get().callServiceBroker("Attach.remove",JSON.stringify(i));return Promise.resolve(e)}async getDownloadKey(t){var i,e,a;if("S"==t.EHARQUIVOREPOSITORIO){const a={config:{path:t.ARQUIVO,tipoconteudo:t.TIPOCONTEUDO}},s=await h.get().callServiceBroker("RepositorioArquivoSP.abreArquivo",JSON.stringify(a));return Promise.resolve({chave:{valor:null===(e=null===(i=null==s?void 0:s.responseBody)||void 0===i?void 0:i.chave)||void 0===e?void 0:e.valor}})}const s={anexo:{codata:t.CODATA,codemp:t.CODEMP,sequencia:t.SEQUENCIA,tipo:t.TIPO,descricao:t.DESCRICAO,tipoConteudo:t.TIPOCONTEUDO}},n=await h.get().callServiceBroker("Attach.view",JSON.stringify(s));return(null==n?void 0:n.chaveAnexo)?Promise.resolve({chave:{valor:null===(a=null==n?void 0:n.chaveAnexo)||void 0===a?void 0:a.idChaveAnexo}}):Promise.reject(new Error("File not found."))}}const S="AnexoSistemaSP.salvar",k="AnexoSistemaSP.excluir",y="AnexoSistemaSP.baixar";class b{constructor(t,i,e){var a;this.entityName=t,this.registerKey=i,this.dataUnitName=e,this.validateFields=t=>{if(t.LINK&&t.NOMEARQUIVO)throw new Error(d.LINK_AND_FILE_AT_THE_SAME_TIME);if(!t.LINK&&!t.NOMEARQUIVO)throw new Error(d.ANY_LINK_OR_FILE_FILLED);if(!this.registerKey)throw new Error("Register key can not be null")},this.resourceID=window.resourceID||(null===(a=window.workspace)||void 0===a?void 0:a.resourceID)}async save(t){var i,e;let{updatingFields:a}=t;a=Object.assign(Object.assign({},a),{NOMEARQUIVO:null===(i=a.NOMEARQUIVO)||void 0===i?void 0:i[0]});try{this.validateFields(a);const t=a.LINK?null:a.NOMEARQUIVO,i={serviceName:S,requestBody:{params:{resourceID:this.resourceID,description:a.DESCRICAO,fileSelect:t?1:0,keySession:null===(e=null==t?void 0:t.properties)||void 0===e?void 0:e.fileNameTmp,nameAttach:null==t?void 0:t.name,link:a.LINK,nameEntity:this.entityName,pkEntity:this.registerKey,typeAcess:a.TIPOACESSO,typeApres:a.TIPOAPRES}}},s=await h.get().callServiceBroker(S,JSON.stringify(i));return Promise.resolve([Object.assign(Object.assign(Object.assign({},s),a),{ARQUIVOOULINK:a.LINK?a.LINK:null==t?void 0:t.name,__owner__dataunit__name__:this.dataUnitName})])}catch(t){return Promise.reject(t)}}async edit(t){var i,e,a;let{updatingFields:s,record:n}=t;const o=t=>void 0!==s[t]?s[t]:n[t],r=o("NOMEARQUIVO"),l=null===(e=null===(i=s.NOMEARQUIVO)||void 0===i?void 0:i[0])||void 0===e?void 0:e.downloadURL;s=Object.assign(Object.assign({},s),{DESCRICAO:o("DESCRICAO"),LINK:o("LINK"),TIPOACESSO:o("TIPOACESSO"),TIPOAPRES:o("TIPOAPRES"),CHAVEARQUIVO:n.CHAVEARQUIVO,NOMEARQUIVO:null==r?void 0:r[0]});const d=s.LINK?null:s.NOMEARQUIVO;try{this.validateFields(s);const t={serviceName:S,requestBody:{params:{resourceID:this.resourceID,nuAttach:null==n?void 0:n.NUATTACH,description:s.DESCRICAO,fileSelect:l?1:0,keySession:null===(a=null==d?void 0:d.properties)||void 0===a?void 0:a.fileNameTmp,keyAttach:s.CHAVEARQUIVO,nameAttach:null==d?void 0:d.name,link:s.LINK,nameEntity:this.entityName,pkEntity:this.registerKey,typeAcess:s.TIPOACESSO,typeApres:s.TIPOAPRES}}},i=await h.get().callServiceBroker(S,JSON.stringify(t));return Promise.resolve([Object.assign(Object.assign(Object.assign({},i),s),{ARQUIVOOULINK:s.LINK?s.LINK:null==d?void 0:d.name,__owner__dataunit__name__:this.dataUnitName})])}catch(t){return Promise.reject(t)}}delete(t){var i;const e=(null===(i=t.NOMEARQUIVO)||void 0===i?void 0:i[0])||{},a={serviceName:k,requestBody:{paramsDelete:{keyAttach:t.CHAVEARQUIVO,nameAttach:null==e?void 0:e.name,nameEntity:t.NOMEINSTANCIA,nuAttach:t.NUATTACH,pkEntity:t.PKREGISTRO}}};return new Promise(((t,i)=>{h.get().callServiceBroker(k,JSON.stringify(a)).then((i=>t(i))).catch((t=>i(t)))}))}getDownloadKey(t){var i;const e=(null===(i=t.NOMEARQUIVO)||void 0===i?void 0:i[0])||{},a={serviceName:y,requestBody:{paramsDown:{nameAttach:null==e?void 0:e.name,nameEntity:t.NOMEINSTANCIA,nuAttach:t.NUATTACH,pkEntity:t.PKREGISTRO,keyAttach:t.CHAVEARQUIVO}}};return new Promise(((t,i)=>{h.get().callServiceBroker(y,JSON.stringify(a)).then((i=>t(i))).catch((t=>i(t)))}))}}class f{constructor(t,i){this.entityName=t,this.getMessage=i,this._application=a.getContextValue("__SNK__APPLICATION__")}initLoaders(t,i,e){this.loader||(this.loader=t.dataLoader),t.dataLoader=(t,i)=>this.dataLoader(t,i),t.saveLoader=(t,a)=>this.saveLoader(a,i).then((t=>(t.length&&e(),t))),t.removeLoader=(t,a)=>this.removeLoader(t,a,i).then((t=>(t.length&&e(),t)))}metadataLoader(t){throw new Error("Method not implemented.")}dataLoader(t,i){return new Promise((e=>{this.loader(t,i).then((t=>{const i=((null==t?void 0:t.records)||[]).map((t=>{let i;return t.LINK||(i=[{name:t.NOMEARQUIVO}]),Object.assign(Object.assign({},t),{ARQUIVOOULINK:t.LINK?t.LINK:t.NOMEARQUIVO,NOMEARQUIVO:i})}));e(Object.assign(Object.assign({},t),{records:i}))}))}))}saveLoader(t,i){return new Promise((e=>{var a;const s=Array.isArray(t)?t[0]:{};((null===(a=null==s?void 0:s.record)||void 0===a?void 0:a.NUATTACH)>=0?i.edit.bind(i):i.save.bind(i))(s).then((t=>{e(t)})).catch((t=>t.message===d.LINK_AND_FILE_AT_THE_SAME_TIME?(this._application.alert(this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.title"),this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.message")),e([])):t.message===d.ANY_LINK_OR_FILE_FILLED?(this._application.alert(this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.title"),this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.message")),e([])):t.message?(this._application.error(t.title||t.name,t.message),e([])):void e([])))}))}removeLoader(t,i,e){return new Promise((a=>{const{records:s}=t.getSelectionInfo(),n=s[0];e.delete(n).then((()=>(c.removeRecords(t,[n]),a(i))))}))}getFilters(t){return[{name:"AttachmentsByPK",expression:"this.PKREGISTRO = :PKREGISTRO",params:[{name:"PKREGISTRO",dataType:s.TEXT,value:`${t}_${this.entityName}`}]}]}getInterceptions(t,i,e){return new Promise((a=>i.type===n.EDITION_CANCELED?t.isDirty()?this._application.confirm(this.getMessage("snkAttach.cancelConfirmation.title"),this.getMessage("snkAttach.cancelConfirmation.message")).then((t=>t?(e.goToView(p.GRID),a(i)):a(void 0))):a(i):i.type===n.DATA_SAVED?(t.loadData(),a(i)):void a(i)))}}const E=a.getContextValue("__SNK__APPLICATION__"),N=t=>{var i,e;return null===(e=null===(i=null==E?void 0:E.messagesBuilder)||void 0===i?void 0:i.getMessage)||void 0===e?void 0:e.call(i,t,null)},g={grid:{columns:[{name:"CODATA",orderIndex:0,width:0},{name:"DESCRICAO",orderIndex:1,width:0},{name:"ARQUIVO",orderIndex:2,width:0},{name:"DTALTER",orderIndex:3,width:0},{name:"USUARIO",orderIndex:4,width:0}]},form:{emptyConfig:!1,fields:[{name:"DESCRICAO",label:N("snkAttach.attachMetadata.lblDescription"),visible:!0,readOnly:!1,required:!0},{name:"CAMINHO_ARQUIVO",label:N("snkAttach.attachMetadata.lblFile"),visible:!0,readOnly:!1,required:!0}]}},C={name:"Attach",label:"Attach List",fields:[{name:"CODATA",label:N("snkAttach.attachMetadata.lblCode"),dataType:s.TEXT},{name:"DESCRICAO",label:N("snkAttach.attachMetadata.lblDescription"),dataType:s.TEXT,readOnly:!1},{name:"ARQUIVO",label:N("snkAttach.attachMetadata.lblFileOrLink"),dataType:s.TEXT},{name:"USUARIO",label:N("snkAttach.attachMetadata.lblUser"),dataType:s.TEXT},{name:"DTALTER",label:N("snkAttach.attachMetadata.lblDate"),dataType:s.TEXT},{name:"CAMINHO_ARQUIVO",label:N("snkAttach.attachMetadata.lblFileUpload"),dataType:s.OBJECT,userInterface:o.FILE,readOnly:!1,required:!0,visible:!0,properties:{subTitle:N("snkAttach.attachMetadata.lblSubTitle"),MAX_FILES:1,STORAGESTRATEGY:"SESSION",INTERNAL_FILENAME:"Attach.upload"}}]};class P{constructor(t){this.getMessage=t,this._records=[],this._application=a.getContextValue("__SNK__APPLICATION__")}initLoaders(t,i,e){t.metadataLoader=t=>this.metadataLoader(t),t.dataLoader=(t,i)=>this.dataLoader(t,i),t.saveLoader=(t,a)=>this.saveLoader(a,i).then((t=>(t.length&&e(),t))),t.removeLoader=(t,a)=>this.removeLoader(t,a,i).then((t=>(t.length&&e(),t)))}metadataLoader(t){return Promise.resolve(C)}async dataLoader(t,i){if(!i.source)return Promise.resolve({records:this._records});if(!Number.isNaN(Number(i.source))){const t={criteria:{codata:i.source,tipoAnexo:"N"}},e=await this._application.getDataFetcher(),{anexos:{anexo:a=[]}}=await e.callServiceBroker("Attach.load",JSON.stringify(t)),s=[];a.forEach((t=>{s.push(Object.assign({__record__id__:r.generateUUID(),CAMINHO_ARQUIVO:[{name:null==t?void 0:t.ARQUIVO}]},t))})),this._records=s}let e=u(this._records,t,i.filters);return e=v(e,t,i.sort),Promise.resolve({records:e,paginationInfo:m(e,i.offset,i.limit)})}saveLoader(t,i){return new Promise((e=>{const a=Array.isArray(t)?t[0]:{};i.save(a).then(e).catch((t=>t.message===d.DESCRIPTION_CANNOT_BE_CHANGED?(this._application.alert(this.getMessage("snkAttach.alertValidation.descriptionCannotBeChanged.title"),this.getMessage("snkAttach.alertValidation.descriptionCannotBeChanged.message")),e([])):t.message===d.LINK_AND_FILE_AT_THE_SAME_TIME?(this._application.alert(this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.title"),this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.message")),e([])):t.message===d.ANY_LINK_OR_FILE_FILLED?(this._application.alert(this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.title"),this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.message")),e([])):t.message?(this._application.error(t.title||t.name,t.message),e([])):void e([])))}))}removeLoader(t,i,e){return new Promise((a=>{t.getSelectionInfo().records.forEach((async t=>{this._application.hasAccess(w.REMOVE).then((async s=>{s&&(await e.delete(t),a(i))}))}))}))}getFilters(){throw new Error("Method not implemented.")}getInterceptions(t,i,e){return new Promise((a=>i.type===n.EDITION_CANCELED?t.isDirty()?this._application.confirm(this.getMessage("snkAttach.cancelConfirmation.title"),this.getMessage("snkAttach.cancelConfirmation.message")).then((t=>t?(e.goToView(p.GRID),a(i)):a(void 0))):a(i):i.type===n.DATA_SAVED?(t.loadData(),a(i)):void a(i)))}}const T=a.getContextValue("__SNK__APPLICATION__"),L=t=>{var i,e;return null===(e=null===(i=null==T?void 0:T.messagesBuilder)||void 0===i?void 0:i.getMessage)||void 0===e?void 0:e.call(i,t,null)},R={DOWNLOAD:{hint:L("snkAttach.taskbar.titleDownload"),name:"DOWNLOAD",iconName:"file-download"},LINK:{hint:L("snkAttach.taskbar.titleLink"),name:"LINK",iconName:"launch"}},x=()=>{const t=[I.REMOVE,"DOWNLOAD","LINK"];return{getButtons:(t,i,e)=>{if((null==i?void 0:i.insertionMode)||(null==i?void 0:i.isDirty))return e.reverse();e.splice(e.indexOf(I.REFRESH),1);const{selectedRecord:a}=i||{},s=(null==a?void 0:a.LINK)?R.LINK:R.DOWNLOAD;e.splice(e.indexOf(I.DIVIDER)+1,0,I.REMOVE,s,I.DIVIDER);const n=Array.from(new Set(e.filter((t=>t!==I.CLONE))));return n.splice(n.indexOf(s)+1,0,I.DIVIDER),n},isEnabled:(i,e,a)=>{const s=void 0!==(null==e?void 0:e.selectedRecord);return!(t.includes(a)&&!s)}}},D={grid:{columns:[{name:"ARQUIVOOULINK",orderIndex:0,width:0},{name:"DESCRICAO",orderIndex:1,width:0},{name:"DHCAD",orderIndex:2,width:0},{name:"DHALTER",orderIndex:3,width:0},{name:"TIPOAPRES",orderIndex:4,width:0},{name:"TIPOACESSO",orderIndex:5,width:0},{name:"CODUSU",orderIndex:6,width:0},{name:"CODUSUALT",orderIndex:7,width:0}]},form:{emptyConfig:!1,fields:[{name:"DESCRICAO",required:!0},{name:"TIPOAPRES",required:!0},{name:"TIPOACESSO",required:!0},{name:"LINK"},{name:"NOMEARQUIVO"}]}},j=class{constructor(e){t(this,e),this.back=i(this,"back",7),this.handleTaskbarClick=async({detail:t})=>{if(["DOWNLOAD","LINK"].includes(t))return this.downloadAttachment(this._currentDataUnit.getSelectedRecord());"Attach"===this.fetcherType&&["SAVE"].includes(t)&&this._currentDataUnit.isDirty()&&await this._currentDataUnit.setFieldValue("REGISTER_KEY",this.registerKey)},this.handleBack=()=>{this._currentDataUnit.cancelEdition().then((t=>{t&&this.back.emit()}))},this.handleFinish=()=>{if(!this._currentDataUnit.isDirty())return this.back.emit();this._currentDataUnit.saveData().then((()=>{this.showFinishedToast(),this.back.emit()}))},this.fetcherType=void 0,this.fetcher=void 0,this.dataUnit=void 0,this.dataUnitBuilder=void 0,this.registerKey=void 0,this.entityName=void 0,this.messagesBuilder=void 0,this._currentFetcher=void 0,this._currentDataUnit=void 0,this.crudConfig=void 0}async registerKeyWatcher(t,i){var e;null==this._currentDataUnit&&this.loadAttachmentDataUnit(),i!==t&&await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData())}async initAttach(){var t,i,e,a,s,n;if(this.fetcherType||this.registerKey){if(this.fetcherType||(this.fetcherType="AnexoSistema"),this.returnToGridMode(),"AnexoSistema"===this.fetcherType)return this._currentFetcher=new b(this.entityName,this.registerKey,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name),null===(i=this._currentDataUnitBuilder)||void 0===i||i.initLoaders(this._currentDataUnit,this._currentFetcher,this.returnToGridMode.bind(this)),void await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData());if("Attach"===this.fetcherType&&(null===(a=this.registerKey)||void 0===a?void 0:a.split("_").length)>1)return;await(null===(s=this._currentDataUnit)||void 0===s?void 0:s.loadMetadata()),await(null===(n=this._currentDataUnit)||void 0===n?void 0:n.loadData(void 0,void 0,!0,this.registerKey))}}getMessage(t,i){if(this.messagesBuilder)return this.messagesBuilder.getMessage(t,i)}showFinishedToast(){this._application.info(this.getMessage("snkAttach.finishedMessage"),{iconName:"check"})}downloadAttachment(t){if(!t)throw new Error("Nenhum registro selecionado");t.LINK?window.open(`${t.LINK}`):this._currentFetcher.getDownloadKey(t).then((({chave:i})=>{var e;let a=!1;(null===(e=null==t?void 0:t.ARQUIVO)||void 0===e?void 0:e.endsWith(".pdf"))||(a=!0),window.open(`/mge/visualizadorArquivos.mge?chaveArquivo=${i.valor}${a?"&forcarDownload=S":""}`)}))}returnToGridMode(){var t;null===(t=this._currentDataUnit)||void 0===t||t.clearSelection(),this._crudElement&&this._crudElement.goToView(p.GRID)}async loadAttachmentDataUnit(){try{switch(this.fetcherType){case"AnexoSistema":await this.loadAnexoSistema();break;case"Attach":await this.loadAttach();break;default:this._currentFetcher=this.fetcher,this._currentDataUnit=this.dataUnit,this._currentDataUnitBuilder=this.dataUnitBuilder}}catch(t){throw new Error("There was an error while creating the data unit")}}async loadAnexoSistema(){var t,i,e;this._currentDataUnit=(new A).getDataUnit("AnexoSistema","br.com.sankhya.core.v3.anexoSistema"),this._currentFetcher=new b(this.entityName,this.registerKey,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name),this._currentDataUnit.metadata||(await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadMetadata()),this.crudConfig=Object.assign({},D)),this.initDataUnitLoaders(),this._currentDataUnit.addFilterProvider({getFilter:()=>this._currentDataUnitBuilder.getFilters(this.registerKey)}),this._currentDataUnit.addInterceptor({interceptAction:t=>this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit,t,this._crudElement)}),await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData()),this.disableEditFieldsNotInForm()}async loadAttach(){var t,i;this._currentFetcher=new _,this._currentDataUnit=new l(O.IN_MEMORY_DATA_UNIT_NAME),this.initDataUnitLoaders(),this._currentDataUnit.addInterceptor({interceptAction:t=>{var i;return t.type===n.METADATA_LOADED&&(this.crudConfig=Object.assign({},g),null===(i=this._crudElement)||void 0===i||i.updateConfig()),this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit,t,this._crudElement)}}),this._currentDataUnit.metadata||(await(null===(t=this._currentDataUnit)||void 0===t?void 0:t.loadMetadata()),this.crudConfig=Object.assign({},g),await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadData(void 0,void 0,!0,this.registerKey)),this.disableEditFieldsNotInForm())}initDataUnitLoaders(){var t,i,e;"AnexoSistema"===this.fetcherType&&(this._currentFetcher=new b(this.entityName,this.registerKey,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name),this._currentDataUnitBuilder=new f(this.entityName,this.getMessage.bind(this)),null===(i=this._currentDataUnitBuilder)||void 0===i||i.initLoaders(this._currentDataUnit,this._currentFetcher,this.returnToGridMode.bind(this))),"Attach"===this.fetcherType&&(this._currentFetcher=new _,this._currentDataUnitBuilder=new P(this.getMessage.bind(this)),null===(e=this._currentDataUnitBuilder)||void 0===e||e.initLoaders(this._currentDataUnit,this._currentFetcher,(async()=>{this.returnToGridMode(),await this._currentDataUnit.loadData(void 0,void 0,!0,this.registerKey)})))}disableEditFieldsNotInForm(){var t;null===(t=this.crudConfig)||void 0===t||t.grid.columns.forEach((t=>{var i;const e=t.name;(null===(i=this.crudConfig)||void 0===i?void 0:i.form.fields.some((t=>t.name===e)))||this._currentDataUnit.disableField(e)}))}async componentWillLoad(){this._application=a.getContextValue("__SNK__APPLICATION__"),await this.initAttach()}componentWillRender(){this.fetcherType||(this.fetcherType="AnexoSistema"),null==this._currentDataUnit&&this.loadAttachmentDataUnit()}async handleOnDataStateChange({detail:t}){"Attach"===this.fetcherType&&(t.insertionMode?this._currentDataUnit.enableField("DESCRICAO"):this._currentDataUnit.disableField("DESCRICAO"),await this._currentDataUnit.loadMetadata())}render(){var t,i;return this._currentDataUnit?e("main",{class:"snk-attach__main"},e("header",{class:"snk-attach__header"},e("snk-simple-bar",{onExit:this.handleBack,messagesBuilder:this.messagesBuilder},e("div",{slot:"rightSlot"},e("ez-button",{class:"ez-button--primary",label:this.getMessage("snkAttach.finish"),onClick:this.handleFinish})))),e("div",{class:"snk-attach__crud-section ez-size-height--full ez-size-width--full ez-flex ez-flex--column"},e("div",{class:"ez-box__container"},e("snk-simple-crud",{ref:t=>this._crudElement=t,dataUnit:this._currentDataUnit,taskbarManager:x(),gridConfig:null===(t=this.crudConfig)||void 0===t?void 0:t.grid,formConfig:null===(i=this.crudConfig)||void 0===i?void 0:i.form,useCancelConfirm:!1,onActionClick:this.handleTaskbarClick,messagesBuilder:this.messagesBuilder,onDataStateChange:this.handleOnDataStateChange.bind(this)},e("div",{slot:"snkSimpleCrudHeader"},e("div",{class:"ez-flex ez-flex--column"},e("span",{class:"ez-title--primary ez-text ez-text--large ez-text--bold ez-padding-bottom--medium"},this.getMessage("snkAttach.title")),e("span",{class:"ez-text ez-text--medium ez-text--secondary"},this.getMessage("snkAttach.description")))))))):null}static get watchers(){return{registerKey:["registerKeyWatcher"]}}};j.style=".snk-attach__header.sc-snk-attach,.snk-attach__crud-section.sc-snk-attach{padding:0 var(--space--lg)}.snk-attach__file-info.sc-snk-attach{padding:var(--space--small);max-width:50%}.snk-attach__main.sc-snk-attach{height:85%}.ez-box__container.sc-snk-attach{height:100%}";export{j as snk_attach}
1
+ import{r as t,c as i,h as e}from"./p-d2d301a6.js";import{ApplicationContext as a,DataType as s,Action as n,UserInterface as o,StringUtils as r,DataUnit as l}from"@sankhyalabs/core";import{D as h}from"./p-dc7c9047.js";import"./p-af8efd95.js";import"./p-30cf616e.js";import{S as d}from"./p-21749402.js";import{P as c,b as u,c as v,d as m,D as A,I as O}from"./p-fe79f83a.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{d as p}from"./p-b0ef4383.js";import{A as w}from"./p-913a9979.js";import{T as I}from"./p-7e7a7473.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";class _{constructor(t){this.dataUnitName=t}async save({dataUnit:t,record:i,updatingFields:e,operation:a}){var s,n;const o="INSERT"==a,r=o?e:i;if(!o&&(null==e?void 0:e.DESCRICAO)&&(null==e?void 0:e.DESCRICAO)!==(null==i?void 0:i.DESCRICAO))throw new Error(d.DESCRIPTION_CANNOT_BE_CHANGED);const l={anexo:{codata:o?null==e?void 0:e.REGISTER_KEY:null==i?void 0:i.CODATA,sequencia:(null==r?void 0:r.SEQUENCIA)||"0",tipo:(null==r?void 0:r.TIPO)||"N",descricao:null==r?void 0:r.DESCRICAO,arquivo:null===(n=null===(s=e.CAMINHO_ARQUIVO)||void 0===s?void 0:s[0])||void 0===n?void 0:n.name,ehInclusao:o?"S":"N",ehArquivoRepositorio:"N"}};return new Promise(((i,a)=>{h.get().callServiceBroker("Attach.save",JSON.stringify(l)).then((a=>{var s;return i([Object.assign(Object.assign(Object.assign({},a),e),{__owner__dataunit__name__:null!==(s=this.dataUnitName)&&void 0!==s?s:t})])})).catch((t=>a(t)))}))}async edit(t){throw new Error("Method not implemented.")}async delete(t){var i={anexo:{codata:t.CODATA,tipo:t.TIPO,descricao:t.DESCRICAO}};const e=await h.get().callServiceBroker("Attach.remove",JSON.stringify(i));return Promise.resolve(e)}async getDownloadKey(t){var i,e,a;if("S"==t.EHARQUIVOREPOSITORIO){const a={config:{path:t.ARQUIVO,tipoconteudo:t.TIPOCONTEUDO}},s=await h.get().callServiceBroker("RepositorioArquivoSP.abreArquivo",JSON.stringify(a));return Promise.resolve({chave:{valor:null===(e=null===(i=null==s?void 0:s.responseBody)||void 0===i?void 0:i.chave)||void 0===e?void 0:e.valor}})}const s={anexo:{codata:t.CODATA,codemp:t.CODEMP,sequencia:t.SEQUENCIA,tipo:t.TIPO,descricao:t.DESCRICAO,tipoConteudo:t.TIPOCONTEUDO}},n=await h.get().callServiceBroker("Attach.view",JSON.stringify(s));return(null==n?void 0:n.chaveAnexo)?Promise.resolve({chave:{valor:null===(a=null==n?void 0:n.chaveAnexo)||void 0===a?void 0:a.idChaveAnexo}}):Promise.reject(new Error("File not found."))}}const S="AnexoSistemaSP.salvar",k="AnexoSistemaSP.excluir",y="AnexoSistemaSP.baixar";class b{constructor(t,i,e){var a;this.entityName=t,this.registerKey=i,this.dataUnitName=e,this.validateFields=t=>{if(t.LINK&&t.NOMEARQUIVO)throw new Error(d.LINK_AND_FILE_AT_THE_SAME_TIME);if(!t.LINK&&!t.NOMEARQUIVO)throw new Error(d.ANY_LINK_OR_FILE_FILLED);if(!this.registerKey)throw new Error("Register key can not be null")},this.resourceID=window.resourceID||(null===(a=window.workspace)||void 0===a?void 0:a.resourceID)}async save(t){var i,e;let{updatingFields:a}=t;a=Object.assign(Object.assign({},a),{NOMEARQUIVO:null===(i=a.NOMEARQUIVO)||void 0===i?void 0:i[0]});try{this.validateFields(a);const t=a.LINK?null:a.NOMEARQUIVO,i={serviceName:S,requestBody:{params:{resourceID:this.resourceID,description:a.DESCRICAO,fileSelect:t?1:0,keySession:null===(e=null==t?void 0:t.properties)||void 0===e?void 0:e.fileNameTmp,nameAttach:null==t?void 0:t.name,link:a.LINK,nameEntity:this.entityName,pkEntity:this.registerKey,typeAcess:a.TIPOACESSO,typeApres:a.TIPOAPRES}}},s=await h.get().callServiceBroker(S,JSON.stringify(i));return Promise.resolve([Object.assign(Object.assign(Object.assign({},s),a),{ARQUIVOOULINK:a.LINK?a.LINK:null==t?void 0:t.name,__owner__dataunit__name__:this.dataUnitName})])}catch(t){return Promise.reject(t)}}async edit(t){var i,e,a;let{updatingFields:s,record:n}=t;const o=t=>void 0!==s[t]?s[t]:n[t],r=o("NOMEARQUIVO"),l=null===(e=null===(i=s.NOMEARQUIVO)||void 0===i?void 0:i[0])||void 0===e?void 0:e.downloadURL;s=Object.assign(Object.assign({},s),{DESCRICAO:o("DESCRICAO"),LINK:o("LINK"),TIPOACESSO:o("TIPOACESSO"),TIPOAPRES:o("TIPOAPRES"),CHAVEARQUIVO:n.CHAVEARQUIVO,NOMEARQUIVO:null==r?void 0:r[0]});const d=s.LINK?null:s.NOMEARQUIVO;try{this.validateFields(s);const t={serviceName:S,requestBody:{params:{resourceID:this.resourceID,nuAttach:null==n?void 0:n.NUATTACH,description:s.DESCRICAO,fileSelect:l?1:0,keySession:null===(a=null==d?void 0:d.properties)||void 0===a?void 0:a.fileNameTmp,keyAttach:s.CHAVEARQUIVO,nameAttach:null==d?void 0:d.name,link:s.LINK,nameEntity:this.entityName,pkEntity:this.registerKey,typeAcess:s.TIPOACESSO,typeApres:s.TIPOAPRES}}},i=await h.get().callServiceBroker(S,JSON.stringify(t));return Promise.resolve([Object.assign(Object.assign(Object.assign({},i),s),{ARQUIVOOULINK:s.LINK?s.LINK:null==d?void 0:d.name,__owner__dataunit__name__:this.dataUnitName})])}catch(t){return Promise.reject(t)}}delete(t){var i;const e=(null===(i=t.NOMEARQUIVO)||void 0===i?void 0:i[0])||{},a={serviceName:k,requestBody:{paramsDelete:{keyAttach:t.CHAVEARQUIVO,nameAttach:null==e?void 0:e.name,nameEntity:t.NOMEINSTANCIA,nuAttach:t.NUATTACH,pkEntity:t.PKREGISTRO}}};return new Promise(((t,i)=>{h.get().callServiceBroker(k,JSON.stringify(a)).then((i=>t(i))).catch((t=>i(t)))}))}getDownloadKey(t){var i;const e=(null===(i=t.NOMEARQUIVO)||void 0===i?void 0:i[0])||{},a={serviceName:y,requestBody:{paramsDown:{nameAttach:null==e?void 0:e.name,nameEntity:t.NOMEINSTANCIA,nuAttach:t.NUATTACH,pkEntity:t.PKREGISTRO,keyAttach:t.CHAVEARQUIVO}}};return new Promise(((t,i)=>{h.get().callServiceBroker(y,JSON.stringify(a)).then((i=>t(i))).catch((t=>i(t)))}))}}class f{constructor(t,i){this.entityName=t,this.getMessage=i,this._application=a.getContextValue("__SNK__APPLICATION__")}initLoaders(t,i,e){this.loader||(this.loader=t.dataLoader),t.dataLoader=(t,i)=>this.dataLoader(t,i),t.saveLoader=(t,a)=>this.saveLoader(a,i).then((t=>(t.length&&e(),t))),t.removeLoader=(t,a)=>this.removeLoader(t,a,i).then((t=>(t.length&&e(),t)))}metadataLoader(t){throw new Error("Method not implemented.")}dataLoader(t,i){return new Promise((e=>{this.loader(t,i).then((t=>{const i=((null==t?void 0:t.records)||[]).map((t=>{let i;return t.LINK||(i=[{name:t.NOMEARQUIVO}]),Object.assign(Object.assign({},t),{ARQUIVOOULINK:t.LINK?t.LINK:t.NOMEARQUIVO,NOMEARQUIVO:i})}));e(Object.assign(Object.assign({},t),{records:i}))}))}))}saveLoader(t,i){return new Promise((e=>{var a;const s=Array.isArray(t)?t[0]:{};((null===(a=null==s?void 0:s.record)||void 0===a?void 0:a.NUATTACH)>=0?i.edit.bind(i):i.save.bind(i))(s).then((t=>{e(t)})).catch((t=>t.message===d.LINK_AND_FILE_AT_THE_SAME_TIME?(this._application.alert(this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.title"),this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.message")),e([])):t.message===d.ANY_LINK_OR_FILE_FILLED?(this._application.alert(this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.title"),this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.message")),e([])):t.message?(this._application.error(t.title||t.name,t.message),e([])):void e([])))}))}removeLoader(t,i,e){return new Promise((a=>{const{records:s}=t.getSelectionInfo(),n=s[0];e.delete(n).then((()=>(c.removeRecords(t,[n]),a(i))))}))}getFilters(t){return[{name:"AttachmentsByPK",expression:"this.PKREGISTRO = :PKREGISTRO",params:[{name:"PKREGISTRO",dataType:s.TEXT,value:`${t}_${this.entityName}`}]}]}getInterceptions(t,i,e){return new Promise((a=>i.type===n.EDITION_CANCELED?t.isDirty()?this._application.confirm(this.getMessage("snkAttach.cancelConfirmation.title"),this.getMessage("snkAttach.cancelConfirmation.message")).then((t=>t?(e.goToView(p.GRID),a(i)):a(void 0))):a(i):i.type===n.DATA_SAVED?(t.loadData(),a(i)):void a(i)))}}const E=a.getContextValue("__SNK__APPLICATION__"),N=t=>{var i,e;return null===(e=null===(i=null==E?void 0:E.messagesBuilder)||void 0===i?void 0:i.getMessage)||void 0===e?void 0:e.call(i,t,null)},g={grid:{columns:[{name:"CODATA",orderIndex:0,width:0},{name:"DESCRICAO",orderIndex:1,width:0},{name:"ARQUIVO",orderIndex:2,width:0},{name:"DTALTER",orderIndex:3,width:0},{name:"USUARIO",orderIndex:4,width:0}]},form:{emptyConfig:!1,fields:[{name:"DESCRICAO",label:N("snkAttach.attachMetadata.lblDescription"),visible:!0,readOnly:!1,required:!0},{name:"CAMINHO_ARQUIVO",label:N("snkAttach.attachMetadata.lblFile"),visible:!0,readOnly:!1,required:!0}]}},C={name:"Attach",label:"Attach List",fields:[{name:"CODATA",label:N("snkAttach.attachMetadata.lblCode"),dataType:s.TEXT},{name:"DESCRICAO",label:N("snkAttach.attachMetadata.lblDescription"),dataType:s.TEXT,readOnly:!1},{name:"ARQUIVO",label:N("snkAttach.attachMetadata.lblFileOrLink"),dataType:s.TEXT},{name:"USUARIO",label:N("snkAttach.attachMetadata.lblUser"),dataType:s.TEXT},{name:"DTALTER",label:N("snkAttach.attachMetadata.lblDate"),dataType:s.TEXT},{name:"CAMINHO_ARQUIVO",label:N("snkAttach.attachMetadata.lblFileUpload"),dataType:s.OBJECT,userInterface:o.FILE,readOnly:!1,required:!0,visible:!0,properties:{subTitle:N("snkAttach.attachMetadata.lblSubTitle"),MAX_FILES:1,STORAGESTRATEGY:"SESSION",INTERNAL_FILENAME:"Attach.upload"}}]};class P{constructor(t){this.getMessage=t,this._records=[],this._application=a.getContextValue("__SNK__APPLICATION__")}initLoaders(t,i,e){t.metadataLoader=t=>this.metadataLoader(t),t.dataLoader=(t,i)=>this.dataLoader(t,i),t.saveLoader=(t,a)=>this.saveLoader(a,i).then((t=>(t.length&&e(),t))),t.removeLoader=(t,a)=>this.removeLoader(t,a,i).then((t=>(t.length&&e(),t)))}metadataLoader(t){return Promise.resolve(C)}async dataLoader(t,i){if(!i.source)return Promise.resolve({records:this._records});if(!Number.isNaN(Number(i.source))){const t={criteria:{codata:i.source,tipoAnexo:"N"}},e=await this._application.getDataFetcher(),{anexos:{anexo:a=[]}}=await e.callServiceBroker("Attach.load",JSON.stringify(t)),s=[];a.forEach((t=>{s.push(Object.assign({__record__id__:r.generateUUID(),CAMINHO_ARQUIVO:[{name:null==t?void 0:t.ARQUIVO}]},t))})),this._records=s}let e=u(this._records,t,i.filters);return e=v(e,t,i.sort),Promise.resolve({records:e,paginationInfo:m(e,i.offset,i.limit)})}saveLoader(t,i){return new Promise((e=>{const a=Array.isArray(t)?t[0]:{};i.save(a).then(e).catch((t=>t.message===d.DESCRIPTION_CANNOT_BE_CHANGED?(this._application.alert(this.getMessage("snkAttach.alertValidation.descriptionCannotBeChanged.title"),this.getMessage("snkAttach.alertValidation.descriptionCannotBeChanged.message")),e([])):t.message===d.LINK_AND_FILE_AT_THE_SAME_TIME?(this._application.alert(this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.title"),this.getMessage("snkAttach.alertValidation.fileAndLinkAtTheSameTime.message")),e([])):t.message===d.ANY_LINK_OR_FILE_FILLED?(this._application.alert(this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.title"),this.getMessage("snkAttach.alertValidation.anyLinkOrFileFilled.message")),e([])):t.message?(this._application.error(t.title||t.name,t.message),e([])):void e([])))}))}removeLoader(t,i,e){return new Promise((a=>{t.getSelectionInfo().records.forEach((async t=>{this._application.hasAccess(w.REMOVE).then((async s=>{s&&(await e.delete(t),a(i))}))}))}))}getFilters(){throw new Error("Method not implemented.")}getInterceptions(t,i,e){return new Promise((a=>i.type===n.EDITION_CANCELED?t.isDirty()?this._application.confirm(this.getMessage("snkAttach.cancelConfirmation.title"),this.getMessage("snkAttach.cancelConfirmation.message")).then((t=>t?(e.goToView(p.GRID),a(i)):a(void 0))):a(i):i.type===n.DATA_SAVED?(t.loadData(),a(i)):void a(i)))}}const T=a.getContextValue("__SNK__APPLICATION__"),L=t=>{var i,e;return null===(e=null===(i=null==T?void 0:T.messagesBuilder)||void 0===i?void 0:i.getMessage)||void 0===e?void 0:e.call(i,t,null)},R={DOWNLOAD:{hint:L("snkAttach.taskbar.titleDownload"),name:"DOWNLOAD",iconName:"file-download"},LINK:{hint:L("snkAttach.taskbar.titleLink"),name:"LINK",iconName:"launch"}},x=()=>{const t=[I.REMOVE,"DOWNLOAD","LINK"];return{getButtons:(t,i,e)=>{if((null==i?void 0:i.insertionMode)||(null==i?void 0:i.isDirty))return e.reverse();e.splice(e.indexOf(I.REFRESH),1);const{selectedRecord:a}=i||{},s=(null==a?void 0:a.LINK)?R.LINK:R.DOWNLOAD;e.splice(e.indexOf(I.DIVIDER)+1,0,I.REMOVE,s,I.DIVIDER);const n=Array.from(new Set(e.filter((t=>t!==I.CLONE))));return n.splice(n.indexOf(s)+1,0,I.DIVIDER),n},isEnabled:(i,e,a)=>{const s=void 0!==(null==e?void 0:e.selectedRecord);return!(t.includes(a)&&!s)}}},D={grid:{columns:[{name:"ARQUIVOOULINK",orderIndex:0,width:0},{name:"DESCRICAO",orderIndex:1,width:0},{name:"DHCAD",orderIndex:2,width:0},{name:"DHALTER",orderIndex:3,width:0},{name:"TIPOAPRES",orderIndex:4,width:0},{name:"TIPOACESSO",orderIndex:5,width:0},{name:"CODUSU",orderIndex:6,width:0},{name:"CODUSUALT",orderIndex:7,width:0}]},form:{emptyConfig:!1,fields:[{name:"DESCRICAO",required:!0},{name:"TIPOAPRES",required:!0},{name:"TIPOACESSO",required:!0},{name:"LINK"},{name:"NOMEARQUIVO"}]}},j=class{constructor(e){t(this,e),this.back=i(this,"back",7),this.handleTaskbarClick=async({detail:t})=>{if(["DOWNLOAD","LINK"].includes(t))return this.downloadAttachment(this._currentDataUnit.getSelectedRecord());"Attach"===this.fetcherType&&["SAVE"].includes(t)&&this._currentDataUnit.isDirty()&&await this._currentDataUnit.setFieldValue("REGISTER_KEY",this.registerKey)},this.handleBack=()=>{this._currentDataUnit.cancelEdition().then((t=>{t&&this.back.emit()}))},this.handleFinish=()=>{if(!this._currentDataUnit.isDirty())return this.back.emit();this._currentDataUnit.saveData().then((()=>{this.showFinishedToast(),this.back.emit()}))},this.fetcherType=void 0,this.fetcher=void 0,this.dataUnit=void 0,this.dataUnitBuilder=void 0,this.registerKey=void 0,this.entityName=void 0,this.messagesBuilder=void 0,this._currentFetcher=void 0,this._currentDataUnit=void 0,this.crudConfig=void 0}async registerKeyWatcher(t,i){var e;null==this._currentDataUnit&&this.loadAttachmentDataUnit(),i!==t&&await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData())}async initAttach(){var t,i,e,a,s,n;if(this.fetcherType||this.registerKey){if(this.fetcherType||(this.fetcherType="AnexoSistema"),this.returnToGridMode(),"AnexoSistema"===this.fetcherType)return this._currentFetcher=new b(this.entityName,this.registerKey,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name),null===(i=this._currentDataUnitBuilder)||void 0===i||i.initLoaders(this._currentDataUnit,this._currentFetcher,this.returnToGridMode.bind(this)),void await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData());if("Attach"===this.fetcherType&&(null===(a=this.registerKey)||void 0===a?void 0:a.split("_").length)>1)return;await(null===(s=this._currentDataUnit)||void 0===s?void 0:s.loadMetadata()),await(null===(n=this._currentDataUnit)||void 0===n?void 0:n.loadData(void 0,void 0,!0,this.registerKey))}}getMessage(t,i){if(this.messagesBuilder)return this.messagesBuilder.getMessage(t,i)}showFinishedToast(){this._application.info(this.getMessage("snkAttach.finishedMessage"),{iconName:"check"})}downloadAttachment(t){if(!t)throw new Error("Nenhum registro selecionado");t.LINK?window.open(`${t.LINK}`):this._currentFetcher.getDownloadKey(t).then((({chave:i})=>{var e;let a=!1;(null===(e=null==t?void 0:t.ARQUIVO)||void 0===e?void 0:e.endsWith(".pdf"))||(a=!0),window.open(`/mge/visualizadorArquivos.mge?chaveArquivo=${i.valor}${a?"&forcarDownload=S":""}`)}))}returnToGridMode(){var t;null===(t=this._currentDataUnit)||void 0===t||t.clearSelection(),this._crudElement&&this._crudElement.goToView(p.GRID)}async loadAttachmentDataUnit(){try{switch(this.fetcherType){case"AnexoSistema":await this.loadAnexoSistema();break;case"Attach":await this.loadAttach();break;default:this._currentFetcher=this.fetcher,this._currentDataUnit=this.dataUnit,this._currentDataUnitBuilder=this.dataUnitBuilder}}catch(t){throw new Error("There was an error while creating the data unit")}}async loadAnexoSistema(){var t,i,e;this._currentDataUnit=(new A).getDataUnit("AnexoSistema","br.com.sankhya.core.v3.anexoSistema"),this._currentFetcher=new b(this.entityName,this.registerKey,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name),this._currentDataUnit.metadata||(await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadMetadata()),this.crudConfig=Object.assign({},D)),this.initDataUnitLoaders(),this._currentDataUnit.addFilterProvider({getFilter:()=>this._currentDataUnitBuilder.getFilters(this.registerKey)}),this._currentDataUnit.addInterceptor({interceptAction:t=>this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit,t,this._crudElement)}),await(null===(e=this._currentDataUnit)||void 0===e?void 0:e.loadData()),this.disableEditFieldsNotInForm()}async loadAttach(){var t,i;this._currentFetcher=new _,this._currentDataUnit=new l(O.IN_MEMORY_DATA_UNIT_NAME),this.initDataUnitLoaders(),this._currentDataUnit.addInterceptor({interceptAction:t=>{var i;return t.type===n.METADATA_LOADED&&(this.crudConfig=Object.assign({},g),null===(i=this._crudElement)||void 0===i||i.updateConfig()),this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit,t,this._crudElement)}}),this._currentDataUnit.metadata||(await(null===(t=this._currentDataUnit)||void 0===t?void 0:t.loadMetadata()),this.crudConfig=Object.assign({},g),await(null===(i=this._currentDataUnit)||void 0===i?void 0:i.loadData(void 0,void 0,!0,this.registerKey)),this.disableEditFieldsNotInForm())}initDataUnitLoaders(){var t,i,e;"AnexoSistema"===this.fetcherType&&(this._currentFetcher=new b(this.entityName,this.registerKey,null===(t=this._currentDataUnit)||void 0===t?void 0:t.name),this._currentDataUnitBuilder=new f(this.entityName,this.getMessage.bind(this)),null===(i=this._currentDataUnitBuilder)||void 0===i||i.initLoaders(this._currentDataUnit,this._currentFetcher,this.returnToGridMode.bind(this))),"Attach"===this.fetcherType&&(this._currentFetcher=new _,this._currentDataUnitBuilder=new P(this.getMessage.bind(this)),null===(e=this._currentDataUnitBuilder)||void 0===e||e.initLoaders(this._currentDataUnit,this._currentFetcher,(async()=>{this.returnToGridMode(),await this._currentDataUnit.loadData(void 0,void 0,!0,this.registerKey)})))}disableEditFieldsNotInForm(){var t;null===(t=this.crudConfig)||void 0===t||t.grid.columns.forEach((t=>{var i;const e=t.name;(null===(i=this.crudConfig)||void 0===i?void 0:i.form.fields.some((t=>t.name===e)))||this._currentDataUnit.disableField(e)}))}async componentWillLoad(){this._application=a.getContextValue("__SNK__APPLICATION__"),await this.initAttach()}componentWillRender(){this.fetcherType||(this.fetcherType="AnexoSistema"),null==this._currentDataUnit&&this.loadAttachmentDataUnit()}async handleOnDataStateChange({detail:t}){"Attach"===this.fetcherType&&(t.insertionMode?this._currentDataUnit.enableField("DESCRICAO"):this._currentDataUnit.disableField("DESCRICAO"),await this._currentDataUnit.loadMetadata())}render(){var t,i;return this._currentDataUnit?e("main",{class:"snk-attach__main"},e("header",{class:"snk-attach__header"},e("snk-simple-bar",{onExit:this.handleBack,messagesBuilder:this.messagesBuilder},e("div",{slot:"rightSlot"},e("ez-button",{class:"ez-button--primary",label:this.getMessage("snkAttach.finish"),onClick:this.handleFinish})))),e("div",{class:"snk-attach__crud-section ez-size-height--full ez-size-width--full ez-flex ez-flex--column"},e("div",{class:"ez-box__container"},e("snk-simple-crud",{ref:t=>this._crudElement=t,dataUnit:this._currentDataUnit,taskbarManager:x(),gridConfig:null===(t=this.crudConfig)||void 0===t?void 0:t.grid,formConfig:null===(i=this.crudConfig)||void 0===i?void 0:i.form,useCancelConfirm:!1,onActionClick:this.handleTaskbarClick,messagesBuilder:this.messagesBuilder,onDataStateChange:this.handleOnDataStateChange.bind(this)},e("div",{slot:"snkSimpleCrudHeader"},e("div",{class:"ez-flex ez-flex--column"},e("span",{class:"ez-title--primary ez-text ez-text--large ez-text--bold ez-padding-bottom--medium"},this.getMessage("snkAttach.title")),e("span",{class:"ez-text ez-text--medium ez-text--secondary"},this.getMessage("snkAttach.description")))))))):null}static get watchers(){return{registerKey:["registerKeyWatcher"]}}};j.style=".snk-attach__header.sc-snk-attach,.snk-attach__crud-section.sc-snk-attach{padding:0 var(--space--lg)}.snk-attach__file-info.sc-snk-attach{padding:var(--space--small);max-width:50%}.snk-attach__main.sc-snk-attach{height:85%}.ez-box__container.sc-snk-attach{height:100%}";export{j as snk_attach}
@@ -1 +1 @@
1
- import{r as t,c as i,h as s,H as e,g as a}from"./p-d2d301a6.js";import{StringUtils as o,ElementIDUtils as n,ApplicationContext as h,JSUtils as r,FloatingManager as d}from"@sankhyalabs/core";import{T as c}from"./p-7e7a7473.js";import"./p-dc7c9047.js";import"./p-af8efd95.js";import{P as l}from"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-6d4f4614.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{d as m}from"./p-b0ef4383.js";import{A as u}from"./p-913a9979.js";import"./p-6dc031de.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";const p=class{constructor(s){t(this,s),this.actionClick=i(this,"actionClick",7),this.configuratorSave=i(this,"configuratorSave",7),this.configuratorCancel=i(this,"configuratorCancel",7),this.formItemsReady=i(this,"formItemsReady",7),this._keyDownHandler=async t=>this.keyDownListener(t),this._viewHistory=[],this._customEditors=new Map,this._customRenders=new Map,this._dataUnit=void 0,this._dataState=void 0,this.attachmentRegisterKey=void 0,this._currentViewMode=m.GRID,this._canEdit=void 0,this._resourceID=void 0,this.configName=void 0,this.filterBarTitle=void 0,this.selectionToastConfig=void 0,this.showActionButtons=!1,this.actionsList=void 0,this.taskbarManager=void 0,this.recordsValidator=void 0,this.statusResolver=void 0,this.multipleSelection=!0,this.presentationMode=l.PRIMARY,this.messagesBuilder=void 0,this.useEnterLikeTab=!1,this.gridLegacyConfigName=void 0,this.filterBarLegacyConfigName=void 0,this.formLegacyConfigName=void 0,this.disablePersonalizedFilter=void 0,this.autoLoad=void 0,this.autoFocus=!0,this.customContainerId=`SNK-CRUD-CUSTOM-CONTAINER-${o.generateUUID()}`}async goToView(t){this.executeAction(t)}async openConfigurator(){var t;null===(t=this._snkConfigurator)||void 0===t||t.open()}async closeConfigurator(){var t;null===(t=this._snkConfigurator)||void 0===t||t.close()}async reloadFilterBar(){var t;null===(t=this._snkGrid)||void 0===t||t.reloadFilterBar()}async getFilterBar(){return await this._snkGrid.getFilterBar()}async addCustomEditor(t,i){if(this._guidesViewer&&this._snkGrid)return this._guidesViewer.addCustomEditor(t,i),void this._snkGrid.addCustomEditor(t,i);const s=new Map(this._customEditors);s.set(t,i),this._customEditors=s}async addGridCustomRender(t,i){if(this._snkGrid)return void this._snkGrid.addGridCustomRender(t,i);const s=new Map(this._customRenders);s.set(t,i),this._customRenders=s}async addCustomValueFormatter(t,i){this._snkGrid.addCustomValueFormatter(t,i)}async removeCustomValueFormatter(t){this._snkGrid.removeCustomValueFormatter(t)}async setFieldProp(t,i,s){await this._guidesViewer.setFieldProp(t,i,s)}currentViewModeWatcher(t){this._viewHistory=[...this._viewHistory.slice(-1),t]}async gridToForm(t=!1){this._backToGrid=!t&&await this._viewStack.getSelectedIndex()===m.GRID,this.setViewMode(m.FORM)}async executeAction(t){return t===c.GRID_MODE?this.setViewMode(m.GRID):t===c.FORM_MODE||t===c.UPDATE?this.gridToForm(t!==c.UPDATE):t===c.CONFIGURATOR?this._snkConfigurator.open():"ATTACH"===t?this.setViewMode(m.ATTACHMENT):void 0}backView(){const t=this._viewHistory.at(-2)||m.GRID;this.setViewMode(t)}setViewMode(t){this._viewStack.show(t),this._currentViewMode=t,t===m.GRID?this._snkGrid.setFocus():t===m.FORM&&this._guidesViewer.setFocus()}openConfig(t){this._snkConfigurator.close(),t===m.GRID?this._snkGrid.showConfig():t===m.FORM&&this._guidesViewer.showFormConfig()}addDataElementID(){n.addIDInfo(this._element,null,{dataUnit:this._dataUnit})}insertionModeHandler(){this.gridToForm()}cancelHandler(){this._backToGrid&&this.setViewMode(m.GRID)}async getAttachmentRegisterKey(){if(this._snkDataUnit)return(await this._snkDataUnit.getSelectedRecordsIDsInfo()).map((({value:t})=>t)).join("_")}setCustomRenders(){if(this._snkGrid)for(const[t,i]of this._customRenders)this._snkGrid.addGridCustomRender(t,i),this._customRenders.delete(t)}setCustomEditors(){if(this._snkGrid&&this._guidesViewer)for(const[t,i]of this._customEditors)this._guidesViewer.addCustomEditor(t,i),this._snkGrid.addCustomEditor(t,i),this._customEditors.delete(t)}componentDidRender(){this.setCustomRenders(),this.setCustomEditors()}componentWillLoad(){this._application=h.getContextValue("__SNK__APPLICATION__");let t=this._element.parentElement;for(this._application.hasAccess(u.UPDATE,this._resourceID).then((t=>this._canEdit=t));t;){if("SNK-DATA-UNIT"===t.tagName.toUpperCase()){this._snkDataUnit=t,this._snkDataUnit.addEventListener("insertionMode",(()=>this.insertionModeHandler())),this._snkDataUnit.addEventListener("cancelEdition",(()=>this.cancelHandler())),this._dataUnit=this._snkDataUnit.dataUnit,this._dataState=this._snkDataUnit.dataState,this._dataUnit?this.initDataUnit():this._snkDataUnit.addEventListener("dataUnitReady",(t=>{this._dataUnit=t.detail,this.initDataUnit()})),this._snkDataUnit.addEventListener("dataStateChange",this.handleDataStateChange.bind(this));break}t=t.parentElement}this.configName||(this.configName=this._application.configName)}componentDidLoad(){this.initKeyboardManager()}disconnectedCallback(){this.removeShortcuts(),window.removeEventListener("keydown",this._keyDownHandler)}async handleDataStateChange(t){var i;this._dataState=t.detail,void 0!==this._dataState.selectedRecord&&(this.attachmentRegisterKey=await this.getAttachmentRegisterKey());const s=await this._snkDataUnit.getFieldsWithRmPrecision();for(const t of s||[]){if(!t)continue;const s=null===(i=this._dataState.rowMetadata)||void 0===i?void 0:i.getProp("rm_precision",t);(s||0===s)&&(await this.setFieldProp(t,"precision",s),await this.setFieldProp(t,"prettyPrecision",s))}}async initKeyboardManager(){var t;const i=await(null===(t=this._application)||void 0===t?void 0:t.getKeyboardManager());if(i){const s=this._dataUnit||await this._snkDataUnit.getDataUnit();async function e(){const t=document.activeElement,i=t==document.body;i||t.blur(),await s.saveData(),i||null==t.setFocus?i||t.focus():t.setFocus()}i.bind("F6",this.toggleView.bind(this),{description:"Alterna entre modo formulário e grade.",element:this._element}).bind("F7",e.bind(this),{description:"Salva os dados.",element:this._element}).bind("ctrl + \\",e.bind(this),{description:"Salva os dados.",element:this._element}).bind("F8",s.addRecord.bind(s),{description:"Adiciona um novo registro.",element:this._element}).bind("F9",s.removeSelectedRecords.bind(s),{description:"Remove o registro selecionado.",element:this._element}).bind("ctrl + F9",s.removeSelectedRecords.bind(s),{description:"Remove o registro selecionado.",element:this._element}).bind("ctrl + .",(()=>0===s.getSelectionInfo().records.length?s.selectFirst():s.nextRecord()),{description:"Avança para o próximo registro.",element:this._element}).bind("ctrl + ,",s.previousRecord.bind(s),{description:"Retorna ao registro anterior.",element:this._element}).bind("F5",(async()=>{const t=await this._viewStack.getSelectedIndex();m.GRID===t&&s.loadData()}),{description:"Atualiza os dados.",element:this._element}).bind("Escape",(()=>{s.isDirty()&&s.cancelEdition()}),{debounceTime:1e3,description:"Cancela uma ação.",element:this._element})}}async removeShortcuts(){var t;const i=await(null===(t=this._application)||void 0===t?void 0:t.getKeyboardManager());i&&i.unbind("F6").unbind("F7").unbind("ctrl + \\").unbind("F8").unbind("F9").unbind("ctrl + F9").unbind("ctrl + .").unbind("ctrl + ,").unbind("F5").unbind("Escape")}async toggleView(){const t=await this._viewStack.getSelectedIndex();this.setViewMode(m.GRID===t?m.FORM:m.GRID)}async initDataUnit(){this.addDataElementID(),this.messagesBuilder||(this.messagesBuilder=this._snkDataUnit.messagesBuilder),null==this._resourceID&&(this._resourceID=this._snkDataUnit.resourceID,null==this._resourceID&&(this._resourceID=await this._application.getResourceID()))}handleConfiguratorEvent(t,i){t.stopImmediatePropagation(),"SAVE"!==i?this.configuratorCancel.emit():this.configuratorSave.emit()}async keyDownListener(t){t.ctrlKey&&null!=t.key&&"F"===t.key.toUpperCase()&&null!=this._element&&(r.isHiddenElement(this._element)||(d.closeAll(),this._currentViewMode===m.GRID?await this._snkGrid.findColumn():await this._guidesViewer.findField(),t.preventDefault()))}connectedCallback(){window.addEventListener("keydown",this._keyDownHandler,{capture:!0})}render(){if(null!=this._resourceID)return this._snkDataUnit.ignoreSaveMessage=this._currentViewMode===m.GRID,s(e,null,s("ez-view-stack",{ref:t=>this._viewStack=t,"data-element-id":"crud"},s("stack-item",null,s("snk-grid",{ref:t=>this._snkGrid=t,filterBarTitle:this.filterBarTitle,"data-element-id":"crud_grid",configName:this.configName,onGridDoubleClick:()=>this.gridToForm(!0),taskbarManager:this.taskbarManager,onActionClick:t=>this.executeAction(t.detail),messagesBuilder:this.messagesBuilder,actionsList:this.actionsList,statusResolver:this.statusResolver,multipleSelection:this.multipleSelection,presentationMode:this.presentationMode,recordsValidator:this.recordsValidator,selectionToastConfig:this.selectionToastConfig,useEnterLikeTab:this.useEnterLikeTab,canEdit:this._canEdit,resourceID:this._resourceID,disablePersonalizedFilter:this.disablePersonalizedFilter,gridLegacyConfigName:this.gridLegacyConfigName,filterBarLegacyConfigName:this.filterBarLegacyConfigName,autoLoad:this.autoLoad,autoFocus:this.autoFocus},s("slot",{name:"GRID_TASKBAR_CUSTOM_ELEMENTS"}),s("slot",{name:"GRID_HEADER_CUSTOM_ELEMENTS"}),s("slot",{name:"SnkGridHeader"}),s("slot",{name:"SnkGridFooter"}),s("slot",{name:"SnkGridTaskBar"}))),s("stack-item",null,s("snk-guides-viewer",{ref:t=>this._guidesViewer=t,entityPath:this._snkDataUnit.entityName,messagesBuilder:this.messagesBuilder,onExit:()=>this.setViewMode(m.GRID),dataState:this._dataState,dataUnit:this._dataUnit,actionsList:this.actionsList,taskbarManager:this.taskbarManager,configName:this.configName,onActionClick:t=>this.executeAction(t.detail),presentationMode:this.presentationMode,"data-element-id":"crud_form",canEdit:this._canEdit,recordsValidator:this.recordsValidator,resourceID:this._resourceID,detailTaskbarCustomContainerId:this.customContainerId,formLegacyConfigName:this.formLegacyConfigName},s("slot",{name:"GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS"}),s("slot",{name:"SnkFormTaskBar"}))),s("stack-item",null,s("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this._snkDataUnit.entityName,onBack:this.backView.bind(this)})),s("snk-configurator",{ref:t=>this._snkConfigurator=t,viewMode:this._currentViewMode,messagesBuilder:this.messagesBuilder,onConfigSelected:t=>this.setViewMode(t.detail),onOpenConfig:t=>this.openConfig(t.detail),showActionButtons:this.showActionButtons,onSave:t=>this.handleConfiguratorEvent(t,"SAVE"),onCancel:t=>this.handleConfiguratorEvent(t,"CANCEL"),resourceID:this._resourceID,customContainerId:this.customContainerId})),s("div",{id:`${this.customContainerId}`},s("slot",{name:"SnkConfigContainerSlot"}),s("slot",{name:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS"}),s("slot",{name:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS"}),s("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))}get _element(){return a(this)}static get watchers(){return{_currentViewMode:["currentViewModeWatcher"]}}};p.style=".sc-snk-crud-h{display:flex;flex-direction:column;height:100%;width:100%}";export{p as snk_crud}
1
+ import{r as t,c as i,h as s,H as e,g as a}from"./p-d2d301a6.js";import{StringUtils as o,ElementIDUtils as n,ApplicationContext as h,JSUtils as r,FloatingManager as d}from"@sankhyalabs/core";import{T as c}from"./p-7e7a7473.js";import"./p-dc7c9047.js";import"./p-af8efd95.js";import{P as l}from"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-fe79f83a.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{d as m}from"./p-b0ef4383.js";import{A as u}from"./p-913a9979.js";import"./p-6dc031de.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";const p=class{constructor(s){t(this,s),this.actionClick=i(this,"actionClick",7),this.configuratorSave=i(this,"configuratorSave",7),this.configuratorCancel=i(this,"configuratorCancel",7),this.formItemsReady=i(this,"formItemsReady",7),this._keyDownHandler=async t=>this.keyDownListener(t),this._viewHistory=[],this._customEditors=new Map,this._customRenders=new Map,this._dataUnit=void 0,this._dataState=void 0,this.attachmentRegisterKey=void 0,this._currentViewMode=m.GRID,this._canEdit=void 0,this._resourceID=void 0,this.configName=void 0,this.filterBarTitle=void 0,this.selectionToastConfig=void 0,this.showActionButtons=!1,this.actionsList=void 0,this.taskbarManager=void 0,this.recordsValidator=void 0,this.statusResolver=void 0,this.multipleSelection=!0,this.presentationMode=l.PRIMARY,this.messagesBuilder=void 0,this.useEnterLikeTab=!1,this.gridLegacyConfigName=void 0,this.filterBarLegacyConfigName=void 0,this.formLegacyConfigName=void 0,this.disablePersonalizedFilter=void 0,this.autoLoad=void 0,this.autoFocus=!0,this.customContainerId=`SNK-CRUD-CUSTOM-CONTAINER-${o.generateUUID()}`}async goToView(t){this.executeAction(t)}async openConfigurator(){var t;null===(t=this._snkConfigurator)||void 0===t||t.open()}async closeConfigurator(){var t;null===(t=this._snkConfigurator)||void 0===t||t.close()}async reloadFilterBar(){var t;null===(t=this._snkGrid)||void 0===t||t.reloadFilterBar()}async getFilterBar(){return await this._snkGrid.getFilterBar()}async addCustomEditor(t,i){if(this._guidesViewer&&this._snkGrid)return this._guidesViewer.addCustomEditor(t,i),void this._snkGrid.addCustomEditor(t,i);const s=new Map(this._customEditors);s.set(t,i),this._customEditors=s}async addGridCustomRender(t,i){if(this._snkGrid)return void this._snkGrid.addGridCustomRender(t,i);const s=new Map(this._customRenders);s.set(t,i),this._customRenders=s}async addCustomValueFormatter(t,i){this._snkGrid.addCustomValueFormatter(t,i)}async removeCustomValueFormatter(t){this._snkGrid.removeCustomValueFormatter(t)}async setFieldProp(t,i,s){await this._guidesViewer.setFieldProp(t,i,s)}currentViewModeWatcher(t){this._viewHistory=[...this._viewHistory.slice(-1),t]}async gridToForm(t=!1){this._backToGrid=!t&&await this._viewStack.getSelectedIndex()===m.GRID,this.setViewMode(m.FORM)}async executeAction(t){return t===c.GRID_MODE?this.setViewMode(m.GRID):t===c.FORM_MODE||t===c.UPDATE?this.gridToForm(t!==c.UPDATE):t===c.CONFIGURATOR?this._snkConfigurator.open():"ATTACH"===t?this.setViewMode(m.ATTACHMENT):void 0}backView(){const t=this._viewHistory.at(-2)||m.GRID;this.setViewMode(t)}setViewMode(t){this._viewStack.show(t),this._currentViewMode=t,t===m.GRID?this._snkGrid.setFocus():t===m.FORM&&this._guidesViewer.setFocus()}openConfig(t){this._snkConfigurator.close(),t===m.GRID?this._snkGrid.showConfig():t===m.FORM&&this._guidesViewer.showFormConfig()}addDataElementID(){n.addIDInfo(this._element,null,{dataUnit:this._dataUnit})}insertionModeHandler(){this.gridToForm()}cancelHandler(){this._backToGrid&&this.setViewMode(m.GRID)}async getAttachmentRegisterKey(){if(this._snkDataUnit)return(await this._snkDataUnit.getSelectedRecordsIDsInfo()).map((({value:t})=>t)).join("_")}setCustomRenders(){if(this._snkGrid)for(const[t,i]of this._customRenders)this._snkGrid.addGridCustomRender(t,i),this._customRenders.delete(t)}setCustomEditors(){if(this._snkGrid&&this._guidesViewer)for(const[t,i]of this._customEditors)this._guidesViewer.addCustomEditor(t,i),this._snkGrid.addCustomEditor(t,i),this._customEditors.delete(t)}componentDidRender(){this.setCustomRenders(),this.setCustomEditors()}componentWillLoad(){this._application=h.getContextValue("__SNK__APPLICATION__");let t=this._element.parentElement;for(this._application.hasAccess(u.UPDATE,this._resourceID).then((t=>this._canEdit=t));t;){if("SNK-DATA-UNIT"===t.tagName.toUpperCase()){this._snkDataUnit=t,this._snkDataUnit.addEventListener("insertionMode",(()=>this.insertionModeHandler())),this._snkDataUnit.addEventListener("cancelEdition",(()=>this.cancelHandler())),this._dataUnit=this._snkDataUnit.dataUnit,this._dataState=this._snkDataUnit.dataState,this._dataUnit?this.initDataUnit():this._snkDataUnit.addEventListener("dataUnitReady",(t=>{this._dataUnit=t.detail,this.initDataUnit()})),this._snkDataUnit.addEventListener("dataStateChange",this.handleDataStateChange.bind(this));break}t=t.parentElement}this.configName||(this.configName=this._application.configName)}componentDidLoad(){this.initKeyboardManager()}disconnectedCallback(){this.removeShortcuts(),window.removeEventListener("keydown",this._keyDownHandler)}async handleDataStateChange(t){var i;this._dataState=t.detail,void 0!==this._dataState.selectedRecord&&(this.attachmentRegisterKey=await this.getAttachmentRegisterKey());const s=await this._snkDataUnit.getFieldsWithRmPrecision();for(const t of s||[]){if(!t)continue;const s=null===(i=this._dataState.rowMetadata)||void 0===i?void 0:i.getProp("rm_precision",t);(s||0===s)&&(await this.setFieldProp(t,"precision",s),await this.setFieldProp(t,"prettyPrecision",s))}}async initKeyboardManager(){var t;const i=await(null===(t=this._application)||void 0===t?void 0:t.getKeyboardManager());if(i){const s=this._dataUnit||await this._snkDataUnit.getDataUnit();async function e(){const t=document.activeElement,i=t==document.body;i||t.blur(),await s.saveData(),i||null==t.setFocus?i||t.focus():t.setFocus()}i.bind("F6",this.toggleView.bind(this),{description:"Alterna entre modo formulário e grade.",element:this._element}).bind("F7",e.bind(this),{description:"Salva os dados.",element:this._element}).bind("ctrl + \\",e.bind(this),{description:"Salva os dados.",element:this._element}).bind("F8",s.addRecord.bind(s),{description:"Adiciona um novo registro.",element:this._element}).bind("F9",s.removeSelectedRecords.bind(s),{description:"Remove o registro selecionado.",element:this._element}).bind("ctrl + F9",s.removeSelectedRecords.bind(s),{description:"Remove o registro selecionado.",element:this._element}).bind("ctrl + .",(()=>0===s.getSelectionInfo().records.length?s.selectFirst():s.nextRecord()),{description:"Avança para o próximo registro.",element:this._element}).bind("ctrl + ,",s.previousRecord.bind(s),{description:"Retorna ao registro anterior.",element:this._element}).bind("F5",(async()=>{const t=await this._viewStack.getSelectedIndex();m.GRID===t&&s.loadData()}),{description:"Atualiza os dados.",element:this._element}).bind("Escape",(()=>{s.isDirty()&&s.cancelEdition()}),{debounceTime:1e3,description:"Cancela uma ação.",element:this._element})}}async removeShortcuts(){var t;const i=await(null===(t=this._application)||void 0===t?void 0:t.getKeyboardManager());i&&i.unbind("F6").unbind("F7").unbind("ctrl + \\").unbind("F8").unbind("F9").unbind("ctrl + F9").unbind("ctrl + .").unbind("ctrl + ,").unbind("F5").unbind("Escape")}async toggleView(){const t=await this._viewStack.getSelectedIndex();this.setViewMode(m.GRID===t?m.FORM:m.GRID)}async initDataUnit(){this.addDataElementID(),this.messagesBuilder||(this.messagesBuilder=this._snkDataUnit.messagesBuilder),null==this._resourceID&&(this._resourceID=this._snkDataUnit.resourceID,null==this._resourceID&&(this._resourceID=await this._application.getResourceID()))}handleConfiguratorEvent(t,i){t.stopImmediatePropagation(),"SAVE"!==i?this.configuratorCancel.emit():this.configuratorSave.emit()}async keyDownListener(t){t.ctrlKey&&null!=t.key&&"F"===t.key.toUpperCase()&&null!=this._element&&(r.isHiddenElement(this._element)||(d.closeAll(),this._currentViewMode===m.GRID?await this._snkGrid.findColumn():await this._guidesViewer.findField(),t.preventDefault()))}connectedCallback(){window.addEventListener("keydown",this._keyDownHandler,{capture:!0})}render(){if(null!=this._resourceID)return this._snkDataUnit.ignoreSaveMessage=this._currentViewMode===m.GRID,s(e,null,s("ez-view-stack",{ref:t=>this._viewStack=t,"data-element-id":"crud"},s("stack-item",null,s("snk-grid",{ref:t=>this._snkGrid=t,filterBarTitle:this.filterBarTitle,"data-element-id":"crud_grid",configName:this.configName,onGridDoubleClick:()=>this.gridToForm(!0),taskbarManager:this.taskbarManager,onActionClick:t=>this.executeAction(t.detail),messagesBuilder:this.messagesBuilder,actionsList:this.actionsList,statusResolver:this.statusResolver,multipleSelection:this.multipleSelection,presentationMode:this.presentationMode,recordsValidator:this.recordsValidator,selectionToastConfig:this.selectionToastConfig,useEnterLikeTab:this.useEnterLikeTab,canEdit:this._canEdit,resourceID:this._resourceID,disablePersonalizedFilter:this.disablePersonalizedFilter,gridLegacyConfigName:this.gridLegacyConfigName,filterBarLegacyConfigName:this.filterBarLegacyConfigName,autoLoad:this.autoLoad,autoFocus:this.autoFocus},s("slot",{name:"GRID_TASKBAR_CUSTOM_ELEMENTS"}),s("slot",{name:"GRID_HEADER_CUSTOM_ELEMENTS"}),s("slot",{name:"SnkGridHeader"}),s("slot",{name:"SnkGridFooter"}),s("slot",{name:"SnkGridTaskBar"}))),s("stack-item",null,s("snk-guides-viewer",{ref:t=>this._guidesViewer=t,entityPath:this._snkDataUnit.entityName,messagesBuilder:this.messagesBuilder,onExit:()=>this.setViewMode(m.GRID),dataState:this._dataState,dataUnit:this._dataUnit,actionsList:this.actionsList,taskbarManager:this.taskbarManager,configName:this.configName,onActionClick:t=>this.executeAction(t.detail),presentationMode:this.presentationMode,"data-element-id":"crud_form",canEdit:this._canEdit,recordsValidator:this.recordsValidator,resourceID:this._resourceID,detailTaskbarCustomContainerId:this.customContainerId,formLegacyConfigName:this.formLegacyConfigName},s("slot",{name:"GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS"}),s("slot",{name:"SnkFormTaskBar"}))),s("stack-item",null,s("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this._snkDataUnit.entityName,onBack:this.backView.bind(this)})),s("snk-configurator",{ref:t=>this._snkConfigurator=t,viewMode:this._currentViewMode,messagesBuilder:this.messagesBuilder,onConfigSelected:t=>this.setViewMode(t.detail),onOpenConfig:t=>this.openConfig(t.detail),showActionButtons:this.showActionButtons,onSave:t=>this.handleConfiguratorEvent(t,"SAVE"),onCancel:t=>this.handleConfiguratorEvent(t,"CANCEL"),resourceID:this._resourceID,customContainerId:this.customContainerId})),s("div",{id:`${this.customContainerId}`},s("slot",{name:"SnkConfigContainerSlot"}),s("slot",{name:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS"}),s("slot",{name:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS"}),s("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))}get _element(){return a(this)}static get watchers(){return{_currentViewMode:["currentViewModeWatcher"]}}};p.style=".sc-snk-crud-h{display:flex;flex-direction:column;height:100%;width:100%}";export{p as snk_crud}
@@ -1,4 +1,4 @@
1
- import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,StringUtils as r,ObjectUtils as o,WaitingChangeException as a,WarningException as c,ErrorException as h,KeyboardManager as l,OnboardingUtils as u,DependencyType as p,ArrayUtils as d,SearchUtils as w,ElementIDUtils as m,ApplicationContext as f,DataType as y,ErrorTracking as P}from"@sankhyalabs/core";import{ApplicationUtils as v}from"@sankhyalabs/ezui/dist/collection/utils";import{C as g}from"./p-aff76a53.js";import{d as _,D as A,U as I}from"./p-dc7c9047.js";import{A as S,a as C}from"./p-913a9979.js";import{D as N}from"./p-6d4f4614.js";import{P as b}from"./p-af8efd95.js";import{S as L}from"./p-7a337364.js";import"./p-df5451c7.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class D{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const T=k;function k(t,s){const e=E();return(k=function(t){return e[t-=378]})(t,s)}function E(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return(E=function(){return t})()}!function(){const t=k,s=E();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;s.push(s.shift())}catch(t){s.push(s.shift())}}();class O{[T(397)](t){const s=T;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new U("S"===t[s(402)]||!0===t[s(402)]);return Array[s(394)](t[s(391)])&&t[s(391)][s(385)]((t=>e.putAccess(t[s(382)],String(t.status)==s(398)))),e}}class U{constructor(t){const s=T;this.isSup=t,this[s(384)]={}}[T(378)](t,s){this[T(384)][t]=s}[T(393)](t){const s=T;if(this[s(402)])return!0;let e=!0;return this[s(384)][s(380)](t)&&(e=this.actions[t]),e}isUserSup(){return this.isSup}}class j{constructor(){this._embeddedParams=new Map,this.templateByQuery=new Map;try{if(null!=window.MGE_PARAMS){atob(window.MGE_PARAMS).split("__;__").forEach((t=>{const[s,e]=t.split("__=__");this._embeddedParams.set(s,e)}))}}catch(t){console.error("Problemas ao obter parâmetros embarcados"),console.error(t)}this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",_.gql`query($name: String!) {
1
+ import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,StringUtils as r,ObjectUtils as o,WaitingChangeException as a,WarningException as c,ErrorException as h,KeyboardManager as l,OnboardingUtils as u,DependencyType as p,ArrayUtils as d,SearchUtils as w,ElementIDUtils as m,ApplicationContext as f,DataType as y,ErrorTracking as P}from"@sankhyalabs/core";import{ApplicationUtils as v}from"@sankhyalabs/ezui/dist/collection/utils";import{C as g}from"./p-aff76a53.js";import{d as _,D as A,U as I}from"./p-dc7c9047.js";import{A as S,a as C}from"./p-913a9979.js";import{D as N}from"./p-fe79f83a.js";import{P as b}from"./p-af8efd95.js";import{S as L}from"./p-7a337364.js";import"./p-df5451c7.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class D{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const T=k;function k(t,s){const e=E();return(k=function(t){return e[t-=378]})(t,s)}function E(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return(E=function(){return t})()}!function(){const t=k,s=E();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;s.push(s.shift())}catch(t){s.push(s.shift())}}();class O{[T(397)](t){const s=T;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new U("S"===t[s(402)]||!0===t[s(402)]);return Array[s(394)](t[s(391)])&&t[s(391)][s(385)]((t=>e.putAccess(t[s(382)],String(t.status)==s(398)))),e}}class U{constructor(t){const s=T;this.isSup=t,this[s(384)]={}}[T(378)](t,s){this[T(384)][t]=s}[T(393)](t){const s=T;if(this[s(402)])return!0;let e=!0;return this[s(384)][s(380)](t)&&(e=this.actions[t]),e}isUserSup(){return this.isSup}}class j{constructor(){this._embeddedParams=new Map,this.templateByQuery=new Map;try{if(null!=window.MGE_PARAMS){atob(window.MGE_PARAMS).split("__;__").forEach((t=>{const[s,e]=t.split("__=__");this._embeddedParams.set(s,e)}))}}catch(t){console.error("Problemas ao obter parâmetros embarcados"),console.error(t)}this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",_.gql`query($name: String!) {
2
2
  $queryAlias$: fetchResource(name: $name){
3
3
  name
4
4
  resource
@@ -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,UserInterface as n,DataType as l,ElementIDUtils as a}from"@sankhyalabs/core";import{ApplicationUtils as d,DialogType as h}from"@sankhyalabs/ezui/dist/collection/utils";import{D as c,a as p,b as u}from"./p-30cf616e.js";import{R as m}from"./p-b0ef4383.js";import{D as v}from"./p-dc7c9047.js";import{S as x}from"./p-c7cbad38.js";import"./p-af8efd95.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-6d4f4614.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import"./p-8d884fab.js";import"./p-7a337364.js";import"./p-9863d682.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class f{constructor(t,e){this._selectedNumber=0,this._getMessage=t,this._selectedNumber=e}setExportOption(t,e){const i=this.getExportGroupName();t===c.EXPORT_TO_PDF&&e.push(this.getExportToPDF(i)),t===c.EXPORT_TO_XLS&&e.push(this.getExportToXLS(i)),this.setExportCurrentPage(t,e),this._selectedNumber>0&&this.setExportAllRecords(t,e),this.setExportByEmail(t,e)}setExportCurrentPage(t,e){var i;const s=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS];if(t===c.EXPORT_CURRENT_PAGE&&e.push(this.getCurrentPage()),s.includes(t)){let s=e.find((t=>t.id===c.EXPORT_CURRENT_PAGE));null==s&&(e.push(this.getCurrentPage()),s=e.find((t=>t.id===c.EXPORT_CURRENT_PAGE))),(null===(i=null==s?void 0:s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===c.EXPORT_PAGE_TO_PDF&&s.children.push(this.getExportPageToPDF()),t===c.EXPORT_PAGE_TO_XLS&&s.children.push(this.getExportPageToXLS())}}setExportAllRecords(t,e){var i;const s=[c.EXPORT_ALL_RECORDS_TO_PDF,c.EXPORT_ALL_RECORDS_TO_XLS];if(t===c.EXPORT_ALL_RECORDS&&e.push(this.getAllRecords()),s.includes(t)){let s=e.find((t=>t.id===c.EXPORT_ALL_RECORDS));null==s&&(e.push(this.getAllRecords()),s=e.find((t=>t.id===c.EXPORT_ALL_RECORDS))),(null===(i=s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===c.EXPORT_ALL_RECORDS_TO_PDF&&s.children.push(this.getExportAllRecordsToPDF()),t===c.EXPORT_ALL_RECORDS_TO_XLS&&s.children.push(this.getExportAllRecordsToXLS())}}setExportByEmail(t,e){t===c.EXPORT_BY_EMAIL&&e.push(this.getExportByEmail())}getExportToPDF(t){return{id:c.EXPORT_TO_PDF,label:"PDF (.pdf)",group:t}}getExportToXLS(t){return{id:c.EXPORT_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`,group:t}}getCurrentPage(){return{id:c.EXPORT_CURRENT_PAGE,label:this._getMessage("snkDataExporter.label.currentPage"),group:this._getMessage("snkDataExporter.group.custom")}}getAllRecords(){return{id:c.EXPORT_ALL_RECORDS,label:this._getMessage("snkDataExporter.label.allRecords"),group:this._getMessage("snkDataExporter.group.custom")}}getExportPageToPDF(){return{id:c.EXPORT_PAGE_TO_PDF,label:"PDF (.pdf)"}}getExportPageToXLS(){return{id:c.EXPORT_PAGE_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportAllRecordsToPDF(){return{id:c.EXPORT_ALL_RECORDS_TO_PDF,label:"PDF (.pdf)"}}getExportAllRecordsToXLS(){return{id:c.EXPORT_ALL_RECORDS_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportByEmail(){return{id:c.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 g(t){const e=[];let i=0;for(const s of t){if(i+=s.width,i>=800)break;e.push(s)}return e}function b(t){return Object.keys(c).find((e=>c[e]===t))}class E{constructor(t){this._provider=t}async getParsedColumns(){return g(await this._provider.getColumnsMetadata())}async getParams(t){var e,i,s,o,r,n;const l=null===(i=(e=this._provider).getFilters)||void 0===i?void 0:i.call(e),a=[p.EXPORT_TO_PDF,p.EXPORT_PAGE_TO_PDF,p.EXPORT_PDF_TO_EMAIL,p.EXPORT_ALL_RECORDS_TO_PDF].includes(b(null==t?void 0:t.exportOption))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),d=null===(o=(s=this._provider).getOrders)||void 0===o?void 0:o.call(s),h=null===(n=(r=this._provider).getResourceURI)||void 0===n?void 0:n.call(r),u=this._provider.getSelectedIDs(),m=t.exportOption,v=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS];delete t.exportOption;let x=Object.assign({filters:l,columns:a,sort:d,resourceURI:h,selectedIDs:u.slice(0,this._provider.getExportLimit())},t);if(v.includes(m)||"page"==t.type){const t=this._provider.getOffset(),e=this._provider.getPageSize();x=Object.assign(Object.assign({},x),{offset:t,limit:e,selectedIDs:[]})}else"all"==t.type&&(x=Object.assign(Object.assign({},x),{offset:0,limit:this._provider.getExportLimit(),selectedIDs:[]}));return Promise.resolve(x)}async executeExport(t){const e=await this.getParams(t),{methodName:i}=e,s=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}(e,["methodName"]),n=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.${i}`,l={serviceName:n,requestBody:s};return new Promise(((t,e)=>{v.get().callServiceBroker(n,r.objectToString(l)).then((e=>t(this.getFormatResponse(e)))).catch((t=>e(t)))}))}getFormatResponse(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)}}class w{constructor(t){this._provider=t}async getParsedColumns(){return g(await this._provider.getColumnsMetadata())}async executeExport(t){const{methodName:e,titleGrid:i}=t,s=await this._provider.getRecords(),o=[p.EXPORT_TO_PDF,p.EXPORT_PAGE_TO_PDF,p.EXPORT_PDF_TO_EMAIL,p.EXPORT_ALL_RECORDS_TO_PDF].includes(b(null==t?void 0:t.exportOption))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),[r,n]=this.getExecutor(e),l={serviceName:r,requestBody:{grid:{titleGrid:i,columns:this.buildColumnsObject(o),rows:this.buildRowsObject(o,s),customOptions:{xlsxExtension:!1}}}};return new Promise(((t,e)=>{v.get().callServiceBroker(r,l).then((e=>t(n(e)))).catch((t=>e(t)))}))}getExecutor(t){return"exportToPDF"===t?["GridPDFBuilderSP.buildPDFFromJson",t=>({fileSessionKey:t.chavePDF.valor,canPrint:"S"===t.permiteImprimir.valor,canExport:"S"===t.permiteExportar.valor,canSendEmail:"S"===t.canSendEmail.valor,useAppPrint:!0})]:["GridXLSBuilderSP.buildXLSFromJson",t=>({fileSessionKey:t.chaveXLS.valor,canPrint:!1,canExport:!1,useAppPrint:!1,canSendEmail:!1})]}buildColumnsObject(t){return{column:t.map(((t,e)=>{const{label:i,id:s,width:o,userInterface:r}=t;return Object.assign({index:e+1,id:s,label:i,width:o,presentationType:"P"},k[r]||{type:"S",align:"left"})}))}}buildRowsObject(t,e){return{row:e.map((e=>{const i={};return t.forEach(((t,s)=>i["c"+(s+1)]={$:this.formatValue(e,t)})),i}))}}formatValue(t,e){return null!=this._provider.formatValue?this._provider.formatValue(t,e):t[e.id]||""}}const k={[n.DATE]:{type:"D",align:"center"},[n.DATETIME]:{type:"H",align:"center"},[n.TIME]:{type:"I",align:"right"},[n.ELAPSEDTIME]:{type:"I",align:"right"},[n.DECIMALNUMBER]:{type:"F",align:"right"},[n.INTEGERNUMBER]:{type:"I",align:"right"},[n.SEARCH]:{type:"S",align:"right"}},D=class{constructor(e){t(this,e),this._selectedNumber=0,this._customPrefix="$custom$",this._releasedToExport=[c.EXPORT_TO_PDF,c.EXPORT_TO_XLS,c.EXPORT_BY_EMAIL,c.EXPORT_PDF_TO_EMAIL,c.EXPORT_XLS_TO_EMAIL,c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS,c.EXPORT_ALL_RECORDS_TO_PDF,c.EXPORT_ALL_RECORDS_TO_XLS],this._items=[],this._showDropdown=!1,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=u[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:u.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,titleGrid:this._appLabel},(()=>{this._snkEmailSender.close(),d.info(this.getMessage("snkDataExporter.message.emailSuccess"),{iconName:"check"})}))}})}getMessage(t,e){if(null==this.messagesBuilder){const t=x.getNearestInstance(this._element);t&&(this.messagesBuilder=t.messagesBuilder)}return this.messagesBuilder.getMessage(t,e)}positionDropdown(){var t;const e=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();null!=e&&null!=this._dropdownParent&&(this._dropdownParent.style.top=e.y+e.height+5+"px",this._dropdownParent.style.left=e.x+"px")}closeDropdown(t){const e=null==t?void 0:t.target;null!=e&&(e.closest(".snk-data-exporter")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}controlDropdown(){this._showDropdown=!this._showDropdown}async resolveExporter(t,e){null!=this.provider&&null!=t&&null!=e&&this.getExporterStrategy().executeExport(t).then((t=>e(t))).catch((t=>{console.error(t);let{title:e,message:i,statusMessage:s}=t||{};d.error(e||this.getMessage("snkDataExporter.message.exportError"),s||i||this.getMessage("snkDataExporter.message.unknownFailure"))}))}getExporterStrategy(){return null==this.provider.getRecords?new E(this.provider):new w(this.provider)}getOptionKey(t){return Object.keys(c).find((e=>c[e]===t))}getExportType(t){return t===c.EXPORT_ALL_RECORDS_TO_PDF||t===c.EXPORT_ALL_RECORDS_TO_XLS?"all":t===c.EXPORT_PAGE_TO_PDF||t===c.EXPORT_PAGE_TO_XLS?"page":"selection"}async dispatchExporter(t){var e,i,s;const r=this.getOptionKey(t),n=null!==(e=p[r])&&void 0!==e?e:p.EXPORT_TO_PDF,l=p[r]===p.EXPORT_TO_XLS,a={methodName:c[`EXPORT_TO_${n}`],fileName:this._appLabel,titleGrid:this._appLabel,exportOption:t,limit:null===(s=null===(i=this.provider)||void 0===i?void 0:i.getExportLimit)||void 0===s?void 0:s.call(i),type:this.getExportType(t)};await this.resolveExporter(a,(t=>{t.canExport||n===p.EXPORT_TO_PDF?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":""}`),d.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:n,isDownload:l})):d.error(this.getMessage("snkDataExporter.title.permission"),this.getMessage("snkDataExporter.message.exportPermission"))}))}async processExporter(t){var e,i,s,o,r,n,l;const a=null==t?void 0:t.detail,p=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS],u=null===(e=null==a?void 0:a.id)||void 0===e?void 0:e.includes(this._customPrefix);if((null==a?void 0:a.id)===c.EXPORT_CURRENT_PAGE)return;const m=null===(i=this.provider)||void 0===i?void 0:i.getSelectedIDs(),v=null===(s=this.provider)||void 0===s?void 0:s.getTotalRecords(),x=null===(r=null===(o=this.provider)||void 0===o?void 0:o.getPageSize)||void 0===r?void 0:r.call(o),f=null===(l=null===(n=this.provider)||void 0===n?void 0:n.getExportLimit)||void 0===l?void 0:l.call(n);let g=!1;if(p.includes(null==a?void 0:a.id)&&x<=f||u?g=!1:(null==m?void 0:m.length)?g=m.length>f:v>f&&(g=!0),g){const t=f.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 d.confirm(e.title,e.description,null,h.WARN,{labelCancel:e.cancel,labelConfirm:e.confirm}))return}if(u)return this.openPersonalizedReports(a.id),void(this._showDropdown=!1);this.getFilteredReleasedToExport().includes(null==a?void 0:a.id)&&(a.id===c.EXPORT_BY_EMAIL?this.exportByEmail():this.dispatchExporter(a.id),this._showDropdown=!1)}getFilteredReleasedToExport(){var t,e;if(null==this.provider)return this._releasedToExport;const i=null===(e=(t=this.provider).getHiddenOptions)||void 0===e?void 0:e.call(t);return null==i?this._releasedToExport:this._releasedToExport.filter((t=>!i.includes(t)))}loadItems(){const t=[];this.getFilteredReleasedToExport().forEach((e=>{var i;null===(i=this._itemBuilder)||void 0===i||i.setExportOption(e,t)})),this.loadPersonalizedItems(t)}async loadPersonalizedItems(t){var e,i;const s=null===(i=null===(e=this.provider)||void 0===e?void 0:e.getRecordID)||void 0===i?void 0:i.call(e);if(null==s)return void(this._items=t);const n=await function(t){const e=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.getPersonalizedReports`,i={serviceName:e,requestBody:t};return new Promise(((t,s)=>v.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:s});null==n||n.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,i;const s=[],o=(null==t?void 0:t.replace(this._customPrefix,""))||"";null===(i=null===(e=this.provider)||void 0===e?void 0:e.getSelectedIDs)||void 0===i||i.call(e).forEach((({name:t,type:e,value:i},o)=>{const r={fields:[]};0===o&&(s[`PK_${t}`]={type:this.parseDataType(e),value:i},s.pks=[]);const n={nome:`PK_${t}`,tipo:this.parseDataType(e),valor:i};r.fields.push(n),s.pks.push(r)})),this._application.openApp(`${m}${o}`,s)}parseDataType(t){switch(t){case l.NUMBER:return"I";case l.DATE:return"D";default:return"S"}}loadDropdown(){var t;this._selectedNumber=(null===(t=this.provider)||void 0===t?void 0:t.getSelectedNumber())||0,this._itemBuilder=new f(this.getMessage.bind(this),this._selectedNumber),this.loadItems()}getElementID(t){return{[a.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:a.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&&(a.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)}};D.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{D 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,UserInterface as n,DataType as l,ElementIDUtils as a}from"@sankhyalabs/core";import{ApplicationUtils as d,DialogType as h}from"@sankhyalabs/ezui/dist/collection/utils";import{D as c,a as p,b as u}from"./p-30cf616e.js";import{R as m}from"./p-b0ef4383.js";import{D as v}from"./p-dc7c9047.js";import{S as x}from"./p-fcac4dfc.js";import"./p-af8efd95.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-fe79f83a.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import"./p-8d884fab.js";import"./p-7a337364.js";import"./p-9863d682.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class f{constructor(t,e){this._selectedNumber=0,this._getMessage=t,this._selectedNumber=e}setExportOption(t,e){const i=this.getExportGroupName();t===c.EXPORT_TO_PDF&&e.push(this.getExportToPDF(i)),t===c.EXPORT_TO_XLS&&e.push(this.getExportToXLS(i)),this.setExportCurrentPage(t,e),this._selectedNumber>0&&this.setExportAllRecords(t,e),this.setExportByEmail(t,e)}setExportCurrentPage(t,e){var i;const s=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS];if(t===c.EXPORT_CURRENT_PAGE&&e.push(this.getCurrentPage()),s.includes(t)){let s=e.find((t=>t.id===c.EXPORT_CURRENT_PAGE));null==s&&(e.push(this.getCurrentPage()),s=e.find((t=>t.id===c.EXPORT_CURRENT_PAGE))),(null===(i=null==s?void 0:s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===c.EXPORT_PAGE_TO_PDF&&s.children.push(this.getExportPageToPDF()),t===c.EXPORT_PAGE_TO_XLS&&s.children.push(this.getExportPageToXLS())}}setExportAllRecords(t,e){var i;const s=[c.EXPORT_ALL_RECORDS_TO_PDF,c.EXPORT_ALL_RECORDS_TO_XLS];if(t===c.EXPORT_ALL_RECORDS&&e.push(this.getAllRecords()),s.includes(t)){let s=e.find((t=>t.id===c.EXPORT_ALL_RECORDS));null==s&&(e.push(this.getAllRecords()),s=e.find((t=>t.id===c.EXPORT_ALL_RECORDS))),(null===(i=s.children)||void 0===i?void 0:i.length)||(s.children=[]),t===c.EXPORT_ALL_RECORDS_TO_PDF&&s.children.push(this.getExportAllRecordsToPDF()),t===c.EXPORT_ALL_RECORDS_TO_XLS&&s.children.push(this.getExportAllRecordsToXLS())}}setExportByEmail(t,e){t===c.EXPORT_BY_EMAIL&&e.push(this.getExportByEmail())}getExportToPDF(t){return{id:c.EXPORT_TO_PDF,label:"PDF (.pdf)",group:t}}getExportToXLS(t){return{id:c.EXPORT_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`,group:t}}getCurrentPage(){return{id:c.EXPORT_CURRENT_PAGE,label:this._getMessage("snkDataExporter.label.currentPage"),group:this._getMessage("snkDataExporter.group.custom")}}getAllRecords(){return{id:c.EXPORT_ALL_RECORDS,label:this._getMessage("snkDataExporter.label.allRecords"),group:this._getMessage("snkDataExporter.group.custom")}}getExportPageToPDF(){return{id:c.EXPORT_PAGE_TO_PDF,label:"PDF (.pdf)"}}getExportPageToXLS(){return{id:c.EXPORT_PAGE_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportAllRecordsToPDF(){return{id:c.EXPORT_ALL_RECORDS_TO_PDF,label:"PDF (.pdf)"}}getExportAllRecordsToXLS(){return{id:c.EXPORT_ALL_RECORDS_TO_XLS,label:`${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`}}getExportByEmail(){return{id:c.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 g(t){const e=[];let i=0;for(const s of t){if(i+=s.width,i>=800)break;e.push(s)}return e}function E(t){return Object.keys(c).find((e=>c[e]===t))}class b{constructor(t){this._provider=t}async getParsedColumns(){return g(await this._provider.getColumnsMetadata())}async getParams(t){var e,i,s,o,r,n;const l=null===(i=(e=this._provider).getFilters)||void 0===i?void 0:i.call(e),a=[p.EXPORT_TO_PDF,p.EXPORT_PAGE_TO_PDF,p.EXPORT_PDF_TO_EMAIL,p.EXPORT_ALL_RECORDS_TO_PDF].includes(E(null==t?void 0:t.exportOption))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),d=null===(o=(s=this._provider).getOrders)||void 0===o?void 0:o.call(s),h=null===(n=(r=this._provider).getResourceURI)||void 0===n?void 0:n.call(r),u=this._provider.getSelectedIDs(),m=t.exportOption,v=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS];delete t.exportOption;let x=Object.assign({filters:l,columns:a,sort:d,resourceURI:h,selectedIDs:u.slice(0,this._provider.getExportLimit())},t);if(v.includes(m)||"page"==t.type){const t=this._provider.getOffset(),e=this._provider.getPageSize();x=Object.assign(Object.assign({},x),{offset:t,limit:e,selectedIDs:[]})}else"all"==t.type&&(x=Object.assign(Object.assign({},x),{offset:0,limit:this._provider.getExportLimit(),selectedIDs:[]}));return Promise.resolve(x)}async executeExport(t){const e=await this.getParams(t),{methodName:i}=e,s=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}(e,["methodName"]),n=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.${i}`,l={serviceName:n,requestBody:s};return new Promise(((t,e)=>{v.get().callServiceBroker(n,r.objectToString(l)).then((e=>t(this.getFormatResponse(e)))).catch((t=>e(t)))}))}getFormatResponse(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)}}class w{constructor(t){this._provider=t}async getParsedColumns(){return g(await this._provider.getColumnsMetadata())}async executeExport(t){const{methodName:e,titleGrid:i}=t,s=await this._provider.getRecords(),o=[p.EXPORT_TO_PDF,p.EXPORT_PAGE_TO_PDF,p.EXPORT_PDF_TO_EMAIL,p.EXPORT_ALL_RECORDS_TO_PDF].includes(E(null==t?void 0:t.exportOption))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),[r,n]=this.getExecutor(e),l={serviceName:r,requestBody:{grid:{titleGrid:i,columns:this.buildColumnsObject(o),rows:this.buildRowsObject(o,s),customOptions:{xlsxExtension:!1}}}};return new Promise(((t,e)=>{v.get().callServiceBroker(r,l).then((e=>t(n(e)))).catch((t=>e(t)))}))}getExecutor(t){return"exportToPDF"===t?["GridPDFBuilderSP.buildPDFFromJson",t=>({fileSessionKey:t.chavePDF.valor,canPrint:"S"===t.permiteImprimir.valor,canExport:"S"===t.permiteExportar.valor,canSendEmail:"S"===t.canSendEmail.valor,useAppPrint:!0})]:["GridXLSBuilderSP.buildXLSFromJson",t=>({fileSessionKey:t.chaveXLS.valor,canPrint:!1,canExport:!1,useAppPrint:!1,canSendEmail:!1})]}buildColumnsObject(t){return{column:t.map(((t,e)=>{const{label:i,id:s,width:o,userInterface:r}=t;return Object.assign({index:e+1,id:s,label:i,width:o,presentationType:"P"},k[r]||{type:"S",align:"left"})}))}}buildRowsObject(t,e){return{row:e.map((e=>{const i={};return t.forEach(((t,s)=>i["c"+(s+1)]={$:this.formatValue(e,t)})),i}))}}formatValue(t,e){return null!=this._provider.formatValue?this._provider.formatValue(t,e):t[e.id]||""}}const k={[n.DATE]:{type:"D",align:"center"},[n.DATETIME]:{type:"H",align:"center"},[n.TIME]:{type:"I",align:"right"},[n.ELAPSEDTIME]:{type:"I",align:"right"},[n.DECIMALNUMBER]:{type:"F",align:"right"},[n.INTEGERNUMBER]:{type:"I",align:"right"},[n.SEARCH]:{type:"S",align:"right"}},D=class{constructor(e){t(this,e),this._selectedNumber=0,this._customPrefix="$custom$",this._releasedToExport=[c.EXPORT_TO_PDF,c.EXPORT_TO_XLS,c.EXPORT_BY_EMAIL,c.EXPORT_PDF_TO_EMAIL,c.EXPORT_XLS_TO_EMAIL,c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS,c.EXPORT_ALL_RECORDS_TO_PDF,c.EXPORT_ALL_RECORDS_TO_XLS],this._items=[],this._showDropdown=!1,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=u[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:u.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,titleGrid:this._appLabel},(()=>{this._snkEmailSender.close(),d.info(this.getMessage("snkDataExporter.message.emailSuccess"),{iconName:"check"})}))}})}getMessage(t,e){if(null==this.messagesBuilder){const t=x.getNearestInstance(this._element);t&&(this.messagesBuilder=t.messagesBuilder)}return this.messagesBuilder.getMessage(t,e)}positionDropdown(){var t;const e=null===(t=this._ezButton)||void 0===t?void 0:t.getBoundingClientRect();null!=e&&null!=this._dropdownParent&&(this._dropdownParent.style.top=e.y+e.height+5+"px",this._dropdownParent.style.left=e.x+"px")}closeDropdown(t){const e=null==t?void 0:t.target;null!=e&&(e.closest(".snk-data-exporter")||(this._showDropdown=!1))}setEvents(){document.removeEventListener("click",this.closeDropdown.bind(this)),document.addEventListener("click",this.closeDropdown.bind(this)),document.removeEventListener("scroll",this.positionDropdown.bind(this)),document.addEventListener("scroll",this.positionDropdown.bind(this))}controlDropdown(){this._showDropdown=!this._showDropdown}async resolveExporter(t,e){null!=this.provider&&null!=t&&null!=e&&this.getExporterStrategy().executeExport(t).then((t=>e(t))).catch((t=>{console.error(t);let{title:e,message:i,statusMessage:s}=t||{};d.error(e||this.getMessage("snkDataExporter.message.exportError"),s||i||this.getMessage("snkDataExporter.message.unknownFailure"))}))}getExporterStrategy(){return null==this.provider.getRecords?new b(this.provider):new w(this.provider)}getOptionKey(t){return Object.keys(c).find((e=>c[e]===t))}getExportType(t){return t===c.EXPORT_ALL_RECORDS_TO_PDF||t===c.EXPORT_ALL_RECORDS_TO_XLS?"all":t===c.EXPORT_PAGE_TO_PDF||t===c.EXPORT_PAGE_TO_XLS?"page":"selection"}async dispatchExporter(t){var e,i,s;const r=this.getOptionKey(t),n=null!==(e=p[r])&&void 0!==e?e:p.EXPORT_TO_PDF,l=p[r]===p.EXPORT_TO_XLS,a={methodName:c[`EXPORT_TO_${n}`],fileName:this._appLabel,titleGrid:this._appLabel,exportOption:t,limit:null===(s=null===(i=this.provider)||void 0===i?void 0:i.getExportLimit)||void 0===s?void 0:s.call(i),type:this.getExportType(t)};await this.resolveExporter(a,(t=>{t.canExport||n===p.EXPORT_TO_PDF?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":""}`),d.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:n,isDownload:l})):d.error(this.getMessage("snkDataExporter.title.permission"),this.getMessage("snkDataExporter.message.exportPermission"))}))}async processExporter(t){var e,i,s,o,r,n,l;const a=null==t?void 0:t.detail,p=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS],u=null===(e=null==a?void 0:a.id)||void 0===e?void 0:e.includes(this._customPrefix);if((null==a?void 0:a.id)===c.EXPORT_CURRENT_PAGE)return;const m=null===(i=this.provider)||void 0===i?void 0:i.getSelectedIDs(),v=null===(s=this.provider)||void 0===s?void 0:s.getTotalRecords(),x=null===(r=null===(o=this.provider)||void 0===o?void 0:o.getPageSize)||void 0===r?void 0:r.call(o),f=null===(l=null===(n=this.provider)||void 0===n?void 0:n.getExportLimit)||void 0===l?void 0:l.call(n);let g=!1;if(p.includes(null==a?void 0:a.id)&&x<=f||u?g=!1:(null==m?void 0:m.length)?g=m.length>f:v>f&&(g=!0),g){const t=f.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 d.confirm(e.title,e.description,null,h.WARN,{labelCancel:e.cancel,labelConfirm:e.confirm}))return}if(u)return this.openPersonalizedReports(a.id),void(this._showDropdown=!1);this.getFilteredReleasedToExport().includes(null==a?void 0:a.id)&&(a.id===c.EXPORT_BY_EMAIL?this.exportByEmail():this.dispatchExporter(a.id),this._showDropdown=!1)}getFilteredReleasedToExport(){var t,e;if(null==this.provider)return this._releasedToExport;const i=null===(e=(t=this.provider).getHiddenOptions)||void 0===e?void 0:e.call(t);return null==i?this._releasedToExport:this._releasedToExport.filter((t=>!i.includes(t)))}loadItems(){const t=[];this.getFilteredReleasedToExport().forEach((e=>{var i;null===(i=this._itemBuilder)||void 0===i||i.setExportOption(e,t)})),this.loadPersonalizedItems(t)}async loadPersonalizedItems(t){var e,i;const s=null===(i=null===(e=this.provider)||void 0===e?void 0:e.getRecordID)||void 0===i?void 0:i.call(e);if(null==s)return void(this._items=t);const n=await function(t){const e=`${o.getContextValue("__SNK__APPLICATION__").getModuleName()}@DataExporterSPBean.getPersonalizedReports`,i={serviceName:e,requestBody:t};return new Promise(((t,s)=>v.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:s});null==n||n.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,i;const s=[],o=(null==t?void 0:t.replace(this._customPrefix,""))||"";null===(i=null===(e=this.provider)||void 0===e?void 0:e.getSelectedIDs)||void 0===i||i.call(e).forEach((({name:t,type:e,value:i},o)=>{const r={fields:[]};0===o&&(s[`PK_${t}`]={type:this.parseDataType(e),value:i},s.pks=[]);const n={nome:`PK_${t}`,tipo:this.parseDataType(e),valor:i};r.fields.push(n),s.pks.push(r)})),this._application.openApp(`${m}${o}`,s)}parseDataType(t){switch(t){case l.NUMBER:return"I";case l.DATE:return"D";default:return"S"}}loadDropdown(){var t;this._selectedNumber=(null===(t=this.provider)||void 0===t?void 0:t.getSelectedNumber())||0,this._itemBuilder=new f(this.getMessage.bind(this),this._selectedNumber),this.loadItems()}getElementID(t){return{[a.DATA_ELEMENT_ID_ATTRIBUTE_NAME]:a.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&&(a.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)}};D.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{D as snk_data_exporter}
@@ -1 +1 @@
1
- import{r as t,c as i,f as s,h as e,H as a}from"./p-d2d301a6.js";import{Action as o}from"@sankhyalabs/core";import{S as h}from"./p-829d4045.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-dc7c9047.js";import"./p-af8efd95.js";import{P as d}from"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-6d4f4614.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{T as l}from"./p-7e7a7473.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-a4b1f1eb.js";import{S as u}from"./p-7a337364.js";import"./p-aff76a53.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-c2495304.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const h=[];this.dataState.hasPrevious||h.push(l.PREVIOUS),this.dataState.hasNext||h.push(l.NEXT),this.dataState.insertionMode&&h.push(l.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){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 h(this._configName,this.resourceID,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===c.GRID,messagesBuilder:this.messagesBuilder,configName:this._configName},e("ez-view-stack",{ref:t=>this.updateViewStack(t)},e("stack-item",null,e("div",{class:"ez-box ez-box--shadow grid-container"},e("div",{class:"ez-flex ez-title--primary ez-size-width--full ez-padding--large detail-header"},e("div",{class:"ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center"},this._levelPath?e("span",{class:"level-path"},this._levelPath+" /"):void 0,this.label)),e("snk-grid",{class:"ez-size-width--full ez-size-height--full",ref:t=>this._snkGrid=t,configName:this._configName,messagesBuilder:this.messagesBuilder,onGridDoubleClick:()=>this.emitSwitchEvent(c.FORM),onActionClick:t=>this.executeActionHandler(t),presentationMode:d.SECONDARY,canEdit:this.canEdit,isDetail:!0,taskbarCustomContainerId:this.taskbarCustomContainerId,gridHeaderCustomSlotId:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS",topTaskbarCustomSlotId:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS"}))),e("stack-item",null,e("snk-form-view",{ref:t=>this._snkFormView=t,canExpand:!1,canFix:!1,name:this.selectedForm,formMetadata:this._formMetadata,dataUnit:this.dataUnit,fields:this.getFormFields(),label:this.label,levelPath:this._levelPath,onFormItemsReady:({detail:t})=>this.formItemsReady.emit(t)},e("snk-taskbar",{key:"guideViewerTaskbar",class:"form-taskbar","data-element-id":"guideViewer",configName:this._configName,messagesBuilder:this.messagesBuilder,disabledButtons:this._disabledButtons,buttons:"INSERT,PREVIOUS,NEXT,DIVIDER,CLONE,REMOVE,MORE_OPTIONS,DIVIDER,GRID_MODE,CONFIGURATOR",primaryButton:"INSERT",presentationMode:d.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit,resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"},e("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))),e("stack-item",null,e("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this.entityName,onBack:this.handleAttachBack.bind(this)})))))}static get watchers(){return{dataUnit:["observeDataUnit"],dataState:["observerDataState"],customEditors:["observerPropsCustomEditor"],customRenders:["observeCustomRenders"]}}};p.REGEX_FORM_ID=/__FORM:[^:]+/g,p.style=".sc-snk-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%}.level-path.sc-snk-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.form-taskbar.sc-snk-detail-view{padding-bottom:var(--space--medium)}.grid-container.sc-snk-detail-view{background-color:#FFF;min-height:100px}.detail-header.sc-snk-detail-view{padding-bottom:0}";export{p as snk_detail_view}
1
+ import{r as t,c as i,f as s,h as e,H as a}from"./p-d2d301a6.js";import{Action as o}from"@sankhyalabs/core";import{S as h}from"./p-829d4045.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-dc7c9047.js";import"./p-af8efd95.js";import{P as d}from"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-fe79f83a.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{T as l}from"./p-7e7a7473.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-cefba299.js";import{S as u}from"./p-7a337364.js";import"./p-aff76a53.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-c2495304.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const h=[];this.dataState.hasPrevious||h.push(l.PREVIOUS),this.dataState.hasNext||h.push(l.NEXT),this.dataState.insertionMode&&h.push(l.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){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 h(this._configName,this.resourceID,(()=>this.loadMetadata())),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===c.GRID,messagesBuilder:this.messagesBuilder,configName:this._configName},e("ez-view-stack",{ref:t=>this.updateViewStack(t)},e("stack-item",null,e("div",{class:"ez-box ez-box--shadow grid-container"},e("div",{class:"ez-flex ez-title--primary ez-size-width--full ez-padding--large detail-header"},e("div",{class:"ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center"},this._levelPath?e("span",{class:"level-path"},this._levelPath+" /"):void 0,this.label)),e("snk-grid",{class:"ez-size-width--full ez-size-height--full",ref:t=>this._snkGrid=t,configName:this._configName,messagesBuilder:this.messagesBuilder,onGridDoubleClick:()=>this.emitSwitchEvent(c.FORM),onActionClick:t=>this.executeActionHandler(t),presentationMode:d.SECONDARY,canEdit:this.canEdit,isDetail:!0,taskbarCustomContainerId:this.taskbarCustomContainerId,gridHeaderCustomSlotId:"DETAIL_GRID_HEADER_CUSTOM_ELEMENTS",topTaskbarCustomSlotId:"DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS"}))),e("stack-item",null,e("snk-form-view",{ref:t=>this._snkFormView=t,canExpand:!1,canFix:!1,name:this.selectedForm,formMetadata:this._formMetadata,dataUnit:this.dataUnit,fields:this.getFormFields(),label:this.label,levelPath:this._levelPath,onFormItemsReady:({detail:t})=>this.formItemsReady.emit(t)},e("snk-taskbar",{key:"guideViewerTaskbar",class:"form-taskbar","data-element-id":"guideViewer",configName:this._configName,messagesBuilder:this.messagesBuilder,disabledButtons:this._disabledButtons,buttons:"INSERT,PREVIOUS,NEXT,DIVIDER,CLONE,REMOVE,MORE_OPTIONS,DIVIDER,GRID_MODE,CONFIGURATOR",primaryButton:"INSERT",presentationMode:d.SECONDARY,onActionClick:t=>this.executeActionHandler(t),dataUnit:this.dataUnit,resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"},e("slot",{name:"DETAIL_TASKBAR_CUSTOM_ELEMENTS"})))),e("stack-item",null,e("snk-attach",{registerKey:this.attachmentRegisterKey,messagesBuilder:this.messagesBuilder,entityName:this.entityName,onBack:this.handleAttachBack.bind(this)})))))}static get watchers(){return{dataUnit:["observeDataUnit"],dataState:["observerDataState"],customEditors:["observerPropsCustomEditor"],customRenders:["observeCustomRenders"]}}};p.REGEX_FORM_ID=/__FORM:[^:]+/g,p.style=".sc-snk-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%}.level-path.sc-snk-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.form-taskbar.sc-snk-detail-view{padding-bottom:var(--space--medium)}.grid-container.sc-snk-detail-view{background-color:#FFF;min-height:100px}.detail-header.sc-snk-detail-view{padding-bottom:0}";export{p as snk_detail_view}
@@ -1 +1 @@
1
- import{r as t,h as i,H as s,g as e,c as n}from"./p-d2d301a6.js";import{ApplicationContext as o,StringUtils as r,ErrorException as a,WarningException as l,ObjectUtils as c,DateUtils as d,ArrayUtils as h,ElementIDUtils as u}from"@sankhyalabs/core";import{D as g}from"./p-dc7c9047.js";import{P as f}from"./p-eaad0aa8.js";import"./p-af8efd95.js";import"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-6d4f4614.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{R as m}from"./p-688dcb4c.js";import{ApplicationUtils as p,DialogType as v}from"@sankhyalabs/ezui/dist/collection/utils";import{CheckMode as b}from"@sankhyalabs/ezui/dist/collection/components/ez-check/CheckMode";import{C as k}from"./p-aff76a53.js";import{O as _}from"./p-b0ef4383.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";class w{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 g.get().callServiceBroker("ActionButtonsSP.executeJava",JSON.stringify(i))}}class C{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 g.get().callServiceBroker("ActionButtonsSP.executeScript",i)}}class y{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 l=i.getFieldValue(e);if(!l){let s=i.getField(e).label;throw s=r.isEmpty(i.getField(e).label)?e:s,new a(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.launchScreen.emptyField",{description:t.description,localFieldLabel:s}))}l=r.isEmpty(l.toString())?void 0:l.toString(),n[s.targetField]=l,o.push({fieldName:s.targetField,value:l})})),n.ACTION_PARAMETERS=o,n.call_time=Date.now(),s(n)}s(null)}))}}class x{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,r={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:r,callback:this.callExecProcedure})}))}async callExecProcedure(t){const i={requestBody:{stpCall:t}};await g.get().callServiceBroker("ActionButtonsSP.executeSTP",JSON.stringify(i))}}var S,z;!function(t){t.LAUNCH_SCREEN="LC",t.JAVASCRIPT="SC",t.JAVA="RJ",t.PROCEDURE="SP",t.EMBEDDED="EB"}(S||(S={}));class A{constructor(t){this.actionType=t,this._application=o.getContextValue("__SNK__APPLICATION__")}get executor(){switch(this.actionType){case S.LAUNCH_SCREEN:return new y;case S.JAVASCRIPT:return new C;case S.JAVA:return new w;case S.PROCEDURE:return new x;default:throw new a(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"}(z||(z={}));const O="__MASTER_ROW__";class N{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 l(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=c.copy(t),e.applyParameters=t=>{this.apply(t,s)},e.openPopup()}else t.type!=S.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 f.DATE:e="D";break;case f.DATETIME:e="H";break;case f.DECIMAL:e="F",i={"sk-precision":Number(t.precision)};break;case f.BOOLEAN:e="S",n=!0,o=t.value?"S":"N";break;case f.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 f.OPTIONS:e="O";let r=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":r}}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 a(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.action.emptyParamName",void 0));r.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=d.formatDate(i):"DH"==t.paramType&&(i=d.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"}};g.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(O)&&(n.master="S",n.entityName=e.__ENTITY_NAME__,delete e[O],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 z.NONE:break;case z.PARENT:case z.MASTER:case z.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 P{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=S.PROCEDURE):t.content.event.hasOwnProperty("runScript")?(i.requestBody=t.content.event.runScript,n=S.JAVASCRIPT):t.content.event.hasOwnProperty("javaCall")&&(i.requestBody=t.content.event.javaCall,n=S.JAVA);let r={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(r);const a=t.content.event.title.$,l=t.content.event.message.$;let c;switch(n){case S.JAVASCRIPT:c={runScript:i.requestBody};break;case S.PROCEDURE:c={requestBody:{stpCall:i.requestBody}};break;case S.JAVA:c={requestBody:{javaCall:i.requestBody}}}if("S"==t.content.event.showNoOption){r.paramName="__ESCOLHA_SIMNAO__";const t=document.createElement("snk-client-confirm");window.document.body.appendChild(t),t.titleMessage=a,t.message=l,t.accept=async()=>{r.$="S",await i.reCall(c),s()},t.cancel=async()=>{r.$="N",await i.reCall(c),s()},t.openPopup()}else e.confirm(a,l,null,"warn",{labelCancel:"Cancelar",labelConfirm:"Sim"}).then((async t=>{t&&(r.paramName="__CONFIRMACAO__",r.$="S",await i.reCall(c),s())}))}))}}const D=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 A(i.type).executor;new N(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 g.get().callServiceBroker("ActionButtonsSP.getActions",t).then((t=>{var i;(null===(i=t.actions)||void 0===i?void 0:i.action)&&(this._actions=this._isOrderActions?h.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 m.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 P;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)}};D.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 I=class{constructor(i){t(this,i),this.configChange=n(this,"configChange",7),this.configCancel=n(this,"configCancel",7),this._orderListItems=[],this._orderPriorityList=[],this._columListItems=[],this._selectedIndex=-1,this._dataChanged=!1,this._componenteInternalKey=Date.now(),this.selectedIndex=0,this.columns=void 0,this.config=void 0,this.configName=void 0,this.resourceID=void 0}getMessage(t,i){return o.getContextValue("__SNK__APPLICATION__").messagesBuilder.getMessage(t,i)}getSortableColumns(){let t=[];return this.columns.filter((t=>{var i;return r.getBooleanValue(null===(i=null==t?void 0:t.props)||void 0===i?void 0:i.get("sortable"),!0)})).forEach((i=>{var s;let e=null===(s=this.config)||void 0===s?void 0:s.columns.find((t=>t.name===i.name)),n={name:i.name,label:i.label};e&&(n.orderIndex=e.orderIndex,n.ascending=e.ascending),i.hidden||t.push(n)})),t}createOrderList(){let t=this.getSortableColumns();t.sort(((t,i)=>0!=t.orderIndex||0!=i.orderIndex||null==t.ascending&&null==i.ascending?null!=t.ascending&&null!=i.ascending?t.orderIndex-i.orderIndex:null!=t.ascending||null!=i.ascending?null!=t.ascending?-1:null!=i.ascending?1:0:t.orderIndex-i.orderIndex:null!=t.ascending?-1:null!=i.ascending?1:0)),this._orderListItems=t}createColumnList(){let t={group:this.getMessage("snkGridConfig.group.visible"),items:[]},i={group:this.getMessage("snkGridConfig.group.hidden"),items:[],sort:_.asc.value};this.columns.forEach((s=>{let e={label:s.label};s.hidden?i.items.push(e):t.items.push(e)})),this._columListItems=[t,i]}createColumnListSlotDataElementId(t){return`configItem_${r.replaceAccentuatedChars(r.toCamelCase(t.label))}`}buildColumnListSlot(t,s){const e=this.createColumnListSlotDataElementId(t);return i("div",null,i("ez-check",{mode:b.SWITCH,id:b.SWITCH+((null==t?void 0:t.label)||"")+((null==s?void 0:s.group)||""),value:s.group===this.getMessage("snkGridConfig.group.visible"),"data-element-id":e,onEzChange:i=>{this.switchColumnGroup(i,t)}}))}createOrderListSlotDataElementId(t){return`${this._element.getAttribute(u.DATA_ELEMENT_ID_ATTRIBUTE_NAME)}_configItem_${r.toCamelCase(t.label)}`}buildOrderListSlot(t){const s=this.createOrderListSlotDataElementId(t);let e=_.none.value;return null!=(null==t?void 0:t.ascending)&&(e=1==t.ascending?_.asc.value:_.desc.value),i("div",null,i("snk-select-box",{selectedOption:e,key:"snk-select-box-"+this._componenteInternalKey+"-"+t,"data-element-id":s,onEzChange:i=>{i.stopPropagation(),this.updateOrder(i.detail,t.label)}}))}updateOrder(t,i){var s;this._dataChanged=!0;let e,n=[...this.columns],o=n.find((t=>t.label===i));o&&(o.sort=t.value===_.none.value?void 0:t.value),(null===(s=this._orderPriorityList)||void 0===s?void 0:s.length)>0?(this._orderPriorityList.find((t=>t.label===o.label)).sort=t,this._orderPriorityList.filter((t=>t.sort)).forEach(((t,i)=>{t.label===o.label&&(o.sortIndex=i)}))):(e=n.filter((t=>t.sort&&!0!==t.hidden)).map(((t,i)=>({label:t.label,orderIndex:i}))),e.forEach((t=>{n.find((i=>i.label===t.label)).sortIndex=t.orderIndex}))),this.columns=n}switchColumnGroup(t,i){t.stopPropagation();let s=[...this._columListItems];if(this._dataChanged=!0,!0===t.detail){let t=s.find((t=>t.group===this.getMessage("snkGridConfig.group.hidden"))),e=t.items.findIndex((t=>t.label===i.label));e>=0&&t.items.splice(e,1),s.find((t=>t.group===this.getMessage("snkGridConfig.group.visible"))).items.push(i),this._columListItems=s,this.createOrderList()}else if(!1===t.detail){let t=s.find((t=>t.group===this.getMessage("snkGridConfig.group.visible"))),e=t.items.findIndex((t=>t.label===i.label));e>=0&&t.items.splice(e,1),s.find((t=>t.group===this.getMessage("snkGridConfig.group.hidden"))).items.push(i),this._columListItems=s,this.createOrderList()}}finish(){if(!this._dataChanged)return void this.closeConfig();let t=[];this._columListItems.forEach((i=>{i.items.forEach((s=>{const e=this.columns.find((t=>t.label===s.label));let n=Object.assign({},e);n.hidden=i.group===this.getMessage("snkGridConfig.group.hidden"),t.push(n)}))})),this.columns=t,this._dataChanged=!1,this.closeConfig(),this.save()}saveGridConfigOnStorage(t){k.saveGridConfig(t,this.configName,this.resourceID).then((t=>{this.configChange.emit(t),this._orderList.clearHistory(),p.info(this.getMessage("snkGridConfig.info.successfullyConfigSaved"),{iconName:"check"})}))}reOrderPriorityColumns(t,i){let s=[];s=t.filter((t=>t.sort&&!0!==t.hidden)).map((t=>({label:t.label,orderIndex:0})));let e=0,n=[];return i.forEach((t=>{let i=s.find((i=>i.label===t.label));i&&(i.orderIndex=e,n.push(i),e++)})),n.length>0&&(s=n),s}save(){var t;let i;i=this.config?this.config:this.createConfigFromState(this.columns);let s,e=[];(null===(t=this._orderPriorityList)||void 0===t?void 0:t.length)>0&&(s=this.reOrderPriorityColumns(this.columns,this._orderPriorityList)),this.columns.forEach((t=>{let n=i.columns.find((i=>t.name===i.name));!0===t.hidden&&n||(n?n.width=t.width:!1===t.hidden&&(n={name:t.name,width:t.width,orderIndex:0}),n&&(t.sort?(n.ascending=t.sort.toUpperCase()===_.asc.value,s?function(t,i){if(s){let e=s.find((i=>i.label===t.label));e&&(i.orderIndex=e.orderIndex)}}(t,n):n.orderIndex=t.sortIndex):(delete n.ascending,n.orderIndex=0),e.push(n)))})),i.columns=e,this.saveGridConfigOnStorage(i)}createConfigFromState(t){let i={columns:[]};return t.forEach((t=>{if(!t.hidden){let s={name:t.name};t.width&&(s.width=t.width),t.sort?(s.ascending=t.sort.toUpperCase()===_.asc.value,s.orderIndex=t.sortIndex):s.orderIndex=0,s&&i.columns.push(s)}})),i}async locateColumn(t,i){var s;const e="Enter"===t.key;if(!(i=i||(null===(s=t.currentTarget)||void 0===s?void 0:s.value)))return void this.removeSelection();const n=await this.getMatchedIndexes(i),o=this.getNewSelectedIndex(n,e);this._selectedIndex=o,1===this.selectedIndex?this.updateOrderListSelection(o):this.updateColumnListSelection(o)}async getMatchedIndexes(t){const i=[];return 1===this.selectedIndex?(await this._orderList.getList()).forEach(((s,e)=>{this.compareWords(s,t)&&i.push(e)})):this.columns.forEach(((s,e)=>{this.compareWords(s,t)&&i.push(e)})),i}getNewSelectedIndex(t,i){if(0===t.length)return-1;if(i)for(const i of t)if(i>this._selectedIndex)return i;return t[0]}updateOrderListSelection(t){-1!==t?this._orderList.getList().then((i=>{const s=i[t];s?this._orderList.setSelection(s,!0):this._orderList.removeSelection()})):this._orderList.removeSelection()}updateColumnListSelection(t){if(-1===t)return void this._columnList.removeSelection();const i=this.columns[t];if(i){const t=this._columListItems.map((t=>t.items)).flat().find((t=>t.label===i.label));t?this._columnList.setSelection(t,!0):this._columnList.removeSelection()}else this._columnList.removeSelection()}removeSelection(){1===this.selectedIndex?this._orderList.removeSelection():this._columnList.removeSelection()}compareWords(t,i){var s,e;const n=null===(s=r.replaceAccentuatedChars(null==t?void 0:t.label))||void 0===s?void 0:s.toUpperCase(),o=null===(e=r.replaceAccentuatedChars(i))||void 0===e?void 0:e.toUpperCase();return!r.isEmpty(n)&&!r.isEmpty(o)&&n.includes(o)}getColumnNames(){const t=[];return t.push(this.getMessage("snkGridConfig.tab.columns")),t.push(this.getMessage("snkGridConfig.tab.lineOrdering")),t.join(",")}closeConfig(){if(this._orderList.scrollToTop(),this._columnList.scrollToTop(),this._searchElement.value="",this._dataChanged){let t={canClose:!1,labelCancel:this.getMessage("snkGridConfig.confirm.cancel"),labelConfirm:this.getMessage("snkGridConfig.confirm.save"),btnConfirmDanger:!1};p.confirm(this.getMessage("snkGridConfig.confirm.alert"),this.getMessage("snkGridConfig.confirm.msgCancel"),null,v.WARN,t).then((t=>{t?this.finish():(this._dataChanged=!1,this.configCancel.emit(),this._orderList.clearHistory(),this._componenteInternalKey=Date.now())}))}else this.configCancel.emit(),this._orderList.clearHistory()}handleTabChange(t){null!=(null==t?void 0:t.index)&&(this.selectedIndex!==t.index&&(0===t.index?this._orderList.scrollToTop():1===t.index&&this._columnList.scrollToTop(),this._searchElement.value=""),1===t.index&&this.createOrderList(),this.selectedIndex=t.index)}handleColumnListChange(t){var i;if(t.detail){let s=null===(i=t.detail.find((t=>t.group===this.getMessage("snkGridConfig.group.visible"))))||void 0===i?void 0:i.items;s&&(this._dataChanged=!0,this._orderListItems=s)}}handleOrderListChange(t){if(t.detail){let i=t.detail;i&&(this._dataChanged=!0,this._orderPriorityList=i)}}componentWillRender(){var t;(null===(t=this.columns)||void 0===t?void 0:t.length)>0&&this.createColumnList()}componentDidRender(){var t;(null===(t=this.columns)||void 0===t?void 0:t.length)>0&&this.locateColumn(new KeyboardEvent("arrow-right",{key:"ArrowRight"}),this._searchElement.value)}componentDidLoad(){u.addIDInfo(this._element)}render(){return i(s,null,i("div",{class:"grid-config__header"},i("div",{class:"title-container"},i("div",{class:""},i("label",{class:"title"},this.getMessage("snkGridConfig.gridConfiguration")),i("label",{class:"subtitle"},this.getMessage("snkGridConfig.columnVisibilityOrder"))),i("div",{class:"button-close"},i("ez-button",{mode:"icon",iconName:"close",size:"medium",onClick:()=>this.closeConfig()}))),i("div",{class:"tabselector-container"},i("ez-tabselector",{selectedIndex:this.selectedIndex,onEzChange:t=>{this.handleTabChange(t.detail)},tabs:this.getColumnNames()})),i("div",null,i("ez-text-input",{"data-element-id":"searchColums",ref:t=>this._searchElement=t,label:this.getMessage("snkGridConfig.findColumn"),onKeyUp:t=>this.locateColumn(t)},i("ez-icon",{slot:"leftIcon",size:"medium",iconName:"search"})))),i("div",{class:"grid-config__main"},i("ez-list",{ref:t=>this._columnList=t,class:0===this.selectedIndex?"":"hidden",dataSource:this._columListItems,onEzChange:t=>this.handleColumnListChange(t),ezDraggable:!0,ezSelectable:!0,itemSlotBuilder:(t,i)=>this.buildColumnListSlot(t,i),useGroups:!0,"data-element-id":"configCols"}),i("div",{class:1===this.selectedIndex?"group-name":"hidden"},this.getMessage("snkGridConfig.info.sortingSequence")),i("ez-list",{ref:t=>this._orderList=t,class:1===this.selectedIndex?"height-calc":"hidden",dataSource:this._orderListItems,ezSelectable:!0,onEzChange:t=>this.handleOrderListChange(t),ezDraggable:!0,itemSlotBuilder:t=>this.buildOrderListSlot(t),"data-element-id":"configDataOrder"})),i("div",{class:"grid-config__footer"},i("ez-button",{class:"padding-right--medium",label:this.getMessage("snkGridConfig.cancel"),onClick:()=>this.closeConfig()}),i("ez-button",{label:this.getMessage("snkGridConfig.complete"),class:"ez-button--primary",onClick:()=>this.finish()})))}static get assetsDirs(){return["../assets"]}get _element(){return e(this)}};I.style='.sc-snk-grid-config-h{--snk-grid-config__footer--padding-top:var(--space--medium, 12px);--snk-grid-config__main--padding-right:var(--space--medium, 12px);--snk-grid-config__tabselector-container--padding:var(--space--medium, 12px);--snk-grid-config__button-close--padding-left:var(--space--medium, 12px);--snk-grid-config__title--color:var(--title--primary, #2B3A54);--snk-grid-config__title--font-family:var(--font-pattern, "Roboto");--snk-grid-config__title--font-size:var(--title--large, 20px);--snk-grid-config__title--font-weight:var(--text-weight--extra-large, 700);--snk-grid-config__subtitle--font-family:var(--font-pattern, "Roboto");--snk-grid-config__subtitle--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-family:var(--font-pattern, "Roboto");--snk-grid-config__group--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-weight:var(--text-weight--large, 600);--snk-grid-config__group--padding-bottom:var(--space-small, 6px);--snk-grid-config__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-grid-config__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-grid-config__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-grid-config__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-grid-config__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-grid-config__scrollbar--width:var(--space--medium, 12px);display:grid;grid-template-rows:auto 1fr auto;max-height:100%;width:100%}@media screen and (min-width: 480px){.sc-snk-grid-config-h{width:359px;max-width:359px}}.padding-right--medium.sc-snk-grid-config{padding-right:var(--space--medium)}ez-list.sc-snk-grid-config{height:100%}.height-calc.sc-snk-grid-config{max-height:calc(100% - 24px)}.grid-config__footer.sc-snk-grid-config{display:flex;justify-content:flex-end;width:100%;padding-top:var(--snk-grid-config__footer--padding-top)}.hidden.sc-snk-grid-config{display:none}.tabselector-container.sc-snk-grid-config{padding:var(--snk-grid-config__tabselector-container--padding) 0}.button-close.sc-snk-grid-config{padding-left:var(--snk-grid-config__button-close--padding-left)}.title-container.sc-snk-grid-config{display:flex;justify-content:space-between;align-items:center;width:100%}.title.sc-snk-grid-config{display:flex;margin:0;line-height:normal;letter-spacing:0em;text-align:left;color:var(--snk-grid-config__title--color);font-size:var(--snk-grid-config__title--font-size);font-family:var(--snk-grid-config__title--font-family);font-weight:var(--snk-grid-config__title--font-weight)}.subtitle.sc-snk-grid-config{color:var(--text--primary);font-size:var(--snk-grid-config__subtitle--font-size);font-family:var(--snk-grid-config__subtitle--font-family)}.grid-config__main.sc-snk-grid-config{overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--snk-grid-config__scrollbar--color-clicked) var(--snk-grid-config__scrollbar--color-background);padding-right:var(--snk-grid-config__main--padding-right)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar{width:var(--snk-grid-config__scrollbar--width);max-width:var(--snk-grid-config__scrollbar--width);min-width:var(--snk-grid-config__scrollbar--width);background-color:var(--snk-grid-config__scrollbar--color-background)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-track{background-color:var(--snk-grid-config__scrollbar--color-background);border-radius:var(--snk-grid-config__scrollbar--border-radius)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb{background-color:var(--snk-grid-config__scrollbar--color-default);border-radius:var(--snk-grid-config__scrollbar--border-radius)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:vertical:hover,.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--snk-grid-config__scrollbar--color-hover)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:vertical:active,.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--snk-grid-config__scrollbar--color-clicked)}.group-name.sc-snk-grid-config{font-family:var(--snk-grid-config__group--font-family);font-size:var(--snk-grid-config__group--font-size);font-weight:var(--snk-grid-config__group--font-weight);padding-bottom:var(--snk-grid-config__group--padding-bottom)}';const E=class{constructor(i){t(this,i),this.ezChange=n(this,"ezChange",7),this.selectedOption=_.none}render(){return i("ez-combo-box",{class:"grid-config-combo ez-input--inverted",label:"",suppressSearch:!0,value:this.selectedOption,enabled:!0,canShowError:!1,suppressEmptyOption:!0},Object.keys(_).map((t=>i("option",{value:_[t].value},_[t].label))))}static get assetsDirs(){return["../assets"]}};E.style="ez-combo-box{width:100px}.grid-config-combo{--ez-text-input--height:28px;--ez-text-input__input--background-color:#fff;--ez-text-input__input--border-color:#dce0e8}";const j=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: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)}};j.style=".sc-taskbar-actions-button-h{display:flex;width:fit-content;height:fit-content}";export{D as snk_actions_button,I as snk_grid_config,E as snk_select_box,j as taskbar_actions_button}
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 r,ErrorException as a,WarningException as l,ObjectUtils as c,DateUtils as d,ArrayUtils as h,ElementIDUtils as u}from"@sankhyalabs/core";import{D as g}from"./p-dc7c9047.js";import{P as f}from"./p-eaad0aa8.js";import"./p-af8efd95.js";import"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-fe79f83a.js";import"./p-ff1990ad.js";import"./p-df5451c7.js";import{R as m}from"./p-688dcb4c.js";import{ApplicationUtils as p,DialogType as v}from"@sankhyalabs/ezui/dist/collection/utils";import{CheckMode as b}from"@sankhyalabs/ezui/dist/collection/components/ez-check/CheckMode";import{C as k}from"./p-aff76a53.js";import{O as _}from"./p-b0ef4383.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";class w{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 g.get().callServiceBroker("ActionButtonsSP.executeJava",JSON.stringify(i))}}class C{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 g.get().callServiceBroker("ActionButtonsSP.executeScript",i)}}class y{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 l=i.getFieldValue(e);if(!l){let s=i.getField(e).label;throw s=r.isEmpty(i.getField(e).label)?e:s,new a(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.launchScreen.emptyField",{description:t.description,localFieldLabel:s}))}l=r.isEmpty(l.toString())?void 0:l.toString(),n[s.targetField]=l,o.push({fieldName:s.targetField,value:l})})),n.ACTION_PARAMETERS=o,n.call_time=Date.now(),s(n)}s(null)}))}}class x{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,r={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:r,callback:this.callExecProcedure})}))}async callExecProcedure(t){const i={requestBody:{stpCall:t}};await g.get().callServiceBroker("ActionButtonsSP.executeSTP",JSON.stringify(i))}}var S,z;!function(t){t.LAUNCH_SCREEN="LC",t.JAVASCRIPT="SC",t.JAVA="RJ",t.PROCEDURE="SP",t.EMBEDDED="EB"}(S||(S={}));class A{constructor(t){this.actionType=t,this._application=o.getContextValue("__SNK__APPLICATION__")}get executor(){switch(this.actionType){case S.LAUNCH_SCREEN:return new y;case S.JAVASCRIPT:return new C;case S.JAVA:return new w;case S.PROCEDURE:return new x;default:throw new a(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"}(z||(z={}));const O="__MASTER_ROW__";class N{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 l(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=c.copy(t),e.applyParameters=t=>{this.apply(t,s)},e.openPopup()}else t.type!=S.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 f.DATE:e="D";break;case f.DATETIME:e="H";break;case f.DECIMAL:e="F",i={"sk-precision":Number(t.precision)};break;case f.BOOLEAN:e="S",n=!0,o=t.value?"S":"N";break;case f.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 f.OPTIONS:e="O";let r=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":r}}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 a(this._application.messagesBuilder.getMessage("snkActionsButton.title.error",void 0),this._application.messagesBuilder.getMessage("snkActionsButton.action.emptyParamName",void 0));r.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=d.formatDate(i):"DH"==t.paramType&&(i=d.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"}};g.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(O)&&(n.master="S",n.entityName=e.__ENTITY_NAME__,delete e[O],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 z.NONE:break;case z.PARENT:case z.MASTER:case z.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 P{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=S.PROCEDURE):t.content.event.hasOwnProperty("runScript")?(i.requestBody=t.content.event.runScript,n=S.JAVASCRIPT):t.content.event.hasOwnProperty("javaCall")&&(i.requestBody=t.content.event.javaCall,n=S.JAVA);let r={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(r);const a=t.content.event.title.$,l=t.content.event.message.$;let c;switch(n){case S.JAVASCRIPT:c={runScript:i.requestBody};break;case S.PROCEDURE:c={requestBody:{stpCall:i.requestBody}};break;case S.JAVA:c={requestBody:{javaCall:i.requestBody}}}if("S"==t.content.event.showNoOption){r.paramName="__ESCOLHA_SIMNAO__";const t=document.createElement("snk-client-confirm");window.document.body.appendChild(t),t.titleMessage=a,t.message=l,t.accept=async()=>{r.$="S",await i.reCall(c),s()},t.cancel=async()=>{r.$="N",await i.reCall(c),s()},t.openPopup()}else e.confirm(a,l,null,"warn",{labelCancel:"Cancelar",labelConfirm:"Sim"}).then((async t=>{t&&(r.paramName="__CONFIRMACAO__",r.$="S",await i.reCall(c),s())}))}))}}const D=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 A(i.type).executor;new N(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 g.get().callServiceBroker("ActionButtonsSP.getActions",t).then((t=>{var i;(null===(i=t.actions)||void 0===i?void 0:i.action)&&(this._actions=this._isOrderActions?h.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 m.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 P;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)}};D.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 I=class{constructor(i){t(this,i),this.configChange=n(this,"configChange",7),this.configCancel=n(this,"configCancel",7),this._orderListItems=[],this._orderPriorityList=[],this._columListItems=[],this._selectedIndex=-1,this._dataChanged=!1,this._componenteInternalKey=Date.now(),this.selectedIndex=0,this.columns=void 0,this.config=void 0,this.configName=void 0,this.resourceID=void 0}getMessage(t,i){return o.getContextValue("__SNK__APPLICATION__").messagesBuilder.getMessage(t,i)}getSortableColumns(){let t=[];return this.columns.filter((t=>{var i;return r.getBooleanValue(null===(i=null==t?void 0:t.props)||void 0===i?void 0:i.get("sortable"),!0)})).forEach((i=>{var s;let e=null===(s=this.config)||void 0===s?void 0:s.columns.find((t=>t.name===i.name)),n={name:i.name,label:i.label};e&&(n.orderIndex=e.orderIndex,n.ascending=e.ascending),i.hidden||t.push(n)})),t}createOrderList(){let t=this.getSortableColumns();t.sort(((t,i)=>0!=t.orderIndex||0!=i.orderIndex||null==t.ascending&&null==i.ascending?null!=t.ascending&&null!=i.ascending?t.orderIndex-i.orderIndex:null!=t.ascending||null!=i.ascending?null!=t.ascending?-1:null!=i.ascending?1:0:t.orderIndex-i.orderIndex:null!=t.ascending?-1:null!=i.ascending?1:0)),this._orderListItems=t}createColumnList(){let t={group:this.getMessage("snkGridConfig.group.visible"),items:[]},i={group:this.getMessage("snkGridConfig.group.hidden"),items:[],sort:_.asc.value};this.columns.forEach((s=>{let e={label:s.label};s.hidden?i.items.push(e):t.items.push(e)})),this._columListItems=[t,i]}createColumnListSlotDataElementId(t){return`configItem_${r.replaceAccentuatedChars(r.toCamelCase(t.label))}`}buildColumnListSlot(t,s){const e=this.createColumnListSlotDataElementId(t);return i("div",null,i("ez-check",{mode:b.SWITCH,id:b.SWITCH+((null==t?void 0:t.label)||"")+((null==s?void 0:s.group)||""),value:s.group===this.getMessage("snkGridConfig.group.visible"),"data-element-id":e,onEzChange:i=>{this.switchColumnGroup(i,t)}}))}createOrderListSlotDataElementId(t){return`${this._element.getAttribute(u.DATA_ELEMENT_ID_ATTRIBUTE_NAME)}_configItem_${r.toCamelCase(t.label)}`}buildOrderListSlot(t){const s=this.createOrderListSlotDataElementId(t);let e=_.none.value;return null!=(null==t?void 0:t.ascending)&&(e=1==t.ascending?_.asc.value:_.desc.value),i("div",null,i("snk-select-box",{selectedOption:e,key:"snk-select-box-"+this._componenteInternalKey+"-"+t,"data-element-id":s,onEzChange:i=>{i.stopPropagation(),this.updateOrder(i.detail,t.label)}}))}updateOrder(t,i){var s;this._dataChanged=!0;let e,n=[...this.columns],o=n.find((t=>t.label===i));o&&(o.sort=t.value===_.none.value?void 0:t.value),(null===(s=this._orderPriorityList)||void 0===s?void 0:s.length)>0?(this._orderPriorityList.find((t=>t.label===o.label)).sort=t,this._orderPriorityList.filter((t=>t.sort)).forEach(((t,i)=>{t.label===o.label&&(o.sortIndex=i)}))):(e=n.filter((t=>t.sort&&!0!==t.hidden)).map(((t,i)=>({label:t.label,orderIndex:i}))),e.forEach((t=>{n.find((i=>i.label===t.label)).sortIndex=t.orderIndex}))),this.columns=n}switchColumnGroup(t,i){t.stopPropagation();let s=[...this._columListItems];if(this._dataChanged=!0,!0===t.detail){let t=s.find((t=>t.group===this.getMessage("snkGridConfig.group.hidden"))),e=t.items.findIndex((t=>t.label===i.label));e>=0&&t.items.splice(e,1),s.find((t=>t.group===this.getMessage("snkGridConfig.group.visible"))).items.push(i),this._columListItems=s,this.createOrderList()}else if(!1===t.detail){let t=s.find((t=>t.group===this.getMessage("snkGridConfig.group.visible"))),e=t.items.findIndex((t=>t.label===i.label));e>=0&&t.items.splice(e,1),s.find((t=>t.group===this.getMessage("snkGridConfig.group.hidden"))).items.push(i),this._columListItems=s,this.createOrderList()}}finish(){if(!this._dataChanged)return void this.closeConfig();let t=[];this._columListItems.forEach((i=>{i.items.forEach((s=>{const e=this.columns.find((t=>t.label===s.label));let n=Object.assign({},e);n.hidden=i.group===this.getMessage("snkGridConfig.group.hidden"),t.push(n)}))})),this.columns=t,this._dataChanged=!1,this.closeConfig(),this.save()}saveGridConfigOnStorage(t){k.saveGridConfig(t,this.configName,this.resourceID).then((t=>{this.configChange.emit(t),this._orderList.clearHistory(),p.info(this.getMessage("snkGridConfig.info.successfullyConfigSaved"),{iconName:"check"})}))}reOrderPriorityColumns(t,i){let s=[];s=t.filter((t=>t.sort&&!0!==t.hidden)).map((t=>({label:t.label,orderIndex:0})));let e=0,n=[];return i.forEach((t=>{let i=s.find((i=>i.label===t.label));i&&(i.orderIndex=e,n.push(i),e++)})),n.length>0&&(s=n),s}save(){var t;let i;i=this.config?this.config:this.createConfigFromState(this.columns);let s,e=[];(null===(t=this._orderPriorityList)||void 0===t?void 0:t.length)>0&&(s=this.reOrderPriorityColumns(this.columns,this._orderPriorityList)),this.columns.forEach((t=>{let n=i.columns.find((i=>t.name===i.name));!0===t.hidden&&n||(n?n.width=t.width:!1===t.hidden&&(n={name:t.name,width:t.width,orderIndex:0}),n&&(t.sort?(n.ascending=t.sort.toUpperCase()===_.asc.value,s?function(t,i){if(s){let e=s.find((i=>i.label===t.label));e&&(i.orderIndex=e.orderIndex)}}(t,n):n.orderIndex=t.sortIndex):(delete n.ascending,n.orderIndex=0),e.push(n)))})),i.columns=e,this.saveGridConfigOnStorage(i)}createConfigFromState(t){let i={columns:[]};return t.forEach((t=>{if(!t.hidden){let s={name:t.name};t.width&&(s.width=t.width),t.sort?(s.ascending=t.sort.toUpperCase()===_.asc.value,s.orderIndex=t.sortIndex):s.orderIndex=0,s&&i.columns.push(s)}})),i}async locateColumn(t,i){var s;const e="Enter"===t.key;if(!(i=i||(null===(s=t.currentTarget)||void 0===s?void 0:s.value)))return void this.removeSelection();const n=await this.getMatchedIndexes(i),o=this.getNewSelectedIndex(n,e);this._selectedIndex=o,1===this.selectedIndex?this.updateOrderListSelection(o):this.updateColumnListSelection(o)}async getMatchedIndexes(t){const i=[];return 1===this.selectedIndex?(await this._orderList.getList()).forEach(((s,e)=>{this.compareWords(s,t)&&i.push(e)})):this.columns.forEach(((s,e)=>{this.compareWords(s,t)&&i.push(e)})),i}getNewSelectedIndex(t,i){if(0===t.length)return-1;if(i)for(const i of t)if(i>this._selectedIndex)return i;return t[0]}updateOrderListSelection(t){-1!==t?this._orderList.getList().then((i=>{const s=i[t];s?this._orderList.setSelection(s,!0):this._orderList.removeSelection()})):this._orderList.removeSelection()}updateColumnListSelection(t){if(-1===t)return void this._columnList.removeSelection();const i=this.columns[t];if(i){const t=this._columListItems.map((t=>t.items)).flat().find((t=>t.label===i.label));t?this._columnList.setSelection(t,!0):this._columnList.removeSelection()}else this._columnList.removeSelection()}removeSelection(){1===this.selectedIndex?this._orderList.removeSelection():this._columnList.removeSelection()}compareWords(t,i){var s,e;const n=null===(s=r.replaceAccentuatedChars(null==t?void 0:t.label))||void 0===s?void 0:s.toUpperCase(),o=null===(e=r.replaceAccentuatedChars(i))||void 0===e?void 0:e.toUpperCase();return!r.isEmpty(n)&&!r.isEmpty(o)&&n.includes(o)}getColumnNames(){const t=[];return t.push(this.getMessage("snkGridConfig.tab.columns")),t.push(this.getMessage("snkGridConfig.tab.lineOrdering")),t.join(",")}closeConfig(){if(this._orderList.scrollToTop(),this._columnList.scrollToTop(),this._searchElement.value="",this._dataChanged){let t={canClose:!1,labelCancel:this.getMessage("snkGridConfig.confirm.cancel"),labelConfirm:this.getMessage("snkGridConfig.confirm.save"),btnConfirmDanger:!1};p.confirm(this.getMessage("snkGridConfig.confirm.alert"),this.getMessage("snkGridConfig.confirm.msgCancel"),null,v.WARN,t).then((t=>{t?this.finish():(this._dataChanged=!1,this.configCancel.emit(),this._orderList.clearHistory(),this._componenteInternalKey=Date.now())}))}else this.configCancel.emit(),this._orderList.clearHistory()}handleTabChange(t){null!=(null==t?void 0:t.index)&&(this.selectedIndex!==t.index&&(0===t.index?this._orderList.scrollToTop():1===t.index&&this._columnList.scrollToTop(),this._searchElement.value=""),1===t.index&&this.createOrderList(),this.selectedIndex=t.index)}handleColumnListChange(t){var i;if(t.detail){let s=null===(i=t.detail.find((t=>t.group===this.getMessage("snkGridConfig.group.visible"))))||void 0===i?void 0:i.items;s&&(this._dataChanged=!0,this._orderListItems=s)}}handleOrderListChange(t){if(t.detail){let i=t.detail;i&&(this._dataChanged=!0,this._orderPriorityList=i)}}componentWillRender(){var t;(null===(t=this.columns)||void 0===t?void 0:t.length)>0&&this.createColumnList()}componentDidRender(){var t;(null===(t=this.columns)||void 0===t?void 0:t.length)>0&&this.locateColumn(new KeyboardEvent("arrow-right",{key:"ArrowRight"}),this._searchElement.value)}componentDidLoad(){u.addIDInfo(this._element)}render(){return i(s,null,i("div",{class:"grid-config__header"},i("div",{class:"title-container"},i("div",{class:""},i("label",{class:"title"},this.getMessage("snkGridConfig.gridConfiguration")),i("label",{class:"subtitle"},this.getMessage("snkGridConfig.columnVisibilityOrder"))),i("div",{class:"button-close"},i("ez-button",{mode:"icon",iconName:"close",size:"medium",onClick:()=>this.closeConfig()}))),i("div",{class:"tabselector-container"},i("ez-tabselector",{selectedIndex:this.selectedIndex,onEzChange:t=>{this.handleTabChange(t.detail)},tabs:this.getColumnNames()})),i("div",null,i("ez-text-input",{"data-element-id":"searchColums",ref:t=>this._searchElement=t,label:this.getMessage("snkGridConfig.findColumn"),onKeyUp:t=>this.locateColumn(t)},i("ez-icon",{slot:"leftIcon",size:"medium",iconName:"search"})))),i("div",{class:"grid-config__main"},i("ez-list",{ref:t=>this._columnList=t,class:0===this.selectedIndex?"":"hidden",dataSource:this._columListItems,onEzChange:t=>this.handleColumnListChange(t),ezDraggable:!0,ezSelectable:!0,itemSlotBuilder:(t,i)=>this.buildColumnListSlot(t,i),useGroups:!0,"data-element-id":"configCols"}),i("div",{class:1===this.selectedIndex?"group-name":"hidden"},this.getMessage("snkGridConfig.info.sortingSequence")),i("ez-list",{ref:t=>this._orderList=t,class:1===this.selectedIndex?"height-calc":"hidden",dataSource:this._orderListItems,ezSelectable:!0,onEzChange:t=>this.handleOrderListChange(t),ezDraggable:!0,itemSlotBuilder:t=>this.buildOrderListSlot(t),"data-element-id":"configDataOrder"})),i("div",{class:"grid-config__footer"},i("ez-button",{class:"padding-right--medium",label:this.getMessage("snkGridConfig.cancel"),onClick:()=>this.closeConfig()}),i("ez-button",{label:this.getMessage("snkGridConfig.complete"),class:"ez-button--primary",onClick:()=>this.finish()})))}static get assetsDirs(){return["../assets"]}get _element(){return e(this)}};I.style='.sc-snk-grid-config-h{--snk-grid-config__footer--padding-top:var(--space--medium, 12px);--snk-grid-config__main--padding-right:var(--space--medium, 12px);--snk-grid-config__tabselector-container--padding:var(--space--medium, 12px);--snk-grid-config__button-close--padding-left:var(--space--medium, 12px);--snk-grid-config__title--color:var(--title--primary, #2B3A54);--snk-grid-config__title--font-family:var(--font-pattern, "Roboto");--snk-grid-config__title--font-size:var(--title--large, 20px);--snk-grid-config__title--font-weight:var(--text-weight--extra-large, 700);--snk-grid-config__subtitle--font-family:var(--font-pattern, "Roboto");--snk-grid-config__subtitle--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-family:var(--font-pattern, "Roboto");--snk-grid-config__group--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-weight:var(--text-weight--large, 600);--snk-grid-config__group--padding-bottom:var(--space-small, 6px);--snk-grid-config__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-grid-config__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-grid-config__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-grid-config__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-grid-config__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-grid-config__scrollbar--width:var(--space--medium, 12px);display:grid;grid-template-rows:auto 1fr auto;max-height:100%;width:100%}@media screen and (min-width: 480px){.sc-snk-grid-config-h{width:359px;max-width:359px}}.padding-right--medium.sc-snk-grid-config{padding-right:var(--space--medium)}ez-list.sc-snk-grid-config{height:100%}.height-calc.sc-snk-grid-config{max-height:calc(100% - 24px)}.grid-config__footer.sc-snk-grid-config{display:flex;justify-content:flex-end;width:100%;padding-top:var(--snk-grid-config__footer--padding-top)}.hidden.sc-snk-grid-config{display:none}.tabselector-container.sc-snk-grid-config{padding:var(--snk-grid-config__tabselector-container--padding) 0}.button-close.sc-snk-grid-config{padding-left:var(--snk-grid-config__button-close--padding-left)}.title-container.sc-snk-grid-config{display:flex;justify-content:space-between;align-items:center;width:100%}.title.sc-snk-grid-config{display:flex;margin:0;line-height:normal;letter-spacing:0em;text-align:left;color:var(--snk-grid-config__title--color);font-size:var(--snk-grid-config__title--font-size);font-family:var(--snk-grid-config__title--font-family);font-weight:var(--snk-grid-config__title--font-weight)}.subtitle.sc-snk-grid-config{color:var(--text--primary);font-size:var(--snk-grid-config__subtitle--font-size);font-family:var(--snk-grid-config__subtitle--font-family)}.grid-config__main.sc-snk-grid-config{overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--snk-grid-config__scrollbar--color-clicked) var(--snk-grid-config__scrollbar--color-background);padding-right:var(--snk-grid-config__main--padding-right)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar{width:var(--snk-grid-config__scrollbar--width);max-width:var(--snk-grid-config__scrollbar--width);min-width:var(--snk-grid-config__scrollbar--width);background-color:var(--snk-grid-config__scrollbar--color-background)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-track{background-color:var(--snk-grid-config__scrollbar--color-background);border-radius:var(--snk-grid-config__scrollbar--border-radius)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb{background-color:var(--snk-grid-config__scrollbar--color-default);border-radius:var(--snk-grid-config__scrollbar--border-radius)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:vertical:hover,.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--snk-grid-config__scrollbar--color-hover)}.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:vertical:active,.grid-config__main.sc-snk-grid-config::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--snk-grid-config__scrollbar--color-clicked)}.group-name.sc-snk-grid-config{font-family:var(--snk-grid-config__group--font-family);font-size:var(--snk-grid-config__group--font-size);font-weight:var(--snk-grid-config__group--font-weight);padding-bottom:var(--snk-grid-config__group--padding-bottom)}';const E=class{constructor(i){t(this,i),this.ezChange=n(this,"ezChange",7),this.selectedOption=_.none}render(){return i("ez-combo-box",{class:"grid-config-combo ez-input--inverted",label:"",suppressSearch:!0,value:this.selectedOption,enabled:!0,canShowError:!1,suppressEmptyOption:!0},Object.keys(_).map((t=>i("option",{value:_[t].value},_[t].label))))}static get assetsDirs(){return["../assets"]}};E.style="ez-combo-box{width:100px}.grid-config-combo{--ez-text-input--height:28px;--ez-text-input__input--background-color:#fff;--ez-text-input__input--border-color:#dce0e8}";const j=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: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)}};j.style=".sc-taskbar-actions-button-h{display:flex;width:fit-content;height:fit-content}";export{D as snk_actions_button,I as snk_grid_config,E as snk_select_box,j as taskbar_actions_button}