jsegd-bpm 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,6 +52,40 @@ interface SearchParams {
52
52
  constraintsLikeSearch?: boolean[];
53
53
  }
54
54
 
55
+ /**
56
+ * Mensagem de requisição enviada do WorkerManager para o worker.
57
+ */
58
+ interface WorkerRequest {
59
+ type: 'request';
60
+ /** Identificador único da requisição. */
61
+ requestId: number;
62
+ /** URL completa da requisição HTTP a ser executada. */
63
+ requestUrl: string;
64
+ }
65
+ /**
66
+ * Mensagem de cancelamento enviada do WorkerManager para o worker.
67
+ */
68
+ interface WorkerAbort {
69
+ type: 'abort';
70
+ /** Identificador da requisição a ser cancelada. */
71
+ requestId: number;
72
+ }
73
+ /**
74
+ * Mensagem de resposta enviada pelo worker de volta ao WorkerManager.
75
+ */
76
+ interface WorkerResponse {
77
+ /** Identificador da requisição correspondente. */
78
+ requestId: number;
79
+ /** Indica se a requisição foi concluída com sucesso. */
80
+ success: boolean;
81
+ /** Dados retornados pela API, quando `success` for `true`. */
82
+ data?: unknown;
83
+ /** Mensagem de erro, quando `success` for `false`. */
84
+ error?: string;
85
+ /** `true` quando a requisição foi abortada intencionalmente via `cancel()`. */
86
+ aborted?: boolean;
87
+ }
88
+
55
89
  /**
56
90
  * Promise cancelável retornada por {@link WorkerManager.query}.
57
91
  */
