forlogic-core 2.3.0 → 2.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.note/memory/patterns/dynamic-supabase-config.md +2 -2
- package/.note/memory/patterns/environment-detection-logic.md +21 -15
- package/README.md +1 -1
- package/dist/action-plans/config/environments.d.ts +18 -3
- package/dist/action-plans/config/index.d.ts +3 -3
- package/dist/action-plans/index.d.ts +1 -1
- package/dist/audit-trail/config/environments.d.ts +18 -3
- package/dist/audit-trail/config/index.d.ts +3 -3
- package/dist/audit-trail/index.d.ts +1 -1
- package/dist/config/environments.d.ts +18 -3
- package/dist/config/index.d.ts +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/leadership/config/environments.d.ts +18 -3
- package/dist/leadership/config/index.d.ts +3 -3
- package/dist/leadership/index.d.ts +1 -1
- package/dist/leadership/index.esm.js +1 -1
- package/dist/leadership/index.js +1 -1
- package/dist/places/config/environments.d.ts +18 -3
- package/dist/places/config/index.d.ts +3 -3
- package/dist/places/index.d.ts +1 -1
- package/dist/places/index.esm.js +1 -1
- package/dist/places/index.js +1 -1
- package/dist/sign/config/environments.d.ts +18 -3
- package/dist/sign/config/index.d.ts +3 -3
- package/dist/sign/index.d.ts +1 -1
- package/dist/sign/index.esm.js +1 -1
- package/dist/sign/index.js +1 -1
- package/dist/vite/index.esm.js +24 -1
- package/dist/vite/index.js +24 -0
- package/docs/WORKSPACE_KNOWLEDGE.md +1 -1
- package/docs/design-system/patterns/core-providers.md +11 -2
- package/docs/design-system/patterns/feature-flags.md +53 -21
- package/package.json +1 -1
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 o,useContext as s,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 S}from"sonner";import*as C 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 L from"@radix-ui/react-hover-card";import z from"i18next";import{useQuery as O}from"@tanstack/react-query";import{createClient as M}from"@supabase/supabase-js";import*as B from"@radix-ui/react-dialog";import*as j from"@radix-ui/react-alert-dialog";import*as H from"@radix-ui/react-scroll-area";const W=A.Root,$=A.CollapsibleTrigger,q=A.CollapsibleContent;function J(...e){return E(T(e))}const Q=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"}}),F=t.forwardRef(({className:a,variant:t,...r},o)=>e("div",{ref:o,className:J(Q({variant:t}),a),...r}));F.displayName="Badge";const K=t.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...o},s)=>e(C.Root,{ref:s,decorative:r,orientation:t,className:J("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...o}));K.displayName=C.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,...o},s)=>e(R.Portal,{container:r,children:e(R.Content,{ref:s,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),...o})}));ae.displayName=R.Content.displayName;t.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:o},s)=>{const n="horizontal"===a;return e("div",{ref:s,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",o),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:o=!1,...s},n)=>e(o?U:"button",{className:J(te({variant:t,size:r,className:a})),ref:n,...s}));re.displayName="Button";const oe=D.Root,se=D.Trigger;t.forwardRef(({className:t,inset:r,children:o,...s},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),...s,children:[o,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},o)=>e(D.Portal,{children:e(D.Content,{ref:o,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},o)=>e(D.Item,{ref:o,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:o,...s},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:o,...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(i,{className:"h-4 w-4"})})}),r]})).displayName=D.CheckboxItem.displayName;t.forwardRef(({className:t,children:r,...o},s)=>a(D.RadioItem,{ref:s,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),...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(c,{className:"h-2 w-2 fill-current"})})}),r]})).displayName=D.RadioItem.displayName;t.forwardRef(({className:a,inset:t,...r},o)=>e(D.Label,{ref:o,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:o},s)=>{const n=e(ie,{ref:s,className:J("opacity-50 cursor-not-allowed pointer-events-auto",o),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:o,onToggleStatus:s,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"}),s&&e.push({key:"toggle-status",icon:n?m:u,label:n?y("deactivate","Inativar"):y("activate","Ativar"),onClick:s,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})}),o&&l&&e.push({key:"delete",icon:p,label:y("remove","Remover"),onClick:o,variant:"destructive"}),e},[t,o,s,n,i,l,c,y]);return 0===b.length?null:"dropdown"===f?e(X,{delayDuration:200,children:a(oe,{children:[e(se,{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,...o},s)=>a(V.Trigger,{ref:s,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),...o,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:o="popper",container:s,collisionBoundary:n,...i},l)=>e(V.Portal,{container:s,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"===o&&"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:o,collisionBoundary:n,...i,children:[e(me,{}),e(V.Viewport,{className:J("p-1","popper"===o&&"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:o,...s},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),...s,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:o})]})}).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:o,showCharCount:s,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:o,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}),s&&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,...o},s)=>e(L.Content,{ref:s,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),...o})).displayName=L.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 o=e.split(".");if(3!==o.length)return null;const s=o[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),a=atob(e),t=new Uint8Array(a.length);for(let o=0;o<a.length;o++)t[o]=a.charCodeAt(o);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(s),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(s),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(o){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const o=this.parseJwtPayload(a),s=this.parseJwtPayload(e);if(!o){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(!s){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(s?.exp&&s.exp<i){const e="Access token expirado - pode precisar de refresh";t.push(e),n=!1}if(o.exp&&o.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(o){const e=`Erro na validação de tokens: ${o}`;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="qualiex_access_token",ge="qualiex_id_token",ye="supabase_token",be="oauth_state",xe="oauth_nonce",ve="selected_alias",we="manual_logout",Ne="supabase_project_id",ke={setAccessToken:e=>localStorage.setItem(fe,e),getAccessToken:()=>localStorage.getItem(fe),setIdToken:e=>localStorage.setItem(ge,e),getIdToken:()=>localStorage.getItem(ge),getSupabaseToken:()=>localStorage.getItem(ye),setOAuthState:e=>sessionStorage.setItem(be,e),getOAuthState:()=>sessionStorage.getItem(be),clearOAuthState:()=>sessionStorage.removeItem(be),setOAuthNonce:e=>sessionStorage.setItem(xe,e),getOAuthNonce:()=>sessionStorage.getItem(xe),clearOAuthNonce:()=>sessionStorage.removeItem(xe),setSelectedAlias:e=>localStorage.setItem(ve,e),getSelectedAlias:()=>localStorage.getItem(ve),clearSelectedAlias:()=>localStorage.removeItem(ve),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!ke.getAccessToken()||!ke.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(Ne);return a&&a!==e?(ke.clearAll(),localStorage.setItem(Ne,e),!0):(a||localStorage.setItem(Ne,e),!1)},setSupabaseToken:e=>{localStorage.setItem(ye,e),ke._clearValidationCache()},areAllTokensValid:()=>{const e=ke.getAccessToken(),a=ke.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=ke.getAccessToken(),t=ke.getIdToken(),r=ke.getSupabaseToken();return a&&ke.isTokenExpired(a)&&(localStorage.removeItem(fe),e=!0),t&&ke.isTokenExpired(t)&&(localStorage.removeItem(ge),e=!0),r&&ke.isTokenExpired(r)&&(localStorage.removeItem(ye),e=!0),e},clearAll:()=>{localStorage.removeItem(fe),localStorage.removeItem(ge),localStorage.removeItem(ye),localStorage.removeItem(ve),localStorage.removeItem(we),sessionStorage.removeItem(be),sessionStorage.removeItem(xe),ke._clearValidationCache()},setManualLogout:()=>localStorage.setItem(we,"true"),isManualLogout:()=>"true"===localStorage.getItem(we),clearManualLogout:()=>localStorage.removeItem(we),isTokenExpired:e=>{try{return he.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{ke._validationCache.isValid=!1,ke._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=ke.getSupabaseToken();if(!e)return!1;if(ke.isTokenExpired(e))return ke._clearValidationCache(),ke._handleExpiredToken(),!1;const a=Date.now();return a-ke._validationCache.timestamp<ke._validationCache.cacheValidityMs?ke._validationCache.isValid:(ke._validationCache.isValid=!0,ke._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>ke.isSupabaseTokenValid()?ke.getSupabaseToken():null,_handleExpiredToken:()=>{ke.clearAll()},extractTokenData:()=>{if(!ke.isSupabaseTokenValid())return null;const e=ke.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,o=a.place_name||null;let s=a.company_id;if(!s&&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){s=e[7];break}}}return{alias:t,companyId:s,placeId:r,placeName:o,payload:a}}catch(a){return ke._handleExpiredToken(),null}},getCompanyId:e=>{const a=ke.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(o){}const t=ke.extractTokenData();if(t?.companyId)return t.companyId;const r=ke.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(o){}return null},getCompanyIdInt:e=>{const a=[ke.getAccessToken(),ke.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=ke.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=ke.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 Ae=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);S.error(e,{description:t})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?z.t("error_session_expired"):a.includes("token")||a.includes("autenticação")?z.t("error_authentication"):a.includes("api")||a.includes("network")?z.t("error_connection"):"Erro"}success(e,a){S.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 Ie(e){return!!e&&e.startsWith("eyJ")}let Te=!1;class Ee{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;Te?Ie(a):e&&Ie(a)?Te=!0:Ie(a)?Te=!0:Te=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:this.config.key};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return M(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(!Ee.instance){const e=function(){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}();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).");Ee.instance=new Ee(e)}return Ee.instance}getClient(){const e=ke.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 Ae.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Se(){return Ee.getInstance().getClient()}class Ce{static async generateToken(e,a,t,r=!1){try{if(!r){const e=ke.getSupabaseToken();if(e&&ke.isSupabaseTokenValid())return e}const o=Se(),{data:s,error:n}=await o.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return n&&(n.message?.includes("401")||n.message?.includes("Unauthorized"))?(t?.(),null):s?.access_token?(ke.setSupabaseToken(s.access_token),s.access_token):null}catch(o){return o instanceof Error&&(o.message.includes("401")||o.message.includes("Unauthorized"))&&t?.(),null}}}class _e{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=ke.getAccessToken(),t=ke.getSelectedAlias();if(!a||!t)return null;const r=await Ce.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}_e.regenerationPromise=null,_e.onLogoutCallback=null;class Re{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(ke.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 Pe{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 _e.attemptRegeneration()?(this.isRetrying=!1,!0):(Re.handleError(e),this.isRetrying=!1,!1)}catch(r){return Re.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=ke.getAccessToken();return e?ke.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."}}}Pe.isRetrying=!1;const Ue={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},De={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function Ve(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return"ccjfvpnndclajkleyqkc"===e?Ue:De}const Le={get oauth(){const e=Ve();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},ze=()=>Ve().qualiexApiUrl;import.meta.env.VITE_IS_QUALIEX;const Oe=new class{get baseUrl(){return ze()}async makeApiCall(e,a,t){const r=Pe.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const o=ke.getAccessToken();if(!o)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 s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const n=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${o}`,"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 Ae.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(e=>this.mapToQualiexUser(e)):(Ae.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(o){if(await Pe.handleApiError(o))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a," após retry")??[]}catch(s){return Ae.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}return Ae.handleError(o instanceof Error?o.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 Ae.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=ke.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||""})):(Ae.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await Pe.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 Ae.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Ae.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})):(Ae.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await Pe.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 Ae.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return Ae.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};var Me;const Be={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};Me=class{static async initialize(){try{const e=!0;if(e){if(ke.checkProjectMismatch())return{...Be}}if(!ke.hasAllTokens()||!ke.areAllTokensValid())return ke.clearExpiredTokens(),{...Be};const a=ke.getAccessToken(),t=ke.getIdToken();ke.clearManualLogout();const r=this.extractUserFromIdToken(t,a),o=this.extractCompaniesFromIdToken(t),s=this.extractAliasFromAccessToken(a),n=e?ke.extractTokenData():null,i=n?.alias;let l=null;if(i&&o.some(e=>e.alias===i))l=i;else{const e=ke.getSelectedAlias(),a=e&&o.some(a=>a.alias===e);l=a?e:s||o[0]?.alias||null}if(e&&(!ke.isSupabaseTokenValid()&&l&&await _e.attemptRegeneration(),!ke.isSupabaseTokenValid()))return{...Be};let c=null;if(l){const e=ke.getCompanyId(l),a=o.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:o,selectedUnit:c,userId:r?.id||null,userAlias:r?.id||null,placeId:d,placeName:m,activePlaceId:d,activePlaceName:m}}catch(e){return{...Be}}}static async loginDev(){try{const e=Se(),{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==";ke.setOAuthState(e);const a=ke.generateOAuthNonce();ke.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Le.oauth.authUrl);r.searchParams.set("client_id",Le.oauth.clientId),r.searchParams.set("response_type",Le.oauth.responseType),r.searchParams.set("scope",Le.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"),o=t("id_token"),s=t("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(r&&o){const e=ke.getAccessToken();e!==r&&ke.clearAll()}const n=!0;if(ke.hasAllTokens()){if(n){ke.getValidSupabaseToken()||await _e.attemptRegeneration(!0)}return!0}const i=r,l=o;if(!i||!l)throw new Error("Tokens não encontrados na URL de callback");ke.setAccessToken(i),ke.setIdToken(l),ke.clearManualLogout();const c=this.extractAliasFromAccessToken(i);if(c)ke.setSelectedAlias(c);else{const e=this.extractCompaniesFromIdToken(l);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");ke.setSelectedAlias(e[0].alias)}if(n){if(!await _e.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return ke.clearOAuthState(),ke.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){ke.setManualLogout(),ke.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return 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,o]=a[e].split("|");r&&o&&t.push({id:"",alias:r.trim(),name:o.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}},_e.setLogoutCallback(()=>{Me.logout()});const je=o(void 0),He=(e={})=>{const{user:a,alias:t}=(()=>{const e=s(je);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 O({queryKey:["qualiex-users",t,o],queryFn:()=>Oe.getUsers(t,o),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},We=j.Root,$e=j.Portal,qe=t.forwardRef(({className:a,...t},r)=>e(j.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}));qe.displayName=j.Overlay.displayName;const Je=t.forwardRef(({className:t,...r},o)=>a($e,{children:[e(qe,{}),e(j.Content,{ref:o,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})]}));Je.displayName=j.Content.displayName;const Qe=({className:a,...t})=>e("div",{className:J("flex flex-col space-y-2 text-center sm:text-left",a),...t});Qe.displayName="AlertDialogHeader";const Fe=({className:a,...t})=>e("div",{className:J("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Fe.displayName="AlertDialogFooter";const Ke=t.forwardRef(({className:a,...t},r)=>e(j.Title,{ref:r,className:J("text-lg font-semibold",a),...t}));Ke.displayName=j.Title.displayName;const Ge=t.forwardRef(({className:a,...t},r)=>e(j.Description,{ref:r,className:J("text-sm text-muted-foreground",a),...t}));Ge.displayName=j.Description.displayName;const Ye=t.forwardRef(({className:a,...t},r)=>e(j.Action,{ref:r,className:J(te(),a),...t}));Ye.displayName=j.Action.displayName;const Xe=t.forwardRef(({className:a,...t},r)=>e(j.Cancel,{ref:r,className:J(te({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Xe.displayName=j.Cancel.displayName;const Ze=B.Root,ea=B.Portal,aa=t.forwardRef(({className:a,...t},r)=>e(B.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}));aa.displayName=B.Overlay.displayName;const ta={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"}},ra=t.forwardRef(({className:r,children:o,size:s,variant:n="informative",isDirty:i,customWidth:l,customMinWidth:c,customMaxWidth:d,customHeight:m,customMinHeight:u,customMaxHeight:p,unsavedChangesTitle:h=z.t("unsaved_changes"),unsavedChangesDescription:f=z.t("unsaved_changes_description"),cancelText:g=z.t("cancel"),leaveWithoutSavingText:b=z.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),S=s??(l||c||d||m||u||p?void 0:"md"),C=S?ta[S]:{},_={...l??C.width?{width:l??C.width}:{},...c??C.minWidth?{minWidth:c??C.minWidth}:{},...d??C.maxWidth?{maxWidth:d??C.maxWidth}:{},...m??C.height?{height:m??C.height}:{},...u??C.minHeight?{minHeight:u??C.minHeight}:{},...p??C.maxHeight?{maxHeight:p??C.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&&o){const e=t.Children.toArray(o);e.some(e=>t.isValidElement(e)&&"DialogFooter"===e.type?.displayName),e.some(e=>t.isValidElement(e)&&"DialogBody"===e.type?.displayName)}return a(ea,{children:[e(aa,{}),a(B.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:[o,U&&a(B.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(We,{open:A,onOpenChange:I,children:a(Je,{children:[a(Qe,{children:[e(Ke,{children:h}),e(Ge,{children:f})]}),a(Fe,{children:[e(Xe,{onClick:()=>{I(!1),T.current=null},children:g}),e(Ye,{onClick:()=>{I(!1),T.current?.(),T.current=null},children:b})]})]})})]})});ra.displayName=B.Content.displayName;const oa=({className:t,showSeparator:r=!1,children:o,...s})=>a("div",{className:J("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:o}),r&&e(K,{className:"mt-2"})]});oa.displayName="DialogHeader";const sa=({className:a,...t})=>e("div",{className:J("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",a),...t});sa.displayName="DialogBody";const na=({className:t,children:r,...o})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(K,{className:"mb-4"}),e("div",{className:J("flex flex-row justify-end gap-2",t),...o,children:r})]});na.displayName="DialogFooter";const ia=t.forwardRef(({className:a,...t},r)=>e(B.Title,{ref:r,className:J("text-xl font-semibold leading-none tracking-tight",a),...t}));ia.displayName=B.Title.displayName;t.forwardRef(({className:a,...t},r)=>e(B.Description,{ref:r,className:J("text-sm text-muted-foreground",a),...t})).displayName=B.Description.displayName;const la=t.forwardRef(({className:t,children:r,...o},s)=>a(H.Root,{ref:s,className:J("relative overflow-hidden",t),...o,children:[e(H.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(ca,{}),e(H.Corner,{})]}));la.displayName=H.Root.displayName;const ca=t.forwardRef(({className:a,orientation:t="vertical",...r},o)=>e(H.ScrollAreaScrollbar,{ref:o,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 da({open:t,onOpenChange:o,placeId:s,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}=He({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,S=p.length>0;return e(Ze,{open:t,onOpenChange:o,children:a(ra,{className:"max-w-2xl",variant:"form",children:[e(oa,{showSeparator:!0,children:a(ia,{className:"flex items-center gap-2",children:[e(b,{className:"h-5 w-5"}),"Gerenciar Acessos - ",i]})}),a(sa,{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(la,{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,o=m.includes(t.userId||""),s=p.includes(t.userId||"");return a("div",{className:J("flex items-center gap-3 p-3 rounded-lg border transition-colors",s&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>T(t.userId||""),children:[e(Y,{checked:s,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||o)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(na,{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],s),h([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[e(v,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),S&&c&&a(re,{onClick:async()=>{if(c&&0!==p.length){g(!0);try{await c(p,s),h([])}finally{g(!1)}}},disabled:f,children:[e(w,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function ma({place:t,level:r=0,manageAccessConfig:o}){const{t:s}=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($,{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(F,{variant:p?"default":"secondary",className:"text-xs",children:p?"Ativo":"Inativo"}),o&&e(ce,{customActions:[{label:s("manage_access"),icon:k,onClick:()=>m(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),u&&e(q,{children:t.subPlaces.map(a=>e(ma,{place:a,level:r+1,manageAccessConfig:o},a.id))})]}),0===r&&e(K,{}),o&&e(da,{open:d,onOpenChange:m,placeId:t.id,placeName:t.name,onMakeManager:o.onMakeManager,onMakeMembers:o.onMakeMembers,currentManagerId:o.getCurrentManagerId?.(t.id),currentMemberIds:o.getCurrentMemberIds?.(t.id)})]})}function ua({places:t,isLoading:r,manageAccessConfig:o}){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(ma,{place:a,manageAccessConfig:o},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."})]})]})}ca.displayName=H.ScrollAreaScrollbar.displayName;const pa=new class{get baseUrl(){return ze()}async makeApiCall(e,a,t){const r=Pe.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const o=ke.getAccessToken();if(!o)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const n=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${o}`,"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 o=a.get(e.parentId);o?(o.subPlaces=o.subPlaces||[],o.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 Pe.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 Ae.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Ae.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};export{da as ManageAccessModal,ma as PlaceCard,ua as PlacesList,pa as placeService};
|
|
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};
|
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),C=N(p),E=N(h),S=N(f),_=N(b),R=N(v),P=N(w);const U=j.Root,D=j.CollapsibleTrigger,V=j.CollapsibleContent;function L(...e){return n.twMerge(o.clsx(e))}const z=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:L(z({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:L("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:L("w-full caption-bottom text-[13px] table-fixed",a),...t})).displayName="Table";k.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:L("[&_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:L("[&_tr:last-child]:border-0",a),...t})).displayName="TableBody";k.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:L("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:L("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:L("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:L("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t})).displayName="TableCell";function B({className:a,...t}){return e.jsx("div",{className:L("animate-pulse rounded-md bg-muted",a),...t})}k.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:L("mt-4 text-sm text-muted-foreground",a),...t})).displayName="TableCaption";const q=k.forwardRef(({className:a,...s},r)=>e.jsx(I.Root,{ref:r,className:L("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:L("flex items-center justify-center text-current"),children:e.jsx(t.Check,{className:"h-4 w-4"})})}));q.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:L("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:L("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:L("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"}}),F=k.forwardRef(({className:a,variant:t,size:s,asChild:r=!1,...o},n)=>{const i=r?m.Slot:"button";return e.jsx(i,{className:L(Q({variant:t,size:s,className:a})),ref:n,...o})});F.displayName="Button";const K=C.Root,G=C.Trigger;k.forwardRef(({className:a,inset:s,children:r,...o},n)=>e.jsxs(C.SubTrigger,{ref:n,className:L("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=C.SubTrigger.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(C.SubContent,{ref:s,className:L("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=C.SubContent.displayName;const Y=k.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(C.Portal,{children:e.jsx(C.Content,{ref:r,sideOffset:t,className:L("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=C.Content.displayName;const X=k.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(C.Item,{ref:r,className:L("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=C.Item.displayName;k.forwardRef(({className:a,children:s,checked:r,...o},n)=>e.jsxs(C.CheckboxItem,{ref:n,className:L("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(C.ItemIndicator,{children:e.jsx(t.Check,{className:"h-4 w-4"})})}),s]})).displayName=C.CheckboxItem.displayName;k.forwardRef(({className:a,children:s,...r},o)=>e.jsxs(C.RadioItem,{ref:o,className:L("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(C.ItemIndicator,{children:e.jsx(t.Circle,{className:"h-2 w-2 fill-current"})})}),s]})).displayName=C.RadioItem.displayName;k.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(C.Label,{ref:r,className:L("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s})).displayName=C.Label.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(C.Separator,{ref:s,className:L("-mx-1 my-1 h-px bg-muted",a),...t})).displayName=C.Separator.displayName;const Z=k.forwardRef(({children:a,disabledReason:t,className:s},r)=>{const o=e.jsx(X,{ref:r,className:L("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(K,{children:[e.jsx(G,{asChild:!0,children:e.jsx(F,{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(F,{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(E.Trigger,{ref:o,className:L("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(E.Icon,{asChild:!0,children:e.jsx(t.ChevronDown,{className:"h-4 w-4 opacity-50"})})]})).displayName=E.Trigger.displayName;const te=k.forwardRef(({className:a,...s},r)=>e.jsx(E.ScrollUpButton,{ref:r,className:L("flex cursor-default items-center justify-center py-1",a),...s,children:e.jsx(t.ChevronUp,{className:"h-4 w-4"})}));te.displayName=E.ScrollUpButton.displayName;const se=k.forwardRef(({className:a,...s},r)=>e.jsx(E.ScrollDownButton,{ref:r,className:L("flex cursor-default items-center justify-center py-1",a),...s,children:e.jsx(t.ChevronDown,{className:"h-4 w-4"})}));se.displayName=E.ScrollDownButton.displayName;k.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:o,...n},i)=>e.jsx(E.Portal,{container:r,children:e.jsxs(E.Content,{ref:i,className:L("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(E.Viewport,{className:L("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=E.Content.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(E.Label,{ref:s,className:L("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t})).displayName=E.Label.displayName;k.forwardRef(({className:a,children:s,...r},o)=>{const{showCheck:n}=k.useContext(ae);return e.jsxs(E.Item,{ref:o,className:L("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(E.ItemIndicator,{children:e.jsx(t.Check,{className:"h-4 w-4"})})}),e.jsx(E.ItemText,{children:s})]})}).displayName=E.Item.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(E.Separator,{ref:s,className:L("-mx-1 my-1 h-px bg-muted",a),...t})).displayName=E.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:L("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:L("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="qualiex_access_token",ie="qualiex_id_token",le="supabase_token",ce="oauth_state",de="oauth_nonce",ue="selected_alias",me="manual_logout",pe="supabase_project_id",he={setAccessToken:e=>localStorage.setItem(ne,e),getAccessToken:()=>localStorage.getItem(ne),setIdToken:e=>localStorage.setItem(ie,e),getIdToken:()=>localStorage.getItem(ie),getSupabaseToken:()=>localStorage.getItem(le),setOAuthState:e=>sessionStorage.setItem(ce,e),getOAuthState:()=>sessionStorage.getItem(ce),clearOAuthState:()=>sessionStorage.removeItem(ce),setOAuthNonce:e=>sessionStorage.setItem(de,e),getOAuthNonce:()=>sessionStorage.getItem(de),clearOAuthNonce:()=>sessionStorage.removeItem(de),setSelectedAlias:e=>localStorage.setItem(ue,e),getSelectedAlias:()=>localStorage.getItem(ue),clearSelectedAlias:()=>localStorage.removeItem(ue),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!he.getAccessToken()||!he.getIdToken()),checkProjectMismatch:()=>{const e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(pe);return a&&a!==e?(he.clearAll(),localStorage.setItem(pe,e),!0):(a||localStorage.setItem(pe,e),!1)},setSupabaseToken:e=>{localStorage.setItem(le,e),he._clearValidationCache()},areAllTokensValid:()=>{const e=he.getAccessToken(),a=he.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=he.getAccessToken(),t=he.getIdToken(),s=he.getSupabaseToken();return a&&he.isTokenExpired(a)&&(localStorage.removeItem(ne),e=!0),t&&he.isTokenExpired(t)&&(localStorage.removeItem(ie),e=!0),s&&he.isTokenExpired(s)&&(localStorage.removeItem(le),e=!0),e},clearAll:()=>{localStorage.removeItem(ne),localStorage.removeItem(ie),localStorage.removeItem(le),localStorage.removeItem(ue),localStorage.removeItem(me),sessionStorage.removeItem(ce),sessionStorage.removeItem(de),he._clearValidationCache()},setManualLogout:()=>localStorage.setItem(me,"true"),isManualLogout:()=>"true"===localStorage.getItem(me),clearManualLogout:()=>localStorage.removeItem(me),isTokenExpired:e=>{try{return oe.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{he._validationCache.isValid=!1,he._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=he.getSupabaseToken();if(!e)return!1;if(he.isTokenExpired(e))return he._clearValidationCache(),he._handleExpiredToken(),!1;const a=Date.now();return a-he._validationCache.timestamp<he._validationCache.cacheValidityMs?he._validationCache.isValid:(he._validationCache.isValid=!0,he._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>he.isSupabaseTokenValid()?he.getSupabaseToken():null,_handleExpiredToken:()=>{he.clearAll()},extractTokenData:()=>{if(!he.isSupabaseTokenValid())return null;const e=he.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 he._handleExpiredToken(),null}},getCompanyId:e=>{const a=he.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=he.extractTokenData();if(t?.companyId)return t.companyId;const s=he.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=[he.getAccessToken(),he.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=he.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=he.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 fe=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 ge(e){return!!e&&e.startsWith("eyJ")}let xe=!1;class ye{constructor(e){this.currentToken=null,this.config=e,function(){const e=(void 0).VITE_SUPABASE_PK_OVERRIDE,a=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;xe?ge(a):e&&ge(a)?xe=!0:ge(a)?xe=!0:xe=!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(!ye.instance){const e=function(){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}();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).");ye.instance=new ye(e)}return ye.instance}getClient(){const e=he.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 fe.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function be(){return ye.getInstance().getClient()}class ve{static async generateToken(e,a,t,s=!1){try{if(!s){const e=he.getSupabaseToken();if(e&&he.isSupabaseTokenValid())return e}const r=be(),{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?(he.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 we{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=he.getAccessToken(),t=he.getSelectedAlias();if(!a||!t)return null;const s=await ve.generateToken(a,t,this.onLogoutCallback||void 0,e);return s||null}catch(a){return null}}}we.regenerationPromise=null,we.onLogoutCallback=null;class Ne{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(he.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 ke{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 we.attemptRegeneration()?(this.isRetrying=!1,!0):(Ne.handleError(e),this.isRetrying=!1,!1)}catch(s){return Ne.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=he.getAccessToken();return e?he.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."}}}ke.isRetrying=!1;const je={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},Ae={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function Ie(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=(void 0).VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return"ccjfvpnndclajkleyqkc"===e?je:Ae}const Te={get oauth(){const e=Ie();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Ce=()=>Ie().qualiexApiUrl;(void 0).VITE_IS_QUALIEX;const Ee=new class{get baseUrl(){return Ce()}async makeApiCall(e,a,t){const s=ke.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=he.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 fe.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(e=>this.mapToQualiexUser(e)):(fe.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 ke.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",s,e);return this.parseUsersResponse(a," após retry")??[]}catch(o){return fe.handleError(o instanceof Error?o:"Erro ao buscar usuários após renovação de token",!0),[]}return fe.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 fe.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=he.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||""})):(fe.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await ke.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 fe.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return fe.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})):(fe.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await ke.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 fe.handleError(s instanceof Error?s:"Erro ao buscar associações após renovação de token",!0),[]}return fe.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};var Se;const _e={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};Se=class{static async initialize(){try{const e=!0;if(e){if(he.checkProjectMismatch())return{..._e}}if(!he.hasAllTokens()||!he.areAllTokensValid())return he.clearExpiredTokens(),{..._e};const a=he.getAccessToken(),t=he.getIdToken();he.clearManualLogout();const s=this.extractUserFromIdToken(t,a),r=this.extractCompaniesFromIdToken(t),o=this.extractAliasFromAccessToken(a),n=e?he.extractTokenData():null,i=n?.alias;let l=null;if(i&&r.some(e=>e.alias===i))l=i;else{const e=he.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);l=a?e:o||r[0]?.alias||null}if(e&&(!he.isSupabaseTokenValid()&&l&&await we.attemptRegeneration(),!he.isSupabaseTokenValid()))return{..._e};let c=null;if(l){const e=he.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{..._e}}}static async loginDev(){try{const e=be(),{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==";he.setOAuthState(e);const a=he.generateOAuthNonce();he.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(Te.oauth.authUrl);s.searchParams.set("client_id",Te.oauth.clientId),s.searchParams.set("response_type",Te.oauth.responseType),s.searchParams.set("scope",Te.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=he.getAccessToken();e!==s&&he.clearAll()}const n=!0;if(he.hasAllTokens()){if(n){he.getValidSupabaseToken()||await we.attemptRegeneration(!0)}return!0}const i=s,l=r;if(!i||!l)throw new Error("Tokens não encontrados na URL de callback");he.setAccessToken(i),he.setIdToken(l),he.clearManualLogout();const c=this.extractAliasFromAccessToken(i);if(c)he.setSelectedAlias(c);else{const e=this.extractCompaniesFromIdToken(l);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");he.setSelectedAlias(e[0].alias)}if(n){if(!await we.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return he.clearOAuthState(),he.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){he.setManualLogout(),he.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return 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}},we.setLogoutCallback(()=>{Se.logout()});const Re=a.createContext(void 0),Pe=(e={})=>{const{user:t,alias:s}=(()=>{const e=a.useContext(Re);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:()=>Ee.getUsers(s,o),enabled:r&&!!s&&!!t,staleTime:3e5,retry:2,retryDelay:1e3})},Ue=R.Root,De=R.Portal,Ve=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Overlay,{className:L("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}));Ve.displayName=R.Overlay.displayName;const Le=k.forwardRef(({className:a,...t},s)=>e.jsxs(De,{children:[e.jsx(Ve,{}),e.jsx(R.Content,{ref:s,className:L("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})]}));Le.displayName=R.Content.displayName;const ze=({className:a,...t})=>e.jsx("div",{className:L("flex flex-col space-y-2 text-center sm:text-left",a),...t});ze.displayName="AlertDialogHeader";const Oe=({className:a,...t})=>e.jsx("div",{className:L("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Oe.displayName="AlertDialogFooter";const Me=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Title,{ref:s,className:L("text-lg font-semibold",a),...t}));Me.displayName=R.Title.displayName;const Be=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Description,{ref:s,className:L("text-sm text-muted-foreground",a),...t}));Be.displayName=R.Description.displayName;const qe=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Action,{ref:s,className:L(Q(),a),...t}));qe.displayName=R.Action.displayName;const He=k.forwardRef(({className:a,...t},s)=>e.jsx(R.Cancel,{ref:s,className:L(Q({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));He.displayName=R.Cancel.displayName;const We=_.Root,$e=_.Portal,Je=k.forwardRef(({className:a,...t},s)=>e.jsx(_.Overlay,{ref:s,className:L("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}));Je.displayName=_.Overlay.displayName;const Qe={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"}},Fe=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),C=r??(i||l||c||d||u||m?void 0:"md"),E=C?Qe[C]:{},S={...i??E.width?{width:i??E.width}:{},...l??E.minWidth?{minWidth:l??E.minWidth}:{},...c??E.maxWidth?{maxWidth:c??E.maxWidth}:{},...d??E.height?{height:d??E.height}:{},...u??E.minHeight?{minHeight:u??E.minHeight}:{},...m??E.maxHeight?{maxHeight:m??E.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($e,{children:[e.jsx(Je,{}),e.jsxs(_.Content,{ref:N,className:L("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(Ue,{open:j,onOpenChange:A,children:e.jsxs(Le,{children:[e.jsxs(ze,{children:[e.jsx(Me,{children:p}),e.jsx(Be,{children:h})]}),e.jsxs(Oe,{children:[e.jsx(He,{onClick:()=>{A(!1),I.current=null},children:f}),e.jsx(qe,{onClick:()=>{A(!1),I.current?.(),I.current=null},children:x})]})]})})]})});Fe.displayName=_.Content.displayName;const Ke=({className:a,showSeparator:t=!1,children:s,...r})=>e.jsxs("div",{className:L("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"})]});Ke.displayName="DialogHeader";const Ge=({className:a,...t})=>e.jsx("div",{className:L("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",a),...t});Ge.displayName="DialogBody";const Ye=({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:L("flex flex-row justify-end gap-2",a),...s,children:t})]});Ye.displayName="DialogFooter";const Xe=k.forwardRef(({className:a,...t},s)=>e.jsx(_.Title,{ref:s,className:L("text-xl font-semibold leading-none tracking-tight",a),...t}));Xe.displayName=_.Title.displayName;k.forwardRef(({className:a,...t},s)=>e.jsx(_.Description,{ref:s,className:L("text-sm text-muted-foreground",a),...t})).displayName=_.Description.displayName;const Ze=k.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(P.Root,{ref:r,className:L("relative overflow-hidden",a),...s,children:[e.jsx(P.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(ea,{}),e.jsx(P.Corner,{})]}));Ze.displayName=P.Root.displayName;const ea=k.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(P.ScrollAreaScrollbar,{ref:r,orientation:t,className:L("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 aa({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}=Pe({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(We,{open:s,onOpenChange:r,children:e.jsxs(Fe,{className:"max-w-2xl",variant:"form",children:[e.jsx(Ke,{showSeparator:!0,children:e.jsxs(Xe,{className:"flex items-center gap-2",children:[e.jsx(t.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs(Ge,{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(Ze,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(B,{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:L("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(q,{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(Ye,{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(F,{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(F,{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 ta({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:L("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(ta,{place:a,level:r+1,manageAccessConfig:o},a.id))})]}),0===r&&e.jsx(M,{}),o&&e.jsx(aa,{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)})]})}ea.displayName=P.ScrollAreaScrollbar.displayName;const sa=new class{get baseUrl(){return Ce()}async makeApiCall(e,a,t){const s=ke.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=he.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 ke.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 fe.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return fe.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};exports.ManageAccessModal=aa,exports.PlaceCard=ta,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(ta,{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=sa;
|
|
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;
|