PageSourceSearch

https://assets.livid.com/assets/_organizationId-Bi3miNnd.js

js livid.com collected 2026-09-24 18:33:16 UTC 116,232 bytes, 1 lines download raw bytes

1import{k as vt,r as x,a8 as Z,N as C,a as Y,M as _,j as e,X as v,U as Ve,B as u,C as ye,D as Be,h as Ke,z as ve,c7 as yt,c6 as St,c8 as Nt,c9 as js,Q as wt,y as Ct,ca as kt,c5 as Rt,Z as $e,I as _s}from"./main-0mA9R0ha.js";import{M as It,z as Et}from"./index-HLoljSSQ.js";import{a as He}from"./queryKeys-BdF9u15s.js";import{P as Bt,a as Tt}from"./ProBadge-CkPMbEUp.js";import{S as N}from"./spinner-DrCkCm73.js";import{T as At,a as Ft,b as Ye,c as Xe}from"./tabs-DbPupjom.js";import{A as Ot}from"./AdminLayout-BYbG5jag.js";import{i as nt}from"./getAllVideos-DlRWLKJh.js";import{a as Lt}from"./ModerateVideoModal-Bd9mCpzv.js";import{u as Se,a as Ne,C as Bs}from"./zod-DA4AU65J.js";import{i as as}from"./getUsersAdmin-DYpX1Hk4.js";import{i as is}from"./getOrganizationsAdmin-CBgWlsFq.js";import{D as U,g as le,a as V,b as K,c as H,f as W,d as Q,e as J}from"./dialog-Vjf52_l7.js";import{F as te,a as ne,c as oe,d as zt}from"./field-exJSamwr.js";import{I as ue}from"./input-CuZMW64l.js";import{S as Me}from"./square-pen-BACPYxPy.js";import{f as rs}from"./formatDistanceToNow-RdjGMbHF.js";import{a as ze,f as _t}from"./utils-Dluy5TA0.js";import{B as Pt,V as Mt}from"./BandwidthUsageValue-CXvgeqPz.js";import{f as bs}from"./formatMills-CzFYgytX.js";import{g as qt}from"./getNextBillingDate-CsQsR0FY.js";import{B as Ps}from"./pricing-BGJ7c-T0.js";import{A as $t,K as Dt,a as Ms}from"./ApiTokenForm-iZOnoEjh.js";import{B as Pe}from"./badge-jwlJvZgN.js";import{C as we,a as Ce,b as ke,c as Re,d as Ie}from"./card-CPiRAOUA.js";import{T as me,d as he,b as O,e as B,a as xe,c as I}from"./table-C_PKjjKM.js";import{T as at}from"./trash-2-BXd8faTH.js";import{R as Ue}from"./refresh-cw-BnX2h6Pv.js";import{S as os}from"./switch-C2jd_loS.js";import{P as We}from"./progress-BRDjNhEA.js";import{W as it}from"./wrench-w0_vBtFW.js";import{X as ls}from"./x-DMa84inB.js";import{S as Ut}from"./search-BYU42hno.js";import{p as ds}from"./parseISO-CVxaNFUA.js";import{P as vs}from"./play-D3UgTizf.js";import{c as Vt}from"./FirstFramePosterBackfillSection-BF6qLc77.js";import{c as Kt}from"./GcsOriginalSizeBackfillSection-BRC3yjju.js";import{c as rt}from"./createLucideIcon-4vlm1tE4.js";import{T as Ht}from"./triangle-alert-CG4glAKf.js";import{S as ys,a as Ss,b as Ns,c as ws,d as ss}from"./select-CmcA--ZY.js";import{S as qs}from"./shield-check-4c7B44dX.js";import{D as Wt}from"./DataTable-vshTeidr.js";import{I as Cs,a as ks,b as Rs}from"./input-group-BIQQWGkB.js";import{r as Te}from"./renderBytes-DbQij4i5.js";import{L as $s}from"./label-ChVe-3FY.js";import{C as hs}from"./copy-CFz_-tqV.js";import{A as Qt,b as Gt,a as Yt}from"./alert-BnfI6jbS.js";import{E as Xt}from"./external-link-D9IULTHP.js";import"./loader-circle-MNFmGwwL.js";import"./index-CpgbVTNg.js";import"./index-DkQxBBIZ.js";import"./index-Bzj8x_lz.js";import"./index-C4uhXlwe.js";import"./index-C5i3-hSU.js";import"./breadcrumb-CTH0CZLh.js";import"./chevron-right-BOGpebV2.js";import"./radio-group-Cfp4aWkE.js";import"./index-BBS4A968.js";import"./index-DzprJ28Q.js";import"./index-DJEMsTTh.js";import"./index-BHj7PaJO.js";import"./tslib.es6-Bdd1sz-K.js";import"./getRoundingMethod-C2sJiTEy.js";import"./endOfMonth-DEG9FJY8.js";import"./endOfDay-DARdjfaX.js";import"./InfiniteQuerySection-DcgSDtCi.js";import"./index-BgDIeaAD.js";import"./videoListItemColumns-30zQOKfD.js";import"./Patreon-BB8g1DGh.js";import"./dropdown-menu-Drl0vodX.js";import"./index-tGM1HEyG.js";import"./check-uGO9KJbG.js";import"./tooltip-yTBPDVlc.js";import"./index-tuxMpY6F.js";import"./formatDatetime-DVPjOdHL.js";import"./lock-CIr6Cg04.js";import"./users-round-CsdCZYyC.js";import"./ellipsis-3uzo08SA.js";import"./flag-Cl_JbeuT.js";import"./refresh-ccw-DudoR1s4.js";import"./addYears-BQBOFwE3.js";import"./isBefore-zsRLu2Jv.js";import"./CopyWithTooltip-D8ii_jRb.js";import"./calendar-DOPkUG3S.js";import"./isAfter-80q3UWB7.js";import"./chevron-left-CKN3Wr-e.js";import"./chevron-down-C_0fMmDI.js";import"./checkbox-CBwRLvuD.js";import"./popover-BCsdoCCU.js";import"./clock-qvktX5hd.js";import"./hard-drive-BLl-cYV1.js";import"./chevron-up-3WZKr6Gt.js";import"./index-B5AmaivZ.js";import"./index-C8Q6bsOO.js";(function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new s.Error().stack;t&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[t]="34ba8d50-0a39-475f-b1f5-c29c01b2c6bc",s._sentryDebugIdIdentifier="sentry-dbid-34ba8d50-0a39-475f-b1f5-c29c01b2c6bc")}catch{}})();function Zt(s,t){if(s===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in s)return s;if(typeof s=="function")return{shouldBlockFn:async()=>await s(),enableBeforeUnload:!0,withResolver:!1};
1const n=!!(s.condition??!0),r=s.blockerFn;return{shouldBlockFn:async()=>n&&r!==void 0?await r():n,enableBeforeUnload:n,withResolver:r===void 0}}function Jt(s,t){const{shouldBlockFn:n,enableBeforeUnload:r=!0,disabled:i=!1,withResolver:l=!1}=Zt(s),d=vt(),{history:c}=d,[g,o]=x.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return x.useEffect(()=>{const S=async a=>{function b(j){const f=d.parseLocation(j),T=d.getMatchedRoutes(f.pathname);return T.foundRoute===void 0?{routeId:"__notFound__",fullPath:f.pathname,pathname:f.pathname,params:T.routeParams,search:d.options.parseSearch(j.search)}:{routeId:T.foundRoute.id,fullPath:T.foundRoute.fullPath,pathname:f.pathname,params:T.routeParams,search:d.options.parseSearch(j.search)}}const h=b(a.currentLocation),p=b(a.nextLocation);if(h.routeId==="__notFound__"&&p.routeId!=="__notFound__")return!1;const m=await n({action:a.action,current:h,next:p});if(!l)return m;if(!m)return!1;const w=await new Promise(j=>{o({status:"blocked",current:h,next:p,action:a.action,proceed:()=>j(!1),reset:()=>j(!0)})});return o({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),w};return i?void 0:c.block({blockerFn:S,enableBeforeUnload:r})},[n,r,i,l,c,d]),g}const en=[["path",{d:"M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6",key:"g5mvt7"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m14 20 2 2 4-4",key:"15kota"}]],sn=rt("file-check-corner",en);const tn=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],ts=rt("scan-search",tn),nn=({organizationId:s})=>C.get(`/v1/organizations/admin/${s}`).then(({data:t})=>t).catch(t=>{const n=t.response?.status;if(![401,403,404].includes(n))throw t;return null}),an=({organizationId:s})=>Z({gcTime:0,queryKey:He.organizationId({id:s}),queryFn:()=>nn({organizationId:s}),refetchOnReconnect:!1,refetchOnWindowFocus:!1,staleTime:1/0,refetchInterval:300*1e3}),rn=({body:s})=>C.post("/v1/videos/admin/moderate",s).then(({data:t})=>t),on=(s={})=>{const t=Y();return _({mutationFn:rn,onError:s.onError,onSuccess:(n,r)=>{nt({queryClient:t}),s.onSuccess?.(n,r)}})},ln=({onClose:s,organizationId:t,organizationName:n})=>{const r=on({onError:()=>{v.error("Failed to update moderation statuses.")},onSuccess:()=>{v.success("Moderation statuses updated"),s()}}),i=({action:l,policyViolated:d})=>{r.mutate({body:{action:l,organizationId:t,policyViolated:l==="flag"?d:void 0}})};return e.jsx(Lt,{content:e.jsx("div",{className:"flex flex-col gap-1 text-sm break-all bg-card p-3 rounded-lg",children:e.jsxs("span",{className:"font-medium",children:["Organization: ",n]})}),description:'"Approve" the videos if there are no issues or "Flag" to remove access.',isSubmitting:r.isPending,onClose:s,onSubmit:i,title:"Moderate all videos"})},dn=({body:s,organizationId:t})=>C.put(`/v1/organizations/admin/${t}`,s??{}).then(({data:n})=>n),fe=(s={})=>{const t=Y();return _({mutationFn:dn,onError:s.onError,onSuccess:(n,r)=>{is({queryClient:t}),as({queryClient:t}),s.onSuccess?.(n,r)}})},cn=ye({freeTrialEnd:Be()}),Ds=s=>s?`${Ve(s,"yyyy-MM-dd")}T${Ve(s,"HH:mm")}`:"",un=({currentFreeTrialEndDatetime:s,organizationId:t})=>{const[n,r]=x.useState(!1),{control:i,formState:{errors:l},handleSubmit:d,reset:c,watch:g}=Se({defaultValues:{freeTrialEnd:Ds(s)},resolver:Ne(cn)}),o=fe({onError:()=>{v.error("Failed to update Free Trial End.")},onSuccess:()=>{v.success("Free Trial End updated successfully."),r(!1)}});x.useEffect(()=>{n&&c({freeTrialEnd:Ds(s)})},[s,n,c]);const S=({freeTrialEnd:p})=>{o.mutate({body:{freeTrialEndDatetime:new Date(p)},organizationId:t})},a=o.isPending,b=g("freeTrialEnd"),h=new Date(b);return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{variant:"ghost",size:"sm",children:e.jsx(Me,{className:"size-4"})})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:d(S),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Update Free Trial End"}),e.jsx(W,{children:"The date and time in your current time zone."})]}),e.jsx(Bs,{control:i,name:"freeTrialEnd",render:({field:p,fieldState:m})=>e.jsxs(te,{"data-invalid":m.invalid,children:[e.jsx(ne,{htmlFor:"freeTrialEnd",children:"Free trial ends"}),e.jsx(ue,{autoComplete:"off",disabled:a,id:"freeTrialEnd",min:`${Ve(ne
1w Date,"yyyy-MM-dd")}T00:00`,onChange:w=>p.onChange(w.target.value),required:!0,type:"datetime-local",value:p.value}),l.freeTrialEnd?.message&&e.jsx(oe,{children:l.freeTrialEnd.message})]})}),h&&h instanceof Date&&!isNaN(h)&&e.jsx("span",{className:"text-sm",children:`(${rs(h,{addSuffix:!0})})`}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:a,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:a,type:"submit",children:[a&&e.jsx(N,{}),"Confirm"]})]})]})})]})},mn=({organizationId:s})=>C.get(`/v1/organizations/admin/${s}/api-tokens`).then(({data:t})=>t),hn=({organizationId:s})=>Z({queryKey:He.organizationApiTokens({id:s}),queryFn:()=>mn({organizationId:s}),refetchOnReconnect:!1,refetchOnWindowFocus:!1}),xn=({organizationId:s,body:t})=>C.post(`/v1/organizations/admin/${s}/api-tokens`,t).then(({data:n})=>n),pn=()=>{const s=Y();return _({gcTime:0,mutationFn:xn,onSuccess:(t,n)=>s.invalidateQueries({queryKey:He.organizationApiTokens({id:n.organizationId})})})},fn=({organizationId:s,organizationName:t})=>{const[n,r]=x.useState(!1),[i,l]=x.useState(null),[d,c]=x.useState(!1),g=pn(),o=()=>{l(null),g.reset(),r(!1)},S=b=>{if(!b){if(d||g.isPending)return;o();return}r(!0)},a=b=>{c(!0),g.mutate({organizationId:s,body:{name:b.name.trim(),scopes:b.scopes,expiresAt:b.expiresAt?new Date(b.expiresAt).toISOString():null}},{onError:h=>{v.error(h.response?.data?.message??"Unable to generate API token.")},onSuccess:h=>{l(h.token),v.success("API token generated.")},onSettled:()=>{c(!1)}})};return e.jsx($t,{allowShowcaseScope:!0,createdToken:i,isOpen:n,isPending:g.isPending,onDismissSecret:o,onOpenChange:S,onSubmit:a,organizationId:s,organizationName:t})},gn=({organizationId:s,tokenId:t})=>C.delete(`/v1/organizations/admin/${s}/api-tokens/${t}`).then(()=>{}),jn=()=>{const s=Y();return _({mutationFn:gn,onSuccess:(t,n)=>s.invalidateQueries({queryKey:He.organizationApiTokens({id:n.organizationId})})})},bn=({name:s,organizationId:t,tokenId:n,tokenPrefix:r})=>{const[i,l]=x.useState(!1),d=jn(),c=()=>{d.mutate({organizationId:t,tokenId:n},{onError:g=>v.error(g.response?.data?.message??"Unable to revoke API token."),onSuccess:()=>{v.success("API token revoked."),l(!1)}})};return e.jsxs(U,{open:i,onOpenChange:l,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{"aria-label":`Revoke ${s}`,size:"icon",variant:"ghost",children:e.jsx(at,{className:"size-4"})})}),e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsx(H,{children:"Revoke API token?"}),e.jsxs(W,{children:[s," (",r,"…) will stop working immediately. This action cannot be undone."]})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:d.isPending,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:d.isPending,onClick:c,variant:"destructive",children:[d.isPending&&e.jsx(N,{className:"size-4"}),"Revoke token"]})]})]})]})},vn=s=>{switch(s){case Ms.videosWrite:return"Videos: write";case Ms.foldersWrite:return"Folders: write";default:return s}},yn=({token:s})=>{switch(s.status){case"active":return e.jsx(Pe,{children:"Active"});case"expired":return e.jsx(Pe,{variant:"outline",children:"Expired"});case"revoked":return e.jsx(Pe,{variant:"destructive",children:"Revoked"})}},Us=(s,t)=>s?ze({date:s}):t,Sn=({organizationId:s,organizationName:t})=>{const n=hn({organizationId:s});return e.jsx("section",{className:"py-4",children:e.jsxs(we,{children:[e.jsxs(Ce,{className:"flex flex-row items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ke,{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"size-4"}),"API tokens"]}),e.jsx(Re,{children:"Long-lived integration credentials restricted to this organization. Token secrets are shown only once."})]}),e.jsx(fn,{organizationId:s,organizationName:t})]}),e.jsxs(Ie,{children:[n.isPending&&e.jsx("div",{className:"flex min-h-32 items-center justify-center",children:e.jsx(N,{})}),n.isError&&e.jsxs("div",{className:"flex min-h-32 flex-col items-center justify-center gap-3 rounded-md border border-destructive/40 bg-destructive/5 p-6 text-center",children:[e.jsx("p",{className:"text-sm",children:"Unable to load API tokens."}),e.jsxs(u,{disabled:n.isFetching,onClick:()=>{n.refetch()},size:"sm",variant:"outline",children:[n.isFetching?e.jsx(N,{className:"size-4"}):e.jsx(Ue,{className:"size-4"}),"Retry"]})]}),n.isSuccess&&n.data.tokens.length===0&&e.jsxs("div",{className:"flex min-h-32 flex-col items-center justify-center gap-1 rounded-md border border-dashed p-6 text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:"No API tokens yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate one when an external integration needs access."})]}),n.isSuccess&&n.data.tokens.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Token"}),e.jsx(B,{children:"Scopes"}),e.jsx(B,{children:"Created by"}),e.jsx(B,{children:"Created"}),e.jsx(B,{children:"Expires"}),e.jsx(B,{children:"Last used"}),e.jsx(B,{children:"Status"}),e.jsx(B,{className:"w-12"})]})}),e.jsx(xe,{children:n.data.tokens.map(r=>e.jsxs(O,{children:[e.jsx(I,{children:e.jsxs("div",{className:"flex min-w-40 flex-col gap-0.5",children:[e.jsx("span",{className:"font-medium",children:r.name}),e.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[r.tokenPrefix,"…"]})]})}),e.jsx(I,{children:e.jsx("div",{className:"flex min-w-32 flex-wrap gap-1",children:r.scopes.map(i=>e.jsx(Pe,{variant:"secondary",children:vn(i)},i))})}),e.jsx(I,{children:e.jsxs("div",{className:"flex min-w-44 flex-col gap-0.5",children:[e.jsx("span",{children:r.createdBy.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r.createdBy.email})]})}),e.jsx(I,{className:"min-w-48 text-xs",children:ze({date:r.createdAt})}),e.jsx(I,{className:"min-w-48 text-xs",children:Us(r.expiresAt,"Never")}),e.jsx(I,{className:"min-w-48 text-xs",children:Us(r.lastUsedAt,"Never used")}),e.jsx(I,{children:e.jsx(yn,{token:r})}),e.jsx(I,{children:r.status==="active"&&e.jsx(bn,{name:r.name,organizationId:s,tokenId:r.id,tokenPrefix:r.tokenPrefix})})]},r.id))})]})})]})]})})},Nn=({body:s})=>C.post("/v1/billing/admin/appsumo-license",s).then(({data:t})=>t),wn=(s={})=>{const t=Y();return _({mutationFn:Nn,onError:s.onError,onSuccess:()=>{is({queryClient:t}),as({queryClient:t}),s.onSuccess?.()}})},Cn=ye({licenseKey:Be().trim().min(1,"Required")}),kn=({organizationId:s})=>{const{t}
1=Ke("common"),[n,r]=x.useState(!1),{formState:{errors:i},handleSubmit:l,register:d}=Se({resolver:Ne(Cn)}),c=wn({onError:S=>v.error(S.response?.data?.message||t("error.unknown")),onSuccess:()=>{v.success("AppSumo License applied successfully"),r(!1)}}),g=({licenseKey:S})=>{c.mutate({body:{licenseKey:S,organizationId:s}})},o=c.isPending;return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{size:"sm",variant:"outline",children:"Apply AppSumo License"})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:l(g),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Apply AppSumo License"}),e.jsx(W,{children:"This will overwrite our database with data from AppSumo."})]}),e.jsx("span",{className:"text-sm",children:"* This cannot be undone."}),e.jsx("span",{className:"text-sm",children:"* Any custom limits or seats must be reset separately."}),e.jsxs(te,{"data-invalid":!!i.licenseKey?.message,children:[e.jsx(ne,{htmlFor:"licenseKey",children:"License Key"}),e.jsx(ue,{...d("licenseKey"),autoComplete:"off",autoFocus:!0,disabled:o,id:"licenseKey",required:!0,type:"text"}),i.licenseKey?.message&&e.jsx(oe,{children:i.licenseKey.message})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:o,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:o,type:"submit",children:[o&&e.jsx(N,{}),"Confirm"]})]})]})})]})},Rn=({currentDefaultGenerateTranscripts:s,organizationId:t})=>{const n=fe({onError:()=>{v.error("Failed to update auto-caption setting.")},onSuccess:(r,i)=>{v.success(i.body.defaultGenerateTranscripts?"Auto-captions enabled for future uploads.":"Auto-captions disabled.")}});return e.jsx(os,{"aria-label":"Auto-generate captions for future uploads",checked:s,disabled:n.isPending,onCheckedChange:r=>n.mutate({body:{defaultGenerateTranscripts:r},organizationId:t})})},In=async s=>{const{data:t}=await C.delete(`/v1/admin/caption-backfill/${s}`);return t},En=()=>_({mutationFn:In}),ot="caption-backfill",Bn=async s=>{try{const{data:t}=await C.get(`/v1/admin/caption-backfill/${s}`);return t}catch(t){if(t.response?.status===404)return null;throw t}},Tn=s=>Z({queryKey:[ot,s],queryFn:()=>Bn(s),enabled:!!s,refetchInterval:t=>{const n=t.state.data;return n===null?!1:!n||n.state==="scanning"?2e3:n.dryRun?!1:n.progress.completed+n.progress.failed<n.candidateCount?5e3:!1}}),An="caption-backfill-latest",Fn=async s=>{const{data:t}=await C.get(`/v1/admin/caption-backfill/org/${s}`);return t},On=s=>Z({queryKey:[An,s],queryFn:()=>Fn(s)}),Ln=async s=>{const{data:t}=await C.post("/v1/admin/caption-backfill",{organizationId:s.organizationId,dryRun:s.dryRun});return t},zn=()=>_({mutationFn:Ln}),_n={generate:"Generate (no captions)",replace:"Replace (existing auto captions)",skip_no_asset:"Skipped: no video asset",skip_not_encoded:"Skipped: not encoded",skip_in_flight:"Skipped: transcription in flight",skip_uploaded_only:"Skipped: uploaded captions only"},Pn=["generate","replace","skip_uploaded_only","skip_in_flight","skip_not_encoded","skip_no_asset"],xs=({batch:s})=>e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Classification"}),e.jsx(B,{className:"text-right",children:"Videos"})]})}),e.jsx(xe,{children:Pn.map(t=>e.jsxs(O,{children:[e.jsx(I,{children:_n[t]}),e.jsx(I,{className:"text-right font-mono",children:s.counts[t]??0})]},t))})]})}),Mn=({batch:s})=>e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:s.candidateCount})," ","video(s) would be transcribed — ~",s.estimate.minutes," min of audio, est. $",s.estimate.estimatedUsd.toFixed(2)," (AssemblyAI)"]}),qn=({organizationId:s})=>{const[t,n]=x.useState(null),[r,i]=x.useState(!1),l=Y(),d=On(s),c=t??d.data?.batchId??null,g=Tn(c),o=zn(),S=En(),a=g.data??null,b=a?a.progress.completed+a.progress.failed:0,h=d.isPending||!!c&&g.isPending,p=!h&&(!c||a===null),m=!!a&&a.dryRun&&a.state==="scanning",w=!!a&&a.dryRun&&a.state==="done",j=!!a&&!a.dryRun&&a.state==="scanning",f=!!a&&!a.dryRun&&a.state==="done"&&b<a.candidateCount,T=!!a&&!a.dryRun&&a.state==="done"&&b>=a.candidateCount,F=!!a&&a.state==="cancelled",L=!!a&&a.state==="failed",R=j||f,G=!!a&&!a.dryRun&&(F||L)&&b<a.candidateCount,ee=a&&a.candidateCount>0?Math.round(b/a.candidateCount*100):0,X=$=>{o.mutate({organizationId:s,dryRun:$},{onSuccess:ge=>{n(ge.batchId),i(!1),v.success($?"Dry run started":"Caption backfill started")},onError:()=>v.error($?"Failed to start dry run":"Failed to start backfill")}
1)},q=()=>{c&&S.mutate(c,{onSuccess:()=>{l.invalidateQueries({queryKey:[ot,c]}),v.success("Backfill cancelled — already-enqueued transcriptions finish normally")},onError:()=>v.error("Failed to cancel backfill")})},E=$=>e.jsxs(u,{disabled:o.isPending,onClick:()=>X(!0),variant:p?"default":"ghost",children:[o.isPending?e.jsx(N,{className:"size-4 mr-2"}):e.jsx(Ut,{className:"w-4 h-4 mr-2"}),$]});return e.jsxs("section",{className:"flex flex-col w-full gap-4",children:[e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsxs(ke,{className:"flex items-center gap-2",children:[(m||R||G)&&e.jsx(N,{className:"size-4"}),"Caption backfill"]}),e.jsx(Re,{children:"Regenerate AssemblyAI captions for this organization's videos — videos without captions get new ones, existing auto captions are replaced, and user-uploaded captions are never touched. Always preview with a dry run first: replacing captions re-bills AssemblyAI."})]}),e.jsxs(Ie,{className:"space-y-4",children:[h&&e.jsx(N,{className:"size-4"}),p&&e.jsx("div",{children:E("Preview (dry run)")}),m&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Scanning… page ",a.pageIndex]}),e.jsx(xs,{batch:a})]}),w&&e.jsxs(e.Fragment,{children:[e.jsx(xs,{batch:a}),e.jsx(Mn,{batch:a}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(u,{disabled:o.isPending||a.candidateCount===0,onClick:()=>i(!0),children:[e.jsx(it,{className:"w-4 h-4 mr-2"}),"Run backfill (",a.candidateCount,")"]}),E("Start new dry run")]})]}),j&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Scanning and enqueuing… page ",a.pageIndex," —"," ",a.candidateCount," video(s) enqueued so far"]}),e.jsx(xs,{batch:a})]}),T&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm",children:["Backfill complete —"," ",e.jsx("span",{className:"font-medium",children:a.progress.completed})," ","transcribed",a.progress.failed>0&&e.jsxs("span",{className:"text-red-600",children:[", ",a.progress.failed," failed"]}),"."]}),e.jsx("div",{children:E("Start new dry run")})]}),F&&e.jsx("div",{className:"p-3 bg-amber-500/10 rounded text-sm text-amber-600",children:"Cancelled — already-enqueued transcriptions finish normally."}),L&&e.jsxs("div",{className:"p-3 bg-red-500/10 rounded text-sm text-red-600",children:["Backfill failed: ",a.error??"Unknown error"]}),(f||G)&&e.jsxs("div",{className:"space-y-2 max-w-xl",children:[e.jsx(We,{className:"h-2",value:ee}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.progress.completed," completed ·"," ",a.progress.processing," processing",a.progress.failed>0&&e.jsxs("span",{className:"text-red-600",children:[" ","· ",a.progress.failed," failed"]})," ","/ ",a.candidateCount," enqueued"]})]}),(F||L)&&!G&&e.jsx("div",{children:E("Start new dry run")}),R&&e.jsxs(u,{disabled:S.isPending,onClick:q,size:"sm",variant:"outline",children:[S.isPending?e.jsx(N,{className:"size-4 mr-2"}):e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Cancel backfill"]})]})]}),e.jsx(U,{open:r,onOpenChange:i,children:e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsxs(H,{
1children:["Backfill ",a?.candidateCount??0," video(s)?"]}),e.jsx(W,{children:a?`${a.counts.generate} video(s) get new captions and ${a.counts.replace} have their auto captions replaced (~${a.estimate.minutes} min of audio, est. $${a.estimate.estimatedUsd.toFixed(2)} on AssemblyAI). Skipped videos are excluded. User-uploaded captions are never touched. Based on a dry run started ${rs(ds(a.createdAt),{addSuffix:!0})} — the live run re-scans the organization, so actual counts may differ.`:""})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:o.isPending,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:o.isPending,onClick:()=>X(!1),children:[o.isPending&&e.jsx(N,{className:"size-4 mr-2"}),"Run backfill (",a?.candidateCount??0,")"]})]})]})})]})},$n=({directLinksOverrideEnabled:s,organizationId:t})=>{const n=fe();return e.jsx(os,{"aria-label":"Enable direct links regardless of plan",checked:s,disabled:n.isPending,onCheckedChange:r=>n.mutate({body:{directLinksOverrideEnabled:r},organizationId:t})})},Dn=async s=>{const{data:t}=await C.delete(`/v1/admin/external-source-repair/${s}`);return t},Un=()=>_({mutationFn:Dn}),lt="admin-external-source-repair",Vn=async s=>{try{const{data:t}=await C.get(`/v1/admin/external-source-repair/${s}`);return t}catch(t){if(t.response?.status===404)return null;throw t}},Kn=s=>Z({queryKey:[lt,s],queryFn:()=>Vn(s),enabled:!!s,refetchInterval:t=>{const n=t.state.data;return n===null?!1:n?n.state==="starting"||n.state==="running"||n.progress.pending+n.progress.encoding>0?15e3:!1:5e3}}),Is="admin-external-source-repair-latest",Hn=async s=>{const{data:t}=await C.get(`/v1/admin/external-source-repair/org/${s}`);return t},Wn=s=>Z({queryKey:[Is,s],queryFn:()=>Hn(s)}),Qn=async s=>{const{data:t}=await C.post("/v1/admin/external-source-repair",{organizationId:s});return t},Gn=()=>_({mutationFn:Qn}),Yn=["queued","skipped","retry","error"],dt={queued:"Repair staged",skipped:"Skipped after fresh validation",retry:"Needs retry",error:"Error"},Vs=s=>s?.response?.data,Xn=({batch:s})=>e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Outcome"}),e.jsx(B,{className:"text-right",children:"Videos"})]})}),e.jsx(xe,{children:Yn.map(t=>e.jsxs(O,{children:[e.jsx(I,{children:dt[t]}),e.jsx(I,{className:"text-right font-mono",children:s.counts[t]??0})]},t))})]})}),Zn=({organizationId:s})=>{const[t,n]=x.useState(null),[r,i]=x.useState(!1),l=Y(),d=Wn(s),c=t??d.data?.batchId??null,g=Kn(c),o=Gn(),S=Un(),a=g.data??null,b=d.isPending||!!c&&g.isPending,h=!b&&(!c||a===null),p=!!a&&(a.state==="starting"||a.state==="running"),m=p&&!a.cancelRequested,w=!!a&&a.progress.pending+a.progress.encoding>0,j=a?a.progress.completed+a.progress.failed+a.progress.missing:0,f=a&&a.stagedCount>0?Math.round(j/a.stagedCount*100):0,T=()=>{o.mutate(s,{onSuccess:R=>{n(R.batchId),i(!1),l.invalidateQueries({queryKey:[Is,s]}),v.success(R.activationPending?"Repair accepted — activation confirmation is pending; monitor this batch":`Repair started — up to ${R.batchSize} videos every ${Math.round(R.delayMs/6e4)} minutes`)},onError:R=>{i(!1);const G=Vs(R),ee=G?.activeBatchId??G?.submissionWindowBatchId;ee&&n(ee),v.error(G?.message??"Failed to start external-source repair")}})},F=()=>{c&&S.mutate(c,{onSuccess:()=>{l.invalidateQueries({queryKey:[lt,c]}),l.invalidateQueries({queryKey:[Is,s]}),v.success("Repair cancelled — no more batches will be staged; queued encodes continue normally")},onError:R=>v.error(Vs(R)?.message??"Failed to cancel external-source repair")})},L=R=>e.jsxs(u,{disabled:o.isPending,onClick:()=>i(!0),variant:h?"default":"outline",children:[o.isPending?e.jsx(N,{className:"size-4"}):e.jsx(vs,{className:"size-4"}),R]});return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsx(ke,{children:"External-source highest-rendition repair"}),e.jsx(Re,{children:"Revalidates this organization's Vimeo source uploads and re-encodes only a truncated highest rendition, or a healthy highest rendition missing from its master. The controller stages at most 50 repairs every ten minutes on the background encode lane."})]}),e.jsxs(Ie,{className:"space-y-4",children:[b&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(N,{className:"size-4"}),"Checking for a repair sweep…"]}),h&&L("Start repair sweep"),a&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.jsxs("span",{className:"font-medium",children:["Repair · ",a.state]}),e.jsxs("span",{className:"text-muted-foreground",children:["tick ",a.tick," · ",a.stagedCount," staged ·"," ",a.scanned," scanned"]}),a.nextBatchAt&&e.jsxs("span",{className:"text-muted-foreground",children:["next batch"," ",rs(new Date(a.nextBatchAt),{addSuffix:!0})]})]}),a.state==="starting"&&e.jsx("p",{className:"text-sm text-amber-600",children:"The first controller job is awaiting durable activation confirmation."}),a.state==="cancelled"&&e.jsx("p",{className:"text-sm text-amber-600",children:"Cancelled. Already-staged encodes continue normally, and a restart cannot bypass the current ten-minute c
1ooldown."}),a.error&&e.jsx("p",{className:"text-sm text-destructive",children:a.error}),a.stagedCount>0&&e.jsxs("div",{className:"space-y-1.5 max-w-xl",children:[e.jsx(We,{value:f}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.progress.completed," completed ·"," ",a.progress.pending," pending · ",a.progress.encoding," ","encoding · ",a.progress.failed," failed ·"," ",a.progress.missing," missing — of ",a.stagedCount," ","staged"]})]}),e.jsx(Xn,{batch:a}),a.attentionOutcomes.length>0&&e.jsxs("div",{className:"space-y-1.5 max-w-3xl",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Needs attention (",a.attentionOutcomes.length,")"]}),a.attentionOutcomes.slice(0,10).map(R=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:R.videoId})," —"," ",R.detail??dt[R.result]]},`${R.tick}:${R.videoId}`)),a.attentionOutcomes.length>10&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.attentionOutcomes.length-10," more in the status response"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[m&&e.jsxs(u,{disabled:S.isPending,onClick:F,variant:"outline",children:[S.isPending?e.jsx(N,{className:"size-4"}):e.jsx(ls,{className:"size-4"}),"Cancel repair sweep"]}),!p&&!w&&L("Start another repair sweep")]})]})]})]}),e.jsx(U,{open:r,onOpenChange:i,children:e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsx(H,{children:"Start organization repair sweep?"}),e.jsx(W,{children:"This revalidates the organization snapshot and stages only each impacted highest rendition, at most 50 every ten minutes. Customer uploads keep queue priority. Cancelling later stops new batches, but already-staged encodes will still finish."})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:o.isPending,children:e.jsx(u,{variant:"ghost",children:"Keep idle"})}),e.jsxs(u,{disabled:o.isPending,onClick:T,children:[o.isPending&&e.jsx(N,{className:"size-4"}),"Start repair sweep"]})]})]})})]})},Jn=({ga4IntegrationEnabled:s,organizationId:t})=>{const n=fe();return e.jsx(os,{"aria-label":"Enable Google Analytics integration",checked:s,disabled:n.isPending,onCheckedChange:r=>n.mutate({body:{ga4IntegrationEnabled:r},organizationId:t})})},ea=async s=>{const{data:t}=await C.delete(`/v1/admin/hdr-backfill/${s}`);return t},sa=()=>_({mutationFn:ea}),ct="admin-hdr-backfill",ta=async s=>{try{const{data:t}=await C.get(`/v1/admin/hdr-backfill/${s}`);return t}catch(t){if(t.response?.status===404)return null;throw t}},na=s=>Z({queryKey:[ct,s],queryFn:()=>ta(s),enabled:!!s,refetchInterval:t=>{const n=t.state.data;return n===null?!1:n?n.state==="running"||n.progress.completed+n.progress.failed<n.stagedCount?15e3:!1:5e3}}),aa="admin-hdr-backfill-latest",ia=async s=>{const{data:t}=await C.get(`/v1/admin/hdr-backfill/org/${s}`);return t},ra=s=>Z({queryKey:[aa,s],queryFn:()=>ia(s)}),oa=async s=>{const{data:t}=await C.post("/v1/admin/hdr-backfill",{organizationId:s.organizationId});return t},la=()=>_({mutationFn:oa}),da={queued:"Repair staged",error:"Errored",skip_already_repaired:"Skipped: already repaired",skip_encoded_after_fix:"Skipped: encoded after the fix",skip_encode_in_flight:"Skipped: encode in flight",skip_no_original_master:"Skipped: no original master",skip_not_repairable:"Skipped: not repairable"},ca=["queued","error","skip_already_repaired","skip_encoded_after_fix","skip_encode_in_flight","skip_no_original_master","skip_not_repairable"],ua=({batch:s})=>e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Outcome"}),e.jsx(B,{className:"text-right",children:"Videos"})]})}),e.jsx(xe,{children:ca.filter(t=>(s.counts[t]??0)>0).map(t=>e.jsxs(O,{children:[e.jsx(I,{children:da[t]}),e.jsx(I,{className:"text-right font-mono",children:s.counts[t]??0})]},t))})]})}),ma=({organizationId:s})=>{const[t,n]=x.useState(null),r=Y(),i=ra(s),l=t??i.data?.batchId??null,d=na(l),c=la(),g=sa(),o=d.data??null,S=o?o.progress.completed+o.progress.failed:0,a=i.isPending||!!l&&d.isPending,b=!a&&(!l||o===null),h=!!o&&o.state==="running",p=o&&o.stagedCount>0?Math.round(S/o.stagedCount*100):0,m=()=>{c.mutate({organizationId:s},{onSuccess:j=>{n(j.batchId);const f=Math.round(j.pageSize*36e5/j.delayMs);v.success(`Backfill started — repairing ~${f} videos/hour`)},onError:j=>v.error(j?.response?.data?.message??"Failed to start backfill")}
1)},w=()=>{l&&g.mutate(l,{onSuccess:()=>{r.invalidateQueries({queryKey:[ct,l]}),v.success("Backfill cancelled — already-staged re-encodes finish and promote normally")},onError:()=>v.error("Failed to cancel backfill")})};return e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsx(ke,{children:"HDR colour backfill"}),e.jsx(Re,{children:"Stages a zero-downtime HDR→SDR re-encode for every video the census counts as needing repair, a few at a time so customer uploads always go first. Videos keep playing throughout; each is swapped only when its replacement finishes."})]}),e.jsxs(Ie,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(N,{className:"size-4"}),"Checking for a running backfill…"]}),b&&e.jsxs(u,{disabled:c.isPending,onClick:m,children:[e.jsx(vs,{className:"size-4"}),"Start backfill"]}),o&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.jsxs("span",{className:"font-medium",children:["Backfill · ",o.state]}),e.jsxs("span",{className:"text-muted-foreground",children:["tick ",o.tick," · ",o.stagedCount," staged · ",o.scanned," ","scanned"]}),o.nextBatchAt&&e.jsxs("span",{className:"text-muted-foreground",children:["next tick"," ",rs(new Date(o.nextBatchAt),{addSuffix:!0})]})]}),o.error&&e.jsx("p",{className:"text-sm text-destructive",children:o.error}),o.stagedCount>0&&e.jsxs("div",{className:"space-y-1.5 max-w-xl",children:[e.jsx(We,{value:p}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.progress.completed," finished ·"," ",o.progress.encoding," encoding · ",o.progress.failed," ","failed — of ",o.stagedCount," staged"]})]}),e.jsx(ua,{batch:o}),o.outcomes.filter(j=>j.detail).length>0&&e.jsx("div",{className:"space-y-1.5 max-w-3xl",children:o.outcomes.filter(j=>j.detail).slice(0,10).map(j=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:j.videoId})," —"," ",j.detail]},j.videoId))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[h&&!o.cancelRequested&&e.jsxs(u,{disabled:g.isPending,onClick:w,variant:"outline",children:[e.jsx(ls,{className:"size-4"}),"Cancel"]}),!h&&e.jsxs(u,{disabled:c.isPending,onClick:m,variant:"outline",children:[e.jsx(vs,{className:"size-4"}),"Start another run"]})]})]})]})]})},ha=async s=>{const{data:t}=await C.get(`/v1/admin/hdr-census/org/${s}`);return t},xa="admin-hdr-census",pa=({organizationId:s,enabled:t})=>Z({enabled:t,queryKey:[xa,s],queryFn:()=>ha(s),staleTime:0,gcTime:0}),_e=s=>Ve(ds(s),"d MMM yyyy"),fa=s=>Ve(ds(s),"d MMM yyyy 'at' HH:mm"),ga=s=>[{key:"sdr-tagged",label:"Mislabelled SDR — washed out everywhere",hint:`BT.709 tags over unconverted HDR pixels: desaturated and flat on every device — encoded ${_e(s.cutoffs.bugIntroducedAt)} onwards`,count:s.needsRepair.sdrTagged,emphasis:!0},{key:"hdr-tagged",label:"Tagged HDR — bright on HDR displays",hint:`The source's own HDR tags over the same unconverted 8-bit pixels: self-consistent, so less visible, but renders bright on an HDR display and bands — encoded before ${_e(s.cutoffs.bugIntroducedAt)}`,count:s.needsRepair.hdrTagged,emphasis:!0},{key:"encoded-after-fix",label:"Excluded: encoded after the fix",hint:"Already converted by the encoder. Most carry no marker to prove it, which is why the cutoff exists",count:s.excluded.encodedAfterFix},{key:"already-repaired",label:"Excluded: already repaired",hint:"Marked as converted. Converting again would tone-map a second time",count:s.excluded.alreadyRepaired},{key:"encode-in-flight",label:"Excluded: encode in flight",hint:"An encode is running now — re-run the census once it settles",count:s.excluded.encodeInFlight},{key:"no-original-master",label:"No original master",hint:"Only a lossy rendition to convert from. Expected to be zero — investigate if it is not",count:s.anomalies.noOriginalMaster,warn:s.anomalies.noOriginalMaster>0},{key:"not-repairable",label:"Not repairable",hint:"Nothing safe to convert from — see the reasons below",count:s.anomalies.notRepairable}],ja=({census:s})=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums",children:s.needsRepair.total}),e.jsxs("span",{className:"text-muted-foreground",children:["video",s.needsRepair.total===1?"":"s"," need a colour repair, of ",s.hdrSourceVideos," HDR-source and ",s.totalVideos," total"]})]}),s.needsRepair.earliestEncodedAt&&s.needsRepair.latestEncodedAt&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Encoded between ",_e(s.needsRepair.earliestEncodedAt)," and"," ",_e(s.needsRepair.latestEncodedAt),". Anything encoded after ",fa(s.cutoffs.fixDeployedAt)," is excluded — the encoder was already convert
1ing by then."]}),e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-3xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Bucket"}),e.jsx(B,{className:"text-right",children:"Videos"})]})}),e.jsx(xe,{children:ga(s).map(t=>e.jsxs(O,{children:[e.jsxs(I,{children:[e.jsxs("div",{className:t.emphasis?"font-medium":"text-muted-foreground",children:[t.label,t.warn&&e.jsx(Ht,{className:"inline size-3.5 ml-1.5 text-amber-600 align-[-2px]"})]}),t.hint&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t.hint})]}),e.jsx(I,{className:`text-right font-mono align-top ${t.emphasis?"font-semibold":""}`,children:t.count})]},t.key))})]})}),s.videosWithoutProvenance>0&&e.jsxs("p",{className:"text-sm text-muted-foreground max-w-3xl",children:[e.jsxs("span",{className:"font-medium text-foreground",children:[s.videosWithoutProvenance," videos are not classified here."]})," ","Their current asset predates source-metadata recording (",_e(s.cutoffs.provenanceRecordedFrom),"), so there is no provenance to read. They are all pre-bug encodes, which makes the mislabelled-SDR count above exact and the tagged-HDR count a lower bound. Identifying them would need a rendition-by-rendition scan."]}),s.notRepairableReasons.length>0&&e.jsxs("div",{className:"space-y-1.5 max-w-3xl",children:[e.jsx("p",{className:"text-sm font-medium",children:"Why videos are not repairable"}),s.notRepairableReasons.map(({reason:t,count:n})=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-mono",children:[n,"×"]})," ",t]},t))]}),s.sample.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Sample of videos needing repair (",s.sample.length," of"," ",s.needsRepair.total,")"]}),e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-3xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Video"}),e.jsx(B,{children:"Cohort"}),e.jsx(B,{children:"Encoded"})]})}),e.jsx(xe,{children:s.sample.map(t=>e.jsxs(O,{children:[e.jsx(I,{className:"max-w-xs truncate",children:e.jsx(u,{asChild:!0,className:"px-0 h-auto",variant:"link",children:e.jsx(ve,{params:{videoId:t.videoId},to:"/admin/videos/$videoId",children:t.title||t.videoId})})}),e.jsx(I,{children:e.jsx(Pe,{variant:"outline",children:t.cohort==="sdr-tagged"?"Mislabelled SDR":"Tagged HDR"})}),e.jsx(I,{className:"text-muted-foreground",children:_e(t.encodedAt)})]},t.videoId))})]})})]}),s.anomalySample.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Anomalies"}),e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-3xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Video"}),e.jsx(B,{children:"Bucket"})]})}),e.jsx(xe,{children:s.anomalySample.map(t=>e.jsxs(O,{children:[e.jsx(I,{className:"max-w-xs truncate",children:e.jsx(u,{asChild:!0,className:"px-0 h-auto",variant:"link",children:e.jsx(ve,{params:{videoId:t.videoId},to:"/admin/videos/$videoId",children:t.title||t.videoId})})}),e.jsx(I,{className:"text-muted-foreground text-xs",children:t.bucket==="no-original-master"?"No original master":t.reason??"Not repairable"})]},t.videoId))})]})})]})]}),ba=({organizationId:s})=>{const[t,n]=x.useState(!1),r=pa({organizationId:s,enabled:t});return e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsx(ke,{children:"HDR colour census"}),e.jsx(Re,{children:"How many of this org's videos still need converting from HDR to SDR, split by how visible the fault is. Both cohorts need repair. Counts only — nothing is queued."})]}),e.jsxs(Ie,{className:"space-y-4",children:[!t&&e.jsxs(u,{onClick:()=>n(!0),variant:"outline",children:[e.jsx(ts,{className:"size-4"}),"Run census"]}),t&&r.isPending&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(N,{className:"size-4"}),"Counting HDR-source videos…"]}),r.isError&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Could not build the census."}),e.jsx(u,{onClick:()=>{r.refetch()},variant:"outline",children:"Try again"})]}),r.data&&e.jsxs(e.Fragment,{children:[e.jsx(ja,{census:r.data}),e.jsxs(u,{disabled:r.isFetching,onClick:()=>{r.refetch()},variant:"outline",children:[r.isFetching?e.jsx(N,{className:"size-4"}):e.jsx(ts,{className:"size-4"}),"Re-run census"]})]})]})]})},ut=async s=>{const{data:t}=await C.get(`/v1/admin/master-preview-scan/org/${s.organizationId}`,{params:{limit:s.limit,verifyCodecs:s.verifyCodecs?"true":"false",...s.cursor?{cursor:s.cursor}:{},...s.snapshotAt?{snapshotAt:s.snapshotAt}:{}},signal:s.signal});return t},ps=(s,t)=>{const n={...s};for(const[r,i]of Object.entries(t))n[r]=(n[r]??0)+i;return n},Ze=(s,t,n)=>{const r=new Map(s.map(i=>[n(i),{...i}]));for(const i of t){const l=n(i),d=r.get(l);r.set(l,d?{...d,count:d.count+i.count}:i)}return[...r.values()].sort((i,l)=>l.count-i.count)},De=(s=[],t=[])=>{const n=new Map(s.map(r=>[r.videoId,r]));for(const r of t)n.set(r.videoId,r);return[...n.values()]},va=(s,t)=>{if(!s)return{...t,requested:t.eligibleVideos,timedOut:t.nextCursor===null?!1:t.timedOut,truncated:t.nextCursor!==null};if(s.organizationId!==t.organizationId)throw new Error("The full scan returned data for a different organization");if(s.snapshotAt!==t.snapshotAt)throw new Error("The full scan cohort changed between batches");const n=()=>s.validation?t.validation?{renderedWithErrors:s.validation.renderedWithErrors+t.validation.renderedWithErrors,liveWithErrors:s.validation.liveWithErrors+t.validation.liveWithErrors,renderedProblems:Ze(s.validation.renderedProblems,t.validation.renderedProblems,d=>`${d.severity}:${d.code}`),liveProblems:Ze(s.validation.liveProblems,t.validation.liveProblems,d=>`${d.severity}:${d.code}`)}:s.validation:t.validation,r=()=>{if(!s.codecs&&!t.codecs)return null;if(!s.codecs||!t.codecs)throw new Error("Codec verification changed between full-scan batches");return{counts:ps(s.codecs.counts,t.codecs.counts),frameCounts:ps(s.codecs.frameCounts??{},t.codecs.frameCounts??{}),bandwidthCounts:ps(s.codecs.bandwidthCounts??{},t.codecs.bandwidthCounts??{}),familyMismatched:De(s.codecs.familyMismatched,t.codecs.familyMismatched)}},i=s.correcting,l=t.correcting;return{...s,nextCursor:t.nextCursor,scanned:s.scanned+t.scanned,requested:s.eligibleVideos,truncated:t.nextCursor!==null,timedOut:t.nextCursor===null?!1:!!(s.timedOut||t.timedOut),counts:{write:s.counts.write+t.counts.write,skip:s.
1counts.skip+t.counts.skip,noop:s.counts.noop+t.counts.noop,error:s.counts.error+t.counts.error},gateReasons:Ze(s.gateReasons,t.gateReasons,({reason:d})=>d),changed:De(s.changed,t.changed),validation:n(),codecs:r(),healing:De(s.healing,t.healing),correcting:i||l?{videos:De(i?.videos,l?.videos),reasons:Ze(i?.reasons??[],l?.reasons??[],({reason:d})=>d)}:void 0,invalid:De(s.invalid,t.invalid)}},ya=({organizationId:s,limit:t,verifyCodecs:n,enabled:r})=>Z({enabled:r,queryKey:["admin-master-preview-scan",s,t,n],queryFn:({signal:i})=>ut({organizationId:s,limit:t,verifyCodecs:n,signal:i}),staleTime:0,gcTime:0,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1}),Sa=async({organizationId:s,targets:t})=>{const{data:n}=await C.post(`/v1/admin/master-preview-scan/org/${s}/force-rebuild`,{targets:t});return n},Na=()=>_({mutationFn:Sa}),Ks=[50,100,200,300],Hs=100,fs=200,mt=200,Je=200,gs=()=>({status:"idle",pages:0,verifyCodecs:!1,batchSize:mt}),Ts=s=>s.response,Ws=(s,t)=>{const n=Ts(s)?.data?.message;return typeof n=="string"&&n.trim().length>0?n:s instanceof Error&&s.message.trim().length>0?s.message:t},Qs=s=>{const t=Ts(s);if(t?.status!==429)return null;const n=t.data?.retryAfter??t.headers?.["retry-after"],r=Number(n);return Number.isFinite(r)&&r>0?Math.ceil(r):60},Gs=(s,t)=>new Promise((n,r)=>{const i=window.setTimeout(n,s);t?.addEventListener("abort",()=>{window.clearTimeout(i),r(new DOMException("Aborted","AbortError"))},{once:!0})}),wa=(s,t)=>Array.from({length:Math.ceil(s.length/t)},(n,r)=>s.slice(r*t,(r+1)*t)),Ys={write:{label:"Would write",variant:"default"},skip:{label:"Would skip",variant:"outline"},noop:{label:"No change",variant:"secondary"},error:{label:"Error",variant:"destructive"}},Ca=(s,t)=>t===0?"0.0":(s/t*100).toFixed(1),ka=s=>{const t=s.response?.data?.message;return typeof t=="string"&&t.trim().length>0?t:"Could not queue the forced master playlist rebuilds."},Ra=({fullOrganization:s=!1,scan:t})=>{const n=t.scanned-t.counts.error,r=t.validation,i=t.healing??[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsxs("span",{className:"text-3xl font-semibold tabular-nums",children:[Ca(t.counts.noop,n),"%"]}),e.jsxs("span",{className:"text-muted-foreground",children:["byte-identical — the rebuild reproduces ",t.counts.noop," of ",n," ","scanned masters exactly as they already are"]})]}),t.truncated&&!s&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing the ",t.scanned," most recently created of"," ",t.eligibleVideos," encoded videos in this org. Re-run to re-check; the scan is capped because each video costs several storage reads."]}),t.timedOut&&!s&&e.jsxs("p",{className:"text-sm text-destructive",children:["The scan hit its time budget after ",t.scanned," of"," ",t.requested??t.scanned," videos, so these counts are partial. Re-run with a smaller batch for a complete answer."]}
1),t.correcting&&t.correcting.videos.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:t.correcting.videos.length})," ",t.correcting.videos.length===1?"video has":"videos have"," ","a live master that contradicts its own files, which the gated rebuild would rewrite:"]}),e.jsx("ul",{className:"text-sm text-muted-foreground ml-4 list-disc",children:t.correcting.reasons.map(({reason:l,count:d})=>e.jsxs("li",{children:[e.jsx("span",{className:"font-mono text-xs",children:l})," — ",d," ",d===1?"tier":"tiers",l==="family-contradiction"&&" (the master names the wrong codec family — this is what black-screens Cast receivers)",l==="exact-parse-differs"&&" (right family, wrong profile/level — harmless to most players, but the master is still lying)"]},l))})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-3xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Comparison verdict"}),e.jsx(B,{className:"text-right",children:"Videos"})]})}),e.jsxs(xe,{children:[e.jsxs(O,{children:[e.jsxs(I,{children:[e.jsx("div",{className:"text-muted-foreground",children:"No change"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Rebuilt master is byte-identical to what is live — nothing would be uploaded"})]}),e.jsx(I,{className:"text-right font-mono align-top",children:t.counts.noop})]}),e.jsxs(O,{children:[e.jsxs(I,{children:[e.jsx("div",{className:"font-medium",children:"Would write"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Differs from live and passes the gate — queueing it replaces the master"})]}),e.jsx(I,{className:"text-right font-mono align-top font-semibold",children:t.counts.write})]}),e.jsxs(O,{children:[e.jsxs(I,{children:[e.jsx("div",{className:"font-medium",children:"Would skip"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"The comparison gate refused: not provably equal-or-better than live. A renderable result can still be forced after review"})]}),e.jsx(I,{className:"text-right font-mono align-top font-semibold",children:t.counts.skip})]}),e.jsxs(O,{children:[e.jsxs(I,{children:[e.jsx("div",{className:"text-muted-foreground",children:"Errored"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"The preview itself failed — usually a transient storage error, so re-run before reading anything into it"})]}),e.jsx(I,{className:"text-right font-mono align-top",children:t.counts.error})]})]})]})}),t.gateReasons.length>0&&e.jsxs("div",{className:"space-y-1.5 max-w-3xl",children:[e.jsx("p",{className:"text-sm font-medium",children:"Why the gate would refuse"}),t.gateReasons.map(({reason:l,count:d})=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-mono",children:[d,"×"]})," ",l]},l))]}),r&&e.jsxs("div",{className:"space-y-1.5 max-w-3xl",children:[e.jsx("p",{className:"text-sm font-medium",children:"Playlist structure"}),e.jsxs("p",{className:r.liveWithErrors>0?"text-sm text-destructive":"text-sm text-muted-foreground",children:[r.liveWithErrors," live master",r.liveWithErrors===1?"":"s"," with structural errors",r.liveWithErrors>0&&" — pre-existing damage the rebuild would reproduce exactly"]}),e.jsxs("p",{className:r.renderedWithErrors>0?"text-sm text-destructive":"text-sm text-muted-foreground",children:[r.renderedWithErrors," rebuilt master",r.renderedWithErrors===1?"":"s"," with structural errors"]}),[...r.renderedProblems.map(l=>({...l,side:"rebuilt"})),...r.liveProblems.map(l=>({...l,side:"live"}))].filter(l=>l.severity==="error").map(l=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-mono",children:[l.count,"×"]})," ",l.code," (",l.side,")"]},`${l.side}-${l.code}`))]}),i.length>0&&e.jsxs("div",{className:"space-y-1.5 max-w-3xl",children:[e.jsx("p",{className:"text-sm font-medium",children:"Codecs the rebuild would correct"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," video",i.length===1?"":"s"," where a rendition row's cached codec contradicts the actual file. The rebuild self-heals, so it publishes the file-evidenced codec. Exact parses also refresh the rendition cache; family-only evidence is deliberately not cached."]}
1),i.map(l=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx(u,{asChild:!0,className:"px-0 h-auto",variant:"link",children:e.jsx(ve,{params:{videoId:l.videoId},to:"/admin/videos/$videoId",children:l.title||l.videoId})}),e.jsxs("span",{className:"ml-2 font-mono",children:[l.healedCount," tier",l.healedCount===1?"":"s"]})]},l.videoId))]}),t.codecs&&e.jsxs("div",{className:"space-y-1.5 max-w-3xl",children:[e.jsx("p",{className:"text-sm font-medium",children:"Codec verification"}),t.codecs.familyMismatched.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No tier declares the wrong codec family."," ",Object.entries(t.codecs.counts).map(([l,d])=>`${d} ${l}`).join(", ")]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-destructive",children:[t.codecs.familyMismatched.length," video",t.codecs.familyMismatched.length===1?"":"s"," declare the WRONG codec family — the mislabelled-HEVC case that black-screens Cast receivers."]}),t.codecs.familyMismatched.map(l=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx(u,{asChild:!0,className:"px-0 h-auto",variant:"link",children:e.jsx(ve,{params:{videoId:l.videoId},to:"/admin/videos/$videoId",children:l.title||l.videoId})}),l.tiers.map(d=>e.jsxs("span",{className:"font-mono ml-2",children:[d.resolution,"p: ",d.declared??"—"," → ",d.actual??"—"]},d.resolution))]},l.videoId))]})]}),t.changed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Videos that would not be a no-op (",t.changed.length,")"]}),e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-3xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Video"}),e.jsx(B,{children:"Verdict"}),e.jsx(B,{children:"Reason"})]})}),e.jsx(xe,{children:t.changed.map(l=>e.jsxs(O,{children:[e.jsx(I,{className:"max-w-xs truncate",children:e.jsx(u,{asChild:!0,className:"px-0 h-auto",variant:"link",children:e.jsx(ve,{params:{videoId:l.videoId},to:"/admin/videos/$videoId",children:l.title||l.videoId})})}),e.jsx(I,{children:e.jsx(Pe,{variant:Ys[l.verdict].variant,children:Ys[l.verdict].label})}),e.jsx(I,{className:"text-muted-foreground text-xs font-mono",children:l.detail??"—"})]},l.videoId))})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Open any video to see the rebuilt master diffed against the live one."})]})]})},Ia=({organizationId:s})=>{const[t,n]=x.useState(!1),[r,i]=x.useState(!1),[l,d]=x.useState(!1),[c,g]=x.useState("batch"),[o,S]=x.useState("batch"),[a,b]=x.useState(gs),[h,p]=x.useState(),m=x.useRef(a),w=x.useRef(void 0),j=x.useRef(0),f=x.useRef(0),T=x.useRef(!1),[F,L]=x.useState(Hs),[R,G]=x.useState(mt),[ee,X]=x.useState(Hs),q=ya({organizationId:s,limit:ee,verifyCodecs:l,enabled:r&&o==="batch"}),E=Na(),$=y=>{m.current=y,b(y)};x.useEffect(()=>{j.current+=1,w.current?.abort();const y=gs();return m.current=y,b(y),f.current+=1,T.current=!1,p(void 0),n(!1),i(!1),S("batch"),()=>{j.current+=1,w.current?.abort(),f.current+=1}},[s]);const ge=async({batchSize:y,resume:z=!1,withCodecs:de})=>{const M=z?m.current:gs(),ce=z?M.batchSize:y,qe=z?M.verifyCodecs:de,ae=j.current+1;j.current=ae,w.current?.abort();const pe=new AbortController;w.current=pe;let Ee=z?M.data:void 0,be=z?M.nextCursor:void 0,Le=z?M.snapshotAt:void 0,us=z?M.pages:0;$({...M,status:"running",data:Ee,error:void 0,pages:us,nextCursor:be,snapshotAt:Le,verifyCodecs:qe,batchSize:ce,waitSeconds:void 0});try{for(;;){if(j.current!==ae)return;let se;try{se=await ut({organizationId:s,limit:ce,verifyCodecs:qe,cursor:be??void 0,snapshotAt:Le,signal:pe.signal})}catch(zs){const ms=Qs(zs);if(ms===null)throw zs;if($({...m.current,status:"waiting",waitSeconds:ms}),await Gs(ms*1e3,pe.signal),j.current!==ae)return;$({...m.current,status:"running",waitSeconds:void 0});continue}if(j.current!==ae)return;if(typeof se.snapshotAt!="string"||!("nextCursor"in se)||se.nextCursor!==null&&typeof se.nextCursor!="string")throw new Error("The API replica does not support resumable full scans yet. Try again after the rollout completes.");if(se.organizationId!==s)throw new Error("The full scan returned a different organization");if(Le&&se.snapshotAt!==Le)throw new Error("The full scan cohort changed between batches");if(be&&se.nextCursor===be)throw new Error("The full scan did not advance to the next batch");if(Le=se.snapshotAt,Ee=va(Ee,se),us+=1,be=se.nextCursor,$({status:be===null?"complete":"running",data:Ee,pages:us,nextCursor:be,snapshotAt:Le,verifyCodecs:qe,batchSize:ce}),be===null)return}}catch(se){if(j.current!==ae)return;$({...m.current,status:pe.signal.aborted?"paused":"error",error:pe.signal.aborted?void 0:Ws(se,"Could not continue the full organization scan."),waitSeconds:void 0})}},Ae=()=>{a.status!=="running"&&a.status!=="waiting"||(j.current+=1,w.current?.abort(),$({...m.current,status:"paused",waitSeconds:void 0}))},k=o==="organization"?a.data:q.data,A=a.status==="running"||a.status==="waiting",P=h?.status==="running"||h?.status==="waiting",cs=o==="organization"&&(a.status==="running"||a.status==="waiting"||a.status==="paused"||a.status==="error")||P,Qe=Jt({disabled:!cs,enableBeforeUnload:cs,shouldBlockFn:()=>cs,withResolver:!0}),Fe=q.isFetching||A||E.isPending||P,Ls=y=>y.renderedErrors===0&&(y.forceWritable??y.verdict==="write"),Oe=(k?.changed??[]).filter(y=>Ls(y)&&!y.videoAssetId).length,je=(k?.changed??[]).filter(y=>y.verdict==="skip"&&y.forceWritable===void 0).length,D=(k?.changed??[]).flatMap(y=>!Ls(y)||!y.videoAssetId?[]:[{videoId:y.videoId,expectedVideoAssetId:y.videoAssetId}]),jt=l?Ks.filter(y=>y<=fs):Ks,Ge=y=>{if(Fe)return;if(d(y),S(c),p(void 0),f.current+=1,T.current=!1,E.reset(),c==="organization"){const M=y?Math.min(R,fs):R;G(M),i(!1),n(!1),ge({batchSize:M,withCodecs:y});return}const z=y?Math.min(F,fs):F,de=y===l&&z===ee;L(z),X(z),i(!0),r&&de&&q.refetch()},bt=async()=>
1{if(!(D.length===0||je>0)){if(o==="organization"){if(a.status!=="complete"||Oe>0||je>0||h||T.current)return;T.current=!0;const y=wa(D,Je),z=f.current+1;f.current=z;let de=0,M=0;const ce=[];p({status:"running",total:D.length,totalBatches:y.length,completedBatches:M,confirmed:de,batchIds:ce});for(const qe of y){if(f.current!==z)return;for(;;){if(f.current!==z)return;try{const ae=await E.mutateAsync({organizationId:s,targets:qe});if(f.current!==z)return;de+=ae.queued,M+=1,ce.push(ae.batchId),p({status:M===y.length?"complete":"running",total:D.length,totalBatches:y.length,completedBatches:M,confirmed:de,batchIds:[...ce]});break}catch(ae){if(f.current!==z)return;const pe=Qs(ae);if(pe!==null){if(p({status:"waiting",total:D.length,totalBatches:y.length,completedBatches:M,confirmed:de,batchIds:[...ce],waitSeconds:pe}),await Gs(pe*1e3),f.current!==z)return;p({status:"running",total:D.length,totalBatches:y.length,completedBatches:M,confirmed:de,batchIds:[...ce]});continue}const Ee=Ts(ae)?.status;p({status:"error",total:D.length,totalBatches:y.length,completedBatches:M,confirmed:de,batchIds:[...ce],error:Ws(ae,"Could not queue the next forced rebuild batch."),ambiguous:Ee===void 0||Ee>=500});return}}}n(!1);return}E.mutate({organizationId:s,targets:D},{onSuccess:()=>n(!1)})}};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsx(ke,{children:"Master playlist comparison"}),e.jsx(Re,{children:"Rebuilds each video's master playlist from verified storage and database truth and compares it with the one that is live. The comparison itself uploads and queues nothing; renderable differences can be explicitly forced through the queue after review."})]}),e.jsxs(Ie,{className:"space-y-4",children:[(c==="organization"||o==="organization"&&a.status!=="idle")&&e.jsxs("div",{className:"space-y-1 text-sm text-amber-600",children:[e.jsx("p",{children:"Full scan and repair progress lives only on this page. Keep this tab open until both finish; leaving may stop future batches and leave a partial scan or repair."}),e.jsx("p",{children:"Video eligibility and current assets may change during the run. Every repair target is revalidated before it is queued and again before anything is written."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Scope"}),e.jsxs(ys,{disabled:Fe,onValueChange:y=>g(y),value:c,children:[e.jsx(Ss,{className:"w-56",id:"master-scan-scope",children:e.jsx(Ns,{})}),e.jsxs(ws,{position:"item-aligned",children:[e.jsx(ss,{value:"batch",children:"Selected batch"}),e.jsx(ss,{value:"organization",children:"Full organization"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:c==="organization"?"Videos per batch":"Videos per run"}),e.jsxs(ys,{disabled:Fe,onValueChange:y=>{const z=Number(y);c==="organization"?G(z):L(z)},value:String(c==="organization"?R:F),children:[e.jsx(Ss,{className:"w-28",id:"master-scan-limit",children:e.jsx(Ns,{})}),e.jsx(ws,{position:"item-aligned",children:jt.map(y=>e.jsx(ss,{value:String(y),children:y},y))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c==="organization"?`continues through the snapshot at the selected comparison size; repair submissions remain capped separately at ${Je}`:"newest first; codec verification reads every rendition file, so it is capped at 200"})]}),!r&&a.status==="idle"&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(u,{onClick:()=>Ge(!1),variant:"outline",children:[e.jsx(ts,{className:"size-4"}),"Run comparison"]}),e.jsxs(u,{onClick:()=>Ge(!0),variant:"outline",children:[e.jsx(qs,{className:"size-4"}),"Run with codec verification"]})]}),o==="batch"&&r&&q.isPending&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(N,{className:"size-4"}),"Rebuilding up to ",ee," masters and comparing…",l&&" Reading every rendition file to check its codec, so this is slower."]}),o==="batch"&&q.isError&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Could not run the comparison."}),e.jsx(u,{onClick:()=>{q.refetch()},variant:"outline",children:"Try again"})]}),o==="organization"&&a.status!=="idle"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[(a.status==="running"||a.status==="waiting")&&e.jsx(N,{className:"size-4"}),e.jsxs("span",{role:"status",children:[a.status==="complete"?`Full organization scan complete: ${a.data?.scanned??0} of ${a.data?.eligibleVideos??0} eligible-at-start videos compared across ${a.pages} ${a.pages===1?"batch":"batches"}.`:`Scanned ${a.data?.scanned??0}${a.data?` of ${a.data.eligibleVideos} eligible at start`:""}; ${a.pages} ${a.pages===1?"batch":"batches"} complete.`,a.status==="running"&&` Reading batch ${a.pages+1} (up to ${a.batchSize} videos)…`,a.status==="waiting"&&` Rate limited; continuing in ${a.waitSeconds??60} seconds.`,a.status==="paused"&&" The scan is paused before the next unconfirmed batch."]})]}),a.status==="error"&&e.jsxs("p",{className:"text-sm text-destructive",role:"alert",children:[a.error," Completed batches remain available; resume retries from the last confirmed cursor."]}
1),(a.status==="running"||a.status==="waiting")&&e.jsx(u,{onClick:Ae,size:"sm",variant:"outline",children:"Stop full scan"}),(a.status==="paused"||a.status==="error")&&e.jsx(u,{onClick:()=>{ge({batchSize:a.batchSize,resume:!0,withCodecs:a.verifyCodecs})},size:"sm",variant:"outline",children:"Resume full scan"})]}),k&&e.jsxs(e.Fragment,{children:[e.jsx(Ra,{fullOrganization:o==="organization",scan:k}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(u,{disabled:Fe,onClick:()=>Ge(l),variant:"outline",children:[q.isFetching||A?e.jsx(N,{className:"size-4"}):e.jsx(ts,{className:"size-4"}),"Re-run comparison"]}),!l&&e.jsxs(u,{disabled:Fe,onClick:()=>Ge(!0),variant:"outline",children:[e.jsx(qs,{className:"size-4"}),"Also verify codecs"]}),(D.length>0||o==="organization"&&Oe>0||je>0)&&e.jsxs(u,{disabled:Fe||!!E.data||!!h||Oe>0||je>0||o==="organization"&&a.status!=="complete",onClick:()=>n(!0),children:[e.jsx(it,{className:"size-4"}),"Queue forced rebuilds (",D.length,")"]})]}),Oe>0&&e.jsxs("p",{className:"text-sm text-destructive",role:"alert",children:[Oe," force-writable candidate",Oe===1?"":"s"," lack a verified asset identity. Re-run after the API rollout completes before queueing this result."]}),je>0&&e.jsxs("p",{className:"text-sm text-destructive",role:"alert",children:[je," “Would skip” result",je===1?"":"s"," came from an API replica without a force-safety classification. Re-run the comparison after the API rollout completes before queueing."]}),o==="batch"&&E.data&&e.jsxs("p",{className:"text-sm",role:"status",children:["Batch"," ",e.jsx("span",{className:"font-mono",children:E.data.batchId})," ","accepted: ",E.data.queued," forced rebuild",E.data.queued===1?"":"s"," queued. Re-run the comparison after the batch completes to verify the live playlists."]}),o==="organization"&&h&&e.jsxs("div",{className:"space-y-1 text-sm",role:"status",children:[e.jsxs("p",{children:[h.status==="complete"?`${h.confirmed} forced rebuilds accepted in ${h.completedBatches} batches.`:`${h.confirmed} of ${h.total} rebuilds confirmed across ${h.completedBatches} of ${h.totalBatches} batches.`,h.status==="waiting"&&` Rate limited; continuing in ${h.waitSeconds??60} seconds.`]}),h.batchIds.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Accepted batch IDs:"," ",e.jsx("span",{className:"font-mono",children:h.batchIds.join(", ")})]}),h.status==="complete"&&e.jsx("p",{children:"Re-run the full comparison after the batches complete to verify the live playlists."})]})]})]})]}),e.jsx(U,{open:t,onOpenChange:y=>{!E.isPending&&!P&&n(y)}
1,children:e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsxs(H,{children:["Force ",D.length," master rebuild",D.length===1?"":"s","?"]}),e.jsxs(W,{children:["This replaces each live master with the valid playlist rendered from current database rows and verified storage, even when the comparison gate would keep a live tier, caption, or stream attribute. Empty or structurally invalid renders still cannot be written. It also rewrites quality masters, purges the CDN, and may refresh cached codec metadata; it does not re-encode video.",o==="organization"&&` The ${D.length} targets are submitted as ${Math.ceil(D.length/Je)} separately accepted batches of at most ${Je}.`]})]}),o==="batch"&&(k?.truncated||k?.timedOut)&&e.jsx("p",{className:"text-sm text-amber-600",children:"This comparison is partial, so the action covers only the force-writable candidates returned by this scan. Unscanned videos are not queued."}),o==="batch"&&E.isError&&e.jsxs("p",{className:"text-sm text-destructive",role:"alert",children:[ka(E.error)," No rebuilds from this request are confirmed as queued; review the error before trying again."]}),o==="organization"&&h?.status==="error"&&e.jsxs("p",{className:"text-sm text-destructive",role:"alert",children:[h.error," ",h.confirmed," of ",h.total," ","rebuilds are confirmed accepted in ",h.completedBatches," ","batches."," ",h.ambiguous?"The failed batch may have reached the server, so do not retry it blindly; run a fresh comparison.":"The failed batch was not accepted; run a fresh comparison before queueing the remaining candidates."]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:E.isPending||P,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:E.isPending||P||D.length===0||je>0||o==="organization"&&!!h||o==="organization"&&a.status!=="complete",onClick:()=>{bt()},children:[(E.isPending||P)&&e.jsx(N,{className:"size-4"}),"Force ",D.length," master rebuild",D.length===1?"":"s"]})]})]})}),e.jsx(U,{open:Qe.status==="blocked",onOpenChange:y=>{y||Qe.reset?.()},children:e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsx(H,{children:"Leave this full playlist operation?"}),e.jsx(W,{children:"Full scan and repair state exists only on this page. Leaving, reloading, or closing the tab may stop future batches and leave a partial scan or repair. Already accepted repair batches cannot be undone by staying or leaving."})]}),e.jsxs(Q,{children:[e.jsx(u,{onClick:()=>Qe.reset?.(),variant:"ghost",children:"Stay on page"}),e.jsx(u,{onClick:()=>Qe.proceed?.(),variant:"destructive",children:"Leave page"})]})]})})]})},Ea=({organizationId:s})=>C.get(`/v1/organizations/admin/${s}/members`).then(({data:t})=>t).catch(t=>{const n=t.response?.status;if(![401,403,404].includes(n))throw t;return null}),Ba=({organizationId:s})=>Z({gcTime:0,queryKey:He.organizationMembers({id:s}),queryFn:()=>Ea({organizationId:s}),refetchOnReconnect:!1,refetchOnWindowFocus:!1,staleTime:1/0}),Ta=[{header:"Name",cell:({row:s})=>{const t=s.original.user;return e.jsx("div",{className:"flex min-w-0 max-w-[250px]",title:t.name,children:e.jsx(u,{asChild:!0,variant:"link",children:e.jsx(ve,{className:"max-w-full px-0!",params:{userId:t.id},to:"/admin/users/$userId",children:e.jsx("span",{className:"truncate",children:t.name})})})})}},{header:"Email",cell:({row:s})=>{const t=s.original.user;return e.jsx("div",{className:"flex min-w-0 max-w-[250px]",title:t.email,children:e.jsx(u,{asChild:!0,variant:"link",children:e.jsx(ve,{className:"max-w-full px-0!",params:{userId:t.id},to:"/admin/users/$userId",children:e.jsx("span",{className:"truncate",children:t.email})})})})}},{accessorKey:"role",header:"Organization role",cell:({row:s})=>e.jsx("span",{children:s.original.role})},{accessorKey:"createdAt",header:"Joined at",cell:({row:s})=>e.jsx("span",{className:"tabular-nums",children:_t({date:s.original.createdAt,variant:"full"})})}],Aa=({organizationId:s})=>{const{t}=Ke("common"),n=Ba({organizationId:s});x.useEffect(()=>{n.isError&&v.error(t("error.unknown",{ns:"common"}))},[n,t]);const r=n.data?.members||[],i=r.length;return e.jsx("section",{className:"flex flex-col w-full gap-4",children:e.jsx(Wt,{columns:Ta,data:r,hasNextPage:!1,isLoading:n.isLoading,isFetchingNextPage:!1,totalCount:i})})},Xs=s=>s===void 0?0n:BigInt(s),Fa=ye({bandwidthLimitBytes:js().nonnegative(),bandwidthLimitPeriod:Nt}),Oa=({currentBandwidthLimitBytes:s,currentBandwidthLimitPeriod:t,organizationId:n})=>{const[r,i]=x.useState(!1),{control:l,formState:{errors:d},handleSubmit:c,register:g,reset:o,watch:S}=Se({defaultValues:{bandwidthLimitBytes:Xs(s),bandwidthLimitPeriod:t},resolver:Ne(Fa)}),a=fe({onError:()=>{v.error("Failed to update bandwidth limit.")},onSuccess:()=>{v.success("Bandwidth limit updated."),i(!1)}});x.useEffect(()=>{r&&o({bandwidthLimitBytes:Xs(s),bandwidthLimitPeriod:t})},[s,t,r,o]);const b=()=>{a.mutate({body:{bandwidthLimitBytes:null,bandwidthLimitPeriod:null},organizationId:n})},h=({bandwidthLimitBytes:w,bandwidthLimitPeriod:j})=>{a.mutate({body:{...w.toString()!==s?{bandwidthLimitBytes:w.toString()}:{},...j!==t?{bandwidthLimitPeriod:j}:{}},organizationId:n})},p=a.isPending,m=S("bandwidthLimitBytes");return e.jsxs(U,{open:r,onOpenChange:i,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{variant:"ghost",size:"sm",children:e.jsx(Me,{className:"size-4"})})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:c(h),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Update Bandwidth Limit"}),e.jsx(W,{children:"Change how much the organization may serve compared to the default their plan allows. Nothing is enforced against this yet."})]}),e.jsxs(te,{"data-invalid":!!d.bandwidthLimitBytes?.message,children:[e.jsx(ne,{htmlFor:"bandwidthLimitBytes",children:"Bandwidth Limit (Bytes) - counted per period below"}),e.jsxs(Cs,{children:[e.jsx(ks,{...g("bandwidthLimitBytes"),className:"text-sm",disabled:p,id:"bandwidthLimitBytes",type:"text"}),e.jsx(Rs,{align:"inline-end",children:Te(Number(m),2)})]}),d.bandwidthLimitBytes?.message&&e.jsx(oe,{children:d.bandwidthLimitBytes.message})]}),e.jsx(Bs,{control:l,name:"bandwidthLimitPeriod",render:({field:w,fieldState:j})=>e.jsxs(te,{"data-invalid":j.invalid,children:[e.jsx(ne,{htmlFor:"bandwidthLimitPeriod",children:"Period the limit is counted over"}),e.jsxs(ys,{disabled:p,name:w.name,onValueChange:w.onChange,required:!0,value:w.value,children:[e.jsx(Ss,{"aria-invalid":j.invalid,id:"bandwidthLimitPeriod",children:e.jsx(Ns,{})}),e.jsx(ws,{position:"item-aligned",children:Object.values(yt).map(f=>e.jsx(ss,{value:f,children:St[f]},f))})]}),d.bandwidthLimitPeriod?.message&&e.jsx(oe,{children:d.bandwidthLimitPeriod.message})]})}),e.jsxs(Q,{className:"sm:justify-between",children:[e.jsxs(u,{disabled:p,onClick:b,type:"button",variant:"destructive",children:[p&&e.jsx(N,{}),"Reset"]}),e.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[e.jsx(J,{asChild:!0,disabled:p,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:p,type:"submit",children:[p&&e.jsx(N,{}),"Confirm"]})]})]})]})})]})},La=s=>s.bandwidthLimitBytes?e.jsx(Zs,{action:e.jsx(Oa,{currentBandwidthLimitBytes:s.bandwidthLimitBytes,currentBandwidthLimitPeriod:s.bandwidthLimitPeriod,organizationId:s.id}),field:"Bandwidth",value:e.jsx(Pt,{...s})}):e.jsx(Zs,{field:"Bandwidth",value:"—"}),Zs=({action:s,field:t,value:n})=>e.jsxs("div",{className:"flex items-center justify-between gap-4 min-h-8",children:[e.jsxs("span",{className:"flex items-center text-sm gap-1",children:[e.jsxs("span",{className:"min-w-42",children:[t,":"]}),e.jsx("span",{className:"font-medium",children:n})]}),s]}),za=ye({storageLimitsIncludeRenditions:wt(),totalLimitBufferBytes:js().nonnegative(),totalLimitSizeBytes:js().nonnegative()}),_a=({currentStorageLimitsIncludeRenditions:s,currentTotalLimitBufferBytes:t,currentTotalLimitSizeBytes:n,organizationId:r})=>{const[i,l]=x.useState(!1),{control:d,formState:{errors:c},handleSubmit:g,register:o,reset:S,watch:a}=Se({defaultValues:{storageLimitsIncludeRenditions:s,totalLimitBufferBytes:BigInt(t),totalLimitSizeBytes:BigInt(n)},resolver:Ne(za)}),b=fe({onError:()=>{v.error("Failed to update storage limits.")},onSuccess:()=>{v.success("Storage limits updated."),l(!1)}});x.useEffect(()=>{i&&S({storageLimitsIncludeRenditions:s,totalLimitBufferBytes:BigInt(t),totalLimitSizeBytes:BigInt(n)})},[s,t,n,i,S]);const h=()=>{b.mutate({body:{totalLimitBufferBytes:null,totalLimitSizeBytes:null},organizationId:r})},p=({storageLimitsIncludeRenditions:f,totalLimitBufferBytes:T,totalLimitSizeBytes:F})=>{b.mutate({body:{...f!==s?{storageLimitsIncludeRenditions:f}:{},...T.toString()!==t?{totalLimitBufferBytes:T.toString()}:{},...F.toString()!==n?{totalLimitSizeBytes:F.toString()}:{}},organizationId:r})},m=b.isPending,w=a("totalLimitBufferBytes"),j=a("totalLimitSizeBytes");return e.jsxs(U,{open:i,onOpenChange:l,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{variant:"ghost",size:"sm",children:e.jsx(Me,{className:"size-4"})})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:g(p),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Update Storage Limits"}),e.jsx(W,{children:"Change the amount the user can upload compared to the default their plan allows."})]}),e.jsxs(te,{"data-invalid":!!c.totalLimitSizeBytes?.message,children:[e.jsx(ne,{htmlFor:"totalLimitSizeBytes",children:"Limit Size (Bytes) - counted against original file sizes (plus renditions when the toggle below is on)"}),e.jsxs(Cs,{children:[e.jsx(ks,{...o("totalLimitSizeBytes"),className:"text-sm",disabled:m,id:"totalLimitSizeBytes",type:"text"}),e.jsx(Rs,{align:"inline-end",children:Te(Number(j),2)})]}),c.totalLimitSizeBytes?.message&&e.jsx(oe,{children:c.totalLimitSizeBytes.message})]}),e.jsxs(te,{"data-invalid":!!c.totalLimitBufferBytes?.message,children:[e.jsx(ne,{htmlFor:"totalLimitBufferBytes",children:"Limit Buffer (Bytes) - amount allowed over limit size"}),e.jsxs(Cs,{children:[e.jsx(ks,{...o("totalLimitBufferBytes"),className:"text-sm",disabled:m,id:"totalLimitBufferBytes",type:"text"}),e.jsx(Rs,{align:"inline-end",children:Te(Number(w),2)})]}),c.totalLimitBufferBytes?.message&&e.jsx(oe,{children:c.totalLimitBufferBytes.message})]}),e.jsxs(te,{className:"justify-between",orientation:"horizontal",children:[e.jsx(ne,{className:"grow-0! pointer-events-none",htmlFor:"storageLimitsIncludeRenditions",children:"Do storage limits include all renditions?"}),e.jsx(Bs,{control:d,name:"storageLimitsIncludeRenditions",render:({field:f})=>e.jsx(os,{checked:f.value,disabled:m,id:"storageLimitsIncludeRenditions",onCheckedChange:f.onChange})})]}),e.jsxs(Q,{className:"sm:justify-between",children:[e.jsxs(u,{disabled:m,onClick:h,type:"button",variant:"destructive",children:[m&&e.jsx(N,{}),"Reset"]}),e.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[e.jsx(J,{asChild:!0,disabled:m,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:m,type:"submit",children:[m&&e.jsx(N,{}),"Confirm"]})]})]})]})})]})},Pa=s=>e.jsxs(e.Fragment,{children:[e.jsx(es,{action:e.jsx(_a,{currentStorageLimitsIncludeRenditions:s.storageLimitsIncludeRenditions,currentTotalLimitBufferBytes:s.totalLimitBufferBytes,currentTotalLimitSizeBytes:s.totalLimitSizeBytes,organizationId:s.id}),field:"Storage",value:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:Ct(Number(s.totalOriginalSizeBytes)>Number(s.totalLimitSizeBytes)&&"text-orange-300",Number(s.totalOriginalSizeBytes)>Number(s.totalLimitSizeBytes)+Number(s.totalLimitBufferBytes)&&"text-destructive"),children:`${Te(Number(s.totalOriginalSizeBytes||0),2)} / ${Te(Number(s.totalLimitSizeBytes),0)}`})," ",e.jsx("span",{children:s.storageLimitsIncludeRenditions?"(renditions + original sizes)":"(original uploads size only)"})]})}),e.jsx(es,{field:"Total Rendition Storage",value:Js({sizeBytes:s.totalRenditionStorageBytes,unmeasured:s.totalRenditionStorageUnmeasuredRenditions,singular:"rendition",plural:"renditions"})}),e.jsx(es,{field:"Total Uploaded Storage",value:Js({sizeBytes:s.totalUploadedStorageBytes,unmeasured:s.totalUploadedStorageUnmeasuredUploads,singular:"upload",plural:"uploads"})}),e.jsx(es,{field:"Total Global Storage",value:Ma(s)})]}),Js=({plural:s,singular:t,sizeBytes:n,unmeasured:r})=>{const i=Te(Number(n||0),2);return r>0?`At least ${i} (${r} unmeasured ${r===1?t:s})`:i},Ma=s=>{const t=[s.totalRenditionStorageUnmeasuredRenditions>0?`${s.totalRenditionStorageUnmeasuredRenditions} unmeasured ${s.totalRenditionStorageUnmeasuredRenditions===1?"rendition":"renditions"}`:null,s.totalUploadedStorageUnmeasuredUploads>0?`${s.totalUploadedStorageUnmeasuredUploads} unmeasured ${s.totalUploadedStorageUnmeasuredUploads===1?"upload":"uploads"}
1`:null].filter(Boolean),n=Te(Number(s.totalGlobalStorageBytes||0),2);return t.length>0?`At least ${n} (${t.join(", ")})`:n},es=({action:s,field:t,value:n})=>e.jsxs("div",{className:"flex items-center justify-between gap-4 min-h-8",children:[e.jsxs("span",{className:"flex items-center text-sm gap-1",children:[e.jsxs("span",{className:"min-w-42",children:[t,":"]}),e.jsx("span",{className:"font-medium",children:n})]}),s]}),ht="admin-organization-thumbnail-batch",As=s=>[ht,s],Fs=s=>[ht,"latest",s],qa=new Set(["abandoned","completed","completed_with_failures"]),$a=new Set(["copying"]),xt=s=>qa.has(s),Da=async s=>{try{const{data:t}=await C.get(`/v1/admin/organization-thumbnails/${s}`);return t}catch(t){if(t.response?.status===404)return null;throw t}},Ua=s=>Z({enabled:!!s,queryFn:()=>Da(s),queryKey:As(s??""),refetchInterval:t=>{const n=t.state.data;return n===null?!1:n?xt(n.state)?!1:$a.has(n.state)?3e3:!1:3e3}}),Va=async s=>{try{const{data:t}=await C.get(`/v1/admin/organization-thumbnails/organizations/${s}/latest`);return t}catch(t){if(t.response?.status===404)return null;throw t}},Ka=s=>Z({queryFn:()=>Va(s),queryKey:Fs(s)}),Os=({batchId:s,organizationId:t,queryClient:n})=>{const r=[n.invalidateQueries({queryKey:As(s)})];return t&&r.push(n.invalidateQueries({queryKey:Fs(t)})),Promise.all(r)},Ha=({csvContent:s,organizationId:t,sourceVideoId:n})=>C.post(`/v1/admin/organization-thumbnails/organizations/${t}/batches`,s,{headers:{"Content-Type":"text/csv"},params:{sourceVideoId:n}}).then(({data:r})=>r),Wa=()=>{const s=Y();return _({mutationFn:Ha,onSuccess:(t,n)=>{s.invalidateQueries({queryKey:Fs(n.organizationId)}),s.invalidateQueries({queryKey:As(t.batchId)})}})},Qa=({batchId:s})=>C.post(`/v1/admin/organization-thumbnails/${s}/start`,{}).then(({data:t})=>t),Ga=s=>{const t=Y();return _({mutationFn:Qa,onSuccess:(n,r)=>{Os({batchId:r.batchId,organizationId:s,queryClient:t})}})},Ya=({batchId:s})=>C.post(`/v1/admin/organization-thumbnails/${s}/retry-failed`,{}).then(({data:t})=>t),Xa=s=>{const t=Y();return _({mutationFn:Ya,onSuccess:(n,r)=>{Os({batchId:r.batchId,organizationId:s,queryClient:t})}})},Za=({batchId:s})=>C.post(`/v1/admin/organization-thumbnails/${s}/abandon`,{}).then(({data:t})=>t),Ja=s=>{const t=Y();return _({mutationFn:Za,onSuccess:(n,r)=>{Os({batchId:r.batchId,organizationId:s,queryClient:t})}})},ei="awaiting_start",si=new Set(["completed_with_failures"]),ti=new Set(["abandoned","completed","completed_with_failures"]),ni={abandoned:"Abandoned",awaiting_start:"Ready to start",completed:"Completed",completed_with_failures:"Completed with failures",copying:"Copying thumbnails"},ai=s=>ni[s]??s.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),Es=(s,t)=>{const n=s.response?.data;return typeof n=="object"&&n!==null&&"message"in n&&typeof n.message=="string"?n.message:s instanceof Error&&s.message?s.message:t},et=({summary:s})=>e.jsxs("div",{className:"grid grid-cols-2 gap-2 rounded-md border p-3 text-sm sm:grid-cols-3 lg:grid-cols-6",children:[e.jsx(re,{label:"CSV rows",value:s.totalRows}),e.jsx(re,{label:"Unique IDs",value:s.uniqueVideoIds}),e.jsx(re,{label:"Duplicate rows",value:s.duplicateCount}),e.jsx(re,{label:"Malformed",value:s.malformedCount}),e.jsx(re,{label:"Invalid",value:s.invalidCount}),e.jsx(re,{label:"Videos targeted",value:s.targetCount})]}),re=({label:s,value:t})=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"font-mono font-medium tabular-nums",children:t})]}),pt=({batch:s})=>e.jsxs("div",{className:"grid grid-cols-2 gap-2 rounded-md border p-3 text-sm sm:grid-cols-3 lg:grid-cols-6",children:[e.jsx(re,{label:"Targeted",value:s.counts.total}),e.jsx(re,{label:"Pending",value:s.counts.pending}),e.jsx(re,{label:"Processing",value:s.counts.processing}),e.jsx(re,{label:"Succeeded",value:s.counts.completed}),e.jsx(re,{label:"Failed",value:s.counts.failed}),e.jsx(re,{label:"Skipped",value:s.counts.skipped})]}),ft=({compact:s=!1,source:t})=>e.jsxs("div",{className:"flex gap-3 rounded-md border p-3",children:[t.thumbnailUrl&&e.jsx("div",{className:s?"flex aspect-video h-16 shrink-0 overflow-hidden rounded bg-muted":"flex aspect-video w-48 max-w-[40%] shrink-0 overflow-hidden rounded bg-muted",children:e.jsx("img",{alt:`Current thumbnail for ${t.title}`,className:"m-auto max-h-full max-w-full object-contain",src:t.thumbnailUrl})}),e.jsxs("div",{className:"min-w-0 space-y-1 text-sm",children:[e.jsx("p",{className:"font-medium",children:t.title}),e.jsxs("p",{className:"break-all font-mono text-xs text-muted-foreground",children:["Video: ",t.videoId]}),!s&&e.jsxs("p",{className:"break-all font-mono text-xs text-muted-foreground",children:["Thumbnail: ",t.thumbnailId]})]})]}),st=({issues:s,label:t})=>s.length===0?null:e.jsxs("div",{className:"space-y-1.5 rounded-md border p-3",children:[e.jsxs("p",{className:"text-sm font-medium",children:[t," (",s.length,")"]}),e.jsxs("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:[s.slice(0,20).map(n=>e.jsxs("p",{className:"text-xs",children:[e.jsx("span",{className:"font-mono",children:n.videoId}),n.error?` · ${n.error}`:""]},n.videoId)),s.length>20&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.length-20," more target(s) not shown."]})]})]}),ii=({organizationId:s,organizationName:t})=>{const n=Y(),[r,i]=x.useState(null),[l,d]=x.useState(!1),[c,g]=x.use
1State(!1),[o,S]=x.useState(null),a=x.useRef(null),b=Ka(s),h=r??b.data?.batch?.batchId??null,p=Ua(h),m=p.data??null,w=Xa(s),j=Ja(s),f=m?.state??null,T=!!m&&xt(m.state),F=f===ei,L=!!m&&m.counts.failed>0&&f!==null&&si.has(f),R=f==="copying",G=!m||f!==null&&ti.has(f),ee=f!==null&&f!=="abandoned"&&f!=="completed",X=b.isPending||!!h&&p.isPending,q=m?m.counts.completed+m.counts.failed+m.counts.skipped:0,E=m&&m.counts.total>0?Math.min(100,Math.round(q/m.counts.total*100)):0;x.useEffect(()=>{if(!m||!T)return;const A=`${m.batchId}:${f}:${m.counts.completed}:${m.counts.failed}:${m.counts.skipped}`;a.current!==A&&(a.current=A,nt({queryClient:n}))},[m,T,n,f]);const $=()=>{S(null),d(!0)},ge=()=>{m&&(S(m),d(!0))},Ae=A=>{m&&w.mutate({batchId:m.batchId},{onError:P=>v.error(Es(P,"Failed to retry thumbnail copies.")),onSuccess:P=>v.success(A==="replay"?`Batch replayed; ${P.retriedCount} target job(s) ensured.`:"Failed thumbnail copies queued again.")})},k=()=>{m&&j.mutate({batchId:m.batchId},{onError:A=>v.error(Es(A,"Failed to abandon thumbnail batch.")),onSuccess:()=>{g(!1),d(!1),v.success("Thumbnail batch abandoned.")}})};return e.jsxs("section",{className:"flex flex-col w-full gap-4",children:[e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsx(ke,{children:"Copy a thumbnail from one video"}),e.jsx(Re,{children:"Choose a source video whose current thumbnail is stored in GCS, then copy its full and small thumbnail files to an exact CSV subset of this organization's videos."})]}),e.jsxs(Ie,{className:"space-y-4",children:[X&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(N,{className:"size-4"}),"Checking for the latest thumbnail batch…"]}),(b.isError||p.isError)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-destructive/40 bg-destructive/5 p-3",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load the latest thumbnail batch."}),e.jsxs(u,{onClick:()=>{b.refetch(),p.refetch()},size:"sm",variant:"outline",children:[e.jsx(Ue,{className:"size-4"}),"Retry"]})]}),!X&&!m&&!b.isError&&e.jsxs(u,{onClick:$,children:[e.jsx(hs,{className:"size-4"}),"Create thumbnail batch"]}),m&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[f==="copying"&&e.jsx(N,{className:"size-4"}),e.jsxs("span",{className:"font-medium",children:["Batch ",m.batchId," · ",ai(m.state)]})]}),m.error&&e.jsx("p",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:m.error}),e.jsx(ft,{compact:!0,source:m.source}),e.jsx(pt,{batch:m}),!F&&m.counts.total>0&&e.jsxs("div",{className:"max-w-xl space-y-1.5",children:[e.jsx(We,{value:E}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[q," of ",m.counts.total," target(s) settled"]})]}),f==="completed_with_failures"&&e.jsx("p",{className:"rounded-md bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-300",children:"The batch completed partially. Successful videos already use the new thumbnail; retry only the failed copies or abandon the batch before starting another."}),e.jsx(st,{issues:m.failedTargets,label:"Failed targets"}),e.jsx(st,{issues:m.skippedTargets,label:"Skipped targets"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[F&&e.jsxs(u,{onClick:ge,children:[e.jsx(hs,{className:"size-4"}),"Review and start"]}),R&&e.jsxs(u,{disabled:w.isPending,onClick:()=>Ae("replay"),size:"sm",variant:"ghost",children:[w.isPending?e.jsx(N,{className:"size-4"}):e.jsx(Ue,{className:"size-4"}),"Ensure jobs are queued"]}),L&&e.jsxs(u,{disabled:w.isPending,onClick:()=>Ae("failed"),variant:"outline",children:[w.isPending?e.jsx(N,{className:"size-4"}):e.jsx(Ue,{className:"size-4"}),"Retry ",m.counts.failed," failed"]}),ee&&e.jsxs(u,{disabled:j.isPending,onClick:()=>g(!0),variant:"outline",children:[e.jsx(at,{className:"size-4"}),"Abandon batch"]}),G&&e.jsxs(u,{onClick:$,variant:"outline",children:[e.jsx(hs,{className:"size-4"}),"Start another batch"]})]})]})]})]}),l&&e.jsx(di,{initialBatch:o,onBatchCreated:i,onClose:()=>d(!1),onProcessingStarted:A=>{i(A),d(!1)},organizationId:s,organizationName:t},o?.batchId??"new"),e.jsx(U,{onOpenChange:A=>!j.isPending&&g(A),open:c,children:e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsx(H,{children:"Abandon thumbnail batch?"}),e.jsx(W,{children:"This stops any work that has not started and closes this batch. Thumbnail copies that already succeeded are not rolled back."})]}),e.jsxs(Q,{children:[e.jsx(u,{disabled:j.isPending,onClick:()=>g(!1),variant:"ghost",children:"Keep batch"}),e.jsxs(u,{disabled:j.isPending,onClick:k,variant:"destructive",children:[j.isPending&&e.jsx(N,{className:"size-4"}),"Abandon batch"]})]})]})})]})},ns=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),ri=s=>{if(typeof s=="string")return s;if(!ns(s))return String(s);const t=s.rowNumber??s.row,n=s.externalVimeoId??s.videoId??s.id??s.value,r=s.message??s.reason??s.error,
1i=[typeof t=="number"?`Row ${t}`:void 0,typeof n=="string"?n:void 0,typeof r=="string"?r:void 0].filter(Boolean);return i.length>0?i.join(" · "):JSON.stringify(s)},oi=s=>{if(!ns(s))return;const{duplicateCount:t,invalidCount:n,malformedCount:r,targetCount:i,totalRows:l,uniqueVideoIds:d}=s;if(!(typeof t!="number"||typeof i!="number"||typeof l!="number"||typeof d!="number"))return{duplicateCount:t,invalidCount:typeof n=="number"?n:0,malformedCount:typeof r=="number"?r:0,targetCount:i,totalRows:l,uniqueVideoIds:d}},li=s=>{const t=s.response?.data;if(!ns(t))return{groups:[],message:"CSV validation failed."};const n=ns(t.details)?t.details:{},r={...t,...n},l=[{key:"malformed",label:"Malformed rows"},{key:"invalidVideos",label:"Invalid or ineligible video IDs"},{key:"invalidVideoIds",label:"Invalid or ineligible video IDs"},{key:"notFound",label:"Videos not found"},{key:"wrongOrganization",label:"Videos in another organization"},{key:"deleted",label:"Deleted videos"}].flatMap(({key:d,label:c})=>{const g=r[d];return!Array.isArray(g)||g.length===0?[]:[{items:g.map(ri),label:c}]});return{activeBatchId:typeof t.activeBatchId=="string"?t.activeBatchId:void 0,groups:l,message:typeof t.message=="string"?t.message:"CSV validation failed.",summary:oi(t.summary)}},di=({initialBatch:s,onBatchCreated:t,onClose:n,onProcessingStarted:r,organizationId:i,organizationName:l})=>{const d=x.useRef(null),[c,g]=x.useState(null),[o,S]=x.useState(s?.source.videoId??""),[a,b]=x.useState(s?.source??null),[h,p]=x.useState(s?.batchId??null),[m,w]=x.useState(null),[j,f]=x.useState(null),[T,F]=x.useState(null),[L,R]=x.useState(null),G=Wa(),ee=Ga(i),X=G.isPending||ee.isPending,q=!!h,E=m?.targetCount??s?.counts.total??0,$=k=>{if(R(null),F(null),!k){g(null);return}if(!k.name.toLowerCase().endsWith(".csv")){g(null),f("Choose a .csv file."),d.current&&(d.current.value="");return}if(k.size===0){g(null),f("The CSV file is empty."),d.current&&(d.current.value="");return}f(null),g(k)},ge=async()=>{const k=o.trim();if(!k&&!c){f("Enter a source video ID and choose a CSV first.");return}if(!k){f("Enter the source video ID first.");return}if(!c){f("Choose a target video CSV first.");return}f(null),F(null),R(null);try{const A=await G.mutateAsync({csvContent:await c.text(),organizationId:i,sourceVideoId:k});p(A.batchId),b(A.source),w(A.summary),t(A.batchId),v.success(`Selection frozen with ${A.summary.targetCount} video(s).`)}catch(A){const P=li(A);if(P.activeBatchId){t(P.activeBatchId),v.error(P.message),n();return}R(P),v.error(P.message)}},Ae=async()=>{if(!(!h||E===0)){F(null);try{const k=await ee.mutateAsync({batchId:h});v.success(`Thumbnail copy started for ${E} video(s); ${k.queuedCount} job(s) queued.`),r(h)}catch(k){F(Es(k,"Failed to start the thumbnail copy batch."))}}};return e.jsx(U,{onOpenChange:k=>!k&&!X&&n(),open:!0,children:e.jsxs(V,{className:"sm:max-w-2xl",children:[e.jsxs(K,{children:[e.jsx(H,{children:"Copy a video thumbnail from CSV"}),e.jsxs(W,{children:["Choose a source video and target videos in ",l,". The source's current GCS thumbnail and the exact CSV selection are frozen before any copy starts."]})]}),e.jsxs("div",{className:"max-h-[65vh] space-y-4 overflow-y-auto pr-1",children:[!q&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx($s,{htmlFor:"organization-thumbnail-source-video",children:"Source video ID"}),e.jsx(ue,{autoComplete:"off",disabled:X,id:"organization-thumbnail-source-video",onChange:k=>{S(k.target.value),f(null),R(null),F(null)},placeholder:"Video UUID",value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set and verify the desired current thumbnail on this video first. The source must be active in this organization and have ready full and small GCS thumbnail files."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx($s,{htmlFor:"organization-thumbnail-csv",children:"Target video CSV"}),e.jsx(ue,{accept:".csv,text/csv",disabled:X,id:"organization-thumbnail-csv",onChange:k=>$(k.target.files?.[0]),ref:d,type:"file"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The CSV must contain only destination video IDs; omit the source video. Invalid, deleted, or out-of-organization rows prevent the batch from being created."})]})]}),j&&e.jsx("p",{className:"text-sm text-destructive",children:j}),L&&e.jsxs("div",{className:"space-y-3 rounded-md border border-destructive/40 bg-destructive/5 p-3",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:L.message}),L.summary&&e.jsx(et,{summary:L.summary}),L.groups.map(k=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-xs font-medium",children:[k.label," (",k.items.length,")"]}),k.items.slice(0,20).map((A,P)=>e.jsx("p",{className:"text-xs",children:A},`${A}-${P}`)),k.items.length>20&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[k.items.length-20," more row(s) not shown."]})]},k.label))]}),q&&e.jsxs(e.Fragment,{children:[a&&e.jsx(ft,{source:a}),m?e.jsx(et,{summary:m}):s&&e.jsx(pt,{batch:s}),e.jsx("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(sn,{className:"mt-0.5 size-4 shrink-0"}),e.jsxs("p",{children:["The source thumbnail and target selection are frozen. Confirming replaces the current thumbnail on exactly"," ",e.jsxs("span",{className:"font-semibold",children:[E," video(s)"]})," ","with the source shown above. Successful copies cannot be rolled back by abandoning the batch."]})]})})]}),T&&e.jsx("p",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:T})]}),e.jsxs(Q,{children:[e.jsx(u,{disabled:X,onClick:n,variant:"ghost",children:q?"Close"
1:"Cancel"}),q?e.jsxs(u,{disabled:!a||E===0||X,onClick:Ae,variant:"destructive",children:[X&&e.jsx(N,{className:"size-4"}),"Copy thumbnail to ",E," video(s)"]}):e.jsxs(u,{disabled:!c||!o.trim()||X,onClick:ge,children:[G.isPending&&e.jsx(N,{className:"size-4"}),"Validate and freeze selection"]})]})]})})},ci=({body:s})=>C.post("/v1/billing/admin/reset-checkout-rate-limit",s).then(({data:t})=>t),ui=({organizationId:s})=>{const{t}=Ke("common"),[n,r]=x.useState(!1),i=_({mutationFn:ci,onError:c=>v.error(c.response?.data?.message||t("error.unknown")),onSuccess:()=>{v.success("Stripe rate limits reset successfully"),r(!1)}}),l=()=>{i.mutate({body:{organizationId:s}})},d=i.isPending;return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{size:"sm",variant:"outline",children:"Reset Stripe rate limits"})}),e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsx(H,{children:"Reset Stripe rate limits"}),e.jsx(W,{children:"Allow the user to create checkout sessions for creating a subscription or updating payment method."})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:d,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:d,onClick:l,type:"button",children:[d&&e.jsx(N,{}),"Reset"]})]})]})]})},mi=async s=>{const{data:t}=await C.delete(`/v1/admin/retry-failed-transcripts/${s}`);return t},hi=()=>_({mutationFn:mi}),xi="retry-failed-transcripts-latest",pi=async s=>{const{data:t}=await C.get(`/v1/admin/retry-failed-transcripts/org/${s}`);return t},fi=s=>Z({queryKey:[xi,s],queryFn:()=>pi(s)}),gt="retry-failed-transcripts",gi=async s=>{try{const{data:t}=await C.get(`/v1/admin/retry-failed-transcripts/${s}`);return t}catch(t){if(t.response?.status===404)return null;throw t}},ji=s=>Z({queryKey:[gt,s],queryFn:()=>gi(s),enabled:!!s,refetchInterval:t=>{const n=t.state.data;return n===null?!1:!n||n.state==="scanning"?2e3:n.progress.completed+n.progress.failed<n.candidateCount?5e3:!1}}),bi=async s=>{const{data:t}=await C.post("/v1/admin/retry-failed-transcripts",{organizationId:s.organizationId});return t},vi=()=>_({mutationFn:bi}),yi={enqueued:"Re-enqueued",in_flight:"Skipped: already in flight",duplicate:"Skipped: duplicate",error:"Errored"},Si=["enqueued","in_flight","duplicate","error"],tt=({batch:s})=>e.jsx("div",{className:"border rounded-lg overflow-hidden max-w-xl",children:e.jsxs(me,{children:[e.jsx(he,{children:e.jsxs(O,{children:[e.jsx(B,{children:"Outcome"}),e.jsx(B,{className:"text-right",children:"Videos"})]})}),e.jsx(xe,{children:Si.map(t=>e.jsxs(O,{children:[e.jsx(I,{children:yi[t]}),e.jsx(I,{className:"text-right font-mono",children:s.counts[t]??0})]},t))})]})}),Ni=({organizationId:s})=>{const[t,n]=x.useState(null),r=Y(),i=fi(s),l=t??i.data?.batchId??null,d=ji(l),c=vi(),g=hi(),o=d.data??null,S=o?o.progress.completed+o.progress.failed:0,a=i.isPending||!!l&&d.isPending,b=!a&&(!l||o===null),h=!!o&&o.state==="scanning",p=!!o&&o.state==="cancelled",m=!!o&&o.state==="failed",w=!!o&&(o.state==="done"||p||m)&&o.candidateCount>0&&S<o.candidateCount,j=!!o&&o.state==="done"&&(o.candidateCount===0||S>=o.candidateCount),f=o&&o.candidateCount>0?Math.round(S/o.candidateCount*100):0,T=()=>{c.mutate({organizationId:s},{onSuccess:R=>{n(R.batchId),v.success("Retry started")},onError:()=>v.error("Failed to start retry")})},F=()=>{l&&g.mutate(l,{onSuccess:()=>{r.invalidateQueries({queryKey:[gt,l]}),v.success("Retry cancelled — already-enqueued transcriptions finish normally")},onError:()=>v.error("Failed to cancel retry")})},L=R=>e.jsxs(u,{disabled:c.isPending,onClick:T,variant:b?"default":"ghost",children:[c.isPending?e.jsx(N,{className:"size-4 mr-2"}):e.jsx(Ue,{className:"w-4 h-4 mr-2"}),R]});return e.jsx("section",{className:"flex flex-col w-full gap-4",children:e.jsxs(we,{children:[e.jsxs(Ce,{children:[e.jsxs(ke,{className:"flex items-center gap-2",children:[(h||w)&&e.jsx(N,{className:"size-4"}),"Retry failed transcripts"]}),e.jsx(Re,{children:"Re-run every video in this organization whose auto transcript failed (both stalled and errored jobs), on the AssemblyAI lane. Only failed auto captions are touched — completed and user-uploaded captions are left alone."})]}),e.jsxs(Ie,{className:"space-y-4",children:[a&&e.jsx(N,{className:"size-4"}),b&&e.jsx("div",{children:L("Retry failed transcripts")}),h&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Scanning and re-enqueuing… page ",o.pageIndex," —"," ",o.
1counts.enqueued," re-enqueued so far"]}),e.jsx(tt,{batch:o})]}),j&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm",children:["Retry complete —"," ",e.jsx("span",{className:"font-medium",children:o.counts.enqueued})," ","re-enqueued",o.progress.completed>0&&e.jsxs(e.Fragment,{children:[","," ",e.jsx("span",{className:"font-medium",children:o.progress.completed})," ","transcribed"]}),o.progress.failed>0&&e.jsxs("span",{className:"text-red-600",children:[", ",o.progress.failed," failed again"]}),"."]}),e.jsx(tt,{batch:o}),e.jsx("div",{children:L("Retry again")})]}),p&&e.jsx("div",{className:"p-3 bg-amber-500/10 rounded text-sm text-amber-600",children:"Cancelled — already-enqueued transcriptions finish normally."}),m&&e.jsxs("div",{className:"p-3 bg-red-500/10 rounded text-sm text-red-600",children:["Retry failed: ",o.error??"Unknown error"]}),w&&e.jsxs("div",{className:"space-y-2 max-w-xl",children:[e.jsx(We,{className:"h-2",value:f}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.progress.completed," completed ·"," ",o.progress.processing," processing",o.progress.failed>0&&e.jsxs("span",{className:"text-red-600",children:[" ","· ",o.progress.failed," failed"]})," ","/ ",o.candidateCount," re-enqueued"]})]}),(p||m)&&!w&&e.jsx("div",{children:L("Retry again")}),h&&e.jsxs(u,{disabled:g.isPending,onClick:F,size:"sm",variant:"outline",children:[g.isPending?e.jsx(N,{className:"size-4 mr-2"}):e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Cancel retry"]})]})]})})},wi=({organizationId:s})=>C.post("/v1/billing/admin/sync-stripe",{organizationId:s}).then(({data:t})=>t),Ci=(s={})=>{const t=Y();return _({mutationFn:wi,onError:s.onError,onSuccess:()=>{is({queryClient:t}),as({queryClient:t}),s.onSuccess?.()}})},ki=({organizationId:s})=>{const{t}=Ke("common"),[n,r]=x.useState(!1),i=Ci({onError:()=>v.error(t("error.unknown")),onSuccess:()=>{v.success("Stripe synced successfully"),r(!1)}}),l=()=>{i.mutate({organizationId:s})},d=i.isPending;return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{size:"sm",variant:"outline",children:"Sync Stripe"})}),e.jsxs(V,{children:[e.jsxs(K,{children:[e.jsx(H,{children:"Sync Stripe Subscription"}),e.jsx(W,{children:"This will overwrite our database with data from Stripe."})]}),e.jsx("span",{className:"text-sm",children:"* This cannot be undone."}),e.jsx("span",{className:"text-sm",children:"* Any custom limits or seats must be reset separately."}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:d,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:d,onClick:l,type:"button",variant:"destructive",children:[d&&e.jsx(N,{}),"Confirm"]})]})]})]})},Ri=({body:s})=>C.post("/v1/billing/admin/appsumo-license/transfer",s).then(({data:t})=>t),Ii=(s={})=>{const t=Y();return _({mutationFn:Ri,onError:s.onError,onSuccess:n=>{is({queryClient:t}),as({queryClient:t}),s.onSuccess?.(n)}})},Ei=ye({confirmationEmail:Be().trim().toLowerCase().email("Invalid email"),destinationUserEmail:Be().trim().toLowerCase().email("Invalid email"),reason:Be().trim().min(1,"Required").max(500,"Maximum 500 characters")}).refine(({confirmationEmail:s,destinationUserEmail:t})=>s===t,{message:"Email must match the destination user",path:["confirmationEmail"]}),Bi=({organizationId:s,organizationName:t,ownerEmail:n,plan:r})=>{const{t:i}=Ke(["common","billing"]),[l,d]=x.useState(!1),{formState:{errors:c},handleSubmit:g,register:o,reset:S}=Se({defaultValues:{confirmationEmail:"",destinationUserEmail:"",reason:""},resolver:Ne(Ei)}),a=Ii({onError:p=>v.error(p.response?.data?.message||i("error.unknown")),onSuccess:()=>{v.success("AppSumo license transferred successfully"),d(!1),S()}}),b=({destinationUserEmail:p,reason:m})=>{a.mutate({body:{destinationUserEmail:p,reason:m,sourceOrganizationId:s}})},h=a.isPending;return e.jsxs(U,{open:l,onOpenChange:p=>{!p&&h||(d(p),p||(S(),a.reset()))},children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{size:"sm",variant:"outline",children:"Transfer AppSumo License"})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:g(b),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Transfer AppSumo License"}),e.jsxs(W,{children:["Move ",i(`plan.name.${r}`,{ns:"billing"})," from"," ",n||t," to another user's organization."]})]}),e.jsxs(Qt,{variant:"destructive",children:[e.jsx(Gt,{children:"This changes billing access immediately"}),e.jsxs(Yt,{children:[e.jsxs("p",{children:[t," (",s,") will move to Free. Its custom storage limits and seats will be reset."]}),e.jsx("p",{children:"The destination user must own exactly one organization and that organization must be on the Free plan."})]})]}),e.jsxs(te,{"data-invalid":!!c.destinationUserEmail?.message,children:[e.jsx(ne,{htmlFor:"destinationUserEmail",children:"Destination user email"}),e.jsx(ue,{...o("destinationUserEmail"),autoComplete:"off",autoFocus:!0,"aria-describedby":c.destinationUserEmail?"destinationUserEmail-error":void 0,"aria-invalid":!!c.destinationUserEmail,disabled:h,id:"destinationUserEmail",required:!0,type:"email"}),c.destinationUserEmail?.message&&e.jsx(oe,{id:"destinationUserEmail-error",children:c.destinationUserEmail.message})]}),e.jsxs(te,{"data-invalid":!!c.reason?.message,children:[e.jsx(ne,{htmlFor:"reason",children:"Reason or support ticket"}),e.jsx(ue,{...o("reason"),autoComplete:"off","aria-describedby":c.reason?"reason-error":void 0,"aria-invalid":!!c.reason,disabled:h,id:"reason",maxLength:500,required:!0,type:"text"}),c.reason?.message&&e.jsx(oe,{id:"reason-error",children:c.reason.message})]}),e.jsxs(te,{"data-invalid":!!c.confirmationEmail?.message,children:[e.jsx(ne,{htmlFor:"confirmationEmail",children:"Re-enter the destination email to confirm"}),e.jsx(ue,{...o("confirmationEmail"),autoComplete:"off","aria-describedby":"
1confirmationEmail-help confirmationEmail-error","aria-invalid":!!c.confirmationEmail,disabled:h,id:"confirmationEmail",required:!0,type:"email"}),e.jsx(zt,{id:"confirmationEmail-help",children:"This action cannot be undone here."}),c.confirmationEmail?.message&&e.jsx(oe,{id:"confirmationEmail-error",children:c.confirmationEmail.message})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:h,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:h,type:"submit",variant:"destructive",children:[h&&e.jsx(N,{}),"Transfer license"]})]})]})})]})},Ti=ye({bandwidthOverageMills:Be()}),Ai=({currentBandwidthOverageMills:s,organizationId:t})=>{const[n,r]=x.useState(!1),{formState:{errors:i},handleSubmit:l,register:d,reset:c,watch:g}=Se({defaultValues:{bandwidthOverageMills:s.toString()},resolver:Ne(Ti)}),o=fe({onError:()=>{v.error("Failed to update bandwidth overage.")},onSuccess:()=>{v.success("Bandwidth overage updated successfully."),r(!1)}});x.useEffect(()=>{n&&c({bandwidthOverageMills:s.toString()})},[s,n,c]);const S=()=>{o.mutate({body:{bandwidthOverageMills:null},organizationId:t})},a=({bandwidthOverageMills:p})=>{o.mutate({body:{bandwidthOverageMills:Number(p)},organizationId:t})},b=o.isPending,h=g("bandwidthOverageMills");return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{variant:"ghost",size:"sm",children:e.jsx(Me,{className:"size-4"})})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:l(a),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Update Bandwidth Overage"}),e.jsx(W,{children:"How much each GB is charged over the limit"})]}),e.jsxs(te,{"data-invalid":!!i.bandwidthOverageMills?.message,children:[e.jsx(ne,{htmlFor:"bandwidthOverageMills",children:"Bandwidth Overage in Mills"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ue,{...d("bandwidthOverageMills"),autoComplete:"off",disabled:b,id:"bandwidthOverageMills",required:!0,type:"text"}),e.jsx("span",{children:bs({mills:Number(h)})})]}),i.bandwidthOverageMills?.message&&e.jsx(oe,{children:i.bandwidthOverageMills.message})]}),e.jsxs(Q,{className:"sm:justify-between",children:[e.jsxs(u,{disabled:b,onClick:S,type:"button",variant:"destructive",children:[b&&e.jsx(N,{}),"Reset"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{asChild:!0,disabled:b,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:b,type:"submit",children:[b&&e.jsx(N,{}),"Confirm"]})]})]})]})})]})},Fi=ye({name:Be().trim().min(1).max(255)}),Oi=({currentName:s,organizationId:t})=>{const[n,r]=x.useState(!1),{formState:{errors:i},handleSubmit:l,register:d,reset:c,watch:g}=Se({defaultValues:{name:s},resolver:Ne(Fi)}),o=fe({onError:()=>{v.error("Failed to update organization name.")},onSuccess:()=>{v.success("Organization name updated successfully."),r(!1)}});x.useEffect(()=>{n&&c({name:s})},[n,c,s]);const S=({name:p})=>{o.mutate({body:{name:p},organizationId:t})},a=o.isPending,h=(g("name")??"").trim()===s.trim();return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{variant:"ghost",size:"sm",children:e.jsx(Me,{className:"size-4"})})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:l(S),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Update Organization Name"}),e.jsx(W,{children:"Update the workspace name shown to the user. The organization slug will not change."})]}),e.jsxs(te,{"data-invalid":!!i.name?.message,children:[e.jsx(ne,{htmlFor:"organizationName",children:"New name"}),e.jsx(ue,{...d("name"),autoComplete:"off",autoFocus:!0,disabled:a,id:"organizationName",required:!0,type:"text"}),i.name?.message&&e.jsx(oe,{children:i.name.message})]}),e.jsxs(Q,{children:[e.jsx(J,{asChild:!0,disabled:a,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:a||h,type:"submit",children:[a&&e.jsx(N,{}),"Confirm"]})]})]})})]})},Li=ye({seats:kt().positive()}),zi=({currentSeats:s,organizationId:t})=>{const[n,r]=x.useState(!1),{formState:{errors:i},handleSubmit:l,register:d,reset:c}=Se({defaultValues:{seats:s},resolver:Ne(Li)}),g=fe({onError:()=>{v.error("Failed to update number of seats.")},onSuccess:()=>{v.success("Number of seats updated successfully."),r(!1)}});x.useEffect(()=>{n&&c({seats:s})},[s,n,c]);const o=()=>{g.mutate({organizationId:t,body:{seats:null}})},S=({seats:b})=>{g.mutate({body:{seats:b},organizationId:t})},a=g.isPending;return e.jsxs(U,{open:n,onOpenChange:r,children:[e.jsx(le,{asChild:!0,children:e.jsx(u,{variant:"ghost",size:"sm",children:e.jsx(Me,{className:"size-4"})})}),e.jsx(V,{children:e.jsxs("form",{className:"flex flex-col w-full gap-4",onSubmit:l(S),children:[e.jsxs(K,{children:[e.jsx(H,{children:"Update Number of Seats"}),e.jsx(W,{children:"This number includes the organization owner."})]}),e.jsxs(te,{"data-invalid":!!i.seats?.message,children:[e.jsx(ne,{htmlFor:"seats",children:"Seats"}),e.jsx(ue,{...d("seats"),autoComplete:"off",autoFocus:!0,disabled:a,id:"seats",required:!0,type:"text"}),i.seats?.message&&e.jsx(oe,{children:i.seats.message})]}),e.jsxs(Q,{className:"sm:justify-between",children:[e.jsxs(u,{disabled:a,onClick:o,type:"button",variant:"destructive",children:[a&&e.jsx(N,{}),"Reset"]}),e.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[e.jsx(J,{asChild:!0,disabled:a,children:e.jsx(u,{variant:"ghost",children:"Cancel"})}),e.jsxs(u,{disabled:a,type:"submit",children:[a&&e.jsx(N,{}),"Confirm"]})]})]})]})})]})},_i=()=>{const{organizationId:s}=Rt({from:"/_withUser/_admin/admin/organizations/$organizationId"}),t=an({organizationId:s}
1),[n,r]=x.useState(!1);return e.jsx(Ot,{links:[e.jsx(ve,{to:"/admin/organizations",children:"Organizations"},"organizations"),e.jsx("span",{children:s},"organization")],children:It(t).with({status:"pending"},()=>e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(N,{})})).with({status:"success",data:Et.not(null)},({data:i})=>e.jsxs("div",{className:"flex flex-col w-full",children:[e.jsxs("div",{className:"flex w-full px-4 pt-4 gap-12",children:[e.jsxs("div",{className:"flex flex-col w-full max-w-2xl gap-0.5",children:[e.jsx(La,{...i}),e.jsx(ie,{action:e.jsx(Ai,{currentBandwidthOverageMills:i.subscription.bandwidthOverageMills??Ps,organizationId:i.id}),field:"Bandwidth Overage",value:i.subscription.bandwidthOverageMills!==null?bs({mills:i.subscription.bandwidthOverageMills}):`${bs({mills:Ps})} (default)`}),e.jsx(ie,{field:"Created at",value:ze({date:i.createdAt})}),e.jsx(ie,{action:e.jsx(un,{currentFreeTrialEndDatetime:i.subscription.freeTrialEndDatetime?ds(i.subscription.freeTrialEndDatetime):null,organizationId:i.id}),field:"Free trial end",value:i.subscription.plan===$e.Free&&i.subscription.freeTrialEndDatetime?ze({date:i.subscription.freeTrialEndDatetime}):null}),e.jsx(ie,{action:e.jsx($n,{directLinksOverrideEnabled:i.directLinksOverrideEnabled,organizationId:i.id}),field:"Direct links override",value:i.directLinksOverrideEnabled?"On — direct links regardless of plan":"Off — Premium, Premium trial or custom plan only"}),e.jsx(ie,{action:e.jsx(Jn,{ga4IntegrationEnabled:i.ga4IntegrationEnabled,organizationId:i.id}),field:"GA4 integration",value:i.ga4IntegrationEnabled?`On — ${i.gaMeasurementId??"no measurement ID set yet"}`:"Off"}),e.jsx(ie,{action:e.jsx(Oi,{currentName:i.name,organizationId:i.id}),field:"Name",value:i.name}),e.jsx(ie,{field:"Replacement URLs",value:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:`${_s.VITE_WEB_URL}/ow/${i.slug}/vimeoId`}),e.jsx("span",{children:`${_s.VITE_WEB_URL}/oe/${i.slug}/video/vimeoId`})]})}),e.jsx(ie,{action:e.jsx(zi,{currentSeats:i.seats,organizationId:i.id}),field:"Seats",value:i.seats}),e.jsx(ie,{field:"Slug",value:i.slug}),e.jsx(Pa,{...i}),e.jsx(ie,{field:"Subscription",value:e.jsxs("div",{className:"flex items-center gap-2",children:[i.subscription.plan===$e.Pro?e.jsxs(e.Fragment,{children:[e.jsx(Bt,{height:14,width:29.27}),e.jsxs("span",{children:["(",i.subscription.billingCycle,")"]})]}):i.subscription.plan===$e.Premium?e.jsxs(e.Fragment,{children:[e.jsx(Tt,{height:14}),e.jsxs("span",{children:["(",i.subscription.billingCycle,")"]})]}):e.jsx("span",{children:i.subscription.plan}),e.jsx(u,{asChild:!0,size:"sm",variant:"ghost",children:e.jsx("a",{className:"flex items-center justify-center",href:`https://dashboard.stripe.com/customers/${i.subscription.stripeCustomerId}`,rel:"noopener noreferrer",target:"_blank",children:e.jsx(Xt,{className:"size-4"})})})]})}),i.subscription.billingAnchor&&e.jsx(ie,{field:"Subscription status",value:i.subscription.endDatetime?e.jsx("span",{className:"text-destructive",children:`Cancels - ${ze({date:i.subscription.endDatetime})}`}):`Renews - ${ze({date:qt({billingAnchor:i.subscription.billingAnchor,billingCycle:i.subscription.billingCycle,dateNow:new Date}).toISOString()})}`}),e.jsx(ie,{action:e.jsx(Rn,{currentDefaultGenerateTranscripts:i.defaultGenerateTranscripts,organizationId:i.id}),field:"Transcript auto-generate",value:i.defaultGenerateTranscripts?"On — future uploads are auto-captioned":"Off"})]}),e.jsxs("div",{className:"flex flex-col gap-4 items-start",children:[e.jsx(ki,{organizationId:s}),e.jsx(kn,{organizationId:s}),(i.subscription.plan===$e.AppSumoTier1||i.subscription.plan===$e.AppSumoTier2)&&e.jsx(Bi,{organizationId:i.id,organizationName:i.name,ownerEmail:i.owner?.email,plan:i.subscription.plan}),e.jsx(ui,{organizationId:s}),e.jsx(u,{onClick:()=>r(!0),size:"sm",variant:"outline",children:"Moderate all videos"}),n&&e.jsx(ln,{onClose:()=>r(!1),organizationId:i.id,organizationName:i.name})]})]}),e.jsxs(At,{defaultValue:"videos",className:"w-full p-4",children:[e.jsxs(Ft,{children:[e.jsxs(Ye,{value:"videos",children:["Videos (",i.videosCount,")"]}),e.jsxs(Ye,{value:"members",children:["Members (",i.membersCount,"/",i.seats,")"]}),e.jsx(Ye,{value:"video-actions",children:"Video actions"}),e.jsx(Ye,{value:"api-tokens",children:"API tokens"})]}),e.jsx(Xe,{value:"videos",children:e.jsx(Mt,{organizationId:i.id})}),e.jsx(Xe,{value:"members",children:e.jsx(Aa,{organizationId:i.id})}),e.jsxs(Xe,{value:"video-actions",className:"flex flex-col gap-4 py-4",children:[e.jsx(qn,{organizationId:i.id}),e.jsx(Vt,{organizationId:i.id}),e.jsx(Ni,{organizationId:i.id}),e.jsx(ba,{organizationId:i.id}),e.jsx(ma,{organizationId:i.id}),e.jsx(Zn,{organizationId:i.id}),e.jsx(Ia,{organizationId:i.id}),e.jsx(Kt,{organizationId:i.id}),e.jsx(ii,{organizationId:i.id,organizationName:i.name})]}),e.jsx(Xe,{value:"api-tokens",children:e.jsx(Sn,{organizationId:i.id,organizationName:i.name})})]})]})).otherwise(()=>e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Organization not found."})}))})},ie=({action:s,field:t,value:n})=>e.jsxs("div",{className:"flex items-center justify-between gap-4 min-h-8",children:[e.jsxs("span",{className:"flex items-center text-sm gap-1",children:[e.jsxs("span",{className:"min-w-42",children:[t,":"]}),e.jsx("span",{className:"font-medium",children:n})]}),s]}),Ro=_i;export{Ro as component};

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.