@@ -1042,4 +1076,4 @@ type StoreProxy<T extends StoreMap> = {
1042
1076
  declare function registerStores<T extends StoreMap>(alpine: Pick<Alpine, 'store'>, storeMap: T): StoreProxy<T>;
1043
1077
 
1044
1078
  export { Attach, AttachButton, AttachmentsTable, BeforeSendValidate, BpmFormRepository, ConstraintsType, MockFormRepository, ScreenContext, WorkerManager, WorkflowViewPatcher, defineWorkflowConfig, extractCompletedStages, extractCurrentStage, loadFields, registerStores, resolveWorkflowScreen, sendRequestEvent };
1045
- export type { ActivityKind, ActivityModulePolicy, AttachButtonRegistration, AttachmentRecord, AttachmentSource, AttachmentsTableMode, AttachmentsTableOptions, BpmHistoryEntry, BpmHistoryMap, CacheOptions, CancelablePromise, DatasetError, DatasetResponse, DatasetRow, DragDropEntry, FieldError, IFormRepository, IWorkflowViewHooks, ProcessCompletionLink, ProcessCompletionMessage, ProcessHistory, ResolvedModule, SearchParams, StoreMap, StoreProxy, WorkerManagerOptions, WorkflowActivityDefinition, WorkflowConfig, WorkflowModuleDefinition };
1079
+ export type { ActivityKind, ActivityModulePolicy, AttachButtonRegistration, AttachmentRecord, AttachmentSource, AttachmentsTableMode, AttachmentsTableOptions, BpmHistoryEntry, BpmHistoryMap, CacheOptions, CancelablePromise, DatasetError, DatasetResponse, DatasetRow, DragDropEntry, FieldError, IFormRepository, IWorkflowViewHooks, ProcessCompletionLink, ProcessCompletionMessage, ProcessHistory, ResolvedModule, SearchParams, StoreMap, StoreProxy, WorkerAbort, WorkerManagerOptions, WorkerRequest, WorkerResponse, WorkflowActivityDefinition, WorkflowConfig, WorkflowModuleDefinition };
package/dist/jsegd-bpm.js CHANGED
@@ -1,2 +1,2 @@
1
- function getStringFromWasm0(o,i){return function(o,i){return a+=i,a>=n&&(e=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),e.decode(),a=i),e.decode((null!==t&&0!==t.byteLength||(t=new Uint8Array(s.memory.buffer)),t).subarray(o,o+i))}(o>>>=0,i)}"undefined"==typeof FinalizationRegistry||new FinalizationRegistry(t=>s.__wbg_validate_free(t>>>0,1)),"undefined"==typeof FinalizationRegistry||new FinalizationRegistry(t=>s.__wbg_writtenout_free(t>>>0,1));let t=null;let e=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});e.decode();const n=2146435072;let a=0;const o=new TextEncoder;let s;"encodeInto"in o||(o.encodeInto=function(t,e){const n=o.encode(t);return e.set(n),{read:t.length,written:n.length}});class LocalCache{static instance;dbPromise=null;isInitialized=!1;cacheExpirationMs;storeName;constructor(){}static getInstance(){return LocalCache.instance||(LocalCache.instance=new LocalCache),LocalCache.instance}initialize(t){if(this.isInitialized)throw new Error(`LocalCache already initialized with storeName="${this.storeName}". Create a new instance or reuse the existing one.`);this.cacheExpirationMs=t.cacheExpirationMs,this.storeName=t.storeName,this.isInitialized=!0}ensureInitialized(){if(!this.isInitialized)throw new Error("LocalCache not initialized. Call getInstance().initialize({ storeName, cacheExpirationMs }) first.")}promisifyRequest(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>n(t.error)})}async openDatabase(){if(this.ensureInitialized(),this.dbPromise)return this.dbPromise;const t=`jsegd_cache_${this.storeName}`;return this.dbPromise=new Promise((e,n)=>{const a=indexedDB.open(t,1);a.onupgradeneeded=()=>{const t=a.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName,{keyPath:"key"})},a.onsuccess=()=>e(a.result),a.onerror=()=>{n(a.error)}}),this.dbPromise}async get(t){this.ensureInitialized();try{const e=(await this.openDatabase()).transaction(this.storeName,"readonly").objectStore(this.storeName),n=await this.promisifyRequest(e.get(t));return n?Date.now()-n.timestamp>this.cacheExpirationMs?(await this.remove(t).catch(()=>{}),null):n.data:null}catch(t){return null}}async set(t,e){this.ensureInitialized();try{const n=(await this.openDatabase()).transaction(this.storeName,"readwrite"),a=n.objectStore(this.storeName),o={key:t,timestamp:Date.now(),data:e};await this.promisifyRequest(a.put(o)),await new Promise((t,e)=>{n.oncomplete=()=>t(),n.onerror=()=>e(n.error)})}catch(t){throw t}}async remove(t){this.ensureInitialized();try{const e=(await this.openDatabase()).transaction(this.storeName,"readwrite"),n=e.objectStore(this.storeName);await this.promisifyRequest(n.delete(t)),await new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error)})}catch(t){throw t}}async clear(){this.ensureInitialized();try{const t=(await this.openDatabase()).transaction(this.storeName,"readwrite"),e=t.objectStore(this.storeName);await this.promisifyRequest(e.clear()),await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error)})}catch(t){throw t}}async purgeExpired(){this.ensureInitialized();try{const t=(await this.openDatabase()).transaction(this.storeName,"readwrite"),e=t.objectStore(this.storeName),n=await this.promisifyRequest(e.getAll()),a=Date.now(),o=n.filter(t=>a-t.timestamp>this.cacheExpirationMs);for(const t of o)await this.promisifyRequest(e.delete(t.key));return await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error)}),o.length}catch(t){return 0}}}var i,r,c,d,l;(c=i||(i={}))[c.Second=0]="Second",c[c.Minute=1]="Minute",c[c.Hour=2]="Hour",c[c.Day=3]="Day",c[c.Week=4]="Week",c[c.Month=5]="Month",c[c.Bimonth=6]="Bimonth",c[c.Quarter=7]="Quarter",c[c.Semester=8]="Semester",c[c.Year=9]="Year",function(t){t[t.BRL=0]="BRL",t[t.USD=1]="USD",t[t.EUR=2]="EUR",t[t.JPY=3]="JPY",t[t.GBP=4]="GBP",t[t.CNY=5]="CNY"}(r||(r={})),r.BRL,r.USD,r.EUR,r.JPY,r.GBP,r.CNY,function(t){t[t.DOCUMENT=0]="DOCUMENT",t[t.EMAIL=1]="EMAIL",t[t.MOBILE=2]="MOBILE",t[t.EVP=3]="EVP"}(d||(d={})),await async function(e){if(void 0!==s)return s;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module_or_path:e}=e):console.warn("using deprecated parameters for the initialization function; pass a single object instead")),void 0===e&&(e=new URL("jsegd_bg.wasm",import.meta.url));const n={__proto__:null,"./jsegd_bg.js":{__proto__:null,__wbg_Error_960c155d3d49e4c2:function(t,e){return Error(getStringFromWasm0(t,e))},__wbg___wbindgen_throw_6b64449b9b9ed33c:function(t,e){throw new Error(getStringFromWasm0(t,e))},__wbindgen_cast_0000000000000001:function(t,e){return getStringFromWasm0(t,e)},__wbindgen_init_externref_table:function(){const t=s.__wbindgen_externrefs,e=t.grow(4);t.set(0,void 0),t.set(e+0,void 0),t.set(e+1,null),t.set(e+2,!0),t.set(e+3,!1)}}};("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:a,module:o}=await async function(t,e){if("function"==typeof Response&&t instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(t,e)}catch(e){if(!t.ok||!function(t){switch(t){case"basic":case"cors":case"default":return!0}return!1}(t.type)||"application/wasm"===t.headers.get("Content-Type"))throw e;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}const n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}{const n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}(await e,n);return function(e){return s=e.exports,t=null,s.__wbindgen_start(),s}(a)}();class WorkerManager{pool=[];workerMeta=new Map;taskQueue=[];inFlight=new Map;cache=null;nextRequestId=0;constructor(t={}){const e=t.poolSize??4;if(t.cache)this.cache=t.cache;else if(t.cacheOptions){const e=LocalCache.getInstance();e.initialize(t.cacheOptions),this.cache=e}for(let t=0;t<e;t++){const t=new Worker(new URL("./worker.ts",import.meta.url),{type:"module"});t.onmessage=e=>this.handleResponse(e.data,t),this.workerMeta.set(t,{busy:!1}),this.pool.push(t)}}query(t,e){const n=this.buildUrl(t,e),a=n,o=this.cache?this.cache.get(a).then(t=>t||this.deduplicateOrEnqueue(a,n)):this.deduplicateOrEnqueue(a,n);let canceller=()=>{};return{promise:new Promise((t,e)=>{canceller=()=>this.abortRequest(a,e),o.then(t,e)}),cancel:canceller}}terminate(){for(const t of this.pool)t.terminate();this.pool=[],this.workerMeta.clear(),this.taskQueue=[],this.inFlight.clear()}deduplicateOrEnqueue(t,e){return this.inFlight.has(t)?this.inFlight.get(t).promise:this.enqueueRequest(t,{type:"request",requestId:++this.nextRequestId,requestUrl:e})}enqueueRequest(t,e){let n,a;const o=new Promise((t,e)=>{n=t,a=e}),s={promise:o,resolve:n,reject:a};return this.inFlight.set(t,s),this.taskQueue.push({key:t,payload:e,pending:s}),this.scheduleNext(),o}scheduleNext(){for(const t of this.pool){if(0===this.taskQueue.length)break;const e=this.workerMeta.get(t);if(!e.busy){const n=this.taskQueue.shift();e.busy=!0,e.currentKey=n.key,e.currentRequestId=n.payload.requestId,t.postMessage(n.payload)}}}abortRequest(t,e){e(new Error("Request cancelled"));const n=this.taskQueue.findIndex(e=>e.key===t);if(-1!==n){const[e]=this.taskQueue.splice(n,1);return this.inFlight.delete(t),void e.pending.reject(new Error("Request cancelled"))}for(const[e,n]of this.workerMeta)if(n.currentKey===t){e.postMessage({type:"abort",requestId:n.currentRequestId});break}}handleResponse(t,e){const n=this.workerMeta.get(e),a=n.currentKey;n.busy=!1,delete n.currentKey,delete n.currentRequestId;const o=this.inFlight.get(a);if(this.inFlight.delete(a),o)if(t.aborted)o.reject(new Error("Request cancelled"));else if(t.success){const e=t.data;this.cache&&this.cache.set(a,e).catch(()=>{}),o.resolve(e)}else o.reject(new Error(t.error));this.scheduleNext()}buildUrl(t,e){const n=new URL(`${t}/dataset/api/v2/dataset-handle/search`);return n.searchParams.set("datasetId",e.datasetId),e.field?.forEach(t=>n.searchParams.append("field",t)),void 0!==e.offset&&n.searchParams.set("offset",String(e.offset)),void 0!==e.limit&&n.searchParams.set("limit",String(e.limit)),e.orderby&&n.searchParams.set("orderby",e.orderby),e.constraintsField?.forEach(t=>n.searchParams.append("constraintsField",t)),e.constraintsInitialValue?.forEach(t=>n.searchParams.append("constraintsInitialValue",t)),e.constraintsFinalValue?.forEach(t=>n.searchParams.append("constraintsFinalValue",t)),e.constraintsType?.forEach(t=>n.searchParams.append("constraintsType",t)),e.constraintsLikeSearch?.forEach(t=>n.searchParams.append("constraintsLikeSearch",String(t))),n.toString()}}!function(t){t.MUST="MUST",t.MUST_NOT="MUST_NOT",t.SHOULD="SHOULD"}(l||(l={}));const u="_Z_",h="_jsegd_metadata";function getAttachmentOps(){if(!parent.WKFViewAttachment)throw new Error("WKFViewAttachment não disponível no contexto do processo");const{WKFViewAttachment:t}=parent;return{getAllAttachments:()=>t.getAllAttachments(),openAttachmentView(e,n,a){t.openAttachmentView(e,n,a)},downloadAttach(e){t.downloadAttach(e)},confirmRemoveAttach(e){t.confirmRemoveAttach(e)},editAttach(e,n){t.attachEdit(e,n)},deleteAttachmentSilent(e){t.deleteAttachments([e])}}}function getProcessInfo(){if(!parent.ECM)throw new Error("ECM não disponível no contexto do processo");const{ECM:t}=parent;return{getUserPermissions:()=>t.workflowView.userPermissions??[],getProcessInstanceId:()=>t.workflowView.processDefinition.processInstanceId,getTaskUserId:()=>t.workflowView.processDefinition.taskUserId,getWorkflowSequence:()=>t.workflowView.sequence,getTableData:()=>t.attachmentTable.getData(),getTableRow:e=>t.attachmentTable.getRow(e)}}function getWorkflowContext(){return{...getAttachmentOps(),...getProcessInfo(),...{parentDocument:parent.document,renderTemplate(t,e){const n=parent.Mustache;if(!n)throw new Error("Mustache não disponível no contexto do processo");return n.render(t,e)},removeDragListeners(){const t=parent.$;"function"==typeof t&&(t("#ecm_wkfview").off("drop dragover dragenter"),t("#ecm-workflowView-attachment").off("drop dragover dragenter"))}},...{overrideSuccessRemoveAttachment(t){parent.WKFViewAttachment.successRemoveAttachment=t.bind(parent.WKFViewAttachment)},bindFileUploadHandlers(t){const e=parent.$;if("function"!=typeof e)return;const getECM=()=>parent.ECM;e("#ecm_navigation_fileupload").off("fileuploadadd").on("fileuploadadd",(e,n)=>{const a=getECM();if(a?.WKFViewAttachment?.validateUpload?.())return!1;if(!a?.workflowView?.userPermissions?.includes("P"))return window.dispatchEvent(new CustomEvent("jsegd:upload:error")),FLUIGC.toast({message:"Usuário não possui permissão para publicar anexos",type:"warning"}),!1;const o=[];n.files.filter((t,e,n)=>{n.indexOf(t)!==e&&o.push(e)}),o.sort((t,e)=>e-t).forEach(t=>n.files.splice(t,1));let s=null;return n.files.forEach(t=>{s=a.attachFileMonitor?.add({name:t.name,fullPath:a.WKFViewAttachment?.defFullPath??"BPM",droppedZipZone:!1,hasApprovers:a.WKFViewAttachment?.defHasApprovers??!1});const e=a.newAttachmentsDocs?.some(t=>t.name===s?.name);if(e)return a.attachFileMonitor?.error(s,"Arquivo duplicado. Você tentou enviar um arquivo já anexado com este nome. "),window.dispatchEvent(new CustomEvent("jsegd:upload:error")),!1;const o=a.maxUploadSize??0;if(o>0&&t.size>=1024*o*1024)return a.attachFileMonitor?.error(s,`Tamanho total do arquivo ultrapassou o limite de ${a.core?.formatSize?.(o)??o+" MB"}`),window.dispatchEvent(new CustomEvent("jsegd:upload:error")),!1;if(n){const t=a.WKFViewAttachment?.datasUpload??window.datasUpload;t&&(t[s.id]=n)}n.context=s?.context}),t.onFileAdd(e,n)}).off("fileuploaddone").on("fileuploaddone",(n,a)=>{const o=getECM();a.result?.files?.forEach(s=>{let i={};if(a.context&&(i.id=a.context.data?.("item-id"),i.fullPath=a.context.data?.("item-full-path"),i.droppedZipZone=a.context.data?.("item-dropped-zip-zone")),s.error)window.dispatchEvent(new CustomEvent("jsegd:upload:error")),o?.attachFileMonitor?.error(i,s.error);else if(i){i.name=s.name,i.internalId=Date.now();const r=e?.("#ecm-navigation-inputFile-clone");if("true"===r?.attr?.("data-on-camera")){const t=r.attr("data-file-name-camera");t&&(i.description=t),r.removeAttr("data-on-camera"),r.removeAttr("data-file-name-camera")}i.uploadId=s.uploadId,o?.WKFViewAttachment?.startPublishingDocument?.(null,i),t.onFileDone(n,a,{description:i.description,name:i.name})}})}).off("fileuploadfail").on("fileuploadfail",(e,n)=>{if(n?.context){const t=getECM(),e={id:n.context.data?.("item-id")};t?.attachFileMonitor?.cancel?.(e)}t.onFileFail(e,n)})}}}}function isMetadataAttachment(t){return t.description.startsWith("_jsegd_")}function getAttachmentsByDescription(t){const e=getWorkflowContext();return t===u?e.getAllAttachments().filter(e=>e.description.toLowerCase().includes(t.toLowerCase())):e.getAllAttachments().filter(e=>e.description.replace(/_V\d+$/,"").toLowerCase()===t.toLowerCase())}function filterPublishedAttachments(t){return t.filter(t=>!0!==t.newAttach)}function findAttachmentTableIndex(t){return getWorkflowContext().getTableData().findIndex(t)}function hasPermission(t){return getWorkflowContext().getUserPermissions().indexOf(t)>=0}function isNewProcess(){return 0===getWorkflowContext().getProcessInstanceId()}function isOwnAttachment(t){return t.colleagueId===getWorkflowContext().getTaskUserId()}function canEditAttachment(t){return isOwnAttachment(t)?hasPermission("M"):hasPermission("O")}function sanitizeAttachmentName(t){let e=t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"");return e=e.replace(/\s+/g," ").trim(),e.length>100&&(e=e.substring(0,100)),e=e.normalize("NFD").replace(/[\u0300-\u036f]/g,""),e}function applyNextVersion(t,e){const n=function(t){let e=0;return t.forEach(t=>{const n=t.description.match(/_V(\d+)$/);if(n){const t=parseInt(n[1],10);e=Math.max(e,t)}}),e+1}(e);return t.replace(/_V\d+$/,"")+`_V${n}`}class AttachmentPickerModal{datatable;modal;constructor(t,e){const n=parent.document.getElementById("modalPesquisa");n&&n.remove(),this.modal=this.createModal(),this.datatable=this.createTable(t),this.bindEvents(e)}createTable(t){return parent.FLUIGC.datatable("#targetModal",{dataRequest:t,renderContent:["attachedActivity","attachedUser","description"],header:[{title:"Atividade"},{title:"Solicitante"},{title:"Descrição"}],multiSelect:!1,search:{enabled:!1,onlyEnterkey:!1,searchAreaStyle:"col-12",onSearch:()=>{}},scroll:{enabled:!1},navButtons:{enabled:!1},tableStyle:"table-striped table-hover table-condensed",emptyMessage:"Nenhum dado encontrado",classSelected:"",actions:{enabled:!0,template:"",actionAreaStyle:""},draggable:{enabled:!1,onDrag:()=>{}}})}createModal(){return parent.FLUIGC.modal({title:"Pesquisar",content:'\n <div class="row">\n <div class="col-xs-12 col-sm-12 col-md-12 fs-xs-padding" id="targetModal">\n </div>\n </div>\n ',id:"modalPesquisa",size:"full",actions:[],showHeader:!0,showFooter:!0,headerActions:[],headerContent:"",formModal:!1},()=>{})}bindEvents(t){this.datatable.on("fluig.datatable.onselectrow",e=>{const n=this.datatable.getRow(e.selectedIndex[0],!1);t(n),"function"==typeof this.datatable.destroy&&this.datatable.destroy(),this.modal.remove()})}}class Attach{static instance;static currentUploadSource="button";static currentUploadAccept=null;constructor(){this.interceptUploadEvents(),window.addEventListener("jsegd:attachment:download",({detail:t})=>{Attach.download(t.documentId)})}static getInstance(){return Attach.instance||(Attach.instance=new Attach),Attach.instance}interceptUploadEvents(){const t=getWorkflowContext();t.removeDragListeners(),t.overrideSuccessRemoveAttachment(t=>{window.dispatchEvent(new CustomEvent("jsegd:upload:reset"));const e=Array.isArray(t)&&t.length>1?"Os anexos foram removidos":"O anexo foi removido";FLUIGC.toast({message:e,type:"success"})}),t.bindFileUploadHandlers({onFileAdd:(t,e)=>{},onFileDone:(t,e,n)=>{window.dispatchEvent(new CustomEvent("jsegd:upload:success",{detail:{description:n.description??n.name,source:Attach.currentUploadSource,accept:Attach.currentUploadAccept}}))},onFileFail:(t,e)=>{window.dispatchEvent(new CustomEvent("jsegd:upload:error"))}})}add(t,e){Attach.currentUploadSource=t===u?"toolbar":"button",Attach.currentUploadAccept=e??null;const n=parent.document.getElementById("ecm-navigation-inputFile-clone"),a=getAttachmentsByDescription(t);e&&n.setAttribute("accept",e),t=applyNextVersion(t,a),n.setAttribute("data-on-camera","true"),n.setAttribute("data-file-name-camera",t),n.click()}view(t){if(isNewProcess())return void FLUIGC.toast({title:"Aviso",message:"Não é possível visualizar anexos em um processo não iniciado",type:"warning"});const e=getAttachmentsByDescription(t);if(0===e.length)return void FLUIGC.toast({title:"Erro",message:"Não há documentos em anexo",type:"danger"});const n=filterPublishedAttachments(e);if(0===n.length)return void FLUIGC.toast({title:"Aviso",message:"Não é possível visualizar documentos anexados nesta etapa do processo",type:"warning"});if(!hasPermission("R")&&!n.some(isOwnAttachment))return void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para visualizar anexos",type:"warning"});new AttachmentPickerModal(n,({colleagueId:t,documentId:e,version:n})=>{getWorkflowContext().openAttachmentView(t,e,n)})}remove(t){if(!hasPermission("E")&&!hasPermission("D"))return void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para remover anexos",type:"warning"});const e=getAttachmentsByDescription(t);if(0===e.length)return void FLUIGC.toast({title:"Erro",message:"Não há documentos em anexo",type:"danger"});const n=getWorkflowContext();new AttachmentPickerModal(e,({description:t})=>{const e=findAttachmentTableIndex(e=>e.description===t);n.confirmRemoveAttach([e])})}static download(t){if(isNewProcess())return void FLUIGC.toast({title:"Aviso",message:"Não é possível fazer download de anexos em um processo não iniciado",type:"warning"});const e=findAttachmentTableIndex(e=>e.documentId===String(t));e>=0&&getWorkflowContext().downloadAttach([e])}edit(t){if(isNewProcess())return void FLUIGC.toast({title:"Aviso",message:"Não é possível editar anexos em um processo não iniciado",type:"warning"});const e=filterPublishedAttachments(getAttachmentsByDescription(t)).filter(canEditAttachment);if(0===e.length)return void FLUIGC.toast({title:"Aviso",message:"Nenhum anexo disponível para edição",type:"warning"});const n=getWorkflowContext();new AttachmentPickerModal(e,({description:t})=>{const e=findAttachmentTableIndex(e=>e.description===t);e>=0&&n.editAttach(n.getTableRow(e),e)})}static getAllAttachments(){return getWorkflowContext().getAllAttachments()}static downloadBlob(t,e,n){const a=n?new Blob([t],{type:n}):t,o=URL.createObjectURL(a),s=document.createElement("a");s.href=o,s.download=e,s.click(),URL.revokeObjectURL(o)}static uploadBlob(t,e,n){if(Attach.currentUploadSource="drag-drop",Attach.currentUploadAccept=null,!(t instanceof Blob)||0===t.size)return void FLUIGC.toast({title:"Erro",message:"Blob inválido ou vazio.",type:"danger"});const a=n||t.type;if(!a)return void FLUIGC.toast({title:"Erro",message:"Tipo MIME não especificado.",type:"danger"});if(!parent||!parent.document)return void FLUIGC.toast({title:"Erro",message:"Contexto parent.document não disponível.",type:"danger"});const o=parent.document.getElementById("ecm-navigation-inputFile-clone");if(!o)return void FLUIGC.toast({title:"Erro",message:"Elemento de input de upload não encontrado.",type:"danger"});const s=sanitizeAttachmentName(e),i=new File([t],s,{type:a}),r=new DataTransfer;r.items.add(i),o.files=r.files,o.dispatchEvent(new Event("change"))}}class DragDropNameModal{modal;files;onConfirm;constructor(t,e){this.files=Array.from(t),this.onConfirm=e;const n=this.files.map((t,e)=>`\n <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px">\n <span style="flex:0 0 auto;font-size:12px;color:#555;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${sanitizeAttributeValue(t.name)}">${sanitizeText(t.name)}</span>\n <input\n type="text"\n class="form-control input-sm drag-drop-name-input"\n data-index="${e}"\n value="${sanitizeAttributeValue(sanitizeAttachmentName(t.name))}"\n style="flex:1"\n />\n </div>`).join(""),a={title:"Associar nomes aos arquivos",content:`\n <div id="drag-drop-name-modal-body">\n <div style="margin-bottom:10px">\n <label style="cursor:pointer;font-weight:normal">\n <input type="checkbox" id="drag-drop-use-originals" style="margin-right:6px">\n Usar nomes originais dos arquivos\n </label>\n </div>\n ${n}\n </div>`,id:"drag-drop-name-modal",size:"medium",showHeader:!0,showFooter:!0,headerActions:[],headerContent:"",formModal:!1,actions:[{label:"Cancelar",classType:"btn-default",autoClose:!0},{label:"Confirmar",classType:"btn-primary",bind:"data-drag-drop-confirm"}]};this.modal=FLUIGC.modal(a,()=>{}),this.bindEvents()}bindEvents(){document.addEventListener("change",this.handleUseOriginals),document.querySelector("[data-drag-drop-confirm]")?.addEventListener("click",()=>this.confirm())}handleUseOriginals=t=>{const e=t.target;if("drag-drop-use-originals"!==e.id)return;document.querySelectorAll(".drag-drop-name-input").forEach((t,n)=>{t.disabled=e.checked,e.checked&&(t.value=sanitizeAttachmentName(this.files[n]?.name??""))})};confirm(){const t=document.querySelectorAll(".drag-drop-name-input"),e=this.files.map((e,n)=>({file:e,name:sanitizeAttachmentName((t[n]?.value||e.name).trim())}));document.removeEventListener("change",this.handleUseOriginals),this.modal?.remove?.(),this.onConfirm(e)}}function sanitizeText(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function sanitizeAttributeValue(t){return sanitizeText(t).replace(/"/g,"&quot;")}let m;class AttachmentMetadataFile{static CURRENT_VERSION=1;static exists(){return!!AttachmentMetadataFile.findAttachment()}static findAttachment(){const t=Attach.getAllAttachments().find(t=>t.description===h);return t?.documentId?t:void 0}static async load(t=!1){if(!t&&void 0!==m)return m;const e=AttachmentMetadataFile.findAttachment();if(!e)return m=null,null;const n=`/content-management/api/v2/documents/${e.documentId}/stream`,a=await fetch(n,{credentials:"include"});if(!a.ok)throw new Error(`Falha ao carregar metadados: HTTP ${a.status}`);const o=await a.json();return m=AttachmentMetadataFile.parseAndMigrate(o),m}static save(t){const e={...t,updatedAt:(new Date).toISOString()};m=e;const n=getWorkflowContext();if(!n.getProcessInstanceId())return;const a=AttachmentMetadataFile.findAttachment();a&&n.deleteAttachmentSilent(a);const o=JSON.stringify(e,null,2),s=new Blob([o],{type:"application/json"});Attach.uploadBlob(s,h,"application/json")}static parseAndMigrate(t){if("object"!=typeof t||null===t)return AttachmentMetadataFile.empty();const e=t;return{version:AttachmentMetadataFile.CURRENT_VERSION,buttons:e.buttons??{},attachments:e.attachments??{},updatedAt:e.updatedAt??(new Date).toISOString()}}static empty(){return{version:AttachmentMetadataFile.CURRENT_VERSION,buttons:{},attachments:{},updatedAt:(new Date).toISOString()}}}const p="attachmentsCustom",f="attachmentsToolbar",g='\n <thead>\n <tr>\n <th data-sort="title" data-order="asc" style="cursor:pointer">\n Nome <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th>Documento</th>\n <th>Versão</th>\n <th data-sort="user" data-order="asc" style="cursor:pointer">\n Usuário <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th data-sort="date" data-order="asc" style="cursor:pointer">\n Data <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th data-sort="activity" data-order="asc" style="cursor:pointer">\n Atividade <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th></th>\n </tr>\n </thead>',w=`\n<table class="table table-condensed" id="attachmentsTableCustom">\n <caption>Lista de documentos anexados</caption>\n ${g}\n <tbody>\n {{#attachments}}\n <tr>\n <td>\n {{#iconUrl}}<img src="/webdesk/{{iconPath}}" class="iconAttachDoc" />{{/iconUrl}}\n {{^iconUrl}}<i class="fluigicon fluigicon-md {{iconClass}}"></i>{{/iconUrl}}\n <a href="#"\n data-attachment-open\n data-colleague-id="{{colleagueId}}"\n data-document-id="{{documentId}}"\n data-version="{{version}}"\n class="fs-sm-margin-left">{{description}}</a>\n </td>\n <td>{{documentId}}</td>\n <td><span>{{#version}}{{version}}{{/version}}{{^version}}{{unpublishedVersion}}{{/version}}</span></td>\n <td>{{attachedUser}}</td>\n <td><span>{{#attachedDate}}{{attachedDate}}{{/attachedDate}}{{^attachedDate}}Ainda não publicado{{/attachedDate}}</span></td>\n <td>{{attachedActivity}}</td>\n <td>\n {{#enableDownload}}\n <i class="flaticon flaticon-download icon-sm"\n aria-hidden="true"\n data-attachment-download\n data-document-id="{{documentId}}"\n style="cursor:pointer"></i>\n {{/enableDownload}}\n </td>\n </tr>\n {{/attachments}}\n </tbody>\n</table>`,b=`\n<table class="table table-condensed" id="attachmentsTableCustom">\n <caption>Lista de documentos anexados</caption>\n ${g}\n <tbody>\n {{#attachments}}\n <tr>\n <td>\n {{#iconUrl}}<img src="/webdesk/{{iconPath}}" class="iconAttachDoc" />{{/iconUrl}}\n {{^iconUrl}}<i class="fluigicon fluigicon-md {{iconClass}}"></i>{{/iconUrl}}\n <a href="#"\n data-attachment-open\n data-colleague-id="{{colleagueId}}"\n data-document-id="{{documentId}}"\n data-version="{{version}}"\n class="fs-sm-margin-left">{{description}}</a>\n </td>\n <td>{{documentId}}</td>\n <td><span>{{#version}}{{version}}{{/version}}{{^version}}{{unpublishedVersion}}{{/version}}</span></td>\n <td>{{attachedUser}}</td>\n <td><span>{{#attachedDate}}{{attachedDate}}{{/attachedDate}}{{^attachedDate}}Ainda não publicado{{/attachedDate}}</span></td>\n <td>{{attachedActivity}}</td>\n <td class="attachments-actions" style="white-space:nowrap">\n {{#enableView}}\n <i class="flaticon flaticon-view icon-sm" aria-hidden="true"\n data-attachment-open\n data-colleague-id="{{colleagueId}}"\n data-document-id="{{documentId}}"\n data-version="{{version}}"\n title="Visualizar"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableView}}\n {{#enableReversion}}\n <i class="flaticon flaticon-upload icon-sm" aria-hidden="true"\n data-attachment-reversion\n data-document-id="{{documentId}}"\n data-button-description="{{buttonDescription}}"\n data-button-accept="{{buttonAccept}}"\n title="Nova versão"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableReversion}}\n {{#enableEdit}}\n <i class="flaticon flaticon-pencil icon-sm" aria-hidden="true"\n data-attachment-edit\n data-document-id="{{documentId}}"\n title="Editar conteúdo"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableEdit}}\n {{#enableDownload}}\n <i class="flaticon flaticon-download icon-sm" aria-hidden="true"\n data-attachment-download\n data-document-id="{{documentId}}"\n title="Download"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableDownload}}\n {{#enableDelete}}\n <i class="flaticon flaticon-trash icon-sm" aria-hidden="true"\n data-attachment-delete\n data-document-id="{{documentId}}"\n title="Excluir"\n style="cursor:pointer"></i>\n {{/enableDelete}}\n </td>\n </tr>\n {{/attachments}}\n </tbody>\n</table>`,v=`\n<div id="${f}" style="margin-bottom:8px">\n <div class="btn-group">\n <button type="button" class="btn btn-sm btn-default" data-attach-quick title="Anexar arquivo usando o nome original">\n <i class="flaticon flaticon-add" aria-hidden="true"></i> Novo Anexo\n </button>\n <button type="button" class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n <span class="caret"></span>\n </button>\n <ul class="dropdown-menu" role="menu">\n <li><a href="#" data-attach-quick>Usar nome do arquivo</a></li>\n <li><a href="#" data-attach-named>Informar nome antes de anexar</a></li>\n </ul>\n </div>\n</div>`;class AttachmentsTable{static instance;static options;static attachInstance=null;static buttonRegistry=new Map;constructor(){AttachmentsTable.start()}static getInstance(t){return AttachmentsTable.instance||(AttachmentsTable.options=t,"self-managed"===t.mode&&(AttachmentsTable.attachInstance=Attach.getInstance()),AttachmentsTable.instance=new AttachmentsTable,AttachmentsTable.hydrateFromMetadata()),AttachmentsTable.instance}static registerButton(t){"self-managed"===AttachmentsTable.options?.mode&&(AttachmentsTable.buttonRegistry.set(t.description.toLowerCase(),t),AttachmentsTable.persistMetadata())}static resolveButtonRegistration(t){const e=t.description.replace(/_V\d+$/,"").toLowerCase();return AttachmentsTable.buttonRegistry.get(e)}static start(){const t=getWorkflowContext();t.removeDragListeners();const e=t.parentDocument.getElementById("ecm-workflowView-attachment");e&&(e.style.display="none");const n=t.parentDocument.getElementById("attachments");if(n){if("self-managed"===AttachmentsTable.options?.mode){const e=t.parentDocument.createElement("div");e.innerHTML=v,n.appendChild(e.firstElementChild)}const e=t.parentDocument.createElement("div");e.id=p,n.appendChild(e)}if(AttachmentsTable.render(),t.parentDocument.getElementById(p)?.addEventListener("click",e=>{const n=e.target,a=n.closest("[data-attachment-open]");if(a){e.preventDefault();const n=a.getAttribute("data-colleague-id")??"",o=Number(a.getAttribute("data-document-id")),s=Number(a.getAttribute("data-version"));return void t.openAttachmentView(n,o,s)}const o=n.closest("[data-attachment-download]");if(o){e.preventDefault();const t=Number(o.getAttribute("data-document-id"));return void window.dispatchEvent(new CustomEvent("jsegd:attachment:download",{detail:{documentId:t}}))}const s=n.closest("th[data-sort]");if(s){const t=s.getAttribute("data-sort"),e="asc"===s.getAttribute("data-order");return AttachmentsTable.sortBy(t,e),void s.setAttribute("data-order",e?"desc":"asc")}if("self-managed"!==AttachmentsTable.options?.mode)return;const i=n.closest("[data-attachment-edit]");if(i){e.preventDefault();const t=Number(i.getAttribute("data-document-id")),n=Attach.getAllAttachments().find(e=>e.documentId===t);return void(n&&AttachmentsTable.attachInstance?.edit(n.description))}const r=n.closest("[data-attachment-reversion]");if(r){e.preventDefault();const t=r.getAttribute("data-button-description")??"",n=r.getAttribute("data-button-accept")||null;return void AttachmentsTable.attachInstance?.add(t,n)}const c=n.closest("[data-attachment-delete]");if(c){e.preventDefault();const t=Number(c.getAttribute("data-document-id")),n=Attach.getAllAttachments().find(e=>e.documentId===t);return void(n&&AttachmentsTable.attachInstance?.remove(n.description))}}),"self-managed"===AttachmentsTable.options?.mode){t.parentDocument.getElementById(f)?.addEventListener("click",t=>{const e=t.target;if(e.closest("[data-attach-quick]"))return t.preventDefault(),hasPermission("P")?void AttachmentsTable.attachInstance?.add(u,AttachmentsTable.options.accept??null):void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para publicar anexos",type:"warning"});if(e.closest("[data-attach-named]")){if(t.preventDefault(),!hasPermission("P"))return void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para publicar anexos",type:"warning"});AttachmentsTable.openNameInputModal(AttachmentsTable.options.accept??null)}});const e=t.parentDocument.getElementById(p);e.addEventListener("dragover",t=>{t.preventDefault(),t.stopPropagation(),e.classList.add("drag-over")}),e.addEventListener("dragleave",()=>e.classList.remove("drag-over")),e.addEventListener("drop",t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove("drag-over");const n=t.dataTransfer?.files;n&&0!==n.length&&(hasPermission("P")?new DragDropNameModal(n,t=>{t.forEach(({file:t,name:e})=>{Attach.uploadBlob(t,e,t.type)})}):FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para publicar anexos",type:"warning"}))})}window.addEventListener("jsegd:upload:reset",()=>AttachmentsTable.render()),window.addEventListener("jsegd:upload:success",async t=>{const e=t.detail;if(AttachmentsTable.render(),!e?.source||"self-managed"!==AttachmentsTable.options?.mode)return;if(!AttachmentsTable.attachInstance)return;const n=Attach.getAllAttachments().filter(t=>!isMetadataAttachment(t)),a=n.find(t=>t.description?.replace(/_V\d+$/,"")===e.description?.replace(/_V\d+$/,""));if(!a||!a.documentId)return;const o=await AttachmentMetadataFile.load()??AttachmentMetadataFile.empty(),s={documentId:a.documentId,source:e.source,buttonDescription:"button"===e.source?e.description:void 0,accept:e.accept??null,workflowSequence:getWorkflowContext().getWorkflowSequence(),uploadedAt:(new Date).toISOString()};AttachmentMetadataFile.save({...o,attachments:{...o.attachments,[String(a.documentId)]:s}})})}static render(){const t=getWorkflowContext(),e=t.parentDocument.getElementById(p);if(!e)return;const n="self-managed"===AttachmentsTable.options?.mode,a=n?b:w,o=Attach.getAllAttachments().filter(t=>!isMetadataAttachment(t)).map(t=>{const e=function(t){return{...t,description:t.description.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}}(t);if(!n)return{...e,enableDownload:!isNewProcess()};const a=AttachmentsTable.resolveButtonRegistration(t);return{...e,enableView:!isNewProcess()&&(hasPermission("R")||isOwnAttachment(t)),enableEdit:!t.newAttach&&canEditAttachment(t),enableReversion:!!a&&hasPermission("P"),enableDownload:!isNewProcess(),enableDelete:hasPermission("E")||hasPermission("D"),buttonDescription:a?.description??"",buttonAccept:a?.accept??""}});e.innerHTML=t.renderTemplate(a,{attachments:o,unpublishedVersion:1e3})}static async hydrateFromMetadata(){const t=await AttachmentMetadataFile.load();if(t)for(const[e,n]of Object.entries(t.buttons))AttachmentsTable.buttonRegistry.has(e)||AttachmentsTable.buttonRegistry.set(e,{description:e,accept:n.accept})}static async persistMetadata(){if(!AttachmentsTable.attachInstance)return;const t=await AttachmentMetadataFile.load()??AttachmentMetadataFile.empty(),e={};for(const[t,n]of AttachmentsTable.buttonRegistry.entries())e[t]={accept:n.accept};AttachmentMetadataFile.save({...t,buttons:e})}static openNameInputModal(t){FLUIGC.modal({title:"Nome do anexo",content:'<div style="padding:8px 0"><label for="attach-name-input" style="display:block;margin-bottom:6px">Informe o nome do arquivo:</label><input type="text" id="attach-name-input" class="form-control" placeholder="Ex: Contrato assinado" maxlength="200"></div>',id:"attach-name-modal",size:"small",showHeader:!0,showFooter:!0,headerActions:[],headerContent:"",formModal:!1,actions:[{label:"Cancelar",classType:"btn-default",autoClose:!0},{label:"Anexar",classType:"btn-primary",bind:"data-attach-name-confirm"}]},()=>{}),document.querySelector("[data-attach-name-confirm]")?.addEventListener("click",()=>{const e=document.getElementById("attach-name-input"),n=e?.value?.trim()??"";if(!n)return;const a=sanitizeAttachmentName(n);AttachmentsTable.attachInstance?.add(a,t)})}static getRows(){return Array.from(getWorkflowContext().parentDocument.querySelectorAll(`#${p} table tbody tr`))}static setOrder(t){const e=getWorkflowContext().parentDocument.querySelector(`#${p} table tbody`);e&&t.forEach(t=>e.appendChild(t))}static sortBy(t,e){const n=AttachmentsTable.getRows();n.sort((n,a)=>{const o=AttachmentsTable.getCellValue(n,t),s=AttachmentsTable.getCellValue(a,t);return o&&s?e?o.localeCompare(s):s.localeCompare(o):0}),AttachmentsTable.setOrder(n)}static getCellValue(t,e){switch(e){case"title":return t.querySelector("[data-attachment-open]")?.closest("td")?.textContent?.trim();case"user":return t.querySelector("td:nth-child(4)")?.textContent?.trim();case"date":return t.querySelector("td:nth-child(5)")?.textContent?.trim();case"activity":return t.querySelector("td:nth-child(6)")?.textContent?.trim()}}}class AttachButton extends HTMLElement{description;accept;noaddbutton=null;noviewbutton=null;noeditbutton=null;nodeletebutton=null;handleSuccess=()=>{const t=this.shadowRoot?.querySelector(".dropdown-button");t&&(t.style.color="rgb(255, 255, 255)",t.style.backgroundColor="rgb(26, 184, 63)")};handleError=()=>{const t=this.shadowRoot?.querySelector(".dropdown-button");t&&(t.style.color="rgb(255, 255, 255)",t.style.backgroundColor="rgb(204, 61, 61)")};handleDefault=()=>{const t=this.shadowRoot?.querySelector(".dropdown-button");t&&(t.style.color="rgb(85, 85, 85)",t.style.backgroundColor="rgb(255, 255, 255)")};constructor(){super();const t=this.attachShadow({mode:"open"}),e=document.createElement("style");e.innerHTML=":host {\n display: inline-block;\n position: relative;\n font-family: Arial, sans-serif;\n}\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n.dropdown-button {\n background-color: #fff;\n color: #555;\n padding: 6px 10px;\n font-size: 14px;\n border: 1px solid #ccc;\n cursor: pointer;\n border-radius: 0 5px 5px 0;\n display: flex;\n align-items: center;\n gap: 5px;\n height: 32px;\n}\n\n.dropdown-button:hover {\n color: #555;\n border-color: #adadad;\n background-color: #e6e6e6;\n}\n\n.dropdown-menu {\n display: none;\n position: absolute;\n top: 100%;\n right: 0;\n background-color: #fff;\n box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);\n min-width: 150px;\n list-style: none;\n padding: 0;\n margin: 0;\n border-radius: 0 0 2px 2px;\n}\n\n.dropdown-menu a {\n display: flex;\n gap: 10px;\n padding: 5px;\n box-sizing: border-box;\n width: 100%;\n text-decoration: none;\n color: #333;\n font-size: 14px;\n justify-content: end;\n align-items: center;\n line-height: 1.5rem;\n}\n\n.dropdown-menu a:hover {\n background-color: #f1f1f1;\n color: #1d1b1b;\n}\n\n.dropdown:hover .dropdown-menu {\n display: block;\n z-index: 9999;\n}\n\n.fs-display-none {\n display: none !important;\n}\r\n";const n=document.createElement("template");n.innerHTML='<div class="dropdown">\r\n <button class="dropdown-button">\r\n <svg width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 18.51">\r\n <g>\r\n <path\r\n d="M11.78,1.68H1.68v11.78H0V1.68c0-.46.16-.85.49-1.18s.72-.49,1.18-.49h10.1v1.68ZM14.3,3.35c.47,0,.87.16,1.2.49.33.33.49.73.49,1.2v11.78c0,.46-.16.86-.49,1.18-.33.33-.73.49-1.2.49H5.05c-.46,0-.86-.16-1.18-.49-.33-.33-.49-.72-.49-1.18V5.05c0-.47.16-.87.49-1.2s.72-.49,1.18-.49h9.25ZM14.3,5.05H5.05v11.78h9.25V5.05ZM7.58,6.73c-.24,0-.44.08-.6.25s-.25.36-.25.6c0,.22.08.42.25.58s.37.25.6.25h1.68c.24,0,.44-.08.6-.25s.25-.36.25-.58c0-.24-.08-.44-.25-.6s-.36-.25-.6-.25h-1.68ZM7.58,10.1c-.24,0-.44.08-.6.25s-.25.36-.25.58c0,.24.08.44.25.6s.37.25.6.25h4.2c.24,0,.44-.08.6-.25s.25-.37.25-.6c0-.22-.08-.42-.25-.58s-.36-.25-.6-.25h-4.2ZM7.58,13.45c-.24,0-.44.08-.6.25s-.25.36-.25.6.08.44.25.6.37.25.6.25h4.2c.24,0,.44-.08.6-.25s.25-.37.25-.6-.08-.44-.25-.6-.36-.25-.6-.25h-4.2Z"\r\n />\r\n </g>\r\n </svg>\r\n <svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" viewBox="0 0 16 14">\r\n <polygon points="0,0 8,12 16,0" fill="#282828" stroke="#282828" stroke-width="1" />\r\n </svg>\r\n </button>\r\n <ul class="dropdown-menu">\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="attach">\r\n <span>Anexar</span>\r\n <svg width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\r\n <g>\r\n <path\r\n d="M14.62,9.83c.16-.16.35-.23.57-.23s.41.08.57.23c.16.16.23.35.23.57v3.2c0,.66-.23,1.23-.7,1.7-.47.47-1.03.7-1.7.7H2.4c-.66,0-1.23-.23-1.7-.7-.47-.47-.7-1.03-.7-1.7v-3.2c0-.22.08-.42.23-.57.16-.16.35-.23.57-.23s.41.08.57.23c.16.16.23.35.23.57v3.2c0,.21.08.4.23.55.16.16.34.23.55.23h11.2c.21,0,.4-.08.55-.23.16-.16.23-.34.23-.55v-3.2c0-.22.08-.42.23-.57ZM4.57,5.38c-.16.15-.35.22-.57.22s-.41-.07-.57-.22c-.15-.16-.22-.35-.22-.57s.07-.41.22-.57L7.44.24c.15-.16.34-.24.56-.24s.41.08.56.24l4.01,3.99c.15.16.22.35.22.57s-.07.41-.22.57c-.16.15-.35.22-.57.22s-.41-.07-.57-.22l-2.62-2.64v7.66c0,.22-.08.42-.23.57-.16.16-.35.23-.57.23s-.42-.08-.57-.23c-.16-.16-.23-.35-.23-.57V2.74l-2.62,2.64Z"\r\n />\r\n </g>\r\n </svg>\r\n </a>\r\n </li>\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="view">\r\n <span>Visualizar</span>\r\n <svg width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 12.37">\r\n <g>\r\n <path\r\n d="M8,12.37c-1.25,0-2.37-.3-3.34-.89-.97-.59-1.79-1.25-2.47-1.97s-1.2-1.4-1.56-2.02c-.35-.63-.55-.97-.58-1.04-.03-.1-.05-.2-.05-.31s.02-.2.05-.31c.03-.05.23-.38.58-.99.36-.63.88-1.3,1.56-2.01s1.5-1.37,2.47-1.96c.98-.58,2.09-.87,3.34-.87s2.37.3,3.34.89c.97.58,1.79,1.23,2.47,1.95.68.72,1.2,1.4,1.56,2.02.35.63.55.97.58,1.04.03.1.05.2.05.31s-.02.2-.05.31c-.03.06-.23.39-.58,1.01-.36.61-.88,1.28-1.56,2-.68.72-1.5,1.37-2.47,1.96-.98.59-2.09.89-3.34.89ZM2.17,7.4c.36.53.83,1.07,1.39,1.6.56.53,1.22.99,1.97,1.39.75.4,1.57.6,2.47.6s1.72-.2,2.46-.6c.74-.4,1.39-.86,1.95-1.39.56-.53,1.03-1.06,1.41-1.6.36-.53.63-.94.8-1.23-.15-.27-.41-.68-.78-1.21-.36-.53-.83-1.07-1.39-1.6-.56-.53-1.22-1-1.97-1.4-.75-.4-1.58-.6-2.47-.6s-1.72.2-2.46.6c-.74.4-1.39.86-1.95,1.4-.56.53-1.03,1.07-1.41,1.6-.36.53-.63.94-.8,1.21.15.28.41.69.78,1.23ZM8,8.94c-.74,0-1.37-.27-1.89-.81-.52-.54-.78-1.19-.78-1.95s.26-1.4.78-1.94c.52-.54,1.15-.81,1.89-.81s1.37.27,1.89.81c.52.54.78,1.19.78,1.94s-.26,1.41-.78,1.95c-.52.54-1.15.81-1.89.81ZM7.06,5.21c-.26.27-.39.59-.39.96s.13.71.39.98c.26.27.57.4.94.4s.68-.13.94-.4c.26-.27.39-.59.39-.98s-.13-.7-.39-.96c-.26-.27-.57-.4-.94-.4s-.68.13-.94.4Z"\r\n />\r\n </g>\r\n </svg>\r\n </a>\r\n </li>\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="edit">\r\n <span>Editar</span>\r\n <i class="fluigicon fluigicon-edit" aria-hidden="true"></i>\r\n </a>\r\n </li>\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="remove">\r\n <span>Excluir</span>\r\n <svg\r\n id="Camada_2"\r\n data-name="Camada 2"\r\n width="16"\r\n height="16"\r\n fill="currentColor"\r\n xmlns="http://www.w3.org/2000/svg"\r\n viewBox="0 0 14.22 16"\r\n >\r\n <g>\r\n <path\r\n d="M13.52,2.91c.21,0,.38.07.51.2s.19.31.19.54c0,.21-.06.38-.19.52s-.3.2-.51.2h-.72v9.46c0,.62-.2,1.13-.61,1.55s-.91.62-1.52.62H3.56c-.6,0-1.11-.21-1.52-.62s-.61-.93-.61-1.55V4.37h-.72c-.21,0-.38-.07-.51-.2s-.19-.31-.19-.52c0-.22.06-.4.19-.54s.3-.2.51-.2h2.85v-.72c0-.62.2-1.14.61-1.56s.91-.63,1.52-.63h2.85c.6,0,1.11.21,1.52.63s.61.94.61,1.56v.72h2.85ZM11.37,13.83V4.37H2.85v9.46c0,.21.06.38.19.52s.3.2.51.2h7.11c.21,0,.38-.07.51-.2s.19-.31.19-.52ZM4.98,2.19v.72h4.26v-.72c0-.22-.06-.4-.19-.53s-.3-.19-.51-.19h-2.85c-.21,0-.38.06-.51.19s-.19.31-.19.53ZM6.41,7.28c0-.22-.07-.4-.2-.53s-.31-.19-.52-.19-.38.06-.51.19-.19.31-.19.53v4.37c0,.21.06.38.19.52s.3.2.51.2.38-.07.52-.2.2-.31.2-.52v-4.37ZM9.24,7.28c0-.22-.06-.4-.19-.53s-.3-.19-.51-.19-.38.06-.52.19-.2.31-.2.53v4.37c0,.21.07.38.2.52s.31.2.52.2.38-.07.51-.2.19-.31.19-.52v-4.37Z"\r\n />\r\n </g>\r\n </svg>\r\n </a>\r\n </li>\r\n </ul>\r\n</div>\r\n',t.appendChild(e),t.appendChild(n.content.cloneNode(!0)),this.description="",this.accept=null}static get observedAttributes(){return["description","accept","noaddbutton","noviewbutton","noeditbutton","nodeletebutton"]}attributeChangedCallback(t,e,n){if(this.isConnected){switch(t){case"description":this.description=n||"";break;case"accept":this.accept=n;break;case"noaddbutton":this.noaddbutton=n;break;case"noviewbutton":this.noviewbutton=n;break;case"noeditbutton":this.noeditbutton=n??"true";break;case"nodeletebutton":this.nodeletebutton=n}this.displayButtons()}}disconnectedCallback(){parent.removeEventListener("jsegd:upload:success",this.handleSuccess),parent.removeEventListener("jsegd:upload:error",this.handleError),parent.removeEventListener("jsegd:upload:reset",this.handleDefault)}connectedCallback(){this.noaddbutton=this.getAttribute("noAddButton"),this.noviewbutton=this.getAttribute("noViewButton"),this.noeditbutton=this.getAttribute("noEditButton")??"true",this.nodeletebutton=this.getAttribute("noDeleteButton"),this.displayButtons(),this.accept=this.getAttribute("accept"),this.description=this.getAttribute("description")||"";const t=Attach.getInstance();this.addButton(t),this.viewButton(t),this.editButton(t),this.removeButton(t),parent.addEventListener("jsegd:upload:success",this.handleSuccess),parent.addEventListener("jsegd:upload:error",this.handleError),parent.addEventListener("jsegd:upload:reset",this.handleDefault),AttachmentsTable.registerButton({description:this.description,accept:this.accept??null})}displayButtons(){"true"!==this.noaddbutton&&this.shadowRoot?.querySelector("#attach")?.parentElement?.classList.remove("fs-display-none"),"true"!==this.noviewbutton&&this.shadowRoot?.querySelector("#view")?.parentElement?.classList.remove("fs-display-none"),"true"!==this.noeditbutton&&this.shadowRoot?.querySelector("#edit")?.parentElement?.classList.remove("fs-display-none"),"true"!==this.nodeletebutton&&this.shadowRoot?.querySelector("#remove")?.parentElement?.classList.remove("fs-display-none")}addButton(t){this.shadowRoot?.querySelector("#attach")?.addEventListener("click",e=>{e.preventDefault(),this.description?t.add(this.description,this.accept):this.showModal()})}viewButton(t){this.shadowRoot?.querySelector("#view")?.addEventListener("click",e=>{e.preventDefault(),t.view(this.description?this.description:u)})}editButton(t){this.shadowRoot?.querySelector("#edit")?.addEventListener("click",e=>{e.preventDefault(),t.edit(this.description?this.description:u)})}removeButton(t){this.shadowRoot?.querySelector("#remove")?.addEventListener("click",e=>{e.preventDefault(),t.remove(this.description?this.description:u)})}showModal(){const t=parent.FLUIGC.modal({title:"Informe a descrição do anexo",content:'\n <div class="row" style="height: 200px;">\n <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">\n <div class="form-group">\n <label for="attach_description">Descrição do anexo</label>\n <input type="text" name="attach_description" id="attach_description"\n class="form-control" />\n </div>\n </div>\n </div>\n ',id:"attachModal",showHeader:!0,showFooter:!0,actions:[{label:"Salvar",bind:"data-save-modal"},{label:"Cancelar",bind:"data-cancel-modal"}],headerActions:[],headerContent:"",size:"large",formModal:!1},(e,n)=>{e||(parent.FLUIGC.autocomplete("#attach_description",{source:(t,e)=>{const n=function(){const t=getAttachmentsByDescription(u).map(t=>t.description.replace(/_Z__V\d+$/,"").replace(/_Z_$/,""));return[...new Set(t)]}().filter(e=>e.toLowerCase().includes(t.toLowerCase())).map(t=>({description:t}));e(n)},highlight:!0,displayKey:"description",tagClass:"tag-gray",type:"autocomplete"},()=>{}),parent.document.querySelector("[data-save-modal]")?.addEventListener("click",()=>{const{value:e}=parent.document.querySelector("#attach_description");if(!e)return void FLUIGC.toast({title:"Erro",message:"Informe a descrição do anexo",type:"danger"});const n=`${e.toUpperCase()}_Z_`;t.remove();Attach.getInstance().add(n,this.accept)}),parent.document.querySelector("[data-cancel-modal]")?.addEventListener("click",()=>{t.remove()}))})}}customElements.get("attachment-button")||customElements.define("attachment-button",AttachButton);class BeforeSendValidate{static clearAllErrors(){document.querySelectorAll("[data-group]").forEach(t=>{t.classList.remove("has-error");const e=t.querySelector("[data-helper]");e&&e.classList.add("fs-display-none")})}static throwValidationError(t){if(!t||0===t.length)throw new Error('<div class="alert alert-danger" role="alert">Erro de validação</div>');this.clearAllErrors(),t.forEach(({field:t,errorMessage:e})=>{if(t){const n=t.closest("[data-group]");if(n){n.classList.add("has-error");const t=n.querySelector("[data-helper]");t&&(t.classList.remove("fs-display-none"),t.textContent=e);const clearErrorHandler=()=>{n.classList.remove("has-error"),t&&(t.classList.add("fs-display-none"),t.textContent="")};n.addEventListener("click",clearErrorHandler,{once:!0}),n.addEventListener("focusin",clearErrorHandler,{once:!0})}}});const e=t.filter(({errorMessage:t})=>t&&t.trim()).map(({errorMessage:t})=>t.replace(/</g,"&lt;").replace(/>/g,"&gt;"));if(0===e.length)throw new Error('<div class="alert alert-danger" role="alert">Erro de validação</div>');const n=e.join("<br>");throw new Error(`<div class="alert alert-danger" role="alert">${n}</div>`)}}const y={beforeValidate:[],afterValidate:[],onMoveSuccess:[],onMoveError:[],onCompletionLinkAdd:[]};async function sendRequestEvent(){const enableButtons=()=>{this.enableSendButton(),this.enableActionButtons()};for(const t of y.beforeValidate)try{const e=t();e instanceof Promise&&await e}catch(t){return void enableButtons()}const t=document.getElementById("nextActivity"),e=t?.value||this.selectActivity();if(await this.callFormFunction("beforeSendValidate",[getProcessInfo().getWorkflowSequence(),e])){for(const t of y.afterValidate)try{const e=t();e instanceof Promise&&await e}catch(t){return void enableButtons()}this.disableActionButtons(),this.sendRequest(!1,!1)}else enableButtons()}const A={sendRequestEvent};class WorkflowViewPatcher{static isInitialized=!1;static isInitializing=!1;static originalMethods={};static async init(t=5e3){if(this.isInitialized)return;if(this.isInitializing)throw new Error("[WorkflowViewPatcher] init() já está em progresso");this.isInitializing=!0;const e=Date.now();for(;!parent.ECM_WKFView;){if(Date.now()-e>t)throw this.isInitializing=!1,new Error("[WorkflowViewPatcher] Timeout: ECM_WKFView não disponível no contexto pai");await new Promise(t=>setTimeout(t,100))}this.isInitializing=!1,this.isInitialized=!0}static patch(t){if(!this.isInitialized)throw new Error("[WorkflowViewPatcher] Chame init() antes de aplicar patches");if(!parent.ECM_WKFView)return;const e=A[t];if(!e)throw new Error(`[WorkflowViewPatcher] Override '${t}' não registrado no mapa de substituições`);this.originalMethods[t]||(this.originalMethods[t]=parent.ECM_WKFView[t]),parent.ECM_WKFView[t]=e.bind(parent.ECM_WKFView)}static patchMany(t){if(!this.isInitialized)throw new Error("[WorkflowViewPatcher] Chame init() antes de aplicar patches");t.forEach(t=>this.patch(t))}static patchAll(){if(!this.isInitialized)throw new Error("[WorkflowViewPatcher] Chame init() antes de aplicar patches");parent.ECM_WKFView&&Object.keys(A).forEach(t=>{this.patch(t)})}static restore(){parent.ECM_WKFView&&(Object.entries(this.originalMethods).forEach(([t,e])=>{const n=t;void 0!==e?parent.ECM_WKFView[n]=e:delete parent.ECM_WKFView[n]}),this.originalMethods={},this.isInitialized=!1,this.isInitializing=!1,y.beforeValidate.length=0,y.afterValidate.length=0,y.onMoveSuccess.length=0,y.onMoveError.length=0,y.onCompletionLinkAdd.length=0)}static getHooks(t){return y[t]}static addBeforeValidate(t){y.beforeValidate.push(t)}static addAfterValidate(t){y.afterValidate.push(t)}static addOnMoveSuccess(t){y.onMoveSuccess.push(t)}static addOnMoveError(t){y.onMoveError.push(t)}static addOnCompletionLinkAdd(t){y.onCompletionLinkAdd.push(t)}}function snakeToCamel(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function camelToSnake(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}class BpmFormRepository{load(t){const e=`${t}_`,n={};return document.querySelectorAll(`input[name^="${e}"], select[name^="${e}"], textarea[name^="${e}"]`).forEach(t=>{const a=t.name;if(!a||a.includes("___"))return;const o=snakeToCamel(a.slice(e.length));t instanceof HTMLInputElement&&"checkbox"===t.type?n[o]=t.checked:n[o]=t.value}),n}loadTable(t){const e=document.querySelectorAll(`table[tablename="${t}"] tbody tr:not([style*="display: none"]):not([style*="display:none"])`),n=[];return e.forEach(t=>{const e={};t.querySelectorAll("input, select, textarea").forEach(t=>{if(!t.name)return;const n=t.name.includes("___")?t.name.substring(0,t.name.lastIndexOf("___")):t.name;t instanceof HTMLInputElement&&"checkbox"===t.type?e[n]=t.checked:e[n]=t.value}),n.push(e)}),n}save(t,e){const n=`${t}_`;Object.entries(e).forEach(([t,e])=>{const a=`${n}${camelToSnake(t)}`,o=document.querySelector(`[name="${a}"]`);o&&(o instanceof HTMLInputElement&&"checkbox"===o.type?o.checked=Boolean(e):o.value=String(e??""))})}saveTable(t,e){document.querySelectorAll(`table[tablename="${t}"] tbody tr`).forEach(t=>{"none"!==t.style.display&&t.remove()}),e.forEach(e=>{const n=wdkAddChild(t,!1);Object.entries(e).forEach(([t,e])=>{const a=document.querySelector(`[name="${t}___${n}"]`);a&&(a instanceof HTMLInputElement&&"checkbox"===a.type?a.checked=Boolean(e):a.value=String(e??""))})})}}class MockFormRepository{store=new Map;tables=new Map;load(t){const e=`${t}_`,n={};for(const[t,a]of this.store.entries())if(t.startsWith(e)){n[snakeToCamel(t.slice(e.length))]=a}return n}loadTable(t){return this.tables.get(t)??[]}save(t,e){const n=`${t}_`;Object.entries(e).forEach(([t,e])=>{this.store.set(`${n}${camelToSnake(t)}`,e)})}saveTable(t,e){this.tables.set(t,[...e])}reset(){this.store.clear(),this.tables.clear()}}function loadFields(t){const e={};for(const n of Object.keys(t)){const a=t[n];if(!a)continue;const o=document.querySelector(`[name="${a}"]`);o&&(e[n]=o instanceof HTMLInputElement&&"checkbox"===o.type?o.checked:o.value)}return e}function defineWorkflowConfig(t){return t}function extractCompletedStages(t,e){const n=Object.values(t).filter(t=>null===t.historyType&&1!==t.stateType&&null!==t.movementDate);n.sort((t,e)=>{const n=t.movementDate-e.movementDate;return 0!==n?n:(t.movementHour??"").localeCompare(e.movementHour??"")});const a=new Set,o=[];for(const t of n){const n=e.find(e=>e.sequence===t.stateSequence);n?.stage&&!a.has(n.stage)&&(a.add(n.stage),o.push(n.stage))}return o}function extractCurrentStage(t,e,n){const a=n.find(e=>e.sequence===t);return a?.stage?{stage:a.stage,status:"SYSTEM"===e?"waiting":"current"}:null}class ScreenContext{activity;resolvedModules;history;constructor(t,e,n){this.activity=t,this.resolvedModules=e,this.history=n}isVisible(t){return this.resolvedModules.find(e=>e.moduleId===t)?.isVisible??!1}isEditable(t){return this.resolvedModules.find(e=>e.moduleId===t)?.isEditable??!1}isActive(t){return this.resolvedModules.find(e=>e.moduleId===t)?.isActive??!1}getSequence(){return this.activity.sequence}isAwaitingSystem(){return"system"===this.activity.kind||"waiting"===this.history.currentStage?.status}isInSupport(){return"support"===this.activity.kind}getProgressBarStages(){const t=this.history.completedStages.map(t=>({stage:t,status:"done"})),e=this.history.currentStage;return e&&!this.history.completedStages.includes(e.stage)&&t.push({stage:e.stage,status:e.status}),t}getModules(){return this.resolvedModules}getVisibleModules(){return[...this.resolvedModules].filter(t=>t.isVisible).sort((t,e)=>t.order-e.order)}getNavigationModules(){return this.getVisibleModules().filter(t=>t.showInNavigation)}}function resolveWorkflowScreen(t,e,n){const a=t.activities.find(t=>t.sequence===e);if(!a)throw new Error(`[jsegd-bpm] Sequência ${e} não encontrada na configuração do workflow.`);const o=t.modules.map(t=>{const e=a.modules?.visible.includes(t.moduleId)??!1,n=a.modules?.editable.includes(t.moduleId)??!1,o=a.modules?.active===t.moduleId;return{...t,isVisible:e,isEditable:n,isActive:o}});if(!o.some(t=>t.isActive)){const t=o.find(t=>t.showInNavigation&&t.isVisible);t&&(t.isActive=!0)}return new ScreenContext(a,o,n)}function registerStores(t,e){for(const[n,a]of Object.entries(e))t.store(n,a);return new Proxy(e,{get:(e,n)=>t.store(n)})}export{Attach,AttachButton,AttachmentsTable,BeforeSendValidate,BpmFormRepository,MockFormRepository,ScreenContext,WorkerManager,WorkflowViewPatcher,defineWorkflowConfig,extractCompletedStages,extractCurrentStage,loadFields,registerStores,resolveWorkflowScreen,sendRequestEvent};
1
+ function getStringFromWasm0(o,i){return function(o,i){return a+=i,a>=n&&(e=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),e.decode(),a=i),e.decode((null!==t&&0!==t.byteLength||(t=new Uint8Array(s.memory.buffer)),t).subarray(o,o+i))}(o>>>=0,i)}"undefined"==typeof FinalizationRegistry||new FinalizationRegistry(t=>s.__wbg_validate_free(t>>>0,1)),"undefined"==typeof FinalizationRegistry||new FinalizationRegistry(t=>s.__wbg_writtenout_free(t>>>0,1));let t=null;let e=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});e.decode();const n=2146435072;let a=0;const o=new TextEncoder;let s;"encodeInto"in o||(o.encodeInto=function(t,e){const n=o.encode(t);return e.set(n),{read:t.length,written:n.length}});class LocalCache{static instance;dbPromise=null;isInitialized=!1;cacheExpirationMs;storeName;constructor(){}static getInstance(){return LocalCache.instance||(LocalCache.instance=new LocalCache),LocalCache.instance}initialize(t){if(this.isInitialized)throw new Error(`LocalCache already initialized with storeName="${this.storeName}". Create a new instance or reuse the existing one.`);this.cacheExpirationMs=t.cacheExpirationMs,this.storeName=t.storeName,this.isInitialized=!0}ensureInitialized(){if(!this.isInitialized)throw new Error("LocalCache not initialized. Call getInstance().initialize({ storeName, cacheExpirationMs }) first.")}promisifyRequest(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>n(t.error)})}async openDatabase(){if(this.ensureInitialized(),this.dbPromise)return this.dbPromise;const t=`jsegd_cache_${this.storeName}`;return this.dbPromise=new Promise((e,n)=>{const a=indexedDB.open(t,1);a.onupgradeneeded=()=>{const t=a.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName,{keyPath:"key"})},a.onsuccess=()=>e(a.result),a.onerror=()=>{n(a.error)}}),this.dbPromise}async get(t){this.ensureInitialized();try{const e=(await this.openDatabase()).transaction(this.storeName,"readonly").objectStore(this.storeName),n=await this.promisifyRequest(e.get(t));return n?Date.now()-n.timestamp>this.cacheExpirationMs?(await this.remove(t).catch(()=>{}),null):n.data:null}catch(t){return null}}async set(t,e){this.ensureInitialized();try{const n=(await this.openDatabase()).transaction(this.storeName,"readwrite"),a=n.objectStore(this.storeName),o={key:t,timestamp:Date.now(),data:e};await this.promisifyRequest(a.put(o)),await new Promise((t,e)=>{n.oncomplete=()=>t(),n.onerror=()=>e(n.error)})}catch(t){throw t}}async remove(t){this.ensureInitialized();try{const e=(await this.openDatabase()).transaction(this.storeName,"readwrite"),n=e.objectStore(this.storeName);await this.promisifyRequest(n.delete(t)),await new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error)})}catch(t){throw t}}async clear(){this.ensureInitialized();try{const t=(await this.openDatabase()).transaction(this.storeName,"readwrite"),e=t.objectStore(this.storeName);await this.promisifyRequest(e.clear()),await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error)})}catch(t){throw t}}async purgeExpired(){this.ensureInitialized();try{const t=(await this.openDatabase()).transaction(this.storeName,"readwrite"),e=t.objectStore(this.storeName),n=await this.promisifyRequest(e.getAll()),a=Date.now(),o=n.filter(t=>a-t.timestamp>this.cacheExpirationMs);for(const t of o)await this.promisifyRequest(e.delete(t.key));return await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error)}),o.length}catch(t){return 0}}}var i,r,c,d,l;(c=i||(i={}))[c.Second=0]="Second",c[c.Minute=1]="Minute",c[c.Hour=2]="Hour",c[c.Day=3]="Day",c[c.Week=4]="Week",c[c.Month=5]="Month",c[c.Bimonth=6]="Bimonth",c[c.Quarter=7]="Quarter",c[c.Semester=8]="Semester",c[c.Year=9]="Year",function(t){t[t.BRL=0]="BRL",t[t.USD=1]="USD",t[t.EUR=2]="EUR",t[t.JPY=3]="JPY",t[t.GBP=4]="GBP",t[t.CNY=5]="CNY"}(r||(r={})),r.BRL,r.USD,r.EUR,r.JPY,r.GBP,r.CNY,function(t){t[t.DOCUMENT=0]="DOCUMENT",t[t.EMAIL=1]="EMAIL",t[t.MOBILE=2]="MOBILE",t[t.EVP=3]="EVP"}(d||(d={})),await async function(e){if(void 0!==s)return s;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module_or_path:e}=e):console.warn("using deprecated parameters for the initialization function; pass a single object instead")),void 0===e&&(e=new URL("jsegd_bg.wasm",import.meta.url));const n={__proto__:null,"./jsegd_bg.js":{__proto__:null,__wbg_Error_960c155d3d49e4c2:function(t,e){return Error(getStringFromWasm0(t,e))},__wbg___wbindgen_throw_6b64449b9b9ed33c:function(t,e){throw new Error(getStringFromWasm0(t,e))},__wbindgen_cast_0000000000000001:function(t,e){return getStringFromWasm0(t,e)},__wbindgen_init_externref_table:function(){const t=s.__wbindgen_externrefs,e=t.grow(4);t.set(0,void 0),t.set(e+0,void 0),t.set(e+1,null),t.set(e+2,!0),t.set(e+3,!1)}}};("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:a,module:o}=await async function(t,e){if("function"==typeof Response&&t instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(t,e)}catch(e){if(!t.ok||!function(t){switch(t){case"basic":case"cors":case"default":return!0}return!1}(t.type)||"application/wasm"===t.headers.get("Content-Type"))throw e;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}const n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}{const n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}(await e,n);return function(e){return s=e.exports,t=null,s.__wbindgen_start(),s}(a)}();class WorkerManager{pool=[];workerMeta=new Map;taskQueue=[];inFlight=new Map;cache=null;nextRequestId=0;constructor(t={}){const e=t.poolSize??4;if(t.cache)this.cache=t.cache;else if(t.cacheOptions){const e=LocalCache.getInstance();e.initialize(t.cacheOptions),this.cache=e}for(let t=0;t<e;t++){const t=new Worker(new URL("./worker.js",import.meta.url),{type:"module"});t.onmessage=e=>this.handleResponse(e.data,t),this.workerMeta.set(t,{busy:!1}),this.pool.push(t)}}query(t,e){const n=this.buildUrl(t,e),a=n,o=this.cache?this.cache.get(a).then(t=>t||this.deduplicateOrEnqueue(a,n)):this.deduplicateOrEnqueue(a,n);let canceller=()=>{};return{promise:new Promise((t,e)=>{canceller=()=>this.abortRequest(a,e),o.then(t,e)}),cancel:canceller}}terminate(){for(const t of this.pool)t.terminate();this.pool=[],this.workerMeta.clear(),this.taskQueue=[],this.inFlight.clear()}deduplicateOrEnqueue(t,e){return this.inFlight.has(t)?this.inFlight.get(t).promise:this.enqueueRequest(t,{type:"request",requestId:++this.nextRequestId,requestUrl:e})}enqueueRequest(t,e){let n,a;const o=new Promise((t,e)=>{n=t,a=e}),s={promise:o,resolve:n,reject:a};return this.inFlight.set(t,s),this.taskQueue.push({key:t,payload:e,pending:s}),this.scheduleNext(),o}scheduleNext(){for(const t of this.pool){if(0===this.taskQueue.length)break;const e=this.workerMeta.get(t);if(!e.busy){const n=this.taskQueue.shift();e.busy=!0,e.currentKey=n.key,e.currentRequestId=n.payload.requestId,t.postMessage(n.payload)}}}abortRequest(t,e){e(new Error("Request cancelled"));const n=this.taskQueue.findIndex(e=>e.key===t);if(-1!==n){const[e]=this.taskQueue.splice(n,1);return this.inFlight.delete(t),void e.pending.reject(new Error("Request cancelled"))}for(const[e,n]of this.workerMeta)if(n.currentKey===t){e.postMessage({type:"abort",requestId:n.currentRequestId});break}}handleResponse(t,e){const n=this.workerMeta.get(e),a=n.currentKey;n.busy=!1,delete n.currentKey,delete n.currentRequestId;const o=this.inFlight.get(a);if(this.inFlight.delete(a),o)if(t.aborted)o.reject(new Error("Request cancelled"));else if(t.success){const e=t.data;this.cache&&this.cache.set(a,e).catch(()=>{}),o.resolve(e)}else o.reject(new Error(t.error));this.scheduleNext()}buildUrl(t,e){const n=new URL(`${t}/dataset/api/v2/dataset-handle/search`);return n.searchParams.set("datasetId",e.datasetId),e.field?.forEach(t=>n.searchParams.append("field",t)),void 0!==e.offset&&n.searchParams.set("offset",String(e.offset)),void 0!==e.limit&&n.searchParams.set("limit",String(e.limit)),e.orderby&&n.searchParams.set("orderby",e.orderby),e.constraintsField?.forEach(t=>n.searchParams.append("constraintsField",t)),e.constraintsInitialValue?.forEach(t=>n.searchParams.append("constraintsInitialValue",t)),e.constraintsFinalValue?.forEach(t=>n.searchParams.append("constraintsFinalValue",t)),e.constraintsType?.forEach(t=>n.searchParams.append("constraintsType",t)),e.constraintsLikeSearch?.forEach(t=>n.searchParams.append("constraintsLikeSearch",String(t))),n.toString()}}!function(t){t.MUST="MUST",t.MUST_NOT="MUST_NOT",t.SHOULD="SHOULD"}(l||(l={}));const u="_Z_",h="_jsegd_metadata";function getAttachmentOps(){if(!parent.WKFViewAttachment)throw new Error("WKFViewAttachment não disponível no contexto do processo");const{WKFViewAttachment:t}=parent;return{getAllAttachments:()=>t.getAllAttachments(),openAttachmentView(e,n,a){t.openAttachmentView(e,n,a)},downloadAttach(e){t.downloadAttach(e)},confirmRemoveAttach(e){t.confirmRemoveAttach(e)},editAttach(e,n){t.attachEdit(e,n)},deleteAttachmentSilent(e){t.deleteAttachments([e])}}}function getProcessInfo(){if(!parent.ECM)throw new Error("ECM não disponível no contexto do processo");const{ECM:t}=parent;return{getUserPermissions:()=>t.workflowView.userPermissions??[],getProcessInstanceId:()=>t.workflowView.processDefinition.processInstanceId,getTaskUserId:()=>t.workflowView.processDefinition.taskUserId,getWorkflowSequence:()=>t.workflowView.sequence,getTableData:()=>t.attachmentTable.getData(),getTableRow:e=>t.attachmentTable.getRow(e)}}function getWorkflowContext(){return{...getAttachmentOps(),...getProcessInfo(),...{parentDocument:parent.document,renderTemplate(t,e){const n=parent.Mustache;if(!n)throw new Error("Mustache não disponível no contexto do processo");return n.render(t,e)},removeDragListeners(){const t=parent.$;"function"==typeof t&&(t("#ecm_wkfview").off("drop dragover dragenter"),t("#ecm-workflowView-attachment").off("drop dragover dragenter"))}},...{overrideSuccessRemoveAttachment(t){parent.WKFViewAttachment.successRemoveAttachment=t.bind(parent.WKFViewAttachment)},bindFileUploadHandlers(t){const e=parent.$;if("function"!=typeof e)return;const getECM=()=>parent.ECM;e("#ecm_navigation_fileupload").off("fileuploadadd").on("fileuploadadd",(e,n)=>{const a=getECM();if(a?.WKFViewAttachment?.validateUpload?.())return!1;if(!a?.workflowView?.userPermissions?.includes("P"))return window.dispatchEvent(new CustomEvent("jsegd:upload:error")),FLUIGC.toast({message:"Usuário não possui permissão para publicar anexos",type:"warning"}),!1;const o=[];n.files.filter((t,e,n)=>{n.indexOf(t)!==e&&o.push(e)}),o.sort((t,e)=>e-t).forEach(t=>n.files.splice(t,1));let s=null;return n.files.forEach(t=>{s=a.attachFileMonitor?.add({name:t.name,fullPath:a.WKFViewAttachment?.defFullPath??"BPM",droppedZipZone:!1,hasApprovers:a.WKFViewAttachment?.defHasApprovers??!1});const e=a.newAttachmentsDocs?.some(t=>t.name===s?.name);if(e)return a.attachFileMonitor?.error(s,"Arquivo duplicado. Você tentou enviar um arquivo já anexado com este nome. "),window.dispatchEvent(new CustomEvent("jsegd:upload:error")),!1;const o=a.maxUploadSize??0;if(o>0&&t.size>=1024*o*1024)return a.attachFileMonitor?.error(s,`Tamanho total do arquivo ultrapassou o limite de ${a.core?.formatSize?.(o)??o+" MB"}`),window.dispatchEvent(new CustomEvent("jsegd:upload:error")),!1;if(n){const t=a.WKFViewAttachment?.datasUpload??window.datasUpload;t&&(t[s.id]=n)}n.context=s?.context}),t.onFileAdd(e,n)}).off("fileuploaddone").on("fileuploaddone",(n,a)=>{const o=getECM();a.result?.files?.forEach(s=>{let i={};if(a.context&&(i.id=a.context.data?.("item-id"),i.fullPath=a.context.data?.("item-full-path"),i.droppedZipZone=a.context.data?.("item-dropped-zip-zone")),s.error)window.dispatchEvent(new CustomEvent("jsegd:upload:error")),o?.attachFileMonitor?.error(i,s.error);else if(i){i.name=s.name,i.internalId=Date.now();const r=e?.("#ecm-navigation-inputFile-clone");if("true"===r?.attr?.("data-on-camera")){const t=r.attr("data-file-name-camera");t&&(i.description=t),r.removeAttr("data-on-camera"),r.removeAttr("data-file-name-camera")}i.uploadId=s.uploadId,o?.WKFViewAttachment?.startPublishingDocument?.(null,i),t.onFileDone(n,a,{description:i.description,name:i.name})}})}).off("fileuploadfail").on("fileuploadfail",(e,n)=>{if(n?.context){const t=getECM(),e={id:n.context.data?.("item-id")};t?.attachFileMonitor?.cancel?.(e)}t.onFileFail(e,n)})}}}}function isMetadataAttachment(t){return t.description.startsWith("_jsegd_")}function getAttachmentsByDescription(t){const e=getWorkflowContext();return t===u?e.getAllAttachments().filter(e=>e.description.toLowerCase().includes(t.toLowerCase())):e.getAllAttachments().filter(e=>e.description.replace(/_V\d+$/,"").toLowerCase()===t.toLowerCase())}function filterPublishedAttachments(t){return t.filter(t=>!0!==t.newAttach)}function findAttachmentTableIndex(t){return getWorkflowContext().getTableData().findIndex(t)}function hasPermission(t){return getWorkflowContext().getUserPermissions().indexOf(t)>=0}function isNewProcess(){return 0===getWorkflowContext().getProcessInstanceId()}function isOwnAttachment(t){return t.colleagueId===getWorkflowContext().getTaskUserId()}function canEditAttachment(t){return isOwnAttachment(t)?hasPermission("M"):hasPermission("O")}function sanitizeAttachmentName(t){let e=t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"");return e=e.replace(/\s+/g," ").trim(),e.length>100&&(e=e.substring(0,100)),e=e.normalize("NFD").replace(/[\u0300-\u036f]/g,""),e}function applyNextVersion(t,e){const n=function(t){let e=0;return t.forEach(t=>{const n=t.description.match(/_V(\d+)$/);if(n){const t=parseInt(n[1],10);e=Math.max(e,t)}}),e+1}(e);return t.replace(/_V\d+$/,"")+`_V${n}`}class AttachmentPickerModal{datatable;modal;constructor(t,e){const n=parent.document.getElementById("modalPesquisa");n&&n.remove(),this.modal=this.createModal(),this.datatable=this.createTable(t),this.bindEvents(e)}createTable(t){return parent.FLUIGC.datatable("#targetModal",{dataRequest:t,renderContent:["attachedActivity","attachedUser","description"],header:[{title:"Atividade"},{title:"Solicitante"},{title:"Descrição"}],multiSelect:!1,search:{enabled:!1,onlyEnterkey:!1,searchAreaStyle:"col-12",onSearch:()=>{}},scroll:{enabled:!1},navButtons:{enabled:!1},tableStyle:"table-striped table-hover table-condensed",emptyMessage:"Nenhum dado encontrado",classSelected:"",actions:{enabled:!0,template:"",actionAreaStyle:""},draggable:{enabled:!1,onDrag:()=>{}}})}createModal(){return parent.FLUIGC.modal({title:"Pesquisar",content:'\n <div class="row">\n <div class="col-xs-12 col-sm-12 col-md-12 fs-xs-padding" id="targetModal">\n </div>\n </div>\n ',id:"modalPesquisa",size:"full",actions:[],showHeader:!0,showFooter:!0,headerActions:[],headerContent:"",formModal:!1},()=>{})}bindEvents(t){this.datatable.on("fluig.datatable.onselectrow",e=>{const n=this.datatable.getRow(e.selectedIndex[0],!1);t(n),"function"==typeof this.datatable.destroy&&this.datatable.destroy(),this.modal.remove()})}}class Attach{static instance;static currentUploadSource="button";static currentUploadAccept=null;constructor(){this.interceptUploadEvents(),window.addEventListener("jsegd:attachment:download",({detail:t})=>{Attach.download(t.documentId)})}static getInstance(){return Attach.instance||(Attach.instance=new Attach),Attach.instance}interceptUploadEvents(){const t=getWorkflowContext();t.removeDragListeners(),t.overrideSuccessRemoveAttachment(t=>{window.dispatchEvent(new CustomEvent("jsegd:upload:reset"));const e=Array.isArray(t)&&t.length>1?"Os anexos foram removidos":"O anexo foi removido";FLUIGC.toast({message:e,type:"success"})}),t.bindFileUploadHandlers({onFileAdd:(t,e)=>{},onFileDone:(t,e,n)=>{window.dispatchEvent(new CustomEvent("jsegd:upload:success",{detail:{description:n.description??n.name,source:Attach.currentUploadSource,accept:Attach.currentUploadAccept}}))},onFileFail:(t,e)=>{window.dispatchEvent(new CustomEvent("jsegd:upload:error"))}})}add(t,e){Attach.currentUploadSource=t===u?"toolbar":"button",Attach.currentUploadAccept=e??null;const n=parent.document.getElementById("ecm-navigation-inputFile-clone"),a=getAttachmentsByDescription(t);e&&n.setAttribute("accept",e),t=applyNextVersion(t,a),n.setAttribute("data-on-camera","true"),n.setAttribute("data-file-name-camera",t),n.click()}view(t){if(isNewProcess())return void FLUIGC.toast({title:"Aviso",message:"Não é possível visualizar anexos em um processo não iniciado",type:"warning"});const e=getAttachmentsByDescription(t);if(0===e.length)return void FLUIGC.toast({title:"Erro",message:"Não há documentos em anexo",type:"danger"});const n=filterPublishedAttachments(e);if(0===n.length)return void FLUIGC.toast({title:"Aviso",message:"Não é possível visualizar documentos anexados nesta etapa do processo",type:"warning"});if(!hasPermission("R")&&!n.some(isOwnAttachment))return void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para visualizar anexos",type:"warning"});new AttachmentPickerModal(n,({colleagueId:t,documentId:e,version:n})=>{getWorkflowContext().openAttachmentView(t,e,n)})}remove(t){if(!hasPermission("E")&&!hasPermission("D"))return void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para remover anexos",type:"warning"});const e=getAttachmentsByDescription(t);if(0===e.length)return void FLUIGC.toast({title:"Erro",message:"Não há documentos em anexo",type:"danger"});const n=getWorkflowContext();new AttachmentPickerModal(e,({description:t})=>{const e=findAttachmentTableIndex(e=>e.description===t);n.confirmRemoveAttach([e])})}static download(t){if(isNewProcess())return void FLUIGC.toast({title:"Aviso",message:"Não é possível fazer download de anexos em um processo não iniciado",type:"warning"});const e=findAttachmentTableIndex(e=>e.documentId===String(t));e>=0&&getWorkflowContext().downloadAttach([e])}edit(t){if(isNewProcess())return void FLUIGC.toast({title:"Aviso",message:"Não é possível editar anexos em um processo não iniciado",type:"warning"});const e=filterPublishedAttachments(getAttachmentsByDescription(t)).filter(canEditAttachment);if(0===e.length)return void FLUIGC.toast({title:"Aviso",message:"Nenhum anexo disponível para edição",type:"warning"});const n=getWorkflowContext();new AttachmentPickerModal(e,({description:t})=>{const e=findAttachmentTableIndex(e=>e.description===t);e>=0&&n.editAttach(n.getTableRow(e),e)})}static getAllAttachments(){return getWorkflowContext().getAllAttachments()}static downloadBlob(t,e,n){const a=n?new Blob([t],{type:n}):t,o=URL.createObjectURL(a),s=document.createElement("a");s.href=o,s.download=e,s.click(),URL.revokeObjectURL(o)}static uploadBlob(t,e,n){if(Attach.currentUploadSource="drag-drop",Attach.currentUploadAccept=null,!(t instanceof Blob)||0===t.size)return void FLUIGC.toast({title:"Erro",message:"Blob inválido ou vazio.",type:"danger"});const a=n||t.type;if(!a)return void FLUIGC.toast({title:"Erro",message:"Tipo MIME não especificado.",type:"danger"});if(!parent||!parent.document)return void FLUIGC.toast({title:"Erro",message:"Contexto parent.document não disponível.",type:"danger"});const o=parent.document.getElementById("ecm-navigation-inputFile-clone");if(!o)return void FLUIGC.toast({title:"Erro",message:"Elemento de input de upload não encontrado.",type:"danger"});const s=sanitizeAttachmentName(e),i=new File([t],s,{type:a}),r=new DataTransfer;r.items.add(i),o.files=r.files,o.dispatchEvent(new Event("change"))}}class DragDropNameModal{modal;files;onConfirm;constructor(t,e){this.files=Array.from(t),this.onConfirm=e;const n=this.files.map((t,e)=>`\n <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px">\n <span style="flex:0 0 auto;font-size:12px;color:#555;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${sanitizeAttributeValue(t.name)}">${sanitizeText(t.name)}</span>\n <input\n type="text"\n class="form-control input-sm drag-drop-name-input"\n data-index="${e}"\n value="${sanitizeAttributeValue(sanitizeAttachmentName(t.name))}"\n style="flex:1"\n />\n </div>`).join(""),a={title:"Associar nomes aos arquivos",content:`\n <div id="drag-drop-name-modal-body">\n <div style="margin-bottom:10px">\n <label style="cursor:pointer;font-weight:normal">\n <input type="checkbox" id="drag-drop-use-originals" style="margin-right:6px">\n Usar nomes originais dos arquivos\n </label>\n </div>\n ${n}\n </div>`,id:"drag-drop-name-modal",size:"medium",showHeader:!0,showFooter:!0,headerActions:[],headerContent:"",formModal:!1,actions:[{label:"Cancelar",classType:"btn-default",autoClose:!0},{label:"Confirmar",classType:"btn-primary",bind:"data-drag-drop-confirm"}]};this.modal=FLUIGC.modal(a,()=>{}),this.bindEvents()}bindEvents(){document.addEventListener("change",this.handleUseOriginals),document.querySelector("[data-drag-drop-confirm]")?.addEventListener("click",()=>this.confirm())}handleUseOriginals=t=>{const e=t.target;if("drag-drop-use-originals"!==e.id)return;document.querySelectorAll(".drag-drop-name-input").forEach((t,n)=>{t.disabled=e.checked,e.checked&&(t.value=sanitizeAttachmentName(this.files[n]?.name??""))})};confirm(){const t=document.querySelectorAll(".drag-drop-name-input"),e=this.files.map((e,n)=>({file:e,name:sanitizeAttachmentName((t[n]?.value||e.name).trim())}));document.removeEventListener("change",this.handleUseOriginals),this.modal?.remove?.(),this.onConfirm(e)}}function sanitizeText(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function sanitizeAttributeValue(t){return sanitizeText(t).replace(/"/g,"&quot;")}let m;class AttachmentMetadataFile{static CURRENT_VERSION=1;static exists(){return!!AttachmentMetadataFile.findAttachment()}static findAttachment(){const t=Attach.getAllAttachments().find(t=>t.description===h);return t?.documentId?t:void 0}static async load(t=!1){if(!t&&void 0!==m)return m;const e=AttachmentMetadataFile.findAttachment();if(!e)return m=null,null;const n=`/content-management/api/v2/documents/${e.documentId}/stream`,a=await fetch(n,{credentials:"include"});if(!a.ok)throw new Error(`Falha ao carregar metadados: HTTP ${a.status}`);const o=await a.json();return m=AttachmentMetadataFile.parseAndMigrate(o),m}static save(t){const e={...t,updatedAt:(new Date).toISOString()};m=e;const n=getWorkflowContext();if(!n.getProcessInstanceId())return;const a=AttachmentMetadataFile.findAttachment();a&&n.deleteAttachmentSilent(a);const o=JSON.stringify(e,null,2),s=new Blob([o],{type:"application/json"});Attach.uploadBlob(s,h,"application/json")}static parseAndMigrate(t){if("object"!=typeof t||null===t)return AttachmentMetadataFile.empty();const e=t;return{version:AttachmentMetadataFile.CURRENT_VERSION,buttons:e.buttons??{},attachments:e.attachments??{},updatedAt:e.updatedAt??(new Date).toISOString()}}static empty(){return{version:AttachmentMetadataFile.CURRENT_VERSION,buttons:{},attachments:{},updatedAt:(new Date).toISOString()}}}const p="attachmentsCustom",f="attachmentsToolbar",g='\n <thead>\n <tr>\n <th data-sort="title" data-order="asc" style="cursor:pointer">\n Nome <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th>Documento</th>\n <th>Versão</th>\n <th data-sort="user" data-order="asc" style="cursor:pointer">\n Usuário <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th data-sort="date" data-order="asc" style="cursor:pointer">\n Data <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th data-sort="activity" data-order="asc" style="cursor:pointer">\n Atividade <i class="flaticon flaticon-ordenation icon-xs" aria-hidden="true" style="margin-left:8px"></i>\n </th>\n <th></th>\n </tr>\n </thead>',w=`\n<table class="table table-condensed" id="attachmentsTableCustom">\n <caption>Lista de documentos anexados</caption>\n ${g}\n <tbody>\n {{#attachments}}\n <tr>\n <td>\n {{#iconUrl}}<img src="/webdesk/{{iconPath}}" class="iconAttachDoc" />{{/iconUrl}}\n {{^iconUrl}}<i class="fluigicon fluigicon-md {{iconClass}}"></i>{{/iconUrl}}\n <a href="#"\n data-attachment-open\n data-colleague-id="{{colleagueId}}"\n data-document-id="{{documentId}}"\n data-version="{{version}}"\n class="fs-sm-margin-left">{{description}}</a>\n </td>\n <td>{{documentId}}</td>\n <td><span>{{#version}}{{version}}{{/version}}{{^version}}{{unpublishedVersion}}{{/version}}</span></td>\n <td>{{attachedUser}}</td>\n <td><span>{{#attachedDate}}{{attachedDate}}{{/attachedDate}}{{^attachedDate}}Ainda não publicado{{/attachedDate}}</span></td>\n <td>{{attachedActivity}}</td>\n <td>\n {{#enableDownload}}\n <i class="flaticon flaticon-download icon-sm"\n aria-hidden="true"\n data-attachment-download\n data-document-id="{{documentId}}"\n style="cursor:pointer"></i>\n {{/enableDownload}}\n </td>\n </tr>\n {{/attachments}}\n </tbody>\n</table>`,b=`\n<table class="table table-condensed" id="attachmentsTableCustom">\n <caption>Lista de documentos anexados</caption>\n ${g}\n <tbody>\n {{#attachments}}\n <tr>\n <td>\n {{#iconUrl}}<img src="/webdesk/{{iconPath}}" class="iconAttachDoc" />{{/iconUrl}}\n {{^iconUrl}}<i class="fluigicon fluigicon-md {{iconClass}}"></i>{{/iconUrl}}\n <a href="#"\n data-attachment-open\n data-colleague-id="{{colleagueId}}"\n data-document-id="{{documentId}}"\n data-version="{{version}}"\n class="fs-sm-margin-left">{{description}}</a>\n </td>\n <td>{{documentId}}</td>\n <td><span>{{#version}}{{version}}{{/version}}{{^version}}{{unpublishedVersion}}{{/version}}</span></td>\n <td>{{attachedUser}}</td>\n <td><span>{{#attachedDate}}{{attachedDate}}{{/attachedDate}}{{^attachedDate}}Ainda não publicado{{/attachedDate}}</span></td>\n <td>{{attachedActivity}}</td>\n <td class="attachments-actions" style="white-space:nowrap">\n {{#enableView}}\n <i class="flaticon flaticon-view icon-sm" aria-hidden="true"\n data-attachment-open\n data-colleague-id="{{colleagueId}}"\n data-document-id="{{documentId}}"\n data-version="{{version}}"\n title="Visualizar"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableView}}\n {{#enableReversion}}\n <i class="flaticon flaticon-upload icon-sm" aria-hidden="true"\n data-attachment-reversion\n data-document-id="{{documentId}}"\n data-button-description="{{buttonDescription}}"\n data-button-accept="{{buttonAccept}}"\n title="Nova versão"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableReversion}}\n {{#enableEdit}}\n <i class="flaticon flaticon-pencil icon-sm" aria-hidden="true"\n data-attachment-edit\n data-document-id="{{documentId}}"\n title="Editar conteúdo"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableEdit}}\n {{#enableDownload}}\n <i class="flaticon flaticon-download icon-sm" aria-hidden="true"\n data-attachment-download\n data-document-id="{{documentId}}"\n title="Download"\n style="cursor:pointer;margin-right:4px"></i>\n {{/enableDownload}}\n {{#enableDelete}}\n <i class="flaticon flaticon-trash icon-sm" aria-hidden="true"\n data-attachment-delete\n data-document-id="{{documentId}}"\n title="Excluir"\n style="cursor:pointer"></i>\n {{/enableDelete}}\n </td>\n </tr>\n {{/attachments}}\n </tbody>\n</table>`,v=`\n<div id="${f}" style="margin-bottom:8px">\n <div class="btn-group">\n <button type="button" class="btn btn-sm btn-default" data-attach-quick title="Anexar arquivo usando o nome original">\n <i class="flaticon flaticon-add" aria-hidden="true"></i> Novo Anexo\n </button>\n <button type="button" class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n <span class="caret"></span>\n </button>\n <ul class="dropdown-menu" role="menu">\n <li><a href="#" data-attach-quick>Usar nome do arquivo</a></li>\n <li><a href="#" data-attach-named>Informar nome antes de anexar</a></li>\n </ul>\n </div>\n</div>`;class AttachmentsTable{static instance;static options;static attachInstance=null;static buttonRegistry=new Map;constructor(){AttachmentsTable.start()}static getInstance(t){return AttachmentsTable.instance||(AttachmentsTable.options=t,"self-managed"===t.mode&&(AttachmentsTable.attachInstance=Attach.getInstance()),AttachmentsTable.instance=new AttachmentsTable,AttachmentsTable.hydrateFromMetadata()),AttachmentsTable.instance}static registerButton(t){"self-managed"===AttachmentsTable.options?.mode&&(AttachmentsTable.buttonRegistry.set(t.description.toLowerCase(),t),AttachmentsTable.persistMetadata())}static resolveButtonRegistration(t){const e=t.description.replace(/_V\d+$/,"").toLowerCase();return AttachmentsTable.buttonRegistry.get(e)}static start(){const t=getWorkflowContext();t.removeDragListeners();const e=t.parentDocument.getElementById("ecm-workflowView-attachment");e&&(e.style.display="none");const n=t.parentDocument.getElementById("attachments");if(n){if("self-managed"===AttachmentsTable.options?.mode){const e=t.parentDocument.createElement("div");e.innerHTML=v,n.appendChild(e.firstElementChild)}const e=t.parentDocument.createElement("div");e.id=p,n.appendChild(e)}if(AttachmentsTable.render(),t.parentDocument.getElementById(p)?.addEventListener("click",e=>{const n=e.target,a=n.closest("[data-attachment-open]");if(a){e.preventDefault();const n=a.getAttribute("data-colleague-id")??"",o=Number(a.getAttribute("data-document-id")),s=Number(a.getAttribute("data-version"));return void t.openAttachmentView(n,o,s)}const o=n.closest("[data-attachment-download]");if(o){e.preventDefault();const t=Number(o.getAttribute("data-document-id"));return void window.dispatchEvent(new CustomEvent("jsegd:attachment:download",{detail:{documentId:t}}))}const s=n.closest("th[data-sort]");if(s){const t=s.getAttribute("data-sort"),e="asc"===s.getAttribute("data-order");return AttachmentsTable.sortBy(t,e),void s.setAttribute("data-order",e?"desc":"asc")}if("self-managed"!==AttachmentsTable.options?.mode)return;const i=n.closest("[data-attachment-edit]");if(i){e.preventDefault();const t=Number(i.getAttribute("data-document-id")),n=Attach.getAllAttachments().find(e=>e.documentId===t);return void(n&&AttachmentsTable.attachInstance?.edit(n.description))}const r=n.closest("[data-attachment-reversion]");if(r){e.preventDefault();const t=r.getAttribute("data-button-description")??"",n=r.getAttribute("data-button-accept")||null;return void AttachmentsTable.attachInstance?.add(t,n)}const c=n.closest("[data-attachment-delete]");if(c){e.preventDefault();const t=Number(c.getAttribute("data-document-id")),n=Attach.getAllAttachments().find(e=>e.documentId===t);return void(n&&AttachmentsTable.attachInstance?.remove(n.description))}}),"self-managed"===AttachmentsTable.options?.mode){t.parentDocument.getElementById(f)?.addEventListener("click",t=>{const e=t.target;if(e.closest("[data-attach-quick]"))return t.preventDefault(),hasPermission("P")?void AttachmentsTable.attachInstance?.add(u,AttachmentsTable.options.accept??null):void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para publicar anexos",type:"warning"});if(e.closest("[data-attach-named]")){if(t.preventDefault(),!hasPermission("P"))return void FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para publicar anexos",type:"warning"});AttachmentsTable.openNameInputModal(AttachmentsTable.options.accept??null)}});const e=t.parentDocument.getElementById(p);e.addEventListener("dragover",t=>{t.preventDefault(),t.stopPropagation(),e.classList.add("drag-over")}),e.addEventListener("dragleave",()=>e.classList.remove("drag-over")),e.addEventListener("drop",t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove("drag-over");const n=t.dataTransfer?.files;n&&0!==n.length&&(hasPermission("P")?new DragDropNameModal(n,t=>{t.forEach(({file:t,name:e})=>{Attach.uploadBlob(t,e,t.type)})}):FLUIGC.toast({title:"Aviso",message:"Usuário não possui permissão para publicar anexos",type:"warning"}))})}window.addEventListener("jsegd:upload:reset",()=>AttachmentsTable.render()),window.addEventListener("jsegd:upload:success",async t=>{const e=t.detail;if(AttachmentsTable.render(),!e?.source||"self-managed"!==AttachmentsTable.options?.mode)return;if(!AttachmentsTable.attachInstance)return;const n=Attach.getAllAttachments().filter(t=>!isMetadataAttachment(t)),a=n.find(t=>t.description?.replace(/_V\d+$/,"")===e.description?.replace(/_V\d+$/,""));if(!a||!a.documentId)return;const o=await AttachmentMetadataFile.load()??AttachmentMetadataFile.empty(),s={documentId:a.documentId,source:e.source,buttonDescription:"button"===e.source?e.description:void 0,accept:e.accept??null,workflowSequence:getWorkflowContext().getWorkflowSequence(),uploadedAt:(new Date).toISOString()};AttachmentMetadataFile.save({...o,attachments:{...o.attachments,[String(a.documentId)]:s}})})}static render(){const t=getWorkflowContext(),e=t.parentDocument.getElementById(p);if(!e)return;const n="self-managed"===AttachmentsTable.options?.mode,a=n?b:w,o=Attach.getAllAttachments().filter(t=>!isMetadataAttachment(t)).map(t=>{const e=function(t){return{...t,description:t.description.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}}(t);if(!n)return{...e,enableDownload:!isNewProcess()};const a=AttachmentsTable.resolveButtonRegistration(t);return{...e,enableView:!isNewProcess()&&(hasPermission("R")||isOwnAttachment(t)),enableEdit:!t.newAttach&&canEditAttachment(t),enableReversion:!!a&&hasPermission("P"),enableDownload:!isNewProcess(),enableDelete:hasPermission("E")||hasPermission("D"),buttonDescription:a?.description??"",buttonAccept:a?.accept??""}});e.innerHTML=t.renderTemplate(a,{attachments:o,unpublishedVersion:1e3})}static async hydrateFromMetadata(){const t=await AttachmentMetadataFile.load();if(t)for(const[e,n]of Object.entries(t.buttons))AttachmentsTable.buttonRegistry.has(e)||AttachmentsTable.buttonRegistry.set(e,{description:e,accept:n.accept})}static async persistMetadata(){if(!AttachmentsTable.attachInstance)return;const t=await AttachmentMetadataFile.load()??AttachmentMetadataFile.empty(),e={};for(const[t,n]of AttachmentsTable.buttonRegistry.entries())e[t]={accept:n.accept};AttachmentMetadataFile.save({...t,buttons:e})}static openNameInputModal(t){FLUIGC.modal({title:"Nome do anexo",content:'<div style="padding:8px 0"><label for="attach-name-input" style="display:block;margin-bottom:6px">Informe o nome do arquivo:</label><input type="text" id="attach-name-input" class="form-control" placeholder="Ex: Contrato assinado" maxlength="200"></div>',id:"attach-name-modal",size:"small",showHeader:!0,showFooter:!0,headerActions:[],headerContent:"",formModal:!1,actions:[{label:"Cancelar",classType:"btn-default",autoClose:!0},{label:"Anexar",classType:"btn-primary",bind:"data-attach-name-confirm"}]},()=>{}),document.querySelector("[data-attach-name-confirm]")?.addEventListener("click",()=>{const e=document.getElementById("attach-name-input"),n=e?.value?.trim()??"";if(!n)return;const a=sanitizeAttachmentName(n);AttachmentsTable.attachInstance?.add(a,t)})}static getRows(){return Array.from(getWorkflowContext().parentDocument.querySelectorAll(`#${p} table tbody tr`))}static setOrder(t){const e=getWorkflowContext().parentDocument.querySelector(`#${p} table tbody`);e&&t.forEach(t=>e.appendChild(t))}static sortBy(t,e){const n=AttachmentsTable.getRows();n.sort((n,a)=>{const o=AttachmentsTable.getCellValue(n,t),s=AttachmentsTable.getCellValue(a,t);return o&&s?e?o.localeCompare(s):s.localeCompare(o):0}),AttachmentsTable.setOrder(n)}static getCellValue(t,e){switch(e){case"title":return t.querySelector("[data-attachment-open]")?.closest("td")?.textContent?.trim();case"user":return t.querySelector("td:nth-child(4)")?.textContent?.trim();case"date":return t.querySelector("td:nth-child(5)")?.textContent?.trim();case"activity":return t.querySelector("td:nth-child(6)")?.textContent?.trim()}}}class AttachButton extends HTMLElement{description;accept;noaddbutton=null;noviewbutton=null;noeditbutton=null;nodeletebutton=null;handleSuccess=()=>{const t=this.shadowRoot?.querySelector(".dropdown-button");t&&(t.style.color="rgb(255, 255, 255)",t.style.backgroundColor="rgb(26, 184, 63)")};handleError=()=>{const t=this.shadowRoot?.querySelector(".dropdown-button");t&&(t.style.color="rgb(255, 255, 255)",t.style.backgroundColor="rgb(204, 61, 61)")};handleDefault=()=>{const t=this.shadowRoot?.querySelector(".dropdown-button");t&&(t.style.color="rgb(85, 85, 85)",t.style.backgroundColor="rgb(255, 255, 255)")};constructor(){super();const t=this.attachShadow({mode:"open"}),e=document.createElement("style");e.innerHTML=":host {\n display: inline-block;\n position: relative;\n font-family: Arial, sans-serif;\n}\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n.dropdown-button {\n background-color: #fff;\n color: #555;\n padding: 6px 10px;\n font-size: 14px;\n border: 1px solid #ccc;\n cursor: pointer;\n border-radius: 0 5px 5px 0;\n display: flex;\n align-items: center;\n gap: 5px;\n height: 32px;\n}\n\n.dropdown-button:hover {\n color: #555;\n border-color: #adadad;\n background-color: #e6e6e6;\n}\n\n.dropdown-menu {\n display: none;\n position: absolute;\n top: 100%;\n right: 0;\n background-color: #fff;\n box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);\n min-width: 150px;\n list-style: none;\n padding: 0;\n margin: 0;\n border-radius: 0 0 2px 2px;\n}\n\n.dropdown-menu a {\n display: flex;\n gap: 10px;\n padding: 5px;\n box-sizing: border-box;\n width: 100%;\n text-decoration: none;\n color: #333;\n font-size: 14px;\n justify-content: end;\n align-items: center;\n line-height: 1.5rem;\n}\n\n.dropdown-menu a:hover {\n background-color: #f1f1f1;\n color: #1d1b1b;\n}\n\n.dropdown:hover .dropdown-menu {\n display: block;\n z-index: 9999;\n}\n\n.fs-display-none {\n display: none !important;\n}\r\n";const n=document.createElement("template");n.innerHTML='<div class="dropdown">\r\n <button class="dropdown-button">\r\n <svg width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 18.51">\r\n <g>\r\n <path\r\n d="M11.78,1.68H1.68v11.78H0V1.68c0-.46.16-.85.49-1.18s.72-.49,1.18-.49h10.1v1.68ZM14.3,3.35c.47,0,.87.16,1.2.49.33.33.49.73.49,1.2v11.78c0,.46-.16.86-.49,1.18-.33.33-.73.49-1.2.49H5.05c-.46,0-.86-.16-1.18-.49-.33-.33-.49-.72-.49-1.18V5.05c0-.47.16-.87.49-1.2s.72-.49,1.18-.49h9.25ZM14.3,5.05H5.05v11.78h9.25V5.05ZM7.58,6.73c-.24,0-.44.08-.6.25s-.25.36-.25.6c0,.22.08.42.25.58s.37.25.6.25h1.68c.24,0,.44-.08.6-.25s.25-.36.25-.58c0-.24-.08-.44-.25-.6s-.36-.25-.6-.25h-1.68ZM7.58,10.1c-.24,0-.44.08-.6.25s-.25.36-.25.58c0,.24.08.44.25.6s.37.25.6.25h4.2c.24,0,.44-.08.6-.25s.25-.37.25-.6c0-.22-.08-.42-.25-.58s-.36-.25-.6-.25h-4.2ZM7.58,13.45c-.24,0-.44.08-.6.25s-.25.36-.25.6.08.44.25.6.37.25.6.25h4.2c.24,0,.44-.08.6-.25s.25-.37.25-.6-.08-.44-.25-.6-.36-.25-.6-.25h-4.2Z"\r\n />\r\n </g>\r\n </svg>\r\n <svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" viewBox="0 0 16 14">\r\n <polygon points="0,0 8,12 16,0" fill="#282828" stroke="#282828" stroke-width="1" />\r\n </svg>\r\n </button>\r\n <ul class="dropdown-menu">\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="attach">\r\n <span>Anexar</span>\r\n <svg width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\r\n <g>\r\n <path\r\n d="M14.62,9.83c.16-.16.35-.23.57-.23s.41.08.57.23c.16.16.23.35.23.57v3.2c0,.66-.23,1.23-.7,1.7-.47.47-1.03.7-1.7.7H2.4c-.66,0-1.23-.23-1.7-.7-.47-.47-.7-1.03-.7-1.7v-3.2c0-.22.08-.42.23-.57.16-.16.35-.23.57-.23s.41.08.57.23c.16.16.23.35.23.57v3.2c0,.21.08.4.23.55.16.16.34.23.55.23h11.2c.21,0,.4-.08.55-.23.16-.16.23-.34.23-.55v-3.2c0-.22.08-.42.23-.57ZM4.57,5.38c-.16.15-.35.22-.57.22s-.41-.07-.57-.22c-.15-.16-.22-.35-.22-.57s.07-.41.22-.57L7.44.24c.15-.16.34-.24.56-.24s.41.08.56.24l4.01,3.99c.15.16.22.35.22.57s-.07.41-.22.57c-.16.15-.35.22-.57.22s-.41-.07-.57-.22l-2.62-2.64v7.66c0,.22-.08.42-.23.57-.16.16-.35.23-.57.23s-.42-.08-.57-.23c-.16-.16-.23-.35-.23-.57V2.74l-2.62,2.64Z"\r\n />\r\n </g>\r\n </svg>\r\n </a>\r\n </li>\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="view">\r\n <span>Visualizar</span>\r\n <svg width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 12.37">\r\n <g>\r\n <path\r\n d="M8,12.37c-1.25,0-2.37-.3-3.34-.89-.97-.59-1.79-1.25-2.47-1.97s-1.2-1.4-1.56-2.02c-.35-.63-.55-.97-.58-1.04-.03-.1-.05-.2-.05-.31s.02-.2.05-.31c.03-.05.23-.38.58-.99.36-.63.88-1.3,1.56-2.01s1.5-1.37,2.47-1.96c.98-.58,2.09-.87,3.34-.87s2.37.3,3.34.89c.97.58,1.79,1.23,2.47,1.95.68.72,1.2,1.4,1.56,2.02.35.63.55.97.58,1.04.03.1.05.2.05.31s-.02.2-.05.31c-.03.06-.23.39-.58,1.01-.36.61-.88,1.28-1.56,2-.68.72-1.5,1.37-2.47,1.96-.98.59-2.09.89-3.34.89ZM2.17,7.4c.36.53.83,1.07,1.39,1.6.56.53,1.22.99,1.97,1.39.75.4,1.57.6,2.47.6s1.72-.2,2.46-.6c.74-.4,1.39-.86,1.95-1.39.56-.53,1.03-1.06,1.41-1.6.36-.53.63-.94.8-1.23-.15-.27-.41-.68-.78-1.21-.36-.53-.83-1.07-1.39-1.6-.56-.53-1.22-1-1.97-1.4-.75-.4-1.58-.6-2.47-.6s-1.72.2-2.46.6c-.74.4-1.39.86-1.95,1.4-.56.53-1.03,1.07-1.41,1.6-.36.53-.63.94-.8,1.21.15.28.41.69.78,1.23ZM8,8.94c-.74,0-1.37-.27-1.89-.81-.52-.54-.78-1.19-.78-1.95s.26-1.4.78-1.94c.52-.54,1.15-.81,1.89-.81s1.37.27,1.89.81c.52.54.78,1.19.78,1.94s-.26,1.41-.78,1.95c-.52.54-1.15.81-1.89.81ZM7.06,5.21c-.26.27-.39.59-.39.96s.13.71.39.98c.26.27.57.4.94.4s.68-.13.94-.4c.26-.27.39-.59.39-.98s-.13-.7-.39-.96c-.26-.27-.57-.4-.94-.4s-.68.13-.94.4Z"\r\n />\r\n </g>\r\n </svg>\r\n </a>\r\n </li>\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="edit">\r\n <span>Editar</span>\r\n <i class="fluigicon fluigicon-edit" aria-hidden="true"></i>\r\n </a>\r\n </li>\r\n <li class="fs-display-none">\r\n <a href="#" class="dropdown-item" id="remove">\r\n <span>Excluir</span>\r\n <svg\r\n id="Camada_2"\r\n data-name="Camada 2"\r\n width="16"\r\n height="16"\r\n fill="currentColor"\r\n xmlns="http://www.w3.org/2000/svg"\r\n viewBox="0 0 14.22 16"\r\n >\r\n <g>\r\n <path\r\n d="M13.52,2.91c.21,0,.38.07.51.2s.19.31.19.54c0,.21-.06.38-.19.52s-.3.2-.51.2h-.72v9.46c0,.62-.2,1.13-.61,1.55s-.91.62-1.52.62H3.56c-.6,0-1.11-.21-1.52-.62s-.61-.93-.61-1.55V4.37h-.72c-.21,0-.38-.07-.51-.2s-.19-.31-.19-.52c0-.22.06-.4.19-.54s.3-.2.51-.2h2.85v-.72c0-.62.2-1.14.61-1.56s.91-.63,1.52-.63h2.85c.6,0,1.11.21,1.52.63s.61.94.61,1.56v.72h2.85ZM11.37,13.83V4.37H2.85v9.46c0,.21.06.38.19.52s.3.2.51.2h7.11c.21,0,.38-.07.51-.2s.19-.31.19-.52ZM4.98,2.19v.72h4.26v-.72c0-.22-.06-.4-.19-.53s-.3-.19-.51-.19h-2.85c-.21,0-.38.06-.51.19s-.19.31-.19.53ZM6.41,7.28c0-.22-.07-.4-.2-.53s-.31-.19-.52-.19-.38.06-.51.19-.19.31-.19.53v4.37c0,.21.06.38.19.52s.3.2.51.2.38-.07.52-.2.2-.31.2-.52v-4.37ZM9.24,7.28c0-.22-.06-.4-.19-.53s-.3-.19-.51-.19-.38.06-.52.19-.2.31-.2.53v4.37c0,.21.07.38.2.52s.31.2.52.2.38-.07.51-.2.19-.31.19-.52v-4.37Z"\r\n />\r\n </g>\r\n </svg>\r\n </a>\r\n </li>\r\n </ul>\r\n</div>\r\n',t.appendChild(e),t.appendChild(n.content.cloneNode(!0)),this.description="",this.accept=null}static get observedAttributes(){return["description","accept","noaddbutton","noviewbutton","noeditbutton","nodeletebutton"]}attributeChangedCallback(t,e,n){if(this.isConnected){switch(t){case"description":this.description=n||"";break;case"accept":this.accept=n;break;case"noaddbutton":this.noaddbutton=n;break;case"noviewbutton":this.noviewbutton=n;break;case"noeditbutton":this.noeditbutton=n??"true";break;case"nodeletebutton":this.nodeletebutton=n}this.displayButtons()}}disconnectedCallback(){parent.removeEventListener("jsegd:upload:success",this.handleSuccess),parent.removeEventListener("jsegd:upload:error",this.handleError),parent.removeEventListener("jsegd:upload:reset",this.handleDefault)}connectedCallback(){this.noaddbutton=this.getAttribute("noAddButton"),this.noviewbutton=this.getAttribute("noViewButton"),this.noeditbutton=this.getAttribute("noEditButton")??"true",this.nodeletebutton=this.getAttribute("noDeleteButton"),this.displayButtons(),this.accept=this.getAttribute("accept"),this.description=this.getAttribute("description")||"";const t=Attach.getInstance();this.addButton(t),this.viewButton(t),this.editButton(t),this.removeButton(t),parent.addEventListener("jsegd:upload:success",this.handleSuccess),parent.addEventListener("jsegd:upload:error",this.handleError),parent.addEventListener("jsegd:upload:reset",this.handleDefault),AttachmentsTable.registerButton({description:this.description,accept:this.accept??null})}displayButtons(){"true"!==this.noaddbutton&&this.shadowRoot?.querySelector("#attach")?.parentElement?.classList.remove("fs-display-none"),"true"!==this.noviewbutton&&this.shadowRoot?.querySelector("#view")?.parentElement?.classList.remove("fs-display-none"),"true"!==this.noeditbutton&&this.shadowRoot?.querySelector("#edit")?.parentElement?.classList.remove("fs-display-none"),"true"!==this.nodeletebutton&&this.shadowRoot?.querySelector("#remove")?.parentElement?.classList.remove("fs-display-none")}addButton(t){this.shadowRoot?.querySelector("#attach")?.addEventListener("click",e=>{e.preventDefault(),this.description?t.add(this.description,this.accept):this.showModal()})}viewButton(t){this.shadowRoot?.querySelector("#view")?.addEventListener("click",e=>{e.preventDefault(),t.view(this.description?this.description:u)})}editButton(t){this.shadowRoot?.querySelector("#edit")?.addEventListener("click",e=>{e.preventDefault(),t.edit(this.description?this.description:u)})}removeButton(t){this.shadowRoot?.querySelector("#remove")?.addEventListener("click",e=>{e.preventDefault(),t.remove(this.description?this.description:u)})}showModal(){const t=parent.FLUIGC.modal({title:"Informe a descrição do anexo",content:'\n <div class="row" style="height: 200px;">\n <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">\n <div class="form-group">\n <label for="attach_description">Descrição do anexo</label>\n <input type="text" name="attach_description" id="attach_description"\n class="form-control" />\n </div>\n </div>\n </div>\n ',id:"attachModal",showHeader:!0,showFooter:!0,actions:[{label:"Salvar",bind:"data-save-modal"},{label:"Cancelar",bind:"data-cancel-modal"}],headerActions:[],headerContent:"",size:"large",formModal:!1},(e,n)=>{e||(parent.FLUIGC.autocomplete("#attach_description",{source:(t,e)=>{const n=function(){const t=getAttachmentsByDescription(u).map(t=>t.description.replace(/_Z__V\d+$/,"").replace(/_Z_$/,""));return[...new Set(t)]}().filter(e=>e.toLowerCase().includes(t.toLowerCase())).map(t=>({description:t}));e(n)},highlight:!0,displayKey:"description",tagClass:"tag-gray",type:"autocomplete"},()=>{}),parent.document.querySelector("[data-save-modal]")?.addEventListener("click",()=>{const{value:e}=parent.document.querySelector("#attach_description");if(!e)return void FLUIGC.toast({title:"Erro",message:"Informe a descrição do anexo",type:"danger"});const n=`${e.toUpperCase()}_Z_`;t.remove();Attach.getInstance().add(n,this.accept)}),parent.document.querySelector("[data-cancel-modal]")?.addEventListener("click",()=>{t.remove()}))})}}customElements.get("attachment-button")||customElements.define("attachment-button",AttachButton);class BeforeSendValidate{static clearAllErrors(){document.querySelectorAll("[data-group]").forEach(t=>{t.classList.remove("has-error");const e=t.querySelector("[data-helper]");e&&e.classList.add("fs-display-none")})}static throwValidationError(t){if(!t||0===t.length)throw new Error('<div class="alert alert-danger" role="alert">Erro de validação</div>');this.clearAllErrors(),t.forEach(({field:t,errorMessage:e})=>{if(t){const n=t.closest("[data-group]");if(n){n.classList.add("has-error");const t=n.querySelector("[data-helper]");t&&(t.classList.remove("fs-display-none"),t.textContent=e);const clearErrorHandler=()=>{n.classList.remove("has-error"),t&&(t.classList.add("fs-display-none"),t.textContent="")};n.addEventListener("click",clearErrorHandler,{once:!0}),n.addEventListener("focusin",clearErrorHandler,{once:!0})}}});const e=t.filter(({errorMessage:t})=>t&&t.trim()).map(({errorMessage:t})=>t.replace(/</g,"&lt;").replace(/>/g,"&gt;"));if(0===e.length)throw new Error('<div class="alert alert-danger" role="alert">Erro de validação</div>');const n=e.join("<br>");throw new Error(`<div class="alert alert-danger" role="alert">${n}</div>`)}}const y={beforeValidate:[],afterValidate:[],onMoveSuccess:[],onMoveError:[],onCompletionLinkAdd:[]};async function sendRequestEvent(){const enableButtons=()=>{this.enableSendButton(),this.enableActionButtons()};for(const t of y.beforeValidate)try{const e=t();e instanceof Promise&&await e}catch(t){return void enableButtons()}const t=document.getElementById("nextActivity"),e=t?.value||this.selectActivity();if(await this.callFormFunction("beforeSendValidate",[getProcessInfo().getWorkflowSequence(),e])){for(const t of y.afterValidate)try{const e=t();e instanceof Promise&&await e}catch(t){return void enableButtons()}this.disableActionButtons(),this.sendRequest(!1,!1)}else enableButtons()}const A={sendRequestEvent};class WorkflowViewPatcher{static isInitialized=!1;static isInitializing=!1;static originalMethods={};static async init(t=5e3){if(this.isInitialized)return;if(this.isInitializing)throw new Error("[WorkflowViewPatcher] init() já está em progresso");this.isInitializing=!0;const e=Date.now();for(;!parent.ECM_WKFView;){if(Date.now()-e>t)throw this.isInitializing=!1,new Error("[WorkflowViewPatcher] Timeout: ECM_WKFView não disponível no contexto pai");await new Promise(t=>setTimeout(t,100))}this.isInitializing=!1,this.isInitialized=!0}static patch(t){if(!this.isInitialized)throw new Error("[WorkflowViewPatcher] Chame init() antes de aplicar patches");if(!parent.ECM_WKFView)return;const e=A[t];if(!e)throw new Error(`[WorkflowViewPatcher] Override '${t}' não registrado no mapa de substituições`);this.originalMethods[t]||(this.originalMethods[t]=parent.ECM_WKFView[t]),parent.ECM_WKFView[t]=e.bind(parent.ECM_WKFView)}static patchMany(t){if(!this.isInitialized)throw new Error("[WorkflowViewPatcher] Chame init() antes de aplicar patches");t.forEach(t=>this.patch(t))}static patchAll(){if(!this.isInitialized)throw new Error("[WorkflowViewPatcher] Chame init() antes de aplicar patches");parent.ECM_WKFView&&Object.keys(A).forEach(t=>{this.patch(t)})}static restore(){parent.ECM_WKFView&&(Object.entries(this.originalMethods).forEach(([t,e])=>{const n=t;void 0!==e?parent.ECM_WKFView[n]=e:delete parent.ECM_WKFView[n]}),this.originalMethods={},this.isInitialized=!1,this.isInitializing=!1,y.beforeValidate.length=0,y.afterValidate.length=0,y.onMoveSuccess.length=0,y.onMoveError.length=0,y.onCompletionLinkAdd.length=0)}static getHooks(t){return y[t]}static addBeforeValidate(t){y.beforeValidate.push(t)}static addAfterValidate(t){y.afterValidate.push(t)}static addOnMoveSuccess(t){y.onMoveSuccess.push(t)}static addOnMoveError(t){y.onMoveError.push(t)}static addOnCompletionLinkAdd(t){y.onCompletionLinkAdd.push(t)}}function snakeToCamel(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function camelToSnake(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}class BpmFormRepository{load(t){const e=`${t}_`,n={};return document.querySelectorAll(`input[name^="${e}"], select[name^="${e}"], textarea[name^="${e}"]`).forEach(t=>{const a=t.name;if(!a||a.includes("___"))return;const o=snakeToCamel(a.slice(e.length));t instanceof HTMLInputElement&&"checkbox"===t.type?n[o]=t.checked:n[o]=t.value}),n}loadTable(t){const e=document.querySelectorAll(`table[tablename="${t}"] tbody tr:not([style*="display: none"]):not([style*="display:none"])`),n=[];return e.forEach(t=>{const e={};t.querySelectorAll("input, select, textarea").forEach(t=>{if(!t.name)return;const n=t.name.includes("___")?t.name.substring(0,t.name.lastIndexOf("___")):t.name;t instanceof HTMLInputElement&&"checkbox"===t.type?e[n]=t.checked:e[n]=t.value}),n.push(e)}),n}save(t,e){const n=`${t}_`;Object.entries(e).forEach(([t,e])=>{const a=`${n}${camelToSnake(t)}`,o=document.querySelector(`[name="${a}"]`);o&&(o instanceof HTMLInputElement&&"checkbox"===o.type?o.checked=Boolean(e):o.value=String(e??""))})}saveTable(t,e){document.querySelectorAll(`table[tablename="${t}"] tbody tr`).forEach(t=>{"none"!==t.style.display&&t.remove()}),e.forEach(e=>{const n=wdkAddChild(t,!1);Object.entries(e).forEach(([t,e])=>{const a=document.querySelector(`[name="${t}___${n}"]`);a&&(a instanceof HTMLInputElement&&"checkbox"===a.type?a.checked=Boolean(e):a.value=String(e??""))})})}}class MockFormRepository{store=new Map;tables=new Map;load(t){const e=`${t}_`,n={};for(const[t,a]of this.store.entries())if(t.startsWith(e)){n[snakeToCamel(t.slice(e.length))]=a}return n}loadTable(t){return this.tables.get(t)??[]}save(t,e){const n=`${t}_`;Object.entries(e).forEach(([t,e])=>{this.store.set(`${n}${camelToSnake(t)}`,e)})}saveTable(t,e){this.tables.set(t,[...e])}reset(){this.store.clear(),this.tables.clear()}}function loadFields(t){const e={};for(const n of Object.keys(t)){const a=t[n];if(!a)continue;const o=document.querySelector(`[name="${a}"]`);o&&(e[n]=o instanceof HTMLInputElement&&"checkbox"===o.type?o.checked:o.value)}return e}function defineWorkflowConfig(t){return t}function extractCompletedStages(t,e){const n=Object.values(t).filter(t=>null===t.historyType&&1!==t.stateType&&null!==t.movementDate);n.sort((t,e)=>{const n=t.movementDate-e.movementDate;return 0!==n?n:(t.movementHour??"").localeCompare(e.movementHour??"")});const a=new Set,o=[];for(const t of n){const n=e.find(e=>e.sequence===t.stateSequence);n?.stage&&!a.has(n.stage)&&(a.add(n.stage),o.push(n.stage))}return o}function extractCurrentStage(t,e,n){const a=n.find(e=>e.sequence===t);return a?.stage?{stage:a.stage,status:"SYSTEM"===e?"waiting":"current"}:null}class ScreenContext{activity;resolvedModules;history;constructor(t,e,n){this.activity=t,this.resolvedModules=e,this.history=n}isVisible(t){return this.resolvedModules.find(e=>e.moduleId===t)?.isVisible??!1}isEditable(t){return this.resolvedModules.find(e=>e.moduleId===t)?.isEditable??!1}isActive(t){return this.resolvedModules.find(e=>e.moduleId===t)?.isActive??!1}getSequence(){return this.activity.sequence}isAwaitingSystem(){return"system"===this.activity.kind||"waiting"===this.history.currentStage?.status}isInSupport(){return"support"===this.activity.kind}getProgressBarStages(){const t=this.history.completedStages.map(t=>({stage:t,status:"done"})),e=this.history.currentStage;return e&&!this.history.completedStages.includes(e.stage)&&t.push({stage:e.stage,status:e.status}),t}getModules(){return this.resolvedModules}getVisibleModules(){return[...this.resolvedModules].filter(t=>t.isVisible).sort((t,e)=>t.order-e.order)}getNavigationModules(){return this.getVisibleModules().filter(t=>t.showInNavigation)}}function resolveWorkflowScreen(t,e,n){const a=t.activities.find(t=>t.sequence===e);if(!a)throw new Error(`[jsegd-bpm] Sequência ${e} não encontrada na configuração do workflow.`);const o=t.modules.map(t=>{const e=a.modules?.visible.includes(t.moduleId)??!1,n=a.modules?.editable.includes(t.moduleId)??!1,o=a.modules?.active===t.moduleId;return{...t,isVisible:e,isEditable:n,isActive:o}});if(!o.some(t=>t.isActive)){const t=o.find(t=>t.showInNavigation&&t.isVisible);t&&(t.isActive=!0)}return new ScreenContext(a,o,n)}function registerStores(t,e){for(const[n,a]of Object.entries(e))t.store(n,a);return new Proxy(e,{get:(e,n)=>t.store(n)})}export{Attach,AttachButton,AttachmentsTable,BeforeSendValidate,BpmFormRepository,MockFormRepository,ScreenContext,WorkerManager,WorkflowViewPatcher,defineWorkflowConfig,extractCompletedStages,extractCurrentStage,loadFields,registerStores,resolveWorkflowScreen,sendRequestEvent};
2
2
  //# sourceMappingURL=jsegd-bpm.js.map