@sankhyalabs/sankhyablocks 8.16.0-dev.37 → 8.16.0-dev.39

Sign up to get free protection for your applications and to get access to all the features.
Files changed (51) hide show
  1. package/dist/cjs/{ContinuousInsertUtils-29b65619.js → ContinuousInsertUtils-c7e35e3b.js} +2 -2
  2. package/dist/cjs/{dataunit-fetcher-f89461c1.js → dataunit-fetcher-a36ae041.js} +2 -2
  3. package/dist/cjs/{pesquisa-fetcher-ca89181c.js → pesquisa-fetcher-490a86c3.js} +6 -1
  4. package/dist/cjs/snk-actions-button_4.cjs.entry.js +2 -2
  5. package/dist/cjs/snk-application.cjs.entry.js +2 -2
  6. package/dist/cjs/snk-attach.cjs.entry.js +2 -2
  7. package/dist/cjs/snk-crud.cjs.entry.js +2 -2
  8. package/dist/cjs/snk-data-exporter.cjs.entry.js +3 -3
  9. package/dist/cjs/{snk-data-unit-668dc5e8.js → snk-data-unit-b460f1da.js} +1 -1
  10. package/dist/cjs/snk-data-unit.cjs.entry.js +2 -2
  11. package/dist/cjs/snk-detail-view.cjs.entry.js +3 -3
  12. package/dist/cjs/snk-grid.cjs.entry.js +3 -3
  13. package/dist/cjs/{snk-guides-viewer-4236cb9d.js → snk-guides-viewer-de0a5c57.js} +2 -2
  14. package/dist/cjs/snk-guides-viewer.cjs.entry.js +3 -3
  15. package/dist/cjs/snk-simple-crud.cjs.entry.js +3 -3
  16. package/dist/collection/lib/http/data-fetcher/fetchers/data-unit/DataUnitDataLoader.js +2 -2
  17. package/dist/collection/lib/http/data-fetcher/fetchers/pesquisa-fetcher.js +6 -1
  18. package/dist/components/dataunit-fetcher.js +2 -2
  19. package/dist/components/pesquisa-fetcher.js +6 -1
  20. package/dist/esm/{ContinuousInsertUtils-30caa626.js → ContinuousInsertUtils-3e520a07.js} +2 -2
  21. package/dist/esm/{dataunit-fetcher-c24c76c6.js → dataunit-fetcher-fd58c640.js} +2 -2
  22. package/dist/esm/{pesquisa-fetcher-8edaa8cd.js → pesquisa-fetcher-50fc7e6b.js} +6 -1
  23. package/dist/esm/snk-actions-button_4.entry.js +2 -2
  24. package/dist/esm/snk-application.entry.js +2 -2
  25. package/dist/esm/snk-attach.entry.js +2 -2
  26. package/dist/esm/snk-crud.entry.js +2 -2
  27. package/dist/esm/snk-data-exporter.entry.js +3 -3
  28. package/dist/esm/{snk-data-unit-0fdfb6c2.js → snk-data-unit-590225b5.js} +1 -1
  29. package/dist/esm/snk-data-unit.entry.js +2 -2
  30. package/dist/esm/snk-detail-view.entry.js +3 -3
  31. package/dist/esm/snk-grid.entry.js +3 -3
  32. package/dist/esm/{snk-guides-viewer-8934c537.js → snk-guides-viewer-c1ef991c.js} +2 -2
  33. package/dist/esm/snk-guides-viewer.entry.js +3 -3
  34. package/dist/esm/snk-simple-crud.entry.js +3 -3
  35. package/dist/sankhyablocks/{p-49f1c9be.entry.js → p-06898e5a.entry.js} +1 -1
  36. package/dist/sankhyablocks/{p-dcead955.entry.js → p-11a0a7ac.entry.js} +1 -1
  37. package/dist/sankhyablocks/{p-16869f77.js → p-11cc69fc.js} +1 -1
  38. package/dist/sankhyablocks/{p-92eadb1c.entry.js → p-1b6d51bf.entry.js} +1 -1
  39. package/dist/sankhyablocks/{p-eb9f0407.entry.js → p-281bc322.entry.js} +1 -1
  40. package/dist/sankhyablocks/{p-7ac7932c.js → p-47bce500.js} +2 -2
  41. package/dist/sankhyablocks/{p-be5d8fcb.entry.js → p-47f79aa0.entry.js} +1 -1
  42. package/dist/sankhyablocks/{p-b9c67e45.entry.js → p-583517ba.entry.js} +1 -1
  43. package/dist/sankhyablocks/{p-01086ff7.entry.js → p-5ea74956.entry.js} +1 -1
  44. package/dist/sankhyablocks/{p-a75d242d.entry.js → p-656f0e51.entry.js} +1 -1
  45. package/dist/sankhyablocks/{p-1bf06cd3.js → p-8a9638ae.js} +1 -1
  46. package/dist/sankhyablocks/{p-2923c1b5.js → p-9f9b99d9.js} +1 -1
  47. package/dist/sankhyablocks/{p-430e4d3c.entry.js → p-d3341910.entry.js} +1 -1
  48. package/dist/sankhyablocks/{p-a42e7a1e.entry.js → p-dbe6174a.entry.js} +2 -2
  49. package/dist/sankhyablocks/{p-5dd8cf4f.js → p-fd13b4d2.js} +1 -1
  50. package/dist/sankhyablocks/sankhyablocks.esm.js +1 -1
  51. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import{ObjectUtils as t,DataUnit as e,DataType as r,DateUtils as n,StringUtils as s,ChangeOperation as a,ApplicationContext as i,UserInterface as o,DataUnitStorage as c}from"@sankhyalabs/core";import{D as l,d as u}from"./p-f3434fc4.js";import{DISTINCT_FILTER_NAME_PREFIX as d}from"@sankhyalabs/ezui/dist/collection/utils/constants";import{DataUnitTransient as h}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{ColumnFilterManager as m}from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import f from"@sankhyalabs/core/dist/utils/SortingUtils";import{R as _}from"./p-688dcb4c.js";class g{constructor(t){this._list=[],this._equalsFunction=t}async load(t,e,r,n){let s=[].concat(this._list);null!=t&&(s=this._list.filter((e=>t(e)))),null!=e&&(s=s.sort(e));const a=s.length;if(null!=n){const t=r||0;s=s.slice(t,n?t+n:s.length)}return Promise.resolve({result:s,count:a})}async distict(t){const e=[];let r=!1;for(const n of this._list){const s=t(n);null!=s&&(null!=s.value?e.push(s):r=!0)}return r&&e.push({key:"",value:null}),Promise.resolve(new Map(e.map((t=>[t.key,t.value]))))}async push(t){this._list.push(...t)}async clear(){this._list=[]}async delete(t){this._list=this._list.filter((e=>{for(const r of t)if(this._equalsFunction(e,r))return!1;return!0}))}async update(t){this._list=this._list.map((e=>{const r=t.find((t=>this._equalsFunction(e,t)));return null==r?e:r}))}async insert(t,e){const r=this._list.indexOf(t);-1!=r?this._list=this._list.slice(0,r).concat(e).concat(this._list.slice(r)):this._list.push(...e)}isOperating(){return!0}async isEmpty(){return Promise.resolve(0===this._list.length)}async count(){return Promise.resolve(this._list.length)}getFromCache(){return t.copy(this._list)}}class p{static setLoadingStatus(t,e){this._loadingStatus.set(t.name,e)}static isCacheEnabled(t){return!0}static cacheRecords(t,e,r,n){p.setLoadingStatus(t,n),p.isCacheEnabled(t)?this.getRepository(t).push(e):r&&this._repositories.delete(t.name)}static getSortingFunction(t,e){return f.getSortingFunction(t,e)}static async getDistinct(t,e){if(!p.isCacheEnabled(t))return Promise.resolve(m.compileDistinct(e,t));let r;const n=t.getLastLoadRequest();if(null!=n){const s=m.getColumnFilters(n.filters,e);r=m.getFilterFunction(t,Array.from(s.values()))}return new Promise(((n,s)=>{p.getRepository(t).distict((n=>{if(null!=r&&!r(n))return;const s=n[e];if(null==s)return{key:null,value:null};const a=null!=s.value?s.value:s;return{key:t.getFormattedValue(e,s),value:a}})).then((t=>{n(null!=t?Array.from(t.entries()).map((([t,e])=>({label:t,value:e,check:!0}))):void 0)})).catch((t=>s(t)))}))}static async loadData(t,r,n){try{if(p.isCacheEnabled(t)){if(["EZ_GRID_LOADING_SOURCE",e.CHANGING_PAGE_LOADING_SOURCE,e.ALL_RECORDS_SELECTION_SOURCE].includes(r.source)&&!await p.getRepository(t).isEmpty())return p.loadFromCache(t,r);p.getRepository(t).clear().catch((()=>{}))}return n(t,r)}catch(t){return console.error(t),Promise.reject(t)}}static insertRecords(t,e,r){p.isCacheEnabled(t)&&p.getRepository(t).insert(e,r)}static updateRecords(t,e){p.isCacheEnabled(t)&&p.getRepository(t).update(e)}static removeRecords(t,e){p.isCacheEnabled(t)&&p.getRepository(t).delete(e)}static async countRecords(t){return p.isCacheEnabled(t)?p.getRepository(t).count():Promise.resolve(0)}static getRepository(t){const e=t.name;return p._repositories.has(e)||p._repositories.set(e,new g(((t,e)=>t.__record__id__===e.__record__id__))),p._repositories.get(e)}static async loadFromCache(t,e){return new Promise(((r,n)=>{const s=m.getColumnFilters(e.filters,""),{limit:a,offset:i,sort:o}=e;p.getRepository(t).load(m.getFilterFunction(t,Array.from(s.values())),p.getSortingFunction(t,o),i,a).then((e=>{const n=p._loadingStatus.get(t.name),{count:s,result:o}=e,c=0==s?0:i+1,l=i+Math.min(o.length,a);r({records:o,paginationInfo:{count:s,currentPage:i/a,firstRecord:c,lastRecord:l,hasMore:n||l<s,total:n?void 0:s}})})).catch((t=>n(t)))}))}static getCachedRecords(t){return p.getRepository(t).getFromCache()}}function y(t,e,r){let n=t?[...t]:[];n=function(t,e,r){const n=m.getColumnFilters(r,"");if(!(null==n?void 0:n.size))return t;const s=m.getFilterFunction(e,Array.from(n.values()));return null==s?t:t.filter(s)}(n,e,r.filters),n=function(t,e,r){if(null==r||0==r.length)return t;const n=p.getSortingFunction(e,r);return null==n?t:t.sort(n)}(n,e,r.sort);const{offset:s,limit:a}=r,i={recordsLength:n.length,offset:s,recordsPerPage:a};return Promise.resolve({records:v(n,s,a),paginationInfo:b(i)})}function v(t,e=0,r=0){return t&&t.length&&function(t,e){return t>=0&&e>=0}(e,r)?0===r&&0===e?t:t.slice(e,e+r):[]}function b({recordsLength:t=0,offset:e=0,recordsPerPage:r=0}){if(!t)return{currentPage:0,firstRecord:0,lastRecord:0,total:0,hasMore:!1};const n=e+r,s=n?Math.min(n,t):t;return{currentPage:0===r?0:Math.ceil(e/r),firstRecord:e+1,lastRecord:s,total:t,hasMore:s<t}}p._repositories=new Map,p._loadingStatus=new Map;class P{constructor(t,r,n){this.metadata=t,this.records=r,this._dataUnit=new e(P.IN_MEMORY_DATA_UNIT_NAME),this._dataUnit.pageSize=150,this._dataUnit.metadataLoader=()=>this.metadaLoader(),this._dataUnit.dataLoader=(t,e)=>this.inMemoryLoader(t,e,this.getRecordsToLoad()),this._dataUnit.saveLoader=(t,e)=>this.saveLoader(t,e),this._dataUnit.removeLoader=(t,e)=>this.removeLoader(t,e),this.dataUnit.loadMetadata().then((()=>{!1!==(null==n?void 0:n.autoLoad)&&this.dataUnit.loadData()}))}getRecordsToLoad(){null==this._initialRecords&&this.dataUnit.records.length>0&&(this._initialRecords=this.dataUnit.records);const t=this.dataUnit.getAddedRecords();return t?[...this._initialRecords,...t]:this._initialRecords}get dataUnit(){return this._dataUnit}get records(){return this.dataUnit.records}static getConvertedValue(t,e){return t.dataType===r.BOOLEAN?"S"===e:t.dataType===r.NUMBER?Number(e):t.dataType===r.DATE?n.strToDate(e,!0):t.dataType===r.OBJECT?JSON.parse(e):e}set records(t){const e=this._metadata?new Map(this._metadata.fields.map((t=>[t.name,t]))):void 0,r=null==t?void 0:t.map((t=>{if(t.__record__id__||(t.__record__id__=this.generateUniqueId()),null!=e)for(const r in t){const n=t[r];"string"==typeof n&&e.has(r)&&(t[r]=P.getConvertedValue(e.get(r),n))}return t}));this._initialRecords=r,this._dataUnit&&this._dataUnit.loadData()}get metadata(){return this._metadata}set metadata(t){this._metadata=t,this._dataUnit&&(this._dataUnit.metadata=this._metadata)}generateUniqueId(){return s.generateUUID()}inMemoryLoader(t,e,r){return y(r,t,e)}metadaLoader(){return Promise.resolve(this._metadata)}saveLoader(t,e){return new Promise((t=>{let r=[];e.forEach((t=>{let{record:e,updatingFields:n,operation:s}=t;const i=Object.assign(Object.assign({},e),n);if(s===a.INSERT||s===a.COPY)i.__old__id__=e.__record__id__,i.__record__id__=this.generateUniqueId(),this.records.push(i);else{const t=this.records.findIndex((t=>t.__record__id__==i.__record__id__));this.records[t]=i}r.push(i)})),t(r)}))}removeLoader(t,e){return new Promise((t=>{t(e)}))}}function D(t,e){var r,n;return void 0!==(null===(r=t[e])||void 0===r?void 0:r.value)?null===(n=t[e])||void 0===n?void 0:n.value:t[e]}P.IN_MEMORY_DATA_UNIT_NAME="InMemoryDataUnit";class N{canSlice(){return!1}processSortingSide(t,e,r){var n;const s=[],a=[];if(null!=t.sort){if(0===r.length)return{localSorting:t.sort,serverSorting:[]};for(const r of t.sort){const t=e.getField(r.field);"true"===(null===(n=null==t?void 0:t.properties)||void 0===n?void 0:n.calculated)||(null==t?void 0:t.userInterface)===o.LONGTEXT?s.push(r):a.push(r)}}return{localSorting:s,serverSorting:a}}async load(t,e,r){var n,s;if(null==t.metadata)return Promise.resolve({records:[],loadingInfo:r});try{const a=null!==(s=null===(n=e.filters)||void 0===n?void 0:n.filter((t=>!t.name.startsWith("FILTRO_COLUNA_"))))&&void 0!==s?s:[],{localSorting:i,serverSorting:o}=this.processSortingSide(e,t,a),c=this.getFieldsList(t),u="DatasetSP.loadRecords",d=this.buildRequestBody(u,c,t,e,r,o,a),h=r.quiet?{urlParams:{quietMode:"true"}}:void 0,{result:m,pagerID:f}=await l.get().callServiceBroker(u,d,h),_=this.processRecords(t,c,m),g=null!=f,p=r.count+_.length,y=t.hasNewRecord(),v=!g&&i.length>0;return v&&y&&t.setWaitingToReload(!0),Promise.resolve({records:_,loadingInfo:Object.assign(Object.assign({},r),{pagerId:f,loadingInProgress:g,total:g?void 0:p,count:p,needReload:v&&!y})})}catch(t){return console.error(t),Promise.reject(t)}}async loadRowMetadata(t,e,r,n={}){try{const s="DatasetSP.loadRowMetadata",a=await this.buildRequestBodyLoadRowMetadata({snkDataUnit:t,fieldName:e,metadataName:r,serviceName:s,updatedFields:n});return await l.get().callServiceBroker(s,a)}catch(t){return console.error(t),Promise.reject(t)}}async buildRequestBodyLoadRowMetadata({snkDataUnit:t,serviceName:e,fieldName:r,metadataName:n,updatedFields:s}){const a=t.dataUnit,i=O.parseDataUnitName(a.name).entityName,o=(await t.getSelectedRecordsIDsInfo()).reduce(((t,e)=>(t[e.name]=e.value,t)),{}),c=a.getSelectedRecord(),l=a.metadata.fields.filter((({standAlone:t,name:e})=>!t&&!e.includes("."))).map((({name:t})=>t)),u=l.reduce(((t,e,r)=>{const n=D(c,e),a=D(s,e);return t[r]=void 0!==a?a:n,t}),{});return JSON.stringify({serviceName:e,requestBody:{dataSetID:a.dataUnitId,entityName:i,standAlone:!1,metadataName:n,fieldName:r,fields:l,record:{pk:o,oldPk:o,values:u}}})}getFieldsList(t){let e=["__record__id__","__record__label__"];return t.metadata.fields.forEach((t=>{t.standAlone||(e=e.concat(this.getFieldNames(t)))})),e}getStandAloneFieldsList(t){let e={};return t.metadata.fields.forEach((t=>{t.standAlone&&(e=Object.assign(Object.assign({},e),{[t.name]:{fieldType:t.dataType,userType:t.userInterface}}))})),e}getFieldNames(t){const e=this.getSearchDescriptionField(t);return null==e?t.name:[t.name,e]}buildRequestBody(t,e,r,n,s,a,i){const o=r.dataUnitId,c=O.parseDataUnitName(r.name).entityName,l=!(!n.limit&&!n.offset),u={serviceName:t,requestBody:{dataSetID:o,fields:e,entityName:c,pageNumber:s.pageNumber,totalRecordsCount:s.count,pagerID:s.pagerId,standAlone:!1,standAloneFieldsMD:Object.assign({__record__id__:{fieldType:"S",userType:"P"},__record__label__:{fieldType:"S",userType:"P"}},this.getStandAloneFieldsList(r)),tryJoinedFields:!0,parallelLoader:l,crudListener:`br.com.sankhya.bff.${this.getModuleName()}.BFFDataUnitDatasetAdapter`,txProperties:this.getTxProperties(r,n,a,i),useDefaultRowsLimit:!1}};return JSON.stringify(u)}getModuleName(){return i.getContextValue("__SNK__APPLICATION__").getModuleName().replace("-bff","")}getTxProperties(t,e,r,n){const s={"__DATA_UNIT_ADAPTER__[dataUnitName]":t.name};0!==n.length&&(s["__DATA_UNIT_ADAPTER__[criteria]"]=JSON.stringify(n)),null!=r&&0!==r.length&&(s["__DATA_UNIT_ADAPTER__[sorting]"]=JSON.stringify(r)),null!=e.parentRecordId&&(s["__DATA_UNIT_ADAPTER__[parentRecordId]"]=e.parentRecordId);const a=t.getGlobalLoaderProps();return null==a||0===a.size||Array.from(a.entries()).forEach((([t,e])=>{s[t]=e})),s}processRecords(t,e,r){return r.map((r=>{const n={__record__id__:r[0],__record__label__:r[1],__record__metadata__:r[r.length-1]._rmd};return t.metadata.fields.forEach((t=>{n[t.name]=this.buildFieldValue(t,e,r)})),n}))}buildFieldValue(t,e,r){const n=e.indexOf(t.name);if(n<0)return null;const a=r[n];if(s.isEmpty(a))return null;const i=this.getSearchDescriptionField(t);if(null!=i){const t=e.indexOf(i);if(t>=0)return{value:a,label:r[t]}}return t.userInterface===o.SEARCH?isNaN(Number(a))?a:Number(a):P.getConvertedValue(t,a)}getSearchDescriptionField(t){if(t.userInterface===o.SEARCH){const{ENTITYNAME:e,mergedFrom:r,DESCRIPTIONFIELD:n}=t.properties;if(!s.isEmpty(n))return null!=r?`${r}.${e}.${n}`:`${e}.${n}`}}}class I{static async debounce(t,e){const r=t.name;I._debouncingTimeouts[r]&&(clearTimeout(I._debouncingTimeouts[r]),delete I._debouncingTimeouts[r]),I._debouncingTimeouts[r]=setTimeout((()=>{delete I._debouncingTimeouts[r],e()}),100)}static async loadData(t,e){return new Promise(((r,n)=>{I.debounce(t,(()=>{p.loadData(t,e,this.loadFromServer).then((t=>r(t))).catch((t=>n(t)))}))}))}static getCachedRecords(t){return p.getCachedRecords(t)}static async loadFromServer(t,e,r){try{r=I.registryLoading(t,r);const n=await I.callLoader(t,e,r);if(null==n)return;const s=n.records,a=I.buildPaginationInfo(s.length,e,n.loadingInfo),i=null==a?s:s.slice(0,a.lastRecord);return Promise.resolve({records:i,paginationInfo:a})}catch(t){return console.error(t),Promise.reject(t)}}static async callLoader(t,e,r,n){null==n&&(n=new N);const s=await n.load(t,e,r),{records:a,loadingInfo:i}=s;if(I.isOldRequest(t,i))return Promise.resolve(void 0);const o=!n.canSlice()||0===i.count;if(p.cacheRecords(t,a,o,i.loadingInProgress),p.isCacheEnabled(t)&&i.loadingInProgress){const r=Object.assign(Object.assign({},e),{offset:i.count}),s=Object.assign(Object.assign({},i),{pageNumber:(i.pageNumber||0)+1,quiet:!0});this.callLoader(t,r,s,n).then((e=>I.afterLoadingPage(t,e.loadingInfo))).catch((t=>console.error(t)))}return Promise.resolve(s)}static afterLoadingPage(t,e){p.setLoadingStatus(t,e.loadingInProgress);const r=t.getPaginationInfo();if(null==r)return;const n=e.count;e.loadingInProgress?t.updatePagination(Object.assign(Object.assign({},r),{count:n})):e.needReload?t.gotoPage(0):t.updatePagination(Object.assign(Object.assign({},r),{total:n,count:n}))}static registryLoading(t,e){return null==e&&(e={requestTime:(new Date).getTime(),count:0}),I._requestTimeByDataUnit.set(t.name,e.requestTime),e}static isOldRequest(t,e){return I._requestTimeByDataUnit.get(t.name)>e.requestTime}static buildPaginationInfo(t,e,r){let{limit:n,offset:s}=e;if(!n)return;1===r.pageNumber&&(s=0);const{total:a,count:i,loadingInProgress:o}=r,c=0===i||0===t?0:s+1,l=s+Math.min(t,n);return{total:a,count:i,lastRecord:l,firstRecord:c,currentPage:s/n,hasMore:l<i||o}}}I._requestTimeByDataUnit=new Map,I._debouncingTimeouts={};const R=/dd:\/\/([^/]+)\/([^/?]+)/;class O{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",u.gql`query($name: String!) {
1
+ import{ObjectUtils as t,DataUnit as e,DataType as r,DateUtils as n,StringUtils as s,ChangeOperation as a,ApplicationContext as i,UserInterface as o,DataUnitStorage as c}from"@sankhyalabs/core";import{D as l,d as u}from"./p-f3434fc4.js";import{DISTINCT_FILTER_NAME_PREFIX as d}from"@sankhyalabs/ezui/dist/collection/utils/constants";import{DataUnitTransient as h}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{ColumnFilterManager as m}from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import f from"@sankhyalabs/core/dist/utils/SortingUtils";import{R as _}from"./p-688dcb4c.js";class g{constructor(t){this._list=[],this._equalsFunction=t}async load(t,e,r,n){let s=[].concat(this._list);null!=t&&(s=this._list.filter((e=>t(e)))),null!=e&&(s=s.sort(e));const a=s.length;if(null!=n){const t=r||0;s=s.slice(t,n?t+n:s.length)}return Promise.resolve({result:s,count:a})}async distict(t){const e=[];let r=!1;for(const n of this._list){const s=t(n);null!=s&&(null!=s.value?e.push(s):r=!0)}return r&&e.push({key:"",value:null}),Promise.resolve(new Map(e.map((t=>[t.key,t.value]))))}async push(t){this._list.push(...t)}async clear(){this._list=[]}async delete(t){this._list=this._list.filter((e=>{for(const r of t)if(this._equalsFunction(e,r))return!1;return!0}))}async update(t){this._list=this._list.map((e=>{const r=t.find((t=>this._equalsFunction(e,t)));return null==r?e:r}))}async insert(t,e){const r=this._list.indexOf(t);-1!=r?this._list=this._list.slice(0,r).concat(e).concat(this._list.slice(r)):this._list.push(...e)}isOperating(){return!0}async isEmpty(){return Promise.resolve(0===this._list.length)}async count(){return Promise.resolve(this._list.length)}getFromCache(){return t.copy(this._list)}}class p{static setLoadingStatus(t,e){this._loadingStatus.set(t.name,e)}static isCacheEnabled(t){return!0}static cacheRecords(t,e,r,n){p.setLoadingStatus(t,n),p.isCacheEnabled(t)?this.getRepository(t).push(e):r&&this._repositories.delete(t.name)}static getSortingFunction(t,e){return f.getSortingFunction(t,e)}static async getDistinct(t,e){if(!p.isCacheEnabled(t))return Promise.resolve(m.compileDistinct(e,t));let r;const n=t.getLastLoadRequest();if(null!=n){const s=m.getColumnFilters(n.filters,e);r=m.getFilterFunction(t,Array.from(s.values()))}return new Promise(((n,s)=>{p.getRepository(t).distict((n=>{if(null!=r&&!r(n))return;const s=n[e];if(null==s)return{key:null,value:null};const a=null!=s.value?s.value:s;return{key:t.getFormattedValue(e,s),value:a}})).then((t=>{n(null!=t?Array.from(t.entries()).map((([t,e])=>({label:t,value:e,check:!0}))):void 0)})).catch((t=>s(t)))}))}static async loadData(t,r,n){try{if(p.isCacheEnabled(t)){if(["EZ_GRID_LOADING_SOURCE",e.CHANGING_PAGE_LOADING_SOURCE,e.ALL_RECORDS_SELECTION_SOURCE].includes(r.source)&&!await p.getRepository(t).isEmpty())return p.loadFromCache(t,r);p.getRepository(t).clear().catch((()=>{}))}return n(t,r)}catch(t){return console.error(t),Promise.reject(t)}}static insertRecords(t,e,r){p.isCacheEnabled(t)&&p.getRepository(t).insert(e,r)}static updateRecords(t,e){p.isCacheEnabled(t)&&p.getRepository(t).update(e)}static removeRecords(t,e){p.isCacheEnabled(t)&&p.getRepository(t).delete(e)}static async countRecords(t){return p.isCacheEnabled(t)?p.getRepository(t).count():Promise.resolve(0)}static getRepository(t){const e=t.name;return p._repositories.has(e)||p._repositories.set(e,new g(((t,e)=>t.__record__id__===e.__record__id__))),p._repositories.get(e)}static async loadFromCache(t,e){return new Promise(((r,n)=>{const s=m.getColumnFilters(e.filters,""),{limit:a,offset:i,sort:o}=e;p.getRepository(t).load(m.getFilterFunction(t,Array.from(s.values())),p.getSortingFunction(t,o),i,a).then((e=>{const n=p._loadingStatus.get(t.name),{count:s,result:o}=e,c=0==s?0:i+1,l=i+Math.min(o.length,a);r({records:o,paginationInfo:{count:s,currentPage:i/a,firstRecord:c,lastRecord:l,hasMore:n||l<s,total:n?void 0:s}})})).catch((t=>n(t)))}))}static getCachedRecords(t){return p.getRepository(t).getFromCache()}}function y(t,e,r){let n=t?[...t]:[];n=function(t,e,r){const n=m.getColumnFilters(r,"");if(!(null==n?void 0:n.size))return t;const s=m.getFilterFunction(e,Array.from(n.values()));return null==s?t:t.filter(s)}(n,e,r.filters),n=function(t,e,r){if(null==r||0==r.length)return t;const n=p.getSortingFunction(e,r);return null==n?t:t.sort(n)}(n,e,r.sort);const{offset:s,limit:a}=r,i={recordsLength:n.length,offset:s,recordsPerPage:a};return Promise.resolve({records:v(n,s,a),paginationInfo:b(i)})}function v(t,e=0,r=0){return t&&t.length&&function(t,e){return t>=0&&e>=0}(e,r)?0===r&&0===e?t:t.slice(e,e+r):[]}function b({recordsLength:t=0,offset:e=0,recordsPerPage:r=0}){if(!t)return{currentPage:0,firstRecord:0,lastRecord:0,total:0,hasMore:!1};const n=e+r,s=n?Math.min(n,t):t;return{currentPage:0===r?0:Math.ceil(e/r),firstRecord:e+1,lastRecord:s,total:t,hasMore:s<t}}p._repositories=new Map,p._loadingStatus=new Map;class P{constructor(t,r,n){this.metadata=t,this.records=r,this._dataUnit=new e(P.IN_MEMORY_DATA_UNIT_NAME),this._dataUnit.pageSize=150,this._dataUnit.metadataLoader=()=>this.metadaLoader(),this._dataUnit.dataLoader=(t,e)=>this.inMemoryLoader(t,e,this.getRecordsToLoad()),this._dataUnit.saveLoader=(t,e)=>this.saveLoader(t,e),this._dataUnit.removeLoader=(t,e)=>this.removeLoader(t,e),this.dataUnit.loadMetadata().then((()=>{!1!==(null==n?void 0:n.autoLoad)&&this.dataUnit.loadData()}))}getRecordsToLoad(){null==this._initialRecords&&this.dataUnit.records.length>0&&(this._initialRecords=this.dataUnit.records);const t=this.dataUnit.getAddedRecords();return t?[...this._initialRecords,...t]:this._initialRecords}get dataUnit(){return this._dataUnit}get records(){return this.dataUnit.records}static getConvertedValue(t,e){return t.dataType===r.BOOLEAN?"S"===e:t.dataType===r.NUMBER?Number(e):t.dataType===r.DATE?n.strToDate(e,!0):t.dataType===r.OBJECT?JSON.parse(e):e}set records(t){const e=this._metadata?new Map(this._metadata.fields.map((t=>[t.name,t]))):void 0,r=null==t?void 0:t.map((t=>{if(t.__record__id__||(t.__record__id__=this.generateUniqueId()),null!=e)for(const r in t){const n=t[r];"string"==typeof n&&e.has(r)&&(t[r]=P.getConvertedValue(e.get(r),n))}return t}));this._initialRecords=r,this._dataUnit&&this._dataUnit.loadData()}get metadata(){return this._metadata}set metadata(t){this._metadata=t,this._dataUnit&&(this._dataUnit.metadata=this._metadata)}generateUniqueId(){return s.generateUUID()}inMemoryLoader(t,e,r){return y(r,t,e)}metadaLoader(){return Promise.resolve(this._metadata)}saveLoader(t,e){return new Promise((t=>{let r=[];e.forEach((t=>{let{record:e,updatingFields:n,operation:s}=t;const i=Object.assign(Object.assign({},e),n);if(s===a.INSERT||s===a.COPY)i.__old__id__=e.__record__id__,i.__record__id__=this.generateUniqueId(),this.records.push(i);else{const t=this.records.findIndex((t=>t.__record__id__==i.__record__id__));this.records[t]=i}r.push(i)})),t(r)}))}removeLoader(t,e){return new Promise((t=>{t(e)}))}}function D(t,e){var r,n;return void 0!==(null===(r=t[e])||void 0===r?void 0:r.value)?null===(n=t[e])||void 0===n?void 0:n.value:t[e]}P.IN_MEMORY_DATA_UNIT_NAME="InMemoryDataUnit";class I{canSlice(){return!1}processSortingSide(t,e,r){var n;const s=[],a=[];if(null!=t.sort){if(0===r.length)return{localSorting:t.sort,serverSorting:[]};for(const r of t.sort){const t=e.getField(r.field);"true"===(null===(n=null==t?void 0:t.properties)||void 0===n?void 0:n.calculated)||(null==t?void 0:t.userInterface)===o.LONGTEXT?s.push(r):a.push(r)}}return{localSorting:s,serverSorting:a}}async load(t,e,r){var n,s;if(null==t.metadata)return Promise.resolve({records:[],loadingInfo:r});try{const a=null!==(s=null===(n=e.filters)||void 0===n?void 0:n.filter((t=>!t.name.startsWith("FILTRO_COLUNA_"))))&&void 0!==s?s:[],{localSorting:i,serverSorting:o}=this.processSortingSide(e,t,a),c=this.getFieldsList(t),u="DatasetSP.loadRecords",d=this.buildRequestBody(u,c,t,e,r,o,a),h=r.quiet?{urlParams:{quietMode:"true"}}:void 0,{result:m,pagerID:f}=await l.get().callServiceBroker(u,d,h),_=this.processRecords(t,c,m),g=null!=f,p=r.count+_.length,y=t.hasNewRecord(),v=!g&&i.length>0;return v&&y&&t.setWaitingToReload(!0),Promise.resolve({records:_,loadingInfo:Object.assign(Object.assign({},r),{pagerId:f,loadingInProgress:g,total:g?void 0:p,count:p,needReload:v&&!y})})}catch(t){return console.error(t),Promise.reject(t)}}async loadRowMetadata(t,e,r,n={}){try{const s="DatasetSP.loadRowMetadata",a=await this.buildRequestBodyLoadRowMetadata({snkDataUnit:t,fieldName:e,metadataName:r,serviceName:s,updatedFields:n});return await l.get().callServiceBroker(s,a)}catch(t){return console.error(t),Promise.reject(t)}}async buildRequestBodyLoadRowMetadata({snkDataUnit:t,serviceName:e,fieldName:r,metadataName:n,updatedFields:s}){const a=t.dataUnit,i=O.parseDataUnitName(a.name).entityName,o=(await t.getSelectedRecordsIDsInfo()).reduce(((t,e)=>(t[e.name]=e.value,t)),{}),c=a.getSelectedRecord(),l=a.metadata.fields.filter((({standAlone:t,name:e})=>!t&&!e.includes("."))).map((({name:t})=>t)),u=l.reduce(((t,e,r)=>{const n=D(c,e),a=D(s,e);return t[r]=void 0!==a?a:n,t}),{});return JSON.stringify({serviceName:e,requestBody:{dataSetID:a.dataUnitId,entityName:i,standAlone:!1,metadataName:n,fieldName:r,fields:l,record:{pk:o,oldPk:o,values:u}}})}getFieldsList(t){let e=["__record__id__","__record__label__"];return t.metadata.fields.forEach((t=>{t.standAlone||(e=e.concat(this.getFieldNames(t)))})),e}getStandAloneFieldsList(t){let e={};return t.metadata.fields.forEach((t=>{t.standAlone&&(e=Object.assign(Object.assign({},e),{[t.name]:{fieldType:t.dataType,userType:t.userInterface}}))})),e}getFieldNames(t){const e=this.getSearchDescriptionField(t);return null==e?t.name:[t.name,e]}buildRequestBody(t,e,r,n,s,a,i){const o=r.dataUnitId,c=O.parseDataUnitName(r.name).entityName,l=!(!n.limit&&!n.offset),u={serviceName:t,requestBody:{dataSetID:o,fields:e,entityName:c,pageNumber:s.pageNumber,totalRecordsCount:s.count,pagerID:s.pagerId,standAlone:!1,standAloneFieldsMD:Object.assign({__record__id__:{fieldType:"S",userType:"P"},__record__label__:{fieldType:"S",userType:"P"}},this.getStandAloneFieldsList(r)),tryJoinedFields:!0,parallelLoader:l,crudListener:`br.com.sankhya.bff.${this.getModuleName()}.BFFDataUnitDatasetAdapter`,txProperties:this.getTxProperties(r,n,a,i),useDefaultRowsLimit:!1}};return JSON.stringify(u)}getModuleName(){return i.getContextValue("__SNK__APPLICATION__").getModuleName().replace("-bff","")}getTxProperties(t,e,r,n){const s={"__DATA_UNIT_ADAPTER__[dataUnitName]":t.name};0!==n.length&&(s["__DATA_UNIT_ADAPTER__[criteria]"]=JSON.stringify(n)),null!=r&&0!==r.length&&(s["__DATA_UNIT_ADAPTER__[sorting]"]=JSON.stringify(r)),null!=e.parentRecordId&&(s["__DATA_UNIT_ADAPTER__[parentRecordId]"]=e.parentRecordId);const a=t.getGlobalLoaderProps();return null==a||0===a.size||Array.from(a.entries()).forEach((([t,e])=>{s[t]=e})),s}processRecords(t,e,r){return r.map((r=>{const n={__record__id__:r[0],__record__label__:r[1],__record__metadata__:r[r.length-1]._rmd};return t.metadata.fields.forEach((t=>{n[t.name]=this.buildFieldValue(t,e,r)})),n}))}buildFieldValue(t,e,r){const n=e.indexOf(t.name);if(n<0)return null;const a=r[n];if(s.isEmpty(a))return null;const i=this.getSearchDescriptionField(t);if(null!=i){const t=e.indexOf(i);if(t>=0)return{value:a,label:r[t]}}return t.userInterface===o.SEARCH?isNaN(Number(a))?a:Number(a):P.getConvertedValue(t,a)}getSearchDescriptionField(t){if(t.userInterface===o.SEARCH){const{ENTITYNAME:e,mergedFrom:r,DESCRIPTIONFIELD:n}=t.properties;if(!s.isEmpty(n))return null!=r?`${r}.${e}.${n}`:`${e}.${n}`}}}class N{static async debounce(t,e){const r=t.name;N._debouncingTimeouts[r]&&(clearTimeout(N._debouncingTimeouts[r]),delete N._debouncingTimeouts[r]),N._debouncingTimeouts[r]=setTimeout((()=>{delete N._debouncingTimeouts[r],e()}),100)}static async loadData(t,e){return new Promise(((r,n)=>{N.debounce(t,(()=>{p.loadData(t,e,this.loadFromServer).then((t=>r(t))).catch((t=>n(t)))}))}))}static getCachedRecords(t){return p.getCachedRecords(t)}static async loadFromServer(t,e,r){try{r=N.registryLoading(t,r);const n=await N.callLoader(t,e,r);if(null==n)return;const s=n.records,a=N.buildPaginationInfo(s.length,e,n.loadingInfo),i=null==a?s:s.slice(0,a.lastRecord);return Promise.resolve({records:i,paginationInfo:a})}catch(t){return console.error(t),Promise.reject(t)}}static async callLoader(t,e,r,n){null==n&&(n=new I);const s=await n.load(t,e,r),{records:a,loadingInfo:i}=s;if(N.isOldRequest(t,i))return Promise.resolve(void 0);const o=!n.canSlice()||0===i.count;if(p.cacheRecords(t,a,o,i.loadingInProgress),p.isCacheEnabled(t)&&i.loadingInProgress){const r=Object.assign(Object.assign({},e),{offset:i.count}),s=Object.assign(Object.assign({},i),{pageNumber:(i.pageNumber||0)+1,quiet:!0});this.callLoader(t,r,s,n).then((e=>N.afterLoadingPage(t,e.loadingInfo))).catch((t=>console.error(t)))}return Promise.resolve(s)}static afterLoadingPage(t,e){p.setLoadingStatus(t,e.loadingInProgress);const r=t.getPaginationInfo();if(null==r)return;const n=e.count;e.loadingInProgress?t.updatePagination(Object.assign(Object.assign({},r),{count:n,loadingInProgress:!0})):e.needReload?t.gotoPage(0):t.updatePagination(Object.assign(Object.assign({},r),{total:n,count:n,loadingInProgress:!1}))}static registryLoading(t,e){return null==e&&(e={requestTime:(new Date).getTime(),count:0}),N._requestTimeByDataUnit.set(t.name,e.requestTime),e}static isOldRequest(t,e){return N._requestTimeByDataUnit.get(t.name)>e.requestTime}static buildPaginationInfo(t,e,r){let{limit:n,offset:s}=e;if(!n)return;1===r.pageNumber&&(s=0);const{total:a,count:i,loadingInProgress:o}=r,c=0===i||0===t?0:s+1,l=s+Math.min(t,n);return{total:a,count:i,lastRecord:l,firstRecord:c,currentPage:s/n,hasMore:l<i||o}}}N._requestTimeByDataUnit=new Map,N._debouncingTimeouts={};const R=/dd:\/\/([^/]+)\/([^/?]+)/;class O{constructor(){this.templateByQuery=new Map,this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchDataUnit",u.gql`query($name: String!) {
2
2
  $queryAlias$: fetchDataUnit(name: $name){
3
3
  name
4
4
  fields{
@@ -57,4 +57,4 @@ import{ObjectUtils as t,DataUnit as e,DataType as r,DateUtils as n,StringUtils a
57
57
  }
58
58
  }`),this.templateByQuery.set("fetchDistinctColumn",u.gql`query($dataUnit: String!, $fieldName: String!, $argument: String, $filters: [InputFilter], $parentRecordId: String) {
59
59
  $queryAlias$: selectDistinct(dataUnit: $dataUnit, fieldName: $fieldName, argument: $argument, filters: $filters, parentRecordId: $parentRecordId)
60
- }`)}static parseDataUnitName(t){if(null==t)return;const e=R.exec(t);return e?{entityName:e[1],resourceID:e[2]}:void 0}getDataUnit(t,r,n,s){null==p.applicationResourceID&&_.getResourceID().then((t=>p.applicationResourceID=t));const a=`dd://${t}/${r}${s?"/"+s:""}`,i=null!=n?n.getChildDataunit(a):new e(a);return i.metadataLoader=t=>this.loadMetadata(t),i.dataLoader=(t,e)=>I.loadData(t,e),i.saveLoader=(t,e)=>this.saveData(i,e),i.removeLoader=(t,e)=>this.removeRecords(t,e),i.recordLoader=(t,e)=>this.loadRecord(t,e),i.allRecordsLoader=t=>I.getCachedRecords(t),i}loadMetadata(t){return new Promise(((e,r)=>{l.get().callGraphQL({values:{name:t.name},query:this.templateByQuery.get("fetchDataUnit")}).then((t=>{var r;const n={name:t.name,label:t.name,children:[...t.children],fields:[]};null===(r=t.fields)||void 0===r||r.forEach((t=>{let e;Array.isArray(t.properties)&&(e={},t.calculated&&(e.gridHeaderTooltip="Campos calculados não podem ser ordenados"),t.properties.forEach((t=>e[t.name]=t.value))),n.fields.push(Object.assign(Object.assign({},t),{properties:e}))})),n.fields.sort(((t,e)=>t.order-e.order)),e(n)})).catch((t=>{r(t)}))}))}loadSelectDistinct(t,e,r){const{parentRecordId:n,filters:s}=t.getLastLoadRequest()||{},a=s.filter((t=>t.name!==`${d}${e}`)),i={dataUnit:t.name,argument:r,fieldName:e,parentRecordId:n,filters:a};return new Promise(((t,e)=>{l.get().callGraphQL({values:i,query:this.templateByQuery.get("fetchDistinctColumn")}).then((e=>{t(e)})).catch((t=>{e(t)}))}))}addTransientProperties(t,e){const r=t.getGlobalLoaderProps();return null==r||0===r.size||(null==e&&(e={}),Array.from(r.entries()).forEach((([t,r])=>{e[`transient.${t}`]=r}))),e}getUpdatingFields(t,e){if(null==e)return;const r=Object.assign({},e);return Object.keys(r).forEach((e=>{const n=t.getField(e);null!=n&&n.standAlone&&delete r[e]})),this.addTransientProperties(t,r)}saveData(t,e){const n=[],s=[],i=e.map((e=>{const{dataUnit:i,record:o,operation:l}=e,u=c.get(i),d=this.getUpdatingFields(u,e.updatingFields);let h;null!=d&&(h=Object.entries(d).map((([t,e])=>{const n=u.getField(t);return{fieldName:t,dataType:n?n.dataType:r.TEXT,value:u.valueToString(t,e)}}))),i===t.name&&(l===a.INSERT||l===a.COPY?s.push(o.__record__id__):n.push(o.__record__id__));const m={dataUnit:i,fields:h,operation:l,recordId:o.__record__id__};return e.sourceId&&(m.sourceId=e.sourceId),o.__parent__record__id__&&(m.parentRecordId=o.__parent__record__id__),m}));return new Promise(((e,r)=>{const a=i.map((t=>function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]])}return r}(t,[])));l.get().callGraphQL({values:{changes:a},query:this.templateByQuery.get("saveData")}).then((r=>{const a=[];null==r||r.forEach((e=>{const r={__record__id__:e.id,__record__label__:e.label,__owner__dataunit__name__:e.ownerDataUnitName},n=c.get(r.__owner__dataunit__name__)||t;e.oldId&&(r.__old__id__=e.oldId),e.fields.forEach((({name:t,value:e})=>{var s;const a=null===(s=null==n?void 0:n.valueFromString)||void 0===s?void 0:s.call(n,t,e);r[t]=void 0!==a?a:e})),a.push(r)})),this.updateCache(t,a,n,s),e(a)})).catch((t=>{r(t)}))}))}updateCache(t,e,r,n){const s=new Map(e.map((t=>[t.__old__id__||t.__record__id__,t]))),a=n.map((t=>{const e=Object.assign({},s.get(t));return delete e.__old__id__,e}));a.length>0&&p.insertRecords(t,t.records[0],a);const i=r.map((t=>Object.assign({},s.get(t))));p.updateRecords(t,i)}getTransientInfo(t,e){const{records:n}=t.getSelectionInfo();return Object.entries(n.filter((t=>t.__record__id__==e))[0]).filter((([t])=>t.startsWith(h.DATA_UNIT_TRANSIENT_PREFIX_NAME))).map((([t,e])=>({fieldName:t,value:e,dataType:r.TEXT})))}removeRecords(t,e){const r=e.map((e=>({dataUnit:t.name,operation:a.DELETE,recordId:e,fields:this.getTransientInfo(t,e)})));return new Promise(((n,s)=>{l.get().callGraphQL({values:{changes:r},query:this.templateByQuery.get("saveData")}).then((()=>{p.removeRecords(t,t.records.filter((t=>e.includes(t.__record__id__)))),n(e)})).catch((t=>{s(t)}))}))}loadRecord(t,e){return new Promise(((r,n)=>{l.get().callGraphQL({values:{recordID:e,dataunit:t.name},query:this.templateByQuery.get("fetchDataRecord")}).then((e=>{const n=[];e.record.forEach((e=>{const r={__record__id__:e.id,__record__label__:e.label};e.fields.forEach((({name:e,value:n})=>{r[e]=t.valueFromString(e,n)})),n.push(r)})),r(n)})).catch((t=>{n(t)}))}))}}export{O as D,P as I,p as P,N as a,y as b,D as g}
60
+ }`)}static parseDataUnitName(t){if(null==t)return;const e=R.exec(t);return e?{entityName:e[1],resourceID:e[2]}:void 0}getDataUnit(t,r,n,s){null==p.applicationResourceID&&_.getResourceID().then((t=>p.applicationResourceID=t));const a=`dd://${t}/${r}${s?"/"+s:""}`,i=null!=n?n.getChildDataunit(a):new e(a);return i.metadataLoader=t=>this.loadMetadata(t),i.dataLoader=(t,e)=>N.loadData(t,e),i.saveLoader=(t,e)=>this.saveData(i,e),i.removeLoader=(t,e)=>this.removeRecords(t,e),i.recordLoader=(t,e)=>this.loadRecord(t,e),i.allRecordsLoader=t=>N.getCachedRecords(t),i}loadMetadata(t){return new Promise(((e,r)=>{l.get().callGraphQL({values:{name:t.name},query:this.templateByQuery.get("fetchDataUnit")}).then((t=>{var r;const n={name:t.name,label:t.name,children:[...t.children],fields:[]};null===(r=t.fields)||void 0===r||r.forEach((t=>{let e;Array.isArray(t.properties)&&(e={},t.calculated&&(e.gridHeaderTooltip="Campos calculados não podem ser ordenados"),t.properties.forEach((t=>e[t.name]=t.value))),n.fields.push(Object.assign(Object.assign({},t),{properties:e}))})),n.fields.sort(((t,e)=>t.order-e.order)),e(n)})).catch((t=>{r(t)}))}))}loadSelectDistinct(t,e,r){const{parentRecordId:n,filters:s}=t.getLastLoadRequest()||{},a=s.filter((t=>t.name!==`${d}${e}`)),i={dataUnit:t.name,argument:r,fieldName:e,parentRecordId:n,filters:a};return new Promise(((t,e)=>{l.get().callGraphQL({values:i,query:this.templateByQuery.get("fetchDistinctColumn")}).then((e=>{t(e)})).catch((t=>{e(t)}))}))}addTransientProperties(t,e){const r=t.getGlobalLoaderProps();return null==r||0===r.size||(null==e&&(e={}),Array.from(r.entries()).forEach((([t,r])=>{e[`transient.${t}`]=r}))),e}getUpdatingFields(t,e){if(null==e)return;const r=Object.assign({},e);return Object.keys(r).forEach((e=>{const n=t.getField(e);null!=n&&n.standAlone&&delete r[e]})),this.addTransientProperties(t,r)}saveData(t,e){const n=[],s=[],i=e.map((e=>{const{dataUnit:i,record:o,operation:l}=e,u=c.get(i),d=this.getUpdatingFields(u,e.updatingFields);let h;null!=d&&(h=Object.entries(d).map((([t,e])=>{const n=u.getField(t);return{fieldName:t,dataType:n?n.dataType:r.TEXT,value:u.valueToString(t,e)}}))),i===t.name&&(l===a.INSERT||l===a.COPY?s.push(o.__record__id__):n.push(o.__record__id__));const m={dataUnit:i,fields:h,operation:l,recordId:o.__record__id__};return e.sourceId&&(m.sourceId=e.sourceId),o.__parent__record__id__&&(m.parentRecordId=o.__parent__record__id__),m}));return new Promise(((e,r)=>{const a=i.map((t=>function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]])}return r}(t,[])));l.get().callGraphQL({values:{changes:a},query:this.templateByQuery.get("saveData")}).then((r=>{const a=[];null==r||r.forEach((e=>{const r={__record__id__:e.id,__record__label__:e.label,__owner__dataunit__name__:e.ownerDataUnitName},n=c.get(r.__owner__dataunit__name__)||t;e.oldId&&(r.__old__id__=e.oldId),e.fields.forEach((({name:t,value:e})=>{var s;const a=null===(s=null==n?void 0:n.valueFromString)||void 0===s?void 0:s.call(n,t,e);r[t]=void 0!==a?a:e})),a.push(r)})),this.updateCache(t,a,n,s),e(a)})).catch((t=>{r(t)}))}))}updateCache(t,e,r,n){const s=new Map(e.map((t=>[t.__old__id__||t.__record__id__,t]))),a=n.map((t=>{const e=Object.assign({},s.get(t));return delete e.__old__id__,e}));a.length>0&&p.insertRecords(t,t.records[0],a);const i=r.map((t=>Object.assign({},s.get(t))));p.updateRecords(t,i)}getTransientInfo(t,e){const{records:n}=t.getSelectionInfo();return Object.entries(n.filter((t=>t.__record__id__==e))[0]).filter((([t])=>t.startsWith(h.DATA_UNIT_TRANSIENT_PREFIX_NAME))).map((([t,e])=>({fieldName:t,value:e,dataType:r.TEXT})))}removeRecords(t,e){const r=e.map((e=>({dataUnit:t.name,operation:a.DELETE,recordId:e,fields:this.getTransientInfo(t,e)})));return new Promise(((n,s)=>{l.get().callGraphQL({values:{changes:r},query:this.templateByQuery.get("saveData")}).then((()=>{p.removeRecords(t,t.records.filter((t=>e.includes(t.__record__id__)))),n(e)})).catch((t=>{s(t)}))}))}loadRecord(t,e){return new Promise(((r,n)=>{l.get().callGraphQL({values:{recordID:e,dataunit:t.name},query:this.templateByQuery.get("fetchDataRecord")}).then((e=>{const n=[];e.record.forEach((e=>{const r={__record__id__:e.id,__record__label__:e.label};e.fields.forEach((({name:e,value:n})=>{r[e]=t.valueFromString(e,n)})),n.push(r)})),r(n)})).catch((t=>{n(t)}))}))}}export{O as D,P as I,p as P,I as a,y as b,D as g}
@@ -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-afbb070d.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-f3434fc4.js";import"./p-1bf06cd3.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-7ac7932c.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import{T as l}from"./p-7e7a7473.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-16869f77.js";import{S as u}from"./p-17425c72.js";import"./p-4d9549cf.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-23736d75.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const h=[];this.dataState.hasPrevious||h.push(l.PREVIOUS),this.dataState.hasNext||h.push(l.NEXT),this.dataState.insertionMode&&h.push(l.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const t=this.formConfigManager.getConfig(this.dataUnit);this._formMetadata=r(null==t||0===t.fields.length?void 0:t,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){var i,s;this._viewStack=t,this._currentView=this.selectedForm?1:0,null===(s=null===(i=this._viewStack)||void 0===i?void 0:i.show)||void 0===s||s.call(i,this._currentView)}getFormFields(){return this.selectedForm&&this._formMetadata?this._formMetadata.getSheet(this.selectedForm).fields:[]}emitSwitchEvent(t){const i=t===c.GRID?this.stripFormPattern(this.branchGuide.id):this.getFormGuideId();i&&this.snkSwitchGuide.emit(i)}handleAttachBack(){this._viewStack.show(c.GRID)}executeActionHandler(t){t.detail===l.GRID_MODE&&(this.emitSwitchEvent(c.GRID),t.stopPropagation()),t.detail!==l.FORM_MODE&&t.detail!==l.UPDATE||(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.dataUnit),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===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-afbb070d.js";import{FormMetadata as n,buildFormMetadata as r}from"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-f3434fc4.js";import"./p-8a9638ae.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-47bce500.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import{T as l}from"./p-7e7a7473.js";import{d as c}from"./p-b0ef4383.js";import{S as m}from"./p-11cc69fc.js";import{S as u}from"./p-17425c72.js";import"./p-4d9549cf.js";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"./p-6dc031de.js";import"./p-23736d75.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";class v{constructor(t,i,s){this._parentGuide=t,this._formMetadata=i,this._dataUnit=s}get id(){return this._parentGuide.id}buildGuideItem(t){const i=Object.assign({},this._parentGuide);delete i.expanded,delete i.children;const s=this._dataUnit.getSelectedRecord();if(!s)return i;const e=this._dataUnit.isNewRecord(s.__record__id__),a=Array.from(this._formMetadata.getAllSheets().values()).map((i=>{const{name:s,label:a}=i,o=null!=n.getDetailName(s.split("::").pop()),h=o&&e,r=this._parentGuide.id,d=o?`${r}::${s}`:`${r}__FORM:${s}`;return o&&t.has(d)&&!h?t.get(d).buildGuideItem(t):{id:d,label:a,disabled:h,tooltip:h?"Finalize o cadastro para ter acesso a esta guia.":void 0}})),o=a.shift();return o.label=e?"Novo Registro":s.__record__label__,o.children=a,i.children=[o],i}}const p=class{constructor(s){t(this,s),this.snkDetailGuidesChange=i(this,"snkDetailGuidesChange",7),this.snkSwitchGuide=i(this,"snkSwitchGuide",7),this.formItemsReady=i(this,"formItemsReady",7),this._disabledButtons=void 0,this._currentView=void 0,this.attachmentRegisterKey=void 0,this.formConfigManager=void 0,this.dataUnitName=void 0,this.resourceID=void 0,this.guideItemPath=void 0,this.entityName=void 0,this.label=void 0,this.dataUnit=void 0,this.selectedForm=void 0,this.dataState=void 0,this.messagesBuilder=void 0,this.branchGuide=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.customEditors=void 0,this.customRenders=void 0}observeDataUnit(t,i){null==t||t.subscribe(this.dataUnitActionHandler.bind(this)),null==i||i.unsubscribe(this.dataUnitActionHandler)}observerDataState(t,i){const s=!(null==i?void 0:i.insertionMode)&&(null==t?void 0:t.insertionMode),e=(null==i?void 0:i.insertionMode)&&!(null==t?void 0:t.insertionMode);if((s||e)&&this.loadMetadata(),null==this._formMetadata)return;const a=null==t?void 0:t.selectedRecord,o=null==i?void 0:i.selectedRecord;(null==a?void 0:a.__record__id__)!==(null==o?void 0:o.__record__id__)&&this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit)),s&&setTimeout((()=>{this.changeViewMode(c.FORM)}),0),e&&this.changeViewMode(c.GRID);const h=[];this.dataState.hasPrevious||h.push(l.PREVIOUS),this.dataState.hasNext||h.push(l.NEXT),this.dataState.insertionMode&&h.push(l.INSERT),this._disabledButtons=h}async changeViewMode(t){this.emitSwitchEvent(t)}async configGrid(){this._snkGrid&&this._snkGrid.showConfig()}async showUp(){this._snkFormView&&this._snkFormView.showUp(),this._snkGrid&&this._snkGrid.scrollIntoView({behavior:"smooth",block:"start"})}async addCustomEditor(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);this._snkGrid.addCustomEditor(t,i,e),this._snkFormView.addCustomEditor(t,i,e)}async observerPropsCustomEditor(t){for(const i in t)await this.addCustomEditor(i,t[i])}async addGridCustomRender(t,i){var s;const e=this.normalizeBranchGuideId(null===(s=this.branchGuide)||void 0===s?void 0:s.id);await this._snkGrid.addGridCustomRender(t,i,e)}onContentCardChanged(t){m.updateContentCard(t.detail.formName,t.detail.cardConfig,t.detail.propertyChanged,this.formConfigManager).then((()=>s(this))),t.stopPropagation()}async observeCustomRenders(t){for(const i in t){const s=t[i];await this.addGridCustomRender(i,s)}}updateLabel(){const t=this.guideItemPath?this.guideItemPath.length:0;if(t>0){const i=t>0?this.guideItemPath.map((t=>t.label)):void 0;this.label=i.pop(),this._levelPath=i.length>0?i.join(" / "):void 0}else this.label="",this._levelPath=void 0}getFormGuideId(t){var i;if(!t){if(null==(null===(i=this.dataState)||void 0===i?void 0:i.selectedRecord))return;const s=Array.from(this._formMetadata.getAllSheets().keys());if(!s||0==s.length)return;t=s[0]}return`${this.stripFormPattern(this.branchGuide.id)}__FORM:${t}`}stripFormPattern(t){return t.replace(p.REGEX_FORM_ID,"")}loadMetadata(){if(!this.dataUnit)return;if(!this.formConfigManager.isLoaded)return;const t=this.formConfigManager.getConfig(this.dataUnit);this._formMetadata=r(null==t||0===t.fields.length?void 0:t,this.dataUnit,!0)}dataUnitReadyHandler(t){this.dataUnit=t.detail,this.loadMetadata()}updateViewStack(t){var i,s;this._viewStack=t,this._currentView=this.selectedForm?1:0,null===(s=null===(i=this._viewStack)||void 0===i?void 0:i.show)||void 0===s||s.call(i,this._currentView)}getFormFields(){return this.selectedForm&&this._formMetadata?this._formMetadata.getSheet(this.selectedForm).fields:[]}emitSwitchEvent(t){const i=t===c.GRID?this.stripFormPattern(this.branchGuide.id):this.getFormGuideId();i&&this.snkSwitchGuide.emit(i)}handleAttachBack(){this._viewStack.show(c.GRID)}executeActionHandler(t){t.detail===l.GRID_MODE&&(this.emitSwitchEvent(c.GRID),t.stopPropagation()),t.detail!==l.FORM_MODE&&t.detail!==l.UPDATE||(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.dataUnit),this.formConfigManager.loadConfig(),null==this.messagesBuilder&&(this.messagesBuilder=new u(this.entityName))}async componentDidLoad(){await this.observerPropsCustomEditor(this.customEditors),await this.observeCustomRenders(this.customRenders)}async dataUnitActionHandler(t){t.type===o.FIELD_INVALIDATED&&this.addErrorBadgeToBranchGuide()}addErrorBadgeToBranchGuide(){this.branchGuide=Object.assign(Object.assign({},this.branchGuide),{badge:"error"}),this.snkDetailGuidesChange.emit(new v(this.branchGuide,this._formMetadata,this.dataUnit))}normalizeBranchGuideId(t){return null==t?void 0:t.replace(/child\[(.*?)\]/g,"$1").replace(/::/g,">")}render(){return this.updateLabel(),e(a,null,e("snk-data-unit",{ref:t=>this._snkDataUnit=t,dataUnitName:`${this.dataUnitName}`,onDataUnitReady:t=>this.dataUnitReadyHandler(t),entityName:this.entityName,onDataStateChange:this.handleDataStateChange.bind(this),ignoreSaveMessage:this._currentView===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
- export{S as snk_data_unit}from"./p-5dd8cf4f.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"@sankhyalabs/ezui/dist/collection/utils";import"./p-17425c72.js";import"./p-7ac7932c.js";import"./p-f3434fc4.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"./p-7dd49d15.js";
1
+ export{S as snk_data_unit}from"./p-fd13b4d2.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"@sankhyalabs/ezui/dist/collection/utils";import"./p-17425c72.js";import"./p-47bce500.js";import"./p-f3434fc4.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"./p-7dd49d15.js";
@@ -1 +1 @@
1
- export{S as snk_guides_viewer}from"./p-16869f77.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"./p-afbb070d.js";import"./p-4d9549cf.js";import"./p-06421fdb.js";import"./p-f3434fc4.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-ff1990ad.js";import"./p-b0ef4383.js";import"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-23736d75.js";import"./p-7e7a7473.js";import"./p-30cf616e.js";import"./p-6dc031de.js";import"./p-1bf06cd3.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"./p-7ac7932c.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";
1
+ export{S as snk_guides_viewer}from"./p-11cc69fc.js";import"./p-d2d301a6.js";import"@sankhyalabs/core";import"./p-afbb070d.js";import"./p-4d9549cf.js";import"./p-06421fdb.js";import"./p-f3434fc4.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-ff1990ad.js";import"./p-b0ef4383.js";import"@sankhyalabs/ezui/dist/collection/utils/form";import"./p-23736d75.js";import"./p-7e7a7473.js";import"./p-30cf616e.js";import"./p-6dc031de.js";import"./p-8a9638ae.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"./p-47bce500.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";import"@sankhyalabs/core/dist/dataunit/DataUnit";
@@ -1 +1 @@
1
- import{r as i,c as t,h as s,F as e,g as a}from"./p-d2d301a6.js";import{Action as r,ElementIDUtils as n,ApplicationContext as d,StringUtils as o}from"@sankhyalabs/core";import{T as h}from"./p-7e7a7473.js";import{C as l}from"./p-4d9549cf.js";import{P as c}from"./p-30cf616e.js";import{T as u,o as g,b as T}from"./p-23736d75.js";import{s as m}from"./p-6dc031de.js";import{C as k,S as v,a as E,R as f,b as p}from"./p-2923c1b5.js";import{SelectionMode as R}from"@sankhyalabs/core/dist/dataunit/DataUnit";import"./p-f3434fc4.js";import"./p-1bf06cd3.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-7ac7932c.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import{g as O}from"./p-7dd49d15.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class b extends k{getFilters(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.getAppliedFilters()}getOrders(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.getSort()}getResourceURI(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.name}getSelectedNumber(){return this.dataUnit.getSelectionInfo().length}getTotalRecords(){var i,t,s;const{total:e}=(null===(i=this.dataUnit)||void 0===i?void 0:i.getPaginationInfo())||{};return null!=e?e:null===(s=null===(t=this.dataUnit)||void 0===t?void 0:t.records)||void 0===s?void 0:s.length}getSelectedIDs(){return O(this.dataUnit)}getOffset(){return this.getExporterOffset(this.getPaginationInfo())}getPageSize(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.pageSize}getExportLimit(){return 5e3}getRecordID(){var i,t,s;return null===(s=null===(t=null===(i=this.dataUnit)||void 0===i?void 0:i.records)||void 0===t?void 0:t[0])||void 0===s?void 0:s.__record__id__}getPaginationInfo(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.getPaginationInfo()}getExporterOffset(i){if(null==i)return;const t=i.firstRecord;return t>0?t-1:t}}const C=class{constructor(s){i(this,s),this.actionClick=t(this,"actionClick",7),this.gridDoubleClick=t(this,"gridDoubleClick",7),this._customEditors=new Map,this._customRenders=new Map,this._topTaskbarProcessor=new u({"snkGridTopTaskbar.regular":["FORM_MODE","CONFIGURATOR","INSERT"],"snkGridTopTaskbar.regular.secondary":["FORM_MODE","CONFIGURATOR","INSERT"],"snkGridTopTaskbar.regular.singleTaskbar":[],"snkGridTopTaskbar.finish_edition":["CANCEL","SAVE",this.handleAddFormMode()],"snkGridTopTaskbar.finish_edition.secondary":[],"snkGridTopTaskbar.finish_edition.singleTaskbar":[]}),this._headerTaskbarProcessor=new u({"snkGridHeaderTaskbar.unselected":["REFRESH","DATA_EXPORTER","ACTIONS_BUTTON","MORE_OPTIONS"],"snkGridHeaderTaskbar.selected":["UPDATE","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","ATTACH","REFRESH","DATA_EXPORTER","ACTIONS_BUTTON"],"snkGridHeaderTaskbar.detail.unselected":["REFRESH","MORE_OPTIONS"],"snkGridHeaderTaskbar.detail.selected":["UPDATE","ATTACH","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","REFRESH"],"snkGridHeaderTaskbar.singleTaskbar.unselected":["INSERT","FORM_MODE","CONFIGURATOR","REFRESH","DATA_EXPORTER","ACTIONS_BUTTON","MORE_OPTIONS"],"snkGridHeaderTaskbar.singleTaskbar.selected":["UPDATE","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","ATTACH","FORM_MODE","CONFIGURATOR","REFRESH","DATA_EXPORTER","ACTIONS_BUTTON"],"snkGridHeaderTaskbar.singleTaskbar.detail.unselected":["INSERT","FORM_MODE","CONFIGURATOR","REFRESH","MORE_OPTIONS"],"snkGridHeaderTaskbar.singleTaskbar.detail.selected":["UPDATE","ATTACH","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","FORM_MODE","CONFIGURATOR","REFRESH"],"snkGridHeaderTaskbar.singleTaskbar.finish_edition":["CANCEL","SAVE",this.handleAddFormMode()]}),this.dataUnitInterceptor={interceptAction:async i=>i.type===r.METADATA_LOADED?await this.interceptMetadataLoaded(i):i},this._dataUnit=void 0,this._dataState=void 0,this._gridConfig=void 0,this._popUpGridConfig=!1,this._showSnkFilterBar=!0,this._enableContinuousInsert=!1,this.columnFilterDataSource=new v,this.configName=void 0,this.filterBarTitle=void 0,this.resourceID=void 0,this.selectionToastConfig=void 0,this.actionsList=void 0,this.isDetail=void 0,this.taskbarManager=void 0,this.statusResolver=void 0,this.multipleSelection=void 0,this.presentationMode=c.PRIMARY,this.messagesBuilder=void 0,this.useEnterLikeTab=!1,this.recordsValidator=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.gridHeaderCustomSlotId="GRID_HEADER_CUSTOM_ELEMENTS",this.topTaskbarCustomSlotId="GRID_TASKBAR_CUSTOM_ELEMENTS",this.disablePersonalizedFilter=void 0,this.gridLegacyConfigName=void 0,this.filterBarLegacyConfigName=void 0,this.autoLoad=void 0,this.autoFocus=!0,this.enableGridInsert=!1}async showConfig(){null!=this._grid&&this.openGridConfig()}async hideConfig(){null!=this._grid&&this.closeGridConfig()}async setConfig(i){this.setGridConfig(i)}async reloadFilterBar(){var i;null===(i=this._snkFilterBar)||void 0===i||i.reload()}async getFilterBar(){return this._snkFilterBar}async findColumn(){await g(this._moreOptions,this._columnSearch)}async addCustomEditor(i,t,s){if(this._grid)return void this._grid.addCustomEditor(i,t,s);const e=new Map(this._customEditors);e.set(i,{customEditor:t,detailContext:s}),this._customEditors=e}async addGridCustomRender(i,t,s){if(this._grid)return void this._grid.addGridCustomRender(i,t,s);const e=new Map(this._customRenders);e.set(i,{customRender:t,detailContext:s}),this._customRenders=e}async addCustomValueFormatter(i,t){this._grid.addCustomValueFormatter(i,t)}async removeCustomValueFormatter(i){this._grid.removeCustomValueFormatter(i)}async setFocus(){this._grid.setFocus()}async handleClick(i){this.hasToBlockEvent(i)&&(i.preventDefault(),i.stopPropagation(),await this._dataUnit.cancelEdition())}hasToBlockEvent(i){var t;return(null===(t=this._snkFilterBar)||void 0===t?void 0:t.contains(i.target))&&this.enableGridInsert&&this._dataUnit.hasNewRecord()}async handleGridLegacyConfigName(i,t){i&&i!==t&&(this.addGridLegacyConfigName(),this.loadConfig())}handleAddFormMode(){return this.enableGridInsert?h.FORM_MODE:""}openGridConfig(){this._grid.getColumnsState().then((i=>{this._snkGridConfig.columns=i.filter((i=>i.name)),this._snkGridConfig.selectedIndex=0,this._popUpGridConfig=!0}))}closeGridConfig(){this._popUpGridConfig=!1}setGridConfig(i){this._gridConfig=i,E.assertDefaultSorting(this._gridConfig,this._dataUnit)}loadConfig(){l.loadGridConfig(this.configName,this.resourceID).then((i=>{this.setGridConfig(i)})).catch((i=>{console.warn(i)}))}addGridLegacyConfigName(){this.gridLegacyConfigName&&this.configName&&l.addGridLegacyConfig(this.configName,this.gridLegacyConfigName)}gridConfigChangeHandler(i){l.saveGridConfig(i.detail,this.configName,this.resourceID),i.stopPropagation()}modalConfigChangeHandler(i){const t=i.detail;this._grid.setColumnsState(t.columns).then((()=>{this.setGridConfig(t),this.closeGridConfig(),this.dataExporterProviderStore()})),i.stopPropagation()}async dataExporterProviderStore(){const i=new b(this._dataUnit,this._grid);m.set("exporterProviders",Object.assign(Object.assign({},m.get("exporterProviders")),{[this.configName]:i}))}addElementID(){n.addIDInfo(this._element,null,{dataUnit:this._dataUnit})}loadGridCustomFormatters(i){i&&this._grid&&i.forEach((i=>{var t;(null===(t=i.properties)||void 0===t?void 0:t.rm_precision)&&this.addCustomValueFormatter(i.name,this._rmPrecisionCustomValueFormatter)}))}async interceptMetadataLoaded(i){return this.loadGridCustomFormatters(i.payload.fields),i}finishLoading(){this._dataUnit.addInterceptor(this.dataUnitInterceptor),E.assertDefaultSorting(this._gridConfig,this._dataUnit),this.addElementID(),null!=this.columnFilterDataSource&&(this.columnFilterDataSource.setApplication(this._application),this.columnFilterDataSource.setDataUnit(this._dataUnit))}setCustomRenders(){if(this._grid)for(const[i,t]of this._customRenders)this._grid.addGridCustomRender(i,t.customRender,t.detailContext),this._customRenders.delete(i)}setCustomEditors(){if(this._grid)for(const[i,t]of this._customEditors)this._grid.addCustomEditor(i,t.customEditor,t.detailContext),this._customEditors.delete(i)}componentWillLoad(){this._application=d.getContextValue("__SNK__APPLICATION__");let i=this._element.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase()){this._snkDataUnit=i,this._dataUnit=this._snkDataUnit.dataUnit,this._dataUnit?this.finishLoading():this._snkDataUnit.addEventListener("dataUnitReady",(i=>{this._dataUnit=i.detail,this.finishLoading()})),this.messagesBuilder||(this.messagesBuilder=this._snkDataUnit.messagesBuilder),this._snkDataUnit.addEventListener("dataStateChange",this.handleDataStateChange.bind(this)),this._snkDataUnit.addEventListener("cancelEdition",(()=>{var i;(null===(i=this._dataState)||void 0===i?void 0:i.recordsIsEmpty)&&this._dataUnit.clearSelection()}));break}i=i.parentElement}this._rmPrecisionCustomValueFormatter=new f,this.addGridLegacyConfigName(),this.loadConfig(),this._continuousInsertUtils=new p(this._application,this.resourceID,this.configName),this.enableGridInsert&&this._continuousInsertUtils.getConfig().then((i=>this._enableContinuousInsert=i))}componentDidRender(){var i,t;this._rmPrecisionCustomValueFormatter.setGrid(this._grid),this.loadGridCustomFormatters(null===(t=null===(i=this._dataUnit)||void 0===i?void 0:i.metadata)||void 0===t?void 0:t.fields),this.setCustomRenders(),this.setCustomEditors()}async handleDataStateChange(i){this._dataState=i.detail,this._rmPrecisionCustomValueFormatter.setDataState(this._dataState)}getHeaderDisabledButtons(){var i;const t=[];return(null===(i=this._dataState)||void 0===i?void 0:i.selectionInfo)&&(this._dataState.selectionInfo.length>1&&t.push(h.CLONE,"ATTACH",h.UPDATE),this._dataState.selectionInfo.isAllRecords()&&t.push("REMOVE")),t}getInvisibleButtons(){let i=[];return this._dataUnit&&0!==this._dataUnit.records.length||i.push("DATA_EXPORTER"),this._dataState&&this._dataState.selectionInfo.mode===R.ALL_RECORDS&&i.push("ACTIONS_BUTTON"),i}componentWillRender(){const i=this.getInvisibleButtons();this._headerTaskbarProcessor.process(this.getHeaderTaskbarId(),this.taskbarManager,this._dataState,this.getHeaderDisabledButtons(),i),this._topTaskbarProcessor.process(this.getTopTaskBarId(),this.taskbarManager,this._dataState,void 0,i),this.dataExporterProviderStore()}getHeaderTaskbarId(){var i,t;const s=this._dataState&&!!(null===(i=this._dataState.selectionInfo)||void 0===i?void 0:i.length),e={primary:this.isDetail?"snkGridHeaderTaskbar.detail":"snkGridHeaderTaskbar",secondary:this.isDetail?"snkGridHeaderTaskbar.detail":"snkGridHeaderTaskbar",singleTaskbar:this.isDetail?"snkGridHeaderTaskbar.singleTaskbar.detail":"snkGridHeaderTaskbar.singleTaskbar"}[this.presentationMode];let a=s?`${e}.selected`:`${e}.unselected`;return(null===(t=this._dataState)||void 0===t?void 0:t.isDirty)&&this.presentationMode===c.SINGLE_TASKBAR&&(a="snkGridHeaderTaskbar.singleTaskbar.finish_edition"),a}getTopTaskBarId(){var i;const t={primary:"",secondary:".secondary",singleTaskbar:".singleTaskbar"}[this.presentationMode];return(null===(i=this._dataState)||void 0===i?void 0:i.isDirty)?`snkGridTopTaskbar.finish_edition${t}`:`snkGridTopTaskbar.regular${t}`}getPrimaryButton(){return{primary:"INSERT",secondary:"",singleTaskbar:"INSERT"}[this.presentationMode]}getColumnSearch(i,t){return null!=this._columnSearch||(this._moreOptions=i,this._columnSearch=T(t,(({argument:i})=>new Promise((t=>{this._grid.filterColumns(i).then((i=>{t(i.filter((i=>!i.hidden)).map((i=>({label:i.label,value:i.name}))))}))}))),(t=>{null!=t&&(this._grid.locateColumn(t.value),i.hideActions())}))),this._columnSearch}getActionsList(){const i=[{value:o.generateUUID(),label:this.messagesBuilder.getMessage("snkGrid.findColumn",{}),disableCloseOnSelect:!0,eagerInitialize:!0,itemBuilder:(i,t)=>this.getColumnSearch(i,t)}];if(this.enableGridInsert&&i.push(this._continuousInsertUtils.actionContinuousInsert(this._enableContinuousInsert,(()=>{this._enableContinuousInsert=!this._enableContinuousInsert,this._continuousInsertUtils.handleSaveConfig(this._enableContinuousInsert)}))),this.isGridInsertActive())return i;if(null!=this.taskbarManager&&null!=this.taskbarManager.getMoreOptions){const t=this.getTopTaskBarId();return i.concat(this.taskbarManager.getMoreOptions(t,this.configName,this._dataState,this.actionsList))}return i.concat(this.actionsList)}handleFilterConfigUpdated(i){this._showSnkFilterBar=!!i.length&&(1!==i.length||"PERSONALIZED_FILTER_GROUP"!==i[0].id||i[0].groupedItems.length>0)}getGridHeaderButtons(){return this.isGridInsertActive()?h.MORE_OPTIONS:this._headerTaskbarProcessor.buttons}isGridInsertActive(){return this.enableGridInsert&&this._dataUnit.hasNewRecord()}render(){if(this._dataUnit)return s("div",{class:"snk-grid__container ez-flex ez-flex--column ez-flex-item--auto ez-padding--large"},s("div",{class:"snk-grid__header ez-margin-bottom--extra-small"},this._showSnkFilterBar&&s(e,null,s("snk-filter-bar",{ref:i=>this._snkFilterBar=i,title:this.filterBarTitle,dataUnit:this._dataUnit,"data-element-id":"gridFilter",class:"snk-grid__filter-bar ez-align--top",configName:this.configName,messagesBuilder:this.messagesBuilder,resourceID:this.resourceID,onConfigUpdated:i=>this.handleFilterConfigUpdated(i.detail),disablePersonalizedFilter:this.disablePersonalizedFilter,filterBarLegacyConfigName:this.filterBarLegacyConfigName,autoLoad:this.autoLoad}),s("hr",{class:"ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-grid__header-divider"})),s("snk-taskbar",{class:"ez-padding-left--medium","data-element-id":"grid_top",key:"topTaskbar",configName:this.configName,dataUnit:this._dataUnit,messagesBuilder:this.messagesBuilder,buttons:this._topTaskbarProcessor.buttons,disabledButtons:this._topTaskbarProcessor.disabledButtons,customButtons:this._topTaskbarProcessor.customButtons,primaryButton:this.getPrimaryButton(),resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:this.topTaskbarCustomSlotId,overflowStrategy:"none"},s("slot",{name:this.topTaskbarCustomSlotId}))),s("ez-grid",{ref:i=>this._grid=i,class:(this.presentationMode===c.SECONDARY?"snk-grid-container__without-shadow ":"")+"snk-grid__table","data-element-id":"embedded",dataUnit:this._dataUnit,key:"grid-"+this._snkDataUnit.entityName,config:this._gridConfig,onConfigChange:i=>{this.gridConfigChangeHandler(i)},onEzDoubleClick:i=>this.gridDoubleClick.emit(i.detail),statusResolver:this.statusResolver,multipleSelection:this.multipleSelection,columnfilterDataSource:this.columnFilterDataSource,selectionToastConfig:this.selectionToastConfig,useEnterLikeTab:this.useEnterLikeTab,recordsValidator:this.recordsValidator,canEdit:this.canEdit,autoFocus:this.autoFocus,enableGridInsert:this.enableGridInsert,enableContinuousInsert:this._enableContinuousInsert},s("snk-taskbar",{id:"teste",dataUnit:this._dataUnit,configName:this.configName,messagesBuilder:this.messagesBuilder,"data-element-id":"grid_left",buttons:this.getGridHeaderButtons(),presentationMode:this.presentationMode,disabledButtons:this._headerTaskbarProcessor.disabledButtons,customButtons:this._headerTaskbarProcessor.customButtons,slot:"leftButtons",actionsList:this.getActionsList(),primaryButton:this.getPrimaryButton(),resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:this.gridHeaderCustomSlotId},s("slot",{name:this.gridHeaderCustomSlotId}))),s("div",{class:"ez-col ez-col--sd-12"},s("slot",{name:"SnkGridFooter"})),s("ez-modal",{modalSize:"small",closeEsc:!1,closeOutsideClick:!1,opened:this._popUpGridConfig,onEzCloseModal:()=>this.closeGridConfig()},s("snk-grid-config",{ref:i=>this._snkGridConfig=i,config:this._gridConfig,"data-element-id":this._element.getAttribute(n.DATA_ELEMENT_ID_ATTRIBUTE_NAME),selectedIndex:0,configName:this.configName,onConfigChange:i=>this.modalConfigChangeHandler(i),onConfigCancel:()=>this.closeGridConfig(),resourceID:this.resourceID})))}get _element(){return a(this)}static get watchers(){return{gridLegacyConfigName:["handleGridLegacyConfigName"]}}};C.style=".sc-snk-grid-h{--snk-grid-min-height:300px;--snk-grid-padding:var(--space--small)}.snk-grid__container.sc-snk-grid{display:flex;height:100%;width:100%;padding:var(--snk-grid-padding)}.snk-grid__header.sc-snk-grid{width:100%;display:flex;flex-wrap:nowrap;justify-content:flex-end}.snk-grid__filter-bar.sc-snk-grid{width:100%}.snk-grid__header-divider.sc-snk-grid{margin-bottom:var(--space--medium)}.snk-grid__table.sc-snk-grid{min-height:var(--snk-grid-min-height)}.snk-grid-container__without-shadow.sc-snk-grid{--ezgrid__container--shadow:unset}";export{C as snk_grid}
1
+ import{r as i,c as t,h as s,F as e,g as a}from"./p-d2d301a6.js";import{Action as r,ElementIDUtils as n,ApplicationContext as d,StringUtils as o}from"@sankhyalabs/core";import{T as h}from"./p-7e7a7473.js";import{C as l}from"./p-4d9549cf.js";import{P as c}from"./p-30cf616e.js";import{T as u,o as g,b as T}from"./p-23736d75.js";import{s as m}from"./p-6dc031de.js";import{C as k,S as v,a as E,R as f,b as p}from"./p-9f9b99d9.js";import{SelectionMode as R}from"@sankhyalabs/core/dist/dataunit/DataUnit";import"./p-f3434fc4.js";import"./p-8a9638ae.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-47bce500.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import{g as O}from"./p-7dd49d15.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource";import"./p-8d884fab.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class b extends k{getFilters(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.getAppliedFilters()}getOrders(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.getSort()}getResourceURI(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.name}getSelectedNumber(){return this.dataUnit.getSelectionInfo().length}getTotalRecords(){var i,t,s;const{total:e}=(null===(i=this.dataUnit)||void 0===i?void 0:i.getPaginationInfo())||{};return null!=e?e:null===(s=null===(t=this.dataUnit)||void 0===t?void 0:t.records)||void 0===s?void 0:s.length}getSelectedIDs(){return O(this.dataUnit)}getOffset(){return this.getExporterOffset(this.getPaginationInfo())}getPageSize(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.pageSize}getExportLimit(){return 5e3}getRecordID(){var i,t,s;return null===(s=null===(t=null===(i=this.dataUnit)||void 0===i?void 0:i.records)||void 0===t?void 0:t[0])||void 0===s?void 0:s.__record__id__}getPaginationInfo(){var i;return null===(i=this.dataUnit)||void 0===i?void 0:i.getPaginationInfo()}getExporterOffset(i){if(null==i)return;const t=i.firstRecord;return t>0?t-1:t}}const C=class{constructor(s){i(this,s),this.actionClick=t(this,"actionClick",7),this.gridDoubleClick=t(this,"gridDoubleClick",7),this._customEditors=new Map,this._customRenders=new Map,this._topTaskbarProcessor=new u({"snkGridTopTaskbar.regular":["FORM_MODE","CONFIGURATOR","INSERT"],"snkGridTopTaskbar.regular.secondary":["FORM_MODE","CONFIGURATOR","INSERT"],"snkGridTopTaskbar.regular.singleTaskbar":[],"snkGridTopTaskbar.finish_edition":["CANCEL","SAVE",this.handleAddFormMode()],"snkGridTopTaskbar.finish_edition.secondary":[],"snkGridTopTaskbar.finish_edition.singleTaskbar":[]}),this._headerTaskbarProcessor=new u({"snkGridHeaderTaskbar.unselected":["REFRESH","DATA_EXPORTER","ACTIONS_BUTTON","MORE_OPTIONS"],"snkGridHeaderTaskbar.selected":["UPDATE","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","ATTACH","REFRESH","DATA_EXPORTER","ACTIONS_BUTTON"],"snkGridHeaderTaskbar.detail.unselected":["REFRESH","MORE_OPTIONS"],"snkGridHeaderTaskbar.detail.selected":["UPDATE","ATTACH","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","REFRESH"],"snkGridHeaderTaskbar.singleTaskbar.unselected":["INSERT","FORM_MODE","CONFIGURATOR","REFRESH","DATA_EXPORTER","ACTIONS_BUTTON","MORE_OPTIONS"],"snkGridHeaderTaskbar.singleTaskbar.selected":["UPDATE","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","ATTACH","FORM_MODE","CONFIGURATOR","REFRESH","DATA_EXPORTER","ACTIONS_BUTTON"],"snkGridHeaderTaskbar.singleTaskbar.detail.unselected":["INSERT","FORM_MODE","CONFIGURATOR","REFRESH","MORE_OPTIONS"],"snkGridHeaderTaskbar.singleTaskbar.detail.selected":["UPDATE","ATTACH","CLONE","REMOVE","MORE_OPTIONS","DIVIDER","FORM_MODE","CONFIGURATOR","REFRESH"],"snkGridHeaderTaskbar.singleTaskbar.finish_edition":["CANCEL","SAVE",this.handleAddFormMode()]}),this.dataUnitInterceptor={interceptAction:async i=>i.type===r.METADATA_LOADED?await this.interceptMetadataLoaded(i):i},this._dataUnit=void 0,this._dataState=void 0,this._gridConfig=void 0,this._popUpGridConfig=!1,this._showSnkFilterBar=!0,this._enableContinuousInsert=!1,this.columnFilterDataSource=new v,this.configName=void 0,this.filterBarTitle=void 0,this.resourceID=void 0,this.selectionToastConfig=void 0,this.actionsList=void 0,this.isDetail=void 0,this.taskbarManager=void 0,this.statusResolver=void 0,this.multipleSelection=void 0,this.presentationMode=c.PRIMARY,this.messagesBuilder=void 0,this.useEnterLikeTab=!1,this.recordsValidator=void 0,this.canEdit=!0,this.taskbarCustomContainerId=void 0,this.gridHeaderCustomSlotId="GRID_HEADER_CUSTOM_ELEMENTS",this.topTaskbarCustomSlotId="GRID_TASKBAR_CUSTOM_ELEMENTS",this.disablePersonalizedFilter=void 0,this.gridLegacyConfigName=void 0,this.filterBarLegacyConfigName=void 0,this.autoLoad=void 0,this.autoFocus=!0,this.enableGridInsert=!1}async showConfig(){null!=this._grid&&this.openGridConfig()}async hideConfig(){null!=this._grid&&this.closeGridConfig()}async setConfig(i){this.setGridConfig(i)}async reloadFilterBar(){var i;null===(i=this._snkFilterBar)||void 0===i||i.reload()}async getFilterBar(){return this._snkFilterBar}async findColumn(){await g(this._moreOptions,this._columnSearch)}async addCustomEditor(i,t,s){if(this._grid)return void this._grid.addCustomEditor(i,t,s);const e=new Map(this._customEditors);e.set(i,{customEditor:t,detailContext:s}),this._customEditors=e}async addGridCustomRender(i,t,s){if(this._grid)return void this._grid.addGridCustomRender(i,t,s);const e=new Map(this._customRenders);e.set(i,{customRender:t,detailContext:s}),this._customRenders=e}async addCustomValueFormatter(i,t){this._grid.addCustomValueFormatter(i,t)}async removeCustomValueFormatter(i){this._grid.removeCustomValueFormatter(i)}async setFocus(){this._grid.setFocus()}async handleClick(i){this.hasToBlockEvent(i)&&(i.preventDefault(),i.stopPropagation(),await this._dataUnit.cancelEdition())}hasToBlockEvent(i){var t;return(null===(t=this._snkFilterBar)||void 0===t?void 0:t.contains(i.target))&&this.enableGridInsert&&this._dataUnit.hasNewRecord()}async handleGridLegacyConfigName(i,t){i&&i!==t&&(this.addGridLegacyConfigName(),this.loadConfig())}handleAddFormMode(){return this.enableGridInsert?h.FORM_MODE:""}openGridConfig(){this._grid.getColumnsState().then((i=>{this._snkGridConfig.columns=i.filter((i=>i.name)),this._snkGridConfig.selectedIndex=0,this._popUpGridConfig=!0}))}closeGridConfig(){this._popUpGridConfig=!1}setGridConfig(i){this._gridConfig=i,E.assertDefaultSorting(this._gridConfig,this._dataUnit)}loadConfig(){l.loadGridConfig(this.configName,this.resourceID).then((i=>{this.setGridConfig(i)})).catch((i=>{console.warn(i)}))}addGridLegacyConfigName(){this.gridLegacyConfigName&&this.configName&&l.addGridLegacyConfig(this.configName,this.gridLegacyConfigName)}gridConfigChangeHandler(i){l.saveGridConfig(i.detail,this.configName,this.resourceID),i.stopPropagation()}modalConfigChangeHandler(i){const t=i.detail;this._grid.setColumnsState(t.columns).then((()=>{this.setGridConfig(t),this.closeGridConfig(),this.dataExporterProviderStore()})),i.stopPropagation()}async dataExporterProviderStore(){const i=new b(this._dataUnit,this._grid);m.set("exporterProviders",Object.assign(Object.assign({},m.get("exporterProviders")),{[this.configName]:i}))}addElementID(){n.addIDInfo(this._element,null,{dataUnit:this._dataUnit})}loadGridCustomFormatters(i){i&&this._grid&&i.forEach((i=>{var t;(null===(t=i.properties)||void 0===t?void 0:t.rm_precision)&&this.addCustomValueFormatter(i.name,this._rmPrecisionCustomValueFormatter)}))}async interceptMetadataLoaded(i){return this.loadGridCustomFormatters(i.payload.fields),i}finishLoading(){this._dataUnit.addInterceptor(this.dataUnitInterceptor),E.assertDefaultSorting(this._gridConfig,this._dataUnit),this.addElementID(),null!=this.columnFilterDataSource&&(this.columnFilterDataSource.setApplication(this._application),this.columnFilterDataSource.setDataUnit(this._dataUnit))}setCustomRenders(){if(this._grid)for(const[i,t]of this._customRenders)this._grid.addGridCustomRender(i,t.customRender,t.detailContext),this._customRenders.delete(i)}setCustomEditors(){if(this._grid)for(const[i,t]of this._customEditors)this._grid.addCustomEditor(i,t.customEditor,t.detailContext),this._customEditors.delete(i)}componentWillLoad(){this._application=d.getContextValue("__SNK__APPLICATION__");let i=this._element.parentElement;for(;i;){if("SNK-DATA-UNIT"===i.tagName.toUpperCase()){this._snkDataUnit=i,this._dataUnit=this._snkDataUnit.dataUnit,this._dataUnit?this.finishLoading():this._snkDataUnit.addEventListener("dataUnitReady",(i=>{this._dataUnit=i.detail,this.finishLoading()})),this.messagesBuilder||(this.messagesBuilder=this._snkDataUnit.messagesBuilder),this._snkDataUnit.addEventListener("dataStateChange",this.handleDataStateChange.bind(this)),this._snkDataUnit.addEventListener("cancelEdition",(()=>{var i;(null===(i=this._dataState)||void 0===i?void 0:i.recordsIsEmpty)&&this._dataUnit.clearSelection()}));break}i=i.parentElement}this._rmPrecisionCustomValueFormatter=new f,this.addGridLegacyConfigName(),this.loadConfig(),this._continuousInsertUtils=new p(this._application,this.resourceID,this.configName),this.enableGridInsert&&this._continuousInsertUtils.getConfig().then((i=>this._enableContinuousInsert=i))}componentDidRender(){var i,t;this._rmPrecisionCustomValueFormatter.setGrid(this._grid),this.loadGridCustomFormatters(null===(t=null===(i=this._dataUnit)||void 0===i?void 0:i.metadata)||void 0===t?void 0:t.fields),this.setCustomRenders(),this.setCustomEditors()}async handleDataStateChange(i){this._dataState=i.detail,this._rmPrecisionCustomValueFormatter.setDataState(this._dataState)}getHeaderDisabledButtons(){var i;const t=[];return(null===(i=this._dataState)||void 0===i?void 0:i.selectionInfo)&&(this._dataState.selectionInfo.length>1&&t.push(h.CLONE,"ATTACH",h.UPDATE),this._dataState.selectionInfo.isAllRecords()&&t.push("REMOVE")),t}getInvisibleButtons(){let i=[];return this._dataUnit&&0!==this._dataUnit.records.length||i.push("DATA_EXPORTER"),this._dataState&&this._dataState.selectionInfo.mode===R.ALL_RECORDS&&i.push("ACTIONS_BUTTON"),i}componentWillRender(){const i=this.getInvisibleButtons();this._headerTaskbarProcessor.process(this.getHeaderTaskbarId(),this.taskbarManager,this._dataState,this.getHeaderDisabledButtons(),i),this._topTaskbarProcessor.process(this.getTopTaskBarId(),this.taskbarManager,this._dataState,void 0,i),this.dataExporterProviderStore()}getHeaderTaskbarId(){var i,t;const s=this._dataState&&!!(null===(i=this._dataState.selectionInfo)||void 0===i?void 0:i.length),e={primary:this.isDetail?"snkGridHeaderTaskbar.detail":"snkGridHeaderTaskbar",secondary:this.isDetail?"snkGridHeaderTaskbar.detail":"snkGridHeaderTaskbar",singleTaskbar:this.isDetail?"snkGridHeaderTaskbar.singleTaskbar.detail":"snkGridHeaderTaskbar.singleTaskbar"}[this.presentationMode];let a=s?`${e}.selected`:`${e}.unselected`;return(null===(t=this._dataState)||void 0===t?void 0:t.isDirty)&&this.presentationMode===c.SINGLE_TASKBAR&&(a="snkGridHeaderTaskbar.singleTaskbar.finish_edition"),a}getTopTaskBarId(){var i;const t={primary:"",secondary:".secondary",singleTaskbar:".singleTaskbar"}[this.presentationMode];return(null===(i=this._dataState)||void 0===i?void 0:i.isDirty)?`snkGridTopTaskbar.finish_edition${t}`:`snkGridTopTaskbar.regular${t}`}getPrimaryButton(){return{primary:"INSERT",secondary:"",singleTaskbar:"INSERT"}[this.presentationMode]}getColumnSearch(i,t){return null!=this._columnSearch||(this._moreOptions=i,this._columnSearch=T(t,(({argument:i})=>new Promise((t=>{this._grid.filterColumns(i).then((i=>{t(i.filter((i=>!i.hidden)).map((i=>({label:i.label,value:i.name}))))}))}))),(t=>{null!=t&&(this._grid.locateColumn(t.value),i.hideActions())}))),this._columnSearch}getActionsList(){const i=[{value:o.generateUUID(),label:this.messagesBuilder.getMessage("snkGrid.findColumn",{}),disableCloseOnSelect:!0,eagerInitialize:!0,itemBuilder:(i,t)=>this.getColumnSearch(i,t)}];if(this.enableGridInsert&&i.push(this._continuousInsertUtils.actionContinuousInsert(this._enableContinuousInsert,(()=>{this._enableContinuousInsert=!this._enableContinuousInsert,this._continuousInsertUtils.handleSaveConfig(this._enableContinuousInsert)}))),this.isGridInsertActive())return i;if(null!=this.taskbarManager&&null!=this.taskbarManager.getMoreOptions){const t=this.getTopTaskBarId();return i.concat(this.taskbarManager.getMoreOptions(t,this.configName,this._dataState,this.actionsList))}return i.concat(this.actionsList)}handleFilterConfigUpdated(i){this._showSnkFilterBar=!!i.length&&(1!==i.length||"PERSONALIZED_FILTER_GROUP"!==i[0].id||i[0].groupedItems.length>0)}getGridHeaderButtons(){return this.isGridInsertActive()?h.MORE_OPTIONS:this._headerTaskbarProcessor.buttons}isGridInsertActive(){return this.enableGridInsert&&this._dataUnit.hasNewRecord()}render(){if(this._dataUnit)return s("div",{class:"snk-grid__container ez-flex ez-flex--column ez-flex-item--auto ez-padding--large"},s("div",{class:"snk-grid__header ez-margin-bottom--extra-small"},this._showSnkFilterBar&&s(e,null,s("snk-filter-bar",{ref:i=>this._snkFilterBar=i,title:this.filterBarTitle,dataUnit:this._dataUnit,"data-element-id":"gridFilter",class:"snk-grid__filter-bar ez-align--top",configName:this.configName,messagesBuilder:this.messagesBuilder,resourceID:this.resourceID,onConfigUpdated:i=>this.handleFilterConfigUpdated(i.detail),disablePersonalizedFilter:this.disablePersonalizedFilter,filterBarLegacyConfigName:this.filterBarLegacyConfigName,autoLoad:this.autoLoad}),s("hr",{class:"ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-grid__header-divider"})),s("snk-taskbar",{class:"ez-padding-left--medium","data-element-id":"grid_top",key:"topTaskbar",configName:this.configName,dataUnit:this._dataUnit,messagesBuilder:this.messagesBuilder,buttons:this._topTaskbarProcessor.buttons,disabledButtons:this._topTaskbarProcessor.disabledButtons,customButtons:this._topTaskbarProcessor.customButtons,primaryButton:this.getPrimaryButton(),resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:this.topTaskbarCustomSlotId,overflowStrategy:"none"},s("slot",{name:this.topTaskbarCustomSlotId}))),s("ez-grid",{ref:i=>this._grid=i,class:(this.presentationMode===c.SECONDARY?"snk-grid-container__without-shadow ":"")+"snk-grid__table","data-element-id":"embedded",dataUnit:this._dataUnit,key:"grid-"+this._snkDataUnit.entityName,config:this._gridConfig,onConfigChange:i=>{this.gridConfigChangeHandler(i)},onEzDoubleClick:i=>this.gridDoubleClick.emit(i.detail),statusResolver:this.statusResolver,multipleSelection:this.multipleSelection,columnfilterDataSource:this.columnFilterDataSource,selectionToastConfig:this.selectionToastConfig,useEnterLikeTab:this.useEnterLikeTab,recordsValidator:this.recordsValidator,canEdit:this.canEdit,autoFocus:this.autoFocus,enableGridInsert:this.enableGridInsert,enableContinuousInsert:this._enableContinuousInsert},s("snk-taskbar",{id:"teste",dataUnit:this._dataUnit,configName:this.configName,messagesBuilder:this.messagesBuilder,"data-element-id":"grid_left",buttons:this.getGridHeaderButtons(),presentationMode:this.presentationMode,disabledButtons:this._headerTaskbarProcessor.disabledButtons,customButtons:this._headerTaskbarProcessor.customButtons,slot:"leftButtons",actionsList:this.getActionsList(),primaryButton:this.getPrimaryButton(),resourceID:this.resourceID,customContainerId:this.taskbarCustomContainerId,customSlotId:this.gridHeaderCustomSlotId},s("slot",{name:this.gridHeaderCustomSlotId}))),s("div",{class:"ez-col ez-col--sd-12"},s("slot",{name:"SnkGridFooter"})),s("ez-modal",{modalSize:"small",closeEsc:!1,closeOutsideClick:!1,opened:this._popUpGridConfig,onEzCloseModal:()=>this.closeGridConfig()},s("snk-grid-config",{ref:i=>this._snkGridConfig=i,config:this._gridConfig,"data-element-id":this._element.getAttribute(n.DATA_ELEMENT_ID_ATTRIBUTE_NAME),selectedIndex:0,configName:this.configName,onConfigChange:i=>this.modalConfigChangeHandler(i),onConfigCancel:()=>this.closeGridConfig(),resourceID:this.resourceID})))}get _element(){return a(this)}static get watchers(){return{gridLegacyConfigName:["handleGridLegacyConfigName"]}}};C.style=".sc-snk-grid-h{--snk-grid-min-height:300px;--snk-grid-padding:var(--space--small)}.snk-grid__container.sc-snk-grid{display:flex;height:100%;width:100%;padding:var(--snk-grid-padding)}.snk-grid__header.sc-snk-grid{width:100%;display:flex;flex-wrap:nowrap;justify-content:flex-end}.snk-grid__filter-bar.sc-snk-grid{width:100%}.snk-grid__header-divider.sc-snk-grid{margin-bottom:var(--space--medium)}.snk-grid__table.sc-snk-grid{min-height:var(--snk-grid-min-height)}.snk-grid-container__without-shadow.sc-snk-grid{--ezgrid__container--shadow:unset}";export{C as snk_grid}
@@ -3,4 +3,4 @@ import{DataType as e,ApplicationContext as t}from"@sankhyalabs/core";import{d as
3
3
  value
4
4
  label
5
5
  }
6
- }`)}loadSearchOptions(t,i,r,s){var a;const l=(null==i?void 0:i.toString().trim())||void 0;i=isNaN(Number(l))&&l?`%${l}`:l,null==r||r.params.forEach((t=>{t.dataType===e.OBJECT&&(t.value=JSON.stringify(t.value))}));const u=this.applySearchListener(o.beforeSearch,t,i,r,s),c={argument:(null==u?void 0:u.argument)||i,entityName:t,criteria:(null==u?void 0:u.criteria)||r,options:(null==u?void 0:u.searchOptions)||s};return c.options&&(null===(a=c.options)||void 0===a||delete a.dataUnitId),new Promise(((e,t)=>{n.get().callGraphQL({values:c,query:this._templateByQuery.get("search")}).then((t=>{e(t)})).catch((e=>{t(e)}))}))}loadAdvancedSearch(i,r,s,a){var l,u,c,d,v;const h=this.applySearchListener(o.beforeSearch,i,r,s,a),p={argument:(null==h?void 0:h.argument)||r,criteria:(null==h?void 0:h.criteria)||s,searchOptions:Object.assign(Object.assign({},a),null==h?void 0:h.searchOptions)},m={query:{$:null===(l=p.criteria)||void 0===l?void 0:l.expression}};(null===(c=null===(u=p.criteria)||void 0===u?void 0:u.params)||void 0===c?void 0:c.length)>0&&(m.params={param:p.criteria.params.map((i=>{let n=i.value;if("string"==typeof n){const e=/CTX\{([^}]+)\}/.exec(n);e&&(n=t.getContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${e[1]})__`))}let r=i.dataType;return r===e.OBJECT?(n=n.value,r="S"):r=function(t){switch(t){case e.NUMBER:return"I";case e.DATE:return"D";default:return"S"}}(i.dataType),{$:n,type:r}}))});const y=null!=a?Object.assign(Object.assign({},null==p?void 0:p.searchOptions),{pkFieldName:a.codeFieldName,label:a.descriptionFieldName,fieldName:a.codeFieldName,useDescriptionOptions:!1,enableRowsCounter:!0}):void 0,f={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:Object.assign({entityName:i,compacted:!1,ignoreEntityCriteria:null!==(d=null==y?void 0:y.ignoreEntityCriteria)&&void 0!==d&&d,limit:this._defaultPageSize,query:{$:p.argument},orderByDesc:!1,externalCriteria:m,localEntityName:null===(v=p.searchOptions)||void 0===v?void 0:v.rootEntity},{options:y}),clientEventList:{clientEvent:[]}}};return new Promise(((e,t)=>{n.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(f)).then((t=>e(t))).catch((e=>t(e)))}))}addSearchListener(e,t,i){var n;const r=this._searchListenersByDataUnit.get(t)||[],o=r.find((t=>t.entity===e));if(o){for(const e of Object.keys(i))if(e in o.listener){if((null===(n=o.listener[e])||void 0===n?void 0:n.toString())===i[e].toString())continue;o.listener[e]=i[e]}}else this._searchListenersByDataUnit.set(t,[...r,{entity:e,listener:i}]);return()=>{const i=r.filter((t=>t.entity!==e));i.length?this._searchListenersByDataUnit.set(t,i):this._searchListenersByDataUnit.delete(t)}}applySearchListener(e,t,i,n,r){var o;const s=null==r?void 0:r.dataUnitId;if(!s)return;const a=null===(o=this._searchListenersByDataUnit.get(s))||void 0===o?void 0:o.find((({entity:e})=>e===t));if(!a)return;const{listener:l}=a;return e in l?l[e]({argument:i,criteria:n,searchOptions:r}):void 0}}var o;!function(e){e.beforeSearch="beforeSearch"}(o||(o={}));export{r as P}
6
+ }`)}loadSearchOptions(t,i,r,s){var a;const l=(null==i?void 0:i.toString().trim())||void 0;i=isNaN(Number(l))&&l?`%${l}`:l,null==r||r.params.forEach((t=>{t.dataType===e.OBJECT&&(t.value=JSON.stringify(t.value))}));const u=this.applySearchListener(o.beforeSearch,t,i,r,s),c={argument:(null==u?void 0:u.argument)||i,entityName:t,criteria:(null==u?void 0:u.criteria)||r,options:(null==u?void 0:u.searchOptions)||s};return c.options&&(null===(a=c.options)||void 0===a||delete a.dataUnitId),new Promise(((e,t)=>{n.get().callGraphQL({values:c,query:this._templateByQuery.get("search")}).then((t=>{e(t)})).catch((e=>{t(e)}))}))}loadAdvancedSearch(i,r,s,a){var l,u,c,d,v;const h=this.applySearchListener(o.beforeSearch,i,r,s,a),m={argument:(null==h?void 0:h.argument)||r,criteria:(null==h?void 0:h.criteria)||s,searchOptions:Object.assign(Object.assign({},a),null==h?void 0:h.searchOptions)},p={query:{$:null===(l=m.criteria)||void 0===l?void 0:l.expression}};(null===(c=null===(u=m.criteria)||void 0===u?void 0:u.params)||void 0===c?void 0:c.length)>0&&(p.params={param:m.criteria.params.map((i=>{let n=i.value;if("string"==typeof n){const e=/CTX\{([^}]+)\}/.exec(n);e&&(n=t.getContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${e[1]})__`))}let r=i.dataType;return r===e.OBJECT?(n=n.value,r="S"):r=function(t){switch(t){case e.NUMBER:return"I";case e.DATE:return"D";default:return"S"}}(i.dataType),{$:n,type:r}}))});const y=null!=a?Object.assign(Object.assign({},null==m?void 0:m.searchOptions),{pkFieldName:a.codeFieldName,label:a.descriptionFieldName,fieldName:a.codeFieldName,useDescriptionOptions:!1,enableRowsCounter:!0}):void 0,f={serviceName:"PesquisaSP.getSuggestion",requestBody:{criteria:Object.assign({entityName:i,compacted:!1,ignoreEntityCriteria:null!==(d=null==y?void 0:y.ignoreEntityCriteria)&&void 0!==d&&d,limit:this._defaultPageSize,query:{$:m.argument},orderByDesc:!1,externalCriteria:p,localEntityName:null===(v=m.searchOptions)||void 0===v?void 0:v.rootEntity},{options:y}),clientEventList:{clientEvent:[]}}},S={urlParams:{quietMode:!0}};return new Promise(((e,t)=>{n.get().callServiceBroker("PesquisaSP.getSuggestion",JSON.stringify(f),S).then((t=>e(t))).catch((e=>t(e)))}))}addSearchListener(e,t,i){var n;const r=this._searchListenersByDataUnit.get(t)||[],o=r.find((t=>t.entity===e));if(o){for(const e of Object.keys(i))if(e in o.listener){if((null===(n=o.listener[e])||void 0===n?void 0:n.toString())===i[e].toString())continue;o.listener[e]=i[e]}}else this._searchListenersByDataUnit.set(t,[...r,{entity:e,listener:i}]);return()=>{const i=r.filter((t=>t.entity!==e));i.length?this._searchListenersByDataUnit.set(t,i):this._searchListenersByDataUnit.delete(t)}}applySearchListener(e,t,i,n,r){var o;const s=null==r?void 0:r.dataUnitId;if(!s)return;const a=null===(o=this._searchListenersByDataUnit.get(s))||void 0===o?void 0:o.find((({entity:e})=>e===t));if(!a)return;const{listener:l}=a;return e in l?l[e]({argument:i,criteria:n,searchOptions:r}):void 0}}var o;!function(e){e.beforeSearch="beforeSearch"}(o||(o={}));export{r as P}
@@ -1 +1 @@
1
- import{D as t}from"./p-f3434fc4.js";import"./p-1bf06cd3.js";import{SortMode as i,ApplicationContext as s,UserInterface as e,DateUtils as r,ObjectUtils as a,StringUtils as n,NumberUtils as o,DataType as l}from"@sankhyalabs/core";import"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import{UserInterface as c}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{P as u}from"./p-7ac7932c.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import d from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource";import{h}from"./p-d2d301a6.js";class m{static assertDefaultSorting(t,s){t&&s&&(s.defaultSorting=t.columns.filter((t=>null!=t.ascending)).sort(((t,i)=>t.orderIndex-i.orderIndex)).map((({name:t,ascending:e})=>{const{dataType:r}=s.getField(t);return{field:t,dataType:r,mode:e?i.ASC:i.DESC}})))}static find(i,e,r,a=!0,n,o){let l=[],c=[],u={},d=s.getContextValue("__SNK__APPLICATION__");if(e){if(!Array.isArray(e))throw new Error(d.messagesBuilder.getMessage("crudUtils.errorArray",null));e.forEach((t=>{l.push({name:t})}))}if(r)for(const t in r)r.hasOwnProperty(t)&&c.push({nome:t,valor:r[t]});n&&(u={expression:{$:n}});let h={requestBody:{entity:{name:i,criterio:c,fields:{field:l},literalCriteria:u,orderby:o}}};return new Promise((i=>{t.get().callServiceBroker("mge@crud.find",JSON.stringify(h)).then((t=>{var s;let e=null===(s=t.entidades)||void 0===s?void 0:s.entidade;if(null!=e){let t={fields:new Map};for(let i in e){let s=e[i];if(s.hasOwnProperty("$")&&t.fields.set(i,s.$),a)break}i(t)}else i(null)}))}))}}class f{setDataUnit(t){this._dataUnit=t}setApplication(t){this._application=t}formatLabel(t,i){const{userInterface:s}=this._dataUnit.getField(t);return s===e.DATETIME?r.formatDate(this._dataUnit.valueFromString(t,i)):String(this._dataUnit.getFormattedValue(t,i))}async getStaticOptions(t){return Promise.resolve(null==t?void 0:await u.getDistinct(this._dataUnit,t))}fetchData(t,i){return new Promise((s=>{this._application.executeSelectDistinct(this._dataUnit,i,t).then((t=>{s(t.map((t=>this._dataUnit.getField(i).userInterface===e.SEARCH?Object.assign(Object.assign({},JSON.parse(t)),{check:!0}):{value:t,label:this.formatLabel(i,t),check:!0})))}))}))}sortItems(t,i){return d.defaultSorterMultSelectionOption(this._dataUnit,t,i)}}class p{setGrid(t){this._grid||(this._grid=t,this.refreshSelectedRows())}setDataState(t){this._dataState&&a.equals(null==t?void 0:t.metadataByRow,this._dataState.metadataByRow)||(this._dataState=t,this.refreshSelectedRows())}format(t,i,s){var e;if(n.isEmpty(t))return t;const r=null===(e=this._dataState)||void 0===e?void 0:e.metadataByRow.get(s),a=null==r?void 0:r.getProp("rm_precision",i.name);return a||0===a?o.format(t,a,a):t}refreshSelectedRows(){var t;null===(t=this._grid)||void 0===t||t.refreshSelectedRows()}}class v{constructor(t,i){this.dataUnit=t,this.grid=i}async getColumnsMetadata(){var t;return this.columnsState=await(null===(t=this.grid)||void 0===t?void 0:t.getColumnsState())||[],await this.buildColumnsMetadata(this.columnsState)}getColumnsState(){return this.columnsState}async buildColumnsMetadata(t){var i,s;const e=[];for(const r of t){if(r.hidden&&"RECDESP"!==r.name)continue;const t=null===(i=this.dataUnit)||void 0===i?void 0:i.getField(r.name),a=await this.grid.getCustomValueFormatter(r.name);if(e.push({label:r.label,id:r.name,width:r.width,type:null==t?void 0:t.dataType,userInterface:null==t?void 0:t.userInterface,customFormatter:a}),null!=(null===(s=null==t?void 0:t.properties)||void 0===s?void 0:s.DESCRIPTIONFIELD)){const i=t.properties.mergedFrom;e.push({label:t.properties.DESCRIPTIONENTITY,id:`${i?i+".":""}${t.properties.ENTITYNAME}.${t.properties.DESCRIPTIONFIELD}`,width:r.width,type:l.TEXT,userInterface:c.LONGTEXT,descriptionFrom:t.name})}}return e||[]}}class b{constructor(t,i,s){this.snkApplication=t,this.keyConfigEnableContinuousInsert=`${i}enableContinuousInsert${s||""}`}handleSaveConfig(t){return this.snkApplication.saveConfig(this.keyConfigEnableContinuousInsert,t)}getConfig(){return this.snkApplication.getConfig(this.keyConfigEnableContinuousInsert).then((t=>!!t&&"true"==t)).catch((()=>!1))}actionContinuousInsert(t,i){return{value:n.generateUUID(),label:t?"Desativar inclusão contínua":"Ativar inclusão contínua",enabled:!0,itemBuilder:()=>h("div",{class:"ez-dropdown__item-wrapper",onClick:i},h("span",{class:"ez-dropdown__item-label"},t?"Desativar inclusão contínua":"Ativar inclusão contínua"))}}}export{v as C,p as R,f as S,m as a,b}
1
+ import{D as t}from"./p-f3434fc4.js";import"./p-8a9638ae.js";import{SortMode as i,ApplicationContext as e,UserInterface as s,DateUtils as r,ObjectUtils as a,StringUtils as n,NumberUtils as o,DataType as l}from"@sankhyalabs/core";import"./p-30cf616e.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import{UserInterface as u}from"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import{P as c}from"./p-47bce500.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import d from"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource";import{h}from"./p-d2d301a6.js";class m{static assertDefaultSorting(t,e){t&&e&&(e.defaultSorting=t.columns.filter((t=>null!=t.ascending)).sort(((t,i)=>t.orderIndex-i.orderIndex)).map((({name:t,ascending:s})=>{const{dataType:r}=e.getField(t);return{field:t,dataType:r,mode:s?i.ASC:i.DESC}})))}static find(i,s,r,a=!0,n,o){let l=[],u=[],c={},d=e.getContextValue("__SNK__APPLICATION__");if(s){if(!Array.isArray(s))throw new Error(d.messagesBuilder.getMessage("crudUtils.errorArray",null));s.forEach((t=>{l.push({name:t})}))}if(r)for(const t in r)r.hasOwnProperty(t)&&u.push({nome:t,valor:r[t]});n&&(c={expression:{$:n}});let h={requestBody:{entity:{name:i,criterio:u,fields:{field:l},literalCriteria:c,orderby:o}}};return new Promise((i=>{t.get().callServiceBroker("mge@crud.find",JSON.stringify(h)).then((t=>{var e;let s=null===(e=t.entidades)||void 0===e?void 0:e.entidade;if(null!=s){let t={fields:new Map};for(let i in s){let e=s[i];if(e.hasOwnProperty("$")&&t.fields.set(i,e.$),a)break}i(t)}else i(null)}))}))}}class f{setDataUnit(t){this._dataUnit=t}setApplication(t){this._application=t}formatLabel(t,i){const{userInterface:e}=this._dataUnit.getField(t);return e===s.DATETIME?r.formatDate(this._dataUnit.valueFromString(t,i)):String(this._dataUnit.getFormattedValue(t,i))}async getStaticOptions(t){return Promise.resolve(null==t?void 0:await c.getDistinct(this._dataUnit,t))}fetchData(t,i){return new Promise((e=>{this._application.executeSelectDistinct(this._dataUnit,i,t).then((t=>{e(t.map((t=>this._dataUnit.getField(i).userInterface===s.SEARCH?Object.assign(Object.assign({},JSON.parse(t)),{check:!0}):{value:t,label:this.formatLabel(i,t),check:!0})))}))}))}sortItems(t,i){return d.defaultSorterMultSelectionOption(this._dataUnit,t,i)}}class p{setGrid(t){this._grid||(this._grid=t,this.refreshSelectedRows())}setDataState(t){this._dataState&&a.equals(null==t?void 0:t.metadataByRow,this._dataState.metadataByRow)||(this._dataState=t,this.refreshSelectedRows())}format(t,i,e){var s;if(n.isEmpty(t))return t;const r=null===(s=this._dataState)||void 0===s?void 0:s.metadataByRow.get(e),a=null==r?void 0:r.getProp("rm_precision",i.name);return a||0===a?o.format(t,a,a):t}refreshSelectedRows(){var t;null===(t=this._grid)||void 0===t||t.refreshSelectedRows()}}class v{constructor(t,i){this.dataUnit=t,this.grid=i}async getColumnsMetadata(){var t;return this.columnsState=await(null===(t=this.grid)||void 0===t?void 0:t.getColumnsState())||[],await this.buildColumnsMetadata(this.columnsState)}getColumnsState(){return this.columnsState}async buildColumnsMetadata(t){var i,e;const s=[];for(const r of t){if(r.hidden&&"RECDESP"!==r.name)continue;const t=null===(i=this.dataUnit)||void 0===i?void 0:i.getField(r.name),a=await this.grid.getCustomValueFormatter(r.name);if(s.push({label:r.label,id:r.name,width:r.width,type:null==t?void 0:t.dataType,userInterface:null==t?void 0:t.userInterface,customFormatter:a}),null!=(null===(e=null==t?void 0:t.properties)||void 0===e?void 0:e.DESCRIPTIONFIELD)){const i=t.properties.mergedFrom;s.push({label:t.properties.DESCRIPTIONENTITY,id:`${i?i+".":""}${t.properties.ENTITYNAME}.${t.properties.DESCRIPTIONFIELD}`,width:r.width,type:l.TEXT,userInterface:u.LONGTEXT,descriptionFrom:t.name})}}return s||[]}}class b{constructor(t,i,e){this.snkApplication=t,this.keyConfigEnableContinuousInsert=`${i}enableContinuousInsert${e||""}`}handleSaveConfig(t){return this.snkApplication.saveConfig(this.keyConfigEnableContinuousInsert,t)}getConfig(){return this.snkApplication.getConfig(this.keyConfigEnableContinuousInsert).then((t=>!!t&&"true"==t)).catch((()=>!1))}actionContinuousInsert(t,i){return{value:n.generateUUID(),label:t?"Desativar inclusão contínua":"Ativar inclusão contínua",enabled:!0,itemBuilder:()=>h("div",{class:"ez-dropdown__item-wrapper",onClick:i},h("span",{class:"ez-dropdown__item-label"},t?"Desativar inclusão contínua":"Ativar inclusão contínua"))}}}export{v as C,p as R,f as S,m as a,b}
@@ -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 u,b as p}from"./p-30cf616e.js";import{R as m}from"./p-b0ef4383.js";import{D as v}from"./p-f3434fc4.js";import{S as x}from"./p-5dd8cf4f.js";import"./p-1bf06cd3.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-7ac7932c.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import"./p-8d884fab.js";import"./p-17425c72.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"./p-7dd49d15.js";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")} (.xls)`,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")} (.xls)`}}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,l;const a=null===(i=(e=this._provider).getFilters)||void 0===i?void 0:i.call(e),d=(null===(s=b(null==t?void 0:t.exportOption))||void 0===s?void 0:s.includes("PDF"))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),h=null===(r=(o=this._provider).getOrders)||void 0===r?void 0:r.call(o),u=null===(l=(n=this._provider).getResourceURI)||void 0===l?void 0:l.call(n),p=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:a,columns:d,sort:h,resourceURI:u,selectedIDs:p.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){var e;const{methodName:i,gridTitle:s}=t,o=await this._provider.getRecords(),r=(null===(e=b(null==t?void 0:t.exportOption))||void 0===e?void 0:e.includes("PDF"))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),[n,l]=this.getExecutor(i),a={serviceName:n,requestBody:{grid:{gridTitle:s,columns:this.buildColumnsObject(r),rows:this.buildRowsObject(r,o),customOptions:{xlsxExtension:!1}}}};return new Promise(((t,e)=>{v.get().callServiceBroker(n,a).then((e=>t(l(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"},D[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 D={[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"}},k=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=p[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:p.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,gridTitle: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=u[r])&&void 0!==e?e:u.EXPORT_TO_PDF,l=u[r]===u.EXPORT_TO_XLS,a={methodName:c[`EXPORT_TO_${n}`],fileName:this._appLabel,gridTitle: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===u.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,u=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS],p=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(u.includes(null==a?void 0:a.id)&&x<=f||p?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(p)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)}};k.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{k 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 u,b as p}from"./p-30cf616e.js";import{R as m}from"./p-b0ef4383.js";import{D as v}from"./p-f3434fc4.js";import{S as x}from"./p-fd13b4d2.js";import"./p-8a9638ae.js";import"./p-21749402.js";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"./p-47bce500.js";import"./p-ff1990ad.js";import"./p-06421fdb.js";import"./p-8d884fab.js";import"./p-17425c72.js";import"@sankhyalabs/core/dist/dataunit/metadata/DataType";import"./p-7dd49d15.js";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class g{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")} (.xls)`,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")} (.xls)`}}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 f(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 f(await this._provider.getColumnsMetadata())}async getParams(t){var e,i,s,o,r,n,l;const a=null===(i=(e=this._provider).getFilters)||void 0===i?void 0:i.call(e),d=(null===(s=b(null==t?void 0:t.exportOption))||void 0===s?void 0:s.includes("PDF"))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),h=null===(r=(o=this._provider).getOrders)||void 0===r?void 0:r.call(o),u=null===(l=(n=this._provider).getResourceURI)||void 0===l?void 0:l.call(n),p=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:a,columns:d,sort:h,resourceURI:u,selectedIDs:p.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 f(await this._provider.getColumnsMetadata())}async executeExport(t){var e;const{methodName:i,gridTitle:s}=t,o=await this._provider.getRecords(),r=(null===(e=b(null==t?void 0:t.exportOption))||void 0===e?void 0:e.includes("PDF"))?await this.getParsedColumns():await this._provider.getColumnsMetadata(),[n,l]=this.getExecutor(i),a={serviceName:n,requestBody:{grid:{gridTitle:s,columns:this.buildColumnsObject(r),rows:this.buildRowsObject(r,o),customOptions:{xlsxExtension:!1}}}};return new Promise(((t,e)=>{v.get().callServiceBroker(n,a).then((e=>t(l(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"},D[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 D={[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"}},k=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=p[null==e?void 0:e.toUpperCase()])&&void 0!==r?r:p.PDF;this.resolveExporter({type:t,methodName:n,to:i,subject:s,message:o,fileName:this._appLabel,gridTitle: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=u[r])&&void 0!==e?e:u.EXPORT_TO_PDF,l=u[r]===u.EXPORT_TO_XLS,a={methodName:c[`EXPORT_TO_${n}`],fileName:this._appLabel,gridTitle: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===u.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,u=[c.EXPORT_PAGE_TO_PDF,c.EXPORT_PAGE_TO_XLS],p=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),g=null===(l=null===(n=this.provider)||void 0===n?void 0:n.getExportLimit)||void 0===l?void 0:l.call(n);let f=!1;if(u.includes(null==a?void 0:a.id)&&x<=g||p?f=!1:(null==m?void 0:m.length)?f=m.length>g:v>g&&(f=!0),f){const t=g.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(p)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 g(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)}};k.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{k as snk_data_exporter}
@@ -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-4d9549cf.js";import{d as _,D as A,U as I}from"./p-f3434fc4.js";import{A as S,a as b}from"./p-ca5ec380.js";import{D as C}from"./p-7ac7932c.js";import{P as N}from"./p-1bf06cd3.js";import{S as L}from"./p-17425c72.js";import"./p-06421fdb.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class D{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const T=k;function k(t,s){const e=E();return(k=function(t){return e[t-=378]})(t,s)}function E(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return(E=function(){return t})()}!function(){const t=k,s=E();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;s.push(s.shift())}catch(t){s.push(s.shift())}}();class O{[T(397)](t){const s=T;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new U("S"===t[s(402)]||!0===t[s(402)]);return Array[s(394)](t[s(391)])&&t[s(391)][s(385)]((t=>e.putAccess(t[s(382)],String(t.status)==s(398)))),e}}class U{constructor(t){const s=T;this.isSup=t,this[s(384)]={}}[T(378)](t,s){this[T(384)][t]=s}[T(393)](t){const s=T;if(this[s(402)])return!0;let e=!0;return this[s(384)][s(380)](t)&&(e=this.actions[t]),e}isUserSup(){return this.isSup}}class j{constructor(){this._embeddedParams=new Map,this.templateByQuery=new Map;try{if(null!=window.MGE_PARAMS){atob(window.MGE_PARAMS).split("__;__").forEach((t=>{const[s,e]=t.split("__=__");this._embeddedParams.set(s,e)}))}}catch(t){console.error("Problemas ao obter parâmetros embarcados"),console.error(t)}this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",_.gql`query($name: String!) {
1
+ import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,StringUtils as r,ObjectUtils as o,WaitingChangeException as a,WarningException as c,ErrorException as h,KeyboardManager as l,OnboardingUtils as u,DependencyType as p,ArrayUtils as d,SearchUtils as w,ElementIDUtils as m,ApplicationContext as y,DataType as f,ErrorTracking as P}from"@sankhyalabs/core";import{ApplicationUtils as v}from"@sankhyalabs/ezui/dist/collection/utils";import{C as g}from"./p-4d9549cf.js";import{d as _,D as A,U as I}from"./p-f3434fc4.js";import{A as S,a as b}from"./p-ca5ec380.js";import{D as C}from"./p-47bce500.js";import{P as N}from"./p-8a9638ae.js";import{S as L}from"./p-17425c72.js";import"./p-06421fdb.js";import"./p-ff1990ad.js";import"./p-8d884fab.js";import"@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata";import"@sankhyalabs/ezui/dist/collection/utils/constants";import"@sankhyalabs/ezui/dist/collection/components/ez-grid/utils";import"@sankhyalabs/core/dist/utils/SortingUtils";import"./p-688dcb4c.js";class D{static webConnectionCaller(t,s,e){var i;null===(i=window.AppletCaller)||void 0===i||i.webConnectionCaller(t,s,e)}}const T=k;function k(t,s){const e=E();return(k=function(t){return e[t-=378]})(t,s)}function E(){const t=["true","863GKWjmo","parse","56355fjjjAm","isSup","putAccess","4324480sjuCdS","hasOwnProperty","239748okvJLB","name","6055770tXeRaU","actions","forEach","7RPRvzn","1042CHxkUw","2988126NIwRMm","20MTNzmH","authorizationSf","item","string","hasAccess","isArray","Objeto não pode ser indefinido.","3071943fWslZp","parseFromJSON"];return(E=function(){return t})()}!function(){const t=k,s=E();for(;;)try{if(281287==parseInt(t(399))/1*(-parseInt(t(387))/2)+-parseInt(t(401))/3+parseInt(t(381))/4*(-parseInt(t(389))/5)+parseInt(t(388))/6*(-parseInt(t(386))/7)+parseInt(t(379))/8+parseInt(t(396))/9+parseInt(t(383))/10)break;s.push(s.shift())}catch(t){s.push(s.shift())}}();class O{[T(397)](t){const s=T;if(typeof(t=utxt(t[s(390)]))==s(392)&&(t=JSON[s(400)](t)),null==t)throw Error(s(395));const e=new U("S"===t[s(402)]||!0===t[s(402)]);return Array[s(394)](t[s(391)])&&t[s(391)][s(385)]((t=>e.putAccess(t[s(382)],String(t.status)==s(398)))),e}}class U{constructor(t){const s=T;this.isSup=t,this[s(384)]={}}[T(378)](t,s){this[T(384)][t]=s}[T(393)](t){const s=T;if(this[s(402)])return!0;let e=!0;return this[s(384)][s(380)](t)&&(e=this.actions[t]),e}isUserSup(){return this.isSup}}class j{constructor(){this._embeddedParams=new Map,this.templateByQuery=new Map;try{if(null!=window.MGE_PARAMS){atob(window.MGE_PARAMS).split("__;__").forEach((t=>{const[s,e]=t.split("__=__");this._embeddedParams.set(s,e)}))}}catch(t){console.error("Problemas ao obter parâmetros embarcados"),console.error(t)}this.buldTemplates()}buldTemplates(){this.templateByQuery.set("fetchParam",_.gql`query($name: String!) {
2
2
  $queryAlias$: fetchResource(name: $name){
3
3
  name
4
4
  resource
@@ -8,4 +8,4 @@ import{r as t,c as s,h as e,g as i}from"./p-d2d301a6.js";import{DateUtils as n,S
8
8
  name
9
9
  value
10
10
  }
11
- }`)}fetchTotals(t,s,e=[]){const i=`${t}_${s}`,n=this.cancel.findIndex((t=>t[i]));return n>=0&&(this.cancel[n][i](),this.cancel.splice(n,1)),Promise.race([new Promise((t=>this.cancel.push({[i]:t}))),this.getTotals(t,s,e)]).then((t=>{let s=new Map;if(t){s=t;const e=this.cancel.findIndex((t=>t[i]));e>=0&&this.cancel.splice(e,1)}return s}))}getTotals(t,s,e=[]){return new Promise(((i,n)=>{A.get().callGraphQL({query:this.templateByQuery.get("fetchTotals"),values:{name:`totals://${t}/${s}`,filters:e}}).then((t=>{if(t.length>0){const s=new Map;return t.forEach((t=>s.set(t.name,parseFloat(t.value)))),i(s)}return n("Não foi possível recuperar os totalizadores")})).catch(n)}))}}function M(){const t=["2909523kXwted","CompanyName=Sankhya Jiva Tecnologia e Inovao Ltda,LicensedApplication=Sankhya Gestao,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=2,LicensedProductionInstancesCount=0,AssetReference=AG-019460,ExpiryDate=9_November_2022_[v2]_MTY2Nzk1MjAwMDAwMA==10487151e296ee4360f80961ca960869","1131048CARoeW","502909mLEPmu","447255iQEXuN","428UHbJwW","270AFTxAV","194369jhGqTI","1540nWuTrj","2044062GicUQI","30CkXPWg"];return(M=function(){return t})()}const R=$;function $(t,s){const e=M();return($=function(t){return e[t-=392]})(t,s)}!function(){const t=$,s=M();for(;;)try{if(951926==-parseInt(t(398))/1+-parseInt(t(393))/2+parseInt(t(395))/3+-parseInt(t(400))/4*(parseInt(t(392))/5)+-parseInt(t(401))/6*(-parseInt(t(402))/7)+parseInt(t(397))/8+-parseInt(t(399))/9*(-parseInt(t(394))/10))break;s.push(s.shift())}catch(t){s.push(s.shift())}}();const z=R(396);var q;class x{static openAppActivity(t,s){var e;null===(e=window.workspace)||void 0===e||e.openAppActivity(t,s)}static getAppLabel(t){if(null!=(null===window||void 0===window?void 0:window.workspace))return null==window.workspace.getAppLabel&&(window.workspace.getAppLabel=t=>(t||"").split(".").pop()),window.workspace.getAppLabel(t)}static setScreenToUseV3Layout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseV3Layout()}static setScreenToUseOldLayout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseOldLayout()}static showDesktop(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.showDesktop)||void 0===s||s.call(t)}static searchApp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.searchApp)||void 0===s||s.call(t)}static openHelp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.openHelp)||void 0===s||s.call(t)}static applicationClick(){var t,s;(null===(t=window.workspace)||void 0===t?void 0:t.applicationClick)&&(null===(s=window.workspace)||void 0===s||s.applicationClick())}}x.resourceID=null===(q=window.workspace)||void 0===q?void 0:q.resourceID;class B{constructor(t){this._app=t,window.addEventListener("error",(t=>this.errorHandler(t))),window.addEventListener("unhandledrejection",(t=>this.rejectionHandler(t)))}rejectionHandler(t){const s=t.reason;s instanceof a||(s?this.processException(s):this._app.isDebugMode().then((t=>{t&&this._app.error("Promise rejeitada","Erro interno: Uma promise foi rejeitada sem razão determinada.")})))}errorHandler(t){this.processException(t.error)}buildErrorCodeHTML(t){return'<br><a href="#" onclick="try{window.workspace.openHelp(\'_tbcode:'+t+"')} catch(e){alert('Não é possível abrir a ajuda fora do workspace Sankhya');}\">Código: "+t+"</a>"}processException(t){t.errorCode&&(t.message+=this.buildErrorCodeHTML(t.errorCode)),t instanceof a||t instanceof c?this._app.alert(t.title,t.message):t instanceof h?this._app.error(t.title,t.message):this._app.isDebugMode().then((s=>{if(s)if(t instanceof Error)this._app.error(t.name,t.message);else{const s=(null==t?void 0:t.title)||"Erro detectado",e="string"==typeof t?t:t.message||`Erro interno "${o.objectToString(t)}"`;this._app.error(s,e)}}))}}const K=class{constructor(e){t(this,e),this.applicationLoaded=s(this,"applicationLoaded",7),this.applicationLoading=s(this,"applicationLoading",7),this.NEW_VERSION_POPUP_LOCKER="NEW_VERSION_POPUP_LOCKER",this._authPromises=[],this._keyboardManager=new l,this._waitingAppReady=new Array,this._duCache=new Map,this._duPromises=new Map,this._requestListener=new H,this._pendingActions=new Map,this._loadPkParameter=null,this._isLoadedByPk=!1,this.messagesBuilder=void 0,this.configName=void 0,this.gridLegacyConfigName=void 0,this.formLegacyConfigName=void 0,this.loadByPK=void 0}async processPendingActions(t){const s=this._pendingActions.get(t);s&&s.length&&(s.forEach((t=>t())),this._pendingActions.set(t,[]))}get parameters(){return this._parameters||(this._parameters=new j),this._parameters}async getAuth(t){return null==t?this.getApplicationAuth():new Promise(((s,e)=>{this.authFetcher.getData(t).then((t=>{s(t)})).catch((t=>{e(t)}))}))}async getApplicationAuth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,s)=>{const e=this._authPromises.length>0;this._authPromises.push(new V(t,s)),e||this.authFetcher.getData(this.applicationResourceID).then((t=>{for(this._auth=t;this._authPromises.length>0;)this._authPromises.pop().resolve(this._auth)})).catch((t=>{for(;this._authPromises.length>0;)this._authPromises.pop().reject(t)}))}))}watchPropHandler(t,s){t&&this._loadPkParameter&&(this.loadByPK(this._loadPkParameter.pk,this._loadPkParameter.redirect),this._loadPkParameter=null)}async getKeyboardManager(){return Promise.resolve(this._keyboardManager)}async isUserSup(){return new Promise(((t,s)=>{this.getAuth().then((e=>{this.getAuthList(e).then((s=>{t(s.isSup)})).catch((t=>s(t)))}))}))}async addPendingAction(t,s){var e;const i=null!==(e=this._pendingActions.get(t))&&void 0!==e?e:[];this._pendingActions.set(t,[...i,s])}async callServiceBroker(t,s,e){return A.get().callServiceBroker(t,s,e)}async initOnboarding(t){this.hasToShowNewVersionPopup()?await this.addPendingAction(this.NEW_VERSION_POPUP_LOCKER,(()=>this.doInitOnboarding(t))):this.doInitOnboarding(t)}doInitOnboarding(t){u.getInstance().init(t,window.envContext)}async hasAccess(t,s){return new Promise(((e,i)=>{this.getAuth(s).then((s=>{this.getAuthList(s).then((s=>{e(s.isSup||s.actions[t])})).catch((t=>i(t)))}))}))}async getAllAccess(t){return new Promise(((s,e)=>{this.getAuth(t).then((t=>{this.getAuthList(t).then((t=>{const e={};e.isSup=t.isSup,Object.entries(S).forEach((s=>{e[s[0]]=t.actions[s[1]]||!1})),s(e)})).catch((t=>e(t)))}))}))}async getStringParam(t){return this.parameters.asString(t)}async getIntParam(t){return this.parameters.asInteger(t)}async getFloatParam(t){return this.parameters.asFloat(t)}async getBooleanParam(t){return this.parameters.asBoolean(t)}async getDateParam(t){return this.parameters.asDate(t)}async showPopUp(t,s="full",e=!0,i){this.clearContent(this._popUp),this._popUp.addEventListener("ezClosePopup",(()=>{i()}),{once:!0}),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=s,this._popUp.useHeader=e,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}showAlerts(t){return v.showAlerts({alerts:t})}async closeModal(){this.clearContent(this._rightModal),this._rightModal.opened=!1}async closePopUp(){this.clearContent(this._popUp),this._popUp.opened=!1,this._popUp.useHeader=!0,this._popUp.heightMode="full"}async temOpcional(t){const s=t.split(",");return new Promise(((t,e)=>{this.getAttributeFromHTMLWrapper("opc0009").then((i=>{"1"===i?t(!0):Promise.all(s.map((t=>this.getAttributeFromHTMLWrapper("opc"+t)))).then((s=>{t(s.includes("1"))})).catch((t=>{e(t)}))})).catch((t=>{e(t)}))}))}async getConfig(t){let s={serviceName:"SystemUtilsSP.getConf",requestBody:{config:{chave:t,tipo:"T"}}};return new Promise(((t,e)=>{A.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(s)).then((s=>{var e;return t(null===(e=s.config)||void 0===e?void 0:e.data)})).catch((t=>e(t)))}))}async saveConfig(t,s){let e={serviceName:"SystemUtilsSP.saveConf",requestBody:{config:{chave:t,tipo:"T",data:s}}};return new Promise(((t,s)=>{A.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(e)).then((s=>t(s))).catch((t=>s(t)))}))}async getAttributeFromHTMLWrapper(t){return Promise.resolve(window[t])}async openApp(t,s){x.openAppActivity(t,s)}async webConnection(t,s,e){this.getStringParam(t).then((t=>{D.webConnectionCaller(t,s,e)}))}getDuPromissesStack(t){let s;return t&&(s=this._duPromises.get(t),s||(s=[],this._duPromises.set(t,s))),s||[]}async createDataunit(t,s,e,i,n){return null==n&&(n=this.applicationResourceID),new Promise(((r,o)=>{const a=this.getDuPromissesStack(s),c=a.length>0;if(a.push(new V(r,o)),!c){const r=this.dataUnitFetcher.getDataUnit(t,n,e,i);r.loadMetadata().then((()=>{this.processResolveDataUnit(r,s,a)})).catch((t=>{for(;a.length>0;)a.pop().reject(t)}))}}))}processResolveDataUnit(t,s,e){for(s&&this.updateDataunitCache(void 0,s,t);e.length>0;)e.pop().resolve(t)}async updateDataunitCache(t,s,e){t&&this._duCache.delete(t),this._duCache.set(s,e)}async getDataUnit(t,s,e,i,n){return new Promise(((r,o)=>{const a=this._duCache.get(s);a?r(a):this.createDataunit(t,s,e,i,n).then((t=>{r(t)})).catch((t=>o(t)))}))}async addClientEvent(t,s){return new Promise((e=>{A.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{A.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(A.hasClientEvent(t))}))}get applicationResourceID(){return this._applicationResourceID||(this._applicationResourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||x.resourceID||"unknown.resource.id"),this._applicationResourceID}async getResourceID(){return Promise.resolve(this.applicationResourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,s,e,i){return v.alert(t,s,e,i)}async error(t,s,e,i){return v.error(t,s,e,i)}async success(t,s,e,i){return v.success(t,s,e,i)}async message(t,s,e,i){return v.message(t,s,e,i)}async confirm(t,s,e,i,n){return v.confirm(t,s,e,i,n)}async info(t,s){return v.info(t,s)}async loadTotals(t,s,e){return this.totalsFetcher.fetchTotals(t,s,e)}async isLoadedByPk(){return Promise.resolve(this._isLoadedByPk)}async getAuthList(t){return await(new O).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=I.getQueryParams(location.search)),this._urlParams}getMessage(t,s){var e;return null===(e=this.messagesBuilder)||void 0===e?void 0:e.getMessage(t,s)}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new C),this._dataUnitFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new F),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new N),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new b),this._authFetcher}async executeSearch(t,s,e){const i=null==e?void 0:e.getField(s);if(i){const{mode:s,argument:n}=t,{ENTITYNAME:r,CODEFIELD:o,DESCRIPTIONFIELD:a,ROOTENTITY:c,DESCRIPTIONENTITY:h}=i.properties,l=i.dependencies;let u;const d={rootEntity:c,descriptionFieldName:a,codeFieldName:o,showInactives:!1,dataUnitId:e.dataUnitId};return null==l||l.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===p.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(u={expression:t.expression,params:t.masterFields.map((t=>{const s=e.getField(t),i=(null==s?void 0:s.dataType)||y.TEXT,n=e.getFieldValue(t);if(null==n)throw this.alert("Erro ao pesquisar",`É necessario informar o campo ${s.label} para executar a pesquisa.`),new Error(`É necessario informar o campo ${s.label} para executar a pesquisa.`);return{name:t,value:n,dataType:i}}))})})),this.executePreparedSearch(s,n,{entity:r,entityDescription:h,criteria:u,searchOptions:d})}}filterInvalidFields(t,s,e){return t.fieldsMetadata.filter((i=>{let n=!r.isEmpty(s[i.fieldName])&&!1!==i.visible&&"B"!==i.type&&t.pkField!==i.fieldName&&t.descriptionField!==i.fieldName&&(i.isPrimaryKey||!i.isLinkField)&&!("S"===i.type&&"H"===i.presentationType);return n&&(e[i.fieldName]=i),("string"!=typeof s[i.fieldName]||!(s[i.fieldName].indexOf("<img")>-1||s[i.fieldName].indexOf("<svg")>-1))&&n}))}filterMathFields(t,s,e,i){return t&&Array.isArray(t)&&t.forEach((t=>{let e=d.removeReference(s,i[t]);e&&s.unshift(e)})),s=s.slice(0,e)}builOptionItem(t,s,e,i,n){var o;return{value:r.highlightValue(t,s.__matchFields,null===(o=s[n])||void 0===o?void 0:o.toString(),e,!0),label:i?r.highlightValue(t,s.__matchFields,s[i],e,!0):"",details:w.buildDetails(t,e,s)}}async executePreparedSearch(t,s,e){const i={},{entity:n,entityDescription:r,criteria:a,searchOptions:c}=e;return new Promise("ADVANCED"===t?(t,e)=>{const i=document.createElement("snk-pesquisa");i[m.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,i.argument=s,i.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,a,c),i.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(i,void 0,void 0,e)}:(t,e)=>{this.pesquisaFetcher.loadAdvancedSearch(n,s,a,c).then((e=>{let n=(e=o.stringToObject(e.json.$)).descriptionField,r=e.pkField;const a=[];e.data.forEach((t=>{let o=this.filterInvalidFields(e,t,i),c=this.filterMathFields(t.__matchFields,o,6,i);a.push(this.builOptionItem(s,t,c,n,r))})),t(a)})).catch((t=>{e(t)}))})}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){return x.getAppLabel(this.applicationResourceID)}addSearchListener(t,s,e){return new Promise((i=>{i(this.pesquisaFetcher.addSearchListener(t,s.dataUnitId,e))}))}importScript(t){return new Promise((s=>{this.getApplicationPath().then((e=>{let i=[];Array.isArray(t)||(i=[t]),i.forEach((t=>{const s=document.createElement("script");s.src=`${e}/${t}`,s.async=!0,document.body.appendChild(s)})),s()}))}))}async getApplicationPath(){return new Promise((t=>{"dev"===window.applicationenv?t(""):t(`/${this.getModuleName()}/labsApps/${window.APPLICATION_NAME}/build`)}))}getModuleName(){return window.MGE_MODULE_NAME||"mgefin-bff"}executeSelectDistinct(t,s,e){return this.dataUnitFetcher.loadSelectDistinct(t,s,e)}getDataFetcher(){return Promise.resolve(A.get())}async whenApplicationReady(){return f.getContextValue("__SNK__APPLICATION__LOADING__")?Promise.resolve(this):new Promise((t=>{this._waitingAppReady.push((()=>t(this)))}))}async setSearchFilterContext(t,s){f.setContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${t})__`,s)}clearContent(t){t&&Array.from(t.children).forEach((s=>{t.removeChild(s)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}async pkChangeListener(){const t=top.window.location.hash.split("/")[2];if(this._currentPkParameter===t)return;const s=this.getResourceIdFromToken(),e=I.getPkObjectFromUrlToken(top.window.location.hash),i=window.redirectFrom;if(void 0===e)return;if((!i||-1===i.split("_")[0].indexOf(s.split("_")[0]))&&s!==this.applicationResourceID)return;const n={pk:e};if(this._isLoadedByPk=!0,this.loadByPK)return this.loadByPK(n,i),void(this._currentPkParameter=t);this._loadPkParameter={pk:n,redirect:i},this.defaultLoadByPK(n,t)}getResourceIdFromToken(){return top.window.location.pathname.indexOf("tabContent.jsp")>-1?I.getResourceIdFromUrlToken(window.location.generateHash(window.location.hash)):I.getResourceIdFromUrlToken(top.window.location.hash)}defaultLoadByPK(t,s){if(!(null==t?void 0:t.pk))return;const e=this.getFirstDataUnitFromDOM(),i=e.dataUnit;if(!i)return console.warn("Dataunit não inicializado"),void e.addEventListener("dataUnitReady",(e=>{this.loadDataWithPKFilter(t,e.detail),this._currentPkParameter=s}));this.loadDataWithPKFilter(t,i),this._currentPkParameter=s}loadDataWithPKFilter(t,s){const e={term:"",filter:{name:"LOAD_BY_PK_FILTER",expression:this.buildFilterExpressionByPkObject(t),params:this.getFilterParamsFromPkObject(t,s)}};s.loadData(e)}getFirstDataUnitFromDOM(){let t=this._element.querySelector("snk-data-unit[data-load-by-pk]");if(t||(t=this._element.querySelector("snk-data-unit")),t)return t}getFilterParamsFromPkObject(t,s){var e;const i=[];for(const n in t.pk)t.pk.hasOwnProperty(n)&&!Array.isArray(t.pk[n])&&i.push({name:n,dataType:(null===(e=s.getField(n))||void 0===e?void 0:e.dataType)||this.getDefaultDataTypeLoadByPK(t.pk[n]),value:t.pk[n]});return i}getDefaultDataTypeLoadByPK(t){return"number"==typeof t||t instanceof Number?y.NUMBER:"boolean"==typeof t||t instanceof Boolean?y.BOOLEAN:t instanceof Date?y.DATE:y.TEXT}buildFilterExpressionByPkObject(t){let s="";for(const e in t.pk)r.isEmpty(s)||(s+=" AND "),Array.isArray(t.pk[e])?s+=`${e} IN (${t.pk[e].toString()})`:s+=`${e} = :${e}`;return s}async showNewVersionPopup(){const t=document.createElement("ez-modal-container"),s=await this.getAppLabel();t.modalTitle=this.getMessage("snkApplication.newVersionPopup.title",{screenName:s}),t.okButtonLabel=this.getMessage("snkApplication.newVersionPopup.okButton"),t.cancelButtonLabel=this.getMessage("snkApplication.newVersionPopup.cancelButton");const e=document.createElement("p");e.innerText=this.getMessage("snkApplication.newVersionPopup.info"),e.className="ez-text",t.appendChild(e),t.addEventListener("ezModalAction",this.newVersionPopupEventListener.bind(this));const i=await v.showPopup({content:t});this._removeVersionLayoutPopup=async()=>{await i(),await this.processPendingActions(this.NEW_VERSION_POPUP_LOCKER)}}async newVersionPopupEventListener(t){"LOAD"!==t.detail&&("OK"===t.detail&&x.setScreenToUseV3Layout(),"CANCEL"===t.detail&&x.setScreenToUseOldLayout(),this._popUp.opened=!1,this._removeVersionLayoutPopup&&await this._removeVersionLayoutPopup())}async handleShowNewVersionPopup(){this.hasToShowNewVersionPopup()&&await this.showNewVersionPopup()}hasToShowNewVersionPopup(){const t=new URLSearchParams(window.location.search).get("firstLoadConv");return t&&"S"===t}registerPkChangeListener(){window.hasOwnProperty("onhashchange")?window.onhashchange=this.pkChangeListener.bind(this):setInterval(this.pkChangeListener.bind(this),100)}componentWillLoad(){f.setContextValue("__SNK__APPLICATION__LOADING__",!0),this._errorHandler=new B(this),this.messagesBuilder=new L,f.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${I.getUrlBase()}/mge/upload/file`),f.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,s,e)=>this.executeSearch(t,s,e))),f.setContextValue("__EZUI__GRID_LICENSE__",z),this.registerPkChangeListener(),P.init(),g.preload(this.applicationResourceID,this.configName,{gridLegacyConfig:this.gridLegacyConfigName,formLegacyConfig:this.formLegacyConfigName}),document.addEventListener("click",(()=>x.applicationClick())),this._waitingAppReady.forEach((t=>t()))}connectedCallback(){f.setContextValue("__SNK__APPLICATION__",this),A.addRequestListener(this._requestListener)}disconnectedCallback(){A.removeRequestListener(this._requestListener),this.removeShortcuts()}async componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{f.setContextValue("__SNK__APPLICATION__LOADING__",!1),this.applicationLoaded.emit(!0),this.pkChangeListener()})),m.addIDInfo(this._element,`resource_${this.applicationResourceID}`),await this.handleShowNewVersionPopup(),this.initKeyboardManager()}initKeyboardManager(){this._keyboardManager.bind("ctrl + g",x.searchApp.bind(this),{description:"Pesquisar por telas"}).bind("ctrl + d",x.showDesktop.bind(this),{description:"Mostrar o desktop"}).bind("F1",x.openHelp.bind(this),{description:"Abrir ajuda"})}removeShortcuts(){this._keyboardManager.unbind("ctrl + g").unbind("ctrl + d").unbind("F1")}render(){return e("div",null,e("ez-loading-bar",{ref:t=>this._requestListener.loadingBar=t}),e("ez-popup",{opened:!1,ref:t=>this._popUp=t,onEzClosePopup:()=>this.closePopUp()}),e("ez-modal",{opened:!1,ref:t=>this._rightModal=t,"modal-size":"small",closeOutsideClick:!0,closeEsc:!0}))}get _element(){return i(this)}static get watchers(){return{loadByPK:["watchPropHandler"]}}};class H{constructor(){this._debounceTime=1e3,this._ignoredNameTypes=["totals"],this._countRequest=0}onRequestStart(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest++,this.loadingBar.show(),this._timerLoading&&clearTimeout(this._timerLoading))}onRequestEnd(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest--,this._timerLoading=setTimeout((()=>{this._countRequest<=0&&this.loadingBar.hide()}),this._debounceTime))}isIgnoreLoadingOnRequest(t){if(null==t)return!1;if(t.url.includes("quietMode=true"))return!0;if(null==t.requestBody)return!1;if(1==t.requestBody.length){const{name:s}=t.requestBody[0].variables;if(s){const t=s.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class V{constructor(t,s){this.resolve=t,this.reject=s}}K.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{K as snk_application}
11
+ }`)}fetchTotals(t,s,e=[]){const i=`${t}_${s}`,n=this.cancel.findIndex((t=>t[i]));return n>=0&&(this.cancel[n][i](),this.cancel.splice(n,1)),Promise.race([new Promise((t=>this.cancel.push({[i]:t}))),this.getTotals(t,s,e)]).then((t=>{let s=new Map;if(t){s=t;const e=this.cancel.findIndex((t=>t[i]));e>=0&&this.cancel.splice(e,1)}return s}))}getTotals(t,s,e=[]){return new Promise(((i,n)=>{A.get().callGraphQL({query:this.templateByQuery.get("fetchTotals"),values:{name:`totals://${t}/${s}`,filters:e}}).then((t=>{if(t.length>0){const s=new Map;return t.forEach((t=>s.set(t.name,parseFloat(t.value)))),i(s)}return n("Não foi possível recuperar os totalizadores")})).catch(n)}))}}function M(){const t=["2909523kXwted","CompanyName=Sankhya Jiva Tecnologia e Inovao Ltda,LicensedApplication=Sankhya Gestao,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=2,LicensedProductionInstancesCount=0,AssetReference=AG-019460,ExpiryDate=9_November_2022_[v2]_MTY2Nzk1MjAwMDAwMA==10487151e296ee4360f80961ca960869","1131048CARoeW","502909mLEPmu","447255iQEXuN","428UHbJwW","270AFTxAV","194369jhGqTI","1540nWuTrj","2044062GicUQI","30CkXPWg"];return(M=function(){return t})()}const R=$;function $(t,s){const e=M();return($=function(t){return e[t-=392]})(t,s)}!function(){const t=$,s=M();for(;;)try{if(951926==-parseInt(t(398))/1+-parseInt(t(393))/2+parseInt(t(395))/3+-parseInt(t(400))/4*(parseInt(t(392))/5)+-parseInt(t(401))/6*(-parseInt(t(402))/7)+parseInt(t(397))/8+-parseInt(t(399))/9*(-parseInt(t(394))/10))break;s.push(s.shift())}catch(t){s.push(s.shift())}}();const z=R(396);var q;class x{static openAppActivity(t,s){var e;null===(e=window.workspace)||void 0===e||e.openAppActivity(t,s)}static getAppLabel(t){if(null!=(null===window||void 0===window?void 0:window.workspace))return null==window.workspace.getAppLabel&&(window.workspace.getAppLabel=t=>(t||"").split(".").pop()),window.workspace.getAppLabel(t)}static setScreenToUseV3Layout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseV3Layout()}static setScreenToUseOldLayout(){var t;null===(t=window.workspace)||void 0===t||t.setScreenToUseOldLayout()}static showDesktop(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.showDesktop)||void 0===s||s.call(t)}static searchApp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.searchApp)||void 0===s||s.call(t)}static openHelp(){var t,s;null===(s=null===(t=window.workspace)||void 0===t?void 0:t.openHelp)||void 0===s||s.call(t)}static applicationClick(){var t,s;(null===(t=window.workspace)||void 0===t?void 0:t.applicationClick)&&(null===(s=window.workspace)||void 0===s||s.applicationClick())}}x.resourceID=null===(q=window.workspace)||void 0===q?void 0:q.resourceID;class B{constructor(t){this._app=t,window.addEventListener("error",(t=>this.errorHandler(t))),window.addEventListener("unhandledrejection",(t=>this.rejectionHandler(t)))}rejectionHandler(t){const s=t.reason;s instanceof a||(s?this.processException(s):this._app.isDebugMode().then((t=>{t&&this._app.error("Promise rejeitada","Erro interno: Uma promise foi rejeitada sem razão determinada.")})))}errorHandler(t){this.processException(t.error)}buildErrorCodeHTML(t){return'<br><a href="#" onclick="try{window.workspace.openHelp(\'_tbcode:'+t+"')} catch(e){alert('Não é possível abrir a ajuda fora do workspace Sankhya');}\">Código: "+t+"</a>"}processException(t){t.errorCode&&(t.message+=this.buildErrorCodeHTML(t.errorCode)),t instanceof a||t instanceof c?this._app.alert(t.title,t.message):t instanceof h?this._app.error(t.title,t.message):this._app.isDebugMode().then((s=>{if(s)if(t instanceof Error)this._app.error(t.name,t.message);else{const s=(null==t?void 0:t.title)||"Erro detectado",e="string"==typeof t?t:t.message||`Erro interno "${o.objectToString(t)}"`;this._app.error(s,e)}}))}}const K=class{constructor(e){t(this,e),this.applicationLoaded=s(this,"applicationLoaded",7),this.applicationLoading=s(this,"applicationLoading",7),this.NEW_VERSION_POPUP_LOCKER="NEW_VERSION_POPUP_LOCKER",this._authPromises=[],this._keyboardManager=new l,this._waitingAppReady=new Array,this._duCache=new Map,this._duPromises=new Map,this._requestListener=new H,this._pendingActions=new Map,this._loadPkParameter=null,this._isLoadedByPk=!1,this.messagesBuilder=void 0,this.configName=void 0,this.gridLegacyConfigName=void 0,this.formLegacyConfigName=void 0,this.loadByPK=void 0}async processPendingActions(t){const s=this._pendingActions.get(t);s&&s.length&&(s.forEach((t=>t())),this._pendingActions.set(t,[]))}get parameters(){return this._parameters||(this._parameters=new j),this._parameters}async getAuth(t){return null==t?this.getApplicationAuth():new Promise(((s,e)=>{this.authFetcher.getData(t).then((t=>{s(t)})).catch((t=>{e(t)}))}))}async getApplicationAuth(){return this._auth?Promise.resolve(this._auth):new Promise(((t,s)=>{const e=this._authPromises.length>0;this._authPromises.push(new V(t,s)),e||this.authFetcher.getData(this.applicationResourceID).then((t=>{for(this._auth=t;this._authPromises.length>0;)this._authPromises.pop().resolve(this._auth)})).catch((t=>{for(;this._authPromises.length>0;)this._authPromises.pop().reject(t)}))}))}watchPropHandler(t,s){t&&this._loadPkParameter&&(this.loadByPK(this._loadPkParameter.pk,this._loadPkParameter.redirect),this._loadPkParameter=null)}async getKeyboardManager(){return Promise.resolve(this._keyboardManager)}async isUserSup(){return new Promise(((t,s)=>{this.getAuth().then((e=>{this.getAuthList(e).then((s=>{t(s.isSup)})).catch((t=>s(t)))}))}))}async addPendingAction(t,s){var e;const i=null!==(e=this._pendingActions.get(t))&&void 0!==e?e:[];this._pendingActions.set(t,[...i,s])}async callServiceBroker(t,s,e){return A.get().callServiceBroker(t,s,e)}async initOnboarding(t){this.hasToShowNewVersionPopup()?await this.addPendingAction(this.NEW_VERSION_POPUP_LOCKER,(()=>this.doInitOnboarding(t))):this.doInitOnboarding(t)}doInitOnboarding(t){u.getInstance().init(t,window.envContext)}async hasAccess(t,s){return new Promise(((e,i)=>{this.getAuth(s).then((s=>{this.getAuthList(s).then((s=>{e(s.isSup||s.actions[t])})).catch((t=>i(t)))}))}))}async getAllAccess(t){return new Promise(((s,e)=>{this.getAuth(t).then((t=>{this.getAuthList(t).then((t=>{const e={};e.isSup=t.isSup,Object.entries(S).forEach((s=>{e[s[0]]=t.actions[s[1]]||!1})),s(e)})).catch((t=>e(t)))}))}))}async getStringParam(t){return this.parameters.asString(t)}async getIntParam(t){return this.parameters.asInteger(t)}async getFloatParam(t){return this.parameters.asFloat(t)}async getBooleanParam(t){return this.parameters.asBoolean(t)}async getDateParam(t){return this.parameters.asDate(t)}async showPopUp(t,s="full",e=!0,i){this.clearContent(this._popUp),this._popUp.addEventListener("ezClosePopup",(()=>{i()}),{once:!0}),this._popUp.appendChild(t),this._popUp.opened=!0,this._popUp.heightMode=s,this._popUp.useHeader=e,"EZ-MODAL-CONTAINER"===t.tagName&&(this._popUp.useHeader=!1)}async showModal(t){this.clearContent(this._rightModal),this._rightModal.appendChild(t),this._rightModal.opened=!0}showAlerts(t){return v.showAlerts({alerts:t})}async closeModal(){this.clearContent(this._rightModal),this._rightModal.opened=!1}async closePopUp(){this.clearContent(this._popUp),this._popUp.opened=!1,this._popUp.useHeader=!0,this._popUp.heightMode="full"}async temOpcional(t){const s=t.split(",");return new Promise(((t,e)=>{this.getAttributeFromHTMLWrapper("opc0009").then((i=>{"1"===i?t(!0):Promise.all(s.map((t=>this.getAttributeFromHTMLWrapper("opc"+t)))).then((s=>{t(s.includes("1"))})).catch((t=>{e(t)}))})).catch((t=>{e(t)}))}))}async getConfig(t){let s={serviceName:"SystemUtilsSP.getConf",requestBody:{config:{chave:t,tipo:"T"}}};return new Promise(((t,e)=>{A.get().callServiceBroker("SystemUtilsSP.getConf",JSON.stringify(s)).then((s=>{var e;return t(null===(e=s.config)||void 0===e?void 0:e.data)})).catch((t=>e(t)))}))}async saveConfig(t,s){let e={serviceName:"SystemUtilsSP.saveConf",requestBody:{config:{chave:t,tipo:"T",data:s}}};return new Promise(((t,s)=>{A.get().callServiceBroker("SystemUtilsSP.saveConf",JSON.stringify(e)).then((s=>t(s))).catch((t=>s(t)))}))}async getAttributeFromHTMLWrapper(t){return Promise.resolve(window[t])}async openApp(t,s){x.openAppActivity(t,s)}async webConnection(t,s,e){this.getStringParam(t).then((t=>{D.webConnectionCaller(t,s,e)}))}getDuPromissesStack(t){let s;return t&&(s=this._duPromises.get(t),s||(s=[],this._duPromises.set(t,s))),s||[]}async createDataunit(t,s,e,i,n){return null==n&&(n=this.applicationResourceID),new Promise(((r,o)=>{const a=this.getDuPromissesStack(s),c=a.length>0;if(a.push(new V(r,o)),!c){const r=this.dataUnitFetcher.getDataUnit(t,n,e,i);r.loadMetadata().then((()=>{this.processResolveDataUnit(r,s,a)})).catch((t=>{for(;a.length>0;)a.pop().reject(t)}))}}))}processResolveDataUnit(t,s,e){for(s&&this.updateDataunitCache(void 0,s,t);e.length>0;)e.pop().resolve(t)}async updateDataunitCache(t,s,e){t&&this._duCache.delete(t),this._duCache.set(s,e)}async getDataUnit(t,s,e,i,n){return new Promise(((r,o)=>{const a=this._duCache.get(s);a?r(a):this.createDataunit(t,s,e,i,n).then((t=>{r(t)})).catch((t=>o(t)))}))}async addClientEvent(t,s){return new Promise((e=>{A.addClientEvent(t,s),e()}))}async removeClientEvent(t){return new Promise((s=>{A.removeClientEvent(t),s()}))}async hasClientEvent(t){return new Promise((s=>{s(A.hasClientEvent(t))}))}get applicationResourceID(){return this._applicationResourceID||(this._applicationResourceID=this.urlParams.get("workspaceResourceID")||this.urlParams.get("resourceID")||x.resourceID||"unknown.resource.id"),this._applicationResourceID}async getResourceID(){return Promise.resolve(this.applicationResourceID)}async getUserID(){return Promise.resolve(window.UID)}async alert(t,s,e,i){return v.alert(t,s,e,i)}async error(t,s,e,i){return v.error(t,s,e,i)}async success(t,s,e,i){return v.success(t,s,e,i)}async message(t,s,e,i){return v.message(t,s,e,i)}async confirm(t,s,e,i,n){return v.confirm(t,s,e,i,n)}async info(t,s){return v.info(t,s)}async loadTotals(t,s,e){return this.totalsFetcher.fetchTotals(t,s,e)}async isLoadedByPk(){return Promise.resolve(this._isLoadedByPk)}async getAuthList(t){return await(new O).parseFromJSON(t)}get urlParams(){return this._urlParams||(this._urlParams=I.getQueryParams(location.search)),this._urlParams}getMessage(t,s){var e;return null===(e=this.messagesBuilder)||void 0===e?void 0:e.getMessage(t,s)}get dataUnitFetcher(){return this._dataUnitFetcher||(this._dataUnitFetcher=new C),this._dataUnitFetcher}get totalsFetcher(){return this._totalsFetcher||(this._totalsFetcher=new F),this._totalsFetcher}get pesquisaFetcher(){return this._pesquisaFetcher||(this._pesquisaFetcher=new N),this._pesquisaFetcher}get authFetcher(){return this._authFetcher||(this._authFetcher=new b),this._authFetcher}async executeSearch(t,s,e){const i=null==e?void 0:e.getField(s);if(i){const{mode:s,argument:n}=t,{ENTITYNAME:r,CODEFIELD:o,DESCRIPTIONFIELD:a,ROOTENTITY:c,DESCRIPTIONENTITY:h}=i.properties,l=i.dependencies;let u;const d={rootEntity:c,descriptionFieldName:a,codeFieldName:o,showInactives:!1,dataUnitId:e.dataUnitId};return null==l||l.filter((t=>t.masterFields)).forEach((t=>{var s;t.type===p.SEARCHING&&(null===(s=t.masterFields)||void 0===s?void 0:s.length)>0&&(u={expression:t.expression,params:t.masterFields.map((t=>{const s=e.getField(t),i=(null==s?void 0:s.dataType)||f.TEXT,n=e.getFieldValue(t);if(null==n)throw this.alert("Erro ao pesquisar",`É necessario informar o campo ${s.label} para executar a pesquisa.`),new Error(`É necessario informar o campo ${s.label} para executar a pesquisa.`);return{name:t,value:n,dataType:i}}))})})),this.executePreparedSearch(s,n,{entity:r,entityDescription:h,criteria:u,searchOptions:d})}}filterInvalidFields(t,s,e){return t.fieldsMetadata.filter((i=>{let n=!r.isEmpty(s[i.fieldName])&&!1!==i.visible&&"B"!==i.type&&t.pkField!==i.fieldName&&t.descriptionField!==i.fieldName&&(i.isPrimaryKey||!i.isLinkField)&&!("S"===i.type&&"H"===i.presentationType);return n&&(e[i.fieldName]=i),("string"!=typeof s[i.fieldName]||!(s[i.fieldName].indexOf("<img")>-1||s[i.fieldName].indexOf("<svg")>-1))&&n}))}filterMathFields(t,s,e,i){return t&&Array.isArray(t)&&t.forEach((t=>{let e=d.removeReference(s,i[t]);e&&s.unshift(e)})),s=s.slice(0,e)}builOptionItem(t,s,e,i,n){var o;return{value:r.highlightValue(t,s.__matchFields,null===(o=s[n])||void 0===o?void 0:o.toString(),e,!0),label:i?r.highlightValue(t,s.__matchFields,s[i],e,!0):"",details:w.buildDetails(t,e,s)}}async executePreparedSearch(t,s,e){const i={},{entity:n,entityDescription:r,criteria:a,searchOptions:c}=e;return new Promise("ADVANCED"===t?(t,e)=>{const i=document.createElement("snk-pesquisa");i[m.DATA_ELEMENT_ID_ATTRIBUTE_NAME]=`entity_${n}`,i.argument=s,i.searchLoader=t=>this.pesquisaFetcher.loadAdvancedSearch(n,t,a,c),i.selectItem=s=>{t(s),this.clearPopUpTitle(),this.closePopUp()},this.setPopUpTitle(r),this.showPopUp(i,void 0,void 0,e)}:(t,e)=>{this.pesquisaFetcher.loadAdvancedSearch(n,s,a,c).then((e=>{let n=(e=o.stringToObject(e.json.$)).descriptionField,r=e.pkField;const a=[];e.data.forEach((t=>{let o=this.filterInvalidFields(e,t,i),c=this.filterMathFields(t.__matchFields,o,6,i);a.push(this.builOptionItem(s,t,c,n,r))})),t(a)})).catch((t=>{e(t)}))})}async isDebugMode(){return new Promise((t=>{t(window.isDebugMode)}))}async getAppLabel(){return x.getAppLabel(this.applicationResourceID)}addSearchListener(t,s,e){return new Promise((i=>{i(this.pesquisaFetcher.addSearchListener(t,s.dataUnitId,e))}))}importScript(t){return new Promise((s=>{this.getApplicationPath().then((e=>{let i=[];Array.isArray(t)||(i=[t]),i.forEach((t=>{const s=document.createElement("script");s.src=`${e}/${t}`,s.async=!0,document.body.appendChild(s)})),s()}))}))}async getApplicationPath(){return new Promise((t=>{"dev"===window.applicationenv?t(""):t(`/${this.getModuleName()}/labsApps/${window.APPLICATION_NAME}/build`)}))}getModuleName(){return window.MGE_MODULE_NAME||"mgefin-bff"}executeSelectDistinct(t,s,e){return this.dataUnitFetcher.loadSelectDistinct(t,s,e)}getDataFetcher(){return Promise.resolve(A.get())}async whenApplicationReady(){return y.getContextValue("__SNK__APPLICATION__LOADING__")?Promise.resolve(this):new Promise((t=>{this._waitingAppReady.push((()=>t(this)))}))}async setSearchFilterContext(t,s){y.setContextValue(`__SNK__APPLICATION__FILTER__CONTEXT(${t})__`,s)}clearContent(t){t&&Array.from(t.children).forEach((s=>{t.removeChild(s)}))}clearPopUpTitle(){this._popUp.ezTitle=""}setPopUpTitle(t){this._popUp.ezTitle=t}async pkChangeListener(){const t=top.window.location.hash.split("/")[2];if(this._currentPkParameter===t)return;const s=this.getResourceIdFromToken(),e=I.getPkObjectFromUrlToken(top.window.location.hash),i=window.redirectFrom;if(void 0===e)return;if((!i||-1===i.split("_")[0].indexOf(s.split("_")[0]))&&s!==this.applicationResourceID)return;const n={pk:e};if(this._isLoadedByPk=!0,this.loadByPK)return this.loadByPK(n,i),void(this._currentPkParameter=t);this._loadPkParameter={pk:n,redirect:i},this.defaultLoadByPK(n,t)}getResourceIdFromToken(){return top.window.location.pathname.indexOf("tabContent.jsp")>-1?I.getResourceIdFromUrlToken(window.location.generateHash(window.location.hash)):I.getResourceIdFromUrlToken(top.window.location.hash)}defaultLoadByPK(t,s){if(!(null==t?void 0:t.pk))return;const e=this.getFirstDataUnitFromDOM(),i=e.dataUnit;if(!i)return console.warn("Dataunit não inicializado"),void e.addEventListener("dataUnitReady",(e=>{this.loadDataWithPKFilter(t,e.detail),this._currentPkParameter=s}));this.loadDataWithPKFilter(t,i),this._currentPkParameter=s}loadDataWithPKFilter(t,s){const e={term:"",filter:{name:"LOAD_BY_PK_FILTER",expression:this.buildFilterExpressionByPkObject(t),params:this.getFilterParamsFromPkObject(t,s)}};s.loadData(e)}getFirstDataUnitFromDOM(){let t=this._element.querySelector("snk-data-unit[data-load-by-pk]");if(t||(t=this._element.querySelector("snk-data-unit")),t)return t}getFilterParamsFromPkObject(t,s){var e;const i=[];for(const n in t.pk)t.pk.hasOwnProperty(n)&&!Array.isArray(t.pk[n])&&i.push({name:n,dataType:(null===(e=s.getField(n))||void 0===e?void 0:e.dataType)||this.getDefaultDataTypeLoadByPK(t.pk[n]),value:t.pk[n]});return i}getDefaultDataTypeLoadByPK(t){return"number"==typeof t||t instanceof Number?f.NUMBER:"boolean"==typeof t||t instanceof Boolean?f.BOOLEAN:t instanceof Date?f.DATE:f.TEXT}buildFilterExpressionByPkObject(t){let s="";for(const e in t.pk)r.isEmpty(s)||(s+=" AND "),Array.isArray(t.pk[e])?s+=`${e} IN (${t.pk[e].toString()})`:s+=`${e} = :${e}`;return s}async showNewVersionPopup(){const t=document.createElement("ez-modal-container"),s=await this.getAppLabel();t.modalTitle=this.getMessage("snkApplication.newVersionPopup.title",{screenName:s}),t.okButtonLabel=this.getMessage("snkApplication.newVersionPopup.okButton"),t.cancelButtonLabel=this.getMessage("snkApplication.newVersionPopup.cancelButton");const e=document.createElement("p");e.innerText=this.getMessage("snkApplication.newVersionPopup.info"),e.className="ez-text",t.appendChild(e),t.addEventListener("ezModalAction",this.newVersionPopupEventListener.bind(this));const i=await v.showPopup({content:t});this._removeVersionLayoutPopup=async()=>{await i(),await this.processPendingActions(this.NEW_VERSION_POPUP_LOCKER)}}async newVersionPopupEventListener(t){"LOAD"!==t.detail&&("OK"===t.detail&&x.setScreenToUseV3Layout(),"CANCEL"===t.detail&&x.setScreenToUseOldLayout(),this._popUp.opened=!1,this._removeVersionLayoutPopup&&await this._removeVersionLayoutPopup())}async handleShowNewVersionPopup(){this.hasToShowNewVersionPopup()&&await this.showNewVersionPopup()}hasToShowNewVersionPopup(){const t=new URLSearchParams(window.location.search).get("firstLoadConv");return t&&"S"===t}registerPkChangeListener(){window.hasOwnProperty("onhashchange")?window.onhashchange=this.pkChangeListener.bind(this):setInterval(this.pkChangeListener.bind(this),100)}componentWillLoad(){y.setContextValue("__SNK__APPLICATION__LOADING__",!0),this._errorHandler=new B(this),this.messagesBuilder=new L,y.setContextValue("__EZUI__UPLOAD__ADD__URL__",`${I.getUrlBase()}/mge/upload/file`),y.setContextValue("__EZUI__SEARCH__OPTION__LOADER__",((t,s,e)=>this.executeSearch(t,s,e))),y.setContextValue("__EZUI__GRID_LICENSE__",z),this.registerPkChangeListener(),P.init(),g.preload(this.applicationResourceID,this.configName,{gridLegacyConfig:this.gridLegacyConfigName,formLegacyConfig:this.formLegacyConfigName}),document.addEventListener("click",(()=>x.applicationClick())),this._waitingAppReady.forEach((t=>t()))}connectedCallback(){y.setContextValue("__SNK__APPLICATION__",this),A.addRequestListener(this._requestListener)}disconnectedCallback(){A.removeRequestListener(this._requestListener),this.removeShortcuts()}async componentDidLoad(){this.applicationLoading.emit(!0),window.requestAnimationFrame((()=>{y.setContextValue("__SNK__APPLICATION__LOADING__",!1),this.applicationLoaded.emit(!0),this.pkChangeListener()})),m.addIDInfo(this._element,`resource_${this.applicationResourceID}`),await this.handleShowNewVersionPopup(),this.initKeyboardManager()}initKeyboardManager(){this._keyboardManager.bind("ctrl + g",x.searchApp.bind(this),{description:"Pesquisar por telas"}).bind("ctrl + d",x.showDesktop.bind(this),{description:"Mostrar o desktop"}).bind("F1",x.openHelp.bind(this),{description:"Abrir ajuda"})}removeShortcuts(){this._keyboardManager.unbind("ctrl + g").unbind("ctrl + d").unbind("F1")}render(){return e("div",null,e("ez-loading-bar",{ref:t=>this._requestListener.loadingBar=t}),e("ez-popup",{opened:!1,ref:t=>this._popUp=t,onEzClosePopup:()=>this.closePopUp()}),e("ez-modal",{opened:!1,ref:t=>this._rightModal=t,"modal-size":"small",closeOutsideClick:!0,closeEsc:!0}))}get _element(){return i(this)}static get watchers(){return{loadByPK:["watchPropHandler"]}}};class H{constructor(){this._debounceTime=1e3,this._ignoredNameTypes=["totals"],this._countRequest=0}onRequestStart(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest++,this.loadingBar.show(),this._timerLoading&&clearTimeout(this._timerLoading))}onRequestEnd(t){this.isIgnoreLoadingOnRequest(t)||(this._countRequest--,this._timerLoading=setTimeout((()=>{this._countRequest<=0&&this.loadingBar.hide()}),this._debounceTime))}isIgnoreLoadingOnRequest(t){if(null==t)return!1;if(t.url.includes("quietMode=true"))return!0;if(null==t.requestBody)return!1;if(1==t.requestBody.length){const{name:s}=t.requestBody[0].variables;if(s){const t=s.split(":");return this._ignoredNameTypes.indexOf(t[0])>=0}}return!1}}class V{constructor(t,s){this.resolve=t,this.reject=s}}K.style=".sc-snk-application-h{display:flex;flex-direction:column;height:100%}";export{K as snk_application}