PageSourceSearch

https://crmduce.lovable.app/assets/Commissions-DmuWVztG.js

js crmduce.lovable.app collected 2026-10-03 03:21:54 UTC 65,090 bytes, 6 lines download raw bytes

1import{j as e,u as se,d as $,e as F}from"./data-DN-eP4ae.js";import{e as me,r as j,h as hs,N as ps}from"./react-BUOzgyp0.js";import{K,cF as Ue,aA as Pe,aB as Re,aC as ke,aD as qe,a0 as u,B as w,A as Ye,a8 as js,i as G,n as C,bw as ve,s as E,Y as gs,y as fs,af as Ge,cd as pe,ce as Je,F as Xe,fn as we,a1 as Ce,a4 as ae,$ as be,c as ys,aT as Ie,bD as Ze,by as vs,bF as bs,a6 as es,cQ as Ns,bJ as Le,U as _s,V as ws,C as Cs,aE as Ss,bu as W,av as ee,b7 as Ms,an as As,ao as Ts,ap as Es,aq as Ps,eN as Se,ci as Rs}from"./index-6GUxm5Tl.js";import{P as ks}from"./PageHeader-CsFfXur0.js";import{M as ss}from"./ModeTabs-BYRAhe3-.js";import{A as qs}from"./AttentionStrip-DreKh8i4.js";import{C as I,b as Is,c as Ls,a as L}from"./card-Bpoa90g8.js";import{E as Fe}from"./EmptyState-ChyoO585.js";import{A as ts}from"./AdvancedSection-CBPqO4JF.js";import{b as as,c as ns,u as is}from"./useCommissions-D4DjCA3_.js";import{u as De}from"./useCommissionSettings-B48-d1F6.js";import{e as Fs,d as Ds,C as rs,a as Me,b as Os,t as $s,s as ne,n as Ks,c as zs,f as Qs,g as Bs,D as Ae,E as je,h as Ke,i as Ws,P as ze,j as Hs,k as Qe,R as Vs,l as Be,T as We,m as Us,o as Ys,q as Gs,u as Js,w as Xs}from"./commission-model-BzN7LK2q.js";import{C as ie,b as os,c as z,d as Zs,e as et}from"./CommissionStateBadge-DtnpZHlB.js";import{f as k}from"./format-BOCe1Q81.js";import{a as st}from"./useCommissionContributions-CRGJJXs3.js";import{S as tt}from"./stethoscope-BOmDDZVC.js";import{S as at}from"./settings-2-1mx35hli.js";import{C as nt}from"./calendar-clock-BrAgRcD7.js";import{f as B}from"./money-BFQpx7jB.js";import{M as it}from"./MyReferralsPanel-C2BWDKJx.js";import{M as rt,u as ot,i as lt}from"./useGuestAccess-CBXI07Hf.js";import{T as ge,a as fe,b as U,c as P,d as ye,e as R}from"./table-CeZUCHxF.js";import{F as ct}from"./FieldLabel-TuIMjPm6.js";import{u as dt,d as mt,c as ut}from"./useSensitiveAccess-CZL_8yzA.js";import{d as xt,a as ht}from"./index-CGSmUr7J.js";import{D as pt}from"./download-D8rVLK2a.js";import{p as Y}from"./parseISO-DAfKL4BD.js";import{F as jt}from"./FilterBar-C1WEZwwP.js";import{S as re,a as oe,b as le,c as ce,d as de}from"./select-C1j_15i9.js";import{W as gt}from"./wallet-hX8y-nkf.js";import{s as ft}from"./subMonths-BYM3BKDE.js";import{s as Te}from"./startOfMonth-kO_ql4le.js";import{a as yt}from"./addDays-FNsJkNgj.js";import{P as He}from"./page-language-DGjnPgNe.js";import"./documents-Bju1cS7G.js";import"./charts-BjVT6r80.js";import"./module-intro-N0cKHpsA.js";import"./ActionChoiceSheet-Bej1gA4Q.js";import"./ellipsis-CAutlZKC.js";import"./settings-return-GcuqJJ7v.js";import"./DirectionalScrollControls-jxYH8aR3.js";import"./chevron-left-BO8s0r98.js";import"./useDisclosurePreference-CSD3NNSj.js";import"./useDismissable-BvpILM0V.js";import"./useSmartGuide-DB5xQ_Gx.js";import"./useIntelligencePlacement-CbLnAc_a.js";import"./app-primitives-C7oGnmBt.js";import"./useOrgSettings-Bek7ES8S.js";import"./useLeads-DsKSjHTD.js";import"./useTasks-xNZM6HdJ.js";import"./spreadsheets-CKN5doRT.js";import"./SearchBar-B8oDBZzP.js";import"./addMonths-CBp3ZtZ_.js";function D({label:s,value:t}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-4 py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"text-sm font-medium text-right",children:t})]})}function ls({row:s,open:t,onOpenChange:a,footer:n}){const r=me(),h=K(),{settings:g}=De(),{data:N=[]}=as(h),{available:p}=Ue("commissions");if(!s)return null;const _=N.find(d=>d.user_id===s.user_id)??N.find(d=>!d.user_id)??null,c=Fs(s,g,u,new Date,_);return e.jsx(Pe,{open:t,onOpenChange:a,children:e.jsxs(Re,{size:"sm",children:[e.jsxs(ke,{children:[e.jsx(qe,{className:"text-base",children:c.dealTitle}),c.customerName&&e.jsx("p",{className:"text-xs text-muted-foreground",children:c.customerName})]}),e.jsxs("div",{className:"divide-y",children:[e.jsxs("div",{className:"pb-1",children:[e.jsx(D,{label:"Sale value",value:u(c.saleValue)}),e.jsx(D,{label:"Your commission rate",value:c.rateLabel}),e.jsx(D,{label:"Commission",value:e.jsx("span",{className:"text-base",children:u(c.amount)})}),e.jsx(D,{label:"Status",value:e.jsx(ie,{row:s})})]}),c.reason&&e.jsxs("div",{className:"py-3",children:[e.jsxs("p",{className:"text-xs font-medium",children:["Why ",c.label.toLowerCase(),"?"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:c.reason}),c.nextStep&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-xs font-medium",children:"What happens next?"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:c.nextStep})]})]}),c.qualifyingCondition&&e.jsxs("div",{className:"py-3",children:[e.jsx("p",{className:"text-xs font-medium",children:"What made this payable?"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:c.qualifyingCondition})]}),(()=>{const d=Ds(s,u);
1return d?e.jsxs("div",{className:"py-3",children:[e.jsxs("p",{className:"text-xs font-medium",children:[rs[Me(s)]," - how this was attributed"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:d})]}):null})(),e.jsx("div",{className:"py-2",children:c.paymentEvidence?e.jsxs(e.Fragment,{children:[e.jsx(D,{label:"Paid on",value:k(c.paymentEvidence.paidOn,"d MMM yyyy")}),c.paymentEvidence.reference&&e.jsx(D,{label:"Payment reference",value:c.paymentEvidence.reference})]}):c.expectedPaymentDate?e.jsx(D,{label:"Expected payment",value:k(c.expectedPaymentDate,"d MMM")}):null}),p&&e.jsxs("div",{className:"py-2",children:[e.jsx("p",{className:"pb-1 text-xs font-medium",children:"Calculation detail"}),e.jsx(D,{label:"Qualifying value",value:u(c.qualifyingValue)}),e.jsx(D,{label:"Rule used",value:c.ruleLabel}),c.calculationLabel&&e.jsx(D,{label:"Worked out as",value:c.calculationLabel}),e.jsx(D,{label:"Payment dependency",value:c.paymentDependency}),e.jsx(D,{label:"Lifecycle",value:c.detailLabel}),c.approvedOn&&e.jsx(D,{label:"Approved on",value:k(c.approvedOn,"d MMM yyyy")}),c.adjusted&&e.jsx(D,{label:"Adjusted by hand",value:"Yes"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.deal_id&&e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>{a(!1),r(`/deals/${s.deal_id}`)},children:["View deal ",e.jsx(Ye,{className:"ml-1.5 h-3.5 w-3.5"})]}),c.invoiceId&&e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>{a(!1),r(`/invoices?invoice=${c.invoiceId}`)},children:[e.jsx(js,{className:"mr-1.5 h-3.5 w-3.5"})," View invoice"]}),n]})]})})}function vt(){const{data:s=[],isLoading:t}=st();return t?e.jsx(G,{className:"h-32 w-full"}):s.length===0?null:e.jsxs(I,{children:[e.jsx(Is,{className:"pb-2",children:e.jsx(Ls,{className:"text-sm",children:"Where your earnings came from"})}),e.jsx(L,{className:"pt-0",children:e.jsx("div",{className:"divide-y",children:s.map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm",children:a.label}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.earnings," earning",a.earnings===1?"":"s",a.paidTotal>0?` - ${u(a.paidTotal)} paid`:""]})]}),e.jsx("span",{className:"shrink-0 text-sm font-semibold tabular-nums",children:u(a.total)})]},a.contribution))})})]})}function bt(s=!0){const t=K();return se({queryKey:["commission-findings",t],enabled:!!t&&s,queryFn:async()=>{const{data:a,error:n}=await E.from("commission_reconciliation_findings").select("*").eq("org_id",t).eq("status","open").order("created_at",{ascending:!1}).limit(50);if(n)throw n;return a??[]}})}function Nt(){const s=K(),t=$();return F({mutationFn:async()=>{const{data:a,error:n}=await E.rpc("reconcile_commissions",{_org:s??null});if(n)throw n;return a??[]},onSuccess:a=>{t.invalidateQueries({queryKey:["commission-findings",s]});const n=a.reduce((r,h)=>r+Number(h.found??0),0);C[n>0?"warning":"success"](n>0?"Commission needs a look":"Commission agrees with the money",{description:n>0?`${n} thing${n===1?"":"s"} to check below.`:"Every payment has the earning it should have."})},onError:a=>{C.error("Could not check commission",{description:ve(a)})}})}function _t(){const s=K(),t=$();return F({mutationFn:async a=>{const{data:n,error:r}=await E.rpc("repair_commission_finding",{_finding_id:a.findingId,_action:a.action,_note:a.note??null});if(r)throw r;return n},onSuccess:a=>{t.invalidateQueries({queryKey:["commission-findings",s]}),t.invalidateQueries({queryKey:["commissions"]}),C.success("Recorded",{description:Number((a==null?void 0:a.earnings_created)??0)>0?"The missing earning has been worked out from the payment.":"Your decision has been recorded against this finding."})},onError:a=>{C.error("Could not record that",{description:ve(a)})}})}function wt(){const{data:s=[],isLoading:t}=bt(),a=Nt(),n=_t();return e.jsx(I,{children:e.jsxs(L,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"flex items-center gap-1.5 text-sm font-medium",children:[e.jsx(tt,{className:"h-4 w-4 text-muted-foreground"}),"Commission health"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Checks that every payment has the earning it should have, and that nothing was paid twice."})]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>a.mutate(),disabled:a.isPending,children:[e.jsx(gs,{className:`mr-1.5 h-3.5 w-3.5 ${a.isPending?"animate-spin":""}`}),"Check now"]})]}),t?e.jsx(G,{className:"h-16 w-full"}):s.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nothing to look at. Run a check any time."}):e.jsx("ul",{className:"divide-y rounded-lg border",children:s.map(r=>{const h=Os(r.finding_kind),g=Number(r.recorded_amount??0);return e.jsxs("li",{className:"space-y-2 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:h.heading}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[h.meaning,g>0&&` · ${u(g)}`]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:h.fix})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[h.canRetry&&r.payment_id&&e.jsx(w,{size:"sm",onClick:()=>n.mutate({findingId:r.id,action:"retry"}),disabled:n.isPending,children:"Work it out now"}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>n.mutate({findingId:r.id,action:"keep"}),disabled:n.isPending,children:"I have reviewed this"}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>n.mutate({findingId:r.id,action:"dismiss"}),disabled:n.isPending,children:"Not a problem"})]})]},r.id)})})]})})}const Ve=5;function V({icon:s,label:t,value:a}){return e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(s,{className:"h-3.5 w-3.5"}),t]}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:a})]})}function Ct({onViewAll:s}){var X,Z;const t=K(),{user:a}=fs(),n=me(),{isAdmin:r,isAdminOrManager:h}=Ge(),{hasPermission:g,isLoading:N}=pe("commission.manage"),p=Je(),_=!p.isLoading&&p.canOpen("deals"),{settings:c,isLoading:d}=De(),{data:y=[],isLoading:b}=ns(t,a==null?void 0:a.id),{data:S=[],isLoading:A}=as(t),[f,l]=j.useState(null),[v,i]=j.useState(!1),m=j.useMemo(()=>$s(y),[y]),M=j.useMemo(()=>ne(m),[m]),H=j.useMemo(()=>Ks(c),[c]),J=j.useMemo(()=>S.find(x=>
1!x.user_id)??S[0]??null,[S]);if(b||d||A||N||p.isLoading)return e.jsx(G,{className:"h-64 w-full"});if(y.length===0){const x=zs({hasConfiguredRules:c.configured||!!J,canManageSettings:r&&g,canOpenDeals:_});return e.jsx(Fe,{icon:x.primaryAction?at:Xe,heading:x.title,subtext:x.description,actionLabel:(X=x.primaryAction)==null?void 0:X.label,onAction:x.primaryAction?()=>n(x.primaryAction.href):void 0,secondaryActionLabel:(Z=x.secondaryAction)==null?void 0:Z.label,onSecondaryAction:x.secondaryAction?()=>n(x.secondaryAction.href):void 0})}const q=y,Q=v?q:q.slice(0,Ve);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"This month"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[e.jsx(V,{icon:we,label:"Earned",value:u(M.earned)}),e.jsx(V,{icon:Ce,label:"Pending",value:u(M.pending)}),e.jsx(V,{icon:ae,label:"Paid",value:u(M.paid)}),e.jsx(V,{icon:nt,label:"Next payment",value:k(H,"d MMM")})]}),e.jsx(vt,{}),h&&e.jsx(wt,{}),e.jsx(I,{children:e.jsxs(L,{className:"p-0",children:[e.jsx("p",{className:"px-4 pt-3 pb-2 text-xs font-medium text-muted-foreground",children:"Recent earnings"}),e.jsx("ul",{className:"divide-y",children:Q.map(x=>{var T,O;const o=Number(x.commission_rate??0);return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>l(x),className:"flex w-full items-start justify-between gap-3 px-4 py-3 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:((O=(T=x.deals)==null?void 0:T.title)==null?void 0:O.trim())||"Sale"}),Me(x)!=="sale"&&e.jsx("p",{className:"mt-0.5 text-[11px] font-medium text-primary",children:rs[Me(x)]}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["Deal won ",u(Number(x.deal_value??0)),o>0&&` · ${o}%`," · You earned"," ",u(Number(x.commission_amount??0))]})]}),e.jsx(ie,{row:x})]})},x.id)})}),q.length>Ve&&e.jsx("div",{className:"border-t p-2",children:e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>s?s():i(x=>!x),children:v?"Show less":"View all"})})]})}),e.jsx(ls,{row:f,open:!!f,onOpenChange:x=>!x&&l(null)}),e.jsx(ts,{module:"commissions",description:"Qualifying value, the rule used, payment dependency and your earnings history.",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm",children:Qs(J,c,u)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[e.jsx(V,{icon:we,label:"Earned all time",value:u(ne(q).earned)}),e.jsx(V,{icon:Ce,label:"Pending all time",value:u(ne(q).pending)}),e.jsx(V,{icon:ae,label:"Ready all time",value:u(ne(q).ready)}),e.jsx(V,{icon:ae,label:"Paid all time",value:u(ne(q).paid)})]}),e.jsx("ul",{className:"divide-y rounded-lg border",children:q.map(x=>{var o,T;return e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"truncate text-sm",children:((T=(o=x.deals)==null?void 0:o.title)==null?void 0:T.trim())||"Sale"}),e.jsxs("span",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[u(Number(x.commission_amount??0)),e.jsx(ie,{row:x,detail:!0})]})]},x.id)})})]})})]})}function Ne({label:s,value:t}){return e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:t})]})}function St(){const{data:s=[],isLoading:t}=os(),a=j.useMemo(()=>{const n=new Date;n.setDate(1),n.setHours(0,0,0,0);let r=0,h=0,g=0;for(const N of s){const p=Number(N.commission_amount??0),_=String(N.status??"").toLowerCase(),c=N.created_at;c&&new Date(c)>=n&&(r+=p),_==="approved"&&(h+=p),(_==="pending"||_==="awaiting_approval"||_==="under_review")&&(g+=p)}return{thisMonth:r,readyForPayout:h,beingConfirmed:g}},[s]);return t?e.jsx("div",{className:"h-28 animate-pulse rounded-lg bg-muted/40","aria-hidden":!0}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Ne,{label:"Earned this month",value:
1B(a.thisMonth)}),e.jsx(Ne,{label:"Ready to be paid",value:B(a.readyForPayout)}),e.jsx(Ne,{label:"Still being confirmed",value:B(a.beingConfirmed)})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Recent earnings"}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing yet. Your earnings appear here as soon as a customer pays."}):e.jsx("div",{className:"space-y-2",children:s.slice(0,8).map(n=>{var r,h,g;return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 rounded-lg border p-3 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:((r=n.deals)==null?void 0:r.title)??((g=(h=n.deals)==null?void 0:h.contacts)==null?void 0:g.full_name)??"A sale"}),e.jsx("span",{className:"font-medium tabular-nums",children:B(Number(n.commission_amount??0))})]},n.id)})})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"What you were brought in for"}),e.jsx(it,{})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:rt})]})}const cs={overview:s=>["commission-overview",s],health:["commission-health"],team:(s,t)=>["commission-team",s,t],payouts:["commission-payouts"],adjustments:s=>["commission-adjustments",s]};function ue(s){s.invalidateQueries({queryKey:["commission-overview"]}),s.invalidateQueries({queryKey:["commission-health"]}),s.invalidateQueries({queryKey:["commission-team"]}),s.invalidateQueries({queryKey:["commission-payouts"]}),s.invalidateQueries({queryKey:["commission-adjustments"]}),s.invalidateQueries({queryKey:["commissions"]}),s.invalidateQueries({queryKey:["commissions-with-deals"]}),s.invalidateQueries({queryKey:["commissions-monthly"]}),s.invalidateQueries({queryKey:["performance-summary"]}),s.invalidateQueries({queryKey:["leaderboard"]})}function Mt(){return se({queryKey:cs.payouts,queryFn:async()=>{const{data:s,error:t}=await E.from("commission_payouts").select("*").order("created_at",{ascending:!1});if(t)throw t;return s??[]},staleTime:15e3})}function At(s){return se({queryKey:cs.adjustments(s),queryFn:async()=>{let t=E.from("commission_adjustments").select("*").order("created_at",{ascending:!1});const{data:a,error:n}=await t;if(n)throw n;return a??[]},staleTime:3e4})}function Oe(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("approve_commission",{_commission_id:t});if(n)throw n;return a},onSuccess:()=>ue(s)})}function Tt(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("reject_commission",{_commission_id:t.id,_reason:t.reason});if(n)throw n;return a},onSuccess:()=>ue(s)})}function Et(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("mark_commissions_ready",{_ids:t});if(n)throw n;return a},onSuccess:()=>ue(s)})}function Pt(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("create_commission_payout",{_user_id:t.user_id,_commission_ids:t.commission_ids,_period_start:t.period_start??null,_period_end:t.period_end??null});if(n)throw n;return a},onSuccess:()=>ue(s)})}function Rt(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("mark_payout_paid",{_payout_id:t.id,_ref:t.reference??null});if(n)throw n;return a},onSuccess:()=>ue(s)})}const kt={calculated:{label:"Earned - waiting for approval",cls:"bg-warning/10 text-warning border-warning/30"},pending_approval:{label:"Earned - waiting for approval",cls:"bg-warning/10 text-warning border-warning/30"},pending:{label:"Earned - waiting for approval",cls:"bg-warning/10 text-warning border-warning/30"},approved:{label:"Approved - in the next payout",cls:"bg-success/10 text-success border-success/30"},ready_for_payout:{label:"Approved - in the next payout",cls:"bg-purple-500/10 text-purple-600 border-purple-500/30"},paid:{label:"Paid",cls:"bg-success text-success-foreground border-success"},rejected:{label:"Rejected",cls:"bg-destructive/10 text-destructive border-destructive/30"},reversed:{label:"Reversed",cls:"bg-muted text-muted-foreground border-border"},draft:{label:"Draft",cls:"bg-muted text-muted-foreground border-border"},cancelled:{label:"Cancelled",cls:"bg-destructive/10 text-destructive border-destructive/30"}};function _e({status:s}){const t=kt[s]??{label:s,cls:"bg-muted text-muted-foreground"};return e.jsx(be,{variant:"outline",className:ys("text-xs font-medium",t.cls),children:t.label})}function qt({open:s,onOpenChange:t,commissionId:a}){const[n,r]=j.useState(""),h=Tt(),g=async()=>
1{if(a){if(!n.trim()){C.error("Reason is required");return}try{await h.mutateAsync({id:a,reason:n.trim()}),C.success("Commission rejected"),r(""),t(!1)}catch(N){C.error("Failed to reject",{cause:N})}}};return e.jsx(Pe,{open:s,onOpenChange:t,children:e.jsxs(Re,{size:"md",className:"",children:[e.jsx(ke,{children:e.jsx(qe,{children:"Reject commission"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:"Reason"}),e.jsx(Ie,{value:n,onChange:N=>r(N.target.value),placeholder:"Explain why this commission is being rejected",rows:4})]}),e.jsxs(Ze,{children:[e.jsx(w,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(w,{variant:"destructive",onClick:g,disabled:h.isPending,children:h.isPending?"Rejecting...":"Reject"})]})]})})}function Ee({section:s="all",memberNames:t}){var x;const a=K(),{data:n=[],isLoading:r}=is(a,{dateRange:{start:"1900-01-01",end:"2999-12-31"}}),{data:h=[]}=Mt(),g=Oe(),N=Et(),p=Pt(),_=Rt(),c=o=>(t==null?void 0:t[o])??o.slice(0,8),[d,y]=j.useState(null),[b,S]=j.useState(new Set),[A,f]=j.useState(!1),l=()=>{f(!1),S(new Set)},v=j.useMemo(()=>n.filter(o=>["pending_approval","calculated","pending"].includes(o.status)),[n]),i=j.useMemo(()=>n.filter(o=>o.status==="approved"),[n]),m=s==="all"||s==="approvals",M=s==="all"||s==="payouts",H=o=>{const T=new Set(b);T.has(o)?T.delete(o):T.add(o),S(T)},J=async()=>{const o=Array.from(b);if(o.length===0)return;const T=new Map;i.filter(O=>o.includes(O.id)).forEach(O=>{T.has(O.user_id)||T.set(O.user_id,[]),T.get(O.user_id).push(O.id)});try{for(const[O,xs]of T)await p.mutateAsync({user_id:O,commission_ids:xs});C.success(`Created payout(s) for ${T.size} member(s)`),S(new Set)}catch(O){C.error("That did not save",{cause:O})}},q=dt("crm.commissions.export"),Q=((x=q.data)==null?void 0:x.allowed)===!0,X=q.data&&!q.data.allowed?mt(q.data,{action:ut("crm.commissions.export")}):null,Z=()=>{if(!Q){C.error("You cannot export this",{description:X??void 0});return}xt([["Member","Amount","Currency","Period start","Period end","Status","Paid","Reference"],...h.map(o=>[c(o.user_id),o.total_amount,o.currency??"NGN",o.period_start??"",o.period_end??"",o.status,o.paid_at??"",o.payment_reference??""])],`${ht("commission-payouts")}.csv`)};return r?e.jsx(G,{className:"h-64 w-full"}):e.jsxs("div",{className:"space-y-5",children:[m&&e.jsx(I,{children:e.jsxs(L,{className:"p-4 space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"font-medium text-sm",children:["Waiting for approval (",v.length,")"]})}),v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No commissions awaiting approval."}):e.jsx("div",{className:"rounded-lg border overflow-x-auto",children:e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(U,{children:[e.jsx(P,{children:"Member"}),e.jsx(P,{className:"text-right",children:"Deal value"}),e.jsx(P,{className:"text-right",children:"Amount"}),e.jsx(P,{children:"Status"}),e.jsx(P,{className:"w-48 text-right",children:"Actions"})]})}),e.jsx(ye,{children:v.map(o=>e.jsxs(U,{children:[e.jsx(R,{className:"text-xs",children:c(o.user_id)}),e.jsx(R,{className:"text-right",children:u(o.deal_value)}),e.jsx(R,{className:"text-right font-medium",children:u(o.commission_amount)}),e.jsx(R,{children:e.jsx(_e,{status:o.status})}),e.jsxs(R,{className:"text-right space-x-1",children:[e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>g.mutate(o.id),children:[e.jsx(ae,{className:"h-3 w-3 mr-1"})," Approve"]}),e.jsxs(w,{size:"sm",variant:"ghost",onClick:()=>y(o.id),children:[e.jsx(vs,{className:"h-3 w-3 mr-1"})," Reject"]})]})]},o.id))})]})})]})}),M&&e.jsxs(e.Fragment,{children:[e.jsx(I,{children:e.jsxs(L,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"font-medium text-sm",children:["Approved, awaiting payout (",i.length,")"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",onClick:()=>N.mutate(i.map(o=>o.id)),disabled:i.length===0,children:"Mark all ready"}),A?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:"sm",variant:"ghost",onClick:l,children:"Cancel"}),e.jsxs(w,{size:"sm",onClick:J,disabled:b.size===0,children:[e.jsx(Ye,{className:"h-3 w-3 mr-1"})," Create payout (",b.size,")"]})]}):e.jsx(w,{size:"sm",variant:"outline",onClick:()=>f(!0),disabled:i.length===0,children:"Select"})]})]}),i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No approved commissions ready for payout."}):e.jsx("div",{className:"rounded-lg border overflow-x-auto",children:e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(U,{children:[A&&e.jsx(P,{className:"w-10"}),e.jsx(P,{children:"Member"}),e.jsx(P,{className:"text-right",children:"Amount"}),e.jsx(P,{children:"Status"}),e.jsx(P,{children:"Approved"})]})}),e.jsx(ye,{children:i.map(o=>e.jsxs(U,{children:[A&&e.jsx(R,{children:e.jsx(bs,{checked:b.has(o.id),onCheckedChange:()=>H(o.id)})}
1),e.jsx(R,{className:"text-xs",children:c(o.user_id)}),e.jsx(R,{className:"text-right font-medium",children:u(o.commission_amount)}),e.jsx(R,{children:e.jsx(_e,{status:o.status})}),e.jsx(R,{className:"text-xs text-muted-foreground",children:o.approved_at?k(Y(o.approved_at),"dd MMM yyyy"):"-"})]},o.id))})]})})]})}),e.jsx(I,{children:e.jsxs(L,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"font-medium text-sm",children:["Payouts (",h.length,")"]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:Z,disabled:h.length===0||q.isLoading||!Q,title:X??void 0,children:[e.jsx(pt,{className:"h-3 w-3 mr-1"})," Export CSV"]})]}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No payouts yet."}):e.jsx("div",{className:"rounded-lg border overflow-x-auto",children:e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(U,{children:[e.jsx(P,{children:"Member"}),e.jsx(P,{className:"text-right",children:"Amount"}),e.jsx(P,{children:"Period"}),e.jsx(P,{children:"Status"}),e.jsx(P,{children:"Paid"}),e.jsx(P,{className:"text-right",children:"Action"})]})}),e.jsx(ye,{children:h.map(o=>e.jsxs(U,{children:[e.jsx(R,{className:"text-xs",children:c(o.user_id)}),e.jsx(R,{className:"text-right font-medium",children:u(o.total_amount)}),e.jsxs(R,{className:"text-xs",children:[o.period_start??"-"," to ",o.period_end??"-"]}),e.jsx(R,{children:e.jsx(_e,{status:o.status})}),e.jsx(R,{className:"text-xs text-muted-foreground",children:o.paid_at?k(Y(o.paid_at),"dd MMM yyyy"):"-"}),e.jsx(R,{className:"text-right",children:o.status!=="paid"&&e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>{const T=window.prompt("Payment reference (optional)")??void 0;_.mutate({id:o.id,reference:T||void 0})},children:[e.jsx(es,{className:"h-3 w-3 mr-1"})," Mark paid"]})})]},o.id))})]})})]})})]}),e.jsx(qt,{open:!!d,onOpenChange:o=>!o&&y(null),commissionId:d})]})}const It=["Commission only applies to closed-won deals.","Deal must have a value greater than zero.","Deal must have an assigned owner.","Commission must match an active commission rule.","Payout requires manager or admin approval.","Paid commission cannot be edited - record an adjustment or reversal instead."];function ds(){const{data:s=[]}=At();return e.jsxs("div",{className:"space-y-5",children:[e.jsx(I,{children:e.jsxs(L,{className:"p-4 space-y-3",children:[e.jsx("div",{className:"text-sm font-medium",children:"Commission rules"}),e.jsx("ul",{className:"space-y-2",children:It.map((t,a)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ae,{className:"h-4 w-4 text-success mt-0.5 shrink-0"}),e.jsx("span",{children:t})]},a))})]})}),e.jsx(I,{children:e.jsxs(L,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Adjustments & exceptions (",s.length,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adjustments are added from a specific commission row in My earnings or Team commissions."}),s.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ns,{className:"h-4 w-4"})," No adjustments recorded."]}):e.jsx("div",{className:"rounded-lg border overflow-x-auto",children:e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(U,{children:[e.jsx(P,{children:"Type"}),e.jsx(P,{className:"text-right",children:"Amount"}),e.jsx(P,{children:"Reason"}),e.jsx(P,{children:"Commission"}),e.jsx(P,{children:"Created"})]})}),e.jsx(ye,{children:s.map(t=>e.jsxs(U,{children:[e.jsx(R,{className:"capitalize",children:t.adjustment_type}),e.jsx(R,{className:"text-right font-medium",children:u(t.amount)}),e.jsx(R,{className:"text-xs text-muted-foreground max-w-md truncate",children:t.reason}),e.jsx(R,{className:"text-xs",children:t.commission_id.slice(0,8)}),e.jsx(R,{className:"text-xs text-muted-foreground",children:k(Y(t.created_at),"dd MMM yyyy")})]},t.id))})]})})]})})]})}function Lt({person:s,onOpen:t}){const a=s.exceptionRows[0];return e.jsxs("li",{className:"flex items-start justify-between gap-3 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:s.name}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s.exceptionReason?s.exceptionReason:`Earned ${u(s.earned)}`})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium tabular-nums",children:u(s.earned)}),a&&e.jsx(w,{variant:"outline",size:"sm",onClick:()=>t(a),children:"Review"})]})]})}function Ft({focus:s=null,memberNames:t}={}){const a=K(),{data:n=[],isLoading:r}=ns(a,void 0),{data:h=[]}
1=Le(a),g=Oe(),N=Ue("commissions"),[p,_]=j.useState(null),[c,d]=j.useState(!1);j.useEffect(()=>{s==="payments"&&d(!0)},[s]);const y=j.useMemo(()=>{const l=new Map;for(const[v,i]of Object.entries(t??{}))l.set(v,i);for(const v of h){const i=[v.first_name,v.last_name].filter(Boolean).join(" ").trim()||v.full_name||v.email||"Team member";v.id&&l.set(v.id,i),v.user_id&&l.set(v.user_id,i)}return v=>l.get(v)??"Team member"},[h,t]),b=j.useMemo(()=>Bs(n,y),[n,y]),S=j.useMemo(()=>{const l={...t??{}};for(const v of[...b.needsAttention,...b.ready])l[v.userId]=v.name;return l},[b,t]);if(r)return e.jsx(G,{className:"h-64 w-full"});if(n.length===0)return e.jsx(Fe,{icon:_s,title:"No commission earned this month",description:"Team commission appears after confirmed customer payments qualify under the approved rules."});const A=async l=>{try{await g.mutateAsync(l.id),C.success("Commission approved"),_(null)}catch{C.error("Could not approve this commission")}},f=b.ready.filter(l=>l.ready>0);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"This month"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Team earned"}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:u(b.totals.earned)})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ready to pay"}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:u(b.totals.readyToPay)})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:u(b.totals.pending)})]})]}),b.needsAttention.length>0&&e.jsx(I,{children:e.jsxs(L,{className:"p-0",children:[e.jsxs("p",{className:"flex items-center gap-1.5 px-4 pt-3 pb-2 text-xs font-medium text-warning",children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"Needs attention"]}),e.jsx("ul",{className:"divide-y",children:b.needsAttention.map(l=>e.jsx(Lt,{person:l,onOpen:_},l.userId))})]})}),f.length>0&&e.jsx(I,{children:e.jsxs(L,{className:"p-0",children:[e.jsx("p",{className:"px-4 pt-3 pb-2 text-xs font-medium text-muted-foreground",children:"Ready to pay"}),e.jsx("ul",{className:"divide-y",children:f.map(l=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:l.name}),e.jsx("span",{className:"text-sm font-medium tabular-nums",children:u(l.ready)})]},l.userId))}),e.jsx("div",{className:"border-t p-3",children:e.jsx(w,{size:"sm",onClick:()=>d(l=>!l),children:c?"Hide payments":"Review payments"})})]})}),c&&e.jsx(Ee,{section:"payouts",memberNames:S}),e.jsx(ls,{row:p,open:!!p,onOpenChange:l=>!l&&_(null),footer:p&&p.status==="pending"?e.jsxs(w,{size:"sm",disabled:g.isPending,onClick:()=>A(p),children:[e.jsx(Cs,{className:"mr-1.5 h-3.5 w-3.5"})," Approve"]}):null}),e.jsx(ts,{module:"commissions",description:"The full commission table, payout batches, adjustments and the calculation audit.",children:e.jsxs("div",{className:"space-y-4",children:[N.can("payouts")&&e.jsx(Ee,{section:"all",memberNames:S}
1),N.can("adjustments")&&e.jsx(ds,{})]})})]})}function ms(s){const t=K();return se({queryKey:[z.disputes,t,(s==null?void 0:s.openOnly)??!1],enabled:!!t,staleTime:3e4,queryFn:async()=>{let a=E.from("commission_disputes").select(`id, commission_id, raised_by, reason_code, expected_amount, explanation, status,
2           original_amount, adjustment_amount, resolution_note, resolved_by, resolved_at, created_at,
3           commissions ( id, commission_amount, commission_rate, deal_value, qualifying_amount,
4                         status, invoice_id, deal_id, rule_snapshot, user_id )`).eq("org_id",t).order("created_at",{ascending:!1}).limit(100);s!=null&&s.openOnly&&(a=a.in("status",["submitted","under_review"]));const{data:n,error:r}=await a;if(r)throw r;return n??[]}})}function $e(){const s=$();return()=>{s.invalidateQueries({queryKey:[z.disputes]}),s.invalidateQueries({queryKey:[z.ledger]}),s.invalidateQueries({queryKey:[z.evidence]}),s.invalidateQueries({queryKey:["commissions"]})}}function Dt(){const s=$e();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("open_commission_dispute",{_commission_id:t.commissionId,_reason_code:t.reasonCode,_expected_amount:t.expectedAmount,_explanation:t.explanation,_attachment_url:t.attachmentUrl??null});if(n)throw n;return a},onSuccess:s})}function Ot(){const s=$e();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("review_commission_dispute",{_dispute_id:t.disputeId,_note:t.note??null});if(n)throw n;return a},onSuccess:s})}function $t(){const s=$e();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("resolve_commission_dispute",{_dispute_id:t.disputeId,_outcome:t.outcome,_adjustment_amount:t.adjustmentAmount??null,_note:t.note??null});if(n)throw n;return a},onSuccess:s})}function Kt({commissionId:s,amount:t,open:a,onOpenChange:n}){const[r,h]=j.useState(Ae[0].code),[g,N]=j.useState(""),[p,_]=j.useState(""),c=Dt(),d=async()=>{if(p.trim().length<5){C.error("Tell your manager what looks wrong",{description:"A sentence is enough - it is what they will read first."});return}try{await c.mutateAsync({commissionId:s,reasonCode:r,expectedAmount:g.trim()?Number(g):null,explanation:p.trim()}),C.success("Raised with your manager",{description:"You will see their decision here, with the reason."}),n(!1),_(""),N("")}catch(y){C.error("That did not save",{cause:y})}};return e.jsx(Pe,{open:a,onOpenChange:n,children:e.jsxs(Re,{className:"max-w-lg",children:[e.jsxs(ke,{children:[e.jsx(qe,{children:"Query this earning"}),e.jsxs(Ss,{children:["This earning is recorded as ",u(t),". Nothing changes until a manager decides."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"What looks wrong?"}),e.jsxs(re,{value:r,onValueChange:h,children:[e.jsx(oe,{children:e.jsx(le,{})}),e.jsx(ce,{children:Ae.map(y=>e.jsx(de,{value:y.code,children:y.label},y.code))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"What did you expect? (optional)"}),e.jsx(ee,{type:"number",inputMode:"decimal",value:g,onChange:y=>N(y.target.value),placeholder:"Amount you expected"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Explain it in your own words"}),e.jsx(Ie,{rows:4,value:p,onChange:y=>_(y.target.value),placeholder:"For example: the customer paid the balance last week, so this should be the full amount."})]})]}),e.jsxs(Ze,{children:[e.jsx(w,{variant:"ghost",onClick:()=>n(!1),children:"Cancel"}),e.jsx(w,{onClick:d,disabled:c.isPending,children:c.isPending?"Sending...":"Send to my manager"})]})]})})}function zt(s){return se({queryKey:["commission-explanation",s??null],enabled:!!s,...Ms("slow"),queryFn:async()=>{const{data:t,error:a}=await E.rpc("explain_commission",{_commission_id:s});if(a)throw a;return t??{}}})}function Qt(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("classify_commission_sale",{_invoice_id:t.invoiceId,_classification:t.classification,_reason:t.reason});if(n)throw n;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["commission-explanation"]}),C.success("Sale classified",{description:"The reason is recorded against the sale."})},onError:t=>C.error("Could not classify this sale",{description:ve(t)})})}function Bt(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("authorise_commission_exception",{_commission_id:t.commissionId,_replacement_amount:t.replacementAmount,_reason:t.reason,_effective_from:t.effectiveFrom??null});if(n)throw n;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["commission-explanation"]}),s.invalidateQueries({queryKey:["commission-ledger"]}),C.success("Exception recorded",{description:"The original rule and amount stay on the record."})},onError:t=>C.error("Could not record this exception",{description:ve(t)})})}function xe({label:s,value:t}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 py-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"text-sm font-medium tabular-nums",children:t})]})}const Wt=[{value:"new_business",label:"New business"},{value:"upsell",label:"Upsell - more of what they already buy"},{value:"cross_sell",label:"Cross-sell - something different"},{value:"renewal",label:"Renewal"}],Ht={payment:"the payment it came from",rule_version:"the rule version used",rule_snapshot:"what the rule said on the day",invoice:"the sale it belongs to"};function Vt({commissionId:s,canManage:t=!1}){var i;const{data:a,isLoading:n}=zt(s),r=Bt(),h=Qt(),[g,N]=j.useState(""),[p,_]=j.useState(""),[c,d]=j.useState("");
4if(n)return e.jsx(G,{className:"h-40 w-full"});if(!a)return null;const y=String(a.currency??"NGN"),b=a.payment,S=a.missing_evidence??[],A=a.classification??[],f=a.exceptions??[],l=a.payout,v=a.classification_history??[];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"What this is built on"}),e.jsx(xe,{label:"Money that qualified",value:B(Number(a.qualifying_amount??0),y)}),e.jsx(xe,{label:"Rate used",value:`${Number(a.rate??0)}%`}),Number(a.share_percent??100)!==100&&e.jsx(xe,{label:"Share of the sale",value:`${Number(a.share_percent)}%`}),e.jsx(xe,{label:"Commission",value:B(Number(a.amount??0),y)}),b&&e.jsx("p",{className:"mt-2 border-t pt-2 text-xs text-muted-foreground",children:b.qualified?`Payment of ${B(Number(b.amount??0),String(b.currency??y))} qualified.`:`This payment does not qualify: ${String(b.why_not??"no reason recorded")}.`}),l&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Payout ",String(l.status??""),l.reference?` · reference ${String(l.reference)}`:""]})]}),A&&A.length>0&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"How the sale was classified"}),A.map((m,M)=>e.jsxs("p",{className:"text-sm",children:[String(m.classification??"").replace(/_/g," "),m.reason?` - ${String(m.reason)}`:""]},M)),v.length>1&&e.jsxs("div",{className:"mt-2 border-t pt-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Earlier decisions"}),v.map((m,M)=>e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.from?`${String(m.from).replace(/_/g," ")} became `:"First recorded as ",String(m.to??"").replace(/_/g," "),m.reason?` - ${String(m.reason)}`:""]},M))]})]}),f&&f.length>0&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Authorised exception"}),f.map((m,M)=>e.jsxs("div",{className:"text-sm",children:[e.jsxs("p",{children:["The rule said ",B(Number(m.original_amount??0),y),"; this was authorised as ",B(Number(m.replacement_amount??0),y),m.reason?` - ${String(m.reason)}`:""]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The rule itself did not change; only this earning was treated differently."})]},M))]}),S.length>0&&e.jsxs("div",{className:"rounded-lg border border-warning/40 bg-warning/10 p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"This amount cannot be fully confirmed"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Missing: ",S.map(m=>Ht[m]??m).join(", "),"."]})]}),t&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Authorise a different amount"}),e.jsx(ee,{inputMode:"decimal",placeholder:"Replacement amount",value:g,onChange:m=>N(m.target.value)}),e.jsx(ee,{placeholder:"Why is this being changed?",value:p,onChange:m=>_(m.target.value)}),e.jsx(w,{size:"sm",variant:"outline",disabled:!s||!p.trim()||r.isPending,onClick:()=>s&&r.mutate({commissionId:s,replacementAmount:Number(g.replace(/[^\d.]/g,""))||0,reason:p.trim()}),children:"Record exception"}),((i=a.invoice)==null?void 0:i.id)&&e.jsxs("div",{className:"space-y-2 border-t pt-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"What kind of sale is this?"}),e.jsxs(re,{value:c,onValueChange:m=>d(m),children:[e.jsx(oe,{children:e.jsx(le,{placeholder:"Choose"})}),e.jsx(ce,{children:Wt.map(m=>e.jsx(de,{value:m.value,children:m.label},m.value))})]}),e.jsx(w,{size:"sm",variant:"outline",disabled:!c||!p.trim()||h.isPending,onClick:()=>{c&&h.mutate({invoiceId:String(a.invoice.id),classification:c,reason:p.trim()})},children:"Record this classification"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Say why. Nothing is assumed, and the earlier decision is kept."})]})]})]})}function te({label:s,value:t}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"text-sm font-medium tabular-nums",children:t})]})}function Ut({row:s,open:t,onOpenChange:a,canDispute:n=!0}){var S,A,f,l,v;const{data:r,isLoading:h}=Zs(t?s==null?void 0:s.id:null),[g,N]=j.useState(!1);if(!s)return null;const p=s.rule_snapshot??{},_=s.earned_trigger??"deal_won",c=Number(s.collected_amount??s.invoice_paid_amount??0),d=Number(s.share_percent??100),y=Number(s.reversed_amount??0),b=Number(s.clawback_amount??0);return e.jsxs(e.Fragment,{children:[e.jsx(As,{open:t,onOpenChange:a,children:e.jsxs(Ts,{side:"right",className:"w-full overflow-y-auto sm:max-w-md",children:[e.jsx(Es,{children:e.jsx(Ps,{children:((A=(S=s.deals)==null?void 0:S.title)==null?void 0:A.trim())||"Sale"})}),e.jsxs("div",{className:"mt-4 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums",children:u(Number(s.commission_amount??0))}),e.jsx(ie,{row:s,detail:!0})]}),e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"How it was worked out"}),e.jsx(te,{label:"Sale value",value:u(Number(s.deal_value??0))}),e.jsx(te,{label:"Money received",value:u(c)}),e.jsx(te,{label:"Rate used",value:`${Number(s.commission_rate??0)}%`}),d!==100&&e.jsx(te,{label:"Your share of the sale",value:`${d}%`}),y>0&&e.jsx(te,{label:"Reversed after a refund",value:u(y)}),b>0&&e.jsx(te,{label:"Recoverable",value:u(b)}),e.jsxs("p",{className:"mt-2 border-t pt-2 text-xs text-muted-foreground",children:[je[_]??"When the sale qualified",p!=null&&p.name?` · Rule: ${String(p.name)}`:""]}),s.split_reason&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Shared: ",s.split_reason]})]}),e.jsx(Vt,{commissionId:s.id}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"What happened"}),h?e.jsx(G,{className:"h-24 w-full"}):e.jsxs("ul",{className:"space-y-2",children:[[...((r==null?void 0:r.events)??[]).map(i=>({id:`e-${i.id}`,at:i.created_at,label:Ke(i.event_kind),detail:i.amount?u(Number(i.amount)):null})),...((r==null?void 0:r.history)??[]).map(i=>({id:`h-${i.id}`,at:i.created_at,label:Ke(i.action),detail:i.reason??null})),...((r==null?void 0:r.adjustments)??[]).map(i=>({id:`a-${i.id}`,at:i.created_at,label:`Adjustment · ${i.adjustment_type}`,detail:`${u(Number(i.amount))}${i.reason?` · ${i.reason}`:""}`}))].sort((i,m)=>String(m.at??"").localeCompare(String(i.at??""))).map(i=>e.jsxs("li",{className:"rounded-md border px-3 py-2",children:[e.jsx("p",{className:"text-sm",children:i.label}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[i.at?k(Y(i.at),"d MMM yyyy, HH:mm"):"",i.detail?` · ${i.detail}`:""]})]},i.id)),(((f=r==null?void 0:r.events)==null?void 0:f.length)??0)+(((l=r==null?void 0:r.history)==null?void 0:l.length)??0)+(((v=r==null?void 0:r.adjustments)==null?void 0:v.length)??0)===0&&e.jsx("li",{className:"text-sm text-muted-foreground",children:"Nothing has been recorded on this earning yet."})]})]}),n&&!s.dispute_id&&e.jsx(w,{variant:"outline",className:"w-full",onClick:()=>N(!0),children:"This looks wrong"}),s.dispute_id&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You have already raised this with your manager."})]})]})}),e.jsx(Kt,{commissionId:s.id,amount:Number(s.commission_amount??0),open:g,onOpenChange:N})]})}const Yt=[{value:"this-month",label:"This month"},{value:"last-month",label:"Last month"},{value:"all",label:"Everything"}];function Gt(s){const t=new Date;if(s==="last-month"){const a=ft(t);
4return{from:Te(a),to:Se(a)}}return s==="all"?{from:new Date(1900,0,1),to:new Date(2999,11,31)}:{from:Te(t),to:Se(t)}}function he({icon:s,label:t,value:a}){return e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(s,{className:"h-3.5 w-3.5"}),t]}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:a})]})}function Jt({userId:s}={}){const t=me(),a=Je(),n=!a.isLoading&&a.canOpen("deals"),[r,h]=j.useState("this-month"),[g,N]=j.useState(""),[p,_]=j.useState(null),c=j.useMemo(()=>Gt(r),[r]),{data:d=[],isLoading:y}=os({userId:s}),b=et({userId:s,from:k(c.from,"yyyy-MM-dd"),to:k(c.to,"yyyy-MM-dd")}),S=j.useMemo(()=>d.filter(l=>{const v=l.created_at?new Date(l.created_at):null;return v?v>=c.from&&v<=c.to:r==="all"}),[d,c,r]),A=j.useMemo(()=>{const l=g.trim().toLowerCase();return l?S.filter(v=>{var i,m,M;return(((i=v.deals)==null?void 0:i.title)??"").toLowerCase().includes(l)||(((M=(m=v.deals)==null?void 0:m.contacts)==null?void 0:M.full_name)??"").toLowerCase().includes(l)}):S},[S,g]);if(y)return e.jsx(G,{className:"h-64 w-full"});const f=b.data;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ss,{tabs:Yt,value:r,onChange:l=>h(l),label:"Earnings period"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[e.jsx(he,{icon:we,label:"Earned",value:u((f==null?void 0:f.grossCommission)??0)}),e.jsx(he,{icon:Ce,label:"Adjustments",value:u((f==null?void 0:f.adjustments)??0)}),e.jsx(he,{icon:gt,label:"Net",value:u((f==null?void 0:f.netCommission)??0)}),e.jsx(he,{icon:ae,label:"Paid",value:u((f==null?void 0:f.paid)??0)})]}),((f==null?void 0:f.revenueCredited)??0)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Worked out on ",u(f.revenueCredited)," of sales credited to you in this period."]}),S.length===0?e.jsx(Fe,{icon:Xe,heading:"Nothing earned in this period",subtext:"An earning appears after a confirmed customer payment qualifies for you under the approved rules.",secondaryActionLabel:n?"View my deals":void 0,onSecondaryAction:n?()=>t(Ws):void 0}):e.jsxs(e.Fragment,{children:[e.jsx(jt,{search:g,onSearchChange:N,searchPlaceholder:"Search by sale or customer..."}),e.jsx(I,{children:e.jsxs(L,{className:"p-0",children:[e.jsx("ul",{className:"divide-y",children:A.map(l=>{var m,M;const v=Number(l.collected_amount??l.invoice_paid_amount??0),i=Number(l.share_percent??100);return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>_(l),className:"flex w-full items-start justify-between gap-3 px-4 py-3 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:((M=(m=l.deals)==null?void 0:m.title)==null?void 0:M.trim())||"Sale"}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[u(Number(l.deal_value??0))," sale",v>0&&` · ${u(v)} received`,Number(l.commission_rate??0)>0&&` · ${Number(l.commission_rate)}%`,i!==100&&` · your share ${i}%`]}),l.created_at&&e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:k(Y(l.created_at),"d MMM yyyy")})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("span",{className:"text-sm font-semibold tabular-nums",children:u(Number(l.commission_amount??0))}),e.jsx(ie,{row:l})]})]})},l.id)})}),A.length===0&&e.jsxs("p",{className:"py-6 text-center text-sm text-muted-foreground",children:['No earnings match "',g,'".']})]})})]}),e.jsx(Ut,{row:p,open:!!p,onOpenChange:l=>!l&&_(null),canDispute:!s}),S.length>0&&e.jsx("div",{children:e.jsx(w,{variant:"outline",size:"sm",onClick:()=>window.print(),title:"Print or save this statement",children:"Print statement"})})]})}function Xt(){const s=K();return se({queryKey:[z.batches,s],enabled:!!s,staleTime:3e4,queryFn:async()=>{const{data:t,error:a}=await E.from("commission_payouts").select(`id, user_id, total_amount, adjustments_total, net_amount, period_start, period_end,
5           status, cycle, reviewed_at, approved_at, processing_at, paid_at, payment_reference,
6           correlation_id, created_at`).eq("org_id",s).order("created_at",{ascending:!1}).limit(100);if(a)throw a;return t??[]}})}function us(){const s=$();return()=>{s.invalidateQueries({queryKey:[z.batches]}),s.invalidateQueries({queryKey:[z.ledger]}),s.invalidateQueries({queryKey:[z.statement]}),s.invalidateQueries({queryKey:["commissions"]}),s.invalidateQueries({queryKey:["commission-payouts"]})}}function Zt(){const s=us();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("build_commission_payout_batch",{_user_id:t.userId,_period_start:t.periodStart,_period_end:t.periodEnd,_cycle:t.cycle??"monthly"});if(n)throw n;return a},onSuccess:s})}function ea(){const s=us();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("advance_commission_payout",{_payout_id:t.payoutId,_to_status:t.to,_reference:t.reference??null});if(n)throw n;return a},onSuccess:s})}function sa({memberNames:s}){const t=K(),{data:a=[]}=Le(t),{data:n=[]}=Xt(),r=Zt(),h=ea(),g=new Date,[N,p]=j.useState(""),[_,c]=j.useState("monthly"),[d,y]=j.useState(k(Te(g),"yyyy-MM-dd")),[b,S]=j.useState(k(Se(g),"yyyy-MM-dd")),A=j.useMemo(()=>a.filter(i=>i.auth_id).map(i=>
6({id:i.auth_id,label:[i.first_name,i.last_name].filter(Boolean).join(" ").trim()||i.full_name||i.email||"Team member"})),[a]),f=i=>{var m;return(s==null?void 0:s[i])??((m=A.find(M=>M.id===i))==null?void 0:m.label)??"Team member"},l=async()=>{if(!N){C.error("Choose who this payout is for");return}try{const i=await r.mutateAsync({userId:N,periodStart:d,periodEnd:b,cycle:_});if(!i||Number(i.included??0)===0){C.info("Nothing to pay in that period",{description:"Only approved earnings that are not already in a payout can be included."});return}C.success(`Draft payout for ${f(N)}: ${u(Number(i.net_amount??i.total_amount??0))}`)}catch(i){C.error("That did not save",{cause:i})}},v=async(i,m)=>{let M=null;if(m==="paid"&&(M=window.prompt("Payment reference (required)")??null,!(M!=null&&M.trim()))){C.error("A payment reference is required",{description:"It is how this payout can be traced to the money that left."});return}try{await h.mutateAsync({payoutId:i,to:m,reference:M}),C.success(`Payout ${Qe[m].toLowerCase()}`)}catch(H){C.error("That did not save",{cause:H})}};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(I,{children:e.jsxs(L,{className:"space-y-3 p-4",children:[e.jsx("p",{className:"text-sm font-medium",children:"Build a payout"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Who"}),e.jsxs(re,{value:N,onValueChange:p,children:[e.jsx(oe,{children:e.jsx(le,{placeholder:"Choose a person"})}),e.jsx(ce,{children:A.map(i=>e.jsx(de,{value:i.id,children:i.label},i.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"How often"}),e.jsxs(re,{value:_,onValueChange:i=>c(i),children:[e.jsx(oe,{children:e.jsx(le,{})}),e.jsx(ce,{children:Object.keys(ze).map(i=>e.jsx(de,{value:i,children:ze[i]},i))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"From"}),e.jsx(ee,{type:"date",value:d,onChange:i=>y(i.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"To"}),e.jsx(ee,{type:"date",value:b,onChange:i=>S(i.target.value)})]})]}),e.jsx(w,{size:"sm",onClick:l,disabled:r.isPending,children:r.isPending?"Building...":"Create draft payout"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only approved earnings that are not already in a payout are included."})]})}),e.jsx(I,{children:e.jsxs(L,{className:"p-0",children:[e.jsx("p",{className:"px-4 pt-3 pb-2 text-xs font-medium text-muted-foreground",children:"Payout batches"}),n.length===0?e.jsx("p",{className:"px-4 pb-4 text-sm text-muted-foreground",children:"No payouts yet."}):e.jsx("ul",{className:"divide-y",children:n.map(i=>{const m=Hs(i.status);return e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-3 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium",children:[f(i.user_id)," ·"," ",u(Number(i.net_amount??i.total_amount??0))]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[i.period_start??"-"," to ",i.period_end??"-",Number(i.adjustments_total??0)!==0&&` · adjustments ${u(Number(i.adjustments_total))}`,i.paid_at&&` · paid ${k(Y(i.paid_at),"d MMM yyyy")}`,i.payment_reference&&` · ref ${i.payment_reference}`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{variant:i.status==="paid"?"outline":"secondary",children:Qe[i.status??"draft"]??i.status}),m&&e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>v(i.id,m.to),disabled:h.isPending,children:[e.jsx(es,{className:"mr-1 h-3 w-3"}),m.label]})]})]},i.id)})})]})}),e.jsx(Ee,{section:"approvals",memberNames:s})]})}function ta(s){const t=K();return se({queryKey:[z.trigger,t,s.newTrigger,s.effectiveFrom],enabled:!!t&&!!s.newTrigger&&s.enabled!==!1,staleTime:15e3,queryFn:async()=>{const{data:a,error:n}=await E.rpc("preview_commission_trigger_change",{_new_trigger:s.newTrigger,_effective_from:s.effectiveFrom});if(n)throw n;const r=a??{};return{currentTrigger:r.current_trigger??"deal_won",newTrigger:r.new_trigger??s.newTrigger,effectiveFrom:String(r.effective_from??s.effectiveFrom),existingEarnings:Number(r.existing_earnings??0),existingAmount:Number(r.existing_amount??0),openInvoices:Number(r.open_invoices??0),uncollectedAmount:Number(r.uncollected_amount??0)}}})}function aa(){const s=$();return F({mutationFn:async t=>{const{data:a,error:n}=await E.rpc("set_commission_trigger",{_new_trigger:t.trigger,_effective_from:t.effectiveFrom});if(n)throw n;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["org-setting"]}),s.invalidateQueries({queryKey:["org-settings"]}),s.invalidateQueries({queryKey:[z.trigger]})}})}const na=["payment_received","invoice_paid","invoice_sent","deal_won"];function ia({canManage:s}){const t=me(),{settings:a}=De(),n=(a==null?void 0:a.earnEvent)??"deal_won",[r,h]=j.useState(null),[g,N]=j.useState(k(yt(new Date,1),"yyyy-MM-dd")),p=ta({newTrigger:r,effectiveFrom:g,enabled:!!r&&r!==n}),_=aa(),c=async()=>
6{if(r)try{await _.mutateAsync({trigger:r,effectiveFrom:g}),C.success("Saved",{description:`From ${k(new Date(g),"d MMM yyyy")}, commission is earned ${je[r].toLowerCase()}. Earnings already recorded are untouched.`}),h(null)}catch(d){C.error("That did not save",{cause:d})}};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(I,{children:e.jsxs(L,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"When commission is earned"}),n===Vs&&e.jsx(be,{variant:"secondary",children:"Recommended"})]}),e.jsx("p",{className:"text-sm",children:je[n]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Be[n]}),s&&e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Change it to"}),e.jsxs(re,{value:r??n,onValueChange:d=>h(d),children:[e.jsx(oe,{children:e.jsx(le,{})}),e.jsx(ce,{children:na.map(d=>e.jsx(de,{value:d,children:je[d]},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Applies from"}),e.jsx(ee,{type:"date",value:g,onChange:d=>N(d.target.value)})]})]}),r&&r!==n&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:Be[r]}),p.data&&e.jsxs("div",{className:"rounded-md bg-muted/40 p-3 text-xs",children:[e.jsxs("p",{children:[p.data.existingEarnings," earning",p.data.existingEarnings===1?"":"s"," worth"," ",u(p.data.existingAmount)," stay exactly as they are."]}),e.jsxs("p",{className:"mt-1",children:[p.data.openInvoices," open invoice",p.data.openInvoices===1?"":"s"," with"," ",u(p.data.uncollectedAmount)," still to collect will follow the new rule."]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{size:"sm",onClick:c,disabled:_.isPending,children:_.isPending?"Saving...":"Apply from that date"}),e.jsx(w,{size:"sm",variant:"ghost",onClick:()=>h(null),children:"Cancel"})]})]})]})]})}),e.jsx(I,{children:e.jsxs(L,{className:"space-y-2 p-4",children:[e.jsx("p",{className:"text-sm font-medium",children:"How the rates are set"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Rates, tiers, targets and per-person exceptions live in Business Settings so one place decides how everybody is paid."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Tiered rules: ",We.whole," — or, if you choose, ",We.band.toLowerCase(),"."]}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>t(Us),children:"Open commission settings"})]})}),e.jsx(ds,{})]})}const ra=s=>{var t;return((t=Ae.find(a=>a.code===s))==null?void 0:t.label)??"Queried"};function oa({memberNames:s}){const{data:t=[]}=ms(),a=Ot(),n=$t(),[r,h]=j.useState(null),[g,N]=j.useState(""),[p,_]=j.useState(""),c=async(d,y)=>{if(p.trim().length<3){C.error("Say why",{description:"The person who raised this will read your reason."});return}try{await n.mutateAsync({disputeId:d,outcome:y,adjustmentAmount:y==="resolved"&&g.trim()?Number(g):null,note:p.trim()}),C.success(y==="resolved"?"Query resolved":"Query rejected"),h(null),N(""),_("")}catch(b){C.error("That did not save",{cause:b})}};return t.length===0?e.jsx(I,{children:e.jsx(L,{className:"p-4 text-sm text-muted-foreground",children:"Nobody has queried their commission."})}):e.jsx("div",{className:"space-y-3",children:t.map(d=>{var A,f;const y=d.status??"submitted",b=y==="submitted"||y==="under_review",S=(s==null?void 0:s[((A=d.commissions)==null?void 0:A.user_id)??""])??"Team member";return e.jsx(I,{children:e.jsxs(L,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:[S," · ",ra(d.reason_code)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Recorded ",u(Number(((f=d.commissions)==null?void 0:f.commission_amount)??0)),d.expected_amount!=null&&` · they expected ${u(Number(d.expected_amount))}`,d.created_at&&` · ${k(Y(d.created_at),"d MMM yyyy")}`]})]}),e.jsx(be,{variant:b?"secondary":"outline",children:Ys[y]})]}),e.jsx("p",{className:"text-sm",children:d.explanation}),!b&&e.jsxs("p",{className:"rounded-md border bg-muted/40 p-2 text-xs text-muted-foreground",children:[d.resolution_note||"Decided",d.adjustment_amount?` · adjustment ${u(Number(d.adjustment_amount))}`:"",d.resolved_at?` · ${k(Y(d.resolved_at),"d MMM yyyy")}`:""]}),b&&r!==d.id&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[y==="submitted"&&e.jsx(w,{size:"sm",variant:"outline",onClick:()=>a.mutate({disputeId:d.id}),children:"Start reviewing"}),e.jsx(w,{size:"sm",onClick:()=>h(d.id),children:"Decide"})]}),b&&r===d.id&&e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsx(ee,{type:"number",inputMode:"decimal",value:g,onChange:l=>N(l.target.value),placeholder:"Adjustment amount (leave empty for no change)"}),e.jsx(Ie,{rows:3,value:p,onChange:l=>_(l.target.value),placeholder:"Explain your decision"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(w,{size:"sm",onClick:()=>c(d.id,"resolved"),disabled:n.isPending,children:"Agree and adjust"}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>c(d.id,"rejected"),disabled:n.isPending,children:"Keep as it is"}),e.jsx(w,{size:"sm",variant:"ghost",onClick:()=>h(null),children:"Cancel"})]})]})]})},d.id)})})}function ln({embedded:s=!1}
6={}){const t=K(),a=me(),{isAdminOrManager:n}=Ge(),[r,h]=hs(),{data:g=[]}=Le(t),N=Rs("commissions"),{hasPermission:p}=pe("commission.view_team"),{hasPermission:_}=pe("commission.manage"),{hasPermission:c}=pe("commission.payout"),d=n&&p,y=n&&_,b=n&&c,{data:S}=ot(),A=!d&&lt(S==null?void 0:S.membershipType),f=j.useMemo(()=>Gs(r.get("tab")),[r]);j.useEffect(()=>{f.redirectTo&&a(f.redirectTo,{replace:!0})},[f.redirectTo,a]);const l=j.useMemo(()=>{const x={};return g.forEach(o=>{const T=[o.first_name,o.last_name].filter(Boolean).join(" ").trim()||o.full_name||o.email||"Team member";o.auth_id&&(x[o.auth_id]=T),o.id&&(x[o.id]=T)}),x},[g]),v=j.useMemo(()=>["overview","earnings",...d?["team"]:[],...b?["payouts"]:[],...y?["rules"]:[]],[d,b,y]),i=j.useMemo(()=>v.map(x=>({value:x,label:Js[x]})),[v]),m=v.includes(f.job)?f.job:"overview",M=x=>{const o=new URLSearchParams(r);o.set("tab",x),h(o,{replace:!1})},{data:H=[]}=is(d?t:void 0,{dateRange:{start:"1900-01-01",end:"2999-12-31"}}),J=Oe(),{data:q=[]}=ms({openOnly:!0}),Q=j.useMemo(()=>H.filter(x=>Xs(x).lifecycle==="pending_approval"),[H]),X=j.useMemo(()=>Q.reduce((x,o)=>x+Number(o.commission_amount??0),0),[Q]),Z=j.useMemo(()=>[...d?q.map(x=>{var o,T;return{id:`dispute-${x.id}`,title:l[((o=x.commissions)==null?void 0:o.user_id)??""]??"Team member",reason:"Queried their commission - needs your decision",meta:u(Number(((T=x.commissions)==null?void 0:T.commission_amount)??0)),actionLabel:"Review",onAction:()=>M("team"),tone:"warning",source:"system"}}):[],...Q.map(x=>({id:x.id,title:l[x.user_id??""]??"Team member",reason:"Earned - waiting for approval",meta:u(Number(x.commission_amount??0)),actionLabel:"Approve",onAction:()=>J.mutate(x.id),tone:"warning",source:"system"}))],[Q,q,l,J,d]);return N?f.redirectTo?null:e.jsxs("div",{className:"space-y-4",children:[!s&&e.jsx(e.Fragment,{children:e.jsx(ks,{module:"commissions",title:He.commissions.title,description:He.commissions.description})}),d&&Z.length>0&&e.jsx(qs,{intent:"system",collapsibleKey:"commissions.attention",dismissKey:"commissions.attention",items:Z,summary:`${u(X)} waiting for approval`,onViewAll:()=>M("team")}),i.length>1&&e.jsx(ss,{tabs:i,value:m,onChange:M,label:"Commission views"}),m==="earnings"&&e.jsx(Jt,{}),m==="team"&&d&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ft,{focus:f.focus==="payments"||f.focus==="attention"?f.focus:null,memberNames:l}),e.jsx(oa,{memberNames:l})]}),m==="payouts"&&b&&e.jsx(sa,{memberNames:l}),m==="rules"&&y&&e.jsx(ia,{canManage:!0}),m==="overview"&&(A?e.jsx(St,{}):e.jsx(Ct,{onViewAll:()=>M("earnings")}))]}):e.jsx(ps,{to:"/dashboard",replace:!0})}export{ln as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.