1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[78056],{24752:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(95155),s=n(12115),i=n(6415),r=n(90568);let l=s.forwardRef(({className:e,...t},n)=>(0,a.jsxs)(i.bL,{ref:n,className:(0,r.cn)("relative flex w-full touch-none select-none items-center",e),...t,children:[(0,a.jsx)(i.CC,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-gray-100",children:(0,a.jsx)(i.Q6,{className:"absolute h-full bg-[#2563FF]"})}),(0,a.jsx)(i.zi,{className:"block h-5 w-5 rounded-full border border-gray-200 bg-white shadow transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF] disabled:pointer-events-none disabled:opacity-50 hover:scale-110 active:scale-95"})]}));l.displayName=i.bL.displayName},31352:(e,t,n)=>{n.d(t,{P:()=>o,d:()=>l});var a=n(95155),s=n(45263),i=n(67401),r=n(90568);function l({"aria-label":e,children:t,className:n,testId:s}){return(0,a.jsx)("div",{"aria-label":e,className:(0,r.cn)("divide-y divide-[#E2E8F0] border-y border-[#E2E8F0] bg-white",n),"data-testid":s,children:t})}function o({className:e,description:t,disabled:n,label:l,role:d,selected:c,type:u="button",...p}){let m=c?s.A:i.A;return(0,a.jsxs)("button",{...p,"aria-checked":"radio"===d?c:void 0,"aria-pressed":"radio"===d?void 0:c,className:(0,r.cn)("group flex min-h-20 w-full min-w-0 items-start gap-3 whitespace-normal px-4 py-3.5 text-left outline-hidden transition-colors","hover:bg-[#F8FAFC] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#2563EB]",c&&"bg-[#EEF3FF] text-[#1D4ED8] hover:bg-[#E8EFFF]",n&&"cursor-not-allowed opacity-45 hover:bg-white",c&&n&&"hover:bg-[#EEF3FF]",e),"data-selected":c?"true":"false",disabled:n,role:d,type:u,children:[(0,a.jsx)(m,{"aria-hidden":"true",className:(0,r.cn)("mt-0.5 h-5 w-5 shrink-0 text-[#A8B3C3]",c&&"text-[#2563EB]"),strokeWidth:c?2.25:1.75}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:(0,r.cn)("block break-words text-sm font-semibold leading-5 text-[#0F172A]",c&&"text-[#1D4ED8]"),children:l}),(0,a.jsx)("span",{className:(0,r.cn)("mt-0.5 block break-words text-[13px] leading-5 text-[#64748B]",c&&"text-[#1D4ED8]"),children:t})]})]})}},58917:(e,t,n)=>{n.d(t,{HT:()=>t_});var a=n(95155),s=n(12115),i=n(5068),r=n(78868),l=n(37121),o=n(61297),d=n(15872),c=n(72682),u=n(39506),p=n(36443),m=n(84470),h=n(66645),g=n(28109),x=n(58970),v=n(51160),f=n(59563),b=n(8481),y=n(22361);let w=["subscription","payments","derived"];var j=n(72811),C=n(13271),_=n(5656);function k(e){if(0===e.length)return null;let t=[];for(let n of e){let e=n.evidence.customerName;if(t.includes(e)||t.push(e),2===t.length)break}let n=e[0];return{customerNames:t,adjustmentLine:(0,y.EE)({assessment:n.assessment,periodKeys:n.evidence.periodKeys})[0]??null}}function N(e){let t={high:0,medium:0,low:0};for(let n of e)t[(0,f.X_)(n.assessment.confidence)]+=1;return t}function R(e){return 0===e.length?0:e.filter(e=>"numeric_adjustment"===(0,j.JF)(e)&&"high"===(0,f.X_)(e.assessment.confidence)).length/e.length}var S=n(78744),A=n(89293),F=n(92571),M=n(92298),E=n(64577),B=n(25182);function K({receipt:e}){return"failure"!==e.tone?null:(0,a.jsx)("p",{className:"mt-1.5 text-[10.5px] leading-4 text-qb-red",role:"alert","data-tone":e.tone,"data-testid":"cleaning-guided-step-outcome",children:e.message})}function q(e){return"keep_as_reported"===(0,j.JF)(e)}function T({steps:e,activeStep:t,focusedRowKeys:n,recordsByRowKey:s,isRecordApplied:i,blockedRows:r,protectedRecords:l,protectedRowKeys:o,outcome:d,busyScopeKey:c,busyOperation:u,appliedRecords:p,remainingRecords:m,remainingSafeRecords:h,remainingProposedRecords:g,consolidatedGroupCount:x,showAllRows:v,showStepRows:f,applyScope:b,applyKeepScope:y,undoScope:w,advanceInformationalStep:_}){var k;if(0===e.length)return null;let N=(k={consolidatedGroupCount:x}).consolidatedGroupCount<=0?null:`${k.consolidatedGroupCount.toLocaleString()} duplicate customer group${1===k.consolidatedGroupCount?"":"s"} consolidated automatically.`,R=d?.scopeKey==="all"?d:null,S=p.length>0||l.length>0?"Apply remaining":"Apply all";return(0,a.jsxs)("section",{className:"px-2","aria-label":"Cleaning review sections","data-testid":"cleaning-guided-review",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsx)("h3",{className:"min-w-0 text-[12px] font-semibold text-[#0E1624]",children:"Review suggestions"}),(0,a.jsx)("button",{type:"button","data-testid":"cleaning-guided-review-show-all",onClick:v,className:"inline-flex h-7 shrink-0 items-center rounded-md px-2 text-[10.5px] font-semibold text-[#2563FF] hover:bg-[#F1F5F9] focus-visible:outline-hidden focu
1s-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:"Show all rows"})]}),(0,a.jsxs)("div",{className:"mt-2 flex items-center gap-2 border-y border-[#E6EAF0] py-2",children:[(0,a.jsxs)("button",{type:"button","data-testid":"cleaning-guided-review-apply-all","aria-busy":"all"===c&&"apply"===u,disabled:0===m.length||null!==c,onClick:()=>b({scopeKey:"all",safeRecords:h,proposedRecords:g,attemptedCount:m.length}),className:"inline-flex h-8 flex-1 items-center justify-center gap-1.5 rounded-md bg-[#2563FF] px-2.5 text-[11.5px] font-semibold text-white hover:bg-[#1D4ED8] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:cursor-not-allowed disabled:bg-[#D8DEE8] disabled:text-[#7A8798]",children:["all"===c&&"apply"===u?(0,a.jsx)(F.A,{className:"h-3.5 w-3.5 motion-safe:animate-spin","aria-hidden":!0}):null,"all"===c&&"apply"===u?"Applyingâ¦":S," ",m.length.toLocaleString()]}),(0,a.jsxs)("button",{type:"button","data-testid":"cleaning-guided-review-undo-all","aria-busy":"all"===c&&"undo"===u,disabled:0===p.length||null!==c,onClick:()=>w("all",p),className:"inline-flex h-8 flex-1 items-center justify-center gap-1.5 rounded-md border border-[#D8DEE8] bg-white px-2.5 text-[11.5px] font-semibold text-[#0E1624] hover:bg-[#F8FAFC] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:cursor-not-allowed disabled:text-[#A0A9B8]",children:["all"===c&&"undo"===u?(0,a.jsx)(F.A,{className:"h-3.5 w-3.5 motion-safe:animate-spin","aria-hidden":!0}):(0,a.jsx)(M.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),"all"===c&&"undo"===u?"Undoingâ¦":"Undo all"," ",p.length.toLocaleString()]})]}),R?(0,a.jsx)(K,{receipt:R.receipt}):null,l.length>0?(0,a.jsxs)("p",{className:"mt-1 text-[10.5px] leading-4 text-[#B45309]",role:"status","data-testid":"cleaning-guided-protected-manual-edits",children:[l.length.toLocaleString()," row",1===l.length?" kept its manual edit":"s kept their manual edits",". The recommended numbers were not applied to"," ",1===l.length?"that row":"those rows","."]}):null,N?(0,a.jsx)("p",{className:"mt-1 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-guided-review-consolidation",children:N}):null,(0,a.jsx)("ol",{className:"mt-2 divide-y divide-[#E6EAF0] border-b border-[#E6EAF0]",children:e.map((l,p)=>{var m;let h=l.stepKey===t?.stepKey,g=function(e){let{step:t,blockedReasonByRowKey:n}=e,a=e.protectedRowKeys??new Set,s=e=>n.has(e.evidence.rowKey)||a.has(e.evidence.rowKey),i=t.safeRecords.filter(e=>!s(e)),r=t.proposedRecords.filter(e=>!s(e)),l=new Map;for(let e of[...t.safeRecords,...t.proposedRecords]){let t=n.get(e.evidence.rowKey);t&&l.set(t,(l.get(t)??0)+1)}let o=[...l.entries()].sort(([e,t],[n,a])=>a-t||e.localeCompare(n)).map(([e,t])=>({reason:e,rowCount:t,message:`${t.toLocaleString()} row${1===t?"":"s"} need${1===t?"s":""} a closer look â ${(0,C.DZ)(e)}.`}));return{safeRecords:i,proposedRecords:r,remainingCount:i.length+r.length,blockedCount:[...t.safeRecords,...t.proposedRecords].filter(e=>n.has(e.evidence.rowKey)&&!a.has(e.evidence.rowKey)).length,protectedCount:[...t.safeRecords,...t.proposedRecords].filter(e=>a.has(e.evidence.rowKey)).length,blockedGroups:o}}({step:l,blockedReasonByRowKey:r,protectedRowKeys:o}),x=l.rowKeys.map(e=>s.get(e)).filter(e=>{let t;return!!(e&&i(e)&&("adjustments"===l.kind?"numeric_adjustment"===(t=(0,j.JF)(e))||"proposed_adjustment"===t:"keeps"===l.kind&&q(e)))}),k="keeps"===l.kind?l.rowKeys.map(e=>s.get(e)).filter(e=>!!(e&&q(e)&&!i(e))):[],N=`step:${l.stepKey}`,R=d?.scopeKey===N?d:null,S=(m=l.rowKeys,null!==n&&n.size===m.length&&m.every(e=>n.has(e)));return h?(0,a.jsxs)("li",{className:"py-2.5","data-testid":`cleaning-guided-step-${l.stepKey}`,"data-state":"active",children:[(0,a.jsxs)("div",{className:"flex items-baseline gap-2 px-1",children:[(0,a.jsx)("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-[#94A3B8]",children:p+1}),(0,a.jsx)("h4",{className:"min-w-0 flex-1 text-[11.5px] font-semibold text-[#0E1624]",children:l.title})]}),(0,a.jsxs)("div",{className:"mt-1.5 pl-7 pr-1",children:[(0,a.jsx)("p",{className:"text-[11px] leading-[17px] text-[#334155]","data-testid":"cleaning-guided-step-rationale",children:l.rationale}),g.blockedGroups.length>0?(0,a.jsx)("ul",{className:"mt-1 space-y-0.5 text-[10.5px] leading-4 text-[#B45309]","data-testid":"cleaning-guided-step-blocked",children:g.blockedGroups.map(e=>(0,a.jsx)("li",{children:e.message},e.reason))}):null,(0,a.jsxs)("div",{className:"mt-2 flex flex-wrap items-center justify-end gap-1.5",children:[(0,a.jsxs)("button",{type:"button","data-testid":"cleaning-guided-step-show-rows",onClick:()=>S?v():f(l),className:"inline-flex h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-semibold text-[#2563FF] hover:bg-[#F1F5F9] focus-visible:outline-hidden focu
1s-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:[(0,a.jsx)(B.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),S?"Show all rows":"Show rows"]}),x.length>0?(0,a.jsxs)("button",{type:"button","data-testid":"cleaning-guided-step-undo","aria-busy":c===N&&"undo"===u,disabled:null!==c,onClick:()=>w(N,x,"keeps"===l.kind?"keeps":"adjustments"),className:"inline-flex h-7 items-center gap-1 rounded-md border border-[#D8DEE8] bg-white px-2 text-[10.5px] font-semibold text-[#0E1624] hover:bg-[#F8FAFC] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:text-[#A0A9B8]",children:[c===N&&"undo"===u?(0,a.jsx)(F.A,{className:"h-3.5 w-3.5 motion-safe:animate-spin","aria-hidden":!0}):(0,a.jsx)(M.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),c===N&&"undo"===u?"Undoingâ¦":"Undo all"," ",x.length.toLocaleString()]}):null,"adjustments"===l.kind&&g.remainingCount>0?(0,a.jsxs)("button",{type:"button","data-testid":"cleaning-guided-step-apply","aria-busy":c===N&&"apply"===u,"data-proposed-count":g.proposedRecords.length,disabled:null!==c,onClick:()=>b({scopeKey:N,safeRecords:g.safeRecords,proposedRecords:g.proposedRecords,attemptedCount:g.remainingCount,nextStep:e[p+1]}),className:"inline-flex h-7 items-center gap-1.5 rounded-md bg-[#2563FF] px-2.5 text-[11px] font-semibold text-white hover:bg-[#1D4ED8] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:bg-[#D8DEE8] disabled:text-[#7A8798]",children:[c===N&&"apply"===u?(0,a.jsx)(F.A,{className:"h-3.5 w-3.5 motion-safe:animate-spin","aria-hidden":!0}):null,c===N&&"apply"===u?`Applying ${g.remainingCount.toLocaleString()}â¦`:function(e,t=0){let n=e.counts.safe+e.counts.proposed-t;return e.counts.alreadyApplied>0||t>0?`Apply remaining ${n.toLocaleString()}`:`Apply all ${n.toLocaleString()}`}(l,g.blockedCount+g.protectedCount)]}):null,"keeps"===l.kind&&k.length>0?(0,a.jsxs)("button",{type:"button","data-testid":"cleaning-guided-step-keep","aria-busy":c===N&&"apply"===u,disabled:null!==c,onClick:()=>y({scopeKey:N,records:k,nextStep:e[p+1]}),className:"inline-flex h-7 items-center gap-1.5 rounded-md bg-[#2563FF] px-2.5 text-[11px] font-semibold text-white hover:bg-[#1D4ED8] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:bg-[#D8DEE8] disabled:text-[#7A8798]",children:[c===N&&"apply"===u?(0,a.jsx)(F.A,{className:"h-3.5 w-3.5 motion-safe:animate-spin","aria-hidden":!0}):null,c===N&&"apply"===u?`Saving ${k.length.toLocaleString()}â¦`:x.length>0?`Keep remaining ${k.length.toLocaleString()}`:`Keep all ${k.length.toLocaleString()}`]}):null,"manual_review"===l.kind||"adjustments"===l.kind&&0===g.remainingCount&&0===g.blockedCount&&g.protectedCount>0||"keeps"===l.kind&&0===k.length?(0,a.jsx)("button",{type:"button","data-testid":"cleaning-guided-step-advance",onClick:()=>_(e[p+1]),className:"inline-flex h-7 items-center rounded-md bg-[#2563FF] px-2.5 text-[11px] font-semibold text-white hover:bg-[#1D4ED8] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:"Advance"}):null]}),R?(0,a.jsx)(K,{receipt:R.receipt}):null]})]},l.stepKey):(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",onClick:()=>{f(l)},"data-testid":`cleaning-guided-step-${l.stepKey}`,"data-state":"manual_review"!==l.kind&&l.counts.alreadyApplied+g.protectedCount===l.counts.total?"complete":"available",className:"flex min-h-9 w-full items-center gap-2 px-1 py-2 text-left text-[#475569] hover:text-[#0E1624] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#2563FF]/30",children:[(0,a.jsx)("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-[#94A3B8]",children:p+1}),(0,a.jsx)("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-medium",children:l.title}),l.counts.alreadyApplied===l.counts.total&&"manual_review"!==l.kind?(0,a.jsx)(E.A,{className:"h-3.5 w-3.5 text-[#087B5B]","aria-hidden":!0}):null]})},l.stepKey)})})]})}var $=n(7953);let I=new Map;function L(e,t){return e instanceof Error?e.message:t}
1function D({analysisId:e,records:t,reviewFingerprint:n,consolidatedGroupCount:i,isRecordApplied:r,isRecordProtected:l,onReviewHandoff:o}){var d;let c,u,p,f,y,F,M,E,B,K,q,P,U=(0,m.useAnalysisMetadataStore)(e=>e.metadata?.period_split??null),z=s.useMemo(()=>(function(e){let t=e.periodNoun??"period",n=new Map,a=[],s=[];for(let t of e.records){let e=(0,j.JF)(t);if("keep_as_reported"===e){t.evidence.detectedIssues.includes("latest_churn")?s.push(t):a.push(t);continue}if("manual_review"===e){s.push(t);continue}let i=function(e){let t=e.evidence.revenueStreamKind;return"recurring"===t?"subscription":"transactional"===t?"payments":"derived"}(t),r=(0,_.F)(t),l=r?(0,b.Ib)(r):null,o=l??"ungrouped",d=n.get(i);d||(d=new Map,n.set(i,d));let c=d.get(o);if(c||(c={familyKey:o,family:l,records:[],treatments:new Map,spans:new Set},d.set(o,c)),c.records.push(t),r){c.spans.add(r.recognitionPeriodCount);let e=c.treatments.get(r.key);e?e.rowCount+=1:c.treatments.set(r.key,{label:r.label,identity:r,rowCount:1})}}let i=[];for(let a of w){let s=n.get(a);if(!s)continue;let r=[],l=[];for(let e of s.values())null!==e.family&&e.records.length>=5?r.push(e):l.push(...e.records);let o=r.map(e=>({familyKey:e.familyKey,family:e.family,records:e.records,treatments:[...e.treatments.entries()].map(([e,n])=>({key:e,label:n.label,rowCount:n.rowCount,plainSummary:(0,C.Kg)({identity:n.identity,rowCount:n.rowCount,periodNoun:t})})).sort((e,t)=>t.rowCount-e.rowCount||e.key.localeCompare(t.key)),spans:e.spans,title:`${b.LL[e.family]} â ${b.RR[a]}`}));if(l.length>0){let t=new Set(l.map(e=>e.evidence.rowKey));o.push({familyKey:"other",family:null,records:e.records.filter(e=>t.has(e.evidence.rowKey)),treatments:[],spans:new Set,title:`Other adjustments â ${b.RR[a]}`})}for(let n of(o.sort((e,t)=>{let n=R(t.records)-R(e.records);if(0!==n)return n;let a=t.records.length-e.records.length;return 0!==a?a:e.familyKey.localeCompare(t.familyKey)}),o)){let{counts:s,safeRecords:r,proposedRecords:l}=function(e){let t=[],n=[],a=0;for(let s of e.records){if(e.isRecordApplied(s)){a+=1;continue}"numeric_adjustment"===(0,j.JF)(s)?t.push(s):n.push(s)}return{counts:{total:e.records.length,safe:t.length,proposed:n.length,alreadyApplied:a},safeRecords:t,proposedRecords:n}}({records:n.records,isRecordApplied:e.isRecordApplied});i.push({stepKey:`${a}|${n.familyKey}
1`,kind:"adjustments",stream:a,title:n.title,rationale:(0,b.gs)({family:n.family,stream:a,rowCount:n.records.length,spans:n.spans,periodNoun:t}),example:k(n.records),rowKeys:n.records.map(e=>e.evidence.rowKey),safeRecords:r,proposedRecords:l,counts:s,treatments:n.treatments,confidenceMix:N(n.records)})}}if(a.length>0){let t=a.filter(e.isRecordApplied).length;i.push({stepKey:"keeps",kind:"keeps",stream:null,title:"Recommended keeps",rationale:(0,b.S9)(a.length),example:k(a),rowKeys:a.map(e=>e.evidence.rowKey),safeRecords:[],proposedRecords:[],counts:{total:a.length,safe:0,proposed:0,alreadyApplied:t},treatments:[],confidenceMix:N(a)})}return s.length>0&&i.push({stepKey:"manual",kind:"manual_review",stream:null,title:"Needs your judgment",rationale:(0,b.MO)(s.length),example:k(s),rowKeys:s.map(e=>e.evidence.rowKey),safeRecords:[],proposedRecords:[],counts:{total:s.length,safe:0,proposed:0,alreadyApplied:0},treatments:[],confidenceMix:N(s)}),i})({records:t,isRecordApplied:r,periodNoun:(0,C.jb)(U)}),[t,r,U]),{recordsByRowKey:O,appliedRecords:V,protectedRecords:J,remainingRecords:G,remainingSafeRecords:Q,remainingProposedRecords:Y}=s.useMemo(()=>{var e;let n,a,s,i,o;return n=new Map((e={records:t,isRecordApplied:r,isRecordProtected:l}).records.map(e=>[e.evidence.rowKey,e])),s=(a=e.records.filter(e=>{let t=(0,j.JF)(e);return"numeric_adjustment"===t||"proposed_adjustment"===t})).filter(e.isRecordApplied),i=a.filter(t=>!e.isRecordApplied(t)&&!!e.isRecordProtected?.(t)),{recordsByRowKey:n,appliedRecords:s,protectedRecords:i,remainingRecords:o=a.filter(t=>!e.isRecordApplied(t)&&!e.isRecordProtected?.(t)),remainingSafeRecords:o.filter(e=>e.assessment.safeToApply),remainingProposedRecords:o.filter(e=>!e.assessment.safeToApply)}},[r,l,t]),H=s.useMemo(()=>new Set(J.map(e=>e.evidence.rowKey)),[J]),W=(0,S.jB)(e=>e.syncCleaningGuidedReview),Z=(0,S.jB)(e=>e.activateCleaningGuidedReviewStep),X=(0,S.jB)(e=>e.focusCleaningGuidedReviewStep),ee=(0,S.jB)(e=>e.clearCleaningGuidedReviewFocus),et=(0,S.jB)(e=>e.collapseCleaningGuidedReviewStep),en=(0,S.jB)(e=>e.clearAgentRowFocus),ea=(0,S.jB)(t=>t.guidedReviewAnalysisId===e?t.guidedReviewActiveStepKey:null),es=(0,S.jB)(t=>t.guidedReviewAnalysisId===e?t.guidedReviewFocusRowKeys:null),[ei,er]=s.useState(null),[el,eo]=s.useState(null),[ed,ec]=s.useState(null),eu=s.useRef(null),ep=s.useRef(null),em=s.useRef(null),[eh,eg]=s.useState(I),[ex,ev]=s.useState(!1);s.useEffect(()=>{W(e,n)},[e,n,W]),s.useEffect(()=>{eg(I),ep.current&&clearTimeout(ep.current),em.current&&clearTimeout(em.current),ep.current=null,em.current=null,eu.current=null,eo(null),ec(null),er(null),ev(!1)},[e,n]),s.useEffect(()=>()=>{ep.current&&clearTimeout(ep.current),em.current&&clearTimeout(em.current)},[]);let ef=z.find(e=>e.stepKey===ea)??null,eb=(d={analysisId:e,steps:z,activeStep:ef},c=s.useMemo(()=>({analysisId:d.analysisId,surface:"cleaning_workspace"}),[d.analysisId]),u=s.useRef(null),p=s.useRef("initial"),f=d.activeStep?d.steps.findIndex(e=>e.stepKey===d.activeStep?.stepKey):-1,s.useEffect(()=>{d.activeStep&&!(f<0)&&((0,$.VN)({context:c,stepKind:d.activeStep.kind,stepIndex:f,stepCount:d.steps.length,actionableCount:Math.max(0,d.activeStep.counts.total-d.activeStep.counts.alreadyApplied),appliedCount:d.activeStep.counts.alreadyApplied,visibleRowCount:d.activeStep.rowKeys.length,stream:d.activeStep.stream??"none",navigationTrigger:p.current}),p.current="restored")},[f,c,d.activeStep?.stepKey,d.steps.length]),s.useEffect(()=>()=>{let e=u.current;e&&!e.terminal&&(0,$.PO)(e,"cancelled",{reason_code:"component_unmounted"}),u.current=null},[]),y=s.useCallback(e=>{p.current="direct",(0,$.dG)({context:c,action:"guide_reopened",source:"guided_review",toStepKind:e.kind,stepIndex:d.steps.findIndex(t=>t.stepKey===e.stepKey),stepCount:d.steps.length})},[c,d.steps]),F=s.useCallback(()=>{(0,$.dG)({context:c,action:"show_all_rows",source:"guided_review",fromStepKind:d.activeStep?.kind,stepIndex:f>=0?f:void 0,stepCount:d.steps.length,navigationTrigger:"direct"})},[f,c,d.activeStep?.kind,d.steps.length]),M=s.useCallback(e=>{p.current="direct";let t=d.steps.findIndex(t=>t.stepKey===e.stepKey);e.stepKey===d.activeStep?.stepKey&&(0,$.VN)({context:c,stepKind:e.kind,stepIndex:t,stepCount:d.steps.length,actionableCount:Math.max(0,e.counts.total-e.counts.alreadyApplied),appliedCount:e.counts.alreadyApplied,visibleRowCount:e.rowKeys.length,stream:e.stream??"none",navigationTrigger:"direct"});let n={context:c,source:"guided_review",fromStepKind:d.activeStep?.kind,toStepKind:e.kind,stepIndex:t>=0?t:void 0,stepCount:d.steps.length,navigationTrigger:"direct"};(0,$.dG)({...n,action:"show_step_rows",focusedRowCount:e.rowKeys.length}),(0,$.dG)({...n,action:"step_selected"})},[c,d.activeStep?.kind,d.steps]),E=s.useCallback((e,t)=>{let n=d.steps.findIndex(t=>t.stepKey===e.stepKey);p.current="auto_advance"===t?"automatic":"manual",(0,$.dG)({context:c,action:t,source:"guided_review",fromStepKind:d.activeStep?.kind,toStepKind:e.kind,stepIndex:n>=0?n:void 0,stepCount:d.steps.length,focusedRowCount:e.rowKeys.length,navigationTrigger:p.current})},[c,d.activeStep?.kind,d.steps]),B=s.useCallback(()=>{for(let e of["guide_completed","guide_collapsed"])(0,$.dG)({context:c,action:e,source:"guided_review",fromStepKind:d.activeStep?.kind,stepCount:d.steps.length,navigationTrigger:"manual"})},[c,d.activeStep?.kind,d.steps.length]),K=s.useCallback(e=>{let t=(0,$.CR)({context:c,action:e.action,bulkKind:"all"===e.scopeKey?"guided_workspace":"guided_step",source:"guided_review",attemptedCount:e.attemptedCount,properties:e.properties});return u.current=t,t},[c]),q=s.useCallback((e,t,n)=>{(0,$.PO)(e,t,n),u.current===e&&(u.current=null)},[]),P=s.useCallback((e,t)=>{(0,$.uX)(e,t),u.current===e&&(u.current=null)},[]),s.useMemo(()=>({guideReopened:y,showAllRows:F,showStepRows:M,advance:E,completeGuide:B,startBulk:K,finishBulk:q,finishBulkMutation:P}),[E,B,q,P,y,F,M,K]));s.useEffect(()=>{0===z.length||null!==ef||ex||Z(e,z[0].stepKey)},[ef,Z,e,ex,z]);let ey=s.useCallback(()=>{em.current&&(clearTimeout(em.current),em.current=null)},[]),ew=s.useCallback(()=>{ey(),ee(e),en(e),eb.showAllRows()},[e,ey,en,ee,eb]),ej=s.useCallback(t=>{ey(),ef||eb.guideReopened(t),ev(!1),er(null),X(e,t.stepKey,t.rowKeys),eb.showStepRows(t)},[e,ef,ey,X,eb]),eC=s.useCallback((t,n="auto_advance")=>
1{er(null),X(e,t.stepKey,t.rowKeys),eb.advance(t,n)},[e,X,eb]),e_=s.useCallback(t=>{if(ey(),t){ev(!1),eC(t,"manual_advance");return}ev(!0),er(null),et(e),eb.completeGuide(),o?.()},[eC,e,ey,et,o,eb]),ek=s.useCallback(t=>{if(t.safeRecords.length+t.proposedRecords.length===0||null!==eu.current)return;let n=eb.startBulk({action:"apply",scopeKey:t.scopeKey,attemptedCount:t.attemptedCount,properties:{safe_count:t.safeRecords.length,proposed_count:t.proposedRecords.length,included_proposed:t.proposedRecords.length>0}});ey(),eu.current=t.scopeKey,eo(t.scopeKey),ec("apply"),ep.current=setTimeout(()=>{ep.current=null;try{let a=(0,x.m6)({analysisId:e,safeRecords:t.safeRecords,proposedRecords:t.proposedRecords}),s=(0,x.gl)({attemptedCount:t.attemptedCount,batch:a}),i=a.appliedRecords.length+a.unchangedRecords.length+a.protectedRecords.length;eb.finishBulkMutation(n,{completedCount:i,blockedCount:a.failures.length,appliedCount:a.appliedRecords.length,unchangedCount:a.unchangedRecords.length+a.protectedRecords.length,effectCount:a.mutationCount}),er({scopeKey:t.scopeKey,receipt:s});let r=a.failures.filter(e=>"existing_manual_edit"!==e.reason&&!(0,C.E_)(e.reason));r.length>0&&eg(e=>(function(e,t){if(0===t.length)return e;let n=new Map(e);for(let e of t)n.set(e.rowKey,e.reason);return n})(e,r)),"success"===s.tone&&t.nextStep&&(em.current=setTimeout(()=>{em.current=null,eC(t.nextStep)},700))}catch(s){eb.finishBulk(n,"failed",{failure_code:"guided_review_apply_failed"});let a=L(s,"These suggestions could not be applied. Nothing changed.");h.vF.error("cleaning_guided_review_apply_failed",{fallback_state:"cleaning_guided_review_apply_error_visible_no_change",analysisId:e,scopeKey:t.scopeKey,error:a}),er({scopeKey:t.scopeKey,receipt:{tone:"failure",message:a}})}finally{eu.current=null,eo(null),ec(null)}},A.Ki)},[eC,e,ey,eb]),eN=s.useCallback(t=>{if(0===t.records.length||null!==eu.current)return;let n=eb.startBulk({action:"keep",scopeKey:t.scopeKey,attemptedCount:t.records.length});ey(),eu.current=t.scopeKey,eo(t.scopeKey),ec("apply"),ep.current=setTimeout(()=>{ep.current=null;try{(0,v.CT)(t.records),(0,g.RQ)({analysisId:e,records:t.records,action:"keep_accepted",actionVia:"bulk"}),eb.finishBulk(n,"completed",{completed_count:t.records.length,applied_count:t.records.length,unchanged_count:0,effect_count:t.records.length}),er({scopeKey:t.scopeKey,receipt:{tone:"success",message:`Kept ${t.records.length.toLocaleString()} row${1===t.records.length?"":"s"} as reported.`}}),t.nextStep&&(em.current=setTimeout(()=>{em.current=null,eC(t.nextStep)},700))}catch(s){eb.finishBulk(n,"failed",{failure_code:"guided_review_keep_apply_failed"});let a=L(s,"These keep decisions could not be saved. Nothing changed.");h.vF.error("cleaning_guided_review_keep_apply_failed",{fallback_state:"cleaning_guided_review_keep_apply_error_visible_no_change",analysisId:e,scopeKey:t.scopeKey,error:a}),er({scopeKey:t.scopeKey,receipt:{tone:"failure",message:a}})}finally{eu.current=null,eo(null),ec(null)}},A.Ki)},[eC,e,ey,eb]),eR=s.useCallback((t,n,a="adjustments")=>{if(0===n.length||null!==eu.current)return;let s=eb.startBulk({action:"keeps"===a?"unkeep":"unapply",scopeKey:t,attemptedCount:n.length});ey(),eu.current=t,eo(t),ec("undo"),ep.current=setTimeout(()=>{ep.current=null;try{"keeps"===a?(0,v.XX)(n):(0,v.Zw)(n),(0,g.RQ)({analysisId:e,records:n,action:"keeps"===a?"keep_undone":"undone",actionVia:"bulk"}),eb.finishBulk(s,"completed",{completed_count:n.length,applied_count:n.length,unchanged_count:0,effect_count:n.length}),er({scopeKey:t,receipt:{tone:"success",message:"keeps"===a?`Reopened ${n.length.toLocaleString()} keep decision${1===n.length?"":"s"}.`:`Undid ${n.length.toLocaleString()} adjustment${1===n.length?"":"s"}.`}})}catch(a){eb.finishBulk(s,"failed",{failure_code:"guided_review_undo_failed"});let n=L(a,"These adjustments could not be undone. Nothing changed.");h.vF.error("cleaning_guided_review_undo_failed",{fallback_state:"cleaning_guided_review_undo_error_visible_no_change",analysisId:e,scopeKey:t,error:n}),er({scopeKey:t,receipt:{tone:"failure",message:n}})}finally{eu.current=null,eo(null),ec(null)}},A.Ki)},[e,ey,eb]);
1return(0,a.jsx)(T,{steps:z,activeStep:ef,focusedRowKeys:es,recordsByRowKey:O,isRecordApplied:r,blockedRows:eh,protectedRecords:J,protectedRowKeys:H,outcome:ei,busyScopeKey:el,busyOperation:ed,appliedRecords:V,remainingRecords:G,remainingSafeRecords:Q,remainingProposedRecords:Y,consolidatedGroupCount:i,showAllRows:ew,showStepRows:ej,applyScope:ek,applyKeepScope:eN,undoScope:eR,advanceInformationalStep:e_})}let P=s.useLayoutEffect;function U({projectionKey:e,focusOnEnter:t,children:n}){let i=(0,s.useRef)(null);return P(()=>{if(!t)return;let e=i.current;e&&(e.querySelector("[data-cleaning-projection-focus='true'], button:not(:disabled)")??e).focus({preventScroll:!0})},[t]),(0,a.jsx)("div",{ref:i,tabIndex:-1,"data-cleaning-projection-key":e,"data-cleaning-projection-present":"true",children:n})}function z({projectionKey:e,children:t}){let n=(0,s.useRef)(e),i=n.current!==e;return P(()=>{n.current=e},[e]),(0,a.jsx)(U,{projectionKey:e,focusOnEnter:i,children:t},e)}var O=n(12675),V=n(45675),J=n(33405),G=n(13044),Q=n(46767),Y=n(13276),H=n(73805);function W(e){return(t,n)=>"unavailable"===(0,H.Ex)({method:e,periodSplit:t,periodCount:n}).kind}let Z=[{value:"arrAsIs",label:"Snapshot (No Conversion)",description:"Use reported values as-is.",exampleText:"e.g., 100k ARR â 100k ARR",pros:["Simple and direct","No risk of over- or under-estimation"],cons:["Assumes data is pre-annualized","May not work if data varies by period"],whenToUse:"Use when your revenue data is already reported annually, such as from yearly contracts or pre-calculated ARR metrics."},{value:"ltm",label:"Sum of LTM (Last 12 Months)",description:"Sums last 12 months of revenue.",isDisabled:W("ltm"),exampleText:"e.g., 10k + 12k + 8k + ... (12 months) â 150k",pros:["Based on actual historical data","Reduces impact of short-term volatility"],cons:["Backward-looking, not predictive","Requires 12 months of data"],whenToUse:"Suitable for non-subscription models or when you want a historical view of total revenue over a year."},{value:"mrrTimes12",label:"MRR \xd7 12",description:"Multiplies Monthly Recurring Revenue by 12.",exampleText:"e.g., 10k MRR â 120k ARR",pros:["Standard for subscription-based businesses","Accounts for predictable monthly revenue"],cons:["Ignores seasonality or churn","Assumes consistent monthly performance"],whenToUse:"Ideal for SaaS or subscription models where revenue is billed monthly and expected to recur."},{value:"l3ma",label:"Last Three Months Annualized",description:"Sums last 3 months of revenue and multiplies by 4.",isDisabled:W("l3ma"),exampleText:"e.g., (10k + 12k + 8k) \xd7 4 â 120k",pros:["More responsive to recent trends","Requires less historical data"],cons:["Can exaggerate short-term spikes or dips","Less stable than longer periods"],whenToUse:"Use for fast-growing or variable revenue streams where recent performance is more indicative of future trends."},{value:"l3m",label:"Last Three Months (Not Annualized)",description:"Sums last 3 months of revenue with no multiplier, so each quarter shows its own revenue.",isDisabled:W("l3m"),exampleText:"e.g., 10k + 12k + 8k â 30k for the quarter",pros:["Quarter totals straight from monthly revenue","Matches an as-is analysis of the same data summed to quarters"],cons:["Not an annual run rate","Analyses use quarterly periods only"],whenToUse:"Use when your team reports each quarter's revenue from monthly data rather than an annualized figure."},{value:"qrrTimes4",label:"QRR \xd7 4",description:"Multiplies Quarterly Recurring Revenue by 4.",exampleText:"e.g., 30k QRR â 120k ARR",pros:["Useful for quarterly billing cycles","Balances short-term fluctuations"],cons:["May amplify quarterly anomalies","Less granular than monthly methods"],whenToUse:"Best for businesses with quarterly contracts or reporting, providing a smoother view than monthly data."}];var X=n(23682),ee=n(88096),et=n(72182),en=n(75215),ea=n(82682),es=n(81816),ei=n(5937);function er(e){return[...e].sort((e,t)=>e.localeCompare(t))}function el(e,t){let n=(0,ee.zK)(e),a=(0,ee.zK)(t);return n.length>0&&n===a}function eo(e){let{rules:t,attributeKey:n,filters:a}=e,s=t.arrAnnualizationByRevenueStream,i=el(n,s?.attributeKey),r=i?s?.methodByValue??{}:{},l=new Set,o=[];for(let t of[...Array.isArray(a?.[n])?a[n]:[],...i?s?.streamValueUniverse??[]:[],...Object.keys(r),...i?e.uncoveredValues:[]]){let e=(0,ee.p0)(t),n=(0,ee.zK)(e);l.has(n)||(l.add(n),o.push(e))}let d={};for(let e of er(o))d[e]=r[e]??t.arrCalculationMethod;return d}function ed(e){let{rules:t}=e,n=t.arrAnnualizationByRevenueStream,a=function(e){let t,{availableAttributeKeys:n}=e;return t=e.rules.arrAnnualizationByRevenueStream?.attributeKey,n.find(e=>el(e,t))??null}(e);return a?{arrCalculationMethod:t.arrCalculationMethod,mixedStreamsEnabled:!!n?.enabled,streamAttributeKey:a,streamMethodByValue:eo({rules:t,attributeKey:a,filters:e.filters,uncoveredValues:e.uncoveredValues})}:{arrCalculationMethod:t.arrCalculationMethod,mixedStreamsEnabled:!1,streamAttributeKey:null,
1streamMethodByValue:null}}var ec=n(9762),eu=n(29991),ep=n(31352),em=n(95006);function eh({reviewRowCount:e,methodOptions:t,availableAttributeKeys:n,draft:s,setDraft:i,mixedStreamsSelected:r,canChooseMixedStreams:l,streamValues:o,onStreamAttributeKeyChange:d}){let c=(0,ec.ux)(e);return(0,a.jsxs)("div",{className:"space-y-3","data-testid":"cleaning-annualization-confirm-settings",children:[e>0?(0,a.jsxs)("div",{className:"rounded-md border border-[#DCE5F2] bg-[#F8FAFD] px-3 py-2","data-testid":"cleaning-review-scope-summary",children:[(0,a.jsxs)("p",{className:"text-[11.5px] font-semibold leading-4 text-[#0E1624]",children:[e.toLocaleString()," row",1===e?"":"s"," to review"]}),(0,a.jsxs)("p",{className:"mt-0.5 text-[11px] leading-4 text-[#64748B]",children:["Up to ",c.toLocaleString()," review batch",1===c?"":"es"," will be sent. Saved rows do not use another call."]})]}):null,(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-[11.5px] font-semibold leading-4 text-[#0E1624]",children:"Revenue calculation method"}),(0,a.jsx)("p",{className:"mt-0.5 text-[11px] leading-4 text-[#64748B]",children:"Choose how Quikirr should calculate recurring revenue from the reported values."}),(0,a.jsxs)(ep.d,{"aria-label":"Revenue calculation methods",className:"mt-1.5 rounded-md border border-[#E2E8F0]",testId:"cleaning-annualization-method-choice-list",children:[t.map(e=>(0,a.jsx)(ep.P,{className:"min-h-0 gap-2 px-3 py-1.5",description:e.description,disabled:e.disabled,label:e.label,onClick:()=>i(t=>({...t,arrCalculationMethod:e.value,mixedStreamsEnabled:!1})),selected:!r&&s.arrCalculationMethod===e.value},e.value)),l?(0,a.jsx)(ep.P,{className:"min-h-0 gap-2 px-3 py-1.5","data-testid":"cleaning-annualization-method-mixed",description:"Each revenue type is pinned to its own method.",label:"Mixed revenue streams",onClick:()=>i(e=>({...e,mixedStreamsEnabled:!0})),selected:r},"mixed_revenue_streams"):null]})]}),r?(0,a.jsxs)("div",{"data-testid":"cleaning-annualization-revenue-types",children:[(0,a.jsx)("p",{className:"text-[11.5px] font-semibold leading-4 text-[#0E1624]",children:"Revenue Type Value"}),(0,a.jsx)("p",{className:"mt-0.5 text-[11px] leading-4 text-[#64748B]",children:"Each value is pinned to a method."}),(0,a.jsxs)("div",{className:"mt-1.5 grid grid-cols-[minmax(0,1fr)_160px] items-center gap-2","data-testid":"cleaning-annualization-revenue-type-column",children:[(0,a.jsx)("span",{className:"truncate text-[11.5px] leading-4 text-[#64748B]",children:"Revenue type column"}),(0,a.jsxs)(eu.l6,{onValueChange:d,value:s.streamAttributeKey??"",children:[(0,a.jsx)(eu.bq,{"aria-label":"Revenue type column",className:"h-7 bg-white text-[11.5px]",children:(0,a.jsx)(eu.yv,{placeholder:"Choose a column"})}),(0,a.jsx)(eu.gC,{children:n.map(e=>(0,a.jsx)(eu.eb,{value:e,children:e},e))})]})]}),s.streamAttributeKey?0===o.length?(0,a.jsx)("div",{className:"mt-1.5 rounded-md border border-[#E2E8F0] px-3 py-2 text-[11px] leading-4 text-[#64748B]","data-testid":"cleaning-annualization-revenue-type-empty",children:"No values found for this column."}):(0,a.jsx)("div",{className:"mt-1.5 max-h-[168px] overflow-auto rounded-md border border-[#E2E8F0]","data-testid":"cleaning-annualization-revenue-type-rows",children:o.map(e=>(0,a.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_160px] items-center gap-2 border-b border-[#EDF1F5] px-3 py-1.5 last:border-b-0",children:[(0,a.jsx)("span",{className:"truncate text-[11.5px] leading-4 text-[#0E1624]",children:(0,ee.Gt)(e)}),(0,a.jsxs)(eu.l6,{onValueChange:t=>i(n=>({...n,streamMethodByValue:{...n.streamMethodByValue??{},[e]:t}})),value:s.streamMethodByValue?.[e],children:[(0,a.jsx)(eu.bq,{"aria-label":`Calculation method for ${(0,ee.Gt)(e)}`,className:"h-7 bg-white text-[11.5px]",children:(0,a.jsx)(eu.yv,{})}),(0,a.jsx)(eu.gC,{children:t.filter(e=>!e.disabled&&(0,em.gM)(e.value)).map(e=>(0,a.jsx)(eu.eb,{value:e.value,children:e.label},e.value))})]})]},""===e?"__empty_stream__":e))}):(0,a.jsx)("div",{className:"mt-1.5 rounded-md border border-[#E2E8F0] px-3 py-2 text-[11px] leading-4 text-[#64748B]","data-testid":"cleaning-annualization-revenue-type-empty",children:"Choose the column that contains your revenue type values."})]}):null]})}let eg={};function ex(){let e=(0,r.Tj)(e=>e.rules);return(0,s.useMemo)(()=>(0,ei.ff)({rules:e}),[e])}function ev({open:e,settings:t,reviewRowCount:n=0,onConfirm:i,onDismiss:l}){let o=(0,r.Tj)(e=>
1e.rules),[d,u]=(0,s.useState)(!1),[p,g]=(0,s.useState)(null),x=(0,X.P)({recalculationMode:"manual"}),v=(0,m.useAnalysisMetadataStore)(e=>e.metadata?.analysis_id!=null?String(e.metadata.analysis_id):""),f=(0,es.d)({analysisId:v}),b=(0,m.useAnalysisMetadataStore)(e=>e.metadata?.period_split??void 0),y=(0,c.useVersionStore)(e=>(e.periodKeys?.length??0)>0?e.periodKeys.length:void 0),w=(0,en.useFilterStore)(e=>e.getCurrentState()?.filters??eg),j=(0,s.useMemo)(()=>(function(e){let t=new Set,n=[];for(let a of[...Object.keys(e.filters??{}),e.persistedAttributeKey]){let e=String(a??"").trim();if(!e)continue;let s=(0,ee.zK)(e);t.has(s)||(t.add(s),n.push(e))}return er(n)})({filters:w,persistedAttributeKey:String(o.arrAnnualizationByRevenueStream?.attributeKey??"").trim()}),[w,o.arrAnnualizationByRevenueStream?.attributeKey]),C=j.join("\0"),_=(0,s.useSyncExternalStore)(et.pq,et.Bq,et.wB),k=(0,s.useMemo)(()=>{let e=(0,ee.zK)(o.arrAnnualizationByRevenueStream?.attributeKey);return e?_.filter(t=>(0,ee.zK)(t.attributeKey)===e).flatMap(e=>e.unmappedValues):[]},[_,o.arrAnnualizationByRevenueStream?.attributeKey]),N=k.join("\0"),R={rules:o,uncoveredValues:k,filters:w,availableAttributeKeys:j},[S,A]=(0,s.useState)(()=>ed(R));(0,s.useEffect)(()=>{A(ed(R)),u(!1),g(null)},[e,t.fingerprint,N,C]);let F=(0,s.useMemo)(()=>Z.map(e=>({...e,disabled:!!e.isDisabled&&e.isDisabled(b,y)})),[y,b]),M=(0,s.useMemo)(()=>S.streamMethodByValue?er(Object.keys(S.streamMethodByValue)):[],[S.streamMethodByValue]),E=j.length>0,B=E&&S.mixedStreamsEnabled,K=(0,ec.hA)(n);return(0,a.jsx)(Y.Lt,{open:e,onOpenChange:e=>{e||l()},children:(0,a.jsxs)(Y.EO,{className:"max-w-[440px] gap-3 border-[#
1E2E8F0] p-5","data-testid":"cleaning-annualization-confirm-dialog",children:[(0,a.jsxs)(Y.wd,{className:"space-y-1.5 text-left",children:[(0,a.jsx)(Y.r7,{className:"text-[15px] font-semibold leading-5 text-[#0E1624]",children:"Confirm revenue calculation settings"}),(0,a.jsx)(Y.$v,{className:"text-[12px] leading-[18px] text-[#64748B]",children:"These settings change which cleaning treatment is correct â for example, whether a large payment stays as entered or is spread across periods."})]}),(0,a.jsx)(eh,{reviewRowCount:n,methodOptions:F,availableAttributeKeys:j,draft:S,setDraft:A,mixedStreamsSelected:B,canChooseMixedStreams:E,streamValues:M,onStreamAttributeKeyChange:e=>{A(t=>({...t,streamAttributeKey:e,streamMethodByValue:eo({rules:o,attributeKey:e,filters:w,uncoveredValues:k})}))}}),K?(0,a.jsxs)("label",{className:"flex cursor-pointer items-start gap-2 rounded-md border border-[#F1D59A] bg-[#FFF9EB] px-3 py-2","data-testid":"cleaning-review-large-scope-confirmation",children:[(0,a.jsx)("input",{type:"checkbox",checked:d,onChange:e=>u(e.currentTarget.checked),className:"mt-0.5 h-4 w-4 shrink-0 accent-[#2563FF]"}),(0,a.jsxs)("span",{className:"text-[11px] leading-4 text-[#6B4F16]",children:["This is a large review. I want to start all"," ",n.toLocaleString()," rows."]})]}):null,p?(0,a.jsx)("p",{role:"alert","data-testid":"cleaning-annualization-confirm-refusal",className:"rounded-md border border-[#FECACA] bg-[#FEF2F2] px-3 py-2 text-[11.5px] leading-4 text-[#991B1B]",children:(0,ea.q5)(p)}):null,(0,a.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[(0,a.jsx)(Y.Zr,{"data-testid":"cleaning-annualization-confirm-cancel",className:"mt-0 h-8 px-3 text-[11.5px] font-semibold",children:"Cancel"}),(0,a.jsx)(Y.Rx,{onClick:e=>{var t;let n,a=0===Object.keys(n=function(e){let{rules:t,draft:n}=e,a={};n.arrCalculationMethod!==t.arrCalculationMethod&&(a.arrCalculationMethod=n.arrCalculationMethod);let s=t.arrAnnualizationByRevenueStream,i=!!s?.enabled;if(!n.mixedStreamsEnabled)return s&&i&&(a.arrAnnualizationByRevenueStream={...s,enabled:!1}),a;let r=n.streamMethodByValue??{},l=er(Object.keys(r));if(0===l.length)return h.vF.error("cleaning_annualization_mixed_streams_has_no_values",{fallback_state:"cleaning_annualization_mixed_streams_rule_not_written_review_runs_under_global_method",attributeKey:n.streamAttributeKey}),a;if(s&&el(n.streamAttributeKey,s.attributeKey)){let e=s.methodByValue??{},t=Object.entries(r).some(([t,n])=>e[t]!==n);return(!i||t)&&(a.arrAnnualizationByRevenueStream={...s,enabled:!0,methodByValue:{...e,...r}}),a}return a.arrAnnualizationByRevenueStream={enabled:!0,attributeKey:n.streamAttributeKey??"",methodByValue:r,streamValueUniverse:l},a}(t={rules:o,draft:S})).length?null:{arrCalculationMethod:n.arrCalculationMethod??t.rules.arrCalculationMethod,...void 0!==n.arrAnnualizationByRevenueStream?{arrAnnualizationByRevenueStream:n.arrAnnualizationByRevenueStream}:{}};if(a){let t=f(a,e=>{x(e)});if("refused"===t.status){e.preventDefault(),g(t.reason);return}}g(null),i((0,ei.ff)({rules:{...o,...a}}).fingerprint)},disabled:K&&!d||B&&(!S.streamAttributeKey||0===M.length),"data-testid":"cleaning-annualization-confirm-start",className:"h-8 bg-[#2563FF] px-3 text-[11.5px] font-semibold text-white hover:bg-[#1D4ED8]",children:"Start review"})]})]})})}var ef=n(93268),eb=n(80294),ey=n(84251),ew=n(32078),ej=n(35449);class eC extends Error{constructor(e){super(`Cleaning review cost probe timed out after ${e}ms.`),this.name="CleaningReviewCostProbeTimeoutError"}}function e_(e){return e.reason instanceof Error?e.reason:Error("Cleaning review cost probe was aborted.")}async function ek(e){let t;if(e.signal.aborted)throw e_(e.signal);let n=e.run().then(e=>({kind:"completed",value:e}),e=>({kind:"failed",error:e}));try{let a=await Promise.race([n,new Promise(n=>{t=()=>n({kind:"aborted"}),e.signal.addEventListener("abort",t,{once:!0})})]);if("aborted"===a.kind)throw e_(e.signal);if("failed"===a.kind)throw a.error;return a.value}finally{t&&e.signal.removeEventListener("abort",t)}}async function eN(e){var t;let n,a,s;if(0===e.evidenceRows.length)return"cache_replay";if(null===(0,j.HF)(e.analysisId))return"billed";let i=(t={ownerSignal:e.signal},n=new AbortController,a=()=>n.abort(t.ownerSignal?.reason),t.ownerSignal?.aborted?a():t.ownerSignal?.addEventListener("abort",a,{once:!0}),s=null,n.signal.aborted||(s=setTimeout(()=>{n.abort(new eC(1e4))},1e4)),{signal:n.signal,dispose:()=>{null!==s&&clearTimeout(s),t.ownerSignal?.removeEventListener("abort",a)}});try{let t=await ek({signal:i.signal,run:()=>fetch(`/api/data-cleanup/cached-adjudications/${encodeURIComponent(e.analysisId)}`,{method:"GET",headers:{Accept:"application/json"},signal:i.signal})});if(!t.ok)return h.vF.error("cleaning_review_cost_probe_request_failed",{fallback_state:"cleaning_review_cost_probe_treated_as_billed_confirmation_gate_shown",analysisId:e.analysisId,status:t.status}),"billed";let n=await ek({signal:i.signal,run:()=>t.json()}),a=n?.records;if(!Array.isArray(a))return h.vF.error("cleaning_review_cost_probe_response_invalid",{fallback_state:"cleaning_review_cost_probe_treated_as_billed_confirmation_gate_shown",analysisId:e.analysisId}),"billed";let s=new Set(a.map(e=>e?.rowEvidenceHash).filter(e=>"string"==typeof e)),r=new Set(a.map(e=>"string"==typeof e.evidence?.rowKey?e.evidence.rowKey:null).filter(e=>null!==e)),l=!0;for(let t of e.evidenceRows)if(!s.has((0,j.iY)(t))){l=!1;break}if(l)return"cache_replay";let o=e.evidenceRows.reduce((e,t)=>
1e+ +!!r.has(t.rowKey),0),d=e.evidenceRows.length-o;if(0===d)return"completed_cache_replay";if(a.length>0){if(0===o)return h.vF.error("cleaning_review_cost_probe_completed_review_without_current_row_match",{fallback_state:"cleaning_review_cost_probe_restore_only_new_detector_rows_remain_table_only",analysisId:e.analysisId,durableRecordCount:a.length,currentRowCount:e.evidenceRows.length}),"completed_cache_replay";return h.vF.error("cleaning_review_cost_probe_legacy_partial_completion",{fallback_state:"cleaning_review_cost_probe_restore_saved_rows_new_detector_rows_remain_table_only",analysisId:e.analysisId,cachedRowCount:o,uncoveredRowCount:d}),"completed_cache_replay"}return h.vF.error("cleaning_review_cost_probe_cache_empty",{fallback_state:"cleaning_review_cost_probe_reset_requires_fresh_confirmation_before_billed_review",analysisId:e.analysisId,currentRowCount:e.evidenceRows.length,cachedStableRowCount:o,uncoveredRowCount:d}),"empty_cache"}catch(t){return h.vF.error("cleaning_review_cost_probe_failed",{fallback_state:"cleaning_review_cost_probe_treated_as_billed_confirmation_gate_shown",analysisId:e.analysisId,aborted:i.signal.aborted,error:t instanceof Error?t.message:String(t)}),"billed"}finally{i.dispose()}}function eR(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),a=t%60;return 0===a?`${n}m`:`${n}m ${a}s`}var eS=n(86272),eA=n(79267),eF=n(35484),eM=n(40852),eE=n(82749),eB=n(33384);function eK({enabled:e,review:t,gate:n,reviewCost:s,costKey:i,confirmPromptOpen:r,setConfirmPromptOpen:l,queueRowCount:o,queueDetectorFlagCount:d,annualizationSettings:c,awaitingAnnualizationConfirmation:u,reviewCompletedForAnnualization:p,partialReviewSettingsChanged:m,retrying:h,reviewClockNowMs:g,retry:x,stopReview:v,continueWithoutAiReview:f,reviewAllRevenueLtmAnyway:b,confirmAnnualizationAndStart:y}){if(!e&&"idle"===t.status)return null;let w=t.records.filter(e=>e.assessment.safeToApply&&e.assessment.valueJudgments.length>0).length,C=Math.max(0,t.totalRows-w),_=Math.min(t.totalRows,Math.max(t.reviewedRows,t.processedRows)),k=Math.max(0,t.totalRows-_),N=Math.max(0,t.totalRows-t.reviewedRows),R=t.totalRows>0?Math.min(100,_/t.totalRows*100):100*("complete"===t.status),S="reviewing"===t.status?g||t.startedAtMs||0:t.lastProgressAtMs||t.startedAtMs||0,A=null===t.startedAtMs?0:Math.max(0,S-t.startedAtMs),M=null===t.lastProgressAtMs?A:Math.max(0,S-t.lastProgressAtMs),B=M>=6e4,{queueRestarted:K,stopRequested:q,stoppedByUser:T}=t;return(0,a.jsxs)("section",{className:"rounded-lg border border-[#E5E7EB] bg-white px-3 py-2.5","aria-label":"Review of proposed cleaning adjustments","data-testid":"cleaning-ai-complete-review","data-review-gate":n,"data-review-cost":s?.key===i?s.cost:"unknown","data-review-prompt-open":r?"true":"false",children:[(0,a.jsxs)("div",{className:"flex items-start gap-2",children:["reviewing"===t.status?(0,a.jsx)(F.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-[#2563FF]","aria-hidden":!0}):K?(0,a.jsx)(eS.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-[#2563FF]","aria-hidden":!0}):T?(0,a.jsx)(eA.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-[#64748B]","aria-hidden":!0}):"failed"===t.status||"incomplete"===t.status?(0,a.jsx)(eF.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-qb-red","aria-hidden":!0}):"complete"===t.status?(0,a.jsx)(E.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-[#087B5B]","aria-hidden":!0}):(0,a.jsx)(eS.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-[#2563FF]","aria-hidden":!0}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"text-[11.5px] font-semibold leading-4 text-[#172033]",children:"block_row_limit"===n?"Cleaning review paused for this dataset":"recommend_skip_all_revenue_ltm"===n?"Continue without AI cleaning":q?`Stopping the review \xb7 ${_.toLocaleString()} of ${t.totalRows.toLocaleString()} checked`:"reviewing"===t.status?`Reviewing customer-product rows \xb7 ${_.toLocaleString()} of ${t.totalRows.toLocaleString()} checked`:"complete"===t.status?"Reviewed all rows":K?"Review restarted with the current rows":T?"Review stopped":"incomplete"===t.status?"Review completed in part":"failed"===t.status?"Review did not complete":u?"Confirm Settings for Cleaning Review":p?"Review saved for the current settings":"Review will start when the cleaning checks are ready"}),"block_row_limit"===n?(0,a.jsxs)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-review-budget-blocked",children:[o.toLocaleStr
1ing()," customer-product rows exceed the"," ",j.MP.toLocaleString(),"-row review limit. No model calls were started. Narrow the detection rules or continue to Review Analysis without AI cleaning."]}):"recommend_skip_all_revenue_ltm"===n?(0,a.jsx)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-review-ltm-recommendation",children:"This dataset is revenue-only and calculated as an LTM sum. Cleaning is usually unnecessary unless the reported values are wrong."}):u?(0,a.jsx)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-review-awaiting-annualization",children:"These settings change which cleaning treatments are correct."}):null,"complete"===t.status?(0,a.jsxs)("p",{className:"mt-1 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-outcome-counts",children:[w.toLocaleString()," high-confidence adjustment",1===w?"":"s"," \xb7"," ",C.toLocaleString()," need",1===C?"s":""," manual review"]}):K?(0,a.jsx)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-review-restarted",children:t.error??eB.Qi}):T?t.totalRows>0?(0,a.jsxs)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]",role:"status","data-testid":"cleaning-ai-review-stopped",children:[t.reviewedRows.toLocaleString()," reviewed and saved \xb7"," ",N.toLocaleString()," remaining"]}):null:"incomplete"===t.status?(0,a.jsxs)("div",{className:"mt-0.5 space-y-1 text-[10.5px] leading-4 text-qb-red",role:"alert","data-testid":"cleaning-ai-review-incomplete",children:[(0,a.jsx)("p",{children:t.error??`${t.reviewedRows.toLocaleString()} rows were reviewed and saved; ${N.toLocaleString()} still need review.`}),(0,a.jsxs)("p",{className:"text-[#64748B]",children:[t.reviewedRows.toLocaleString()," reviewed \xb7"," ",N.toLocaleString()," remaining. You can work through the reviewed rows now, then continue only the remainder."]})]}):"failed"===t.status?(0,a.jsx)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-qb-red",children:t.error??"Quikirr could not connect to the review service."}):"reviewing"===t.status?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-review-progress-counts",children:[_.toLocaleString()," checked \xb7"," ",t.reviewedRows.toLocaleString()," reviewed \xb7"," ",k.toLocaleString()," remaining"]}),t.failedRows>0?(0,a.jsxs)("p",{className:"mt-0.5 text-[10px] leading-4 text-[#64748B]",children:[t.failedRows.toLocaleString()," checked row",1===t.failedRows?"":"s"," will need another pass."]}):null,d!==t.totalRows?(0,a.jsxs)("p",{className:"mt-0.5 text-[10.5px] leading-4 text-[#64748B]",children:["Every finding is included:"," ",d.toLocaleString()," cleaning findings are grouped into ",t.totalRows.toLocaleString()," unique customer-product rows."]}):null,(0,a.jsx)("div",{className:"mt-2 h-1 overflow-hidden rounded-full bg-[#E2E8F0]",role:"progressbar","aria-label":"Cleaning review progress","aria-valuemin":0,"aria-valuemax":t.totalRows,"aria-valuenow":_,children:(0,a.jsx)("div",{className:"h-full rounded-full bg-[#2563FF] transition-[width] duration-300 ease-out",style:{width:`${R}%`}})}),(0,a.jsxs)("p",{className:"mt-1 text-[10px] leading-4 text-[#64748B]","data-testid":"cleaning-ai-review-timing",children:[`Elapsed ${eR(A)}`,q?null:" \xb7 Review continues until every row has a result.",B&&!q?` No batch has finished for ${eR(M)}; provider fallback is still in progress.`:null]})]}):null]}),"block_row_limit"===n?(0,a.jsx)("button",{type:"button",onClick:f,"data-testid":"cleaning-ai-review-budget-continue",className:"inline-flex min-h-8 shrink-0 items-center rounded-md px-2 text-[10.5px] font-semibold text-[#2563FF] hover:bg-[#F8FAFC] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:"Continue without AI cleaning"}):"recommend_skip_all_revenue_ltm"===n?(0,a.jsxs)("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[(0,a.jsx)("button",{type:"button",onClick:f,"data-testid":"cleaning-ai-review-ltm-continue",className:"inline-flex min-h-8 items-center rounded-md bg-[#2563FF] px-2.5 text-[10.5px] font-semibold text-white hover:bg-[#1D4ED8] focus-visible:outline-hidden focu
1s-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:"Continue without AI cleaning"}),(0,a.jsx)("button",{type:"button",onClick:b,"data-testid":"cleaning-ai-review-ltm-override",className:"inline-flex min-h-6 items-center rounded px-1.5 text-[10px] font-medium text-[#64748B] hover:bg-[#F8FAFC] hover:text-[#0E1624] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:"Review anyway"})]}):"reviewing"===t.status?(0,a.jsxs)("button",{type:"button",onClick:v,disabled:q,title:"Stop the review. Rows already reviewed are kept, and you can continue the rest later.","data-testid":"cleaning-ai-review-stop",className:"inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-2 text-[10.5px] font-semibold text-[#64748B] hover:bg-[#F8FAFC] hover:text-[#0E1624] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:opacity-50",children:[q?(0,a.jsx)(F.A,{className:"h-3 w-3 animate-spin","aria-hidden":!0}):(0,a.jsx)(eM.A,{className:"h-3 w-3","aria-hidden":!0}),q?"Stopping":"Stop"]}):("failed"!==t.status||K)&&("incomplete"!==t.status||m)?null:(0,a.jsxs)("button",{type:"button",onClick:()=>void x(),disabled:h,className:"inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-2 text-[10.5px] font-semibold text-[#2563FF] hover:bg-[#F8FAFC] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:opacity-50",children:[h?(0,a.jsx)(F.A,{className:"h-3 w-3 animate-spin","aria-hidden":!0}):(0,a.jsx)(eE.A,{className:"h-3 w-3","aria-hidden":!0}),"incomplete"===t.status?"Continue remaining":"Retry"]})]}),u&&!r?(0,a.jsx)("button",{type:"button",onClick:()=>l(!0),"data-testid":"cleaning-ai-review-confirm-annualization",className:"mt-2 inline-flex min-h-9 w-full items-center justify-center rounded-md bg-[#2563FF] px-3 text-[11.5px] font-semibold text-white hover:bg-[#1D4ED8] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:"Review & Confirm"}):null,(0,a.jsx)(ev,{open:r,settings:c,reviewRowCount:o,onConfirm:y,onDismiss:()=>l(!1)})]})}var eq=n(8549),eT=n(55573),e$=n(67275),eI=n(34175);let eL=new Set(["ALL_REVENUE_LTM_REVIEW_NOT_CONFIRMED","INVALID_REQUEST","REVIEW_BUDGET_EXCEEDED"]);function eD(e,t){(0,e$.PN)(e,t.outcome,{reasonCode:t.reasonCode,resultSource:t.resultSource,reviewedRows:t.reviewedRows,failedRows:t.failedRows,resultCode:t.resultCode,batchCount:t.batchCount,cachedRows:t.cachedRows,modelRows:t.modelRows})}function eP({analysisId:e,enabled:t,inputsReady:n,queueFingerprint:i,queueRowCount:r,queueDetectorFlagCount:l,queueEvidence:o,annualizationRules:d,onContinueWithoutAiReview:c}){var u,p;let m=(0,S.jB)(e=>e.agentAdjudicationAnalysisId),g=(0,S.jB)(e=>e.agentAdjudicationRunId),x=(0,S.jB)(e=>(0,ej.Xp)(e,e.agentAdjudicationRunId)),v=(0,S.jB)(e=>e.agentAdjudicationStatus),f=(0,S.jB)(e=>e.agentAdjudicationQueueFingerprint),b=(0,S.jB)(e=>e.agentAdjudicationSettingsFingerprint),y=(0,S.jB)(e=>e.agentAdjudicationTotalRows),w=(0,S.jB)(e=>e.agentAdjudicationReviewedRows),j=(0,S.jB)(e=>e.agentAdjudicationProcessedRows),C=(0,S.jB)(e=>e.agentAdjudicationFailedRows),_=(0,S.jB)(e=>e.agentAdjudicationStartedAtMs),k=(0,S.jB)(e=>e.agentAdjudicationLastProgressAtMs),N=(0,S.jB)(e=>e.agentAdjudicationError),R=(0,S.jB)(e=>e.agentAdjudicationErrorKind),A=(0,S.jB)(e=>e.completeAgentAdjudications),F=(0,S.jB)(e=>e.clearCompleteAgentAdjudications),M=(0,S.jB)(e=>e.requestAgentAdjudicationReviewStop),E=s.useCallback(()=>{null!==g&&M(e,g)},[e,g,M]),B=m===e?{...{stopRequested:"reviewing"===(u={status:v,errorKind:R,stopRequestedForRun:x}).status&&u.stopRequestedForRun,stoppedByUser:"incomplete"===u.status&&"stopped_by_user"===u.errorKind,queueRestarted:"failed"===u.status&&"queue_restarted"===u.errorKind},status:v,queueFingerprint:f,settingsFingerprint:b??null,totalRows:y,reviewedRows:w,processedRows:j??w,failedRows:C??0,startedAtMs:_??null,lastProgressAtMs:k??null,error:N,errorKind:R,records:A}:{status:"idle",queueFingerprint:null,settingsFingerprint:null,totalRows:0,reviewedRows:0,processedRows:0,failedRows:0,startedAtMs:null,lastProgressAtMs:null,error:null,errorKind:null,records:[],stopRequested:!1,stoppedByUser:!1,queueRestarted:!1},[K,q]=s.useState(!1),[T,$]=s.useState(0);s.useEffect(()=>{if("reviewing"!==B.status||null===B.startedAtMs)return void $(0);let e=()=>$(Date.now());e();let t=window.setInterval(e,5e3);return()=>window.clearInterval(t)},[B.startedAtMs,B.status]),s.useEffect(()=>{n&&null===i&&m===e&&"reviewing"!==v&&"complete"!==v&&"incomplete"!==v&&F(e)},[e,F,n,v,i,m]);let{runReview:I,confirmPromptOpen:L,setConfirmPromptOpen:D,resolveConfirmation:P}=function(e){let[t,n]=s.useState(!1),a=s.useRef(null),i=s.useRef(null),r=s.useRef(null),l=s.useCallback(t=>{t&&!a.current?a.current=(0,e$.UD)({context:{analysisId:e.analysisId},trigger:"manual",totalRows:e.queueRowCount,source:"annualization_settings"}):!t&&a.current&&((0,e$.M0)(a.current,"dismissed"),a.current=null),n(t)},[e.analysisId,e.queueRowCount]),o=s.useCallback(t=>{if(a.current&&((0,e$.M0)(a.current,t),a.current=null),"confirmed"===t||"ltm_override"===t){let t=(0,e$.iD)({context:{analysisId:e.analysisId},trigger:"manual",source:"annualization_settings",totalRows:e.queueRowCount});i.current=t,r.current=t}n(!1)},[e.analysisId,e.queueRowCount]),d=s.useCallback(async(t,n=!1,a=!1,s=!1)=>{var l;let o=(l={force:t,refresh:a}).force?"retry":l.refresh?"refresh":"auto",d=i.current,c=r.current;d&&d!==c&&!d.terminal&&(0,e$.PN)(d,"abandoned",{reasonCode:"superseded_by_new_review_attempt"});let u=c&&!c.terminal?c:(0,e$.iD)({context:{analysisId:e.analysisId},trigger:o,source:n?"cache_restore":a?"settings_refresh":t?"retry":"automatic_review",totalRows:e.queueRowCount});r.current=null,i.current=u;try{let i=await (0,eB.T3)({analysisId:e.analysisId,force:t,restoreOnly:n,refresh:a,trigger:t?"manual":"auto",allowAllRevenueLtmReview:s,interactionWait:u});if(u.terminal)return;i.interactionOutcome.reviewedRows>0&&(0,e$.rH)(u,{resultSource:i.interactionOutcome.resultSource,reviewedRows:i.interactionOutcome.reviewedRows,failedRows:i.interactionOutcome.failedRows,batchCount:i.interactionOutcome.batchCount,cachedRows:i.interactionOutcome.cachedRows,modelRows:i.interactionOutcome.modelRows}),eD(u,i.interactionOutcome)}catch(s){if(u.terminal)return;!function(e,t){if(t instanceof eT.UZ)return eD(e,t.interactionOutcome);if(t instanceof eB.Yo)return(0,e$.PN)(e,"abandoned",{reasonCode:"queue_restarted"});let n=(0,eI.yk)(t instanceof eq.aF?t.failureCode:"UNKNOWN");(0,e$.PN)(e,eL.has(n)?"blocked":"failed",eL.has(n)?{reasonCode:"ALL_REVENUE_LTM_REVIEW_NOT_CONFIRMED"===n?"all_revenue_ltm_review_not_confirmed":"INVALID_REQUEST"===n?"invali
1d_request":"review_budget_exceeded",failureCode:n}:{failureCode:n})}(u,s);let t=s instanceof Error?s.message:"Quikirr could not complete the review of every proposed cleaning row.",n=s instanceof eB.Yo?"queue_restarted":"failure",a=S.jB.getState();(a.agentAdjudicationAnalysisId!==e.analysisId||"idle"===a.agentAdjudicationStatus)&&(a.beginAgentAdjudicationReview(e.analysisId,0,{force:!0,...e.queueFingerprint?{queueFingerprint:e.queueFingerprint}:{}}),a.failAgentAdjudicationReview(e.analysisId,t,void 0,n)),h.vF.error("cleaning_llm_complete_review_ui_failed",{fallback_state:"queue_restarted"===n?"cleaning_llm_complete_review_queue_restarted_auto_rerun":"cleaning_llm_complete_review_error_visible_manual_retry_available",analysisId:e.analysisId,errorKind:n,error:t})}finally{i.current===u&&(i.current=null)}},[e.analysisId,e.queueFingerprint,e.queueRowCount]);return s.useEffect(()=>{let e=e=>{let t=a.current;a.current=null,t&&(0,e$.M0)(t,"dismissed");let n=i.current;i.current=null,r.current=null,n&&!n.terminal&&(0,e$.PN)(n,"abandoned",{reasonCode:e})},t=()=>e("page_departure");return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t),e("workspace_unmounted")}},[]),{runReview:d,confirmPromptOpen:t,setConfirmPromptOpen:l,resolveConfirmation:o}}({analysisId:e,queueFingerprint:i,queueRowCount:r}),U=ex(),z=U.fingerprint,[O,V]=s.useState(null),[J,G]=s.useState(null);s.useEffect(()=>{V((0,ei.Y5)({analysisId:e,fingerprint:z})?z:null)},[e,z]);let Q=O===z,Y=(0,ei.xu)({analysisId:e,fingerprint:z}),H=!Y&&(0,ei.HH)(e),W=("complete"===B.status||"incomplete"===B.status)&&B.settingsFingerprint!==z,Z="incomplete"===B.status&&W,X=W||H,ee=`${e}|${i??""}`,et=`${ee}|${z}`,[en,ea]=s.useState(null),es=en===et,[er,el]=s.useState(null),eo=er===ee,ed=(0,ec.eL)({rowCount:r,rules:d,allowAllRevenueLtmReview:eo}),eu=function(e){if(!e.autoRunWanted)return"idle";let t=e.spendPolicy??"allow";if(e.annualizationChangedAfterCompletedReview)return"allow"!==t?t:e.settingsConfirmed?"run":"confirm";if(e.reviewCompletedForAnnualization)return"unknown"===e.reviewCost?"probe":"empty_cache"===e.reviewCost?"allow"!==t?t:e.emptyCompletedReviewCacheReconfirmed?"run":"confirm":"restore";return"unknown"===e.reviewCost?"probe":"completed_cache_replay"===e.reviewCost?"restore":"cache_replay"===e.reviewCost?"run":"allow"!==t?t:e.settingsConfirmed?"run":"confirm"}({autoRunWanted:!!(p={enabled:t,queueFingerprint:i,status:B.status,ownedQueueFingerprint:B.queueFingerprint,errorKind:B.errorKind,annualizationChangedAfterCompletedReview:X}).enabled&&!!p.queueFingerprint&&"reviewing"!==p.status&&(!!p.annualizationChangedAfterCompletedReview&&"failed"!==p.status||"incomplete"!==p.status&&("failed"===p.status?"queue_restarted"===p.errorKind&&p.ownedQueueFingerprint!==p.queueFingerprint:"complete"!==p.status||p.ownedQueueFingerprint!==p.queueFingerprint)),settingsConfirmed:Q,reviewCompletedForAnnualization:Y,annualizationChangedAfterCompletedReview:X,emptyCompletedReviewCacheReconfirmed:es,reviewCost:J?.key===ee?J.cost:"unknown",spendPolicy:ed}),ep=s.useRef(null);s.useEffect(()=>{if("probe"!==eu)return;let t=!1;return eN({analysisId:e,evidenceRows:o}).then(e=>{t||G({key:ee,cost:e})}),()=>{t=!0}},[e,ee,eu]),s.useEffect(()=>{if("restore"===eu){if(D(!1),ep.current===ee)return;ep.current=ee,I(!1,!0);return}if("run"===eu){D(!1),I(!1,!1,X||es,eo);return}"confirm"!==eu&&"idle"===eu&&D(!1)},[X,ee,es,eu,r,B.totalRows,I,eo]);let em=s.useCallback(t=>{(0,ei.vl)({analysisId:e,fingerprint:t}),V(t),Y&&J?.key===ee&&"empty_cache"===J.cost&&ea(`${ee}|${t}`),P(eo?"ltm_override":"confirmed")},[e,ee,eo,P,Y,J]),eh="confirm"===eu,eg=s.useCallback(async()=>{if(!K){if(Z)return void D(!0);q(!0);try{await I(!0,!1,!1,eo)}finally{q(!1)}}},[eo,Z,K,I]),ev=s.useCallback(()=>{P("skipped"),(0,ey.PJ)(ew.R2.CLEANING_LLM_COMPLETE_REVIEW_SKIPPED,{analysis_id:e,row_count:r,reason:"block_row_limit"===eu?"row_limit":"all_revenue_ltm_recommendation"}),c?.()},[e,eu,c,r,P]),ef=s.useCallback(()=>{(0,ey.PJ)(ew.R2.CLEANING_LLM_COMPLETE_REVIEW_LTM_OVERRIDE,{analysis_id:e,row_count:r}),el(ee),D(!0)},[e,ee,r]);return(0,a.jsx)(eK,{enabled:t,review:B,gate:eu,reviewCost:J,costKey:ee,confirmPromptOpen:L,setConfirmPromptOpen:D,queueRowCount:r,queueDetectorFlagCount:l,annualizationSettings:U,awaitingAnnualizationConfirmation:eh,reviewCompletedForAnnualization:Y,partialReviewSettingsChanged:Z,retrying:K,reviewClockNowMs:T,retry:eg,stopReview:E,continueWithoutAiReview:ev,reviewAllRevenueLtmAnyway:ef,confirmAnnualizationAndStart:em})}var eU=n(37683),ez=n(18368),eO=n(80846),eV=n(12363),eJ=n(76721),eG=n(89239),eQ=n(1658),eY=n(43772),eH=n(78780),eW=n(72662),eZ=n(71947);let eX={"all-anomalies":"All anomalies",consolidation:"Duplicate customers","latest-churns":"Recent churns","revenue-regularities":"Revenue irregularities",negatives:"Negative revenue"},e0=["patterns","gaps","spikes","plan_conversion","de_minimis"];function e1({analysisId:e,available:t,compact:n=!1,surface:i="cleaning_navigation"}){let[r,l]=s.useState(null),[o,d]=s.useState(!1),[u,p]=s.useState(null),m=s.useRef(null);return(s.useEffect(()=>()=>{m.current&&((0,$.NI)(m.current,"cancelled"),m.current=null)},[]),t)?(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)(eG.$,{size:"xs",variant:n?"ghost":"outline",onClick:()=>{let t=Date.now();(0,eZ.ve)({analysisId:e,surface:i,concern:"negative_handling",operation:"preview_reset",actor:"user"});try{let n=(0,eW.OY)({analysisId:e,getVersionStore:()=>c.useVersionStore.getState()});l(n),(0,eZ.Fx)({analysisId:e,surface:i,concern:"negative_handling",operation:"preview_reset",actor:"user",durationMs:Date.now()-t,removedVersionCount:n.removedVersionIds.length,properties:{retained_version_count:n.retainedVersionIds.length}}),p(null),d(!0),m.current=(0,$.QK)({context:{analysisId:e,surface:i},bulkKind:"concern_reset",source:"negative_reset_dialog",safeCount:n.removedVersionIds.length,proposedCount:0})}catch(a){let n=a instanceof Error?a.message:"Reset preview failed.";(0,eZ.ts)({analysisId:e,surface:i,concern:"negative_handling",operation:"preview_reset",actor:"user",failureCode:"negative_reset_preview_failed",error:a,fallbackState:"cleaning_negative_reset_preview_failed",durationMs:Date.now()-t}
1),p((0,eY.A)(n,"We couldn't apply the data-cleanup change. Review the selection and try again.","ui_boundary_features_data_cleanup_cleaningworkspace_cleaningconcerncontrols_openreset_1_failed"))}},"aria-label":"Reset negative handling",className:n?"shrink-0 gap-1 px-2 text-[11px] font-medium text-qb-slate hover:text-qb-midnight":void 0,children:[(0,a.jsx)(M.A,{className:"mr-1 h-3 w-3","aria-hidden":"true"}),n?"Reset":"Reset negative handling"]}),u?(0,a.jsxs)("p",{role:"alert",className:"text-[11px] leading-4 text-qb-red",children:[u," Nothing was changed."]}):null,(0,a.jsx)(Y.Lt,{open:o,onOpenChange:e=>{!e&&m.current&&((0,$.NI)(m.current,"dismissed"),m.current=null),d(e)},children:(0,a.jsxs)(Y.EO,{children:[(0,a.jsxs)(Y.wd,{children:[(0,a.jsx)(Y.r7,{children:"Restore the original negative values?"}),(0,a.jsx)(Y.$v,{children:"This removes the negative-handling decisions and restores the original values. Other cleaning decisions remain active."})]}),(0,a.jsxs)(Y.ck,{children:[(0,a.jsx)(Y.Zr,{children:"Cancel"}),(0,a.jsx)(Y.Rx,{onClick:()=>{if(!r)return;m.current&&((0,$.NI)(m.current,"all"),m.current=null);let t=(0,$.CR)({context:{analysisId:e,surface:i},action:"reset",bulkKind:"concern_reset",source:"negative_reset_dialog",attemptedCount:r.removedVersionIds.length}),n=Date.now(),a={interaction_id:t.id};(0,eZ.ve)({analysisId:e,surface:i,concern:"negative_handling",operation:"reset_concern",actor:"user",properties:a});try{let s=(0,eW.un)({analysisId:e,preview:r,getVersionStore:()=>c.useVersionStore.getState()});(0,eZ.Fx)({analysisId:e,surface:i,concern:"negative_handling",operation:"reset_concern",actor:"user",durationMs:Date.now()-n,removedVersionCount:s.removedVersionIds.length,properties:a}),(0,$.fg)(t,s.removedVersionIds.length),d(!1),l(null),p(null)}catch(r){(0,$.Sy)(t,"negative_reset_failed");let s=r instanceof Error?r.message:"Negative reset failed.";(0,eZ.ts)({analysisId:e,surface:i,concern:"negative_handling",operation:"reset_concern",actor:"user",failureCode:"negative_reset_failed",error:r,fallbackState:"cleaning_negative_reset_failed",durationMs:Date.now()-n,properties:a}),p((0,eY.A)(s,"We couldn't apply the data-cleanup change. Review the selection and try again.","ui_boundary_features_data_cleanup_cleaningworkspace_cleaningconcerncontrols_confirmreset_2_failed"))}},className:"bg-qb-red text-white hover:bg-qb-red/90",children:"Restore original values"})]})]})})]}):null}function e5({analysisId:e,showRegularitiesBackAction:t=!0,showHeading:n=!0,focusedActions:s}){let i=(0,S.jB)(e=>e.concern),r=(0,S.jB)(e=>e.decisionConcerns??{}),l=(0,S.jB)(e=>e.regularitiesDrillCategory),o=(0,S.jB)(e=>e.setRegularitiesDrillCategory),c=(0,S.jB)(e=>e.setUnifiedFilter),u=new Map;for(let e of e0)u.set(e,0);for(let e of r.smoothing?.candidates??[]){if("needs_review"!==e.status&&"stale"!==e.status&&"blocked"!==e.status)continue;let t=e.candidate.subtype;u.has(t)&&u.set(t,(u.get(t)??0)+1)}return i?(0,a.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"cleaning-concern-controls","data-concern":i,children:[n?(0,a.jsx)("div",{className:"flex items-center gap-2",children:(0,a.jsx)("h3",{className:"text-[12px] font-semibold text-[#0E1624]",children:"revenue-regularities"===i&&l?d.b3[l]:eX[i]})}):null,"all-anomalies"===i?null:"negatives"===i||"latest-churns"===i?s:"consolidation"===i?(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsx)("div",{className:"space-y-2 text-[12px] leading-5 text-[#64748B]",children:(0,a.jsx)("p",{children:"Select duplicate groups, then merge or keep them separate."})}),s]}):(0,a.jsxs)(z,{projectionKey:l?`category:${l}`:"overview",children:[l?(0,a.jsx)("div",{className:"space-y-2",children:t?(0,a.jsxs)("button",{type:"button",onClick:()=>{o(null),c("regularities")},"data-testid":"regularities-category-back",className:"inline-flex items-center gap-1 text-[12px] font-medium text-[#475569] hover:text-[#0E1624]",children:[(0,a.jsx)(eH.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"All irregularity types"]}):null}):(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)("p",{className:"text-[11px] leading-4 text-[#64748B]",children:"Choose a type to filter the worksheet. Select rows there, then use the actions below."}),(0,a.jsx)("ul",{"aria-label":"Revenue irregularity types",children:e0.map(e=>{let t=u.get(e)??0;return(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",onClick:()=>{o(e),c(e)},className:"group flex w-full items-center gap-2 rounded-md px-2 py-2 text-left hover:bg-[#F8FAFC]",children:[(0,a.jsx)("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-[#0E1624]",children:d.b3[e]}),(0,a.jsx)("span",{className:"text-[11px] tabular-nums text-[#64748B]",children:t}),(0,a.jsx)(eJ.A,{className:"h-3.5 w-3.5 text-[#94A3B8]","aria-hidden":"true"})]})},e)})})]}),s]})]}):null}var e2=n(36460);let e3={monthlyMultiplierMin:6,monthlyMultiplierMax:15,quarterlyMultiplierMin:2.5,quarterlyMultiplierMax:5};var e4=n(16317),e6=n(64976),e8=n(42763),e7=n(24752),e9=n(33807),te=n(14577),tt=n(70872),tn=n(21767),ta=n(60529),ts=n(73994);let ti=({isOpen:e,onClose:t,monthThreshold:n,quarterThreshold:i,requireContiguous:r,revenueThreshold:l,deMinim
1isMode:o,onSave:d,isProcessing:c=!1,presentation:u="dialog"})=>{let[p,h]=(0,s.useState)(n),[g,x]=(0,s.useState)(i),[v,f]=(0,s.useState)(r),[b,y]=(0,s.useState)(l),[w,j]=(0,s.useState)(o),C=(0,m.useAnalysisMetadataStore)(e=>e.getPeriodSplit()),_=(0,s.useMemo)(()=>C?.toLowerCase()==="quarterly",[C]);(0,s.useEffect)(()=>{e&&(h(n),x(i),f(r),y(l),j(o))},[e,n,i,r,l,o]);let k=p!==n||g!==i||v!==r||b!==l||w!==o,N=_?g:p,R=_?"quarter":"month",S=_?"quarters":"months",A=_?4:6;if(!e)return null;let F=(0,a.jsxs)("div",{className:"space-y-6 py-4",children:[(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsx)(e9.J,{children:"Detection Mode"}),(0,a.jsxs)(ts.z,{value:w,onValueChange:e=>j(e),disabled:c,children:[(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(ts.C,{value:"period",id:"period-mode"}),(0,a.jsxs)(e9.J,{htmlFor:"period-mode",className:"font-normal cursor-pointer",children:["Period-based (detect by number of ",S," with revenue)"]})]}),(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(ts.C,{value:"revenue",id:"revenue-mode"}),(0,a.jsx)(e9.J,{htmlFor:"revenue-mode",className:"font-normal cursor-pointer",children:"Revenue-based (detect by total revenue amount)"})]})]})]}),(0,a.jsxs)("div",{className:"min-h-[150px] space-y-6",children:["period"===w&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)(e9.J,{htmlFor:"threshold",children:[_?"Quarterly":"Monthly"," Data Threshold"]}),(0,a.jsx)(tt.Bc,{children:(0,a.jsxs)(tt.m_,{children:[(0,a.jsx)(tt.k$,{asChild:!0,children:(0,a.jsx)(te.A,{className:"w-4 h-4 text-gray-400 cursor-help"})}),(0,a.jsx)(tt.ZI,{side:"right",className:"max-w-xs",children:(0,a.jsxs)("p",{className:"text-xs",children:["Maximum number of ",S," with revenue to flag as de minimis."]})})]})})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(e7.A,{id:"threshold",min:1,max:A,step:1,value:[N],onValueChange:e=>{_?x(e[0]):h(e[0])},className:"w-full",disabled:c}),(0,a.jsxs)("div",{className:"flex justify-between text-xs text-gray-500",children:[(0,a.jsxs)("span",{children:["1 ",R]}),(0,a.jsxs)("span",{className:"font-medium text-gray-700 text-sm",children:[N," ",1!==N?S:R," or fewer"]}),(0,a.jsxs)("span",{children:[A," ",S]})]})]})]}),(0,a.jsxs)("div",{className:"flex items-center justify-between space-x-3 py-2",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(e9.J,{htmlFor:"requireContiguous",className:"font-medium",children:"Require Consecutive Periods"}),(0,a.jsx)("p",{className:"text-xs text-gray-500",children:v?"Only flag customers with consecutive revenue periods":"Flag customers with sparse revenue (any periods)"})]}),(0,a.jsx)(tn.d,{id:"requireContiguous",checked:v,onCheckedChange:f,disabled:c})]})]}),"revenue"===w&&(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(e9.J,{htmlFor:"revenueThreshold",children:"Total Revenue Threshold"}),(0,a.jsx)(tt.Bc,{children:(0,a.jsxs)(tt.m_,{children:[(0,a.jsx)(tt.k$,{asChild:!0,children:(0,a.jsx)(te.A,{className:"w-4 h-4 text-gray-400 cursor-help"})}),(0,a.jsx)(tt.ZI,{side:"right",className:"max-w-xs",children:(0,a.jsx)("p",{className:"text-xs",children:"Flag customers whose total revenue across all periods is below this amount."})})]})})]}),(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)("span",{className:"text-sm text-gray-600",children:"$"}),(0,a.jsx)(ta.p,{id:"revenueThreshold",type:"number",value:b,onChange:e=>y(Number(e.target.value)),className:"w-full",placeholder:"10000",disabled:c})]})]})]}),(0,a.jsx)("div",{className:"bg-gray-50 p-3 rounded-lg",children:(0,a.jsxs)("p",{className:"text-xs text-gray-600",children:[(0,a.jsx)("strong",{children:"Example:"})," With current settings, customers"," ","period"===w?(0,a.jsxs)(a.Fragment,{children:["with ",v?"consecutive":"any"," ",N," ",1!==N?S:R," ","or fewer will be flagged for review."]}):(0,a.jsxs)(a.Fragment,{children:["with total revenue below $",b.toLocaleStr
1ing()," will be flagged for review."]})]})})]}),M=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eG.$,{variant:"outline",onClick:t,disabled:c,children:"Cancel"}),(0,a.jsx)(eG.$,{onClick:()=>{d({monthThreshold:p,quarterThreshold:g,requireContiguous:v,revenueThreshold:b,deMinimisMode:w})},disabled:c||!k,children:c?"Applying...":"Save & Re-detect"})]});return"inline"===u?(0,a.jsxs)("div",{"data-testid":"de-minimis-settings-editor",children:[F,(0,a.jsx)("div",{className:"flex items-center justify-end gap-2 border-t border-[#E5EAF0] pt-4",children:M})]}):(0,a.jsx)(e8.lG,{open:e,onOpenChange:t,children:(0,a.jsxs)(e8.Cf,{className:"sm:max-w-[500px]",children:[(0,a.jsxs)(e8.c7,{children:[(0,a.jsx)(e8.L3,{children:"De Minimis Revenue Detection Settings"}),(0,a.jsx)(e8.rr,{children:"Configure how to detect customers with minimal revenue history."})]}),F,(0,a.jsx)(e8.Es,{children:M})]})})},tr=({isOpen:e,onClose:t,rule:n,onSave:i,isProcessing:r=!1,presentation:l="dialog"})=>{var o;let[d,c]=(0,s.useState)(n?.config||{});if((0,s.useEffect)(()=>{e&&n?.config&&c(n.config)},[e,n]),!n||!e)return null;let u=(0,a.jsxs)("div",{className:"space-y-6 py-4",children:[(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(e9.J,{children:"Detection Method"}),(0,a.jsxs)(ts.z,{value:d.detectionMode,onValueChange:e=>{c(t=>({...t,detectionMode:e}))},className:"space-y-1",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(ts.C,{value:"spike",id:"r1"}),(0,a.jsx)(e9.J,{htmlFor:"r1",className:"font-normal",children:"Spike After Gap"})]}),(0,a.jsx)("p",{className:"text-xs text-gray-500 pl-6 pt-1",children:"Looks for a zero-payment period followed by a significant payment spike."})]}),(0,a.jsxs)("div",{className:"pt-2",children:[(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(ts.C,{value:"intra-period",id:"r2"}),(0,a.jsx)(e9.J,{htmlFor:"r2",className:"font-normal",children:"Consecutive Gaps"})]}),(0,a.jsx)("p",{className:"text-xs text-gray-500 pl-6 pt-1",children:"Looks for consecutive empty periods between the first and last customer payments."})]})]})]}),"spike"===d.detectionMode&&(0,a.jsxs)("div",{className:"space-y-3 pt-4 border-t border-gray-200",children:[(0,a.jsx)(e9.J,{children:"Spike Threshold Multiplier"}),(0,a.jsx)(e7.A,{value:[d.threshold||1.5],onValueChange:e=>{c(t=>({...t,threshold:e[0]}))},min:d.min||1.2,max:d.max||3,step:d.step||.1}),(0,a.jsxs)("p",{className:"text-xs text-gray-500 text-center",children:["Flags a gap if the next payment is ",void 0===(o=d.threshold)?"":`${Math.round((o-1)*100)}%`," the previous average."]})]}),"intra-period"===d.detectionMode&&(0,a.jsxs)("div",{className:"space-y-3 pt-4 border-t border-gray-200",children:[(0,a.jsx)(e9.J,{htmlFor:"gap-threshold",children:"Maximum Consecutive Missing Periods"}),(0,a.jsx)(ta.p,{id:"gap-threshold",type:"number",value:d.gapThresholdMonths||3,onChange:e=>{let t=parseInt(e.target.value,10);isNaN(t)||c(e=>({...e,gapThresholdMonths:t}))},min:"1",className:"w-24"}),(0,a.jsx)("p",{className:"text-xs text-gray-500",children:"Flags gaps of up to this many periods. Longer gaps are ignored as potential churn."})]})]}),p=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eG.$,{variant:"outline",onClick:t,disabled:r,children:"Cancel"}),(0,a.jsx)(eG.$,{onClick:()=>{i(d),t()},disabled:r||JSON.stringify(d)===JSON.stringify(n.config),children:r?"Applying...":"Save & Re-detect"})]});return"inline"===l?(0,a.jsxs)("div",{"data-testid":"missing-payment-settings-editor",children:[u,(0,a.jsx)("div",{className:"flex items-center justify-end gap-2 border-t border-[#E5EAF0] pt-4",children:p})]}):(0,a.jsx)(e8.lG,{open:e,onOpenChange:t,children:(0,a.jsxs)(e8.Cf,{className:"sm:max-w-[425px]",children:[(0,a.jsxs)(e8.c7,{children:[(0,a.jsx)(e8.L3,{children:"Missing Payments Rule Settings"}),(0,a.jsx)(e8.rr,{children:"Choose a detection method and adjust its settings."})]}),u,(0,a.jsx)(e8.Es,{children:p})]})})};var tl=n(9192);let to=({id:e,checked:t,onCheckedChange:n,disabled:s,label:i,tooltip:r,hint:l,tooltipContentClassName:o,tooltipTextClassName:d="text-xs"})=>(0,a.jsxs)("div",{className:"flex items-start space-x-3",children:[(0,a.jsx)(tl.S,{id:e,checked:t,onCheckedChange:e=>n(e),disabled:s}),(0,a.jsxs)("div",{className:"space-y-1 flex-1",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(e9.J,{htmlFor:e,className:"font-medium cursor-pointer",children:i}),(0,a.jsx)(tt.Bc,{children:(0,a.jsxs)(tt.m_,{children:[(0,a.jsx)(tt.k$,{asChild:!0,children:(0,a.jsx)(te.A,{className:"w-4 h-4 text-gray-400 cursor-help"})}),(0,a.jsx)(tt.ZI,{side:"right",className:o,children:(0,a.jsx)("p",{className:d,children:r})})]})})]}),(0,a.jsx)("p",{className:"text-xs text-gray-500",children:l})]})]}),td=({isOpen:e,onClose:t,detectQuarterly:n,detectAnnual:i,enableSinglePaymentDetection:r,enableAnnualSingletonDetection:l,onSave:o,isProcessing:d=!1,presentation:c="dialog"})=>
1{let[u,p]=(0,s.useState)(n),[m,h]=(0,s.useState)(i),[g,x]=(0,s.useState)(r),[v,f]=(0,s.useState)(l);(0,s.useEffect)(()=>{e&&(p(n),h(i),x(r),f(l))},[e,n,i,r,l]);let b=u!==n||m!==i||g!==r||v!==l,y=u||m;if(!e)return null;let w=(0,a.jsxs)("div",{className:"space-y-6 py-4",children:[(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsx)(to,{id:"quarterly",checked:u,onCheckedChange:p,disabled:d,label:"Quarterly Payments",tooltip:"Detects customers who pay exactly every 3 months, indicating quarterly billing cycles.",tooltipContentClassName:"max-w-xs",hint:"Example: Payments in Jan, Apr, Jul, Oct"}),(0,a.jsx)(to,{id:"annual",checked:m,onCheckedChange:h,disabled:d,label:"Annual Payments",tooltip:"Detects customers who pay once per year in the same month, indicating annual billing cycles.",tooltipContentClassName:"max-w-xs",hint:"Example: Payments only in March each year"}),(0,a.jsx)(to,{id:"singlePayment",checked:g,onCheckedChange:x,disabled:d,label:"Detect Single Payments in the Last Year",tooltip:"When historical annual or quarterly patterns exist elsewhere in the dataset, detect a single interior payment that falls within the last year of visible data.",tooltipTextClassName:"text-xs leading-relaxed",hint:"Keeps the original recent single-payment detection behavior."}),(0,a.jsx)(to,{id:"annualSingleton",checked:v,onCheckedChange:f,disabled:d,label:"Include Single Annual Payments",tooltip:"When Annual Payments detection is enabled, customers with exactly one interior payment are still shown as annual spread-forward candidates.",tooltipTextClassName:"text-xs leading-relaxed",hint:"Use for customers with only one annual payment in the data. Only applies when Annual Payments detection is enabled."})]}),!y&&(0,a.jsx)("div",{className:"bg-amber-50 border border-amber-200 p-3 rounded-lg",children:(0,a.jsxs)("p",{className:"text-xs text-amber-800",children:[(0,a.jsx)("strong",{children:"Note:"})," At least one pattern type must be selected for detection to work."]})})]}),j=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eG.$,{variant:"outline",onClick:t,disabled:d,children:"Cancel"}),(0,a.jsx)(eG.$,{onClick:()=>{o(u,m,g,v)},disabled:d||!b||!y,children:d?"Applying...":"Save & Re-detect"})]});return"inline"===c?(0,a.jsxs)("div",{"data-testid":"payment-pattern-settings-editor",children:[w,(0,a.jsx)("div",{className:"flex items-center justify-end gap-2 border-t border-[#E5EAF0] pt-4",children:j})]}):(0,a.jsx)(e8.lG,{open:e,onOpenChange:t,children:(0,a.jsxs)(e8.Cf,{className:"sm:max-w-[425px]",children:[(0,a.jsxs)(e8.c7,{children:[(0,a.jsx)(e8.L3,{children:"Payment Pattern Detection Settings"}),(0,a.jsx)(e8.rr,{children:"Choose which payment patterns to detect in your revenue data."})]}),w,(0,a.jsx)(e8.Es,{children:j})]})})},tc=({isOpen:e,onClose:t,monthlyMultiplierMin:n,monthlyMultiplierMax:i,quarterlyMultiplierMin:r,quarterlyMultiplierMax:l,onSave:o,isProcessing:d=!1,presentation:c="dialog"})=>{let[u,p]=(0,s.useState)(n),[m,h]=(0,s.useState)(i),[g,x]=(0,s.use
1State)(r),[v,f]=(0,s.useState)(l);(0,s.useEffect)(()=>{e&&(p(n),h(i),x(r),f(l))},[e,n,i,r,l]);let b=u!==n||m!==i||g!==r||v!==l,y=u>0&&m>u&&g>0&&v>g;if(!e)return null;let w=(0,a.jsxs)("div",{className:"grid gap-6 py-4",children:[(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(e9.J,{className:"text-sm font-medium",children:"Monthly Plan Conversions"}),(0,a.jsxs)(tt.m_,{children:[(0,a.jsx)(tt.k$,{children:(0,a.jsx)(te.A,{className:"h-4 w-4 text-gray-400"})}),(0,a.jsx)(tt.ZI,{children:(0,a.jsx)("p",{children:"Detects when customers switch from monthly to annual billing"})})]})]}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(e9.J,{htmlFor:"monthlyMin",className:"text-xs text-gray-600",children:"Min Multiplier"}),(0,a.jsx)(ta.p,{id:"monthlyMin",type:"number",min:"1",max:"20",step:"0.5",value:u,onChange:e=>p(Number(e.target.value)),className:"mt-1"})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(e9.J,{htmlFor:"monthlyMax",className:"text-xs text-gray-600",children:"Max Multiplier"}),(0,a.jsx)(ta.p,{id:"monthlyMax",type:"number",min:"1",max:"20",step:"0.5",value:m,onChange:e=>h(Number(e.target.value)),className:"mt-1"})]})]}),(0,a.jsxs)("p",{className:"text-xs text-gray-500",children:["Spike must be ",u,"x to ",m,"x the baseline (typically 7-12x for annual plans)"]})]}),(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(e9.J,{className:"text-sm font-medium",children:"Quarterly Plan Conversions"}),(0,a.jsxs)(tt.m_,{children:[(0,a.jsx)(tt.k$,{children:(0,a.jsx)(te.A,{className:"h-4 w-4 text-gray-400"})}),(0,a.jsx)(tt.ZI,{children:(0,a.jsx)("p",{children:"Detects when customers switch from quarterly to annual billing"})})]})]}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(e9.J,{htmlFor:"quarterlyMin",className:"text-xs text-gray-600",children:"Min Multiplier"}),(0,a.jsx)(ta.p,{id:"quarterlyMin",type:"number",min:"1",max:"10",step:"0.1",value:g,onChange:e=>x(Number(e.target.value)),className:"mt-1"})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(e9.J,{htmlFor:"quarterlyMax",className:"text-xs text-gray-600",children:"Max Multiplier"}),(0,a.jsx)(ta.p,{id:"quarterlyMax",type:"number",min:"1",max:"10",step:"0.1",value:v,onChange:e=>f(Number(e.target.value)),className:"mt-1"})]})]}),(0,a.jsxs)("p",{className:"text-xs text-gray-500",children:["Spike must be ",g,"x to ",v,"x the baseline (typically 2.5-4x for annual plans)"]})]})]}),j=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eG.$,{variant:"outline",onClick:t,disabled:d,children:"Cancel"}),(0,a.jsx)(eG.$,{onClick:()=>{o({monthlyMultiplierMin:u,monthlyMultiplierMax:m,quarterlyMultiplierMin:g,quarterlyMultiplierMax:v})},disabled:!b||!y||d,children:d?"inline"===c?"Applying...":"Saving...":"inline"===c?"Save & Re-detect":"Save Changes"})]});return"inline"===c?(0,a.jsxs)("div",{"data-testid":"payment-plan-settings-editor",children:[w,(0,a.jsx)("div",{className:"flex items-center justify-end gap-2 border-t border-[#E5EAF0] pt-4",children:j})]}):(0,a.jsx)(e8.lG,{open:e,onOpenChange:t,children:(0,a.jsxs)(e8.Cf,{className:"sm:max-w-[500px]",children:[(0,a.jsxs)(e8.c7,{children:[(0,a.jsx)(e8.L3,{children:"Payment Plan Conversion Settings"}),(0,a.jsx)(e8.rr,{children:"Configure the detection thresholds for payment plan conversions."})]}),w,(0,a.jsx)(e8.Es,{children:j})]})})},tu=e=>{let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null},tp=({isOpen:e,onClose:t,currentThreshold:n,currentMaxConsecutiveSpikePeriods:i,temporaryElevatedRegimeEnabled:r=!1,temporaryElevatedRegimeMinMultiplier:l=e4.yg,temporaryElevatedRegimeMaxPeriods:o=e4.Zw,onSave:d,isProcessing:c=!1,presentation:u="dialog"})=>{let[p,m]=(0,s.useState)(n),[h,g]=(0,s.useState)(i.toString()),x=tu(h),v=null!==x&&x>=1&&x<=12,f=""===h.trim()?"Enter a number from 1 to 12.":null===x?"Use whole numbers only.":x<1?"Enter at least 1 period.":x>12?"Enter 12 periods or fewer.":null;if((0,s.useEffect)(()=>{e&&(m(n),g(i.toString()))},[e,n,i]),!e)return null;let b=(0,a.jsxs)("div",{className:"space-y-6 py-4",children:[(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(e9.J,{htmlFor:"threshold",children:"High-Spike Threshold"}),(0,a.jsx)(tt.Bc,{children:(0,a.jsxs)(tt.m_,{children:[(0,a.jsx)(tt.k$,{asChild:!0,children:(0,a.jsx)(te.A,{className:"w-4 h-4 text-gray-400 cursor-help"})}),(0,a.jsx)(tt.ZI,{side:"right",className:"max-w-xs",children:(0,a.jsx)("p",{className:"text-xs",children:"The minimum increase above the recent average needed to start an isolated or high-magnitude spike run. Lower values detect more high spikes; higher values are more selective."})})]})})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(e7.A,{id:"threshold",min:10,max:1e3,step:10,value:[p],onValueChange:e=>m(e[0]),className:"w-full"}),(0,a.jsxs)("div",{className:"flex justify-between text-xs text-gray-500",children:[(0,a.jsx)("span",{children:"10% increase"}),(0,a.jsxs)("span",{className:"font-medium text-gray-700 text-sm",children:[`${p}%`," increase required"]}),(0,a.jsx)("span",{children:"1000% increase"})]})]})]}),(0,a.jsxs)("div",{className:"space-y-3 pt-4 border-t border-gray-200",children:[(0,a.jsx)(e9.J,{htmlFor:"max-consecutive-spike-periods",children:"Maximum High-Spike Run Length"}),(0,a.jsx)(ta.p,{id:"max-consecutive-spike-periods",type:"number",value:h,onChange:e=>{let{value:t}=e.target;/^\d*$/.test(t)&&g(t)},onBlur:()=>{null===tu(h)&&g(i.toString())},onFocus:e=>e.currentTarget.select(),min:1,max:12,inputMode:"numeric","aria-invalid":!v,"aria-describedby":f?"max-consecutive-spike-periods-error":void 0,className:`w-24 ${!v?"border-red-500 focus-visible:ring-red-500":""}`}),f&&(0,a.jsx)("p",{id:"max-consecutive-spike-periods-error",className:"text-xs text-red-600",children:f}),(0,a.jsx)("p",{className:"text-xs text-gray-500",children:"Applies to threshold-based high-spike runs from 1 period through this number. Use 6 to include high-spike runs up to six periods."})]}),(0,a.jsxs)("div",{className:"space-y-2 border-t border-gray-200 pt-4",children:[(0,a.jsx)(e9.J,{children:"Temporary Elevated Regimes"}),(0,a.jsx)("p",{className:"text-xs text-gray-500",children:r?`Separately reviews bounded 2â${o}-month regimes when every value is at least ${l}\xd7 comparable pre- and post-regime baselines.`:"This separate bounded-regime review is disabled."})]})]}),y=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eG.$,{variant:"outline",onClick:t,disabled:c,
1children:"Cancel"}),(0,a.jsx)(eG.$,{onClick:()=>{let e=tu(h);null===e||e<1||e>12||d(p,e)},disabled:c||!v||p===n&&x===i,children:c?"Applying...":"Save & Re-detect"})]});return"inline"===u?(0,a.jsxs)("div",{"data-testid":"spike-settings-editor",children:[b,(0,a.jsx)("div",{className:"flex items-center justify-end gap-2 border-t border-[#E5EAF0] pt-4",children:y})]}):(0,a.jsx)(e8.lG,{open:e,onOpenChange:t,children:(0,a.jsxs)(e8.Cf,{className:"sm:max-w-[480px]",children:[(0,a.jsxs)(e8.c7,{children:[(0,a.jsx)(e8.L3,{children:"Revenue Spike Detection Settings"}),(0,a.jsx)(e8.rr,{children:"Configure isolated and high-magnitude spike runs. Bounded elevated regimes are reviewed separately under the policy shown below."})]}),b,(0,a.jsx)(e8.Es,{children:y})]})})};var tm=n(90568),th=n(39419);function tg({value:e,max:t,customerCount:n,rowCount:i,windowLabel:r,onApply:l,placement:o="settings"}){let d=Math.max(1,Math.trunc(t)),c=(0,V.n4)(e,d),[u,p]=s.useState(c);s.useEffect(()=>{p(c)},[c]);let m=(0,V.n4)(u,d),h=m!==c;return(0,a.jsxs)("div",{className:"settings"===o?"flex min-h-16 shrink-0 flex-wrap items-center gap-x-3 gap-y-2 rounded-md border border-[#D8DEE8] bg-white px-3 py-2":"flex min-h-11 shrink-0 items-center gap-3 border-b border-[#E5E7EB] bg-[#F8FAFC] px-3","data-testid":"recent-churn-filter-control","data-control-placement":o,children:[(0,a.jsxs)("div",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,a.jsx)("span",{className:"shrink-0 text-[12px] font-semibold text-[#0E1624]",children:"Recent churns"}),(0,a.jsxs)("span",{className:"min-w-0 truncate text-[11px] tabular-nums text-[#64748B]","data-testid":"recent-churn-result-count","aria-live":"polite",children:[n," ",1===n?"customer":"customers",i!==n?` \xb7 ${i} rows`:""," \xb7"," ",r]})]}),(0,a.jsxs)("label",{className:"flex shrink-0 items-center gap-2 text-[11px] font-medium text-[#475569]",children:["Last",(0,a.jsx)(th.P,{value:m,max:d,ariaLabel:"Churn lookback periods",onValueChange:p,className:"gap-1.5",inputClassName:"h-8 w-12 text-[12px]"}),(0,a.jsx)("span",{children:1===m?"period":"periods"})]}),(0,a.jsx)("button",{type:"button","data-testid":"apply-recent-churn-lookback",disabled:!h,onClick:()=>l(m),className:"inline-flex h-8 shrink-0 items-center rounded-md bg-[#2563FF] px-3 text-[11px] font-semibold text-white transition-colors hover:bg-[#1D4ED8] disabled:cursor-default disabled:bg-[#E2E8F0] disabled:text-[#94A3B8]",children:"Apply"})]})}let tx={patterns:"Choose which payment cadences Quikirr should detect.",gaps:"Choose how missing payments are identified.",spikes:"Configure high-magnitude spikes and review the separate bounded-regime policy.",plan_conversion:"Set the multipliers used to detect payment-plan changes.",de_minimis:"Choose how minimal revenue histories should be flagged."};function tv({embedded:e,recentChurnEditorOpen:t,setRecentChurnEditorOpen:n,displayCategory:s,headingRef:i,focusedLabel:r,activeCategory:l,initialCategory:o,initialCategoryAvailability:d,smoothingServiceReady:c,returnToParent:u,exitActiveEditor:p,cancelActiveEditor:m,recentChurnLookbackPeriods:h,monthKeys:g,recentChurnCustomerCount:x,recentChurnRowCount:v,setRecentChurnLookbackPeriods:f,patterns:b,missing:y,spikes:w,plans:j,deMinimis:C,rows:_}){return(0,a.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"cleaning-rules-subthread",children:[!e||t?(0,a.jsxs)("div",{className:"flex items-center gap-2 pb-1",children:[(0,a.jsx)(eQ.h,{testId:t?"cleaning-recent-churn-editor-back":s?"cleaning-rule-editor-back":"cleaning-rules-subthread-back",onClick:t?()=>n(!1):l?()=>p("back"):u}),(0,a.jsx)("h3",{ref:i,tabIndex:-1,className:"min-w-0 flex-1 truncate text-[12.5px] font-semibold text-[#0E1624] focus:outline-hidden",children:r})]}):null,(0,a.jsx)("p",{className:"px-1 text-[12px] leading-5 text-[#64748B]",children:t?"Choose how many recent periods to inspect for churn.":s?tx[s]:"Adjust what Quikirr flags. Saving a rule re-runs anomaly detection."}),t?(0,a.jsx)(tg,{placement:"settings",value:h,max:Math.max(1,g.length-1),customerCount:x,rowCount:v,windowLabel:(0,V.JK)({lookbackPeriods:h,periodLabels:g}),onApply:f}):"patterns"===l?(0,a.jsx)(td,{isOpen:!0,presentation:"inline",onClose:m,detectQuarterly:b.detectQuarterly,detectAnnual:b.detectAnnual,enableSinglePaymentDetection:b.enableSinglePaymentDetection,enableAnnualSingletonDetection:b.enableAnnualSingletonDetection,onSave:b.updateSettings,isProcessing:b.isUpdating}):"gaps"===l?(0,a.jsx)(tr,{isOpen:!0,presentation:"inline",onClose:m,rule:y.rule,onSave:y.updateConfig,isProcessing:y.isUpdating}):"spikes"===l?(0,a.jsx)(tp,{isOpen:!0,presentation:"inline",onClose:m,currentThreshold:w.currentThreshold,currentMaxConsecutiveSpikePeriods:w.currentMaxConsecutiveSpikePeriods,temporaryElevatedRegimeEnabled:w.isTemporaryElevatedRegimeDetectionEnabled,temporaryElevatedRegimeMinMultiplier:w.currentTemporaryElevatedRegimeMinMultiplier,temporaryElevatedRegimeMaxPeriods:w.currentTemporaryElevatedRegimeMaxPeriods,onSave:w.updateSettings,isProcessing:w.isUpdating}):"plan_conversion"===l?(0,a.jsx)(tc,{isOpen:!0,presentation:"inline",onClose:m,...j.config,onSave:j.saveConfig,isProcessing:j.isProcessing}):"de_minimis"===l?(0,a.jsx)(ti,{isOpen:!0,presentation:"inline",onClose:m,monthThreshold:C.monthThreshold,quarterThreshold:C.quarterThreshold,requireContiguous:C.requireContiguous,revenueThreshold:C.revenueThreshold,deMinimisMode:C.deMinimisMode,onSave:C.updateSettings,isProcessing:C.isUpdating}):o&&!d.available?(0,a.jsxs)("p",{role:"alert",className:"rounded-md border border-[#F5D99B] bg-[#FFFBEB] px-3 py-2 text-[12px] leading-5 text-[#8A5A00]",children:[d.blockedReason," Nothing was changed."]}):c?o?(0,a.jsx)("p",{role:"status",className:"px-1 text-[12px] leading-5 text-[#64748B]",children:"Loading detection settingsâ¦"}):(0,a.jsxs)("ul",{className:"space-y-2","aria-label":"Detection rules",children:[(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",onClick:()=>n(!0),"data-testid":"cleaning-rules-recent-churn",className:"group flex min-h-14 w-full items-center gap-3 rounded-md border border-[#DCE5F1] bg-white px-3 py-2 text-left transition-colors hover:bg-[#F8FAFC] focu
1s-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30","aria-label":`Configure Recent churns. ${x.toLocaleString()} customers in the ${(0,V.JK)({lookbackPeriods:h,periodLabels:g})}`,children:[(0,a.jsx)("span",{className:"h-2.5 w-2.5 shrink-0 rounded-full bg-[#2563FF]","aria-hidden":"true"}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block text-[12.5px] font-semibold text-[#334E78]",children:"Recent churns"}),(0,a.jsxs)("span",{className:"mt-0.5 block text-[11.5px] leading-4 text-[#64748B]",children:[x.toLocaleString()," customer",1===x?"":"s"," \xb7"," ",(0,V.JK)({lookbackPeriods:h,periodLabels:g})]})]}),(0,a.jsx)(eJ.A,{className:"h-3.5 w-3.5 shrink-0 text-[#94A3B8] transition-colors group-hover:text-[#475569]","aria-hidden":"true"})]})}),_.map(e=>{let t=e6.L[e.category];return(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",onClick:e.onOpen,disabled:e.busy,"data-testid":`cleaning-rule-${e.category}`,"data-tone":t.tone,className:(0,tm.cn)("group flex min-h-14 w-full items-center gap-3 rounded-md border px-3 py-2 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[#2563FF]/30 disabled:cursor-not-allowed disabled:opacity-60",t.rowClassName),"aria-label":`Configure ${t.label}. ${e.summary}`,children:[(0,a.jsx)("span",{className:(0,tm.cn)("h-2.5 w-2.5 shrink-0 rounded-full",t.dotClassName),"aria-hidden":"true"}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:(0,tm.cn)("block text-[12.5px] font-semibold",t.textClassName),children:t.label}),(0,a.jsx)("span",{className:"mt-0.5 block text-[11.5px] leading-4 text-[#64748B]",children:e.busy?"Applying and re-checkingâ¦":e.summary})]}),(0,a.jsx)(eJ.A,{className:"h-3.5 w-3.5 shrink-0 text-[#94A3B8] transition-colors group-hover:text-[#475569]","aria-hidden":"true"})]})},e.category)})]}):(0,a.jsx)("p",{role:"alert",className:"rounded-md border border-[#F5D99B] bg-[#FFFBEB] px-3 py-2 text-[12px] leading-5 text-[#8A5A00]",children:"Detection rules are unavailable until the source data is ready. Nothing was changed."})]})}let tf={patterns:"frequency",gaps:"missing",spikes:"variations",plan_conversion:"plan_conversion",de_minimis:"de_minimis"},tb=[];function ty({analysisId:e,surface:t="cleaning_navigation",onBack:n,initialCategory:i=null,embedded:l=!1}){let c=s.useRef(null),[u,p]=s.useState(!1),g=s.useRef(null),x=s.useRef(!1),v=(0,r.Tj)(e=>e.rules.arrCalculationMethod),f=(0,S.jB)(e=>e.recentChurnLookbackPeriods),b=(0,S.jB)(e=>e.setRecentChurnLookbackPeriods),y=(0,S.jB)(e=>e.recentChurnReviewRows),w=(0,m.useAnalysisMetadataStore)(e=>e.metadata),j=w?.monthKeys??tb,C=s.useMemo(()=>new Set(y.map(e=>e.customerId)).size,[y]),{service:_}=(0,o.H)(),k=s.useMemo(()=>Object.fromEntries(Object.entries(tf).map(([n,a])=>[n,e?{analysisId:e,surface:t,category:n,ruleId:a}:void 0])),[e,t]),N=(e=>{let[t,n]=(0,s.useState)(!1),[a,i]=(0,s.useState)(!0),[r,l]=(0,s.useState)(!0),[d,c]=(0,s.useState)(!1),[u,p]=(0,s.useState)(!1),[m,g]=(0,s.useState)(!1),{service:x}=(0,o.H)();(0,s.useEffect)(()=>{if(!x)return;let e=x.getRuleConfig("frequency");e&&(i(e.detectQuarterly??!0),l(e.detectAnnual??!0),c(e.enableSinglePaymentDetection??!1),p(e.enableAnnualSingletonDetection??!1))},[x]);let v=(0,s.useCallback)(()=>{if(!x)return;let e=x.getRuleConfig("frequency");e&&(i(e.detectQuarterly??!0),l(e.detectAnnual??!0),c(e.enableSinglePaymentDetection??!1),p(e.enableAnnualSingletonDetection??!1)),n(!0)},[x]),f=(0,s.useCallback)(()=>{n(!1)},[]),b=(0,s.useCallback)(async(t,n,s,o)=>{if(!x)return void h.vF.error("Smoothing service not available for payment-pattern rule update",{fallback_state:"cleaning_rule_service_unavailable",ruleId:"frequency"});g(!0);try{h.vF.info("Updating payment pattern detection settings",{detectQuarterly:t,detectAnnual:n,enableSinglePaymentDetection:s,enableAnnualSingletonDetection:o});let m=await (0,eZ.J_)({context:e,previousConfiguration:{detectQuarterly:a,detectAnnual:r,enableSinglePaymentDetection:d,enableAnnualSingletonDetection:u},nextConfiguration:{detectQuarterly:t,detectAnnual:n,enableSinglePaymentDetection:s,enableAnnualSingletonDetection:o},run:()=>x.updateRuleAndRedetect("frequency",{detectQuarterly:t,detectAnnual:n,enableSinglePaymentDetection:s,enableAnnualSingletonDetection:o})});if(m.success){i(t),l(n),c(s),p(o);let e=[];t&&e.push("quarterly"),n&&e.push("annual");let a=e.length>0?`Detecting ${e.join(" and ")} patterns`:"All pattern detection disabled",r=s?" (recent single payment detection enabled)":"",d=o?" (single annual payment candidates enabled)":"";
1e2.lY.notify({heading:"Settings Updated",message:`${a}${r}${d}. ${m.candidateCount||0} patterns detected.`,type:"success"}),f()}else e2.lY.notify({heading:"Update Failed",message:m.error||"Failed to update detection settings",type:"error"})}catch(e){h.vF.error("Error updating payment pattern settings",{error:e}),e2.lY.notify({heading:"Update Failed",message:"An unexpected error occurred while updating settings",type:"error"})}finally{g(!1)}},[x,f,e,a,r,d,u]);return{isModalOpen:t,openModal:v,closeModal:f,detectQuarterly:a,detectAnnual:r,enableSinglePaymentDetection:d,enableAnnualSingletonDetection:u,updateSettings:b,isUpdating:m}})(k.patterns),R=(e=>{let[t,n]=(0,s.useState)(!1),[a,i]=(0,s.useState)(void 0),[r,l]=(0,s.useState)(!1),{service:d}=(0,o.H)(),c=(0,s.useCallback)(()=>{if(!d)return;let e=d.getRules().find(e=>"missing"===e.id);e&&i(e)},[d]);(0,s.useEffect)(()=>{c()},[c]);let u=(0,s.useCallback)(()=>{c(),n(!0)},[c]),p=(0,s.useCallback)(()=>{n(!1)},[]),m=(0,s.useCallback)(async t=>{if(!d)return void h.vF.error("Smoothing service not available for missing-payment rule update",{fallback_state:"cleaning_rule_service_unavailable",ruleId:"missing"});l(!0);try{h.vF.info("Updating missing payment rule config",{config:t});let n=await (0,eZ.J_)({context:e,previousConfiguration:{...a?.config??{}},nextConfiguration:{...a?.config??{},...t},run:()=>d.updateRuleAndRedetect("missing",t)});n.success?(c(),e2.lY.notify({heading:"Settings Updated",message:`Missing payment detection settings updated. ${n.candidateCount||0} patterns detected.`,type:"success"}),p()):e2.lY.notify({heading:"Update Failed",message:n.error||"Failed to update detection settings",type:"error"})}catch(e){h.vF.error("Error updating missing payment rule config",{error:e}),e2.lY.notify({heading:"Update Failed",message:"An unexpected error occurred while updating settings",type:"error"})}finally{l(!1)}},[d,p,c,e,a?.config]);return{isModalOpen:t,openModal:u,closeModal:p,rule:a,updateConfig:m,isUpdating:r}})(k.gaps),A=(e=>{let[t,n]=(0,s.useState)(!1),[a,i]=(0,s.useState)(450),[r,l]=(0,s.useState)(1),[d,c]=(0,s.useState)(!1),[u,p]=(0,s.useState)(e4.yg),[m,g]=(0,s.useState)(e4.Zw),[x,v]=(0,s.useState)(!1),{service:f}=(0,o.H)(),b=(0,s.useCallback)(()=>{if(!f)return;let e=f.getRuleConfig("variations");e?.threshold&&i(e.threshold),e?.maxConsecutiveSpikePeriods&&l(e.maxConsecutiveSpikePeriods);let t=(0,e4.$t)(e);c(t.enabled),p(t.minMultiplier),g(t.maxPeriods)},[f]);(0,s.useEffect)(()=>{b()},[b]);let y=(0,s.useCallback)(()=>{f&&(b(),n(!0))},[f,b]),w=(0,s.useCallback)(()=>{n(!1)},[]),j=(0,s.useCallback)(async(t,n)=>{if(!f)return void h.vF.error("Smoothing service not available for spike rule update",{fallback_state:"cleaning_rule_service_unavailable",ruleId:"variations"});v(!0);try{h.vF.info("Updating spike detection settings",{oldThreshold:a,newThreshold:t,oldMaxConsecutiveSpikePeriods:r,newMaxConsecutiveSpikePeriods:n,temporaryElevatedRegimePolicy:{enabled:d,minMultiplier:u,maxPeriods:m}});let s=await (0,eZ.J_)({context:e,previousConfiguration:{threshold:a,maxConsecutiveSpikePeriods:r,detectTemporaryElevatedRegimes:d,temporaryElevatedRegimeMinMultiplier:u,temporaryElevatedRegimeMaxPeriods:m},nextConfiguration:{threshold:t,maxConsecutiveSpikePeriods:n,detectTemporaryElevatedRegimes:d,temporaryElevatedRegimeMinMultiplier:u,temporaryElevatedRegimeMaxPeriods:m},run:()=>f.updateRuleAndRedetect("variations",{threshold:t,maxConsecutiveSpikePeriods:n})});s.success?(i(t),l(n),e2.lY.notify({heading:"Settings Updated",message:`High-spike detection updated to ${t}% for up to ${n} consecutive periods. `+(d?`Temporary elevated-regime review remains ${u}\xd7 for up to ${m} months. `:"Temporary elevated-regime review remains disabled. ")+`${s.candidateCount||0} patterns detected.`,type:"success"}),w()):e2.lY.notify({heading:"Update Failed",message:s.error||"Failed to update detection settings",type:"error"})}catch(e){h.vF.error("Error updating spike detection threshold",{error:e}),e2.lY.notify({heading:"Update Failed",message:"An unexpected error occurred while updating settings",type:"error"})}finally{v(!1)}},[a,r,d,u,m,f,w,e]);
1return{isModalOpen:t,openModal:y,closeModal:w,currentThreshold:a,currentMaxConsecutiveSpikePeriods:r,isTemporaryElevatedRegimeDetectionEnabled:d,currentTemporaryElevatedRegimeMinMultiplier:u,currentTemporaryElevatedRegimeMaxPeriods:m,updateSettings:j,updateThreshold:j,isUpdating:x}})(k.spikes),F=(e=>{let[t,n]=(0,s.useState)(!1),[a,i]=(0,s.useState)(!1),[r,l]=(0,s.useState)(e3),{service:d}=(0,o.H)(),c=(0,s.useCallback)(()=>{if(!d)return;let e=d.getRuleConfig("plan_conversion");l({monthlyMultiplierMin:e?.monthlyMultiplierMin??e3.monthlyMultiplierMin,monthlyMultiplierMax:e?.monthlyMultiplierMax??e3.monthlyMultiplierMax,quarterlyMultiplierMin:e?.quarterlyMultiplierMin??e3.quarterlyMultiplierMin,quarterlyMultiplierMax:e?.quarterlyMultiplierMax??e3.quarterlyMultiplierMax})},[d]);(0,s.useEffect)(()=>{c()},[c]);let u=(0,s.useCallback)(()=>{d?(c(),n(!0)):h.vF.error("Payment-plan rule settings require the smoothing service",{fallback_state:"cleaning_rule_service_unavailable",ruleId:"plan_conversion"})},[c,d]),p=(0,s.useCallback)(()=>{n(!1)},[]),m=(0,s.useCallback)(async t=>{if(!d)return void h.vF.error("Payment-plan rule update could not reach the smoothing service",{fallback_state:"cleaning_rule_service_unavailable",ruleId:"plan_conversion"});i(!0);try{let a=await (0,eZ.J_)({context:e,previousConfiguration:{...r},nextConfiguration:{...t},run:()=>d.updateRuleAndRedetect("plan_conversion",t)});if(!a.success)return void e2.lY.notify({heading:"Update Failed",message:a.error||"Failed to update plan-conversion detection",type:"error"});l(t),n(!1),e2.lY.notify({heading:"Settings Updated",message:`Plan-conversion detection updated. ${a.candidateCount??0} anomalies detected.`,type:"success"})}catch(e){h.vF.error("Error updating payment-plan detection settings",{error:e,ruleId:"plan_conversion"}),e2.lY.notify({heading:"Update Failed",message:"An unexpected error occurred while updating settings",type:"error"})}finally{i(!1)}},[r,e,d]);return{isModalOpen:t,isProcessing:a,config:r,openModal:u,closeModal:p,saveConfig:m}})(k.plan_conversion),M=(e=>{let[t,n]=(0,s.useState)(!1),[a,i]=(0,s.useState)(3),[r,l]=(0,s.useState)(1),[d,c]=(0,s.useState)(!0),[u,p]=(0,s.useState)(1e4),[m,g]=(0,s.useState)("period"),[x,v]=(0,s.useState)(!1),{service:f}=(0,o.H)();(0,s.useEffect)(()=>{if(!f)return;let e=f.getRuleConfig("de_minimis");e&&(i(e.monthThreshold??3),l(e.quarterThreshold??1),c(e.requireContiguous??!0),p(e.revenueThreshold??1e4),g(e.deMinimisMode??"period"))},[f]);let b=(0,s.useCallback)(()=>{if(!f)return;let e=f.getRuleConfig("de_minimis");e&&(i(e.monthThreshold??3),l(e.quarterThreshold??1),c(e.requireContiguous??!0),p(e.revenueThreshold??1e4),g(e.deMinimisMode??"period")),n(!0)},[f]),y=(0,s.useCallback)(()=>{n(!1)},[]),w=(0,s.useCallback)(async t=>{if(!f)return void h.vF.error("Smoothing service not available for de minimis rule update",{fallback_state:"cleaning_rule_service_unavailable",ruleId:"de_minimis"});v(!0);try{h.vF.info("Updating de minimis settings",t);let n=await (0,eZ.J_)({context:e,previousConfiguration:{monthThreshold:a,quarterThreshold:r,requireContiguous:d,revenueThreshold:u,deMinim
1isMode:m},nextConfiguration:t,run:()=>f.updateRuleAndRedetect("de_minimis",t)});if(n.success){let e;if(i(t.monthThreshold),l(t.quarterThreshold),c(t.requireContiguous),p(t.revenueThreshold),g(t.deMinimisMode),"revenue"===t.deMinimisMode)e=`De minimis detection updated to revenue threshold of $${t.revenueThreshold.toLocaleString()}. ${n.candidateCount||0} customers detected.`;else{let a=t.requireContiguous?"consecutive":"sparse";e=`De minimis detection updated to ${t.monthThreshold} months (${a}). ${n.candidateCount||0} customers detected.`}e2.lY.notify({heading:"Settings Updated",message:e,type:"success"}),y()}else e2.lY.notify({heading:"Update Failed",message:n.error||"Failed to update detection settings",type:"error"})}catch(e){h.vF.error("Error updating de minimis settings",{error:e}),e2.lY.notify({heading:"Update Failed",message:"An unexpected error occurred while updating settings",type:"error"})}finally{v(!1)}},[f,y,e,a,r,d,u,m]);return{isModalOpen:t,openModal:b,closeModal:y,monthThreshold:a,quarterThreshold:r,requireContiguous:d,revenueThreshold:u,deMinim
1isMode:m,updateSettings:w,isUpdating:x}})(k.de_minimis),E=N.isModalOpen?"patterns":R.isModalOpen?"gaps":A.isModalOpen?"spikes":F.isModalOpen?"plan_conversion":M.isModalOpen?"de_minimis":null,B=i?(0,d.Ly)(i,v):{available:!0},K=E??i,q=u?"Recent churns":K?e6.L[K].label:"Detection rules",T=s.useCallback(()=>{n?n():h.vF.error("[CleaningDetectionRulesSubthread] Back action unavailable outside embedded presentation",{fallback_state:"cleaning_detection_rules_back_action_missing"})},[n]),I=s.useCallback(e=>{switch(e){case"patterns":return{detectQuarterly:N.detectQuarterly,detectAnnual:N.detectAnnual,enableSinglePaymentDetection:N.enableSinglePaymentDetection,enableAnnualSingletonDetection:N.enableAnnualSingletonDetection};case"gaps":return{...R.rule?.config??{}};case"spikes":return{threshold:A.currentThreshold,maxConsecutiveSpikePeriods:A.currentMaxConsecutiveSpikePeriods,detectTemporaryElevatedRegimes:A.isTemporaryElevatedRegimeDetectionEnabled,temporaryElevatedRegimeMinMultiplier:A.currentTemporaryElevatedRegimeMinMultiplier,temporaryElevatedRegimeMaxPeriods:A.currentTemporaryElevatedRegimeMaxPeriods};case"plan_conversion":return{...F.config};case"de_minimis":return{monthThreshold:M.monthThreshold,quarterThreshold:M.quarterThreshold,requireContiguous:M.requireContiguous,revenueThreshold:M.revenueThreshold,deMinimisMode:M.deMinimisMode}}},[M,R.rule?.config,N,F.config,A]),L=s.useCallback((e,t="rules_index")=>{let n=k[e];switch(n&&(0,eZ.hl)({context:n,entryPoint:t,currentConfiguration:I(e)}),e){case"patterns":N.openModal();return;case"gaps":R.openModal();return;case"spikes":A.openModal();return;case"plan_conversion":F.openModal();return;case"de_minimis":M.openModal();return}},[M.openModal,I,R.openModal,N.openModal,F.openModal,k,A.openModal]),D=s.useCallback(e=>{let t=E?k[E]:void 0;switch(t&&(0,eZ.Y4)({context:t,reason:e}),E){case"patterns":N.closeModal();return;case"gaps":R.closeModal();return;case"spikes":A.closeModal();return;case"plan_conversion":F.closeModal();return;case"de_minimis":M.closeModal();return;default:return}},[E,M,R,N,F,k,A]),P=s.useCallback((e="back")=>{D(e),i&&(x.current=!1,T())},[D,i,T]);s.useEffect(()=>{i&&B.available&&_&&g.current!==i&&(g.current=i,L(i,"focused_category"))},[i,B.available,L,_]),s.useEffect(()=>{if(i){if(E===i){x.current=!0;return}null===E&&x.current&&(x.current=!1,T())}},[E,i,T]),s.useEffect(()=>{c.current?.focus()},[E,u]);let U=s.useMemo(()=>{let e,t;return[{category:"patterns",summary:(e=[N.detectQuarterly?"quarterly":null,N.detectAnnual?"annual":null].filter(e=>null!==e),`${e.join(" and ")} billing${N.enableSinglePaymentDetection||N.enableAnnualSingletonDetection?" \xb7 single-payment checks on":""}`),busy:N.isUpdating,onOpen:()=>L("patterns")},{category:"gaps",summary:(t=R.rule?.config,t?.detectionMode==="intra-period"?`Consecutive gaps \xb7 up to ${t.gapThresholdMonths??3} months`:`Spike after gap \xb7 ${Math.round(((t?.threshold??1.5)-1)*100)}% increase`),busy:R.isUpdating,onOpen:()=>L("gaps")},{category:"spikes",summary:`${A.currentThreshold}% high-spike \xb7 up to ${A.currentMaxConsecutiveSpikePeriods} period${1===A.currentMaxConsecutiveSpikePeriods?"":"s"} \xb7 ${A.isTemporaryElevatedRegimeDetectionEnabled?`${A.currentTemporaryElevatedRegimeMinMultiplier}\xd7 regime \xb7 up to ${A.currentTemporaryElevatedRegimeMaxPeriods} months`:"regime review off"}`,busy:A.isUpdating,onOpen:()=>L("spikes")},{category:"plan_conversion",summary:`${F.config.monthlyMultiplierMin}â${F.config.monthlyMultiplierMax}\xd7 monthly baseline`,busy:F.isProcessing,onOpen:()=>L("plan_conversion")},{category:"de_minimis",summary:"revenue"===M.deMinimisMode?`Revenue below $${M.revenueThreshold.toLocaleString()}`:`${M.monthThreshold} months or fewer \xb7 ${M.requireContiguous?"consecutive":"any periods"}`,busy:M.isUpdating,onOpen:()=>L("de_minimis")}].filter(e=>(0,d.Ly)(e.category,v).available)},[v,M,R,L,N,F,A]);s.useEffect(()=>{e&&(0,eZ.AN)({analysisId:e,surface:t,entryPoint:i?"focused_category":"rules_index",initialCategory:i,calculationMethod:v,availableRuleCount:U.length+1})},[e,v,i,U.length,t]),s.useEffect(()=>{if(e)return(0,$.dG)({context:{analysisId:e,surface:t},action:"rules_opened",source:"rules_subthread"}),()=>(0,$.dG)({context:{analysisId:e,surface:t},action:"rules_closed",source:"rules_subthread_unmounted"})},[e,t]);let z=s.useCallback(()=>i?P("cancel"):D("cancel"),[D,P,i]);return(0,a.jsx)(tv,{embedded:l,recentChurnEditorOpen:u,setRecentChurnEditorOpen:p,displayCategory:K,headingRef:c,focusedLabel:q,activeCategory:E,initialCategory:i,initialCategoryAvailability:B,smoothingServiceReady:!!_,returnToParent:T,exitActiveEditor:P,cancelActiveEditor:z,recentChurnLookbackPeriods:f,monthKeys:j,recentChurnCustomerCount:C,recentChurnRowCount:y.length,setRecentChurnLookbackPeriods:b,patterns:N,missing:R,spikes:A,plans:F,deMinimis:M,rows:U})}function tw({analysisId:e,activeConcern:t,activeRegularityCategory:n,detectionRulesRoute:s,setDetectionRulesRoute:i,negativeReviewed:r,surface:l,focusedActions:o,onClose:c}
1){let u="negatives"===t?"Negatives":"consolidation"===t?"Duplicate customers":"latest-churns"===t?"Recent churns":n?d.b3[n]:"Revenue irregularities";return(0,a.jsx)(z,{projectionKey:`concern:${t}`,children:(0,a.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"cleaning-concern-subthread",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 pb-3",children:[(0,a.jsx)(eQ.h,{testId:"cleaning-subthread-back",onClick:c}),(0,a.jsx)("h3",{className:"min-w-0 flex-1 truncate text-[12.5px] font-semibold text-[#0E1624]",children:u}),"revenue-regularities"===t&&n?(0,a.jsxs)(eG.$,{size:"xs",variant:"ghost",onClick:()=>i(e=>e?.initialCategory===n?null:{initialCategory:n}),"data-testid":"cleaning-category-detection-settings","aria-label":`Adjust ${u} detection settings`,"aria-expanded":s?.initialCategory===n,className:"shrink-0 gap-1.5 px-2 text-[11px] font-medium text-qb-slate hover:text-qb-midnight",children:[(0,a.jsx)(eO.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Detection settings"]}):null,"negatives"===t&&r>0?(0,a.jsx)(e1,{analysisId:e,available:!0,compact:!0}):null]}),"revenue-regularities"===t&&n&&s?.initialCategory===n?(0,a.jsx)("div",{className:"rounded-lg border border-[#E1E7EF] bg-[#F8FAFC] p-3",children:(0,a.jsx)(ty,{analysisId:e,surface:l,initialCategory:n,embedded:!0,onBack:()=>i(null)},n)}):null,(0,a.jsx)(e5,{analysisId:e,showRegularitiesBackAction:!1,showHeading:!1,focusedActions:o})]})})}function tj({analysisId:e,surface:t,detectionRulesRoute:n,setDetectionRulesRoute:s}){let i=n?.initialCategory===null;return(0,a.jsxs)("div",{className:"border-t border-[#E8EDF3] pt-3",children:[(0,a.jsxs)("button",{type:"button",onClick:()=>s(e=>e?.initialCategory===null?null:{initialCategory:null}),"data-testid":"cleaning-alert-rules",className:"group flex min-h-11 w-full items-center gap-3 rounded-md py-2 text-left transition-colors hover:bg-[#F8FAFC] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#2563FF]/30","aria-label":"Detection rules. Find rows worth reviewing","aria-expanded":i,children:[(0,a.jsx)(eO.A,{className:"h-4 w-4 shrink-0 text-[#64748B]","aria-hidden":"true"}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block text-[12.5px] font-semibold text-[#0E1624]",children:"Detection rules"}),(0,a.jsx)("span",{className:"mt-0.5 block text-[11.5px] leading-4 text-[#64748B]",children:"Detection rules find rows worth reviewing. They do not change values."})]}),i?(0,a.jsx)(eV.A,{className:"h-3.5 w-3.5 shrink-0 text-[#94A3B8]","aria-hidden":"true"}):(0,a.jsx)(eJ.A,{className:"h-3.5 w-3.5 shrink-0 text-[#94A3B8] transition-colors group-hover:text-[#475569]","aria-hidden":"true"})]}),i?(0,a.jsx)("div",{className:"mt-2 rounded-lg border border-[#E1E7EF] bg-[#F8FAFC] p-3",children:(0,a.jsx)(ty,{analysisId:e,surface:t,embedded:!0,onBack:()=>s(null)},"rules-index")}):null]})}let tC=[];function t_({analysisId:e,activeConcern:t,onActiveConcernChange:n,focusedActions:m,surface:g="cleaning_navigation",onReviewHandoff:x}){let f=(0,S.jB)(e=>e.navigateReviewScope),b=(0,S.jB)(e=>e.lifecycleFilter),y=(0,S.jB)(e=>e.regularitiesDrillCategory),w=(0,S.jB)(e=>e.recentChurnLookbackPeriods),C=(0,S.jB)(e=>e.recentChurnProjectionAnalysisId),_=(0,S.jB)(e=>e.recentChurnReviewRows),k=(0,S.jB)(t=>t.agentAdjudicationAnalysisId===e?t.agentAdjudicationStatus:"idle"),N=(0,S.jB)(t=>t.agentAdjudicationAnalysisId===e?t.agentAdjudicationQueueFingerprint:null),R=(0,S.jB)(t=>t.agentAdjudicationAnalysisId===e?t.agentAdjudicationSettingsFingerprint??null:null),F=(0,S.jB)(t=>(0,eb.w)(t,e)),M=(0,c.useVersionStore)(e=>(0,Q.j)({versions:e.versions,currentIndex:e.currentIndex,prefix:"cleaning-concern-alerts-overrides"})),E=s.useMemo(()=>(0,ef.OR)(),[M]),B=s.useMemo(()=>(0,v.v8)(E),[E]),K=s.useCallback(e=>"keep_as_reported"===e.assessment.recommendation?(0,v.GY)(e):(0,v.kg)({record:e,activeOverrideCells:B}),[B]),q=s.useCallback(e=>(0,v.No)({record:e,activeOverrideByCell:B}),[B]),[T,$]=s.useState(null),[I,L]=s.useState(null),P=void 0!==t?t:T,U=n??$,Y=s.useCallback(()=>{L({initialCategory:null}),x?.()},[x,L]),H=(0,p.useProcessedDataStore)(t=>(0,p.processedDataBelongsToAnalysis)(t.processedData,e)),W=(0,u.uF)(t=>
1t.byAnalysisId[e]?.substrateStatus??"idle"),Z=(0,S.jB)(e=>e.decisionConcerns??{}),X=(0,S.jB)(e=>e.decisionConcernsAnalysisId),ee=(0,r.Tj)(e=>e.rules.arrCalculationMethod),et=(0,r.Tj)(e=>e.rules.arrAnnualizationByRevenueStream),en=ex(),{service:ea}=(0,l.P)(),{service:es}=(0,o.H)(),er=(0,O.U)(ea),el=(0,O.U)(es),{rows:eo}=(0,J.W)("CleaningConcernAlerts"),ed=(0,c.useVersionStore)(e=>e.periodKeys??tC),ec=s.useMemo(()=>({analysisId:e,sourceRows:eo,monthKeys:ed}),[e,ed,eo]),eu=(0,A.d6)(ec,"CleaningConcernAlerts.completeReviewEvidence",A.dA,e),ep=eu.analysisId===e?eu.sourceRows:[],em=eu.analysisId===e?eu.monthKeys:tC,eh=s.useMemo(()=>(0,j.CZ)({arrCalculationMethod:ee,arrAnnualizationByRevenueStream:et}),[ee,et]),eg=s.useMemo(()=>(0,V.rV)({sourceRows:ep,lookbackPeriods:w,annualizationRules:eh}),[eh,w,ep]),ev=s.useMemo(()=>(0,G.iy)({analysisId:e,projectionAnalysisId:C,projectedRows:_,detectedRows:eg.ok?eg.rows:[]}),[e,_,C,eg]),ey=s.useMemo(()=>new Set(ev.map(e=>e.customerId)).size,[ev]),ew=Z.negative_handling?.counts,ej=Z.consolidation?.counts,eC=ej?.total??0,e_=ej?.reviewed??0,ek=ew?.total??0,eN=ew?.reviewed??0,eR=s.useMemo(()=>d.Gz.filter(e=>(0,d.Ly)(e,ee).available).map(e=>{let t=(0,S.sp)({scope:(0,S.Hm)("revenue-regularities",{lifecycle:"all",regularitiesCategory:e}),concerns:Z});return{category:e,total:t?.total??0}}),[ee,Z]),eS=s.useMemo(()=>{let e=ea?.getStateSnapshot(),t=es?.getStateSnapshot();return!!(e?.isCheckingForNegatives||t?.isCheckingForSmoothing)},[ea,es,er,el]),eA=!!(ew||Z.smoothing||ej),eF=!eS&&eA,eM=eC>0||ek>0||ey>0||eR.some(e=>e.total>0)||F.length>0,eE=eF&&X===e&&!!Z.negative_handling&&!!Z.smoothing&&eg.ok&&ep.length>0&&em.length>0,eB=(0,ei.xu)({analysisId:e,fingerprint:en.fingerprint}),eK=null!==R&&R===en.fingerprint,{evidence:eq,queueFingerprint:eT,detectorFlagCount:e$}=function({analysisId:e,completedReviewLocked:t,agentAdjudications:n,agentAdjudicationQueueFingerprint:a,agentAdjudicationStatus:i,activeConcern:r,aiReviewInputsReady:l,reviewSourceRows:o,reviewMonthKeys:d,recentChurnRows:c,annualizationRules:u,isRecordApplied:p}){let m=(0,eU.IU)(),g=(0,s.useMemo)(()=>{if(t){let e=n.map(e=>e.evidence);return{mode:"completed_review",evidence:e,queueFingerprint:a,detectorFlagCount:e.reduce((e,t)=>e+t.candidateIds.length,0),durationMs:0}}if(r||!l)return{mode:"waiting",evidence:[],queueFingerprint:null,detectorFlagCount:0,durationMs:0};let e=(0,A.qj)(),s=(0,ez.vi)({recentChurnReviewRows:c}),m=(0,j.kn)({sourceRows:o,periodKeys:d,workbenchRows:s,annualizationRules:u}),h=(0,j.H7)({currentProposalEvidence:m,workbenchRows:s,reviewedRecords:n,retainReviewedEvidence:"complete"===i||"incomplete"===i,isNumericJudgmentApplied:p});return{mode:"derived",evidence:h,queueFingerprint:h.length>0?(0,j.ol)(h):null,detectorFlagCount:h.reduce((e,t)=>e+t.candidateIds.length,0),durationMs:(0,A.qj)()-e}},[r,a,i,n,l,u,t,p,c,d,o]);return(0,s.useEffect)(()=>{if("derived"!==g.mode)return;let t={analysisId:e,rowCount:g.evidence.length,durationMs:g.durationMs,slow:g.durationMs>=100,paneActive:m};document.documentElement.dataset.quikirrCleaningLastReviewDerivation=JSON.stringify(t),window.dispatchEvent(new CustomEvent("quikirr:cleaning-review-derivation",{detail:t})),t.slow&&h.vF.warn("[CleaningReviewPerf] Completed-review evidence derivation exceeded budget",t)},[e,g]),g}({analysisId:e,completedReviewLocked:"complete"===k&&eB&&null!==N&&F.length>0,agentAdjudications:F,agentAdjudicationQueueFingerprint:N,agentAdjudicationStatus:k,activeConcern:P,aiReviewInputsReady:eE,reviewSourceRows:ep,reviewMonthKeys:em,recentChurnRows:ev,annualizationRules:eh,isRecordApplied:K}),eI=s.useCallback(()=>{n?n(null):U(null),f({...S.Yq,lifecycle:b})},[b,f,n,U]);return(s.useEffect(()=>{P&&L(null)},[P,e]),P)?(0,a.jsx)(tw,{analysisId:e,activeConcern:P,activeRegularityCategory:y,detectionRulesRoute:I,setDetectionRulesRoute:L,negativeReviewed:eN,surface:g,focusedActions:m,onClose:eI}):(0,a.jsx)(z,{projectionKey:"overview",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"cleaning-concern-alerts",children:[eF?null:(0,a.jsx)(i._p,{statusLabel:eS?"Checking your dataâ¦":H?"The cleaning checks are getting ready.":"requested"===W||"running"===W?"Preparing your data â the cleaning checks run automatically once it's ready.":"complete"!==W?"The cleaning checks run once the source data mapping is set.":"The cleaning checks are getting ready."}),eF?(0,a.jsxs)("div",{className:"space-y-5","data-testid":"cleaning-anomaly-summary",children:[eM?null:(0,a.jsx)("p",{className:"text-[12px] leading-5 text-[#64748B]",children:"No cleaning items found with the current detection rules."}
1),(0,a.jsx)(eP,{analysisId:e,inputsReady:eE,queueFingerprint:eT,queueRowCount:eq.length,queueDetectorFlagCount:e$,queueEvidence:eq,annualizationRules:eh,onContinueWithoutAiReview:x,enabled:eE&&eM&&null!==eT}),eK&&("complete"===k||"incomplete"===k&&F.length>0)?(0,a.jsx)(D,{analysisId:e,records:F,reviewFingerprint:N,consolidatedGroupCount:e_,isRecordApplied:K,isRecordProtected:q,onReviewHandoff:Y}):null,(0,a.jsx)(tj,{analysisId:e,surface:g,detectionRulesRoute:I,setDetectionRulesRoute:L})]}):null]})})}},73994:(e,t,n)=>{n.d(t,{C:()=>d,z:()=>o});var a=n(95155),s=n(12115),i=n(86033),r=n(67401),l=n(90568);let o=s.forwardRef(({className:e,...t},n)=>(0,a.jsx)(i.bL,{className:(0,l.cn)("grid gap-2",e),...t,ref:n}));o.displayName=i.bL.displayName;let d=s.forwardRef(({className:e,children:t,...n},s)=>(0,a.jsx)(i.q7,{ref:s,className:(0,l.cn)("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...n,children:(0,a.jsx)(i.C1,{className:"flex items-center justify-center",children:(0,a.jsx)(r.A,{className:"h-2.5 w-2.5 fill-current text-current"})})}));d.displayName=i.q7.displayName},93060:(e,t,n)=>{n.d(t,{H9:()=>S,MA:()=>R});var a=n(95155),s=n(43772),i=n(12115),r=n(15330),l=n(60976),o=n(31966),d=n(90467),c=n(25960),u=n(81290),p=n(86957),m=n(77508),h=n(9005),g=n(89239),x=n(90568),v=n(70872),f=n(64577),b=n(84218),y=n(66645);function w({preview:e,busy:t=!1,onApply:n,onClose:s}){let r=i.useRef(null);return i.useEffect(()=>{r.current?.focus()},[e.previewFingerprint]),(0,a.jsxs)("section",{className:"bg-[#F8FAFC] px-3 py-2","aria-labelledby":"safe-defaults-preview-heading","data-testid":"cleaning-safe-defaults-preview",children:[(0,a.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h3",{ref:r,id:"safe-defaults-preview-heading",tabIndex:-1,className:"text-[12px] font-semibold text-qb-midnight outline-hidden",children:"Recommended defaults"}),(0,a.jsxs)("p",{className:"mt-0.5 text-[11px] text-qb-slate",children:[e.transformedCandidateCount," row",1===e.transformedCandidateCount?"":"s"," will change",e.keptCandidateCount>0?` \xb7 ${e.keptCandidateCount} unchanged`:""]})]}),(0,a.jsx)(g.$,{size:"icon-xs",variant:"ghost",onClick:s,"aria-label":"Close safe-default preview",children:(0,a.jsx)(h.A,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),(0,a.jsx)("ul",{className:"mt-2 flex flex-wrap gap-x-4 gap-y-1","aria-label":"Proposed decision methods",children:Object.entries(e.decisionMethodCounts).map(([e,t])=>(0,a.jsxs)("li",{className:"flex items-center gap-1 text-[11px] text-qb-slate",children:[(0,a.jsx)(f.A,{className:"h-3 w-3 text-qb-green","aria-hidden":"true"}),(0,a.jsx)("span",{children:function(e){if("keep"===e)return"No change";let t=(0,b.wi)(e);return t?t.previewLabel:(y.vF.error("[CleaningSafeDefaultsPreview] Unknown treatment method",{method:e,fallback_state:"cleaning_safe_defaults_unknown_treatment"}),`Unknown treatment (${e})`)}(e)}),(0,a.jsx)("span",{className:"font-medium tabular-nums text-qb-midnight",children:t})]},e))}),(0,a.jsx)("div",{className:"mt-2 flex justify-end",children:(0,a.jsxs)(g.$,{size:"xs",onClick:n,disabled:t,className:"bg-qb-midnight text-white hover:bg-qb-midnight/90",children:["Apply ",e.decisionCount," default",1===e.decisionCount?"":"s"]})})]})}var j=n(78744);let C="Select at least one row to use this action.";function _(e){return(0,a.jsxs)("div",{className:(0,x.cn)("grid grid-cols-2 gap-1.5",e.className),"aria-label":"Cleaning history","data-testid":"cleaning-history-controls",children:[(0,a.jsxs)(g.$,{size:"xs",variant:"outline",className:"justify-center gap-1.5",disabled:e.busy||!e.canUndo||!e.onUndo,onClick:e.onUndo,title:e.undoLabel??"Undo the latest cleaning action",children:[(0,a.jsx)(r.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Undo"]}),(0,a.jsxs)(g.$,{size:"xs",variant:"outline",className:"justify-center gap-1.5",disabled:e.busy||!e.canRedo||!e.onRedo,onClick:e.onRedo,title:e.redoLabel??"Redo the last undone cleaning action",children:[(0,a.jsx)(l.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Redo"]})]})}
1function k(e){let t=Math.round(e),n=Math.abs(t).toLocaleString();return t<0?`(${n})`:n}function N({label:e,value:t}){return(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{className:"text-[10px] leading-4 text-qb-slate",children:e}),(0,a.jsx)("dd",{className:"text-[13px] font-semibold tabular-nums text-qb-midnight",children:t})]})}function R({analysisId:e,placement:t="panel"}){let n=(0,j.jB)(t=>t.commandController?.analysisId===e?t.commandController:null);return n?(0,a.jsx)(_,{busy:n.busy,canUndo:!!n.canUndo,canRedo:!!n.canRedo,undoLabel:n.undoLabel,redoLabel:n.redoLabel,onUndo:n.onUndo,onRedo:n.onRedo,className:"panel"===t?"mb-3":void 0}):null}function S({analysisId:e,showHistory:t=!0}){var n;let l=(0,j.jB)(t=>t.commandController?.analysisId===e?t.commandController:null),[x,f]=(0,i.useState)(null);if((0,i.useEffect)(()=>{f(null)},[e,l?.scopeKey]),!l)return null;let b=!!l.treatmentActions?.length,y=l.selectedCount>0&&!l.busy,_=!!(l.onSelectAll&&l.selectableCount>0),A=l.selectableCount>0&&l.selectedCount>=l.selectableCount,F=l.insights.changes.decisionCount>0||l.insights.changes.hasUnattributedHistory;return(0,a.jsxs)("section",{"aria-label":"Cleaning controls","data-testid":"cleaning-sidebar-actions",children:[t?(0,a.jsx)(R,{analysisId:e}):null,(0,a.jsxs)("div",{className:"flex min-h-8 items-center justify-between gap-3","data-testid":"cleaning-selection-status",children:[(0,a.jsxs)("p",{className:"text-[12px] text-qb-slate",children:[(0,a.jsx)("span",{className:"font-semibold tabular-nums text-qb-midnight",children:l.selectedCount.toLocaleString()})," ","selected"]}),(0,a.jsxs)("div",{className:"flex items-center gap-1.5",children:[l.onClear?(0,a.jsxs)(g.$,{size:"xs",variant:"ghost",onClick:l.onClear,disabled:l.busy,className:"gap-1.5 px-2 text-[11px] font-medium text-qb-slate hover:text-qb-midnight",children:[(0,a.jsx)(h.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Clear"]}):null,_&&l.onSelectAll?(0,a.jsxs)(g.$,{size:"xs",variant:"outline",onClick:l.onSelectAll,disabled:l.busy||A,children:["Select all ",l.selectableCount.toLocaleString()]}):null]})]}),l.error?(0,a.jsxs)("p",{role:"alert",className:"mt-2 rounded-md bg-qb-red/8 px-2.5 py-2 text-[11px] leading-4 text-qb-red",children:[(0,s.A)((0,s.m)(l.error),"We couldn't apply the data-cleanup change. Review the selection and try again.","ui_boundary_features_data_cleanup_cleaningworkspace_cleaningsidebaractions_cleaningsidebaractions_1_failed")," Nothing was changed."]}):null,(0,a.jsxs)("div",{className:"mt-5 min-h-[204px]","data-testid":"cleaning-action-region",children:[(0,a.jsx)("p",{className:"mb-2 text-[11px] font-semibold text-qb-midnight",children:"Actions"}),b?(0,a.jsx)(v.Bc,{delayDuration:250,children:(0,a.jsx)("div",{className:"flex flex-col gap-1.5","data-testid":"cleaning-treatment-actions",children:l.treatmentActions?.map(e=>{var t;let n=`${l.ownerId}-${e.id}-description`,s=0===l.selectedCount,i=(0,a.jsxs)(g.$,{size:"xs",variant:"outline","aria-label":e.label,"aria-describedby":n,onClick:e.onSelect,disabled:!y,className:"h-auto min-h-[52px] w-full justify-start gap-2.5 whitespace-normal border-qb-line px-3 py-2 text-left transition-[background-color,border-color,transform,opacity] duration-150 ease-out hover:border-qb-slate/40 hover:bg-[#F8FAFC] active:scale-[0.99] disabled:border-qb-line disabled:bg-[#F8FAFC] disabled:opacity-60 disabled:active:scale-100",children:[(0,a.jsx)("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[#F1F5F9] text-qb-slate",children:"spread-backward"===(t=e.id)?(0,a.jsx)(o.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):"spread-forward"===t?(0,a.jsx)(d.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):"set-zero"===t?(0,a.jsx)(c.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):"undo-action"===t?(0,a.jsx)(r.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):"merge-selected"===t?(0,a.jsx)(u.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):"keep-separate-selected"===t?(0,a.jsx)(p.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):(0,a.jsx)(m.A,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block text-[12px] font-semibold leading-4 text-qb-midnight",children:e.label}),(0,a.jsx)("span",{id:n,className:"mt-0.5 block text-[10px] font-normal leading-4 text-qb-slate",children:e.description})]})]},e.id);return s?(0,a.jsxs)(v.m_,{children:[(0,a.jsx)(v.k$,{asChild:!0,children:(0,a.jsx)("span",{tabIndex:0,"data-testid":`cleaning-disabled-action-${e.id}`,"aria-label":`${e.label}. ${C}`,className:"block w-full cursor-help rounded-md focus-visible:outline-hidden focu
1s-visible:ring-2 focus-visible:ring-[#2563FF]/30",children:i})}),(0,a.jsx)(v.ZI,{side:"top",align:"center",className:"text-[11px] leading-4",children:C})]},e.id):i})})}):null,l.previewLabel&&l.onPreview?(0,a.jsxs)("div",{className:"mt-4","data-testid":"cleaning-bulk-defaults-action",children:[(0,a.jsx)("p",{className:"mb-1.5 text-[10px] font-medium text-qb-slate",children:"All eligible rows"}),(0,a.jsxs)(g.$,{size:"xs",variant:"ghost","aria-label":l.previewLabel,"aria-describedby":`${l.ownerId}-safe-defaults-description`,onClick:l.onPreview,disabled:l.busy||!!l.previewUnavailableReason,className:"h-auto min-h-[52px] w-full justify-start gap-2.5 whitespace-normal bg-[#F8FAFC] px-3 py-2 text-left transition-colors hover:bg-[#F1F5F9]",children:[(0,a.jsx)("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-white text-qb-slate",children:(0,a.jsx)(m.A,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block text-[12px] font-semibold leading-4 text-qb-midnight",children:l.previewLabel}),(0,a.jsx)("span",{id:`${l.ownerId}-safe-defaults-description`,className:"mt-0.5 block text-[10px] font-normal leading-4 text-qb-slate",...l.previewUnavailableReason?{"data-testid":"cleaning-bulk-defaults-unavailable"}:{},children:l.previewUnavailableReason??"Review Quikirr's recommended treatment for every eligible row, then apply."})]})]})]}):null,l.safeDefaultsPreview&&l.onApplyPreview&&l.onClosePreview?(0,a.jsx)("div",{className:"mt-4",children:(0,a.jsx)(w,{preview:l.safeDefaultsPreview,busy:l.busy,onApply:l.onApplyPreview,onClose:l.onClosePreview})}):null]}),F?(0,a.jsx)(g.$,{size:"xs",variant:"ghost","aria-expanded":"changes"===x,onClick:()=>f(e=>"changes"===e?null:"changes"),className:"mt-2 w-fit px-2 text-qb-slate hover:text-qb-midnight",children:"Changes"}):null,"changes"===x?(0,a.jsxs)("div",{className:"mt-3 bg-[#F8FAFC] px-2.5 py-2.5",role:"region","aria-label":"Cleaning changes",children:[(0,a.jsxs)("dl",{className:"grid grid-cols-4 gap-x-3 gap-y-2",children:[(0,a.jsx)(N,{label:"Decisions",value:l.insights.changes.decisionCount.toLocaleString()}),(0,a.jsx)(N,{label:"Cells changed",value:l.insights.changes.changedCellCount.toLocaleString()}),(0,a.jsx)(N,{label:"Customers",value:l.insights.changes.affectedCustomerCount.toLocaleString()}),(0,a.jsx)(N,{label:"Periods",value:l.insights.changes.affectedPeriodCount.toLocaleString()})]}),l.insights.changes.changedCellCount>0?(0,a.jsxs)("dl",{className:"mt-2 grid grid-cols-3 gap-x-3 pt-2",children:[(0,a.jsx)(N,{label:"Before",value:k(l.insights.changes.beforeTotal)}),(0,a.jsx)(N,{label:"After",value:k(l.insights.changes.afterTotal)}),(0,a.jsx)(N,{label:"Net change",value:0===(n=l.insights.changes.netChange)?"0":`${n>0?"+":"â"}${Math.abs(Math.round(n)).toLocaleString()}`})]}):(0,a.jsx)("p",{className:"mt-2 pt-2 text-[10px] leading-4 text-qb-slate",children:"These saved decisions do not have a cell-value difference."}),l.insights.changes.actionCounts.length>0?(0,a.jsx)("ul",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 pt-2 text-[10px] text-qb-slate",children:l.insights.changes.actionCounts.map(e=>(0,a.jsxs)("li",{children:[(0,a.jsx)("span",{className:"font-medium text-qb-midnight",children:e.count.toLocaleString()})," ",e.action]},e.action))}):null,l.insights.changes.hasUnattributedHistory?(0,a.jsx)("p",{className:"mt-2 text-[10px] leading-4 text-qb-slate",children:"Some earlier saved decisions do not include cell-level change detail."}):null]}):null]})}}}]);
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.