1import{c as ge,r as l,e as rs,a as R,b as w,q as E,j as e,L as f,B as n,Z as ls,a0 as ys,a1 as M,S as js,W as ds,a2 as Ae,X as os}from"./index-DYXUW0vG.js";import{B as D}from"./badge-DmXAJSlg.js";import{I as y}from"./input-B1NWoQzQ.js";import{L as N}from"./label-BRMszslK.js";import{S as Se,a as ke,b as ze,c as Fe,d as K,C as fs}from"./select-CGAl9Ea6.js";import{P as Pe}from"./plus-CoPGylEx.js";import{S as ts}from"./search-D6isxPVv.js";import{U as bs}from"./users-CKDn2cdf.js";import{C as Ns}from"./clock-Dxr7jxlL.js";import{T as Ee}from"./trash-2-DS9XqFS8.js";import{E as Ie}from"./external-link-CaGi32qg.js";import{C as vs}from"./chevron-left-UWbwfJGR.js";import{C as ws}from"./chevron-right-Do_6DmHj.js";import"./index-6kWqEXXl.js";/** 2 * @license lucide-react v0.453.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const as=ge("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** 7 * @license lucide-react v0.453.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const is=ge("FlaskConical",[["path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2",key:"pzvekw"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** 12 * @license lucide-react v0.453.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Cs=ge("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** 17 * @license lucide-react v0.453.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const ns=ge("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);async function p(t,r,u){const o=await fetch(r,{method:t,credentials:"include",headers:u?{"Content-Type":"application/json"}:void 0,body:u?JSON.stringify(u):void 0}),c=await o.json().catch(()=>({}));if(!o.ok)throw new Error(c.error||"Admin request failed");return c}function Te(){return{email:"",name:"",role:"fitter"}}function ee(t){if(!t)return"-";const r=new Date(t);return Number.isNaN(r.getTime())?"-":r.toLocaleString()}function Ss({org:t}){var h;const[r,u]=l.useState(null),{toast:o}=rs(),c=R({queryKey:["admin-marshal",t.id],queryFn:()=>p("GET",`/api/admin/fitter-admin/organizations/${t.id}/marshal`)}),d=w({mutationFn:C=>p("POST",`/api/admin/fitter-admin/organizations/${t.id}/marshal/pairing${C?"/rotate":""}`,C?{confirm:!0}:{}),onSuccess:u}),m=(h=c.data)==null?void 0:h.status,a=async()=>{r&&(await navigator.clipboard.writeText(r.pairingUrl),o({title:"Pairing handoff copied",description:"It can be used once before it expires."}))};return e.jsxs("div",{className:"mt-3 rounded-md border border-slate-200 bg-slate-50 p-3 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:"Marshal support"}),c.isLoading?e.jsx("p",{className:"text-gray-500",children:"Checking connectionâ¦"}):c.error?e.jsx("p",{className:"text-red-600",children:c.error.message}):e.jsxs("p",{className:"text-gray-600",children:[m!=null&&m.hasKey?"Connected":"Not connected",m!=null&&m.keyLastRotatedAt?` · Last rotated ${ee(m.keyLastRotatedAt)}`:""]})]}),m&&e.jsxs(n,{type:"button",size:"sm",variant:m.hasKey?"destructive":"outline",disabled:d.isPending,onClick:()=>{m.hasKey&&!window.confirm("Create a replacement handoff? The current key remains active until this one-time handoff is consumed, then it becomes unusable.")||(u(null),d.mutate(m.hasKey))},children:[d.isPending&&e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),m.hasKey?"Create replacement handoff":"Create setup handoff"]}
21)]}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Existing Marshal keys cannot be viewed or recovered. Handoffs are short-lived and single-use."}),d.error&&e.jsx("p",{className:"mt-2 text-sm text-red-600",children:d.error.message}),r&&e.jsxs("div",{className:"mt-3 rounded-md border border-amber-200 bg-amber-50 p-3",children:[e.jsxs("p",{className:"font-medium text-amber-900",children:[r.intent==="rotate"?"Replacement":"Setup"," handoff ready"]}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-amber-900",children:r.pairingUrl}),e.jsxs("p",{className:"mt-1 text-xs text-amber-800",children:["Expires ",ee(r.expiresAt),". It will not be shown again."]}),e.jsxs(n,{type:"button",size:"sm",variant:"outline",className:"mt-2",onClick:a,children:[e.jsx(Ae,{className:"mr-2 h-3.5 w-3.5"})," Copy handoff"]})]})]})}function de(t,r=""){return t==null?"-":`${Math.round(t)}${r}`}function Y({testId:t,heading:r,description:u,children:o}){return e.jsxs("details",{"data-testid":t,className:"group rounded-lg border border-gray-200 bg-white p-5",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-start justify-between gap-3 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden",children:[e.jsxs("div",{className:"min-w-0",children:[r,u]}),e.jsx(fs,{"aria-hidden":"true",className:"mt-1 h-5 w-5 shrink-0 text-gray-400 transition-transform group-open:rotate-180"})]}),e.jsx("div",{className:"mt-5",children:o})]})}function ks({selection:t,data:r,isLoading:u,error:o,onClose:c,onDelete:d}){const m=(r==null?void 0:r.fittings)??[];return e.jsxs("div",{className:"mt-5 rounded-lg border border-gray-200 bg-gray-50 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-500",children:[t.type==="organization"?"Organization fitting history":"Fitter fitting history",r?` | ${m.length} fitting${m.length===1?"":"s"}`:""]})]}),e.jsxs(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:c,children:[e.jsx(os,{className:"mr-2 h-4 w-4"}),"Close"]})]}),u?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(f,{className:"h-5 w-5 animate-spin text-gray-400"})}):o?e.jsx("p",{className:"mt-4 text-sm text-red-600",children:o.message}):m.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-gray-400",children:"No fittings found for this scope."}):e.jsx("div",{className:"mt-4 overflow-x-auto rounded-md border border-gray-200 bg-white",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50 text-left text-xs text-gray-500",children:[e.jsx("th",{className:"px-3 py-2 font-medium",children:"Date"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Fitting"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Customer"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Fitter"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Club"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Metrics"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Notes"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Delete"})]})}),e.jsx("tbody",{children:m.map(a=>{var z,S,P,$;const h=((z=a.customer)==null?void 0:z.name)||a.email||"Unknown",C=((S=a.customer)==null?void 0:S.email)||a.email,F=[a.currentBrand,a.currentModel].filter(Boolean).join(" ");return e.jsxs("tr",{className:"border-b border-gray-100 align-top last:border-0",children:[e.jsx("td",{className:"whitespace-nowrap px-3 py-3 text-xs text-gray-500",children:ee(a.createdAt)}),e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-mono text-xs text-gray-800",children:a.publicId||a.id}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2",children:[e.jsxs("a",{href:a.resultsPath,target:"_blank",rel:"noreferrer",className:"inline-flex items-center text-xs text-gray-600 hover:text-gray-900",children:["Results ",e.jsx(Ie,{className:"ml-1 h-3 w-3"})]}),e.jsxs("a",{href:a.fitterSessionPath,target:"_blank",rel:"noreferrer",className:"inline-flex items-center text-xs text-gray-600 hover:text-gray-900",children:["Fitter ",e.jsx(Ie,{className:"ml-1 h-3 w-3"})]})]})]}),e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-medium text-gray-900",children:h}),C&&e.jsx("div",{className:"text-xs text-gray-500",children:C})]}),e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"text-gray-800",children:((P=a.fitter)==null?void 0:P.name)||"-"}),(($=a.fitter)==null?void 0:$.email)&&e.jsx("div",{className:"text-xs text-gray-500",children:a.fitter.email})]}),e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"text-gray-800",children:a.clubType||a.fittingType||"-"}),e.jsx("div",{className:"text-xs text-gray-500",children:a.status||"No status"}),F&&e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:F})]}),e.jsxs("td",{className:"whitespace-nowrap px-3 py-3 text-xs text-gray-600",children:[e.jsxs("div",{children:["SS ",de(a.swingSpeed)]}),e.jsxs("div",{children:["BS ",de(a.ballSpeed)]}),e.jsxs("div",{children:["Carry ",de(a.carryDistance)]}),e.jsxs("div",{children:["Total ",de(a.totalDistance)]}),e.jsxs("div",{children:["Spin ",de(a.spinRate)]})]}),e.jsx("td",{className:"max-w-xs px-3 py-3 text-xs text-gray-500",children:e.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap",children:a.fitterNotes||"-"})}),e.jsx("td",{className:"px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(n,{variant:"outline",size:"sm",className:"h-7 rounded-md text-xs text-red-600",onClick:()=>d({entityType:"fitting",entityId:a.id,label:`Fitting ${a.publicId||a.id}`,organizationName:t.organizationName}),children:"Fitting"}),a.customer&&e.jsx(n,{variant:"outline",size:"sm",className:"h-7 rounded-md text-xs text-red-600",onClick:()=>d({entityType:"customer",entityId:a.customer.id,label:a.customer.name,organizationName:t.organizationName}),children:"Customer"})]})})]},a.id)})})]})})]})}function zs({orgId:t,onClose:r,onOrgRefresh:u}){var L,T,O;const o=R({queryKey:[`/api/admin/fitter-admin/organizations/${t}/billing`],queryFn:()=>p("GET",`/api/admin/fitter-admin/organizations/${t}/billing`)}),c=R({queryKey:[`/api/admin/fitter-admin/organizations/${t}/invoices`],queryFn:()=>p("GET",`/api/admin/fitter-admin/organizations/${t}/invoices`)}),d=R({queryKey:[`/api/admin/fitter-admin/organizations/${t}/refunds`],queryFn:()=>p("GET",`/api/admin/fitter-admin/organizations/${t}/refunds`)}),[m,a]=l.useState(""),[h,C]=l.useState("full"),[F,z]=l.useState(""),[S,P]=l.useState(""),[$,q]=l.useState(()=>crypto.randomUUID());l.useEffect(()=>{q(crypto.randomUUID())},[m,h,F,S]);const b=w({mutationFn:()=>{const x=h==="custom"?Math.round(Number(F)*100):void 0;return p("POST",`/api/admin/fitter-admin/organizations/${t}/refunds`,{invoiceId:m,mode:h,amountCents:x,reason:S.trim(),idempotencyKey:$})},onSuccess:async()=>{z(""),P(""),q(crypto.randomUUID()),await Promise.all([c.refetch(),d.refetch()])}}),k=w({mutationFn:x=>p("POST",`/api/admin/fitter-admin/organizations/${t}/refunds/${x}/reconcile`),onSuccess:async()=>{await Promise.all([c.refetch(),d.refetch()])}}),v=async()=>
21{await Promise.all([o.refetch(),c.refetch(),d.refetch()]),u()},j=o.data;return e.jsxs("div",{className:"mt-4 rounded-lg border border-blue-100 bg-blue-50 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900",children:"Live Billing"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(n,{variant:"outline",size:"sm",className:"rounded-md h-7 px-2 text-xs",onClick:v,disabled:o.isFetching,children:[e.jsx(ls,{className:`mr-1 h-3 w-3 ${o.isFetching?"animate-spin":""}`}),"Refresh Billing"]}),e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md h-7 w-7 p-0",onClick:r,children:e.jsx(os,{className:"h-3 w-3"})})]})]}),o.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-400 py-2",children:[e.jsx(f,{className:"h-4 w-4 animate-spin"})," Loading billingâ¦"]}):o.error?e.jsx("p",{className:"text-sm text-red-600",children:o.error.message}):j!=null&&j.hasSubscription?e.jsxs("div",{className:"rounded-md border border-gray-200 bg-white p-3 text-sm space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-gray-700",children:"Status:"}),e.jsx("span",{className:"capitalize text-gray-800",children:j.stripeStatus}),j.cancelAtPeriodEnd&&e.jsx(D,{className:"text-xs bg-orange-100 text-orange-700 border-orange-200",children:"Cancels at period end"})]}),j.currentPeriodEnd&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-700",children:j.cancelAtPeriodEnd?"Ends:":"Renews:"})," ",e.jsx("span",{className:"text-gray-800",children:new Date(j.currentPeriodEnd).toLocaleDateString()})]}),j.amountCents!=null&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-700",children:"Amount:"})," ",e.jsxs("span",{className:"text-gray-800",children:["$",(j.amountCents/100).toFixed(2),"/",j.interval??"mo"]})]})]}):e.jsx("p",{className:"text-sm text-gray-500",children:(j==null?void 0:j.stripeError)??"No Stripe subscription on file."}),e.jsxs("div",{className:"mt-4 border-t border-blue-100 pt-4",children:[e.jsx("h5",{className:"text-sm font-semibold text-gray-900",children:"Refundable subscription invoices"}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Refunding does not cancel or modify the subscription."}),c.isLoading?e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"})," Loading invoicesâ¦"]}):c.error?e.jsx("p",{className:"mt-3 text-xs text-red-600",children:c.error.message}):(((L=c.data)==null?void 0:L.invoices)??[]).length===0?e.jsx("p",{className:"mt-3 text-xs text-gray-500",children:"No refundable B2B subscription invoices found."}):e.jsx("div",{className:"mt-3 space-y-2",children:(((T=c.data)==null?void 0:T.invoices)??[]).map(x=>e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-md border border-gray-200 bg-white p-3",children:[e.jsx("input",{type:"radio",name:`refund-invoice-${t}`,checked:m===x.id,onChange:()=>a(x.id),className:"mt-1"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block text-sm font-medium text-gray-900",children:[(x.amountPaidCents/100).toLocaleString(void 0,{style:"currency",currency:x.currency.toUpperCase()})," · ",new Date(x.createdAt).toLocaleDateString()]}),e.jsx("span",{className:"block font-mono text-[11px] text-gray-400",children:x.id}),e.jsxs("span",{className:"block text-xs text-gray-600",children:["Remaining refundable: ",(x.remainingRefundableCents/100).toLocaleString(void 0,{style:"currency",currency:x.currency.toUpperCase()})]})]}),x.hostedInvoiceUrl&&e.jsx("a",{href:x.hostedInvoiceUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-blue-600",children:"Invoice"})]},x.id))}),m&&e.jsxs("div",{className:"mt-3 rounded-md border border-gray-200 bg-white p-3",children:[e.jsxs("div",{className:"flex gap-4 text-xs",children:[e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",checked:h==="full",onCh
21ange:()=>C("full")}),"Full remaining invoice"]}),e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",checked:h==="custom",onChange:()=>C("custom")}),"Custom outage credit"]})]}),h==="custom"&&e.jsxs("div",{className:"mt-3",children:[e.jsx(N,{className:"text-xs",children:"Amount ($)"}),e.jsx(y,{type:"number",min:"0.01",step:"0.01",value:F,onChange:x=>z(x.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(N,{className:"text-xs",children:"Operational reason (required)"}),e.jsx(y,{value:S,onChange:x=>P(x.target.value),placeholder:"e.g. Service outage credit approved byâ¦",className:"mt-1"})]}),b.error&&e.jsx("p",{className:"mt-2 text-xs text-red-600",children:b.error.message}),e.jsxs(n,{size:"sm",className:"mt-3 rounded-md",disabled:b.isPending||S.trim().length<5||h==="custom"&&(!F||Number(F)<=0),onClick:()=>b.mutate(),children:[b.isPending&&e.jsx(f,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Issue refund"]})]}),(((O=d.data)==null?void 0:O.refunds)??[]).length>0&&e.jsxs("div",{className:"mt-4 border-t border-blue-100 pt-3",children:[e.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-gray-500",children:"Refund operation history"}),e.jsx("div",{className:"mt-2 space-y-2",children:d.data.refunds.map(x=>e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-gray-200 bg-white p-3 text-xs",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-gray-900",children:[(x.amountCents/100).toLocaleString(void 0,{style:"currency",currency:x.currency.toUpperCase()})," · ",x.status]}),e.jsx("p",{className:"text-gray-600",children:x.reason}),e.jsx("p",{className:"font-mono text-[11px] text-gray-400",children:x.invoiceId}),x.errorMessage&&e.jsx("p",{className:"mt-1 text-amber-700",children:x.errorMessage})]}),x.status==="pending"&&e.jsx(n,{variant:"outline",size:"sm",className:"h-7 rounded-md text-xs",disabled:k.isPending,onClick:()=>k.mutate(x.id),children:"Reconcile"})]},x.id))}),k.error&&e.jsx("p",{className:"mt-2 text-xs text-red-600",children:k.error.message})]})]})]})}function Fs({org:t,onClose:r,onRefresh:u}){const[o,c]=l.useState("14"),[d,m]=l.useState(""),a=w({mutationFn:()=>p("POST",`/api/admin/fitter-admin/organizations/${t.id}/trial`,{days:Number(o),reason:d.trim()}),onSuccess:u}),h=w({mutationFn:()=>p("DELETE",`/api/admin/fitter-admin/organizations/${t.id}/trial`,{reason:d.trim()}),onSuccess:u}),C=a.error||h.error,F=!!(t.stripeSubscriptionId||t.subscriptionStatus==="active");return e.jsxs("div",{className:"mt-4 rounded-lg border border-amber-200 bg-amber-50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900",children:"Exception trial"}),t.trialGrant?e.jsxs("p",{className:"mt-1 text-xs text-gray-600",children:[t.trialGrant.status==="active"?"Granted":"Revoked"," · ",ee(t.trialGrant.startsAt)," to ",ee(t.trialGrant.endsAt)," · ",t.trialGrant.reason]}):e.jsx("p",{className:"mt-1 text-xs text-gray-600",children:"No explicit trial has been granted."})]}),e.jsx(n,{variant:"outline",size:"sm",className:"h-7 rounded-md",onClick:r,children:"Close"})]}),F?e.jsx("p",{className:"mt-3 text-xs text-gray-600",children:"Paid organizations cannot receive an exception trial."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-[120px_1fr]",children:[e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Days"}),e.jsx(y,{type:"number",min:"1",max:"90",value:o,onChange:z=>c(z.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Operational reason"}),e.jsx(y,{value:d,onChange:z=>m(z.target.value),className:"mt-1"})]})]}),C&&e.jsx("p",{className:"mt-2 text-xs text-red-600",children:C.message}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsxs(n,{size:"sm",className:"rounded-md",disabled:d.trim().length<5||!o||a.isPending,onClick:()=>a.mutate(),children:[a.isPending&&e.jsx(f,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),t.trialGrant?"Re-extend trial":"Grant trial"]}),t.accountState==="trial"&&e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md text-red-600",disabled:d.trim().length<5||h.isPending,onClick:()=>h.mutate(),children:"Revoke trial"})]})]})]})}function Ws(){var Ze,Xe,Ye,es;const[t,r]=l.useState(""),[u,o]=l.useState(""),[c,d]=l.useState(!1),[m,a]=l.useState(""),[h,C]=l.useState(!1),[F,z]=l.useState(!1),[S,P]=l.useState({name:"",email:"",ph
21one:""}),[$,q]=l.useState(null),[b,k]=l.useState(Te()),[v,j]=l.useState(null),[L,T]=l.useState(""),[O,x]=l.useState(""),[V,ye]=l.useState("all"),[B,I]=l.useState(""),[G,De]=l.useState(""),[se,U]=l.useState(0),[oe,Re]=l.useState(""),{toast:je}=rs(),[Le,fe]=l.useState(null),[Oe,$e]=l.useState(null),[W,ce]=l.useState(null),[te,me]=l.useState({monthlyPriceDollars:"",discountExpiresAt:""}),[ae,qe]=l.useState(null),[Me,Ke]=l.useState(!1),[ms,be]=l.useState(!1),Ne=R({queryKey:["/api/admin-session/me"],queryFn:async()=>{const s=await fetch("/api/admin-session/me",{credentials:"include"});if(s.status===401)return null;if(!s.ok)throw new Error("Failed to check admin auth");return s.json()},retry:!1}),J=!!((Ze=Ne.data)!=null&&Ze.authenticated),H=R({queryKey:["/api/admin/fitter-admin/organizations"],queryFn:()=>p("GET","/api/admin/fitter-admin/organizations"),enabled:J}),[xe,xs]=l.useState("all"),[Be,us]=l.useState(""),[Ge,Ue]=l.useState(null),ve=v?v.type==="organization"?`/api/admin/fitter-admin/organizations/${v.orgId}/fittings`:`/api/admin/fitter-admin/organizations/${v.orgId}/members/${v.memberId}/fittings`:"",ue=R({queryKey:["admin-fitting-history",ve],queryFn:()=>p("GET",ve),enabled:J&&!!v&&!!ve}),we=50,Q=new URLSearchParams;L&&Q.set("search",L),O&&Q.set("orgName",O),V!=="all"&&Q.set("clubType",V),B&&Q.set("dateFrom",B),G&&Q.set("dateTo",G),Q.set("limit",String(we)),Q.set("offset",String(se*we));const he=R({queryKey:["/api/admin/analysts"],queryFn:()=>p("GET","/api/admin/analysts"),enabled:J}),Z=R({queryKey:["/api/admin/export/golfer-emails/stats"],queryFn:()=>p("GET","/api/admin/export/golfer-emails/stats"),enabled:J}),X=w({mutationFn:()=>p("POST","/api/admin/analysts",{email:oe.trim().toLowerCase()}),onSuccess:()=>{Re(""),E.invalidateQueries({queryKey:["/api/admin/analysts"]})}}),Qe=w({mutationFn:s=>p("DELETE",`/api/admin/analysts/${s}`),onSuccess:()=>{E.invalidateQueries({queryKey:["/api/admin/analysts"]})}}),ie=R({queryKey:["/api/admin/sessions",L,O,V,B,G,se],queryFn:()=>p("GET",`/api/admin/sessions?${Q.toString()}`),enabled:J}),ne=w({mutationFn:()=>p("POST","/api/admin/fitter-admin/organizations",{name:S.name.trim(),email:S.email.trim()||void 0,phone:S.phone.trim()||void 0}),onSuccess:()=>{P({name:"",email:"",phone:""}),z(!1),E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]})}}),re=w({mutationFn:s=>p("POST",`/api/admin/fitter-admin/organizations/${s}/members`,{email:b.email.trim(),name:b.name.trim(),role:b.role,isActive:1}),onSuccess:()=>{k(Te()),q(null),E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]})}}),He=w({mutationFn:({orgId:s,memberId:i,body:g})=>p("PATCH",`/api/admin/fitter-admin/organizations/${s}/members/${i}`,g),onSuccess:()=>{E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]})}}),le=w({mutationFn:({orgId:s,monthlyPriceCents:i,discountExpiresAt:g})=>p("POST",`/api/admin/fitter-admin/organizations/${s}/subscription`,{monthlyPriceCents:i||void 0,discountExpiresAt:g||void 0}),onSuccess:()=>{fe(null),me({monthlyPriceDollars:"",discountExpiresAt:""}),E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]})}}),_e=w({mutationFn:s=>p("DELETE",`/api/admin/fitter-admin/organizations/${s}/subscription`),onSuccess:()=>{E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]})}}),Ve=w({mutationFn:s=>p("PATCH",`/api/admin/fitter-admin/organizations/${s}/subscription`,{clearDiscount:!0}),onSuccess:()=>{E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]})}}),We=w({mutationFn:({orgId:s,memberId:i})=>p("POST",`/api/admin/fitter-admin/organizations/${s}/members/${i}/send-welcome`),onSuccess:s=>{je({title:"Welcome email sent",description:`Sent to ${s.email}`})},onError:()=>{je({title:"Failed to send",description:"Check Resend configuration.",variant:"destructive"})}});async function hs(s){if(s.preventDefault(),!h){C(!0),a("");try{await p("POST","/api/admin-session/magic-code/send",{email:t.trim().toLowerCase()}),d(!0)}catch(i){a(i instanceof Error?i.message:"Failed to send code")}finally{C(!1)}}}async function ps(s){s.preventDefault(),a("");
21try{await p("POST","/api/admin-session/magic-code/verify",{email:t.trim().toLowerCase(),code:u.trim().toUpperCase()}),o(""),await E.invalidateQueries({queryKey:["/api/admin-session/me"]})}catch(i){a(i instanceof Error?i.message:"Invalid code")}}async function gs(){await p("POST","/api/admin-session/logout"),E.clear(),d(!1)}if(Ne.isLoading)return e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsx(f,{className:"h-5 w-5 animate-spin text-gray-400"})});if(!J)return e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center px-6",children:e.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-gray-200 bg-white p-6 shadow-sm",children:[e.jsx("h1",{className:"text-xl font-semibold text-gray-900 text-center",children:"Admin"}),e.jsx("p",{className:"mt-1 text-center text-sm text-gray-500",children:"Sign in with your owner email."}),c?e.jsxs("form",{onSubmit:ps,className:"mt-6 space-y-4",children:[e.jsx("p",{className:"text-sm text-green-700",children:"Code sent. Check your email; delivery may take a moment."}),e.jsxs("div",{children:[e.jsx(N,{htmlFor:"admin-code",children:"Code"}),e.jsx(y,{id:"admin-code",value:u,onChange:s=>o(s.target.value),className:"mt-1 uppercase",autoComplete:"one-time-code",placeholder:"ABC123"})]}),m&&e.jsx("p",{className:"text-sm text-red-600",children:m}),e.jsx(n,{type:"submit",className:"w-full rounded-md",disabled:!u.trim(),children:"Verify"}),e.jsx("button",{type:"button",className:"w-full text-center text-sm text-gray-500 hover:text-gray-900",onClick:()=>{d(!1),o(""),a("")},children:"Use a different email"})]}):e.jsxs("form",{onSubmit:hs,className:"mt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(N,{htmlFor:"admin-email",children:"Email"}),e.jsx(y,{id:"admin-email",type:"email",value:t,onChange:s=>r(s.target.value),className:"mt-1",autoComplete:"email"})]}),m&&e.jsx("p",{className:"text-sm text-red-600",children:m}),e.jsxs(n,{type:"submit",className:"w-full rounded-md",disabled:!t.trim()||h,children:[h&&e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),h?"Sendingâ¦":"Send Code"]})]})]})});const A=H.data??[],_={total:A.length,demo:A.filter(s=>s.accountState==="demo").length,active:A.filter(s=>s.accountState==="active").length,trial:A.filter(s=>s.accountState==="trial").length,past_due:A.filter(s=>s.accountState==="past_due").length,canceled:A.filter(s=>s.accountState==="canceled").length,none:A.filter(s=>s.accountState==="none").length},Je=A.filter(s=>{const i=xe==="all"||s.accountState===xe,g=Be.trim().toLowerCase(),Ce=!g||s.name.toLowerCase().includes(g)||(s.email??"").toLowerCase().includes(g)||(s.members??[]).some(ss=>ss.email.toLowerCase().includes(g)||ss.name.toLowerCase().includes(g));return i&&Ce});return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("header",{className:"border-b border-gray-200 bg-white",children:e.jsxs("div",{className:"mx-auto flex max-w-6xl items-center justify-between px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold text-gray-900",children:"Admin"}),e.jsx("p",{className:"text-sm text-gray-500",children:(Xe=Ne.data)==null?void 0:Xe.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(n,{variant:"outline",className:"rounded-md",onClick:()=>{H.refetch(),he.refetch(),v&&ue.refetch()},children:[e.jsx(ls,{className:"mr-2 h-4 w-4"}),"Refresh"]}),e.jsx("a",{href:"/admin/products","data-testid":"link-admin-products",children:e.jsx(n,{variant:"outline",className:"rounded-md",children:"Product Catalog"})}),e.jsx("a",{href:"/admin/canary","data-testid":"link-admin-canary",children:e.jsxs(n,{variant:"outline",className:"rounded-md",children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),"Model Canary"]})}),e.jsx("a",{href:"/admin/fitting-lab","data-testid":"link-admin-fitting-lab",children:e.jsxs(n,{variant:"outline",className:"rounded-md",children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),"Fitting Lab"]})}),e.jsx("a",{href:"/admin/catalog-agents",children:e.jsx(n,{variant:"outline",children:"Catalog agents"})}),e.jsxs(n,{variant:"outline",className:"rounded-md",onClick:gs,children:[e.jsx(ys,{className:"mr-2 h-4 w-4"}),"Sign Out"]})]})]})}),e.jsxs("main",{className:"mx-auto max-w-6xl space-y-8 px-5 py-8",children:[W&&e.jsx(As,{target:W,onClose:()=>ce(null),onDeleted:()=>{j(null),E.setQueryData(["/api/admin/fitter-admin/organizations"],s=>W.entityType==="organization"?s==null?void 0:s.filter(i=>i.id!==W.entityId):s==null?void 0:s.map(i=>({...i,members:W.entityType==="fitter"?i.members.filter(g=>g.id!==W.entityId):i.members}))),E.invalidateQueries({queryKey:["/api/admin/fitter-admin/organizations"]}),E.invalidateQueries({queryKey:["/api/admin/sessions"]})}}),e.jsx(Ds,{}),e.jsxs(Y,{testId:"admin-section-organizations",heading:e.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"Fitter Organizations"}),description:e.jsx("p",{className:"text-sm text-gray-500",children:"Create shops and confirm fitter access."}),children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(n,{className:"rounded-md",onClick:()=>z(s=>!s),children:[e.jsx(Pe,{className:"mr-2 h-4 w-4"}),"New Organization"]})}),F&&e.jsxs("div",{className:"mt-5 rounded-lg border border-gray-200 bg-gray-50 p-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(N,{htmlFor:"org-name",children:"Name"}),e.jsx(y,{id:"org-name",value:S.name,onChange:s=>P(i=>({...i,name:s.target.value})),className:"mt-1",placeholder:"Shop name"})]}),e.jsxs("div",{children:[e.jsx(N,{htmlFor:"org-email",children:"Email"}),e.jsx(y,{id:"org-email",type:"email",value:S.email,onChange:s=>P(i=>({...i,email:s.target.value})),className:"mt-1",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx(N,{htmlFor:"org-phone",children:"Phone (optional)"}),e.jsx(y,{id:"org-phone",value:S.phone,onChange:s=>P(i=>({...i,phone:s.target.value})),className:"mt-1",placeholder:"(555) 555-5555"})]})]}),ne.error&&e.jsx("p",{className:"mt-3 text-sm text-red-600",children:ne.error.message}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(n,{className:"rounded-md",disabled:!S.name.trim()||ne.isPending,onClick:()=>ne.mutate(),children:[ne.isPending?e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Create"]}),e.jsx(n,{variant:"outline",className:"rounded-md",onClick:()=>z(!1),children:"Cancel"})]})]}),v&&e.jsx(ks,{selection:v,data:ue.data,isLoading:ue.isLoading,error:ue.error,onClose:()=>j(null),onDelete:ce}),!H.isLoading&&A.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-3 sm:grid-cols-7 gap-2",children:[{label:"Total",value:_.total,state:"all",color:"bg-gray-50 border-gray-200"},{label:"Demo",value:_.demo,state:"demo",color:"bg-purple-50 border-purple-200"},{label:"Trialing",value:_.trial,state:"trial",color:"bg-blue-50 border-blue-200"},{label:"Active",value:_.active,state:"active",color:"bg-green-50 border-green-200"},{label:"Past Due",value:_.past_due,state:"past_due",color:"bg-yellow-50 border-yellow-200"},{label:"Canceled",value:_.canceled,state:"canceled",color:"bg-red-50 border-red-200"},{label:"No Sub",value:_.none,state:"none",color:"bg-gray-50 border-gray-200"}].map(({label:s,value:i,state:g,color:Ce})=>e.jsxs("button",{onClick:()=>xs(xe===g?"all":g),className:`rounded-md border px-3 py-2 text-left transition-all ${Ce} ${xe===g?"ring-2 ring-offset-1 ring-gray-400":"hover:opacity-80"}`,children:[e.jsx("p",{className:"text-lg font-semibold text-gray-900",children:i}),e.jsx("p",{className:"text-xs text-gray-500",children:s})]},s))}),!H.isLoading&&A.length>0&&e.jsxs("div",{className:"mt-3 relative",children:[e.jsx(ts,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(y,{value:Be,onChange:s=>us(s.target.value),placeholder:"Search by org name, email, or fitterâ¦",className:"pl-9"})]}),H.isLoading?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(f,{className:"h-5 w-5 animate-spin text-gray-400"})}):A.length===0?e.jsx("p",{className:"py-10 text-center text-sm text-gray-400",children:"No fitter organizations yet."}):Je.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-gray-400",children:"No organizations match the current filter."}):e.jsx("div",{className:"mt-5 space-y-5",children:Je.map(s=>e.jsxs("div",{className:`rounded-lg border p-4 ${s.accountState==="demo"?"border-purple-200 bg-purple-50/30":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(bs,{className:"h-4 w-4 text-gray-400"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:s.name}),e.jsxs(D,{variant:"outline",className:"text-xs",children:["Org #",s.id]}),s.accountState==="demo"&&e.jsx(D,{className:"text-xs bg-purple-100 text-purple-800 border-purple-200",children:"Demo"}),s.accountState==="active"&&e.jsx(D,{className:"text-xs bg-green-100 text-green-800 border-green-200",children:"Active"}),s.accountState==="past_due"&&e.jsx(D,{className:"text-xs bg-yellow-100 text-yellow-800 border-yellow-200",children:"Past Due"}),s.accountState==="canceled"&&e.jsx(D,{className:"text-xs bg-red-100 text-red-800 border-red-200",children:"Canceled"}),s.accountState==="trial"&&e.jsxs(D,{className:"text-xs bg-blue-100 text-blue-800 border-blue-200",children:["Trial · ",s.trialDaysRemaining,"d left"]}),s.accountState==="none"&&e.jsx(D,{variant:"secondary",className:"text-xs",children:"No Sub"})]}),e.jsx("p",{className:"mt-1 text-sm text-gray-500",children:[s.email,s.phone,s.city,s.state].filter(
21Boolean).join(" | ")||"No contact info"}),s.monthlyPriceCents&&e.jsxs("p",{className:"mt-0.5 text-xs text-blue-600",children:["Custom rate: $",(s.monthlyPriceCents/100).toFixed(2),"/mo",s.discountExpiresAt&&e.jsxs("span",{className:"ml-1 text-gray-400",children:["· expires ",new Date(s.discountExpiresAt).toLocaleDateString()]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>j({type:"organization",orgId:s.id,organizationName:s.name,title:s.name}),children:"View Fittings"}),s.stripeSubscriptionId&&e.jsxs(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>Ue(Ge===s.id?null:s.id),children:[e.jsx(as,{className:"mr-1.5 h-3.5 w-3.5"}),"Billing"]}),e.jsxs(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>{fe(Le===s.id?null:s.id),me({monthlyPriceDollars:"",discountExpiresAt:""})},children:[e.jsx(as,{className:"mr-1.5 h-3.5 w-3.5"}),"Subscription"]}),e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>{q($===s.id?null:s.id),k(Te())},children:"Add Fitter"}),e.jsxs(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>$e(Oe===s.id?null:s.id),children:[e.jsx(Ns,{className:"mr-1.5 h-3.5 w-3.5"}),"Trial"]}
21),e.jsxs(n,{variant:"outline",size:"sm",className:"rounded-md text-red-600",onClick:()=>ce({entityType:"organization",entityId:s.id,label:s.name,organizationName:s.name}),children:[e.jsx(Ee,{className:"mr-1.5 h-3.5 w-3.5"}),"Delete"]})]})]}),e.jsx(Ss,{org:s}),Ge===s.id&&e.jsx(zs,{orgId:s.id,onClose:()=>Ue(null),onOrgRefresh:()=>H.refetch()}),Oe===s.id&&e.jsx(Fs,{org:s,onClose:()=>$e(null),onRefresh:()=>H.refetch()}),Le===s.id&&e.jsxs("div",{className:"mt-4 rounded-lg border border-blue-100 bg-blue-50 p-4",children:[e.jsx("h4",{className:"mb-3 text-sm font-semibold text-gray-900",children:"Subscription Management"}),s.stripeSubscriptionId?e.jsxs("div",{className:"mb-3 rounded-md border border-gray-200 bg-white p-3 text-sm",children:[e.jsxs("p",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Subscription ID:"})," ",e.jsx("span",{className:"font-mono text-xs text-gray-500",children:s.stripeSubscriptionId})]}),e.jsxs("p",{className:"mt-1 text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Status:"})," ",s.subscriptionStatus]}),s.monthlyPriceCents&&e.jsxs("p",{className:"mt-1 text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Current rate:"})," $",(s.monthlyPriceCents/100).toFixed(2),"/mo"]}),s.discountExpiresAt&&e.jsxs("p",{className:"mt-1 text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Discount expires:"})," ",new Date(s.discountExpiresAt).toLocaleDateString()]})]}):null,e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Custom Price ($/mo, leave blank for standard)"}),e.jsx(y,{type:"number",min:"0",step:"0.01",placeholder:"e.g. 99",value:te.monthlyPriceDollars,onChange:i=>me(g=>({...g,monthlyPriceDollars:i.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Discount Expires At (optional)"}),e.jsx(y,{type:"date",value:te.discountExpiresAt,onChange:i=>me(g=>({...g,discountExpiresAt:i.target.value})),className:"mt-1"})]})]}),le.error&&e.jsx("p",{className:"mt-2 text-sm text-red-600",children:le.error.message}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(n,{size:"sm",className:"rounded-md",disabled:le.isPending,onClick:()=>{const i=te.monthlyPriceDollars?Math.round(parseFloat(te.monthlyPriceDollars)*100):void 0;le.mutate({orgId:s.id,monthlyPriceCents:i,discountExpiresAt:te.discountExpiresAt||void 0})},children:[le.isPending?e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}
21):null,s.stripeSubscriptionId?"Replace Subscription":"Create Subscription"]}),s.monthlyPriceCents&&e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",disabled:Ve.isPending,onClick:()=>Ve.mutate(s.id),children:"Clear Discount"}),s.stripeSubscriptionId&&e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md text-red-600 hover:text-red-700",disabled:_e.isPending,onClick:()=>{confirm(`Cancel subscription for ${s.name}?`)&&_e.mutate(s.id)},children:"Cancel Subscription"}),e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>fe(null),children:"Close"})]})]}),$===s.id&&e.jsxs("div",{className:"mt-4 rounded-lg border border-gray-200 bg-gray-50 p-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-[1fr_1fr_150px]",children:[e.jsxs("div",{children:[e.jsx(N,{children:"Email"}),e.jsx(y,{type:"email",value:b.email,onChange:i=>k(g=>({...g,email:i.target.value})),className:"mt-1",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Name"}),e.jsx(y,{value:b.name,onChange:i=>k(g=>({...g,name:i.target.value})),className:"mt-1",placeholder:"Fitter name"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Role"}),e.jsxs(Se,{value:b.role,onValueChange:i=>k(g=>({...g,role:i})),children:[e.jsx(ke,{className:"mt-1 rounded-md",children:e.jsx(ze,{})}),e.jsxs(Fe,{children:[e.jsx(K,{value:"owner",children:"Owner"}),e.jsx(K,{value:"fitter",children:"Fitter"}),e.jsx(K,{value:"employee",children:"Employee"})]})]})]})]}),re.error&&e.jsx("p",{className:"mt-3 text-sm text-red-600",children:re.error.message}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(n,{className:"rounded-md",disabled:!b.email.trim()||!b.name.trim()||re.isPending,onClick:()=>re.mutate(s.id),children:[re.isPending?e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Save Fitter"]}),e.jsx(n,{variant:"outline",className:"rounded-md",onClick:()=>q(null),children:"Cancel"})]})]}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 text-left text-xs text-gray-500",children:[e.jsx("th",{className:"px-2 py-2 font-medium",children:"Name"}),e.jsx("th",{className:"px-2 py-2 font-medium",children:"Email"}),e.jsx("th",{className:"px-2 py-2 font-medium",children:"Role"}),e.jsx("th",{className:"px-2 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"px-2 py-2 font-medium"})]})}),e.jsxs("tbody",{children:[s.members.map(i=>e.jsxs("tr",{className:"border-b border-gray-100 last:border-0",children:[e.jsx("td",{className:"px-2 py-3 font-medium text-gray-900",children:i.name}),e.jsx("td",{className:"px-2 py-3 text-gray-600",children:i.email}),e.jsx("td",{className:"px-2 py-3",children:e.jsxs(Se,{value:i.role,onValueChange:g=>He.mutate({orgId:s.id,memberId:i.id,body:{role:g}}),children:[e.jsx(ke,{className:"h-8 w-28 rounded-md text-xs",children:e.jsx(ze,{})}),e.jsxs(Fe,{children:[e.jsx(K,{value:"owner",children:"Owner"}),e.jsx(K,{value:"fitter",children:"Fitter"}),e.jsx(K,{value:"employee",children:"Employee"})]})]})}),e.jsx("td",{className:"px-2 py-3",children:e.jsx(D,{variant:i.isActive?"default":"secondary",className:"text-xs",children:i.isActive?"Active":"Inactive"})}),e.jsx("td",{className:"px-2 py-3 text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>j({type:"member",orgId:s.id,memberId:i.id,organizationName:s.name,title:`${i.name} | ${s.name}`}),children:"Fittings"}),e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",onClick:()=>He.mutate({orgId:s.id,memberId:i.id,body:{isActive:i.isActive?0:1}}),children:i.isActive?"Deactivate":"Activate"}),e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",disabled:We.isPending,onClick:()=>We.mutate({orgId:s.id,memberId:i.id}),title:"Send welcome email",children:e.jsx(ns,{className:"h-3.5 w-3.5"})}),e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md text-red-600",onClick:()=>ce({entityType:"fitter",entityId:i.id,label:i.name,organizationName:s.name}),children:e.jsx(Ee,{className:"h-3.5 w-3.5"})})]})})]},i.id)),s.members.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"px-2 py-8 text-center text-sm text-gray-400",children:"No fitters in this organization."})})]})]})})]},s.id))})]}),e.jsxs(Y,{testId:"admin-section-all-fittings",heading:e.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"All Fittings"}),description:e.jsxs("p",{className:"text-sm text-gray-500 mt-0.5",children:["Every fitting session across all organisations â ",((Ye=ie.data)==null?void 0:Ye.total)??0," total"]}),children:[e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ts,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(y,{value:L,onChange:s=>{T(s.target.value),U(0)},placeholder:"Search by customer email, name, or org...",className:"pl-9"})]}),e.jsx(y,{value:O,onChange:s=>{x(s.target.value),U(0)},placeholder:"Filter by org...",className:"sm:w-[180px]"}),e.jsxs(Se,{value:V,onValueChange:s=>{ye(s),U(0)},children:[e.jsx(ke,{className:"sm:w-[140px]",children:e.jsx(ze,{placeholder:"Club type"})}),e.jsxs(Fe,{children:[e.jsx(K,{value:"all",children:"All clubs"}),e.jsx(K,{value:"driver",children:"Driver"}),e.jsx(K,{value:"iron",children:"Iron"})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 items-center",children:[e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap",children:"Date range:"}),e.jsx(y,{type:"date",value:B,onChange:s=>{I(s.target.value),U(0)},className:"sm:w-[155px]"}),e.jsx("span",{className:"text-xs text-gray-400",children:"to"}),e.jsx(y,{type:"date",value:G,onChange:s=>{De(s.target.value),U(0)},className:"sm:w-[155px]"}),(B||G||O)&&e.jsx("button",{className:"text-xs text-gray-400 hover:text-gray-600 underline",onClick:()=>{I(""),De(""),x(""),U(0)},children:"Clear"})]})]}),ie.isLoading?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(f,{className:"h-5 w-5 animate-spin text-gray-400"})}):(es=ie.data)!=null&&es.sessions.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto rounded-md border border-gray-200",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200 text-left text-xs text-gray-500",children:[e.jsx("th",{className:"px-3 py-2 font-medium",children:"Date"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Org"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Customer"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Club"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Fitter"}),e.jsx("th",{className:"px-3 py-2 font-medium"})]})}),e.jsx("tbody",{children:ie.data.sessions.map(s=>e.jsxs("tr",{className:"border-b border-gray-100 last:border-0 hover:bg-gray-50",children:[e.jsx("td",{className:"px-3 py-3 text-gray-500 text-xs whitespace-nowrap",children:s.createdAt?new Date(s.createdAt).toLocaleDateString():"â"}),e.jsx("td",{className:"px-3 py-3 text-gray-800 font-medium",children:s.orgName||e.jsx("span",{className:"text-gray-400",children:"â"})}),e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"text-gray-900",children:s.customerName||s.customerEmail||s.email||"â"}),s.customerEmail&&s.customerName&&e.jsx("div",{className:"text-xs text-gray-400",children:s.customerEmail})]}),e.jsx("td",{className:"px-3 py-3 capitalize text-gray-700",children:s.clubType||"â"}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(D,{variant:s.status==="completed"?"default":"secondary",className:"text-xs",children:s.status==="completed"?"Completed":s.status==="processing"?"In progress":s.status||"Pending"})}),e.jsx("td",{className:"px-3 py-3 text-gray-500",children:s.fitterName||"â"}),e.jsx("td",{className:"px-3 py-3 text-right",children:e.jsxs("a",{href:`/admin/sessions/${s.publicId||s.id}`,target:"_blank",rel:"noreferrer",className:"text-xs text-gray-400 hover:text-gray-700 inline-flex items-center gap-1",children:["View ",e.jsx(Ie,{className:"h-3 w-3"})]})})]},s.id))})]})}),(()=>{const s=ie.data.total,i=Math.ceil(s/we);return i>1?e.jsxs("div",{className:"flex items-center justify-between mt-3",children:[e.jsxs("span",{className:"text-xs text-gray-500",children:["Page ",se+1," of ",i]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(n,{variant:"outline",size:"sm",disabled:se===0,onClick:()=>U(g=>Math.max(0,g-1)),children:[e.jsx(vs,{className:"h-4 w-4"})," Prev"]}),e.jsxs(n,{variant:"outline",size:"sm",disabled:se>=i-1,onClick:()=>U(g=>g+1),children:["Next ",e.jsx(ws,{className:"h-4 w-4"})]})]})]}):null})()]}):e.jsx("p",{className:"py-8 text-center text-sm text-gray-400",children:"No sessions foun
21d."})]}),e.jsxs(Y,{testId:"admin-section-exports",heading:e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-gray-900",children:[e.jsx(ns,{className:"h-5 w-5 text-gray-400"}),"Admin Exports"]}),description:e.jsx("p",{className:"text-sm text-gray-500 mt-0.5",children:"Archive the current fitting rules or download golfer emails with fitting metadata."}),children:[e.jsxs("div",{className:"flex flex-wrap justify-end gap-2 mb-4",children:[e.jsx("a",{href:"/api/admin/export/master-rules.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Download Master Rules"]})}),e.jsx("a",{href:"/api/admin/export/golfer-emails.csv",download:!0,children:e.jsxs(n,{size:"sm",className:"rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Download CSV"]})})]}),e.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700 mb-2",children:"Download rules by segment"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2",children:[e.jsx("a",{href:"/api/admin/export/master-rules/sh
21ared-base.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Shared / Base"]})}),e.jsx("a",{href:"/api/admin/export/master-rules/driver.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Driver Rules"]})}),e.jsx("a",{href:"/api/admin/export/master-rules/iron.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Iron Rules"]})}),e.jsx("a",{href:"/api/admin/export/master-rules/fairway.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Fairway Wood Rules"]})}),e.jsx("a",{href:"/api/admin/export/master-rules/hybrid.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Hybrid Rules"]})}),e.jsx("a",{href:"/api/admin/export/master-rules/wedge.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Wedge Rules"]})}),e.jsx("a",{href:"/api/admin/export/master-rules/product-matching.md",download:!0,children:e.jsxs(n,{size:"sm",variant:"outline",className:"w-full justify-start rounded-md gap-2",children:[e.jsx(M,{className:"h-4 w-4"}),"Product Matching"]})})]})]}),Z.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-400 py-2",children:[e.jsx(f,{className:"h-4 w-4 animate-spin"})," Loading statsâ¦"]}):Z.data?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[[{label:"Unique emails",value:Z.data.totalUniqueEmails},{label:"With completed fitting",value:Z.data.withCompletedFitting},{label:"No completed fitting",value:Z.data.withoutCompletedFitting}].map(({label:s,value:i})=>e.jsxs("div",{className:"rounded-md border border-gray-100 bg-gray-50 px-4 py-3",children:[e.jsx("p",{className:"text-2xl font-semibold text-gray-900",children:i.toLocaleString()}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:s})]},s)),e.jsxs("div",{className:"rounded-md border border-gray-100 bg-gray-50 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1.5",children:"By club type"}),e.jsx("div",{className:"space-y-0.5",children:Object.entries(Z.data.byClubType).map(([s,i])=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"capitalize text-gray-600",children:s}),e.jsx("span",{className:"font-medium text-gray-800",children:i.toLocaleString()})]},s))})]})]}):null]}),e.jsxs(Y,{testId:"admin-section-super-analysts",heading:e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-gray-900",children:[e.jsx(js,{className:"h-5 w-5 text-gray-400"}),"Super Analysts"]}),description:e.jsx("p",{className:"text-sm text-gray-500",children:"Analysts can view all fitting sessions across all orgs. Customer names and emails are redacted for them."}),children:[e.jsx("div",{className:"flex flex-wrap justify-end gap-2 mb-4",children:e.jsx("a",{href:"/analyst",target:"_blank",rel:"noreferrer",children:e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md",children:"Open Analyst Portal"})})}),e.jsxs("div",{className:"mb-4 flex gap-2",children:[e.jsx(y,{type:"email",value:oe,onChange:s=>Re(s.target.value),placeholder:"[email protected]",className:"max-w-xs",onKeyDown:s=>s.key==="Enter"&&oe.trim()&&X.mutate()}),e.jsxs(n,{className:"rounded-md",disabled:!oe.trim()||X.isPending,onClick:()=>X.mutate(),children:[X.isPending?e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),"Add Analyst"]})]}),X.error&&e.jsx("p",{className:"mb-3 text-sm text-red-600",children:X.error.message}),he.isLoading?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(f,{className:"h-5 w-5 animate-spin text-gray-400"})}):(he.data??[]).length===0?e.jsx("p",{className:"py-6 text-center text-sm text-gray-400",children:"No anal
21ysts yet."}):e.jsx("div",{className:"overflow-x-auto rounded-md border border-gray-200",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50 text-left text-xs text-gray-500",children:[e.jsx("th",{className:"px-3 py-2 font-medium",children:"Email"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Added By"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Added"}),e.jsx("th",{className:"px-3 py-2 font-medium"})]})}),e.jsx("tbody",{children:(he.data??[]).map(s=>e.jsxs("tr",{className:"border-b border-gray-100 last:border-0",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-gray-900",children:s.email}),e.jsx("td",{className:"px-3 py-3 text-gray-500",children:s.addedByEmail}),e.jsx("td",{className:"px-3 py-3 text-xs text-gray-400",children:s.createdAt?new Date(s.createdAt).toLocaleDateString():"â"}),e.jsx("td",{className:"px-3 py-3 text-right",children:e.jsx(n,{variant:"outline",size:"sm",className:"rounded-md text-red-600 hover:text-red-700",onClick:()=>Qe.mutate(s.id),disabled:Qe.isPending,children:e.jsx(Ee,{className:"h-3.5 w-3.5"})})})]},s.id))})]})})]}),e.jsxs(Y,{testId:"admin-section-demo-access",heading:e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-gray-900",children:[e.jsx(Cs,{className:"h-5 w-5 text-indigo-600"}),"Demo Access"]}),description:e.jsx("p",{className:"text-sm text-gray-500",children:"Generate a 7-day demo link to share with prospects. They'll land directly in the demo fitter portal with seeded data."}),children:[e.jsxs(n,{size:"sm",disabled:Me,onClick:async()=>{Ke(!0),qe(null);try{const s=await p("GET","/api/admin/demo/link");qe(s),be(!1)}catch{je({title:"Failed to generate demo link",variant:"destructive"})}finally{Ke(!1)}},children:[Me?e.jsx(f,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Pe,{className:"h-4 w-4 mr-1"}),"Generate Demo Link"]}),ae&&e.jsxs("div",{className:"mt-4 rounded-lg border border-indigo-200 bg-indigo-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("code",{className:"flex-1 text-xs font-mono text-indigo-900 break-all bg-white border border-indigo-100 rounded px-2 py-1.5",children:ae.url}),e.jsx(n,{size:"sm",variant:"outline",className:"shrink-0 h-8 px-2",onClick:()=>{navigator.clipboard.writeText(ae.url),be(!0),setTimeout(()=>be(!1),1800)},children:ms?e.jsx(ds,{className:"h-3.5 w-3.5 text-green-600"}):e.jsx(Ae,{className:"h-3.5 w-3.5"})})]}),e.jsxs("p",{className:"text-xs text-indigo-700",children:["Expires: ",e.jsx("span",{className:"font-medium",children:new Date(ae.expiresAt).toLocaleString()})," · ",ae.ttlHours,"h TTL"]})]})]})]})]})}const cs={members:{label:"Fitter accounts and access",description:"Fitter accounts and their organization access will be removed.",group:"business"},customers:{label:"Customer profiles",description:"Customer profiles and contact records will be removed.",group:"business"},fittings:{label:"Fitting sessions",description:"Fitting sessions and their stored fitting information will be removed.",group:"business"},recommendations:{label:"Recommendations",description:"Product recommendations generated for fittings will be removed.",group:"business"},builds:{label:"Builds",description:"Club builds and build records will be removed.",group:"business"},slots:{label:"Fitting slots",description:"Fitting slots associated with the organization will be removed.",group:"business"},attributedFittings:{label:"Fittings attributed to this fitter",description:"Fittings attributed to this fitter will remain, with the fitter identity anonymized.",group:"related"},attributedBuilds:{label:"Builds attributed to this fitter",description:"Builds attributed to this fitter will remain, with the fitter identity anonymized.",group:"related"},inventorySettings:{label:"Inventory settings",description:"Organization inventory settings will be removed.",group:"business"},inventoryItems:{label:"Inventory items",description:"Inventory items and their organization links will be removed.",group:"business"},inventoryMovements:{label:"Inventory movement history",description:"Inventory movement history will be removed.",group:"business"},productPrices:{label:"Product pricing",description:"Organization-specific product prices will be removed.",group:"business"}
21,trialGrants:{label:"Trial access records",description:"Organization trial access records will be removed.",group:"business"},reviewRequests:{label:"Review requests",description:"Requests connected to these fittings will be removed.",group:"related"},expertReviewAnnotations:{label:"Expert review notes",description:"Expert review notes connected to these fittings will be removed.",group:"related"},recommendationFeedback:{label:"Recommendation feedback",description:"Feedback connected to these fittings will be removed.",group:"related"},recommendationIntents:{label:"Recommendation activity",description:"Recommendation activity connected to these fittings will be removed.",group:"related"},ingests:{label:"Imported session records",description:"Internal records used to import fitting sessions will be removed.",group:"technical"},marshalPairings:{label:"Connection pairing records",description:"Internal connection and pairing records will be removed.",group:"technical"},canarySuites:{label:"Model evaluation suites",description:"Internal model evaluation suites linked to the organization will be removed.",group:"technical"},canaryCases:{label:"Model evaluation cases",description:"Internal model evaluation cases linked to the organization will be removed.",group:"technical"},canaryRuns:{label:"Model evaluation runs",description:"Internal model evaluation runs linked to the organization will be removed.",group:"technical"},canaryResults:{label:"Model evaluation results",description:"Internal model evaluation results linked to the organization will be removed.",group:"technical"},purchaseRecordsRetainedAndAnonymized:{label:"Payment evidence retained",description:"Required payment evidence remains, while its customer contact information, fitting specifications, and public fitting identifier are anonymized.",group:"retained"},signupProvisioningRetainedAndAnonymized:{label:"Signup payment evidence retained",description:"Required signup payment evidence remains without live organization access or identifying contact information.",group:"retained"}};function Ps(t){return Array.isArray(t)?`${t.length} ${t.length===1?"record":"records"}`:typeof t=="number"&&Number.isFinite(t)?`${t} ${t===1?"record":"records"}`:"Count unavailable"}function Es(t,r,u){const o=cs[t];return{key:t,value:r,definition:t==="members"&&u==="fitter"?{label:"Fitter account and access",description:"Sign-in access will be revoked and identifying account information will be anonymized.",group:"business"}:o??{label:"Other related records",description:u==="organization"?"Other organization records included in the permanent deletion.":"Other records included in this permanent deletion.",group:"related"}}}function pe({records:t,entityType:r,group:u}){const o=t.map(([c,d])=>Es(c,d,r)).filter(({definition:c})=>c.group===u);return o.length?e.jsx("div",{className:"divide-y divide-red-100 rounded-md border border-red-200 bg-white",children:o.map(({key:c,value:d,definition:m})=>e.jsxs("div",{className:"flex items-start justify-between gap-4 px-3 py-2.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-red-900",children:m.label}),e.jsx("p",{className:"mt-0.5 text-xs text-red-700",children:m.description})]}),e.jsx("span",{className:"shrink-0 pt-0.5 text-xs font-medium text-red-700",children:Ps(d)})]},c))}):e.jsx("p",{className:"rounded-md border border-dashed border-red-200 bg-white px-3 py-2 text-sm text-red-700",children:"No records in this category were found."})}function Ts({entityType:t,value:r}){const u=r&&typeof r=="object"?r:{},o=u.cancelStripeSubscription===!0,c=u.revokeExternalEntitlement===!0,d=u.revokeSessionAccess===!0;return e.jsxs("div",{className:"rounded-md border border-amber-300 bg-amber-50 p-3",children:[e.jsx("h4",{className:"text-sm font-semibold text-amber-950",children:"External effects"}),e.jsxs("ul",{className:"mt-2 space-y-1.5 text-sm text-amber-900",children:[t==="organization"&&o&&e.jsx("li",{children:"⢠The organization's active subscription will be canceled."}),t==="organization"&&!o&&e.jsx("li",{children:"⢠No active subscription cancellation is needed."}),c&&e.jsx("li",{children:"⢠The organization's external entitlement will be revoked."}),d&&e.jsx("li",{children:"⢠Fitter sign-in access for this account will be revoked."}),t!=="organization"&&!d&&!c&&e.jsx("li",{children:"⢠No external account or billing actions are needed."})]})]})}function Is(t){return{organization:"Organization",fitter:"Fitter",customer:"Customer",fitting:"Fitting"}[t]}function As({target:t,onClose:r,onDeleted:u}){const[o,c]=l.useState(""),[d,m]=l.useState(""),[a,h]=l.useState(null),[C,F]=l.useState(!1),[z,S]=l.useState(!1),[P,$]=l.useState(!1),q=o.trim().length>=5,b=w({mutationFn:()=>p("POST","/api/admin/fitter-admin/deletions/preview",{...t,reason:o.trim()}),onSuccess:I=>{m(I.challengeId),h(I.impact),F(!1),S(!1)}}),k=w({mutationFn:()=>p("POST","/api/admin/fitter-admin/deletions/acknowledge",{challengeId:d,acknowledge:!0}),onSuccess:()=>S(!0)}),v=w({mutationFn:()=>p("POST","/api/admin/fitter-admin/deletions/execute",{challengeId:d,confirm:!0}),onSuccess:()=>{$(!0),u()}}),j=b.error||k.error||v.error,L=b.isPending||k.isPending||v.isPending,T=a&&typeof a.records=="object"&&a.records?Object.entries(a.records):[],O=a&&typeof a.externalEffects=="object"&&a.externalEffects?a.externalEffects:null,x=a!=null&&a.entity&&typeof a.entity=="object"&&"type"in a.entity&&typeof a.entity.type=="string"?a.entity.type:t.entityType,V=a!=null&&a.entity&&typeof a.entity=="object"&&"label"in a.entity&&typeof a.entity.label=="string"?a.entity.label:t.label,ye=T.some(([I])=>{var G;return((G=cs[I])==null?void 0:G.group)==="retained"}),B=Is(t.entityType);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4",role:"dialog","aria-modal":"true","aria-labelledby":"deletion-workflow-title","data-testid":"deletion-workflow-overlay",children:e.jsxs("section",{className:"flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-lg border-2 border-red-200 bg-red-50 shadow-2xl",children:[e.jsxs("div",{className:"sticky top-0 z-10 shrink-0 border-b-2 border-red-300 bg-red-100 px-5 py-4","data-testid":"deletion-identity-banner","aria-label":`Deleting ${B.toLowerCase()} from organization ${t.organizationName}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h2",{id:"deleti
21on-workflow-title",className:"font-semibold text-red-950",children:["Permanent deletion: ",t.label]}),e.jsxs("div",{className:"mt-2 space-y-1 text-sm",children:[e.jsx("p",{className:"font-semibold uppercase tracking-wide text-red-800",children:"Organization"}),e.jsx("p",{className:"break-words font-semibold text-red-950 [overflow-wrap:anywhere]","data-testid":"deletion-organization-name",children:t.organizationName}),e.jsxs("p",{className:"break-words text-red-800 [overflow-wrap:anywhere]","data-testid":"deletion-action-identity",children:[B," deletion target: ",t.label]})]})]}),e.jsx(n,{variant:"outline",size:"sm",disabled:L,onClick:r,className:"shrink-0",children:P?"Done":"Close"})]}),e.jsx("p",{className:"mt-3 text-sm text-red-700",children:"This cannot be restored. Review a fresh impact preview, acknowledge it, then confirm deletion."})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-5",children:[P?e.jsxs("div",{className:"rounded-md border border-green-300 bg-green-50 p-4",role:"status",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium text-green-900",children:[e.jsx(ds,{className:"h-5 w-5"}),t.entityType==="organization"?"Organization":"Record"," permanently deleted"]}),e.jsxs("p",{className:"mt-1 text-sm text-green-800",children:[t.label," was removed and the Admin organization and session lists are being refreshed."]}),e.jsx(n,{className:"mt-4 rounded-md",onClick:r,"data-testid":"deletion-done",children:"Done"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(N,{htmlFor:"deletion-reason",children:"Operational reason"}),e.jsx(y,{id:"deletion-reason",value:o,disabled:!!a,onChange:I=>c(I.target.value),className:"mt-1 bg-white",placeholder:"Required: at least 5 characters",autoFocus:!0}),!q&&e.jsx("p",{className:"mt-1 text-xs text-red-700",children:"Enter at least 5 characters before generating the impact preview."})]}),!a&&e.jsxs(n,{variant:"outline",className:"mt-3 rounded-md border-red-300 text-red-700",disabled:!q||b.isPending,onClick:()=>b.mutate(),"data-testid":"deletion-preview",children:[b.isPending&&e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Generating impact previewâ¦":"Preview exact impact"]}),a&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("details",{open:!0,className:"rounded-md border border-red-200 bg-red-100/60",children:[e.jsx("summary",{className:"cursor-pointer list-none px-3 py-2 text-sm font-medium text-red-900 [&::-webkit-details-marker]:hidden",children:e.jsxs("span",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:t.entityType==="fitter"?"What will change":"What will be removed"}),e.jsxs("span",{className:"text-xs font-normal text-red-700",children:[T.length," ",T.length===1?"area":"areas"," reviewed"]})]})}),e.jsxs("div",{className:"space-y-4 border-t border-red-200 p-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-red-950",children:x==="organization"?`Organization data for ${V}`:"Access and business data"}),e.jsx("p",{className:"mb-2 mt-1 text-xs text-red-700",children:x==="fitter"?"This fitter's access will be revoked and identifying information anonymized.":"The selected access, customer, fitting, recommendation, build, and inventory data will be permanently removed."}),e.jsx(pe,{records:T,entityType:t.entityType,group:"business"})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-semibold text-red-950",children:"Related records"}),e.jsx(pe,{records:T,entityType:t.entityType,group:"related"})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-semibold text-red-950",children:"Internal and technical records"}),e.jsx(pe,{records:T,entityType:t.entityType,group:"technical"})]})]})]}),e.jsx(Ts,{entityType:t.entityType,value:O}),e.jsxs("div",{className:"rounded-md border border-blue-200 bg-blue-50 p-3",children:[e.jsx("h4",{className:"text-sm font-semibold text-blue-950",children:"Retention and anonymization"}),e.jsx("p",{className:"mt-1 text-sm text-blue-900",children:t.entityType==="organization"?"Required payment evidence remains, while customer contact information, fitting specifications, and public fitting identifiers are anonymized.":typeof a.retention=="str
21ing"?a.retention:"Any required historical evidence remains anonymized."}),ye&&e.jsx(pe,{records:T,entityType:t.entityType,group:"retained"})]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm text-red-900",children:[e.jsx("input",{type:"checkbox",checked:C,disabled:z||k.isPending,onChange:I=>F(I.target.checked),className:"mt-1"}),"I understand what will be permanently removed, which external actions will happen, and what payment evidence will remain anonymized."]}),z?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-red-900",children:"Acknowledgement recorded. Final confirmation is now available."}),e.jsxs(n,{className:"rounded-md bg-red-700 text-white hover:bg-red-800",disabled:v.isPending,onClick:()=>v.mutate(),"data-testid":"deletion-execute",children:[v.isPending&&e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),v.isPending?"Canceling access and deleting tenant dataâ¦":t.entityType==="fitter"?"Permanently revoke and anonymize fitter":`Permanently delete ${t.entityType}`]})]}):e.jsxs("div",{children:[e.jsxs(n,{variant:"outline",className:"rounded-md border-red-300 text-red-700",disabled:!C||k.isPending,onClick:()=>k.mutate(),"data-testid":"deletion-acknowledge",children:[k.isPending&&e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),k.isPending?"Recording acknowledgementâ¦":"Record acknowledgement"]}),!C&&e.jsx("p",{className:"mt-1 text-xs text-red-700",children:"Review the impact and check the acknowledgement before continuing."})]})]})]}),j&&!P&&e.jsxs("div",{className:"mt-3 rounded-md border border-red-300 bg-white p-3 text-sm text-red-800",role:"alert",children:[e.jsx("p",{className:"font-medium",children:"Deletion request failed"}),e.jsx("p",{className:"mt-1",children:j.message}),v.error&&e.jsx("p",{className:"mt-1 text-xs",children:"This acknowledged operation still owns its lock. Use the final delete button to safely retry it."})]}),L&&e.jsxs("p",{className:"mt-3 flex items-center gap-2 text-sm text-red-800",role:"status",children:[e.jsx(f,{className:"h-4 w-4 animate-spin"}),"Please keep this window open while the operation completes."]})]})]})})}function Ds(){const[t,r]=l.useState({orgName:"",ownerEmail:"",trialDays:"14",expiresInHours:"48",reason:""}),[u,o]=l.useState(""),c=R({queryKey:["/api/admin/fitter-admin/trial-invitations"],queryFn:()=>p("GET","/api/admin/fitter-admin/trial-invitations")}),d=w({mutationFn:()=>p("POST","/api/admin/fitter-admin/trial-invitations",{orgName:t.orgName.trim(),ownerEmail:t.ownerEmail.trim().toLowerCase(),trialDays:Number(t.trialDays),expiresInHours:Number(t.expiresInHours),reason:t.reason.trim()}),onSuccess:a=>{o(a.url),r({orgName:"",ownerEmail:"",trialDays:"14",expiresInHours:"48",reason:""}),c.refetch()}}),m=w({mutationFn:a=>p("DELETE",`/api/admin/fitter-admin/trial-invitations/${a}`,{reason:"Revoked from Admin operations console"}),onSuccess:()=>c.refetch()});return e.jsxs(Y,{testId:"admin-section-trial-invitations",heading:e.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"Single-use trial invitations"}),description:e.jsx("p",{className:"text-sm text-gray-500",children:"Provision a new unpaid organization with an explicit, expiring exception trial."}),children:[e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(N,{children:"Organization name"}),e.jsx(y,{value:t.orgName,onChange:a=>r(h=>({...h,orgName:a.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Owner email"}),e.jsx(y,{type:"email",value:t.ownerEmail,onChange:a=>r(h=>({...h,ownerEmail:a.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Trial days"}),e.jsx(y,{type:"number",min:"1",max:"90",value:t.trialDays,onChange:a=>r(h=>({...h,trialDays:a.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Invitation expires in hours"}),e.jsx(y,{type:"number",min:"1",max:"168",value:t.expiresInHours,onChange:a=>r(h=>({...h,expiresInHours:a.target.value})),className:"mt-1"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(N,{children:"Operational reason"}),e.jsx(y,{value:t.reason,onChange:a=>r(h=>({...h,reason:a.target.value})),className:"mt-1"})]}),d.error&&e.jsx("p",{className:"mt-2 text-sm text-red-600",children:d.error.message}),e.jsxs(n,{className:"mt-3 rounded-md",disabled:d.isPending||t.orgName.trim().length<2||!t.ownerEmail.includes("@")||t.reason.trim().length<5,onClick:()=>d.mutate(),children:[d.isPending&&e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),"Generate invitation"]}),u&&e.jsxs("div",{className:"mt-4 rounded-md border border-green-200 bg-green-50 p-3",children:[e.jsx("p",{className:"text-xs font-medium text-green-800",children:"Copy this link now. The raw token is not stored."}),e.jsxs("div",{className:"mt-2 flex gap-2",children:[e.jsx(y,{readOnly:!0,value:u,className:"bg-white font-mono text-xs"}),e.jsx(n,{variant:"outline",onClick:()=>navigator.clipboard.writeText(u),children:e.jsx(Ae,{className:"h-4 w-4"})})]})]}),(c.data??[]).length>0&&e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-xs text-gray-500",children:[e.jsx("th",{className:"px-2 py-2",children:"Organization"}),e.jsx("th",{className:"px-2 py-2",children:"Owner"}),e.jsx("th",{className:"px-2 py-2",children:"Trial"}),e.jsx("th",{className:"px-2 py-2",children:"Expires"}),e.jsx("th",{className:"px-2 py-2",children:"Status"}),e.jsx("th",{className:"px-2 py-2"})]})}),e.jsx("tbody",{children:c.data.map(a=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"px-2 py-2",children:a.orgName}),e.jsx("td",{className:"px-2 py-2",children:a.ownerEmail}),e.jsxs("td",{className:"px-2 py-2",children:[a.trialDays,"d"]}),e.jsx("td",{className:"px-2 py-2",children:ee(a.expiresAt)}),e.jsx("td",{className:"px-2 py-2",children:e.jsx(D,{variant:"secondary",children:a.effectiveStatus})}),e.jsx("td",{className:"px-2 py-2 text-right",children:a.effectiveStatus==="pending"&&e.jsx(n,{variant:"outline",size:"sm",className:"h-7 rounded-md text-xs text-red-600",disabled:m.isPending,onClick:()=>m.mutate(a.id),children:"Revoke"})})]},a.id))})]})})]})}export{Ws 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.