PageSourceSearch

https://workspace.mind-verse.de/_next/static/chunks/5858-e6c2a9297a2df32a.js

js mind-verse.de collected 2026-10-03 20:35:52 UTC 197,715 bytes, 2 lines download raw bytes

1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="01a0fc07-1e93-73b2-95d6-50f8b9c62611")}catch(e){}}();"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[5858],{3110:(e,s,t)=>{t.d(s,{k:()=>E});var a=t(68987),n=t(42725),r=t(2315),i=t(22707),l=t(87809),o=t(57934),d=t(44410),c=t(36037),u=t(24688),m=t(94499),h=t(29146),p=t(34451),x=t(55264),y=t(44991),g=t(25069),f=t(91541),j=t(99834),b=t(47747);let v={normal:"Normal",big:"Big",large:"Large",xl:"XL"};function N(e){return Math.round(e).toLocaleString("en-US")}function C(e){return null==e?"—":e>=1e3?`${e/1e3}k`:String(e)}function E({section:e="pricing"}={}){let s=(0,n.t0)(),t=(0,n.WD)(),[h,p]=(0,r.useState)(null),[w,S]=(0,r.useState)(null),[T,k]=(0,r.useState)(!0),[D,I]=(0,r.useState)(!1),P=(0,r.useCallback)(async()=>{try{let[e,s]=await Promise.all([fetch("/api/admin/credit-system"),fetch("/api/admin/integration-drift")]);if(!e.ok)throw Error("Failed to fetch credit system");let t=await e.json();if(p(t.creditSystem??null),s.ok){let e=await s.json();S(e.data??e??null)}}catch(e){j.logger.error("Error fetching credit system:",{error:e instanceof Error?e.message:String(e)})}finally{k(!1),I(!1)}},[]);if((0,r.useEffect)(()=>{P()},[P]),T)return(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsx)(f.E,{className:"h-40 w-full"}),(0,a.jsx)(f.E,{className:"h-56 w-full"}),(0,a.jsx)(f.E,{className:"h-40 w-full"})]});if(!h)return(0,a.jsx)(g.Card,{children:(0,a.jsx)(g.CardContent,{className:"py-large text-center text-body text-muted-foreground",children:s.noCreditSystemConfigurationFound})});let{tiers:_,llm:O,generation:R,integrations:L,planAccess:F,settlementNote:M}=h,U={normal:`≤ ${C(O.thresholds.normal)}`,big:`≤ ${C(O.thresholds.big)}`,large:`≤ ${C(O.thresholds.large)}`,xl:`> ${C(O.thresholds.large)}`};return(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"flex-between gap-body",children:[(0,a.jsx)("p",{className:"text-body text-muted-foreground min-w-0",children:s.howCreditsApplyPerTierFor}),(0,a.jsxs)(y.$,{variant:"outline",size:"small",onClick:()=>{I(!0),P()},disabled:D,children:[(0,a.jsx)(i.A,{className:`icon-body ${D?"animate-spin":""}`}),"Refresh"]})]}),"pricing"===e&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(g.Card,{children:[(0,a.jsxs)(g.CardHeader,{children:[(0,a.jsx)(g.CardTitle,{className:"text-body",children:"Tiers"}),(0,a.jsx)(g.CardDescription,{children:s.eachModelLlmAndImageVideo})]}),(0,a.jsx)(g.CardContent,{className:"overflow-x-auto",children:(0,a.jsxs)("table",{className:"w-full text-body",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"border-b border-border text-left text-small text-muted-foreground",children:[(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Tier"}),(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Name"}),(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Description"}),(0,a.jsx)("th",{className:"py-small pr-body font-medium text-right",children:s.llmModels}),(0,a.jsx)("th",{className:"py-small font-medium text-right",children:s.imageVideoModels})]})}),(0,a.jsx)("tbody",{children:_.map(e=>(0,a.jsxs)("tr",{className:"border-b border-border/50",children:[(0,a.jsx)("td",{className:"py-body pr-body",children:(0,a.jsx)(b.y,{tierId:e.id})}),(0,a.jsx)("td",{className:"py-body pr-body font-medium",children:e.name}),(0,a.jsx)("td",{className:"py-body pr-body text-muted-foreground",children:e.description||"—"}),(0,a.jsx)("td",{className:"py-body pr-body text-right tabular-nums",children:e.llmCount}),(0,a.jsx)("td",{className:"py-body text-right tabular-nums",children:e.generativeCount})]},e.id))})]})})]}),(0,a.jsxs)(g.Card,{children:[(0,a.jsxs)(g.CardHeader,{children:[(0,a.jsxs)(g.CardTitle,{className:"text-body flex items-center gap-body",children:[(0,a.jsx)(l.A,{className:"icon-body"}),s.llmCreditsByContextSize]}),(0,a.jsxs)(g.CardDescription,{children:[s.creditsByContextCellDesc," ",(0,a.jsx)("span",{className:"font-mono",children:s.inputTokensRate})," ",s.creditsByContextBucketsDesc]})]}),(0,a.jsx)(g.CardContent,{className:"overflow-x-auto",children:(0,a.jsxs)("table",{className:"w-full text-body",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"border-b border-border text-left text-small text-muted-foreground",children:[(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Tier"}),O.buckets.map(e=>(0,a.jsxs)("th",{className:"py-small px-body font-medium text-right",children:[(0,a.jsx)("div",{children:v[e]}),(0,a.jsxs)("div",{className:"font-normal",children:[U[e]," tok"]})]},e))]})}),(0,a.jsx)("tbody",{children:_.map(e=>{let s=O.rates[String(e.id)]??{};return(0,a.jsxs)("tr",{className:"border-b border-border/50",children:[(0,a.jsx)("td",{className:"py-body pr-body",children:(0,a.jsx)(b.y,{tierId:e.id,tierName:e.name})}),O.buckets.map(e=>(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=s[e]?N(s[e]):"—"},e))]},e.id)})})]})})]}),(0,a.jsxs)(g.Card,{children:[(0,a.jsxs)(g.CardHeader,{children:[(0,a.jsxs)(g.CardTitle,{className:"text-body flex items-center gap-body",children:[(0,a.jsx)(o.A,{className:"icon-body"}),s.imageVideoCreditsByGeneration]}),(0,a.jsx)(g.CardDescription,{children:s.flatCreditsPerUnitOfGeneration})]}),(0,a.jsxs)(g.CardContent,{className:"overflow-x-auto",children:[(0,a.jsxs)("table",{className:"w-full text-body",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"border-b border-border text-left text-small text-muted-foreground",children:[(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Tier"}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:s.creditsImage}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:s.creditsVideoSecond})]})}),(0,a.jsx)("tbody",{children:_.map(e=>(0,a.jsxs)("tr",{className:"border-b border-border/50",children:[(0,a.jsx)("td",{className:"py-body pr-body",children:(0,a.jsx)(b.y,{tierId:e.id,tierName:e.name})}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=R.image[String(e.id)]?N(R.image[String(e.id)]):"—"}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=R.video[String(e.id)]?N(R.video[String(e.id)]):"—"})]},e.id))})]}),(0,a.jsxs)("p",{className:"mt-body text-small text-muted-foreground",children:[s.transcription," ",null!=R.transcriptionPerMinute?t("settings.creditPerMinute",{count:N(R.transcriptionPerMinute)}):"—"," ",s.allTiersSingleModelToday]})]})]})]}),"integrations"===e&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(g.Card,{children:[(0,a.jsxs)(g.CardHeader,{children:[(0,a.jsxs)(g.CardTitle,{className:"text-body flex items-center gap-body",children:[(0,a.jsx)(d.A,{className:"icon-body"}),s.integrationsTokenCost]}),(0,a.jsx)(g.CardDescription,{children:s.integrationsDonAposTHaveTheir})]}),(0,a.jsxs)(g.CardContent,{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"flex items-baseline gap-body",children:[(0,a.jsx)("span",{className:"text-heading font-semibold tabular-nums",children:null!=L.defaultAvgTokens?N(L.defaultAvgTokens):"—"}),(0,a.jsx)("span",{className:"text-body text-muted-foreground",children:s.defaultTokensPerIntegrationCall})]}),w&&w.summary.total>0&&(0,a.jsxs)("div",{className:"flex items-center gap-body text-small",children:[(0,a.jsx)("span",{className:"text-muted-foreground",children:t("settings.activity7dEndpoints",{count:w.summary.total})}),w.summary.accurate>0&&(0,a.jsxs)(x.E,{variant:"success",size:"small",children:[w.summary.accurate," accurate"]}),w.summary.drifting>0&&(0,a.jsxs)(x.E,{variant:"warning",size:"small",children:[w.summary.drifting," drifting"]}),w.summary.uncalibrated>0&&(0,a.jsxs)(x.E,{variant:"secondary",size:"small",children:[w.summary.uncalibrated," uncalibrated"]})]}),w&&w.endpoints.length>0?(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)("table",{className:"w-full text-body",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"border-b border-border text-left text-small text-muted-foreground",children:[(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Endpoint"}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:s.calls7d}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:s.avgSession}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:"Configured"}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:s.avgEstimated}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:s.avgActual}),(0,a.jsx)("th",{className:"py-small px-body font-medium text-right",children:"Drift"}),(0,a.jsx)("th",{className:"py-small pl-body font-medium",children:"Status"})]})}),(0,a.jsx)("tbody",{children:w.endpoints.map(e=>(0,a.jsxs)("tr",{className:"border-b border-border/50",children:[(0,a.jsxs)("td",{className:"py-body pr-body",children:[(0,a.jsx)("span",{className:"font-mono text-small",children:e.endpoint}),e.hasOverride&&(0,a.jsx)("span",{className:"ml-small text-mini text-muted-foreground",children:s.override})]}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:N(e.callCount7d)}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=e.avgCallsPerSession?e.avgCallsPerSession.toFixed(1):"—"}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=e.configuredTokens?N(e.configuredTokens):"—"}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=e.avgEstimatedTokens?N(e.avgEstimatedTokens):"—"}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=e.avgActualTokens?N(e.avgActualTokens):"—"}),(0,a.jsx)("td",{className:"py-body px-body text-right tabular-nums",children:null!=e.driftPct?(0,a.jsxs)("span",{className:"critical"===e.status?"text-destructive font-medium":"warning"===e.status?"text-amber-600 font-medium":"",children:[null!=e.driftRatio&&e.driftRatio<1?"−":"+",e.driftPct,"%"]}):"—"}),(0,a.jsx)("td",{className:"py-body pl-body",children:(0,a.jsx)(A,{status:e.status})})]},e.endpoint))})]})}):(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:s.noIntegrationCallsRecordedInThe})]})]}),w&&w.patterns.length>0&&(0,a.jsxs)(g.Card,{children:[(0,a.jsxs)(g.CardHeader,{children:[(0,a.jsxs)(g.CardTitle,{className:"text-body flex items-center gap-body",children:[(0,a.jsx)(d.A,{className:"icon-body"}),s.integrationCallPatterns7d]}),(0,a.jsx)(g.CardDescription,{children:s.top3MostCommonToolCall})]}),(0,a.jsx)(g.CardContent,{className:"space-y-body",children:w.patterns.map(e=>(0,a.jsxs)("div",{className:"space-y-small",children:[(0,a.jsxs)("div",{className:"flex items-baseline gap-body",children:[(0,a.jsx)("span",{className:"font-mono text-body font-medium",children:e.slug}),(0,a.jsxs)("span",{className:"text-small text-muted-foreground",children:[e.totalSessions," sessions"]})]}),(0,a.jsx)("div",{className:"pl-body space-y-small",children:e.topPatterns.map((e,s)=>(0,a.jsxs)("div",{className:"flex items-start gap-body text-small",children:[(0,a.jsxs)("span",{className:"text-muted-foreground tabular-nums shrink-0",children:["#",s+1]}),(0,a.jsx)("span",{className:"font-mono text-mini leading-relaxed break-all",children:e.sequence.join(" → ")}),(0,a.jsxs)("span",{className:"text-muted-foreground tabular-nums shrink-0 ml-auto",children:[e.sessionCount,"\xd7"]})]},e.sequence.join("→")))})]},e.slug))})]})]}),"pricing"===e&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(g.Card,{children:[(0,a.jsxs)(g.CardHeader,{children:[(0,a.jsxs)(g.CardTitle,{className:"text-body flex items-center gap-body",children:[(0,a.jsx)(c.A,{className:"icon-body"}),s.planAccess]}),(0,a.jsx)(g.CardDescription,{children:s.whichSubscriptionPlansMayUseWhich})]}),(0,a.jsx)(g.CardContent,{className:"overflow-x-auto",children:(0,a.jsxs)("table",{className:"w-full text-body",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"border-b border-border text-left text-small text-muted-foreground",children:[(0,a.jsx)("th",{className:"py-small pr-body font-medium",children:"Plan"}),_.map(e=>(0,a.jsxs)("th",{className:"py-small px-body font-medium text-center",children:["Tier ",e.id]},e.id))]})}),(0,a.jsx)("tbody",{children:F.plans.map(e=>{let s=new Set(F.access[e.id]??[]);return(0,a.jsxs)("tr",{className:"border-b border-border/50",children:[(0,a.jsx)("td",{className:"py-body pr-body font-medium",children:e.displayName}),_.map(e=>(0,a.jsx)("td",{className:"py-body px-body text-center",children:s.has(e.id)?(0,a.jsx)(u.A,{className:"icon-body text-green-600 inline"}):(0,a.jsx)("span",{className:"text-muted-foreground",children:"–"})},e.id))]},e.id)})})]})})]}),(0,a.jsxs)("div",{className:"flex items-start gap-body rounded-default border border-border bg-muted/30 p-body text-small text-muted-foreground",children:[(0,a.jsx)(m.A,{className:"icon-body mt-px shrink-0"}),(0,a.jsxs)("div",{children:[s.settlementIntro," ",(0,a.jsx)("strong",{children:s.estimation})," ",s.settlementModelDesc," ",(0,a.jsx)("em",{children:s.settle})," ",s.settlementTextFlatRate," ",(0,a.jsx)("strong",{children:s.textLabel}
1),t("settings.settlementFlatRateDetail",{input:M.inputTokensPerCredit??"—",output:M.outputTokensPerCredit??"—"})]})]})]})]})}let w={accurate:{label:"Accurate",variant:"success"},warning:{label:"Drifting",variant:"warning"},critical:{label:"Critical",variant:"destructive"},"low-sample":{label:"Low sample",variant:"outline"},uncalibrated:{label:"No data",variant:"secondary"}};function A({status:e}){let s=w[e];return(0,a.jsxs)(x.E,{variant:s.variant,size:"small",children:["critical"===e&&(0,a.jsx)(h.A,{className:"icon-small"}),"accurate"===e&&(0,a.jsx)(u.A,{className:"icon-small"}),"low-sample"===e&&(0,a.jsx)(p.A,{className:"icon-small"}),s.label]})}},4884:(e,s,t)=>{t.d(s,{t:()=>A});var a=t(68987),n=t(42725),r=t(2315),i=t(52615),l=t(64253),o=t(65706),d=t(29146),c=t(22694),u=t(44991),m=t(38339),h=t(2793),p=t(77959),x=t(4965),y=t(75279),g=t(64895),f=t(99834),j=t(54324),b=t(71519),v=t(21710);let N={type:"enterprise",planName:"Enterprise",billingType:"external",accessLevel:"FULL_ACCESS",expiresAt:"",billingCycle:"monthly",renewsAt:"",externalReference:"",notes:"",creditOverrideMode:"inherit",monthlyCreditsOverride:"",creditsPerSeatOverride:"",creditPeriodAnchor:"",trialEndsAt:"",neverExpire:!1},C=i.Yj().refine(e=>""===e||Number.parseInt(e,10)>0,"Must be a positive number"),E=i.Ik({type:i.eu("enterprise"),planName:i.Yj().min(1,"Plan name is required"),billingType:i.k5(["external","stripe_managed","free"]),accessLevel:i.k5(["FULL_ACCESS","READ_ONLY","BLOCKED"]),expiresAt:i.Yj(),billingCycle:i.k5(["monthly","yearly"]),renewsAt:i.Yj(),externalReference:i.Yj(),notes:i.Yj(),creditOverrideMode:i.k5(["inherit","flat","perSeat"]),monthlyCreditsOverride:C,creditsPerSeatOverride:C,creditPeriodAnchor:i.Yj()}).refine(e=>"flat"!==e.creditOverrideMode||Number.parseInt(e.monthlyCreditsOverride,10)>0,{message:"Monthly credits is required",path:["monthlyCreditsOverride"]}).refine(e=>"perSeat"!==e.creditOverrideMode||Number.parseInt(e.creditsPerSeatOverride,10)>0,{message:"Credits per seat is required",path:["creditsPerSeatOverride"]}),w=i.Ik({type:i.eu("trial"),trialEndsAt:i.Yj(),neverExpire:i.zM()}).refine(e=>e.neverExpire||e.trialEndsAt.length>0,{message:"Trial end date is required",path:["trialEndsAt"]});function A({companyId:e,companyName:s,initialType:t,initialValue:i,hasStripeSubscription:b=!1,onSaved:C,onCancel:T}){let k=(0,n.t0)(),D=(0,n.WD)(),I=(0,r.useMemo)(()=>({...N,type:t??"enterprise",...i}),[t,i]),[P,_]=(0,r.useState)(I),[O,R]=(0,r.useState)(!1),[L,F]=(0,r.useState)(!1),[M,U]=(0,r.useState)("NO_PLAN"),[$,K]=(0,r.useState)(""),[B,H]=(0,r.useState)(""),[q,G]=(0,r.useState)("14"),[z,W]=(0,r.useState)(!0),[J,Q]=(0,r.useState)("");function V(){F(!1),U("NO_PLAN"),K(""),H(""),G("14"),W(!0),Q("")}let{data:Y=[]}=(0,c.useDeveloperPlans)(L&&"enterprise"===t),X=(0,r.useMemo)(()=>Y.filter(e=>!["enterprise","trial","custom"].includes(e.name.toLowerCase())),[Y]),Z="COMPED_TRIAL"===M||"STRIPE_REQUIRED"===M,ee=J.trim().length>=v.n&&(!Z||$.length>0&&B.length>0)&&("COMPED_TRIAL"!==M||q.length>0),es="enterprise"===t,et=(e,s)=>_(t=>({...t,[e]:s})),ea=(0,r.useMemo)(()=>!!("enterprise"===P.type?E:w).safeParse(P).success&&("enterprise"!==P.type||"inherit"===P.creditOverrideMode||!!b||!!P.creditPeriodAnchor),[P,b]),en=(0,r.useMemo)(()=>{let e=e=>({mode:e.creditOverrideMode,value:"flat"===e.creditOverrideMode?e.monthlyCreditsOverride:"perSeat"===e.creditOverrideMode?e.creditsPerSeatOverride:"",anchor:b?"":e.creditPeriodAnchor}),s=e(I),t=e(P);return s.mode!==t.mode||s.value!==t.value||s.anchor!==t.anchor},[I,P,b]);async function er(){R(!0);try{"enterprise"===P.type?await ei():await eo(),C?.()}catch(s){f.logger.error("[CompanySubscriptionForm] save failed",{companyId:e,error:s}),(0,j.AG)("save","subscription","error",{detail:s instanceof Error?s.message:void 0})}finally{R(!1)}}async function ei(){let s="enterprise"===t,a=`/api/admin/billing/custom-subscriptions/${e}`,n={planName:P.planName,billingType:P.billingType,accessLevel:P.accessLevel,expiresAt:P.expiresAt?new Date(P.expiresAt).toISOString():null,billingCycle:P.billingCycle,renewsAt:P.renewsAt?new Date(P.renewsAt).toISOString():null,externalReference:P.externalReference||null,notes:P.notes||null},r={"Content-Type":"application/json"},i=await fetch(s?a:"/api/admin/billing/custom-subscriptions",{method:s?"PUT":"POST",headers:r,body:JSON.stringify(s?n:{companyId:e,...n})});if(s||409!==i.status||(i=await fetch(a,{method:"PUT",headers:r,body:JSON.stringify(n)})),!i.ok)throw Error("Failed to save enterprise subscription");await el(),(0,j.AG)("save","subscription","success")}async function el(){if(!en)return;
1let s=!b&&P.creditPeriodAnchor?new Date(P.creditPeriodAnchor).toISOString():null,t={companyId:e,monthlyCreditsOverride:"flat"===P.creditOverrideMode?Number(P.monthlyCreditsOverride):null,creditsPerSeatOverride:"perSeat"===P.creditOverrideMode?Number(P.creditsPerSeatOverride):null,creditPeriodAnchor:s},a=await fetch("/api/admin/billing/credit-override",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok)throw Error((await a.json().catch(()=>({}))).error??"Failed to save credit override")}async function eo(){let a="trial"===t?"extend":"start";if(!(await fetch("/api/admin/billing/update-trial",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:e,action:a,endsAt:P.neverExpire?null:P.trialEndsAt?new Date(P.trialEndsAt).toISOString():null,neverExpire:P.neverExpire})})).ok)throw Error("Failed to save trial");j.me.success("start"===a?k.developerSettings.toasts.trialStarted:k.developerSettings.toasts.trialUpdated,{description:D("settings.developerSettings.toasts.trialSavedFor",{company:s})})}async function ed(){R(!0);try{if(!(await fetch("/api/admin/billing/update-trial",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:e,action:"end"})})).ok)throw Error("Failed to end trial");j.me.success(k.developerSettings.toasts.trialEnded,{description:D("settings.developerSettings.toasts.trialEndedDesc",{companyName:s})}),C?.()}catch(s){f.logger.error("[CompanySubscriptionForm] endTrial failed",{companyId:e,error:s}),j.me.error(D("common.error"),{description:s instanceof Error?s.message:k.developerSettings.toasts.endTrialFailed})}finally{R(!1)}}async function ec(){R(!0);try{let t={targetState:M,clearSubscriptionCredits:z,reason:J.trim()};Z&&(t.planId=$,t.seats=Number.parseInt(B,10)),"COMPED_TRIAL"===M&&(t.freeDays=Number.parseInt(q,10));let a=await fetch(`/api/admin/billing/custom-subscriptions/${e}/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.json().catch(()=>({}));throw Error(e.error??"Failed to end enterprise plan")}j.me.success(k.developerSettings.toasts.enterprisePlanEnded,{description:D("settings.developerSettings.toasts.companyTransitioned",{company:s})}),C?.()}catch(s){f.logger.error("[CompanySubscriptionForm] endEnterprise failed",{companyId:e,error:s}),j.me.error(D("common.error"),{description:s instanceof Error?s.message:k.developerSettings.toasts.endEnterprisePlanFailed})}finally{R(!1)}}return(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{children:k.subscriptionType}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-body",children:[(0,a.jsx)(S,{active:"trial"===P.type,disabled:es,icon:(0,a.jsx)(l.A,{className:"icon-body"}),label:"Trial",onClick:()=>et("type","trial")}),(0,a.jsx)(S,{active:"enterprise"===P.type,icon:(0,a.jsx)(o.A,{className:"icon-body"}),label:"Enterprise",onClick:()=>et("type","enterprise")})]}),es&&(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:k.enterpriseCompaniesCanTBeMoved})]}),"trial"===P.type&&(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"flex-between rounded-default border p-body",children:[(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsx)(p.J,{htmlFor:"neverExpire",children:"Never expire"}),(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"Trial stays active with no end date."})]}),(0,a.jsx)(y.d,{id:"neverExpire",checked:P.neverExpire,onCheckedChange:e=>et("neverExpire",e)})]}),!P.neverExpire&&(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"trialEndsAt",children:"Trial ends"}),(0,a.jsx)(h.p,{id:"trialEndsAt",type:"date",value:P.trialEndsAt,onChange:e=>et("trialEndsAt",e.target.value)}),(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"trial"===t?"Adjusts the existing trial end date.":"Starts a new trial running until this date."})]}),"trial"===t&&(0,a.jsxs)(u.$,{variant:"ghost",className:"text-destructive",onClick:ed,disabled:O,children:[(0,a.jsx)(d.A,{className:"mr-body icon-body"}),"End trial now"]})]}),"enterprise"===P.type&&(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"planName",children:k.planName}),(0,a.jsx)(h.p,{id:"planName",placeholder:k.eGEnterprisePartner,value:P.planName,onChange:e=>et("planName",e.target.value)})]}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-large",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"billingType",children:"Billing"}),(0,a.jsxs)(g.l6,{value:P.billingType,onValueChange:e=>et("billingType",e),children:[(0,a.jsx)(g.bq,{id:"billingType",children:(0,a.jsx)(g.yv,{})}),(0,a.jsxs)(g.gC,{children:[(0,a.jsx)(g.eb,{value:"external",children:k.externalBilling}),(0,a.jsx)(g.eb,{value:"stripe_managed",children:k.stripeManaged}),(0,a.jsx)(g.eb,{value:"free",children:"Free"})]})]})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"accessLevel",children:k.accessLevel}),(0,a.jsxs)(g.l6,{value:P.accessLevel,onValueChange:e=>et("accessLevel",e),children:[(0,a.jsx)(g.bq,{id:"accessLevel",children:(0,a.jsx)(g.yv,{})}),(0,a.jsxs)(g.gC,{children:[(0,a.jsx)(g.eb,{value:"FULL_ACCESS",children:k.fullAccess}),(0,a.jsx)(g.eb,{value:"READ_ONLY",children:k.readOnly}),(0,a.jsx)(g.eb,{value:"BLOCKED",children:"Blocked"})]})]})]})]}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-large",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"expiresAt",children:k.expiresOptional}),(0,a.jsx)(h.p,{id:"expiresAt",type:"date",value:P.expiresAt,onChange:e=>et("expiresAt",e.target.value)})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"externalReference",children:k.externalReference}),(0,a.jsx)(h.p,{id:"externalReference",placeholder:k.eGPo12345,value:P.externalReference,onChange:e=>et("externalReference",e.target.value)})]})]}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-large",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"billingCycle",children:k.billingCycle}),(0,a.jsxs)(g.l6,{value:P.billingCycle,onValueChange:e=>et("billingCycle",e),children:[(0,a.jsx)(g.bq,{id:"billingCycle",children:(0,a.jsx)(g.yv,{})}),(0,a.jsxs)(g.gC,{children:[(0,a.jsx)(g.eb,{value:"monthly",children:"Monthly"}),(0,a.jsx)(g.eb,{value:"yearly",children:"Yearly"})]})]})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"renewsAt",children:k.nextRenewalOptional}),(0,a.jsx)(h.p,{id:"renewsAt",type:"date",value:P.renewsAt,onChange:e=>et("renewsAt",e.target.value)}),(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:"Auto-renews on this day each cycle (until the expiry date, if set) — no monthly edits needed. Leave blank for Stripe-managed contracts; renewal is read from the live Stripe period."})]})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"notes",children:k.internalNotes}),(0,a.jsx)(x.T,{id:"notes",placeholder:k.internalNotesAboutThisContract,rows:3,value:P.notes,onChange:e=>et("notes",e.target.value)})]}),(0,a.jsxs)("div",{className:"space-y-body rounded-default border p-body",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"creditOverrideMode",children:"Monthly credits"}),(0,a.jsxs)(g.l6,{value:P.creditOverrideMode,onValueChange:e=>et("creditOverrideMode",e),children:[(0,a.jsx)(g.bq,{id:"creditOverrideMode",children:(0,a.jsx)(g.yv,{})}),(0,a.jsxs)(g.gC,{children:[(0,a.jsx)(g.eb,{value:"inherit",children:"Inherit from plan"}),(0,a.jsx)(g.eb,{value:"flat",children:"Flat monthly override"}),(0,a.jsx)(g.eb,{value:"perSeat",children:"Per-seat override"})]})]})]}),"flat"===P.creditOverrideMode&&(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"monthlyCreditsOverride",children:"Monthly credits"}),(0,a.jsx)(h.p,{id:"monthlyCreditsOverride",type:"number",min:"1",placeholder:"e.g. 50000",value:P.monthlyCreditsOverride,onChange:e=>et("monthlyCreditsOverride",e.target.value)})]}),"perSeat"===P.creditOverrideMode&&(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"creditsPerSeatOverride",children:"Credits per seat"}),(0,a.jsx)(h.p,{id:"creditsPerSeatOverride",type:"number",min:"1",placeholder:"e.g. 2000",value:P.creditsPerSeatOverride,onChange:e=>et("creditsPerSeatOverride",e.target.value)})]}),!b&&"inherit"!==P.creditOverrideMode&&(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(p.J,{htmlFor:"creditPeriodAnc
1hor",children:"Period anchor"}),(0,a.jsx)(h.p,{id:"creditPeriodAnchor",type:"date",value:P.creditPeriodAnchor,onChange:e=>et("creditPeriodAnchor",e.target.value)}),(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"Required for externally-billed (non-Stripe) subscriptions — defines the period boundary for the credit grant."})]}),(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"Takes effect next billing period. To grant credits now, use Grant Credits."})]})]}),(0,a.jsxs)("div",{className:"flex-between gap-body pt-body",children:[(0,a.jsx)("div",{children:"enterprise"===t&&(0,a.jsxs)(u.$,{variant:"ghost",className:"text-destructive",onClick:()=>F(e=>!e),disabled:O,children:[(0,a.jsx)(d.A,{className:"mr-body icon-body"}),k.endEnterprisePlan]})}),(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[T&&(0,a.jsx)(u.$,{variant:"outline",onClick:T,disabled:O,children:"Cancel"}),(0,a.jsx)(u.$,{onClick:er,disabled:!ea||O,children:O?"Saving…":"Save"})]})]}),(0,a.jsx)(m.lG,{open:L&&"enterprise"===t,onOpenChange:e=>{e||V()},closeOnAction:!1,size:"lg",title:k.endEnterprisePlan,description:"Choose the company's next state. This action is recorded in the audit log.",children:(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsx)(p.J,{htmlFor:"endTargetState",children:k.nextState}),(0,a.jsxs)(g.l6,{value:M,onValueChange:e=>{U(e),K(""),H(""),G("14")},children:[(0,a.jsx)(g.bq,{id:"endTargetState",children:(0,a.jsx)(g.yv,{})}),(0,a.jsxs)(g.gC,{children:[(0,a.jsx)(g.eb,{value:"NO_PLAN",children:k.noPlan}),(0,a.jsx)(g.eb,{value:"COMPED_TRIAL",children:k.compedTrialFirstPeriodFree}),(0,a.jsx)(g.eb,{value:"STRIPE_REQUIRED",children:k.stripeRequiredFromStart})]})]})]}),Z&&(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-body",children:[(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsx)(p.J,{htmlFor:"endPlanId",children:"Plan"}),(0,a.jsxs)(g.l6,{value:$,onValueChange:e=>K(e),children:[(0,a.jsx)(g.bq,{id:"endPlanId",children:(0,a.jsx)(g.yv,{placeholder:k.selectAPlan})}),(0,a.jsx)(g.gC,{children:X.map(e=>(0,a.jsx)(g.eb,{value:e.id,children:e.displayName},e.id))})]})]}),(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsx)(p.J,{htmlFor:"endSeats",children:"Seats"}),(0,a.jsx)(h.p,{id:"endSeats",type:"number",min:"1",placeholder:k.eG5,value:B,onChange:e=>H(e.target.value)})]})]}),"COMPED_TRIAL"===M&&(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsx)(p.J,{htmlFor:"endFreeDays",children:k.freeDays}),(0,a.jsx)(h.p,{id:"endFreeDays",type:"number",min:"1",max:"365",placeholder:k.eG14,value:q,onChange:e=>G(e.target.value)}),(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:k.numberOfFreeDaysForThe})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsx)("input",{id:"endClearCredits",type:"checkbox",checked:z,onChange:e=>W(e.target.checked),className:"h-body w-body rounded-default border-border"}),(0,a.jsx)(p.J,{htmlFor:"endClearCredits",className:"cursor-pointer",children:k.clearExistingSubscriptionCredits})]}),(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsxs)(p.J,{htmlFor:"endReason",children:["Reason"," ",(0,a.jsx)("span",{className:"text-muted-foreground text-mini",children:k.min10Chars})]}),(0,a.jsx)(x.T,{id:"endReason",placeholder:k.reasonForEndingTheEnterprisePlan,rows:2,value:J,onChange:e=>Q(e.target.value)})]}),(0,a.jsxs)("div",{className:"flex justify-end gap-body",children:[(0,a.jsx)(u.$,{variant:"outline",onClick:V,disabled:O,children:"Cancel"}),(0,a.jsx)(u.$,{variant:"destructive",onClick:ec,disabled:O||!ee,children:O?"Ending…":"Confirm end"})]})]})})]})}function S({active:e,disabled:s,icon:t,label:n,onClick:r}){return(0,a.jsxs)("button",{type:"button",disabled:s,onClick:r,className:(0,b.cn)("flex-center gap-body rounded-default border p-large text-body font-medium transition-colors",e?"border-primary bg-primary/5 text-foreground":"border-border text-muted-foreground hover:bg-muted/50",s&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[t,n]})}},10655:(e,s,t)=>{t.d(s,{m:()=>b,r:()=>j.r});var a=t(2315),n=t(73591),r=t(7586),i=t(34973),l=t(54324),o=t(42725),d=t(36037),c=t(19953),u=t
1(14915),m=t(10042),h=t(15128),p=t(57934);function x(e){return(0,a.lazy)(e)}let y={dashboard:{"billing-summary":{id:"billing-summary",label:"Billing Summary",description:"Current plan, credit usage, and renewal date",icon:d.A,component:x(()=>Promise.all([t.e(37866),t.e(9534)]).then(t.bind(t,9534)).then(e=>({default:e.BillingSummaryCard}))),defaultWidth:"half",defaultVisible:!0,resizable:!0,pinnableByAdmin:!0,requiredPermission:"MANAGE_BILLING"},"video-tutorials":{id:"video-tutorials",label:"Video Tutorials",description:"Getting started video guides",icon:c.A,component:x(()=>t.e(43432).then(t.bind(t,43432)).then(e=>({default:e.VideotutorialModule}))),defaultWidth:"half",defaultVisible:!0,resizable:!0,pinnableByAdmin:!0},search:{id:"search",label:"Quick Search",description:"Search and navigate to any feature",icon:u.A,component:x(()=>t.e(55148).then(t.bind(t,55148)).then(e=>({default:e.SearchModule}))),defaultWidth:"full",defaultVisible:!0,resizable:!0,showHeader:!1,chromeless:!0,pinnableByAdmin:!0},support:{id:"support",label:"Help & Feedback",description:"Book a meeting, request help, or read docs",icon:m.A,component:x(()=>Promise.all([t.e(19201),t.e(52615),t.e(39292),t.e(39878),t.e(38339),t.e(50118)]).then(t.bind(t,70233)).then(e=>({default:e.SupportCard}))),defaultWidth:"half",defaultVisible:!0,resizable:!0,pinnableByAdmin:!0},"onboarding-checklist":{id:"onboarding-checklist",label:"Getting Started",description:"Onboarding checklist",icon:h.A,component:x(()=>Promise.all([t.e(19201),t.e(44313),t.e(32378),t.e(52615),t.e(39292),t.e(37182),t.e(8180),t.e(97341),t.e(90225),t.e(39878),t.e(92061),t.e(24810),t.e(37866),t.e(38339),t.e(93676),t.e(46603),t.e(83218),t.e(9e4),t.e(23568),t.e(58435),t.e(24006),t.e(16020),t.e(22211)]).then(t.bind(t,34474)).then(e=>({default:e.ChecklistPanelWidget}))),defaultWidth:"half",defaultVisible:!0,resizable:!1,pinnableByAdmin:!1},highlights:{id:"highlights",label:"Feature Highlights",description:"Discover key platform features",icon:p.A,component:x(()=>Promise.all([t.e(37866),t.e(40149)]).then(t.bind(t,40149)).then(e=>({default:e.DashboardHighlights}))),defaultWidth:"half",defaultVisible:!0,resizable:!0,pinnableByAdmin:!1}},reports:{}};async function g(e){let s=await fetch(`/api/layout/${e}`);if(!s.ok)throw Error("Failed to fetch layout");let t=await s.json(),a=y[e]??{};return t.data.filter(e=>a[e.id]).map(e=>({...e,definition:a[e.id]}))}async function f(e,s){if(!(await fetch(`/api/layout/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).ok)throw Error("Failed to save layout")}var j=t(26118);function b(e){let s=(0,o.WD)(),t=(0,n.useQueryClient)(),{data:d}=(0,r.useQuery)({queryKey:["layout",e],queryFn:()=>g(e)}),[c,u]=(0,a.useState)(null),m=null!==c,h=c??d??[],{mutateAsync:p}=(0,i.useMutation)({mutationFn:s=>f(e,s),onSuccess:()=>{t.invalidateQueries({queryKey:["layout",e]})},onError:()=>{l.me.error(s("common.toasts.layoutSaveFailed"))}});return{layout:h,isEditing:m,enterEditMode:()=>u(d??[]),cancelEditMode:()=>u(null),saveChanges:async()=>{if(null!==c)try{var e;await p((e=c,{version:1,widgets:e.map((e,s)=>({id:e.definition.id,visible:e.visible,width:e.width,order:s}))})),u(null)}catch{}},reorder:(e,s)=>u(t=>(function(e,s,t){let a=[...e],[n]=a.splice(s,1);return a.splice(t,0,n),a})(t??[],e,s)),setWidth:(e,s)=>u(t=>v(t??[],e,{width:s})),setVisible:(e,s)=>u(t=>v(t??[],e,{visible:s}))}}function v(e,s,t){return e.map(e=>e.definition.id===s?{...e,...t}:e)}},22694:(e,s,t)=>{t.r(s),t.d(s,{AIGovernorConfig:()=>sX,APP_STATE_CONFIG:()=>v,AdjustTrialDialog:()=>st,AdminDestructiveRateLimitConfig:()=>sd,AdminRateLimitConfig:()=>sl,AutoCompactPolicyConfig:()=>sY,AutoModelDefaultsOverview:()=>tm,BlockedEmailsTab:()=>tR,CompanyDirectory:()=>eZ,CompanyDirectoryRow:()=>eW,CompanyDirectoryToolbar:()=>eR,CompanySupportAccessPanel:()=>e1,ComplianceAuditLogTab:()=>tt.k,ComposioFailureReportCard:()=>s8,ContactTestCard:()=>s1,CreditSystemTab:()=>th.k,CronConfigCard:()=>sg,CronOverviewTab:()=>sN,DEVELOPER_PILLARS:()=>j,DeveloperCalibrationTab:()=>td.Q,DeveloperChecklistsTab:()=>t_,DeveloperCustomSubscriptionsTab:()=>to,DeveloperDashboard:()=>A,DeveloperToursTab:()=>tS,DeveloperUsersTab:()=>tn,EmailTestCard:()=>s3,ExportPolicyCard:()=>sQ,ExportRuleReviewDialog:()=>sO,ExportRulesTable:()=>sU,InternalIntegrationsTab:()=>tw,LangfuseFailureReportCard:()=>ts,LifecycleSummaryTestCard:()=>s5,MoveToTrialDialog:()=>sa,PLAN_LABELS:()=>b,SupportAccessDialog:()=>eX,TrialCompaniesTable:()=>sn,TrialConfigPanel:()=>sr,TrialGlobalConfig:()=>e9,adminKeys:()=>I.a,useAssignedCompanies:()=>L,useDeveloperCompanies:()=>O,useDeveloperPlans:()=>X,useDeveloperTrialConfig:()=>Q,useDeveloperUsers:()=>ei,useEndTrial:()=>en,useExportRuleSample:()=>ej,useExportRules:()=>ex,useExtendTrial:()=>et,useGrantSupportAccess:()=>H,usePromoteExportFields:()=>eb,useStartTrial:()=>ea,useSwitchCompany:()=>
1K,useUpdateTrialConfig:()=>V});var a=t(68987),n=t(42725),r=t(1343),i=t(65706),l=t(96831),o=t(87809),d=t(36037),c=t(17334),u=t(44410),m=t(22940),h=t(67624),p=t(52348),x=t(33298),y=t(90504),g=t(71212),f=t(86588);let j=[{id:"companies",label:"Company Management",description:"Browse companies, billing, and enterprise subscriptions",route:"companies",iconName:"Building2"},{id:"users",label:"User Management",description:"Global user directory and identity operations",route:"users",iconName:"Users"},{id:"models",label:"AI Models",description:"Default models, calibration, and credit pricing",route:"models",iconName:"Cpu"},{id:"credits",label:"Credit System",description:"Credit pricing reference and usage overview",route:"credits",iconName:"CreditCard"},{id:"news",label:"News",description:"Manage platform announcements and news",route:"news",iconName:"Newspaper"},{id:"integrations",label:"Integrations",description:"Internal integrations and custom connectors",route:"integrations",iconName:"Link2"},{id:"marketplace",label:"Marketplace",description:"Publish and archive shared agents, assistants, and workflows",route:"marketplace",iconName:"Store"},{id:"general",label:"General",description:"Trial defaults, roles, tours, and checklists",route:"general",iconName:"Settings"},{id:"compliance",label:"Compliance",description:"SOC 2 audit log — policy events and admin actions",route:"compliance",iconName:"Shield"},{id:"crons",label:"Scheduled Jobs",description:"Every cron with schedule, kill switch, knobs and heartbeats",route:"crons",iconName:"Clock"},{id:"ai-runs",label:"AI Runs",description:"Operator view of AI run health, active and stale runs",route:"ai-runs",iconName:"Activity"},{id:"ui-system",label:"UI System",description:"Component catalog and design system reference",route:"ui-system",iconName:"Palette"}],b={trial:"Trial",starter:"Starter",pro:"Pro",team:"Team",enterprise:"Enterprise",unknown:"No plan"},v={ACTIVE:{label:"Active",variant:"success",description:"Paying subscription in good standing."},TRIAL:{label:"Trial",variant:"default",description:"Active trial period, not yet converted."},TRIAL_EXPIRED:{label:"Trial expired",variant:"warning",description:"Trial ended without conversion — the customer must subscribe to regain access."},PAST_DUE:{label:"Past due",variant:"warning",description:"Stripe payment failed — the customer resolves it in the Stripe portal."},READ_ONLY:{label:"Read only",variant:"secondary",description:"Enterprise access level set to read-only (custom-subscription switch)."},SUSPENDED:{label:"Suspended",variant:"destructive",description:'Operator action ("Suspend full access") — independent of billing; only an operator can lift it. Wins over every other state.'},BLOCKED:{label:"Blocked",variant:"destructive",description:"Derived from billing: canceled/unpaid/no subscription, seat overflow after a downgrade, or enterprise access level set to blocked. Self-heals once the customer fixes billing."}},N=["trial","starter","pro","team","enterprise","unknown"],C=["ACTIVE","TRIAL","TRIAL_EXPIRED","PAST_DUE","READ_ONLY","SUSPENDED","BLOCKED"],E=[{value:"7d",label:"Last 7 days",days:7},{value:"30d",label:"Last 30 days",days:30},{value:"90d",label:"Last 90 days",days:90},{value:"12m",label:"Last 12 months",days:365}],w={Building2:i.A,Users:l.A,Cpu:o.A,CreditCard:d.A,Newspaper:c.A,Link2:u.A,Store:m.A,Settings:h.A,Shield:p.A,Palette:x.A,Activity:y.A,TrendingUp:g.A};function A(){let e=(0,n.t0)(),s=(0,r.useParams)(),t=s?.lang||"en",i=[{id:"developer",cards:j.map(e=>{let s=w[e.iconName]??h.A;return{id:e.id,label:e.label,description:e.description,icon:(0,a.jsx)(s,{className:"icon-body text-muted-foreground"}),href:`/${t}/settings/developer/${e.route}`}})}];return(0,a.jsx)(f.q,{title:e.developerSettings2,groups:i})}var S=t(2315),T=t(91541),k=t(73591),D=t(54324),I=t(33922),P=t(7586);async function _(){let e=await fetch("/api/companies");if(!e.ok)throw Error(`Failed to fetch companies: ${e.statusText}`);let s=await e.json();return s.data||s||[]}function O(e,s=!0){return(0,P.useQuery)({queryKey:I.a.companies.list(e),queryFn:_,staleTime:3e5,gcTime:6e5,enabled:s})}async function R(){let e=await fetch("/api/companies/assigned");if(!e.ok)throw Error(`Failed to fetch assigned companies: ${e.statusText}`);let s=await e.json();return s.data||s||[]}function L(e=!0){return(0,P.useQuery)({queryKey:I.a.companies.assigned,queryFn:R,staleTime:3e5,gcTime:6e5,enabled:e})}async function F(){let e=await fetch("/api/admin/companies/support-grants");if(!e.ok)throw Error(`Failed to fetch support grants: ${e.statusText}`);let s=await e.json();return s.data||s||[]}function M(e=!0){return(0,P.useQuery)({queryKey:I.a.companies.supportGrants,queryFn:F,staleTime:6e4,gcTime:3e5,enabled:e})}var U=t(34973),$=t(85416);function K(){return(0,U.useMutation)({mutationFn:({companyId:e})=>(0,$.$b)(e),onSuccess:(e,{companyId:s})=>{(0,$.Nv)({companyId:s,reason:"switch"}),window.dispatchEvent(new CustomEvent("refreshNavbar",{detail:{source:"company-directory"}}))}})}async function B({companyId:e,reason:s}){let t=await fetch(`/api/admin/companies/${e}/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:s})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.details?.reason?._errors?.[0]||e.message||"Failed to grant support access")}}function H(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:B,onSuccess:()=>
1{e.invalidateQueries({queryKey:I.a.companies.all}),e.invalidateQueries({queryKey:I.a.companies.assigned}),e.invalidateQueries({queryKey:["companies"]})}})}var q=t(90053);async function G({companyId:e,reason:s}){let t=await fetch(`/api/admin/companies/${e}/join`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:s||"Manual session end"})});if(!t.ok)throw Error((await t.json().catch(()=>({}))).message||"Failed to revoke support access")}function z(){let e=(0,k.useQueryClient)(),{userContext:s}=(0,q.ur)(),t=s?.activeCompany?.id;return(0,U.useMutation)({mutationFn:G,onSuccess:(s,{companyId:a})=>{t&&t===a?(0,$.Nv)({companyId:a,reason:"support-revoke"}):(e.invalidateQueries({queryKey:I.a.companies.all}),e.invalidateQueries({queryKey:I.a.companies.assigned}),e.invalidateQueries({queryKey:["companies"]}))}})}async function W(){let e=await fetch("/api/admin/billing/trial-config");if(!e.ok)throw Error(`Failed to fetch trial config: ${e.statusText}`);let s=await e.json();return s.data||s}async function J(e){let s=await fetch("/api/admin/billing/trial-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw Error((await s.json().catch(()=>({}))).message||"Failed to update trial config");let t=await s.json();return t.data||t}function Q(e=!0){return(0,P.useQuery)({queryKey:I.a.billing.trialConfig,queryFn:W,staleTime:3e5,gcTime:6e5,enabled:e})}function V(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:J,onSuccess:()=>{e.invalidateQueries({queryKey:I.a.billing.trialConfig})}})}async function Y(){let e=await fetch("/api/admin/billing/plans");if(!e.ok)throw Error(`Failed to fetch plans: ${e.statusText}`);let s=await e.json();return s.data?.plans??s.plans??[]}function X(e=!0){return(0,P.useQuery)({queryKey:I.a.billing.plans,queryFn:Y,staleTime:3e5,gcTime:6e5,enabled:e})}async function Z(e){let s=await fetch("/api/admin/billing/extend-trial",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw Error((await s.json().catch(()=>({}))).message||"Failed to extend trial")}async function ee(e){let s=await fetch("/api/admin/billing/start-trial",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw Error((await s.json().catch(()=>({}))).message||"Failed to start trial")}async function es(e){let s=await fetch("/api/admin/billing/end-trial",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw Error((await s.json().catch(()=>({}))).message||"Failed to end trial")}function et(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:Z,onSuccess:()=>{e.invalidateQueries({queryKey:I.a.companies.all}),e.invalidateQueries({queryKey:I.a.billing.all})}})}function ea(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:ee,onSuccess:()=>{e.invalidateQueries({queryKey:I.a.companies.all}),e.invalidateQueries({queryKey:I.a.billing.all})}})}function en(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:es,onSuccess:()=>{e.invalidateQueries({queryKey:I.a.companies.all}),e.invalidateQueries({queryKey:I.a.billing.all})}})}async function er(e){let s=await fetch(`/api/admin/users?search=${encodeURIComponent(e)}`);
1if(!s.ok)throw Error(`Failed to fetch users: ${s.statusText}`);let t=await s.json();return t.data?.users||t.users||[]}function ei(e,s=!0){return(0,P.useQuery)({queryKey:I.a.users.search(e),queryFn:()=>er(e),staleTime:3e4,enabled:s&&e.length>=2})}async function el(){let e=await fetch("/api/admin/system-config");if(!e.ok)throw Error(`Failed to fetch system config: ${e.statusText}`);return(await e.json()).data}async function eo(e){let s=await fetch("/api/admin/system-config",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to save: ${s.statusText}`)}return(await s.json()).data}function ed(e=!0){return(0,P.useQuery)({queryKey:I.a.systemConfig,queryFn:el,staleTime:6e4,enabled:e})}async function ec(){let e=await fetch("/api/admin/cron-config");if(!e.ok)throw Error(`Failed to fetch cron config: ${e.statusText}`);return(await e.json()).data}async function eu(e){let s=await fetch("/api/admin/cron-config",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to save: ${s.statusText}`)}return(await s.json()).data}function em(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:eu,onSuccess:()=>{e.invalidateQueries({queryKey:I.a.cronConfig}),e.invalidateQueries({queryKey:I.a.cronOverview})},meta:{notify:{action:"save",entity:"setting"}}})}async function eh(){let e=await fetch("/api/admin/cron-overview");if(!e.ok)throw Error(`Failed to fetch cron overview: ${e.statusText}`);return(await e.json()).data}async function ep(e){let s=await fetch(`/api/admin/export-rules?days=${e}`);if(!s.ok)throw Error(`Failed to fetch export rules: ${s.statusText}`);return(await s.json()).data}function ex(e=90){return(0,P.useQuery)({queryKey:I.a.exportRules(e),queryFn:()=>ep(e),staleTime:6e4})}class ey extends Error{status;retryAfterSeconds;constructor(e,s){super(e),this.name="ExportPromoteError",this.status=s.status,this.retryAfterSeconds=s.retryAfterSeconds??null}}async function eg(e,s){let t=await fetch(`/api/admin/export-rules/sample?slug=${encodeURIComponent(e)}&action=${encodeURIComponent(s)}`);if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??`Failed to sample: ${t.statusText}`)}return(await t.json()).data}async function ef(e){let s=await fetch("/api/admin/export-rules/promote",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let e=await s.json().catch(()=>null),t=Number(s.headers.get("Retry-After"));throw new ey(e?.error??`Failed to promote: ${s.statusText}`,{status:s.status,retryAfterSeconds:Number.isFinite(t)&&t>0?t:null})}return(await s.json()).data}function ej(e,s){return(0,P.useQuery)({queryKey:I.a.exportRuleSample(e??"",s??""),queryFn:()=>eg(e,s),enabled:!!(e&&s),staleTime:3e4})}function eb(){let e=(0,k.useQueryClient)();return(0,U.useMutation)({mutationFn:ef,retry:!1,onSuccess:()=>{e.invalidateQueries({queryKey:["admin","export-rules"]})},meta:{notify:{action:"save",entity:"setting"}}})}async function ev(){let e=await fetch("/api/admin/ai-policy/global");if(!e.ok)throw Error(`Failed to fetch global AI policy: ${e.statusText}`);return(await e.json()).data}async function eN(e){let s=await fetch("/api/admin/ai-policy/global",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to save: ${s.statusText}`)}return(await s.json()).data}async function eC(){let e=await fetch("/api/admin/ai-policy/governor");if(!e.ok)throw Error(`Failed to fetch AI governor policy: ${e.statusText}`);return(await e.json()).data}async function eE(e){let s=await fetch("/api/admin/ai-policy/governor",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to save: ${s.statusText}`)}return(await s.json()).data}async function ew(){let e=await fetch("/api/admin/contact-test",{method:"POST"});if(!e.ok){let s=await e.json().catch(()=>null);throw Error(s?.error??`Failed to send: ${e.statusText}`)}return(await e.json()).data}async function eA(e){let s=await fetch("/api/admin/email-test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templateId:e})});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to send: ${s.statusText}`)}return(await s.json()).data}async function eS(){let e=await fetch("/api/admin/lifecycle-summary-test",{method:"POST"});if(!e.ok){let s=await e.json().catch(()=>null);throw Error(s?.error??`Failed to send: ${e.statusText}`)}return(await e.json()).data}async function eT(e){let s=await fetch("/api/admin/composio-failure-report-test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e?{hours:e}:{})});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to send: ${s.statusText}`)}return(await s.json()).data}async function ek(e){let s=await fetch("/api/admin/langfuse-failure-report-test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e?{hours:e}:{})});if(!s.ok){let e=await s.json().catch(()=>null);throw Error(e?.error??`Failed to send: ${s.statusText}`)}return(await s.json()).data}var eD=t(23431),eI=t(22707),eP=t(44991),e_=t(50703),eO=t(64895);function eR({search:e,onSearchChange:s,planFilter:t,onPlanFilterChange:r,statusFilter:i,onStatusFilterChange:l,createdFilter:o,onCreatedFilterChange:d,onClearFilters:c,hasActiveFilters:u,onRefresh:m,actions:h}){let p=(0,n.t0)();return(0,a.jsxs)("div",{className:"flex flex-col gap-body sm:flex-row sm:items-center",children:[(0,a.jsx)("div",{className:"flex-1",children:(0,a.jsx)(e_.I,{value:e,onCh
1ange:s,placeholder:p.searchByCompanyNameOrId})}),(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-body shrink-0",children:[(0,a.jsxs)(eO.l6,{value:t,onValueChange:e=>r(e),children:[(0,a.jsx)(eO.bq,{className:"w-[150px]",children:(0,a.jsx)(eO.yv,{placeholder:"Plan"})}),(0,a.jsxs)(eO.gC,{children:[(0,a.jsx)(eO.eb,{value:"all",children:p.allPlans}),N.map(e=>(0,a.jsx)(eO.eb,{value:e,children:b[e]},e))]})]}),(0,a.jsxs)(eO.l6,{value:i,onValueChange:e=>l(e),children:[(0,a.jsx)(eO.bq,{className:"w-[160px]",children:(0,a.jsx)(eO.yv,{placeholder:"Status"})}),(0,a.jsxs)(eO.gC,{children:[(0,a.jsx)(eO.eb,{value:"all",children:p.allStatuses}),C.map(e=>(0,a.jsx)(eO.eb,{value:e,children:v[e].label},e))]})]}),(0,a.jsxs)(eO.l6,{value:o,onValueChange:e=>d(e),children:[(0,a.jsx)(eO.bq,{className:"w-[160px]",children:(0,a.jsx)(eO.yv,{placeholder:"Created"})}),(0,a.jsxs)(eO.gC,{children:[(0,a.jsx)(eO.eb,{value:"all",children:p.anyTime}),E.map(e=>(0,a.jsx)(eO.eb,{value:e.value,children:e.label},e.value))]})]}),u&&(0,a.jsxs)(eP.$,{variant:"ghost",size:"small",onClick:c,children:[(0,a.jsx)(eD.A,{className:"icon-body"}),"Clear"]}),(0,a.jsx)(eP.$,{variant:"outline",size:"icon","aria-label":"Refresh",onClick:m,children:(0,a.jsx)(eI.A,{className:"icon-body"})}),h]})]})}var eL=t(59455),eF=t(94089),eM=t(52021),eU=t(55981),e$=t(82671),eK=t(41450),eB=t(27469),eH=t(71519),eq=t(55264),eG=t(1544),ez=t(8272);function eW({company:e,isActive:s,isMember:t,isSupportGrant:r,otherOperators:o,isSwitching:d,isJoining:c,isRevoking:u,onViewDetails:m,onSwitch:h,onRequestAccess:p,onRevokeAccess:x}){let y=(0,n.t0)(),g=(0,n.WD)();return(0,a.jsxs)("div",{className:(0,eH.cn)("flex-between p-large rounded-default border transition-all",s?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[(0,a.jsxs)("div",{className:"flex items-center gap-large min-w-0 flex-1",children:[(0,a.jsxs)(eG.eu,{className:"h-10 w-10 shrink-0",children:[e.logo?(0,a.jsx)(eG.BK,{src:e.logo,alt:e.name}):null,(0,a.jsx)(eG.q5,{children:(0,a.jsx)(i.A,{className:"icon-heading"})})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-small min-w-0",children:[(0,a.jsxs)("div",{className:"flex items-center flex-wrap gap-body min-w-0",children:[(0,a.jsx)("span",{className:"font-medium truncate max-w-full",children:e.name}),r&&(0,a.jsx)(eq.E,{variant:"secondary",className:"text-small h-small bg-amber-100 text-amber-800 border-amber-300",children:y.supportSession}),o.length>0&&(0,a.jsx)(ez.Bc,{children:(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsx)(eq.E,{variant:"secondary",className:"text-small h-small bg-amber-50 text-amber-700 border-amber-200",children:g("settings.inSupportSessionCount",{count:o.length})})}),(0,a.jsx)(ez.ZI,{children:(0,a.jsx)("div",{className:"flex flex-col gap-small",children:o.map(e=>{let s;return(0,a.jsx)("span",{children:(s=e.name||e.email||e.userId,e.expiresAt?`${s} \xb7 until ${(0,eL.r6)(e.expiresAt)}`:s)},e.userId)})})})]})})]}),(0,a.jsx)("span",{className:"text-small text-muted-foreground font-mono truncate max-w-full",children:e.id}),e.description&&(0,a.jsx)("span",{className:"text-small text-muted-foreground max-w-[200px] truncate",children:e.description})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-large shrink-0",children:[(0,a.jsxs)("div",{className:"hidden lg:flex items-center gap-large text-small text-muted-foreground",children:[(0,a.jsxs)("span",{className:"flex items-center gap-small w-[76px]",children:[(0,a.jsx)(eF.A,{className:"icon-small"}),g((e.teamCount??0)===1?"settings.developerSettings.companyTeamCountOne":"settings.developerSettings.companyTeamCount",{count:e.teamCount??0})]}),(0,a.jsxs)("span",{className:"flex items-center gap-small w-[76px]",children:[(0,a.jsx)(l.A,{className:"icon-small"}),g((e.userCount??0)===1?"settings.developerSettings.companyUserCountOne":"settings.developerSettings.companyUserCount",{count:e.userCount??0})]}),(0,a.jsxs)("span",{className:"flex items-center gap-small w-[116px]",children:[(0,a.jsx)(eM.A,{className:"icon-small"}),(0,eL.Yq)(e.createdAt)]})]}),(0,a.jsxs)("div",{className:"flex items-center justify-end gap-small w-[212px]",children:[e.plan&&(0,a.jsx)(eq.E,{variant:"outline",className:"text-small h-small w-[92px] justify-center",children:b[e.plan]}),e.appState&&(0,a.jsx)(ez.Bc,{children:(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsx)(eq.E,{variant:v[e.appState].variant,className:"text-small h-small w-[108px] justify-center cursor-help",children:v[e.appState].label})}),(0,a.jsx)(ez.ZI,{className:"max-w-[260px]",children:v[e.appState].description})]})})]}),(0,a.jsx)("div",{className:"flex items-center justify-end gap-body w-[256px]",children:(0,a.jsxs)(ez.Bc,{children:[(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsxs)(eP.$,{variant:"outline",size:"small",className:"w-[80px]",onClick:()=>m(e.id),children:[(0,a.jsx)(eU.A,{className:"icon-body"}),"Open"]})}),(0,a.jsx)(ez.ZI,{children:y.openCompanyDetails})]}),s&&(0,a.jsxs)(eq.E,{variant:"default",className:"text-small h-small w-[120px] justify-center",children:[(0,a.jsx)(e$.A,{className:"icon-small"}),"Active"]}),t&&!s&&!r&&(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsxs)(eP.$,{variant:"outline",size:"small",className:"w-[120px]",onClick:()=>h(e.id),disabled:d,children:[d?(0,a.jsx)(eI.A,{className:"icon-body animate-spin"}):(0,a.jsx)(e$.A,{className:"icon-body"}),y.setActive]})}),(0,a.jsx)(ez.ZI,{children:y.switchToThisCompany})]}),r&&(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsxs)(eP.$,{variant:"destructive",size:"small",className:"w-[120px]",onClick:()=>x(e.id),disabled:u,children:[u?(0,a.jsx)(eI.A,{className:"icon-body animate-spin"}):(0,a.jsx)(eK.A,{className:"icon-body"}),y.revokeAccess]})}),(0,a.jsx)(ez.ZI,{children:y.endSupportSessionImmediately})]}),!t&&(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsxs)(eP.$,{variant:"default",size:"small",className:"w-[120px]",onClick:()=>
1p(e),disabled:c,children:[c?(0,a.jsx)(eI.A,{className:"icon-body animate-spin mr-small"}):(0,a.jsx)(eB.A,{className:"icon-body"}),y.grantAccess]})}),(0,a.jsx)(ez.ZI,{children:y.startATemporaryAuditedSupportSession})]})]})})]})]})}var eJ=t(77959),eQ=t(4965),eV=t(38339),eY=t(21710);function eX({company:e,isGranting:s,onGrant:t,onClose:r}){let i=(0,n.t0)(),l=(0,n.WD)(),[o,d]=(0,S.useState)(""),c=o.trim().length>=eY.n;function u(){d(""),r()}return(0,a.jsx)(eV.Dz,{open:null!==e,onOpenChange:e=>{e||u()},children:(0,a.jsxs)(eV.Cf,{children:[(0,a.jsxs)(eV.c7,{children:[(0,a.jsx)(eV.L3,{children:i.startSupportSession}),(0,a.jsx)(eV.rr,{children:l("settings.grantsTempAdminAccess",{company:e?.name??i.thisCompany})})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"support-access-reason",children:"Reason"}),(0,a.jsx)(eQ.T,{id:"support-access-reason",value:o,onChange:e=>d(e.target.value),placeholder:i.eGTicket1234BillingFix,rows:3}),o.length>0&&!c&&(0,a.jsxs)("span",{className:"text-small text-destructive",children:["At least ",eY.n," characters."]})]}),(0,a.jsxs)(eV.Es,{children:[(0,a.jsx)(eP.$,{variant:"outline",size:"small",onClick:u,children:"Cancel"}),(0,a.jsxs)(eP.$,{variant:"default",size:"small",disabled:!c||s,onClick:()=>{e&&(t(e.id,o.trim()),d(""))},children:[s&&(0,a.jsx)(eI.A,{className:"icon-body animate-spin mr-small"}),i.startSession]})]})]})})}function eZ({userId:e,locale:s="en",headerAction:t,activeCompanyId:i}){let l=(0,n.t0)(),o=(0,n.WD)(),d=(0,r.useRouter)(),c=(0,r.useParams)(),u=c?.lang||s,m=(0,k.useQueryClient)(),[h,p]=(0,S.useState)(""),[x,y]=(0,S.useState)("all"),[g,f]=(0,S.useState)("all"),[j,b]=(0,S.useState)("all"),[v,N]=(0,S.useState)(null),[C,w]=(0,S.useState)(null),{data:A=[],isLoading:P}=O(),{data:_=[],isLoading:R}=L(),{data:F=[]}=M(),U=K(),$=H(),B=z(),q=(0,S.useMemo)(()=>new Set(_.map(e=>e.companyId)),[_]),G=(0,S.useMemo)(()=>new Map(F.map(e=>[e.companyId,e.accessors])),[F]),W=""!==h.trim()||"all"!==x||"all"!==g||"all"!==j,J=(0,S.useMemo)(()=>{let e,s=h.trim().toLowerCase(),t="all"===j?null:(e=E.find(e=>e.value===j)?.days??0,new Date(Date.now()-24*e*36e5));return A.filter(e=>!(s&&!e.name.toLowerCase().includes(s)&&!e.id.toLowerCase().includes(s)||"all"!==x&&e.plan!==x||"all"!==g&&e.appState!==g||t&&new Date(e.createdAt)<t))},[A,h,x,g,j]),Q=(0,S.useMemo)(()=>{if(W)return J;let e=[],s=[],t=[];for(let a of J)a.id===i?e.push(a):G.has(a.id)?s.push(a):t.push(a);return[...e,...s,...t]},[J,W,i,G]);function V(e){d.push(`/${u}/settings/developer/company/${e}`)}async function Y(e){w(e);try{await U.mutateAsync({companyId:e}),D.me.success(l.developerSettings.toasts.companySwitched,{description:l.developerSettings.toasts.companySwitchedDescription}),d.refresh()}catch(e){D.me.error(o("common.error"),{description:e instanceof Error?e.message:l.developerSettings.toasts.switchCompanyFailed})}finally{w(null)}}async function X(e,s){try{await $.mutateAsync({companyId:e,reason:s}),N(null),await U.mutateAsync({companyId:e}),D.me.success(l.developerSettings.toasts.supportSessionActive,{description:l.developerSettings.toasts.supportSessionActiveDescription}),d.refresh()}catch(e){D.me.error(o("common.error"),{description:e instanceof Error?e.message:l.developerSettings.toasts.startSupportSessionFailed})}}async function Z(e){try{await B.mutateAsync({companyId:e}),D.me.success(l.developerSettings.toasts.accessRevoked,{description:l.developerSettings.toasts.accessRevokedDescription}),d.refresh()}catch(e){D.me.error(o("common.error"),{description:e instanceof Error?e.message:l.developerSettings.toasts.revokeSupportAccessFailed})}}return P||R?(0,a.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,a.jsx)("div",{className:"shrink-0 pt-body pb-body",children:(0,a.jsx)(T.E,{className:"h-body w-full"})}),(0,a.jsx)("div",{className:"flex-1 min-h-0 space-y-large",children:[1,2,3].map(e=>(0,a.jsx)(T.E,{className:"h-20 w-full"},e))})]}):(0,a.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,a.jsx)("div",{className:"shrink-0 pt-body pb-body pr-large",children:(0,a.jsx)(eR,{search:h,onSearchChange:p,planFilter:x,onPlanFilterChange:y,statusFilter:g,onStatusFilterChange:f,createdFilter:j,onCreatedFilterChange:b,onClearFilters:()=>{p(""),y("all"),f("all"),b("all")}
1,hasActiveFilters:W,onRefresh:function(){m.invalidateQueries({queryKey:I.a.companies.all}),D.me.success(l.developerSettings.toasts.refreshed,{description:l.developerSettings.toasts.refreshedDescription})},actions:t})}),(0,a.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto pb-large pr-large",children:(0,a.jsx)("div",{className:"space-y-large",children:0===A.length?(0,a.jsx)("p",{className:"text-muted-foreground text-center py-large",children:l.noCompaniesFound}):0===J.length?(0,a.jsx)("p",{className:"text-muted-foreground text-center py-large",children:l.noCompaniesMatchTheCurrentFilters}):Q.map(s=>{var t,n;let r;return(0,a.jsx)(eW,{company:s,isActive:i===s.id,isMember:q.has(s.id),isSupportGrant:(t=s.id,r=_.find(e=>e.companyId===t),r?.isSupportGrant??!1),otherOperators:(n=s.id,(G.get(n)??[]).filter(s=>s.userId!==e)),isSwitching:C===s.id,isJoining:$.isPending,isRevoking:B.isPending,onViewDetails:V,onSwitch:Y,onRequestAccess:N,onRevokeAccess:Z},s.id)})})}),(0,a.jsx)(eX,{company:v,isGranting:$.isPending,onGrant:X,onClose:()=>N(null)})]})}var e0=t(27115);function e1({companyId:e,currentUserId:s}){let t=(0,n.t0)(),r=(0,n.WD)(),{data:i,isLoading:l,isError:o}=M(),d=z(),c=(0,S.useMemo)(()=>{let s=i?.find(s=>s.companyId===e);return s?[...s.accessors].sort((e,s)=>(e.expiresAt?new Date(e.expiresAt).getTime():1/0)-(s.expiresAt?new Date(s.expiresAt).getTime():1/0)):[]},[i,e]);async function u(){try{await d.mutateAsync({companyId:e,reason:"Ended from the company detail page"}),D.me.success(t.developerSettings.toasts.accessRevoked,{description:t.developerSettings.toasts.accessRevokedDescription})}catch(e){D.me.error(r("common.error"),{description:e instanceof Error?e.message:t.developerSettings.toasts.revokeSupportAccessFailed})}}return(0,a.jsxs)("section",{className:"rounded-default border border-border p-large",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsx)(e0.A,{className:"icon-body text-muted-foreground"}),(0,a.jsx)("h3",{className:"text-body font-semibold",children:t.supportAccessTitle}),c.length>0&&(0,a.jsx)(eq.E,{variant:"secondary",className:"text-small h-small bg-amber-100 text-amber-800 border-amber-300",children:r("settings.inSupportSessionCount",{count:c.length})})]}),(0,a.jsx)("div",{className:"mt-body",children:l?(0,a.jsx)(T.E,{className:"h-body w-64"}):o?(0,a.jsx)("p",{className:"text-small text-destructive",children:t.supportAccessLoadFailed}):0===c.length?(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:t.supportAccessNone}):(0,a.jsx)("ul",{className:"flex flex-col gap-body",children:c.map(e=>{let n=e.userId===s,i=n?t.supportAccessYou:e.name||e.email||e.userId,l=function(e){if(!e.expiresAt)return null;let s=(0,eL.om)(e.expiresAt);return r(new Date(e.expiresAt).getTime()<=Date.now()?"settings.supportAccessExpired":"settings.supportAccessExpires",{date:s})}(e);return(0,a.jsxs)("li",{className:"flex-between gap-body flex-wrap",children:[(0,a.jsxs)("div",{className:"flex flex-col min-w-0",children:[(0,a.jsxs)("span",{className:"text-body truncate",children:[i,n&&e.email?` \xb7 ${e.email}`:""]}),l&&(0,a.jsx)("span",{className:"text-small text-muted-foreground",children:l})]}),n?(0,a.jsx)(ez.Bc,{children:(0,a.jsxs)(ez.m_,{children:[(0,a.jsx)(ez.k$,{asChild:!0,children:(0,a.jsxs)(eP.$,{variant:"destructive",size:"small",onClick:()=>void u(),disabled:d.isPending,children:[d.isPending?(0,a.jsx)(eI.A,{className:"icon-body animate-spin"}):(0,a.jsx)(eK.A,{className:"icon-body"}),t.revokeAccess]})}),(0,a.jsx)(ez.ZI,{children:t.endSupportSessionImmediately})]})}):(0,a.jsx)("span",{className:"text-small text-muted-foreground",children:t.supportAccessSelfRevokeOnly})]},e.userId)})})})]})}var e2=t(64253),e4=t(68256),e3=t(2793),e6=t(75279),e5=t(25069);function e9(){let e=(0,n.t0)(),{data:s,isLoading:t,refetch:r}=Q(),{data:i=[]}=X(),l=V(),[o,d]=(0,S.useState)({defaultTrialDays:7,enableAutoTrial:!0,trialPlanId:null,maxTrialSeats:null});async function c(){try{await l.mutateAsync(o),D.me.success(e.developerSettings.toasts.trialConfigSaved)}catch{D.me.error(e.developerSettings.toasts.saveTrialConfigFailed,{description:e.developerSettings.toasts.pleaseTryAgain})}}return(0,S.useEffect)(()=>
1{if(s){let e=s.config??s;e&&d(e)}},[s]),(0,a.jsxs)(e5.Card,{children:[(0,a.jsx)(e5.CardHeader,{children:(0,a.jsxs)("div",{className:"flex-between",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(e2.A,{className:"icon-heading"}),e.globalTrialSettings]}),(0,a.jsx)(e5.CardDescription,{children:e.defaultsAppliedToEveryNewCompany})]}),(0,a.jsx)(eP.$,{onClick:()=>r(),variant:"ghost",size:"icon",disabled:t,children:(0,a.jsx)(eI.A,{className:`icon-body ${t?"animate-spin":""}`})})]})}),(0,a.jsx)(e5.CardContent,{children:t?(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsx)(T.E,{className:"h-10 w-full"}),(0,a.jsx)(T.E,{className:"h-10 w-2/3"})]}):(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"grid gap-large md:grid-cols-3",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"trialDays",children:e.trialDurationDays2}),(0,a.jsx)(e3.p,{id:"trialDays",type:"number",min:1,max:365,value:o.defaultTrialDays,onChange:e=>d(s=>({...s,defaultTrialDays:Number.parseInt(e.target.value,10)||0}))})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"maxTrialSeats",children:e.trialSeats}),(0,a.jsx)(e3.p,{id:"maxTrialSeats",type:"text",disabled:!0,value:"10 (managed per plan since 2026-05-21)"})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"trialPlanId",children:e.trialPlan}),(0,a.jsxs)(eO.l6,{value:o.trialPlanId??"__none__",onValueChange:e=>d(s=>({...s,trialPlanId:"__none__"===e?null:e})),children:[(0,a.jsx)(eO.bq,{id:"trialPlanId",children:(0,a.jsx)(eO.yv,{placeholder:e.noneFreeLimits2})}),(0,a.jsxs)(eO.gC,{children:[(0,a.jsx)(eO.eb,{value:"__none__",children:e.noneFreeLimits}),i.map(e=>(0,a.jsx)(eO.eb,{value:e.id,children:e.displayName},e.id))]})]})]})]}),(0,a.jsxs)("div",{className:"flex-between rounded-default border p-large",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(eJ.J,{children:e.autoStartTrials}),(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:e.automaticallyStartATrialWhenA})]}),(0,a.jsx)(e6.d,{checked:o.enableAutoTrial,onCheckedChange:e=>d(s=>({...s,enableAutoTrial:e}))})]}),(0,a.jsx)("div",{className:"flex justify-end",children:(0,a.jsxs)(eP.$,{onClick:c,disabled:l.isPending,children:[(0,a.jsx)(e4.A,{className:"mr-body icon-body"}),l.isPending?"Saving...":"Save"]})})]})})]})}var e7=t(58951),e8=t(14915),se=t(71612),ss=t(75475);function st({company:e,onClose:s,onSuccess:t}){let r,i=(0,n.t0)(),l=(0,n.WD)(),[o,d]=(0,S.useState)(7),[c,u]=(0,S.useState)(""),m=et();async function h(){if(!e)return;let s=new Date((e.CompanySubscription?.trialEndsAt?new Date(e.CompanySubscription.trialEndsAt):new Date).getTime()+864e5*o);try{let a=o>=0,n=Math.abs(o);await m.mutateAsync({companyId:e.id,trialEndsAt:s.toISOString(),reason:c.trim()||`${a?"Extended":"Shortened"} by ${n} days via developer panel`}),D.me.success(a?i.developerSettings.toasts.trialExtended:i.developerSettings.toasts.trialShortened,{description:l(a?"settings.developerSettings.toasts.trialExtendedByDays":"settings.developerSettings.toasts.trialShortenedByDays",{count:n})}),d(7),u(""),t()}catch{D.me.error(l("common.error"),{description:i.developerSettings.toasts.adjustTrialFailed})}}return(0,a.jsxs)(eV.lG,{open:!!e,onOpenChange:e=>{e||s()},closeOnAction:!1,title:i.adjustTrial,description:e?l("settings.adjustTrialDescription",{company:e.name,currentEnd:e.CompanySubscription?.trialEndsAt?l("settings.currentEndDate",{date:(0,eL.Yq)(e.CompanySubscription.trialEndsAt)}):i.noCurrentEndDate}):void 0,actions:[{label:"Cancel",onClick:s,variant:"outline"},{label:m.isPending?i.saving:o>0?l("settings.extendByDays",{count:o}):o<0?l("settings.shortenByDays",{count:-o}):i.apply,onClick:h,disabled:m.isPending||0===o}],children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)(eJ.J,{htmlFor:"extendDays",children:[i.changeByDays," ",(0,a.jsx)("span",{className:"text-muted-foreground font-normal",children:i.negativeShortens})]}),(0,a.jsx)(e3.p,{id:"extendDays",type:"number",min:-3650,max:3650,value:o,onChange:e=>{let s=Number.parseInt(e.target.value,10);d(Number.isNaN(s)?0:s)}}),e&&0!==o&&(0,a.jsxs)("p",{className:"text-small text-muted-foreground",children:[i.newEnd," ",(r=new Date((e.CompanySubscription?.trialEndsAt?new Date(e.CompanySubscription.tri
1alEndsAt):new Date).getTime()+864e5*o),(0,eL.Yq)(r))]})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"extendReason",children:i.reasonOptional}),(0,a.jsx)(e3.p,{id:"extendReason",placeholder:i.eGCustomerRequestedExtension,value:c,onChange:e=>u(e.target.value)})]})]})}function sa({open:e,companies:s,defaultDays:t,onClose:r,onSuccess:i}){let l=(0,n.t0)(),o=(0,n.WD)(),[d,c]=(0,S.useState)(""),[u,m]=(0,S.useState)(null),[h,p]=(0,S.useState)(t),[x,y]=(0,S.useState)(""),g=ea(),f=(0,S.useMemo)(()=>{if(!d)return s;let e=d.toLowerCase();return s.filter(s=>s.name.toLowerCase().includes(e))},[s,d]);function j(){m(null),c(""),y(""),r()}async function b(){if(u)try{await g.mutateAsync({companyId:u,reason:x.trim()||"Moved to trial via developer panel"}),D.me.success(l.developerSettings.toasts.trialStarted,{description:o("settings.developerSettings.toasts.trialStartedDescription",{days:h})}),j(),i()}catch(e){D.me.error(l.developerSettings.toasts.startTrialFailed,{description:e instanceof Error?e.message:l.developerSettings.toasts.pleaseTryAgain})}}return(0,a.jsxs)(eV.lG,{open:e,onOpenChange:e=>{e||j()},closeOnAction:!1,size:"2xl",title:l.moveCompanyToTrial,description:"Select a company that is not currently in a trial",actions:[{label:"Cancel",onClick:j,variant:"outline"},{label:g.isPending?"Starting...":"Move to trial",onClick:b,disabled:!u||g.isPending}],children:[(0,a.jsx)(e3.p,{icon:(0,a.jsx)(e8.A,{}),iconPosition:"left",placeholder:l.searchCompanies2,value:d,onChange:e=>c(e.target.value)}),(0,a.jsx)("div",{className:"max-h-[420px] overflow-y-auto",children:0===f.length?(0,a.jsx)("div",{className:"py-12 text-center text-muted-foreground text-small",children:l.noCompaniesFound2}):(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{className:"[&_th]:sticky [&_th]:top-0 [&_th]:z-10 [&_th]:bg-background [&_th]:border-b",children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{className:"w-12"}),(0,a.jsx)(ss.nd,{children:"Company"}),(0,a.jsx)(ss.nd,{className:"w-24",children:"Users"}),(0,a.jsx)(ss.nd,{children:l.currentPlan2})]})}),(0,a.jsx)(ss.BF,{children:f.map(e=>{let s=e.CompanySubscription?.PaymentPlan?.displayName??e.CompanySubscription?.status??"No plan",t=u===e.id;
1return(0,a.jsxs)(ss.Hj,{className:t?"bg-primary/5 cursor-pointer":"cursor-pointer hover:bg-muted/50",onClick:()=>m(e.id),children:[(0,a.jsx)(ss.nA,{children:(0,a.jsx)("input",{type:"radio",checked:t,onChange:()=>m(e.id)})}),(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)("div",{className:"font-medium",children:e.name}),(0,a.jsx)("div",{className:"text-mini text-muted-foreground",children:e.id})]}),(0,a.jsx)(ss.nA,{children:e._count.UserCompanyRole}),(0,a.jsx)(ss.nA,{children:s})]},e.id)})})]})}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-large",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"moveDays",children:l.trialDurationDays}),(0,a.jsx)(e3.p,{id:"moveDays",type:"number",min:1,max:3650,value:h,onChange:e=>p(Number.parseInt(e.target.value,10)||1)})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"moveReason",children:l.reasonOptional2}),(0,a.jsx)(e3.p,{id:"moveReason",placeholder:l.eGPartnerOutreach,value:x,onChange:e=>y(e.target.value)})]})]})]})}function sn({defaultTrialDays:e=7}){let s=(0,n.t0)(),t=(0,n.WD)();(0,k.useQueryClient)();let[r,l]=(0,S.useState)(""),[o,d]=(0,S.useState)(null),[c,u]=(0,S.useState)(!1),{data:m=[],isLoading:h,refetch:p}=(0,P.useQuery)({queryKey:["admin","companies","billing"],queryFn:async()=>{let e=await fetch("/api/admin/companies");if(!e.ok)throw Error("Failed to fetch companies");let s=await e.json(),t=s.data?.companies??s.companies??[];return Array.isArray(t)?t:[]},staleTime:3e5}),x=en(),y=(0,S.useMemo)(()=>m.filter(e=>e.CompanySubscription?.status==="trialing"),[m]),g=(0,S.useMemo)(()=>{if(!r)return y;let e=r.toLowerCase();return y.filter(s=>s.name.toLowerCase().includes(e))},[y,r]),f=(0,S.useMemo)(()=>m.filter(e=>e.CompanySubscription?.status!=="trialing"),[m]);async function j(e){try{await x.mutateAsync({companyId:e,reason:"Ended by admin via developer panel"}),D.me.success(s.developerSettings.toasts.trialEnded,{description:s.developerSettings.toasts.trialEndedDescription}),p()}catch(e){D.me.error(s.developerSettings.toasts.endTrialFailedTitle,{description:e instanceof Error?e.message:s.developerSettings.toasts.pleaseTryAgain})}}return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(e5.Card,{children:[(0,a.jsx)(e5.CardHeader,{children:(0,a.jsxs)("div",{className:"flex-between",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(i.A,{className:"icon-heading"}),t("settings.trialCompaniesCount",{count:y.length})]}),(0,a.jsx)(e5.CardDescription,{children:s.companiesCurrentlyInATrialPeriod})]}),(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsx)(eP.$,{onClick:()=>p(),variant:"ghost",size:"icon",disabled:h,children:(0,a.jsx)(eI.A,{className:`icon-body ${h?"animate-spin":""}`})}),(0,a.jsxs)(eP.$,{onClick:()=>u(!0),children:[(0,a.jsx)(e7.A,{className:"mr-body icon-body"}),s.moveCompanyToTrial]})]})]})}),(0,a.jsxs)(e5.CardContent,{children:[(0,a.jsx)("div",{className:"mb-large",children:(0,a.jsx)(e3.p,{icon:(0,a.jsx)(e8.A,{}),iconPosition:"left",placeholder:s.searchCompanies3,value:r,onChange:e=>l(e.target.value)})}),h?(0,a.jsx)("div",{className:"space-y-body",children:[void 0,void 0,void 0].map((e,s)=>(0,a.jsx)(T.E,{className:"h-16 w-full"},s))}):0===g.length?(0,a.jsx)("div",{className:"py-large text-center text-muted-foreground",children:r?"No matching trial companies":"No companies currently in trial"}):(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{children:"Company"}),(0,a.jsx)(ss.nd,{children:"Users"}),(0,a.jsx)(ss.nd,{children:s.daysLeft}),(0,a.jsx)(ss.nd,{children:"Status"}),(0,a.jsx)(ss.nd,{className:"text-right",children:"Actions"})]})}),(0,a.jsx)(ss.BF,{children:g.map(s=>{var n,r,i;let l=s.CompanySubscription,o=(n=l?.trialEndsAt??null)?Math.ceil((new Date(n).getTime()-Date.now())/864e5):null,c=(r=l?.trialStartedAt??null,i=l?.trialEndsAt??null,!!r&&!!i&&(new Date(i).getTime()-new Date(r).getTime())/864e5>e+.5);return(0,a.jsxs)(ss.Hj,{children:[(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)("div",{className:"font-medium",children:s.name}),(0,a.jsx)("div",{className:"text-mini text-muted-foreground",children:s.id})]}),(0,a.jsx)(ss.nA,{children:s._count.UserCompanyRole}),(0,a.jsx)(ss.nA,{children:null===o?"—":o<=0?(0,a.jsx)("span",{className:"text-destructive",children:"Expired"}):t("settings.daysCount",{count:o})}),(0,a.jsx)(ss.nA,{children:c?(0,a.jsx)(eq.E,{variant:"secondary",children:"Extended"}):(0,a.jsx)(eq.E,{variant:"outline",children:"Standard"})}),(0,a.jsxs)(ss.nA,{className:"text-right space-x-body",children:[(0,a.jsxs)(eP.$,{variant:"ghost",size:"small",onClick:()=>d(s),children:[(0,a.jsx)(eM.A,{className:"mr-mini icon-body"}),"Adjust"]}),(0,a.jsxs)(eP.$,{variant:"ghost",size:"small",onClick:()=>j(s.id),children:[(0,a.jsx)(se.A,{className:"mr-mini icon-body text-destructive"}),"End"]})]})]},s.id)})})]})]})]}),(0,a.jsx)(st,{company:o,onClose:()=>d(null),onSuccess:function(){d(null),p()}}),(0,a.jsx)(sa,{open:c,companies:f,defaultDays:e,onClose:()=>u(!1),onSuccess:function(){u(!1),p()}})]})}function sr(){return(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsx)(e9,{}),(0,a.jsx)(sn,{})]})}var si=t(30710);function sl(){let e,s=(0,n.t0)(),t=(0,n.WD)(),{data:r,isLoading:i}=ed(),l=(e=(0,k.useQueryClient)(),(0,U.useMutation)({mutationFn:e=>eo({adminRateLimitPerMin:e}),onSuccess:()=>e.invalidateQueries({queryKey:I.a.systemConfig}),meta:{notify:{action:"save",entity:"setting"}}})),[o,d]=(0,S.useState)("");(0,S.useEffect)(()=>{r&&d(String(r.adminRateLimitPerMin))},[r]);let c=r?.bounds.min??1,u=r?.bounds.max??60,m=Number(o),h=Number.isInteger(m)&&m>=c&&m<=u,p=null!=r&&m!==r.adminRateLimitPerMin;async function x(){h&&p&&await l.mutateAsync(m)}return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(si.A,{className:"icon-heading"}),s.adminActionRateLimit]}),(0,a.jsx)(e5.CardDescription,{children:"Max privileged admin mutations per operator per minute, across every developer-settings action. The SOC\xa02 default is 2/min; raising it loosens the throttle. Changes are audited and apply within ~30s."})]}),(0,a.jsxs)(e5.CardContent,{children:[i?(0,a.jsx)(T.E,{className:"h-10 w-48"}):(0,a.jsxs)("div",{className:"flex items-end gap-body",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"adminRateLimit",children:s.actionsPerMinute}),(0,a.jsx)(e3.p,{id:"adminRateLimit",type:"number",min:c,max:u,step:1,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&x()},className:"w-32 tabular-nums"})]}),(0,a.jsxs)(eP.$,{onClick:x,disabled:!h||!p||l.isPending,loading:l.isPending,children:[(0,a.jsx)(e4.A,{className:"mr-body icon-body"}),"Save"]})]}),!h&&""!==o&&(0,a.jsx)("p",{className:"mt-body text-mini text-destructive",children:t("settings.enterWholeNumberBetween",{min:c,max:u})}),r?.rateLimitEnforced===!1&&(0,a.jsx)("p",{className:"mt-body text-mini text-destructive",children:"NOT ENFORCED on this deployment — Redis is not configured, so this limit (and every other rate limit) fails open."})]})]})}var so=t(66665);function sd(){let e,s=(0,n.t0)(),t=(0,n.WD)(),{data:r,isLoading:i}=ed(),l=(e=(0,k.useQueryClient)(),(0,U.useMutation)({mutationFn:e=>eo({adminDestructiveRateLimitPerHour:e}),onSuccess:()=>e.invalidateQueries({queryKey:I.a.systemConfig}),meta:{notify:{action:"save",entity:"setting"}}})),[o,d]=(0,S.useState)("");(0,S.useEffect)(()=>{r&&d(String(r.adminDestructiveRateLimitPerHour))},[r]);let c=r?.destructiveBounds.min??1,u=r?.destructiveBounds.max??10,m=Number(o),h=Number.isInteger(m)&&m>=c&&m<=u,p=null!=r&&m!==r.adminDestructiveRateLimitPerHour;async function x(){h&&p&&await l.mutateAsync(m)}return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(so.A,{className:"icon-heading"}),s.adminDestructiveRateLimit]}),(0,a.jsx)(e5.CardDescription,{children:"Max retries of a destructive action (takedown, purge, cancel-draft, force-unenroll-MFA, company/user delete, …) against the same target within an hour. The SOC\xa02 default is 1/hour; raising it only shortens the lockout on a single target — it does not loosen the per-actor throttle above. Changes are audited and apply within ~30s."})]}),(0,a.jsxs)(e5.CardContent,{children:[i?(0,a.jsx)(T.E,{className:"h-10 w-48"}):(0,a.jsxs)("div",{className:"flex items-end gap-body",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"adminDestructiveRateLimit",children:s.attemptsPerTargetPerHour}),(0,a.jsx)(e3.p,{id:"adminDestructiveRateLimit",type:"number",min:c,max:u,step:1,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&x()},className:"w-32 tabular-nums"})]}),(0,a.jsxs)(eP.$,{onClick:x,disabled:!h||!p||l.isPending,loading:l.isPending,children:[(0,a.jsx)(e4.A,{className:"mr-body icon-body"}),"Save"]})]}),!h&&""!==o&&(0,a.jsx)("p",{className:"mt-body text-mini text-destructive",children:t("settings.enterWholeNumberBetween",{min:c,max:u})}),r?.rateLimitEnforced===!1&&(0,a.jsx)("p",{className:"mt-body text-mini text-destructive",children:"NOT ENFORCED on this deployment — Redis is not configured, so this limit (and every other rate limit) fails open."})]})]})}var sc=t(62468),su=t(46578),sm=t(54351),sh=t(75102);let sp=["Mo","Tu","We","Th","Fr","Sa","Su"];function sx(e){return String(e).padStart(2,"0")}
1function sy({value:e,onChange:s,disabled:t,placeholder:r="Pick a date…",className:i}){let l=(0,n.xu)(),o=(0,n.Ym)(),d=e?new Date(e):null,c=d&&!Number.isNaN(d.getTime())?d:null,[u,m]=(0,S.useState)((c??new Date).getUTCFullYear()),[h,p]=(0,S.useState)((c??new Date).getUTCMonth()),x=(0,S.useMemo)(()=>new Intl.DateTimeFormat(o,{month:"long",timeZone:"UTC"}).format(new Date(Date.UTC(u,h,1))),[o,h,u]),y=e=>{let s=new Date(Date.UTC(u,h+e,1));m(s.getUTCFullYear()),p(s.getUTCMonth())},g=(0,S.useId)();return(0,a.jsxs)(sh.AM,{children:[(0,a.jsx)(sh.Wv,{asChild:!0,children:(0,a.jsxs)(eP.$,{variant:"outline",disabled:t,className:(0,eH.cn)("justify-start gap-body font-normal",i),children:[(0,a.jsx)(eM.A,{className:"icon-body"}),c?`${c.getUTCFullYear()}-${sx(c.getUTCMonth()+1)}-${sx(c.getUTCDate())} ${sx(c.getUTCHours())}:${sx(c.getUTCMinutes())} UTC`:r]})}),(0,a.jsx)(sh.hl,{className:"w-auto p-body",children:(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"flex-between gap-body",children:[(0,a.jsx)(eP.$,{variant:"ghost",size:"small","aria-label":l.previousMonth,onClick:()=>y(-1),children:(0,a.jsx)(su.A,{className:"icon-body"})}),(0,a.jsxs)("span",{className:"text-body font-medium",children:[x," ",u]}),(0,a.jsx)(eP.$,{variant:"ghost",size:"small","aria-label":l.nextMonth,onClick:()=>y(1),children:(0,a.jsx)(sm.A,{className:"icon-body"})})]}),(0,a.jsxs)("div",{role:"grid",className:"grid grid-cols-7 gap-mini",children:[sp.map(e=>(0,a.jsx)("div",{className:"text-center text-mini text-muted-foreground",children:e},e)),Array.from({length:(new Date(Date.UTC(u,h,1)).getUTCDay()+6)%7}).map((e,s)=>(0,a.jsx)("div",{},`blank-${u}-${h}-${s}`)),Array.from({length:new Date(Date.UTC(u,h+1,0)).getUTCDate()}).map((e,t)=>{let n=t+1;return(0,a.jsx)(eP.$,{variant:c&&c.getUTCFullYear()===u&&c.getUTCMonth()===h&&c.getUTCDate()===n?"default":"ghost",size:"small",className:"h-small w-small tabular-nums",onClick:()=>{let e;return e=c??new Date,void s(new Date(Date.UTC(u,h,n,c?e.getUTCHours():0,c?e.getUTCMinutes():0,0,0)).toISOString())},children:n},n)})]}),(0,a.jsxs)("div",{className:"space-y-mini",children:[(0,a.jsx)(eJ.J,{htmlFor:g,className:"text-mini",children:"Time (UTC)"}),(0,a.jsx)(e3.p,{id:g,type:"time",value:c?`${sx(c.getUTCHours())}:${sx(c.getUTCMinutes())}`:"00:00",onChange:e=>(e=>{let[t,a]=e.split(":").map(Number);if(!Number.isFinite(t)||!Number.isFinite(a))return;let n=c??new Date;s(new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),t,a,0,0)).toISOString())})(e.target.value),className:"tabular-nums"})]}),(0,a.jsxs)("div",{className:"flex-between gap-body",children:[(0,a.jsx)(eP.$,{variant:"ghost",size:"small",onClick:()=>s(null),children:"Clear"}),(0,a.jsx)(eP.$,{variant:"outline",size:"small",onClick:()=>s(new Date().toISOString()),children:"Now"})]})]})})]})}function sg(){let{data:e,isLoading:s}=function(e=!0){return(0,P.useQuery)({queryKey:I.a.cronConfig,queryFn:ec,staleTime:6e4,enabled:e})}();return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(e2.A,{className:"icon-heading"}),"Cron knobs"]}),(0,a.jsx)(e5.CardDescription,{children:"Live configuration for scheduled jobs (config beats the legacy env var, which beats the built-in default). Crons fire on production only. Changes are audited and apply within ~30s — no redeploy."})]}),(0,a.jsx)(e5.CardContent,{className:"space-y-large",children:s||!e?(0,a.jsx)(T.E,{className:"h-24 w-full"}):e.knobs.map(e=>(0,a.jsx)(sj,{knob:e},e.key))})]})}let sf={config:"set here",env:"legacy env var",default:"default"};function sj({knob:e}){let s=em(),[t,n]=(0,S.useState)(null),r=t=>s.mutate({key:e.key,value:t});return(0,a.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-body border-b border-border pb-body last:border-b-0 last:pb-0",children:[(0,a.jsxs)("div",{className:"min-w-0 flex-1 space-y-mini",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsx)("code",{className:"text-small",children:e.key}),(0,a.jsx)("span",{className:"rounded-default bg-muted px-small text-mini text-muted-foreground",children:sf[e.source]})]}),(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:e.description})]}),(0,a.jsxs)("div",{className:"flex items-center gap-body",children:["bool"===e.type&&(0,a.jsx)(e6.d,{checked:!0===e.value,disabled:s.isPending,onCheckedChange:e=>r(e)}),"int"===e.type&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(e3.p,{type:"number",min:e.bounds?.min,max:e.bounds?.max,value:t??String(e.value??""),onChange:e=>n(e.target.value),className:"w-28 tabular-nums"}),(0,a.jsx)(eP.$,{size:"small",disabled:s.isPending||null===t||!Number.isInteger(Number(t)),loading:s.isPending,onClick:()=>{r(Number(t)),n(null)},children:(0,a.jsx)(e4.A,{className:"icon-body"})})]}),"isoDate"===e.type&&(0,a.jsx)(sy,{value:"string"==typeof e.value?e.value:null,disabled:s.isPending,onChange:e=>r(e),className:"w-64"}),"config"===e.source&&(0,a.jsx)(eP.$,{size:"small",variant:"ghost",title:"Clear the config row — fall back to env/default",disabled:s.isPending,onClick:()=>{r(null),n(null)},children:(0,a.jsx)(sc.A,{className:"icon-body"})})]})]})}var sb=t(29146),sv=t(82247);function sN(){let{data:e,isLoading:s}=(0,P.useQuery)({queryKey:I.a.cronOverview,queryFn:eh,staleTime:3e4,refetchOnWindowFocus:!0});return s||!e?(0,a.jsx)(T.E,{className:"h-64 w-full"}):(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsx)(e5.CardTitle,{children:"Scheduled jobs"}),(0,a.jsxs)(e5.CardDescription,{children:["All ",e.jobs.length," cron routes. Schedules are baked from vercel.json at build time; heartbeats come from every execution (production fires on schedule — elsewhere only manual runs appear). Toggling a switch is audited and stops the job on its next fire."]})]}),(0,a.jsx)(e5.CardContent,{children:(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)(sv.XI,{children:[(0,a.jsx)(sv.A0,{children:(0,a.jsxs)(sv.Hj,{children:[(0,a.jsx)(sv.nd,{children:"Job"}),(0,a.jsx)(sv.nd,{children:"Schedule (UTC)"}),(0,a.jsx)(sv.nd,{children:"Enabled"}),(0,a.jsx)(sv.nd,{children:"Last run"}),(0,a.jsx)(sv.nd,{className:"text-right",children:"Duration"}),(0,a.jsx)(sv.nd,{className:"text-right",children:"Errors 7d"})]})}),(0,a.jsx)(sv.BF,{children:e.jobs.map(e=>(0,a.jsx)(sC,{row:e},e.job))})]})})})]}),(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsx)(e5.CardTitle,{children:"Outside the app (read-only)"}),(0,a.jsx)(e5.CardDescription,{children:"Scheduled automation controlled in other systems — listed for the full picture, edited at the source."})]}),(0,a.jsx)(e5.CardContent,{className:"space-y-body",children:e.external.map(e=>(0,a.jsxs)("div",{className:"flex flex-wrap items-baseline gap-body",children:[(0,a.jsx)(eq.E,{variant:"outline",children:e.system}),(0,a.jsx)("span",{className:"text-body font-medium",children:e.name}),(0,a.jsx)("code",{className:"text-small text-muted-foreground",children:e.schedule}),(0,a.jsx)("span",{className:"text-small text-muted-foreground",children:e.note})]},`${e.system}:${e.name}`))})]})]})}function sC({row:e}){let s=em();return(0,a.jsxs)(sv.Hj,{children:[(0,a.jsx)(sv.nA,{children:(0,a.jsx)("code",{className:"text-small",children:e.job})}),(0,a.jsx)(sv.nA,{children:e.schedule?(0,a.jsx)("code",{className:"text-small",children:e.schedule}):(0,a.jsx)("span",{className:"text-small text-muted-foreground",children:"manual only"})}),(0,a.jsx)(sv.nA,{children:(0,a.jsx)(e6.d,{checked:e.enabled,disabled:s.isPending,onCheckedChange:t=>s.mutate({key:`cron.job.${e.job}.enabled`,value:t})})}),(0,a.jsx)(sv.nA,{children:(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[e.wedged?(0,a.jsxs)(eq.E,{variant:"destructive",children:[(0,a.jsx)(sb.A,{className:"mr-mini icon-small"}),"wedged"]}):e.lastRun?"success"===e.lastRun.outcome?(0,a.jsx)(eq.E,{variant:"success",children:"success"}):"error"===e.lastRun.outcome?(0,a.jsx)(eq.E,{variant:"destructive",children:"error"}):"disabled"===e.lastRun.outcome?(0,a.jsx)(eq.E,{variant:"secondary",children:"skipped"}):(0,a.jsx)(eq.E,{variant:"secondary",children:"running"}):(0,a.jsx)(eq.E,{variant:"outline",children:"never ran"}),e.lastRun&&(0,a.jsx)("span",{className:"text-small text-muted-foreground",title:e.lastRun.error??void 0,children:function(e){let s=Math.round((Date.now()-new Date(e).getTime())/6e4);if(s<1)return"just now";if(s<60)return`${s}m ago`;let t=Math.round(s/60);return t<48?`${t}h ago`:`${Math.round(t/24)}d ago`}(e.lastRun.startedAt)})]})}),(0,a.jsx)(sv.nA,{className:"text-right text-small tabular-nums",children:e.lastRun?.durationMs!=null?`${(e.lastRun.durationMs/1e3).toFixed(1)}s`:"—"}),(0,a.jsx)(sv.nA,{className:"text-right text-small tabular-nums",children:e.errors7d>0?(0,a.jsx)("span",{className:"text-destructive",children:e.errors7d}):"0"})]})}var sE=t(35076),sw=t(29403),sA=t(39825),sS=t(50363),sT=t(35622);let sk="key-name:";function sD(e){if(!e)return null;let s=e.signal??"",t="SECRET"===e.classify;if(s.startsWith(sk)){let e=s.slice(sk.length),a=(0,sT.N9)(e);return{kind:"key-name",label:"key name",explanation:t?a?`The field is named as a credential ("${e}"), so its value is one whatever it looks like. This cannot be reclassified.`:`Only part of the name matched ("${e}" merely contains a credential word) — a known over-fire, so this one can be reclassified after checking the field.`:`Proposed from the field's name ("${e}").`,overridable:!t||!a}}if("shape:signed-url"===s)return{kind:"signed-url",label:"signed URL",explanation:"The URL carries its own signature or token — anyone holding the string holds the access it grants. This cannot be reclassified.",overridable:!1};if("entropy"===s)return{kind:"entropy",label:"entropy",explanation:"A high-entropy sampled value. Timestamps, commit hashes and opaque ids trip this too — a documented false positive, so this one can be reclassified once the field is understood.",overridable:!0};if(s.startsWith("shape:")){let e=s.slice(6);return{kind:"shape",label:`${e} shape`,explanation:`Proposed from the shape of the sampled value (${e}).`,overridable:!t}}return{kind:"unknown",label:s||"no signal",explanation:t?"The signal behind this proposal is not one this build recognises, so it is treated as binding.":"No recorded signal for this proposal.",overridable:!t}}let sI=["SAFE","PII","INTERNAL_ID","SECRET"],sP=["raw","hash","domain_only","count_only","drop"];function s_({failure:e}){return(0,a.jsxs)(sS.Fc,{variant:e.retryable?"default":"destructive",children:[(0,a.jsx)(sb.A,{className:"icon-body"}),(0,a.jsx)(sS.XL,{children:e.title}),(0,a.jsx)(sS.TN,{children:e.message})]})}function sO({target:e,onClose:s}){let{data:t,isLoading:n,error:r}
1=ej(e?.integrationSlug??null,e?.realActionName??null),i=eb(),[l,o]=(0,S.useState)({}),[d,c]=(0,S.useState)(""),[u,m]=(0,S.useState)(null);(0,S.useEffect)(()=>{o({}),c(""),m(null)},[e?.integrationSlug,e?.realActionName]);let h=(0,S.useMemo)(()=>new Set(t?.reviewedPaths??[]),[t?.reviewedPaths]),p=Object.entries(l),x=p.length>0,y=p.filter(([,e])=>"drop"!==e.transform&&"SECRET"!==e.classify).length;async function g(){if(e&&x){m(null);try{let a=await i.mutateAsync({integrationSlug:e.integrationSlug,realActionName:e.realActionName,reason:d.trim(),entries:p.map(([e,s])=>({path:e,classify:s.classify,transform:s.transform,sampleBasis:t?.frontier.find(s=>s.path===e)?.occurrences,suggestedBy:s.fromProposal?"preclassifier@v1":null}))}),n=a.coercedSecretPaths.length>0?`. ${a.coercedSecretPaths.length} SECRET field(s) were force-dropped.`:"";D.me.success("Export rule updated",{description:`${a.widenedPaths.length} field(s) now reveal more for ${a.toolKey} — applies to every tenant${n}`}),s()}catch(s){let e=function(e){if(e instanceof ey&&429===e.status){let s=e.retryAfterSeconds,t=s&&s>0?`Wait about ${s} second${1===s?"":"s"}`:"Wait a moment";return{title:"Not saved yet, nothing lost",message:`Rate limit reached. Admin actions are capped per minute, so nothing was saved and nothing was lost: your verdicts and justification are still here. ${t} and press Promote again.`,retryable:!0}}let s=e instanceof Error&&e.message?e.message:"Unknown error";return{title:"Promotion failed",message:`Promotion failed: ${s}. Your verdicts and justification are kept, so you can correct and retry.`,retryable:!1}}(s);m(e),D.me.error(e.title,{description:e.message})}}}let f=d.trim().length>=eY.n;return(0,a.jsx)(eV.lG,{open:!!e,onOpenChange:e=>{e||s()},closeOnAction:!1,preventCloseOnEscape:x,preventCloseOnOverlayClick:x,size:"2xl",title:"Review export fields",description:e?`${e.integrationSlug} \xb7 ${e.realActionName} — this rule is PLATFORM-GLOBAL: it changes what every tenant's exports of this action reveal, not one company's. Paths you leave untouched stay denied.`:void 0,actions:[{label:"Cancel",onClick:s,variant:"outline"},{label:i.isPending?"Saving…":`Promote ${y} field(s)`,onClick:g,disabled:i.isPending||!x||!f}],children:n?(0,a.jsx)(T.E,{className:"h-64 w-full"}):r?(0,a.jsx)("p",{className:"text-body text-destructive",children:r instanceof Error?r.message:"Failed to sample"}):t&&0!==t.frontier.length?(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-body text-mini text-muted-foreground",children:[(0,a.jsxs)("span",{className:"flex items-center gap-small",children:[(0,a.jsx)(sw.A,{className:"icon-body"}),t.frontier.length," paths sampled"]}),(0,a.jsxs)("span",{children:[h.size," already reviewed"]}),(0,a.jsx)("span",{children:"values are never shown — types and proposals only"})]}),(0,a.jsx)("div",{className:"max-h-96 overflow-y-auto space-y-small",children:t.frontier.map(e=>{var s;let t=l[e.path],n=(s=e.proposal,s?.classify!=="SECRET"||sD(s)?.overridable?sI:sI.filter(e=>"SECRET"===e));return(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-body border-b border-border/50 pb-small",children:[(0,a.jsx)("code",{className:"flex-1 min-w-48 text-mini font-mono break-all",children:e.path}),(0,a.jsx)(eq.E,{variant:"outline",children:e.valueType}),(0,a.jsxs)("span",{className:"text-mini text-muted-foreground tabular-nums",children:["\xd7",e.occurrences]}),h.has(e.path)&&(0,a.jsx)(eq.E,{variant:"secondary",children:"reviewed"}),e.hasDynamicKey&&(0,a.jsxs)(eq.E,{variant:"destructive",title:"This path contains a tenant-defined key (e.g. a customer's own field name). Promoting it writes that key into a platform-global rule, and it won't match other tenants' output.",children:[(0,a.jsx)(sb.A,{className:"mr-small icon-mini"}),"tenant-defined key"]}),function(e){if(!e.proposal)return null;let s="SECRET"===e.proposal.classify,t=sD(e.proposal),n=s&&t?.overridable===!1;return(0,a.jsxs)(eq.E,{variant:s?"destructive":"secondary",title:t?.explanation,children:[s&&(0,a.jsx)(sb.A,{className:"mr-small icon-mini"}),"suggested: ",e.proposal.classify," / ",e.proposal.transform,t&&` \xb7 ${t.label}`,n&&" \xb7 locked"]})}(e),(0,a.jsxs)(eO.l6,{value:t?.classify??"",onValueChange:s=>o(t=>({...t,[e.path]:{classify:s,transform:function({classify:e,previousClassify:s,currentTransform:t,proposedTransform:a}){if("SECRET"===e)return"drop";if(void 0!==t&&e===s)return t;let n=t??a??"raw";return"PII"===e&&"raw"===n?"hash":n}({classify:s,previousClassify:t[e.path]?.classify,currentTransform:t[e.path]?.transform,proposedTransform:e.proposal?.transform}),fromProposal:s===e.proposal?.classify}})),children:[(0,a.jsx)(eO.bq,{className:"w-36",children:(0,a.jsx)(eO.yv,{placeholder:"Deny (default)"})}),(0,a.jsx)(eO.gC,{children:n.map(e=>(0,a.jsx)(eO.eb,{value:e,children:e},e))})]}),(0,a.jsxs)(eO.l6,{value:t?.transform??"",disabled:!t||"SECRET"===t.classify,onValueChange:s=>o(t=>({...t,[e.path]:{classify:t[e.path]?.classify??"SAFE",transform:s,fromProposal:!1}})),children:[(0,a.jsx)(eO.bq,{className:"w-36",children:(0,a.jsx)(eO.yv,{placeholder:"—"})}),(0,a.jsx)(eO.gC,{children:sP.map(e=>(0,a.jsx)(eO.eb,{value:e,children:e},e))})]})]},e.path)})}),(0,a.jsxs)("div",{className:"space-y-small",children:[(0,a.jsxs)(eJ.J,{htmlFor:"promoteReason",children:["Justification"," ",(0,a.jsxs)("span",{className:"font-normal text-muted-foreground",children:["(audited with the promotion, min ",eY.n," ","characters)"]})]}),(0,a.jsx)(e3.p,{id:"promoteReason",value:d,onChange:e=>c(e.target.value),placeholder:"Why these fields are safe to leave the platform…"})]}),x&&(0,a.jsxs)("p",{className:"text-mini text-muted-foreground",children:[p.length," path(s) decided \xb7 ",y," will export \xb7"," ",p.length-y," recorded as denied. SECRET is always dropped, whatever transform is set."]}),u&&(0,a.jsx)(s_,{failure:u})]}):(0,a.jsx)("p",{className:"text-body text-muted-foreground",children:"No stored outputs for this action yet, so there is nothing to review. The tool keeps exporting metadata only until real calls exist to sample."})})}let sR={builtin:"Built-in (code)",platform:"Platform toolkit (code)",rule:"Reviewed rule (DB)","default-deny":"Denied — metadata only"};function sL({source:e}){return"default-deny"===e?(0,a.jsx)(eq.E,{variant:"outline",children:sR[e]}):"rule"===e?(0,a.jsx)(eq.E,{variant:"secondary",children:sR[e]}):(0,a.jsx)(eq.E,{variant:"default",children:sR[e]})}function sF({row:e}){return e.allowedKeys?(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"Keeps these key names wherever they appear;
1 everything else is dropped. Kept strings are still value-scanned for secrets."}),(0,a.jsx)("div",{className:"flex flex-wrap gap-small",children:e.allowedKeys.map(e=>(0,a.jsx)("code",{className:"rounded-default bg-muted px-small text-mini font-mono",children:e},e))})]}):e.allowEntries?0===e.allowEntries.length?(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"Rule exists but allows nothing yet — exports metadata only."}):(0,a.jsx)("div",{className:"space-y-small",children:e.allowEntries.map(e=>(0,a.jsxs)("div",{className:"flex items-center gap-body text-mini",children:[(0,a.jsx)("code",{className:"font-mono",children:e.path}),(0,a.jsx)(eq.E,{variant:"outline",children:e.classify}),(0,a.jsx)(eq.E,{variant:"secondary",children:e.transform}),e.verifiedAt&&(0,a.jsxs)("span",{className:"text-muted-foreground",children:["verified ",(0,eL.Yq)(e.verifiedAt)]})]},e.path))}):(0,a.jsx)("p",{className:"text-mini text-muted-foreground",children:"No guideline for this tool, so a customer export shows only its name, status, duration and error code — never its output. Promote fields via the verification workflow to widen it."})}function sM(e){if("builtin"===e.source||"platform"===e.source)return null;let s=e.toolKey.indexOf(":");if(s<=0)return null;let t=e.toolKey.slice(0,s),a=e.toolKey.slice(s+1);return t&&a&&"unknown"!==t?{integrationSlug:t,realActionName:a}:null}function sU(){let{data:e,isLoading:s}=ex(),[t,n]=(0,S.useState)(""),[r,i]=(0,S.useState)(null),[l,o]=(0,S.useState)(null),d=(0,S.useMemo)(()=>{let s=e?.rows??[],a=t.trim().toLowerCase();return a?s.filter(e=>e.label.toLowerCase().includes(a)||e.toolKey.toLowerCase().includes(a)||e.source.includes(a)):s},[e,t]);return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(sE.A,{className:"icon-heading"}),"Run-export rules"]}),(0,a.jsxs)(e5.CardDescription,{children:["What a customer's run export may reveal of each tool's output. Everything is denied by default — a tool exports its payload only where a reviewed guideline exists. Built-in and platform toolkits are code-owned (changed in a PR); customer-connected integrations are data-owned (`tool_export_rules`), and stay metadata-only until a field is verified. ",(0,a.jsx)("strong",{children:"Every rule here is platform-global"})," — it governs all tenants' exports of that tool, not one company's. Observed calls cover the last ",e?.windowDays??90," ","days."]})]}),(0,a.jsx)(e5.CardContent,{className:"space-y-body",children:s?(0,a.jsx)(T.E,{className:"h-64 w-full"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-body",children:[(0,a.jsxs)("div",{className:"relative flex-1 min-w-48",children:[(0,a.jsx)(e8.A,{className:"absolute left-body top-1/2 -translate-y-1/2 icon-body text-muted-foreground"}),(0,a.jsx)(e3.p,{value:t,onChange:e=>n(e.target.value),placeholder:"Filter by tool, toolkit or state…",className:"pl-large"})]}),(0,a.jsxs)("div",{className:"flex items-center gap-body text-mini text-muted-foreground",children:[(0,a.jsxs)("span",{className:"flex items-center gap-small",children:[(0,a.jsx)(sw.A,{className:"icon-body"}),e?.totals.covered??0," with a guideline"]}),(0,a.jsxs)("span",{children:[e?.totals.denied??0," denied"]}),(0,a.jsxs)("span",{children:[(e?.totals.deniedCalls??0).toLocaleString()," denied calls"]}),(0,a.jsxs)("span",{children:[e?.totals.dbRules??0," reviewed DB rules"]})]})]}),(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{className:"w-8"}),(0,a.jsx)(ss.nd,{children:"Tool"}),(0,a.jsx)(ss.nd,{children:"Export rule"}),(0,a.jsx)(ss.nd,{className:"text-right",children:"Fields"}),(0,a.jsx)(ss.nd,{className:"text-right",children:"Calls"}),(0,a.jsx)(ss.nd,{})]})}),(0,a.jsxs)(ss.BF,{children:[d.map(e=>{let s=r===e.toolKey,t=e.allowedKeys?.length??e.allowEntries?.filter(e=>"drop"!==e.transform).length??0;return(0,a.jsxs)(S.Fragment,{children:[(0,a.jsxs)(ss.Hj,{className:"cursor-pointer",onClick:()=>i(s?null:e.toolKey),children:[(0,a.jsx)(ss.nA,{children:s?(0,a.jsx)(sA.A,{className:"icon-body text-muted-foreground"}):(0,a.jsx)(sm.A,{className:"icon-body text-muted-foreground"})}),(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)("div",{className:"font-medium",children:e.label}),(0,a.jsx)("code",{className:"text-mini text-muted-foreground font-mono",children:e.toolKey})]}),(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)(sL,{source:e.source}),"disabled"===e.status&&(0,a.jsx)(eq.E,{variant:"destructive",className:"ml-small",children:"disabled"})]}),(0,a.jsx)(ss.nA,{className:"text-right tabular-nums",children:"default-deny"===e.source?"—":t}),(0,a.jsx)(ss.nA,{className:"text-right tabular-nums",children:e.calls.toLocaleStr
1ing()}),(0,a.jsx)(ss.nA,{className:"text-right",children:sM(e)&&(0,a.jsx)(eP.$,{variant:"outline",size:"small",onClick:s=>{s.stopPropagation(),o(sM(e))},children:"Review"})})]}),s&&(0,a.jsx)(ss.Hj,{children:(0,a.jsx)(ss.nA,{colSpan:6,className:"bg-muted/30",children:(0,a.jsx)(sF,{row:e})})})]},e.toolKey)}),0===d.length&&(0,a.jsx)(ss.Hj,{children:(0,a.jsx)(ss.nA,{colSpan:6,className:"text-center text-muted-foreground",children:"No tools match that filter."})})]})]})})]})}),(0,a.jsx)(sO,{target:l,onClose:()=>o(null)})]})}var s$=t(96095);let sK=10,sB=200,sH=[{name:"Run analytics export",where:"GET /api/runs/[runId]/export",audience:"customer",protection:"redaction-engine",contains:"One run: prompts, inputs, reasoning, outputs, tool calls, artifacts, credits",basis:"Tool output is default-denied; only reviewed fields are included. Every tool call carries a redaction block naming what was withheld."},{name:"Run details page",where:"ToolCallDetails / ToolRenderer / ToolResultDisplay + /api/runs/[runId]",audience:"customer",protection:"secret-floor",contains:"The same run, rendered on screen and copyable",basis:"In-boundary (own tenant, authenticated) so it deliberately shows more than an export — but credential-named fields and credential-shaped spans are removed before render AND before the clipboard copy."},{name:"Chat export (PDF / DOCX)",where:"frontend/components/domain/export-dialog.tsx",audience:"customer",protection:"content-only",contains:"Message text, generated artifacts and images",basis:"formatMessagesForExport keeps `text` parts plus artifact/image parts; every other part type (tool calls, tool results, reasoning) returns null and is skipped. The tool layer cannot reach the file."},{name:"Workflow node log export",where:"features/workflows/components/NodeTestTab.tsx (Export node log)",audience:"customer",protection:"redaction-engine",contains:"One workflow node's slice of the run log",basis:"Same route and redaction as the run export, scoped by nodeKey; the manifest states which parts of the run the node scope omits."},{name:"Workflow node content export (PDF/DOCX)",where:"features/workflows/components/NodeTestTab.tsx (export dialog)",audience:"customer",protection:"secret-floor",contains:"A node's readable output as a document",basis:"formatOutput falls back to serialising the whole output object when it finds no text field, so the SECRET floor is applied first — as it is to that panel’s Copy button."}],sq=[{where:"app/api/canvas/export-pptx/route.ts",reason:"The customer's own canvas design."},{where:"features/canvas/services/CanvasExportService.ts",reason:"Same design, rendered client-side."},{where:"features/artifacts/components/ArtifactViewer/artifact-export-utils.ts",reason:"A file the user already holds, re-saved in another format."},{where:"frontend/components/ui/enhanced-table/utils/export-helpers.ts",reason:"Table rows already displayed to the viewer."},{where:"features/billing/components/usage-workbench/UsageWorkbench.tsx",reason:"Usage aggregates (credits, tokens) — no prompt or output content."},{where:"app/api/admin/compliance/events/export",reason:"Audit columns; PolicyEvent metadata is deliberately not a column, so no run content."}],sG=["JWTs (eyJ…)","Authorization: Bearer tokens","sk- / pk- / rk- API keys","AWS access key ids","GitHub personal access tokens","Slack tokens (xoxb-…)","URL userinfo credentials (scheme://user:pass@host)","Credential-named query params (?api_key=…, &access_token=…)"],sz=["Run details page — before render and before the clipboard copy","GET /api/runs/[runId] — before the payload reaches the browser","Run analytics export — on top of the default-deny allowlist"],sW={"redaction-engine":"Redaction engine","secret-floor":"SECRET floor","content-only":"Content layer only"};function sJ({protection:e}){return(0,a.jsx)(eq.E,{variant:"redaction-engine"===e?"default":"secondary",children:sW[e]})}function sQ(){return(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(s$.A,{className:"icon-heading"}),"AI-result surfaces"]}),(0,a.jsxs)(e5.CardDescription,{children:["Every way data leaves the platform — file downloads plus the in-boundary display surface — and what keeps the tool and log layer out of it. Rows marked ",(0,a.jsx)("strong",{children:"Not yet reviewed"}
1)," were found by the sweep but not assessed. Adding a new export means adding a row to",(0,a.jsx)("code",{className:"mx-small text-mini",children:"features/run-export/lib/exportPolicy.ts"}),"— if it is not listed here, it has not been reviewed."]})]}),(0,a.jsxs)(e5.CardContent,{children:[(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{children:"Surface"}),(0,a.jsx)(ss.nd,{children:"Audience"}),(0,a.jsx)(ss.nd,{children:"Protection"}),(0,a.jsx)(ss.nd,{children:"Contains / basis"})]})}),(0,a.jsx)(ss.BF,{children:sH.map(e=>(0,a.jsxs)(ss.Hj,{children:[(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)("div",{className:"font-medium",children:e.name}),(0,a.jsx)("code",{className:"text-mini text-muted-foreground font-mono break-all",children:e.where})]}),(0,a.jsx)(ss.nA,{children:(0,a.jsx)(eq.E,{variant:"outline",children:e.audience})}),(0,a.jsx)(ss.nA,{children:(0,a.jsx)(sJ,{protection:e.protection})}),(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)("div",{className:"text-mini",children:e.contains}),(0,a.jsx)("div",{className:"text-mini text-muted-foreground",children:e.basis})]})]},e.where))})]})}),(0,a.jsxs)("p",{className:"mt-body text-mini text-muted-foreground",children:[(0,a.jsx)("strong",{children:"Checked and out of scope"})," — these download paths carry no AI run results and are handled separately:"," ",sq.map(e=>e.where.split("/").pop()).join(", "),"."]})]})]}),(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(sw.A,{className:"icon-heading"}),"SECRET floor"]}),(0,a.jsx)(e5.CardDescription,{children:"The one rule that applies everywhere, on screen as well as in exports: a credential never renders and never exports. It is a floor, not the export allowlist — in-boundary surfaces still show internal ids that an export would hash or deny."})]}),(0,a.jsxs)(e5.CardContent,{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"space-y-small",children:[(0,a.jsx)("p",{className:"text-mini font-medium",children:"Applies at"}),(0,a.jsx)("ul",{className:"text-mini text-muted-foreground space-y-mini",children:sz.map(e=>(0,a.jsxs)("li",{children:["\xb7 ",e]},e))})]}),(0,a.jsxs)("div",{className:"space-y-small",children:[(0,a.jsxs)("p",{className:"text-mini font-medium",children:["Fields withheld by name"," ",(0,a.jsx)("span",{className:"font-normal text-muted-foreground",children:"(matched on the key's last word, so `tokenMs` stays visible)"})]}),(0,a.jsx)("div",{className:"flex flex-wrap gap-small",children:[...sT.KV].map(e=>(0,a.jsx)("code",{className:"rounded-default bg-muted px-small text-mini font-mono",children:e},e))})]}),(0,a.jsxs)("div",{className:"space-y-small",children:[(0,a.jsx)("p",{className:"text-mini font-medium",children:"Value patterns redacted"}),(0,a.jsx)("div",{className:"flex flex-wrap gap-small",children:sG.map(e=>(0,a.jsx)(eq.E,{variant:"secondary",children:e},e))})]})]})]}),(0,a.jsxs)("div",{className:"grid gap-body md:grid-cols-2",children:[(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(si.A,{className:"icon-heading"}),"Customer export limits"]}),(0,a.jsx)(e5.CardDescription,{children:"Enforced per user on the run-export route. An export is an exfiltration primitive — a compromised account could otherwise drain every run it can read."})]}),(0,a.jsx)(e5.CardContent,{children:(0,a.jsxs)("ul",{className:"text-body space-y-small",children:[(0,a.jsxs)("li",{children:[(0,a.jsx)("strong",{className:"tabular-nums",children:sK})," ","exports per minute"]}),(0,a.jsxs)("li",{children:[(0,a.jsx)("strong",{className:"tabular-nums",children:sB})," ","exports per day"]}),(0,a.jsx)("li",{className:"text-mini text-muted-foreground",children:"Owner-scoped: a colleague's run id returns 404, as does a run with no unified record."})]})})]}),(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(sE.A,{className:"icon-heading"}),"Artifact contract"]}),(0,a.jsx)(e5.CardDescription,{children:"What a customer receives, and what the file promises its reader."})]}),(0,a.jsx)(e5.CardContent,{children:(0,a.jsxs)("ul",{className:"text-body space-y-small",children:[(0,a.jsxs)("li",{children:["Schema version"," ",(0,a.jsx)("strong",{className:"tabular-nums",children:2}
1)," ","— JSON array, first record is the manifest"]}),(0,a.jsx)("li",{children:"Generated on demand and streamed; never stored"}),(0,a.jsxs)("li",{className:"text-mini text-muted-foreground",children:["Every tool call carries a ",(0,a.jsx)("code",{children:"redaction"})," block (status, reason codes, omitted field names, sizes) and a"," ",(0,a.jsx)("code",{children:"resultShape"}),", so a reader can tell “removed by policy” from “the tool returned nothing”."]})]})})]})]})]})}var sV=t(60948);function sY(){let e,{data:s,isLoading:t}=function(e=!0){return(0,P.useQuery)({queryKey:I.a.globalAIPolicy,queryFn:ev,staleTime:6e4,enabled:e})}(),n=(e=(0,k.useQueryClient)(),(0,U.useMutation)({mutationFn:eN,onSuccess:()=>e.invalidateQueries({queryKey:I.a.globalAIPolicy}),meta:{notify:{action:"save",entity:"setting"}}})),[r,i]=(0,S.useState)(!0),[l,o]=(0,S.useState)("");(0,S.useEffect)(()=>{s&&(i(s.autoCompactEnabled),o(String(s.autoCompactThresholdPct)))},[s]);let d=s?.bounds.min??50,c=s?.bounds.max??95,u=Number(l),m=Number.isInteger(u)&&u>=d&&u<=c,h=null!=s&&(r!==s.autoCompactEnabled||u!==s.autoCompactThresholdPct);async function p(){m&&h&&await n.mutateAsync({autoCompactEnabled:r,autoCompactThresholdPct:u})}return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(sV.A,{className:"icon-heading"}),"Auto-compaction"]}),(0,a.jsx)(e5.CardDescription,{children:"When an AI turn's context exceeds this percent of the model's window, the conversation history is summarized so the turn can continue. Platform-wide default (per-company overrides live on the company detail page); disabling it lets context run uncapped until the provider rejects. Changes are audited and apply within ~60s."})]}),(0,a.jsxs)(e5.CardContent,{children:[t?(0,a.jsx)(T.E,{className:"h-10 w-48"}):(0,a.jsxs)("div",{className:"flex items-end gap-body",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"autoCompactEnabled",children:"Enabled"}),(0,a.jsx)("div",{className:"flex h-body items-center",children:(0,a.jsx)(e6.d,{id:"autoCompactEnabled",checked:r,onCheckedChange:i,disabled:n.isPending})})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"autoCompactThresholdPct",children:"Threshold %"}),(0,a.jsx)(e3.p,{id:"autoCompactThresholdPct",type:"number",min:d,max:c,step:1,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p()},disabled:n.isPending,className:"w-32 tabular-nums"})]}),(0,a.jsxs)(eP.$,{onClick:p,disabled:!m||!h||n.isPending,loading:n.isPending,children:[(0,a.jsx)(e4.A,{className:"mr-body icon-body"}),"Save"]})]}),!m&&""!==l&&(0,a.jsxs)("p",{className:"mt-body text-mini text-destructive",children:["Enter a whole number between ",d," and ",c,"."]})]})]})}function sX(){let e,{data:s,isLoading:t}=function(e=!0){return(0,P.useQuery)({queryKey:I.a.aiGovernorPolicy,queryFn:eC,staleTime:6e4,enabled:e})}(),n=(e=(0,k.useQueryClient)(),(0,U.useMutation)({mutationFn:eE,onSuccess:()=>e.invalidateQueries({queryKey:I.a.aiGovernorPolicy}),meta:{notify:{action:"save",entity:"setting"}}})),[r,i]=(0,S.useState)(!0),[l,o]=(0,S.useState)("");(0,S.useEffect)(()=>{s&&(i(s.aiConcurrencyEnabled),o(String(s.aiConcurrencyBaseLimit)))},[s]);let d=s?.bounds.min??3,c=s?.bounds.max??16,u=Number(l),m=Number.isInteger(u)&&u>=d&&u<=c,h=null!=s&&(r!==s.aiConcurrencyEnabled||u!==s.aiConcurrencyBaseLimit);async function p(){m&&h&&await n.mutateAsync({aiConcurrencyEnabled:r,aiConcurrencyBaseLimit:u})}return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(si.A,{className:"icon-heading"}),"AI concurrency governor"]}),(0,a.jsx)(e5.CardDescription,{children:"Bounds concurrent LLM provider calls platform-wide (one shared OpenRouter pool). Interactive chat/agent turns keep reserved headroom and are never hard-blocked; workflows and background summarizers queue at the boundary. The limit self-adjusts around this base on provider health. Changes are audited; the limit applies immediately."})]}),(0,a.jsxs)(e5.CardContent,{children:[t?(0,a.jsx)(T.E,{className:"h-10 w-48"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"flex items-end gap-body",children:[(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"aiConcurrencyEnabled",children:"Enabled"}),(0,a.jsx)("div",{className:"flex h-body items-center",children:(0,a.jsx)(e6.d,{id:"aiConcurrencyEnabled",checked:r,onCheckedChange:i,disabled:n.isPending})})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"aiConcurrencyBaseLimit",children:"Base limit"}),(0,a.jsx)(e3.p,{id:"aiConcurrencyBaseLimit",type:"number",min:d,max:c,step:1,value:l,onCh
1ange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p()},disabled:n.isPending,className:"w-32 tabular-nums"})]}),(0,a.jsxs)(eP.$,{onClick:p,disabled:!m||!h||n.isPending,loading:n.isPending,children:[(0,a.jsx)(e4.A,{className:"mr-body icon-body"}),"Save"]})]}),s&&!s.live.redisUnavailable&&(0,a.jsxs)("p",{className:"mt-body text-mini text-muted-foreground tabular-nums",children:["Live: ",s.live.activeCalls," active / limit"," ",s.live.currentLimit," (background allowance"," ",s.live.backgroundAllowance,") \xb7 ",s.live.overflowCount," ","interactive overflows \xb7 ",s.live.terminatedIn60s," provider terminations in 60s"]}),s?.live.redisUnavailable&&(0,a.jsx)("p",{className:"mt-body text-mini text-muted-foreground",children:"Redis unavailable — governor is failing open (calls proceed ungoverned)."})]}),!m&&""!==l&&(0,a.jsxs)("p",{className:"mt-body text-mini text-destructive",children:["Enter a whole number between ",d," and ",c,"."]})]})]})}var sZ=t(39397),s0=t(48897);function s1(){let e=(0,U.useMutation)({mutationFn:ew,meta:{notify:{action:"send",entity:"message",successToast:!1}}});return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(sZ.A,{className:"icon-heading"}),"Contact Support Test"]}),(0,a.jsxs)(e5.CardDescription,{children:["Sends a real test message through the contact-support pipeline — email to ",s0.Te," plus the Slack mirror — and reports whether Slack actually delivered. Customer submissions never surface a Slack failure; this does."]})]}),(0,a.jsxs)(e5.CardContent,{className:"space-y-large",children:[(0,a.jsxs)(eP.$,{onClick:()=>e.mutate(),disabled:e.isPending,loading:e.isPending,children:[(0,a.jsx)(sZ.A,{className:"mr-body icon-body"}),"Send test message"]}),e.data&&(0,a.jsxs)("div",{className:"space-y-mini text-body",children:[(0,a.jsxs)("p",{className:"text-muted-foreground",children:["Email: delivered to ",s0.Te]}),e.data.slackDelivered?(0,a.jsx)("p",{children:"Slack mirror: delivered — check the support channel."}):(0,a.jsx)("p",{className:"text-destructive",children:"Slack mirror: failed. Check SLACK_BOT_TOKEN / SLACK_WEBHOOK_URL / SLACK_SUPPORT_CHANNEL in this environment, and server logs for “[CONTACT] Slack mirror failed”."})]})]})]})}var s2=t(42346);let s4=[{id:"welcome",label:"Welcome (lifecycle)",description:"Sent by daily-lifecycle when a new user signs up."},{id:"no-company-nudge",label:"No-company nudge (lifecycle)",description:"Signed up but never created a workspace."},{id:"stuck-onboarding",label:"Stuck-onboarding nudge (lifecycle)",description:"Workspace created but onboarding not finished."},{id:"invitation",label:"Invitation",description:"Sent when a colleague is invited. The one mail with its own layout."},{id:"trial-warning",label:"Trial warning (7/3/1 day)",description:"check-trial-expiration warning — lists what would be deleted."},{id:"trial-expired",label:"Trial expired nudge",description:"check-trial-expiration upgrade nudge (sample data)."},{id:"low-credit",label:"Low-credit alert",description:"low-credit-alert cron, warning state (sample data)."},{id:"credits-exhausted",label:"Credits exhausted",description:"The same cron at zero — different subject, heading and tone."},{id:"auto-recharge",label:"Auto-recharge receipt",description:"A top-up went through. Amount and credits, both ICU-formatted."},{id:"auto-recharge-failed",label:"Auto-recharge failed",description:"A top-up was declined. Carries Stripe's reason verbatim."},{id:"payment-failed-renewal",label:"Payment failed (renewal)",description:"A renewal charge failed and Stripe will retry."},{id:"payment-failed-seats",label:"Payment failed (seat change)",description:"A seat change did not apply. No retry — different copy."},{id:"subscription-active",label:"Subscription activated",description:"The plan went live."},{id:"plan-changed",label:"Plan changed",description:"One template for both upgrade and downgrade."},{id:"subscription-canceled",label:"Subscription cancelled",description:"What the customer keeps, and for how long."},{id:"async-payment-submitted",label:"SEPA payment submitted",description:"Direct debit authorized, not yet cleared. Advance credits."},{id:"async-payment-confirmed",label:"SEPA payment confirmed",description:"Direct debit cleared and the full allocation landed."},{id:"team-deletion",label:"Team data deleted",description:"Downgrade off a teams plan. Lists what was destroyed."},{id:"data-retention",label:"Data-retention warning",description:"The customer's legal notice before deleti
1on (sample data)."},{id:"company-suspended",label:"Company suspended",description:"Staff action. Neutral copy — the cause is never disclosed."},{id:"company-restored",label:"Company restored",description:"The reverse transition, from the same builder."},{id:"member-departed",label:"Member left the company",description:"Sent to the OTHER admins. Lists what the workspace lost."},{id:"member-departed-account-deleted",label:"Member account deleted",description:"Same mail, deletion wording, and the empty-content branch."}];function s3(){let[e,s]=(0,S.useState)("welcome"),t=(0,U.useMutation)({mutationFn:eA,meta:{notify:{action:"send",entity:"message",successToast:!1}}}),n=s4.find(s=>s.id===e);return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(s2.A,{className:"icon-heading"}),"Send Test Email"]}),(0,a.jsx)(e5.CardDescription,{children:"Renders a platform email template and sends it to your own address via the real SendGrid pipeline — the same path the cron uses. Verifies rendering + delivery (and catches empty-content 400s) without waiting for the scheduled job. The recipient is always you."})]}),(0,a.jsxs)(e5.CardContent,{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsxs)(eO.l6,{value:e,onValueChange:e=>s(e),children:[(0,a.jsx)(eO.bq,{className:"w-80",children:(0,a.jsx)(eO.yv,{})}),(0,a.jsx)(eO.gC,{children:s4.map(e=>(0,a.jsx)(eO.eb,{value:e.id,children:e.label},e.id))})]}),(0,a.jsxs)(eP.$,{onClick:()=>t.mutate(e),disabled:t.isPending,loading:t.isPending,children:[(0,a.jsx)(sZ.A,{className:"mr-body icon-body"}),"Send to me"]})]}),n&&(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:n.description}),t.data&&(0,a.jsxs)("p",{className:"text-body",children:["Sent ",(0,a.jsx)("strong",{children:t.data.templateId})," to ",t.data.sentTo," — check your inbox. Subject: “",t.data.subject,"”."]})]})]})}s4.map(e=>e.id);var s6=t(12888);function s5(){let e=(0,U.useMutation)({mutationFn:eS,meta:{notify:{action:"send",entity:"message",successToast:!1}}}),s=e.data?.counts;return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(s6.A,{className:"icon-heading"}),"Daily Activity Summary Test"]}),(0,a.jsx)(e5.CardDescription,{children:"Sends the real Daily Lifecycle Summary (live trial/activity data) to the lifecycle Slack channel (SLACK_LIFECYCLE_CHANNEL, default #saas-activity) — same message as the 4am cron, but without the customer nudge emails or the Monday weekly recap."})]}),(0,a.jsxs)(e5.CardContent,{className:"space-y-large",children:[(0,a.jsxs)(eP.$,{onClick:()=>e.mutate(),disabled:e.isPending,loading:e.isPending,children:[(0,a.jsx)(sZ.A,{className:"mr-body icon-body"}),"Send daily summary"]}),e.data&&(0,a.jsxs)("div",{className:"space-y-mini text-body",children:[e.data.slackDelivered?(0,a.jsx)("p",{children:"Slack: delivered — check the lifecycle channel."}):(0,a.jsxs)("p",{className:"text-destructive",children:["Slack: failed",e.data.slackError?` (${e.data.slackError})`:"",". Check SLACK_BOT_TOKEN / SLACK_WEBHOOK_URL / SLACK_LIFECYCLE_CHANNEL in this environment."]}),s&&(0,a.jsxs)("p",{className:"text-muted-foreground",children:["Data: ",s.newTrials," new trials,"," ",s.trialEndedConverted+s.trialEndedExpired," ended today, ",s.expiringTomorrow," expiring tomorrow,"," ",s.inTrial," in trial."]})]})]})]})}var s9=t(39571);let s7=[{value:"24",label:"Last 24 hours (same as cron)"},{value:"48",label:"Last 48 hours"},{value:"168",label:"Last 7 days"}];function s8(){let[e,s]=(0,S.useState)("24"),t=(0,U.useMutation)({mutationFn:e=>eT(e),meta:{notify:{action:"send",entity:"message",successToast:!1}}}),n=t.data;return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(s9.A,{className:"icon-heading"}),"Composio Failure Report"]}),(0,a.jsx)(e5.CardDescription,{children:"Runs the real nightly Composio integration failure report and sends it to the integrations Slack channel (SLACK_INTEGRATIONS_CHANNEL, defaulting to SLACK_DEFAULT_CHANNEL) — the same message as the 5am cron. Reads Composio's execution logs, which record whether Composio's call to the upstream API succeeded; this is independent of how our AI flow handled the result."})]}),(0,a.jsxs)(e5.CardContent,{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsxs)(eO.l6,{value:e,onValueChange:s,children:[(0,a.jsx)(eO.bq,{className:"w-64",children:(0,a.jsx)(eO.yv,{})}),(0,a.jsx)(eO.gC,{children:s7.map(e=>(0,a.jsx)(eO.eb,{value:e.value,children:e.label},e.value))})]}),(0,a.jsxs)(eP.$,{onClick:()=>t.mutate(Number(e)),disabled:t.isPending,loading:t.isPending,children:[(0,a.jsx)(sZ.A,{className:"mr-body icon-body"}),"Run report"]})]}),n&&(0,a.jsxs)("div",{className:"space-y-mini text-body",children:[n.logsError?(0,a.jsxs)("p",{className:"text-destructive",children:["Composio logs unavailable (",n.logsError,"). Integration health is unknown for this window — this is not an all-clear."]}):(0,a.jsxs)("p",{className:"text-muted-foreground",children:["Data: ",n.counts.totalExecutions," executions,"," ",n.counts.totalFailures," failures across"," ",n.counts.failingEndpoints," endpoint",1===n.counts.failingEndpoints?"":"s"," (last"," ",n.windowHours,"h)."]}),n.slackDelivered?(0,a.jsx)("p",{children:"Slack: delivered — check the integrations channel."}):(0,a.jsxs)("p",{className:"text-destructive",children:["Slack: failed",n.slackError?` (${n.slackError})`:"",". Check SLACK_BOT_TOKEN / SLACK_WEBHOOK_URL / SLACK_INTEGRATIONS_CHANNEL in this environment."]}),n.topFailures.length>0&&(0,a.jsx)("ul",{className:"space-y-mini text-muted-foreground",children:n.topFailures.map(e=>(0,a.jsxs)("li",{children:[e.appKey," — ",e.actionKey,": ",e.count,"\xd7",e.reason?` (${e.reason})`:""]},`${e.appKey}:${e.actionKey}`))})]})]})]})}let te=[{value:"24",label:"Last 24 hours (same as cron)"},{value:"48",label:"Last 48 hours"},{value:"168",label:"Last 7 days"}];function ts(){let[e,s]=(0,S.useState)("24"),t=(0,U.useMutation)({mutationFn:e=>ek(e),meta:{notify:{action:"send",entity:"message",successToast:!1}}}),n=t.data;return(0,a.jsxs)(e5.Card,{children:[(0,a.jsxs)(e5.CardHeader,{children:[(0,a.jsxs)(e5.CardTitle,{className:"flex items-center gap-body",children:[(0,a.jsx)(y.A,{className:"icon-heading"}),"Langfuse Failure Report"]}),(0,a.jsx)(e5.CardDescription,{children:"Runs the real nightly Langfuse AI failure report and sends it to the Langfuse Slack channel (SLACK_LANGFUSE_CHANNEL, defaulting to SLACK_DEFAULT_CHANNEL) — the same message as the 5:30am cron. Groups ERROR/WARNING observations by error signature with trace deep links, scoped to this deployment's L
1angfuse environment. Runs that swallowed an error without marking their trace do not appear — the report can only under-state failures."})]}),(0,a.jsxs)(e5.CardContent,{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsxs)(eO.l6,{value:e,onValueChange:s,children:[(0,a.jsx)(eO.bq,{className:"w-64",children:(0,a.jsx)(eO.yv,{})}),(0,a.jsx)(eO.gC,{children:te.map(e=>(0,a.jsx)(eO.eb,{value:e.value,children:e.label},e.value))})]}),(0,a.jsxs)(eP.$,{onClick:()=>t.mutate(Number(e)),disabled:t.isPending,loading:t.isPending,children:[(0,a.jsx)(sZ.A,{className:"mr-body icon-body"}),"Run report"]})]}),n&&(0,a.jsxs)("div",{className:"space-y-mini text-body",children:[n.apiError?(0,a.jsxs)("p",{className:"text-destructive",children:["Langfuse observations unavailable (",n.apiError,"). AI-run health is unknown for this window — this is not an all-clear."]}):(0,a.jsxs)("p",{className:"text-muted-foreground",children:["Data: ",n.counts.totalErrors," errors,"," ",n.counts.totalWarnings," warnings across"," ",n.counts.affectedTraces," trace",1===n.counts.affectedTraces?"":"s",","," ",n.counts.signatures," signature",1===n.counts.signatures?"":"s"," (last"," ",n.windowHours,"h)."]}),n.slackDelivered?(0,a.jsx)("p",{children:"Slack: delivered — check the Langfuse channel."}):(0,a.jsxs)("p",{className:"text-destructive",children:["Slack: failed",n.slackError?` (${n.slackError})`:"",". Check SLACK_BOT_TOKEN / SLACK_WEBHOOK_URL / SLACK_LANGFUSE_CHANNEL in this environment."]}),n.topGroups.length>0&&(0,a.jsx)("ul",{className:"space-y-mini text-muted-foreground",children:n.topGroups.map(e=>(0,a.jsxs)("li",{children:["[",e.level,"] ",e.name,": ",e.count,"\xd7 across"," ",e.affectedTraces," trace",1===e.affectedTraces?"":"s",e.message?` (${e.message})`:""]},`${e.level}:${e.name}:${e.message}`))})]})]})]})}var tt=t(66499),ta=t(30446);function tn(){let e=(0,n.t0)(),[s,t]=(0,S.useState)(""),[r,l]=(0,S.useState)(null),o=s.trim(),{data:d,isFetching:c}=(0,P.useQuery)({queryKey:["admin","user-directory",o],queryFn:async()=>{let e=await fetch(`/api/admin/users?search=${encodeURIComponent(o)}`);if(!e.ok)throw Error(`HTTP ${e.status}`);return(await e.json()).data.users},enabled:o.length>=2,staleTime:3e4});return(0,a.jsxs)("div",{className:"space-y-large pt-body pb-large",children:[(0,a.jsx)(e_.I,{value:s,onChange:t,placeholder:e.searchByEmailOrUserId}),o.length<2?(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:e.typeAtLeast2CharactersTo}):c?(0,a.jsx)(T.E,{className:"h-40 w-full"}):d?.length?(0,a.jsx)("div",{className:"space-y-body",children:d.map(e=>(0,a.jsxs)("div",{className:"flex-between p-body rounded-default border hover:bg-muted/50",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:"font-medium truncate",children:e.email}),(0,a.jsx)("div",{className:"text-small text-muted-foreground font-mono truncate",children:e.id}),(0,a.jsxs)("div",{className:"flex items-center flex-wrap gap-large text-small text-muted-foreground mt-small",children:[(0,a.jsxs)("span",{className:"flex items-center gap-small",children:[(0,a.jsx)(eM.A,{className:"icon-small"}),(0,eL.Yq)(e.createdAt)]}),(0,a.jsxs)("span",{className:"flex items-center gap-small",children:[(0,a.jsx)(i.A,{className:"icon-small"}),e.companyCount," ",1===e.companyCount?"company":"companies"]})]})]}),(0,a.jsxs)(eP.$,{variant:"outline",size:"small",onClick:()=>l(e.id),children:[(0,a.jsx)(h.A,{className:"icon-body"}),"Manage"]})]},e.id))}):(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:e.noUsersFound}),(0,a.jsx)(ta.C,{userId:r,userLabel:d?.find(e=>e.id===r)?.email??void 0,onOpenChange:e=>{e||l(null)}})]})}var tr=t(29716),ti=t(99834),tl=t(4884);function to(e){let s=(0,n.t0)(),t=(0,n.WD)(),[r,i]=(0,S.useState)([]),[l,o]=(0,S.useState)([]),[d,c]=(0,S.useState)(!0),[u,m]=(0,S.useState)(""),[h,p]=(0,S.useState)(!1),[x,y]=(0,S.useState)(null),[g,f]=(0,S.useState)(""),[j,b]=(0,S.useState)(""),v=(0,S.useCallback)(async()=>{c(!0);try{let[e,s]=await Promise.all([fetch("/api/admin/billing/custom-subscriptions"),fetch("/api/admin/companies")]);if(!e.ok)throw Error("Failed to fetch subscriptions");let t=await e.json(),a=t.data?.subscriptions??t.subscriptions??[];if(i(Array.isArray(a)?a:[]),s.ok){let e=await s.json(),t=e.data?.companies??e.companies??[];o(Array.isArray(t)?t:[])}}catch(e){ti.logger.error("[DeveloperCustomSubscriptionsTab] Failed to fetch",{error:e}),D.me.error(s.developerSettings.toasts.loadEnterpriseSubscriptionsFailed)}finally{c(!1)}},[]);function N(){p(!1),y(null),f(""),b("")}(0,S.useEffect)(()=>{v()},[v]);let C=(0,S.useMemo)(()=>{let e=new Set(r.map(e=>e.companyId));return l.filter(s=>!e.has(s.id))},[l,r]),E=(0,S.useMemo)(()=>
1{if(!j)return C;let e=j.toLowerCase();return C.filter(s=>s.name.toLowerCase().includes(e))},[C,j]),w=(0,S.useMemo)(()=>l.find(e=>e.id===g)??null,[l,g]),A=r.filter(e=>e.Company.name.toLowerCase().includes(u.toLowerCase())||e.companyId.toLowerCase().includes(u.toLowerCase())||e.planName.toLowerCase().includes(u.toLowerCase())),k=x?{type:"enterprise",planName:x.planName,billingType:x.billingType||"external",billingCycle:"yearly"===x.billingCycle?"yearly":"monthly",accessLevel:x.accessLevel,expiresAt:x.expiresAt?x.expiresAt.split("T")[0]:"",renewsAt:x.renewsAt?x.renewsAt.split("T")[0]:"",externalReference:x.externalReference??"",notes:x.notes??"",creditOverrideMode:null!=x.creditsPerSeatOverride?"perSeat":null!=x.monthlyCreditsOverride?"flat":"inherit",monthlyCreditsOverride:null!=x.monthlyCreditsOverride?String(x.monthlyCreditsOverride):"",creditsPerSeatOverride:null!=x.creditsPerSeatOverride?String(x.creditsPerSeatOverride):"",creditPeriodAnchor:x.creditPeriodAnchor?x.creditPeriodAnchor.split("T")[0]:""}:void 0,I=w?.CompanySubscription?.status==="trialing"?"trial":null,P=x?.companyId??g,_=x?.Company.name??w?.name??P;return(0,a.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body shrink-0 pt-body pb-body",children:[(0,a.jsx)("div",{className:"flex-1",children:(0,a.jsx)(e3.p,{icon:(0,a.jsx)(e8.A,{}),iconPosition:"left",placeholder:s.searchCompaniesOrPlans,value:u,onChange:e=>m(e.target.value)})}),(0,a.jsx)(eP.$,{onClick:v,variant:"ghost",size:"icon",disabled:d,children:(0,a.jsx)(eI.A,{className:`icon-body ${d?"animate-spin":""}`})}),(0,a.jsxs)(eP.$,{onClick:function(){y(null),f(""),b(""),p(!0)},children:[(0,a.jsx)(e7.A,{className:"mr-body icon-body"}),s.addSubscription]})]}),(0,a.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto pb-large",children:d?(0,a.jsx)("div",{className:"space-y-body",children:[void 0,void 0,void 0].map((e,s)=>(0,a.jsx)(T.E,{className:"h-16 w-full"},s))}):0===A.length?(0,a.jsx)("div",{className:"py-large text-center text-muted-foreground",children:u?"No matching subscriptions found":"No enterprise subscriptions configured"}):(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{children:"Company"}),(0,a.jsx)(ss.nd,{children:"Plan"}),(0,a.jsx)(ss.nd,{children:"Billing"}),(0,a.jsx)(ss.nd,{children:"Access"}),(0,a.jsx)(ss.nd,{children:"Expires"}),(0,a.jsx)(ss.nd,{className:"text-right",children:"Actions"})]})}),(0,a.jsx)(ss.BF,{children:A.map(e=>{let t,n=!!(t=e.expiresAt)&&new Date(t)<new Date;return(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nA,{children:(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{className:"font-medium",children:e.Company.name}),(0,a.jsx)("div",{className:"text-mini text-muted-foreground",children:e.companyId})]})}),(0,a.jsx)(ss.nA,{children:e.planName}),(0,a.jsx)(ss.nA,{children:(e=>{switch(e){case"stripe_managed":return(0,a.jsx)(eq.E,{variant:"secondary",children:"Stripe"});case"free":return(0,a.jsx)(eq.E,{variant:"default",children:"Free"});default:return(0,a.jsx)(eq.E,{variant:"outline",children:"External"})}})(e.billingType)}),(0,a.jsx)(ss.nA,{children:((e,t)=>{if(t)return(0,a.jsx)(eq.E,{variant:"destructive",children:"Expired"});switch(e){case"FULL_ACCESS":return(0,a.jsx)(eq.E,{variant:"default",children:"Full"});case"READ_ONLY":return(0,a.jsx)(eq.E,{variant:"secondary",children:s.readOnly2});case"BLOCKED":return(0,a.jsx)(eq.E,{variant:"destructive",children:"Blocked"});default:return(0,a.jsx)(eq.E,{variant:"outline",children:e})}})(e.accessLevel,n)}),(0,a.jsx)(ss.nA,{children:e.expiresAt?(0,a.jsxs)("div",{className:"flex items-center gap-mini",children:[n&&(0,a.jsx)(sb.A,{className:"icon-body text-destructive"}),(0,a.jsx)("span",{className:n?"text-destructive":"",children:(0,eL.Yq)(e.expiresAt)})]}):(0,a.jsx)("span",{className:"text-muted-foreground",children:"Never"})}),(0,a.jsx)(ss.nA,{className:"text-right",children:(0,a.jsx)(eP.$,{variant:"ghost",size:"icon",onClick:()=>{y(e),f(e.companyId),p(!0)},children:(0,a.jsx)(tr.A,{className:"icon-body"})})})]},e.id)})})]})}),(0,a.jsxs)(eV.lG,{open:h,onOpenChange:e=>{e||N()},closeOnAction:!1,size:"2xl",title:x?"Edit subscription":"Add subscription",description:x?t("settings.configureBillingFor",{company:x.Company.name}):w?t("settings.configuringCompany",{company:w.name}):"Pick a company that doesn't already have an enterprise subscription",children:[!x&&!g&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(e3.p,{icon:(0,a.jsx)(e8.A,{}),iconPosition:"left",placeholder:s.searchCompanies,value:j,onChange:e=>b(e.target.value)}),(0,a.jsx)("div",{className:"max-h-[420px] overflow-y-auto",children:0===E.length?(0,a.jsx)("div",{className:"py-12 text-center text-muted-foreground text-small",children:0===C.length?"All companies already have an enterprise subscription":"No companies match your search"}):(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{className:"[&_th]:sticky [&_th]:top-0 [&_th]:z-10 [&_th]:bg-background [&_th]:border-b",children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{children:"Company"}),(0,a.jsx)(ss.nd,{className:"w-24",children:"Users"}),(0,a.jsx)(ss.nd,{children:s.currentPlan})]})}),(0,a.jsx)(ss.BF,{children:E.map(e=>{let s=e.CompanySubscription?.PaymentPlan?.displayName??e.CompanySubscription?.status??"No plan";return(0,a.jsxs)(ss.Hj,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>f(e.id),children:[(0,a.jsxs)(ss.nA,{children:[(0,a.jsx)("div",{className:"font-medium",children:e.name}),(0,a.jsx)("div",{className:"text-mini text-muted-foreground",children:e.id})]}),(0,a.jsx)(ss.nA,{children:e._count.UserCompanyRole}),(0,a.jsx)(ss.nA,{children:s})]},e.id)})})]})})]}),P&&(0,a.jsx)("div",{className:"max-h-[70vh] overflow-y-auto",children:(0,a.jsx)(tl.t,{companyId:P,companyName:_,initialType:x?"enterprise":I,initialValue:k,hasStripeSubscription:!!x?.stripeSubscriptionId,onSaved:function(){N(),v()},onCancel:N})})]})]})}var td=t(34864),tc=t(85149),tu=t(47747);function tm(){let e=(0,n.t0)(),s=(0,n.WD)(),[t,r]=(0,S.useState)([]),[i,l]=(0,S.useState)(!0),[o,d]=(0,S.useState)(""),[c,u]=(0,S.useState)(!1),m=(0,S.useCallback)(async()=>{try{let e=await fetch("/api/admin/auto-model-defaults");if(!e.ok)throw Error("Failed to fetch auto-model defaults");let s=await e.json();r(s.autoModelDefaults||[])}catch(e){ti.logger.error("Error fetching auto-model defaults:",{error:e instanceof Error?e.message:String(e)})}finally{l(!1),u(!1)}},[]);(0,S.useEffect)(()=>{m()},[m]);let h=(0,S.useMemo)(()=>o.trim()?(0,tc.XK)(t,o,["autoModelTypeName","autoModelTypeId","modelName","providerName"],{threshold:.4}).map(e=>e.item):t,[o,t]),p=(0,S.useMemo)(()=>[{id:"type",accessorKey:"autoModelTypeName",header:"Auto-Model Type",cell:({row:e})=>(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{className:"font-semibold",children:e.original.autoModelTypeName}),(0,a.jsx)("span",{className:"text-small text-muted-foreground font-mono",children:e.original.autoModelTypeId})]}),widthMode:"fill-remaining",minWidth:220,enableSorting:!0},{id:"model",accessorKey:"modelName",header:"Default Model",cell:({row:e})=>(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{className:"font-semibold",children:e.original.modelName}),e.original.providerName&&(0,a.jsx)("span",{className:"text-small text-muted-foreground",children:e.original.providerName})]}),widthMode:"fill-remaining",minWidth:220,enableSorting:!0},{id:"tier",accessorFn:e=>e.tierId,header:"Credit Tier",cell:({row:e})=>(0,a.jsx)(tu.y,{tierId:e.original.tierId,tierName:e.original.tierName}),widthMode:"fit-content",minWidth:130,enableSorting:!0}],[]);return i?(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsx)(T.E,{className:"h-body w-full"}),(0,a.jsx)(T.E,{className:"h-48 w-full"})]}):(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsxs)("div",{className:"relative flex-1",children:[(0,a.jsx)(e8.A,{className:"absolute left-3 top-1/2 -translate-y-1/2 icon-body text-muted-foreground"}),(0,a.jsx)(e3.p,{placeholder:e.searchAutoModelTypesOrModels,value:o,onChange:e=>d(e.target.value),className:"pl-10"}),o&&(0,a.jsx)(eP.$,{variant:"ghost",size:"small",className:"absolute right-1 top-1/2 -translate-y-1/2 icon-heading p-0",onClick:()=>d(""),children:(0,a.jsx)(eD.A,{className:"icon-body"})})]}),(0,a.jsxs)(eP.$,{variant:"outline",size:"small",onClick:()=>{u(!0),m()}
1,disabled:c,children:[(0,a.jsx)(eI.A,{className:`icon-body ${c?"animate-spin":""}`}),"Refresh"]})]}),(0,a.jsx)(ss.bQ,{columns:p,data:h,persistenceKey:"system-auto-model-defaults",maxHeight:"none"}),(0,a.jsxs)("div",{className:"flex items-center gap-large text-small text-muted-foreground",children:[(0,a.jsx)("span",{children:s("settings.totalAutoModelTypes",{count:t.length})}),o&&(0,a.jsx)("span",{children:s("settings.showingResults",{count:h.length})})]})]})}var th=t(3110),tp=t(16965),tx=t(39874),ty=t(24688),tg=t(78344),tf=t(53536),tj=t(86689),tb=t(37182),tv=t(61129);let tN={all:["admin","internal-integrations"],list:()=>[...tN.all,"list"],fields:e=>[...tN.all,"fields",e]};async function tC(){let e=await fetch("/api/admin/integrations/internal");if(!e.ok)throw Error(`Failed to load integrations (${e.status})`);let s=await e.json();return(s.data??s).integrations??[]}async function tE(e){let s=await fetch(`/api/admin/integrations/internal/${e}`);if(!s.ok)throw Error(`Failed to load integration credentials (${s.status})`);let t=await s.json();return(t.data??t).fields??{}}function tw(){var e;let s,t=(0,n.t0)(),r=(0,n.WD)(),{data:i=[],isLoading:l,isError:o,error:d}=(0,P.useQuery)({queryKey:tN.list(),queryFn:tC,staleTime:3e4,refetchOnWindowFocus:!0}),c=(s=(0,k.useQueryClient)(),(0,U.useMutation)({mutationFn:async({integrationId:e,settings:s,clear:t})=>{let a=await fetch("/api/admin/integrations/internal",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({integrationId:e,internalSettings:s,clear:t})});if(!a.ok){let e=await a.json().catch(()=>({}));throw Error(e.error??e.message??"Failed to save settings")}},onSuccess:()=>s.invalidateQueries({queryKey:tN.list()}),onError:e=>{ti.logger.error("Failed to save internal integration settings",{},e instanceof Error?e:void 0)},meta:{notify:{action:"save",entity:"integration"}}})),[u,m]=(0,S.useState)(null),[h,p]=(0,S.useState)(!1),[x,y]=(0,S.useState)({}),[g,f]=(0,S.useState)({}),[j,b]=(0,S.useState)({}),v=c.isPending,N=(e=h?u?.id??null:null,(0,P.useQuery)({queryKey:tN.fields(e),queryFn:()=>tE(e),enabled:!!e,staleTime:0,gcTime:0,refetchOnWindowFocus:!1})),C=N.data;return((0,S.useEffect)(()=>{if(!u||!C)return;let e=tv.iM[u.slug]||[],s={};for(let t of e)s[t.key]=C[t.key]?.value??"";y(s)},[C,u]),l)?(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsx)(T.E,{className:"h-8 w-48"}),(0,a.jsx)(T.E,{className:"h-24 w-full"}),(0,a.jsx)(T.E,{className:"h-24 w-full"})]}):(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h2",{className:"text-heading font-semibold",children:t.internalIntegrations}),(0,a.jsx)("p",{className:"text-body text-muted-foreground mt-small",children:t.internalIntegrationsDescription})]}),o&&(0,a.jsxs)(sS.Fc,{variant:"destructive",children:[(0,a.jsx)(tx.A,{className:"icon-body"}),(0,a.jsx)(sS.TN,{children:d instanceof Error?d.message:r("settings.internalIntegrationsToasts.loadFailed")})]}),o?null:0===i.length?(0,a.jsx)(e5.Card,{children:(0,a.jsxs)(e5.CardContent,{className:"py-large text-center",children:[(0,a.jsx)(tx.A,{className:"icon-heading mx-auto text-muted-foreground mb-body"}),(0,a.jsx)("p",{className:"text-body text-muted-foreground",children:t.noInternalIntegrationsFound})]})}):(0,a.jsx)("div",{className:"space-y-large",children:i.map(e=>{let s;return(0,a.jsxs)(e5.Card,{children:[(0,a.jsx)(e5.CardHeader,{className:"pb-body",children:(0,a.jsxs)("div",{className:"flex-between",children:[(0,a.jsxs)("div",{className:"flex items-center gap-large",children:[(s=e.iconUrl||e.logoUrl)?(0,a.jsx)(tb.default,{src:s,alt:e.displayName,width:32,height:32,className:"rounded-default"}):(0,a.jsx)("div",{className:"icon-heading rounded-default bg-muted flex-center",children:(0,a.jsx)(tp.A,{className:"icon-body text-muted-foreground"})}),(0,a.jsxs)("div",{children:[(0,a.jsx)(e5.CardTitle,{className:"text-body",children:e.displayName}),(0,a.jsx)(e5.CardDescription,{className:"text-small",children:e.description||e.slug})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[e.configured?(0,a.jsxs)(eq.E,{variant:"default",className:"bg-green-600 text-small",children:[(0,a.jsx)(ty.A,{className:"icon-small"}),t.configured]}):(0,a.jsxs)(eq.E,{variant:"outline",className:"text-small",children:[(0,a.jsx)(tx.A,{className:"icon-small"}),t.notConfigured]}),(0,a.jsxs)(eP.$,{variant:"outline",size:"small",onClick:()=>{m(e),y({}),f({}),b({}),p(!0)},children:[(0,a.jsx)(tp.A,{className:"icon-small"}),t.configure]})]})]})}),(0,a.jsx)(e5.CardContent,{children:(0,a.jsx)("div",{className:"text-small text-muted-foreground",children:tv.iM[e.slug]?(0,a.jsx)("span",{children:r("settings.fieldsRequired",{count:tv.iM[e.slug].length})}):(0,a.jsx)("span",{children:t.noConfigurationDefined})})})]},e.id)})}),(0,a.jsx)(eV.Dz,{open:h,onOpenChange:p,children:(0,a.jsxs)(eV.Cf,{className:"sm:max-w-[500px]",children:[(0,a.jsxs)(eV.c7,{children:[(0,a.jsx)(eV.L3,{children:r("settings.configureIntegration",{name:u?.displayName??""})}),(0,a.jsx)(eV.rr,{children:t.internalIntegrationCredentialsDescription})]}),u&&N.isPending&&(0,a.jsxs)("div",{className:"space-y-large py-large",children:[(0,a.jsx)(T.E,{className:"h-body w-full"}),(0,a.jsx)(T.E,{className:"h-body w-full"}),(0,a.jsx)(T.E,{className:"h-body w-full"})]}),u&&N.isError&&(0,a.jsxs)(sS.Fc,{variant:"destructive",children:[(0,a.jsx)(tx.A,{className:"icon-body"}),(0,a.jsx)(sS.TN,{children:r("settings.internalIntegrationsToasts.loadFailed")})]}),u&&C&&(0,a.jsx)("div",{className:"space-y-large py-large",children:(tv.iM[u.slug]||[]).map(e=>{let s=C[e.key],n=(0,tv.Nl)(e.key),r=(tv.L$[u.slug]??[]).includes(e.ke
1y),i=!!j[e.key],l=x[e.key]??"",o=n&&s?.set===!0;return(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)(eJ.J,{htmlFor:e.key,children:[e.label,r&&!o&&(0,a.jsx)("span",{className:"text-destructive ml-small",children:"*"})]}),(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(e3.p,{id:e.key,type:"password"!==e.type||g[e.key]?"text":"password",autoComplete:"password"===e.type?"new-password":"off",placeholder:o&&!i?t.credentialStoredKeepBlank:e.placeholder,value:l,disabled:i,onChange:s=>y(t=>({...t,[e.key]:s.target.value})),className:"password"===e.type?"pr-10":""}),"password"===e.type&&""!==l&&(0,a.jsx)("button",{type:"button",onClick:()=>{var s;return s=e.key,void f(e=>({...e,[s]:!e[s]}))},className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:g[e.key]?(0,a.jsx)(tg.A,{className:"icon-body"}):(0,a.jsx)(tf.A,{className:"icon-body"})})]}),(0,a.jsxs)("div",{className:"flex-between gap-body text-small text-muted-foreground",children:[(0,a.jsx)("span",{children:i?t.credentialWillBeCleared:s?.set?t.configured:t.credentialNotConfigured}),s?.set&&(0,a.jsx)("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>b(s=>({...s,[e.key]:!s[e.key]})),children:i?t.undoClearCredential:t.clearCredential})]})]},e.key)})}),(0,a.jsxs)(eV.Es,{children:[(0,a.jsx)(eP.$,{variant:"outline",onClick:()=>p(!1),disabled:v,children:t.cancel}),(0,a.jsx)(eP.$,{onClick:()=>{if(!u||!C)return;let e=(0,tv.QP)(u.slug,C,x,j);(0,tv.tx)(e)?p(!1):c.mutate({integrationId:u.id,...e},{onSuccess:()=>{p(!1),y({}),f({}),b({})}})},disabled:v||!C,children:v?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tj.A,{className:"icon-body animate-spin"}),t.saving]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(e4.A,{className:"icon-body"}),t.save]})})]})]})})]})}var tA=t(56331);function tS(){return(0,a.jsx)(tA.TourListPage,{})}var tT=t(37866),tk=t.n(tT),tD=t(13863);function tI({checklistId:e,open:s,onOpenChange:t}){let{data:n,isLoading:r}=(0,P.useQuery)({queryKey:["admin-checklist-preview",e],enabled:s&&!!e,queryFn:async()=>{let s=await fetch(`/api/admin/tours/checklists/${e}`);if(!s.ok)return null;let t=(await s.json()).data;return t?{...t,items:(t.items??[]).map(e=>({...e,completed:!1}))}:null}});return(0,a.jsx)(eV.Dz,{open:s,onOpenChange:t,children:(0,a.jsxs)(eV.Cf,{children:[(0,a.jsxs)(eV.c7,{children:[(0,a.jsx)(eV.L3,{children:"Checklist preview"}),(0,a.jsx)(eV.rr,{children:"Live render of the checklist as users see it. Items show as incomplete; dismiss and item navigation are disabled here."})]}),r&&(0,a.jsx)("div",{className:"py-large text-body text-muted-foreground",children:"Loading…"}),!r&&!n&&(0,a.jsx)("div",{className:"py-large text-body text-muted-foreground",children:"Not found."}),n&&(0,a.jsx)("div",{className:"rounded-default border border-border bg-muted/30 p-large",children:(0,a.jsx)(tD.f,{checklist:n,variant:"inline",preview:!0})})]})})}function tP(){let[e,s]=(0,S.useState)(null),{data:t=[],isLoading:n}=(0,P.useQuery)({queryKey:["admin-onboarding-checklists"],queryFn:async()=>{let e=await fetch("/api/admin/tours/checklists");return e.ok?(await e.json()).data??[]:[]}});return(0,a.jsxs)("div",{className:"flex flex-col gap-large",children:[(0,a.jsxs)("div",{className:"flex-between",children:[(0,a.jsx)("h2",{className:"text-heading font-semibold",children:"Checklists"}),(0,a.jsx)(tk(),{href:"/settings/developer/tours/checklists/new",children:(0,a.jsx)(eP.$,{children:"New checklist"})})]}),(0,a.jsxs)(ss.XI,{children:[(0,a.jsx)(ss.A0,{children:(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nd,{children:"Name"}),(0,a.jsx)(ss.nd,{children:"Status"}),(0,a.jsx)(ss.nd,{children:"Items"}),(0,a.jsx)(ss.nd,{children:"Priority"}),(0,a.jsx)(ss.nd,{children:"Conditions"}),(0,a.jsx)(ss.nd,{})]})}),(0,a.jsxs)(ss.BF,{children:[n&&(0,a.jsx)(ss.Hj,{children:(0,a.jsx)(ss.nA,{colSpan:6,className:"text-muted-foreground",children:"Loading…"})}),!n&&0===t.length&&(0,a.jsx)(ss.Hj,{children:(0,a.jsx)(ss.nA,{colSpan:6,className:"text-muted-foreground",children:"No checklists yet."})}),t.map(e=>(0,a.jsxs)(ss.Hj,{children:[(0,a.jsx)(ss.nA,{className:"font-medium",children:e.name}),(0,a.jsx)(ss.nA,{children:(0,a.jsx)(eq.E,{variant:"PUBLISHED"===e.status?"default":"outline",children:e.status})}),(0,a.jsx)(ss.nA,{children:e.items.length}),(0,a.jsx)(ss.nA,{children:e.priority}),(0,a.jsx)(ss.nA,{children:e.conditions.length}),(0,a.jsx)(ss.nA,{children:(0,a.jsxs)("div",{className:"flex items-center justify-end gap-body",children:[(0,a.jsxs)(eP.$,{variant:"ghost",size:"small",onClick:()=>s(e.id),children:[(0,a.jsx)(tf.A,{className:"icon-body"}),"Preview"]}),(0,a.jsx)(tk(),{href:`/settings/developer/tours/checklists/${e.id}/edit`,children:(0,a.jsx)(eP.$,{variant:"ghost",size:"small",children:"Edit"})})]})})]},e.id))]})]}),(0,a.jsx)(tI,{checklistId:e,open:null!==e,onOpenChange:e=>{e||s(null)}})]})}function t_(){return(0,a.jsx)(tP,{})}var tO=t(94288);function tR(){let e=(0,n.t0)(),s=(0,k.useQueryClient)(),[t,r]=(0,S.useState)(""),[i,l]=(0,S.useState)(""),[o,d]=(0,S.useState)(""),[c,u]=(0,S.useState)(null),[m,h]=(0,S.useState)(""),{data:p,isLoading:x}=(0,P.useQuery)({queryKey:["admin","email-blocklist",t],queryFn:async()=>{let e=t?`?search=${encodeURIComponent(t)}`:"",s=await fetch(`/api/admin/email-blocklist${e}`);if(!s.ok)throw Error(`HTTP ${s.status}`);return(await s.json()).data},staleTime:0,refetchOnWindowFocus:!1}),y=()=>s.invalidateQueries({queryKey:["admin","email-blocklist"]}),g=(0,U.useMutation)({mutationFn:async()=>{let e=await fetch("/api/admin/email-blocklist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:i.trim(),reason:o.trim()})}),s=await e.json().catch(()=>({}));if(!e.ok)throw Error(s.message||s.error||`HTTP ${e.status}`);return s.data},onSuccess:s=>{D.me.success(e.emailBlockedSuccess),s.existingProfileId&&D.me.info(e.emailBlockedExistingAccount),l(""),d(""),y()},onError:s=>{D.me.error(e.emailBlockedError,{description:s instanceof Error?s.message:String(s)})}}),f=(0,U.useMutation)({mutationFn:async()=>
1{if(!c)throw Error("No target");let e=await fetch(`/api/admin/email-blocklist/${c.id}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:m.trim()})}),s=await e.json().catch(()=>({}));if(!e.ok)throw Error(s.message||s.error||`HTTP ${e.status}`)},onSuccess:()=>{D.me.success(e.emailUnblockedSuccess),u(null),h(""),y()},onError:s=>{D.me.error(e.emailUnblockedError,{description:s instanceof Error?s.message:String(s)})}}),j=i.includes("@")&&o.trim().length>=eY.n&&!g.isPending;return(0,a.jsxs)("div",{className:"space-y-large",children:[(0,a.jsxs)(sS.Fc,{children:[(0,a.jsx)(so.A,{className:"icon-body"}),(0,a.jsx)(sS.TN,{children:"A blocked address cannot create a new account on any signup path (password, invitation, Google/Microsoft, SSO). Plus-tag aliases are matched too. Existing accounts and their logins are NOT affected — use user deletion for those. Every change here is audited."})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(eJ.J,{htmlFor:"blockEmail",children:"Block an email address"}),(0,a.jsxs)("div",{className:"flex gap-body",children:[(0,a.jsx)(e3.p,{id:"blockEmail",placeholder:"[email protected]",value:i,onChange:e=>l(e.target.value),disabled:g.isPending}),(0,a.jsx)(eP.$,{variant:"destructive",disabled:!j,onClick:()=>g.mutate(),children:"Block"})]}),(0,a.jsx)(e3.p,{placeholder:`Reason for the audit log (min. ${eY.n} characters)`,value:o,onChange:e=>d(e.target.value),disabled:g.isPending})]}),(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsxs)("div",{className:"flex-between gap-body",children:[(0,a.jsxs)(eJ.J,{htmlFor:"blocklistSearch",children:["Blocked addresses",p?` (${p.entries.length})`:""]}),(0,a.jsx)(e3.p,{id:"blocklistSearch",placeholder:"Search…",value:t,onChange:e=>r(e.target.value),className:"max-w-64"})]}),x?(0,a.jsx)(T.E,{className:"h-32 w-full"}):p?.entries.length?(0,a.jsx)("ul",{className:"max-h-96 overflow-y-auto space-y-small border rounded-default p-small text-small",children:p.entries.map(e=>(0,a.jsxs)("li",{className:"flex-between gap-body border-b last:border-0 py-small",children:[(0,a.jsxs)("span",{className:"min-w-0",children:[(0,a.jsx)("span",{className:"font-medium",children:e.email})," ",(0,a.jsxs)("span",{className:"text-muted-foreground",children:[e.reason," \xb7 ",(0,eL.Yq)(e.createdAt)," \xb7"]})," ",(0,a.jsx)("code",{className:"font-mono select-all text-muted-foreground",children:e.id})]}),(0,a.jsxs)(eP.$,{variant:"outline",size:"small",onClick:()=>u(e),children:[(0,a.jsx)(tO.A,{className:"icon-small"}),"Unblock"]})]},e.id))}):(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:"No blocked addresses."})]}),(0,a.jsx)(eV.Dz,{open:null!==c,onOpenChange:e=>{e||(u(null),h(""))},children:(0,a.jsxs)(eV.Cf,{children:[(0,a.jsxs)(eV.c7,{children:[(0,a.jsx)(eV.L3,{children:"Unblock email address"}),(0,a.jsxs)(eV.rr,{children:["Removing this entry immediately allows"," ",(0,a.jsx)("code",{className:"font-mono select-all",children:c?.email})," ","(and its aliases) to register again. Provide a reason for the audit log."]})]}),(0,a.jsx)(eQ.T,{value:m,onChange:e=>h(e.target.value),placeholder:`Reason (min. ${eY.n} characters)`,rows:3,autoFocus:!0}),(0,a.jsxs)(eV.Es,{children:[(0,a.jsx)(eP.$,{variant:"outline",onClick:()=>{u(null),h("")},children:"Cancel"}),(0,a.jsx)(eP.$,{variant:"destructive",disabled:m.trim().length<eY.n||f.isPending,onClick:()=>f.mutate(),children:"Unblock"})]})]})})]})}},26118:(e,s,t)=>{t.d(s,{b:()=>n,r:()=>r});var a=t(2315);let n=(0,a.createContext)(null);function r(e){let s=(0,a.useContext)(n);(0,a.useEffect)(()=>{if(s)return s(e),()=>s(!1)},[s,e])}},30446:(e,s,t)=>{t.d(s,{C:()=>_});var a=t(68987),n=t(42725),r=t(2315),i=t(73591),l=t(7586),o=t(34973),d=t(82332),c=t(9519),u=t(44991),m=t(55264),h=t(4965),p=t(91541),x=t(50363),y=t(38339),g=t(22707),f=t(82671),j=t(97717),b=t(42346),v=t(66665),N=t(94288),C=t(59455),E=t(54324),w=t(21710),A=t(35777);let S=new Set(["force-unenroll-mfa"]),T=e=>["admin","user-auth-status",e],k={"password-reset":"Send password-reset email","resend-verification":"Resend verification email","force-verify":"Force-verify email","force-unenroll-mfa":"Remove MFA (recovery)"},D={"password-reset":"Password-reset email sent","resend-verification":"Verification email sent","force-verify":"Email marked as verified","force-unenroll-mfa":"MFA removed — the user can re-enrol at next sign-in"},I={"password-reset":"Couldn't send the password-reset email","resend-verification":"Couldn't send the verification email","force-verify":"Couldn't verify the email","force-unenroll-mfa":"Couldn't remove MFA"};function P(e){return e?(0,C.r6)(e):"—"}function _({userId:e,companyId:s,userLabel:t,onOpenChange:C}){let R=(0,n.t0)(),L=(0,n.WD)(),F=null!==e,M=(0,i.useQueryClient)(),[U,$]=(0,r.useState)(null),[K,B]=(0,r.useState)(""),[H,q]=(0,r.useState)("overview"),[G,z]=(0,r.useState)(!1);(0,r.useEffect)(()=>{e&&q("overview")},[e]);let{data:W,isLoading:J}=(0,l.useQuery)({queryKey:e?T(e):["admin","user-auth-status","none"],queryFn:async()=>{let s=await fetch(`/api/admin/users/${e}/status`);if(!s.ok)throw Error(`HTTP ${s.status}`);return(await s.json()).data},enabled:F,staleTime:0,refetchOnWindowFocus:!1,retry:!1}),{data:Q,isLoading:V}=(0,l.useQuery)({queryKey:e?["admin","user-companies",e]:["admin","user-companies","none"],queryFn:async()=>{let s=await fetch(`/api/admin/users/${e}/companies`);if(!s.ok)throw Error(`HTTP ${s.status}`);return(await s.json()).data.companies},enabled:F&&"companies"===H,staleTime:0,refetchOnWindowFocus:!1,retry:!1}),Y=(0,o.useMutation)({mutationFn:async({action:t,reason:a})=>{let n=s?`?companyId=${encodeURIComponent(s)}`:"",r=await fetch(`/api/admin/users/${e}/${t}${n}`,{method:"POST",...a?{headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:a})}:{}}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||`HTTP ${r.status}`);return t},onSuccess:s=>{E.me.success(D[s]),e&&M.invalidateQueries({queryKey:T(e)})},onError:(s,t)=>{E.me.error(I[t.action],{description:s instanceof Error?s.message:String(s)}),e&&M.invalidateQueries({queryKey:T(e)})}}),X=Y.isPending;function Z({action:e,icon:s,enabled:t,disabledReason:n}){return(0,a.jsxs)(u.$,{variant:"outline",className:"w-full justify-start",disabled:!t||X,title:t?void 0:n,onClick:()=>$(e),children:[X&&Y.variables?.action===e?(0,a.jsx)(g.A,{className:"icon-body animate-spin"}):s,k[e]]})}let ee=J?(0,a.jsx)(p.E,{className:"h-40 w-full"}):W?(0,a.jsxs)("dl",{className:"space-y-body text-small",children:[(0,a.jsx)(O,{label:"Email",children:W.email??"—"}),(0,a.jsx)(O,{label:"Verified",children:W.emailVerified?(0,a.jsxs)(m.E,{variant:"success",className:"text-small",children:[(0,a.jsx)(f.A,{className:"icon-small"})," Verified"]}):(0,a.jsx)(m.E,{variant:"warning",className:"text-small",children:"Unverified"})}),(0,a.jsx)(O,{label:R.lastSignIn,children:P(W.lastSignInAt)}),(0,a.jsx)(O,{label:"Created",children:P(W.createdAt)}),(0,a.jsx)(O,{label:"Providers",children:W.providers.length?W.providers.join(", "):"—"}),(0,a.jsx)(O,{label:"MFA",children:W.mfaEnrolled?"Enrolled":"None"})]}):(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:R.noData}),es=J?(0,a.jsx)(p.E,{className:"h-32 w-full"}):W?(0,a.jsxs)("div",{className:"flex flex-col gap-body",children:[(0,a.jsx)(Z,{action:"password-reset",icon:(0,a.jsx)(j.A,{className:"icon-body"}),enabled:W.can.sendPasswordReset,disabledReason:W.ssoEntryPath?`Signs in via SSO (${W.ssoEntryPath})`:"No email on file"}),(0,a.jsx)(Z,{action:"resend-verification",icon:(0,a.jsx)(b.A,{className:"icon-body"}),enabled:W.can.resendVerification,disabledReason:"Email already verified"}),(0,a.jsx)(Z,{action:"force-verify",icon:(0,a.jsx)(f.A,{className:"icon-body"}),enabled:W.can.forceVerify,disabledReason:"Email already verified"}),W.can.forceUnenrollMfa&&(0,a.jsx)(Z,{action:"force-unenroll-mfa",icon:(0,a.jsx)(v.A,{className:"icon-body"}),enabled:W.can.forceUnenrollMfa,disabledReason:"No MFA enrolled"}),(0,a.jsx)("div",{className:"border-t pt-body",children:(0,a.jsxs)(u.$,{variant:"destructive",className:"w-full justify-start",disabled:X,onClick:()=>z(!0),children:[(0,a.jsx)(N.A,{className:"icon-body"}),"Delete user completely"]})})]}):(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:R.noData2}),et=V?(0,a.jsx)(p.E,{className:"h-32 w-full"}):Q?.length?(0,a.jsx)("ul",{className:"space-y-small text-small",children:Q.map(e=>(0,a.jsxs)("li",{className:"flex-between gap-body border-b last:border-0 py-small",children:[(0,a.jsx)("span",{className:"font-medium",children:e.companyName}),(0,a.jsx)(m.E,{variant:"outline",className:"text-small",children:e.role})]},e.companyId))}):(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:R.notAMemberOfAnyCompany});return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(d.cj,{open:F,onOpenChange:C,children:(0,a.jsxs)(d.h,{className:"flex flex-col gap-large",children:[(0,a.jsxs)(d.Fm,{children:[(0,a.jsxs)(d.qp,{children:[R.manageUserTitle,t?` — ${t}`:""]}),(0,a.jsx)(d.Qs,{children:R.platformIdentityActionsForThisUser})]}),(0,a.jsxs)(x.Fc,{children:[(0,a.jsx)(v.A,{className:"icon-body"}),(0,a.jsxs)(x.TN,{children:[R.theseActionsAffectAcross," ",(0,a.jsx)("strong",{children:R.entirePlatform}),R.notJustThisCompany]})]}),(0,a.jsx)(c.Vw,{activeTab:H,onTabChange:q,tabs:[{id:"overview",label:"Overview",content:ee},{id:"identity",label:"Identity",content:es},{id:"companies",label:"Companies",content:et}]})]})}),e&&(0,a.jsx)(A.$,{open:G,onOpenChange:z,userId:e,userEmail:W?.email??null,companyId:s,onDeleted:()=>C(!1)}),(0,a.jsx)(y.Dz,{open:null!==U,onOpenChange:e=>{e||($(null),B(""))},children:(0,a.jsxs)(y.Cf,{children:[(0,a.jsxs)(y.c7,{children:[(0,a.jsx)(y.L3,{children:U?k[U]:""}),(0,a.jsx)(y.rr,{children:"force-unenroll-mfa"===U?"This removes all of the user's MFA factors across the entire platform so they can sign in and re-enroll. Provide a reason for the audit log.":"force-verify"===U?"This marks the email as verified without the user confirming it.":"This sends an email to the user. Continue?"})]}),U&&S.has(U)&&(0,a.jsx)(h.T,{value:K,onChange:e=>B(e.target.value),placeholder:L("settings.reasonMinCharacters",{count:w.n}),rows:3,autoFocus:!0}),(0,a.jsxs)(y.Es,{children:[(0,a.jsx)(u.$,{variant:"outline",onClick:()=>{$(null),B("")},children:"Cancel"}),(0,a.jsx)(u.$,{variant:U&&S.has(U)?"destructive":"default",disabled:null!==U&&S.has(U)&&K.trim().length<w.n,onClick:()=>
1{if(U){let e=S.has(U);Y.mutate({action:U,reason:e?K.trim():void 0})}$(null),B("")},children:"Confirm"})]})]})})]})}function O({label:e,children:s}){return(0,a.jsxs)("div",{className:"flex-between gap-body",children:[(0,a.jsx)("dt",{className:"text-muted-foreground",children:e}),(0,a.jsx)("dd",{className:"font-medium",children:s})]})}},30891:(e,s,t)=>{t.d(s,{z:()=>l});var a=t(68987);t(2315);var n=t(9519),r=t(71519),i=t(82903);function l({title:e,description:s,subtitle:t,tabs:o,actions:d,activeTab:c,onTabChange:u,backButton:m,className:h="",variant:p="compact",titleContent:x,inContentContainer:y=!0,tourPrefix:g}){let f="expanded"===p&&(s||o&&o.length>0),j=e||x||m,b=j||d,v=o&&o.length>0&&!b&&!s,N=o&&o.length>0&&d&&!j&&!s,C=i.U.HEADER,E=f||v||N;return(0,a.jsx)("div",{"data-onboarding":g?`${g}.header`:void 0,className:(0,r.cn)("border-b bg-background flex-shrink-0",C,"min-h-[56px]",E?(0,r.cn)("flex flex-col",v?"px-4 sm:px-6 lg:px-8 py-body":N?i.U.STANDARD_HEADER_PADDING:"px-4 sm:px-6 lg:px-8 py-small"):"flex items-center px-4 sm:px-6 lg:px-8",h),children:N?(0,a.jsxs)("div",{className:"flex items-center h-full relative",children:[(0,a.jsx)("div",{className:"flex-1"}),(0,a.jsx)("div",{className:"flex-center",children:(0,a.jsx)(n.Vw,{tabs:o.map(e=>({id:e.id,label:e.label,mobileLabel:"string"==typeof e.label?e.label.split(" ")[0]:e.label,icon:e.icon})),activeTab:c,onTabChange:u,responsiveLabels:!0,showContent:!1,tabsListVariant:"pill",containerPadding:"p-0",className:"w-auto"})}),(0,a.jsx)("div",{className:"flex items-center gap-body flex-shrink-0 flex-1 justify-end",children:d})]}):(0,a.jsxs)(a.Fragment,{children:[b&&(0,a.jsxs)("div",{className:(0,r.cn)("flex-between gap-large overflow-x-auto w-full",f&&"h-7 flex-shrink-0"),children:[(0,a.jsxs)("div",{className:"flex items-center gap-body min-w-0 flex-1",children:[m&&(0,a.jsx)("div",{className:"flex-shrink-0",children:m}),x?(0,a.jsx)("div",{className:"flex items-center gap-body flex-shrink-0",children:x}):e&&(0,a.jsxs)("div",{className:"flex items-center gap-body min-w-0",children:[(0,a.jsx)("h1",{className:"text-heading font-semibold tracking-tight md:text-title truncate",children:e}),t&&(0,a.jsx)("span",{className:"text-body text-muted-foreground hidden sm:inline truncate",children:t})]})]}),d&&(0,a.jsx)("div",{"data-onboarding":g?`${g}.header.actions`:void 0,className:"flex items-center gap-body flex-shrink-0",children:d})]}),f&&(0,a.jsx)("div",{className:(0,r.cn)("flex-center w-full flex-shrink-0",v?"h-full":"h-7"),children:o&&o.length>0?(0,a.jsx)(n.Vw,{tabs:o.map(e=>({id:e.id,label:e.label,mobileLabel:"string"==typeof e.label?e.label.split(" ")[0]:e.label,icon:e.icon})),activeTab:c,onTabChange:u,responsiveLabels:!0,showContent:!1,tabsListVariant:"pill",containerPadding:"p-0",className:"w-auto"}):s&&(0,a.jsx)("p",{className:"text-muted-foreground text-body truncate",children:s})})]})})}},35622:(e,s,t)=>{t.d(s,{KV:()=>c,zk:()=>m,N9:()=>u});let a=[/eyJ[A-Za-z0-9._-]{10,}/g,/sb-[a-zA-Z0-9-]+-auth-token/g,/\bBearer\s+[A-Za-z0-9._\-]{12,}/gi,/\b(?:sk|pk|rk)[-_](?:live|test|prod)?[-_]?[A-Za-z0-9]{16,}/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bghp_[A-Za-z0-9]{30,}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/gi,/[?&][^=&\s]*(?:key|token|secret|password|passwd|credential|auth)[^=&\s]*=[^&\s"']{8,}/gi],n="[REDACTED]",r=/=\\?"|<\/|[{}\\]|&#|&[a-z]+;/,i=[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,/^[0-9a-f]{32}$/i,/^c[a-z0-9]{20,32}$/,/^[\w][\w.-]*\.[A-Za-z0-9]{1,6}$/,/^\/[\w/.-]+$/,/^[A-Za-z][A-Za-z0-9]*(?:[_-][A-Za-z0-9]+){2,}$/],l=/https?:\/\//i,o=/[?&][^=&\s]*(signature|sig|token|key|secret|password|auth|credential)[^=&\s]*=|\/object\/sign\/|[?&]se=/i;function d(e){return!!i.some(s=>s.test(e))||!!l.test(e)&&!o.test(e)}let c=new Set(["password","passwd","pass","secret","token","key","apikey","authorization","auth","cookie","credential","credentials","bearer","jwt","signature"]);function u(e){let s=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[\s_\-.]+/).filter(Boolean).map(e=>e.toLowerCase());return 0!==s.length&&c.has(s[s.length-1])}function m(e,s=24){let t=0,i=0;return{value:function e(l,o){if(o>s)return l;if("string"==typeof l){let s=function(e){let s=e.trim();if(s.startsWith("{")||s.startsWith("["))try{let e=JSON.parse(s);return"object"==typeof e&&null!==e?e:void 0}catch{return}}(l);if(void 0!==s)return JSON.stringify(e(s,o+1));let{redacted:t,hits:c}=function(e,s={}){let t=0,i=e;for(let e of a)i=i.replace(e,()=>(t++,n));return!1===s.entropySweep?{redacted:i,hits:t}:{redacted:i=i.replace(/\S{24,}/g,e=>{if(e===n||r.test(e))return e;let s=e.replace(/^["'([{\\]+/,"").replace(/["'),.\]}:;\\]+$/,"");return d(e)||d(s)||!function(e){if(e.length<20||/\s/.test(e))return!1;let s=/[A-Za-z]/.test(e),t=/\d/.test(e);return!!s&&!!t&&function(e){if(0===e.length)return 0;let s=new Map;for(let t of e)s.set(t,(s.get(t)??0)+1);let t=0;for(let a of s.values()){let s=a/e.length;t-=s*Math.log2(s)}return t}(e)>=3.5}(e)?e:(t++,n)}),hits:t}}(l,{entropySweep:!1});return i+=c,t}if(Array.isArray(l))return l.map(s=>e(s,o+1));if(l&&"object"==typeof l){let s={};for(let[a,n]of Object.entries(l)){if(u(a)){t++,s[a]="[SECRET WITHHELD]";continue}s[a]=e(n,o+1)}return s}return l}(e,0),fieldsWithheld:t,spansRedacted:i}}},35777:(e,s,t)=>{t.d(s,{$:()=>v});var a=t(68987),n=t(2315),r=t(73591),i=t(7586),l=t(34973),o=t(38339),d=t(50363),c=t(44991),u=t(2793),m=t(4965),h=t(91541),p=t(32848),x=t(29146),y=t(22707),g=t(54324),f=t(42725),j=t(21710);let b={SELF_DELETION_FORBIDDEN:"You cannot delete your own account.",TARGET_IS_SUPER_ADMIN:"The target is another super-admin. Peer deletion is not allowed (separation of duties).",USER_HAS_ADMIN_AUDIT_TRAIL:"This user has operator audit records (AdminAction). The audit trail must stay attributable, so the account cannot be hard-deleted.",USER_IS_LAST_COMPANY_ADMIN:"The user is the last admin (or sole member) of the companies below. Delete each company first via its own audited path — company deletion is blocked while a subscription is active, so cancel that first if prompted."};function v({open:e,onOpenChange:s,userId:t,userEmail:N,companyId:C,onDeleted:E,deferAdminInvalidation:w=!1}
1){let A=(0,f.t0)(),S=(0,r.useQueryClient)(),[T,k]=(0,n.useState)(""),[D,I]=(0,n.useState)(""),[P,_]=(0,n.useState)(!1),[O,R]=(0,n.useState)(null),{data:L,isLoading:F}=(0,i.useQuery)({queryKey:["admin","user-deletion-preflight",t],queryFn:async()=>{let e=await fetch(`/api/admin/users/${t}/deletion-preflight`);if(!e.ok)throw Error(`HTTP ${e.status}`);return(await e.json()).data.blockers},enabled:e&&!O,staleTime:0,refetchOnWindowFocus:!1,retry:!1}),M=(0,l.useMutation)({mutationFn:async()=>{let e=C?`?companyId=${encodeURIComponent(C)}`:"",s=await fetch(`/api/admin/users/${t}${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:T.trim()})}),a=await s.json().catch(()=>({}));if(!s.ok){let e=a.details?.blockers?.map(e=>e.code).join(", ")??"";throw Error([a.message||a.error||`HTTP ${s.status}`,e].filter(Boolean).join(" — "))}return a.data},onSuccess:async e=>{if(R(e),g.me.success(A.userDeletedEverywhere),P&&N)try{let e=await fetch("/api/admin/email-blocklist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:N,reason:`user-deletion follow-up: ${T.trim()}`})});if(!e.ok)throw Error(`HTTP ${e.status}`);g.me.success(A.emailBlockedSuccess)}catch(e){g.me.error(A.emailBlockedError,{description:e instanceof Error?e.message:String(e)})}w||S.invalidateQueries({queryKey:["admin"]})},onError:e=>{g.me.error(A.couldntDeleteUser,{description:e instanceof Error?e.message:String(e)}),S.invalidateQueries({queryKey:["admin","user-deletion-preflight",t]})}}),U=(L?.length??0)>0,$=!!N&&D.trim()===N,K=T.trim().length>=j.n;function B(e){if(!e){let e=null!==O;_(!1),k(""),I(""),R(null),e&&E?.()}s(e)}return(0,a.jsx)(o.Dz,{open:e,onOpenChange:B,children:(0,a.jsxs)(o.Cf,{children:[(0,a.jsxs)(o.c7,{children:[(0,a.jsx)(o.L3,{children:"Delete user completely"}),(0,a.jsxs)(o.rr,{children:["Permanently deletes this user across the"," ",(0,a.jsx)("strong",{children:"entire platform"})," — every company footprint, the account row, and the sign-in identity (including Google/Microsoft links and MFA factors). This is not reversible."]})]}),(0,a.jsxs)("p",{className:"text-small text-muted-foreground",children:["Target:"," ",(0,a.jsx)("code",{className:"font-mono select-all",children:N??"—"})," — id"," ",(0,a.jsx)("code",{className:"font-mono select-all",children:t})]}),O?(0,a.jsxs)("div",{className:"space-y-small text-small",children:[(0,a.jsx)(d.Fc,{children:(0,a.jsx)(d.TN,{children:O.repair?"Orphaned sign-in identity removed (repair run).":"Deletion complete. The full manifest is recorded as a USER_DELETED event in Compliance."})}),O.companiesSwept.length>0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("p",{className:"font-medium",children:[O.companiesSwept.length," company footprint(s) erased:"]}),(0,a.jsx)("ul",{className:"max-h-48 overflow-y-auto space-y-small border rounded-default p-small",children:O.companiesSwept.map(e=>(0,a.jsxs)("li",{className:"flex-between gap-body",children:[(0,a.jsx)("span",{children:e.companyName}),(0,a.jsx)("code",{className:"font-mono select-all text-muted-foreground",children:e.companyId})]},e.companyId))})]}),!O.authUserDeleted&&(0,a.jsxs)(d.Fc,{variant:"destructive",children:[(0,a.jsx)(x.A,{className:"icon-body"}),(0,a.jsx)(d.TN,{children:"The sign-in identity could not be removed. Re-run the deletion to finish the cleanup."})]})]}):F?(0,a.jsx)(h.E,{className:"h-24 w-full"}):U?(0,a.jsxs)("div",{className:"space-y-small text-small",children:[(0,a.jsxs)("p",{className:"font-medium",children:[L?.length," blocker(s) must be resolved first:"]}),(0,a.jsx)("div",{className:"max-h-60 overflow-y-auto space-y-body border rounded-default p-small",children:L?.map(e=>(0,a.jsxs)(d.Fc,{variant:"destructive",children:[(0,a.jsx)(x.A,{className:"icon-body"}),(0,a.jsxs)(d.TN,{children:[b[e.code]??e.code,"USER_HAS_ADMIN_AUDIT_TRAIL"===e.code&&(0,a.jsxs)(a.Fragment,{children:[" (",e.adminActionCount," records)"]}),"USER_IS_LAST_COMPANY_ADMIN"===e.code&&(0,a.jsx)("ul",{className:"mt-small space-y-small",children:e.companies.map(e=>(0,a.jsxs)("li",{className:"flex-between gap-body",children:[(0,a.jsx)("span",{className:"font-medium",children:e.name}),(0,a.jsx)("code",{className:"font-mono select-all",children:e.id})]},e.id))})]})]},e.code))})]}):(0,a.jsxs)("div",{className:"space-y-body",children:[(0,a.jsx)(m.T,{value:T,onChange:e=>k(e.target.value),placeholder:`Reason for the audit log (min. ${j.n} characters)`,rows:3,autoFocus:!0}),(0,a.jsxs)("div",{className:"space-y-small",children:[(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:"Type the user's email to confirm:"}),(0,a.jsx)(u.p,{value:D,onChange:e=>I(e.target.value),placeholder:N??"",disabled:!N})]}),N&&(0,a.jsxs)("label",{className:"flex items-center gap-body text-small cursor-pointer",children:[(0,a.jsx)(p.S,{checked:P,onCheckedChange:e=>_(!0===e)}),"Also block this email address (prevents re-registration on every signup path; separately audited)"]})]}),(0,a.jsxs)(o.Es,{children:[(0,a.jsx)(c.$,{variant:"outline",onClick:()=>
1B(!1),children:O?"Close":"Cancel"}),!O&&(0,a.jsxs)(c.$,{variant:"destructive",disabled:F||U||!K||!$||M.isPending,onClick:()=>M.mutate(),children:[M.isPending?(0,a.jsx)(y.A,{className:"icon-body animate-spin"}):null,"Delete user"]})]})]})})}},50703:(e,s,t)=>{t.d(s,{I:()=>c});var a=t(68987),n=t(2315),r=t(14915),i=t(86689),l=t(23431),o=t(71519),d=t(85149);function c(e){let{placeholder:s="Search...",isLoading:t=!1,disabled:c=!1,className:u,inputClassName:m,autoFocus:h=!1,variant:p="default",size:x="body"}=e,y="value"in e&&"onChange"in e&&!("items"in e&&void 0!==e.items),g=y?null:e,[f,j]=(0,n.useState)(""),b=y?e.value:g?.value??f,v=(0,n.useCallback)(s=>{y?e.onChange(s):g?.onChange?g.onChange(s):j(s)},[y,e,g]),[N,C]=(0,n.useState)(!1),[E,w]=(0,n.useState)(-1),A=(0,n.useRef)(null),S=(0,n.useRef)(null),T=(0,n.useRef)(null),k=g?.showDropdown??!0,D=g?.showSuggestions??!0,I=g?.maxSuggestions??5,P=g?.maxResults??10,_=g?.debounceMs??300,O=g?.clearOnSelect??!0,R=(0,n.useMemo)(()=>!y&&g?.items&&b.trim()?(0,d.XK)(g.items,b,g.searchFields,{maxResults:P,...g.searchOptions}):[],[y,g,b,P]),L=(0,n.useMemo)(()=>{if(y||!D||!b.trim()||b.length<2)return[];let e=new Set;return R.forEach(s=>{g?.searchFields.forEach(t=>{let a=String(s.item[t]||"");a.toLowerCase().includes(b.toLowerCase())&&e.add(a)})}),Array.from(e).slice(0,I)},[y,b,R,g?.searchFields,D,I]);(0,n.useEffect)(()=>{!y&&g?.onResultsChange&&g.onResultsChange(R)},[y,R,g]);let F=(0,n.useCallback)(e=>{v(e),w(-1),y||(T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{},_))},[y,v,_]),M=(0,n.useCallback)(e=>{g?.onItemSelect?.(e),O&&v(""),C(!1),A.current?.blur()},[g,O,v]),U=(0,n.useCallback)(e=>{v(e),C(!1),A.current?.blur()},[v]),$=(0,n.useCallback)(e=>{if(y){"Escape"===e.key&&(v(""),A.current?.blur());return}let s=L.length+R.length;switch(e.key){case"ArrowDown":e.preventDefault(),w(e=>Math.min(e+1,s-1));break;case"ArrowUp":e.preventDefault(),w(e=>Math.max(e-1,-1));break;case"Enter":e.preventDefault(),E>=0&&E<L.length?U(L[E]):E>=L.length&&E<s&&M(R[E-L.length].item);break;case"Escape":C(!1),A.current?.blur()}},[y,E,L,R,U,M,v]),K=(0,n.useCallback)(()=>{C(!0),w(-1)},[]),B=(0,n.useCallback)(()=>{setTimeout(()=>{S.current?.contains(document.activeElement)||(C(!1),w(-1))},150)},[]),H=(0,n.useCallback)(()=>{v(""),w(-1),A.current?.focus()},[v]);(0,n.useEffect)(()=>{h&&A.current&&A.current.focus()},[h]),(0,n.useEffect)(()=>()=>{T.current&&clearTimeout(T.current)},[]);let q=!y&&k&&N&&(b.trim()||L.length>0),G=R.length>0,z=L.length>0;return(0,a.jsxs)("div",{className:(0,o.cn)("relative w-full",u),children:[(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(r.A,{className:(0,o.cn)("absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground","large"===x?"icon-heading":"small"===x?"icon-small":"icon-body")}),(0,a.jsx)("input",{ref:A,type:"text",value:b,onChange:e=>F(e.target.value),onKeyDown:$,onFocus:K,onBlur:B,placeholder:s,disabled:c,className:(0,o.cn)("w-full pl-[2rem] pr-[2rem]","ring-offset-background","placeholder:text-muted-foreground","focus-visible:outline-none","disabled:cursor-not-allowed disabled:opacity-50",{large:"h-large text-body rounded-default",body:"h-body text-body rounded-default",small:"h-small text-mini rounded-default"}[x],{default:"border border-input bg-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",filled:"border-0 bg-muted focus-visible:ring-2 focus-visible:ring-primary",minimal:"border-0 bg-transparent hover:bg-muted/50 focus-visible:bg-muted focus-visible:ring-1 focus-visible:ring-ring"}[p],m)}),t&&(0,a.jsx)(i.A,{className:(0,o.cn)("absolute right-9 top-1/2 -translate-y-1/2 animate-spin text-muted-foreground","large"===x?"icon-heading":"small"===x?"icon-small":"icon-body")}),b&&!t&&(0,a.jsx)("button",{type:"button",onClick:H,className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors",children:(0,a.jsx)(l.A,{className:(0,o.cn)("large"===x?"icon-heading":"small"===x?"icon-small":"icon-body")})})]}),q&&(0,a.jsxs)("div",{ref:S,className:"absolute z-50 mt-small max-h-60 w-full overflow-auto rounded-default border bg-popover p-small text-popover-foreground shadow-md",children:[z&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"px-body py-small text-small font-semibold text-muted-foreground",children:"Suggestions"}),L.map((e,s)=>(0,a.jsx)("div",{className:(0,o.cn)("flex cursor-pointer items-center rounded-default px-body py-small text-body hover:bg-accent hover:text-accent-foreground",E===s&&"bg-accent text-accent-foreground"),onClick:()=>
1U(e),children:g?.renderSuggestion?g.renderSuggestion(e):(0,a.jsx)("span",{children:e})},`suggestion-${s}`))]}),G&&(0,a.jsxs)(a.Fragment,{children:[z&&(0,a.jsx)("div",{className:"my-small border-t"}),(0,a.jsxs)("div",{className:"px-body py-small text-small font-semibold text-muted-foreground",children:["Results (",R.length,")"]}),R.map((e,s)=>{let t=L.length+s;return(0,a.jsx)("div",{className:(0,o.cn)("flex cursor-pointer items-center rounded-default px-body py-small text-body hover:bg-accent hover:text-accent-foreground",E===t&&"bg-accent text-accent-foreground"),onClick:()=>M(e.item),children:g?.renderResult?g.renderResult(e):(0,a.jsx)("div",{className:"flex flex-col",children:g?.searchFields.map(s=>{let t=String(e.item[s]||"");return(0,a.jsx)("span",{className:"truncate",children:t},s)})})},`result-${s}`)})]}),!G&&!z&&b.trim()&&(0,a.jsxs)("div",{className:"px-body py-small text-body text-muted-foreground",children:['No results found for "',b,'"']})]})]})}},52619:(e,s,t)=>{t.d(s,{g:()=>i});var a=t(68987);t(2315);var n=t(71519),r=t(14326);function i({children:e,padding:s="default",className:t}){let l=r.B[s];return(0,a.jsx)("div",{className:(0,n.cn)("h-full min-h-0 w-full flex flex-col overflow-hidden",l,t),children:e})}},61129:(e,s,t)=>{t.d(s,{iM:()=>a,L$:()=>i,QP:()=>l,tx:()=>o,Nl:()=>r});let a={"sitecore-xm-cloud":[{key:"tokenUrl",label:"Token URL",type:"url",placeholder:"https://auth.sitecorecloud.io/oauth/token"},{key:"apiUrl",label:"API URL (GraphQL Endpoint)",type:"url",placeholder:"https://edge.sitecorecloud.io/api/graphql/v1"},{key:"clientId",label:"Client ID",type:"text",placeholder:"Your Sitecore Client ID"},{key:"clientSecret",label:"Client Secret",type:"password",placeholder:"Your Sitecore Client Secret"},{key:"keyId",label:"Key ID (API Gateway)",type:"password",placeholder:"API Gateway Key ID"},{key:"audience",label:"Audience",type:"text",placeholder:"https://api.sitecorecloud.io"}],prohandel:[{key:"authUrl",label:"Auth URL",type:"url",placeholder:"https://api.prohandel.de/auth"},{key:"baseUrl",label:"API Base URL",type:"url",placeholder:"https://api.prohandel.de/v1"},{key:"apiKey",label:"API Key",type:"password",placeholder:"Your ProHandel API Key"},{key:"secret",label:"API Secret",type:"password",placeholder:"Your ProHandel API Secret"}]},n=new Set(["tokenUrl","apiUrl","authUrl","baseUrl","audience","repositoryRootPath","mediaRootPath","branchTemplateId","parentItemId","anchorRenderingId","anchorNavigationRenderingId"]);function r(e){return!n.has(e)}let i={"sitecore-xm-cloud":["tokenUrl","apiUrl","clientId","clientSecret","keyId","audience"],prohandel:["authUrl","baseUrl","apiKey","secret"]};function l(e,s,t,n){let i={settings:{},clear:[]};for(let l of(a[e]??[]).map(e=>e.key)){if(n[l]){i.clear.push(l);continue}let e=t[l]??"";if(r(l)){""!==e&&(i.settings[l]=e);continue}e!==(s[l]?.value??"")&&(""===e?i.clear.push(l):i.settings[l]=e)}return i}function o(e){return 0===Object.keys(e.settings).length&&0===e.clear.length}},66499:(e,s,t)=>{t.d(s,{k:()=>j});var a=t(68987),n=t(42725),r=t(2315),i=t(44991),l=t(96095),o=t(951);let d={SIGNUP_REJECTED_DISPOSABLE_EMAIL:"system",SIGNUP_REJECTED_BLOCKED_EMAIL:"system",SIGNUP_REJECTED_EXISTING_EMAIL:"system",SIGNUP_REDIRECTED_CONSUMER_OAUTH:"system",SIGNUP_REDIRECTED_SSO_DOMAIN:"system",PASSWORD_SET_BLOCKED_SSO_DOMAIN:"system",TRIAL_REFUSED_POLICY:"system",INVITE_BLOCKED_SEAT_LIMIT:"system",INVITE_BLOCKED_COMPANY_MEMBERSHIP_LIMIT:"system",INVITE_BLOCKED_COMPANY_BLOCKED:"system",CHECKOUT_BLOCKED_SEAT_INCOMPATIBILITY:"system",COMPANY_TRIAL_EXPIRED:"system",COMPANY_PAYMENT_FAILED:"system",AUTO_RECHARGE_FAILED:"system",MEDIA_RETENTION_SWEPT:"system",STUDIO_BIN_PURGED:"system",BLOCK_CAUSE_BACKFILLED:"system",COMPANY_BLOCKED:"operator",COMPANY_SUSPENDED:"operator",COMPANY_UNSUSPENDED:"operator",COMPANY_PROVISIONED:"operator",COMPANY_SUSPENSION_NOTIFIED:"system",CREDIT_GRANT_HELD:"system",COMPANY_DELETED:"operator",COMPANY_DATA_DELETED:"system",DELETION_WARNING_SENT:"system",TRIAL_OVERRIDE_APPLIED:"system",COMPANY_UNLIMITED_CREDITS_EXPIRED:"system",COMPANY_UNLIMITED_CREDITS_CLEARED_ON_UPGRADE:"system",SUPPORT_ACCESS_GRANTED:"operator",SUPPORT_ACCESS_REVOKED:"operator",USER_PASSWORD_RESET_SENT:"operator",USER_VERIFICATION_RESENT:"operator",USER_EMAIL_FORCE_VERIFIED:"operator",USER_MFA_ENROLLED:"user",USER_MFA_UNENROLLED:"user",USER_MFA_CHALLENGE_FAILED:"user",USER_MFA_FORCE_UNENROLLED:"operator",USER_DELET
1ED:"operator",EMAIL_BLOCKLISTED:"operator",EMAIL_UNBLOCKLISTED:"operator",COMPANY_MFA_ENFORCED:"user",COMPANY_MFA_UNENFORCED:"user",USER_MEMBERSHIPS_VIEWED:"operator",CREDITS_GRANTED:"operator",TRIAL_EXTENDED:"operator",TRIAL_STARTED:"operator",TRIAL_ENDED:"operator",TRIAL_UPDATED:"operator",TRIAL_OVERRIDE_UPDATED:"operator",TRIAL_OVERRIDE_DELETED:"operator",SEAT_OVERRIDE_UPDATED:"operator",MONTHLY_CREDIT_OVERRIDE_UPDATED:"operator",COMPANY_AI_POLICY_UPDATED:"operator",GLOBAL_AI_POLICY_UPDATED:"operator",AI_GOVERNOR_POLICY_UPDATED:"operator",UNLIMITED_CREDITS_SET:"operator",UNLIMITED_CREDITS_CLEARED:"operator",ANALYTICS_RECOMPUTED:"operator",ADMIN_RATE_LIMIT_UPDATED:"operator",CRON_CONFIG_UPDATED:"operator",CREDIT_RECONCILE_POLICY_UPDATED:"operator",CONTACT_TEST_MESSAGE_SENT:"operator",LIFECYCLE_SUMMARY_TEST_SENT:"operator",EMAIL_TEST_SENT:"operator",LLM_RUNTIME_TEST_EXECUTED:"operator",COMPOSIO_FAILURE_REPORT_TRIGGERED:"operator",LANGFUSE_FAILURE_REPORT_TRIGGERED:"operator",REFUND_RUN_TRIGGERED:"operator",MEDIA_REFUND_RUN_TRIGGERED:"operator",REFUND_STAMP_CAP_BACKFILL:"operator",INTEGRATION_CREDENTIALS_UPDATED:"operator",INTEGRATION_CREDENTIALS_VIEWED:"operator",PLATFORM_CREDENTIALS_VIEWED:"operator",COMPANY_ADMIN_VIEWED:"operator",INTEGRATION_DEFAULT_UPDATED:"operator",CUSTOM_SUBSCRIPTION_CREATED:"operator",CUSTOM_SUBSCRIPTION_UPDATED:"operator",CUSTOM_SUBSCRIPTION_BULK_UPSERTED:"operator",ENTERPRISE_PLAN_ENDED:"operator",TRIAL_OVERRIDE_CREATED:"operator",TRIAL_CONFIG_UPDATED:"operator",TEAM_DELETED:"user",MEMBER_REMOVED_FROM_COMPANY:"user",MEMBER_LEFT_COMPANY:"user",MEMBER_DEPARTURE_NOTIFIED:"system",USER_ONBOARDING_RESET:"operator",TOUR_CREATED:"operator",TOUR_UPDATED:"operator",TOUR_DELETED:"operator",TOUR_STATUS_CHANGED:"operator",CHECKLIST_CREATED:"operator",CHECKLIST_UPDATED:"operator",CHECKLIST_DELETED:"operator",CHECKLIST_STATUS_CHANGED:"operator",MARKETPLACE_TENANT_SET:"operator",MARKETPLACE_ITEM_CREATED:"operator",MARKETPLACE_ITEM_UPDATED:"operator",MARKETPLACE_ITEM_ARCHIVED:"operator",MARKETPLACE_ITEM_PUBLISHED:"operator",MARKETPLACE_UPDATE_PROPAGATED:"operator",MARKETPLACE_ITEM_PURGED:"operator",MARKETPLACE_ITEM_TAKEN_DOWN:"operator",MARKETPLACE_ITEM_RESTORED:"operator",MARKETPLACE_DRAFT_CANCELLED:"operator",INTERNAL_INTEGRATION_UPDATED:"operator",COMPOSIO_CONNECTION_REFRESHED:"operator",COMPOSIO_CONNECTIONS_FIXED:"operator",COMPLIANCE_LOG_VIEWED:"operator",AI_RUNTIME_RETENTION_PURGED:"system",AI_RUNS_DASHBOARD_VIEWED:"operator",AI_RUN_SWEPT_STALE:"system",SESSION_STARTED:"user",SESSION_IDLE_WARNING:"user",SESSION_IDLE_DISMISSED:"user",SESSION_TIMEOUT_LOGOUT:"user",SESSION_REFRESH_FAILED:"user",LOGIN_FAILED:"user",MODEL_CATALOG_CREATED:"operator",MODEL_CATALOG_UPDATED:"operator",MODEL_CATALOG_DELETED:"operator",MODEL_UPGRADED:"operator",MODEL_RETIRED:"operator",MODEL_WENT_LIVE:"operator",MODEL_TEST_RUN:"operator",MODEL_USAGE_VIEWED:"operator",MODEL_REPLACED:"operator",MODEL_REPLACEMENT_UNDONE:"operator",MODEL_SLOT_UPDATED:"operator",COMPANY_MODELS_PROVISIONED:"operator",API_KEY_REVOKED:"user",WEBHOOK_CONFIG_DEACTIVATED:"user",TOOL_EXPORT_FIELD_VERIFIED:"operator",TOOL_EXPORT_SAMPLE_VIEWED:"operator",RUN_ANALYTICS_EXPORTED:"user"};function c({filters:e,onFiltersChange:s,onExport:t,isExporting:n,exportDisabled:u}){let m=e.stream??"all",h=(0,r.useMemo)(()=>[{value:"",label:"All events"},...("all"===m?Object.keys(d):Object.entries(d).filter(([,e])=>e===m).map(([e])=>e)).sort().map(e=>({value:e,label:e.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}))],[m]);return(0,a.jsx)("div",{className:"flex flex-col gap-body",children:(0,a.jsx)(o.X,{search:{value:e.id??"",onChange:t=>s({...e,id:t.trim()||void 0}),placeholder:"Paste a complete user or company ID..."},filters:[{key:"stream",value:m,options:[{value:"operator",label:"Operator actions"},{value:"user",label:"User & tenant events"},{value:"system",label:"System events"},{value:"all",label:"All streams"}],onChange:t=>
1s({...e,stream:t,code:void 0})},{key:"outcome",value:e.outcome??"all",options:[{value:"all",label:"All outcomes"},{value:"allowed",label:"Allowed"},{value:"blocked",label:"Blocked"}],onChange:t=>s({...e,outcome:t})},{key:"code",value:e.code??"",options:h,onChange:t=>s({...e,code:t||void 0})}],actions:(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[(0,a.jsx)("input",{type:"date",className:"h-body px-body text-small border rounded-default bg-background",value:e.from?.split("T")[0]??"",onChange:t=>s({...e,from:t.target.value?`${t.target.value}T00:00:00.000Z`:void 0})}),(0,a.jsx)("span",{className:"text-small text-muted-foreground",children:"to"}),(0,a.jsx)("input",{type:"date",className:"h-body px-body text-small border rounded-default bg-background",value:e.to?.split("T")[0]??"",onChange:t=>s({...e,to:t.target.value?`${t.target.value}T23:59:59.999Z`:void 0})}),(0,a.jsxs)(i.$,{variant:"outline",size:"small",onClick:t,disabled:n||u,children:[(0,a.jsx)(l.A,{className:"icon-small mr-mini"}),n?"Exporting...":"Export CSV"]})]})})})}var u=t(82247),m=t(55264);function h({event:e}){let s=(0,n.t0)();return(0,a.jsxs)("div",{className:"px-body py-body bg-muted rounded-default",children:[(0,a.jsxs)("div",{className:"flex gap-body text-small text-muted-foreground mb-body",children:[(0,a.jsxs)("span",{children:[s.sourceLabel," ",(0,a.jsx)("strong",{children:"policy"===e.source?"PolicyEvent":"AdminAction"})]}),e.reason&&(0,a.jsxs)("span",{children:[s.reasonLabel," ",(0,a.jsx)("strong",{children:e.reason})]})]}),e.metadata&&Object.keys(e.metadata).length>0&&(0,a.jsx)("pre",{className:"text-small overflow-x-auto whitespace-pre-wrap break-all",children:JSON.stringify(e.metadata,null,2)}),(!e.metadata||0===Object.keys(e.metadata).length)&&(0,a.jsx)("p",{className:"text-small text-muted-foreground",children:s.noAdditionalMetadata})]})}function p(e,s){return e?e.length>s?`${e.slice(0,s)}...`:e:""}function x({events:e}){let s=(0,n.t0)(),t=(0,n.WD)(),[i,l]=(0,r.useState)(new Set);return(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)(u.XI,{children:[(0,a.jsx)(u.A0,{children:(0,a.jsxs)(u.Hj,{children:[(0,a.jsx)(u.nd,{children:"Timestamp"}),(0,a.jsx)(u.nd,{children:"Actor"}),(0,a.jsx)(u.nd,{children:"Event"}),(0,a.jsx)(u.nd,{children:"Target"}),(0,a.jsx)(u.nd,{children:"Outcome"}),(0,a.jsx)(u.nd,{children:"Reason"})]})}),(0,a.jsxs)(u.BF,{children:[e.map(e=>{let n,o=function(e){if(!e)return null;let s=[];return("string"==typeof e.integrationSlug&&s.push(e.integrationSlug),Array.isArray(e.integrationSlugs)&&e.integrationSlugs.length>0&&s.push(e.integrationSlugs.join(", ")),Array.isArray(e.changedKeys)&&e.changedKeys.length>0&&s.push(`changed: ${e.changedKeys.join(", ")}`),Array.isArray(e.clearedKeys)&&e.clearedKeys.length>0&&s.push(`cleared: ${e.clearedKeys.join(", ")}`),0===s.length)?null:p(s.join(" \xb7 "),60)}(e.metadata);return(0,a.jsxs)(r.Fragment,{children:[(0,a.jsxs)(u.Hj,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>{var s;return s=e.id,void l(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},children:[(0,a.jsx)(u.nA,{className:"text-small font-mono whitespace-nowrap",children:(n=new Date(e.timestamp),`${n.toISOString().slice(0,10)} ${n.toISOString().slice(11,16)} UTC`)}),(0,a.jsx)(u.nA,{className:"text-small",children:e.actorName?`${e.actorName} (${e.actorEmail})`:e.actorEmail}),(0,a.jsxs)(u.nA,{children:[(0,a.jsx)(m.E,{variant:"outline",className:"font-mono text-small",children:e.eventCode}),o&&(0,a.jsx)("div",{className:"text-small text-muted-foreground mt-small",children:o})]}),(0,a.jsx)(u.nA,{className:"text-small text-muted-foreground",children:e.targetType&&e.targetId?`${e.targetType}: ${p(e.targetId,12)}`:e.companyId?t("settings.companyLabelColon",{id:p(e.companyId,12)}):e.metadata?.scope==="platform"?"Platform":"—"}),(0,a.jsxs)(u.nA,{children:["allowed"===e.outcome&&(0,a.jsx)(m.E,{variant:"success",children:"Allowed"}),"blocked"===e.outcome&&(0,a.jsx)(m.E,{variant:"destructive",children:"Blocked"}),null===e.outcome&&(0,a.jsx)(m.E,{variant:"secondary",children:s.nA})]}),(0,a.jsx)(u.nA,{className:"text-small text-muted-foreground max-w-[200px] truncate",children:p(e.reason,50)})]}),i.has(e.id)&&(0,a.jsx)(u.Hj,{children:(0,a.jsx)(u.nA,{colSpan:6,className:"p-0 pb-body px-body",children:(0,a.jsx)(h,{event:e})})})]},e.id)}),0===e.length&&(0,a.jsx)(u.Hj,{children:(0,a.jsx)(u.nA,{colSpan:6,className:"text-center text-muted-foreground py-body",children:s.noAuditEventsFoundForThe})})]})]})})}var y=t(36786),g=t(33922);async function f(e,s){let t=new URLSearchParams;s&&t.set("cursor",s),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.id&&t.set("id",e.id),e.company&&t.set("company",e.company),e.code&&t.set("code",e.code),e.outcome&&"all"!==e.outcome&&t.set("outcome",e.outcome),e.stream&&"all"!==e.stream&&t.set("stream",e.stream),t.set("limit","50");let a=await fetch(`/api/admin/compliance/events?${t.toString()}`);if(!a.ok)throw Error(`Failed to fetch compliance events: ${a.statusText}`);return(await a.json()).data}function j(){let e=(0,n.t0)(),[s,t]=(0,r.useState)({outcome:"all",stream:"all"}),{data:l,isLoading:o,isFetchingNextPage:d,hasNextPage:u,fetchNextPage:m}=(0,y.useInfiniteQuery)({queryKey:g.a.compliance.events(s),queryFn:({pageParam:e})=>f(s,e),getNextPageParam:e=>e.nextCursor??void 0,initialPageParam:void 0,staleTime:3e4,gcTime:3e5}),{exportCsv:h,isExporting:p,isCoolingDown:j}=function(e){let[s,t]=(0,r.useState)(!1),[a,n]=(0,r.useState)(0),i=Date.now()<a;return{exportCsv:(0,r.useCallback)(async()=>
1{if(!s&&!i){t(!0);try{let s=new URLSearchParams;e.from&&s.set("from",e.from),e.to&&s.set("to",e.to),e.id&&s.set("id",e.id),e.company&&s.set("company",e.company),e.code&&s.set("code",e.code),e.outcome&&"all"!==e.outcome&&s.set("outcome",e.outcome),e.stream&&"all"!==e.stream&&s.set("stream",e.stream);let t=await fetch(`/api/admin/compliance/events/export?${s.toString()}`);if(429===t.status)return void n(Date.now()+6e4);if(!t.ok)throw Error(`Export failed: ${t.statusText}`);let a=await t.blob(),r=URL.createObjectURL(a),i=document.createElement("a");i.href=r,i.download=t.headers.get("Content-Disposition")?.match(/filename="(.+)"/)?.[1]??"audit-log.csv",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r),n(Date.now()+6e4)}finally{t(!1)}}},[e,s,i]),isExporting:s,isCoolingDown:i}}(s),b=(0,r.useMemo)(()=>l?.pages.flatMap(e=>e.events)??[],[l]);return(0,a.jsxs)("div",{className:"flex flex-col gap-body h-full min-h-0",children:[(0,a.jsx)(c,{filters:s,onFiltersChange:t,onExport:h,isExporting:p,exportDisabled:j}),(0,a.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto",children:o?(0,a.jsx)("div",{className:"flex-center py-body text-muted-foreground",children:e.loadingAuditEvents}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(x,{events:b}),u&&(0,a.jsx)("div",{className:"flex justify-center py-body",children:(0,a.jsx)(i.$,{variant:"outline",size:"small",onClick:()=>m(),disabled:d,children:d?"Loading...":"Load more"})})]})})]})}},86588:(e,s,t)=>{t.d(s,{U:()=>h,q:()=>p});var a=t(68987);t(2315);var n=t(37866),r=t.n(n),i=t(25069),l=t(71519),o=t(30891),d=t(52619),c=t(14326);function u({card:e}){return(0,a.jsx)(i.Card,{variant:"interactive",className:"h-full",children:(0,a.jsx)(i.CardHeader,{children:(0,a.jsxs)("div",{className:"flex items-center gap-body",children:[e.icon&&(0,a.jsx)("div",{className:"flex h-large w-large items-center justify-center rounded-default bg-muted",children:e.icon}),(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsx)(i.CardTitle,{className:"text-body font-medium",children:e.label}),e.description&&(0,a.jsx)(i.CardDescription,{className:"text-small text-muted-foreground",children:e.description})]})]})})})}function m({card:e}){return e.onSelect?(0,a.jsx)("button",{type:"button",onClick:e.onSelect,disabled:e.disabled,className:"h-full w-full text-left disabled:opacity-50",children:(0,a.jsx)(u,{card:e})}):(0,a.jsx)(r(),{href:e.href??"#",children:(0,a.jsx)(u,{card:e})})}function h({groups:e,className:s}){let t=e.filter(e=>!e.hidden).map(e=>({...e,cards:e.cards.filter(e=>!e.hidden)})).filter(e=>e.cards.length>0);return(0,a.jsx)("div",{className:(0,l.cn)("flex flex-col gap-large",s),children:t.map(e=>(0,a.jsxs)("section",{className:"flex flex-col gap-body",children:[e.label&&(0,a.jsx)("h2",{className:"text-small font-medium uppercase tracking-wide text-muted-foreground",children:e.label}),(0,a.jsx)("div",{className:"grid grid-cols-1 gap-large sm:grid-cols-2 lg:grid-cols-3",children:e.cards.map(e=>(0,a.jsx)(m,{card:e},e.id))})]},e.id))})}function p({title:e,description:s,groups:t,headerActions:n,className:r}){return(0,a.jsx)(d.g,{padding:"none",children:(0,a.jsxs)("div",{className:(0,l.cn)("flex-1 min-h-0 flex flex-col overflow-y-auto",r),children:[(0,a.jsx)(o.z,{title:e,description:s,actions:n,variant:s?"expanded":"compact"}),(0,a.jsx)(h,{groups:t,className:c.B.default})]})})}}}]);
2//# chunkId=01a0fc07-1e93-73b2-95d6-50f8b9c62611

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.