1import{r as a,j as e,b as ve}from"./react-vendor-QlMg5G0i.js";import{a as fe,b as Ze}from"./query-vendor-7bKRow_J.js";import{u as pt,C as ut,a as Me,b as ht}from"./ClarioTrendChart-B_TBL1e9.js";import{E as De,ar as Ue,a1 as vt,I as J,s as je,k as be,B as Xe,q as ft,F as gt,d as Fe,e as tt,o as yt,L as jt,jN as bt,R as Ee,A as Pe,m as $e,D as qe,f as Ke,W as ze,g as _e,jz as Nt,ay as wt,Y as He,jR as kt,S as Ct,a as St,b as Tt,c as Pt,aq as $t,a3 as It,M as At}from"./app-entry-C64IZ4Vk.js";import{u as Dt}from"./usePax8TenantMap-u_bgejaP.js";import{l as Et,a as Ft,L as Mt,m as Rt,b as Lt,g as Ut,A as Ot,U as Bt}from"./LicenseChangeDetail-DX7uRSC0.js";import{I as qt}from"./InsightLightbulb-BHym6hbl.js";import{h as st,C as Ne,B as R,L as re,E as Oe,s as Ie,X as we,t as Ae,F as Be,D as at}from"./index-D8uw7Gn1.js";import{L as G}from"./label-HC6KUHtN.js";import{P as Kt}from"./Pax8Nav-Bf1w7aG9.js";import{P as zt}from"./Pax8AiChatLauncher-D6hZoD4a.js";import{c as _t,L as rt}from"./router-vendor-CiP11j9Q.js";import{r as Vt,M as Qt}from"./M365ConsentErrorAlert-jUHS97Lr.js";import{c as Ve}from"./pricing-tiers-DRxnXGuv.js";import{l as Ge,a as nt}from"./LicenseTableShared-BPsfSeFh.js";import{R as Xt}from"./RegistrationConsentStatus-Dbxrmrkk.js";import{s as Gt,i as Ht,d as me,r as Wt,b as Re}from"./pax8-formatters-CRKfqxYz.js";import{u as We}from"./use-display-currency-BiQ6Cua1.js";import{R as Zt}from"./RatesAsOfNote-Bmfc_Yqb.js";import{j as ee,q as xe}from"./fortifySecureScoreTiers-DlgAw-ZI.js";import{c as ce}from"./csvExport-Ds3KaoIN.js";import{M as Yt}from"./ManageSubscriptionDialog-W-otwCzg.js";import{C as ye}from"./circle-check-D05XmDDB.js";import{C as Jt}from"./chevron-left-DDfEBnKv.js";import{U as es}from"./user-check-V802WJEb.js";import{S as lt}from"./search-C3fhPBrD.js";import{S as ts}from"./shopping-bag-BXyRxmtN.js";import{P as it}from"./plus-DJEuodrN.js";import{S as ss}from"./save-CTz2E22C.js";import{U as Ye}from"./user-plus-BCHJ8kBp.js";import{A as as,a as Je}from"./arrow-up-89rBQ5p5.js";import{T as rs}from"./trending-up-ChSdjGot.js";import{T as ns}from"./trending-down-rairNyST.js";import{C as ls}from"./chevron-up-DNpMLRkb.js";import{i as is}from"./pricing-tiers-BDrImYnd.js";import{M as cs}from"./minus-BaKkZ9Zj.js";import{C as os}from"./circle-x-Dv_WoUz1.js";import{M as ds}from"./map-pin-ChOG5lrK.js";import{P as ms}from"./phone-Bt_n-Fgy.js";import"./ComposedChart-2dWKsWQa.js";import"./Area-Cu7ZFqfo.js";import"./index-WpFs0KKI.js";import"./helmet-vendor-BkSo4FTL.js";import"./WhiteLabelContext-7faOb9VJ.js";import"./popover-D8ZfbBvh.js";import"./command-mWDLtyme.js";import"./user-x-4RKHDOJr.js";import"./sparkles-B8NVItzd.js";import"./shield-alert-C2gD6tN1.js";import"./octagon-alert-tRUvIng-.js";import"./zap-Cw1Oei78.js";import"./lightbulb-BA_Udv3S.js";import"./use-account-display-currency-4g2lYx_5.js";import"./select-Db12z4QW.js";import"./lock-DnefIqK6.js";import"./shopping-cart-DN4wdZg3.js";import"./trash-2-Cyp4cLN2.js";import"./bot-5PDaxMrS.js";import"./table-Ef_bjV17.js";import"./TrialBadge-DEOssQNr.js";import"./m365LicenseSavings-CcUtEVnf.js";import"./currencies-DzwDK5Gj.js";import"./info-DhvubW4G.js";const xs=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],ps=st("circle-plus",xs);const us=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],ct=st("pen",us);function hs(t,i,c){return t&&c?.queryKey[2]===t?i:void 0}const Qe={firstName:"",lastName:"",email:"",phone:""},vs=["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY","DC"];function Le({contact:t,onChange:i,label:c,existingContacts:h,onSelectExisting:y,loadingExisting:v}){const r=c.toLowerCase().replace(/\s/g,"-"),[o,l]=a.useState(!1),[p,d]=a.useState(""),b=h.filter(x=>{if(!p)return!0;const k=p.toLowerCase();return x.firstName.toLowerCase().includes(k)||x.lastName.toLowerCase().includes(k)||x.email.toLowerCase().includes(k)||x.companyName.toLowerCase().includes(k)});return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wider",children:c}),e.jsxs(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px] text-blue-600 hover:text-blue-800 hover:bg-blue-50",onClick:()=>l(!o),"data-testid":`button-pick-existing-${r}`,children:[e.jsx(es,{className:"h-3 w-3 mr-1"}),o?"Manual Entry":"Use Existing Contact"]})]}),o&&e.jsxs("div",{className:"rounded-lg border bg-blue-50/50 p-2 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(lt,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-gray-400"}),e.jsx(J,{value:p,onChange:x=>d(x.target.value),placeholder:"Search by name, email, or company...",className:"h-7 text-xs pl-7","data-testid":`input-search-existing-${r}`})]}),v?e.jsxs("div",{className:"flex items-center justify-center py-3 text-xs text-gray-500",children:[e.jsx(re,{className:"h-3 w-3 mr-1 animate-spin"})," Loading contacts..."]}):b.length===0?e.jsx("div",{className:"py-2 text-center text-xs text-gray-400",children:p?"No matching contacts":"No existing contacts found"}):e.jsx("div",{className:"max-h-32 overflow-y-auto space-y-1",children:b.map((x,k)=>e.jsxs("button",{type:"button",className:"w-full text-left px-2 py-1.5 rounded text-xs hover:bg-blue-100 transition-colors flex items-center justify-between group",onClick:()=>{y(x),l(!1),d("")},"data-testid":`button-select-contact-${r}-${k}`,children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[x.firstName," ",x.lastName]}),e.jsxs("span",{className:"text-gray-500 ml-1",children:["â ",x.email]})]}),e.jsx("span",{className:"text-[9px] text-gray-400 group-hover:text-gray-600",children:x.companyName})]},`${x.email}-${k}`))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-${r}-first-name`,className:"text-[11px] text-gray-500",children:"First Name"}),e.jsx(J,{id:`contact-${r}-first-name`,value:t.firstName,onChange:x=>i("firstName",x.target.value),placeholder:"John",className:"h-8 text-sm","data-testid":`input-contact-${r}-first-name`})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-${r}-last-name`,className:"text-[11px] text-gray-500",children:"Last Name"}),e.jsx(J,{id:`contact-${r}-last-name`,value:t.lastName,onChange:x=>i("lastName",x.target.value),placeholder:"Smith",className:"h-8 text-sm","data-testid":`input-contact-${r}-last-name`})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-${r}-email`,className:"text-[11px] text-gray-500",children:"Email"}),e.jsx(J,{id:`contact-${r}-email`,type:"email",value:t.email,onChange:x=>i("email",x.target.value),placeholder:"[email protected]",className:"h-8 text-sm","data-testid":`input-contact-${r}-email`})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-${r}-phone`,className:"text-[11px] text-gray-500",children:"Phone"}),e.jsx(J,{id:`contact-${r}-phone`,value:t.phone,onChange:x=>i("phone",x.target.value),placeholder:"(555) 123-4567",className:"h-8 text-sm","data-testid":`input-contact-${r}-phone`})]})]})]})}function fs({onSuccess:t,onCancel:i}
1){const[c,h]=a.useState(1),[y,v]=a.useState(!1),[r,o]=a.useState(null),[l,p]=a.useState(null),[d,b]=a.useState(0),[x,k]=a.useState(!1),[A,C]=a.useState([]),[D,u]=a.useState(!1),[m,f]=a.useState({name:"",phone:"",website:"",street:"",street2:"",city:"",stateOrProvince:"",postalCode:"",country:"US"}),[$,K]=a.useState(""),[U,Q]=a.useState(!0),[M,O]=a.useState({...Qe}),[g,T]=a.useState({...Qe}),[E,H]=a.useState({...Qe});a.useEffect(()=>{let n=!1;async function _(){u(!0);try{const ie=await(await ee("GET","/api/pax8/contacts/existing")).json();!n&&ie.contacts&&C(ie.contacts)}catch{}finally{n||u(!1)}}return _(),()=>{n=!0}},[]);const oe=m.name.trim()&&m.phone.trim()&&m.website.trim()&&m.street.trim()&&m.city.trim()&&m.stateOrProvince.trim()&&m.postalCode.trim()&&m.country.trim(),W=n=>n.firstName.trim()&&n.lastName.trim()&&n.email.trim()&&n.phone.trim(),se=U?W(M):W(M)&&W(g)&&W(E),te=a.useCallback((n,_)=>{O(F=>({...F,[n]:_}))},[]),I=a.useCallback((n,_)=>{T(F=>({...F,[n]:_}))},[]),V=a.useCallback((n,_)=>{H(F=>({...F,[n]:_}))},[]),w=a.useCallback(n=>{O({firstName:n.firstName,lastName:n.lastName,email:n.email,phone:n.phone})},[]),ae=a.useCallback(n=>{T({firstName:n.firstName,lastName:n.lastName,email:n.email,phone:n.phone})},[]),N=a.useCallback(n=>{H({firstName:n.firstName,lastName:n.lastName,email:n.email,phone:n.phone})},[]);function P(){const n=[];return U?n.push({firstName:M.firstName,lastName:M.lastName,email:M.email,phone:M.phone,types:[{type:"Admin",primary:!0},{type:"Billing",primary:!0},{type:"Technical",primary:!0}]}):(n.push({...M,types:[{type:"Admin",primary:!0}]}),n.push({...g,types:[{type:"Billing",primary:!0}]}),n.push({...E,types:[{type:"Technical",primary:!0}]})),n}async function L(){v(!0),o(null);try{const n={company:{name:m.name.trim(),phone:m.phone.trim(),website:m.website.trim(),address:{street:m.street.trim()||void 0,street2:m.street2.trim()||void 0,city:m.city.trim(),stateOrProvince:m.stateOrProvince.trim(),postalCode:m.postalCode.trim()||void 0,country:m.country.trim()}},contacts:P(),microsoftTenantId:$.trim()||void 0},F=await(await ee("POST","/api/pax8/customers",n)).json();F.success?(p(F),h(4),t?.({pax8CompanyId:F.pax8CompanyId,companyName:m.name})):o(F.error||"Failed to create customer")}catch(n){o(n.message||"Failed to create customer")}finally{v(!1)}}async function B(){if(!l?.pax8CompanyId)return;k(!0);const n=P(),_=new Set((l?.contacts||[]).flatMap(z=>(z.types||[]).map(Y=>Y.type))),F=n.filter(z=>!z.types.every(Y=>_.has(Y.type))),ie=[];for(const z of F)try{const s=await(await ee("POST",`/api/pax8/customers/${l.pax8CompanyId}/contacts`,z)).json();ie.push(s)}catch{}const ge=ie.length>=F.length;p(z=>({...z,contacts:[...z?.contacts||[],...ie],contactsFailed:!ge,contactsExpected:n.length})),b(z=>z+1),k(!1)}const Z=[{num:1,label:"Company",icon:De},{num:2,label:"Contacts",icon:Ue},{num:3,label:"Review",icon:vt}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-center gap-1 mb-2",children:Z.map((n,_)=>e.jsxs(ve.Fragment,{children:[_>0&&e.jsx("div",{className:`w-8 h-px ${c>=n.num?"bg-[#203c59]":"bg-gray-300"}`}),e.jsxs("div",{className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-semibold ${c===n.num?"bg-[#203c59] text-white":c>n.num?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:[c>n.num?e.jsx(ye,{className:"h-3 w-3"}):e.jsx(n.icon,{className:"h-3 w-3"}),n.label]})]},n.num))}),c===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-name",className:"text-[11px] text-gray-500",children:"Company Name *"}),e.jsx(J,{id:"company-name",value:m.name,onChange:n=>f({...m,name:n.target.value}),placeholder:"Acme Corp",className:"h-8 text-sm","data-testid":"input-company-name"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-phone",className:"text-[11px] text-gray-500",children:"Phone Number *"}),e.jsx(J,{id:"company-phone",value:m.phone,onChange:n=>f({...m,phone:n.target.value}),placeholder:"(555) 123-4567",className:"h-8 text-sm","data-testid":"input-company-phone"})]})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-street",className:"text-[11px] text-gray-500",children:"Street Address *"}),e.jsx(J,{id:"company-street",value:m.street,onChange:n=>
1f({...m,street:n.target.value}),placeholder:"123 Main St",className:"h-8 text-sm","data-testid":"input-company-street"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-street2",className:"text-[11px] text-gray-500",children:"Street Address 2"}),e.jsx(J,{id:"company-street2",value:m.street2,onChange:n=>f({...m,street2:n.target.value}),placeholder:"Suite 100",className:"h-8 text-sm","data-testid":"input-company-street2"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-city",className:"text-[11px] text-gray-500",children:"City *"}),e.jsx(J,{id:"company-city",value:m.city,onChange:n=>f({...m,city:n.target.value}),placeholder:"Denver",className:"h-8 text-sm","data-testid":"input-company-city"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-state",className:"text-[11px] text-gray-500",children:"State / Province *"}),e.jsxs("select",{id:"company-state",value:m.stateOrProvince,onChange:n=>f({...m,stateOrProvince:n.target.value}),className:"h-8 w-full rounded-md border border-input bg-background px-2 text-sm","data-testid":"select-company-state",children:[e.jsx("option",{value:"",children:"Select..."}),vs.map(n=>e.jsx("option",{value:n,children:n},n))]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-postal",className:"text-[11px] text-gray-500",children:"Postal Code *"}),e.jsx(J,{id:"company-postal",value:m.postalCode,onChange:n=>f({...m,postalCode:n.target.value}),placeholder:"80202",className:"h-8 text-sm","data-testid":"input-company-postal"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-country",className:"text-[11px] text-gray-500",children:"Country *"}),e.jsxs("select",{id:"company-country",value:m.country,onChange:n=>f({...m,country:n.target.value}),className:"h-8 w-full rounded-md border border-input bg-background px-2 text-sm","data-testid":"select-company-country",children:[e.jsx("option",{value:"US",children:"United States"}),e.jsx("option",{value:"CA",children:"Canada"}),e.jsx("option",{value:"GB",children:"United Kingdom"}),e.jsx("option",{value:"AU",children:"Australia"})]})]})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-website",className:"text-[11px] text-gray-500",children:"Domain Name *"}),e.jsx(J,{id:"company-website",value:m.website,onChange:n=>f({...m,website:n.target.value}),placeholder:"company.com",className:"h-8 text-sm","data-testid":"input-company-website"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"company-tenant-id",className:"text-[11px] text-gray-500",children:"Microsoft Tenant ID (optional)"}),e.jsx(J,{id:"company-tenant-id",value:$,onChange:n=>K(n.target.value),placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",className:"h-8 text-sm font-mono","data-testid":"input-company-tenant-id"})]})]}),c===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-1",children:[e.jsx(Ne,{id:"same-for-all",checked:U,onCheckedChange:n=>Q(n===!0),"data-testid":"checkbox-same-contact"}),e.jsx(G,{htmlFor:"same-for-all",className:"text-xs text-gray-600 cursor-pointer",children:"Use the same person for Admin, Billing, and Technical contacts"})]}),U?e.jsx(Le,{contact:M,onChange:te,label:"Primary Contact",existingContacts:A,onSelectExisting:w,loadingExisting:D}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Le,{contact:M,onChange:te,label:"Admin Contact",existingContacts:A,onSelectExisting:w,loadingExisting:D}),e.jsx(Le,{contact:g,onChange:I,label:"Billing Contact",existingContacts:A,onSelectExisting:ae,loadingExisting:D}),e.jsx(Le,{contact:E,onChange:V,label:"Technical Contact",existingContacts:A,onSelectExisting:N,loadingExisting:D})]})]}),c===3&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border bg-gray-50 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wider",children:"Company Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",e.jsx("span",{className:"font-medium",children:m.name})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Phone:"})," ",e.jsx("span",{className:"font-medium",children:m.phone})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Domain:"})," ",e.jsx("span",{className:"font-medium",children:m.website})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"City:"})," ",e.jsxs("span",{className:"font-medium",children:[m.city,", ",m.stateOrProvince]})]}),m.street&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",e.jsxs("span",{className:"font-medium",children:[m.street,m.street2?`, ${m.street2}`:""]})]}),m.postalCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Postal Code:"})," ",e.jsx("span",{className:"font-medium",children:m.postalCode})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Country:"})," ",e.jsx("span",{className:"font-medium",children:m.country})]}),$&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"MS Tenant ID:"})," ",e.jsx("span",{className:"font-medium font-mono text-xs",children:$})]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-gray-50 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wider",children:"Contacts"}),U?e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"All roles:"})," ",e.jsxs("span",{className:"font-medium",children:[M.firstName," ",M.lastName]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Email:"})," ",e.jsx("span",{className:"font-medium",children:M.email})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Phone:"})," ",e.jsx("span",{className:"font-medium",children:M.phone})]})]}):e.jsx("div",{className:"space-y-1.5 text-sm",children:[{label:"Admin",c:M},{label:"Billing",c:g},{label:"Technical",c:E}].map(({label:n,c:_})=>e.jsxs("div",{children:[e.jsxs("span",{className:"text-gray-500",children:[n,":"]})," ",e.jsxs("span",{className:"font-medium",children:[_.firstName," ",_.lastName]})," ","â ",_.email]},n))})]}),r&&e.jsxs("div",{className:"flex gap-2 p-2.5 rounded-lg bg-red-50 border border-red-200",children:[e.jsx(je,{className:"h-4 w-4 text-red-500 flex-shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs text-red-700",children:r})]})]}),c===4&&!l?.contactsFailed&&e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-green-50 border border-green-200",children:[e.jsx(ye,{className:"h-5 w-5 text-green-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-green-800",children:[e.jsx("div",{className:"font-semibold mb-1","data-testid":"text-create-success",children:"Customer Created Successfully"}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Company:"})," ",m.name]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAX8 ID:"})," ",e.jsx("span",{className:"font-mono",children:l?.pax8CompanyId})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Contacts added:"})," ",l?.contacts?.length||0]})]})]})]}),c===4&&l?.contactsFailed&&d===0&&e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-amber-50 border border-amber-200",children:[e.jsx(be,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-amber-800 w-full",children:[e.jsx("div",{className:"font-semibold mb-1","data-testid":"text-contacts-warning",children:"Company Created â Contacts Failed"}),e.jsxs("div",{className:"text-xs space-y-0.5 mb-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Company:"})," ",m.name]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAX8 ID:"})," ",e.jsx("span",{className:"font-mono",children:l?.pax8CompanyId})]}),e.jsxs("div",{children:["The company was created but contact creation failed. The company will remain"," ",e.jsx("strong",{children:"Inactive"})," in PAX8 until contacts are added."]})]}),e.jsx(R,{size:"sm",variant:"outline",className:"border-amber-300 text-amber-700 hover:bg-amber-100",onClick:B,disabled:x,"data-testid":"button-retry-contacts",children:x?e.jsxs(e.Fragment,{children:[e.jsx(re,{className:"h-3 w-3 mr-1 animate-spin"})," Retrying..."]}):"Retry Adding Contacts"})]})]}),c===4&&l?.contactsFailed&&d>0&&e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-red-50 border border-red-200",children:[e.jsx(je,{className:"h-5 w-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-red-800 w-full",children:[e.jsx("div",{className:"font-semibold mb-1","data-testid":"text-contacts-failed",children:"Company Created â Contacts Could Not Be Added"}),e.jsxs("div",{className:"text-xs space-y-0.5 mb-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Company:"})," ",m.name]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAX8 ID:"})," ",e.jsx("span",{className:"font-mono",children:l?.pax8CompanyId})]}),e.jsx("div",{children:"Automatic contact creation failed after retry. Please add contacts manually in the PAX8 portal to activate this company."})]}),e.jsx("a",{href:`https://app.pax8.com/companies/${l?.pax8CompanyId}`,target:"_blank",rel:"noopener noreferrer","data-testid":"link-pax8-portal",children:e.jsxs(R,{size:"sm",variant:"outline",className:"border-red-300 text-red-700 hover:bg-red-100",children:["Open PAX8 Portal ",e.jsx(Oe,{className:"h-3 w-3 ml-1"})]})})]})]}),e.jsxs("div",{className:"flex justify-between pt-1",children:[c>1&&c<4?e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>h(c-1),"data-testid":"button-create-back",children:[e.jsx(Jt,{className:"h-3 w-3 mr-1"})," Back"]}):e.jsx("div",{}),c===1&&e.jsxs(R,{size:"sm",className:"bg-[#203c59] hover:bg-[#3d7ab0] text-white",onClick:()=>h(2),disabled:!oe,"data-testid":"button-create-next-contacts",children:["Contacts ",e.jsx(Ie,{className:"h-3 w-3 ml-1"})]}),c===2&&e.jsxs(R,{size:"sm",className:"bg-[#203c59] hover:bg-[#3d7ab0] text-white",onClick:()=>h(3),disabled:!se,"data-testid":"button-create-next-review",children:["Review ",e.jsx(Ie,{className:"h-3 w-3 ml-1"})]}),c===3&&e.jsx(R,{size:"sm",className:"bg-[#203c59] hover:bg-[#3d7ab0] text-white",onClick:L,disabled:y,"data-testid":"button-create-submit",children:y?e.jsxs(e.Fragment,{children:[e.jsx(re,{className:"h-3 w-3 mr-1 animate-spin"})," Creating..."]}):"Create Customer"}),c===4&&e.jsx(R,{size:"sm",onClick:i,"data-testid":"button-create-done",children:"Done"})]})]})}function et(t,i){return t!==null&&t>0?i(t):"â"}function ot(t){return Ge(Ve(t,t))}function dt(t){return nt(Ve(t,t))}function gs(t){const i=t.licenseFilters.length>0?Array.from(new Set(t.licenseFilters.flatMap(c=>c.companyIds))):null;return{page:t.currentPage,pageSize:t.pageSize,sort:t.sortKey??"",dir:t.sortDir,search:t.searchTerm.trim(),hideZero:t.hideZeroRevenue,companyIds:i,kpiCategory:t.draftFilter}}const ys=!1;function js(t){const{subData:i,invoiceData:c}=t,h=!!i&&i.subscriptions.length>0,y=!!c&&c.nonMicrosoftItems.length>0,v=!!c?.breakdown&&c.breakdown.groups.length>0;if(!h&&!y&&!v)return null;const r=[];if(h&&i){const o=["Product","Pricing Tier","Qty","Mo. Cost","Mo. Price","Mo. Total Cost","Mo. Total Price","Renewal Date","Margin %","Is Trial"];r.push(o.join(","));for(const l of i.subscriptions){const p=l.pricingTier||Ve(l.billingTerm,l.commitmentTermType),d=l.commitmentEndDate?me(l.commitmentEndDate):"";r.push([ce(l.productName),ce(p),String(l.quantity),l.monthlyUnitCost?.toFixed(2)??"",l.monthlyUnitPrice?.toFixed(2)??"",l.monthlyTotalCost?.toFixed(2)??"",l.monthlyTotalPrice?.toFixed(2)??"",d,l.margin.toFixed(1)+"%",l.isTrial?"Yes":"No"].join(","))}r.push(""),r.push(`"Monthly Subtotal","","","","",${i.moTotalCost!=null?i.moTotalCost.toFixed(2):""},${i.moTotalPrice!=null?i.moTotalPrice.toFixed(2):""},"",${i.margin.toFixed(1)}%,""`),r.push(`"Annual Revenue (x12)","","","","",${i.annualRevenue!=null?i.annualRevenue.toFixed(2):""},"","","",""`)}if(y&&c){h&&(r.push(""),r.push(""));const o=c.invoice?me(c.invoice.invoiceDate):"";r.push(`"Non-Microsoft Invoice Items${o?` â Invoice ${o}`:""}"`);const l=["Product Name","Vendor","SKU","Qty","Unit Price","Unit Cost","Revenue","Cost","Margin %","Term","Period"];r.push(l.join(","));for(const p of c.nonMicrosoftItems){const d=p.startPeriod&&p.endPeriod?`${me(p.startPeriod)} - ${me(p.endPeriod)}`:"";
1r.push([ce(p.productName),ce(p.vendor),ce(p.sku),String(p.qty),p.unitPrice.toFixed(2),p.unitCost.toFixed(2),p.subTotal.toFixed(2),p.costTotal.toFixed(2),p.marginPct===null?"n/a":p.marginPct.toFixed(1)+"%",ce(p.term),ce(d)].join(","))}r.push(""),r.push(`"Non-Microsoft Totals","","","","","",${c.totals.nonMicrosoftRevenue.toFixed(2)},${c.totals.nonMicrosoftCost.toFixed(2)},"","",""`)}if(c?.breakdown&&c.breakdown.groups.length>0){r.length&&(r.push(""),r.push(""));const o=c.invoice?me(c.invoice.invoiceDate):"";r.push(`"Last Invoice Breakdown${o?` â Invoice ${o}`:""}"`);const l=["Group","Product Name","Vendor","SKU","Qty","Unit Price","Amount","Term","Period"];r.push(l.join(","));for(const p of c.breakdown.groups){for(const d of p.items){const b=d.startPeriod&&d.endPeriod?`${me(d.startPeriod)} - ${me(d.endPeriod)}`:"";r.push([ce(p.label),ce(d.productName),ce(d.vendor),ce(d.sku),String(d.qty),d.unitPrice.toFixed(2),d.total.toFixed(2),ce(d.term),ce(b)].join(","))}r.push(`${ce(p.label+" subtotal")},"","","","","",${p.subtotal.toFixed(2)},"",""`)}r.push(`"Last Invoice total","","","","","",${c.breakdown.total.toFixed(2)},"",""`)}return r.join(` 2`)}function mt(t){return t==null||Number.isNaN(t)?"â":String(Math.round(t*100)/100)}function xt(t,i,c){return[...t].sort((y,v)=>{const r=i(y),o=i(v);let l;return typeof r=="number"&&typeof o=="number"?l=r-o:l=String(r).localeCompare(String(o),void 0,{numeric:!0,sensitivity:"base"}),c==="asc"?l:-l})}function de({label:t,col:i,sortKey:c,sortDir:h,onSort:y,align:v="left",lastCol:r=!1}){const o=c===i,l=v==="right"?"text-right":v==="center"?"text-center":"text-left",p=v==="right"?"justify-end":v==="center"?"justify-center":"justify-start";return e.jsx("th",{"aria-sort":o?h==="asc"?"ascending":"descending":"none","data-testid":`th-sort-${i}`,className:`p-0 ${l} ${r?"":"border-r border-[var(--clr-navy-600)]"}`,children:e.jsx("button",{type:"button",onClick:d=>{d.stopPropagation(),y(i)},className:`w-full px-1 py-1.5 ${l} text-[10px] font-semibold uppercase tracking-wider cursor-pointer select-none hover:bg-[var(--clr-navy-600)] focus:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-white`,children:e.jsxs("span",{className:`inline-flex items-center gap-0.5 ${p}`,children:[t,e.jsx(Ae,{className:`h-2.5 w-2.5 transition-transform ${o?"opacity-90":"opacity-30"} ${o&&h==="asc"?"rotate-180":""}`})]})})})}function bs({breakdown:t,invoice:i,index:c,display:h}){const[y,v]=a.useState(!1),[r,o]=a.useState({}),[l,p]=a.useState("vendor"),[d,b]=a.useState("asc"),x=C=>{C===l?b(D=>D==="asc"?"desc":"asc"):(p(C),b("asc"))},k=C=>{switch(l){case"productName":return C.productName||"";case"sku":return C.sku||"";case"qty":return C.qty;case"unitPrice":return C.unitPrice;case"total":return C.total;case"term":return C.term||"";default:return C.vendor||""}},A=t.groups.reduce((C,D)=>C+D.items.length,0);return e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button","data-testid":`button-toggle-invoice-breakdown-${c}`,className:"flex w-full items-center gap-2 px-3 py-1.5 rounded cursor-pointer transition-colors bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white border-0",onClick:C=>{C.stopPropagation(),v(!y)},"aria-expanded":y,children:[y?e.jsx(Ae,{className:"h-3 w-3 flex-shrink-0"}):e.jsx(Ie,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] font-semibold",children:"Last Invoice Breakdown"}),i&&e.jsxs("span",{className:"text-[10px] text-white/70 ml-1",children:["â Invoice ",me(i.invoiceDate)]}),e.jsxs("span",{className:"text-[10px] text-white/70 ml-auto",children:[h.format(t.total)," · ",A," line",A!==1?"s":""]})]}),y&&e.jsxs("div",{className:"mt-1 border border-[var(--clr-rule)] rounded overflow-hidden",children:[e.jsx("div",{className:"bg-[var(--clr-navy)] px-3 py-1 text-center",children:e.jsx("p",{className:"text-[10px] text-white/80",children:"Every line on the latest PAX8 invoice, grouped by charge type. Group subtotals add up to the Last Invoice â click a group to see its lines."})}),e.jsxs("table",{className:"w-full text-xs border-collapse table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[14%]"}),e.jsx("col",{}),e.jsx("col",{className:"w-[120px]"}),e.jsx("col",{className:"w-[70px]"}),e.jsx("col",{className:"w-[90px]"}),e.jsx("col",{className:"w-[100px]"}),e.jsx("col",{className:"w-[70px]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--clr-navy)] text-white",children:[e.jsx(de,{label:"Vendor",col:"vendor",sortKey:l,sortDir:d,onSort:x,align:"left"}),e.jsx(de,{label:"Product",col:"productName",sortKey:l,sortDir:d,onSort:x,align:"left"}),e.jsx(de,{label:"SKU",col:"sku",sortKey:l,sortDir:d,onSort:x,align:"left"}),e.jsx(de,{label:"Qty",col:"qty",sortKey:l,sortDir:d,onSort:x,align:"center"}),e.jsx(de,{label:"Unit Price",col:"unitPrice",sortKey:l,sortDir:d,onSort:x,align:"right"}),e.jsx(de,{label:"Amount",col:"total",sortKey:l,sortDir:d,onSort:x,align:"right"}),e.jsx(de,{label:"Term",col:"term",sortKey:l,sortDir:d,onSort:x,align:"center",lastCol:!0})]})}),e.jsxs("tbody",{children:[t.groups.map(C=>{const D=!!r[C.key],u=xt(C.items,k,d);return e.jsxs(ve.Fragment,{children:[e.jsxs("tr",{className:"bg-[var(--clr-sky-050)] border-t border-[var(--clr-rule)] cursor-pointer hover:bg-[var(--clr-sky-100)]",onClick:m=>{m.stopPropagation(),o(f=>({...f,[C.key]:!f[C.key]}))},"aria-expanded":D,"data-testid":`row-invoice-breakdown-group-${c}-${C.key}`,children:[e.jsx("td",{colSpan:2,className:"px-2 py-1.5 font-semibold text-[var(--clr-navy)] border-r border-r-[var(--clr-rule)]",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[D?e.jsx(Ae,{className:"h-3 w-3"}):e.jsx(Ie,{className:"h-3 w-3"}),C.label,e.jsxs("span",{className:"font-normal text-[10px] text-[var(--clr-ink-3)]",children:["(",C.items.length,")"]})]})}),e.jsx("td",{className:"border-r border-r-[var(--clr-rule)]"}),e.jsx("td",{className:"border-r border-r-[var(--clr-rule)]"}),e.jsx("td",{className:"border-r border-r-[var(--clr-rule)]"}),e.jsx("td",{className:"px-1 py-1.5 text-right font-semibold text-[var(--clr-navy)] border-r border-r-[var(--clr-rule)]",children:h.format(C.subtotal)}),e.jsx("td",{})]}),D&&u.map((m,f)=>e.jsxs("tr",{className:f%2===0?"bg-white":"bg-[var(--clr-pearl-100)]","data-testid":`row-invoice-breakdown-item-${c}-${C.key}-${f}`,children:[e.jsx("td",{className:"px-2 py-1.5 pl-7 text-[var(--clr-ink-2)] truncate border-r border-r-[var(--clr-rule)]","data-tip":m.vendor,children:m.vendor}),e.jsx("td",{className:"px-1 py-1.5 text-[var(--clr-ink-2)] border-r border-r-[var(--clr-rule)]",children:e.jsx("span",{className:"block truncate","data-tip":m.productName,children:m.productName})}),e.jsx("td",{className:"px-1 py-1.5 border-r border-r-[var(--clr-rule)]",children:e.jsx("span",{className:"block truncate font-mono text-[10px] text-[var(--clr-ink-2)]","data-tip":m.sku,children:m.sku||"â"})}),e.jsx("td",{className:"px-1 py-1.5 text-center border-r border-r-[var(--clr-rule)]",children:mt(m.qty)}),e.jsx("td",{className:"px-1 py-1.5 text-right border-r border-r-[var(--clr-rule)]",children:m.unitPrice?h.format(m.unitPrice):"â"}),e.jsx("td",{className:`px-1 py-1.5 text-right border-r border-r-[var(--clr-rule)] ${m.total<0?"text-[var(--clr-shell)]":""}`,children:h.format(m.total)}),e.jsx("td",{className:"px-1 py-1.5 text-center",children:m.term?e.jsx("span",{title:m.term,className:`inline-block px-1 py-0.5 rounded text-[9px] font-medium ${ot(m.term)}`,children:dt(m.term)}):"â"})]},`bd-item-${C.key}-${f}`))]},`bd-group-${C.key}`)}),e.jsxs("tr",{className:"font-semibold bg-[var(--clr-navy)]/10 border-t border-[var(--clr-rule)]",children:[e.jsx("td",{colSpan:5,className:"px-2 py-1.5 text-[11px]",children:"Last Invoice total"}),e.jsx("td",{className:"px-1 py-1.5 text-right text-[11px]",children:h.format(t.total)}),e.jsx("td",{})]})]})]})]})]})}function Ns({target:t,open:i,onClose:c,allowMock:h=!1}
2){const v=h,[r,o]=a.useState(1),[l,p]=a.useState(!1),[d,b]=a.useState("edit"),[x,k]=a.useState(!1),[A,C]=a.useState(null),[D,u]=a.useState(null),[m,f]=a.useState(!1),[$,K]=a.useState(null);if(a.useEffect(()=>{v||p(!1)},[v]),a.useEffect(()=>{t&&(o(t.quantity),b("edit"),C(null),u(null),p(!1),K(null),f(!0),ee("GET",`/api/pax8/subscriptions/${t.subscriptionId}/detail`).then(n=>n.json()).then(n=>K(n)).catch(()=>{}).finally(()=>f(!1)))},[t]),!t)return null;const U=$?.subscription?.quantity??t.quantity,Q=$?.subscription?.commitmentTermEndDate??$?.subscription?.commitmentEndDate??t.commitmentEndDate,M=$?.subscription?.billingTerm??t.billingTerm,O=t.unitCost,g=t.unitPrice;function T(n){if(!$?.pricing||!Array.isArray($.pricing))return{cost:O,price:g};const _=M?$.pricing.filter(ie=>ie.billingTerm===M):$.pricing,F=_.length>0?_:$.pricing;for(const ie of F){const ge=ie.rates||[];for(const z of ge){const Y=z.startQuantityRange??0,s=z.endQuantityRange??1/0;if(n>=Y&&n<=s){const q=z.partnerBuyRate??null,pe=z.suggestedRetailPrice??null;return{cost:q,price:pe}}}}return{cost:O,price:g}}const E=T(U),H=T(r),oe=E.cost,W=E.price,se=r<U,te=r>U,I=r===U,V=r-U,w=(oe||0)*U,ae=(H.cost||0)*r,N=(W||0)*U,P=(H.price||0)*r,L=!!Q,B=Q?me(Q):null;async function Z(){const n=t;if(n){k(!0),u(null);try{const F=await(await ee("PUT",`/api/pax8/subscriptions/${n.subscriptionId}`,{quantity:r,companyId:n.companyId,companyName:n.companyName,productId:n.productId,productName:n.productName,previousQuantity:n.quantity,isMock:l})).json();F.success?(C(F),b("result"),l||(xe.invalidateQueries({queryKey:[`/api/pax8/customers/${n.companyId}/subscriptions`]}),xe.invalidateQueries({queryKey:["/api/pax8/orders"]}))):u(F.error||"Modification failed")}catch(_){u(_.message||"Modification failed")}finally{k(!1)}}}return e.jsx(qe,{open:i,onOpenChange:n=>{n||c()},children:e.jsxs(Ke,{className:"max-w-lg",onClick:n=>n.stopPropagation(),children:[e.jsx(ze,{children:e.jsxs(_e,{className:"text-[var(--clr-navy)] flex items-center gap-2",children:[e.jsx(kt,{className:"h-5 w-5"}),"Modify Subscription"]})}),d==="edit"&&e.jsxs("div",{className:"space-y-4",children:[m&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-[var(--clr-ink-3)] py-1",children:[e.jsx(re,{className:"h-3 w-3 animate-spin"})," Loading subscription details..."]}),e.jsxs("div",{className:"rounded-lg border bg-[var(--clr-pearl-100)] p-3 space-y-1.5",children:[e.jsx("div",{className:"text-xs text-[var(--clr-ink-3)] uppercase tracking-wider font-semibold",children:"Subscription Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Company:"})," ",e.jsx("span",{className:"font-medium",children:t.companyName})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Billing:"})," ",e.jsx("span",{className:"font-medium",children:M||"N/A"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Product:"})," ",e.jsx("span",{className:"font-medium",children:t.productName})]}),L&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Commitment ends:"})," ",e.jsx("span",{className:"font-medium",children:B})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{htmlFor:"modify-subscription-quantity",className:"text-xs uppercase tracking-wider font-semibold text-[var(--clr-ink-2)]",children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-sm text-[var(--clr-ink-3)]",children:[e.jsx("span",{children:"Current:"}),e.jsx("span",{className:"font-bold text-[var(--clr-navy)]",children:U})]}),e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"â"}),e.jsx("div",{className:"flex items-center gap-1 text-sm text-[var(--clr-ink-3)]",children:e.jsx("span",{children:"New:"})}),e.jsxs("div",{className:"flex items-center border rounded-md overflow-hidden",children:[e.jsx("button",{type:"button","aria-label":"Decrease subscription quantity",onClick:()=>o(Math.max(1,r-1)),className:"px-2 py-1 bg-[var(--clr-pearl-100)] hover:bg-[var(--clr-rule)] transition-colors border-r","data-testid":"button-modify-decrease",children:e.jsx(cs,{className:"h-3.5 w-3.5"})}),e.jsx("input",{id:"modify-subscription-quantity","aria-label":"New subscription quantity",type:"number",min:1,value:r,onChange:n=>o(Math.max(1,parseInt(n.target.value)||1)),className:"w-16 text-center text-sm font-medium py-1 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none","data-testid":"input-modify-quantity"}),e.jsx("button",{type:"button","aria-label":"Increase subscription quantity",onClick:()=>o(r+1),className:"px-2 py-1 bg-[var(--clr-pearl-100)] hover:bg-[var(--clr-rule)] transition-colors border-l","data-testid":"button-modify-increase",children:e.jsx(it,{className:"h-3.5 w-3.5"})})]}),!I&&e.jsxs("span",{className:`text-xs font-semibold ${te?"text-[var(--clr-moss-700)]":"text-[var(--clr-shell)]"}`,children:[te?`+${V}`:V," seat",Math.abs(V)!==1?"s":""]})]})]}),t.unitCost!==null&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--clr-ink-3)] uppercase tracking-wider font-semibold",children:"Cost Impact (Monthly)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-[10px] text-[var(--clr-ink-3)] uppercase",children:"Partner Cost"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:Re(w)}),e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"â"}),e.jsx("span",{className:`font-semibold ${I?"":te?"text-[var(--clr-shell)]":"text-[var(--clr-moss-700)]"}`,children:Re(ae)}
2)]})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-[10px] text-[var(--clr-ink-3)] uppercase",children:"Customer Price"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:Re(N)}),e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"â"}),e.jsx("span",{className:`font-semibold ${I?"":te?"text-[var(--clr-shell)]":"text-[var(--clr-moss-700)]"}`,children:Re(P)})]})]})]})]}),se&&L&&e.jsxs("div",{role:"alert",className:"flex gap-2 p-2.5 rounded-lg bg-[var(--clr-shell-100)] border border-[var(--clr-shell-300)]",children:[e.jsx(be,{className:"h-4 w-4 text-[var(--clr-shell)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-[var(--clr-shell-700)]",children:[e.jsx("div",{className:"font-semibold mb-0.5",children:"Commitment Term Active"}),/microsoft|office\s*365|m365/i.test(t.productName)?e.jsxs(e.Fragment,{children:["This subscription is under a commitment term ending ",B,". For Microsoft NCE products, seat decreases may only take effect after the commitment term ends or within the 7-day window after renewal."]}):e.jsxs(e.Fragment,{children:["This subscription is under a commitment term ending ",B,". Seat decreases may be restricted until the commitment period ends. Check the vendor's cancellation policy for details."]})]})]}),v&&e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(Ne,{id:"modify-mock",checked:l,onCheckedChange:n=>p(n===!0),"data-testid":"checkbox-modify-mock"}),e.jsx(G,{htmlFor:"modify-mock",className:"text-xs text-[var(--clr-ink-2)] cursor-pointer",children:"Run as test (mock mode â no actual changes)"})]}),D&&e.jsxs("div",{className:"flex gap-2 p-2.5 rounded-lg bg-[var(--clr-shell-100)] border border-[var(--clr-shell-300)]",children:[e.jsx(je,{className:"h-4 w-4 text-[var(--clr-shell)] flex-shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs text-[var(--clr-shell-700)]",children:D})]})]}),d==="confirm"&&e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-[var(--clr-sky-050)] border border-[var(--clr-sky-300)]",children:[e.jsx(be,{className:"h-4 w-4 text-[var(--clr-sky-600)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-[var(--clr-navy)]",children:[e.jsx("div",{className:"font-semibold mb-1",children:"Confirm Modification"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Product:"})," ",t.productName]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Company:"})," ",t.companyName]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Quantity change:"})," ",e.jsxs("span",{className:"font-semibold",children:[U," â ",r]})," ","(",V>0?`+${V}`:V," seat",Math.abs(V)!==1?"s":"",")"]}),l&&e.jsx("div",{className:"font-semibold text-[var(--clr-shell)] mt-1",children:"TEST MODE â No actual changes will be made"})]})]})]})}),d==="result"&&e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-[var(--clr-moss-100)] border border-[var(--clr-moss-300)]",children:[e.jsx(ye,{className:"h-5 w-5 text-[var(--clr-moss-700)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-[var(--clr-moss-700)]",children:[e.jsx("div",{className:"font-semibold mb-1",children:A?.isMock?"Test Modification Successful":"Subscription Modified"}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsxs("div",{children:["Quantity updated: ",U," â ",r]}),A?.isMock&&e.jsx("div",{className:"text-[var(--clr-shell)] font-medium mt-1",children:"This was a test â no actual changes were made to PAX8"})]})]})]})}),e.jsxs(He,{children:[d==="edit"&&e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"outline",size:"sm",onClick:c,"data-testid":"button-modify-cancel",children:"Cancel"}),e.jsx(R,{size:"sm",className:"bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:()=>b("confirm"),disabled:I,"data-testid":"button-modify-review",children:"Review Changes"})]}),d==="confirm"&&e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>b("edit"),"data-testid":"button-modify-back",children:"Back"}),e.jsx(R,{size:"sm",className:"bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:Z,disabled:x,"data-testid":"button-modify-submit",children:x?e.jsxs(e.Fragment,{children:[e.jsx(re,{className:"h-3 w-3 mr-1 animate-spin"})," Submitting..."]}):l?"Run Test":"Modify Subscription"})]}),d==="result"&&e.jsx(R,{size:"sm",onClick:c,"data-testid":"button-modify-done",children:"Done"})]})]})})}function ws({target:t,open:i,onClose:c,allowMock:h=!1}
2){const v=h,[r,o]=a.useState("today"),[l,p]=a.useState(""),[d,b]=a.useState(!1),[x,k]=a.useState("edit"),[A,C]=a.useState(!1),[D,u]=a.useState(null),[m,f]=a.useState(null),[$,K]=a.useState(!1),[U,Q]=a.useState(null);if(a.useEffect(()=>{v||b(!1)},[v]),a.useEffect(()=>{t&&(o("today"),p(""),k("edit"),u(null),f(null),b(!1),Q(null),K(!0),ee("GET",`/api/pax8/subscriptions/${t.subscriptionId}/detail`).then(I=>I.json()).then(I=>Q(I)).catch(()=>{}).finally(()=>K(!1)))},[t]),!t)return null;const M=U?.subscription?.commitmentTermEndDate??U?.subscription?.commitmentEndDate??t.commitmentEndDate,O=U?.subscription?.billingTerm??t.billingTerm,g=U?.subscription?.quantity??t.quantity,T=!!M,E=M?me(M):null,H=M?new Date(M).toISOString():null;function oe(){if(r!=="today"){if(r==="end_of_term"&&H)return H;if(r==="specific"&&l)return new Date(l).toISOString()}}function W(){return r==="today"?"Today (immediate)":r==="end_of_term"&&E?`End of commitment term (${E})`:r==="specific"&&l?me(l):"Not set"}async function se(){const I=t;if(I){C(!0),f(null);try{const w=await(await ee("DELETE",`/api/pax8/subscriptions/${I.subscriptionId}`,{cancelDate:oe(),companyId:I.companyId,companyName:I.companyName,productId:I.productId,productName:I.productName,quantity:I.quantity,billingTerm:I.billingTerm,isMock:d})).json();w.success?(u(w),k("result"),d||(xe.invalidateQueries({queryKey:[`/api/pax8/customers/${I.companyId}/subscriptions`]}),xe.invalidateQueries({queryKey:["/api/pax8/orders"]}))):f(w.error||"Cancellation failed")}catch(V){f(V.message||"Cancellation failed")}finally{C(!1)}}}const te=new Date().toISOString().split("T")[0];return e.jsx(qe,{open:i,onOpenChange:I=>{I||c()},children:e.jsxs(Ke,{className:"max-w-lg",onClick:I=>I.stopPropagation(),children:[e.jsx(ze,{children:e.jsxs(_e,{className:"text-[var(--clr-shell-700)] flex items-center gap-2",children:[e.jsx(os,{className:"h-5 w-5"}),"Cancel Subscription"]})}),x==="edit"&&e.jsxs("div",{className:"space-y-4",children:[$&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-[var(--clr-ink-3)] py-1",children:[e.jsx(re,{className:"h-3 w-3 animate-spin"})," Loading subscription details..."]}),e.jsxs("div",{className:"rounded-lg border bg-[var(--clr-pearl-100)] p-3 space-y-1.5",children:[e.jsx("div",{className:"text-xs text-[var(--clr-ink-3)] uppercase tracking-wider font-semibold",children:"Subscription to Cancel"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Company:"})," ",e.jsx("span",{className:"font-medium",children:t.companyName})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Quantity:"})," ",e.jsx("span",{className:"font-medium",children:g})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Product:"})," ",e.jsx("span",{className:"font-medium",children:t.productName})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Billing:"})," ",e.jsx("span",{className:"font-medium",children:O||"N/A"})]}),T&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-3)]",children:"Term ends:"})," ",e.jsx("span",{className:"font-medium",children:E})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs uppercase tracking-wider font-semibold text-[var(--clr-ink-2)]",children:"Cancellation Date"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 p-2 rounded border cursor-pointer hover:bg-[var(--clr-pearl-100)] transition-colors",children:[e.jsx("input",{type:"radio",name:"cancelDate",checked:r==="today",onChange:()=>o("today"),className:"accent-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Cancel today"}),e.jsx("div",{className:"text-[10px] text-[var(--clr-ink-3)]",children:"Immediate cancellation â takes effect now"})]})]}),T&&e.jsxs("label",{className:"flex items-center gap-2 p-2 rounded border cursor-pointer hover:bg-[var(--clr-pearl-100)] transition-colors",children:[e.jsx("input",{type:"radio",name:"cancelDate",checked:r==="end_of_term",onChange:()=>o("end_of_term"),className:"accent-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Cancel at end of commitment term"}),e.jsxs("div",{className:"text-[10px] text-[var(--clr-ink-3)]",children:["Cancellation scheduled for ",E]})]})]}),e.jsxs("label",{className:"flex items-center gap-2 p-2 rounded border cursor-pointer hover:bg-[var(--clr-pearl-100)] transition-colors",children:[e.jsx("input",{type:"radio",name:"cancelDate",checked:r==="specific",onChange:()=>o("specific"),className:"accent-red-600"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium",children:"Cancel on a specific date"}),r==="specific"&&e.jsx("input",{type:"date",min:te,value:l,onCh
2ange:I=>p(I.target.value),className:"mt-1 border rounded px-2 py-1 text-sm w-full","data-testid":"input-cancel-date"})]})]})]})]}),e.jsxs("div",{className:"flex gap-2 p-2.5 rounded-lg bg-[var(--clr-shell-100)] border border-[var(--clr-shell-300)]",children:[e.jsx(be,{className:"h-4 w-4 text-[var(--clr-shell)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-[var(--clr-shell-700)]",children:[e.jsx("div",{className:"font-semibold mb-0.5",children:"Important"}),/microsoft|office\s*365|m365/i.test(t.productName)?e.jsx(e.Fragment,{children:"For Microsoft NCE products: full refund if cancelled on Day 1, pro-rated refund Days 2-7, no refund after Day 7. After cancellation, admins have 90 days to access data."}):e.jsx(e.Fragment,{children:"Cancellation terms vary by vendor. Refund eligibility depends on the product's billing cycle and the vendor's cancellation policy. Review the subscription terms before proceeding."})]})]}),v&&e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(Ne,{id:"cancel-mock",checked:d,onCheckedChange:I=>b(I===!0),"data-testid":"checkbox-cancel-mock"}),e.jsx(G,{htmlFor:"cancel-mock",className:"text-xs text-[var(--clr-ink-2)] cursor-pointer",children:"Run as test (mock mode â no actual cancellation)"})]}),m&&e.jsxs("div",{className:"flex gap-2 p-2.5 rounded-lg bg-[var(--clr-shell-100)] border border-[var(--clr-shell-300)]",children:[e.jsx(je,{className:"h-4 w-4 text-[var(--clr-shell)] flex-shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs text-[var(--clr-shell-700)]",children:m})]})]}),x==="confirm"&&e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-[var(--clr-shell-100)] border border-[var(--clr-shell-300)]",children:[e.jsx(be,{className:"h-5 w-5 text-[var(--clr-shell)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-[var(--clr-shell-700)]",children:[e.jsx("div",{className:"font-semibold mb-1",children:"Confirm Cancellation"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-2)]",children:"Product:"})," ",t.productName]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-2)]",children:"Company:"})," ",t.companyName]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-2)]",children:"Quantity:"})," ",g," seat",g!==1?"s":""]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--clr-ink-2)]",children:"Cancel date:"})," ",e.jsx("span",{className:"font-semibold",children:W()})]}),d&&e.jsx("div",{className:"font-semibold text-[var(--clr-shell)] mt-1",children:"TEST MODE â No actual cancellation will occur"}),!d&&e.jsx("div",{className:"font-semibold text-[var(--clr-shell-700)] mt-1",children:"This action cannot be undone."})]})]})]})}),x==="result"&&e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg bg-[var(--clr-moss-100)] border border-[var(--clr-moss-300)]",children:[e.jsx(ye,{className:"h-5 w-5 text-[var(--clr-moss-700)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-[var(--clr-moss-700)]",children:[e.jsx("div",{className:"font-semibold mb-1",children:D?.isMock?"Test Cancellation Successful":"Subscription Cancelled"}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsxs("div",{children:[t.productName," â ",g," seat",g!==1?"s":""]}),e.jsxs("div",{children:["Cancel date: ",W()]}),D?.isMock&&e.jsx("div",{className:"text-[var(--clr-shell)] font-medium mt-1",children:"This was a test â no actual cancellation was made in PAX8"})]})]})]})}),e.jsxs(He,{children:[x==="edit"&&e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"outline",size:"sm",onClick:c,"data-testid":"button-cancel-dismiss",children:"Cancel"}),e.jsx(R,{size:"sm",variant:"destructive",onClick:()=>k("confirm"),disabled:r==="specific"&&!l,"data-testid":"button-cancel-review",children:"Review Cancellation"})]}),x==="confirm"&&e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>k("edit"),"data-testid":"button-cancel-back",children:"Back"}),e.jsx(R,{size:"sm",variant:"destructive",onClick:se,disabled:A,"data-testid":"button-cancel-submit",children:A?e.jsxs(e.Fragment,{children:[e.jsx(re,{className:"h-3 w-3 mr-1 animate-spin"})," Submitting..."]}):d?"Run Test":"Cancel Subscription"})]}),x==="result"&&e.jsx(R,{size:"sm",onClick:c,"data-testid":"button-cancel-done",children:"Done"})]})]})})}function Te({label:t,value:i,onSave:c,icon:h,placeholder:y,type:v="text"}
2){const[r,o]=a.useState(!1),[l,p]=a.useState(i),[d,b]=a.useState(!1);a.useEffect(()=>{p(i)},[i]);async function x(){if(l===i){o(!1);return}b(!0);try{await c(l),o(!1)}catch{}b(!1)}return r?e.jsxs("div",{className:"flex items-center gap-1.5",children:[h&&e.jsx(h,{className:"h-3.5 w-3.5 text-[var(--clr-ink-3)] flex-shrink-0"}),e.jsxs("div",{className:"flex-1 flex items-center gap-1",children:[e.jsx(J,{type:v,value:l,onChange:k=>p(k.target.value),className:"h-7 text-xs",placeholder:y,autoFocus:!0,onKeyDown:k=>{k.key==="Enter"&&x(),k.key==="Escape"&&(p(i),o(!1))},"data-testid":`input-edit-${t.toLowerCase().replace(/\s+/g,"-")}`}),e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:x,disabled:d,"data-testid":`button-save-${t.toLowerCase().replace(/\s+/g,"-")}`,"aria-label":`Save ${t}`,children:d?e.jsx(re,{className:"h-3 w-3 animate-spin"}):e.jsx(ss,{className:"h-3 w-3 text-[var(--clr-moss-700)]"})}),e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{p(i),o(!1)},"data-testid":`button-cancel-${t.toLowerCase().replace(/\s+/g,"-")}`,"aria-label":`Cancel editing ${t}`,children:e.jsx(we,{className:"h-3 w-3 text-[var(--clr-ink-3)]"})})]})]}):e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 group cursor-pointer w-full text-left",onClick:()=>o(!0),"data-testid":`field-${t.toLowerCase().replace(/\s+/g,"-")}`,children:[h&&e.jsx(h,{className:"h-3.5 w-3.5 text-[var(--clr-ink-3)] flex-shrink-0"}),e.jsx("span",{className:"text-xs text-[var(--clr-navy)] flex-1 min-w-0 truncate",children:i||e.jsx("span",{className:"text-[var(--clr-ink-3)] italic",children:y||"Not set"})}),e.jsx(ct,{className:"h-3 w-3 text-[var(--clr-ink-3)] opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"})]})}function ks({contact:t,companyId:i,onUpdated:c}){const[h,y]=a.useState(!1),[v,r]=a.useState(t.firstName),[o,l]=a.useState(t.lastName),[p,d]=a.useState(t.email),[b,x]=a.useState(t.phone||""),[k,A]=a.useState(!1),[C,D]=a.useState(null);a.useEffect(()=>{r(t.firstName),l(t.lastName),d(t.email),x(t.phone||"")},[t]);async function u(){A(!0),D(null);try{await ee("PUT",`/api/pax8/customers/${i}/contacts/${t.id}`,{firstName:v,lastName:o,email:p,phone:b,types:t.types}),y(!1),c()}catch(f){D(f.message||"Failed to save")}A(!1)}const m=t.types||[];return e.jsxs("div",{className:"border rounded-lg p-3 bg-white space-y-2","data-testid":`card-contact-${t.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:m.map((f,$)=>e.jsxs(Xe,{variant:f.primary?"default":"outline",className:`text-[9px] px-1.5 py-0 ${f.primary?"bg-[var(--clr-navy)]":""}`,children:[f.type,f.primary?" (Primary)":""]},$))}),e.jsx(R,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:()=>y(!h),"data-testid":`button-edit-contact-${t.id}`,"aria-label":"Edit contact",children:e.jsx(ct,{className:"h-3 w-3 text-[var(--clr-ink-3)]"})})]}),h?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-first-${t.id}`,className:"text-[10px] text-[var(--clr-ink-3)]",children:"First Name"}),e.jsx(J,{id:`contact-first-${t.id}`,value:v,onChange:f=>r(f.target.value),className:"h-7 text-xs","data-testid":`input-contact-first-${t.id}`})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-last-${t.id}`,className:"text-[10px] text-[var(--clr-ink-3)]",children:"Last Name"}),e.jsx(J,{id:`contact-last-${t.id}`,value:o,onChange:f=>l(f.target.value),className:"h-7 text-xs","data-testid":`input-contact-last-${t.id}`})]})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-email-${t.id}`,className:"text-[10px] text-[var(--clr-ink-3)]",children:"Email"}),e.jsx(J,{id:`contact-email-${t.id}`,type:"email",value:p,onChange:f=>d(f.target.value),className:"h-7 text-xs","data-testid":`input-contact-email-${t.id}`})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:`contact-phone-${t.id}`,className:"text-[10px] text-[var(--clr-ink-3)]",children:"Phone"}),e.jsx(J,{id:`contact-phone-${t.id}`,type:"tel",value:b,onChange:f=>x(f.target.value),className:"h-7 text-xs","data-testid":`input-contact-phone-${t.id}`})]}),C&&e.jsx("p",{role:"alert",className:"text-[10px] text-[var(--clr-shell)]",children:C}),e.jsxs("div",{className:"flex justify-end gap-1.5",children:[e.jsx(R,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:()=>y(!1),"data-testid":`button-contact-cancel-${t.id}`,children:"Cancel"}),e.jsx(R,{size:"sm",className:"h-6 text-[10px] px-2 bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:u,disabled:k,"data-testid":`button-contact-save-${t.id}`,children:k?e.jsx(re,{className:"h-3 w-3 animate-spin"}):"Save"})]})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(It,{className:"h-3 w-3 text-[var(--clr-ink-3)]"}),e.jsxs("span",{className:"text-xs font-medium text-[var(--clr-navy)]",children:[t.firstName," ",t.lastName]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(At,{className:"h-3 w-3 text-[var(--clr-ink-3)]"}),e.jsx("span",{className:"text-xs text-[var(--clr-ink-2)]",children:t.email})]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ms,{className:"h-3 w-3 text-[var(--clr-ink-3)]"}),e.jsx("span",{className:"text-xs text-[var(--clr-ink-2)]",children:t.phone})]})]})]})}function Cs({companyId:t,onCreated:i,onCancel:c}){const[h,y]=a.useState(""),[v,r]=a.useState(""),[o,l]=a.useState(""),[p,d]=a.use
2State(""),[b,x]=a.useState("Admin"),[k,A]=a.useState(!1),[C,D]=a.useState(!1),[u,m]=a.useState(null);async function f(){if(!(!h||!v||!o)){D(!0),m(null);try{await ee("POST",`/api/pax8/customers/${t}/contacts`,{firstName:h,lastName:v,email:o,phone:p,types:[{type:b,primary:k}]}),i()}catch($){m($.message||"Failed to create contact")}D(!1)}}return e.jsxs("div",{className:"border rounded-lg p-3 bg-[var(--clr-sky-050)] space-y-2","data-testid":"form-add-contact",children:[e.jsx("div",{className:"text-xs font-semibold text-[var(--clr-navy)] uppercase tracking-wider",children:"New Contact"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(G,{htmlFor:"new-contact-first",className:"text-[10px] text-[var(--clr-ink-3)]",children:"First Name *"}),e.jsx(J,{id:"new-contact-first",value:h,onChange:$=>y($.target.value),className:"h-7 text-xs","data-testid":"input-new-contact-first"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"new-contact-last",className:"text-[10px] text-[var(--clr-ink-3)]",children:"Last Name *"}),e.jsx(J,{id:"new-contact-last",value:v,onChange:$=>r($.target.value),className:"h-7 text-xs","data-testid":"input-new-contact-last"})]})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"new-contact-email",className:"text-[10px] text-[var(--clr-ink-3)]",children:"Email *"}),e.jsx(J,{id:"new-contact-email",type:"email",value:o,onChange:$=>l($.target.value),className:"h-7 text-xs","data-testid":"input-new-contact-email"})]}),e.jsxs("div",{children:[e.jsx(G,{htmlFor:"new-contact-phone",className:"text-[10px] text-[var(--clr-ink-3)]",children:"Phone"}),e.jsx(J,{id:"new-contact-phone",type:"tel",value:p,onChange:$=>d($.target.value),className:"h-7 text-xs","data-testid":"input-new-contact-phone"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx(G,{className:"text-[10px] text-[var(--clr-ink-3)]",children:"Role"}),e.jsxs("select",{value:b,onChange:$=>x($.target.value),className:"h-7 text-xs border rounded px-2","data-testid":"select-new-contact-role",children:[e.jsx("option",{value:"Admin",children:"Admin"}),e.jsx("option",{value:"Billing",children:"Billing"}),e.jsx("option",{value:"Technical",children:"Technical"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-3",children:[e.jsx(Ne,{id:"new-contact-primary",checked:k,onCheckedChange:$=>A($===!0),"data-testid":"checkbox-new-contact-primary"}),e.jsx(G,{htmlFor:"new-contact-primary",className:"text-[10px] text-[var(--clr-ink-2)] cursor-pointer",children:"Primary"})]})]}),u&&e.jsx("p",{role:"alert",className:"text-[10px] text-[var(--clr-shell)]",children:u}),e.jsxs("div",{className:"flex justify-end gap-1.5",children:[e.jsx(R,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:c,"data-testid":"button-cancel-add-contact",children:"Cancel"}),e.jsx(R,{size:"sm",className:"h-6 text-[10px] px-2 bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:f,disabled:C||!h||!v||!o,"data-testid":"button-save-new-contact",children:C?e.jsx(re,{className:"h-3 w-3 animate-spin"}):"Add Contact"})]})]})}function Ss({companyId:t,contacts:i,tenantId:c,onSaveTenantId:h,savingTenant:y,tenantError:v,tenantSuccess:r,onUpdated:o}){const[l,p]=a.useState(null),[d,b]=a.useState(null),[x,k]=a.useState(!1),[A,C]=a.useState(!1),[D,u]=a.useState(null),[m,f]=a.useState([]),[$,K]=a.useState(null),U=a.useRef(null),Q=a.useRef(null),M=a.useRef(null),O=a.useRef(null),g=a.useRef(null),T=a.useRef(null);async function E(){k(!0),u(null);try{const P=await(await ee("GET",`/api/pax8/customers/${t}/order-defaults`)).json().catch(()=>null),L=P&&typeof P=="object"?P:{},B={primaryAdminContactId:L.defaults?.primaryAdminContactId??null,primaryBillingContactId:L.defaults?.primaryBillingContactId??null,primaryTechnicalContactId:L.defaults?.primaryTechnicalContactId??null,partnerTosAcceptedAt:L.defaults?.partnerTosAcceptedAt??null,partnerTosAcceptedBy:L.defaults?.partnerTosAcceptedBy??null,partnerTosVersion:L.defaults?.partnerTosVersion??null,defaultProvisioningValues:L.defaults?.defaultProvisioningValues??null};p(B),b(L.readiness??null),f(B.defaultProvisioningValues?Object.entries(B.defaultProvisioningValues).map(([Z,n])=>({id:crypto.randomUUID(),key:Z,value:typeof n=="string"?n:String(n??"")})):[]),K(null)}catch(N){u(N?.message||"Failed to load order defaults")}k(!1)}a.useEffect(()=>{E()},[t]);const[H,oe]=a.useState(0);a.useEffect(()=>{const N=()=>{f(P=>P.findIndex(B=>B.key.trim().toLowerCase()==="parentsubscriptionid")>=0?P:[...P,{id:crypto.randomUUID(),key:"parentSubscriptionId",value:""}]),oe(P=>P+1)};return window.addEventListener("clario:focus-parent-subscription",N),(
2)=>window.removeEventListener("clario:focus-parent-subscription",N)},[]),a.useEffect(()=>{if(H===0)return;const N=m.findIndex(P=>P.key.trim().toLowerCase()==="parentsubscriptionid");M.current?.scrollIntoView({behavior:"smooth",block:"center"}),N>=0&&M.current?.querySelector(`[data-testid="input-default-provisioning-value-${N}"]`)?.focus()},[H]);async function W(N,P){if(l){C(!0),u(null);try{const L={...l,[N]:P};await ee("PUT",`/api/pax8/customers/${t}/order-defaults`,{primaryAdminContactId:L.primaryAdminContactId,primaryBillingContactId:L.primaryBillingContactId,primaryTechnicalContactId:L.primaryTechnicalContactId}),p(L),await E(),o?.()}catch(L){u(L?.message||"Failed to save")}C(!1)}}async function se(){K(null);const N={},P=new Set;for(const B of m){const Z=B.key.trim();if(Z){if(P.has(Z.toLowerCase())){K(`Duplicate field name "${Z}" â each field name must be unique.`);return}P.add(Z.toLowerCase()),N[Z]=B.value}}const L=Object.keys(N).length>0?N:null;C(!0),u(null);try{await ee("PUT",`/api/pax8/customers/${t}/order-defaults`,{defaultProvisioningValues:L}),await E(),o?.()}catch(B){u(B?.message||"Failed to save")}C(!1)}async function te(){C(!0),u(null);try{await ee("POST",`/api/pax8/customers/${t}/attest-tos`,{version:"v1"}),await E(),o?.()}catch(N){u(N?.message||"Failed to record acceptance")}C(!1)}if(x&&!l)return e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(re,{className:"h-4 w-4 animate-spin text-[var(--clr-ink-3)]"})});const I=d?[{key:"hasMicrosoftTenantId",label:"Microsoft Tenant ID linked",ok:d.hasMicrosoftTenantId,focusKey:"tenant"},{key:"partnerTosAccepted",label:"Partner Terms of Service accepted",ok:d.partnerTosAccepted,focusKey:"tos"},{key:"hasPrimaryAdminContact",label:"Primary Admin contact set",ok:d.hasPrimaryAdminContact,focusKey:"admin"},{key:"hasPrimaryBillingContact",label:"Primary Billing contact set",ok:d.hasPrimaryBillingContact,focusKey:"billing"},{key:"hasPrimaryTechnicalContact",label:"Primary Technical contact set",ok:d.hasPrimaryTechnicalContact,focusKey:"technical"}]:[],V=I.filter(N=>!N.ok).length,w=!!d&&V===0,ae=N=>{const P=N==="tenant"?U.current:N==="tos"?Q.current:N==="admin"?O.current:N==="billing"?g.current:T.current;if(!P)return;P.scrollIntoView({behavior:"smooth",block:"center"});const L=P.querySelector("input, button, select, [tabindex]:not([tabindex='-1'])");L?L.focus():typeof P.focus=="function"&&P.focus()};return e.jsxs("div",{className:"space-y-3","data-testid":"section-order-defaults",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[10px] font-semibold text-[var(--clr-ink-3)] uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(ts,{className:"h-3 w-3"})," Order Defaults"]}),d&&(w?e.jsxs(Xe,{className:"bg-[var(--clr-moss-100)] text-[var(--clr-moss-700)] border-[var(--clr-moss-300)] text-[10px] gap-1","data-testid":"badge-ready-to-order",children:[e.jsx(ye,{className:"h-3 w-3"})," Ready to order"]}):e.jsxs(Xe,{className:"bg-[var(--clr-shell-100)] text-[var(--clr-shell-700)] border-[var(--clr-shell-300)] text-[10px] gap-1","data-testid":"badge-not-ready-to-order",children:[e.jsx(be,{className:"h-3 w-3"})," Not ready (",V,")"]}))]}),d&&e.jsx("div",{className:"bg-[var(--clr-pearl-100)] rounded-lg p-3 space-y-1.5","data-testid":"checklist-readiness",children:I.map(N=>N.ok?e.jsxs("div",{className:"flex items-start gap-1.5 text-[11px]","data-testid":`readiness-item-${N.key}`,children:[e.jsx(ye,{className:"h-3.5 w-3.5 text-[var(--clr-moss-700)] mt-0.5 shrink-0"}),e.jsx("span",{className:"text-[var(--clr-navy)]",children:N.label})]},N.key):e.jsxs("button",{type:"button",onClick:()=>ae(N.focusKey),className:"flex items-start gap-1.5 text-[11px] text-left w-full hover:bg-[var(--clr-shell-100)] -mx-1 px-1 py-0.5 rounded","data-testid":`readiness-item-${N.key}`,children:[e.jsx(be,{className:"h-3.5 w-3.5 text-[var(--clr-shell)] mt-0.5 shrink-0"}),e.jsx("span",{className:"text-[var(--clr-shell-700)] font-medium underline-offset-2 hover:underline",children:N.label})]},N.key))}
2),e.jsxs("div",{ref:U,tabIndex:-1,className:"bg-[var(--clr-pearl-100)] rounded-lg p-3 space-y-1.5 focus:outline-none focus:ring-2 focus:ring-[var(--clr-shell)]","data-testid":"section-default-tenant-id",children:[e.jsx(G,{className:"text-[10px] text-[var(--clr-ink-3)]",children:"Microsoft Tenant ID"}),e.jsx(Te,{label:"",value:c,onSave:async N=>{await h(N)},placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}),y&&e.jsx("p",{className:"text-[10px] text-[var(--clr-ink-3)]",children:"Saving..."}),r&&e.jsxs("p",{className:"text-[10px] text-[var(--clr-moss-700)] flex items-center gap-1",children:[e.jsx(ye,{className:"h-3 w-3"})," Saved"]}),v&&e.jsx("p",{className:"text-[10px] text-[var(--clr-shell)]",children:v})]}),e.jsx("div",{className:"bg-[var(--clr-pearl-100)] rounded-lg p-3 space-y-2.5",children:["Admin","Billing","Technical"].map(N=>{const P=N==="Admin"?"primaryAdminContactId":N==="Billing"?"primaryBillingContactId":"primaryTechnicalContactId",L=Array.isArray(i)?i:[],B=L.filter(z=>Array.isArray(z?.types)&&z.types.some(Y=>Y?.type===N)),Z=l?.[P]||"",n=z=>{if(!z)return[];const Y=[];return z.firstName||Y.push("first name"),z.lastName||Y.push("last name"),z.email||Y.push("email"),Y},_=N==="Admin",F=Z?L.find(z=>z?.id===Z):null,ie=_?n(F):[],ge=N==="Admin"?O:N==="Billing"?g:T;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(G,{className:"text-[10px] text-[var(--clr-ink-3)]",children:["Primary ",N," Contact"]}),e.jsxs("select",{ref:ge,className:"w-full h-7 text-xs border rounded px-2 bg-white",value:Z,disabled:A,onChange:z=>{W(P,z.target.value||null)},"data-testid":`select-default-${N.toLowerCase()}-contact`,children:[e.jsx("option",{value:"",children:"â None â"}),B.map(z=>{const Y=_?n(z):[];return e.jsxs("option",{value:z.id,children:[z.firstName||"(no first name)"," ",z.lastName||"(no last name)"," (",z.email||"no email",")",Y.length>0?` â incomplete: missing ${Y.join(", ")}`:""]},z.id)})]}),_&&ie.length>0&&e.jsxs("p",{className:"text-[10px] text-[var(--clr-shell-700)] flex items-start gap-1","data-testid":"warning-admin-contact-incomplete",children:[e.jsx(be,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsxs("span",{children:["This contact is missing ",ie.join(", ")," in PAX8, so orders can't use it. Orders will fall back to the first complete contact instead. Fix the contact in PAX8 or pick a complete one."]})]})]},N)})}),e.jsx("div",{ref:Q,tabIndex:-1,className:"bg-[var(--clr-pearl-100)] rounded-lg p-3 space-y-2 focus:outline-none focus:ring-2 focus:ring-[var(--clr-shell)]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold text-[var(--clr-navy)]",children:"Partner ToS Attestation"}),e.jsx("p",{className:"text-[10px] text-[var(--clr-ink-3)]",children:l?.partnerTosAcceptedAt?`Accepted ${new Date(l.partnerTosAcceptedAt).toLocaleDateString()} by ${l.partnerTosAcceptedBy||"â"} (${l.partnerTosVersion||"v1"})`:"Not yet accepted by the partner"})]}),e.jsx(R,{size:"sm",variant:l?.partnerTosAcceptedAt?"outline":"default",className:"h-7 text-[10px] px-2",onClick:()=>{te()},disabled:A,"data-testid":"button-attest-partner-tos",children:l?.partnerTosAcceptedAt?"Re-accept":"Accept on behalf of customer"})]})}),e.jsxs("div",{ref:M,tabIndex:-1,className:"bg-[var(--clr-pearl-100)] rounded-lg p-3 space-y-2 focus:outline-none focus:ring-2 focus:ring-[var(--clr-shell)]","data-testid":"section-default-provisioning",children:[e.jsxs("div",{children:[e.jsx(G,{className:"text-[10px] text-[var(--clr-ink-3)]",children:"Default Provisioning Values"}),e.jsxs("p",{className:"text-[10px] text-[var(--clr-ink-3)] mt-0.5",children:["Pre-fill provisioning fields on every storefront order for this customer. Field name on the left (e.g. ",e.jsx("code",{className:"font-mono",children:"domainPrefix"}),","," ",e.jsx("code",{className:"font-mono",children:"countryCode"}),","," ",e.jsx("code",{className:"font-mono",children:"region"}),"), value on the right."]})]}),e.jsxs("datalist",{id:"prov-key-suggestions",children:[e.jsx("option",{value:"domainPrefix"}),e.jsx("option",{value:"countryCode"}),e.jsx("option",{value:"region"}),e.jsx("option",{value:"language"}),e.jsx("option",{value:"timezone"}),e.jsx("option",{value:"organizationName"})]}),m.length===0&&e.jsx("p",{className:"text-[10px] text-[var(--clr-ink-3)] italic","data-testid":"text-default-prov
2isioning-empty",children:'No defaults set. Click "Add field" to add your first one.'}),e.jsx("div",{className:"space-y-1.5","data-testid":"list-default-provisioning-rows",children:m.map((N,P)=>e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`row-default-provisioning-${P}`,children:[e.jsx(J,{list:"prov-key-suggestions",className:"h-7 text-xs flex-1 bg-white",value:N.key,placeholder:"Field name",onChange:L=>{const B=L.target.value;f(Z=>Z.map((n,_)=>_===P?{...n,key:B}:n)),$&&K(null)},"data-testid":`input-default-provisioning-key-${P}`}),e.jsx(J,{className:"h-7 text-xs flex-1 bg-white",value:N.value,placeholder:"Value",onChange:L=>{const B=L.target.value;f(Z=>Z.map((n,_)=>_===P?{...n,value:B}:n))},"data-testid":`input-default-provisioning-value-${P}`}),e.jsx("button",{type:"button",className:"h-7 w-7 flex items-center justify-center rounded text-[var(--clr-ink-3)] hover:bg-[var(--clr-shell-100)] hover:text-[var(--clr-shell)] shrink-0",onClick:()=>{f(L=>L.filter((B,Z)=>Z!==P)),$&&K(null)},title:"Remove this field","data-testid":`button-default-provisioning-remove-${P}`,children:e.jsx(we,{className:"h-3.5 w-3.5"})})]},N.id))}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-0.5",children:[e.jsxs(R,{type:"button",size:"sm",variant:"outline",className:"h-7 text-[10px] px-2 gap-1",onClick:()=>f(N=>[...N,{id:crypto.randomUUID(),key:"",value:""}]),"data-testid":"button-default-provisioning-add",children:[e.jsx(it,{className:"h-3 w-3"})," Add field"]}),e.jsx(R,{size:"sm",className:"h-7 text-[10px] px-2 bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:()=>{se()},disabled:A,"data-testid":"button-save-default-provisioning",children:A?e.jsx(re,{className:"h-3 w-3 animate-spin"}):"Save Provisioning Defaults"})]}),$&&e.jsx("p",{className:"text-[10px] text-[var(--clr-shell)]","data-testid":"text-default-provisioning-error",children:$})]}),D&&e.jsx("p",{className:"text-[10px] text-[var(--clr-shell)] px-1",children:D})]})}function Ts(t){const i=t?Array.from(new Set(t)).sort():null;return fe({queryKey:["/api/pax8/customer-readiness",i],queryFn:i?async()=>(await ee("POST","/api/pax8/customer-readiness/query",{companyIds:i})).json():void 0,enabled:i==null||i.length>0,staleTime:60*1e3})}function Ps({customer:t,open:i,onClose:c}){const{currentAccount:h,canManageAssignments:y}=Fe(),[v,r]=a.useState(!1),[o,l]=a.useState(!1),[p,d]=a.useState(!1),[b,x]=a.useState(null),[k,A]=a.useState(null),[C,D]=a.useState(!1),{data:u,isLoading:m,refetch:f}=fe({queryKey:[`/api/pax8/customers/${t?.id}/details`],enabled:i&&!!t,staleTime:6e4});if(a.useEffect(()=>{r(!1),x(null),A(null),D(!1)},[t?.id]),!t)return null;async function $(O,g){l(!0),x(null);try{const T={};if(O==="name")T.name=g;else{const E=u?.company?.address||{};T.address={...E,[O]:g}}await ee("PUT",`/api/pax8/customers/${t.id}`,T),f(),xe.invalidateQueries({queryKey:["/api/pax8/customers"]})}catch(T){x(T.message||"Failed to save")}l(!1)}async function K(O){d(!0),A(null),D(!1);try{await ee("PUT",`/api/pax8/customers/${t.id}/tenant-id`,{microsoftTenantId:O}),D(!0),f(),xe.invalidateQueries({queryKey:["/api/pax8/tenant-map"]}),setTimeout(()=>D(!1),2e3)}catch(g){A(g.message||"Failed to save")}d(!1)}const U=u?.company,Q=u?.contacts||[],M=u?.microsoftTenantId||"";return e.jsx(Ct,{open:i,onOpenChange:O=>{O||c()},children:e.jsxs(St,{side:"right",className:"w-[420px] sm:max-w-[420px] overflow-y-auto p-0","data-testid":"panel-customer-details",children:[e.jsxs(Tt,{className:"px-5 pt-5 pb-3 border-b bg-gradient-to-r from-[var(--clr-navy)] to-[var(--clr-navy-600)]",children:[e.jsxs(Pt,{className:"text-white text-sm font-bold flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),t.name]}),e.jsxs($t,{className:"text-[var(--clr-sky-300)] text-[10px]",children:[t.status||"Active"," · ",t.city||"",t.city&&t.stateOrProvince?", ":"",t.stateOrProvince||""]})]}),e.jsxs("div",{className:"p-5 space-y-5",children:[h?.id&&e.jsx(Ot,{accountId:h.id,resourceType:"customer-by-pax8",resourceId:t.id,className:"w-full justify-start"}),m&&e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(re,{className:"h-5 w-5 animate-spin text-[var(--clr-ink-3)]"})}),!m&&U&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-[10px] font-semibold text-[var(--clr-ink-3)] uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(De,{className:"h-3 w-3"})," Company Details"]}
2),e.jsxs("div",{className:"space-y-2 bg-[var(--clr-pearl-100)] rounded-lg p-3",children:[e.jsx(Te,{label:"Company Name",value:U.name||"",onSave:O=>$("name",O),icon:De,placeholder:"Company name"}),e.jsx(Te,{label:"Street",value:U.address?.street||"",onSave:O=>$("street",O),icon:ds,placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Te,{label:"City",value:U.address?.city||"",onSave:O=>$("city",O),placeholder:"City"}),e.jsx(Te,{label:"State",value:U.address?.stateOrProvince||"",onSave:O=>$("stateOrProvince",O),placeholder:"State"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Te,{label:"Zip",value:U.address?.postalCode||"",onSave:O=>$("postalCode",O),placeholder:"Zip code"}),e.jsx(Te,{label:"Country",value:U.address?.country||"",onSave:O=>$("country",O),placeholder:"Country"})]})]}),b&&e.jsx("p",{className:"text-[10px] text-[var(--clr-shell)] px-1",children:b})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[10px] font-semibold text-[var(--clr-ink-3)] uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Ue,{className:"h-3 w-3"})," Contacts (",Q.length,")"]}),!v&&e.jsxs(R,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2 gap-1",onClick:()=>r(!0),"data-testid":"button-add-contact",children:[e.jsx(ps,{className:"h-3 w-3"})," Add"]})]}),v&&e.jsx(Cs,{companyId:t.id,onCreated:()=>{r(!1),f()},onCancel:()=>r(!1)}),Q.length===0&&!v&&e.jsx("div",{className:"text-xs text-[var(--clr-ink-3)] text-center py-4",children:"No contacts found"}),e.jsx("div",{className:"space-y-2",children:Q.map(O=>e.jsx(ks,{contact:O,companyId:t.id,onUpdated:()=>f()},O.id))})]}),e.jsx(Ss,{companyId:t.id,contacts:Q,tenantId:M,onSaveTenantId:K,savingTenant:p,tenantError:k,tenantSuccess:C,onUpdated:()=>{xe.invalidateQueries({queryKey:["/api/pax8/customer-readiness"]})}}),y&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs(rt,{href:"/settings/users",className:"flex items-center gap-1.5 text-xs text-[var(--clr-sky-600)] hover:text-[var(--clr-navy)] transition-colors","data-testid":"link-manage-team-access",children:[e.jsx(Ue,{className:"h-3 w-3"})," Manage team access for this customer"]}),e.jsx("p",{className:"text-[10px] text-[var(--clr-ink-3)] mt-1",children:"Assign Account Managers / Viewers in Settings â Users."})]}),e.jsx("div",{className:"pt-2 border-t",children:e.jsxs("a",{href:`https://app.pax8.com/companies/${t.id}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-xs text-[var(--clr-sky-600)] hover:text-[var(--clr-navy)] transition-colors","data-testid":"link-pax8-company",children:[e.jsx(Oe,{className:"h-3 w-3"})," Open in PAX8 Portal"]})})]})]})]})})}function $s(t){if(t.changeType!=="price_change")return null;const i=Number(t.oldValue?.partnerCost),c=Number(t.newValue?.partnerCost),h=Number(t.oldValue?.price),y=Number(t.newValue?.price);return![h,y].every(v=>Number.isFinite(v)&&v>0)||![i,c].every(v=>Number.isFinite(v))?null:{oldM:(h-i)/h*100,newM:(y-c)/y*100}}function Is({companyId:t,expanded:i,apiBase:c="/api/pax8",format:h}){const{data:y,isLoading:v}=fe({queryKey:[`${c}/customers/${t}/subscription-changes?days=30`],enabled:i,staleTime:3e5});return!i||v||!y||y.changes.length===0?null:e.jsxs("div",{className:"mx-1 mb-2 mt-1 border border-[var(--clr-sky-300)] rounded bg-[var(--clr-sky-050)]/50 px-3 py-2","data-testid":"section-recent-changes","data-analytics-section":"pax8_customers_recent_changes",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-[var(--clr-navy)] mb-1.5 uppercase tracking-wider",children:"Recent Changes (30 days)"}),e.jsx("div",{className:"space-y-1",children:y.changes.slice(0,15).map(r=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]","data-testid":`change-row-${r.id}`,children:[e.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[9px] font-semibold ${Ft(r.changeType)}`,children:Et(r.changeType)}),e.jsx("span",{className:"text-[var(--clr-navy)] truncate flex-1 min-w-0",children:(r.productName||"Unknown").replace(/\s*\[New Commerce Experience\]/gi,"")}),e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Mt,{change:r,format:h})}),(()=>{const o=$s(r);if(!o)return null;const l=Rt(o.oldM,o.newM);return e.jsxs("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[9px] font-semibold flex-shrink-0 ${Lt
2(l)}`,"data-testid":`margin-change-${r.id}`,title:"Margin change",children:[l==="positive"?"â²":l==="negative"?"â¼":"â¢"," ",o.oldM.toFixed(1),"% â ",o.newM.toFixed(1),"%"]})})(),e.jsx("span",{className:"text-[var(--clr-ink-3)] flex-shrink-0",children:Wt(r.detectedAt)})]},r.id))})]})}function As({tenantId:t,accountId:i,expanded:c}){const[h,y]=a.useState(!1),{data:v,isLoading:r}=fe({queryKey:[`/api/accounts/${i}/m365/tenants/${t}/upsell-opportunities`],enabled:c,staleTime:300*1e3});if(!c||r||!v||v.opportunities.length===0)return null;const o=v.opportunities.reduce((p,d)=>p+(d.estimatedMonthlyRevenue??0),0),l=v.opportunities.slice(0,2).map(p=>p.motionName).join(", ");return e.jsxs("div",{className:"mx-1 mb-2 mt-1 border border-[var(--clr-rule)] rounded overflow-hidden","data-testid":"section-upsell-opportunities","data-analytics-section":"pax8_customers_upsell_opportunities",children:[e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 bg-[var(--clr-sky-050)] hover:bg-[var(--clr-sky)] border-b border-[var(--clr-rule)] px-3 py-1.5 text-left transition-colors",onClick:()=>y(p=>!p),"data-testid":"button-toggle-upsell-section",children:[e.jsx("span",{className:"text-[11px] font-semibold text-[var(--clr-navy)] uppercase tracking-wider",children:"Upsell Motions"}),e.jsx("span",{className:"bg-[var(--clr-sky-600)] text-white text-[9px] font-bold rounded-full px-1.5 py-0.5 leading-none flex-shrink-0",children:v.opportunities.length}),e.jsxs("span",{className:"text-[10px] text-[var(--clr-sky-600)] truncate flex-1",children:[l,v.opportunities.length>2?` +${v.opportunities.length-2} more`:""]}),o>0&&e.jsxs("span",{className:"text-[10px] font-bold text-[var(--clr-navy)] flex-shrink-0",children:["+$",new Intl.NumberFormat("en-US",{maximumFractionDigits:0}).format(o),"/mo"]}),h?e.jsx(ls,{className:"h-3 w-3 text-[var(--clr-sky-600)] flex-shrink-0"}):e.jsx(Ae,{className:"h-3 w-3 text-[var(--clr-sky-600)] flex-shrink-0"})]}),h&&(()=>{const p=Ut(v.opportunities),d=(b,x,k)=>e.jsxs("div",{"data-testid":`upsell-column-${k}`,children:[e.jsxs("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-[var(--clr-sky-600)] mb-1 flex items-center gap-1",children:[b,e.jsx("span",{className:"bg-[var(--clr-sky-050)] text-[var(--clr-navy)] rounded-full px-1 text-[8px] font-bold",children:x.length})]}),x.length===0?e.jsx("div",{className:"text-[10px] text-[var(--clr-ink-3)] italic",children:"â"}):e.jsx("div",{className:"space-y-1",children:x.map(A=>e.jsx(Bt,{opportunity:A},A.motionId))})]});return e.jsx("div",{className:"bg-[var(--clr-sky-050)]/30 px-3 py-2",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2",children:[d("Licence Path",p.licensePath,"license-path"),d("Security & Risk",p.securityAndRisk,"security-risk"),d("Beyond 365",p.mspServices,"msp-services"),d("Cross-tier Attach",p.other,"other")]})})})()]})}function Ds(t,i,c){if(is(i))return!1;const h=Date.now()-720*60*60*1e3;return c?new Date(c).getTime()>h:t?new Date(t).getTime()>h:!1}function Es({customer:t,index:i,apiBase:c="/api/pax8",draftFlags:h,licenseFilterNames:y,autoExpand:v,autoExpandInvoice:r,selected:o,onToggleSelect:l,allowMock:p=!1,readiness:d}){const[b,x]=a.useState(!1),[k,A]=a.useState(!1),[C,D]=a.useState(!1),[u,m]=a.useState("vendor"),[f,$]=a.useState("asc"),K=s=>{s===u?$(q=>q==="asc"?"desc":"asc"):(m(s),$("asc"))},U=s=>{switch(u){case"productName":return s.productName||"";case"sku":return s.sku||"";case"qty":return s.qty;case"unitPrice":return s.unitPrice;case"unitCost":return s.unitCost;case"subTotal":return s.subTotal;case"costTotal":return s.costTotal;case"marginPct":return s.marginPct===null?-1/0:s.marginPct;case"term":return s.term||"";default:return s.vendor||""}},Q=a.useRef(null),M=y&&y.length>0;a.useEffect(()=>{M&&x(!0)},[M]),a.useEffect(()=>{if(v){x(!0),r&&A(!0);const s=setTimeout(()=>{Q.current?.scrollIntoView({behavior:"smooth",block:"start"})},50);return()=>clearTimeout(s)}},[v,r]);const{canOrder:O,isPlatformAdmin:g,currentAccount:T}=Fe(),E=We({companyCurrency:t.displayCurrency??null,accountCurrency:T?.displayCurrency??null,accountCountry:T?.country??null}
2),[H,oe]=a.useState(null),[W,se]=a.useState(null),[te,I]=a.useState(null),[V,w]=a.useState("modify"),[ae,N]=a.useState({}),{data:P}=Dt(),L=P?.[t.id],{data:B,isLoading:Z,error:n,refetch:_}=fe({queryKey:[`${c}/customers/${t.id}/subscriptions`],enabled:b,staleTime:300*1e3,retry:1}),{data:F,isLoading:ie,error:ge,refetch:z}=fe({queryKey:[`${c}/customers/${t.id}/invoice`],enabled:b,staleTime:600*1e3,retry:1});function Y(){const s=js({subData:B??null,invoiceData:F??null});if(!s)return;const q=new Blob([s],{type:"text/csv"}),pe=URL.createObjectURL(q),ue=document.createElement("a");ue.href=pe,ue.download=`${t.name.replace(/[^a-zA-Z0-9]/g,"_")}_products.csv`,ue.click(),URL.revokeObjectURL(pe)}return e.jsxs("div",{ref:Q,className:`${i>0?"border-t border-[var(--clr-rule)]":""} ${v?"ring-2 ring-[var(--clr-sky-300)]":""}`,children:[e.jsxs("div",{"data-testid":`card-customer-${i}`,className:`grid w-full text-left cursor-pointer transition-colors ${b?"bg-[var(--clr-sky-050)] border-b border-[var(--clr-sky-300)]":"hover:bg-[var(--clr-pearl-100)]"}`,style:{gridTemplateColumns:"36px 1fr 110px 120px 130px 110px 80px 90px 50px"},role:"button",tabIndex:0,onClick:()=>x(!b),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),x(!b))},children:[e.jsx("div",{className:"flex items-center justify-center",onClick:s=>{s.stopPropagation()},onKeyDown:s=>{s.stopPropagation()},children:l&&e.jsx(Ne,{checked:!!o,onCheckedChange:s=>l(t.id,s===!0),"aria-label":`Select ${t.name}`,"data-testid":`checkbox-bulk-select-${t.id}`})}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0 px-3 py-2",children:[e.jsx("button",{type:"button",className:"p-0 bg-transparent border-0 cursor-pointer flex-shrink-0 flex items-center","aria-label":b?"Collapse customer":"Expand customer","aria-expanded":b,onClick:s=>{s.stopPropagation(),x(!b)},children:b?e.jsx(Ae,{className:"h-3.5 w-3.5 text-[var(--clr-navy)]"}):e.jsx(Ie,{className:"h-3.5 w-3.5 text-[var(--clr-navy)]"})}),e.jsx("span",{className:"text-xs font-bold text-[var(--clr-navy)] truncate","data-testid":`text-customer-name-${i}`,children:t.name}),h&&h.size>0&&e.jsxs("span",{className:"flex items-center gap-1 flex-shrink-0","data-testid":`badge-draft-flags-${i}`,children:[h.has("cost_increases")&&e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-[var(--clr-moss-100)] text-[var(--clr-moss-700)]",children:"â"}),h.has("new_line_items")&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-[var(--clr-shell-100)] text-[var(--clr-shell-700)]",children:[e.jsx(Be,{className:"h-2.5 w-2.5"})," New"]}),h.has("cost_decreases")&&e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-[var(--clr-shell-100)] text-[var(--clr-shell-700)]",children:"â"})]}),e.jsxs("button",{"data-testid":`button-customer-details-${i}`,className:"flex-shrink-0 flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium bg-[var(--clr-pearl-100)] text-[var(--clr-navy)] hover:bg-[var(--clr-rule)] transition-colors",onClick:s=>{s.stopPropagation(),D(!0)},title:"View customer details",children:[e.jsx(De,{className:"h-3 w-3"})," Details"]}),b&&(B&&B.subscriptions.length>0||F&&F.nonMicrosoftItems.length>0||F?.breakdown&&F.breakdown.groups.length>0)&&e.jsxs("button",{"data-testid":`button-export-csv-${i}`,className:"flex-shrink-0 ml-auto flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium bg-[var(--clr-navy)] text-white hover:bg-[var(--clr-navy-600)] transition-colors",onClick:s=>{s.stopPropagation(),Y()},title:"Export to CSV",children:[e.jsx(at,{className:"h-3 w-3"})," CSV"]})]}),(()=>{const s=B?.moTotalCost??t.moTotalCost??null,q=B?.moTotalPrice??t.moTotalPrice??null,pe=B?.annualRevenue??t.annualRevenue??null,ue=B?.margin??t.margin??null;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center justify-end px-3 py-2 text-xs font-semibold text-[var(--clr-navy)]",children:et(s,E.formatWhole)}),e.jsx("div",{className:"flex items-center justify-end px-3 py-2 text-xs font-semibold text-[var(--clr-navy)]",children:et(q,E.formatWhole)}),e.jsx("div",{className:"flex items-center justify-end px-3 py-2 text-xs font-semibold text-[var(--clr-navy)]","data-testid":`text-last-invoice-${i}`,children:t.lastInvoiceTotal&&t.lastInvoiceTotal>0?E.formatWhole(t.lastInvoiceTotal):"â"}),e.jsx("div",{className:"flex items-center justify-end px-3 py-2 text-xs font-semibold text-[var(--clr-navy)]",children:pe!==null&&pe>0?E.formatWhole(pe):"â"}),e.jsx("div",{className:`flex items-center justify-end px-3 py-2 text-xs font-bold ${ue!==null&&ue>=0?"text-[var(--clr-moss-700)]":"text-[var(--clr-shell)]"}`,children:ue!==null&&(q??0)>0?`${ue.toFixed(1)}%`:"â"})]})})(),e.jsx("div",{className:"flex items-center justify-center px-2 py-2",children:L?e.jsx(rt,{href:`/m365-tenants/${L}`,onClick:s=>s.stopPropagation(),children:e.jsxs("span",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-semibold bg-[var(--clr-moss-100)] text-[var(--clr-moss-700)] curs
2or-pointer hover:bg-[var(--clr-moss-100)] transition-colors","data-testid":`badge-connected-${i}`,children:[e.jsx(ye,{className:"h-3 w-3"})," Connected"]})}):e.jsx("button",{type:"button",className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-semibold bg-[var(--clr-shell-100)] text-[var(--clr-shell-700)] cursor-pointer hover:bg-[var(--clr-shell-100)] transition-colors","data-testid":`badge-connect-${i}`,onClick:s=>{if(s.stopPropagation(),T){if(!window.confirm("This opens Microsoft's tenant-wide admin consent flow for the reporting registration selected for this customer. Microsoft will show the exact application and permissions. This is a real administrator grant; a grant to another app registration does not transfer. Continue?"))return;window.location.href=`/api/accounts/${T.id}/m365/consent?pax8CompanyId=${t.id}`}},children:"Connect"})}),e.jsx("div",{className:"flex items-center justify-end px-2 py-2",onClick:s=>s.stopPropagation(),children:e.jsx("div",{className:"flex items-center gap-1",children:e.jsx(qt,{customerId:t.id,customerName:t.name,allSurfaces:!0,tenantId:L,size:"lg"})})})]}),b&&e.jsxs("div",{className:"bg-white border-b border-[var(--clr-rule)] px-3 pb-2",children:[e.jsx(Is,{companyId:t.id,expanded:b,apiBase:c,format:E.format}),L&&T&&e.jsxs(e.Fragment,{children:[e.jsx(Xt,{accountId:T.id,tenantId:L,resource:"reporting"}),e.jsx(As,{tenantId:L,accountId:T.id,expanded:b})]}),Z&&e.jsxs("div",{className:"flex items-center justify-center py-6",children:[e.jsx(re,{className:"h-5 w-5 animate-spin text-[var(--clr-ink-3)] mr-2"}),e.jsx("span",{className:"text-xs text-[var(--clr-ink-3)]",children:"Loading subscriptions..."})]}),n&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"text-xs text-[var(--clr-shell)] mb-1",children:"Failed to load subscriptions"}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:s=>{s.stopPropagation(),_()},"data-testid":`button-retry-subs-${i}`,children:[e.jsx(Ee,{className:"h-2.5 w-2.5 mr-1"})," Retry"]})]}),B&&B.subscriptions.length===0&&e.jsx("div",{className:"py-4 text-center text-xs text-[var(--clr-ink-3)]",children:"No active subscriptions"}),B&&B.subscriptions.length>0&&e.jsx("div",{className:"border border-[var(--clr-rule)] rounded overflow-hidden mt-1",children:e.jsxs("table",{className:"w-full text-xs border-collapse",style:{tableLayout:"fixed"},children:[e.jsxs("colgroup",{children:[e.jsx("col",{}),e.jsx("col",{style:{width:"105px"}}),e.jsx("col",{style:{width:"50px"}}),e.jsx("col",{style:{width:"80px"}}),e.jsx("col",{style:{width:"80px"}}),e.jsx("col",{style:{width:"80px"}}),e.jsx("col",{style:{width:"80px"}}),e.jsx("col",{style:{width:"85px"}}),e.jsx("col",{style:{width:"55px"}})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--clr-shell)] text-white",children:[e.jsx("th",{className:"px-2 py-1.5 text-left text-[10px] font-semibold uppercase tracking-wider border-r border-[var(--clr-shell-300)]",children:"Product"}),e.jsx("th",{className:"px-2 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider border-r border-[var(--clr-shell-300)]",children:"Pricing Tier"}),e.jsx("th",{className:"px-2 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider border-r border-[var(--clr-shell-300)]",children:"Qty"}),e.jsx("th",{className:"px-1.5 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider border-r border-[var(--clr-shell-300)]",children:"Mo. Cost"}),e.jsx("th",{className:"px-1.5 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider border-r border-[var(--clr-shell-300)]",children:"Mo. Price"}),e.jsxs("th",{className:"px-1.5 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider whitespace-nowrap leading-tight border-r border-[var(--clr-shell-300)]",children:["Mo. Total",e.jsx("br",{}),"Cost"]}),e.jsxs("th",{className:"px-1.5 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider whitespace-nowrap leading-tight border-r border-[var(--clr-shell-300)]",children:["Mo. Total",e.jsx("br",{}),"Price"]}),e.jsxs("th",{className:"px-2 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider whitespace-nowrap leading-tight border-r border-[var(--clr-shell-300)]",children:["Renewal",e.jsx("br",{}),"Date"]}),e.jsx("th",{className:"px-2 py-1.5 text-center text-[10px] font-semibold uppercase tracking-wider whitespace-nowrap",children:"Margin"})]})}),e.jsx("tbody",{children:(M?B.subscriptions.filter(s=>y.some(q=>(s.productName||"").toLowerCase().includes(q.toLowerCase()))):B.subscriptions).slice().sort((s,q)=>(s.productName||"").localeCompare(q.productName||"")).map((s,q,pe)=>{const le=q===pe.length-1?"border-b-2 border-[var(--clr-rule)]":"border-b border-[var(--clr-rule)]",ke={subscriptionId:s.pax8SubscriptionId,companyId:s.pax8CompanyId,companyName:t.name,productId:s.pax8ProductId,productName:s.productName,quantity:s.quantity,billingTerm:s.billingTerm,unitCost:s.monthlyUnitCost,unitPrice:s.monthlyUnitPrice,commitmentEndDate:s.commitmentEndDate||null,commitmentTermType:s.commitmentTermType||null,isCancelled:s.isCancelled||!1,scheduledCancellationDate:s.scheduledCancellationDate||null},ne=s.isUsageBased&&s.usageSummaries&&s.usageSummaries.length>0,j=ae[s.pax8SubscriptionId];return e.jsxs(ve.Fragment,{children:[e.jsxs("tr",{className:s.isCancelled?"bg-[var(--clr-shell-100)]":q%2===0?"bg-white":"bg-[var(--clr-pearl-100)]",children:[e.jsx("td",{className:`px-2 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)]`,children:e.jsxs("div",{className:"flex items-center gap-1",children:[ne&&e.jsx("button",{onClick:S=>{S.stopPropagation(),N(X=>({...X,[s.pax8SubscriptionId]:!X[s.pax8SubscriptionId]}))},className:"flex-shrink-0 text-[var(--clr-sky-600)] hover:text-[var(--clr-navy)] transition-colors","data-testid":`button-toggle-usage-${q}`,"aria-label":j?"Collapse usage details":"Expand usage details","aria-expanded":j,children:j?e.jsx(Ae,{className:"h-3 w-3"}):e.jsx(Ie,{className:"h-3 w-3"})}),s.isCancelled&&!(s.scheduledCancellationDate&&s.status!=="Cancelled")&&e.jsx("span",{className:"flex-shrink-0 inline-flex items-center text-[var(--clr-shell)]","data-tip":"Cancelled","data-testid":`badge-cancelled-${q}
2`,children:e.jsx(Nt,{className:"h-3.5 w-3.5",strokeWidth:2.5})}),e.jsx("span",{className:"min-w-0",children:(s.productName||"Unknown Product").replace(/\s*\[New Commerce Experience\]/gi,"")}),Ds(s.firstSeenAt,s.billingTerm,s.startDate)&&!s.isCancelled&&e.jsx("span",{className:"flex-shrink-0 inline-block px-1.5 py-0.5 bg-[var(--clr-moss-100)] text-[var(--clr-moss-700)] text-[9px] font-bold rounded whitespace-nowrap","data-testid":`badge-new-sub-${q}`,children:"NEW"}),s.isTrial&&e.jsx("span",{className:"flex-shrink-0 inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-semibold bg-[var(--clr-shell-100)] text-[var(--clr-shell-700)] border border-[var(--clr-shell-300)] uppercase tracking-wide whitespace-nowrap",title:"Trial subscription","data-testid":`badge-trial-${s.pax8SubscriptionId}`,children:"Trial"}),s.isCancelled&&s.scheduledCancellationDate&&s.status!=="Cancelled"&&e.jsx("span",{className:"flex-shrink-0 inline-block px-1.5 py-0.5 bg-[var(--clr-shell-100)] text-[var(--clr-shell-700)] text-[9px] font-semibold rounded whitespace-nowrap cursor-default","data-tip":`Scheduled cancellation on ${me(s.scheduledCancellationDate)}`,children:"Pending Cancel"}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:[(O||g)&&e.jsx("span",{className:"relative flex-shrink-0 group/manage",children:e.jsx("button",{onClick:S=>{S.stopPropagation(),I(ke),w("modify")},className:"cursor-pointer select-none px-1.5 py-0.5 text-[9px] font-semibold text-white bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] active:scale-95 rounded transition-all","data-testid":`button-manage-sub-${q}`,children:"Manage"})}),s.pax8SubscriptionId&&e.jsx("a",{href:`https://app.pax8.com/subscriptions/${s.pax8SubscriptionId}`,target:"_blank",rel:"noopener noreferrer",className:"flex-shrink-0 text-[var(--clr-sky-600)] hover:text-[var(--clr-navy)] transition-colors","data-tip":"Open in PAX8 portal","data-testid":`link-pax8-sub-${q}`,children:e.jsx(Oe,{className:"h-3 w-3"})})]})]})}),e.jsx("td",{className:`px-2 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] whitespace-nowrap text-center`,children:(()=>{const S=s.pricingTier||Ve(s.billingTerm,s.commitmentTermType);return!S||S==="Unknown"?"â":ne&&S==="Usage"?e.jsx("button",{className:`inline-block px-1 py-0.5 rounded text-[9px] font-medium whitespace-nowrap cursor-pointer hover:opacity-80 transition-opacity ${Ge(S)}`,onClick:X=>{X.stopPropagation(),N(he=>({...he,[s.pax8SubscriptionId]:!he[s.pax8SubscriptionId]}))},"data-testid":`btn-usage-toggle-${s.pax8SubscriptionId}`,children:S}):e.jsx("span",{title:S,className:`inline-block px-1 py-0.5 rounded text-[9px] font-medium whitespace-nowrap ${Ge(S)}`,children:nt(S)})})()}),e.jsx("td",{className:`px-2 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] text-center tabular-nums`,children:s.isUsageBased?"â":s.quantity}),e.jsx("td",{className:`px-1.5 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] text-right`,children:s.isUsageBased?"â":E.format(s.monthlyUnitCost)}),e.jsx("td",{className:`px-1.5 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] text-right`,children:s.isUsageBased?"â":E.format(s.monthlyUnitPrice)}),e.jsx("td",{className:`px-1.5 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] text-right`,children:E.format(s.monthlyTotalCost)}),e.jsx("td",{className:`px-1.5 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] text-right`,children:E.format(s.monthlyTotalPrice)}),e.jsx("td",{className:`px-2 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} border-r border-r-[var(--clr-rule)] text-center whitespace-nowrap`,children:s.isCancelled?e.jsx("span",{className:"inline-block px-2 py-0.5 bg-[var(--clr-shell)] text-white text-[11px] font-semibold rounded-full cursor-default",title:`Cancelled effective ${me(s.scheduledCancellationDate||s.cancelledEndDate||s.commitmentEndDate)}`,children:me(s.scheduledCancellationDate||s.cancelledEndDate||s.commitmentEndDate)}):me(s.commitmentEndDate)}),e.jsxs("td",{className:`px-2 py-1.5 ${ne&&j?"border-b border-[var(--clr-rule)]":le} text-center font-semibold ${s.margin>=0?"text-[var(--clr-moss-700)]":"text-[var(--clr-shell)]"}`,children:[s.margin.toFixed(1),"%"]})]}),ne&&j&&e.jsx("tr",{className:"bg-[var(--clr-sky-050)]/50",children:e.jsx("td",{colSpan:9,className:le,children:e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[var(--clr-navy)] uppercase tracking-wider mb-1",children:"Current Month Resource Group Breakdown"}),e.jsxs("table",{className:"w-full text-xs border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[9px] text-[var(--clr-sky-600)] uppercase",children:[e.jsx("th",{className:"text-left py-0.5 pr-2 font-semibold",children:"Resource Group"}),e.jsx("th",{className:"text-right py-0.5 px-2 font-semibold",children:"Partner Cost"}),e.jsx("th",{className:"text-right py-0.5 px-2 font-semibold",children:"Charges"}),e.jsx("th",{className:"text-right py-0.5 pl-2 font-semibold",children:"Margin"})]})}),e.jsx("tbody",{children:s.usageSummaries.map((S,X)=>{const he=S.currentCharges>0?(S.currentCharges-S.partnerTotal)/S.currentCharges*100:0;return e.jsxs("tr",{className:X%2===0?"":"bg-[var(--clr-sky-050)]/60","data-testid":`row-usage-rg-${q}-${X}`,children:[e.jsx("td",{className:"py-0.5 pr-2 text-[var(--clr-navy)]",children:S.resourceGroup}),e.jsx("td",{className:"py-0.5 px-2 text-right tabular-nums",children:E.format(S.partnerTotal)}),e.jsx("td",{className:"py-0.5 px-2 text-right tabular-nums",children:E.format(S.currentCharges)}),e.jsxs("td",{className:`py-0.5 pl-2 text-right font-semibold ${he>=0?"text-[var(--clr-moss-700)]":"text-[var(--clr-shell)]"}`,children:[he.toFixed(1),"%"]})]},S.id||X)})})]})]})})})]},s.pax8SubscriptionId||q)})})]})}),ys,B&&F&&F.nonMicrosoftItems.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button","data-testid":`button-toggle-invoice-${i}`,className:"flex w-full items-center gap-2 px-3 py-1.5 rounded cursor-pointer transition-colors bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white border-0",onClick:s=>{s.stopPropagation(),A(!k)},"aria-expanded":k,children:[k?e.jsx(Ae,{className:"h-3 w-3 flex-shrink-0"}):e.jsx(Ie,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] font-semibold",children:"Non-Microsoft Invoice Items"}),F?.invoice&&e.jsxs("span",{className:"text-[10px] text-white/70 ml-1",children:["â Invoice ",me(F.invoice.invoiceDate)]}),e.jsxs("span",{className:"text-[10px] text-white/70 ml-auto",children:[F.nonMicrosoftItems.length," item",F.nonMicrosoftItems.length!==1?"s":""]})]}),k&&e.jsxs("div",{className:"mt-1",children:[ge&&e.jsxs("div",{className:"py-3 text-center",children:[e.jsx("p",{className:"text-xs text-[var(--clr-shell)] mb-1",children:"Failed to load invoice data"}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:s=>{s.stopPropagation(),z()},"data-testid":`button-retry-invoice-${i}`,children:[e.jsx(Ee,{className:"h-2.5 w-2.5 mr-1"})," Retry"]})]}),F&&F.nonMicrosoftItems.length>0&&e.jsxs("div",{className:"border border-[var(--clr-rule)] rounded overflow-visible",children:[e.jsx("div",{className:"bg-[var(--clr-navy)] px-3 py-1 text-center rounded-t",children:e.jsxs("p",{className:"text-[10px] text-white/80",children:["Non-Microsoft products billed through PAX8",F.invoice?` â Invoice ${me(F.invoice.invoiceDate)}`:"","."]})}),e.jsx("div",{children:e.jsxs("table",{className:"w-full text-xs border-collapse table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[10%]"}),e.jsx("col",{}),e.jsx("col",{className:"w-[10%]"}),e.jsx("col",{className:"w-[50px]"}),e.jsx("col",{className:"w-[80px]"}),e.jsx("col",{className:"w-[80px]"}),e.jsx("col",{className:"w-[80px]"}),e.jsx("col",{className:"w-[80px]"}),e.jsx("col",{className:"w-[60px]"}),e.jsx("col",{className:"w-[70px]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--clr-navy)] text-white",children:[e.jsx(de,{label:"Vendor",col:"vendor",sortKey:u,sortDir:f,onSort:K,align:"left"}),e.jsx(de,{label:"Product Name",col:"productName",sortKey:u,sortDir:f,onSort:K,align:"left"}),e.jsx(de,{label:"SKU",col:"sku",sortKey:u,sortDir:f,onSort:K,align:"left"}),e.jsx(de,{label:"Qty",col:"qty",sortKey:u,sortDir:f,onSort:K,align:"center"}),e.jsx(de,{label:"Unit Price",col:"unitPrice",sortKey:u,sortDir:f,onSort:K,align:"right"}),e.jsx(de,{label:"Unit Cost",col:"unitCost",sortKey:u,sortDir:f,onSort:K,align:"right"}),e.jsx(de,{label:"Revenue",col:"subTotal",sortKey:u,sortDir:f,onSort:K,align:"right"}),e.jsx(de,{label:"Cost",col:"costTotal",sortKey:u,sortDir:f,onSort:K,align:"right"}),e.jsx(de,{label:"Margin",col:"marginPct",sortKey:u,sortDir:f,onSort:K,align:"center"}),e.jsx(de,{label:"Term",col:"term",sortKey:u,sortDir:f,onSort:K,align:"center",lastCol:!0})]})}),e.jsxs("tbody",{children:[xt(F.nonMicrosoftItems,U,f).map((s,q)=>e.jsxs("tr",{className:q%2===0?"bg-white":"bg-[var(--clr-pearl-100)]","data-testid":`row-customer-invoice-nm-${i}-${q}`,children:[e.jsx("td",{className:"px-2 py-1.5 text-[var(--clr-ink-2)] truncate border-r border-r-[var(--clr-rule)]","data-tip":s.vendor,children:s.vendor}),e.jsx("td",{className:"px-1 py-1.5 font-medium text-[var(--clr-navy)] border-r border-r-[var(--clr-rule)]",children:e.jsxs("div",{className:"flex items-start gap-1",children:[e.jsx("span",{className:"min-w-0 truncate","data-tip":s.productName,children:s.productName}),s.subscriptionId&&e.jsx("a",{href:`https://app.pax8.com/subscriptions/${s.subscriptionId}`,target:"_blank",rel:"noopener noreferrer",className:"flex-shrink-0 mt-0.5 text-[var(--clr-sky-600)] hover:text-[var(--clr-navy)] transition-colors","data-tip":"Open in PAX8 portal",children:e.jsx(Oe,{className:"h-3 w-3"})})]})}),e.jsx("td",{className:"px-1 py-1.5 border-r border-r-[var(--clr-rule)]",children:e.jsx("span",{className:"block truncate font-mono text-[10px] text-[var(--clr-ink-2)]","data-tip":s.sku,children:s.sku||"â"})}),e.jsx("td",{className:"px-1 py-1.5 text-center border-r border-r-[var(--clr-rule)]",children:mt(s.qty)}),e.jsx("td",{className:"px-1 py-1.5 text-right border-r border-r-[var(--clr-rule)]",children:s.unitPrice>0?E.format(s.unitPrice):"â"}),e.jsx("td",{className:"px-1 py-1.5 text-right border-r border-r-[var(--clr-rule)]",children:s.unitCost>0?E.format(s.unitCost):"â"}),e.jsx("td",{className:"px-1 py-1.5 text-right border-r border-r-[var(--clr-rule)]",children:s.subTotal>0?E.format(s.subTotal):"â"}),e.jsx("td",{className:"px-1 py-1.5 text-right border-r border-r-[var(--clr-rule)]",children:s.costTotal>0?E.format(s.costTotal):"â"}),e.jsx("td",{className:`px-1 py-1.5 text-center font-semibold border-r border-r-[var(--clr-rule)] ${s.marginPct===null?"text-[var(--clr-ink-3)]":s.marginPct>=0?"text-[var(--clr-moss-700)]":"text-[var(--clr-shell)]"}`,children:s.marginPct===null?"â":`${s.marginPct.toFixed(1)}%`}),e.jsx("td",{className:"px-1 py-1.5 text-center",children:s.term?e.jsx("span",{title:s.term,className:`inline-block px-1 py-0.5 rounded text-[9px] font-medium ${ot(s.term)}`,children:dt(s.term)}):"â"})]},`invoice-nm-${q}`)),(()=>{const s=F.nonMicrosoftItems.filter(le=>le.marginPct!==0&&le.marginPct!==null),q=s.reduce((le,ke)=>le+ke.subTotal,0),pe=s.reduce((le,ke)=>le+ke.costTotal,0),ue=q>0?((1-pe/q)*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"font-semibold bg-[var(--clr-navy)]/10 border-t border-[var(--clr-rule)]",children:[e.jsx("td",{className:"px-2 py-1.5 text-[11px]",children:"Totals"}),e.jsx("td",{colSpan:5,className:"px-1 py-1.5 text-right",children:e.jsx("span",{className:"font-normal text-[10px] text-[var(--clr-ink-3)] italic",children:"Margin % excludes 0% margin product costs"})}),e.jsx("td",{className:"px-1 py-1.5 text-right text-[11px]",children:E.format(F.totals.nonMicrosoftRevenue)}),e.jsx("td",{className:"px-1 py-1.5 text-right text-[11px]",children:E.format(F.totals.nonMicrosoftCost)}),e.jsxs("td",{className:"px-1 py-1.5 text-center text-[11px]",children:[ue,"%"]}),e.jsx("td",{className:"px-1 py-1.5"})]})})()]})]})})]})]})]}),F?.breakdown&&F.breakdown.groups.length>0&&e.jsx(bs,{breakdown:F.breakdown,invoice:F.invoice,index:i,display:E})]}),e.jsx(Ns,{target:H,open:!!H,onClose:()=>oe(null),allowMock:p}
2),e.jsx(ws,{target:W,open:!!W,onClose:()=>se(null),allowMock:p}),e.jsx(Yt,{target:te,open:!!te,onClose:()=>I(null),initialTab:V,allowMock:p}),e.jsx(Ps,{customer:t,open:C,onClose:()=>D(!1)})]})}function Fs({summary:t,activeFilter:i,onFilter:c}){const{currentAccount:h}=Fe(),y=We({accountCurrency:h?.displayCurrency??null,accountCountry:h?.country??null});if(!t)return null;const v=(()=>{const o=t.lastInvoiceDate;if(!o)return null;const l=/^(\d{4})-(\d{2})-(\d{2})/.exec(o),p=l?new Date(Number(l[1]),Number(l[2])-1,Number(l[3])):new Date(o);return Number.isNaN(p.getTime())?null:p.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})})(),r=[{key:"recurring_mrr",label:"Recurring MRR",icon:wt,value:y.formatCompact(t.runRateMrr??0),subValue:"run-rate from active subscriptions",tooltip:"Forward-looking monthly recurring revenue from active subscriptions â equals the sum of the Mo. Revenue column.",change:null,filterKey:null,color:"var(--clr-navy)",alertColor:null},{key:"last_invoice",label:"Last Invoice",icon:Be,value:y.formatCompact(t.lastFinalizedTotal),subValue:v?`billed ${v}`:"no invoice yet",tooltip:"Amount billed on the most recent finalized invoice, excluding balances carried forward from earlier invoices.",change:null,filterKey:null,color:"var(--clr-navy)",alertColor:null},{key:"new_line_items",label:"New Licenses",icon:Be,value:`${t.newLineItems.count}`,subValue:"customers with new products added",tooltip:null,change:null,filterKey:"new_line_items",color:"var(--clr-shell)",alertColor:t.newLineItems.count>0?"var(--clr-shell)":null},{key:"cost_increases",label:"License Increases",icon:rs,value:`${t.costIncreases.count}`,subValue:"customers with added seats or new pricing",tooltip:null,change:null,filterKey:"cost_increases",color:"#16a34a",alertColor:t.costIncreases.count>0?"#16a34a":null},{key:"cost_decreases",label:"License Decreases",icon:ns,value:`${t.costDecreases.count}`,subValue:"customers with removed seats or cancellations",tooltip:null,change:null,filterKey:"cost_decreases",color:"#dc2626",alertColor:t.costDecreases.count>0?"#dc2626":null}];return e.jsx("div",{className:"flex flex-wrap justify-center gap-2","data-testid":"draft-insight-cards",children:r.map(o=>{const l=o.icon,p=i===o.filterKey&&o.filterKey!==null,d=o.filterKey!==null;return e.jsxs("button",{type:"button","data-testid":`draft-card-${o.key}`,title:o.tooltip??void 0,className:`relative flex w-40 flex-col items-center justify-between px-3 py-2.5 rounded-lg transition-all text-center min-h-[80px] ${d?"cursor-pointer":"cursor-default"} ${p?"shadow-lg scale-[1.03] bg-white":"bg-white shadow-sm hover:shadow-md"}`,style:{borderTop:`4px solid ${o.alertColor||o.color}`,...p?{outline:`2px solid ${o.color}`,outlineOffset:"1px"}:{}},onClick:()=>{d&&c(p?null:o.filterKey)},children:[e.jsx(l,{className:"absolute left-2 top-2 h-3.5 w-3.5 flex-shrink-0",style:{color:o.alertColor||o.color}}),e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider leading-tight text-[var(--clr-ink-3)]",children:o.label.split(" ").map((b,x)=>e.jsx("span",{className:"block",children:b},x))}),e.jsx("span",{className:"text-lg font-bold leading-tight mt-0.5 tabular-nums",style:{color:o.alertColor||"var(--clr-navy)"},children:o.value}),e.jsx("span",{className:`text-[9px] text-[var(--clr-ink-3)] ${d||o.subValue?"":"invisible"}`,children:d?"click to filter":o.subValue||"click to filter"})]},o.key)})})}function Ms({onAdd:t,onRemove:i,onClearAll:c,activeFilters:h}){const[y,v]=a.useState(""),[r,o]=a.useState(!1),l=a.useRef(null),p=a.useRef(void 0),[d,b]=a.useState(null),[x,k]=a.useState(!1),{toast:A}=tt(),C=new Set(h.map(g=>g.productName)),D=g=>g.replace(/\s*\[New Commerce Experience\]/gi,""),u=[...h.map(g=>g.productName)].sort(),{data:m,isFetching:f,isError:$}=fe({queryKey:["/api/pax8/license-search/export",...u],queryFn:async()=>{const g=new URLSearchParams;for(const E of u)g.append("product",E);const T=await fetch(`/api/pax8/license-search/export?${g.toString()}`,{credentials:"include"});if(!T.ok)throw new Error(`Export request failed (${T.status})`);return T.json()},enabled:h.length>0,staleTime:3e5}),K=()=>
2{if($){A({title:"Export failed",description:"Couldn't prepare the CSV. Please try again.",variant:"destructive"});return}const g=m?.rows??[];if(g.length===0){A({title:"Nothing to export",description:"No licenses matched the current search."});return}const T=(I,V=2)=>I!=null?I.toFixed(V):"",H=[["Customer","License","Quantity","Pricing Tier","Mo. Unit Cost","Mo. Unit Price","Mo. Total Cost","Mo. Total Price","Margin %","Pricing Status"].map(ce).join(",")];for(const I of g)H.push([ce(I.customerName),ce(D(I.productName)),String(I.quantity??""),ce(I.pricingTier),T(I.monthlyUnitCost),T(I.monthlyUnitPrice),T(I.monthlyTotalCost),T(I.monthlyTotalPrice),I.margin!=null?I.margin.toFixed(1)+"%":"",I.pricingUnavailable?"Unavailable â encrypted pricing could not be read":"Complete"].join(","));const oe=H.join(` 3`),W=new Blob([oe],{type:"text/csv"}),se=URL.createObjectURL(W),te=document.createElement("a");te.href=se,te.download="license_search_export.csv",te.click(),URL.revokeObjectURL(se)};a.useEffect(()=>{function g(T){l.current&&!l.current.contains(T.target)&&o(!1)}return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const U=async g=>{if(g.length<2){b(null);return}k(!0);try{const T=await fetch(`/api/pax8/license-search?q=${encodeURIComponent(g)}`);if(T.ok){const E=await T.json();b(E)}}catch{}k(!1)},Q=g=>{v(g),p.current&&clearTimeout(p.current),g.length>=2?(o(!0),p.current=setTimeout(()=>U(g),300)):(o(!1),b(null))},M=g=>{C.has(g.productName)?i(g.productName):t(g.companyIds,g.productName),v(""),o(!1),b(null)},O=()=>{v(""),o(!1),b(null),c()};return e.jsxs("div",{ref:l,className:"relative flex-1","data-testid":"license-search",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Be,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--clr-ink-3)]"}),e.jsx("input",{type:"text","aria-label":"Search licenses",placeholder:h.length>0?"Add another license...":"Search licenses...",value:y,onChange:g=>Q(g.target.value),onFocus:()=>{y.length>=2&&o(!0)},className:"w-full h-8 pl-8 pr-8 border border-[var(--clr-rule)] rounded text-sm focus:outline-none focus:ring-2 focus:ring-[var(--clr-navy)]","data-testid":"input-search-licenses"}),(y||h.length>0)&&e.jsx("button",{onClick:O,className:"absolute right-2 top-1/2 -translate-y-1/2 text-[var(--clr-ink-3)] hover:text-[var(--clr-ink-2)]","data-testid":"btn-clear-license-search","aria-label":"Clear license search",children:e.jsx(we,{className:"h-3.5 w-3.5"})})]}),h.length>0&&e.jsxs("div",{className:"mt-1 flex items-center gap-1 flex-wrap",children:[e.jsxs("span",{className:"text-[10px] text-[var(--clr-ink-3)]",children:["License",h.length>1?"s":"",":"]}),h.map(g=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-[var(--clr-navy)] bg-[var(--clr-shell-100)] border border-[var(--clr-shell-300)] px-2 py-0.5 rounded-full max-w-[240px] truncate",children:[D(g.productName),e.jsx("button",{onClick:()=>i(g.productName),className:"hover:text-[var(--clr-shell)] ml-0.5 flex-shrink-0","aria-label":`Remove ${D(g.productName)}`,children:e.jsx(we,{className:"h-2.5 w-2.5"})})]},g.productName)),h.length>1&&e.jsx("button",{onClick:O,className:"text-[10px] text-[var(--clr-ink-3)] hover:text-[var(--clr-shell)] ml-1","data-testid":"btn-clear-all-licenses",children:"Clear all"}),e.jsxs("button",{onClick:K,disabled:f,className:"ml-auto flex-shrink-0 flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium bg-[var(--clr-navy)] text-white hover:bg-[var(--clr-navy-600)] transition-colors disabled:opacity-60","data-testid":"button-export-license-search",title:"Export searched licenses to CSV",children:[f?e.jsx(re,{className:"h-3 w-3 animate-spin"}):e.jsx(at,{className:"h-3 w-3"}),f?"Loading...":"Export CSV"]})]}),r&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-[var(--clr-rule)] rounded-lg shadow-lg max-h-72 overflow-y-auto",children:x?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(re,{className:"h-4 w-4 animate-spin text-[var(--clr-ink-3)]"})}):d&&d.products.length>0?d.products.map(g=>{const T=C.has(g.productName);return e.jsxs("button",{className:`w-full text-left px-3 py-2 hover:bg-[var(--clr-sky-050)] hover:text-[var(--clr-navy)] transition-colors border-b border-[var(--clr-rule)] last:border-0 ${T?"bg-[var(--clr-shell-100)]":""}`,onClick:()=>M(g),"data-testid":`license-suggestion-${g.productName}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[T&&e.jsx(ye,{className:"h-3 w-3 text-[var(--clr-shell)] flex-shrink-0"}),e.jsx("span",{className:"text-sm text-[var(--clr-navy)] truncate",children:D(g.productName)})]}),e.jsxs("div",{className:"text-[10px] text-[var(--clr-ink-3)]",children:[g.customerCount," customer",g.customerCount!==1?"s":""," · ",g.totalSeats," total seats"]})]},g.productName)}):d&&d.products.length===0?e.jsx("div",{className:"px-3 py-3 text-xs text-[var(--clr-ink-3)] text-center",children:"No licenses found"}):null})]})}function Rs(){const{currentAccount:t}=Fe(),i=We({accountCurrency:t?.displayCurrency??null,accountCountry:t?.country??null}),{data:c}=fe({queryKey:["/api/pax8/mrr/trends"],staleTime:300*1e3}),{hidden:h,toggle:y}=pt(),v=[{key:"total",label:"Total",color:Me.navy,variant:"area"},{key:"m365",label:"Microsoft 365",color:Me.green},{key:"azure",label:"Azure",color:Me.sky},{key:"other",label:"Other",color:Me.slate,dashed:!0}],r=x=>{const k=/^(\d{4})-(\d{2})$/.exec(x);return k?new Date(Number(k[1]),Number(k[2])-1,1).toLocaleDateString("en-US",{month:"short"}):x},o=x=>i.formatWhole(x),l=x=>{const k=/^(\d{4})-(\d{2})$/.exec(x);return k?new Date(Number(k[1]),Number(k[2])-1,1).toLocaleDateString("en-US",{month:"long",year:"numeric"}):x};if(!c||!c.overall.some(x=>x.m365+x.azure+x.other>0))return null;const p=c.overall.map(x=>({...x,total:Number((x.m365+x.azure+x.other).toFixed(2))})),d=p[p.length-1],b=d?h.has("total")?["m365","azure","other"].reduce((x,k)=>x+(h.has(k)?0:d[k]||0),0):d.total:0;return e.jsxs("div",{className:"border border-[var(--clr-rule)] rounded-lg bg-white shadow-sm px-3 py-2","data-testid":"chart-mrr-trend",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1 gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-[var(--clr-ink-2)]",children:"MRR â 12 month trend (all customers)"}),e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-[var(--clr-shell)]","data-testid":"text-mrr-data-source",children:"PAX8 INVOICE DATA"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ut,{series:v,hidden:h,onToggle:y,testIdPrefix:"chart-mrr-trend",testIdFor:x=>`button-mrr-series-${x}`}),e.jsxs("span",{className:"text-[10px] text-[var(--clr-ink-3)]","data-testid":"text-mrr-this-month",children:[o(b)," this month"]})]})]}),e.jsx("div",{style:{height:144},children:e.jsx(ht,{chartId:"mrrTrend",data:p,xKey:"month",series:v,hidden:h,xTickFormatter:r,xTooltipFormatter:l,yTickFormatter:x=>i.formatCompact(x),valueFormatter:x=>o(x)})})]})}function Ls({accountId:t,searchTerm:i,onSelect:c,onClear:h}
3){const[y,v]=a.useState(""),[r,o]=a.useState(""),[l,p]=a.useState(!1),d=a.useRef(null);a.useEffect(()=>{i&&!y&&v(i)},[i]),a.useEffect(()=>{function u(m){d.current&&!d.current.contains(m.target)&&p(!1)}return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[]),a.useEffect(()=>{const u=window.setTimeout(()=>o(y.trim()),200);return()=>window.clearTimeout(u)},[y]);const{data:b,isFetching:x}=fe({queryKey:["/api/pax8/customers/search",t,r],queryFn:async()=>{const u=new URLSearchParams({q:r});return(await ee("GET",`/api/pax8/customers/search?${u.toString()}`)).json()},enabled:!!t&&r.length>0&&!i,staleTime:300*1e3}),k=b?.names??[],A=u=>{v(u),p(!1),c(u)},C=()=>{v(""),p(!1),h()},D=u=>{v(u),p(u.length>0),u.length===0&&h()};return e.jsxs("div",{ref:d,className:"relative flex-1","data-testid":"customer-search",children:[e.jsxs("div",{className:"relative",children:[e.jsx(lt,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--clr-ink-3)]"}),e.jsx("input",{type:"text","aria-label":"Search customers",placeholder:"Search customers...",value:y,onChange:u=>D(u.target.value),onFocus:()=>{y.length>0&&!i&&p(!0)},className:"w-full h-8 pl-8 pr-8 border border-[var(--clr-rule)] rounded text-sm focus:outline-none focus:ring-2 focus:ring-[var(--clr-navy)]","data-testid":"input-search-customers"}),(y||i)&&e.jsx("button",{onClick:C,className:"absolute right-2 top-1/2 -translate-y-1/2 text-[var(--clr-ink-3)] hover:text-[var(--clr-ink-2)]","data-testid":"btn-clear-search","aria-label":"Clear search",children:e.jsx(we,{className:"h-3.5 w-3.5"})})]}),i&&e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-[var(--clr-ink-3)]",children:"Filtered to:"}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-[var(--clr-navy)] bg-[var(--clr-sky-050)] border border-[var(--clr-sky-300)] px-2 py-0.5 rounded-full",children:[i,e.jsx("button",{onClick:C,className:"hover:text-[var(--clr-shell)] ml-0.5","data-testid":"btn-remove-filter","aria-label":"Remove filter",children:e.jsx(we,{className:"h-2.5 w-2.5"})})]})]}),l&&k.length>0&&!i&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-[var(--clr-rule)] rounded-lg shadow-lg max-h-60 overflow-y-auto",children:k.map(u=>e.jsx("button",{className:"w-full text-left px-3 py-2 text-sm text-[var(--clr-navy)] hover:bg-[var(--clr-sky-050)] hover:text-[var(--clr-navy)] transition-colors",onClick:()=>A(u),"data-testid":`suggestion-${u}`,children:u},u))}),l&&k.length===0&&y.length>0&&!i&&!x&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-[var(--clr-rule)] rounded-lg shadow-lg px-3 py-3 text-xs text-[var(--clr-ink-3)] text-center",children:"No customers found"})]})}function Us(){const[t,i]=a.useState(!1);return e.jsx(R,{size:"sm",variant:"outline",className:"h-8 text-xs px-3 flex-shrink-0 relative z-10",disabled:t,onClick:async c=>{c.stopPropagation(),i(!0);try{const h=new Promise(y=>setTimeout(y,600));await Promise.all([xe.refetchQueries({queryKey:["/api/pax8/customers"]}),xe.refetchQueries({queryKey:["/api/pax8/tenant-map"]}),h])}finally{i(!1)}},"data-testid":"button-refresh-customer-list",children:t?e.jsxs(e.Fragment,{children:[e.jsx(re,{className:"h-3 w-3 mr-1.5 animate-spin"})," Refreshing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:"h-3 w-3 mr-1.5"})," Refresh"]})})}function Ha(){const{hasAccess:t}=ft(gt.STOREFRONT_MOCK_ORDERS,{platformAdminBypass:!1}),i=_t(),c=ve.useMemo(()=>Vt(typeof window<"u"?window.location.search:""),[i]),[h,y]=a.useState(()=>typeof window<"u"?window.location.hash:"");a.useEffect(()=>{if(typeof window>"u")return;const j=()=>y(window.location.hash),S=window;if(!S.__pax8HistoryPatched){const X=history.pushState.bind(history),he=history.replaceState.bind(history);history.pushState=function(...Ce){const Se=X(...Ce);return window.dispatchEvent(new Event("pax8:locationchange")),Se},history.replaceState=function(...Ce){const Se=he(...Ce);return window.dispatchEvent(new Event("pax8:locationchange")),Se},S.__pax8HistoryPatched=!0}return window.addEventListener("hashchange",j),window.addEventListener("popstate",j),window.addEventListener("pax8:locationchange",j),j(),()=>{window.removeEventListener("hashchange",j),window.removeEventListener("popstate",j),window.removeEventListener("pax8:locationchange",j)}},[]);const{focusCompanyId:v,focusInvoice:r}=ve.useMemo(()=>({focusCompanyId:new URLSearchParams(i).get("companyId"),focusInvoice:h==="#invoice"}),[i,h]),{currentAccount:o,isSuperAdmin:l}=Fe(),{toast:p}=tt(),[d,b]=a.useState(!1),[x,k]=a.useState(!1),[A,C]=a.useState(""),D=50,[u,m]=a.useState(0),[f,$]=a.useState(null),[K,U]=a.useState("desc"),[Q,M]=a.use
3State([]),[O,g]=a.useState(!1),[T,E]=a.useState(null),[H,oe]=a.useState(!0),[W,se]=a.useState(new Set),[te,I]=a.useState(!1),{data:V}=yt({refetchInterval:d?3e3:!1}),{data:w}=fe({queryKey:["/api/pax8/invoices/draft-summary"],enabled:V?.enabled===!0,staleTime:300*1e3,retry:1}),ae=ve.useMemo(()=>gs({currentPage:u,pageSize:D,sortKey:f,sortDir:K,searchTerm:A,hideZeroRevenue:H,licenseFilters:Q,draftFilter:T}),[u,f,K,A,H,Q,T]),{data:N,isLoading:P,isFetching:L,error:B,refetch:Z}=fe({queryKey:["/api/pax8/customers",ae,o?.id],queryFn:async()=>(await ee("POST","/api/pax8/customers/query",ae)).json(),enabled:!!o?.id&&V?.enabled===!0,staleTime:3e5,placeholderData:(j,S)=>hs(o?.id,j,S)}),n=Ze({mutationFn:async()=>{await ee("POST","/api/pax8/sync",{scope:"full"})},onSuccess:()=>{b(!0),k(!1),xe.invalidateQueries({queryKey:["/api/pax8/status"]})},onError:()=>{b(!1)}}),_=d||n.isPending,F=V?.syncStatus==="queued",ie=Ze({mutationFn:async()=>{await ee("POST","/api/pax8/sync/cancel",{})},onSuccess:()=>p({title:"Cancellation requested",description:"The sync will stop after the current batch completes."}),onError:j=>p({title:"Cancel failed",description:j?.message??"Unknown",variant:"destructive"})});a.useEffect(()=>{!d&&V?.syncStatus==="syncing"&&(b(!0),k(!0)),d&&V?.syncStatus==="syncing"&&k(!0),d&&x&&V?.syncStatus==="idle"&&(b(!1),k(!1),xe.invalidateQueries({queryKey:["/api/pax8/customers"]}),xe.invalidateQueries({queryKey:["/api/pax8/invoices/draft-summary"]}))},[d,x,V?.syncStatus]),a.useEffect(()=>{xe.invalidateQueries({queryKey:["/api/pax8/tenant-map"]})},[]);const ge=V?.lastCompaniesSyncAt||V?.lastSyncAt,z=N?.totals,Y=N?.customers??[],s=N?.totalCount??0,q=Math.ceil(s/D),pe=ve.useMemo(()=>[...Y.map(j=>j.id),...W],[Y,W]),{data:ue}=Ts(pe),le=ve.useMemo(()=>{const j=new Map;for(const S of Y)S.kpiCategories?.length&&j.set(S.id,new Set(S.kpiCategories));return j},[Y]);a.useEffect(()=>{m(0),se(new Set)},[A,Q,T,H,f,K]),a.useEffect(()=>{if(!v)return;let j=!1;return ee("POST","/api/pax8/customers/position",{...ae,page:0,companyId:v}).then(S=>S.json()).then(S=>{!j&&typeof S.page=="number"&&m(S.page)}).catch(()=>{}),()=>{j=!0}},[v,f,K,A,H,Q,T]),a.useEffect(()=>{q>0&&u>q-1&&m(q-1)},[q,u]);const ke=j=>{f===j?U(K==="asc"?"desc":"asc"):($(j),U(j==="tenant"||j==="name"?"asc":"desc"))},ne=({k:j,label:S,align:X})=>{const he=f===j,Ce=X==="right"?"justify-end":X==="center"?"justify-center":"justify-start";return e.jsxs("button",{type:"button","data-testid":`sort-${j}`,onClick:()=>ke(j),className:`px-3 py-1.5 flex items-center gap-1 ${Ce} hover:bg-[#2d5070] transition-colors w-full h-full text-white uppercase tracking-wider text-[10px] font-semibold`,children:[e.jsx("span",{children:S}),he?K==="asc"?e.jsx(as,{className:"h-3 w-3"}):e.jsx(Je,{className:"h-3 w-3"}):e.jsx(Je,{className:"h-3 w-3 opacity-30"})]})};return e.jsx(jt,{children:e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--clr-navy)]",children:"Pax8 Customers"}),e.jsx(zt,{}),e.jsx(bt,{kind:"customer"})]}),e.jsx("p",{className:"text-xs text-[var(--clr-ink-3)]",children:"Click a customer to load their subscriptions on demand"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{accountCurrency:o?.displayCurrency??null,accountCountry:o?.country??null}),e.jsx("span",{className:`text-xs ${Ht(ge||null)?"text-[var(--clr-shell)]":"text-[var(--clr-ink-3)]"}`,"data-testid":"text-last-synced",children:Gt(ge||null)}),l&&e.jsx(R,{size:"sm",className:"h-7 text-xs px-3 bg-[var(--clr-shell)] hover:bg-[var(--clr-shell-700)] text-white",onClick:()=>n.mutate(),disabled:_||n.isPending,"data-testid":"button-refresh-customers",children:_?e.jsxs(e.Fragment,{children:[e.jsx(re,{className:"h-3 w-3 mr-1.5 animate-spin"})," Syncing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:"h-3 w-3 mr-1.5"})," Sync PAX8"]})}),F&&e.jsx("span",{className:"text-xs font-medium text-[var(--clr-ink-3)] rounded-full bg-[var(--clr-ink-1)]/5 px-2 py-0.5","data-testid":"badge-sync-queued",children:"Queued"}),l&&(_||F)&&e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 text-xs px-3 rounded",onClick:()=>ie.mutate(),disabled:ie.isPending,"data-testid":"button-cancel-sync",children:[ie.isPending?e.jsx(re,{className:"h-3 w-3 mr-1.5 animate-spin"}):e.jsx(we,{className:"h-3 w-3 mr-1.5"}),"Cancel"]}),e.jsxs(R,{size:"sm",className:"h-7 text-xs px-3 bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:()=>g(!0),"data-testid":"button-add-customer",children:[e.jsx(Ye,{className:"h-3 w-3 mr-1.5"})," Add Customer"]})]})]}),e.jsx(Kt,{}),e.jsx(Fs,{summary:w,activeFilter:T,onFilter:j=>{E(j),j&&oe(!1)}}),c&&(/pending verification/i.test(c.title)?e.jsxs(Pe,{role:"status",className:"border-amber-300 bg-amber-50 text-amber-950","data-testid":"alert-pax8-consent-pending-verification",children:[e.jsx(je,{className:"h-4 w-4 text-amber-700"}),e.jsxs($e,{children:[e.jsx("strong",{className:"block",children:c.title}),c.explanation," ",c.suggestion]})]}):e.jsx(Qt,{error:c,testId:"alert-pax8-consent-error"})),V?.syncStatus==="error"&&V?.syncError&&e.jsxs(Pe,{variant:"destructive",className:"py-2",children:[e.jsx(je,{className:"h-3 w-3"}),e.jsx($e,{className:"text-xs",children:V.syncError})]}),N&&L&&e.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center gap-2 text-xs text-[var(--clr-ink-3)]","data-testid":"customers-refreshing",children:[e.jsx(re,{"aria-hidden":"true",className:"h-3 w-3 animate-spin"}),"Refreshing customersâ¦"]}),N&&B&&!L&&e.jsxs(Pe,{variant:"destructive","data-testid":"customers-refresh-error",children:[e.jsx(je,{className:"h-3 w-3"}),e.jsxs($e,{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{children:"Could not refresh customers. Showing the last loaded results."}),e.jsx(R,{size:"sm",variant:"outline",onClick:()=>{Z()},children:"Retry"})]})]}),P?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(re,{className:"h-6 w-6 animate-spin text-[var(--clr-ink-3)]"})}):B&&!N?e.jsxs(Pe,{variant:"destructive",children:[e.jsx(je,{className:"h-3 w-3"}),e.jsxs($e,{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{children:"Failed to load customer data."}),e.jsx(R,{size:"sm",variant:"outline",onClick:()=>{Z()},children:"Retry"})]})]}):N?.hasVisibleCustomers===!1?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ue,{className:"h-8 w-8 text-[var(--clr-ink-3)] mb-2"}),e.jsx("p",{className:"text-sm font-medium text-[var(--clr-ink-2)] mb-1",children:"No PAX8 data available"}),e.jsx("p",{className:"text-xs text-[var(--clr-ink-3)] mb-3",children:l?"Click Refresh to sync your customer list.":"No data has been synced yet. A super-admin can run a sync."}),l&&e.jsxs(R,{size:"sm",className:"h-7 text-xs",onClick:()=>n.mutate(),disabled:_,"data-testid":"button-initial-sync",children:[e.jsx(Ee,{className:"h-3 w-3 mr-1"})," Sync Now"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{}),z&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ls,{accountId:o?.id??null,searchTerm:A,onSelect:j=>C(j),onClear:()=>C("")}),e.jsx(Ms,{activeFilters:Q,onAdd:(j,S)=>M(X=>[...X.filter(he=>he.productName!==S),{companyIds:j,productName:S}]),onRemove:j=>M(S=>S.filter(X=>X.productName!==j)),onClearAll:()=>M([])}),e.jsx(Us,{}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-[var(--clr-navy)] cursor-pointer select-none flex-shrink-0 whitespace-nowrap","data-testid":"label-filter-zero-revenue",children:[e.jsx(Ne,{checked:H,onCheckedChange:j=>oe(j===!0),"data-testid":"checkbox-filter-zero-revenue","aria-label":"Filter $0 Clients"}),"Filter $0 Clients"]})]}),T&&e.jsxs("div",{className:"flex items-center gap-2","data-testid":"draft-filter-indicator",children:[e.jsxs("span",{className:"text-[11px] text-[var(--clr-ink-2)]",children:["Showing ",e.jsx("span",{className:"font-semibold",children:s})," filtered customer",s!==1?"s":"",T==="cost_increases"&&" with cost increases",T==="new_line_items"&&" with new line items",T==="cost_decreases"&&" with cost decreases"]}),e.jsxs("button",{"data-testid":"button-clear-draft-filter",className:"inline-flex items-center gap-1 text-[10px] font-semibold text-[var(--clr-navy)] bg-[var(--clr-sky-050)] border border-[var(--clr-sky-300)] px-2 py-0.5 rounded-full hover:bg-[var(--clr-sky-050)] transition-colors",onClick:()=>E(null),children:["Show All",e.jsx(we,{className:"h-2.5 w-2.5"})]})]})]}),W.size>0&&e.jsxs("div",{"data-testid":"bar-bulk-selection",className:"sticky top-0 z-20 flex items-center justify-between gap-3 px-4 py-2 mb-2 bg-[var(--clr-sky-050)] border border-[var(--clr-sky-300)] rounded-md shadow-sm",children:[e.jsxs("div",{className:"text-sm text-[var(--clr-navy)]",children:[e.jsx("span",{"data-testid":"text-bulk-selection-count",className:"font-semibold",children:W.size}),e.jsx("span",{children:" selected"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{"data-testid":"button-bulk-clear",variant:"ghost",size:"sm",onClick:()=>se(new Set),children:"Clear"}),e.jsx(R,{"data-testid":"button-bulk-edit-defaults",size:"sm",className:"bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",onClick:()=>I(!0),children:"Bulk edit defaults"})]})]}),e.jsxs("div",{className:"border border-[var(--clr-rule)] rounded-lg overflow-hidden bg-white shadow-sm",children:[e.jsxs("div",{className:"grid bg-[var(--clr-navy)] text-white text-[10px] font-semibold uppercase tracking-wider",style:{gridTemplateColumns:"36px 1fr 110px 120px 130px 110px 80px 90px 50px"},children:[e.jsx("div",{className:"flex items-center justify-center",onClick:j=>j.stopPropagation(),children:e.jsx(Ne,{"data-testid":"checkbox-bulk-select-all","aria-label":"Select all customers",checked:s>0&&W.size===s,onCheckedChange:async j=>{if(j!==!0){se(new Set);return}try{const X=await(await ee("POST","/api/pax8/customers/selection",ae)).json();
3se(new Set(X.ids??[]))}catch(S){p({title:"Unable to select all customers",description:S?.message??"Narrow the filters and try again.",variant:"destructive"})}}})}),e.jsx(ne,{k:"name",label:"Customer",align:"left"}),e.jsx(ne,{k:"moCost",label:"Mo. Cost",align:"right"}),e.jsx(ne,{k:"moPrice",label:"Mo. Revenue",align:"right"}),e.jsx(ne,{k:"lastInvoice",label:"Last Invoice",align:"right"}),e.jsx(ne,{k:"annual",label:"Annual Revenue",align:"right"}),e.jsx(ne,{k:"margin",label:"Margin",align:"right"}),e.jsx(ne,{k:"tenant",label:"Tenant",align:"center"}),e.jsx("div",{"aria-hidden":"true"})]}),Y.map((j,S)=>e.jsx(Es,{customer:j,index:u*D+S,draftFlags:le.get(j.id),licenseFilterNames:Q.map(X=>X.productName),autoExpand:v===j.id,autoExpandInvoice:v===j.id&&!!r,selected:W.has(j.id),onToggleSelect:(X,he)=>se(Ce=>{const Se=new Set(Ce);return he?Se.add(X):Se.delete(X),Se}),allowMock:t,readiness:ue?.readiness?.[j.id]},j.id)),s===0&&(A||Q.length>0||T||H)&&e.jsx("div",{className:"py-6 text-center text-xs text-[var(--clr-ink-3)]",children:T?"No customers match the selected filter":Q.length>0?"No customers match the selected license filters":A?`No customers match "${A}"`:"No customers with revenue above $0"}),s===0&&!A&&Q.length===0&&!T&&!H&&e.jsx("div",{className:"py-10 text-center text-sm text-[var(--clr-ink-3)]",children:o?.role==="account_manager"||o?.role==="viewer"?"No customers assigned to you yet. Ask an admin to assign customers to you in Settings â Users.":"No customers found."}),q>1&&e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("span",{className:"text-xs text-[var(--clr-ink-3)]",children:["Showing ",u*D+1,"â",Math.min((u+1)*D,s)," of ",s]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(R,{variant:"outline",size:"sm",className:"h-7 text-xs px-2",disabled:u===0,onClick:()=>m(j=>j-1),"data-testid":"button-prev-page",children:"Previous"}),Array.from({length:Math.min(q,7)},(j,S)=>{let X;return q<=7||u<3?X=S:u>q-4?X=q-7+S:X=u-3+S,e.jsx(R,{variant:X===u?"default":"outline",size:"sm",className:`h-7 w-7 text-xs p-0 ${X===u?"bg-[var(--clr-navy)] hover:bg-[var(--clr-navy)]":""}`,onClick:()=>m(X),"data-testid":`button-page-${X}`,children:X+1},X)}),e.jsx(R,{variant:"outline",size:"sm",className:"h-7 text-xs px-2",disabled:u>=q-1,onClick:()=>m(j=>j+1),"data-testid":"button-next-page",children:"Next"})]})]})]})]}),e.jsx(qe,{open:O,onOpenChange:g,children:e.jsxs(Ke,{className:"max-w-lg",children:[e.jsx(ze,{children:e.jsxs(_e,{className:"text-[var(--clr-navy)] flex items-center gap-2",children:[e.jsx(Ye,{className:"h-5 w-5"}),"Add PAX8 Customer"]})}),e.jsx(fs,{onSuccess:()=>{xe.invalidateQueries({queryKey:["/api/pax8/customers"]})},onCancel:()=>g(!1)})]})}),e.jsx(Os,{open:te,onOpenChange:I,selectedCustomers:(()=>{const j=new Map((N?.customers??[]).map(S=>[S.id,S.name]));return Array.from(W).map(S=>({id:S,name:j.get(S)??S,tosAccepted:!!ue?.readiness?.[S]?.partnerTosAccepted}))})(),onApplied:()=>{xe.invalidateQueries({queryKey:["/api/pax8/customer-readiness"]}),xe.invalidateQueries({queryKey:["/api/pax8/customers"]}),se(new Set)}})]})})}function Os({open:t,onOpenChange:i,selectedCustomers:c,onApplied:h}){const[y,v]=a.useState("contact"),[r,o]=a.useState({Admin:"",Billing:"",Technical:""}),[l,p]=a.useState(!1),[d,b]=a.useState(null),[x,k]=a.useState(!1),[A,C]=a.useState(!1),[D,u]=a.useState(null),[m,f]=a.useState(null),[$,K]=a.useState(!1),[U,Q]=a.use
3State(null),M=ve.useMemo(()=>c.map(w=>w.id),[c]),O=M.join(","),g=c.length>0&&c.every(w=>w.tosAccepted),T=c.length>0&&c.every(w=>!w.tosAccepted),E=c.length>0&&!g&&!T;ve.useEffect(()=>{if(!t){b(null),u(null),o({Admin:"",Billing:"",Technical:""}),f(null),Q(null);return}p(g)},[t,g]),ve.useEffect(()=>{if(!t||M.length===0)return;let w=!1;return K(!0),Q(null),(async()=>{try{const N=await(await ee("POST","/api/pax8/customers/contacts-for-selected",{customerIds:M})).json();w||f(N)}catch(ae){w||Q(ae?.message||"Failed to load contacts")}finally{w||K(!1)}})(),()=>{w=!0}},[t,O]);const H=ve.useMemo(()=>{if(y==="tos")return{kind:"tos",accepted:l};const w={};return r.Admin&&(w.Admin=r.Admin),r.Billing&&(w.Billing=r.Billing),r.Technical&&(w.Technical=r.Technical),!w.Admin&&!w.Billing&&!w.Technical?null:{kind:"contact",assignments:w}},[y,r,l]),oe=E||l!==g;async function W(w){return await(await ee("POST","/api/pax8/customers/bulk-order-defaults",{customerIds:M,dryRun:w,update:H})).json()}async function se(){if(H){k(!0),u(null);try{const w=await W(!0);b(w)}catch(w){u(w?.message||"Preview failed")}finally{k(!1)}}}async function te(){if(H){C(!0),u(null);try{const w=await W(!1);b(w),h()}catch(w){u(w?.message||"Apply failed")}finally{C(!1)}}}function I(w,ae){o(N=>({...N,[w]:ae})),b(null)}function V(w){const ae=(m?.contacts??[]).filter(P=>P.roles[w]>0),N=r[w];return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-24 shrink-0 text-sm font-medium text-[var(--clr-navy)]",children:w}),e.jsx("div",{className:"flex-1",children:e.jsxs("select",{"data-testid":`select-contact-${w.toLowerCase()}`,className:"w-full border border-[var(--clr-rule)] rounded-md px-2 py-1.5 text-sm bg-white",value:N,onChange:P=>I(w,P.target.value),disabled:$,children:[e.jsx("option",{value:"",children:$?"Loading contactsâ¦":ae.length===0?"No contacts with this role on the selected customers":"â Don't change â"}),ae.map(P=>e.jsxs("option",{value:P.email,children:[`${P.firstName} ${P.lastName}`.trim()||P.email," â ",P.email,c.length>1?` (on ${P.roles[w]}/${c.length})`:""]},P.email))]})})]},w)}return e.jsx(qe,{open:t,onOpenChange:i,children:e.jsxs(Ke,{className:"max-w-2xl","data-testid":"dialog-bulk-edit-defaults",children:[e.jsx(ze,{children:e.jsxs(_e,{className:"text-[var(--clr-navy)]",children:["Bulk edit order defaults â ",c.length," customer",c.length===1?"":"s"]})}),e.jsx("div",{className:"flex gap-2 border-b border-[var(--clr-rule)] mb-4",children:["contact","tos"].map(w=>e.jsx("button",{"data-testid":`tab-bulk-${w}`,type:"button",onClick:()=>{v(w),b(null)},className:`px-3 py-1.5 text-sm font-medium border-b-2 -mb-px transition-colors ${y===w?"border-[var(--clr-navy)] text-[var(--clr-navy)]":"border-transparent text-[var(--clr-ink-3)] hover:text-[var(--clr-navy)]"}`,children:w==="contact"?"Default contact":"Accept partner ToS"},w))}),y==="contact"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-[11px] text-[var(--clr-ink-3)]",children:"Pick a contact for each role you want to set. Roles you leave blank are not changed. Each customer is only updated for a role if a contact with that email already exists on that customer under that role."}),U&&e.jsx(Pe,{className:"border-[var(--clr-shell-300)] bg-[var(--clr-shell-100)]",children:e.jsx($e,{className:"text-[var(--clr-shell-700)] text-xs",children:U})}),m?.partial&&!U&&e.jsx(Pe,{className:"border-[var(--clr-shell-300)] bg-[var(--clr-shell-100)]",children:e.jsxs($e,{className:"text-[var(--clr-shell-700)] text-xs",children:["Couldn't load contacts for ",m.failedCustomers," of ",m.totalCustomers," ","selected customers. Their contacts may not appear in the dropdown."]})}),e.jsxs("div",{className:"space-y-2",children:[V("Admin"),V("Billing"),V("Technical")]})]}),y==="tos"&&e.jsx("div",{className:"text-sm text-[var(--clr-navy)] space-y-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ne,{id:"checkbox-tos-accepted","data-testid":"checkbox-tos-accepted",checked:l,onCheckedChange:w=>{p(w===!0),b(null)}}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{htmlFor:"checkbox-tos-accepted",className:"text-sm font-medium cursor-pointer",children:"Partner Terms of Service accepted"}),e.jsx("p",{className:"text-[11px] text-[var(--clr-ink-3)] mt-1",children:"Checked: record acceptance on every selected customer with a linked Microsoft Tenant ID. Unchecked: clear any previously recorded acceptance for those customers. Customers without a linked tenant are listed as skipped."}),E&&e.jsx("p",{className:"text-[11px] text-[var(--clr-shell-700)] mt-1","data-testid":"text-tos-mixed-hint",children:"Mixed selection â some of these customers already have ToS accepted and some don't."})]})]})}),D&&e.jsx(Pe,{className:"mt-3 border-[var(--clr-shell-300)] bg-[var(--clr-shell-100)]",children:e.jsx($e,{className:"text-[var(--clr-shell-700)] text-xs","data-testid":"text-bulk-error",children:D})}),d&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3 text-xs",children:[e.jsxs("div",{className:"border border-[var(--clr-moss-300)] bg-[var(--clr-moss-100)] rounded-md p-2",children:[e.jsxs("div",{className:"font-semibold text-[var(--clr-moss-700)] mb-1",children:["Will change"," ",e.jsx("span",{"data-testid":"text-bulk-preview-changed-count",children:d.changed.length})]}),e.jsxs("ul",{className:"max-h-40 overflow-auto space-y-0.5",children:[d.changed.map(w=>e.jsx("li",{className:"truncate","data-testid":`row-bulk-changed-${w.id}`,children:w.name},w.id)),d.changed.length===0&&e.jsx("li",{className:"text-[var(--clr-ink-3)]",children:"None"})]})]}),e.jsxs("div",{className:"border border-[var(--clr-shell-300)] bg-[var(--clr-shell-100)] rounded-md p-2",children:[e.jsxs("div",{className:"font-semibold text-[var(--clr-shell-700)] mb-1",children:["Skipped"," ",e.jsx("span",{"data-testid":"text-bulk-preview-skipped-count",children:d.skipped.length})]}),e.jsxs("ul",{className:"max-h-40 overflow-auto space-y-0.5",children:[d.skipped.map(w=>e.jsxs("li",{className:"truncate","data-testid":`row-bulk-skipped-${w.id}`,children:[e.jsx("span",{className:"font-medium",children:w.name}),e.jsxs("span",{className:"text-[var(--clr-ink-2)]",children:[" â ",w.reason]})]},w.id)),d.skipped.length===0&&e.jsx("li",{className:"text-[var(--clr-ink-3)]",children:"None"})]})]})]}),e.jsxs(He,{className:"mt-4",children:[e.jsx(R,{variant:"outline","data-testid":"button-bulk-close",onClick:()=>i(!1),children:"Close"}),e.jsx(R,{variant:"outline","data-testid":"button-bulk-preview",disabled:!H||x||A||M.length===0||y==="tos"&&!oe,onClick:se,children:x?"Previewingâ¦":"Preview"}),e.jsx(R,{"data-testid":"button-bulk-apply",className:"bg-[var(--clr-navy)] hover:bg-[var(--clr-navy-600)] text-white",disabled:!H||A||x||M.length===0||y==="tos"&&!oe||d?.dryRun===!1,onClick:te,children:A?"Applyingâ¦":d?.dryRun===!1?"Applied":"Ap
3ply"})]})]})})}export{Es as CustomerRow,Ss as OrderDefaultsSection,js as buildCustomerProductsCsv,gs as buildPax8CustomersQueryParams,Ha as default,et as formatMoneyCell};
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.