forlogic-core 2.3.1 → 2.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action-plans/index.esm.js +1 -1
- package/dist/action-plans/index.js +1 -1
- package/dist/audit-trail/index.esm.js +1 -1
- package/dist/audit-trail/index.js +1 -1
- package/dist/leadership/index.esm.js +1 -1
- package/dist/leadership/index.js +1 -1
- package/dist/places/index.esm.js +1 -1
- package/dist/places/index.js +1 -1
- package/dist/sign/index.esm.js +1 -1
- package/dist/sign/index.js +1 -1
- package/package.json +1 -1
package/dist/places/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as a}from"react/jsx-runtime";import*as t from"react";import{useMemo as r,createContext as s,useContext as o,useState as n}from"react";import{Check as i,ChevronRight as l,Circle as c,Edit as d,PowerOff as m,Power as u,Trash2 as p,EllipsisVertical as h,ChevronDown as f,ChevronUp as g,X as y,Users as b,Search as x,Crown as v,UserPlus as w,Building2 as N,Settings as k}from"lucide-react";import*as A from"@radix-ui/react-collapsible";import{cva as I}from"class-variance-authority";import{clsx as T}from"clsx";import{twMerge as E}from"tailwind-merge";import"date-fns";import{toast as C}from"sonner";import*as S from"@radix-ui/react-separator";import*as _ from"@radix-ui/react-checkbox";import*as R from"@radix-ui/react-tooltip";import{useTranslation as P}from"react-i18next";import{Slot as U}from"@radix-ui/react-slot";import*as D from"@radix-ui/react-dropdown-menu";import*as V from"@radix-ui/react-select";import*as z from"@radix-ui/react-hover-card";import L from"i18next";import{useQuery as M}from"@tanstack/react-query";import{createClient as O}from"@supabase/supabase-js";import*as j from"@radix-ui/react-dialog";import*as B from"@radix-ui/react-alert-dialog";import*as H from"@radix-ui/react-scroll-area";const W=A.Root,q=A.CollapsibleTrigger,$=A.CollapsibleContent;function J(...e){return E(T(e))}const K=I("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Q=t.forwardRef(({className:a,variant:t,...r},s)=>e("div",{ref:s,className:J(K({variant:t}),a),...r}));Q.displayName="Badge";const F=t.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...s},o)=>e(S.Root,{ref:o,decorative:r,orientation:t,className:J("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...s}));F.displayName=S.Root.displayName;t.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:J("w-full caption-bottom text-[13px] table-fixed",a),...t})).displayName="Table";t.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:J("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t})).displayName="TableHeader";t.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:J("[&_tr:last-child]:border-0",a),...t})).displayName="TableBody";t.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:J("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t})).displayName="TableFooter";t.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:J("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t})).displayName="TableRow";t.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:J("h-9 px-4 py-2 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t})).displayName="TableHead";t.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:J("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t})).displayName="TableCell";function G({className:a,...t}){return e("div",{className:J("animate-pulse rounded-md bg-muted",a),...t})}t.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:J("mt-4 text-sm text-muted-foreground",a),...t})).displayName="TableCaption";const Y=t.forwardRef(({className:a,...t},r)=>e(_.Root,{ref:r,className:J("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e(_.Indicator,{className:J("flex items-center justify-center text-current"),children:e(i,{className:"h-4 w-4"})})}));Y.displayName=_.Root.displayName;const X=({delayDuration:a=300,...t})=>e(R.Provider,{delayDuration:a,...t}),Z=R.Root,ee=R.Trigger,ae=t.forwardRef(({className:a,sideOffset:t=4,container:r,...s},o)=>e(R.Portal,{container:r,children:e(R.Content,{ref:o,sideOffset:t,className:J("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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",a),...s})}));ae.displayName=R.Content.displayName;t.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:s},o)=>{const n="horizontal"===a;return e("div",{ref:o,onMouseDown:t,className:J("absolute z-20 select-none touch-none","transition-colors duration-150",n&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!n&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",s),children:e("div",{className:J("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",n?"h-6 w-0.5":"w-6 h-0.5")})})}).displayName="TableResizeHandle";const te=I("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=t.forwardRef(({className:a,variant:t,size:r,asChild:s=!1,...o},n)=>e(s?U:"button",{className:J(te({variant:t,size:r,className:a})),ref:n,...o}));re.displayName="Button";const se=D.Root,oe=D.Trigger;t.forwardRef(({className:t,inset:r,children:s,...o},n)=>a(D.SubTrigger,{ref:n,className:J("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...o,children:[s,e(l,{className:"ml-auto h-4 w-4"})]})).displayName=D.SubTrigger.displayName;t.forwardRef(({className:a,...t},r)=>e(D.SubContent,{ref:r,className:J("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg 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",a),...t})).displayName=D.SubContent.displayName;const ne=t.forwardRef(({className:a,sideOffset:t=4,...r},s)=>e(D.Portal,{children:e(D.Content,{ref:s,sideOffset:t,className:J("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg 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",a),...r})}));ne.displayName=D.Content.displayName;const ie=t.forwardRef(({className:a,inset:t,...r},s)=>e(D.Item,{ref:s,className:J("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));ie.displayName=D.Item.displayName;t.forwardRef(({className:t,children:r,checked:s,...o},n)=>a(D.CheckboxItem,{ref:n,className:J("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...o,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(D.ItemIndicator,{children:e(i,{className:"h-4 w-4"})})}),r]})).displayName=D.CheckboxItem.displayName;t.forwardRef(({className:t,children:r,...s},o)=>a(D.RadioItem,{ref:o,className:J("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(D.ItemIndicator,{children:e(c,{className:"h-2 w-2 fill-current"})})}),r]})).displayName=D.RadioItem.displayName;t.forwardRef(({className:a,inset:t,...r},s)=>e(D.Label,{ref:s,className:J("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r})).displayName=D.Label.displayName;t.forwardRef(({className:a,...t},r)=>e(D.Separator,{ref:r,className:J("-mx-1 my-1 h-px bg-muted",a),...t})).displayName=D.Separator.displayName;const le=t.forwardRef(({children:t,disabledReason:r,className:s},o)=>{const n=e(ie,{ref:o,className:J("opacity-50 cursor-not-allowed pointer-events-auto",s),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return r?e(X,{delayDuration:100,children:a(Z,{children:[e(ee,{asChild:!0,children:e("div",{className:"w-full",children:n})}),e(ae,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):n});function ce({onEdit:t,onDelete:s,onToggleStatus:o,isActive:n=!0,canEdit:i=!0,canDelete:l=!0,customActions:c=[],renderAs:f="dropdown",variant:g="default"}){const{t:y}=P(),b=r(()=>{const e=[];return t&&i&&e.push({key:"edit",icon:d,label:y("edit","Editar"),onClick:t,variant:"default"}),o&&e.push({key:"toggle-status",icon:n?m:u,label:n?y("deactivate","Inativar"):y("activate","Ativar"),onClick:o,variant:"default"}),c.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),s&&l&&e.push({key:"delete",icon:p,label:y("remove","Remover"),onClick:s,variant:"destructive"}),e},[t,s,o,n,i,l,c,y]);return 0===b.length?null:"dropdown"===f?e(X,{delayDuration:200,children:a(se,{children:[e(oe,{asChild:!0,children:e(re,{variant:"ghost",size:"compact"===g?"sm":"default",className:"compact"===g?"h-7 px-2":"",children:e(h,{size:"compact"===g?14:16})})}),e(ne,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:b.map(t=>t.disabled?a(le,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):a(ie,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e("div",{className:"flex items-center gap-1",children:b.map(t=>a(re,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===g?"sm":"default",onClick:t.onClick,className:"compact"===g?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===g?14:16}),"compact"!==g&&e("span",{className:"ml-1",children:t.label})]},t.key))})}le.displayName="DisabledMenuItem";const de=t.createContext({showCheck:!1});t.forwardRef(({className:t,children:r,...s},o)=>a(V.Trigger,{ref:o,className:J("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:[r,e(V.Icon,{asChild:!0,children:e(f,{className:"h-4 w-4 opacity-50"})})]})).displayName=V.Trigger.displayName;const me=t.forwardRef(({className:a,...t},r)=>e(V.ScrollUpButton,{ref:r,className:J("flex cursor-default items-center justify-center py-1",a),...t,children:e(g,{className:"h-4 w-4"})}));me.displayName=V.ScrollUpButton.displayName;const ue=t.forwardRef(({className:a,...t},r)=>e(V.ScrollDownButton,{ref:r,className:J("flex cursor-default items-center justify-center py-1",a),...t,children:e(f,{className:"h-4 w-4"})}));ue.displayName=V.ScrollDownButton.displayName;t.forwardRef(({className:t,children:r,position:s="popper",container:o,collisionBoundary:n,...i},l)=>e(V.Portal,{container:o,children:a(V.Content,{ref:l,className:J("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:n,...i,children:[e(me,{}),e(V.Viewport,{className:J("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(ue,{})]})})).displayName=V.Content.displayName;t.forwardRef(({className:a,...t},r)=>e(V.Label,{ref:r,className:J("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t})).displayName=V.Label.displayName;t.forwardRef(({className:r,children:s,...o},n)=>{const{showCheck:l}=t.useContext(de);return a(V.Item,{ref:n,className:J("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",l?"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",l?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",r),...o,children:[l&&e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(V.ItemIndicator,{children:e(i,{className:"h-4 w-4"})})}),e(V.ItemText,{children:s})]})}).displayName=V.Item.displayName;t.forwardRef(({className:a,...t},r)=>e(V.Separator,{ref:r,className:J("-mx-1 my-1 h-px bg-muted",a),...t})).displayName=V.Separator.displayName;const pe=t.forwardRef(({className:r,type:s,showCharCount:o,maxLength:n,onChange:i,...l},c)=>{const[d,m]=t.useState(0);t.useEffect(()=>{"string"==typeof l.value?m(l.value.length):"string"==typeof l.defaultValue&&m(l.defaultValue.length)},[l.value,l.defaultValue]);return a("div",{className:"w-full",children:[e("input",{type:s,className:J("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",r),ref:c,maxLength:n,onChange:e=>{m(e.target.value.length),i?.(e)},...l}),o&&n&&a("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",n]})]})});pe.displayName="Input";t.forwardRef(({className:a,align:t="center",sideOffset:r=4,...s},o)=>e(z.Content,{ref:o,align:t,sideOffset:r,className:J("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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",a),...s})).displayName=z.Content.displayName;class he{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const s=e.split(".");if(3!==s.length)return null;const o=s[1];o.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(o),a=atob(e),t=new Uint8Array(a.length);for(let s=0;s<a.length;s++)t[s]=a.charCodeAt(s);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(o),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(o),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(s){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const s=this.parseJwtPayload(a),o=this.parseJwtPayload(e);if(!s){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let n=!0;if(!o){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),n=!1}const i=Math.floor(Date.now()/1e3);if(o?.exp&&o.exp<i){const e="Access token expirado - pode precisar de refresh";t.push(e),n=!1}if(s.exp&&s.exp<i){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:n,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:n,warnings:t,errors:r}}catch(s){const e=`Erro na validação de tokens: ${s}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}he.LARGE_PAYLOAD_THRESHOLD=1e3;const fe={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"},ge={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 ye(){return"DEV"===import.meta.env.VITE_APP_ENV?"DEV":"PROD"}function be(){return"DEV"===ye()?ge:fe}const xe="qualiex_access_token",ve="qualiex_id_token",we="supabase_token",Ne="oauth_state",ke="oauth_nonce",Ae="selected_alias",Ie="manual_logout",Te="supabase_project_id",Ee={setAccessToken:e=>localStorage.setItem(xe,e),getAccessToken:()=>localStorage.getItem(xe),setIdToken:e=>localStorage.setItem(ve,e),getIdToken:()=>localStorage.getItem(ve),getSupabaseToken:()=>localStorage.getItem(we),setOAuthState:e=>sessionStorage.setItem(Ne,e),getOAuthState:()=>sessionStorage.getItem(Ne),clearOAuthState:()=>sessionStorage.removeItem(Ne),setOAuthNonce:e=>sessionStorage.setItem(ke,e),getOAuthNonce:()=>sessionStorage.getItem(ke),clearOAuthNonce:()=>sessionStorage.removeItem(ke),setSelectedAlias:e=>localStorage.setItem(Ae,e),getSelectedAlias:()=>localStorage.getItem(Ae),clearSelectedAlias:()=>localStorage.removeItem(Ae),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ee.getAccessToken()||!Ee.getIdToken()),checkProjectMismatch:()=>{const e=be().supabaseProjectId,a=localStorage.getItem(Te);return a&&a!==e?(Ee.clearAll(),localStorage.setItem(Te,e),!0):(a||localStorage.setItem(Te,e),!1)},setSupabaseToken:e=>{localStorage.setItem(we,e),Ee._clearValidationCache()},areAllTokensValid:()=>{const e=Ee.getAccessToken(),a=Ee.getIdToken();if(!e||!a)return!1;try{const t=he.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ee.getAccessToken(),t=Ee.getIdToken(),r=Ee.getSupabaseToken();return a&&Ee.isTokenExpired(a)&&(localStorage.removeItem(xe),e=!0),t&&Ee.isTokenExpired(t)&&(localStorage.removeItem(ve),e=!0),r&&Ee.isTokenExpired(r)&&(localStorage.removeItem(we),e=!0),e},clearAll:()=>{localStorage.removeItem(xe),localStorage.removeItem(ve),localStorage.removeItem(we),localStorage.removeItem(Ae),sessionStorage.removeItem(Ne),sessionStorage.removeItem(ke),Ee._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Ie,"true"),isManualLogout:()=>"true"===localStorage.getItem(Ie),clearManualLogout:()=>localStorage.removeItem(Ie),isTokenExpired:e=>{try{return he.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ee._validationCache.isValid=!1,Ee._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ee.getSupabaseToken();if(!e)return!1;if(Ee.isTokenExpired(e))return Ee._clearValidationCache(),Ee._handleExpiredToken(),!1;const a=Date.now();return a-Ee._validationCache.timestamp<Ee._validationCache.cacheValidityMs?Ee._validationCache.isValid:(Ee._validationCache.isValid=!0,Ee._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ee.isSupabaseTokenValid()?Ee.getSupabaseToken():null,_handleExpiredToken:()=>{Ee.clearAll()},extractTokenData:()=>{if(!Ee.isSupabaseTokenValid())return null;const e=Ee.getSupabaseToken();if(!e)return null;try{const a=he.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,s=a.place_name||null;let o=a.company_id;if(!o&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){o=e[7];break}}}return{alias:t,companyId:o,placeId:r,placeName:s,payload:a}}catch(a){return Ee._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ee.getAccessToken();if(a)try{const t=he.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(s){}const t=Ee.extractTokenData();if(t?.companyId)return t.companyId;const r=Ee.getIdToken();if(r)try{const a=he.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(s){}return null},getCompanyIdInt:e=>{const a=[Ee.getAccessToken(),Ee.getIdToken()];for(const t of a)if(t)try{const a=he.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=Ee.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ee.getIdToken();if(!e)return[];try{const a=he.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const Ce=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);C.error(e,{description:t})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?L.t("error_session_expired"):a.includes("token")||a.includes("autenticação")?L.t("error_authentication"):a.includes("api")||a.includes("network")?L.t("error_connection"):"Erro"}success(e,a){C.success(e,{description:a})}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 Se(e){return!!e&&e.startsWith("eyJ")}let _e=!1;function Re(){if("DEV"===ye()){const e=be();return{url:e.supabaseUrl,key:e.supabasePublishableKey}}const e=import.meta.env.VITE_SUPABASE_URL,a=import.meta.env.VITE_SUPABASE_PK_OVERRIDE||(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY??"");return e&&a?{url:e,key:a}:null}class Pe{constructor(e){this.currentToken=null,this.config=e,function(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE,a=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;_e?Se(a):e&&Se(a)?_e=!0:Se(a)?_e=!0:_e=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:this.config.key};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return O(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("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,a)}})}static getInstance(){if(!Pe.instance){const e=Re();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).");Pe.instance=new Pe(e)}return Pe.instance}getClient(){const e=Ee.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!he.isTokenExpired(e)}catch(a){return Ce.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Ue(){return Pe.getInstance().getClient()}class De{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Ee.getSupabaseToken();if(e&&Ee.isSupabaseTokenValid())return e}const s=Ue(),{data:o,error:n}=await s.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return n&&(n.message?.includes("401")||n.message?.includes("Unauthorized"))?(t?.(),null):o?.access_token?(Ee.setSupabaseToken(o.access_token),o.access_token):null}catch(s){return s instanceof Error&&(s.message.includes("401")||s.message.includes("Unauthorized"))&&t?.(),null}}}class Ve{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 a=Ee.getAccessToken(),t=Ee.getSelectedAlias();if(!a||!t)return null;const r=await De.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}Ve.regenerationPromise=null,Ve.onLogoutCallback=null;class ze{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ee.clearAll(),window.location.href="/login",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class Le{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await Ve.attemptRegeneration()?(this.isRetrying=!1,!0):(ze.handleError(e),this.isRetrying=!1,!1)}catch(r){return ze.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ee.getAccessToken();return e?Ee.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}Le.isRetrying=!1;const Me={get oauth(){const e=be();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Oe=()=>be().qualiexApiUrl;import.meta.env.VITE_IS_QUALIEX;const je=new class{get baseUrl(){return Oe()}async makeApiCall(e,a,t){const r=Le.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Ee.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const o=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{o.searchParams.append(e,a)});const n=await fetch(o.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!n.ok){const e=new Error(`API call failed: ${n.status} ${n.statusText}`);throw e.status=n.status,e.statusCode=n.status,e}return await n.json()}mapToQualiexUser(e){let a;return a="boolean"==typeof e.isActive?e.isActive:"boolean"==typeof e.active?e.active:"string"!=typeof e.status||"active"===e.status.toLowerCase(),{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0,isActive:a}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return Ce.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(e=>this.mapToQualiexUser(e)):(Ce.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a,t="active"){const r={companyId:a,search:"",filterStatus:t};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a)??[]}catch(s){if(await Le.handleApiError(s))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a," após retry")??[]}catch(o){return Ce.handleError(o instanceof Error?o:"Erro ao buscar usuários após renovação de token",!0),[]}return Ce.handleError(s instanceof Error?s.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Ce.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a,"active"),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async fetchAllUsersMap(e,a){const t=await this.fetchUsers(e,a,"all"),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e,a="active"){const t=Ee.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId,a):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(Ce.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await Le.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return Ce.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Ce.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(Ce.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await Le.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return Ce.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return Ce.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};var Be;const He={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};Be=class{static async initialize(){try{const e=!0;if(e){if(Ee.checkProjectMismatch())return{...He}}if(!Ee.hasAllTokens()||!Ee.areAllTokensValid())return Ee.clearExpiredTokens(),{...He};const a=Ee.getAccessToken(),t=Ee.getIdToken();Ee.clearManualLogout();const r=this.extractUserFromIdToken(t,a),s=this.extractCompaniesFromIdToken(t),o=this.extractAliasFromAccessToken(a),n=e?Ee.extractTokenData():null,i=n?.alias;let l=null;if(i&&s.some(e=>e.alias===i))l=i;else{const e=Ee.getSelectedAlias(),a=e&&s.some(a=>a.alias===e);l=a?e:o||s[0]?.alias||null}if(e&&(!Ee.isSupabaseTokenValid()&&l&&await Ve.attemptRegeneration(),!Ee.isSupabaseTokenValid()))return{...He};let c=null;if(l){const e=Ee.getCompanyId(l),a=s.find(e=>e.alias===l);a&&(c={id:e||a.id,name:a.name,alias:a.alias})}const d=n?.placeId??null,m=n?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:s,selectedUnit:c,userId:r?.id||null,userAlias:r?.id||null,placeId:d,placeName:m,activePlaceId:d,activePlaceName:m}}catch(e){return{...He}}}static async loginDev(){try{const e=Ue(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";Ee.setOAuthState(e);const a=Ee.generateOAuthNonce();Ee.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Me.oauth.authUrl);r.searchParams.set("client_id",Me.oauth.clientId),r.searchParams.set("response_type",Me.oauth.responseType),r.searchParams.set("scope",Me.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),s=t("id_token"),o=t("error");if(o)throw new Error(`Erro OAuth: ${o}`);if(r&&s){const e=Ee.getAccessToken();e!==r&&Ee.clearAll()}const n=!0;if(Ee.hasAllTokens()){if(n){Ee.getValidSupabaseToken()||await Ve.attemptRegeneration(!0)}return!0}const i=r,l=s;if(!i||!l)throw new Error("Tokens não encontrados na URL de callback");Ee.setAccessToken(i),Ee.setIdToken(l),Ee.clearManualLogout();const c=this.extractAliasFromAccessToken(i);if(c)Ee.setSelectedAlias(c);else{const e=this.extractCompaniesFromIdToken(l);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ee.setSelectedAlias(e[0].alias)}if(n){if(!await Ve.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return Ee.clearOAuthState(),Ee.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){Ee.clearAll(),Ee.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 he.parseJwtPayload(e)}static extractUserFromIdToken(e,a){const t=this.decodeToken(e);if(!t)return null;const r=a?this.decodeToken(a):null;return{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier,isSysAdmin:"1"===r?.admin}}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,s]=a[e].split("|");r&&s&&t.push({id:"",alias:r.trim(),name:s.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}},Ve.setLogoutCallback(()=>{Be.logout()});const We=s(void 0),qe=(e={})=>{const{user:a,alias:t}=(()=>{const e=o(We);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e})(),{enabled:r=!0,status:s="active"}=e;return M({queryKey:["qualiex-users",t,s],queryFn:()=>je.getUsers(t,s),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},$e=B.Root,Je=B.Portal,Ke=t.forwardRef(({className:a,...t},r)=>e(B.Overlay,{className:J("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Ke.displayName=B.Overlay.displayName;const Qe=t.forwardRef(({className:t,...r},s)=>a(Je,{children:[e(Ke,{}),e(B.Content,{ref:s,className:J("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));Qe.displayName=B.Content.displayName;const Fe=({className:a,...t})=>e("div",{className:J("flex flex-col space-y-2 text-center sm:text-left",a),...t});Fe.displayName="AlertDialogHeader";const Ge=({className:a,...t})=>e("div",{className:J("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Ge.displayName="AlertDialogFooter";const Ye=t.forwardRef(({className:a,...t},r)=>e(B.Title,{ref:r,className:J("text-lg font-semibold",a),...t}));Ye.displayName=B.Title.displayName;const Xe=t.forwardRef(({className:a,...t},r)=>e(B.Description,{ref:r,className:J("text-sm text-muted-foreground",a),...t}));Xe.displayName=B.Description.displayName;const Ze=t.forwardRef(({className:a,...t},r)=>e(B.Action,{ref:r,className:J(te(),a),...t}));Ze.displayName=B.Action.displayName;const ea=t.forwardRef(({className:a,...t},r)=>e(B.Cancel,{ref:r,className:J(te({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));ea.displayName=B.Cancel.displayName;const aa=j.Root,ta=j.Portal,ra=t.forwardRef(({className:a,...t},r)=>e(j.Overlay,{ref:r,className:J("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));ra.displayName=j.Overlay.displayName;const sa={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},oa=t.forwardRef(({className:r,children:s,size:o,variant:n="informative",isDirty:i,customWidth:l,customMinWidth:c,customMaxWidth:d,customHeight:m,customMinHeight:u,customMaxHeight:p,unsavedChangesTitle:h=L.t("unsaved_changes"),unsavedChangesDescription:f=L.t("unsaved_changes_description"),cancelText:g=L.t("cancel"),leaveWithoutSavingText:b=L.t("leave_without_saving"),style:x,onInteractOutside:v,onEscapeKeyDown:w,...N},k)=>{const[A,I]=t.useState(!1),T=t.useRef(null),E=t.useRef(!1),C=o??(l||c||d||m||u||p?void 0:"md"),S=C?sa[C]:{},_={...l??S.width?{width:l??S.width}:{},...c??S.minWidth?{minWidth:c??S.minWidth}:{},...d??S.maxWidth?{maxWidth:d??S.maxWidth}:{},...m??S.height?{height:m??S.height}:{},...u??S.minHeight?{minHeight:u??S.minHeight}:{},...p??S.maxHeight?{maxHeight:p??S.maxHeight}:{},...x},R=t.useCallback(e=>{"form"===n&&i?(T.current=e,I(!0)):e()},[n,i]),P=t.useRef(null),U="destructive"!==n;if("development"===process.env.NODE_ENV&&s){const e=t.Children.toArray(s);e.some(e=>t.isValidElement(e)&&"DialogFooter"===e.type?.displayName),e.some(e=>t.isValidElement(e)&&"DialogBody"===e.type?.displayName)}return a(ta,{children:[e(ra,{}),a(j.Content,{ref:k,className:J("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border-0 border-l-[10px] border-l-primary bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",r),style:_,onInteractOutside:e=>{"form"!==n&&"destructive"!==n?v?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==n)return"form"===n&&i?(e.preventDefault(),void R(()=>{E.current=!0,P.current?.click()})):void w?.(e);e.preventDefault()},...N,children:[s,U&&a(j.Close,{ref:P,onClick:e=>{E.current?E.current=!1:"form"===n&&i&&(e.preventDefault(),R(()=>{E.current=!0,P.current?.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(y,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e($e,{open:A,onOpenChange:I,children:a(Qe,{children:[a(Fe,{children:[e(Ye,{children:h}),e(Xe,{children:f})]}),a(Ge,{children:[e(ea,{onClick:()=>{I(!1),T.current=null},children:g}),e(Ze,{onClick:()=>{I(!1),T.current?.(),T.current=null},children:b})]})]})})]})});oa.displayName=j.Content.displayName;const na=({className:t,showSeparator:r=!1,children:s,...o})=>a("div",{className:J("flex flex-col flex-shrink-0",t),...o,children:[e("div",{className:"flex flex-col text-left",children:s}),r&&e(F,{className:"mt-2"})]});na.displayName="DialogHeader";const ia=({className:a,...t})=>e("div",{className:J("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",a),...t});ia.displayName="DialogBody";const la=({className:t,children:r,...s})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(F,{className:"mb-4"}),e("div",{className:J("flex flex-row justify-end gap-2",t),...s,children:r})]});la.displayName="DialogFooter";const ca=t.forwardRef(({className:a,...t},r)=>e(j.Title,{ref:r,className:J("text-xl font-semibold leading-none tracking-tight",a),...t}));ca.displayName=j.Title.displayName;t.forwardRef(({className:a,...t},r)=>e(j.Description,{ref:r,className:J("text-sm text-muted-foreground",a),...t})).displayName=j.Description.displayName;const da=t.forwardRef(({className:t,children:r,...s},o)=>a(H.Root,{ref:o,className:J("relative overflow-hidden",t),...s,children:[e(H.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(ma,{}),e(H.Corner,{})]}));da.displayName=H.Root.displayName;const ma=t.forwardRef(({className:a,orientation:t="vertical",...r},s)=>e(H.ScrollAreaScrollbar,{ref:s,orientation:t,className:J("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(H.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));function ua({open:t,onOpenChange:s,placeId:o,placeName:i,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:m=[]}){const{t:u}=P(),[p,h]=n([]),[f,g]=n(!1),[y,N]=n(""),{data:k=[],isLoading:A}=qe({enabled:t}),I=r(()=>{let e=[...k];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),y){const a=y.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[k,y]),T=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},E=1===p.length,C=p.length>0;return e(aa,{open:t,onOpenChange:s,children:a(oa,{className:"max-w-2xl",variant:"form",children:[e(na,{showSeparator:!0,children:a(ca,{className:"flex items-center gap-2",children:[e(b,{className:"h-5 w-5"}),"Gerenciar Acessos - ",i]})}),a(ia,{children:[a("div",{className:"relative mb-4",children:[e(x,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(pe,{placeholder:"Pesquisar...",value:y,onChange:e=>N(e.target.value),className:"pl-9"})]}),e(da,{className:"h-[400px] pr-4",children:A?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(G,{className:"h-16 w-full"},t))}):0===I.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(b,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:u(y?"leadership_no_users_found":"leadership_no_users_available")})]}):e("div",{className:"space-y-2",children:I.map(t=>{const r=t.userId===d,s=m.includes(t.userId||""),o=p.includes(t.userId||"");return a("div",{className:J("flex items-center gap-3 p-3 rounded-lg border transition-colors",o&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>T(t.userId||""),children:[e(Y,{checked:o,onCheckedChange:()=>T(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(v,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||s)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(la,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:p.length>0&&a("span",{children:[p.length," selecionado(s)"]})}),E&&l&&a(re,{onClick:async()=>{if(l&&1===p.length){g(!0);try{await l(p[0],o),h([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[e(v,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(re,{onClick:async()=>{if(c&&0!==p.length){g(!0);try{await c(p,o),h([])}finally{g(!1)}}},disabled:f,children:[e(w,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function pa({place:t,level:r=0,manageAccessConfig:s}){const{t:o}=P(),[i,c]=n(!1),[d,m]=n(!1),u=t.subPlaces&&t.subPlaces.length>0,p=t.isActive??!0,h=t.usersCount??0;return a("div",{children:[a(W,{open:i,onOpenChange:c,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[u?a(q,{className:"flex items-center gap-2 flex-1",children:[e(l,{className:J("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e(N,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(N,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:h})]}),e(Q,{variant:p?"default":"secondary",className:"text-xs",children:p?"Ativo":"Inativo"}),s&&e(ce,{customActions:[{label:o("manage_access"),icon:k,onClick:()=>m(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),u&&e($,{children:t.subPlaces.map(a=>e(pa,{place:a,level:r+1,manageAccessConfig:s},a.id))})]}),0===r&&e(F,{}),s&&e(ua,{open:d,onOpenChange:m,placeId:t.id,placeName:t.name,onMakeManager:s.onMakeManager,onMakeMembers:s.onMakeMembers,currentManagerId:s.getCurrentManagerId?.(t.id),currentMemberIds:s.getCurrentMemberIds?.(t.id)})]})}function ha({places:t,isLoading:r,manageAccessConfig:s}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(pa,{place:a,manageAccessConfig:s},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(N,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}ma.displayName=H.ScrollAreaScrollbar.displayName;const fa=new class{get baseUrl(){return Oe()}async makeApiCall(e,a,t){const r=Le.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Ee.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const o=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{o.searchParams.append(e,a)});const n=await fetch(o.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!n.ok){const e=new Error(`API call failed: ${n.status}`);throw e.status=n.status,e}return n.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const s=a.get(e.parentId);s?(s.subPlaces=s.subPlaces||[],s.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await Le.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Ce.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Ce.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};export{ua as ManageAccessModal,pa as PlaceCard,ha as PlacesList,fa as placeService};
|
|
1
|
+
import{jsx as e,jsxs as a}from"react/jsx-runtime";import{useState as r,useMemo as s}from"react";import{Users as n,Search as t,Crown as c,UserPlus as l,ChevronRight as o,Building2 as i,Settings as d}from"lucide-react";import{useQualiexUsers as m,Dialog as u,DialogContent as h,DialogHeader as p,DialogTitle as f,DialogBody as g,Input as x,ScrollArea as N,Skeleton as b,Checkbox as v,cn as w,DialogFooter as y,Button as C,Collapsible as k,CollapsibleTrigger as M,Badge as I,ActionMenu as A,CollapsibleContent as E,Separator as P,getQualiexApiUrl as L,QualiexErrorInterceptor as j,TokenManager as T,errorService as _}from"forlogic-core";import{useTranslation as O}from"react-i18next";function G({open:o,onOpenChange:i,placeId:d,placeName:k,onMakeManager:M,onMakeMembers:I,currentManagerId:A,currentMemberIds:E=[]}){const{t:P}=O(),[L,j]=r([]),[T,_]=r(!1),[G,H]=r(""),{data:U=[],isLoading:S}=m({enabled:o}),$=s(()=>{let e=[...U];if(e.sort((e,a)=>{const r=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return r.localeCompare(s)}),G){const a=G.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[U,G]),q=e=>{j(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},z=1===L.length,B=L.length>0;return e(u,{open:o,onOpenChange:i,children:a(h,{className:"max-w-2xl",variant:"form",children:[e(p,{showSeparator:!0,children:a(f,{className:"flex items-center gap-2",children:[e(n,{className:"h-5 w-5"}),"Gerenciar Acessos - ",k]})}),a(g,{children:[a("div",{className:"relative mb-4",children:[e(t,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(x,{placeholder:"Pesquisar...",value:G,onChange:e=>H(e.target.value),className:"pl-9"})]}),e(N,{className:"h-[400px] pr-4",children:S?e("div",{className:"space-y-2",children:[...Array(5)].map((a,r)=>e(b,{className:"h-16 w-full"},r))}):0===$.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(n,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:P(G?"leadership_no_users_found":"leadership_no_users_available")})]}):e("div",{className:"space-y-2",children:$.map(r=>{const s=r.userId===A,n=E.includes(r.userId||""),t=L.includes(r.userId||"");return a("div",{className:w("flex items-center gap-3 p-3 rounded-lg border transition-colors",t&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>q(r.userId||""),children:[e(v,{checked:t,onCheckedChange:()=>q(r.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:r.userName}),s&&e(c,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:r.userEmail})]}),(s||n)&&e("div",{className:"text-xs text-muted-foreground",children:s?"Gestor":"Membro"})]},r.userId)})})})]}),a(y,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:L.length>0&&a("span",{children:[L.length," selecionado(s)"]})}),z&&M&&a(C,{onClick:async()=>{if(M&&1===L.length){_(!0);try{await M(L[0],d),j([])}finally{_(!1)}}},disabled:T,variant:"outline",children:[e(c,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),B&&I&&a(C,{onClick:async()=>{if(I&&0!==L.length){_(!0);try{await I(L,d),j([])}finally{_(!1)}}},disabled:T,children:[e(l,{className:"h-4 w-4 mr-2"}),"Tornar ",L.length>1?"Membros":"Membro"]})]})]})})}function H({place:s,level:t=0,manageAccessConfig:c}){const{t:l}=O(),[m,u]=r(!1),[h,p]=r(!1),f=s.subPlaces&&s.subPlaces.length>0,g=s.isActive??!0,x=s.usersCount??0;return a("div",{children:[a(k,{open:m,onOpenChange:u,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*t+1+"rem"},children:[f?a(M,{className:"flex items-center gap-2 flex-1",children:[e(o,{className:w("h-4 w-4 transition-transform shrink-0",m&&"rotate-90")}),e(i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:s.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",s.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:s.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(n,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:x})]}),e(I,{variant:g?"default":"secondary",className:"text-xs",children:g?"Ativo":"Inativo"}),c&&e(A,{customActions:[{label:l("manage_access"),icon:d,onClick:()=>p(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),f&&e(E,{children:s.subPlaces.map(a=>e(H,{place:a,level:t+1,manageAccessConfig:c},a.id))})]}),0===t&&e(P,{}),c&&e(G,{open:h,onOpenChange:p,placeId:s.id,placeName:s.name,onMakeManager:c.onMakeManager,onMakeMembers:c.onMakeMembers,currentManagerId:c.getCurrentManagerId?.(s.id),currentMemberIds:c.getCurrentMemberIds?.(s.id)})]})}function U({places:r,isLoading:s,manageAccessConfig:n}){return s?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):r&&0!==r.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),r.map(a=>e(H,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(i,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const S=new class{get baseUrl(){return L()}async makeApiCall(e,a,r){const s=j.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const n=T.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!r||""===r.trim())throw new Error("Alias da unidade é obrigatório");const t=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{t.searchParams.append(e,a)});const c=await fetch(t.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":r}});if(!c.ok){const e=new Error(`API call failed: ${c.status}`);throw e.status=c.status,e}return c.json()}buildHierarchy(e){const a=new Map,r=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const s=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(s)):r.push(s)}else r.push(s)}),r}async getPlaces(e,a){try{const r=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=r.data||r||[];return this.buildHierarchy(s)}catch(r){if(await j.handleApiError(r))try{const r=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=r.data||r||[];return this.buildHierarchy(s)}catch(s){return _.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return _.handleError(r instanceof Error?r.message:"Erro ao buscar locais",!0),[]}}};export{G as ManageAccessModal,H as PlaceCard,U as PlacesList,S as placeService};
|
package/dist/places/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=require("lucide-react"),s=require("@radix-ui/react-collapsible"),r=require("class-variance-authority"),o=require("clsx"),n=require("tailwind-merge");require("date-fns");var i=require("sonner"),l=require("@radix-ui/react-separator"),c=require("@radix-ui/react-checkbox"),d=require("@radix-ui/react-tooltip"),u=require("react-i18next"),m=require("@radix-ui/react-slot"),p=require("@radix-ui/react-dropdown-menu"),h=require("@radix-ui/react-select"),f=require("@radix-ui/react-hover-card"),g=require("i18next"),x=require("@tanstack/react-query"),y=require("@supabase/supabase-js"),b=require("@radix-ui/react-dialog"),v=require("@radix-ui/react-alert-dialog"),w=require("@radix-ui/react-scroll-area");function N(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var k=N(a),j=N(s),A=N(l),I=N(c),T=N(d),E=N(p),C=N(h),S=N(f),_=N(b),R=N(v),P=N(w);const U=j.Root,D=j.CollapsibleTrigger,V=j.CollapsibleContent;function z(...e){return n.twMerge(o.clsx(e))}const L=r.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),O=k.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,className:z(L({variant:t}),a),...s}));O.displayName="Badge";const M=k.forwardRef(({className:a,orientation:t="horizontal",decorative:s=!0,...r},o)=>e.jsx(A.Root,{ref:o,decorative:s,orientation:t,className:z("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...r}));M.displayName=A.Root.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx("table",{ref:s,className:z("w-full caption-bottom text-[13px] table-fixed",a),...t})).displayName="Table";k.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:z("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t})).displayName="TableHeader";k.forwardRef(({className:a,...t},s)=>e.jsx("tbody",{ref:s,className:z("[&_tr:last-child]:border-0",a),...t})).displayName="TableBody";k.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:z("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t})).displayName="TableFooter";k.forwardRef(({className:a,...t},s)=>e.jsx("tr",{ref:s,className:z("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t})).displayName="TableRow";k.forwardRef(({className:a,...t},s)=>e.jsx("th",{ref:s,className:z("h-9 px-4 py-2 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t})).displayName="TableHead";k.forwardRef(({className:a,...t},s)=>e.jsx("td",{ref:s,className:z("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t})).displayName="TableCell";function q({className:a,...t}){return e.jsx("div",{className:z("animate-pulse rounded-md bg-muted",a),...t})}k.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:z("mt-4 text-sm text-muted-foreground",a),...t})).displayName="TableCaption";const B=k.forwardRef(({className:a,...s},r)=>e.jsx(I.Root,{ref:r,className:z("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...s,children:e.jsx(I.Indicator,{className:z("flex items-center justify-center text-current"),children:e.jsx(t.Check,{className:"h-4 w-4"})})}));B.displayName=I.Root.displayName;const H=({delayDuration:a=300,...t})=>e.jsx(T.Provider,{delayDuration:a,...t}),W=T.Root,$=T.Trigger,J=k.forwardRef(({className:a,sideOffset:t=4,container:s,...r},o)=>e.jsx(T.Portal,{container:s,children:e.jsx(T.Content,{ref:o,sideOffset:t,className:z("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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",a),...r})}));J.displayName=T.Content.displayName;k.forwardRef(({direction:a,onMouseDown:t,isDragging:s,className:r},o)=>{const n="horizontal"===a;return e.jsx("div",{ref:o,onMouseDown:t,className:z("absolute z-20 select-none touch-none","transition-colors duration-150",n&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!n&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],s&&"bg-primary/30",r),children:e.jsx("div",{className:z("rounded-full bg-border transition-colors group-hover:bg-primary",s&&"bg-primary",n?"h-6 w-0.5":"w-6 h-0.5")})})}).displayName="TableResizeHandle";const Q=r.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"}}),K=k.forwardRef(({className:a,variant:t,size:s,asChild:r=!1,...o},n)=>{const i=r?m.Slot:"button";return e.jsx(i,{className:z(Q({variant:t,size:s,className:a})),ref:n,...o})});K.displayName="Button";const F=E.Root,G=E.Trigger;k.forwardRef(({className:a,inset:s,children:r,...o},n)=>e.jsxs(E.SubTrigger,{ref:n,className:z("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",s&&"pl-8",a),...o,children:[r,e.jsx(t.ChevronRight,{className:"ml-auto h-4 w-4"})]})).displayName=E.SubTrigger.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(E.SubContent,{ref:s,className:z("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg 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",a),...t})).displayName=E.SubContent.displayName;const Y=k.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(E.Portal,{children:e.jsx(E.Content,{ref:r,sideOffset:t,className:z("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg 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",a),...s})}));Y.displayName=E.Content.displayName;const X=k.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(E.Item,{ref:r,className:z("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...s}));X.displayName=E.Item.displayName;k.forwardRef(({className:a,children:s,checked:r,...o},n)=>e.jsxs(E.CheckboxItem,{ref:n,className:z("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:r,...o,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(E.ItemIndicator,{children:e.jsx(t.Check,{className:"h-4 w-4"})})}),s]})).displayName=E.CheckboxItem.displayName;k.forwardRef(({className:a,children:s,...r},o)=>e.jsxs(E.RadioItem,{ref:o,className:z("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(E.ItemIndicator,{children:e.jsx(t.Circle,{className:"h-2 w-2 fill-current"})})}),s]})).displayName=E.RadioItem.displayName;k.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(E.Label,{ref:r,className:z("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s})).displayName=E.Label.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(E.Separator,{ref:s,className:z("-mx-1 my-1 h-px bg-muted",a),...t})).displayName=E.Separator.displayName;const Z=k.forwardRef(({children:a,disabledReason:t,className:s},r)=>{const o=e.jsx(X,{ref:r,className:z("opacity-50 cursor-not-allowed pointer-events-auto",s),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:a});return t?e.jsx(H,{delayDuration:100,children:e.jsxs(W,{children:[e.jsx($,{asChild:!0,children:e.jsx("div",{className:"w-full",children:o})}),e.jsx(J,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:t})]})}):o});function ee({onEdit:s,onDelete:r,onToggleStatus:o,isActive:n=!0,canEdit:i=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:m="default"}){const{t:p}=u.useTranslation(),h=a.useMemo(()=>{const e=[];return s&&i&&e.push({key:"edit",icon:t.Edit,label:p("edit","Editar"),onClick:s,variant:"default"}),o&&e.push({key:"toggle-status",icon:n?t.PowerOff:t.Power,label:n?p("deactivate","Inativar"):p("activate","Ativar"),onClick:o,variant:"default"}),c.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:t.Trash2,label:p("remove","Remover"),onClick:r,variant:"destructive"}),e},[s,r,o,n,i,l,c,p]);return 0===h.length?null:"dropdown"===d?e.jsx(H,{delayDuration:200,children:e.jsxs(F,{children:[e.jsx(G,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"compact"===m?"sm":"default",className:"compact"===m?"h-7 px-2":"",children:e.jsx(t.EllipsisVertical,{size:"compact"===m?14:16})})}),e.jsx(Y,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(a=>a.disabled?e.jsxs(Z,{disabledReason:a.disabledReason,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},a.key):e.jsxs(X,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},a.key))})]})}):e.jsx("div",{className:"flex items-center gap-1",children:h.map(a=>e.jsxs(K,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===m?"sm":"default",onClick:a.onClick,className:"compact"===m?"h-7 px-2":"",children:[a.icon&&e.jsx(a.icon,{size:"compact"===m?14:16}),"compact"!==m&&e.jsx("span",{className:"ml-1",children:a.label})]},a.key))})}Z.displayName="DisabledMenuItem";const ae=k.createContext({showCheck:!1});k.forwardRef(({className:a,children:s,...r},o)=>e.jsxs(C.Trigger,{ref:o,className:z("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:[s,e.jsx(C.Icon,{asChild:!0,children:e.jsx(t.ChevronDown,{className:"h-4 w-4 opacity-50"})})]})).displayName=C.Trigger.displayName;const te=k.forwardRef(({className:a,...s},r)=>e.jsx(C.ScrollUpButton,{ref:r,className:z("flex cursor-default items-center justify-center py-1",a),...s,children:e.jsx(t.ChevronUp,{className:"h-4 w-4"})}));te.displayName=C.ScrollUpButton.displayName;const se=k.forwardRef(({className:a,...s},r)=>e.jsx(C.ScrollDownButton,{ref:r,className:z("flex cursor-default items-center justify-center py-1",a),...s,children:e.jsx(t.ChevronDown,{className:"h-4 w-4"})}));se.displayName=C.ScrollDownButton.displayName;k.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:o,...n},i)=>e.jsx(C.Portal,{container:r,children:e.jsxs(C.Content,{ref:i,className:z("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",a),position:s,collisionBoundary:o,...n,children:[e.jsx(te,{}),e.jsx(C.Viewport,{className:z("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(se,{})]})})).displayName=C.Content.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(C.Label,{ref:s,className:z("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t})).displayName=C.Label.displayName;k.forwardRef(({className:a,children:s,...r},o)=>{const{showCheck:n}=k.useContext(ae);return e.jsxs(C.Item,{ref:o,className:z("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",n?"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",n?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",a),...r,children:[n&&e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(C.ItemIndicator,{children:e.jsx(t.Check,{className:"h-4 w-4"})})}),e.jsx(C.ItemText,{children:s})]})}).displayName=C.Item.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(C.Separator,{ref:s,className:z("-mx-1 my-1 h-px bg-muted",a),...t})).displayName=C.Separator.displayName;const re=k.forwardRef(({className:a,type:t,showCharCount:s,maxLength:r,onChange:o,...n},i)=>{const[l,c]=k.useState(0);k.useEffect(()=>{"string"==typeof n.value?c(n.value.length):"string"==typeof n.defaultValue&&c(n.defaultValue.length)},[n.value,n.defaultValue]);return e.jsxs("div",{className:"w-full",children:[e.jsx("input",{type:t,className:z("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",a),ref:i,maxLength:r,onChange:e=>{c(e.target.value.length),o?.(e)},...n}),s&&r&&e.jsxs("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[l," / ",r]})]})});re.displayName="Input";k.forwardRef(({className:a,align:t="center",sideOffset:s=4,...r},o)=>e.jsx(S.Content,{ref:o,align:t,sideOffset:s,className:z("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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",a),...r})).displayName=S.Content.displayName;class oe{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}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),a=atob(e),t=new Uint8Array(a.length);for(let r=0;r<a.length;r++)t[r]=a.charCodeAt(r);const s=new TextDecoder("utf-8").decode(t);return JSON.parse(s)}catch(a){try{const e=this.normalizeBase64Url(o),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(o),a=atob(e);return JSON.parse(a)}catch(s){throw s}}}}catch(r){return null}}static validateTokens(e,a){const t=[],s=[];try{a.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(a),o=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}let n=!0;if(!o){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),n=!1}const i=Math.floor(Date.now()/1e3);if(o?.exp&&o.exp<i){const e="Access token expirado - pode precisar de refresh";t.push(e),n=!1}if(r.exp&&r.exp<i){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:n,warnings:t,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:n,warnings:t,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}oe.LARGE_PAYLOAD_THRESHOLD=1e3;const ne={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"},ie={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 le(){return"DEV"===(void 0).VITE_APP_ENV?"DEV":"PROD"}function ce(){return"DEV"===le()?ie:ne}const de="qualiex_access_token",ue="qualiex_id_token",me="supabase_token",pe="oauth_state",he="oauth_nonce",fe="selected_alias",ge="manual_logout",xe="supabase_project_id",ye={setAccessToken:e=>localStorage.setItem(de,e),getAccessToken:()=>localStorage.getItem(de),setIdToken:e=>localStorage.setItem(ue,e),getIdToken:()=>localStorage.getItem(ue),getSupabaseToken:()=>localStorage.getItem(me),setOAuthState:e=>sessionStorage.setItem(pe,e),getOAuthState:()=>sessionStorage.getItem(pe),clearOAuthState:()=>sessionStorage.removeItem(pe),setOAuthNonce:e=>sessionStorage.setItem(he,e),getOAuthNonce:()=>sessionStorage.getItem(he),clearOAuthNonce:()=>sessionStorage.removeItem(he),setSelectedAlias:e=>localStorage.setItem(fe,e),getSelectedAlias:()=>localStorage.getItem(fe),clearSelectedAlias:()=>localStorage.removeItem(fe),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!ye.getAccessToken()||!ye.getIdToken()),checkProjectMismatch:()=>{const e=ce().supabaseProjectId,a=localStorage.getItem(xe);return a&&a!==e?(ye.clearAll(),localStorage.setItem(xe,e),!0):(a||localStorage.setItem(xe,e),!1)},setSupabaseToken:e=>{localStorage.setItem(me,e),ye._clearValidationCache()},areAllTokensValid:()=>{const e=ye.getAccessToken(),a=ye.getIdToken();if(!e||!a)return!1;try{const t=oe.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=ye.getAccessToken(),t=ye.getIdToken(),s=ye.getSupabaseToken();return a&&ye.isTokenExpired(a)&&(localStorage.removeItem(de),e=!0),t&&ye.isTokenExpired(t)&&(localStorage.removeItem(ue),e=!0),s&&ye.isTokenExpired(s)&&(localStorage.removeItem(me),e=!0),e},clearAll:()=>{localStorage.removeItem(de),localStorage.removeItem(ue),localStorage.removeItem(me),localStorage.removeItem(fe),sessionStorage.removeItem(pe),sessionStorage.removeItem(he),ye._clearValidationCache()},setManualLogout:()=>localStorage.setItem(ge,"true"),isManualLogout:()=>"true"===localStorage.getItem(ge),clearManualLogout:()=>localStorage.removeItem(ge),isTokenExpired:e=>{try{return oe.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{ye._validationCache.isValid=!1,ye._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=ye.getSupabaseToken();if(!e)return!1;if(ye.isTokenExpired(e))return ye._clearValidationCache(),ye._handleExpiredToken(),!1;const a=Date.now();return a-ye._validationCache.timestamp<ye._validationCache.cacheValidityMs?ye._validationCache.isValid:(ye._validationCache.isValid=!0,ye._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>ye.isSupabaseTokenValid()?ye.getSupabaseToken():null,_handleExpiredToken:()=>{ye.clearAll()},extractTokenData:()=>{if(!ye.isSupabaseTokenValid())return null;const e=ye.getSupabaseToken();if(!e)return null;try{const a=oe.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,s=a.place_id||null,r=a.place_name||null;let o=a.company_id;if(!o&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===t){o=e[7];break}}}return{alias:t,companyId:o,placeId:s,placeName:r,payload:a}}catch(a){return ye._handleExpiredToken(),null}},getCompanyId:e=>{const a=ye.getAccessToken();if(a)try{const t=oe.parseJwtPayload(a);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 a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}const t=ye.extractTokenData();if(t?.companyId)return t.companyId;const s=ye.getIdToken();if(s)try{const a=oe.parseJwtPayload(s);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 a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const a=[ye.getAccessToken(),ye.getIdToken()];for(const t of a)if(t)try{const a=oe.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=ye.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=ye.getIdToken();if(!e)return[];try{const a=oe.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const be=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);i.toast.error(e,{description:t})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?g.t("error_session_expired"):a.includes("token")||a.includes("autenticação")?g.t("error_authentication"):a.includes("api")||a.includes("network")?g.t("error_connection"):"Erro"}success(e,a){i.toast.success(e,{description:a})}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 ve(e){return!!e&&e.startsWith("eyJ")}let we=!1;function Ne(){if("DEV"===le()){const e=ce();return{url:e.supabaseUrl,key:e.supabasePublishableKey}}const e=(void 0).VITE_SUPABASE_URL,a=(void 0).VITE_SUPABASE_PK_OVERRIDE||((void 0).VITE_SUPABASE_PUBLISHABLE_KEY??"");return e&&a?{url:e,key:a}:null}class ke{constructor(e){this.currentToken=null,this.config=e,function(){const e=(void 0).VITE_SUPABASE_PK_OVERRIDE,a=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;we?ve(a):e&&ve(a)?we=!0:ve(a)?we=!0:we=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:this.config.key};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return y.createClient(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("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,a)}})}static getInstance(){if(!ke.instance){const e=Ne();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).");ke.instance=new ke(e)}return ke.instance}getClient(){const e=ye.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!oe.isTokenExpired(e)}catch(a){return be.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function je(){return ke.getInstance().getClient()}class Ae{static async generateToken(e,a,t,s=!1){try{if(!s){const e=ye.getSupabaseToken();if(e&&ye.isSupabaseTokenValid())return e}const r=je(),{data:o,error:n}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return n&&(n.message?.includes("401")||n.message?.includes("Unauthorized"))?(t?.(),null):o?.access_token?(ye.setSupabaseToken(o.access_token),o.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&t?.(),null}}}class Ie{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 a=ye.getAccessToken(),t=ye.getSelectedAlias();if(!a||!t)return null;const s=await Ae.generateToken(a,t,this.onLogoutCallback||void 0,e);return s||null}catch(a){return null}}}Ie.regenerationPromise=null,Ie.onLogoutCallback=null;class Te{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(ye.clearAll(),window.location.href="/login",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class Ee{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await Ie.attemptRegeneration()?(this.isRetrying=!1,!0):(Te.handleError(e),this.isRetrying=!1,!1)}catch(s){return Te.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=ye.getAccessToken();return e?ye.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}Ee.isRetrying=!1;const Ce={get oauth(){const e=ce();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Se=()=>ce().qualiexApiUrl;(void 0).VITE_IS_QUALIEX;const _e=new class{get baseUrl(){return Se()}async makeApiCall(e,a,t){const s=Ee.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=ye.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const o=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{o.searchParams.append(e,a)});const n=await fetch(o.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!n.ok){const e=new Error(`API call failed: ${n.status} ${n.statusText}`);throw e.status=n.status,e.statusCode=n.status,e}return await n.json()}mapToQualiexUser(e){let a;return a="boolean"==typeof e.isActive?e.isActive:"boolean"==typeof e.active?e.active:"string"!=typeof e.status||"active"===e.status.toLowerCase(),{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0,isActive:a}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return be.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(e=>this.mapToQualiexUser(e)):(be.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a,t="active"){const s={companyId:a,search:"",filterStatus:t};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",s,e);return this.parseUsersResponse(a)??[]}catch(r){if(await Ee.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",s,e);return this.parseUsersResponse(a," após retry")??[]}catch(o){return be.handleError(o instanceof Error?o:"Erro ao buscar usuários após renovação de token",!0),[]}return be.handleError(r instanceof Error?r.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(s){return be.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a,"active"),s=new Map;return t.forEach(e=>s.set(e.userId,e)),s}async fetchAllUsersMap(e,a){const t=await this.fetchUsers(e,a,"all"),s=new Map;return t.forEach(e=>s.set(e.userId,e)),s}async getUsers(e,a="active"){const t=ye.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId,a):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(be.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await Ee.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return be.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return be.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),s=t?.data||t;return Array.isArray(s)?s.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(be.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await Ee.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),s=t?.data||t;return Array.isArray(s)?s.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(s){return be.handleError(s instanceof Error?s:"Erro ao buscar associações após renovação de token",!0),[]}return be.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};var Re;const Pe={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};Re=class{static async initialize(){try{const e=!0;if(e){if(ye.checkProjectMismatch())return{...Pe}}if(!ye.hasAllTokens()||!ye.areAllTokensValid())return ye.clearExpiredTokens(),{...Pe};const a=ye.getAccessToken(),t=ye.getIdToken();ye.clearManualLogout();const s=this.extractUserFromIdToken(t,a),r=this.extractCompaniesFromIdToken(t),o=this.extractAliasFromAccessToken(a),n=e?ye.extractTokenData():null,i=n?.alias;let l=null;if(i&&r.some(e=>e.alias===i))l=i;else{const e=ye.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);l=a?e:o||r[0]?.alias||null}if(e&&(!ye.isSupabaseTokenValid()&&l&&await Ie.attemptRegeneration(),!ye.isSupabaseTokenValid()))return{...Pe};let c=null;if(l){const e=ye.getCompanyId(l),a=r.find(e=>e.alias===l);a&&(c={id:e||a.id,name:a.name,alias:a.alias})}const d=n?.placeId??null,u=n?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:s,alias:l,companies:r,selectedUnit:c,userId:s?.id||null,userAlias:s?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{...Pe}}}static async loginDev(){try{const e=je(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";ye.setOAuthState(e);const a=ye.generateOAuthNonce();ye.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(Ce.oauth.authUrl);s.searchParams.set("client_id",Ce.oauth.clientId),s.searchParams.set("response_type",Ce.oauth.responseType),s.searchParams.set("scope",Ce.oauth.scope),s.searchParams.set("redirect_uri",t),s.searchParams.set("state",e),s.searchParams.set("nonce",a),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),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),s=t("access_token"),r=t("id_token"),o=t("error");if(o)throw new Error(`Erro OAuth: ${o}`);if(s&&r){const e=ye.getAccessToken();e!==s&&ye.clearAll()}const n=!0;if(ye.hasAllTokens()){if(n){ye.getValidSupabaseToken()||await Ie.attemptRegeneration(!0)}return!0}const i=s,l=r;if(!i||!l)throw new Error("Tokens não encontrados na URL de callback");ye.setAccessToken(i),ye.setIdToken(l),ye.clearManualLogout();const c=this.extractAliasFromAccessToken(i);if(c)ye.setSelectedAlias(c);else{const e=this.extractCompaniesFromIdToken(l);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");ye.setSelectedAlias(e[0].alias)}if(n){if(!await Ie.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return ye.clearOAuthState(),ye.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){ye.clearAll(),ye.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 oe.parseJwtPayload(e)}static extractUserFromIdToken(e,a){const t=this.decodeToken(e);if(!t)return null;const s=a?this.decodeToken(a):null;return{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier,isSysAdmin:"1"===s?.admin}}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const s=a[e].split(";");if(s.length>=4)t.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=a[e].split("|");s&&r&&t.push({id:"",alias:s.trim(),name:r.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}},Ie.setLogoutCallback(()=>{Re.logout()});const Ue=a.createContext(void 0),De=(e={})=>{const{user:t,alias:s}=(()=>{const e=a.useContext(Ue);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e})(),{enabled:r=!0,status:o="active"}=e;return x.useQuery({queryKey:["qualiex-users",s,o],queryFn:()=>_e.getUsers(s,o),enabled:r&&!!s&&!!t,staleTime:3e5,retry:2,retryDelay:1e3})},Ve=R.Root,ze=R.Portal,Le=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Overlay,{className:z("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:s}));Le.displayName=R.Overlay.displayName;const Oe=k.forwardRef(({className:a,...t},s)=>e.jsxs(ze,{children:[e.jsx(Le,{}),e.jsx(R.Content,{ref:s,className:z("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...t})]}));Oe.displayName=R.Content.displayName;const Me=({className:a,...t})=>e.jsx("div",{className:z("flex flex-col space-y-2 text-center sm:text-left",a),...t});Me.displayName="AlertDialogHeader";const qe=({className:a,...t})=>e.jsx("div",{className:z("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});qe.displayName="AlertDialogFooter";const Be=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Title,{ref:s,className:z("text-lg font-semibold",a),...t}));Be.displayName=R.Title.displayName;const He=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Description,{ref:s,className:z("text-sm text-muted-foreground",a),...t}));He.displayName=R.Description.displayName;const We=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Action,{ref:s,className:z(Q(),a),...t}));We.displayName=R.Action.displayName;const $e=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Cancel,{ref:s,className:z(Q({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));$e.displayName=R.Cancel.displayName;const Je=_.Root,Qe=_.Portal,Ke=k.forwardRef(({className:a,...t},s)=>e.jsx(_.Overlay,{ref:s,className:z("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));Ke.displayName=_.Overlay.displayName;const Fe={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},Ge=k.forwardRef(({className:a,children:s,size:r,variant:o="informative",isDirty:n,customWidth:i,customMinWidth:l,customMaxWidth:c,customHeight:d,customMinHeight:u,customMaxHeight:m,unsavedChangesTitle:p=g.t("unsaved_changes"),unsavedChangesDescription:h=g.t("unsaved_changes_description"),cancelText:f=g.t("cancel"),leaveWithoutSavingText:x=g.t("leave_without_saving"),style:y,onInteractOutside:b,onEscapeKeyDown:v,...w},N)=>{const[j,A]=k.useState(!1),I=k.useRef(null),T=k.useRef(!1),E=r??(i||l||c||d||u||m?void 0:"md"),C=E?Fe[E]:{},S={...i??C.width?{width:i??C.width}:{},...l??C.minWidth?{minWidth:l??C.minWidth}:{},...c??C.maxWidth?{maxWidth:c??C.maxWidth}:{},...d??C.height?{height:d??C.height}:{},...u??C.minHeight?{minHeight:u??C.minHeight}:{},...m??C.maxHeight?{maxHeight:m??C.maxHeight}:{},...y},R=k.useCallback(e=>{"form"===o&&n?(I.current=e,A(!0)):e()},[o,n]),P=k.useRef(null),U="destructive"!==o;if("development"===process.env.NODE_ENV&&s){const e=k.Children.toArray(s);e.some(e=>k.isValidElement(e)&&"DialogFooter"===e.type?.displayName),e.some(e=>k.isValidElement(e)&&"DialogBody"===e.type?.displayName)}return e.jsxs(Qe,{children:[e.jsx(Ke,{}),e.jsxs(_.Content,{ref:N,className:z("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border-0 border-l-[10px] border-l-primary bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",a),style:S,onInteractOutside:e=>{"form"!==o&&"destructive"!==o?b?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&n?(e.preventDefault(),void R(()=>{T.current=!0,P.current?.click()})):void v?.(e);e.preventDefault()},...w,children:[s,U&&e.jsxs(_.Close,{ref:P,onClick:e=>{T.current?T.current=!1:"form"===o&&n&&(e.preventDefault(),R(()=>{T.current=!0,P.current?.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(t.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]}),e.jsx(Ve,{open:j,onOpenChange:A,children:e.jsxs(Oe,{children:[e.jsxs(Me,{children:[e.jsx(Be,{children:p}),e.jsx(He,{children:h})]}),e.jsxs(qe,{children:[e.jsx($e,{onClick:()=>{A(!1),I.current=null},children:f}),e.jsx(We,{onClick:()=>{A(!1),I.current?.(),I.current=null},children:x})]})]})})]})});Ge.displayName=_.Content.displayName;const Ye=({className:a,showSeparator:t=!1,children:s,...r})=>e.jsxs("div",{className:z("flex flex-col flex-shrink-0",a),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),t&&e.jsx(M,{className:"mt-2"})]});Ye.displayName="DialogHeader";const Xe=({className:a,...t})=>e.jsx("div",{className:z("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",a),...t});Xe.displayName="DialogBody";const Ze=({className:a,children:t,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(M,{className:"mb-4"}),e.jsx("div",{className:z("flex flex-row justify-end gap-2",a),...s,children:t})]});Ze.displayName="DialogFooter";const ea=k.forwardRef(({className:a,...t},s)=>e.jsx(_.Title,{ref:s,className:z("text-xl font-semibold leading-none tracking-tight",a),...t}));ea.displayName=_.Title.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(_.Description,{ref:s,className:z("text-sm text-muted-foreground",a),...t})).displayName=_.Description.displayName;const aa=k.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(P.Root,{ref:r,className:z("relative overflow-hidden",a),...s,children:[e.jsx(P.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(ta,{}),e.jsx(P.Corner,{})]}));aa.displayName=P.Root.displayName;const ta=k.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(P.ScrollAreaScrollbar,{ref:r,orientation:t,className:z("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...s,children:e.jsx(P.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));function sa({open:s,onOpenChange:r,placeId:o,placeName:n,onMakeManager:i,onMakeMembers:l,currentManagerId:c,currentMemberIds:d=[]}){const{t:m}=u.useTranslation(),[p,h]=a.useState([]),[f,g]=a.useState(!1),[x,y]=a.useState(""),{data:b=[],isLoading:v}=De({enabled:s}),w=a.useMemo(()=>{let e=[...b];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return t.localeCompare(s)}),x){const a=x.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[b,x]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},k=1===p.length,j=p.length>0;return e.jsx(Je,{open:s,onOpenChange:r,children:e.jsxs(Ge,{className:"max-w-2xl",variant:"form",children:[e.jsx(Ye,{showSeparator:!0,children:e.jsxs(ea,{className:"flex items-center gap-2",children:[e.jsx(t.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs(Xe,{children:[e.jsxs("div",{className:"relative mb-4",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(re,{placeholder:"Pesquisar...",value:x,onChange:e=>y(e.target.value),className:"pl-9"})]}),e.jsx(aa,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(q,{className:"h-16 w-full"},t))}):0===w.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(t.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m(x?"leadership_no_users_found":"leadership_no_users_available")})]}):e.jsx("div",{className:"space-y-2",children:w.map(a=>{const s=a.userId===c,r=d.includes(a.userId||""),o=p.includes(a.userId||"");return e.jsxs("div",{className:z("flex items-center gap-3 p-3 rounded-lg border transition-colors",o&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(a.userId||""),children:[e.jsx(B,{checked:o,onCheckedChange:()=>N(a.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:a.userName}),s&&e.jsx(t.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(s||r)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:s?"Gestor":"Membro"})]},a.userId)})})})]}),e.jsxs(Ze,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:p.length>0&&e.jsxs("span",{children:[p.length," selecionado(s)"]})}),k&&i&&e.jsxs(K,{onClick:async()=>{if(i&&1===p.length){g(!0);try{await i(p[0],o),h([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[e.jsx(t.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),j&&l&&e.jsxs(K,{onClick:async()=>{if(l&&0!==p.length){g(!0);try{await l(p,o),h([])}finally{g(!1)}}},disabled:f,children:[e.jsx(t.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function ra({place:s,level:r=0,manageAccessConfig:o}){const{t:n}=u.useTranslation(),[i,l]=a.useState(!1),[c,d]=a.useState(!1),m=s.subPlaces&&s.subPlaces.length>0,p=s.isActive??!0,h=s.usersCount??0;return e.jsxs("div",{children:[e.jsxs(U,{open:i,onOpenChange:l,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[m?e.jsxs(D,{className:"flex items-center gap-2 flex-1",children:[e.jsx(t.ChevronRight,{className:z("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e.jsx(t.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:s.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",s.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(t.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:s.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(t.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:h})]}),e.jsx(O,{variant:p?"default":"secondary",className:"text-xs",children:p?"Ativo":"Inativo"}),o&&e.jsx(ee,{customActions:[{label:n("manage_access"),icon:t.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),m&&e.jsx(V,{children:s.subPlaces.map(a=>e.jsx(ra,{place:a,level:r+1,manageAccessConfig:o},a.id))})]}),0===r&&e.jsx(M,{}),o&&e.jsx(sa,{open:c,onOpenChange:d,placeId:s.id,placeName:s.name,onMakeManager:o.onMakeManager,onMakeMembers:o.onMakeMembers,currentManagerId:o.getCurrentManagerId?.(s.id),currentMemberIds:o.getCurrentMemberIds?.(s.id)})]})}ta.displayName=P.ScrollAreaScrollbar.displayName;const oa=new class{get baseUrl(){return Se()}async makeApiCall(e,a,t){const s=Ee.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=ye.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const o=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{o.searchParams.append(e,a)});const n=await fetch(o.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!n.ok){const e=new Error(`API call failed: ${n.status}`);throw e.status=n.status,e}return n.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const s=a.get(e.id);if(e.parentId){const r=a.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):t.push(s)}else t.push(s)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(t){if(await Ee.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(s){return be.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return be.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};exports.ManageAccessModal=sa,exports.PlaceCard=ra,exports.PlacesList=function({places:a,isLoading:s,manageAccessConfig:r}){return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):a&&0!==a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(a=>e.jsx(ra,{place:a,manageAccessConfig:r},a.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(t.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.placeService=oa;
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),s=require("react"),a=require("lucide-react"),r=require("forlogic-core"),t=require("react-i18next");function n({open:n,onOpenChange:l,placeId:c,placeName:o,onMakeManager:i,onMakeMembers:d,currentManagerId:m,currentMemberIds:u=[]}){const{t:x}=t.useTranslation(),[h,p]=s.useState([]),[g,f]=s.useState(!1),[j,N]=s.useState(""),{data:b=[],isLoading:v}=r.useQualiexUsers({enabled:n}),w=s.useMemo(()=>{let e=[...b];if(e.sort((e,s)=>{const a=e.userName?.toLowerCase()||"",r=s.userName?.toLowerCase()||"";return a.localeCompare(r)}),j){const s=j.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(s)||e.userEmail?.toLowerCase().includes(s))}return e},[b,j]),C=e=>{p(s=>s.includes(e)?s.filter(s=>s!==e):[...s,e])},y=1===h.length,k=h.length>0;return e.jsx(r.Dialog,{open:n,onOpenChange:l,children:e.jsxs(r.DialogContent,{className:"max-w-2xl",variant:"form",children:[e.jsx(r.DialogHeader,{showSeparator:!0,children:e.jsxs(r.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(a.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),e.jsxs(r.DialogBody,{children:[e.jsxs("div",{className:"relative mb-4",children:[e.jsx(a.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(r.Input,{placeholder:"Pesquisar...",value:j,onChange:e=>N(e.target.value),className:"pl-9"})]}),e.jsx(r.ScrollArea,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((s,a)=>e.jsx(r.Skeleton,{className:"h-16 w-full"},a))}):0===w.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(a.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x(j?"leadership_no_users_found":"leadership_no_users_available")})]}):e.jsx("div",{className:"space-y-2",children:w.map(s=>{const t=s.userId===m,n=u.includes(s.userId||""),l=h.includes(s.userId||"");return e.jsxs("div",{className:r.cn("flex items-center gap-3 p-3 rounded-lg border transition-colors",l&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>C(s.userId||""),children:[e.jsx(r.Checkbox,{checked:l,onCheckedChange:()=>C(s.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:s.userName}),t&&e.jsx(a.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.userEmail})]}),(t||n)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},s.userId)})})})]}),e.jsxs(r.DialogFooter,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:h.length>0&&e.jsxs("span",{children:[h.length," selecionado(s)"]})}),y&&i&&e.jsxs(r.Button,{onClick:async()=>{if(i&&1===h.length){f(!0);try{await i(h[0],c),p([])}finally{f(!1)}}},disabled:g,variant:"outline",children:[e.jsx(a.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),k&&d&&e.jsxs(r.Button,{onClick:async()=>{if(d&&0!==h.length){f(!0);try{await d(h,c),p([])}finally{f(!1)}}},disabled:g,children:[e.jsx(a.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",h.length>1?"Membros":"Membro"]})]})]})})}function l({place:c,level:o=0,manageAccessConfig:i}){const{t:d}=t.useTranslation(),[m,u]=s.useState(!1),[x,h]=s.useState(!1),p=c.subPlaces&&c.subPlaces.length>0,g=c.isActive??!0,f=c.usersCount??0;return e.jsxs("div",{children:[e.jsxs(r.Collapsible,{open:m,onOpenChange:u,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*o+1+"rem"},children:[p?e.jsxs(r.CollapsibleTrigger,{className:"flex items-center gap-2 flex-1",children:[e.jsx(a.ChevronRight,{className:r.cn("h-4 w-4 transition-transform shrink-0",m&&"rotate-90")}),e.jsx(a.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:c.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",c.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(a.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(a.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:f})]}),e.jsx(r.Badge,{variant:g?"default":"secondary",className:"text-xs",children:g?"Ativo":"Inativo"}),i&&e.jsx(r.ActionMenu,{customActions:[{label:d("manage_access"),icon:a.Settings,onClick:()=>h(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),p&&e.jsx(r.CollapsibleContent,{children:c.subPlaces.map(s=>e.jsx(l,{place:s,level:o+1,manageAccessConfig:i},s.id))})]}),0===o&&e.jsx(r.Separator,{}),i&&e.jsx(n,{open:x,onOpenChange:h,placeId:c.id,placeName:c.name,onMakeManager:i.onMakeManager,onMakeMembers:i.onMakeMembers,currentManagerId:i.getCurrentManagerId?.(c.id),currentMemberIds:i.getCurrentMemberIds?.(c.id)})]})}const c=new class{get baseUrl(){return r.getQualiexApiUrl()}async makeApiCall(e,s,a){const t=r.QualiexErrorInterceptor.validateToken();if(!t.valid)throw new Error(t.message||"Token inválido");const n=r.TokenManager.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório");const l=new URL(e,this.baseUrl);Object.entries(s).forEach(([e,s])=>{l.searchParams.append(e,s)});const c=await fetch(l.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!c.ok){const e=new Error(`API call failed: ${c.status}`);throw e.status=c.status,e}return c.json()}buildHierarchy(e){const s=new Map,a=[];return e.forEach(e=>{s.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=s.get(e.id);if(e.parentId){const t=s.get(e.parentId);t?(t.subPlaces=t.subPlaces||[],t.subPlaces.push(r)):a.push(r)}else a.push(r)}),a}async getPlaces(e,s){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:s},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(a){if(await r.QualiexErrorInterceptor.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:s},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(t){return r.errorService.handleError(t instanceof Error?t:"Erro ao buscar locais após renovação de token",!0),[]}return r.errorService.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};exports.ManageAccessModal=n,exports.PlaceCard=l,exports.PlacesList=function({places:s,isLoading:r,manageAccessConfig:t}){return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):s&&0!==s.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),s.map(s=>e.jsx(l,{place:s,manageAccessConfig:t},s.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(a.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.placeService=c;
|
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 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};
|
|
1
|
+
import{jsxs as e,jsx as n}from"react/jsx-runtime";import{useState as i,useEffect as a,useCallback as r,useRef as s}from"react";import{useAuth as t,getSupabaseClient as o,resolvePublishableKey as c,TokenManager as l,Alert as d,AlertTitle as m,AlertDescription as g,toast as u,Card as p,CardContent as _,Button as h,CardHeader as f,CardTitle as v,Label as y,Input as x,Select as w,SelectTrigger as N,SelectValue as b,SelectContent as E,SelectItem as k}from"forlogic-core";import{Loader2 as S,CheckCircle2 as C,Download as D,RefreshCw as $,Upload as A,CheckCircle as P,AlertCircle as T}from"lucide-react";import{useTranslation as L}from"react-i18next";import j from"i18next";function I(){const{alias:e}=t(),[n,s]=i(null),[c,l]=i(!0);a(()=>{if(!e)return void l(!1);let n=!1;return(async()=>{l(!0);try{const i=o(),{data:a,error:r}=await i.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();n||s(a)}catch(i){n||s(null)}finally{n||l(!1)}})(),()=>{n=!0}},[e]);return{config:n,isLoading:c,saveConfig:r(async(n,i)=>{if(!e)throw new Error("Alias not available");const a=o(),{data:r,error:t}=await a.schema("common").from("sign_configs").upsert({alias:e,api_key:n,environment:i,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(t)throw t;return s(r),r},[e])}}const q=import.meta.env.VITE_SUPABASE_URL,B=c();async function F(e,n,i){const a=l.getSupabaseToken(),r={"Content-Type":"application/json",apikey:B};a&&(r.Authorization=`Bearer ${a}`);const s=await fetch(`${q}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:n,data:i})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const O={async createEnvelopeWithSigner(e){const n="d4sign"===e.provider?"d4sign":"clicksign",i="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await F(n,i,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const n="d4sign"===e.provider?"d4sign":"clicksign";return(await F(n,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let R=null;function U(){return window.Clicksign?Promise.resolve():R||(R=new Promise((e,n)=>{const i=document.createElement("script");i.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",i.onload=()=>e(),i.onerror=()=>n(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(i)}),R)}const z="clicksign-container";function K({signerId:r,environment:t="sandbox",onSign:o,onError:c,onClose:l}){const{t:d}=L(),m=s(null),[g,u]=i(!0),[p,_]=i(null);return a(()=>{let e=!1;return m.current&&(m.current.unmount(),m.current=null),_(null),u(!0),U().then(()=>{if(e)return;const n=new window.Clicksign(r);n.endpoint="production"===t?"https://app.clicksign.com":"https://sandbox.clicksign.com",n.origin=window.origin,n.mount(z),n.on("loaded",function(){u(!1)}),n.on("signed",function(){o?.()}),n.on("resized",function(e){const n=e,i=document.getElementById(z);i&&n?.data?.height&&(i.style.height=n.data.height+"px")}),n.on("error",function(e){u(!1),c?.(e instanceof Error?e:new Error(d("sign_widget_error")))}),n.on("closed",function(){l?.()}),m.current=n}).catch(n=>{e||(_("Falha ao carregar o script de assinatura."),u(!1),c?.(n))}),()=>{e=!0,m.current&&(m.current.unmount(),m.current=null)}},[r,t]),e("div",{className:"relative h-full",children:[g&&n("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[n(S,{className:"h-5 w-5 animate-spin"}),n("span",{className:"text-sm",children:"Carregando documento..."})]})}),p&&n("div",{className:"absolute inset-0 flex items-center justify-center",children:n("p",{className:"text-sm text-destructive",children:p})}),n("div",{id:z,style:{height:"600px"}})]})}function H({documentKey:t,signerEmail:o,signerName:c,keySigner:l,environment:u,onSign:p,onError:_}){const h=s(null),[f,v]=i("loading"),[y,x]=i(null),w="production"===u?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",N=(()=>{const e=new URLSearchParams({email:o,display_name:c||"",disable_preview:"0"});return l&&e.set("key_signer",l),`${w}/${t}?${e.toString()}`})(),b=r(e=>"signed"===e.data?(v("ready"),void p?.()):"wrong-data"===e.data?(v("error"),x(j.t("sign_incorrect_data")),void _?.(new Error(j.t("sign_incorrect_data")))):void 0,[p,_]);a(()=>(window.addEventListener("message",b,!1),()=>{window.removeEventListener("message",b,!1)}),[b]);const E=r(()=>{"loading"===f&&v("ready")},[f]);return"error"===f?e(d,{variant:"danger",className:"my-4",children:[n(m,{children:j.t("sign_doc_load_error")}),n(g,{children:y||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e("div",{className:"relative h-full",children:["loading"===f&&n("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[n(S,{className:"h-5 w-5 animate-spin"}),n("span",{className:"text-sm",children:"Carregando documento..."})]})}),n("iframe",{ref:h,id:"d4sign-container",src:N,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:E})]})}function M({file:o,onDocumentSigned:c,onError:l,showEventLog:d=!1}){const{user:m,alias:g}=t(),{config:f,isLoading:v}=I(),{t:y}=L(),[x,w]=i(null),[N,b]=i(!1),[E,k]=i(null),[P,T]=i("sandbox"),[q,B]=i("clicksign"),[F,R]=i(null),[U,z]=i(null),[M,V]=i(!1),[W,J]=i(0),[Y,G]=i(!1),[Q,X]=i([]),Z=s(null),ee=s(null),ne=r(e=>{d&&X(n=>[...n,`[${(new Date).toLocaleTimeString()}] ${e}`])},[d]),ie=r(async e=>{if(w(e),k(null),R(null),z(null),ne(`Arquivo selecionado: ${e.name}`),g&&m){b(!0);try{const n=f?.provider??"clicksign";B(n),ne(`Provedor resolvido: ${n}`);const i=new FileReader,a=await new Promise((n,a)=>{i.onload=()=>{const e=i.result;n(e)},i.onerror=a,i.readAsDataURL(e)});ne(`Criando envelope para assinatura via ${n}...`);const r=await O.createEnvelopeWithSigner({alias:g,contentBase64:a,filename:e.name,signerEmail:m.email||"",signerName:m.name||"",provider:n});ne(`Envelope criado: ${r.envelope_id}`),R({envelope_id:r.envelope_id,document_id:r.document_id,signer_email:r.signer_email,key_signer:r.signer_id}),T(r.environment),B(r.provider||n),"d4sign"===n?(ne("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),k(r.document_id),u.success(y("sign_doc_sent","Documento enviado! Assine abaixo."))):r.signer_id?(ne(`Signer ID obtido: ${r.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),k(r.signer_id),u.success(y("sign_doc_sent","Documento enviado! Assine abaixo."))):(ne(j.t("sign_signer_unavailable")),u.error(y("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),l?.(new Error(y("sign_signer_unavailable"))))}catch(n){const e=n instanceof Error?n:new Error(y("sign_process_error",y("sign_doc_process_error"))),i=e.message||"";i.includes("MONTHLY_LIMIT_REACHED")?(ne(j.t("sign_monthly_limit")),u.error(y("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(ne(`Erro: ${i}`),u.error(i)),l?.(e)}finally{b(!1)}}},[g,m,ne,l,f]);a(()=>{o&&g&&m&&!v&&o!==ee.current&&(ee.current=o,ie(o))},[o,g,m,v,ie]);const ae=r(async()=>{if(!F||!g)return;V(!0),J(0),G(!1),ne("Buscando documento assinado...");for(let n=1;n<=6;n++){J(n),ne(`Tentativa ${n}/6...`);try{const e=await O.getSignedDocument({alias:g,envelopeId:F.envelope_id,documentId:F.document_id,provider:q});if(e.download_url)return ne(j.t("sign_doc_available")),z(e.download_url),void V(!1)}catch(e){ne(`Erro na tentativa ${n}: ${e instanceof Error?e.message:y("unknown_error")}`)}n<6&&(ne("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}ne(j.t("sign_fetch_failed")),V(!1),G(!0)},[F,g,ne,q]),re=r(async()=>{ne("Documento assinado com sucesso!"),u.success(y("sign_signed_success","Documento assinado com sucesso!")),k(null),F&&g&&(c?.({success:!0,provider:q,envelope_id:F.envelope_id,document_id:F.document_id,signer_id:E||"",environment:P}),await ae())},[ne,c,F,E,g,P,q,ae]);if(!g)return n(p,{className:"border-amber-200 bg-amber-50",children:n(_,{className:"flex items-start gap-3 py-6",children:e("div",{children:[n("p",{className:"font-medium text-amber-800",children:y("sign_auth_required","Autenticação necessária")}),n("p",{className:"text-sm text-amber-700 mt-1",children:y("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const se="d4sign"===q?"D4Sign":"Clicksign",te=()=>d&&Q.length>0?n("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:Q.map((e,i)=>n("div",{children:e},i))}):null;return F&&!E&&(U||M||Y)?e("div",{className:"space-y-4",children:[n(p,{className:"border-green-200 bg-green-50",children:e(_,{className:"flex flex-col items-center gap-4 py-8",children:[n(C,{className:"h-12 w-12 text-green-600"}),e("div",{className:"text-center",children:[n("p",{className:"text-lg font-semibold text-green-800",children:y("sign_signed_success","Documento assinado com sucesso!")}),n("p",{className:"text-sm text-green-700 mt-1",children:x?.name})]}),M?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:[n(S,{className:"h-4 w-4 animate-spin"}),y("sign_preparing_doc","Preparando documento assinado...")," (",y("sign_attempt","tentativa")," ",W,"/6)"]}),n("p",{className:"text-xs text-muted-foreground",children:y("sign_waiting_provider",`Aguardando processamento pelo ${se}...`)})]}):U?n(h,{asChild:!0,variant:"default",className:"gap-2",children:e("a",{href:U,target:"_blank",rel:"noopener noreferrer",children:[n(D,{className:"h-4 w-4"}),y("sign_download_signed","Baixar documento assinado")]})}):Y?e("div",{className:"text-center space-y-3",children:[e("div",{className:"space-y-1",children:[n("p",{className:"text-sm text-muted-foreground",children:y("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),n("p",{className:"text-xs text-muted-foreground",children:y("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e(h,{variant:"secondary",className:"gap-2",onClick:ae,children:[n($,{className:"h-4 w-4"}),y("sign_try_again","Tentar novamente")]})]}):null]})}),n(te,{})]}):E?e("div",{className:"space-y-4",children:["d4sign"===q?n(H,{documentKey:E,signerEmail:F?.signer_email||m?.email||"",signerName:m?.name,keySigner:F?.key_signer,environment:P,onSign:re,onError:l}):n(K,{signerId:E,environment:P,onSign:re,onError:l}),n(te,{})]}):o&&(N||v)?n(p,{children:e(_,{className:"flex items-center justify-center gap-3 py-10",children:[n(S,{className:"h-6 w-6 animate-spin text-primary"}),n("p",{className:"font-medium",children:y("sign_sending_doc","Enviando documento para assinatura...")})]})}):e("div",{className:"space-y-4",children:[n("input",{ref:Z,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const n=e.target.files?.[0];n&&"application/pdf"===n.type?ie(n):u.error(y("sign_select_pdf","Selecione um arquivo PDF"))}}),n(p,N?{children:e(_,{className:"flex items-center justify-center gap-3 py-10",children:[n(S,{className:"h-6 w-6 animate-spin text-primary"}),n("p",{className:"font-medium",children:y("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Z.current?.click(),children:e(_,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[n(A,{className:"h-8 w-8 text-muted-foreground"}),e("div",{className:"text-center",children:[n("p",{className:"font-medium",children:y("sign_select_pdf","Selecione um arquivo PDF")}),n("p",{className:"text-sm text-muted-foreground",children:y("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),n(te,{})]})}function V({onSaved:r}){const{config:s,isLoading:t,saveConfig:o}=I(),{t:c}=L(),[l,d]=i(""),[m,g]=i("sandbox"),[C,D]=i(!1);a(()=>{!t&&s&&(d(s.api_key),g(s.environment))},[s,t]);return t?n("div",{className:"flex items-center justify-center py-8",children:n(S,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e("div",{className:"space-y-4",children:[e("div",s?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[n(P,{className:"h-4 w-4"}),n("span",{children:c("sign_configured",c("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[n(T,{className:"h-4 w-4"}),n("span",{children:c("sign_not_configured",c("sign_not_configured_unit"))})]}),e(p,{children:[n(f,{children:n(v,{className:"text-base",children:c("sign_digital_config")})}),n(_,{children:e("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){D(!0);try{await o(l.trim(),m),u.success(c("sign_config_saved",c("sign_config_saved_success"))),r?.()}catch(n){u.error(c("sign_config_save_error",c("sign_config_save_err")))}finally{D(!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:[n(y,{htmlFor:"sign-api-key",children:"API Key"}),n(x,{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:[n(y,{children:c("sign_environment","Ambiente")}),e(w,{value:m,onValueChange:e=>g(e),children:[n(N,{children:n(b,{})}),e(E,{children:[n(k,{value:"sandbox",children:"Sandbox (Testes)"}),n(k,{value:"production",children:"Produção"})]})]})]}),e(h,{type:"submit",disabled:C,children:[C&&n(S,{className:"mr-2 h-4 w-4 animate-spin"}),s?c("sign_update_config",c("sign_update_config_btn")):c("sign_save_config",c("sign_save_config_btn"))]})]})})]})]})}export{H as D4SignWidget,M as DocumentSigner,V as SignConfigForm,K as SignWidget,U as loadClicksignScript,O as signService,I as useSignConfig};
|