forlogic-core 2.3.0 → 2.3.1
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.
- package/.note/memory/patterns/dynamic-supabase-config.md +2 -2
- package/.note/memory/patterns/environment-detection-logic.md +21 -15
- package/README.md +1 -1
- package/dist/action-plans/config/environments.d.ts +18 -3
- package/dist/action-plans/config/index.d.ts +3 -3
- package/dist/action-plans/index.d.ts +1 -1
- package/dist/audit-trail/config/environments.d.ts +18 -3
- package/dist/audit-trail/config/index.d.ts +3 -3
- package/dist/audit-trail/index.d.ts +1 -1
- package/dist/config/environments.d.ts +18 -3
- package/dist/config/index.d.ts +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/leadership/config/environments.d.ts +18 -3
- package/dist/leadership/config/index.d.ts +3 -3
- package/dist/leadership/index.d.ts +1 -1
- package/dist/leadership/index.esm.js +1 -1
- package/dist/leadership/index.js +1 -1
- package/dist/places/config/environments.d.ts +18 -3
- package/dist/places/config/index.d.ts +3 -3
- package/dist/places/index.d.ts +1 -1
- package/dist/places/index.esm.js +1 -1
- package/dist/places/index.js +1 -1
- package/dist/sign/config/environments.d.ts +18 -3
- package/dist/sign/config/index.d.ts +3 -3
- package/dist/sign/index.d.ts +1 -1
- package/dist/sign/index.esm.js +1 -1
- package/dist/sign/index.js +1 -1
- package/dist/vite/index.esm.js +24 -1
- package/dist/vite/index.js +24 -0
- package/docs/WORKSPACE_KNOWLEDGE.md +1 -1
- package/docs/design-system/patterns/core-providers.md +11 -2
- package/docs/design-system/patterns/feature-flags.md +53 -21
- package/package.json +1 -1
|
@@ -1,12 +1,27 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Detecção de ambiente prod/dev.
|
|
3
|
+
*
|
|
4
|
+
* Fonte de verdade ÚNICA: `VITE_APP_ENV` (`"PROD"` | `"DEV"`).
|
|
5
|
+
* - `"DEV"` → API/OAuth/Supabase de dev.
|
|
6
|
+
* - `"PROD"` ou ausente / qualquer outro valor → PROD (failsafe).
|
|
7
|
+
*
|
|
8
|
+
* Não há fallback baseado em env vars Supabase: apps sem Supabase precisam
|
|
9
|
+
* configurar `VITE_APP_ENV="DEV"` explicitamente quando quiserem apontar para dev.
|
|
10
|
+
*
|
|
11
|
+
* **Storage de assets (logos/favicon) é sempre prod** — bucket público fixo.
|
|
12
|
+
*/
|
|
13
|
+
export type AppEnv = 'PROD' | 'DEV';
|
|
2
14
|
export interface EnvironmentConfig {
|
|
3
15
|
storageProjectId: string;
|
|
16
|
+
supabaseProjectId: string;
|
|
17
|
+
supabaseUrl: string;
|
|
18
|
+
supabasePublishableKey: string;
|
|
4
19
|
oauth: {
|
|
5
20
|
authUrl: string;
|
|
6
21
|
clientId: string;
|
|
7
22
|
};
|
|
8
23
|
qualiexApiUrl: string;
|
|
9
24
|
}
|
|
25
|
+
export declare function getAppEnv(): AppEnv;
|
|
10
26
|
export declare function getEnvironmentConfig(): EnvironmentConfig;
|
|
11
|
-
export declare function
|
|
12
|
-
export { PROD_PROJECT_ID };
|
|
27
|
+
export declare function isDevEnv(): boolean;
|
|
@@ -22,13 +22,13 @@ export declare const SEARCH_CONFIG: {
|
|
|
22
22
|
export declare const isLovablePreview: () => boolean;
|
|
23
23
|
/**
|
|
24
24
|
* Determines auth method: true → use dev-tokens edge function, false → use OAuth.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* Requer modo Supabase: em modo dotnet, dev-tokens não existe e devemos sempre
|
|
26
|
+
* cair no OAuth real (loginProd), mesmo em localhost/preview.
|
|
27
27
|
*/
|
|
28
28
|
export declare const shouldUseDevTokens: () => boolean;
|
|
29
29
|
/** @deprecated Use `isLovablePreview()` or `shouldUseDevTokens()` instead */
|
|
30
30
|
export declare const isDevEnvironment: () => boolean;
|
|
31
|
-
export {
|
|
31
|
+
export { isDevEnv, getAppEnv, type AppEnv } from './environments';
|
|
32
32
|
export declare const getQualiexApiUrl: () => string;
|
|
33
33
|
export declare const QUERY_KEYS: {
|
|
34
34
|
readonly crud: (entity: string) => readonly [string];
|
package/dist/sign/index.d.ts
CHANGED
|
@@ -90,7 +90,7 @@ export { loadForlogicFonts } from './utils/load-fonts';
|
|
|
90
90
|
export * from './types';
|
|
91
91
|
export * from './types/sidebar';
|
|
92
92
|
export * from './config';
|
|
93
|
-
export { getEnvironmentConfig,
|
|
93
|
+
export { getEnvironmentConfig, isDevEnv, getAppEnv, type AppEnv } from './config/environments';
|
|
94
94
|
export type { EnvironmentConfig } from './config/environments';
|
|
95
95
|
export { setBackendMode, getBackendMode, isSupabaseBackend } from './config/backend';
|
|
96
96
|
export type { BackendMode } from './config/backend';
|
package/dist/sign/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t}from"react/jsx-runtime";import*as a from"react";import{createContext as n,useContext as r,useState as o,useEffect as s,useCallback as i,useRef as c}from"react";import"@tanstack/react-query";import l from"i18next";import{createClient as d}from"@supabase/supabase-js";import{toast as u}from"sonner";import{Loader2 as m,CheckCircle as g,AlertTriangle as p,Info as h,CheckCircle2 as f,Download as v,RefreshCw as y,Upload as _,ChevronDown as b,ChevronUp as w,Check as x,AlertCircle as k}from"lucide-react";import{useTranslation as N}from"react-i18next";import{cva as S}from"class-variance-authority";import{clsx as T}from"clsx";import{twMerge as I}from"tailwind-merge";import"date-fns";import{Slot as A}from"@radix-ui/react-slot";import*as E from"@radix-ui/react-label";import*as C from"@radix-ui/react-select";class P{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const r=e.split(".");if(3!==r.length)return null;const o=r[1];o.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(o),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const n=new TextDecoder("utf-8").decode(a);return JSON.parse(n)}catch(t){try{const e=this.normalizeBase64Url(o),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(o),t=atob(e);return JSON.parse(t)}catch(n){throw n}}}}catch(r){return null}}static validateTokens(e,t){const a=[],n=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),o=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:n}}let s=!0;if(!o){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),s=!1}const i=Math.floor(Date.now()/1e3);if(o?.exp&&o.exp<i){const e="Access token expirado - pode precisar de refresh";a.push(e),s=!1}if(r.exp&&r.exp<i){const e="ID token expirado - autenticação inválida";return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:s,warnings:a,errors:n}}return{isValid:!0,idTokenValid:!0,accessTokenValid:s,warnings:a,errors:n}}catch(r){const e=`Erro na validação de tokens: ${r}`;return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:n}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}P.LARGE_PAYLOAD_THRESHOLD=1e3;const V="qualiex_access_token",L="qualiex_id_token",R="supabase_token",U="oauth_state",D="oauth_nonce",B="selected_alias",j="manual_logout",O="supabase_project_id",$={setAccessToken:e=>localStorage.setItem(V,e),getAccessToken:()=>localStorage.getItem(V),setIdToken:e=>localStorage.setItem(L,e),getIdToken:()=>localStorage.getItem(L),getSupabaseToken:()=>localStorage.getItem(R),setOAuthState:e=>sessionStorage.setItem(U,e),getOAuthState:()=>sessionStorage.getItem(U),clearOAuthState:()=>sessionStorage.removeItem(U),setOAuthNonce:e=>sessionStorage.setItem(D,e),getOAuthNonce:()=>sessionStorage.getItem(D),clearOAuthNonce:()=>sessionStorage.removeItem(D),setSelectedAlias:e=>localStorage.setItem(B,e),getSelectedAlias:()=>localStorage.getItem(B),clearSelectedAlias:()=>localStorage.removeItem(B),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!$.getAccessToken()||!$.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const t=localStorage.getItem(O);return t&&t!==e?($.clearAll(),localStorage.setItem(O,e),!0):(t||localStorage.setItem(O,e),!1)},setSupabaseToken:e=>{localStorage.setItem(R,e),$._clearValidationCache()},areAllTokensValid:()=>{const e=$.getAccessToken(),t=$.getIdToken();if(!e||!t)return!1;try{const a=P.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=$.getAccessToken(),a=$.getIdToken(),n=$.getSupabaseToken();return t&&$.isTokenExpired(t)&&(localStorage.removeItem(V),e=!0),a&&$.isTokenExpired(a)&&(localStorage.removeItem(L),e=!0),n&&$.isTokenExpired(n)&&(localStorage.removeItem(R),e=!0),e},clearAll:()=>{localStorage.removeItem(V),localStorage.removeItem(L),localStorage.removeItem(R),localStorage.removeItem(B),localStorage.removeItem(j),sessionStorage.removeItem(U),sessionStorage.removeItem(D),$._clearValidationCache()},setManualLogout:()=>localStorage.setItem(j,"true"),isManualLogout:()=>"true"===localStorage.getItem(j),clearManualLogout:()=>localStorage.removeItem(j),isTokenExpired:e=>{try{return P.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{$._validationCache.isValid=!1,$._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=$.getSupabaseToken();if(!e)return!1;if($.isTokenExpired(e))return $._clearValidationCache(),$._handleExpiredToken(),!1;const t=Date.now();return t-$._validationCache.timestamp<$._validationCache.cacheValidityMs?$._validationCache.isValid:($._validationCache.isValid=!0,$._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>$.isSupabaseTokenValid()?$.getSupabaseToken():null,_handleExpiredToken:()=>{$.clearAll()},extractTokenData:()=>{if(!$.isSupabaseTokenValid())return null;const e=$.getSupabaseToken();if(!e)return null;try{const t=P.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,n=t.place_id||null,r=t.place_name||null;let o=t.company_id;if(!o&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const n=t[e];if(n&&"string"==typeof n){const e=n.split(";");if(e.length>7&&e[0]===a){o=e[7];break}}}return{alias:a,companyId:o,placeId:n,placeName:r,payload:t}}catch(t){return $._handleExpiredToken(),null}},getCompanyId:e=>{const t=$.getAccessToken();if(t)try{const a=P.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const n=a[t];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=$.extractTokenData();if(a?.companyId)return a.companyId;const n=$.getIdToken();if(n)try{const t=P.parseJwtPayload(n);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const n=t[a];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const t=[$.getAccessToken(),$.getIdToken()];for(const a of t)if(a)try{const t=P.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const n=t[a];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=$.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=$.getIdToken();if(!e)return[];try{const t=P.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const n=t[e];if(n&&"string"==typeof n){const e=n.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}},q={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},z={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};const J={get oauth(){const e=function(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=import.meta.env.VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return"ccjfvpnndclajkleyqkc"===e?q:z}();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}};import.meta.env.VITE_IS_QUALIEX;const F=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);u.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?l.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?l.t("error_authentication"):t.includes("api")||t.includes("network")?l.t("error_connection"):"Erro"}success(e,t){u.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function M(e){return!!e&&e.startsWith("eyJ")}function W(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE;return e||(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY??"")}let H=!1;class K{constructor(e){this.currentToken=null,this.config=e,function(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE,t=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;H?M(t):e&&M(t)?H=!0:M(t)?H=!0:H=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:this.config.key};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return d(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){if(!K.instance){const e=function(){const e=import.meta.env.VITE_SUPABASE_URL,t=W();return e&&t?{url:e,key:t}:null}();if(!e)throw new Error("[forlogic-core] Supabase não configurado. Defina VITE_SUPABASE_URL e VITE_SUPABASE_PUBLISHABLE_KEY no .env, ou não invoque getSupabaseClient() (use isSupabaseConfigured() para checar antes).");K.instance=new K(e)}return K.instance}getClient(){const e=$.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!P.isTokenExpired(e)}catch(t){return F.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function Y(){return K.getInstance().getClient()}class G{static async generateToken(e,t,a,n=!1){try{if(!n){const e=$.getSupabaseToken();if(e&&$.isSupabaseTokenValid())return e}const r=Y(),{data:o,error:s}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return s&&(s.message?.includes("401")||s.message?.includes("Unauthorized"))?(a?.(),null):o?.access_token?($.setSupabaseToken(o.access_token),o.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}class Q{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const t=$.getAccessToken(),a=$.getSelectedAlias();if(!t||!a)return null;const n=await G.generateToken(t,a,this.onLogoutCallback||void 0,e);return n||null}catch(t){return null}}}Q.regenerationPromise=null,Q.onLogoutCallback=null;var X;const Z={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};X=class{static async initialize(){try{const e=!0;if(e){if($.checkProjectMismatch())return{...Z}}if(!$.hasAllTokens()||!$.areAllTokensValid())return $.clearExpiredTokens(),{...Z};const t=$.getAccessToken(),a=$.getIdToken();$.clearManualLogout();const n=this.extractUserFromIdToken(a,t),r=this.extractCompaniesFromIdToken(a),o=this.extractAliasFromAccessToken(t),s=e?$.extractTokenData():null,i=s?.alias;let c=null;if(i&&r.some(e=>e.alias===i))c=i;else{const e=$.getSelectedAlias(),t=e&&r.some(t=>t.alias===e);c=t?e:o||r[0]?.alias||null}if(e&&(!$.isSupabaseTokenValid()&&c&&await Q.attemptRegeneration(),!$.isSupabaseTokenValid()))return{...Z};let l=null;if(c){const e=$.getCompanyId(c),t=r.find(e=>e.alias===c);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=s?.placeId??null,u=s?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:n,alias:c,companies:r,selectedUnit:l,userId:n?.id||null,userAlias:n?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{...Z}}}static async loginDev(){try{const e=Y(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const n=new URL("/callback",window.location.origin);return n.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=n.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";$.setOAuthState(e);const t=$.generateOAuthNonce();$.setOAuthNonce(t);const a=`${window.location.origin}/callback`,n=new URL(J.oauth.authUrl);n.searchParams.set("client_id",J.oauth.clientId),n.searchParams.set("response_type",J.oauth.responseType),n.searchParams.set("scope",J.oauth.scope),n.searchParams.set("redirect_uri",a),n.searchParams.set("state",e),n.searchParams.set("nonce",t),n.searchParams.set("response_mode","fragment"),window.location.href=n.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),n=a("access_token"),r=a("id_token"),o=a("error");if(o)throw new Error(`Erro OAuth: ${o}`);if(n&&r){const e=$.getAccessToken();e!==n&&$.clearAll()}const s=!0;if($.hasAllTokens()){if(s){$.getValidSupabaseToken()||await Q.attemptRegeneration(!0)}return!0}const i=n,c=r;if(!i||!c)throw new Error("Tokens não encontrados na URL de callback");$.setAccessToken(i),$.setIdToken(c),$.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)$.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(c);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");$.setSelectedAlias(e[0].alias)}if(s){if(!await Q.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return $.clearOAuthState(),$.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){$.setManualLogout(),$.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return P.parseJwtPayload(e)}static extractUserFromIdToken(e,t){const a=this.decodeToken(e);if(!a)return null;const n=t?this.decodeToken(t):null;return{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier,isSysAdmin:"1"===n?.admin}}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const n=t[e].split(";");if(n.length>=4)a.push({id:n.length>7?n[7].trim():"",alias:n[0].trim(),name:n[3].trim()});else{const[n,r]=t[e].split("|");n&&r&&a.push({id:"",alias:n.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}},Q.setLogoutCallback(()=>{X.logout()});const ee=n(void 0),te=()=>{const e=r(ee);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function ae(){const{alias:e}=te(),[t,a]=o(null),[n,r]=o(!0);s(()=>{if(!e)return void r(!1);let t=!1;return(async()=>{r(!0);try{const n=Y(),{data:r,error:o}=await n.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||a(r)}catch(n){t||a(null)}finally{t||r(!1)}})(),()=>{t=!0}},[e]);return{config:t,isLoading:n,saveConfig:i(async(t,n)=>{if(!e)throw new Error("Alias not available");const r=Y(),{data:o,error:s}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:n,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(s)throw s;return a(o),o},[e])}}const ne=import.meta.env.VITE_SUPABASE_URL,re=W();async function oe(e,t,a){const n=$.getSupabaseToken(),r={"Content-Type":"application/json",apikey:re};n&&(r.Authorization=`Bearer ${n}`);const o=await fetch(`${ne}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:t,data:a})});if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${o.status}`)}return o}const se={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await oe(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await oe(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let ie=null;function ce(){return window.Clicksign?Promise.resolve():ie||(ie=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),ie)}const le="clicksign-container";function de({signerId:a,environment:n="sandbox",onSign:r,onError:i,onClose:l}){const{t:d}=N(),u=c(null),[g,p]=o(!0),[h,f]=o(null);return s(()=>{let e=!1;return u.current&&(u.current.unmount(),u.current=null),f(null),p(!0),ce().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===n?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(le),t.on("loaded",function(){p(!1)}),t.on("signed",function(){r?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(le);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){p(!1),i?.(e instanceof Error?e:new Error(d("sign_widget_error")))}),t.on("closed",function(){l?.()}),u.current=t}).catch(t=>{e||(f("Falha ao carregar o script de assinatura."),p(!1),i?.(t))}),()=>{e=!0,u.current&&(u.current.unmount(),u.current=null)}},[a,n]),e("div",{className:"relative h-full",children:[g&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t(m,{className:"h-5 w-5 animate-spin"}),t("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:t("p",{className:"text-sm text-destructive",children:h})}),t("div",{id:le,style:{height:"600px"}})]})}function ue(...e){return I(T(e))}const me=S("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ge={info:h,warning:h,danger:p,success:g},pe=a.forwardRef(({className:a,variant:n="info",showIcon:r=!0,children:o,...s},i)=>{const c=ge[n||"info"];return e("div",{ref:i,role:"alert",className:ue(me({variant:n}),a),...s,children:[r&&t(c,{className:"h-4 w-4"}),o]})});pe.displayName="Alert";const he=a.forwardRef(({className:e,...a},n)=>t("h5",{ref:n,className:ue("mb-1 font-medium leading-none tracking-tight",e),...a}));he.displayName="AlertTitle";const fe=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("text-sm [&_p]:leading-relaxed",e),...a}));fe.displayName="AlertDescription";function ve({documentKey:a,signerEmail:n,signerName:r,keySigner:d,environment:u,onSign:g,onError:p}){const h=c(null),[f,v]=o("loading"),[y,_]=o(null),b="production"===u?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:n,display_name:r||"",disable_preview:"0"});return d&&e.set("key_signer",d),`${b}/${a}?${e.toString()}`})(),x=i(e=>"signed"===e.data?(v("ready"),void g?.()):"wrong-data"===e.data?(v("error"),_(l.t("sign_incorrect_data")),void p?.(new Error(l.t("sign_incorrect_data")))):void 0,[g,p]);s(()=>(window.addEventListener("message",x,!1),()=>{window.removeEventListener("message",x,!1)}),[x]);const k=i(()=>{"loading"===f&&v("ready")},[f]);return"error"===f?e(pe,{variant:"danger",className:"my-4",children:[t(he,{children:l.t("sign_doc_load_error")}),t(fe,{children:y||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e("div",{className:"relative h-full",children:["loading"===f&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t(m,{className:"h-5 w-5 animate-spin"}),t("span",{className:"text-sm",children:"Carregando documento..."})]})}),t("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:k})]})}const ye=S("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),_e=a.forwardRef(({className:e,variant:a,size:n,asChild:r=!1,...o},s)=>t(r?A:"button",{className:ue(ye({variant:a,size:n,className:e})),ref:s,...o}));_e.displayName="Button";const be=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("rounded-lg border bg-card text-card-foreground shadow-sm",e),...a}));be.displayName="Card";const we=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("flex flex-col space-y-1.5 p-6",e),...a}));we.displayName="CardHeader";const xe=a.forwardRef(({className:e,...a},n)=>t("h3",{ref:n,className:ue("text-2xl font-semibold leading-none tracking-tight",e),...a}));xe.displayName="CardTitle";a.forwardRef(({className:e,...a},n)=>t("p",{ref:n,className:ue("text-sm text-muted-foreground",e),...a})).displayName="CardDescription";const ke=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("p-6 pt-0",e),...a}));ke.displayName="CardContent";function Ne({file:a,onDocumentSigned:n,onError:r,showEventLog:d=!1}){const{user:g,alias:p}=te(),{config:h,isLoading:b}=ae(),{t:w}=N(),[x,k]=o(null),[S,T]=o(!1),[I,A]=o(null),[E,C]=o("sandbox"),[P,V]=o("clicksign"),[L,R]=o(null),[U,D]=o(null),[B,j]=o(!1),[O,$]=o(0),[q,z]=o(!1),[J,F]=o([]),M=c(null),W=c(null),H=i(e=>{d&&F(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[d]),K=i(async e=>{if(k(e),A(null),R(null),D(null),H(`Arquivo selecionado: ${e.name}`),p&&g){T(!0);try{const t=h?.provider??"clicksign";V(t),H(`Provedor resolvido: ${t}`);const a=new FileReader,n=await new Promise((t,n)=>{a.onload=()=>{const e=a.result;t(e)},a.onerror=n,a.readAsDataURL(e)});H(`Criando envelope para assinatura via ${t}...`);const o=await se.createEnvelopeWithSigner({alias:p,contentBase64:n,filename:e.name,signerEmail:g.email||"",signerName:g.name||"",provider:t});H(`Envelope criado: ${o.envelope_id}`),R({envelope_id:o.envelope_id,document_id:o.document_id,signer_email:o.signer_email,key_signer:o.signer_id}),C(o.environment),V(o.provider||t),"d4sign"===t?(H("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),A(o.document_id),u.success(w("sign_doc_sent","Documento enviado! Assine abaixo."))):o.signer_id?(H(`Signer ID obtido: ${o.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),A(o.signer_id),u.success(w("sign_doc_sent","Documento enviado! Assine abaixo."))):(H(l.t("sign_signer_unavailable")),u.error(w("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),r?.(new Error(w("sign_signer_unavailable"))))}catch(t){const e=t instanceof Error?t:new Error(w("sign_process_error",w("sign_doc_process_error"))),a=e.message||"";a.includes("MONTHLY_LIMIT_REACHED")?(H(l.t("sign_monthly_limit")),u.error(w("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(H(`Erro: ${a}`),u.error(a)),r?.(e)}finally{T(!1)}}},[p,g,H,r,h]);s(()=>{a&&p&&g&&!b&&a!==W.current&&(W.current=a,K(a))},[a,p,g,b,K]);const Y=i(async()=>{if(!L||!p)return;j(!0),$(0),z(!1),H("Buscando documento assinado...");for(let t=1;t<=6;t++){$(t),H(`Tentativa ${t}/6...`);try{const e=await se.getSignedDocument({alias:p,envelopeId:L.envelope_id,documentId:L.document_id,provider:P});if(e.download_url)return H(l.t("sign_doc_available")),D(e.download_url),void j(!1)}catch(e){H(`Erro na tentativa ${t}: ${e instanceof Error?e.message:w("unknown_error")}`)}t<6&&(H("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}H(l.t("sign_fetch_failed")),j(!1),z(!0)},[L,p,H,P]),G=i(async()=>{H("Documento assinado com sucesso!"),u.success(w("sign_signed_success","Documento assinado com sucesso!")),A(null),L&&p&&(n?.({success:!0,provider:P,envelope_id:L.envelope_id,document_id:L.document_id,signer_id:I||"",environment:E}),await Y())},[H,n,L,I,p,E,P,Y]);if(!p)return t(be,{className:"border-amber-200 bg-amber-50",children:t(ke,{className:"flex items-start gap-3 py-6",children:e("div",{children:[t("p",{className:"font-medium text-amber-800",children:w("sign_auth_required","Autenticação necessária")}),t("p",{className:"text-sm text-amber-700 mt-1",children:w("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const Q="d4sign"===P?"D4Sign":"Clicksign",X=()=>d&&J.length>0?t("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:J.map((e,a)=>t("div",{children:e},a))}):null;return L&&!I&&(U||B||q)?e("div",{className:"space-y-4",children:[t(be,{className:"border-green-200 bg-green-50",children:e(ke,{className:"flex flex-col items-center gap-4 py-8",children:[t(f,{className:"h-12 w-12 text-green-600"}),e("div",{className:"text-center",children:[t("p",{className:"text-lg font-semibold text-green-800",children:w("sign_signed_success","Documento assinado com sucesso!")}),t("p",{className:"text-sm text-green-700 mt-1",children:x?.name})]}),B?e("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e("div",{className:"flex items-center gap-2",children:[t(m,{className:"h-4 w-4 animate-spin"}),w("sign_preparing_doc","Preparando documento assinado...")," (",w("sign_attempt","tentativa")," ",O,"/6)"]}),t("p",{className:"text-xs text-muted-foreground",children:w("sign_waiting_provider",`Aguardando processamento pelo ${Q}...`)})]}):U?t(_e,{asChild:!0,variant:"default",className:"gap-2",children:e("a",{href:U,target:"_blank",rel:"noopener noreferrer",children:[t(v,{className:"h-4 w-4"}),w("sign_download_signed","Baixar documento assinado")]})}):q?e("div",{className:"text-center space-y-3",children:[e("div",{className:"space-y-1",children:[t("p",{className:"text-sm text-muted-foreground",children:w("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),t("p",{className:"text-xs text-muted-foreground",children:w("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e(_e,{variant:"secondary",className:"gap-2",onClick:Y,children:[t(y,{className:"h-4 w-4"}),w("sign_try_again","Tentar novamente")]})]}):null]})}),t(X,{})]}):I?e("div",{className:"space-y-4",children:["d4sign"===P?t(ve,{documentKey:I,signerEmail:L?.signer_email||g?.email||"",signerName:g?.name,keySigner:L?.key_signer,environment:E,onSign:G,onError:r}):t(de,{signerId:I,environment:E,onSign:G,onError:r}),t(X,{})]}):a&&(S||b)?t(be,{children:e(ke,{className:"flex items-center justify-center gap-3 py-10",children:[t(m,{className:"h-6 w-6 animate-spin text-primary"}),t("p",{className:"font-medium",children:w("sign_sending_doc","Enviando documento para assinatura...")})]})}):e("div",{className:"space-y-4",children:[t("input",{ref:M,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?K(t):u.error(w("sign_select_pdf","Selecione um arquivo PDF"))}}),t(be,S?{children:e(ke,{className:"flex items-center justify-center gap-3 py-10",children:[t(m,{className:"h-6 w-6 animate-spin text-primary"}),t("p",{className:"font-medium",children:w("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>M.current?.click(),children:e(ke,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[t(_,{className:"h-8 w-8 text-muted-foreground"}),e("div",{className:"text-center",children:[t("p",{className:"font-medium",children:w("sign_select_pdf","Selecione um arquivo PDF")}),t("p",{className:"text-sm text-muted-foreground",children:w("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),t(X,{})]})}a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("flex items-center p-6 pt-0",e),...a})).displayName="CardFooter";const Se=a.forwardRef(({className:n,type:r,showCharCount:o,maxLength:s,onChange:i,...c},l)=>{const[d,u]=a.useState(0);a.useEffect(()=>{"string"==typeof c.value?u(c.value.length):"string"==typeof c.defaultValue&&u(c.defaultValue.length)},[c.value,c.defaultValue]);return e("div",{className:"w-full",children:[t("input",{type:r,className:ue("flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",n),ref:l,maxLength:s,onChange:e=>{u(e.target.value.length),i?.(e)},...c}),o&&s&&e("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",s]})]})});Se.displayName="Input";const Te=S("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ie=a.forwardRef(({className:e,...a},n)=>t(E.Root,{ref:n,className:ue(Te(),e),...a}));Ie.displayName=E.Root.displayName;const Ae=a.createContext({showCheck:!1}),Ee=({showCheck:e=!1,...a})=>t(Ae.Provider,{value:{showCheck:e},children:t(C.Root,{...a})}),Ce=C.Value,Pe=a.forwardRef(({className:a,children:n,...r},o)=>e(C.Trigger,{ref:o,className:ue("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",a),...r,children:[n,t(C.Icon,{asChild:!0,children:t(b,{className:"h-4 w-4 opacity-50"})})]}));Pe.displayName=C.Trigger.displayName;const Ve=a.forwardRef(({className:e,...a},n)=>t(C.ScrollUpButton,{ref:n,className:ue("flex cursor-default items-center justify-center py-1",e),...a,children:t(w,{className:"h-4 w-4"})}));Ve.displayName=C.ScrollUpButton.displayName;const Le=a.forwardRef(({className:e,...a},n)=>t(C.ScrollDownButton,{ref:n,className:ue("flex cursor-default items-center justify-center py-1",e),...a,children:t(b,{className:"h-4 w-4"})}));Le.displayName=C.ScrollDownButton.displayName;const Re=a.forwardRef(({className:a,children:n,position:r="popper",container:o,collisionBoundary:s,...i},c)=>t(C.Portal,{container:o,children:e(C.Content,{ref:c,className:ue("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===r&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:r,collisionBoundary:s,...i,children:[t(Ve,{}),t(C.Viewport,{className:ue("p-1","popper"===r&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:n}),t(Le,{})]})}));Re.displayName=C.Content.displayName;a.forwardRef(({className:e,...a},n)=>t(C.Label,{ref:n,className:ue("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...a})).displayName=C.Label.displayName;const Ue=a.forwardRef(({className:n,children:r,...o},s)=>{const{showCheck:i}=a.useContext(Ae);return e(C.Item,{ref:s,className:ue("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",i?"pl-8":"pl-2","data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground data-[state=checked]:font-medium data-[state=checked]:border-l-2 data-[state=checked]:border-primary",i?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",n),...o,children:[i&&t("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t(C.ItemIndicator,{children:t(x,{className:"h-4 w-4"})})}),t(C.ItemText,{children:r})]})});Ue.displayName=C.Item.displayName;function De({onSaved:a}){const{config:n,isLoading:r,saveConfig:i}=ae(),{t:c}=N(),[l,d]=o(""),[p,h]=o("sandbox"),[f,v]=o(!1);s(()=>{!r&&n&&(d(n.api_key),h(n.environment))},[n,r]);return r?t("div",{className:"flex items-center justify-center py-8",children:t(m,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e("div",{className:"space-y-4",children:[e("div",n?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[t(g,{className:"h-4 w-4"}),t("span",{children:c("sign_configured",c("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[t(k,{className:"h-4 w-4"}),t("span",{children:c("sign_not_configured",c("sign_not_configured_unit"))})]}),e(be,{children:[t(we,{children:t(xe,{className:"text-base",children:c("sign_digital_config")})}),t(ke,{children:e("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){v(!0);try{await i(l.trim(),p),u.success(c("sign_config_saved",c("sign_config_saved_success"))),a?.()}catch(t){u.error(c("sign_config_save_error",c("sign_config_save_err")))}finally{v(!1)}}else u.error(c("sign_api_key_required",c("sign_api_key_info")))},className:"space-y-4",children:[e("div",{className:"space-y-2",children:[t(Ie,{htmlFor:"sign-api-key",children:"API Key"}),t(Se,{id:"sign-api-key",type:"password",placeholder:c("sign_api_key_placeholder",c("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),e("div",{className:"space-y-2",children:[t(Ie,{children:c("sign_environment","Ambiente")}),e(Ee,{value:p,onValueChange:e=>h(e),children:[t(Pe,{children:t(Ce,{})}),e(Re,{children:[t(Ue,{value:"sandbox",children:"Sandbox (Testes)"}),t(Ue,{value:"production",children:"Produção"})]})]})]}),e(_e,{type:"submit",disabled:f,children:[f&&t(m,{className:"mr-2 h-4 w-4 animate-spin"}),n?c("sign_update_config",c("sign_update_config_btn")):c("sign_save_config",c("sign_save_config_btn"))]})]})})]})]})}a.forwardRef(({className:e,...a},n)=>t(C.Separator,{ref:n,className:ue("-mx-1 my-1 h-px bg-muted",e),...a})).displayName=C.Separator.displayName;export{ve as D4SignWidget,Ne as DocumentSigner,De as SignConfigForm,de as SignWidget,ce as loadClicksignScript,se as signService,ae as useSignConfig};
|
|
1
|
+
import{jsxs as e,jsx as t}from"react/jsx-runtime";import*as a from"react";import{createContext as n,useContext as r,useState as s,useEffect as o,useCallback as i,useRef as c}from"react";import"@tanstack/react-query";import l from"i18next";import{createClient as d}from"@supabase/supabase-js";import{toast as u}from"sonner";import{Loader2 as m,CheckCircle as g,AlertTriangle as p,Info as h,CheckCircle2 as f,Download as v,RefreshCw as b,Upload as y,ChevronDown as _,ChevronUp as w,Check as k,AlertCircle as x}from"lucide-react";import{useTranslation as N}from"react-i18next";import{cva as S}from"class-variance-authority";import{clsx as T}from"clsx";import{twMerge as I}from"tailwind-merge";import"date-fns";import{Slot as E}from"@radix-ui/react-slot";import*as A from"@radix-ui/react-label";import*as C from"@radix-ui/react-select";class P{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const r=e.split(".");if(3!==r.length)return null;const s=r[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const n=new TextDecoder("utf-8").decode(a);return JSON.parse(n)}catch(t){try{const e=this.normalizeBase64Url(s),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(s),t=atob(e);return JSON.parse(t)}catch(n){throw n}}}}catch(r){return null}}static validateTokens(e,t){const a=[],n=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),s=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:n}}let o=!0;if(!s){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),o=!1}const i=Math.floor(Date.now()/1e3);if(s?.exp&&s.exp<i){const e="Access token expirado - pode precisar de refresh";a.push(e),o=!1}if(r.exp&&r.exp<i){const e="ID token expirado - autenticação inválida";return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:a,errors:n}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:a,errors:n}}catch(r){const e=`Erro na validação de tokens: ${r}`;return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:n}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}P.LARGE_PAYLOAD_THRESHOLD=1e3;const V={storageProjectId:"ccjfvpnndclajkleyqkc",supabaseProjectId:"ccjfvpnndclajkleyqkc",supabaseUrl:"https://ccjfvpnndclajkleyqkc.supabase.co",supabasePublishableKey:"sb_publishable_w-TKU0hE4bjM_uOgt3fK1g_ewrXKJ8J",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},L={storageProjectId:"ccjfvpnndclajkleyqkc",supabaseProjectId:"tskpcuganynhsppzoqgj",supabaseUrl:"https://tskpcuganynhsppzoqgj.supabase.co",supabasePublishableKey:"sb_publishable_2EIWdYocxgrN4t_f64Ms3g_pKRcbHfL",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function R(){return"DEV"===import.meta.env.VITE_APP_ENV?"DEV":"PROD"}function U(){return"DEV"===R()?L:V}const D="qualiex_access_token",j="qualiex_id_token",B="supabase_token",O="oauth_state",$="oauth_nonce",q="selected_alias",z="manual_logout",J="supabase_project_id",F={setAccessToken:e=>localStorage.setItem(D,e),getAccessToken:()=>localStorage.getItem(D),setIdToken:e=>localStorage.setItem(j,e),getIdToken:()=>localStorage.getItem(j),getSupabaseToken:()=>localStorage.getItem(B),setOAuthState:e=>sessionStorage.setItem(O,e),getOAuthState:()=>sessionStorage.getItem(O),clearOAuthState:()=>sessionStorage.removeItem(O),setOAuthNonce:e=>sessionStorage.setItem($,e),getOAuthNonce:()=>sessionStorage.getItem($),clearOAuthNonce:()=>sessionStorage.removeItem($),setSelectedAlias:e=>localStorage.setItem(q,e),getSelectedAlias:()=>localStorage.getItem(q),clearSelectedAlias:()=>localStorage.removeItem(q),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!F.getAccessToken()||!F.getIdToken()),checkProjectMismatch:()=>{const e=U().supabaseProjectId,t=localStorage.getItem(J);return t&&t!==e?(F.clearAll(),localStorage.setItem(J,e),!0):(t||localStorage.setItem(J,e),!1)},setSupabaseToken:e=>{localStorage.setItem(B,e),F._clearValidationCache()},areAllTokensValid:()=>{const e=F.getAccessToken(),t=F.getIdToken();if(!e||!t)return!1;try{const a=P.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=F.getAccessToken(),a=F.getIdToken(),n=F.getSupabaseToken();return t&&F.isTokenExpired(t)&&(localStorage.removeItem(D),e=!0),a&&F.isTokenExpired(a)&&(localStorage.removeItem(j),e=!0),n&&F.isTokenExpired(n)&&(localStorage.removeItem(B),e=!0),e},clearAll:()=>{localStorage.removeItem(D),localStorage.removeItem(j),localStorage.removeItem(B),localStorage.removeItem(q),sessionStorage.removeItem(O),sessionStorage.removeItem($),F._clearValidationCache()},setManualLogout:()=>localStorage.setItem(z,"true"),isManualLogout:()=>"true"===localStorage.getItem(z),clearManualLogout:()=>localStorage.removeItem(z),isTokenExpired:e=>{try{return P.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{F._validationCache.isValid=!1,F._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=F.getSupabaseToken();if(!e)return!1;if(F.isTokenExpired(e))return F._clearValidationCache(),F._handleExpiredToken(),!1;const t=Date.now();return t-F._validationCache.timestamp<F._validationCache.cacheValidityMs?F._validationCache.isValid:(F._validationCache.isValid=!0,F._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>F.isSupabaseTokenValid()?F.getSupabaseToken():null,_handleExpiredToken:()=>{F.clearAll()},extractTokenData:()=>{if(!F.isSupabaseTokenValid())return null;const e=F.getSupabaseToken();if(!e)return null;try{const t=P.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,n=t.place_id||null,r=t.place_name||null;let s=t.company_id;if(!s&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const n=t[e];if(n&&"string"==typeof n){const e=n.split(";");if(e.length>7&&e[0]===a){s=e[7];break}}}return{alias:a,companyId:s,placeId:n,placeName:r,payload:t}}catch(t){return F._handleExpiredToken(),null}},getCompanyId:e=>{const t=F.getAccessToken();if(t)try{const a=P.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const n=a[t];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=F.extractTokenData();if(a?.companyId)return a.companyId;const n=F.getIdToken();if(n)try{const t=P.parseJwtPayload(n);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const n=t[a];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const t=[F.getAccessToken(),F.getIdToken()];for(const a of t)if(a)try{const t=P.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const n=t[a];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=F.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=F.getIdToken();if(!e)return[];try{const t=P.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const n=t[e];if(n&&"string"==typeof n){const e=n.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}};const K={get oauth(){const e=U();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}};import.meta.env.VITE_IS_QUALIEX;const M=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);u.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?l.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?l.t("error_authentication"):t.includes("api")||t.includes("network")?l.t("error_connection"):"Erro"}success(e,t){u.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function W(e){return!!e&&e.startsWith("eyJ")}function H(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE;return e||(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY??"")}let Y=!1;function G(){if("DEV"===R()){const e=U();return{url:e.supabaseUrl,key:e.supabasePublishableKey}}const e=import.meta.env.VITE_SUPABASE_URL,t=H();return e&&t?{url:e,key:t}:null}class X{constructor(e){this.currentToken=null,this.config=e,function(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE,t=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;Y?W(t):e&&W(t)?Y=!0:W(t)?Y=!0:Y=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:this.config.key};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return d(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){if(!X.instance){const e=G();if(!e)throw new Error("[forlogic-core] Supabase não configurado. Defina VITE_SUPABASE_URL e VITE_SUPABASE_PUBLISHABLE_KEY no .env, ou não invoque getSupabaseClient() (use isSupabaseConfigured() para checar antes).");X.instance=new X(e)}return X.instance}getClient(){const e=F.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!P.isTokenExpired(e)}catch(t){return M.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function Q(){return X.getInstance().getClient()}class Z{static async generateToken(e,t,a,n=!1){try{if(!n){const e=F.getSupabaseToken();if(e&&F.isSupabaseTokenValid())return e}const r=Q(),{data:s,error:o}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(a?.(),null):s?.access_token?(F.setSupabaseToken(s.access_token),s.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}class ee{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const t=F.getAccessToken(),a=F.getSelectedAlias();if(!t||!a)return null;const n=await Z.generateToken(t,a,this.onLogoutCallback||void 0,e);return n||null}catch(t){return null}}}var te;ee.regenerationPromise=null,ee.onLogoutCallback=null;const ae={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};te=class{static async initialize(){try{const e=!0;if(e){if(F.checkProjectMismatch())return{...ae}}if(!F.hasAllTokens()||!F.areAllTokensValid())return F.clearExpiredTokens(),{...ae};const t=F.getAccessToken(),a=F.getIdToken();F.clearManualLogout();const n=this.extractUserFromIdToken(a,t),r=this.extractCompaniesFromIdToken(a),s=this.extractAliasFromAccessToken(t),o=e?F.extractTokenData():null,i=o?.alias;let c=null;if(i&&r.some(e=>e.alias===i))c=i;else{const e=F.getSelectedAlias(),t=e&&r.some(t=>t.alias===e);c=t?e:s||r[0]?.alias||null}if(e&&(!F.isSupabaseTokenValid()&&c&&await ee.attemptRegeneration(),!F.isSupabaseTokenValid()))return{...ae};let l=null;if(c){const e=F.getCompanyId(c),t=r.find(e=>e.alias===c);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=o?.placeId??null,u=o?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:n,alias:c,companies:r,selectedUnit:l,userId:n?.id||null,userAlias:n?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{...ae}}}static async loginDev(){try{const e=Q(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const n=new URL("/callback",window.location.origin);return n.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=n.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";F.setOAuthState(e);const t=F.generateOAuthNonce();F.setOAuthNonce(t);const a=`${window.location.origin}/callback`,n=new URL(K.oauth.authUrl);n.searchParams.set("client_id",K.oauth.clientId),n.searchParams.set("response_type",K.oauth.responseType),n.searchParams.set("scope",K.oauth.scope),n.searchParams.set("redirect_uri",a),n.searchParams.set("state",e),n.searchParams.set("nonce",t),n.searchParams.set("response_mode","fragment"),window.location.href=n.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),n=a("access_token"),r=a("id_token"),s=a("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(n&&r){const e=F.getAccessToken();e!==n&&F.clearAll()}const o=!0;if(F.hasAllTokens()){if(o){F.getValidSupabaseToken()||await ee.attemptRegeneration(!0)}return!0}const i=n,c=r;if(!i||!c)throw new Error("Tokens não encontrados na URL de callback");F.setAccessToken(i),F.setIdToken(c),F.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)F.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(c);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");F.setSelectedAlias(e[0].alias)}if(o){if(!await ee.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return F.clearOAuthState(),F.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){F.clearAll(),F.setManualLogout(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return P.parseJwtPayload(e)}static extractUserFromIdToken(e,t){const a=this.decodeToken(e);if(!a)return null;const n=t?this.decodeToken(t):null;return{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier,isSysAdmin:"1"===n?.admin}}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const n=t[e].split(";");if(n.length>=4)a.push({id:n.length>7?n[7].trim():"",alias:n[0].trim(),name:n[3].trim()});else{const[n,r]=t[e].split("|");n&&r&&a.push({id:"",alias:n.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}},ee.setLogoutCallback(()=>{te.logout()});const ne=n(void 0),re=()=>{const e=r(ne);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function se(){const{alias:e}=re(),[t,a]=s(null),[n,r]=s(!0);o(()=>{if(!e)return void r(!1);let t=!1;return(async()=>{r(!0);try{const n=Q(),{data:r,error:s}=await n.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||a(r)}catch(n){t||a(null)}finally{t||r(!1)}})(),()=>{t=!0}},[e]);return{config:t,isLoading:n,saveConfig:i(async(t,n)=>{if(!e)throw new Error("Alias not available");const r=Q(),{data:s,error:o}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:n,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return a(s),s},[e])}}const oe=import.meta.env.VITE_SUPABASE_URL,ie=H();async function ce(e,t,a){const n=F.getSupabaseToken(),r={"Content-Type":"application/json",apikey:ie};n&&(r.Authorization=`Bearer ${n}`);const s=await fetch(`${oe}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:t,data:a})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const le={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await ce(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await ce(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let de=null;function ue(){return window.Clicksign?Promise.resolve():de||(de=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),de)}const me="clicksign-container";function ge({signerId:a,environment:n="sandbox",onSign:r,onError:i,onClose:l}){const{t:d}=N(),u=c(null),[g,p]=s(!0),[h,f]=s(null);return o(()=>{let e=!1;return u.current&&(u.current.unmount(),u.current=null),f(null),p(!0),ue().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===n?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(me),t.on("loaded",function(){p(!1)}),t.on("signed",function(){r?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(me);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){p(!1),i?.(e instanceof Error?e:new Error(d("sign_widget_error")))}),t.on("closed",function(){l?.()}),u.current=t}).catch(t=>{e||(f("Falha ao carregar o script de assinatura."),p(!1),i?.(t))}),()=>{e=!0,u.current&&(u.current.unmount(),u.current=null)}},[a,n]),e("div",{className:"relative h-full",children:[g&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t(m,{className:"h-5 w-5 animate-spin"}),t("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:t("p",{className:"text-sm text-destructive",children:h})}),t("div",{id:me,style:{height:"600px"}})]})}function pe(...e){return I(T(e))}const he=S("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),fe={info:h,warning:h,danger:p,success:g},ve=a.forwardRef(({className:a,variant:n="info",showIcon:r=!0,children:s,...o},i)=>{const c=fe[n||"info"];return e("div",{ref:i,role:"alert",className:pe(he({variant:n}),a),...o,children:[r&&t(c,{className:"h-4 w-4"}),s]})});ve.displayName="Alert";const be=a.forwardRef(({className:e,...a},n)=>t("h5",{ref:n,className:pe("mb-1 font-medium leading-none tracking-tight",e),...a}));be.displayName="AlertTitle";const ye=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:pe("text-sm [&_p]:leading-relaxed",e),...a}));ye.displayName="AlertDescription";function _e({documentKey:a,signerEmail:n,signerName:r,keySigner:d,environment:u,onSign:g,onError:p}){const h=c(null),[f,v]=s("loading"),[b,y]=s(null),_="production"===u?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:n,display_name:r||"",disable_preview:"0"});return d&&e.set("key_signer",d),`${_}/${a}?${e.toString()}`})(),k=i(e=>"signed"===e.data?(v("ready"),void g?.()):"wrong-data"===e.data?(v("error"),y(l.t("sign_incorrect_data")),void p?.(new Error(l.t("sign_incorrect_data")))):void 0,[g,p]);o(()=>(window.addEventListener("message",k,!1),()=>{window.removeEventListener("message",k,!1)}),[k]);const x=i(()=>{"loading"===f&&v("ready")},[f]);return"error"===f?e(ve,{variant:"danger",className:"my-4",children:[t(be,{children:l.t("sign_doc_load_error")}),t(ye,{children:b||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e("div",{className:"relative h-full",children:["loading"===f&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t(m,{className:"h-5 w-5 animate-spin"}),t("span",{className:"text-sm",children:"Carregando documento..."})]})}),t("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:x})]})}const we=S("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),ke=a.forwardRef(({className:e,variant:a,size:n,asChild:r=!1,...s},o)=>t(r?E:"button",{className:pe(we({variant:a,size:n,className:e})),ref:o,...s}));ke.displayName="Button";const xe=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:pe("rounded-lg border bg-card text-card-foreground shadow-sm",e),...a}));xe.displayName="Card";const Ne=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:pe("flex flex-col space-y-1.5 p-6",e),...a}));Ne.displayName="CardHeader";const Se=a.forwardRef(({className:e,...a},n)=>t("h3",{ref:n,className:pe("text-2xl font-semibold leading-none tracking-tight",e),...a}));Se.displayName="CardTitle";a.forwardRef(({className:e,...a},n)=>t("p",{ref:n,className:pe("text-sm text-muted-foreground",e),...a})).displayName="CardDescription";const Te=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:pe("p-6 pt-0",e),...a}));Te.displayName="CardContent";function Ie({file:a,onDocumentSigned:n,onError:r,showEventLog:d=!1}){const{user:g,alias:p}=re(),{config:h,isLoading:_}=se(),{t:w}=N(),[k,x]=s(null),[S,T]=s(!1),[I,E]=s(null),[A,C]=s("sandbox"),[P,V]=s("clicksign"),[L,R]=s(null),[U,D]=s(null),[j,B]=s(!1),[O,$]=s(0),[q,z]=s(!1),[J,F]=s([]),K=c(null),M=c(null),W=i(e=>{d&&F(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[d]),H=i(async e=>{if(x(e),E(null),R(null),D(null),W(`Arquivo selecionado: ${e.name}`),p&&g){T(!0);try{const t=h?.provider??"clicksign";V(t),W(`Provedor resolvido: ${t}`);const a=new FileReader,n=await new Promise((t,n)=>{a.onload=()=>{const e=a.result;t(e)},a.onerror=n,a.readAsDataURL(e)});W(`Criando envelope para assinatura via ${t}...`);const s=await le.createEnvelopeWithSigner({alias:p,contentBase64:n,filename:e.name,signerEmail:g.email||"",signerName:g.name||"",provider:t});W(`Envelope criado: ${s.envelope_id}`),R({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),C(s.environment),V(s.provider||t),"d4sign"===t?(W("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),E(s.document_id),u.success(w("sign_doc_sent","Documento enviado! Assine abaixo."))):s.signer_id?(W(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),E(s.signer_id),u.success(w("sign_doc_sent","Documento enviado! Assine abaixo."))):(W(l.t("sign_signer_unavailable")),u.error(w("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),r?.(new Error(w("sign_signer_unavailable"))))}catch(t){const e=t instanceof Error?t:new Error(w("sign_process_error",w("sign_doc_process_error"))),a=e.message||"";a.includes("MONTHLY_LIMIT_REACHED")?(W(l.t("sign_monthly_limit")),u.error(w("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(W(`Erro: ${a}`),u.error(a)),r?.(e)}finally{T(!1)}}},[p,g,W,r,h]);o(()=>{a&&p&&g&&!_&&a!==M.current&&(M.current=a,H(a))},[a,p,g,_,H]);const Y=i(async()=>{if(!L||!p)return;B(!0),$(0),z(!1),W("Buscando documento assinado...");for(let t=1;t<=6;t++){$(t),W(`Tentativa ${t}/6...`);try{const e=await le.getSignedDocument({alias:p,envelopeId:L.envelope_id,documentId:L.document_id,provider:P});if(e.download_url)return W(l.t("sign_doc_available")),D(e.download_url),void B(!1)}catch(e){W(`Erro na tentativa ${t}: ${e instanceof Error?e.message:w("unknown_error")}`)}t<6&&(W("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}W(l.t("sign_fetch_failed")),B(!1),z(!0)},[L,p,W,P]),G=i(async()=>{W("Documento assinado com sucesso!"),u.success(w("sign_signed_success","Documento assinado com sucesso!")),E(null),L&&p&&(n?.({success:!0,provider:P,envelope_id:L.envelope_id,document_id:L.document_id,signer_id:I||"",environment:A}),await Y())},[W,n,L,I,p,A,P,Y]);if(!p)return t(xe,{className:"border-amber-200 bg-amber-50",children:t(Te,{className:"flex items-start gap-3 py-6",children:e("div",{children:[t("p",{className:"font-medium text-amber-800",children:w("sign_auth_required","Autenticação necessária")}),t("p",{className:"text-sm text-amber-700 mt-1",children:w("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const X="d4sign"===P?"D4Sign":"Clicksign",Q=()=>d&&J.length>0?t("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:J.map((e,a)=>t("div",{children:e},a))}):null;return L&&!I&&(U||j||q)?e("div",{className:"space-y-4",children:[t(xe,{className:"border-green-200 bg-green-50",children:e(Te,{className:"flex flex-col items-center gap-4 py-8",children:[t(f,{className:"h-12 w-12 text-green-600"}),e("div",{className:"text-center",children:[t("p",{className:"text-lg font-semibold text-green-800",children:w("sign_signed_success","Documento assinado com sucesso!")}),t("p",{className:"text-sm text-green-700 mt-1",children:k?.name})]}),j?e("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e("div",{className:"flex items-center gap-2",children:[t(m,{className:"h-4 w-4 animate-spin"}),w("sign_preparing_doc","Preparando documento assinado...")," (",w("sign_attempt","tentativa")," ",O,"/6)"]}),t("p",{className:"text-xs text-muted-foreground",children:w("sign_waiting_provider",`Aguardando processamento pelo ${X}...`)})]}):U?t(ke,{asChild:!0,variant:"default",className:"gap-2",children:e("a",{href:U,target:"_blank",rel:"noopener noreferrer",children:[t(v,{className:"h-4 w-4"}),w("sign_download_signed","Baixar documento assinado")]})}):q?e("div",{className:"text-center space-y-3",children:[e("div",{className:"space-y-1",children:[t("p",{className:"text-sm text-muted-foreground",children:w("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),t("p",{className:"text-xs text-muted-foreground",children:w("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e(ke,{variant:"secondary",className:"gap-2",onClick:Y,children:[t(b,{className:"h-4 w-4"}),w("sign_try_again","Tentar novamente")]})]}):null]})}),t(Q,{})]}):I?e("div",{className:"space-y-4",children:["d4sign"===P?t(_e,{documentKey:I,signerEmail:L?.signer_email||g?.email||"",signerName:g?.name,keySigner:L?.key_signer,environment:A,onSign:G,onError:r}):t(ge,{signerId:I,environment:A,onSign:G,onError:r}),t(Q,{})]}):a&&(S||_)?t(xe,{children:e(Te,{className:"flex items-center justify-center gap-3 py-10",children:[t(m,{className:"h-6 w-6 animate-spin text-primary"}),t("p",{className:"font-medium",children:w("sign_sending_doc","Enviando documento para assinatura...")})]})}):e("div",{className:"space-y-4",children:[t("input",{ref:K,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?H(t):u.error(w("sign_select_pdf","Selecione um arquivo PDF"))}}),t(xe,S?{children:e(Te,{className:"flex items-center justify-center gap-3 py-10",children:[t(m,{className:"h-6 w-6 animate-spin text-primary"}),t("p",{className:"font-medium",children:w("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>K.current?.click(),children:e(Te,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[t(y,{className:"h-8 w-8 text-muted-foreground"}),e("div",{className:"text-center",children:[t("p",{className:"font-medium",children:w("sign_select_pdf","Selecione um arquivo PDF")}),t("p",{className:"text-sm text-muted-foreground",children:w("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),t(Q,{})]})}a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:pe("flex items-center p-6 pt-0",e),...a})).displayName="CardFooter";const Ee=a.forwardRef(({className:n,type:r,showCharCount:s,maxLength:o,onChange:i,...c},l)=>{const[d,u]=a.useState(0);a.useEffect(()=>{"string"==typeof c.value?u(c.value.length):"string"==typeof c.defaultValue&&u(c.defaultValue.length)},[c.value,c.defaultValue]);return e("div",{className:"w-full",children:[t("input",{type:r,className:pe("flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",n),ref:l,maxLength:o,onChange:e=>{u(e.target.value.length),i?.(e)},...c}),s&&o&&e("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",o]})]})});Ee.displayName="Input";const Ae=S("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ce=a.forwardRef(({className:e,...a},n)=>t(A.Root,{ref:n,className:pe(Ae(),e),...a}));Ce.displayName=A.Root.displayName;const Pe=a.createContext({showCheck:!1}),Ve=({showCheck:e=!1,...a})=>t(Pe.Provider,{value:{showCheck:e},children:t(C.Root,{...a})}),Le=C.Value,Re=a.forwardRef(({className:a,children:n,...r},s)=>e(C.Trigger,{ref:s,className:pe("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",a),...r,children:[n,t(C.Icon,{asChild:!0,children:t(_,{className:"h-4 w-4 opacity-50"})})]}));Re.displayName=C.Trigger.displayName;const Ue=a.forwardRef(({className:e,...a},n)=>t(C.ScrollUpButton,{ref:n,className:pe("flex cursor-default items-center justify-center py-1",e),...a,children:t(w,{className:"h-4 w-4"})}));Ue.displayName=C.ScrollUpButton.displayName;const De=a.forwardRef(({className:e,...a},n)=>t(C.ScrollDownButton,{ref:n,className:pe("flex cursor-default items-center justify-center py-1",e),...a,children:t(_,{className:"h-4 w-4"})}));De.displayName=C.ScrollDownButton.displayName;const je=a.forwardRef(({className:a,children:n,position:r="popper",container:s,collisionBoundary:o,...i},c)=>t(C.Portal,{container:s,children:e(C.Content,{ref:c,className:pe("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===r&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:r,collisionBoundary:o,...i,children:[t(Ue,{}),t(C.Viewport,{className:pe("p-1","popper"===r&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:n}),t(De,{})]})}));je.displayName=C.Content.displayName;a.forwardRef(({className:e,...a},n)=>t(C.Label,{ref:n,className:pe("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...a})).displayName=C.Label.displayName;const Be=a.forwardRef(({className:n,children:r,...s},o)=>{const{showCheck:i}=a.useContext(Pe);return e(C.Item,{ref:o,className:pe("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",i?"pl-8":"pl-2","data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground data-[state=checked]:font-medium data-[state=checked]:border-l-2 data-[state=checked]:border-primary",i?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",n),...s,children:[i&&t("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t(C.ItemIndicator,{children:t(k,{className:"h-4 w-4"})})}),t(C.ItemText,{children:r})]})});Be.displayName=C.Item.displayName;function Oe({onSaved:a}){const{config:n,isLoading:r,saveConfig:i}=se(),{t:c}=N(),[l,d]=s(""),[p,h]=s("sandbox"),[f,v]=s(!1);o(()=>{!r&&n&&(d(n.api_key),h(n.environment))},[n,r]);return r?t("div",{className:"flex items-center justify-center py-8",children:t(m,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e("div",{className:"space-y-4",children:[e("div",n?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[t(g,{className:"h-4 w-4"}),t("span",{children:c("sign_configured",c("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[t(x,{className:"h-4 w-4"}),t("span",{children:c("sign_not_configured",c("sign_not_configured_unit"))})]}),e(xe,{children:[t(Ne,{children:t(Se,{className:"text-base",children:c("sign_digital_config")})}),t(Te,{children:e("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){v(!0);try{await i(l.trim(),p),u.success(c("sign_config_saved",c("sign_config_saved_success"))),a?.()}catch(t){u.error(c("sign_config_save_error",c("sign_config_save_err")))}finally{v(!1)}}else u.error(c("sign_api_key_required",c("sign_api_key_info")))},className:"space-y-4",children:[e("div",{className:"space-y-2",children:[t(Ce,{htmlFor:"sign-api-key",children:"API Key"}),t(Ee,{id:"sign-api-key",type:"password",placeholder:c("sign_api_key_placeholder",c("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),e("div",{className:"space-y-2",children:[t(Ce,{children:c("sign_environment","Ambiente")}),e(Ve,{value:p,onValueChange:e=>h(e),children:[t(Re,{children:t(Le,{})}),e(je,{children:[t(Be,{value:"sandbox",children:"Sandbox (Testes)"}),t(Be,{value:"production",children:"Produção"})]})]})]}),e(ke,{type:"submit",disabled:f,children:[f&&t(m,{className:"mr-2 h-4 w-4 animate-spin"}),n?c("sign_update_config",c("sign_update_config_btn")):c("sign_save_config",c("sign_save_config_btn"))]})]})})]})]})}a.forwardRef(({className:e,...a},n)=>t(C.Separator,{ref:n,className:pe("-mx-1 my-1 h-px bg-muted",e),...a})).displayName=C.Separator.displayName;export{_e as D4SignWidget,Ie as DocumentSigner,Oe as SignConfigForm,ge as SignWidget,ue as loadClicksignScript,le as signService,se as useSignConfig};
|
package/dist/sign/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("react");require("@tanstack/react-query");var a=require("i18next"),s=require("@supabase/supabase-js"),n=require("sonner"),r=require("lucide-react"),o=require("react-i18next"),i=require("class-variance-authority"),c=require("clsx"),l=require("tailwind-merge");require("date-fns");var d=require("@radix-ui/react-slot"),u=require("@radix-ui/react-label"),m=require("@radix-ui/react-select");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,Object.freeze(t)}var h=g(t),p=g(u),f=g(m);class x{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const r=n[1];r.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(r),t=atob(e),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);const s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}catch(t){try{const e=this.normalizeBase64Url(r),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(r),t=atob(e);return JSON.parse(t)}catch(s){throw s}}}}catch(n){return null}}static validateTokens(e,t){const a=[],s=[];try{t.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(t),r=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}let o=!0;if(!r){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),o=!1}const i=Math.floor(Date.now()/1e3);if(r?.exp&&r.exp<i){const e="Access token expirado - pode precisar de refresh";a.push(e),o=!1}if(n.exp&&n.exp<i){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:a,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:a,errors:s}}catch(n){const e=`Erro na validação de tokens: ${n}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}x.LARGE_PAYLOAD_THRESHOLD=1e3;const v="qualiex_access_token",y="qualiex_id_token",b="supabase_token",_="oauth_state",k="oauth_nonce",w="selected_alias",S="manual_logout",j="supabase_project_id",N={setAccessToken:e=>localStorage.setItem(v,e),getAccessToken:()=>localStorage.getItem(v),setIdToken:e=>localStorage.setItem(y,e),getIdToken:()=>localStorage.getItem(y),getSupabaseToken:()=>localStorage.getItem(b),setOAuthState:e=>sessionStorage.setItem(_,e),getOAuthState:()=>sessionStorage.getItem(_),clearOAuthState:()=>sessionStorage.removeItem(_),setOAuthNonce:e=>sessionStorage.setItem(k,e),getOAuthNonce:()=>sessionStorage.getItem(k),clearOAuthNonce:()=>sessionStorage.removeItem(k),setSelectedAlias:e=>localStorage.setItem(w,e),getSelectedAlias:()=>localStorage.getItem(w),clearSelectedAlias:()=>localStorage.removeItem(w),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!N.getAccessToken()||!N.getIdToken()),checkProjectMismatch:()=>{const e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const t=localStorage.getItem(j);return t&&t!==e?(N.clearAll(),localStorage.setItem(j,e),!0):(t||localStorage.setItem(j,e),!1)},setSupabaseToken:e=>{localStorage.setItem(b,e),N._clearValidationCache()},areAllTokensValid:()=>{const e=N.getAccessToken(),t=N.getIdToken();if(!e||!t)return!1;try{const a=x.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=N.getAccessToken(),a=N.getIdToken(),s=N.getSupabaseToken();return t&&N.isTokenExpired(t)&&(localStorage.removeItem(v),e=!0),a&&N.isTokenExpired(a)&&(localStorage.removeItem(y),e=!0),s&&N.isTokenExpired(s)&&(localStorage.removeItem(b),e=!0),e},clearAll:()=>{localStorage.removeItem(v),localStorage.removeItem(y),localStorage.removeItem(b),localStorage.removeItem(w),localStorage.removeItem(S),sessionStorage.removeItem(_),sessionStorage.removeItem(k),N._clearValidationCache()},setManualLogout:()=>localStorage.setItem(S,"true"),isManualLogout:()=>"true"===localStorage.getItem(S),clearManualLogout:()=>localStorage.removeItem(S),isTokenExpired:e=>{try{return x.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{N._validationCache.isValid=!1,N._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=N.getSupabaseToken();if(!e)return!1;if(N.isTokenExpired(e))return N._clearValidationCache(),N._handleExpiredToken(),!1;const t=Date.now();return t-N._validationCache.timestamp<N._validationCache.cacheValidityMs?N._validationCache.isValid:(N._validationCache.isValid=!0,N._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>N.isSupabaseTokenValid()?N.getSupabaseToken():null,_handleExpiredToken:()=>{N.clearAll()},extractTokenData:()=>{if(!N.isSupabaseTokenValid())return null;const e=N.getSupabaseToken();if(!e)return null;try{const t=x.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,s=t.place_id||null,n=t.place_name||null;let r=t.company_id;if(!r&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===a){r=e[7];break}}}return{alias:a,companyId:r,placeId:s,placeName:n,payload:t}}catch(t){return N._handleExpiredToken(),null}},getCompanyId:e=>{const t=N.getAccessToken();if(t)try{const a=x.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(n){}const a=N.extractTokenData();if(a?.companyId)return a.companyId;const s=N.getIdToken();if(s)try{const t=x.parseJwtPayload(s);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const t=[N.getAccessToken(),N.getIdToken()];for(const a of t)if(a)try{const t=x.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=N.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=N.getIdToken();if(!e)return[];try{const t=x.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}},T={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},I={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};const A={get oauth(){const e=function(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=(void 0).VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return"ccjfvpnndclajkleyqkc"===e?T:I}();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}};(void 0).VITE_IS_QUALIEX;const E=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);n.toast.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?a.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?a.t("error_authentication"):t.includes("api")||t.includes("network")?a.t("error_connection"):"Erro"}success(e,t){n.toast.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function C(e){return!!e&&e.startsWith("eyJ")}function P(){const e=(void 0).VITE_SUPABASE_PK_OVERRIDE;return e||((void 0).VITE_SUPABASE_PUBLISHABLE_KEY??"")}let L=!1;class R{constructor(e){this.currentToken=null,this.config=e,function(){const e=(void 0).VITE_SUPABASE_PK_OVERRIDE,t=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;L?C(t):e&&C(t)?L=!0:C(t)?L=!0:L=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:this.config.key};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return s.createClient(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){if(!R.instance){const e=function(){const e=(void 0).VITE_SUPABASE_URL,t=P();return e&&t?{url:e,key:t}:null}();if(!e)throw new Error("[forlogic-core] Supabase não configurado. Defina VITE_SUPABASE_URL e VITE_SUPABASE_PUBLISHABLE_KEY no .env, ou não invoque getSupabaseClient() (use isSupabaseConfigured() para checar antes).");R.instance=new R(e)}return R.instance}getClient(){const e=N.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!x.isTokenExpired(e)}catch(t){return E.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function V(){return R.getInstance().getClient()}class U{static async generateToken(e,t,a,s=!1){try{if(!s){const e=N.getSupabaseToken();if(e&&N.isSupabaseTokenValid())return e}const n=V(),{data:r,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(a?.(),null):r?.access_token?(N.setSupabaseToken(r.access_token),r.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&a?.(),null}}}class D{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const t=N.getAccessToken(),a=N.getSelectedAlias();if(!t||!a)return null;const s=await U.generateToken(t,a,this.onLogoutCallback||void 0,e);return s||null}catch(t){return null}}}D.regenerationPromise=null,D.onLogoutCallback=null;var O;const q={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};O=class{static async initialize(){try{const e=!0;if(e){if(N.checkProjectMismatch())return{...q}}if(!N.hasAllTokens()||!N.areAllTokensValid())return N.clearExpiredTokens(),{...q};const t=N.getAccessToken(),a=N.getIdToken();N.clearManualLogout();const s=this.extractUserFromIdToken(a,t),n=this.extractCompaniesFromIdToken(a),r=this.extractAliasFromAccessToken(t),o=e?N.extractTokenData():null,i=o?.alias;let c=null;if(i&&n.some(e=>e.alias===i))c=i;else{const e=N.getSelectedAlias(),t=e&&n.some(t=>t.alias===e);c=t?e:r||n[0]?.alias||null}if(e&&(!N.isSupabaseTokenValid()&&c&&await D.attemptRegeneration(),!N.isSupabaseTokenValid()))return{...q};let l=null;if(c){const e=N.getCompanyId(c),t=n.find(e=>e.alias===c);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=o?.placeId??null,u=o?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:s,alias:c,companies:n,selectedUnit:l,userId:s?.id||null,userAlias:s?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{...q}}}static async loginDev(){try{const e=V(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";N.setOAuthState(e);const t=N.generateOAuthNonce();N.setOAuthNonce(t);const a=`${window.location.origin}/callback`,s=new URL(A.oauth.authUrl);s.searchParams.set("client_id",A.oauth.clientId),s.searchParams.set("response_type",A.oauth.responseType),s.searchParams.set("scope",A.oauth.scope),s.searchParams.set("redirect_uri",a),s.searchParams.set("state",e),s.searchParams.set("nonce",t),s.searchParams.set("response_mode","fragment"),window.location.href=s.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),s=a("access_token"),n=a("id_token"),r=a("error");if(r)throw new Error(`Erro OAuth: ${r}`);if(s&&n){const e=N.getAccessToken();e!==s&&N.clearAll()}const o=!0;if(N.hasAllTokens()){if(o){N.getValidSupabaseToken()||await D.attemptRegeneration(!0)}return!0}const i=s,c=n;if(!i||!c)throw new Error("Tokens não encontrados na URL de callback");N.setAccessToken(i),N.setIdToken(c),N.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)N.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(c);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");N.setSelectedAlias(e[0].alias)}if(o){if(!await D.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return N.clearOAuthState(),N.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){N.setManualLogout(),N.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return x.parseJwtPayload(e)}static extractUserFromIdToken(e,t){const a=this.decodeToken(e);if(!a)return null;const s=t?this.decodeToken(t):null;return{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier,isSysAdmin:"1"===s?.admin}}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const s=t[e].split(";");if(s.length>=4)a.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,n]=t[e].split("|");s&&n&&a.push({id:"",alias:s.trim(),name:n.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}},D.setLogoutCallback(()=>{O.logout()});const B=t.createContext(void 0),$=()=>{const e=t.useContext(B);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function z(){const{alias:e}=$(),[a,s]=t.useState(null),[n,r]=t.useState(!0);t.useEffect(()=>{if(!e)return void r(!1);let t=!1;return(async()=>{r(!0);try{const a=V(),{data:n,error:r}=await a.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||s(n)}catch(a){t||s(null)}finally{t||r(!1)}})(),()=>{t=!0}},[e]);return{config:a,isLoading:n,saveConfig:t.useCallback(async(t,a)=>{if(!e)throw new Error("Alias not available");const n=V(),{data:r,error:o}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:a,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return s(r),r},[e])}}const J=(void 0).VITE_SUPABASE_URL,F=P();async function W(e,t,a){const s=N.getSupabaseToken(),n={"Content-Type":"application/json",apikey:F};s&&(n.Authorization=`Bearer ${s}`);const r=await fetch(`${J}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:t,data:a})});if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${r.status}`)}return r}const M={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await W(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await W(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let H=null;function K(){return window.Clicksign?Promise.resolve():H||(H=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),H)}const Y="clicksign-container";function G({signerId:a,environment:s="sandbox",onSign:n,onError:i,onClose:c}){const{t:l}=o.useTranslation(),d=t.useRef(null),[u,m]=t.useState(!0),[g,h]=t.useState(null);return t.useEffect(()=>{let e=!1;return d.current&&(d.current.unmount(),d.current=null),h(null),m(!0),K().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===s?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(Y),t.on("loaded",function(){m(!1)}),t.on("signed",function(){n?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(Y);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){m(!1),i?.(e instanceof Error?e:new Error(l("sign_widget_error")))}),t.on("closed",function(){c?.()}),d.current=t}).catch(t=>{e||(h("Falha ao carregar o script de assinatura."),m(!1),i?.(t))}),()=>{e=!0,d.current&&(d.current.unmount(),d.current=null)}},[a,s]),e.jsxs("div",{className:"relative h-full",children:[u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(r.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),g&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-destructive",children:g})}),e.jsx("div",{id:Y,style:{height:"600px"}})]})}function Q(...e){return l.twMerge(c.clsx(e))}const X=i.cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),Z={info:r.Info,warning:r.Info,danger:r.AlertTriangle,success:r.CheckCircle},ee=h.forwardRef(({className:t,variant:a="info",showIcon:s=!0,children:n,...r},o)=>{const i=Z[a||"info"];return e.jsxs("div",{ref:o,role:"alert",className:Q(X({variant:a}),t),...r,children:[s&&e.jsx(i,{className:"h-4 w-4"}),n]})});ee.displayName="Alert";const te=h.forwardRef(({className:t,...a},s)=>e.jsx("h5",{ref:s,className:Q("mb-1 font-medium leading-none tracking-tight",t),...a}));te.displayName="AlertTitle";const ae=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Q("text-sm [&_p]:leading-relaxed",t),...a}));ae.displayName="AlertDescription";function se({documentKey:s,signerEmail:n,signerName:o,keySigner:i,environment:c,onSign:l,onError:d}){const u=t.useRef(null),[m,g]=t.useState("loading"),[h,p]=t.useState(null),f="production"===c?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",x=(()=>{const e=new URLSearchParams({email:n,display_name:o||"",disable_preview:"0"});return i&&e.set("key_signer",i),`${f}/${s}?${e.toString()}`})(),v=t.useCallback(e=>"signed"===e.data?(g("ready"),void l?.()):"wrong-data"===e.data?(g("error"),p(a.t("sign_incorrect_data")),void d?.(new Error(a.t("sign_incorrect_data")))):void 0,[l,d]);t.useEffect(()=>(window.addEventListener("message",v,!1),()=>{window.removeEventListener("message",v,!1)}),[v]);const y=t.useCallback(()=>{"loading"===m&&g("ready")},[m]);return"error"===m?e.jsxs(ee,{variant:"danger",className:"my-4",children:[e.jsx(te,{children:a.t("sign_doc_load_error")}),e.jsx(ae,{children:h||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e.jsxs("div",{className:"relative h-full",children:["loading"===m&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(r.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),e.jsx("iframe",{ref:u,id:"d4sign-container",src:x,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:y})]})}const ne=i.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),re=h.forwardRef(({className:t,variant:a,size:s,asChild:n=!1,...r},o)=>{const i=n?d.Slot:"button";return e.jsx(i,{className:Q(ne({variant:a,size:s,className:t})),ref:o,...r})});re.displayName="Button";const oe=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Q("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));oe.displayName="Card";const ie=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Q("flex flex-col space-y-1.5 p-6",t),...a}));ie.displayName="CardHeader";const ce=h.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:Q("text-2xl font-semibold leading-none tracking-tight",t),...a}));ce.displayName="CardTitle";h.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Q("text-sm text-muted-foreground",t),...a})).displayName="CardDescription";const le=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Q("p-6 pt-0",t),...a}));le.displayName="CardContent";h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Q("flex items-center p-6 pt-0",t),...a})).displayName="CardFooter";const de=h.forwardRef(({className:t,type:a,showCharCount:s,maxLength:n,onChange:r,...o},i)=>{const[c,l]=h.useState(0);h.useEffect(()=>{"string"==typeof o.value?l(o.value.length):"string"==typeof o.defaultValue&&l(o.defaultValue.length)},[o.value,o.defaultValue]);return e.jsxs("div",{className:"w-full",children:[e.jsx("input",{type:a,className:Q("flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",t),ref:i,maxLength:n,onChange:e=>{l(e.target.value.length),r?.(e)},...o}),s&&n&&e.jsxs("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[c," / ",n]})]})});de.displayName="Input";const ue=i.cva("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),me=h.forwardRef(({className:t,...a},s)=>e.jsx(p.Root,{ref:s,className:Q(ue(),t),...a}));me.displayName=p.Root.displayName;const ge=h.createContext({showCheck:!1}),he=({showCheck:t=!1,...a})=>e.jsx(ge.Provider,{value:{showCheck:t},children:e.jsx(f.Root,{...a})}),pe=f.Value,fe=h.forwardRef(({className:t,children:a,...s},n)=>e.jsxs(f.Trigger,{ref:n,className:Q("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",t),...s,children:[a,e.jsx(f.Icon,{asChild:!0,children:e.jsx(r.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));fe.displayName=f.Trigger.displayName;const xe=h.forwardRef(({className:t,...a},s)=>e.jsx(f.ScrollUpButton,{ref:s,className:Q("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(r.ChevronUp,{className:"h-4 w-4"})}));xe.displayName=f.ScrollUpButton.displayName;const ve=h.forwardRef(({className:t,...a},s)=>e.jsx(f.ScrollDownButton,{ref:s,className:Q("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(r.ChevronDown,{className:"h-4 w-4"})}));ve.displayName=f.ScrollDownButton.displayName;const ye=h.forwardRef(({className:t,children:a,position:s="popper",container:n,collisionBoundary:r,...o},i)=>e.jsx(f.Portal,{container:n,children:e.jsxs(f.Content,{ref:i,className:Q("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,collisionBoundary:r,...o,children:[e.jsx(xe,{}),e.jsx(f.Viewport,{className:Q("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),e.jsx(ve,{})]})}));ye.displayName=f.Content.displayName;h.forwardRef(({className:t,...a},s)=>e.jsx(f.Label,{ref:s,className:Q("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a})).displayName=f.Label.displayName;const be=h.forwardRef(({className:t,children:a,...s},n)=>{const{showCheck:o}=h.useContext(ge);return e.jsxs(f.Item,{ref:n,className:Q("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",o?"pl-8":"pl-2","data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground data-[state=checked]:font-medium data-[state=checked]:border-l-2 data-[state=checked]:border-primary",o?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",t),...s,children:[o&&e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(f.ItemIndicator,{children:e.jsx(r.Check,{className:"h-4 w-4"})})}),e.jsx(f.ItemText,{children:a})]})});be.displayName=f.Item.displayName;h.forwardRef(({className:t,...a},s)=>e.jsx(f.Separator,{ref:s,className:Q("-mx-1 my-1 h-px bg-muted",t),...a})).displayName=f.Separator.displayName,exports.D4SignWidget=se,exports.DocumentSigner=function({file:s,onDocumentSigned:i,onError:c,showEventLog:l=!1}){const{user:d,alias:u}=$(),{config:m,isLoading:g}=z(),{t:h}=o.useTranslation(),[p,f]=t.useState(null),[x,v]=t.useState(!1),[y,b]=t.useState(null),[_,k]=t.useState("sandbox"),[w,S]=t.useState("clicksign"),[j,N]=t.useState(null),[T,I]=t.useState(null),[A,E]=t.useState(!1),[C,P]=t.useState(0),[L,R]=t.useState(!1),[V,U]=t.useState([]),D=t.useRef(null),O=t.useRef(null),q=t.useCallback(e=>{l&&U(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[l]),B=t.useCallback(async e=>{if(f(e),b(null),N(null),I(null),q(`Arquivo selecionado: ${e.name}`),u&&d){v(!0);try{const t=m?.provider??"clicksign";S(t),q(`Provedor resolvido: ${t}`);const s=new FileReader,r=await new Promise((t,a)=>{s.onload=()=>{const e=s.result;t(e)},s.onerror=a,s.readAsDataURL(e)});q(`Criando envelope para assinatura via ${t}...`);const o=await M.createEnvelopeWithSigner({alias:u,contentBase64:r,filename:e.name,signerEmail:d.email||"",signerName:d.name||"",provider:t});q(`Envelope criado: ${o.envelope_id}`),N({envelope_id:o.envelope_id,document_id:o.document_id,signer_email:o.signer_email,key_signer:o.signer_id}),k(o.environment),S(o.provider||t),"d4sign"===t?(q("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),b(o.document_id),n.toast.success(h("sign_doc_sent","Documento enviado! Assine abaixo."))):o.signer_id?(q(`Signer ID obtido: ${o.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),b(o.signer_id),n.toast.success(h("sign_doc_sent","Documento enviado! Assine abaixo."))):(q(a.t("sign_signer_unavailable")),n.toast.error(h("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),c?.(new Error(h("sign_signer_unavailable"))))}catch(t){const e=t instanceof Error?t:new Error(h("sign_process_error",h("sign_doc_process_error"))),s=e.message||"";s.includes("MONTHLY_LIMIT_REACHED")?(q(a.t("sign_monthly_limit")),n.toast.error(h("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(q(`Erro: ${s}`),n.toast.error(s)),c?.(e)}finally{v(!1)}}},[u,d,q,c,m]);t.useEffect(()=>{s&&u&&d&&!g&&s!==O.current&&(O.current=s,B(s))},[s,u,d,g,B]);const J=t.useCallback(async()=>{if(!j||!u)return;E(!0),P(0),R(!1),q("Buscando documento assinado...");for(let t=1;t<=6;t++){P(t),q(`Tentativa ${t}/6...`);try{const e=await M.getSignedDocument({alias:u,envelopeId:j.envelope_id,documentId:j.document_id,provider:w});if(e.download_url)return q(a.t("sign_doc_available")),I(e.download_url),void E(!1)}catch(e){q(`Erro na tentativa ${t}: ${e instanceof Error?e.message:h("unknown_error")}`)}t<6&&(q("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}q(a.t("sign_fetch_failed")),E(!1),R(!0)},[j,u,q,w]),F=t.useCallback(async()=>{q("Documento assinado com sucesso!"),n.toast.success(h("sign_signed_success","Documento assinado com sucesso!")),b(null),j&&u&&(i?.({success:!0,provider:w,envelope_id:j.envelope_id,document_id:j.document_id,signer_id:y||"",environment:_}),await J())},[q,i,j,y,u,_,w,J]);if(!u)return e.jsx(oe,{className:"border-amber-200 bg-amber-50",children:e.jsx(le,{className:"flex items-start gap-3 py-6",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-800",children:h("sign_auth_required","Autenticação necessária")}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:h("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const W="d4sign"===w?"D4Sign":"Clicksign",H=()=>l&&V.length>0?e.jsx("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:V.map((t,a)=>e.jsx("div",{children:t},a))}):null;return j&&!y&&(T||A||L)?e.jsxs("div",{className:"space-y-4",children:[e.jsx(oe,{className:"border-green-200 bg-green-50",children:e.jsxs(le,{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(r.CheckCircle2,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-green-800",children:h("sign_signed_success","Documento assinado com sucesso!")}),e.jsx("p",{className:"text-sm text-green-700 mt-1",children:p?.name})]}),A?e.jsxs("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.Loader2,{className:"h-4 w-4 animate-spin"}),h("sign_preparing_doc","Preparando documento assinado...")," (",h("sign_attempt","tentativa")," ",C,"/6)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("sign_waiting_provider",`Aguardando processamento pelo ${W}...`)})]}):T?e.jsx(re,{asChild:!0,variant:"default",className:"gap-2",children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(r.Download,{className:"h-4 w-4"}),h("sign_download_signed","Baixar documento assinado")]})}):L?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:h("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e.jsxs(re,{variant:"secondary",className:"gap-2",onClick:J,children:[e.jsx(r.RefreshCw,{className:"h-4 w-4"}),h("sign_try_again","Tentar novamente")]})]}):null]})}),e.jsx(H,{})]}):y?e.jsxs("div",{className:"space-y-4",children:["d4sign"===w?e.jsx(se,{documentKey:y,signerEmail:j?.signer_email||d?.email||"",signerName:d?.name,keySigner:j?.key_signer,environment:_,onSign:F,onError:c}):e.jsx(G,{signerId:y,environment:_,onSign:F,onError:c}),e.jsx(H,{})]}):s&&(x||g)?e.jsx(oe,{children:e.jsxs(le,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(r.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:h("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:D,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?B(t):n.toast.error(h("sign_select_pdf","Selecione um arquivo PDF"))}}),x?e.jsx(oe,{children:e.jsxs(le,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(r.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:h("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsx(oe,{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>D.current?.click(),children:e.jsxs(le,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx(r.Upload,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:h("sign_select_pdf","Selecione um arquivo PDF")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e.jsx(H,{})]})},exports.SignConfigForm=function({onSaved:a}){const{config:s,isLoading:i,saveConfig:c}=z(),{t:l}=o.useTranslation(),[d,u]=t.useState(""),[m,g]=t.useState("sandbox"),[h,p]=t.useState(!1);return t.useEffect(()=>{!i&&s&&(u(s.api_key),g(s.environment))},[s,i]),i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(r.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[s?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e.jsx(r.CheckCircle,{className:"h-4 w-4"}),e.jsx("span",{children:l("sign_configured",l("sign_configured_unit"))})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-600",children:[e.jsx(r.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{children:l("sign_not_configured",l("sign_not_configured_unit"))})]}),e.jsxs(oe,{children:[e.jsx(ie,{children:e.jsx(ce,{className:"text-base",children:l("sign_digital_config")})}),e.jsx(le,{children:e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),d.trim()){p(!0);try{await c(d.trim(),m),n.toast.success(l("sign_config_saved",l("sign_config_saved_success"))),a?.()}catch(t){n.toast.error(l("sign_config_save_error",l("sign_config_save_err")))}finally{p(!1)}}else n.toast.error(l("sign_api_key_required",l("sign_api_key_info")))},className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{htmlFor:"sign-api-key",children:"API Key"}),e.jsx(de,{id:"sign-api-key",type:"password",placeholder:l("sign_api_key_placeholder",l("sign_api_key_input")),value:d,onChange:e=>u(e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{children:l("sign_environment","Ambiente")}),e.jsxs(he,{value:m,onValueChange:e=>g(e),children:[e.jsx(fe,{children:e.jsx(pe,{})}),e.jsxs(ye,{children:[e.jsx(be,{value:"sandbox",children:"Sandbox (Testes)"}),e.jsx(be,{value:"production",children:"Produção"})]})]})]}),e.jsxs(re,{type:"submit",disabled:h,children:[h&&e.jsx(r.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),s?l("sign_update_config",l("sign_update_config_btn")):l("sign_save_config",l("sign_save_config_btn"))]})]})})]})]})},exports.SignWidget=G,exports.loadClicksignScript=K,exports.signService=M,exports.useSignConfig=z;
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react");require("@tanstack/react-query");var a=require("i18next"),s=require("@supabase/supabase-js"),n=require("sonner"),r=require("lucide-react"),o=require("react-i18next"),i=require("class-variance-authority"),c=require("clsx"),l=require("tailwind-merge");require("date-fns");var d=require("@radix-ui/react-slot"),u=require("@radix-ui/react-label"),m=require("@radix-ui/react-select");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,Object.freeze(t)}var h=g(t),p=g(u),f=g(m);class x{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const r=n[1];r.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(r),t=atob(e),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);const s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}catch(t){try{const e=this.normalizeBase64Url(r),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(r),t=atob(e);return JSON.parse(t)}catch(s){throw s}}}}catch(n){return null}}static validateTokens(e,t){const a=[],s=[];try{t.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(t),r=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}let o=!0;if(!r){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),o=!1}const i=Math.floor(Date.now()/1e3);if(r?.exp&&r.exp<i){const e="Access token expirado - pode precisar de refresh";a.push(e),o=!1}if(n.exp&&n.exp<i){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:a,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:a,errors:s}}catch(n){const e=`Erro na validação de tokens: ${n}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}x.LARGE_PAYLOAD_THRESHOLD=1e3;const v={storageProjectId:"ccjfvpnndclajkleyqkc",supabaseProjectId:"ccjfvpnndclajkleyqkc",supabaseUrl:"https://ccjfvpnndclajkleyqkc.supabase.co",supabasePublishableKey:"sb_publishable_w-TKU0hE4bjM_uOgt3fK1g_ewrXKJ8J",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},b={storageProjectId:"ccjfvpnndclajkleyqkc",supabaseProjectId:"tskpcuganynhsppzoqgj",supabaseUrl:"https://tskpcuganynhsppzoqgj.supabase.co",supabasePublishableKey:"sb_publishable_2EIWdYocxgrN4t_f64Ms3g_pKRcbHfL",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function y(){return"DEV"===(void 0).VITE_APP_ENV?"DEV":"PROD"}function _(){return"DEV"===y()?b:v}const k="qualiex_access_token",w="qualiex_id_token",S="supabase_token",j="oauth_state",N="oauth_nonce",T="selected_alias",I="manual_logout",E="supabase_project_id",A={setAccessToken:e=>localStorage.setItem(k,e),getAccessToken:()=>localStorage.getItem(k),setIdToken:e=>localStorage.setItem(w,e),getIdToken:()=>localStorage.getItem(w),getSupabaseToken:()=>localStorage.getItem(S),setOAuthState:e=>sessionStorage.setItem(j,e),getOAuthState:()=>sessionStorage.getItem(j),clearOAuthState:()=>sessionStorage.removeItem(j),setOAuthNonce:e=>sessionStorage.setItem(N,e),getOAuthNonce:()=>sessionStorage.getItem(N),clearOAuthNonce:()=>sessionStorage.removeItem(N),setSelectedAlias:e=>localStorage.setItem(T,e),getSelectedAlias:()=>localStorage.getItem(T),clearSelectedAlias:()=>localStorage.removeItem(T),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!A.getAccessToken()||!A.getIdToken()),checkProjectMismatch:()=>{const e=_().supabaseProjectId,t=localStorage.getItem(E);return t&&t!==e?(A.clearAll(),localStorage.setItem(E,e),!0):(t||localStorage.setItem(E,e),!1)},setSupabaseToken:e=>{localStorage.setItem(S,e),A._clearValidationCache()},areAllTokensValid:()=>{const e=A.getAccessToken(),t=A.getIdToken();if(!e||!t)return!1;try{const a=x.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=A.getAccessToken(),a=A.getIdToken(),s=A.getSupabaseToken();return t&&A.isTokenExpired(t)&&(localStorage.removeItem(k),e=!0),a&&A.isTokenExpired(a)&&(localStorage.removeItem(w),e=!0),s&&A.isTokenExpired(s)&&(localStorage.removeItem(S),e=!0),e},clearAll:()=>{localStorage.removeItem(k),localStorage.removeItem(w),localStorage.removeItem(S),localStorage.removeItem(T),sessionStorage.removeItem(j),sessionStorage.removeItem(N),A._clearValidationCache()},setManualLogout:()=>localStorage.setItem(I,"true"),isManualLogout:()=>"true"===localStorage.getItem(I),clearManualLogout:()=>localStorage.removeItem(I),isTokenExpired:e=>{try{return x.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{A._validationCache.isValid=!1,A._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=A.getSupabaseToken();if(!e)return!1;if(A.isTokenExpired(e))return A._clearValidationCache(),A._handleExpiredToken(),!1;const t=Date.now();return t-A._validationCache.timestamp<A._validationCache.cacheValidityMs?A._validationCache.isValid:(A._validationCache.isValid=!0,A._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>A.isSupabaseTokenValid()?A.getSupabaseToken():null,_handleExpiredToken:()=>{A.clearAll()},extractTokenData:()=>{if(!A.isSupabaseTokenValid())return null;const e=A.getSupabaseToken();if(!e)return null;try{const t=x.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,s=t.place_id||null,n=t.place_name||null;let r=t.company_id;if(!r&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===a){r=e[7];break}}}return{alias:a,companyId:r,placeId:s,placeName:n,payload:t}}catch(t){return A._handleExpiredToken(),null}},getCompanyId:e=>{const t=A.getAccessToken();if(t)try{const a=x.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(n){}const a=A.extractTokenData();if(a?.companyId)return a.companyId;const s=A.getIdToken();if(s)try{const t=x.parseJwtPayload(s);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const t=[A.getAccessToken(),A.getIdToken()];for(const a of t)if(a)try{const t=x.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=A.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=A.getIdToken();if(!e)return[];try{const t=x.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}};const C={get oauth(){const e=_();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}};(void 0).VITE_IS_QUALIEX;const P=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);n.toast.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?a.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?a.t("error_authentication"):t.includes("api")||t.includes("network")?a.t("error_connection"):"Erro"}success(e,t){n.toast.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function V(e){return!!e&&e.startsWith("eyJ")}function L(){const e=(void 0).VITE_SUPABASE_PK_OVERRIDE;return e||((void 0).VITE_SUPABASE_PUBLISHABLE_KEY??"")}let R=!1;function D(){if("DEV"===y()){const e=_();return{url:e.supabaseUrl,key:e.supabasePublishableKey}}const e=(void 0).VITE_SUPABASE_URL,t=L();return e&&t?{url:e,key:t}:null}class U{constructor(e){this.currentToken=null,this.config=e,function(){const e=(void 0).VITE_SUPABASE_PK_OVERRIDE,t=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;R?V(t):e&&V(t)?R=!0:V(t)?R=!0:R=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:this.config.key};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return s.createClient(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){if(!U.instance){const e=D();if(!e)throw new Error("[forlogic-core] Supabase não configurado. Defina VITE_SUPABASE_URL e VITE_SUPABASE_PUBLISHABLE_KEY no .env, ou não invoque getSupabaseClient() (use isSupabaseConfigured() para checar antes).");U.instance=new U(e)}return U.instance}getClient(){const e=A.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!x.isTokenExpired(e)}catch(t){return P.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function q(){return U.getInstance().getClient()}class O{static async generateToken(e,t,a,s=!1){try{if(!s){const e=A.getSupabaseToken();if(e&&A.isSupabaseTokenValid())return e}const n=q(),{data:r,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(a?.(),null):r?.access_token?(A.setSupabaseToken(r.access_token),r.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&a?.(),null}}}class B{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const t=A.getAccessToken(),a=A.getSelectedAlias();if(!t||!a)return null;const s=await O.generateToken(t,a,this.onLogoutCallback||void 0,e);return s||null}catch(t){return null}}}var $;B.regenerationPromise=null,B.onLogoutCallback=null;const z={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};$=class{static async initialize(){try{const e=!0;if(e){if(A.checkProjectMismatch())return{...z}}if(!A.hasAllTokens()||!A.areAllTokensValid())return A.clearExpiredTokens(),{...z};const t=A.getAccessToken(),a=A.getIdToken();A.clearManualLogout();const s=this.extractUserFromIdToken(a,t),n=this.extractCompaniesFromIdToken(a),r=this.extractAliasFromAccessToken(t),o=e?A.extractTokenData():null,i=o?.alias;let c=null;if(i&&n.some(e=>e.alias===i))c=i;else{const e=A.getSelectedAlias(),t=e&&n.some(t=>t.alias===e);c=t?e:r||n[0]?.alias||null}if(e&&(!A.isSupabaseTokenValid()&&c&&await B.attemptRegeneration(),!A.isSupabaseTokenValid()))return{...z};let l=null;if(c){const e=A.getCompanyId(c),t=n.find(e=>e.alias===c);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=o?.placeId??null,u=o?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:s,alias:c,companies:n,selectedUnit:l,userId:s?.id||null,userAlias:s?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{...z}}}static async loginDev(){try{const e=q(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";A.setOAuthState(e);const t=A.generateOAuthNonce();A.setOAuthNonce(t);const a=`${window.location.origin}/callback`,s=new URL(C.oauth.authUrl);s.searchParams.set("client_id",C.oauth.clientId),s.searchParams.set("response_type",C.oauth.responseType),s.searchParams.set("scope",C.oauth.scope),s.searchParams.set("redirect_uri",a),s.searchParams.set("state",e),s.searchParams.set("nonce",t),s.searchParams.set("response_mode","fragment"),window.location.href=s.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),s=a("access_token"),n=a("id_token"),r=a("error");if(r)throw new Error(`Erro OAuth: ${r}`);if(s&&n){const e=A.getAccessToken();e!==s&&A.clearAll()}const o=!0;if(A.hasAllTokens()){if(o){A.getValidSupabaseToken()||await B.attemptRegeneration(!0)}return!0}const i=s,c=n;if(!i||!c)throw new Error("Tokens não encontrados na URL de callback");A.setAccessToken(i),A.setIdToken(c),A.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)A.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(c);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");A.setSelectedAlias(e[0].alias)}if(o){if(!await B.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return A.clearOAuthState(),A.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){A.clearAll(),A.setManualLogout(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return x.parseJwtPayload(e)}static extractUserFromIdToken(e,t){const a=this.decodeToken(e);if(!a)return null;const s=t?this.decodeToken(t):null;return{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier,isSysAdmin:"1"===s?.admin}}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const s=t[e].split(";");if(s.length>=4)a.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,n]=t[e].split("|");s&&n&&a.push({id:"",alias:s.trim(),name:n.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}},B.setLogoutCallback(()=>{$.logout()});const J=t.createContext(void 0),F=()=>{const e=t.useContext(J);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function K(){const{alias:e}=F(),[a,s]=t.useState(null),[n,r]=t.useState(!0);t.useEffect(()=>{if(!e)return void r(!1);let t=!1;return(async()=>{r(!0);try{const a=q(),{data:n,error:r}=await a.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||s(n)}catch(a){t||s(null)}finally{t||r(!1)}})(),()=>{t=!0}},[e]);return{config:a,isLoading:n,saveConfig:t.useCallback(async(t,a)=>{if(!e)throw new Error("Alias not available");const n=q(),{data:r,error:o}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:a,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return s(r),r},[e])}}const M=(void 0).VITE_SUPABASE_URL,W=L();async function H(e,t,a){const s=A.getSupabaseToken(),n={"Content-Type":"application/json",apikey:W};s&&(n.Authorization=`Bearer ${s}`);const r=await fetch(`${M}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:t,data:a})});if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${r.status}`)}return r}const Y={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await H(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await H(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let G=null;function X(){return window.Clicksign?Promise.resolve():G||(G=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),G)}const Q="clicksign-container";function Z({signerId:a,environment:s="sandbox",onSign:n,onError:i,onClose:c}){const{t:l}=o.useTranslation(),d=t.useRef(null),[u,m]=t.useState(!0),[g,h]=t.useState(null);return t.useEffect(()=>{let e=!1;return d.current&&(d.current.unmount(),d.current=null),h(null),m(!0),X().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===s?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(Q),t.on("loaded",function(){m(!1)}),t.on("signed",function(){n?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(Q);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){m(!1),i?.(e instanceof Error?e:new Error(l("sign_widget_error")))}),t.on("closed",function(){c?.()}),d.current=t}).catch(t=>{e||(h("Falha ao carregar o script de assinatura."),m(!1),i?.(t))}),()=>{e=!0,d.current&&(d.current.unmount(),d.current=null)}},[a,s]),e.jsxs("div",{className:"relative h-full",children:[u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(r.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),g&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-destructive",children:g})}),e.jsx("div",{id:Q,style:{height:"600px"}})]})}function ee(...e){return l.twMerge(c.clsx(e))}const te=i.cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ae={info:r.Info,warning:r.Info,danger:r.AlertTriangle,success:r.CheckCircle},se=h.forwardRef(({className:t,variant:a="info",showIcon:s=!0,children:n,...r},o)=>{const i=ae[a||"info"];return e.jsxs("div",{ref:o,role:"alert",className:ee(te({variant:a}),t),...r,children:[s&&e.jsx(i,{className:"h-4 w-4"}),n]})});se.displayName="Alert";const ne=h.forwardRef(({className:t,...a},s)=>e.jsx("h5",{ref:s,className:ee("mb-1 font-medium leading-none tracking-tight",t),...a}));ne.displayName="AlertTitle";const re=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:ee("text-sm [&_p]:leading-relaxed",t),...a}));re.displayName="AlertDescription";function oe({documentKey:s,signerEmail:n,signerName:o,keySigner:i,environment:c,onSign:l,onError:d}){const u=t.useRef(null),[m,g]=t.useState("loading"),[h,p]=t.useState(null),f="production"===c?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",x=(()=>{const e=new URLSearchParams({email:n,display_name:o||"",disable_preview:"0"});return i&&e.set("key_signer",i),`${f}/${s}?${e.toString()}`})(),v=t.useCallback(e=>"signed"===e.data?(g("ready"),void l?.()):"wrong-data"===e.data?(g("error"),p(a.t("sign_incorrect_data")),void d?.(new Error(a.t("sign_incorrect_data")))):void 0,[l,d]);t.useEffect(()=>(window.addEventListener("message",v,!1),()=>{window.removeEventListener("message",v,!1)}),[v]);const b=t.useCallback(()=>{"loading"===m&&g("ready")},[m]);return"error"===m?e.jsxs(se,{variant:"danger",className:"my-4",children:[e.jsx(ne,{children:a.t("sign_doc_load_error")}),e.jsx(re,{children:h||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e.jsxs("div",{className:"relative h-full",children:["loading"===m&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(r.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),e.jsx("iframe",{ref:u,id:"d4sign-container",src:x,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:b})]})}const ie=i.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),ce=h.forwardRef(({className:t,variant:a,size:s,asChild:n=!1,...r},o)=>{const i=n?d.Slot:"button";return e.jsx(i,{className:ee(ie({variant:a,size:s,className:t})),ref:o,...r})});ce.displayName="Button";const le=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));le.displayName="Card";const de=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:ee("flex flex-col space-y-1.5 p-6",t),...a}));de.displayName="CardHeader";const ue=h.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:ee("text-2xl font-semibold leading-none tracking-tight",t),...a}));ue.displayName="CardTitle";h.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:ee("text-sm text-muted-foreground",t),...a})).displayName="CardDescription";const me=h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:ee("p-6 pt-0",t),...a}));me.displayName="CardContent";h.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:ee("flex items-center p-6 pt-0",t),...a})).displayName="CardFooter";const ge=h.forwardRef(({className:t,type:a,showCharCount:s,maxLength:n,onChange:r,...o},i)=>{const[c,l]=h.useState(0);h.useEffect(()=>{"string"==typeof o.value?l(o.value.length):"string"==typeof o.defaultValue&&l(o.defaultValue.length)},[o.value,o.defaultValue]);return e.jsxs("div",{className:"w-full",children:[e.jsx("input",{type:a,className:ee("flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",t),ref:i,maxLength:n,onChange:e=>{l(e.target.value.length),r?.(e)},...o}),s&&n&&e.jsxs("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[c," / ",n]})]})});ge.displayName="Input";const he=i.cva("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),pe=h.forwardRef(({className:t,...a},s)=>e.jsx(p.Root,{ref:s,className:ee(he(),t),...a}));pe.displayName=p.Root.displayName;const fe=h.createContext({showCheck:!1}),xe=({showCheck:t=!1,...a})=>e.jsx(fe.Provider,{value:{showCheck:t},children:e.jsx(f.Root,{...a})}),ve=f.Value,be=h.forwardRef(({className:t,children:a,...s},n)=>e.jsxs(f.Trigger,{ref:n,className:ee("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",t),...s,children:[a,e.jsx(f.Icon,{asChild:!0,children:e.jsx(r.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));be.displayName=f.Trigger.displayName;const ye=h.forwardRef(({className:t,...a},s)=>e.jsx(f.ScrollUpButton,{ref:s,className:ee("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(r.ChevronUp,{className:"h-4 w-4"})}));ye.displayName=f.ScrollUpButton.displayName;const _e=h.forwardRef(({className:t,...a},s)=>e.jsx(f.ScrollDownButton,{ref:s,className:ee("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(r.ChevronDown,{className:"h-4 w-4"})}));_e.displayName=f.ScrollDownButton.displayName;const ke=h.forwardRef(({className:t,children:a,position:s="popper",container:n,collisionBoundary:r,...o},i)=>e.jsx(f.Portal,{container:n,children:e.jsxs(f.Content,{ref:i,className:ee("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,collisionBoundary:r,...o,children:[e.jsx(ye,{}),e.jsx(f.Viewport,{className:ee("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),e.jsx(_e,{})]})}));ke.displayName=f.Content.displayName;h.forwardRef(({className:t,...a},s)=>e.jsx(f.Label,{ref:s,className:ee("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a})).displayName=f.Label.displayName;const we=h.forwardRef(({className:t,children:a,...s},n)=>{const{showCheck:o}=h.useContext(fe);return e.jsxs(f.Item,{ref:n,className:ee("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",o?"pl-8":"pl-2","data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground data-[state=checked]:font-medium data-[state=checked]:border-l-2 data-[state=checked]:border-primary",o?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",t),...s,children:[o&&e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(f.ItemIndicator,{children:e.jsx(r.Check,{className:"h-4 w-4"})})}),e.jsx(f.ItemText,{children:a})]})});we.displayName=f.Item.displayName;h.forwardRef(({className:t,...a},s)=>e.jsx(f.Separator,{ref:s,className:ee("-mx-1 my-1 h-px bg-muted",t),...a})).displayName=f.Separator.displayName,exports.D4SignWidget=oe,exports.DocumentSigner=function({file:s,onDocumentSigned:i,onError:c,showEventLog:l=!1}){const{user:d,alias:u}=F(),{config:m,isLoading:g}=K(),{t:h}=o.useTranslation(),[p,f]=t.useState(null),[x,v]=t.useState(!1),[b,y]=t.useState(null),[_,k]=t.useState("sandbox"),[w,S]=t.useState("clicksign"),[j,N]=t.useState(null),[T,I]=t.useState(null),[E,A]=t.useState(!1),[C,P]=t.useState(0),[V,L]=t.useState(!1),[R,D]=t.useState([]),U=t.useRef(null),q=t.useRef(null),O=t.useCallback(e=>{l&&D(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[l]),B=t.useCallback(async e=>{if(f(e),y(null),N(null),I(null),O(`Arquivo selecionado: ${e.name}`),u&&d){v(!0);try{const t=m?.provider??"clicksign";S(t),O(`Provedor resolvido: ${t}`);const s=new FileReader,r=await new Promise((t,a)=>{s.onload=()=>{const e=s.result;t(e)},s.onerror=a,s.readAsDataURL(e)});O(`Criando envelope para assinatura via ${t}...`);const o=await Y.createEnvelopeWithSigner({alias:u,contentBase64:r,filename:e.name,signerEmail:d.email||"",signerName:d.name||"",provider:t});O(`Envelope criado: ${o.envelope_id}`),N({envelope_id:o.envelope_id,document_id:o.document_id,signer_email:o.signer_email,key_signer:o.signer_id}),k(o.environment),S(o.provider||t),"d4sign"===t?(O("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),y(o.document_id),n.toast.success(h("sign_doc_sent","Documento enviado! Assine abaixo."))):o.signer_id?(O(`Signer ID obtido: ${o.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),y(o.signer_id),n.toast.success(h("sign_doc_sent","Documento enviado! Assine abaixo."))):(O(a.t("sign_signer_unavailable")),n.toast.error(h("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),c?.(new Error(h("sign_signer_unavailable"))))}catch(t){const e=t instanceof Error?t:new Error(h("sign_process_error",h("sign_doc_process_error"))),s=e.message||"";s.includes("MONTHLY_LIMIT_REACHED")?(O(a.t("sign_monthly_limit")),n.toast.error(h("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(O(`Erro: ${s}`),n.toast.error(s)),c?.(e)}finally{v(!1)}}},[u,d,O,c,m]);t.useEffect(()=>{s&&u&&d&&!g&&s!==q.current&&(q.current=s,B(s))},[s,u,d,g,B]);const $=t.useCallback(async()=>{if(!j||!u)return;A(!0),P(0),L(!1),O("Buscando documento assinado...");for(let t=1;t<=6;t++){P(t),O(`Tentativa ${t}/6...`);try{const e=await Y.getSignedDocument({alias:u,envelopeId:j.envelope_id,documentId:j.document_id,provider:w});if(e.download_url)return O(a.t("sign_doc_available")),I(e.download_url),void A(!1)}catch(e){O(`Erro na tentativa ${t}: ${e instanceof Error?e.message:h("unknown_error")}`)}t<6&&(O("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}O(a.t("sign_fetch_failed")),A(!1),L(!0)},[j,u,O,w]),z=t.useCallback(async()=>{O("Documento assinado com sucesso!"),n.toast.success(h("sign_signed_success","Documento assinado com sucesso!")),y(null),j&&u&&(i?.({success:!0,provider:w,envelope_id:j.envelope_id,document_id:j.document_id,signer_id:b||"",environment:_}),await $())},[O,i,j,b,u,_,w,$]);if(!u)return e.jsx(le,{className:"border-amber-200 bg-amber-50",children:e.jsx(me,{className:"flex items-start gap-3 py-6",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-800",children:h("sign_auth_required","Autenticação necessária")}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:h("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const J="d4sign"===w?"D4Sign":"Clicksign",M=()=>l&&R.length>0?e.jsx("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:R.map((t,a)=>e.jsx("div",{children:t},a))}):null;return j&&!b&&(T||E||V)?e.jsxs("div",{className:"space-y-4",children:[e.jsx(le,{className:"border-green-200 bg-green-50",children:e.jsxs(me,{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(r.CheckCircle2,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-green-800",children:h("sign_signed_success","Documento assinado com sucesso!")}),e.jsx("p",{className:"text-sm text-green-700 mt-1",children:p?.name})]}),E?e.jsxs("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.Loader2,{className:"h-4 w-4 animate-spin"}),h("sign_preparing_doc","Preparando documento assinado...")," (",h("sign_attempt","tentativa")," ",C,"/6)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("sign_waiting_provider",`Aguardando processamento pelo ${J}...`)})]}):T?e.jsx(ce,{asChild:!0,variant:"default",className:"gap-2",children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(r.Download,{className:"h-4 w-4"}),h("sign_download_signed","Baixar documento assinado")]})}):V?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:h("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e.jsxs(ce,{variant:"secondary",className:"gap-2",onClick:$,children:[e.jsx(r.RefreshCw,{className:"h-4 w-4"}),h("sign_try_again","Tentar novamente")]})]}):null]})}),e.jsx(M,{})]}):b?e.jsxs("div",{className:"space-y-4",children:["d4sign"===w?e.jsx(oe,{documentKey:b,signerEmail:j?.signer_email||d?.email||"",signerName:d?.name,keySigner:j?.key_signer,environment:_,onSign:z,onError:c}):e.jsx(Z,{signerId:b,environment:_,onSign:z,onError:c}),e.jsx(M,{})]}):s&&(x||g)?e.jsx(le,{children:e.jsxs(me,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(r.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:h("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:U,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?B(t):n.toast.error(h("sign_select_pdf","Selecione um arquivo PDF"))}}),x?e.jsx(le,{children:e.jsxs(me,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(r.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:h("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsx(le,{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>U.current?.click(),children:e.jsxs(me,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx(r.Upload,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:h("sign_select_pdf","Selecione um arquivo PDF")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e.jsx(M,{})]})},exports.SignConfigForm=function({onSaved:a}){const{config:s,isLoading:i,saveConfig:c}=K(),{t:l}=o.useTranslation(),[d,u]=t.useState(""),[m,g]=t.useState("sandbox"),[h,p]=t.useState(!1);return t.useEffect(()=>{!i&&s&&(u(s.api_key),g(s.environment))},[s,i]),i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(r.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[s?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e.jsx(r.CheckCircle,{className:"h-4 w-4"}),e.jsx("span",{children:l("sign_configured",l("sign_configured_unit"))})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-600",children:[e.jsx(r.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{children:l("sign_not_configured",l("sign_not_configured_unit"))})]}),e.jsxs(le,{children:[e.jsx(de,{children:e.jsx(ue,{className:"text-base",children:l("sign_digital_config")})}),e.jsx(me,{children:e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),d.trim()){p(!0);try{await c(d.trim(),m),n.toast.success(l("sign_config_saved",l("sign_config_saved_success"))),a?.()}catch(t){n.toast.error(l("sign_config_save_error",l("sign_config_save_err")))}finally{p(!1)}}else n.toast.error(l("sign_api_key_required",l("sign_api_key_info")))},className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{htmlFor:"sign-api-key",children:"API Key"}),e.jsx(ge,{id:"sign-api-key",type:"password",placeholder:l("sign_api_key_placeholder",l("sign_api_key_input")),value:d,onChange:e=>u(e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{children:l("sign_environment","Ambiente")}),e.jsxs(xe,{value:m,onValueChange:e=>g(e),children:[e.jsx(be,{children:e.jsx(ve,{})}),e.jsxs(ke,{children:[e.jsx(we,{value:"sandbox",children:"Sandbox (Testes)"}),e.jsx(we,{value:"production",children:"Produção"})]})]})]}),e.jsxs(ce,{type:"submit",disabled:h,children:[h&&e.jsx(r.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),s?l("sign_update_config",l("sign_update_config_btn")):l("sign_save_config",l("sign_save_config_btn"))]})]})})]})]})},exports.SignWidget=Z,exports.loadClicksignScript=X,exports.signService=Y,exports.useSignConfig=K;
|
package/dist/vite/index.esm.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { loadEnv } from 'vite';
|
|
2
|
+
|
|
1
3
|
const DEFAULT_SCRIPT_SRC = [
|
|
2
4
|
"'self'",
|
|
3
5
|
"https://cdn.gpteng.co",
|
|
@@ -207,4 +209,25 @@ function createForlogicViteConfig(options = {}) {
|
|
|
207
209
|
}
|
|
208
210
|
const defaultForlogicViteConfig = createForlogicViteConfig();
|
|
209
211
|
|
|
210
|
-
|
|
212
|
+
function resolveSupabaseEnv(mode, cwd = process.cwd()) {
|
|
213
|
+
const env = loadEnv(mode, cwd, "");
|
|
214
|
+
const url = env.VITE_SUPABASE_URL || env.SUPABASE_URL || "";
|
|
215
|
+
const publishableKey = env.VITE_SUPABASE_PUBLISHABLE_KEY || env.SUPABASE_PUBLISHABLE_KEY || "";
|
|
216
|
+
const pkOverride = env.VITE_SUPABASE_PK_OVERRIDE || "";
|
|
217
|
+
let projectId = env.VITE_SUPABASE_PROJECT_ID || env.SUPABASE_PROJECT_ID || "";
|
|
218
|
+
if (!projectId && url) {
|
|
219
|
+
try {
|
|
220
|
+
projectId = new URL(url).hostname.split(".")[0];
|
|
221
|
+
} catch {
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const define = {
|
|
225
|
+
"import.meta.env.VITE_SUPABASE_URL": JSON.stringify(url),
|
|
226
|
+
"import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY": JSON.stringify(publishableKey),
|
|
227
|
+
"import.meta.env.VITE_SUPABASE_PROJECT_ID": JSON.stringify(projectId),
|
|
228
|
+
"import.meta.env.VITE_SUPABASE_PK_OVERRIDE": JSON.stringify(pkOverride)
|
|
229
|
+
};
|
|
230
|
+
return { url, publishableKey, projectId, pkOverride, define };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export { createForlogicViteConfig, createSecurityHeadersPlugin, defaultForlogicViteConfig, generateCSPPolicy, resolveSupabaseEnv };
|
package/dist/vite/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var vite = require('vite');
|
|
4
|
+
|
|
3
5
|
const DEFAULT_SCRIPT_SRC = [
|
|
4
6
|
"'self'",
|
|
5
7
|
"https://cdn.gpteng.co",
|
|
@@ -209,7 +211,29 @@ function createForlogicViteConfig(options = {}) {
|
|
|
209
211
|
}
|
|
210
212
|
const defaultForlogicViteConfig = createForlogicViteConfig();
|
|
211
213
|
|
|
214
|
+
function resolveSupabaseEnv(mode, cwd = process.cwd()) {
|
|
215
|
+
const env = vite.loadEnv(mode, cwd, "");
|
|
216
|
+
const url = env.VITE_SUPABASE_URL || env.SUPABASE_URL || "";
|
|
217
|
+
const publishableKey = env.VITE_SUPABASE_PUBLISHABLE_KEY || env.SUPABASE_PUBLISHABLE_KEY || "";
|
|
218
|
+
const pkOverride = env.VITE_SUPABASE_PK_OVERRIDE || "";
|
|
219
|
+
let projectId = env.VITE_SUPABASE_PROJECT_ID || env.SUPABASE_PROJECT_ID || "";
|
|
220
|
+
if (!projectId && url) {
|
|
221
|
+
try {
|
|
222
|
+
projectId = new URL(url).hostname.split(".")[0];
|
|
223
|
+
} catch {
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const define = {
|
|
227
|
+
"import.meta.env.VITE_SUPABASE_URL": JSON.stringify(url),
|
|
228
|
+
"import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY": JSON.stringify(publishableKey),
|
|
229
|
+
"import.meta.env.VITE_SUPABASE_PROJECT_ID": JSON.stringify(projectId),
|
|
230
|
+
"import.meta.env.VITE_SUPABASE_PK_OVERRIDE": JSON.stringify(pkOverride)
|
|
231
|
+
};
|
|
232
|
+
return { url, publishableKey, projectId, pkOverride, define };
|
|
233
|
+
}
|
|
234
|
+
|
|
212
235
|
exports.createForlogicViteConfig = createForlogicViteConfig;
|
|
213
236
|
exports.createSecurityHeadersPlugin = createSecurityHeadersPlugin;
|
|
214
237
|
exports.defaultForlogicViteConfig = defaultForlogicViteConfig;
|
|
215
238
|
exports.generateCSPPolicy = generateCSPPolicy;
|
|
239
|
+
exports.resolveSupabaseEnv = resolveSupabaseEnv;
|
|
@@ -87,7 +87,7 @@ supabase.from('tabela').select('*');
|
|
|
87
87
|
|
|
88
88
|
| Modo | Quando usar | Envs exigidas |
|
|
89
89
|
|------|-------------|---------------|
|
|
90
|
-
| `'supabase'` (default) | App usa tabelas/edge functions do Supabase | `
|
|
90
|
+
| `'supabase'` (default) | App usa tabelas/edge functions do Supabase | `SUPABASE_URL` + `SUPABASE_PUBLISHABLE_KEY` (ou `VITE_SUPABASE_*` legadas — consolidadas pelo `resolveSupabaseEnv()` no `vite.config.ts`) + `VITE_SUPABASE_PK_OVERRIDE` |
|
|
91
91
|
| `'dotnet'` | App consome apenas a API .NET do Qualiex (ex.: Documentos) | nenhuma do Supabase |
|
|
92
92
|
|
|
93
93
|
```tsx
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
|
|
40
40
|
A prop `backend` controla se a lib usa o stack Supabase ou apenas a API .NET do Qualiex.
|
|
41
41
|
|
|
42
|
-
- `'supabase'` (default, retrocompat): inicializa o cliente Supabase, valida tokens via Edge Function `validate-token` e exige `
|
|
43
|
-
- `'dotnet'`: a lib **não** chama Supabase em nenhum momento da inicialização. O `AuthProvider` autentica apenas com os tokens OAuth do Qualiex (`access_token` + `id_token`). Não exige envs do Supabase.
|
|
42
|
+
- `'supabase'` (default, retrocompat): inicializa o cliente Supabase, valida tokens via Edge Function `validate-token` e exige `SUPABASE_URL` + `SUPABASE_PUBLISHABLE_KEY` (ou as versões `VITE_SUPABASE_*` legadas) no `.env`. O `vite.config.ts` consolida ambos os formatos via `resolveSupabaseEnv()` — ver `docs/design-system/patterns/feature-flags.md`.
|
|
43
|
+
- `'dotnet'`: a lib **não** chama Supabase em nenhum momento da inicialização. O `AuthProvider` autentica apenas com os tokens OAuth do Qualiex (`access_token` + `id_token`). Não exige envs do Supabase. **Importante:** defina `VITE_APP_ENV="DEV"` no `.env` quando o app rodar contra o ambiente dev do Qualiex — sem essa variável, o failsafe assume `PROD`.
|
|
44
44
|
|
|
45
45
|
```tsx
|
|
46
46
|
// Módulo sem Supabase (ex.: Documentos)
|
|
@@ -49,6 +49,15 @@ A prop `backend` controla se a lib usa o stack Supabase ou apenas a API .NET do
|
|
|
49
49
|
</CoreProviders>
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
+
### O que funciona sem Supabase em `backend="dotnet"`
|
|
53
|
+
|
|
54
|
+
A lib mantém os seguintes recursos funcionando 100% sem nenhuma env var Supabase:
|
|
55
|
+
|
|
56
|
+
- **Logos e favicon** (`assets`, `logoSrc`, `smallLogoSrc`): servidos a partir de bucket público fixo embutido na lib.
|
|
57
|
+
- **Login automático em dev/preview**: `shouldUseDevTokens()` agora exige modo Supabase, então em modo dotnet o `ProtectedRoute` sempre vai para `loginProd()` (OAuth real), mesmo em `localhost`/Lovable preview.
|
|
58
|
+
- **Logoff manual**: `TokenManager.clearAll()` preserva o flag `manual_logout`, garantindo que `logout()` realmente deslogue (sem auto-login no próximo render).
|
|
59
|
+
- **`LegacyKeyBanner`**: oculto automaticamente em modo dotnet.
|
|
60
|
+
|
|
52
61
|
### Features que continuam exigindo Supabase
|
|
53
62
|
|
|
54
63
|
Mesmo com `backend="dotnet"`, se você importar qualquer um dos módulos abaixo eles vão falhar em runtime sem Supabase configurado:
|