1import{nr as It,ns as He,nt as Mt,nu as Lt,l$ as mt,h as Kt,nv as Ft,nw as qt,r as d,nx as Ht,ny as Qt,nz as _t,nA as Ut,nB as it,nC as zt,nD as Vt,j as e,e6 as Bt,e9 as X,e7 as Wt,nE as Gt,nF as Yt,e5 as Jt,nG as ht,ea as Zt,nH as Xt,nI as es,dW as ts,bI as xt,g as Je,u as B,b1 as ss,be as ns,p as ce,nJ as as,nK as rs,nL as is,nM as os,nN as cs,nO as ls,nP as Ce,bc as ue,C as ds,c as us,bt as ps,nQ as ms,n as Ee,B as T,_ as Ze,ba as q,nR as hs,nS as xs,a$ as ve,aS as ft,bv as Qe,nT as fs,nU as gt,k as R,nV as gs,bP as se,bC as ee,aF as je,ag as pe,b3 as be,nW as vt,b4 as U,aC as $,nX as vs,nY as js,gW as ys,bw as bs,bE as Ns,bD as he,T as xe,O as fe,Q as ge,nZ as Ss,bg as ws,aG as jt,aH as _e,aI as Ue,aJ as ze,aK as Ve,aL as Be,aM as We,aN as Ge,n_ as Cs,n$ as Z,D as ke,d as Te,e as Pe,f as Re,bf as De,b9 as A,bx as Es,by as ks,a2 as Ts,a3 as Ps,a4 as Rs,a5 as Ds,o0 as As,a6 as $s,aO as Os,bb as Ae,bA as yt,bB as ot,bZ as Is,a_ as Ms,bW as Ls,af as Ks,s as Fs,lY as qs,bF as Hs,bG as Qs,bH as _s,bJ as Us}from"./index-DNBzpCbc.js";import{S as zs}from"./switch-BXai0--o.js";import{T as Xe,a as et,b as oe,c as te,d as tt,e as F}from"./table-Djry4FPK.js";import{T as Vs,a as Bs,b as Le,c as Ke}from"./tabs-COTwfcaN.js";import{S as ct}from"./skeleton-BILgyhvB.js";import{R as Ws}from"./role-badge-WwN5eCrx.js";import{U as Gs}from"./user-form-dialog-BC7v1nXa.js";import{P as Ys}from"./phone-input-DqZhrb8a.js";import"./checkbox-Cz3Uxznu.js";function lt(t,s){const n=new Set(s);return t.filter(i=>!n.has(i))}function Js(t,s,n){const i=t.slice(0);return i[s]=n,i}var Zs=class extends It{#a;#e;#r;#n;#t;#s;#i;#o;#c;#l=[];constructor(t,s,n){super(),this.#a=t,this.#n=n,this.#r=[],this.#t=[],this.#e=[],this.setQueries(s)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(t=>{t.subscribe(s=>{this.#m(t,s)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(t=>{t.destroy()})}setQueries(t,s){this.#r=t,this.#n=s,He.batch(()=>{const n=this.#t,i=this.#p(this.#r);i.forEach(j=>j.observer.setOptions(j.defaultedQueryOptions));const a=i.map(j=>j.observer),l=a.map(j=>j.getCurrentResult()),r=n.length!==a.length,o=a.some((j,b)=>j!==n[b]),g=r||o,N=g?!0:l.some((j,b)=>{const w=this.#e[b];return!w||!Mt(j,w)});!g&&!N||(g&&(this.#l=i,this.#t=a),this.#e=l,this.hasListeners()&&(g&&(lt(n,a).forEach(j=>{j.destroy()}),lt(a,n).forEach(j=>{j.subscribe(b=>{this.#m(j,b)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(t=>t.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(t,s){const n=this.#p(t),i=n.map(l=>l.observer.getOptimisticResult(l.defaultedQueryOptions)),a=n.map(l=>l.defaultedQueryOptions.queryHash);return[i,l=>this.#u(l??i,s,a),()=>this.#d(i,n)]}#d(t,s){return s.map((n,i)=>{const a=t[i];return n.defaultedQueryOptions.notifyOnChangeProps?a:n.observer.trackResult(a,l=>{s.forEach(r=>{r.observer.trackProp(l)})})})}#u(t,s,n){if(s){const i=this.#c,a=n!==void 0&&i!==void 0&&(i.length!==n.length||n.some((l,r)=>l!==i[r]));return(!this.#s||this.#e!==this.#o||a||s!==this.#i)&&(this.#i=s,this.#o=this.#e,n!==void 0&&(this.#c=n),this.#s=Lt(this.#s,s(t))),this.#s}return t}#x(){return this.#n?.combine!==void 0&&this.#t.some((t,s)=>t.options.suspense&&this.#e[s]?.data===void 0)}#p(t){const s=new Map;this.#t.forEach(i=>{const a=i.options.queryHash;if(!a)return;const l=s.get(a);l?l.push(i):s.set(a,[i])});const n=[];return t.forEach(i=>{const a=this.#a.defaultQueryOptions(i),r=s.get(a.queryHash)?.shift()??new mt(this.#a,a);n.push({defaultedQueryOptions:a,observer:r})}),n}#m(t,s){const n=this.#t.indexOf(t);n!==-1&&(this.#e=Js(this.#e,n,s),this.#h())}#h(){if(this.hasListeners()){const t=this.#d(this.#e,this.#l),s=this.#x(),n=this.#s,i=s?n:this.#u(t,this.#n?.combine);(s||n!==i)&&He.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function Xs({queries:t,...s},n){const i=Kt(),a=Ft(),l=qt(),r=d.useMemo(()=>t.map(p=>{const u=i.defaultQueryOptions(p);return u._optimisticResults=a?"isRestoring":"optimistic",u}),[t,i,a]);r.forEach(p=>{Ht(p);const u=i.getQueryCache().get(p.queryHash);Qt(p,l,u)}),_t(l);const[o]=d.useState(()=>new Zs(i,r,s)),[g,N,j]=o.getOptimisticResult(r,s.combine),b=!a&&s.subscribed!==!1;d.useSyncExternalStore(d.useCallback(p=>b?o.subscribe(He.batchCalls(p)):Ut,[o,b]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),d.useEffect(()=>{o.setQueries(r,s)},[r,s,o]);const h=g.some((p,u)=>it(r[u],p))?g.flatMap((p,u)=>{const v=r[u];
1if(v&&it(v,p)){const c=new mt(i,v);return zt(v,c,l)}return[]}):[];if(h.length>0)throw Promise.all(h);const y=g.find((p,u)=>{const v=r[u];return v&&Vt({result:p,errorResetBoundary:l,throwOnError:v.throwOnError,query:i.getQueryCache().get(v.queryHash),suspense:v.suspense})});if(y?.error)throw y.error;return N(j())}var en=Object.defineProperty,ne=(t,s)=>en(t,"name",{value:s,configurable:!0}),Fe,st="HoverCard",[bt]=Jt(st,[ht]),nt=ht(),[tn,at]=bt(st),sn=ne(t=>{const{__scopeHoverCard:s,children:n,open:i,defaultOpen:a,onOpenChange:l,openDelay:r=700,closeDelay:o=300}=t,g=nt(s),N=d.useRef(0),j=d.useRef(0),b=d.useRef(!1),w=d.useRef(!1),[h,y]=Zt({prop:i,defaultProp:a??!1,onChange:l,caller:st}),p=d.useCallback(()=>{clearTimeout(j.current),N.current=window.setTimeout(()=>y(!0),r)},[r,y]),u=d.useCallback(()=>{clearTimeout(N.current),!b.current&&!w.current&&(j.current=window.setTimeout(()=>y(!1),o))},[o,y]),v=d.useCallback(()=>y(!1),[y]);return d.useEffect(()=>()=>{clearTimeout(N.current),clearTimeout(j.current)},[]),e.jsx(tn,{scope:s,open:h,onOpenChange:y,onOpen:p,onClose:u,onDismiss:v,hasSelectionRef:b,isPointerDownOnContentRef:w,children:e.jsx(Xt,{...g,children:n})})},"HoverCard"),nn="HoverCardTrigger",an=d.forwardRef(ne(function(s,n){const{__scopeHoverCard:i,...a}
1=s,l=at(nn,i),r=nt(i);return e.jsx(es,{asChild:!0,...r,children:e.jsx(ts.a,{"data-state":l.open?"open":"closed",...a,ref:n,onPointerEnter:X(s.onPointerEnter,ye(l.onOpen)),onPointerLeave:X(s.onPointerLeave,ye(l.onClose)),onFocus:X(s.onFocus,l.onOpen),onBlur:X(s.onBlur,l.onClose),onTouchStart:X(s.onTouchStart,o=>o.preventDefault())})})},"HoverCardTrigger")),rn="HoverCardPortal",[qn,on]=bt(rn,{forceMount:void 0}),Ye="HoverCardContent",cn=d.forwardRef(ne(function(s,n){const i=on(Ye,s.__scopeHoverCard),{forceMount:a=i.forceMount,...l}=s,r=at(Ye,s.__scopeHoverCard);return e.jsx(Bt,{present:a||r.open,children:e.jsx(ln,{"data-state":r.open?"open":"closed",...l,onPointerEnter:X(s.onPointerEnter,ye(r.onOpen)),onPointerLeave:X(s.onPointerLeave,ye(r.onClose)),ref:n})})},"HoverCardContent")),ln=d.forwardRef(ne(function(s,n){const{__scopeHoverCard:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:r,onInteractOutside:o,...g}=s,N=at(Ye,i),j=nt(i),b=d.useRef(null),w=Wt(n,b),[h,y]=d.useState(!1);return d.useEffect(()=>{if(h){const p=document.body;return Fe=p.style.userSelect||p.style.webkitUserSelect,p.style.userSelect="none",p.style.webkitUserSelect="none",()=>{p.style.userSelect=Fe,p.style.webkitUserSelect=Fe}}},[h]),d.useEffect(()=>{if(b.current){const p=ne(()=>{y(!1),N.isPointerDownOnContentRef.current=!1,setTimeout(()=>{document.getSelection()?.toString()!==""&&(N.hasSelectionRef.current=!0)})},"handlePointerUp");return document.addEventListener("pointerup",p),()=>{document.removeEventListener("pointerup",p),N.hasSelectionRef.current=!1,N.isPointerDownOnContentRef.current=!1}}},[N.isPointerDownOnContentRef,N.hasSelectionRef]),d.useEffect(()=>{b.current&&Nt(b.current).forEach(u=>u.setAttribute("tabindex","-1"))}),e.jsx(Gt,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:X(r,p=>{p.preventDefault()}),onDismiss:N.onDismiss,children:e.jsx(Yt,{...j,...g,onPointerDown:X(g.onPointerDown,p=>{p.currentTarget.contains(p.target)&&y(!0),N.hasSelectionRef.current=!1,N.isPointerDownOnContentRef.current=!0}),ref:w,style:{...g.style,userSelect:h?"text":void 0,WebkitUserSelect:h?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})},"HoverCardContentImpl"));function ye(t){return s=>s.pointerType==="touch"?void 0:t()}ne(ye,"excludeTouch");function Nt(t){const s=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:ne(i=>i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,"acceptNode")});for(;n.nextNode();)s.push(n.currentNode);return s}ne(Nt,"getTabbableNodes");var dn=sn,un=an,St=cn;const pn=dn,mn=un,wt=d.forwardRef(({className:t,align:s="center",sideOffset:n=4,...i},a)=>e.jsx(St,{ref:a,align:s,sideOffset:n,className:xt("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 origin-[--radix-hover-card-content-transform-origin]",t),...i}));wt.displayName=St.displayName;const dt={label:"",server:"",port:3342,database:"",username:"",password:"",enterpriseId:"",nocApiKey:""},ut={name:"",address1:"",city:"",state:"",zip:"",phone:"",email:"",website:"",notes:"",logo:"",subscriptionTier:"max"};function Ct(t,s){return!t||t.key!==s?{key:s,dir:"asc"}:t.dir==="asc"?{key:s,dir:"desc"}:null}function Et(t,s,n){if(!s)return t;const i=s.dir==="asc"?1:-1;return t.map((a,l)=>({row:a,i:l})).sort((a,l)=>{const r=n(a.row,s.key),o=n(l.row,s.key);if(typeof r=="number"&&typeof o=="number")return r===o?a.i-l.i:(r-o)*i;const g=String(r),N=String(o),j=g===""||g==="â",b=N===""||N==="â";if(j&&b)return a.i-l.i;if(j)return 1;if(b)return-1;const w=g.localeCompare(N);return w===0?a.i-l.i:w*i}).map(a=>a.row)}function Y({label:t,sortKey:s,sort:n,onSort:i,className:a,align:l="left"}){const r=n?.key===s,o=r?n.dir==="asc"?Qs:_s:Hs,g=l==="right"?"justify-end":l==="center"?"justify-center":"justify-start";return e.jsx(te,{className:xt("sticky top-0 z-20 bg-background border-b",a),children:e.jsxs("button",{type:"button",onClick:()=>i(s),className:`group/sort flex w-full items-center gap-1 ${g} text-left font-medium hover:text-foreground focus:outline-none`,"data-testid":`sort-${s}`,"aria-label":`Sort by ${t}`,children:[e.jsx("span",{className:"truncate",children:t}),e.jsx(o,{className:`w-3.5 h-3.5 shrink-0 ${r?"text-foreground":"text-muted-foreground
1/50"}`,"aria-hidden":"true"})]})})}function $e(t,s){return t instanceof Error&&t.message.startsWith(`${s}:`)}function hn(){return ce({queryKey:["/api/admin/enterprises","setup-list"],staleTime:300*1e3,placeholderData:gt,queryFn:async()=>{try{const s=await(await R("GET","/api/admin/enterprises")).json();return{details:Array.isArray(s)?s:[],adminApiAvailable:!0}}catch(t){if(!$e(t,404))throw t;return{details:[],adminApiAvailable:!1}}}})}function kt(t){return ce({queryKey:["/api/admin/enterprises",t,"users"],enabled:!!t,queryFn:async()=>{if(!t)return[];const n=await(await R("GET",`/api/admin/enterprises/${t}/users`)).json();return Array.isArray(n)?n:[]}})}function xn(t,s){return ce({queryKey:["/api/admin/enterprises",t,"profile"],enabled:s&&!!t,queryFn:async()=>{if(!t)return null;try{return await(await R("GET",`/api/admin/enterprises/${t}`)).json()}catch(n){if($e(n,404))return null;throw n}}})}function fn(t){const s=Xs({queries:t.map(n=>({queryKey:["/api/admin/enterprises",n,"profile"],staleTime:3e5,placeholderData:gt,queryFn:async()=>{try{return await(await R("GET",`/api/admin/enterprises/${n}`)).json()}catch(i){if($e(i,404))return null;throw i}}}))});return d.useMemo(()=>{const n={},i=[];return t.forEach((a,l)=>{const r=s[l];n[a]=r?.data??null,r&&r.data===void 0&&!r.isFetched&&i.push(a)}),{profilesById:n,pendingIds:i}},[t,s])}function Tt(t){return ce({queryKey:["/api/admin/enterprises",t,"data-sources"],enabled:!!t,queryFn:async()=>{if(!t)return[];const n=await(await R("GET",`/api/admin/enterprises/${t}/data-sources`)).json();return Array.isArray(n)?n:[]}})}function gn({mode:t,enterprise:s,open:n,onOpenChange:i,onSaved:a}){const{t:l}=B(),[r,o]=d.useState(ut),[g,N]=d.useState(null),[j,b]=d.useState(null),w=n&&t==="edit"&&!!s,{data:h}=xn(s?.id??null,w);d.useEffect(()=>{if(n)if(N(null),b(null),t==="edit"&&s){const c=h??s;o({name:vt(c,s.id),address1:Z(c,"address1"),city:Z(c,"city"),state:Z(c,"state"),zip:Z(c,"zip"),phone:Z(c,"phone"),email:Z(c,"email"),website:Z(c,"website"),notes:Z(c,"notes"),logo:Z(c,"logo"),subscriptionTier:Cs(c.subscriptionTier)})}else o(ut)},[n,t,s,h]);const y=U({mutationFn:async()=>await(t==="add"?await R("POST","/api/admin/enterprises",r):await R("PUT",`/api/admin/enterprises/${s.id}`,r)).json(),onSuccess:c=>{const k=c?.id||s?.id||"";k&&$.setQueryData(["/api/admin/enterprises",k,"profile"],P=>({...P??{},id:k,...r})),$.invalidateQueries({queryKey:["/api/admin/enterprises"]}),a(k),i(!1)},onError:c=>{$e(c,404)?N(l("enterpriseSetup.dialog.unsupported")):N(c?.message||"Save failed")}});function p(c){const k=c.target.files?.[0];if(c.target.value="",!k)return;if(b(null),!k.type.startsWith("image/")){b("Please select an image file.");return}if(k.size>500*1024){b("Image must be smaller than 500 KB.");return}const P=new FileReader;P.onload=()=>o(M=>({...M,logo:String(P.result||"")})),P.onerror=()=>b("Could not read file."),P.readAsDataURL(k)}function u(){o(c=>({...c,logo:""}))}const v=t==="edit";return e.jsx(ke,{open:n,onOpenChange:i,children:e.jsxs(Te,{className:"max-w-2xl max-h-[85vh] overflow-y-auto","data-testid":"enterprise-profile-dialog",children:[e.jsxs(Pe,{children:[e.jsxs(Re,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),l(v?"enterpriseSetup.dialog.editTitle":"enterpriseSetup.dialog.addTitle")]}),e.jsx(De,{children:l(v?"enterpriseSetup.dialog.editDescription":"enterpriseSetup.dialog.addDescription")})]}),e.jsxs("div",{className:"mb-2 pb-6 border-b border-border",children:[e.jsx(A,{className:"text-xs text-muted-foreground mb-1 block",children:l("admin.enterprise.companyLogo")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"relative group",children:r.logo?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:r.logo,alt:"Enterprise logo",className:"h-16 w-auto max-w-[200px] object-contain rounded-lg border border-border bg-white p-2"}),e.jsx("button",{type:"button",onClick:u,className:"absolute -top-2 -right-2 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs leading-none flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity","aria-label":"Remove logo",title:"Remove logo",children:"Ã"})]}):e.jsx("div",{className:"h-16 w-32 rounded-lg border-2 border-dashed border-border flex items-center justify-center text-muted-foreground",children:e.jsx(Es,{className:"w-5 h-5"})})}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("label",{className:"inline-flex",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p}),e.jsx(T,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{className:"cursor-pointer gap-2",children:[e.jsx(ks,{className:"w-4 h-4"}),r.logo?"Replace Logo":"Upload Logo"]})})]}),j&&e.jsx("p",{className:"text-xs text-destructive",children:j})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(A,{className:"text-xs text-muted-foreground",children:[l("admin.enterprise.name")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{value:r.name,onChange:c=>o({...r,name:c.target.value}),className:"mt-1",placeholder:"Acme Catering Co.","data-testid":"enterprise-profile-name"})]}),e.jsxs("div",{className:"w-40 shrink-0",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.tier")}),e.jsxs(Ts,{value:r.subscriptionTier,onValueChange:c=>o({...r,subscriptionTier:c}),children:[e.jsx(Ps,{className:"mt-1","data-testid":"enterprise-profile-tier",children:e.jsx(Rs,{})}),e.jsx(Ds,{children:As.map(c=>e.jsx($s,{value:c.value,"data-testid":`enterprise-profile-tier-${c.value}`,children:c.label},c.value))})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.address")}),e.jsx(q,{value:r.address1,onChange:c=>o({...r,address1:c.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.city")}),e.jsx(q,{value:r.city,onChange:c=>o({...r,city:c.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.state")}),e.jsx(q,{value:r.state,onChange:c=>o({...r,state:c.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.zip")}),e.jsx(q,{value:r.zip,onChange:c=>o({...r,zip:c.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.phone")}),e.jsx(Ys,{value:r.phone,onChange:c=>o({...r,phone:c.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.email")}),e.jsx(q,{value:r.email,onChange:c=>o({...r,email:c.target.value}),className:"mt-1",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:l("admin.enterprise.website")}),e.jsx(q,{value:r.website,onChange:c=>o({...r,website:c.target.value}),className:"mt-1"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx(Os,{value:r.notes,onChange:c=>o({...r,notes:c.target.value}),className:"mt-1",rows:3})]})]}),g&&e.jsx("p",{className:"text-xs text-destructive","data-testid":"enterprise-profile-error",children:g}),e.jsxs(Ae,{children:[e.jsx(T,{variant:"outline",onClick:()=>i(!1),disabled:y.isPending,children:l("common.cancel")}),e.jsxs(T,{onClick:()=>y.mutate(),disabled:!r.name||y.isPending,"data-testid":"enterprise-profile-save",className:"gap-2",children:[e.jsx(yt,{className:"w-4 h-4"}),y.isPending?l("enterpriseSetup.dialog.saving"):l("admin.enterprise.saveChanges")]})]})]})})}function vn({enterprise:t,onClose:s}){const{t:n}=B(),[i,a]=d.useState(null),[l,r]=d.useState(!1),[o,g]=d.useState(null),[N,j]=d.use
1State(!1),[b,w]=d.useState(null),h=!!t?.connectionVerifiedAt,y=l,p=U({mutationFn:async()=>{if(!t)throw new Error("No enterprise");return(await R("POST",`/api/admin/enterprises/${t.id}/verify-connection`)).json()},onSuccess:c=>{a(c.checks||[]),r(!!c.success),g(c.message||null),j(!!c.multipleConnections),w(null),$.invalidateQueries({queryKey:["/api/admin/enterprises"]})},onError:c=>{w(c?.message||"Verification failed"),r(!1),j(!1)}}),u=U({mutationFn:async c=>{if(!t)throw new Error("No enterprise");return(await R("PATCH",`/api/admin/enterprises/${t.id}/active`,{active:c})).json()},onSuccess:()=>{$.invalidateQueries({queryKey:["/api/admin/enterprises"]}),s()},onError:c=>w(c?.message||"Failed to update status")});d.useEffect(()=>{a(null),r(!1),g(null),j(!1),w(null)},[t?.id]);const v=t?t.active!==!1:!1;return e.jsx(ke,{open:!!t,onOpenChange:c=>{c||s()},children:e.jsxs(Te,{className:"max-w-lg min-w-0 overflow-hidden",children:[e.jsxs(Pe,{className:"min-w-0",children:[e.jsxs(Re,{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Qe,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:t?.name})]}),e.jsx(De,{children:"Verify the database connection, then deactivate or re-activate this enterprise. An enterprise cannot be activated until its connection verifies successfully."})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border p-3 min-w-0",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:"Current status"}),e.jsx("p",{className:"text-xs text-muted-foreground break-words",children:v?"Active â users can sign in.":"Inactive â non-admin users are blocked."})]}),e.jsx(ve,{variant:v?"default":"secondary",className:"shrink-0","data-testid":"enterprise-status-badge",children:v?"Active":"Inactive"})]}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:"Database connection"}),e.jsxs(T,{variant:"outline",size:"sm",className:"shrink-0",onClick:()=>p.mutate(),disabled:p.isPending,"data-testid":"verify-connection",children:[e.jsx(Qe,{className:"w-3.5 h-3.5 mr-1"}),p.isPending?"Verifyingâ¦":"Verify Connection"]})]}),h&&!i&&e.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"already-verified",children:["Last verified ",new Date(t.connectionVerifiedAt).toLocaleString(),"."]}),i&&e.jsxs("div",{className:"space-y-2 min-w-0","data-testid":"verify-results",children:[i.length===0&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 p-2 min-w-0","data-testid":"verify-no-connection",children:[e.jsx(se,{className:"w-4 h-4 text-destructive mt-0.5 shrink-0"}),e.jsx("p",{className:"text-xs text-destructive break-words",children:o||n("enterpriseSetup.status.noConnection")})]}),N&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 p-2 min-w-0","data-testid":"verify-multiple-connections",children:[e.jsx(se,{className:"w-4 h-4 text-destructive mt-0.5 shrink-0"}),e.jsx("p",{className:"text-xs text-destructive break-words",children:o||n("enterpriseSetup.status.multipleConnections").replace("{count}",String(i.length))})]}),i.length>0&&e.jsx("div",{className:"border rounded-lg divide-y overflow-hidden min-w-0",children:i.map(c=>e.jsxs("div",{className:"flex items-start gap-2 p-2 min-w-0",children:[c.success?e.jsx(ot,{className:"w-4 h-4 text-green-600 mt-0.5 shrink-0"}):e.jsx(se,{className:"w-4 h-4 text-destructive mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.label}),e.jsxs("p",{className:"text-xs text-muted-foreground break-all",children:[c.server,c.database?` / ${c.database}`:""]}),c.success?e.jsx("p",{className:"text-xs text-muted-foreground break-words","data-testid":"verify-location-count",children:typeof c.locationCount=="number"?n("enterpriseSetup.status.locationCount").replace("{count}",String(c.locationCount)):c.message}):e.jsx("pre",{className:"mt-1 w-full max-w-full max-h-32 overflow-auto whitespace-pre-wrap break-all rounded bg-muted/50 p-2 text-xs text-destructive font-mono",children:c.message})]})]},c.id))})]})]}),b&&e.jsx("p",{className:"text-xs text-destructive break-words","data-testid":"status-error",children:b})]}),e.jsxs(Ae,{className:"gap-2 sm:gap-2 min-w-0 flex-wrap",children:[v?e.jsxs(T,{variant:"destructive",onClick:()=>u.mutate(!1),disabled:u.isPending,"data-testid":"deactivate-enterprise",children:[e.jsx(pe,{className:"w-3.5 h-3.5 mr-1"})," Deactivate"]}):e.jsxs(T,{onClick:()=>u.mutate(!0),disabled:!y||u.isPending,"data-testid":"activate-enterprise",title:y?void 0:"Verify the database connection first",children:[e.jsx(ot,{className:"w-3.5 h-3.5 mr-1"})," Activate"]}),e.jsx(T,{variant:"outline",onClick:s,children:"Done"})]})]})})}function jn({enterprise:t,open:s,onOpenChange:n,onDeleted:i}){const{t:a}=B(),{toast:l}
1=be(),[r,o]=d.useState("confirm"),[g,N]=d.useState(null),{data:j=[]}=kt(s?t?.id??null:null),b=d.useMemo(()=>j.filter(p=>!ue(p.role)).length,[j]);d.useEffect(()=>{s&&(o("confirm"),N(null))},[s,t?.id]);const w=U({mutationFn:async()=>{if(!t)throw new Error("No enterprise");return(await R("DELETE",`/api/admin/enterprises/${t.id}`)).json()},onSuccess:p=>{$.invalidateQueries({queryKey:["/api/admin/enterprises"]}),l({description:a("enterpriseSetup.delete.done")}),n(!1),i(p.id)},onError:p=>{o("confirm"),N(p?.message||a("enterpriseSetup.delete.failed"))}});function h(){if(b>0){o("secondary");return}w.mutate()}const y=w.isPending;return e.jsx(jt,{open:s,onOpenChange:p=>{!p&&!y&&n(!1)},children:r==="confirm"?e.jsxs(_e,{"data-testid":"delete-enterprise-confirm",children:[e.jsxs(Ue,{children:[e.jsx(ze,{children:a("enterpriseSetup.delete.confirmTitle")}),e.jsx(Ve,{children:a("enterpriseSetup.delete.confirmBody").replace("{name}",t?.name||"")})]}),g&&e.jsx("p",{className:"text-xs text-destructive","data-testid":"delete-enterprise-error",children:g}),e.jsxs(Be,{children:[e.jsx(We,{disabled:y,children:a("enterpriseSetup.delete.cancel")}),e.jsx(Ge,{onClick:p=>{p.preventDefault(),h()},disabled:y,"data-testid":"delete-enterprise-confirm-action",children:y?a("enterpriseSetup.delete.pending"):b>0?a("enterpriseSetup.delete.continue"):a("enterpriseSetup.delete.confirm")})]})]}):e.jsxs(_e,{"data-testid":"delete-enterprise-secondary",children:[e.jsxs(Ue,{children:[e.jsx(ze,{children:a("enterpriseSetup.delete.secondaryTitle")}),e.jsx(Ve,{children:a("enterpriseSetup.delete.secondaryBody").replace("{count}",String(b)).replace("{name}",t?.name||"")})]}),g&&e.jsx("p",{className:"text-xs text-destructive","data-testid":"delete-enterprise-error",children:g}),e.jsxs(Be,{children:[e.jsx(We,{disabled:y,children:a("enterpriseSetup.delete.cancel")}),e.jsx(Ge,{onClick:p=>{p.preventDefault(),w.mutate()},disabled:y,"data-testid":"delete-enterprise-secondary-action",children:a(y?"enterpriseSetup.delete.pending":"enterpriseSetup.delete.confirmFinal")})]})]})})}function yn({enterpriseId:t,enterprises:s,mode:n,connection:i,open:a,onOpenChange:l}){const{t:r}=B(),[o,g]=d.useState(dt),[N,j]=d.useState(null),[b,w]=d.useState(null),[h,y]=d.useState("api"),[p,u]=d.useState(null),[v,c]=d.useState(null),[k,P]=d.useState(null),[M,O]=d.useState(!1),m=d.useRef(!1);d.useEffect(()=>{if(a)if(j(null),c(null),w(null),P(null),O(!1),m.current=!1,n==="edit"&&i){g({label:i.label||"",server:i.server||"",port:i.port||3342,database:i.database||"",username:i.username||"",password:"",enterpriseId:i.enterpriseId||t,nocApiKey:""});const f=i.type==="api"?"api":"direct";y(f),u(null)}else g({...dt,enterpriseId:t}),y("api"),u(null)},[a,n,i,t]);function x(){const f={label:o.label,server:o.server,port:o.port,database:o.database,username:o.username,password:o.password,enterpriseId:o.enterpriseId},H=o.nocApiKey.trim();return H&&(f.nocApiKey=H),f}const C=i??k;async function E(){if(C)return C;const H=await(await R("POST",`/api/admin/enterprises/${t}/data-sources`,x())).json();return P(H),$.invalidateQueries({queryKey:["/api/admin/enterprises",t,"data-sources"]}),H}const I=U({mutationFn:async()=>{const f=C,_=await(f?await R("PUT",`/api/admin/enterprises/${t}/data-sources/${f.id}`,x()):await R("POST",`/api/admin/enterprises/${t}/data-sources`,x())).json();return f&&h==="direct"&&f.type==="api"&&await R("POST",`/api/admin/enterprises/${t}/data-sources/${f.id}/set-mode`,{mode:"direct"}),_},onSuccess:()=>{O(!1),m.current=!1,$.invalidateQueries({queryKey:["/api/admin/enterprises"]}),l(!1)},onError:f=>j(f?.message||"Save failed")}),z=U({mutationFn:async()=>{O(!0);const f=C;f&&!m.current&&(await R("POST",`/api/admin/enterprises/${t}/data-sources/${f.id}/noc-key/snapshot`,{force:!0}),m.current=!0);const H=await E();return o.nocApiKey.trim()&&f&&await R("PUT",`/api/admin/enterprises/${t}/data-sources/${H.id}`,x()),(await R("POST",`/api/admin/enterprises/${t}/data-sources/${H.id}/verify-noc-key`,{})).json()},onSuccess:f=>{f.success?(c({ok:!0,message:f.message||"Verified",database:f.database||null}),u("api"),g(H=>({...H,nocApiKey:""})),$.invalidateQueries({queryKey:["/api/admin/enterprises",t,"data-sources"]}),$.invalidateQueries({queryKey:["/api/admin/enterprises"]}),$.invalidateQueries({queryKey:["/api/admin/enterprise"]})):c({ok:!1,message:f.message||"Verification failed",httpStatus:f.httpStatus,detail:f.detail})},onError:f=>c({ok:!1,message:f?.message||"Verification failed"})}),G=U({mutationFn:async()=>{O(!0);const f=await E();return(await R("POST",`/api/admin/enterprises/${t}/data-sources/${f.id}/test-sql`,{server:o.server,port:o.port,database:o.database,username:o.username,...o.password?{password:o.password}:{}})).json()},onSuccess:f=>{f.success?(c({ok:!0,message:f.message||"SQL connection verified"}),u("direct")):c({ok:!1,message:f.message||"SQL connection failed"})},onError:f=>c({ok:!1,message:f?.message||"SQL connection failed"})}),Q=U({mutationFn:async()=>{const f=C;return f?(await R("PUT",`/api/admin/enterprises/${t}/data-sources/${f.id}`,{nocApiKey:""}),{cleared:!0,hadRow:!0}
1):{cleared:!0,hadRow:!1}},onSuccess:()=>{g(f=>({...f,nocApiKey:""})),p==="api"&&u(null),c({ok:!0,message:"API key cleared."}),$.invalidateQueries({queryKey:["/api/admin/enterprises"]})},onError:f=>j(f?.message||"Failed to clear the API key")});async function ae(){const f=C;if(M&&f){try{await R("POST",`/api/admin/enterprises/${t}/data-sources/${f.id}/noc-key/rollback`,{deleteIfCreated:n==="add"&&!i})}catch{}$.invalidateQueries({queryKey:["/api/admin/enterprises",t,"data-sources"]})}l(!1)}const D=!!i?.hasNocApiKey,le=h==="direct",J=h==="api"||D,re=h==="direct",L=p==="api",de=h==="api"?D||!!o.nocApiKey.trim()||L||!!k?.hasNocApiKey:!!o.server&&!!o.database&&!!o.username&&(n==="edit"||!!o.password),ie=z.isPending||G.isPending,Oe=de&&!ie&&!!o.label&&!!o.enterpriseId,me=p===h,K=v&&v.ok&&v.database||i?.database||"",Ie=!!o.label&&!!o.enterpriseId&&de&&me;function Ne(f){f!==h&&(y(f),w(null),c(null))}function V(){p==="direct"&&u(null),c(null)}function Me(f){if(!f){ae();return}l(f)}return e.jsx(ke,{open:a,onOpenChange:Me,children:e.jsxs(Te,{className:"max-w-lg","data-testid":"connection-dialog",children:[e.jsxs(Pe,{children:[e.jsx(Re,{children:r(n==="add"?"enterpriseSetup.connections.addTitle":"enterpriseSetup.connections.editTitle")}),e.jsx(De,{children:"Establish a connection to a Caterease database."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(A,{className:"text-xs",children:["Connection Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{value:o.label,onChange:f=>g({...o,label:f.target.value}),placeholder:"Production DB","data-testid":"connection-label"})]}),e.jsxs("div",{className:"space-y-1.5","data-testid":"connection-mode-toggle",children:[e.jsx(A,{className:"text-xs text-center block",children:"Connection mode"}),e.jsx("div",{className:"flex justify-center",children:e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-lg border bg-muted/60 p-1",children:[e.jsx(T,{type:"button",size:"sm",variant:h==="api"?"default":"ghost",className:"h-8 px-6 text-xs font-medium rounded-md",onClick:()=>Ne("api"),"data-testid":"connection-mode-api",children:"API"}),e.jsx(T,{type:"button",size:"sm",variant:h==="direct"?"default":"ghost",className:"h-8 px-6 text-xs font-medium rounded-md",onClick:()=>Ne("direct"),"data-testid":"connection-mode-direct",children:"Direct Data"})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground text-center","data-testid":"connection-mode-hint",children:h==="api"?"Uses a NOC-provisioned API key. Verify the key to enable Save.":"Uses direct SQL credentials. Verify the connection to enable Save."}),b&&e.jsx("p",{className:"text-[11px] text-destructive text-center","data-testid":"connection-mode-error",children:b})]}),le&&e.jsxs("div",{className:"space-y-3 rounded-md border p-3","data-testid":"connection-sql-block",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(A,{className:"text-xs font-medium",children:"Direct Data (SQL) credentials"}),p==="direct"&&o.database.trim()&&e.jsxs("span",{className:"text-[11px] text-green-600 font-medium","data-testid":"connection-sql-verified-db",children:["⢠verified (",o.database.trim(),")"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsxs(A,{className:"text-xs",children:["Server ",re&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{value:o.server,onChange:f=>{g({...o,server:f.target.value}),V()},placeholder:"db.example.com","data-testid":"connection-server"})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Port"}),e.jsx(q,{type:"number",value:o.port,onChange:f=>{g({...o,port:Number(f.target.value)||3342}),V()}})]})]}),e.jsxs("div",{children:[e.jsxs(A,{className:"text-xs",children:["Database ",re&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{value:o.database,onChange:f=>{g({...o,database:f.target.value}),V()},"data-testid":"connection-database"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsxs(A,{className:"text-xs",children:["Username ",re&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{value:o.username,onChange:f=>{g({...o,username:f.target.value}),V()},autoComplete:"off",name:"sql-connection-username","data-1p-ignore":!0,"data-lpignore":"true","data-testid":"connection-username"})]}),e.jsxs("div",{children:[e.jsxs(A,{className:"text-xs",children:["Password ",re&&n==="add"&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{type:"password",value:o.password,onChange:f=>{g({...o,password:f.target.value}),V()},placeholder:n==="edit"?"â¢â¢â¢â¢â¢â¢â¢â¢ (unchanged)":"",autoComplete:"off",name:"sql-connection-password","data-1p-ignore":!0,"data-lpignore":"true","data-testid":"connection-password"})]})]})]}),J&&e.jsxs("div",{className:"rounded-md border border-dashed p-3 space-y-2","data-testid":"connection-noc-block",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(A,{className:"text-xs font-medium",children:"NOC API key"}),i?.type==="api"&&i.nocApiKeyDegraded&&e.jsx("span",{className:"text-[11px] text-amber-600 font-medium","data-testid":"connection-noc-degraded-badge",children:"degraded"}),i?.type==="api"&&!i.nocApiKeyDegraded&&e.jsx("span",{className:"text-[11px] text-green-600 font-medium","data-testid":"connection-noc-mode-badge",children:"api mode"}),i&&i.type!=="api"&&D&&e.jsx("span",{className:"text-[11px] text-amber-600 font-medium","data-testid":"connection-noc-mode-badge",children:"unverified"})]}),D&&e.jsxs("p",{className:"text-[11px] text-muted-foreground font-mono","data-testid":"connection-noc-preview",children:["stored: ",i?.nocApiKeyPreview||"set",i?.nocApiKeyVerifiedAt&&e.jsxs("span",{className:"ml-2 text-green-600","data-testid":"connection-noc-verified-db",children:["⢠verified",K?` (${K})`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{type:"text",value:o.nocApiKey,onChange:f=>{g({...o,nocApiKey:f.target.value}),p==="api"&&u(null),c(null)},placeholder:D?"â¢â¢â¢â¢â¢â¢â¢â¢ (unchanged â paste to replace)":"cea_⦠(paste tenant key from NOC)","data-testid":"connection-noc-api-key",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,name:"noc-api-key","data-form-type":"other","data-1p-ignore":!0,"data-lpignore":"true","data-bwignore":!0,style:o.nocApiKey?{WebkitTextSecurity:"disc",textSecurity:"disc"}:void 0}),(D||!!k?.hasNocApiKey||!!o.nocApiKey.trim())&&e.jsxs(T,{type:"button",variant:"outline",size:"sm",onClick:()=>Q.mutate(),disabled:Q.isPending||ie,"data-testid":"connection-clear-key",className:"shrink-0 gap-1.5 text-muted-foreground",title:"Clear the API key (keeps the connection record)",children:[e.jsx(pe,{className:"w-3.5 h-3.5"}),Q.isPending?"Clearingâ¦":"Clear"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Paste the tenant key, then click Verify to probe NOC and switch to api mode. (New connections are saved automatically as part of Verify.)"})]})]}),N&&e.jsx("p",{className:"text-xs text-destructive","data-testid":"connection-error",children:N}),v&&v.ok&&e.jsxs("p",{className:"text-xs text-green-600","data-testid":"connection-verify-result",children:["â ",v.message]}),v&&!v.ok&&e.jsxs("div",{className:"text-xs text-destructive space-y-1","data-testid":"connection-verify-result",children:[e.jsxs("p",{children:["à ",v.message]}),"detail"in v&&v.detail&&e.jsx("p",{className:"text-[10px] text-muted-foreground font-mono break-all",children:v.detail})]}),!me&&e.jsx("p",{className:"text-[11px] text-amber-600","data-testid":"connection-verify-needed",children:h==="api"?"Click Verify to check the NOC key. It's saved and probed for you, then Save unlocks for the final save.":"Click Verify to test the SQL connection. It's saved and tested for you, then Save unlocks for the final save."}),e.jsxs(Ae,{className:"gap-2 sm:justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(T,{variant:"outline",onClick:ae,disabled:I.isPending||ie,"data-testid":"connection-cancel",children:r("common.cancel")})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{type:"button",variant:"outline",onClick:()=>h==="api"?z.mutate():G.mutate(),disabled:!Oe,"data-testid":"connection-verify",className:"gap-2",children:ie?"Verifyingâ¦":me?"Re-verify":"Verify"}),e.jsxs(T,{onClick:()=>I.mutate(),disabled:!Ie||I.isPending,"data-testid":"connection-save",className:"gap-2",children:[e.jsx(yt,{className:"w-4 h-4"}),I.isPending?r("enterpriseSetup.dialog.saving"):r("common.save")]})]})]})]})})}function bn({count:t,expanded:s,onToggle:n,testId:i}){const{t:a}=B();return t===0?null:e.jsxs(ve,{variant:"destructive",className:"gap-1 cursor-pointer select-none",role:"button",tabIndex:0,onClick:n,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},"aria-expanded":s,"data-testid":i,children:[e.jsx(se,{className:"w-3 h-3"}),t===1?a("enterpriseSetup.connections.warn.one"):a("enterpriseSetup.connections.warn.many").replace("{count}",String(t)),s?e.jsx(Ks,{className:"w-3 h-3"}):e.jsx(Fs,{className:"w-3 h-3"})]})}function Nn(t,s){switch(t.kind){case"owner":return t.enterpriseName?s("enterpriseSetup.connections.diag.owner").replace("{name}",t.enterpriseName):s("enterpriseSetup.connections.diag.ownerUnassigned");case"selected":return s("enterpriseSetup.connections.diag.selected").replace("{name}",t.enterpriseName||"");case"linkedLocations":return s("enterpriseSetup.connections.diag.linkedLocations").replace("{count}",String(t.count??0)).replace("{name}",t.enterpriseName||"");case"noLinkedLocations":return s("enterpriseSetup.connections.diag.noLinkedLocations");case"whyUnassigned":return s("enterpriseSetup.connections.diag.whyUnassigned");case"whyMismatch":return s("enterpriseSetup.connections.diag.whyMismatch");case"whyMultiEnterprise":return s("enterpriseSetup.connections.diag.whyMultiEnterprise");case"whyLocationsDisagree":return s("enterpriseSetup.connections.diag.whyLocationsDisagree");default:return""}}function Sn(t,s){return s(`enterpriseSetup.connections.repair.${t.kind}`).replace("{name}",t.targetEnterpriseName)}
1function wn({lines:t,repairs:s,onRepair:n,repairing:i,connId:a}){const{t:l}=B();return e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 space-y-2","data-testid":`connection-diagnostics-${a}`,children:[e.jsx("ul",{className:"space-y-1 text-xs",children:t.map((r,o)=>{const g=r.kind.startsWith("why");return e.jsxs("li",{className:g?"text-destructive font-medium flex items-start gap-1.5":"text-muted-foreground flex items-start gap-1.5",children:[g&&e.jsx(se,{className:"w-3 h-3 mt-0.5 shrink-0"}),e.jsx("span",{children:Nn(r,l)})]},o)})}),s.length>0?e.jsx("div",{className:"flex flex-wrap gap-2 pt-1","data-testid":`connection-repairs-${a}`,children:s.map(r=>e.jsxs(T,{size:"sm",variant:"outline",className:"gap-1.5 h-7",disabled:i,onClick:()=>n(r),"data-testid":`connection-repair-${r.kind}-${a}`,children:[e.jsx(qs,{className:"w-3 h-3"}),Sn(r,l)]},`${r.kind}:${r.setEnterpriseId}`))}):e.jsx("p",{className:"text-[11px] text-muted-foreground pt-1","data-testid":`connection-repairs-none-${a}`,children:l("enterpriseSetup.connections.repair.noneGuidance")})]})}function Cn({enterprise:t,enterprises:s}){const{t:n}=B(),{toast:i}=be(),{data:a=[],isLoading:l}=Tt(t.id),[r,o]=d.useState(null),[g,N]=d.useState(null),[j,b]=d.useState(new Set),w=d.useMemo(()=>{const u=new Map(s.map(v=>[v.id,v.name]));return v=>u.get(v)||vt(null)},[s]),h=U({mutationFn:async({dsId:u,setEnterpriseId:v})=>(await R("PUT",`/api/admin/enterprises/${t.id}/data-sources/${u}`,{enterpriseId:v})).json(),onSuccess:()=>{$.invalidateQueries({queryKey:["/api/admin/enterprises",t.id,"data-sources"]}),i({description:n("enterpriseSetup.connections.repair.done")})},onError:u=>{i({variant:"destructive",description:u?.message||n("enterpriseSetup.connections.repair.failed")})}});function y(u){b(v=>{const c=new Set(v);return c.has(u)?c.delete(u):c.add(u),c})}const p=vs(a.length);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-end",children:p.canAdd&&e.jsxs(T,{size:"sm",className:"gap-1.5",onClick:()=>{N(null),o("add")},"data-testid":"add-connection",children:[e.jsx(Ze,{className:"w-3.5 h-3.5"})," ",n("enterpriseSetup.connections.add")]})}),p.note==="atCapacity"&&e.jsx("p",{className:"text-xs text-muted-foreground rounded-md border bg-muted/40 px-3 py-2","data-testid":"connections-at-capacity",children:n("enterpriseSetup.connections.atCapacity")}),p.note==="tooMany"&&e.jsxs("div",{className:"flex items-start gap-2 text-xs text-destructive rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2","data-testid":"connections-too-many",children:[e.jsx(se,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:n("enterpriseSetup.connections.tooMany").replace("{count}",String(a.length))})]}),l&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Loadingâ¦"}),!l&&a.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground","data-testid":"connections-empty",children:n("enterpriseSetup.connections.empty")}),!l&&a.length>0&&e.jsxs(Xe,{children:[e.jsx(et,{children:e.jsxs(oe,{children:[e.jsx(te,{children:n("enterpriseSetup.connections.col.label")}),e.jsx(te,{children:n("enterpriseSetup.connections.col.type")}),e.jsx(te,{children:n("enterpriseSetup.connections.col.database")}),e.jsx(te,{children:n("enterpriseSetup.connections.col.status")}),e.jsx(te,{className:"w-12"})]})}),e.jsx(tt,{children:a.map(u=>{const v=u.relationship,c=v?.codes.length??0,k=j.has(u.id),P=k&&v&&!v.ok?js(v,t.id,w):null;return e.jsxs(d.Fragment,{children:[e.jsxs(oe,{"data-testid":`connection-${u.id}`,children:[e.jsx(F,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ys,{className:"w-3.5 h-3.5 text-muted-foreground"}),e.jsx("span",{children:u.label?.trim()||n("enterpriseSetup.connections.unnamed")}),e.jsx(bn,{count:c,expanded:k,onToggle:()=>y(u.id),testId:`connection-warning-${u.id}`}),u.type==="api"&&u.nocApiKeyDegraded&&e.jsxs(ve,{variant:"outline",className:"gap-1 border-amber-500/40 text-amber-600 bg-amber-500/5 text-[10px] font-medium",title:n("enterpriseSetup.connections.degradedHint"),"data-testid":`connection-degraded-${u.id}`,children:[e.jsx(se,{className:"w-3 h-3"}),n("enterpriseSetup.connections.status.degraded")]})]})}),e.jsx(F,{className:"text-xs text-muted-foreground",children:u.type==="api"?"API":"Direct Data"}),e.jsx(F,{className:"font-mono text-xs text-muted-foreground",children:u.database}),e.jsx(F,{children:e.jsx(ve,{variant:t.active!==!1?"default":"secondary","data-testid":`connection-status-${u.id}`,children:t.active!==!1?n("enterpriseSetup.connections.status.active"):n("enterpriseSetup.connections.status.inactive")})}),e.jsx(F,{children:e.jsx(T,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{N(u),o("edit")},"data-testid":`edit-connection-${u.id}`,children:e.jsx(je,{className:"w-3.5 h-3.5"})})})]}),k&&P&&e.jsx(oe,{"data-testid":`connection-detail-row-${u.id}`,children:e.jsx(F,{colSpan:5,className:"py-2",children:e.jsx(wn,{lines:P.lines,repairs:P.repairs,repairing:h.isPending,connId:u.id,onRepair:M=>h.mutate({dsId:u.id,setEnterpriseId:M.setEnterpriseId})})})})]},u.id)})})]}),e.jsx(yn,{enterpriseId:t.id,enterprises:s,mode:r==="edit"?"edit":"add",connection:r==="edit"?g:null,open:r!==null,onOpenChange:u=>{u||(o(null),N(null))}})]})}function En({enterprise:t}){const s=bs(),{t:n}=B(),{user:i}=Je(),{toast:a}=be(),{data:l=[],isLoading:r,error:o}=kt(t.id),g=d.useMemo(()=>l.filter(x=>!ue(x.role)),[l]),{data:N=[]}=ce({queryKey:["/api/admin/locations"]}),[j,b]=d.useState(null),[w,h]=d.useState(!1),[y,p]=d.useState(""),[u,v]=d.useState(null),c=x=>v(C=>Ct(C,x)),k=d.useMemo(()=>{const x=y.trim().toLowerCase(),C=x?g.filter(E=>[E.username,E.displayName,E.email,E.role].some(I=>(I||"").toLowerCase().includes(x))):g;return Et(C,u,(E,I)=>{switch(I){case"username":return E.username||"";case"displayName":return E.displayName||"";case"email":return E.email||"";case"role":return E.role||"";case"locations":return E.locationIds.length;default:return""}})},[g,y,u]);function P(){h(!0),b(null)}function M(x){h(!1),b({id:x.id,username:x.username,displayName:x.displayName,email:x.email,phone:x.phone,role:x.role,locationIds:x.locationIds,serials:x.serials||[],appAccess:x.appAccess,userType:x.userType})}const O=U({mutationFn:async x=>{await R("DELETE",`/api/admin/users/${x}`)},onSuccess:()=>{$.invalidateQueries({queryKey:["/api/admin/enterprises",t.id,"users"]}),$.invalidateQueries({queryKey:["/api/admin/users"]})},onError:x=>{const{code:C,message:E}=Ns(x);a({title:"Could not delete user",description:C==="LAST_ADMIN"?n("users.error.lastAdmin"):E,variant:"destructive"})}}),m=w||!!j;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground","data-testid":"users-count",children:n("enterpriseSetup.users.userCount").replace("{count}",String(g.length))}),e.jsxs(T,{size:"sm",className:"gap-1",onClick:P,"data-testid":"add-user",children:[e.jsx(Ze,{className:"w-4 h-4"})," ",n("users.addUser")]})]}),!r&&!o&&g.length>0&&e.jsx(q,{value:y,onChange:x=>p(x.target.value),placeholder:n("enterpriseSetup.users.searchPlaceholder"),className:"h-9","data-testid":"users-search","aria-label":n("enterpriseSetup.users.searchPlaceholder")}),r&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Loadingâ¦"}),o&&!r&&e.jsx("p",{className:"py-8 text-center text-sm text-destructive","data-testid":"users-error",children:n("enterpriseSetup.users.error")}),!r&&!o&&g.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground","data-testid":"users-empty",children:n("enterpriseSetup.users.empty")}),!r&&!o&&g.length>0&&k.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground","data-testid":"users-search-empty",children:n("enterpriseSetup.users.searchEmpty")}),!r&&!o&&k.length>0&&e.jsxs(Xe,{className:"w-full table-fixed",containerClassName:"max-h-[calc(100vh-22rem)] rounded-md border","data-testid":"users-scroll",children:[e.jsx(et,{children:e.jsxs(oe,{children:[e.jsx(Y,{label:n("users.username"),sortKey:"username",sort:u,onSort:c,className:"w-[16%]"}),e.jsx(Y,{label:n("users.displayName"),sortKey:"displayName",sort:u,onSort:c,className:"w-[20%]"}),e.jsx(Y,{label:n("users.email"),sortKey:"email",sort:u,onSort:c,className:"w-[24%]"}),e.jsx(Y,{label:n("users.role"),sortKey:"role",sort:u,onSort:c,className:"w-[14%]"}),e.jsx(Y,{label:n("users.locations"),sortKey:"locations",sort:u,onSort:c,className:"w-[14%]",align:"center"}),e.jsx(te,{className:"w-24 sticky top-0 z-20 bg-background border-b"})]})}),e.jsx(tt,{children:k.map(x=>{const C=!!i&&x.id===i.id,E=ue(x.role),I=E,z=E||C,G=E?n("enterpriseSetup.users.cannotEditSystemAdmin"):"",Q=n(E?"enterpriseSetup.users.cannotEditSystemAdmin":"enterpriseSetup.users.cannotDeleteSelf");return e.jsxs(oe,{"data-testid":`user-${x.id}`,children:[e.jsx(F,{className:"font-mono text-xs align-top truncate",title:x.username,children:ee(x.username,y)}),e.jsx(F,{className:"font-medium align-top truncate",title:x.displayName,children:ee(x.displayName,y)}),e.jsx(F,{className:"text-xs text-muted-foreground align-top",children:x.email?e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(fe,{asChild:!0,children:e.jsx("span",{className:"block truncate cursor-default",children:ee(x.email,y)})}),e.jsx(ge,{children:x.email})]})}):null}),e.jsx(F,{className:"align-top",children:e.jsx(Ws,{role:x.role,t:n})}),e.jsx(F,{className:"align-top text-center tabular-nums",children:x.locationIds.length}),e.jsx(F,{children:e.jsxs("div",{className:"flex gap-1",children:[I?e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(fe,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8",disabled:!0,"data-testid":`edit-user-${x.id}`,children:e.jsx(je,{className:"w-3.5 h-3.5"})})})}),e.jsx(ge,{children:G})]})}):e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>M(x),"data-testid":`edit-user-${x.id}`,children:e.jsx(je,{className:"w-3.5 h-3.5"})}),z?e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(fe,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",disabled:!0,"data-testid":`delete-user-${x.id}`,children:e.jsx(pe,{className:"w-3.5 h-3.5"})})})}),e.jsx(ge,{children:Q})]})}):e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{s({title:"Delete user?",description:`Delete user ${x.username}?`,confirmLabel:"Yes, Delete",destructive:!0}).then(ae=>{ae&&O.mutate(x.id)})},"data-testid":`delete-user-${x.id}`,children:e.jsx(pe,{className:"w-3.5 h-3.5"})})]})})]},x.id)})})]}),e.jsx(Gs,{open:m,onOpenChange:x=>{x||(b(null),h(!1))},mode:w?"add":"edit",initialUser:j,userRole:i?.role,locations:N,enterpriseScope:{kind:"fixed",enterpriseId:t.id,enterpriseName:t.name},onSaved:()=>{$.invalidateQueries({queryKey:["/api/admin/enterprises",t.id,"users"]}),$.invalidateQueries({queryKey:["/api/admin/users"]})}})]})}function kn({enterprise:t,locations:s,selectedLocationId:n,hasConnection:i}){const{t:a}=B(),{toast:l}=be(),{user:r}
1=Je(),o=ue(r?.role),[g,N]=d.useState(null),[j,b]=d.useState(null),w=d.useMemo(()=>Ss(s,t.id),[s,t.id]),[h,y]=d.useState(""),[p,u]=d.useState(null),v=m=>u(x=>Ct(x,m)),c=d.useMemo(()=>{const m=h.trim().toLowerCase(),x=m?w.filter(C=>[C.name,C.region,C.category,C.serial,C.locNum].some(E=>(E||"").toLowerCase().includes(m))):w;return Et(x,p,(C,E)=>{switch(E){case"name":return C.name||C.locNum||"";case"region":return C.region||"";case"category":return C.category||"";case"serial":return C.serial||"";case"id":return C.locNum||"";default:return""}})},[w,h,p]),k=d.useRef(new Map),P=d.useRef(null);d.useEffect(()=>{if(!n||P.current===n||!w.some(C=>C.id===n))return;const x=k.current.get(n);x&&(P.current=n,x.scrollIntoView({block:"nearest"}))},[n,w,c]);const M=U({mutationFn:async()=>(await R("POST",`/api/admin/enterprises/${t.id}/refresh-locations`)).json(),onSuccess:m=>{$.invalidateQueries({queryKey:["/api/locations"]}),$.invalidateQueries({queryKey:["/api/admin/locations",{enterpriseId:t.id}]}),$.invalidateQueries({queryKey:["/api/admin/enterprises"]});const x=(m.sources||[]).filter(I=>!I.success);m.success&&l({description:a("enterpriseSetup.locations.refresh.done").replace("{count}",String(m.refreshed))});const C=m?.conflicts??[];if(C.length>0){const I=C.map(Q=>Q.locNum).filter(Boolean),z=I.slice(0,5).join(", "),G=I.length>5?`${z}â¦`:z;l({variant:"destructive",description:`${C.length} location(s) were not refreshed because they already belong to another enterprise: ${G}. Check the connection assignment.`})}const E=m?.invalidLocations??[];if(E.length>0){const I=E.map(Q=>Q.name||Q.locNum).filter(Boolean),z=I.slice(0,5).join(", "),G=I.length>5?`${z}â¦`:z;l({variant:"destructive",description:`${E.length}
1 location(s) have no serial number and were flagged invalid: ${G}. They can't be used until the serial is restored in Caterease.`})}m.success||l({variant:"destructive",description:x[0]?.message?`${a("enterpriseSetup.locations.refresh.failed")} ${x[0].message}`:a("enterpriseSetup.locations.refresh.failed")})},onError:m=>{l({variant:"destructive",description:m?.message||a("enterpriseSetup.locations.refresh.failed")})}}),O=U({mutationFn:async m=>(await R("DELETE",`/api/admin/enterprises/${t.id}/locations/${encodeURIComponent(m)}`)).json(),onSuccess:()=>{$.invalidateQueries({queryKey:["/api/locations"]}),$.invalidateQueries({queryKey:["/api/admin/locations",{enterpriseId:t.id}]}),$.invalidateQueries({queryKey:["/api/admin/enterprises"]}),l({description:a("enterpriseSetup.locations.delete.done")}),b(null)},onError:m=>{l({variant:"destructive",description:m?.message||a("enterpriseSetup.locations.delete.failed")})}});return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(T,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",onClick:()=>M.mutate(),disabled:M.isPending||!i,"data-testid":"refresh-locations",children:[e.jsx(ws,{className:`w-3.5 h-3.5 ${M.isPending?"animate-spin":""}`}),M.isPending?a("enterpriseSetup.locations.refresh.pending"):a("enterpriseSetup.locations.refresh.action")]})}),w.length>0&&e.jsx(q,{value:h,onChange:m=>y(m.target.value),placeholder:a("enterpriseSetup.locations.searchPlaceholder"),className:"h-9","data-testid":"locations-search","aria-label":a("enterpriseSetup.locations.searchPlaceholder")}),w.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground","data-testid":"locations-empty",children:a("enterpriseSetup.locations.empty")}):c.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground","data-testid":"locations-search-empty",children:a("enterpriseSetup.locations.searchEmpty")}):e.jsxs(Xe,{containerClassName:"max-h-[calc(100vh-22rem)] rounded-md border","data-testid":"locations-scroll",children:[e.jsx(et,{children:e.jsxs(oe,{children:[e.jsx(Y,{label:a("enterpriseSetup.locations.col.name"),sortKey:"name",sort:p,onSort:v}),e.jsx(Y,{label:a("enterpriseSetup.locations.col.region"),sortKey:"region",sort:p,onSort:v}),e.jsx(Y,{label:a("enterpriseSetup.locations.col.category"),sortKey:"category",sort:p,onSort:v}),e.jsx(Y,{label:a("enterpriseSetup.locations.col.serial"),sortKey:"serial",sort:p,onSort:v}),e.jsx(Y,{label:a("enterpriseSetup.locations.col.id"),sortKey:"id",sort:p,onSort:v}),e.jsx(te,{className:"w-24 text-right sticky top-0 z-20 bg-background border-b",children:a("enterpriseSetup.locations.col.actions")})]})}),e.jsx(tt,{children:c.map(m=>e.jsxs(oe,{"data-testid":`location-${m.id||m.locNum}`,ref:x=>{m.id&&(x?k.current.set(m.id,x):k.current.delete(m.id))},children:[e.jsx(F,{className:"font-medium",children:ee(m.name||m.locNum,h)}),e.jsx(F,{className:"text-muted-foreground",children:m.region?ee(m.region,h):"â"}),e.jsx(F,{className:"text-muted-foreground","data-testid":`location-category-${m.id||m.locNum}`,children:m.category?ee(m.category,h):"â"}),e.jsx(F,{className:"font-mono text-xs text-muted-foreground","data-testid":`location-serial-${m.id||m.locNum}`,children:m.serial?ee(m.serial,h):"â"}),e.jsx(F,{className:"font-mono text-xs text-muted-foreground",children:m.locNum?ee(m.locNum,h):"â"}),e.jsx(F,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[o&&m.id?e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(fe,{asChild:!0,children:e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N({id:m.id,name:m.name||m.locNum||m.id}),"data-testid":`edit-merchant-${m.id}`,children:e.jsx(je,{className:"w-3.5 h-3.5"})})}),e.jsx(ge,{children:a("enterpriseSetup.locations.merchant.editTooltip")})]})}):null,m.id?e.jsx(he,{children:e.jsxs(xe,{...j?{open:!1}:{},children:[e.jsx(fe,{asChild:!0,children:e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>b({id:m.id,name:m.name||m.locNum||m.id}),disabled:O.isPending,"data-testid":`delete-location-${m.id}`,"aria-label":`${a("enterpriseSetup.locations.delete.action")}: ${m.name||m.locNum||m.id}`,children:e.jsx(pe,{className:"w-3.5 h-3.5"})})}),e.jsx(ge,{children:a("enterpriseSetup.locations.delete.action")})]})}):null]})})]},m.id||m.locNum))})]}),o&&g&&e.jsx(Tn,{locationId:g.id,locationName:g.name,open:!!g,onOpenChange:m=>{m||N(null)}}),e.jsx(jt,{open:j!==null,onOpenChange:m=>{!m&&!O.isPending&&b(null)},children:e.jsxs(_e,{"data-testid":"delete-location-confirm",children:[e.jsxs(Ue,{children:[e.jsx(ze,{children:a("enterpriseSetup.locations.delete.confirmTitle")}),e.jsx(Ve,{children:a("enterpriseSetup.locations.delete.confirmBody").replace("{name}",j?.name||"")})]}),e.jsxs(Be,{children:[e.jsx(We,{disabled:O.isPending,"data-testid":"delete-location-cancel",children:a("enterpriseSetup.locations.delete.cancel")}),e.jsx(Ge,{disabled:O.isPending,"data-testid":"delete-location-confirm-yes",onClick:m=>{m.preventDefault(),j?.id&&O.mutate(j.id)},children:O.isPending?a("enterpriseSetup.locations.delete.pending"):a("enterpriseSetup.locations.delete.confirm")})]})]})})]})}function Tn({locationId:t,locationName:s,open:n,onOpenChange:i}){const{t:a}=B(),{toast:l}=be(),{data:r,isLoading:o}=ce({queryKey:[`/api/locations/${t}/merchant-settings`],enabled:n&&!!t}
1),[g,N]=d.useState(Us),[j,b]=d.useState(""),[w,h]=d.useState(!1),[y,p]=d.useState(0),[u,v]=d.useState(!1),[c,k]=d.useState(!0);d.useEffect(()=>{r&&(N(r.provider),b(r.merchantId||""),h(r.applySurcharge??!1),p(r.surchargeRate??0),v(r.tipsEnabled??!1),k(r.active??!0))},[r,t]);const P={worldpay_payrix:a("settings.merchant.providerWorldpay"),stripe:a("settings.merchant.providerStripe")},M=U({mutationFn:async()=>(await R("PUT",`/api/locations/${t}/merchant-settings`,{active:c})).json(),onSuccess:()=>{$.invalidateQueries({queryKey:[`/api/locations/${t}/merchant-settings`]}),l({description:a("enterpriseSetup.locations.merchant.saved")}),i(!1)},onError:O=>{l({variant:"destructive",description:O?.message||a("enterpriseSetup.locations.merchant.failed")})}});return e.jsx(ke,{open:n,onOpenChange:i,children:e.jsxs(Te,{className:"max-w-sm",children:[e.jsxs(Pe,{children:[e.jsx(Re,{children:a("enterpriseSetup.locations.merchant.dialogTitle")}),e.jsx(De,{children:a("enterpriseSetup.locations.merchant.dialogDescription").replace("{name}",s)})]}),o?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:a("enterpriseSetup.locations.merchant.loading")}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a("settings.merchant.ceSourcedNote")}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:a("settings.merchant.provider")}),e.jsx("p",{className:"text-sm","data-testid":"merchant-edit-provider-value",children:P[g]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:a("settings.merchant.merchantId")}),e.jsx("p",{className:"font-mono text-xs break-all","data-testid":"merchant-edit-id-value",children:j||"â"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:a("settings.merchant.surcharge")}),e.jsx("p",{className:"text-sm","data-testid":"merchant-edit-surcharge-value",children:w?`${y.toFixed(2)}%`:"Off"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:a("settings.merchant.tips")}),e.jsx("p",{className:"text-sm","data-testid":"merchant-edit-tips-value",children:u?"On":"Off"})]}),e.jsxs("div",{className:"border-t pt-4 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zs,{checked:c,onCheckedChange:O=>k(O),"data-testid":"merchant-edit-active-toggle"}),e.jsx(A,{className:"text-sm",children:"Active"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a("settings.merchant.activeHelp")})]})]}),e.jsxs(Ae,{children:[e.jsx(T,{variant:"outline",onClick:()=>i(!1),"data-testid":"merchant-edit-cancel",children:a("enterpriseSetup.locations.merchant.cancel")}),e.jsx(T,{onClick:()=>M.mutate(),disabled:o||M.isPending,"data-testid":"merchant-edit-save",children:M.isPending?a("enterpriseSetup.locations.merchant.saving"):a("enterpriseSetup.locations.merchant.save")})]})]})})}function qe({icon:t,children:s,testId:n}){return e.jsxs("div",{className:"flex items-start gap-2 text-xs text-muted-foreground","data-testid":n,children:[e.jsx("span",{className:"mt-0.5 shrink-0 text-muted-foreground",children:t}),e.jsx("span",{className:"break-words",children:s})]})}function Pn({enterprise:t}){const s=[t.address1,t.city,t.state].filter(Boolean).join(", ");return e.jsxs(wt,{align:"start",side:"right",className:"w-72 space-y-2","data-testid":`enterprise-popover-${t.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4 shrink-0 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-semibold truncate",children:t.name})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(qe,{icon:e.jsx(ft,{className:"w-3.5 h-3.5"}),children:s||"â"}),t.phone&&e.jsx(qe,{icon:e.jsx(Ms,{className:"w-3.5 h-3.5"}),children:Is(t.phone)}),t.email&&e.jsx(qe,{icon:e.jsx(Ls,{className:"w-3.5 h-3.5"}),children:t.email})]})]})}function Rn({enterprise:t,isCurrent:s,isActive:n,optionId:i,onSelect:a,canEdit:l,onEdit:r,onDelete:o,editLabel:g,deleteLabel:N,locationsLabel:j,query:b,rowRef:w}){const{t:h}=B();
1return e.jsx("li",{ref:w,id:i,role:"option","aria-selected":n,children:e.jsxs(pn,{openDelay:150,closeDelay:100,children:[e.jsx(mn,{asChild:!0,children:e.jsxs("div",{className:`group flex items-center border-b hover:bg-accent/50 ${s?"bg-accent":n?"bg-primary/[0.06]":""}`,children:[e.jsx("button",{type:"button",onClick:a,className:"flex-1 min-w-0 text-left pl-4 pr-2 py-2 focus:outline-none focus:bg-accent/50","data-testid":`enterprise-row-${t.id}`,"data-current":s?"true":void 0,"aria-current":s?"true":void 0,children:e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(gs,{type:t.primaryConnectionType,className:"w-3.5 h-3.5",showInactive:!0,testId:`enterprise-mode-symbol-${t.id}`}),t.primaryConnectionDegraded&&e.jsx("span",{className:"inline-flex shrink-0",title:h("enterpriseSetup.connections.degradedHint"),"aria-label":h("enterpriseSetup.connections.status.degraded"),role:"img","data-testid":`enterprise-degraded-${t.id}`,children:e.jsx(se,{className:"w-3.5 h-3.5 text-amber-500"})}),e.jsx("span",{className:"block font-medium truncate",children:ee(t.name,b)})]})}),e.jsx("span",{className:"shrink-0 px-2 text-xs text-muted-foreground tabular-nums","data-testid":`enterprise-row-count-${t.id}`,children:j}),l&&e.jsxs("div",{className:"shrink-0 flex items-center gap-1 pr-2 w-[4.25rem] justify-end",children:[e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:y=>{y.stopPropagation(),r()},"data-testid":`enterprise-row-edit-${t.id}`,"aria-label":`${g}: ${t.name}`,title:g,children:e.jsx(je,{className:"w-3.5 h-3.5"})}),s&&e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:y=>{y.stopPropagation(),o()},"data-testid":`enterprise-row-delete-${t.id}`,"aria-label":`${N}: ${t.name}`,title:N,children:e.jsx(pe,{className:"w-3.5 h-3.5"})})]})]})}),e.jsx(Pn,{enterprise:t})]})})}function pt({label:t,value:s,onChange:n,options:i,testId:a,allLabel:l}){return e.jsxs("label",{className:"min-w-0 flex flex-col gap-1",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:t}),e.jsx("select",{value:s,onChange:r=>n(r.target.value),className:"h-8 w-full rounded-md border border-input bg-background px-2 text-xs focus:outline-none focus:ring-2 focus:ring-ring","data-testid":a,"aria-label":t,children:i.map(r=>e.jsx("option",{value:r.value,children:r.value==="all"?l:r.label},r.value))})]})}function Hn(){const{user:t}=Je(),{t:s}=B(),{selectedLocationId:n}=ss(),{selectedEnterpriseId:i}=ns(),{data:a,isLoading:l,error:r}=hn(),[o,g]=d.useState(""),[N,j]=d.useState("all"),[b,w]=d.useState("all"),[h,y]=d.useState(null),{data:p=[]}=ce({queryKey:["/api/admin/locations",{enterpriseId:h}],queryFn:async()=>(await R("GET",`/api/admin/locations?enterpriseId=${encodeURIComponent(h||"")}`)).json(),enabled:!!h}),[u,v]=d.useState("connections"),[c,k]=d.useState(!1),[P,M]=d.useState(null),[O,m]=d.useState(null),[x,C]=d.useState(null),E=d.useMemo(()=>as([],a?.details||[]),[a]),I=d.useMemo(()=>rs(E),[E]),z=I.join("|"),G=d.useMemo(()=>I,[z]),{profilesById:Q,pendingIds:ae}=fn(G),D=d.useMemo(()=>is(E,Q),[E,Q]),{ready:le,pendingCount:J}=d.useMemo(()=>os(D,ae),[D,ae]),re=N!=="all"||b!=="all",L=d.useMemo(()=>cs(le,{query:o,hosting:N,tier:b}),[le,o,N,b]),de=d.useRef(null);d.useEffect(()=>{i&&(J>0||de.current!==i&&D.some(S=>S.id===i)&&(de.current=i,y(i)))},[i,J,D]);const ie=!!i&&de.current!==i&&D.some(S=>S.id===i),Oe=D.map(S=>S.id).join("\0"),me=le.map(S=>S.id).join("\0");d.useEffect(()=>{const S=ls(D,le,h,ie);S!==h&&y(S)},[Oe,me,ie,h]);const K=d.useMemo(()=>Ce(D,h),[D,h]),{data:Ie=[],isLoading:Ne}=Tt(K?.id??null),V=!Ne&&Ie.length>0;d.useEffect(()=>{!V&&(u==="users"||u==="locations")&&v("connections")},[V,u]);const Me=d.useMemo(()=>!!n&&!!h&&p.some(S=>S.id===n&&(S.enterpriseId||"")===h),[p,n,h]),f=d.useRef(new Map),H=d.useRef(null);d.useEffect(()=>{if(!h||J>0||H.current===h)return;const S=f.current.get(h);S&&(H.current=h,S.scrollIntoView({block:"nearest"}))},[h,J,L]);const[_,Se]=d.useState(-1);d.useEffect(()=>{Se(-1)},[L.length]),d.useEffect(()=>{if(_<0)return;const S=L[_];S&&f.current.get(S.id)?.scrollIntoView({block:"nearest"})},[_,L]);const Pt=_>=0&&L[_]?`enterprise-option-${L[_].id}`:void 0;function Rt(S){L.length!==0&&(S.key==="ArrowDown"?(S.preventDefault(),Se(W=>Math.min(W+1,L.length-1))):S.key==="ArrowUp"?(S.preventDefault(),Se(W=>W<=0?0:W-1)):S.key==="Enter"?_>=0&&L[_]&&(S.preventDefault(),y(L[_].id)):S.key==="Escape"&&Se(-1))}const Dt=d.useMemo(()=>Ce(D,P),[D,P]),At=d.useMemo(()=>Ce(D,O),[D,O]),$t=d.useMemo(()=>Ce(D,x),[D,x]),rt=!!t&&ue(t.role);if(!t||!ue(t.role))return e.jsx("div",{className:"flex-1 flex items-center justify-center p-8",children:e.jsx(ds,{className:"max-w-sm",children:e.jsxs(us,{className:"pt-6 text-center",children:[e.jsx(ps,{className:"w-10 h-10 mx-auto mb-3 text-muted-foreground"}),e.jsx("h2",{className:"text-lg font-semibold mb-1",children:"Access denied"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This area is only available to System Admins."})]})})});const Ot=s("enterpriseSetup.list.count").replace("{count}",String(ms(L,h))).replace("{total}",String(L.length));return e.jsxs("div",{className:"h-full min-h-0 overflow-hidden bg-background flex flex-col",children:[e.jsxs("div",{className:"border-b px-6 py-4 flex items-start justify-between shrink-0",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5"})," ",s("enterpriseSetup.title")]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("enterpriseSetup.subtitle")})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(T,{onClick:()=>k(!0),disabled:!rt,"data-testid":"add-enterprise",children:[e.jsx(Ze,{className:"w-4 h-4 mr-1"})," ",s("enterpriseSetup.add")]})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden grid grid-cols-1 md:grid-rows-[minmax(0,1fr)] md:grid-cols-[minmax(280px,360px)_1fr]",children:[e.jsxs("div",{className:"border-r flex flex-col overflow-hidden min-h-0",children:[e.jsxs("div",{className:"p-3 border-b shrink-0",children:[e.jsx(q,{value:o,onChange:S=>g(S.target.value),onKeyDown:Rt,placeholder:s("enterpriseSetup.searchPlaceholder"),className:"h-9","data-testid":"enterprise-search","aria-label":s("enterpriseSetup.searchPlaceholder"),role:"combobox","aria-expanded":L.length>0,"aria-controls":"enterprise-listbox","aria-activedescendant":Pt}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[e.jsx(pt,{label:s("enterpriseSetup.filter.hosting"),value:N,onChange:j,options:hs,testId:"enterprise-hosting-filter",allLabel:s("enterpriseSetup.filter.all")}),e.jsx(pt,{label:s("enterpriseSetup.filter.tier"),value:b,onChange:w,options:xs,testId:"enterprise-tier-filter",allLabel:s("enterpriseSetup.filter.all")})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[e.jsx(T,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{j("all"),w("all")},disabled:!re,"data-testid":"enterprise-filters-clear",children:s("enterpriseSetup.filter.clear")}),e.jsx("p",{className:"text-xs text-muted-foreground tabular-nums","data-testid":"enterprise-count",children:Ot})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto","data-testid":"enterprise-list-scroll",children:[l&&e.jsx("p",{className:"p-4 text-sm text-muted-foreground","data-testid":"enterprise-list-loading",children:s("enterpriseSetup.list.loading")}),r&&!l&&e.jsx("p",{className:"p-4 text-sm text-destructive","data-testid":"enterprise-list-error",children:s("enterpriseSetup.list.error")}),!l&&!r&&D.length===0&&e.jsx("p",{className:"p-4 text-sm text-muted-foreground","data-testid":"enterprise-list-none",children:s("enterpriseSetup.list.none")}),!l&&!r&&D.length>0&&L.length===0&&J===0&&e.jsx("p",{className:"p-4 text-sm text-muted-foreground","data-testid":"enterprise-list-empty",children:s(re?"enterpriseSetup.list.emptyFilters":"enterpriseSetup.list.empty")}),e.jsx("ul",{id:"enterprise-listbox",role:"listbox",children:L.map((S,W)=>e.jsx(Rn,{enterprise:S,isCurrent:S.id===h,isActive:W===_,optionId:`enterprise-option-${S.id}`,onSelect:()=>y(S.id),canEdit:rt,onEdit:()=>M(S.id),onDelete:()=>C(S.id),editLabel:s("enterpriseSetup.edit"),deleteLabel:s("enterpriseSetup.delete.action"),locationsLabel:s("enterpriseSetup.list.locations").replace("{count}",String(S.locationCount)),query:o,rowRef:we=>{we?f.current.set(S.id,we):f.current.delete(S.id)}},S.id))}),!l&&!r&&J>0&&e.jsxs("div",{className:"p-2 space-y-1","data-testid":"enterprise-list-hydrating",children:[e.jsx("p",{className:"sr-only",role:"status",children:s("enterpriseSetup.list.resolvingNames")}),e.jsx("div",{className:"space-y-1","aria-hidden":"true",children:Array.from({length:Math.min(J,6)}).map((S,W)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 px-2 py-2 border-b",children:[e.jsx(ct,{className:"h-4 w-40"}),e.jsx(ct,{className:"h-3 w-12 shrink-0"})]},W))})]})]})]}),e.jsx("div",{className:"overflow-auto p-6",children:K?e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2","data-testid":"detail-name",children:[e.jsx(Ee,{className:"w-4 h-4"})," ",K.name,e.jsx(ve,{variant:K.active!==!1?"default":"secondary","data-testid":`status-badge-${K.id}`,children:K.active!==!1?"Active":"Inactive"}),e.jsx("span",{className:"text-xs font-normal text-muted-foreground tabular-nums","data-testid":"detail-location-count",children:s("enterpriseSetup.list.locations").replace("{count}",String(K.locationCount))})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1.5",children:[e.jsx(ft,{className:"w-3.5 h-3.5"}
1),[K.address1,K.city,K.state].filter(Boolean).join(", ")||"â"]})]}),e.jsxs(T,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",onClick:()=>m(K.id),disabled:!V,"data-testid":`manage-status-${K.id}`,children:[e.jsx(Qe,{className:"w-3.5 h-3.5"})," Status"]})]}),e.jsxs(Vs,{value:u,onValueChange:v,className:"w-full",children:[e.jsxs(Bs,{children:[e.jsx(Le,{value:"connections","data-testid":"tab-connections",children:s("enterpriseSetup.tabs.connections")}),e.jsx(Le,{value:"users","data-testid":"tab-users",disabled:!V,children:s("enterpriseSetup.tabs.users")}),e.jsx(Le,{value:"locations","data-testid":"tab-locations",disabled:!V,children:s("enterpriseSetup.tabs.locations")})]}),e.jsx(Ke,{value:"connections",className:"mt-4",children:e.jsx(Cn,{enterprise:K,enterprises:D})}),e.jsx(Ke,{value:"users",className:"mt-4",children:e.jsx(En,{enterprise:K})}),e.jsx(Ke,{value:"locations",className:"mt-4",children:e.jsx(kn,{enterprise:K,locations:p,selectedLocationId:Me?n:null,hasConnection:V})})]})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"detail-placeholder",children:s("enterpriseSetup.detail.placeholder")})})})]}),e.jsx(gn,{mode:P?"edit":"add",enterprise:P?Dt:null,open:c||P!==null,onOpenChange:S=>{S||(k(!1),M(null))},onSaved:S=>{S&&!P&&y(S)}}),e.jsx(vn,{enterprise:At,onClose:()=>m(null)}),e.jsx(jn,{enterprise:$t,open:x!==null,onOpenChange:S=>{S||C(null)},onDeleted:S=>{C(null),y(W=>W===S?fs(L.map(we=>we.id),S):W)}})]})}export{Hn as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.