forlogic-core 2.3.0 → 2.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.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/action-plans/index.esm.js +1 -1
- package/dist/action-plans/index.js +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/audit-trail/index.esm.js +1 -1
- package/dist/audit-trail/index.js +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
|
@@ -22,13 +22,13 @@ export declare const SEARCH_CONFIG: {
|
|
|
22
22
|
export declare const isLovablePreview: () => boolean;
|
|
23
23
|
/**
|
|
24
24
|
* Determines auth method: true → use dev-tokens edge function, false → use OAuth.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* Requer modo Supabase: em modo dotnet, dev-tokens não existe e devemos sempre
|
|
26
|
+
* cair no OAuth real (loginProd), mesmo em localhost/preview.
|
|
27
27
|
*/
|
|
28
28
|
export declare const shouldUseDevTokens: () => boolean;
|
|
29
29
|
/** @deprecated Use `isLovablePreview()` or `shouldUseDevTokens()` instead */
|
|
30
30
|
export declare const isDevEnvironment: () => boolean;
|
|
31
|
-
export {
|
|
31
|
+
export { isDevEnv, getAppEnv, type AppEnv } from './environments';
|
|
32
32
|
export declare const getQualiexApiUrl: () => string;
|
|
33
33
|
export declare const QUERY_KEYS: {
|
|
34
34
|
readonly crud: (entity: string) => readonly [string];
|
package/dist/places/index.d.ts
CHANGED
|
@@ -90,7 +90,7 @@ export { loadForlogicFonts } from './utils/load-fonts';
|
|
|
90
90
|
export * from './types';
|
|
91
91
|
export * from './types/sidebar';
|
|
92
92
|
export * from './config';
|
|
93
|
-
export { getEnvironmentConfig,
|
|
93
|
+
export { getEnvironmentConfig, isDevEnv, getAppEnv, type AppEnv } from './config/environments';
|
|
94
94
|
export type { EnvironmentConfig } from './config/environments';
|
|
95
95
|
export { setBackendMode, getBackendMode, isSupabaseBackend } from './config/backend';
|
|
96
96
|
export type { BackendMode } from './config/backend';
|
package/dist/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{useState as r,useMemo as s}from"react";import{Users as n,Search as t,Crown as c,UserPlus as l,ChevronRight as o,Building2 as i,Settings as d}from"lucide-react";import{useQualiexUsers as m,Dialog as u,DialogContent as h,DialogHeader as p,DialogTitle as f,DialogBody as g,Input as x,ScrollArea as N,Skeleton as b,Checkbox as v,cn as w,DialogFooter as y,Button as C,Collapsible as k,CollapsibleTrigger as M,Badge as I,ActionMenu as A,CollapsibleContent as E,Separator as P,getQualiexApiUrl as L,QualiexErrorInterceptor as j,TokenManager as T,errorService as _}from"forlogic-core";import{useTranslation as O}from"react-i18next";function G({open:o,onOpenChange:i,placeId:d,placeName:k,onMakeManager:M,onMakeMembers:I,currentManagerId:A,currentMemberIds:E=[]}){const{t:P}=O(),[L,j]=r([]),[T,_]=r(!1),[G,H]=r(""),{data:U=[],isLoading:S}=m({enabled:o}),$=s(()=>{let e=[...U];if(e.sort((e,a)=>{const r=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return r.localeCompare(s)}),G){const a=G.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[U,G]),q=e=>{j(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},z=1===L.length,B=L.length>0;return e(u,{open:o,onOpenChange:i,children:a(h,{className:"max-w-2xl",variant:"form",children:[e(p,{showSeparator:!0,children:a(f,{className:"flex items-center gap-2",children:[e(n,{className:"h-5 w-5"}),"Gerenciar Acessos - ",k]})}),a(g,{children:[a("div",{className:"relative mb-4",children:[e(t,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(x,{placeholder:"Pesquisar...",value:G,onChange:e=>H(e.target.value),className:"pl-9"})]}),e(N,{className:"h-[400px] pr-4",children:S?e("div",{className:"space-y-2",children:[...Array(5)].map((a,r)=>e(b,{className:"h-16 w-full"},r))}):0===$.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(n,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:P(G?"leadership_no_users_found":"leadership_no_users_available")})]}):e("div",{className:"space-y-2",children:$.map(r=>{const s=r.userId===A,n=E.includes(r.userId||""),t=L.includes(r.userId||"");return a("div",{className:w("flex items-center gap-3 p-3 rounded-lg border transition-colors",t&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>q(r.userId||""),children:[e(v,{checked:t,onCheckedChange:()=>q(r.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:r.userName}),s&&e(c,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:r.userEmail})]}),(s||n)&&e("div",{className:"text-xs text-muted-foreground",children:s?"Gestor":"Membro"})]},r.userId)})})})]}),a(y,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:L.length>0&&a("span",{children:[L.length," selecionado(s)"]})}),z&&M&&a(C,{onClick:async()=>{if(M&&1===L.length){_(!0);try{await M(L[0],d),j([])}finally{_(!1)}}},disabled:T,variant:"outline",children:[e(c,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),B&&I&&a(C,{onClick:async()=>{if(I&&0!==L.length){_(!0);try{await I(L,d),j([])}finally{_(!1)}}},disabled:T,children:[e(l,{className:"h-4 w-4 mr-2"}),"Tornar ",L.length>1?"Membros":"Membro"]})]})]})})}function H({place:s,level:t=0,manageAccessConfig:c}){const{t:l}=O(),[m,u]=r(!1),[h,p]=r(!1),f=s.subPlaces&&s.subPlaces.length>0,g=s.isActive??!0,x=s.usersCount??0;return a("div",{children:[a(k,{open:m,onOpenChange:u,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*t+1+"rem"},children:[f?a(M,{className:"flex items-center gap-2 flex-1",children:[e(o,{className:w("h-4 w-4 transition-transform shrink-0",m&&"rotate-90")}),e(i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:s.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",s.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:s.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(n,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:x})]}),e(I,{variant:g?"default":"secondary",className:"text-xs",children:g?"Ativo":"Inativo"}),c&&e(A,{customActions:[{label:l("manage_access"),icon:d,onClick:()=>p(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),f&&e(E,{children:s.subPlaces.map(a=>e(H,{place:a,level:t+1,manageAccessConfig:c},a.id))})]}),0===t&&e(P,{}),c&&e(G,{open:h,onOpenChange:p,placeId:s.id,placeName:s.name,onMakeManager:c.onMakeManager,onMakeMembers:c.onMakeMembers,currentManagerId:c.getCurrentManagerId?.(s.id),currentMemberIds:c.getCurrentMemberIds?.(s.id)})]})}function U({places:r,isLoading:s,manageAccessConfig:n}){return s?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):r&&0!==r.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),r.map(a=>e(H,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(i,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const S=new class{get baseUrl(){return L()}async makeApiCall(e,a,r){const s=j.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const n=T.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!r||""===r.trim())throw new Error("Alias da unidade é obrigatório");const t=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{t.searchParams.append(e,a)});const c=await fetch(t.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":r}});if(!c.ok){const e=new Error(`API call failed: ${c.status}`);throw e.status=c.status,e}return c.json()}buildHierarchy(e){const a=new Map,r=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const s=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(s)):r.push(s)}else r.push(s)}),r}async getPlaces(e,a){try{const r=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=r.data||r||[];return this.buildHierarchy(s)}catch(r){if(await j.handleApiError(r))try{const r=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=r.data||r||[];return this.buildHierarchy(s)}catch(s){return _.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return _.handleError(r instanceof Error?r.message:"Erro ao buscar locais",!0),[]}}};export{G as ManageAccessModal,H as PlaceCard,U as PlacesList,S as placeService};
|
package/dist/places/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=require("lucide-react"),s=require("@radix-ui/react-collapsible"),r=require("class-variance-authority"),o=require("clsx"),n=require("tailwind-merge");require("date-fns");var i=require("sonner"),l=require("@radix-ui/react-separator"),c=require("@radix-ui/react-checkbox"),d=require("@radix-ui/react-tooltip"),u=require("react-i18next"),m=require("@radix-ui/react-slot"),p=require("@radix-ui/react-dropdown-menu"),h=require("@radix-ui/react-select"),f=require("@radix-ui/react-hover-card"),g=require("i18next"),x=require("@tanstack/react-query"),y=require("@supabase/supabase-js"),b=require("@radix-ui/react-dialog"),v=require("@radix-ui/react-alert-dialog"),w=require("@radix-ui/react-scroll-area");function N(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var k=N(a),j=N(s),A=N(l),I=N(c),T=N(d),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"),s=require("react"),a=require("lucide-react"),r=require("forlogic-core"),t=require("react-i18next");function n({open:n,onOpenChange:l,placeId:c,placeName:o,onMakeManager:i,onMakeMembers:d,currentManagerId:m,currentMemberIds:u=[]}){const{t:x}=t.useTranslation(),[h,p]=s.useState([]),[g,f]=s.useState(!1),[j,N]=s.useState(""),{data:b=[],isLoading:v}=r.useQualiexUsers({enabled:n}),w=s.useMemo(()=>{let e=[...b];if(e.sort((e,s)=>{const a=e.userName?.toLowerCase()||"",r=s.userName?.toLowerCase()||"";return a.localeCompare(r)}),j){const s=j.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(s)||e.userEmail?.toLowerCase().includes(s))}return e},[b,j]),C=e=>{p(s=>s.includes(e)?s.filter(s=>s!==e):[...s,e])},y=1===h.length,k=h.length>0;return e.jsx(r.Dialog,{open:n,onOpenChange:l,children:e.jsxs(r.DialogContent,{className:"max-w-2xl",variant:"form",children:[e.jsx(r.DialogHeader,{showSeparator:!0,children:e.jsxs(r.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(a.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),e.jsxs(r.DialogBody,{children:[e.jsxs("div",{className:"relative mb-4",children:[e.jsx(a.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(r.Input,{placeholder:"Pesquisar...",value:j,onChange:e=>N(e.target.value),className:"pl-9"})]}),e.jsx(r.ScrollArea,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((s,a)=>e.jsx(r.Skeleton,{className:"h-16 w-full"},a))}):0===w.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(a.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x(j?"leadership_no_users_found":"leadership_no_users_available")})]}):e.jsx("div",{className:"space-y-2",children:w.map(s=>{const t=s.userId===m,n=u.includes(s.userId||""),l=h.includes(s.userId||"");return e.jsxs("div",{className:r.cn("flex items-center gap-3 p-3 rounded-lg border transition-colors",l&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>C(s.userId||""),children:[e.jsx(r.Checkbox,{checked:l,onCheckedChange:()=>C(s.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:s.userName}),t&&e.jsx(a.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.userEmail})]}),(t||n)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},s.userId)})})})]}),e.jsxs(r.DialogFooter,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:h.length>0&&e.jsxs("span",{children:[h.length," selecionado(s)"]})}),y&&i&&e.jsxs(r.Button,{onClick:async()=>{if(i&&1===h.length){f(!0);try{await i(h[0],c),p([])}finally{f(!1)}}},disabled:g,variant:"outline",children:[e.jsx(a.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),k&&d&&e.jsxs(r.Button,{onClick:async()=>{if(d&&0!==h.length){f(!0);try{await d(h,c),p([])}finally{f(!1)}}},disabled:g,children:[e.jsx(a.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",h.length>1?"Membros":"Membro"]})]})]})})}function l({place:c,level:o=0,manageAccessConfig:i}){const{t:d}=t.useTranslation(),[m,u]=s.useState(!1),[x,h]=s.useState(!1),p=c.subPlaces&&c.subPlaces.length>0,g=c.isActive??!0,f=c.usersCount??0;return e.jsxs("div",{children:[e.jsxs(r.Collapsible,{open:m,onOpenChange:u,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*o+1+"rem"},children:[p?e.jsxs(r.CollapsibleTrigger,{className:"flex items-center gap-2 flex-1",children:[e.jsx(a.ChevronRight,{className:r.cn("h-4 w-4 transition-transform shrink-0",m&&"rotate-90")}),e.jsx(a.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:c.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",c.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(a.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(a.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:f})]}),e.jsx(r.Badge,{variant:g?"default":"secondary",className:"text-xs",children:g?"Ativo":"Inativo"}),i&&e.jsx(r.ActionMenu,{customActions:[{label:d("manage_access"),icon:a.Settings,onClick:()=>h(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),p&&e.jsx(r.CollapsibleContent,{children:c.subPlaces.map(s=>e.jsx(l,{place:s,level:o+1,manageAccessConfig:i},s.id))})]}),0===o&&e.jsx(r.Separator,{}),i&&e.jsx(n,{open:x,onOpenChange:h,placeId:c.id,placeName:c.name,onMakeManager:i.onMakeManager,onMakeMembers:i.onMakeMembers,currentManagerId:i.getCurrentManagerId?.(c.id),currentMemberIds:i.getCurrentMemberIds?.(c.id)})]})}const c=new class{get baseUrl(){return r.getQualiexApiUrl()}async makeApiCall(e,s,a){const t=r.QualiexErrorInterceptor.validateToken();if(!t.valid)throw new Error(t.message||"Token inválido");const n=r.TokenManager.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório");const l=new URL(e,this.baseUrl);Object.entries(s).forEach(([e,s])=>{l.searchParams.append(e,s)});const c=await fetch(l.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!c.ok){const e=new Error(`API call failed: ${c.status}`);throw e.status=c.status,e}return c.json()}buildHierarchy(e){const s=new Map,a=[];return e.forEach(e=>{s.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=s.get(e.id);if(e.parentId){const t=s.get(e.parentId);t?(t.subPlaces=t.subPlaces||[],t.subPlaces.push(r)):a.push(r)}else a.push(r)}),a}async getPlaces(e,s){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:s},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(a){if(await r.QualiexErrorInterceptor.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:s},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(t){return r.errorService.handleError(t instanceof Error?t:"Erro ao buscar locais após renovação de token",!0),[]}return r.errorService.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};exports.ManageAccessModal=n,exports.PlaceCard=l,exports.PlacesList=function({places:s,isLoading:r,manageAccessConfig:t}){return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):s&&0!==s.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),s.map(s=>e.jsx(l,{place:s,manageAccessConfig:t},s.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(a.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.placeService=c;
|
|
@@ -1,12 +1,27 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Detecção de ambiente prod/dev.
|
|
3
|
+
*
|
|
4
|
+
* Fonte de verdade ÚNICA: `VITE_APP_ENV` (`"PROD"` | `"DEV"`).
|
|
5
|
+
* - `"DEV"` → API/OAuth/Supabase de dev.
|
|
6
|
+
* - `"PROD"` ou ausente / qualquer outro valor → PROD (failsafe).
|
|
7
|
+
*
|
|
8
|
+
* Não há fallback baseado em env vars Supabase: apps sem Supabase precisam
|
|
9
|
+
* configurar `VITE_APP_ENV="DEV"` explicitamente quando quiserem apontar para dev.
|
|
10
|
+
*
|
|
11
|
+
* **Storage de assets (logos/favicon) é sempre prod** — bucket público fixo.
|
|
12
|
+
*/
|
|
13
|
+
export type AppEnv = 'PROD' | 'DEV';
|
|
2
14
|
export interface EnvironmentConfig {
|
|
3
15
|
storageProjectId: string;
|
|
16
|
+
supabaseProjectId: string;
|
|
17
|
+
supabaseUrl: string;
|
|
18
|
+
supabasePublishableKey: string;
|
|
4
19
|
oauth: {
|
|
5
20
|
authUrl: string;
|
|
6
21
|
clientId: string;
|
|
7
22
|
};
|
|
8
23
|
qualiexApiUrl: string;
|
|
9
24
|
}
|
|
25
|
+
export declare function getAppEnv(): AppEnv;
|
|
10
26
|
export declare function getEnvironmentConfig(): EnvironmentConfig;
|
|
11
|
-
export declare function
|
|
12
|
-
export { PROD_PROJECT_ID };
|
|
27
|
+
export declare function isDevEnv(): boolean;
|
|
@@ -22,13 +22,13 @@ export declare const SEARCH_CONFIG: {
|
|
|
22
22
|
export declare const isLovablePreview: () => boolean;
|
|
23
23
|
/**
|
|
24
24
|
* Determines auth method: true → use dev-tokens edge function, false → use OAuth.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* Requer modo Supabase: em modo dotnet, dev-tokens não existe e devemos sempre
|
|
26
|
+
* cair no OAuth real (loginProd), mesmo em localhost/preview.
|
|
27
27
|
*/
|
|
28
28
|
export declare const shouldUseDevTokens: () => boolean;
|
|
29
29
|
/** @deprecated Use `isLovablePreview()` or `shouldUseDevTokens()` instead */
|
|
30
30
|
export declare const isDevEnvironment: () => boolean;
|
|
31
|
-
export {
|
|
31
|
+
export { isDevEnv, getAppEnv, type AppEnv } from './environments';
|
|
32
32
|
export declare const getQualiexApiUrl: () => string;
|
|
33
33
|
export declare const QUERY_KEYS: {
|
|
34
34
|
readonly crud: (entity: string) => readonly [string];
|
package/dist/sign/index.d.ts
CHANGED
|
@@ -90,7 +90,7 @@ export { loadForlogicFonts } from './utils/load-fonts';
|
|
|
90
90
|
export * from './types';
|
|
91
91
|
export * from './types/sidebar';
|
|
92
92
|
export * from './config';
|
|
93
|
-
export { getEnvironmentConfig,
|
|
93
|
+
export { getEnvironmentConfig, isDevEnv, getAppEnv, type AppEnv } from './config/environments';
|
|
94
94
|
export type { EnvironmentConfig } from './config/environments';
|
|
95
95
|
export { setBackendMode, getBackendMode, isSupabaseBackend } from './config/backend';
|
|
96
96
|
export type { BackendMode } from './config/backend';
|
package/dist/sign/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t}from"react/jsx-runtime";import*as a from"react";import{createContext as n,useContext as r,useState as o,useEffect as s,useCallback as i,useRef as c}from"react";import"@tanstack/react-query";import l from"i18next";import{createClient as d}from"@supabase/supabase-js";import{toast as u}from"sonner";import{Loader2 as m,CheckCircle as g,AlertTriangle as p,Info as h,CheckCircle2 as f,Download as v,RefreshCw as y,Upload as _,ChevronDown as b,ChevronUp as w,Check as x,AlertCircle as k}from"lucide-react";import{useTranslation as N}from"react-i18next";import{cva as S}from"class-variance-authority";import{clsx as T}from"clsx";import{twMerge as I}from"tailwind-merge";import"date-fns";import{Slot as A}from"@radix-ui/react-slot";import*as E from"@radix-ui/react-label";import*as C from"@radix-ui/react-select";class P{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const r=e.split(".");if(3!==r.length)return null;const o=r[1];o.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(o),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const n=new TextDecoder("utf-8").decode(a);return JSON.parse(n)}catch(t){try{const e=this.normalizeBase64Url(o),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(o),t=atob(e);return JSON.parse(t)}catch(n){throw n}}}}catch(r){return null}}static validateTokens(e,t){const a=[],n=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),o=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:n}}let s=!0;if(!o){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),s=!1}const i=Math.floor(Date.now()/1e3);if(o?.exp&&o.exp<i){const e="Access token expirado - pode precisar de refresh";a.push(e),s=!1}if(r.exp&&r.exp<i){const e="ID token expirado - autenticação inválida";return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:s,warnings:a,errors:n}}return{isValid:!0,idTokenValid:!0,accessTokenValid:s,warnings:a,errors:n}}catch(r){const e=`Erro na validação de tokens: ${r}`;return n.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:n}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}P.LARGE_PAYLOAD_THRESHOLD=1e3;const V="qualiex_access_token",L="qualiex_id_token",R="supabase_token",U="oauth_state",D="oauth_nonce",B="selected_alias",j="manual_logout",O="supabase_project_id",$={setAccessToken:e=>localStorage.setItem(V,e),getAccessToken:()=>localStorage.getItem(V),setIdToken:e=>localStorage.setItem(L,e),getIdToken:()=>localStorage.getItem(L),getSupabaseToken:()=>localStorage.getItem(R),setOAuthState:e=>sessionStorage.setItem(U,e),getOAuthState:()=>sessionStorage.getItem(U),clearOAuthState:()=>sessionStorage.removeItem(U),setOAuthNonce:e=>sessionStorage.setItem(D,e),getOAuthNonce:()=>sessionStorage.getItem(D),clearOAuthNonce:()=>sessionStorage.removeItem(D),setSelectedAlias:e=>localStorage.setItem(B,e),getSelectedAlias:()=>localStorage.getItem(B),clearSelectedAlias:()=>localStorage.removeItem(B),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!$.getAccessToken()||!$.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const t=localStorage.getItem(O);return t&&t!==e?($.clearAll(),localStorage.setItem(O,e),!0):(t||localStorage.setItem(O,e),!1)},setSupabaseToken:e=>{localStorage.setItem(R,e),$._clearValidationCache()},areAllTokensValid:()=>{const e=$.getAccessToken(),t=$.getIdToken();if(!e||!t)return!1;try{const a=P.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=$.getAccessToken(),a=$.getIdToken(),n=$.getSupabaseToken();return t&&$.isTokenExpired(t)&&(localStorage.removeItem(V),e=!0),a&&$.isTokenExpired(a)&&(localStorage.removeItem(L),e=!0),n&&$.isTokenExpired(n)&&(localStorage.removeItem(R),e=!0),e},clearAll:()=>{localStorage.removeItem(V),localStorage.removeItem(L),localStorage.removeItem(R),localStorage.removeItem(B),localStorage.removeItem(j),sessionStorage.removeItem(U),sessionStorage.removeItem(D),$._clearValidationCache()},setManualLogout:()=>localStorage.setItem(j,"true"),isManualLogout:()=>"true"===localStorage.getItem(j),clearManualLogout:()=>localStorage.removeItem(j),isTokenExpired:e=>{try{return P.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{$._validationCache.isValid=!1,$._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=$.getSupabaseToken();if(!e)return!1;if($.isTokenExpired(e))return $._clearValidationCache(),$._handleExpiredToken(),!1;const t=Date.now();return t-$._validationCache.timestamp<$._validationCache.cacheValidityMs?$._validationCache.isValid:($._validationCache.isValid=!0,$._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>$.isSupabaseTokenValid()?$.getSupabaseToken():null,_handleExpiredToken:()=>{$.clearAll()},extractTokenData:()=>{if(!$.isSupabaseTokenValid())return null;const e=$.getSupabaseToken();if(!e)return null;try{const t=P.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,n=t.place_id||null,r=t.place_name||null;let o=t.company_id;if(!o&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const n=t[e];if(n&&"string"==typeof n){const e=n.split(";");if(e.length>7&&e[0]===a){o=e[7];break}}}return{alias:a,companyId:o,placeId:n,placeName:r,payload:t}}catch(t){return $._handleExpiredToken(),null}},getCompanyId:e=>{const t=$.getAccessToken();if(t)try{const a=P.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const n=a[t];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=$.extractTokenData();if(a?.companyId)return a.companyId;const n=$.getIdToken();if(n)try{const t=P.parseJwtPayload(n);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const n=t[a];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const t=[$.getAccessToken(),$.getIdToken()];for(const a of t)if(a)try{const t=P.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const n=t[a];if(n&&"string"==typeof n){const t=n.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=$.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=$.getIdToken();if(!e)return[];try{const t=P.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const n=t[e];if(n&&"string"==typeof n){const e=n.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}},q={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},z={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};const J={get oauth(){const e=function(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=import.meta.env.VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return"ccjfvpnndclajkleyqkc"===e?q:z}();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}};import.meta.env.VITE_IS_QUALIEX;const F=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);u.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?l.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?l.t("error_authentication"):t.includes("api")||t.includes("network")?l.t("error_connection"):"Erro"}success(e,t){u.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function M(e){return!!e&&e.startsWith("eyJ")}function W(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE;return e||(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY??"")}let H=!1;class K{constructor(e){this.currentToken=null,this.config=e,function(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE,t=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;H?M(t):e&&M(t)?H=!0:M(t)?H=!0:H=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:this.config.key};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return d(this.config.url,this.config.key,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){if(!K.instance){const e=function(){const e=import.meta.env.VITE_SUPABASE_URL,t=W();return e&&t?{url:e,key:t}:null}();if(!e)throw new Error("[forlogic-core] Supabase não configurado. Defina VITE_SUPABASE_URL e VITE_SUPABASE_PUBLISHABLE_KEY no .env, ou não invoque getSupabaseClient() (use isSupabaseConfigured() para checar antes).");K.instance=new K(e)}return K.instance}getClient(){const e=$.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!P.isTokenExpired(e)}catch(t){return F.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function Y(){return K.getInstance().getClient()}class G{static async generateToken(e,t,a,n=!1){try{if(!n){const e=$.getSupabaseToken();if(e&&$.isSupabaseTokenValid())return e}const r=Y(),{data:o,error:s}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return s&&(s.message?.includes("401")||s.message?.includes("Unauthorized"))?(a?.(),null):o?.access_token?($.setSupabaseToken(o.access_token),o.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}class Q{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const t=$.getAccessToken(),a=$.getSelectedAlias();if(!t||!a)return null;const n=await G.generateToken(t,a,this.onLogoutCallback||void 0,e);return n||null}catch(t){return null}}}Q.regenerationPromise=null,Q.onLogoutCallback=null;var X;const Z={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};X=class{static async initialize(){try{const e=!0;if(e){if($.checkProjectMismatch())return{...Z}}if(!$.hasAllTokens()||!$.areAllTokensValid())return $.clearExpiredTokens(),{...Z};const t=$.getAccessToken(),a=$.getIdToken();$.clearManualLogout();const n=this.extractUserFromIdToken(a,t),r=this.extractCompaniesFromIdToken(a),o=this.extractAliasFromAccessToken(t),s=e?$.extractTokenData():null,i=s?.alias;let c=null;if(i&&r.some(e=>e.alias===i))c=i;else{const e=$.getSelectedAlias(),t=e&&r.some(t=>t.alias===e);c=t?e:o||r[0]?.alias||null}if(e&&(!$.isSupabaseTokenValid()&&c&&await Q.attemptRegeneration(),!$.isSupabaseTokenValid()))return{...Z};let l=null;if(c){const e=$.getCompanyId(c),t=r.find(e=>e.alias===c);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=s?.placeId??null,u=s?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:n,alias:c,companies:r,selectedUnit:l,userId:n?.id||null,userAlias:n?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{...Z}}}static async loginDev(){try{const e=Y(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const n=new URL("/callback",window.location.origin);return n.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=n.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";$.setOAuthState(e);const t=$.generateOAuthNonce();$.setOAuthNonce(t);const a=`${window.location.origin}/callback`,n=new URL(J.oauth.authUrl);n.searchParams.set("client_id",J.oauth.clientId),n.searchParams.set("response_type",J.oauth.responseType),n.searchParams.set("scope",J.oauth.scope),n.searchParams.set("redirect_uri",a),n.searchParams.set("state",e),n.searchParams.set("nonce",t),n.searchParams.set("response_mode","fragment"),window.location.href=n.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),n=a("access_token"),r=a("id_token"),o=a("error");if(o)throw new Error(`Erro OAuth: ${o}`);if(n&&r){const e=$.getAccessToken();e!==n&&$.clearAll()}const s=!0;if($.hasAllTokens()){if(s){$.getValidSupabaseToken()||await Q.attemptRegeneration(!0)}return!0}const i=n,c=r;if(!i||!c)throw new Error("Tokens não encontrados na URL de callback");$.setAccessToken(i),$.setIdToken(c),$.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)$.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(c);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");$.setSelectedAlias(e[0].alias)}if(s){if(!await Q.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase")}return $.clearOAuthState(),$.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){$.setManualLogout(),$.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return P.parseJwtPayload(e)}static extractUserFromIdToken(e,t){const a=this.decodeToken(e);if(!a)return null;const n=t?this.decodeToken(t):null;return{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier,isSysAdmin:"1"===n?.admin}}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const n=t[e].split(";");if(n.length>=4)a.push({id:n.length>7?n[7].trim():"",alias:n[0].trim(),name:n[3].trim()});else{const[n,r]=t[e].split("|");n&&r&&a.push({id:"",alias:n.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}},Q.setLogoutCallback(()=>{X.logout()});const ee=n(void 0),te=()=>{const e=r(ee);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function ae(){const{alias:e}=te(),[t,a]=o(null),[n,r]=o(!0);s(()=>{if(!e)return void r(!1);let t=!1;return(async()=>{r(!0);try{const n=Y(),{data:r,error:o}=await n.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||a(r)}catch(n){t||a(null)}finally{t||r(!1)}})(),()=>{t=!0}},[e]);return{config:t,isLoading:n,saveConfig:i(async(t,n)=>{if(!e)throw new Error("Alias not available");const r=Y(),{data:o,error:s}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:n,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(s)throw s;return a(o),o},[e])}}const ne=import.meta.env.VITE_SUPABASE_URL,re=W();async function oe(e,t,a){const n=$.getSupabaseToken(),r={"Content-Type":"application/json",apikey:re};n&&(r.Authorization=`Bearer ${n}`);const o=await fetch(`${ne}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:t,data:a})});if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${o.status}`)}return o}const se={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await oe(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await oe(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let ie=null;function ce(){return window.Clicksign?Promise.resolve():ie||(ie=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),ie)}const le="clicksign-container";function de({signerId:a,environment:n="sandbox",onSign:r,onError:i,onClose:l}){const{t:d}=N(),u=c(null),[g,p]=o(!0),[h,f]=o(null);return s(()=>{let e=!1;return u.current&&(u.current.unmount(),u.current=null),f(null),p(!0),ce().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===n?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(le),t.on("loaded",function(){p(!1)}),t.on("signed",function(){r?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(le);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){p(!1),i?.(e instanceof Error?e:new Error(d("sign_widget_error")))}),t.on("closed",function(){l?.()}),u.current=t}).catch(t=>{e||(f("Falha ao carregar o script de assinatura."),p(!1),i?.(t))}),()=>{e=!0,u.current&&(u.current.unmount(),u.current=null)}},[a,n]),e("div",{className:"relative h-full",children:[g&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t(m,{className:"h-5 w-5 animate-spin"}),t("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:t("p",{className:"text-sm text-destructive",children:h})}),t("div",{id:le,style:{height:"600px"}})]})}function ue(...e){return I(T(e))}const me=S("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ge={info:h,warning:h,danger:p,success:g},pe=a.forwardRef(({className:a,variant:n="info",showIcon:r=!0,children:o,...s},i)=>{const c=ge[n||"info"];return e("div",{ref:i,role:"alert",className:ue(me({variant:n}),a),...s,children:[r&&t(c,{className:"h-4 w-4"}),o]})});pe.displayName="Alert";const he=a.forwardRef(({className:e,...a},n)=>t("h5",{ref:n,className:ue("mb-1 font-medium leading-none tracking-tight",e),...a}));he.displayName="AlertTitle";const fe=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("text-sm [&_p]:leading-relaxed",e),...a}));fe.displayName="AlertDescription";function ve({documentKey:a,signerEmail:n,signerName:r,keySigner:d,environment:u,onSign:g,onError:p}){const h=c(null),[f,v]=o("loading"),[y,_]=o(null),b="production"===u?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:n,display_name:r||"",disable_preview:"0"});return d&&e.set("key_signer",d),`${b}/${a}?${e.toString()}`})(),x=i(e=>"signed"===e.data?(v("ready"),void g?.()):"wrong-data"===e.data?(v("error"),_(l.t("sign_incorrect_data")),void p?.(new Error(l.t("sign_incorrect_data")))):void 0,[g,p]);s(()=>(window.addEventListener("message",x,!1),()=>{window.removeEventListener("message",x,!1)}),[x]);const k=i(()=>{"loading"===f&&v("ready")},[f]);return"error"===f?e(pe,{variant:"danger",className:"my-4",children:[t(he,{children:l.t("sign_doc_load_error")}),t(fe,{children:y||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e("div",{className:"relative h-full",children:["loading"===f&&t("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t(m,{className:"h-5 w-5 animate-spin"}),t("span",{className:"text-sm",children:"Carregando documento..."})]})}),t("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:k})]})}const ye=S("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),_e=a.forwardRef(({className:e,variant:a,size:n,asChild:r=!1,...o},s)=>t(r?A:"button",{className:ue(ye({variant:a,size:n,className:e})),ref:s,...o}));_e.displayName="Button";const be=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("rounded-lg border bg-card text-card-foreground shadow-sm",e),...a}));be.displayName="Card";const we=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("flex flex-col space-y-1.5 p-6",e),...a}));we.displayName="CardHeader";const xe=a.forwardRef(({className:e,...a},n)=>t("h3",{ref:n,className:ue("text-2xl font-semibold leading-none tracking-tight",e),...a}));xe.displayName="CardTitle";a.forwardRef(({className:e,...a},n)=>t("p",{ref:n,className:ue("text-sm text-muted-foreground",e),...a})).displayName="CardDescription";const ke=a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("p-6 pt-0",e),...a}));ke.displayName="CardContent";function Ne({file:a,onDocumentSigned:n,onError:r,showEventLog:d=!1}){const{user:g,alias:p}=te(),{config:h,isLoading:b}=ae(),{t:w}=N(),[x,k]=o(null),[S,T]=o(!1),[I,A]=o(null),[E,C]=o("sandbox"),[P,V]=o("clicksign"),[L,R]=o(null),[U,D]=o(null),[B,j]=o(!1),[O,$]=o(0),[q,z]=o(!1),[J,F]=o([]),M=c(null),W=c(null),H=i(e=>{d&&F(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[d]),K=i(async e=>{if(k(e),A(null),R(null),D(null),H(`Arquivo selecionado: ${e.name}`),p&&g){T(!0);try{const t=h?.provider??"clicksign";V(t),H(`Provedor resolvido: ${t}`);const a=new FileReader,n=await new Promise((t,n)=>{a.onload=()=>{const e=a.result;t(e)},a.onerror=n,a.readAsDataURL(e)});H(`Criando envelope para assinatura via ${t}...`);const o=await se.createEnvelopeWithSigner({alias:p,contentBase64:n,filename:e.name,signerEmail:g.email||"",signerName:g.name||"",provider:t});H(`Envelope criado: ${o.envelope_id}`),R({envelope_id:o.envelope_id,document_id:o.document_id,signer_email:o.signer_email,key_signer:o.signer_id}),C(o.environment),V(o.provider||t),"d4sign"===t?(H("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),A(o.document_id),u.success(w("sign_doc_sent","Documento enviado! Assine abaixo."))):o.signer_id?(H(`Signer ID obtido: ${o.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),A(o.signer_id),u.success(w("sign_doc_sent","Documento enviado! Assine abaixo."))):(H(l.t("sign_signer_unavailable")),u.error(w("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),r?.(new Error(w("sign_signer_unavailable"))))}catch(t){const e=t instanceof Error?t:new Error(w("sign_process_error",w("sign_doc_process_error"))),a=e.message||"";a.includes("MONTHLY_LIMIT_REACHED")?(H(l.t("sign_monthly_limit")),u.error(w("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(H(`Erro: ${a}`),u.error(a)),r?.(e)}finally{T(!1)}}},[p,g,H,r,h]);s(()=>{a&&p&&g&&!b&&a!==W.current&&(W.current=a,K(a))},[a,p,g,b,K]);const Y=i(async()=>{if(!L||!p)return;j(!0),$(0),z(!1),H("Buscando documento assinado...");for(let t=1;t<=6;t++){$(t),H(`Tentativa ${t}/6...`);try{const e=await se.getSignedDocument({alias:p,envelopeId:L.envelope_id,documentId:L.document_id,provider:P});if(e.download_url)return H(l.t("sign_doc_available")),D(e.download_url),void j(!1)}catch(e){H(`Erro na tentativa ${t}: ${e instanceof Error?e.message:w("unknown_error")}`)}t<6&&(H("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}H(l.t("sign_fetch_failed")),j(!1),z(!0)},[L,p,H,P]),G=i(async()=>{H("Documento assinado com sucesso!"),u.success(w("sign_signed_success","Documento assinado com sucesso!")),A(null),L&&p&&(n?.({success:!0,provider:P,envelope_id:L.envelope_id,document_id:L.document_id,signer_id:I||"",environment:E}),await Y())},[H,n,L,I,p,E,P,Y]);if(!p)return t(be,{className:"border-amber-200 bg-amber-50",children:t(ke,{className:"flex items-start gap-3 py-6",children:e("div",{children:[t("p",{className:"font-medium text-amber-800",children:w("sign_auth_required","Autenticação necessária")}),t("p",{className:"text-sm text-amber-700 mt-1",children:w("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const Q="d4sign"===P?"D4Sign":"Clicksign",X=()=>d&&J.length>0?t("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:J.map((e,a)=>t("div",{children:e},a))}):null;return L&&!I&&(U||B||q)?e("div",{className:"space-y-4",children:[t(be,{className:"border-green-200 bg-green-50",children:e(ke,{className:"flex flex-col items-center gap-4 py-8",children:[t(f,{className:"h-12 w-12 text-green-600"}),e("div",{className:"text-center",children:[t("p",{className:"text-lg font-semibold text-green-800",children:w("sign_signed_success","Documento assinado com sucesso!")}),t("p",{className:"text-sm text-green-700 mt-1",children:x?.name})]}),B?e("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e("div",{className:"flex items-center gap-2",children:[t(m,{className:"h-4 w-4 animate-spin"}),w("sign_preparing_doc","Preparando documento assinado...")," (",w("sign_attempt","tentativa")," ",O,"/6)"]}),t("p",{className:"text-xs text-muted-foreground",children:w("sign_waiting_provider",`Aguardando processamento pelo ${Q}...`)})]}):U?t(_e,{asChild:!0,variant:"default",className:"gap-2",children:e("a",{href:U,target:"_blank",rel:"noopener noreferrer",children:[t(v,{className:"h-4 w-4"}),w("sign_download_signed","Baixar documento assinado")]})}):q?e("div",{className:"text-center space-y-3",children:[e("div",{className:"space-y-1",children:[t("p",{className:"text-sm text-muted-foreground",children:w("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),t("p",{className:"text-xs text-muted-foreground",children:w("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e(_e,{variant:"secondary",className:"gap-2",onClick:Y,children:[t(y,{className:"h-4 w-4"}),w("sign_try_again","Tentar novamente")]})]}):null]})}),t(X,{})]}):I?e("div",{className:"space-y-4",children:["d4sign"===P?t(ve,{documentKey:I,signerEmail:L?.signer_email||g?.email||"",signerName:g?.name,keySigner:L?.key_signer,environment:E,onSign:G,onError:r}):t(de,{signerId:I,environment:E,onSign:G,onError:r}),t(X,{})]}):a&&(S||b)?t(be,{children:e(ke,{className:"flex items-center justify-center gap-3 py-10",children:[t(m,{className:"h-6 w-6 animate-spin text-primary"}),t("p",{className:"font-medium",children:w("sign_sending_doc","Enviando documento para assinatura...")})]})}):e("div",{className:"space-y-4",children:[t("input",{ref:M,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?K(t):u.error(w("sign_select_pdf","Selecione um arquivo PDF"))}}),t(be,S?{children:e(ke,{className:"flex items-center justify-center gap-3 py-10",children:[t(m,{className:"h-6 w-6 animate-spin text-primary"}),t("p",{className:"font-medium",children:w("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>M.current?.click(),children:e(ke,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[t(_,{className:"h-8 w-8 text-muted-foreground"}),e("div",{className:"text-center",children:[t("p",{className:"font-medium",children:w("sign_select_pdf","Selecione um arquivo PDF")}),t("p",{className:"text-sm text-muted-foreground",children:w("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),t(X,{})]})}a.forwardRef(({className:e,...a},n)=>t("div",{ref:n,className:ue("flex items-center p-6 pt-0",e),...a})).displayName="CardFooter";const Se=a.forwardRef(({className:n,type:r,showCharCount:o,maxLength:s,onChange:i,...c},l)=>{const[d,u]=a.useState(0);a.useEffect(()=>{"string"==typeof c.value?u(c.value.length):"string"==typeof c.defaultValue&&u(c.defaultValue.length)},[c.value,c.defaultValue]);return e("div",{className:"w-full",children:[t("input",{type:r,className:ue("flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",n),ref:l,maxLength:s,onChange:e=>{u(e.target.value.length),i?.(e)},...c}),o&&s&&e("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",s]})]})});Se.displayName="Input";const Te=S("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ie=a.forwardRef(({className:e,...a},n)=>t(E.Root,{ref:n,className:ue(Te(),e),...a}));Ie.displayName=E.Root.displayName;const Ae=a.createContext({showCheck:!1}),Ee=({showCheck:e=!1,...a})=>t(Ae.Provider,{value:{showCheck:e},children:t(C.Root,{...a})}),Ce=C.Value,Pe=a.forwardRef(({className:a,children:n,...r},o)=>e(C.Trigger,{ref:o,className:ue("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",a),...r,children:[n,t(C.Icon,{asChild:!0,children:t(b,{className:"h-4 w-4 opacity-50"})})]}));Pe.displayName=C.Trigger.displayName;const Ve=a.forwardRef(({className:e,...a},n)=>t(C.ScrollUpButton,{ref:n,className:ue("flex cursor-default items-center justify-center py-1",e),...a,children:t(w,{className:"h-4 w-4"})}));Ve.displayName=C.ScrollUpButton.displayName;const Le=a.forwardRef(({className:e,...a},n)=>t(C.ScrollDownButton,{ref:n,className:ue("flex cursor-default items-center justify-center py-1",e),...a,children:t(b,{className:"h-4 w-4"})}));Le.displayName=C.ScrollDownButton.displayName;const Re=a.forwardRef(({className:a,children:n,position:r="popper",container:o,collisionBoundary:s,...i},c)=>t(C.Portal,{container:o,children:e(C.Content,{ref:c,className:ue("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===r&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:r,collisionBoundary:s,...i,children:[t(Ve,{}),t(C.Viewport,{className:ue("p-1","popper"===r&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:n}),t(Le,{})]})}));Re.displayName=C.Content.displayName;a.forwardRef(({className:e,...a},n)=>t(C.Label,{ref:n,className:ue("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...a})).displayName=C.Label.displayName;const Ue=a.forwardRef(({className:n,children:r,...o},s)=>{const{showCheck:i}=a.useContext(Ae);return e(C.Item,{ref:s,className:ue("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",i?"pl-8":"pl-2","data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground data-[state=checked]:font-medium data-[state=checked]:border-l-2 data-[state=checked]:border-primary",i?"data-[state=checked]:pl-[calc(2rem-2px)]":"data-[state=checked]:pl-[calc(0.5rem-2px)]",n),...o,children:[i&&t("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t(C.ItemIndicator,{children:t(x,{className:"h-4 w-4"})})}),t(C.ItemText,{children:r})]})});Ue.displayName=C.Item.displayName;function De({onSaved:a}){const{config:n,isLoading:r,saveConfig:i}=ae(),{t:c}=N(),[l,d]=o(""),[p,h]=o("sandbox"),[f,v]=o(!1);s(()=>{!r&&n&&(d(n.api_key),h(n.environment))},[n,r]);return r?t("div",{className:"flex items-center justify-center py-8",children:t(m,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e("div",{className:"space-y-4",children:[e("div",n?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[t(g,{className:"h-4 w-4"}),t("span",{children:c("sign_configured",c("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[t(k,{className:"h-4 w-4"}),t("span",{children:c("sign_not_configured",c("sign_not_configured_unit"))})]}),e(be,{children:[t(we,{children:t(xe,{className:"text-base",children:c("sign_digital_config")})}),t(ke,{children:e("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){v(!0);try{await i(l.trim(),p),u.success(c("sign_config_saved",c("sign_config_saved_success"))),a?.()}catch(t){u.error(c("sign_config_save_error",c("sign_config_save_err")))}finally{v(!1)}}else u.error(c("sign_api_key_required",c("sign_api_key_info")))},className:"space-y-4",children:[e("div",{className:"space-y-2",children:[t(Ie,{htmlFor:"sign-api-key",children:"API Key"}),t(Se,{id:"sign-api-key",type:"password",placeholder:c("sign_api_key_placeholder",c("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),e("div",{className:"space-y-2",children:[t(Ie,{children:c("sign_environment","Ambiente")}),e(Ee,{value:p,onValueChange:e=>h(e),children:[t(Pe,{children:t(Ce,{})}),e(Re,{children:[t(Ue,{value:"sandbox",children:"Sandbox (Testes)"}),t(Ue,{value:"production",children:"Produção"})]})]})]}),e(_e,{type:"submit",disabled:f,children:[f&&t(m,{className:"mr-2 h-4 w-4 animate-spin"}),n?c("sign_update_config",c("sign_update_config_btn")):c("sign_save_config",c("sign_save_config_btn"))]})]})})]})]})}a.forwardRef(({className:e,...a},n)=>t(C.Separator,{ref:n,className:ue("-mx-1 my-1 h-px bg-muted",e),...a})).displayName=C.Separator.displayName;export{ve as D4SignWidget,Ne as DocumentSigner,De as SignConfigForm,de as SignWidget,ce as loadClicksignScript,se as signService,ae as useSignConfig};
|
|
1
|
+
import{jsxs as e,jsx as n}from"react/jsx-runtime";import{useState as i,useEffect as a,useCallback as r,useRef as s}from"react";import{useAuth as t,getSupabaseClient as o,resolvePublishableKey as c,TokenManager as l,Alert as d,AlertTitle as m,AlertDescription as g,toast as u,Card as p,CardContent as _,Button as h,CardHeader as f,CardTitle as v,Label as y,Input as x,Select as w,SelectTrigger as N,SelectValue as b,SelectContent as E,SelectItem as k}from"forlogic-core";import{Loader2 as S,CheckCircle2 as C,Download as D,RefreshCw as $,Upload as A,CheckCircle as P,AlertCircle as T}from"lucide-react";import{useTranslation as L}from"react-i18next";import j from"i18next";function I(){const{alias:e}=t(),[n,s]=i(null),[c,l]=i(!0);a(()=>{if(!e)return void l(!1);let n=!1;return(async()=>{l(!0);try{const i=o(),{data:a,error:r}=await i.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();n||s(a)}catch(i){n||s(null)}finally{n||l(!1)}})(),()=>{n=!0}},[e]);return{config:n,isLoading:c,saveConfig:r(async(n,i)=>{if(!e)throw new Error("Alias not available");const a=o(),{data:r,error:t}=await a.schema("common").from("sign_configs").upsert({alias:e,api_key:n,environment:i,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(t)throw t;return s(r),r},[e])}}const q=import.meta.env.VITE_SUPABASE_URL,B=c();async function F(e,n,i){const a=l.getSupabaseToken(),r={"Content-Type":"application/json",apikey:B};a&&(r.Authorization=`Bearer ${a}`);const s=await fetch(`${q}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:n,data:i})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const O={async createEnvelopeWithSigner(e){const n="d4sign"===e.provider?"d4sign":"clicksign",i="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await F(n,i,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const n="d4sign"===e.provider?"d4sign":"clicksign";return(await F(n,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let R=null;function U(){return window.Clicksign?Promise.resolve():R||(R=new Promise((e,n)=>{const i=document.createElement("script");i.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",i.onload=()=>e(),i.onerror=()=>n(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(i)}),R)}const z="clicksign-container";function K({signerId:r,environment:t="sandbox",onSign:o,onError:c,onClose:l}){const{t:d}=L(),m=s(null),[g,u]=i(!0),[p,_]=i(null);return a(()=>{let e=!1;return m.current&&(m.current.unmount(),m.current=null),_(null),u(!0),U().then(()=>{if(e)return;const n=new window.Clicksign(r);n.endpoint="production"===t?"https://app.clicksign.com":"https://sandbox.clicksign.com",n.origin=window.origin,n.mount(z),n.on("loaded",function(){u(!1)}),n.on("signed",function(){o?.()}),n.on("resized",function(e){const n=e,i=document.getElementById(z);i&&n?.data?.height&&(i.style.height=n.data.height+"px")}),n.on("error",function(e){u(!1),c?.(e instanceof Error?e:new Error(d("sign_widget_error")))}),n.on("closed",function(){l?.()}),m.current=n}).catch(n=>{e||(_("Falha ao carregar o script de assinatura."),u(!1),c?.(n))}),()=>{e=!0,m.current&&(m.current.unmount(),m.current=null)}},[r,t]),e("div",{className:"relative h-full",children:[g&&n("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[n(S,{className:"h-5 w-5 animate-spin"}),n("span",{className:"text-sm",children:"Carregando documento..."})]})}),p&&n("div",{className:"absolute inset-0 flex items-center justify-center",children:n("p",{className:"text-sm text-destructive",children:p})}),n("div",{id:z,style:{height:"600px"}})]})}function H({documentKey:t,signerEmail:o,signerName:c,keySigner:l,environment:u,onSign:p,onError:_}){const h=s(null),[f,v]=i("loading"),[y,x]=i(null),w="production"===u?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",N=(()=>{const e=new URLSearchParams({email:o,display_name:c||"",disable_preview:"0"});return l&&e.set("key_signer",l),`${w}/${t}?${e.toString()}`})(),b=r(e=>"signed"===e.data?(v("ready"),void p?.()):"wrong-data"===e.data?(v("error"),x(j.t("sign_incorrect_data")),void _?.(new Error(j.t("sign_incorrect_data")))):void 0,[p,_]);a(()=>(window.addEventListener("message",b,!1),()=>{window.removeEventListener("message",b,!1)}),[b]);const E=r(()=>{"loading"===f&&v("ready")},[f]);return"error"===f?e(d,{variant:"danger",className:"my-4",children:[n(m,{children:j.t("sign_doc_load_error")}),n(g,{children:y||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e("div",{className:"relative h-full",children:["loading"===f&&n("div",{className:"absolute inset-0 flex items-center justify-center",children:e("div",{className:"flex items-center gap-2 text-muted-foreground",children:[n(S,{className:"h-5 w-5 animate-spin"}),n("span",{className:"text-sm",children:"Carregando documento..."})]})}),n("iframe",{ref:h,id:"d4sign-container",src:N,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:E})]})}function M({file:o,onDocumentSigned:c,onError:l,showEventLog:d=!1}){const{user:m,alias:g}=t(),{config:f,isLoading:v}=I(),{t:y}=L(),[x,w]=i(null),[N,b]=i(!1),[E,k]=i(null),[P,T]=i("sandbox"),[q,B]=i("clicksign"),[F,R]=i(null),[U,z]=i(null),[M,V]=i(!1),[W,J]=i(0),[Y,G]=i(!1),[Q,X]=i([]),Z=s(null),ee=s(null),ne=r(e=>{d&&X(n=>[...n,`[${(new Date).toLocaleTimeString()}] ${e}`])},[d]),ie=r(async e=>{if(w(e),k(null),R(null),z(null),ne(`Arquivo selecionado: ${e.name}`),g&&m){b(!0);try{const n=f?.provider??"clicksign";B(n),ne(`Provedor resolvido: ${n}`);const i=new FileReader,a=await new Promise((n,a)=>{i.onload=()=>{const e=i.result;n(e)},i.onerror=a,i.readAsDataURL(e)});ne(`Criando envelope para assinatura via ${n}...`);const r=await O.createEnvelopeWithSigner({alias:g,contentBase64:a,filename:e.name,signerEmail:m.email||"",signerName:m.name||"",provider:n});ne(`Envelope criado: ${r.envelope_id}`),R({envelope_id:r.envelope_id,document_id:r.document_id,signer_email:r.signer_email,key_signer:r.signer_id}),T(r.environment),B(r.provider||n),"d4sign"===n?(ne("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),k(r.document_id),u.success(y("sign_doc_sent","Documento enviado! Assine abaixo."))):r.signer_id?(ne(`Signer ID obtido: ${r.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),k(r.signer_id),u.success(y("sign_doc_sent","Documento enviado! Assine abaixo."))):(ne(j.t("sign_signer_unavailable")),u.error(y("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),l?.(new Error(y("sign_signer_unavailable"))))}catch(n){const e=n instanceof Error?n:new Error(y("sign_process_error",y("sign_doc_process_error"))),i=e.message||"";i.includes("MONTHLY_LIMIT_REACHED")?(ne(j.t("sign_monthly_limit")),u.error(y("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(ne(`Erro: ${i}`),u.error(i)),l?.(e)}finally{b(!1)}}},[g,m,ne,l,f]);a(()=>{o&&g&&m&&!v&&o!==ee.current&&(ee.current=o,ie(o))},[o,g,m,v,ie]);const ae=r(async()=>{if(!F||!g)return;V(!0),J(0),G(!1),ne("Buscando documento assinado...");for(let n=1;n<=6;n++){J(n),ne(`Tentativa ${n}/6...`);try{const e=await O.getSignedDocument({alias:g,envelopeId:F.envelope_id,documentId:F.document_id,provider:q});if(e.download_url)return ne(j.t("sign_doc_available")),z(e.download_url),void V(!1)}catch(e){ne(`Erro na tentativa ${n}: ${e instanceof Error?e.message:y("unknown_error")}`)}n<6&&(ne("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}ne(j.t("sign_fetch_failed")),V(!1),G(!0)},[F,g,ne,q]),re=r(async()=>{ne("Documento assinado com sucesso!"),u.success(y("sign_signed_success","Documento assinado com sucesso!")),k(null),F&&g&&(c?.({success:!0,provider:q,envelope_id:F.envelope_id,document_id:F.document_id,signer_id:E||"",environment:P}),await ae())},[ne,c,F,E,g,P,q,ae]);if(!g)return n(p,{className:"border-amber-200 bg-amber-50",children:n(_,{className:"flex items-start gap-3 py-6",children:e("div",{children:[n("p",{className:"font-medium text-amber-800",children:y("sign_auth_required","Autenticação necessária")}),n("p",{className:"text-sm text-amber-700 mt-1",children:y("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const se="d4sign"===q?"D4Sign":"Clicksign",te=()=>d&&Q.length>0?n("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:Q.map((e,i)=>n("div",{children:e},i))}):null;return F&&!E&&(U||M||Y)?e("div",{className:"space-y-4",children:[n(p,{className:"border-green-200 bg-green-50",children:e(_,{className:"flex flex-col items-center gap-4 py-8",children:[n(C,{className:"h-12 w-12 text-green-600"}),e("div",{className:"text-center",children:[n("p",{className:"text-lg font-semibold text-green-800",children:y("sign_signed_success","Documento assinado com sucesso!")}),n("p",{className:"text-sm text-green-700 mt-1",children:x?.name})]}),M?e("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e("div",{className:"flex items-center gap-2",children:[n(S,{className:"h-4 w-4 animate-spin"}),y("sign_preparing_doc","Preparando documento assinado...")," (",y("sign_attempt","tentativa")," ",W,"/6)"]}),n("p",{className:"text-xs text-muted-foreground",children:y("sign_waiting_provider",`Aguardando processamento pelo ${se}...`)})]}):U?n(h,{asChild:!0,variant:"default",className:"gap-2",children:e("a",{href:U,target:"_blank",rel:"noopener noreferrer",children:[n(D,{className:"h-4 w-4"}),y("sign_download_signed","Baixar documento assinado")]})}):Y?e("div",{className:"text-center space-y-3",children:[e("div",{className:"space-y-1",children:[n("p",{className:"text-sm text-muted-foreground",children:y("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),n("p",{className:"text-xs text-muted-foreground",children:y("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e(h,{variant:"secondary",className:"gap-2",onClick:ae,children:[n($,{className:"h-4 w-4"}),y("sign_try_again","Tentar novamente")]})]}):null]})}),n(te,{})]}):E?e("div",{className:"space-y-4",children:["d4sign"===q?n(H,{documentKey:E,signerEmail:F?.signer_email||m?.email||"",signerName:m?.name,keySigner:F?.key_signer,environment:P,onSign:re,onError:l}):n(K,{signerId:E,environment:P,onSign:re,onError:l}),n(te,{})]}):o&&(N||v)?n(p,{children:e(_,{className:"flex items-center justify-center gap-3 py-10",children:[n(S,{className:"h-6 w-6 animate-spin text-primary"}),n("p",{className:"font-medium",children:y("sign_sending_doc","Enviando documento para assinatura...")})]})}):e("div",{className:"space-y-4",children:[n("input",{ref:Z,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const n=e.target.files?.[0];n&&"application/pdf"===n.type?ie(n):u.error(y("sign_select_pdf","Selecione um arquivo PDF"))}}),n(p,N?{children:e(_,{className:"flex items-center justify-center gap-3 py-10",children:[n(S,{className:"h-6 w-6 animate-spin text-primary"}),n("p",{className:"font-medium",children:y("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Z.current?.click(),children:e(_,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[n(A,{className:"h-8 w-8 text-muted-foreground"}),e("div",{className:"text-center",children:[n("p",{className:"font-medium",children:y("sign_select_pdf","Selecione um arquivo PDF")}),n("p",{className:"text-sm text-muted-foreground",children:y("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),n(te,{})]})}function V({onSaved:r}){const{config:s,isLoading:t,saveConfig:o}=I(),{t:c}=L(),[l,d]=i(""),[m,g]=i("sandbox"),[C,D]=i(!1);a(()=>{!t&&s&&(d(s.api_key),g(s.environment))},[s,t]);return t?n("div",{className:"flex items-center justify-center py-8",children:n(S,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e("div",{className:"space-y-4",children:[e("div",s?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[n(P,{className:"h-4 w-4"}),n("span",{children:c("sign_configured",c("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[n(T,{className:"h-4 w-4"}),n("span",{children:c("sign_not_configured",c("sign_not_configured_unit"))})]}),e(p,{children:[n(f,{children:n(v,{className:"text-base",children:c("sign_digital_config")})}),n(_,{children:e("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){D(!0);try{await o(l.trim(),m),u.success(c("sign_config_saved",c("sign_config_saved_success"))),r?.()}catch(n){u.error(c("sign_config_save_error",c("sign_config_save_err")))}finally{D(!1)}}else u.error(c("sign_api_key_required",c("sign_api_key_info")))},className:"space-y-4",children:[e("div",{className:"space-y-2",children:[n(y,{htmlFor:"sign-api-key",children:"API Key"}),n(x,{id:"sign-api-key",type:"password",placeholder:c("sign_api_key_placeholder",c("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),e("div",{className:"space-y-2",children:[n(y,{children:c("sign_environment","Ambiente")}),e(w,{value:m,onValueChange:e=>g(e),children:[n(N,{children:n(b,{})}),e(E,{children:[n(k,{value:"sandbox",children:"Sandbox (Testes)"}),n(k,{value:"production",children:"Produção"})]})]})]}),e(h,{type:"submit",disabled:C,children:[C&&n(S,{className:"mr-2 h-4 w-4 animate-spin"}),s?c("sign_update_config",c("sign_update_config_btn")):c("sign_save_config",c("sign_save_config_btn"))]})]})})]})]})}export{H as D4SignWidget,M as DocumentSigner,V as SignConfigForm,K as SignWidget,U as loadClicksignScript,O as signService,I as useSignConfig};
|