1import{j as e,u as oe,d as $s,e as dt,f as mt}from"./data-DN-eP4ae.js";import{r as f,L as I,h as Be,e as ut}from"./react-BUOzgyp0.js";import{T as xt,a as ht,b as pt,c as Xe}from"./tabs-C7nTENN3.js";import{E as As,H as Rs,el as gt,c as B,P as vt,e as ft,B as y,cD as jt,f as Nt,bu as Ke,av as Q,$ as O,i as te,V as ue,a4 as Pe,cC as $e,j as Ve,ds as bt,k as Is,J as ke,x as pe,a$ as re,Q as Ae,aa as yt,U as wt,K as X,s as U,eN as ge,b1 as cs,af as ds,z as _t,a1 as kt,au as Ct,cQ as St,_ as Es,Y as ms,G as Tt,c2 as Dt,c3 as Mt,c4 as Pt,c5 as $t,ax as Ls,n as q,cs as At,I as Rt,X as It,fo as us,fn as Fs,A as xs,dr as Et,cF as Lt,aA as hs,aB as ps,aC as gs,aD as vs,aT as Ft,bD as Ot,a6 as Wt,o as Kt,bB as ns,F as Je,aE as Os,bA as _s,Z as zt,cd as qt,ce as Bt}from"./index-6GUxm5Tl.js";import{f as le,d as De}from"./format-BOCe1Q81.js";import{C as b,a as _,b as Vt,c as Ht}from"./card-Bpoa90g8.js";import{T as Re,a as Ie,b as ae,c as D,d as Ee,e as M}from"./table-CeZUCHxF.js";import{s as Yt,a as Gt,u as He,f as w,b as Ut,c as fs,d as Qt,e as Ws,g as js,m as Ks,p as zs,h as Ns,t as qs,C as Xt,i as Bs,j as Jt,k as Zt,l as ea,n as sa,o as ta,q as aa,r as na,v as ra,w as la,x as oa,y as ia,z as ca,A as da,B as ma,D as ua,E as xa,G as ha,F as pa,H as se,P as ga}from"./PerformanceAlignmentDiagnostic-BgOjFpNS.js";import{S as ve,a as fe,b as je,c as Ne,d as G}from"./select-C1j_15i9.js";import{G as rs}from"./gauge-D09rc50z.js";import{W as va}from"./workflow-BQhqW2ze.js";import{F as Vs}from"./flag-MJRNLl_Q.js";import{u as Ye,S as fa,a as ja}from"./business-signals-DgWOKYzq.js";import{A as bs}from"./AdvancedSection-CBPqO4JF.js";import{C as Na}from"./ContextualInsights-Gpukgl55.js";import{e as ba}from"./module-insights-DIdF2rv9.js";import{P as ya,G as wa,d as _a}from"./metricRegistry-CSrMgFtq.js";import{u as ka}from"./useFollowups-YB0qEXzK.js";import{u as Ca}from"./useDashboardFeatureMetrics-DDUJBq5T.js";import{s as Me}from"./startOfMonth-kO_ql4le.js";import{u as Hs,r as Sa,P as Ta}from"./useTeamContribution-D3gt-sDB.js";import{R as Ys,L as Da,C as Gs,X as Us,Y as Qs,T as Xs,a as Ma,B as Pa,b as $a}from"./charts-BjVT6r80.js";import{E as Aa}from"./eye-BMa0xke4.js";import{C as Ra,M as Ia}from"./mouse-pointer-click-DELbrTN2.js";import{E as Ea}from"./ellipsis-CAutlZKC.js";import{M as Js}from"./ModuleControlBar-Un2wShWM.js";import{F as de}from"./FieldLabel-TuIMjPm6.js";import{S as La}from"./StatCard-BFLxrhDG.js";import{u as Zs}from"./useCommissions-D4DjCA3_.js";import{T as Fa}from"./trash-2-DEbXoeSC.js";import{S as et}from"./SimpleDisclosure-VZmRaKZG.js";import{C as Oa}from"./calculator-793hz_om.js";import{d as Wa}from"./index-CGSmUr7J.js";import{F as ye}from"./file-spreadsheet-C0YUyC8u.js";import{D as st}from"./download-D8rVLK2a.js";import{u as Ka,r as za,d as qa,S as Ba,T as Va}from"./TeamAvatar-CX7lCsWL.js";import{F as Ha}from"./filter-CXt2ShtC.js";import{M as Ya}from"./minus-DzNOUrXP.js";import"./intents-B7QdDHP4.js";import{p as Ga}from"./page-language-DGjnPgNe.js";import{r as Ua}from"./secondary-CgtJLxBm.js";import{P as Qa}from"./PageHeader-CsFfXur0.js";import{b as Xa}from"./page-primary-BUiSypsU.js";import{C as Ja}from"./chevron-left-BO8s0r98.js";import{W as Za}from"./wallet-hX8y-nkf.js";import"./documents-Bju1cS7G.js";import"./pencil-DC8kxVxB.js";import"./useBusinessHoursData-taUmFrzr.js";import"./useBusinessProfileData-CXmZ_ZR5.js";import"./recognised-revenue-CWypD7KS.js";import"./subDays-BHo4iHhB.js";import"./addDays-FNsJkNgj.js";import"./useBusinessIntel-BD4boyNC.js";import"./business-taxonomy-DjKP5GVb.js";import"./layers-3zKAEbPs.js";import"./pen-line-9jiWvZNl.js";import"./wand-sparkles-5e-vVx-4.js";import"./thumbs-up-C_QXljbQ.js";import"./EvidenceBlock-D_VAY3Vh.js";import"./useSmartGuide-DB5xQ_Gx.js";import"./useIntelligencePlacement-CbLnAc_a.js";import"./module-intro-N0cKHpsA.js";import"./ActionChoiceSheet-Bej1gA4Q.js";import"./SearchBar-B8oDBZzP.js";import"./square-check-big-CBgkfjtW.js";import"./HelpTip-Dhp2bChC.js";import"./useDismissable-BvpILM0V.js";import"./useDisclosurePreference-CSD3NNSj.js";import"./spreadsheets-CKN5doRT.js";import"./settings-return-GcuqJJ7v.js";function en({actorId:s,eventSource:t,eventType:a,description:n,at:r,size:o="sm",className:c}){const{data:l}=Ka(),d=za({actorId:s,eventSource:t,eventType:a}),x=qa(r);let m=null;d.kind==="human"&&(m=(l??[]).find(u=>u.id===d.actorId||u.authId===d.actorId)??{id:d.actorId,name:"Team member"});const h=d.kind==="system"&&d.name===Ba.duceBot.name;return e.jsxs("div",{className:B("flex items-center gap-2 min-w-0",c),children:[m?e.jsx(Va,{member:m,size:o==="xs"?"xs":"sm"}):e.jsx(As,{className:B(o==="xs"?"h-5 w-5":"h-6 w-6","ring-2 ring-background"),children:e.jsx(Rs,{className:"bg-muted text-muted-foreground",children:h?e.jsx(gt,{className:"h-3 w-3"}):e.jsx(Ra,{className:"h-3 w-3"})})}),e.jsxs("p",{className:"min-w-0 truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:m?m.name:d.name}),n?e.jsxs("span",{className:"text-muted-foreground",children:[" ",n]}):null,x?e.jsxs("span",{className:"text-muted-foreground",children:[" · ",x==="Now"?"just now":`${x} ago`]}):null]})]})}const ls=[{key:"today",label:"Today",mode:"today"},{key:"7",label:"Last 7 days",days:7},{key:"month",label:"This month",mode:"this_month"},{key:"30",label:"Last 30 days",days:30},{key:"90",label:"Last 90 days",days:90}],we=s=>s.toISOString().slice(0,10);function tt(s){const t=new Date;if(s.mode==="today")return{start:we(t),end:we(t)};if(s.mode==="this_month")return{start:we(new Date(t.getFullYear(),t.getMonth(),1)),end:we(t)};const a=new Date;return s.days&&a.setDate(t.getDate()-(s.days-1)),{start:we(a),end:we(t)}}function sn(s){for(const t of ls){const a=tt(t);if(a.start===s.start&&a.end===s.end)return t.key}return"custom"}function tn({range:s,onChange:t}){var l;const[a,n]=f.useState(!1),r=sn(s),o=((l=ls.find(d=>d.key===r))==null?void 0:l.label)||"Custom range",c=`${le(new Date(s.start),"MMM d")} â ${le(new Date(s.end),"MMM d, yyyy")}`;return e.jsxs(vt,{open:a,onOpenChange:n,children:[e.jsx(ft,{asChild:!0,children:e.jsxs(y,{variant:"outline",className:"h-9 gap-2",children:[e.jsx(jt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:o}),e.jsxs("span",{className:"text-xs text-muted-foreground hidden sm:inline",children:["· ",c]})]})}),e.jsxs(Nt,{align:"end",className:"w-72 p-3 space-y-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:ls.map(d=>e.jsx("button",{type:"button",onClick:()=>{t(tt(d)),n(!1)},className:B("h-8 rounded-md text-xs font-medium border transition-colors",r===d.key?"bg-primary text-primary-foreground border-primary":"hover:bg-muted"),children:d.label},d.key))}),e.jsxs("div",{className:"border-t pt-2 space-y-2",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Custom range"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(Ke,{className:"text-[10px] text-muted-foreground",children:"From"}
1),e.jsx(Q,{type:"date",value:s.start,onChange:d=>t({...s,start:d.target.value}),className:"h-8"})]}),e.jsxs("div",{children:[e.jsx(Ke,{className:"text-[10px] text-muted-foreground",children:"To"}),e.jsx(Q,{type:"date",value:s.end,onChange:d=>t({...s,end:d.target.value}),className:"h-8"})]})]})]})]})]})}function at({status:s,className:t}){return e.jsxs(O,{variant:"outline",className:B(Gt(s),"text-[11px]",t),children:[e.jsx("span",{className:B("h-1.5 w-1.5 rounded-full mr-1",s==="green"?"bg-emerald-500":s==="yellow"?"bg-amber-500":"bg-rose-500")}),Yt(s)]})}const an={green:"Healthy",yellow:"Watch",red:"At risk"},nn={green:"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 border-emerald-500/30",yellow:"bg-amber-500/15 text-amber-700 dark:text-amber-400 border-amber-500/30",red:"bg-rose-500/15 text-rose-700 dark:text-rose-400 border-rose-500/30"},rn={responsiveness:{label:"Reply speed",icon:Is,hint:"Calls, replies, meetings attended vs missed"},pipeline_hygiene:{label:"Deals moving",icon:va,hint:"Deals advancing vs stalling"},followup_discipline:{label:"Follow-ups on time",icon:bt,hint:"Tasks & follow-ups completed vs overdue"},engagement_volume:{label:"Customer activity",icon:Ve,hint:"Notes, contacts, leads, campaigns activity"}};function Oe({pkey:s,pillar:t}){const a=rn[s]??{label:s,icon:$e,hint:""},n=a.icon,r=Math.round(t.score/t.max*100),o=r>=75?"text-emerald-600":r>=50?"text-amber-600":"text-rose-600";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(n,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm font-medium truncate",children:a.label})]}),e.jsxs("span",{className:B("text-xs font-semibold tabular-nums",o),children:[t.score.toFixed(1)," / ",t.max]})]}),e.jsx(ke,{value:r,className:"h-1.5"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.hint,typeof t.positive=="number"&&e.jsxs("span",{className:"ml-1",children:["· ",e.jsxs("span",{className:"text-emerald-600",children:["+",t.positive]})," ",e.jsxs("span",{className:"text-rose-600",children:["-",t.negative??0]})]}),typeof t.volume=="number"&&e.jsxs("span",{className:"ml-1",children:["· ",t.volume," events"]})]})]})}function ln(){const[s,t]=f.useState(30),{data:a,isLoading:n}=He(s);if(n)return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsx(te,{className:"h-5 w-40"}),e.jsx(te,{className:"h-16 w-full"}),e.jsx(te,{className:"h-24 w-full"})]})});if(!a)return e.jsx(b,{children:e.jsxs(_,{className:"p-4 flex items-start gap-2",children:[e.jsx(ue,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"No score yet. Activate the Event Engine in Performance Rules so work starts being counted."})]})});const r=a.status==="green"?Pe:a.status==="yellow"?$e:ue;return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(rs,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold leading-tight",children:"Business condition score"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["One score, from ",a.window_days," days of recorded work"]})]})]}),e.jsxs(ve,{value:String(s),onValueChange:o=>t(Number(o)),children:[e.jsx(fe,{className:"h-7 w-[110px] text-xs",children:e.jsx(je,{})}),e.jsxs(Ne,{children:[e.jsx(G,{value:"7",children:"Last 7 days"}),e.jsx(G,{value:"14",children:"Last 14 days"}),e.jsx(G,{value:"30",children:"Last 30 days"}),e.jsx(G,{value:"90",children:"Last 90 days"})]})]})]}),e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsx("div",{className:"text-4xl font-bold tabular-nums leading-none",children:a.score}),e.jsx("div",{className:"text-sm text-muted-foreground mb-1",children:"/ 100"}),e.jsxs(O,{variant:"outline",className:B("ml-auto border",nn[a.status]),children:[e.jsx(r,{className:"h-3 w-3 mr-1"}),an[a.status]]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(Oe,{pkey:"responsiveness",pillar:a.pillars.responsiveness}),e.jsx(Oe,{pkey:"pipeline_hygiene",pillar:a.pillars.pipeline_hygiene}),e.jsx(Oe,{pkey:"followup_discipline",pillar:a.pillars.followup_discipline}),e.jsx(Oe,{pkey:"engagement_volume",pillar:a.pillars.engagement_volume})]})]})})}function on(s){return s>=100?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30":s>=60?"bg-amber-500/15 text-amber-700 dark:text-amber-300 border-amber-500/30":"bg-rose-500/15 text-rose-700 dark:text-rose-300 border-rose-500/30"}
1function ks(s,t){return t==="currency"?w(s):s.toLocaleString()}function nt({title:s,subtitle:t,rows:a,overall:n,emptyHint:r,icon:o="flag"}){const c=o==="target"?pe:Vs;return a.length===0?e.jsx(b,{children:e.jsxs(_,{className:"p-4",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(c,{className:"h-4 w-4 text-primary"})," ",s]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:r??"No targets set for this period. Set targets to grade against a real number."})]})}):e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(c,{className:"h-4 w-4 text-primary"})," ",s]}),t&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:t})]}),e.jsxs(O,{variant:"outline",className:B("tabular-nums",on(n)),children:[n,"% attained"]})]}),e.jsx("ul",{className:"space-y-2.5",children:a.map(l=>e.jsxs("li",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium",children:l.label}),e.jsxs("span",{className:"tabular-nums text-muted-foreground",children:[ks(l.actual,l.format)," / ",ks(l.target,l.format),e.jsxs("span",{className:B("ml-2 font-semibold",l.pct>=100?"text-emerald-600":l.pct>=60?"text-amber-600":"text-rose-600"),children:[l.pct,"%"]})]})]}),e.jsx(ke,{value:Math.min(l.pct,100),className:"h-1.5"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Feeds ",l.pillar," pillar of the score"]})]},l.key))})]})})}function cn(s){const t=Number(s??0);return t>=75?{label:"Doing well",meaning:"Ahead of where you need to be",tone:"good"}:t>=50?{label:"On track",meaning:"Moving in the right direction",tone:"ok"}:{label:"Needs attention",meaning:"Something is being missed",tone:"bad"}}const dn={good:"bg-success/15 text-success border-success/30",ok:"bg-warning/15 text-warning border-warning/30",bad:"bg-destructive/15 text-destructive border-destructive/30"};function mn({score:s,className:t}){return e.jsx(O,{variant:"outline",className:B("font-medium",dn[s.tone],t),children:s.label})}const un={responsiveness:{good:"You are replying to customers quickly",bad:"Customers are waiting too long for a reply",action:"Clear your inbox",to:"/inbox"},pipeline_hygiene:{good:"Deals are moving forward",bad:"Deals are sitting still",action:"Review stuck deals",to:"/pipeline"},followup_discipline:{good:"Follow-ups are being done on time",bad:"Follow-ups are being missed",action:"Do today's follow-ups",to:"/customer-care"},engagement_volume:{good:"You are staying in touch with customers",bad:"Contact with customers has gone quiet",action:"Reach out to quiet customers",to:"/customer-care"}};function xn({evidence:s}){const{data:t,isLoading:a}=He(30);if(a)return e.jsx(te,{className:"h-40 w-full"});if(!t||s&&!s.sufficient)return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"How the business is doing"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Not enough activity yet"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(s==null?void 0:s.coverageLine)??"Nothing has been recorded for this period yet."," ","Log calls, complete tasks and move deals for a few days and this will fill in - we would rather say nothing than show you a score built on no work."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsx(y,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs(I,{to:"/pipeline",children:["Open pipeline ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})}),e.jsx(y,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs(I,{to:"/tasks",children:["Open tasks ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})})]})]})});const n=cn(t.score),r=Object.entries(t.pillars||{}).map(([l,d])=>({key:l,pct:d.max?Math.round(d.score/d.max*100):0,words:un[l]})).filter(l=>l.words),o=r.filter(l=>l.pct>=70),c=r.filter(l=>l.pct<70).sort((l,d)=>l.pct-d.pct);return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"How the business is doing"}),e.jsx("h2",{className:"text-lg font-semibold",children:n.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.meaning}),s&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:s.coverageLine})]}),e.jsx(mn,{score:n})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Going well"}),o.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing standing out yet."}
1):o.map(l=>e.jsxs("p",{className:"text-sm flex items-start gap-2",children:[e.jsx(Pe,{className:"h-4 w-4 text-success mt-0.5 shrink-0"}),l.words.good]},l.key))]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Needs attention"}),c.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing is being missed right now."}):c.map(l=>e.jsxs("p",{className:"text-sm flex items-start gap-2",children:[e.jsx(ue,{className:"h-4 w-4 text-warning mt-0.5 shrink-0"}),l.words.bad]},l.key))]})]}),c.length>0&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:"What to do today"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.slice(0,2).map(l=>e.jsx(y,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs(I,{to:l.words.to,children:[l.words.action," ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})},l.key))})]})]})})}function hn({data:s}){const t=Number((s==null?void 0:s.total_revenue)??0),a=Number((s==null?void 0:s.deals_closed)??0),n=[{label:"leads converted",value:Number((s==null?void 0:s.leads_converted)??0)},{label:"tasks completed",value:Number((s==null?void 0:s.tasks_completed)??0)},{label:"calls logged",value:Number((s==null?void 0:s.calls_logged)??0)}].filter(o=>o.value>0),r=t<=0&&a<=0&&n.length===0;return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Activity this period"}),r?e.jsx("p",{className:"text-sm font-medium",children:"Not enough activity this period"}):t>0||a>0?e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-6 gap-y-1",children:[t>0&&e.jsxs("span",{className:"text-lg font-semibold tabular-nums",children:[w(t),e.jsx("span",{className:"ml-1.5 text-xs font-normal text-muted-foreground",children:"closed"})]}),a>0&&e.jsxs("span",{className:"text-lg font-semibold tabular-nums",children:[a,e.jsx("span",{className:"ml-1.5 text-xs font-normal text-muted-foreground",children:a===1?"deal won":"deals won"})]})]}):e.jsx("p",{className:"text-sm",children:"No revenue or deals recorded yet."}),n.length>0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n.map((o,c)=>e.jsxs("span",{children:[c>0&&", ",e.jsx("span",{className:"text-foreground tabular-nums",children:o.value})," ",o.label]},o.label))})]})})}function os({title:s,hint:t}){return e.jsxs("div",{className:"rounded-md border border-dashed bg-muted/20 px-3 py-2.5",children:[e.jsx("p",{className:"text-sm font-medium",children:s}),t&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t})]})}const pn=5,gn=10,me=s=>{const t=Number(s??0);return Number.isFinite(t)?t:0};function _e(s,t,a){return`${s} ${s===1?t:a}`}function vn(s){const t=s.overview??{},a=me(t.deals_closed),n=me(t.tasks_completed),r=me(t.calls_logged),o=me(t.leads_converted);me(t.total_revenue);const c=Math.max(0,me(s.teamCount)),l=me(s.windowDays)||30,d=Object.values(s.eventCounts??{}).reduce((j,C)=>j+me(C),0),x=a+n+r+o,m=x>=pn||d>=gn,h=[];a&&h.push(_e(a,"deal","deals")),n&&h.push(_e(n,"task","tasks")),r&&h.push(_e(r,"call","calls")),o&&h.push(_e(o,"converted lead","converted leads")),!h.length&&d&&h.push(_e(d,"recorded event","recorded events"));const u=h.length>0;u&&c&&h.push(_e(c,"person","people"));const k=u?`Based on ${h.join(", ")} in the last ${l} days.`:`No revenue, deals or tasks recorded in the last ${l} days.`;return{sufficient:m,coverageLine:k,workItems:x,eventTotal:d}}function fn({facts:s}){const{revenue:t,deals:a,team:n,daysLeft:r}=s,o=r>0?`${r} ${r===1?"day":"days"} left`:"Last day of the month";return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(Ae,{className:"h-3.5 w-3.5 text-primary"})," Revenue"]}),t.hasTarget?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xl font-semibold tabular-nums",children:[w(t.actual),e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:[" / ",w(t.target)]})]}),e.jsx(ke,{value:Math.min(100,t.pct),className:"h-1.5"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.pct,"% of target · ",o]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xl font-semibold tabular-nums",children:w(t.actual)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No target set"}),e.jsx(y,{asChild:!0,size:"sm",variant:"outline",className:"mt-1",children:e.jsxs(I,{to:"/performance?tab=goals",children:["Set target ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})})]})]})}),e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(yt,{className:"h-3.5 w-3.5 text-primary"})," Deals"]}
1),a.hasTarget?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xl font-semibold tabular-nums",children:[a.actual,e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:` / ${a.target}`})]}),e.jsx(ke,{value:Math.min(100,a.pct??0),className:"h-1.5"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.pct,"% of target"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xl font-semibold tabular-nums",children:a.actual}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No target set"}),e.jsx(y,{asChild:!0,size:"sm",variant:"outline",className:"mt-1",children:e.jsxs(I,{to:"/performance?tab=goals",children:["Set target ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})})]})]})}),e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(wt,{className:"h-3.5 w-3.5 text-primary"})," Team"]}),e.jsx("p",{className:"text-xl font-semibold",children:n.headline}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.detail}),n.needsAttention>0&&e.jsx(y,{asChild:!0,size:"sm",variant:"outline",className:"mt-1",children:e.jsxs(I,{to:"/performance?tab=team",children:["See who needs help ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})})]})})]})}function jn({recommendation:s}){const[t,a]=f.useState(!1);return s!=null&&s.basis?e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"What should we do?"}),e.jsx("h2",{className:"text-base font-semibold",children:s.headline}),s.detail&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.detail}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx(y,{asChild:!0,size:"sm",children:e.jsxs(I,{to:s.to,children:[s.actionLabel," ",e.jsx(re,{className:"h-3.5 w-3.5 ml-1"})]})}),e.jsx(y,{type:"button",size:"sm",variant:"ghost",className:"h-8 px-2 text-xs text-muted-foreground",onClick:()=>a(n=>!n),children:t?"Hide why":"Why this?"})]}),t&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-xs text-muted-foreground space-y-1",children:[e.jsx("p",{className:"text-foreground",children:s.basis.because}),e.jsxs("p",{children:["Measured from: ",s.basis.source]})]})]})}):null}function Nn({item:s}){const[t,a]=f.useState(!1),n=s.moreActions??[];return e.jsxs("li",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 items-start gap-2 text-left",onClick:()=>n.length>0&&a(r=>!r),children:[e.jsx(ue,{className:`h-4 w-4 mt-0.5 shrink-0 ${s.severity==="high"?"text-destructive":"text-warning"}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.evidence})]})]}),e.jsx(y,{asChild:!0,size:"sm",variant:"outline",className:"shrink-0",children:e.jsx(I,{to:s.to,children:s.actionLabel})})]}),t&&n.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-2 pl-6",children:n.map(r=>e.jsx(y,{asChild:!0,size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",children:e.jsx(I,{to:r.to,children:r.label})},r.to))})]})}function bn({items:s,limit:t=5}){return s.length?e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"Needs attention"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.length," ",s.length===1?"thing":"things"," to deal with."]})]}),e.jsx("ul",{className:"divide-y",children:s.slice(0,t).map(a=>e.jsx(Nn,{item:a},a.key))})]})}):null}function rt(s){const t=X(),a=oe({queryKey:["team-roster",t,s.start,s.end],enabled:!!t,staleTime:6e4,queryFn:async()=>{const{data:n,error:r}=await U.rpc("get_team_performance",{_period_start:s.start,_period_end:s.end});if(r)throw r;return(n??[]).map(o=>({userId:o.user_id,name:o.full_name||"Unnamed",role:o.role??null,managerName:o.manager_name??null,revenue:Number(o.revenue??0),dealsClosed:Number(o.deals_closed??0),tasksCompleted:Number(o.tasks_completed??0),tasksDue:Number(o.tasks_due??0),callsLogged:Number(o.calls_logged??0),leadsConverted:Number(o.leads_converted??0),conversionRate:Number(o.conversion_rate??0),score:Number(o.kpi_score??0),revenueTarget:Number(o.revenue_target??0),dealsTarget:Number(o.deals_target??0),isRevenueEligible:o.is_revenue_eligible===void 0?!0:!!o.is_revenue_eligible}))}});return{rows:a.data??[],isLoading:a.isLoading,isError:a.isError,refetch:()=>void a.refetch()}}function yn(s,t,a){const n=t.trim().toLowerCase(),r=(a||"").trim().toLowerCase();return s.filter(o=>{const c=!n||o.name.toLowerCase().includes(n),l=!r||(o.role||"").toLowerCase().includes(r);return c&&l})}const Cs=70,Ss=40;
1function wn(s){const t={support_rep:"Support",viewer:"Viewer",partner:"Partner",staff:"Staff",sales_rep:"Sales",manager:"Manager",team_manager:"Team manager",admin:"Admin",owner:"Owner"},a=(s||"").toLowerCase();return t[a]||(s?s.replace(/_/g," "):"This role")}function ys(s){const t=Number(s.revenueTarget??0),a=Number(s.dealsTarget??0),n=Number(s.stalledDeals??0),r=Number(s.stalledDays??0),o=n>0?`${n} ${n===1?"deal has":"deals have"} not moved${r>0?` in ${r} days`:""}.`:void 0;if(s.isRevenueEligible===!1)return{state:"not_enough_data",label:"No sales goal",evidence:`${wn(s.role)} - no sales goal assigned.`};const c=(l,d)=>({state:l<Ss?"at_risk":"needs_attention",label:l<Ss?"At risk":"Needs attention",behindPct:Math.max(0,100-l),evidence:o??d});if(t>0){const l=Math.round(Number(s.revenue??0)/t*100);return l<Cs?c(l,`${l}% of their revenue target so far.`):{state:"on_track",label:"On track"}}if(a>0){const l=Math.round(Number(s.dealsClosed??0)/a*100);return l<Cs?c(l,`${s.dealsClosed} of ${a} deals so far.`):{state:"on_track",label:"On track"}}return{state:"not_enough_data",label:"No goal yet",evidence:o??"No target assigned yet."}}function _n(s){if(!s.length)return{onTrack:0,needsAttention:0,notEnoughData:0,headline:"No people yet",detail:"Invite your team to see this."};let t=0,a=0,n=0;return s.forEach(r=>{const o=ys(r).state;o==="on_track"?t++:o==="needs_attention"||o==="at_risk"?a++:n++}),{onTrack:t,needsAttention:a,notEnoughData:n,headline:`${t} on track`,detail:a>0?`${a} need attention`:n===s.length?"No goals set yet":"Everyone is on track"}}function kn(s){const t=[],a=r=>{!r.title||!r.evidence||!r.actionLabel||!r.to||t.push(r)};s.people.forEach(r=>{const o=ys(r);o.state!=="needs_attention"&&o.state!=="at_risk"||o.evidence&&a({key:`person:${r.userId}`,title:o.behindPct!==void 0?`${r.name} is ${o.behindPct}% behind target`:`${r.name} needs support`,evidence:o.evidence,actionLabel:`View ${r.name.split(" ")[0]}`,to:`/performance?tab=team&user=${r.userId}`,severity:(o.behindPct??0)>=40?"high":"normal",moreActions:[{label:"Review their deals",to:`/pipeline?owner=${r.userId}`},{label:"Set their target",to:"/performance?tab=goals"}]})});const n=s.stuckThresholdDays??14;return s.stuckDeals>0&&a({key:"stuck-deals",title:`${s.stuckDeals} ${s.stuckDeals===1?"deal has":"deals have"} been stuck for ${n}+ days`,evidence:s.stuckDealsValue&&s.stuckDealsValue>0?`${s.formatMoney(s.stuckDealsValue)} of revenue is not moving.`:"Revenue you are counting on is not moving.",actionLabel:`Review ${s.stuckDeals} stuck ${s.stuckDeals===1?"deal":"deals"}`,to:"/pipeline?view=attention",severity:"high"}),s.overdueFollowups>0&&a({key:"overdue-followups",title:`${s.overdueFollowups} customer ${s.overdueFollowups===1?"follow-up is":"follow-ups are"} overdue`,evidence:"Customers waiting on a reply are the ones most likely to go quiet.",actionLabel:"Do follow-ups",to:"/customer-care",severity:"normal",moreActions:[{label:"See all customers",to:"/contacts"}]}),(s.overdueTasks??0)>0&&a({key:"overdue-tasks",title:`${s.overdueTasks} ${s.overdueTasks===1?"task is":"tasks are"} overdue`,evidence:"Work that was promised to a customer has not been done yet.",actionLabel:"Clear overdue tasks",to:"/tasks",severity:"normal"}),t.sort((r,o)=>r.severity===o.severity?0:r.severity==="high"?-1:1)}function Cn(s){const t=s.formatMoney,a=s.revenueTarget-s.revenueActual,n=s.expectedToDate??null;if(s.revenueTarget>0&&n!==null&&n>s.revenueActual){const r=n-s.revenueActual,o=s.stuckDealsValue??0,c=s.stuckThresholdDays??14,l=o>0?`${t(o)} of your pipeline has not moved in ${c} days.`:(s.openPipeline??0)>0?`You have ${t(s.openPipeline)} open in the pipeline to work with.`:"There is not enough open pipeline to close the gap.";return{headline:"You are behind pace this month",detail:`You should have reached about ${t(n)} by today. You are at ${t(s.revenueActual)}, ${t(r)} behind. ${l}`,actionLabel:s.stuckDeals>0?`Review ${s.stuckDeals} stuck ${s.stuckDeals===1?"deal":"deals"}`:"Open pipeline",to:s.stuckDeals>0?"/pipeline?view=attention":"/pipeline",basis:{signal:"behind_pace",because:`${t(s.revenueActual)} won against ${t(n)} expected by today on a ${t(s.revenueTarget)} target.`,source:"Recognised CRM Revenue this period against an even pace to the team revenue target"}}}if(s.revenueTarget>0&&a>0){const r=[`You need ${t(a)} more this month.`];(s.openPipeline??0)>0&&(r.push(`You have ${t(s.openPipeline)} open`),(s.stuckDealsValue??0)>0?r.push(`but ${t(s.stuckDealsValue)} has not moved in ${s.stuckThresholdDays??14} days.`):r.push("in the pipeline."));const o=r.join(" ").replace(" but",", but").replace(" in the pipeline."," in the pipeline.");return s.stuckDeals>0?{headline:"You are behind this month's revenue target",detail:o,actionLabel:`Review ${s.stuckDeals} stuck ${s.stuckDeals===1?"deal":"deals"}`,to:"/pipeline?view=attention",basis:{signal:"revenue_gap",because:`${t(s.revenueActual)} won against a ${t(s.revenueTarget)} target, and ${s.stuckDeals} open ${s.stuckDeals===1?"deal has":"deals have"} not moved.`,source:"Recognised CRM Revenue this period vs the team revenue target"}}:{headline:"You are behind this month's revenue target",detail:o,actionLabel:"Open pipeline",to:"/pipeline",basis:{signal:"revenue_gap",because:`${t(s.revenueActual)} won against a ${t(s.revenueTarget)} target.`,source:"Recognised CRM Revenue this period vs the team revenue target"}}}return s.stuckDeals>0?{headline:`${s.stuckDeals} ${s.stuckDeals===1?"deal is":"deals are"}
1 holding up revenue`,detail:(s.stuckDealsValue??0)>0?`${t(s.stuckDealsValue)} has not moved in ${s.stuckThresholdDays??14} days.`:void 0,actionLabel:`Review ${s.stuckDeals} stuck ${s.stuckDeals===1?"deal":"deals"}`,to:"/pipeline?view=attention",basis:{signal:"stuck_deals",because:`${s.stuckDeals} open ${s.stuckDeals===1?"deal has":"deals have"} not moved in ${s.stuckThresholdDays??14} days.`,source:"Open deals with no stage change past the stuck threshold"}}:s.overdueFollowups>0?{headline:"Customers are waiting on you",detail:`${s.overdueFollowups} follow-${s.overdueFollowups===1?"up is":"ups are"} overdue.`,actionLabel:"Do follow-ups",to:"/customer-care",basis:{signal:"overdue_followups",because:`${s.overdueFollowups} follow-${s.overdueFollowups===1?"up is":"ups are"} past its due date.`,source:"Customer Care follow-up queue"}}:s.revenueTarget>0&&s.revenueActual>=s.revenueTarget?{headline:"You have hit this month's target",detail:`${t(s.revenueActual)} closed against a ${t(s.revenueTarget)} target.`,actionLabel:"Set next month's target",to:"/performance?tab=goals",basis:{signal:"target_met",because:`${t(s.revenueActual)} won against a ${t(s.revenueTarget)} target.`,source:"Recognised CRM Revenue this period vs the team revenue target"}}:s.revenueTarget<=0?{headline:"No revenue target set for this month",detail:"Set one and Performance can tell you whether you are winning.",actionLabel:"Set target",to:"/performance?tab=goals",basis:{signal:"no_target",because:"No team revenue target exists for this period.",source:"Team targets for this period"}}:null}const Sn=864e5,Ze=fa;function Tn(){const s=X();return oe({queryKey:["performance-open-deals",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:a}=await U.from("deals").select("id, value, updated_at, owner_id, assigned_rep_id").eq("org_id",s).eq("is_archived",!1).not("stage","in",'("closed_won","closed_lost")').limit(1e3);if(a)throw a;return t??[]}})}function Dn(){const s=X(),t=le(Me(new Date),"yyyy-MM-dd"),a=le(ge(new Date),"yyyy-MM-dd");return oe({queryKey:["performance-user-targets",s,t],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:n,error:r}=await U.from("deal_targets").select("user_id, target_type, target_value").eq("org_id",s).not("user_id","is",null).lte("period_start",a).gte("period_end",t);if(r)throw r;return n??[]}})}function Ge(s){const{rows:t,isLoading:a}=rt(s),{data:n,isLoading:r}=Ye(),{data:o}=ka(30),{data:c}=Ca(),{data:l=[],isLoading:d}=Tn(),{data:x=[]}=Dn();return f.useMemo(()=>{const m=Date.now(),h=l.filter(g=>g.updated_at&&m-new Date(g.updated_at).getTime()>Ze*Sn),u=new Map;h.forEach(g=>{const S=g.owner_id||g.assigned_rep_id;S&&u.set(S,(u.get(S)??0)+1)});const k=(g,...S)=>{var L;for(const P of S){const R=Number(((L=x.find(v=>v.user_id===g&&v.target_type===P))==null?void 0:L.target_value)??0);if(R>0)return R}return null},j=t.map(g=>({userId:g.userId,name:g.name,role:g.role,isRevenueEligible:g.isRevenueEligible,revenue:g.revenue,dealsClosed:g.dealsClosed,revenueTarget:g.revenueTarget>0?g.revenueTarget:k(g.userId,wa.personRevenue),dealsTarget:g.dealsTarget>0?g.dealsTarget:k(g.userId,...ya),score:g.score,stalledDeals:u.get(g.userId)??0,stalledDays:Ze})),C=((n==null?void 0:n.rows)??[]).find(g=>g.key==="revenue"),$=((n==null?void 0:n.rows)??[]).find(g=>g.key==="deals"),E=Number((C==null?void 0:C.target)??0),W=Number((C==null?void 0:C.actual)??0),T=new Date,A={people:j,stuckDeals:h.length,stuckDealsValue:h.reduce((g,S)=>g+Number(S.value??0),0),stuckThresholdDays:Ze,overdueFollowups:Number((o==null?void 0:o.open_overdue)??0),overdueTasks:Number((c==null?void 0:c.tasksOverdue)??0),revenueTarget:E,revenueActual:W,openPipeline:l.reduce((g,S)=>g+Number(S.value??0),0),daysLeft:Math.max(0,De(ge(T),T)),expectedToDate:(()=>{const g=De(ge(T),Me(T))+1,S=De(T,Me(T))+1;return E>0&&g>0?Math.round(E*S/g):null})(),formatMoney:g=>w(g)};return{facts:A,people:j,attention:kn(A),recommendation:Cn(A),team:_n(j),revenue:{target:E,actual:W,pct:E>0?Math.round(W/E*100):0,hasTarget:E>0},deals:(()=>{const g=Number(($==null?void 0:$.target)??0),S=Number(($==null?void 0:$.actual)??0);return{target:g,actual:S,pct:g>0?Math.round(S/g*100):null,hasTarget:g>0}})(),daysLeft:A.daysLeft??0,isLoading:a||r||d}},[t,n,o,c,l,x,a,r,d])}const Mn=[{key:"customers_engaged",label:"Customers engaged",source:"customersEngaged"},{key:"opportunities_progressed",label:"Opportunities progressed",source:"dealsMoved"},{key:"deals_won",label:"Deals won",source:"dealsWon"},{key:"customers_retained",label:"Customers retained",source:null}
1,{key:"revenue",label:"Revenue",source:"revenueWon",money:!0}];function Pn(s,t=5){return Mn.filter(a=>a.source&&typeof s[a.source]=="number").slice(0,t).map(a=>({key:a.key,label:a.label,value:Number(s[a.source]??0),money:!!a.money}))}const xe=s=>Number(s??0),he=(s,t,a)=>`${s} ${s===1?t:a}`;function $n(s){const t=xe(s.proposalsSent),a=xe(s.dealsWon),n=xe(s.customersEngaged),r=xe(s.dealsMoved),o=xe(s.stuckDeals),c=xe(s.overdueFollowups),l=xe(s.peopleNeedingAttention),d={label:"See what needs attention",href:"?tab=team&focus=attention"},x={label:"View team performance",href:"?tab=team"},m=[];n&&m.push(`${he(n,"customer was","customers were")} engaged`),r&&m.push(`${he(r,"opportunity","opportunities")} moved forward`),t&&m.push(`${he(t,"proposal was","proposals were")} sent`),m.push(a?`${he(a,"deal was","deals were")} won`:"no deals were won");const h=`${m.join(", ").replace(/^./,k=>k.toUpperCase())} in this period.`;if(!n&&!r&&!t&&!a)return{evidence:"No customer activity, opportunities or wins were recorded in this period.",interpretation:"We do not have enough activity data yet to explain the result. Customer conversations, follow-ups and deals are what create it.",primary:x};let u;return c>0?u=`${he(c,"follow-up is","follow-ups are")} overdue, so customer work is waiting before new proposals will pay off.`:o>0?u=`${he(o,"opportunity has","opportunities have")} not moved recently - reviving them is the fastest route to a win.`:t>0&&a===0?u="Proposals went out but nothing closed yet, so the next step is following those customers up rather than sending more.":l>0?u=`${he(l,"person is","people are")} behind their own targets, which is where the result is being decided.`:a>0?u="Work is converting into wins, so keeping engagement at this level should hold the result.":u="We do not have enough activity data yet to explain the change.",{evidence:h,interpretation:u,primary:c>0||o>0||l>0||a===0?d:x,secondary:c>0||o>0||l>0||a===0?x:d}}function An({range:s}){var z,ie;const{data:t,isLoading:a}=Ut(s),{data:n=[]}=fs(s),{data:r}=Qt(s),{data:o}=cs(),{data:c}=Ws(o==null?void 0:o.id,s),{data:l=[]}=js(s),d=Ge(s),{isAdmin:x,role:m}=ds(),h=x,[,u]=Be(),k=()=>u(i=>{const p=new URLSearchParams(i);return p.set("tab","goals"),p},{replace:!0}),j=f.useMemo(()=>l.filter(i=>i.role===m||i.role==="*"),[l,m]),C=f.useMemo(()=>(r==null?void 0:r.insights)||[],[r]),$=f.useMemo(()=>({from:new Date(`${s.start}T00:00:00`).toISOString(),to:new Date(`${s.end}T23:59:59`).toISOString(),label:"Selected period"}),[s.start,s.end]),{rows:E=[]}=Hs({period:$}),W=f.useMemo(()=>E.reduce((i,p)=>({customersEngaged:i.customersEngaged+p.customersContacted,dealsMoved:i.dealsMoved+p.dealsMoved,proposalsSent:i.proposalsSent+p.proposalsSent,dealsWon:i.dealsWon+p.dealsWon,revenueWon:i.revenueWon+p.revenueWon}),{customersEngaged:0,dealsMoved:0,proposalsSent:0,dealsWon:0,revenueWon:0}),[E]),T=f.useMemo(()=>Pn(W),[W]),A=f.useMemo(()=>{var i;return $n({...W,stuckDeals:d.facts.stuckDeals,overdueFollowups:d.facts.overdueFollowups,peopleNeedingAttention:(i=d.team)==null?void 0:i.needsAttention})},[W,d.facts.stuckDeals,d.facts.overdueFollowups,(z=d.team)==null?void 0:z.needsAttention]),{data:g}=Ye(),S=f.useMemo(()=>{const i=((g==null?void 0:g.rows)??[]).find(F=>F.key==="revenue"),p=new Date;return ba({target:Number((i==null?void 0:i.target)??0),achieved:Number((i==null?void 0:i.actual)??(t==null?void 0:t.total_revenue)??0),daysLeft:Math.max(0,De(ge(p),p)),formatMoney:F=>w(F)})},[g,t]),L=f.useMemo(()=>n.slice(0,5),[n]),P=f.useMemo(()=>{if(!n.length)return{avg:0,green:0,yellow:0,red:0};const i=n.reduce((p,F)=>p+Number(F.kpi_score||0),0);return{avg:Math.round(i/n.length*10)/10,green:n.filter(p=>p.status_color==="green").length,yellow:n.filter(p=>p.status_color==="yellow").length,red:n.filter(p=>p.status_color==="red").length}},[n]),{data:R}=He(30),v=f.useMemo(()=>vn({eventCounts:R==null?void 0:R.event_counts,overview:t,teamCount:n.length,windowDays:(R==null?void 0:R.window_days)??30}),[R,t,n.length]);return a?e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{className:"h-24 w-full"}),e.jsx(te,{className:"h-64 w-full"})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm font-medium",children:"Is the team turning customer activity into business growth?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The health of the business for the selected period."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{size:"sm",asChild:!0,children:e.jsx(I,{to:"?tab=team&focus=attention",children:"See what needs attention"})}),e.jsx(y,{size:"sm",variant:"outline",asChild:!0,children:e.jsx(I,{to:"?tab=team",children:"View team performance"})})]})]}),T.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(i=>e.jsxs("div",{className:"flex-1 min-w-[130px] rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-tight",children:i.label}),e.jsx("p",{className:"mt-1 text-xl font-semibold tabular-nums",children:i.money?w(i.value):i.value})]},i.key))}),e.jsx("h3",{className:"text-xs font-medium text-muted-foreground",children:"Are we on target this month?"}),e.jsx(fn,{facts:d})]}),e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsx("p",{className:"text-sm",children:A.evidence}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.interpretation}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx(y,{size:"sm",asChild:!0,children:e.jsx(I,{to:A.primary.href,children:A.primary.label})}),A.secondary&&e.jsx(y,{size:"sm",variant:"outline",asChild:!0,children:e.jsx(I,{to:A.secondary.href,children:A.secondary.label})})]})]})}),e.jsx(bn,{items:d.attention}),e.jsx(jn,{recommendation:d.recommendation}),e.jsx(Na,{module:"performance",summary:"Whether the month is on course",...S}),e.jsxs(bs,{module:"performance",label:"Performance analytics",description:"Scores, trends and the full numbers behind this month.",children:[e.jsx(xn,{evidence:v}),e.jsx(hn,{data:t}),e.jsx(ln,{}),e.jsx(Rn,{}),e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Vs,{className:"h-4 w-4 text-primary"})," My targets this period"]}),h&&e.jsx(y,{size:"sm",variant:"outline",onClick:k,children:"Manage KPIs"})]}),j.length===0?e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:h?"No KPIs defined yet. Create them in the KPIs tab so every team member knows what to hit.":"No KPIs set for your role yet. Ask your admin to define KPIs in the KPIs tab."}):e.jsxs(Re,{children:[e.jsx(Ie,{children:e.jsxs(ae,{children:[e.jsx(D,{children:"KPI"}),e.jsx(D,{children:"Period"}),e.jsx(D,{className:"text-right",children:"Target"}),e.jsx(D,{className:"text-right",children:"Actual"}),e.jsx(D,{className:"text-right",children:"Completion %"}),e.jsx(D,{children:"Status"})]})}),e.jsx(Ee,{children:j.map((i,p)=>{const F=Number(i.achieved_pct||0),V=F>=100?"Achieved":F>=60?"On Track":"Behind",H=F>=100?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30":F>=60?"bg-amber-500/15 text-amber-700 dark:text-amber-300 border-amber-500/30":"bg-rose-500/15 text-rose-700 dark:text-rose-300 border-rose-500/30";return e.jsxs(ae,{children:[e.jsx(M,{children:Ks[i.metric_name]||i.metric_name}),e.jsx(M,{className:"text-xs",children:zs[i.period]}),e.jsx(M,{className:"text-right tabular-nums",children:i.metric_name==="revenue"?w(i.scaled_target):i.scaled_target}),e.jsx(M,{className:"text-right tabular-nums",children:i.metric_name==="revenue"?w(i.actual):i.actual}),e.jsxs(M,{className:"text-right tabular-nums",children:[F,"%"]}),e.jsx(M,{children:e.jsx(O,{variant:"outline",className:H,children:V})})]},p)})})]})]})}),e.jsx(b,{children:e.jsxs(_,{className:"p-4",children:[e.jsx("div",{className:"text-sm font-medium mb-3",children:"Revenue trend"}),(ie=c==null?void 0:c.trend)!=null&&ie.length?e.jsx("div",{className:"h-56",children:e.jsx(Ys,{children:e.jsxs(Da,{data:c.trend,children:[e.jsx(Gs,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Us,{dataKey:"week",fontSize:11}),e.jsx(Qs,{fontSize:11,tickFormatter:i=>`â¦${(i/1e3).toFixed(0)}k`}),e.jsx(Xs,{formatter:i=>w(Number(i))}),e.jsx(Ma,{type:"monotone",dataKey:"revenue",stroke:"hsl(var(--primary))",strokeWidth:2,dot:!1})]})})}):e.jsx(os,{title:"No revenue trend yet",hint:"Revenue will appear here after deals are won."})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(_t,{className:"h-4 w-4 text-primary"})," Top performers"]}),L.length===0?e.jsx(os,{title:"No top performers yet",hint:"People appear here once they close work."}):e.jsx("ul",{className:"space-y-2",children:L.map((i,p)=>e.jsxs("li",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums w-4",children:[p+1,"."]}
1),e.jsx("span",{className:"truncate",children:i.full_name})]}),e.jsxs("span",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-xs tabular-nums text-muted-foreground",children:w(i.revenue)}),e.jsx(at,{status:Ns(i.kpi_score)})]})]},i.user_id))})]})}),e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(pe,{className:"h-4 w-4 text-primary"})," KPI completion"]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-3xl font-semibold tabular-nums",children:[P.avg,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Average across ",n.length," ",n.length===1?"rep":"reps"]})]}),e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsxs("span",{className:"rounded-md border border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 px-2 py-1",children:[P.green," on track"]}),e.jsxs("span",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300 px-2 py-1",children:[P.yellow," at risk"]}),e.jsxs("span",{className:"rounded-md border border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300 px-2 py-1",children:[P.red," off"]})]})]})}),e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ve,{className:"h-4 w-4 text-primary"})," Performance alerts"]}),C.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No alerts. Everything looks healthy."}):e.jsx("ul",{className:"space-y-1",children:C.slice(0,5).map((i,p)=>e.jsxs("li",{className:"text-xs flex items-start gap-2",children:[i.tone==="warning"?e.jsx(ue,{className:"h-3.5 w-3.5 text-amber-500 mt-0.5 shrink-0"}):e.jsx(Pe,{className:"h-3.5 w-3.5 text-emerald-500 mt-0.5 shrink-0"}),e.jsx("span",{children:i.text})]},p))})]})})]})]})]})}function Rn(){const{data:s}=Ye();return s?e.jsx(nt,{title:"Company revenue goal",subtitle:"From Goals & KPIs - drives the Pipeline pillar of Org Health",rows:s.rows,overall:s.overall,emptyHint:"Set a Company Revenue Goal in Goals & KPIs to grade the org against a target."}):null}function In(s,t){const a=X();return oe({queryKey:["team-usage",a,s.start,s.end],enabled:!!a&&t,queryFn:async()=>{const{data:n,error:r}=await U.rpc("get_team_usage",{_period_start:s.start,_period_end:s.end});if(r){if(/insufficient_privileges|does not exist/i.test(r.message))return[];throw r}return n||[]}})}function En(s,t){if(t<=0||s===0)return{label:"Inactive",variant:"outline"};const a=s/t;return a>=.7?{label:"Highly active",variant:"default"}:a>=.3?{label:"Engaged",variant:"secondary"}:{label:"Light use",variant:"outline"}}function Ln({range:s}){const[t,a]=f.useState(""),{data:n=[],isLoading:r,error:o}=In(s,!0),c=f.useMemo(()=>{const x=new Date(s.start).getTime(),m=new Date(s.end).getTime();return Math.max(1,Math.round((m-x)/864e5)+1)},[s.start,s.end]),l=f.useMemo(()=>n.filter(x=>!t||(x.full_name||"").toLowerCase().includes(t.toLowerCase())),[n,t]),d=f.useMemo(()=>{const x=n.filter(u=>u.sessions>0).length,m=n.length-x,h=n.reduce((u,k)=>u+(k.total_minutes||0),0);return{active:x,inactive:m,minutes:h}},[n]);return e.jsxs(b,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-semibold",children:"Team CRM usage"}),e.jsxs(O,{variant:"outline",className:"text-[10px]",children:[c,"-day window"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(O,{variant:"secondary",className:"text-[11px]",children:[e.jsx(kt,{className:"h-3 w-3 mr-1"}),Math.round(d.minutes/60),"h tracked"]}),e.jsxs(O,{className:"text-[11px]",children:[d.active," active"]}),d.inactive>0&&e.jsxs(O,{variant:"outline",className:"text-[11px]",children:[d.inactive," inactive"]})]})]}),e.jsxs("div",{className:"relative max-w-xs",children:[e.jsx(Ct,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Q,{placeholder:"Search team...",value:t,onChange:x=>a(x.target.value),className:"pl-9 h-9"})]}),o?e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/20 p-3 text-xs flex gap-2",children:[e.jsx(St,{className:"h-4 w-4 text-amber-600 shrink-0 mt-0.5"}),e.jsxs("p",{children:["Could not load team usage. ",String(o.message||"")]})]}):r?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loadingâ¦"}):l.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No usage recorded for this period yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(Ie,{children:e.jsxs(ae,{children:[e.jsx(D,{children:"Member"}),e.jsx(D,{children:"Adoption"}),e.jsx(D,{className:"text-right",children:"Sessions"}),e.jsx(D,{className:"text-right",children:"Active days"}),e.jsxs(D,{className:"text-right",children:[e.jsx(Aa,{className:"h-3 w-3 inline mb-0.5"})," Pages"]}),e.jsxs(D,{className:"text-right",children:[e.jsx(Ia,{className:"h-3 w-3 inline mb-0.5"})," Clicks"]}),e.jsx(D,{className:"text-right",children:"Time"}),e.jsx(D,{children:"Last active"})]})}),e.jsx(Ee,{children:l.map(x=>{const m=En(x.active_days,c);return e.jsxs(ae,{children:[e.jsx(M,{children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:x.full_name||"Unnamed"}),x.role&&e.jsx("span",{className:"text-[11px] text-muted-foreground capitalize",children:x.role})]})}),e.jsx(M,{children:e.jsx(O,{variant:m.variant,children:m.label})}),e.jsx(M,{className:"text-right tabular-nums",children:x.sessions.toLocaleStr
1ing()}),e.jsxs(M,{className:"text-right tabular-nums",children:[x.active_days," / ",c]}),e.jsx(M,{className:"text-right tabular-nums",children:x.page_views.toLocaleString()}),e.jsx(M,{className:"text-right tabular-nums",children:x.clicks.toLocaleString()}),e.jsx(M,{className:"text-right tabular-nums",children:x.total_minutes<60?`${x.total_minutes}m`:`${Math.round(x.total_minutes/60)}h`}),e.jsx(M,{className:"text-xs text-muted-foreground",children:x.last_active_at?Es(new Date(x.last_active_at),{addSuffix:!0}):"Never"})]},x.user_id)})})]})})]})}function Fn({kpis:s,member:t,period:a,className:n}){return s.length?e.jsx("div",{className:B("grid grid-cols-2 gap-2 sm:grid-cols-3",n),children:s.map(r=>{const o=qs(r.source,t,a),c=r.money?w(r.actual):String(r.actual),l=r.target===null?null:r.money?w(r.target):String(r.target);return e.jsxs(I,{to:o.href,"aria-label":o.label,className:"group rounded-lg border bg-card p-3 transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-tight",children:r.label}),e.jsx(re,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 shrink-0"})]}),e.jsxs("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:[c,l&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:[" / ",l]})]})]},r.id)})}):null}const ze={sales:{focus:"Sales Growth",line:"Turning conversations into revenue"},account_management:{focus:"Customer Retention",line:"Keeping and growing customers"},support:{focus:"Customer Service",line:"Helping customers quickly and effectively"},manager:{focus:"Team Performance",line:"Keeping the team on target"},general:{focus:"Execution",line:"Keeping customer work moving"}},K=(s,t,a)=>({id:s,label:t,source:a}),On={sales:[K("conversations","Conversations","customerReplies"),K("opportunities_progressed","Opportunities progressed","dealsMoved"),K("proposals_sent","Proposals sent","proposalsSent"),K("deals_won","Deals won","dealsWon"),K("revenue","Revenue","revenueWon")],account_management:[K("customers_contacted","Customers contacted","customersContacted"),K("followups_completed","Follow-ups completed","followupsCompleted"),K("upsell_opportunities","Upsell opportunities",null),K("upsells_won","Upsells won",null),K("customers_reactivated","Customers reactivated",null)],support:[K("conversations_handled","Conversations handled","customerReplies"),K("response_time","Response time",null),K("resolutions","Resolutions",null),K("satisfaction","Satisfaction",null)],manager:[K("team_target_attainment","Team target attainment",null),K("pipeline_health","Pipeline health",null),K("conversion","Conversion",null),K("followup_coverage","Follow-up coverage","followupsCompleted"),K("forecast","Forecast",null)],general:[K("customers_contacted","Customers contacted","customersContacted"),K("followups_completed","Follow-ups completed","followupsCompleted"),K("opportunities_progressed","Opportunities progressed","dealsMoved")]},Se={on_track:"On track",needs_attention:"Needs attention",at_risk:"At risk",no_data:"No data"};function lt(s){const t=`${s.workProfile??""} ${s.department??""} ${s.jobTitle??""}`.toLowerCase();return/account manage|customer success|renewal|client manage|retention/.test(t)?"account_management":/support|service|help ?desk|care/.test(t)?"support":/head of|team lead|team manager|sales manager|manager\b|supervisor/.test(t)?"manager":/sales|business development|revenue|rep\b|account exec/.test(t)?"sales":"general"}function ot(s,t={},a=lt(s)){const r=On[a].filter(o=>o.source&&typeof s[o.source]=="number").map(o=>{var m;const c=o.source,l=Number(s[c]??0),d=Number(t[o.id]??0),x=d>0?d:null;return{id:o.id,label:o.label,source:c,actual:l,target:x,pct:x?Math.round(l/x*100):null,money:!!((m=Xt[c])!=null&&m.money)}});return!r.length&&a==="manager"?ot(s,t,"general"):r}function es(s){return s.length<=1?s[0]??"":`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}const Ts=s=>s.map(t=>t.label.toLowerCase());function Wn(s,t){const a=t.filter(m=>m.pct!==null);if(!a.length){if(!t.length)return{state:"no_data",label:Se.no_data,sentence:"There is nothing measurable for this role yet, so performance cannot be judged fairly."};const m=t.filter(u=>u.actual>0);if(!m.length)return{state:"no_data",label:Se.no_data,sentence:`No ${ze[s].focus.toLowerCase()} activity recorded in this period, and no target has been set yet.`};const h=es(m.slice(0,2).map(u=>`${u.label.toLowerCase()} ${u.actual}`));return{state:"no_data",label:Se.no_data,sentence:`${h}. No target has been set yet, so performance cannot be judged fairly.`}}const n=a.filter(m=>m.pct>=85),r=a.filter(m=>m.pct<70),o=a.filter(m=>m.pct<40);if(!r.length)return{state:"on_track",label:Se.on_track,sentence:`Every ${ze[s].focus.toLowerCase()} target is being met so far.`};const c=o.length>=Math.max(2,Math.ceil(a.length/2))?"at_risk":"needs_attention",l=[...r].sort((m,h)=>m.pct-h.pct),d=es(Ts(l.slice(0,3))),x=n.length?`${es(Ts(n.slice(0,2)))} ${n.length===1?"is":"are"} strong, but `:"";return{state:c,label:Se[c],sentence:`${x}${d} ${r.length===1?"is":"are"} below target.`}}function Kn(s,t={}){const a=lt(s),n=ot(s,t,a);return{role:a,focus:ze[a].focus,line:ze[a].line,kpis:n,verdict:Wn(a,n)}}const zn=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)||"?";function Te({label:s,value:t,href:a}){return e.jsxs(I,{to:a,className:"group flex-1 min-w-[130px] rounded-lg border bg-card p-3 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-tight",children:s}),e.jsx(re,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0"})]}),e.jsx("p",{className:"mt-1 text-xl font-semibold tabular-nums",children:t})]})}
1function qn({row:s,period:t,targets:a}){const{focus:n,line:r,kpis:o,verdict:c}=Kn(s,a??{});return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(As,{className:"h-10 w-10",children:[e.jsx(Tt,{src:s.avatarUrl??void 0}),e.jsx(Rs,{children:zn(s.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.jobTitle||s.department||"No job title yet"}),e.jsx("p",{className:"text-xs font-medium mt-0.5 truncate",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r})]}),e.jsx(O,{variant:"outline",className:"text-xs shrink-0",children:c.label})]}),e.jsx(Fn,{kpis:o,member:{userId:s.userId,name:s.name},period:t}),e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3 space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:c.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.sentence})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{size:"sm",asChild:!0,children:e.jsx(I,{to:`?tab=team&user=${s.userId}`,children:"Review performance"})}),e.jsx(y,{size:"sm",variant:"outline",asChild:!0,children:e.jsx(I,{to:"?tab=goals",children:"View goals"})}),e.jsx(Bn,{row:s,period:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.lastActionAt?`Last meaningful action: ${Es(new Date(s.lastActionAt))} ago`:"No meaningful action recorded in this period"})]})})}function Bn({row:s,period:t}){const a=`member=${s.userId}&from=${t.from.slice(0,10)}&to=${t.to.slice(0,10)}`,n=[{key:"activity",label:"View activity",to:`/activity?${a}`},{key:"customers",label:"View customers",to:`/contacts?owner=${s.userId}`},{key:"deals",label:"View deals",to:`/deals?${a}`},{key:"profile",label:"Open profile",to:`/admin-panel?section=team&member=${s.userId}`}];return e.jsxs(Dt,{children:[e.jsx(Mt,{asChild:!0,children:e.jsx(y,{size:"sm",variant:"ghost","aria-label":`More for ${s.name}`,children:e.jsx(Ea,{className:"h-4 w-4"})})}),e.jsx(Pt,{align:"end",children:n.map(r=>e.jsx($t,{asChild:!0,children:e.jsx(I,{to:r.to,children:r.label})},r.key))})]})}function Vn({range:s,targets:t}){const[a,n]=f.useState("7d"),r=f.useMemo(()=>a==="custom"?{from:new Date(`${s.start}T00:00:00`).toISOString(),to:new Date(`${s.end}T23:59:59`).toISOString(),label:"Custom"}:Sa(a),[a,s.start,s.end]),{rows:o,isLoading:c,isError:l,refetch:d}=Hs({period:r}),x=f.useMemo(()=>o.reduce((u,k)=>({engaged:u.engaged+k.customersContacted,progressed:u.progressed+k.dealsMoved,proposals:u.proposals+k.proposalsSent,won:u.won+k.dealsWon,revenue:u.revenue+k.revenueWon}),{engaged:0,progressed:0,proposals:0,won:0,revenue:0}),[o]),m=o.find(u=>u.userId),h=u=>m?qs(u,{userId:"all",name:"the team"},r).href:"#";return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:"How is each person performing against their role and goals?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The numbers below are totals for the people shown, not one person's targets."})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[["today","7d","30d"].map(u=>e.jsx(y,{size:"sm",variant:a===u?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>n(u),children:Ta[u]},u)),e.jsx(y,{size:"sm",variant:a==="custom"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>n("custom"),children:"Custom"})]})]}),c?e.jsx("div",{className:"grid gap-2 sm:grid-cols-5",children:Array.from({length:5}).map((u,k)=>e.jsx(te,{className:"h-20"},k))}):l?e.jsx(b,{children:e.jsxs(_,{className:"p-4 flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"We couldn't load the team's contribution. This is usually a connection problem."}),e.jsxs(y,{size:"sm",variant:"outline",onClick:d,children:[e.jsx(ms,{className:"h-3.5 w-3.5 mr-1"})," Try again"]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Te,{label:"Customers engaged",value:String(x.engaged),href:h("customersContacted")}),e.jsx(Te,{label:"Opportunities progressed",value:String(x.progressed),href:h("dealsMoved")}),e.jsx(Te,{label:"Proposals sent",value:String(x.proposals),href:h("proposalsSent")}),e.jsx(Te,{label:"Deals won",value:String(x.won),href:h("dealsWon")}),e.jsx(Te,{label:"Revenue",value:w(x.revenue),href:h("revenueWon")})]}),e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:o.map(u=>e.jsx(qn,{row:u,period:r,targets:t==null?void 0:t[u.userId]}
1,u.userId))})]})]})}function Hn(s,t){const a=X();return oe({queryKey:["team-targets-v2",a,s,t],enabled:!!a&&!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("team_targets").select("*").eq("is_archived",!1).eq("org_id",a).eq("period_start",s).eq("period_end",t).order("team_id");if(r)throw r;return n||[]}})}function Yn(s){return oe({queryKey:["competitions",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:a}=await U.from("competitions").select("*").eq("org_id",s).order("created_at",{ascending:!1});if(a)throw a;return t||[]}})}function Gn(){const s=$s();return dt({mutationFn:async t=>{if(t.id){const{id:a,...n}=t,{error:r}=await U.from("competitions").update(n).eq("id",a);if(r)throw r}else{const{error:a}=await U.from("competitions").insert(t);if(a)throw a}},onSuccess:()=>s.invalidateQueries({queryKey:["competitions"]})})}const Un=[{name:"Highest Revenue",metric:"revenue",type:"monthly"},{name:"Most Deals Closed",metric:"deals",type:"monthly"},{name:"Best Follow-Up Rate",metric:"tasks",type:"weekly"},{name:"Most Improved Rep",metric:"deals",type:"monthly"},{name:"Team Revenue Challenge",metric:"revenue",type:"campaign"}];function Qn({orgId:s,userId:t,canManage:a}){const{data:n}=Yn(s),r=Gn(),[o,c]=f.useState(!1),[l,d]=f.useState({name:"",type:"weekly",metric:"deals",reward_description:"",reward_points:"0",start_date:"",end_date:""}),x=()=>{r.mutate({org_id:s,...l,reward_points:parseInt(l.reward_points),status:"draft",created_by:t},{onSuccess:()=>{q.success("Competition created"),c(!1)},onError:u=>q.error("That did not save",{cause:u})})},m=u=>{r.mutate({id:u,status:"active"},{onSuccess:()=>q.success("Competition activated")})},h=u=>{c(!0),d({...l,name:u.name,metric:u.metric,type:u.type})};return e.jsxs(b,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsxs(Ht,{className:"text-sm",children:["Competitions (",(n||[]).length,")"]}),a&&e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>c(!o),children:[e.jsx(Ls,{className:"h-3 w-3 mr-1"}),"New"]})]}),e.jsxs(_,{className:"space-y-2",children:[a&&e.jsxs("div",{children:[e.jsx(de,{children:"Quick templates"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Un.map(u=>e.jsx(y,{size:"sm",variant:"outline",className:"text-xs h-7",onClick:()=>h(u),children:u.name},u.name))})]}),o&&a&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-2 bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(de,{children:"Name"}),e.jsx(Q,{value:l.name,onChange:u=>d({...l,name:u.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(de,{children:"Type"}),e.jsxs(ve,{value:l.type,onValueChange:u=>d({...l,type:u}),children:[e.jsx(fe,{children:e.jsx(je,{})}),e.jsx(Ne,{children:["weekly","monthly","campaign"].map(u=>e.jsx(G,{value:u,className:"capitalize",children:u},u))})]})]}),e.jsxs("div",{children:[e.jsx(de,{children:"Metric"}),e.jsxs(ve,{value:l.metric,onValueChange:u=>d({...l,metric:u}),children:[e.jsx(fe,{children:e.jsx(je,{})}),e.jsx(Ne,{children:["revenue","deals","calls","referrals","tasks"].map(u=>e.jsx(G,{value:u,className:"capitalize",children:u},u))})]})]}),e.jsxs("div",{children:[e.jsx(de,{children:"Start"}),e.jsx(Q,{type:"date",value:l.start_date,onChange:u=>d({...l,start_date:u.target.value})})]}),e.jsxs("div",{children:[e.jsx(de,{children:"End"}),e.jsx(Q,{type:"date",value:l.end_date,onChange:u=>d({...l,end_date:u.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(de,{children:"Reward description"}),e.jsx(Q,{value:l.reward_description,onChange:u=>d({...l,reward_description:u.target.value})})]}),e.jsxs("div",{children:[e.jsx(de,{children:"Bonus points"}),e.jsx(Q,{type:"number",value:l.reward_points,onChange:u=>d({...l,reward_points:u.target.value})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(y,{size:"sm",onClick:x,disabled:r.isPending||!l.name,children:"Create"})})]}),(n||[]).map(u=>e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:u.name}),e.jsxs("p",{className:"text-xs text-muted-foreground capitalize",children:[u.type," · ",u.metric," · ",u.reward_points," pts"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{variant:"outline",className:"text-xs capitalize",children:u.status}),a&&u.status==="draft"&&e.jsx(y,{size:"sm",variant:"outline",onClick:()=>m(u.id),children:"Activate"})]})]},u.id))]})]})}function Xn(){const s=le(Me(new Date),"yyyy-MM-dd"),t=le(ge(new Date),"yyyy-MM-dd"),{data:a=[]}=Hn(s,t);return a.length?e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b text-sm font-medium flex items-center gap-2",children:[e.jsx(pe,{className:"h-4 w-4 text-primary"})," Team targets - this month"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(Ie,{children:e.jsxs(ae,{children:[e.jsx(D,{children:"Team"}),e.jsx(D,{className:"text-right",children:"Revenue target"}),e.jsx(D,{className:"text-right",children:"Deals"}),e.jsx(D,{className:"text-right",children:"Leads"}),e.jsx(D,{className:"text-right",children:"Calls"}),e.jsx(D,{className:"text-right",children:"Tasks"}),e.jsx(D,{className:"text-right",children:"Follow-ups"})]})}),e.jsx(Ee,{children:a.map(n=>e.jsxs(ae,{children:[e.jsx(M,{className:"font-medium",children:n.team_id}),e.jsx(M,{className:"text-right tabular-nums",children:w(n.revenue_target)}),e.jsx(M,{className:"text-right tabular-nums",children:n.deals_target}),e.jsx(M,{className:"text-right tabular-nums",children:n.leads_target}),e.jsx(M,{className:"text-right tabular-nums",children:n.calls_target}),e.jsx(M,{className:"text-right tabular-nums",children:n.tasks_target}),e.jsx(M,{className:"text-right tabular-nums",children:n.followup_target})]},n.id))})]})})]})}):null}function Jn({range:s,canManage:t}){var R;const[a,n]=f.useState(""),[r,o]=f.useState(""),[c,l]=f.useState(!1),[d]=Be(),[x,m]=f.useState(d.get("focus")==="attention"),h=rt(s),u=Ge(s),{data:k}=cs(),j=X(),C=Bs(),{isAdminOrManager:$}=ds(),E=$,W=h.rows.length<=1&&((R=h.rows[0])==null?void 0:R.userId)===(k==null?void 0:k.id),T=f.useMemo(()=>yn(h.rows,a,r),[h.rows,a,r]),A=f.useMemo(()=>new Set(T.map(v=>
1v.userId)),[T]),g=f.useMemo(()=>u.people.filter(v=>A.has(v.userId)),[u.people,A]),S=T.map(v=>({name:v.name.split(" ")[0]||v.name,revenue:v.revenue})),L=h.rows.some(v=>v.revenueTarget>0||v.dealsTarget>0),P=f.useMemo(()=>Object.fromEntries(h.rows.map(v=>[v.userId,{revenue:v.revenueTarget||null,deals_won:v.dealsTarget||null}])),[h.rows]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Js,{search:a,onSearchChange:n,searchPlaceholder:"Search people...",onOpenFilters:()=>l(v=>!v),activeFilterCount:r?1:0,action:e.jsxs("div",{className:"flex items-center gap-2",children:[t&&e.jsx(y,{size:"sm",variant:"outline",asChild:!0,className:"hidden sm:inline-flex",children:e.jsxs(I,{to:"?tab=goals",children:[e.jsx(pe,{className:"h-3.5 w-3.5 mr-1"})," Manage goals"]})}),e.jsx(y,{size:"sm",className:"flex-1 sm:flex-none",variant:x?"secondary":"default",onClick:()=>m(v=>!v),children:x?"Show everyone":"Review performance"})]}),filterChips:c?e.jsx(Q,{placeholder:"Filter by role...",value:r,onChange:v=>o(v.target.value),className:"max-w-xs h-8"}):void 0}),h.isLoading?e.jsx(Zn,{}):h.isError?e.jsx(We,{title:"We couldn't load your team.",body:"This is usually a connection problem. Try again in a moment.",action:e.jsxs(y,{size:"sm",variant:"outline",onClick:h.refetch,children:[e.jsx(ms,{className:"h-3.5 w-3.5 mr-1"})," Try again"]})}):h.rows.length===0?e.jsx(We,{title:"No team members yet",body:"Performance follows the people in your business. Invite someone to see their numbers here.",action:t?e.jsx(y,{size:"sm",asChild:!0,children:e.jsxs(I,{to:"/admin-panel?section=team",children:[e.jsx(At,{className:"h-3.5 w-3.5 mr-1"})," Invite person"]})}):void 0}):T.length===0?e.jsx(We,{title:`No team member matches "${a||r}".`,body:"Clear the search to see everyone again.",action:e.jsx(y,{size:"sm",variant:"outline",onClick:()=>{n(""),o("")},children:"Clear search"})}):e.jsxs(e.Fragment,{children:[!L&&e.jsx(We,{title:"Your team is ready",body:`${h.rows.length} ${h.rows.length===1?"person is":"people are"} here. Set a goal so DuceCRM can tell you who needs help.`,action:t?e.jsx(y,{size:"sm",asChild:!0,children:e.jsxs(I,{to:"?tab=goals",children:[e.jsx(pe,{className:"h-3.5 w-3.5 mr-1"})," Set goal"]})}):void 0}),e.jsx(Vn,{range:s,targets:P}),e.jsx(er,{people:g,canManage:t,attentionOnly:x})]}),!E&&W&&e.jsx(b,{children:e.jsxs(_,{className:"p-4 flex items-start gap-3",children:[e.jsx(Rt,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"You're seeing your own performance only. Team-wide visibility is limited to managers and admins. Ask your admin to assign you a manager role or to share team reports."})]})}),e.jsxs(bs,{module:"performance",label:"Team analytics",description:"Ranking, scores and the full numbers per person.",children:[E&&e.jsx(Ln,{range:s}),E&&e.jsx(Xn,{}),E&&j&&C.shows("competitions")&&e.jsx(Qn,{orgId:j,userId:k==null?void 0:k.id,canManage:t}),e.jsx(b,{children:e.jsxs(_,{className:"p-4",children:[e.jsx("div",{className:"text-sm font-medium mb-3",children:"Revenue per person"}),S.length?e.jsx("div",{className:"h-56",children:e.jsx(Ys,{children:e.jsxs(Pa,{data:S,children:[e.jsx(Gs,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Us,{dataKey:"name",fontSize:11}),e.jsx(Qs,{fontSize:11,tickFormatter:v=>`â¦${(v/1e3).toFixed(0)}k`}),e.jsx(Xs,{formatter:v=>w(Number(v))}),e.jsx($a,{dataKey:"revenue",fill:"hsl(var(--primary))",radius:[4,4,0,0]})]})})}):e.jsx(os,{title:"No revenue per person yet",hint:"This fills in once people start closing deals."})]})}),e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsx("div",{className:"px-4 py-3 border-b text-sm font-medium",children:"Everyone, with the numbers"}),T.length===0?e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"No team data for this period."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(Ie,{children:e.jsxs(ae,{children:[e.jsx(D,{children:"Name"}),e.jsx(D,{children:"Manager"}),e.jsx(D,{className:"text-right",children:"Revenue"}),e.jsx(D,{className:"text-right",children:"Deals won"}),e.jsx(D,{className:"text-right",children:"Tasks done"}),e.jsx(D,{className:"text-right",children:"Score"}),e.jsx(D,{className:"text-right",children:"Conv %"}),e.jsx(D,{children:"Status"}),e.jsx(D,{})]})}),e.jsx(Ee,{children:T.map(v=>e.jsxs(ae,{children:[e.jsx(M,{className:"font-medium",children:v.name}),e.jsx(M,{className:"text-xs text-muted-foreground",children:v.managerName||"â"}),e.jsx(M,{className:"text-right tabular-nums",children:w(v.revenue)}),e.jsx(M,{className:"text-right tabular-nums",children:v.dealsClosed}),e.jsx(M,{className:"text-right tabular-nums",children:v.tasksCompleted}),e.jsx(M,{className:"text-right tabular-nums",children:v.score}),e.jsxs(M,{className:"text-right tabular-nums",children:[v.conversionRate,"%"]}),e.jsx(M,{children:e.jsx(at,{status:Ns(v.score)})}),e.jsx(M,{className:"text-right",children:e.jsx(y,{asChild:!0,size:"sm",variant:"ghost",children:e.jsx(I,{to:`?tab=team&user=${v.userId}`,children:"View"})})})]}
1,v.userId))})]})})]})})]})]})}function Zn(){return e.jsx(b,{children:e.jsx(_,{className:"p-0",children:e.jsx("ul",{className:"divide-y",children:[0,1,2].map(s=>e.jsxs("li",{className:"px-4 py-3 space-y-2",children:[e.jsx(te,{className:"h-4 w-40"}),e.jsx(te,{className:"h-3 w-24"})]},s))})})})}function We({title:s,body:t,action:a}){return e.jsx(b,{children:e.jsxs(_,{className:"p-4 flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:s}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t})]}),a]})})}function er({people:s,canManage:t,attentionOnly:a}){const n=s.map(l=>({person:l,status:ys(l)})),r=[...n.filter(l=>l.status.state==="at_risk"),...n.filter(l=>l.status.state==="needs_attention")],o=a?[]:n.filter(l=>l.status.state==="on_track"),c=a?[]:n.filter(l=>l.status.state==="not_enough_data");return e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"Needs attention"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.length===0?"Nobody needs help right now.":`${r.length} of ${n.length} ${n.length===1?"person":"people"}.`})]}),r.length>0&&e.jsx("ul",{className:"divide-y",children:r.map(({person:l,status:d})=>e.jsx(ss,{person:l,evidence:d.evidence,needsHelp:!0},l.userId))})]})}),o.length>0&&e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"On track"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length," ",o.length===1?"person is":"people are"," where they should be."]})]}),e.jsx("ul",{className:"divide-y",children:o.map(({person:l})=>e.jsx(ss,{person:l},l.userId))})]})}),c.length>0&&e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"Not enough data"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length," ",c.length===1?"person has":"people have"," nothing to be measured against yet."]})]}),e.jsx("ul",{className:"divide-y",children:c.map(({person:l,status:d})=>e.jsx(ss,{person:l,evidence:d.evidence,reviewPlan:t},l.userId))})]})})]})}function ss({person:s,evidence:t,needsHelp:a,reviewPlan:n}){const r=Number(s.dealsTarget??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:"text-sm font-medium truncate",children:s.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w(s.revenue),r>0?` · ${s.dealsClosed} / ${r} deals`:` · ${s.dealsClosed} deals won`]}),t&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t})]}),n?e.jsx(y,{asChild:!0,size:"sm",variant:"ghost",className:"shrink-0",children:e.jsx(I,{to:"?tab=goals",children:"Review plan"})}):e.jsx(y,{asChild:!0,size:"sm",variant:a?"outline":"ghost",className:"shrink-0",children:e.jsx(I,{to:`?tab=team&user=${s.userId}`,children:a?`View ${s.name.split(" ")[0]}`:"View"})})]})}function sr(s){return new Date(Date.now()-s*864e5).toISOString()}function tr(s,t=7){const a=X();return oe({queryKey:["user-recognition",a,s,t],enabled:!!a&&!!s,staleTime:6e4,queryFn:async()=>{const n={totalPoints:0,positivePoints:0,negativePoints:0,awardCount:0,penaltyCount:0,recent:[],scoreNudge:0};if(!a||!s)return n;const{data:r}=await U.from("loyalty_points").select("points, source, description, user_id, created_at").eq("org_id",a).eq("user_id",s).gte("created_at",sr(t)).order("created_at",{ascending:!1}).limit(20),o=r??[],c=o.filter(x=>x.points>0),l=o.filter(x=>x.points<0),d=o.reduce((x,m)=>x+Number(m.points||0),0);return{totalPoints:d,positivePoints:c.reduce((x,m)=>x+m.points,0),negativePoints:l.reduce((x,m)=>x+m.points,0),awardCount:c.length,penaltyCount:l.length,recent:o.slice(0,5),scoreNudge:Math.max(-10,Math.min(10,Math.round(d*.1)))}}})}function ar({userId:s}){const{data:t}=tr(s);if(!s||!t)return null;const a=t.awardCount+t.penaltyCount>0;return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(It,{className:"h-4 w-4 text-primary"})," Manager recognition (7d)"]}),e.jsxs(O,{variant:"outline",className:"tabular-nums",children:["+",t.positivePoints," pts"]})]}),a?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:B("grid gap-2 text-xs",t.penaltyCount>0?"grid-cols-2":"grid-cols-1"),children:[e.jsxs("div",{className:"rounded-md border border-emerald-500/30 bg-emerald-500/10 p-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-700 dark:text-emerald-300",children:[e.jsx(Ae,{className:"h-3 w-3"})," Awarded"]}),e.jsxs("p",{className:"text-lg font-semibold tabular-nums text-foreground mt-0.5",children:["+",t.positivePoints," ",e.jsxs("span",{className:"text-[10px] text-muted-foreground font-normal",children:["(",t.awardCount,")"]})]})]}),e.jsxs("div",{className:B("rounded-md border border-rose-500/30 bg-rose-500/10 p-2",t.penaltyCount===0&&"hidden"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-rose-700 dark:text-rose-300",children:[e.jsx(us,{className:"h-3 w-3"})," Past deductions"]}),e.jsxs("p",{className:"text-lg font-semibold tabular-nums text-foreground mt-0.5",children:[t.negativePoints," ",e.jsxs("span",{className:"text-[10px] text-muted-foreground font-normal",children:["(",t.penaltyCount,")"]})]})]})]}),t.recent.length>0&&e.jsx("ul",{className:"divide-y border rounded-md",children:t.recent.map((n,r)=>e.jsxs("li",{className:"flex items-center justify-between gap-2 px-2.5 py-1.5 text-xs",children:[e.jsxs("span",{className:"truncate",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n.source??"manual"," · "]}),n.description||"â"]}
1),e.jsxs("span",{className:B("tabular-nums font-semibold shrink-0",n.points>0?"text-emerald-600":"text-rose-600"),children:[n.points>0?"+":"",n.points]})]},r))}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Recognition is separate from measured performance and never changes the score."})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recognition this week. Recognition is appreciation - it never changes measured performance."})]})})}function qe({title:s="How this feeds your scores",subtitle:t,rows:a}){return a.length===0?null:e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(rs,{className:"h-4 w-4 text-primary"})," ",s]}),t&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t})]}),e.jsx("ul",{className:"space-y-2",children:a.map((n,r)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:n.signal}),e.jsx("span",{className:"text-muted-foreground",children:"->"}),n.individual&&e.jsxs(O,{variant:"outline",className:"bg-primary/10 border-primary/30 text-primary",children:[e.jsx(Ve,{className:"h-3 w-3 mr-1"})," Individual: ",n.individual]}),n.org&&e.jsxs(O,{variant:"outline",className:"bg-emerald-500/10 border-emerald-500/30 text-emerald-700 dark:text-emerald-300",children:[e.jsx(rs,{className:"h-3 w-3 mr-1"})," Org Health: ",n.org]}),n.earnings&&e.jsxs(O,{variant:"outline",className:"bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-300",children:[e.jsx(Fs,{className:"h-3 w-3 mr-1"})," Earnings: ",n.earnings]})]},r))})]})})}function nr({userId:s}){const t=X(),a=new Date,n={start:Me(a).toISOString(),end:ge(a).toISOString()},{data:r=[]}=Zs(t,{userId:s??void 0,dateRange:n});if(!s)return null;const o=m=>r.filter(h=>!m||h.status===m).reduce((h,u)=>h+Number(u.commission_amount||0),0),c=r.reduce((m,h)=>m+Number(h.deal_value||0),0),l=o(),d=r.length,x=c>0?l/c*100:0;return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4 text-primary"})," Commission earnings (this period)"]}),e.jsx(O,{variant:"outline",className:"bg-primary/10 border-primary/30 text-primary tabular-nums",children:w(l)})]}),d===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No commissions yet this period. Closing a deal auto-generates a commission and lifts this person's Sales Activity score."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs",children:[e.jsx(ts,{label:"Pending",value:w(o("pending"))}),e.jsx(ts,{label:"Approved",value:w(o("approved")),tone:"positive"}),e.jsx(ts,{label:"Paid",value:w(o("paid")),tone:"positive"})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[d," deal",d===1?"":"s"," -> ",w(c)," revenue -> ",x.toFixed(1),"% effective rate. These same `deal_won` events drive this person's ",e.jsx("span",{className:"text-foreground",children:"Sales Activity"})," category and the org's ",e.jsx("span",{className:"text-foreground",children:"Pipeline Hygiene"})," pillar."]})]}),e.jsx(y,{asChild:!0,size:"sm",variant:"ghost",className:"w-full",children:e.jsxs(I,{to:`/commissions?user=${s}`,children:["Open commissions ledger ",e.jsx(xs,{className:"h-3.5 w-3.5 ml-1"})]})})]})})}function ts({label:s,value:t,tone:a}){return e.jsxs("div",{className:"rounded-md border bg-muted/30 p-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:s}),e.jsx("p",{className:`text-sm font-semibold tabular-nums ${a==="positive"?"text-emerald-600":""}`,children:t})]})}const rr=[{signal:"Revenue contribution",individual:"Sales Activity",org:"Pipeline Hygiene"},{signal:"Deal won",individual:"Sales Activity",org:"Pipeline Hygiene",earnings:"Commission auto-generated"},{signal:"Tasks completed",individual:"Task Execution",org:"Follow-up Discipline"},{signal:"Calls logged",individual:"Sales Activity",org:"Responsiveness"},{signal:"Conversion rate",individual:"Customer Engagement",org:"Engagement Volume"}];function Ds({range:s,canManage:t}){var Y,Z,ee,Ce,ws;const[a,n]=Be(),{data:r}=cs(),{data:o=[]}=fs(s),l=a.get("user")||(r==null?void 0:r.id)||"",d=!!l&&l===(r==null?void 0:r.id),{level:x}=Et(),m=Lt("performance"),h=na({personalLevel:x,advancedAvailable:m.available}),u=Bs(),k=N=>{const J=new URLSearchParams(a);J.set("tab","team"),J.set("user",N),n(J,{replace:!0})},{data:j,isLoading:C}=Ws(l,s),{data:$}=ja(l),{data:E=[]}=js(s),{data:W=[]}=Jt(l),T=Ge(s),A=o.find(N=>N.user_id===l),g=A==null?void 0:A.role,S=f.useMemo(()=>E.filter(N=>N.role===g||N.role==="*"),[E,g]),L=f.useMemo(()=>{var N,J,ce,Fe;return Zt({revenue:(N=j==null?void 0:j.revenue)==null?void 0:N.total,dealsWon:(J=j==null?void 0:j.revenue)==null?void 0:J.deals_closed,tasksCompleted:(ce=j==null?void 0:j.activity)==null?void 0:ce.tasks_completed,callsLogged:(Fe=j==null?void 0:j.activity)==null?void 0:Fe.calls_logged,formatMoney:w})},[j]),P=(($==null?void 0:$.rows)??[]).find(N=>N.key==="revenue"),R=f.useMemo(()=>{var J;const N=new Date;return ea({target:Number((P==null?void 0:P.target)??0),actual:Number((P==null?void 0:P.actual)??((J=j==null?void 0:j.revenue)==null?void 0:J.total)??0),daysLeft:Math.max(0,De(ge(N),N)),formatMoney:w})}
1,[P,j]),v=T.people.find(N=>N.userId===l),z=f.useMemo(()=>sa({stuckDeals:Number((v==null?void 0:v.stalledDeals)??0),stuckValue:Number(T.facts.stuckDealsValue??0),offersNotSent:0,overdueFollowups:d?Number(T.facts.overdueFollowups??0):0,unpaidInvoices:0,formatMoney:w}),[v,T.facts.stuckDealsValue,T.facts.overdueFollowups,d]),[ie,i]=f.useState(!1),[p,F]=f.useState("feedback"),[V,H]=f.useState(""),be=ta(),Ue=aa(),Qe=async()=>{if(!(!l||!V.trim()))try{await be.mutateAsync({user_id:l,note_type:p,content:V.trim()}),q.success("Coaching note added"),H(""),i(!1)}catch(N){q.error("Failed to add",{cause:N})}},Le=N=>N==="revenue"?Wt:N==="deals"?Pe:N==="tasks"?pe:Kt;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Viewing"}),e.jsxs(ve,{value:l,onValueChange:k,children:[e.jsx(fe,{className:"w-[260px]",children:e.jsx(je,{placeholder:"Pick a person"})}),e.jsx(Ne,{children:o.map(N=>e.jsxs(G,{value:N.user_id,children:[N.full_name," â ",N.role]},N.user_id))})]})]}),C?e.jsx(te,{className:"h-64 w-full"}):!j||!l?e.jsx(b,{children:e.jsx(_,{className:"p-6 text-sm text-muted-foreground",children:"No data yet."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:L.map(N=>e.jsx(La,{icon:Le(N.key),label:N.label,value:N.value},N.key))}),e.jsx(b,{children:e.jsx(_,{className:"p-4",children:e.jsx("p",{className:"text-sm",children:R})})}),e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:d?"Your focus":"What would help most"}),z.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing is waiting. Keep the conversations moving and the month takes care of itself."}):e.jsx("ul",{className:"space-y-2",children:z.map(N=>e.jsxs("li",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.reason})]}),N.href&&e.jsx(y,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs(I,{to:N.href,children:["Open ",e.jsx(xs,{className:"h-3.5 w-3.5 ml-1"})]})})]},N.id))})]})}),h!=="simple"&&e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"How this month compares"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:`${w(Number(((Y=j==null?void 0:j.revenue)==null?void 0:Y.total)??0))} from ${Number(((Z=j==null?void 0:j.revenue)==null?void 0:Z.deals_closed)??0)} won ${Number(((ee=j==null?void 0:j.revenue)==null?void 0:ee.deals_closed)??0)===1?"deal":"deals"}, with ${Number(((Ce=j==null?void 0:j.activity)==null?void 0:Ce.calls_logged)??0)} calls and ${Number(((ws=j==null?void 0:j.activity)==null?void 0:ws.tasks_completed)??0)} tasks behind it.`})]})}),u.shows("recognition")&&h!=="simple"&&e.jsx(ar,{userId:l}),e.jsxs(bs,{module:"performance",label:"The numbers behind this",description:"Targets, scores and the full detail for this person.",children:[e.jsx(nt,{title:"Individual target attainment",subtitle:"From Individual Targets - feeds this person's Performance Score categories",rows:($==null?void 0:$.rows)??[],overall:($==null?void 0:$.overall)??0,icon:"target",emptyHint:"No individual targets set for this person this period. Add them in Goals & KPIs > Individual Targets."}),u.shows("advanced_scoring")&&e.jsx(qe,{title:"How these KPIs feed scores",subtitle:"Each KPI above maps to a category in this person's Performance Score and a pillar in Org Health.",rows:rr}),e.jsx(nr,{userId:l}),u.shows("kpi_plans")&&e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsx("div",{className:"px-4 py-3 border-b text-sm font-medium",children:"KPI status"}),S.length===0?e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"No KPIs defined for this role."}):e.jsxs(Re,{children:[e.jsx(Ie,{children:e.jsxs(ae,{children:[e.jsx(D,{children:"KPI"}),e.jsx(D,{children:"Period"}),e.jsx(D,{className:"text-right",children:"Target"}),e.jsx(D,{className:"text-right",children:"Actual"}),e.jsx(D,{className:"text-right",children:"Completion %"}),e.jsx(D,{children:"Status"})]})}),e.jsx(Ee,{children:S.map((N,J)=>{const ce=Number(N.achieved_pct||0),Fe=ce>=100?"Achieved":ce>=60?"On Track":"Behind",ct=ce>=100?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30":ce>=60?"bg-amber-500/15 text-amber-700 dark:text-amber-300 border-amber-500/30":"bg-rose-500/15 text-rose-700 dark:text-rose-300 border-rose-500/30";return e.jsxs(ae,{children:[e.jsx(M,{children:Ks[N.metric_name]||N.metric_name}),e.jsx(M,{className:"text-xs",children:zs[N.period]}),e.jsx(M,{className:"text-right tabular-nums",children:N.metric_name==="revenue"?w(N.scaled_target):N.scaled_target}),e.jsx(M,{className:"text-right tabular-nums",children:N.metric_name==="revenue"?w(N.actual):N.actual}),e.jsxs(M,{className:"text-right tabular-nums",children:[ce,"%"]}),e.jsx(M,{children:e.jsx(O,{variant:"outline",className:ct,children:Fe})})]},J)})})]})]})})]}),e.jsx(b,{children:e.jsxs(_,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-primary"})," Manager feedback"]}),t&&e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>i(!0),children:[e.jsx(Ls,{className:"h-3.5 w-3.5 mr-1"})," Add note"]})]}),W.length===0?e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"No coaching notes yet."}):e.jsx("ul",{className:"divide-y",children:W.map(N=>e.jsxs("li",{className:"p-3 flex items-start gap-3",children:[e.jsx(O,{variant:"outline",className:"text-[10px] uppercase shrink-0",children:N.note_type}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:le(new Date(N.created_at),"MMM d, yyyy h:mm a")})]}),t&&e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive shrink-0",onClick:()=>Ue.mutate({id:N.id,user_id:l}),"aria-label":"Delete",children:e.jsx(Fa,{className:"h-3.5 w-3.5"})})]},N.id))})]})})]}),e.jsx(hs,{open:ie,onOpenChange:i,children:e.jsxs(ps,{size:"md",className:"",children:[e.jsx(gs,{children:e.jsx(vs,{children:"Add coaching note"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ve,{value:p,onValueChange:N=>F(N),children:[e.jsx(fe,{children:e.jsx(je,{})}),e.jsxs(Ne,{children:[e.jsx(G,{value:"feedback",children:"Feedback"}),e.jsx(G,{value:"warning",children:"Warning"}),e.jsx(G,{value:"praise",children:"Praise"}),e.jsx(G,{value:"plan",children:"Plan"})]})]}),e.jsx(Ft,{value:V,onChange:N=>H(N.target.value),rows:4,placeholder:"What did you observe? What needs to change?"})]}),e.jsxs(Ot,{children:[e.jsx(y,{variant:"ghost",onClick:()=>i(!1),children:"Cancel"}),e.jsx(y,{onClick:Qe,disabled:!V.trim()||be.isPending,children:"Save note"})]})]})})]})}function lr({revenue:s,deals:t,suggestion:a,canManage:n,saving:r,learning:o,onRevenueChange:c,onDealsChange:l,onSave:d,onCancel:x}){const m=Number(s)>0;return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"What do we want to achieve?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This month"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-xl",children:[e.jsxs("div",{children:[e.jsx(Ke,{className:"text-xs",children:"Revenue target (â¦)"}),e.jsx(Q,{type:"number",inputMode:"numeric",placeholder:"10,000,000",value:s,onChange:h=>c(h.target.value),disabled:!n})]}),e.jsxs("div",{children:[e.jsxs(Ke,{className:"text-xs",children:["Deal
1s target ",a.deals===null&&e.jsx("span",{className:"text-muted-foreground",children:"· optional"})]}),e.jsx(Q,{type:"number",inputMode:"numeric",placeholder:a.deals!==null?String(a.deals):"Optional",value:t,onChange:h=>l(h.target.value),disabled:!n}),a.deals!==null&&Number(t)!==a.deals&&e.jsxs(y,{type:"button",size:"sm",variant:"ghost",className:"mt-1 h-7 px-2 text-xs",onClick:()=>l(String(a.deals)),disabled:!n,children:[e.jsx(Ve,{className:"h-3.5 w-3.5 mr-1"})," Suggested: ",a.deals," · use it"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:a.basis})]})]}),o&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3",children:[e.jsx("p",{className:"text-sm",children:"DuceCRM is still learning how your business sells."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"As you close more deals, we'll automatically improve your target recommendations."}),e.jsx(et,{title:"How this works",rememberKey:"performance.goals.learning",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"We read your own won deals to work out a typical deal size and how often deals close. Until there are enough of them, we don't pretend to know - you set the target and we measure against it."})})]}),n&&e.jsxs("div",{className:"flex justify-end gap-2",children:[x&&e.jsx(y,{variant:"ghost",onClick:x,disabled:r,children:"Cancel"}),e.jsx(y,{onClick:d,disabled:!m||r,children:r?"Savingâ¦":"Save goal"})]})]})})}function or({gap:s,deals:t,workingDaysLeft:a,evidence:n,monthLabel:r,canManage:o,onAdjust:c}){return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold",children:["Your plan for ",r]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w(s.target),t.target>0?` · ${t.target} deals`:""," ·"," ",a===0?"last working day":`${a} working ${a===1?"day":"days"} remaining`]})]}),o&&e.jsx(y,{size:"sm",variant:"outline",onClick:c,children:"Adjust plan"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xl font-semibold tabular-nums",children:[w(s.won),e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:[" of ",w(s.target)," achieved"]})]}),e.jsx(ke,{value:Math.min(100,s.pct??0),className:"h-1.5"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.pct??0,"% · ",w(s.remaining)," remaining",t.target>0?` · ${t.actual} of ${t.target} deals won`:""]})]}),s.openPipeline>0&&e.jsxs("p",{className:"text-sm",children:["You currently have"," ",e.jsx("span",{className:"font-semibold tabular-nums",children:w(s.openPipeline)})," in open deals.",s.stuckValue>0&&e.jsxs("span",{className:"text-muted-foreground",children:[" ",w(s.stuckValue)," of it has not moved recently."]})]}),s.expectedToDate!==null&&(s.paceGap??0)>0&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 p-3 text-sm",children:[e.jsx("p",{className:"font-medium",children:"You're behind pace"}),e.jsxs("p",{className:"text-xs mt-0.5",children:["You should have reached about ",w(s.expectedToDate)," by today. You're at"," ",w(s.won)," - ",w(s.paceGap??0)," behind."]})]}),!n.insufficientHistory&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5 mb-2",children:[e.jsx(Ae,{className:"h-4 w-4 text-primary"})," Based on your recent sales"]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:n.basis.filter(l=>l.display).map(l=>e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:l.label}),e.jsx("p",{className:"text-base font-semibold tabular-nums",children:l.display})]},l.label))}),n.dealsNeeded!==null&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["At your current performance, reaching ",w(s.target)," may require approximately"," ",e.jsx("span",{className:"font-semibold text-foreground",children:n.dealsNeeded})," won deals."]}),e.jsx(et,{title:"See calculation",rememberKey:"performance.goals.calculation",children:e.jsx("ul",{className:"space-y-1 text-xs text-muted-foreground",children:n.calculation.map(l=>e.jsxs("li",{className:"flex items-start gap-1.5",children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mt-0.5 shrink-0 text-primary"}),e.jsx("span",{children:l})]},l))})})]}),n.insufficientHistory&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3",children:[e.jsx("p",{className:"text-sm",children:"DuceCRM is still learning how your business sells."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"As you close more deals, we'll automatically improve your target recommendations."})]})]})})}const ir=[{key:"recommend",label:"Recommend for me",hint:"Split using each person's recent results"},{key:"equal",label:"Split equally",hint:"Everyone carries the same number"},{key:"manual",label:"I'll decide",hint:"Type each person's number yourself"}];function cr({result:s,members:t,mode:a,canManage:n,saving:r,actuals:o,onModeChange:c,onManualChange:l,onSave:d}){const x=s.rows.reduce((m,h)=>m+h.revenue,0);return t.length?e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Who will carry this goal?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every person's number adds up to the company target."})]}),n&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ir.map(m=>e.jsx(y,{size:"sm",variant:a===m.key?"default":"outline",onClick:()=>c(m.key),title:m.hint,children:m.label},m.key))}),s.usedFallback&&s.message&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s.message}),e.jsx("div",{className:"divide-y rounded-md border",children:s.rows.map(m=>{const h=o[m.userId]??0,u=m.revenue>0?Math.min(100,Math.round(h/m.revenue*100)):0;return e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:m.name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:m.basis})]}),a==="manual"&&n?e.jsx(Q,{type:"number",inputMode:"numeric",className:"w-36 h-8",value:m.revenue||"",onChange:k=>l(m.userId,Number(k.target.value)||0)}):e.jsx("p",{className:"text-sm font-semibold tabular-nums shrink-0",children:w(m.revenue)})]}),m.revenue>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{value:u,className:"h-1"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[w(h)," won · ",u,"%",m.deals>0?` · ${m.deals} deals`:""]})]})]},m.userId)})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Allocated ",e.jsx("span",{className:"font-semibold text-foreground tabular-nums",children:w(x)}),s.unassignedRevenue>0&&e.jsxs(e.Fragment,{children:[" · unassigned ",e.jsx("span",{className:"font-semibold text-foreground tabular-nums",children:w(s.unassignedRevenue)})]})]}),s.reconciled?e.jsxs(O,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-600/30",children:[e.jsx(Pe,{className:"h-3.5 w-3.5"})," Adds up to the company target"]}):e.jsxs(O,{variant:"outline",className:"gap-1 text-amber-600 border-amber-600/30",children:[e.jsx(ue,{className:"h-3.5 w-3.5"})," ",w(s.overAllocatedRevenue)," over the company target"]})]}),n&&e.jsx("div",{className:"flex justify-end",children:e.jsx(y,{onClick:d,disabled:r||!s.reconciled,children:r?"Savingâ¦":"Save plan"})})]})}):e.jsx(b,{children:e.jsxs(_,{className:"p-4",children:[e.jsx("p",{className:"text-sm font-medium",children:"Who will carry this goal?"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Invite your team and DuceCRM will divide the target between them. Until then the whole target sits with the business."})]})})}const dr="We don't know enough about your team yet. For now we can divide the target equally, or you can assign it yourself.";function is(s,t){if(t<=0)return[];const a=Math.floor(s/t),n=new Array(t).fill(a);let r=s-a*t;for(let o=0;r>0;o=(o+1)%t)n[o]+=1,r-=1;return n}function Ms(s,t){const a=t.reduce((l,d)=>l+Math.max(0,d),0);if(a<=0)return is(s,t.length);const n=t.map(l=>s*Math.max(0,l)/a),r=n.map(l=>Math.floor(l));let o=s-r.reduce((l,d)=>l+d,0);const c=n.map((l,d)=>({i:d,frac:l-Math.floor(l)})).sort((l,d)=>d.frac-l.frac);for(let l=0;o>0&&c.length;l++)r[c[l%c.length].i]+=1,o-=1;return r}function mr(s){const t=Math.max(0,Math.round(Number(s.companyRevenue)||0)),a=Math.max(0,Math.round(Number(s.companyDeals)||0)),n=s.members??[],r=Math.min(90,Math.max(0,Number(s.unassignedPct??0)));if(!n.length)return{mode:s.mode,effectiveMode:s.mode,rows:[],unassignedRevenue:t,unassignedDeals:a,reconciled:!0,overAllocatedRevenue:0,overAllocatedDeals:0,usedFallback:!1,message:"No team members yet - the whole target sits with the business."};if(s.mode==="manual"){const g=n.map(P=>({userId:P.userId,name:P.name,revenue:Math.max(0,Math.round(Number(P.manualRevenue??0))),deals:Math.max(0,Math.round(Number(P.manualDeals??0))),basis:"You set this."})),S=g.reduce((P,R)=>P+R.revenue,0),L=g.reduce((P,R)=>P+R.deals,0);return{mode:"manual",effectiveMode:"manual",rows:g,unassignedRevenue:Math.max(0,t-S),unassignedDeals:Math.max(0,a-L),reconciled:S<=t&&L<=a,overAllocatedRevenue:Math.max(0,S-t),overAllocatedDeals:Math.max(0,L-a),usedFallback:!1}}const o=Math.round(t*r/100),c=Math.round(a*r/100),l=t-o,d=a-c,x=n.map(g=>Math.max(0,Number(g.pastRevenue??0))),m=n.map(g=>Math.max(0,Number(g.openPipeline??0))),h=x.some(g=>g>0),u=m.some(g=>g>0);let k=null,j="";s.mode==="recommend"&&h?(k=x,j="Based on what they closed recently."):s.mode==="recommend"&&u&&(k=m,j="Based on the open deals assigned to them.");const C=s.mode==="recommend"&&k===null,$=k?Ms(l,k):is(l,n.length),E=k?Ms(d,k):is(d,n.length),W=n.map((g,S)=>({userId:g.userId,name:g.name,revenue:$[S]??0,deals:E[S]??0,basis:k?j:"Divided equally - we don't have enough history yet."})),T=W.reduce((g,S)=>g+S.revenue,0),A=W.reduce((g,S)=>g+S.deals,0);return{mode:s.mode,effectiveMode:C?"equal":s.mode,rows:W,unassignedRevenue:t-T,unassignedDeals:a-A,reconciled:T+(t-T)===t&&A+(a-A)===a,overAllocatedRevenue:0,overAllocatedDeals:0,usedFallback:C,message:C?dr:void 0}}const ur=[{signal:"Monthly Revenue Goal",individual:"Sales Activity",org:"Pipeline Hygiene"},{signal:"Per-person revenue target",individual:"Sales Activity",org:"Pipeline Hygiene"}],xr=[{signal:"Calls KPI",individual:"Sales Activity",org:"Responsiveness"},{signal:"Tasks KPI",individual:"Task Execution",org:"Follow-up Discipline"},{signal:"Follow-ups KPI",individual:"Workflow Discipline",org:"Follow-up Discipline"},{signal:"Meetings KPI",individual:"Workflow Discipline",org:"Responsiveness"}];function hr({range:s,canManage:t,roleLoading:a,openFormSignal:n=0}){const{revenue:r,deals:o,facts:c,people:l,team:d}=Ge(s),{data:x}=ra(),{data:m=[]}=la(),h=oa(),u=ia(),[k,j]=f.useState(!1);f.useEffect(()=>{n>0&&t&&j(!0)},[n,t]);const[C,$]=f.useState(""),[E,W]=f.useState(""),[T,A]=f.useState("recommend"),[g,S]=f.useState({}),[L,P]=f.useState(null),R=r.hasTarget||!!L,v=t&&(k||!R),z=r.hasTarget?r.target:(L==null?void 0:L.revenue)??0,ie=r.hasTarget?o.target:(L==null?void 0:L.deals)??0,i=v?Number(C)||0:z,p=v?Number(E)||0:ie,F=f.useMemo(()=>ca(i,x),[i,x]),V=f.useMemo(()=>mr({companyRevenue:i,companyDeals:p,mode:T,members:m.map(Y=>({...Y,manualRevenue:g[Y.userId]??null}))}),[i,p,T,m,g]),H=f.useMemo(()=>
1da({target:z,won:r.actual,openPipeline:c.openPipeline??0,stuckValue:c.stuckDealsValue??0,workingDaysLeft:h.left,workingDaysElapsed:h.elapsed,formatMoney:w}),[z,r.actual,c.openPipeline,c.stuckDealsValue,h]),be=f.useMemo(()=>ma({revenueTarget:z,benchmarks:x,formatMoney:w}),[z,x]),Ue=f.useMemo(()=>{const Y={};return l.forEach(Z=>{Y[Z.userId]=Z.revenue}),Y},[l]),Qe=ua(),Le=async(Y,Z)=>{if(Y<=0){q.blocked("Add a revenue goal first",{description:"Tell DuceCRM what the business wants to earn this month."});return}try{const ee=await u.mutateAsync({...Qe,companyRevenue:Y,companyDeals:Z,rows:V.rows});P({revenue:Y,deals:Z}),j(!1);const Ce=_a({companyRevenue:Y,peopleWithNumbers:(ee==null?void 0:ee.peopleWithNumbers)??0,monthLabel:le(new Date,"MMMM"),formatMoney:w});q.success(Ce.title,{description:Ce.description})}catch(ee){q.error("We could not save the goal",{description:"Nothing was lost - your numbers are still here. Try saving again.",cause:ee})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-sm font-medium",children:"What are we trying to achieve?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set clear targets for your team and see whether execution is moving the business forward."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r!=null&&r.hasTarget||o!=null&&o.hasTarget?`${r!=null&&r.hasTarget?`Revenue target ${w(r.target)} (${r.pct}% reached)`:`Deals target ${o.target} (${o.pct}% reached)`}. ${d!=null&&d.needsAttention?`${d.needsAttention} ${d.needsAttention===1?"person is":"people are"} behind their target.`:"Nobody is behind their target."}`:"No target is set for this period yet, so nothing can be measured against it."}),!!(d!=null&&d.needsAttention)&&e.jsx(I,{to:"?tab=team&focus=attention",className:"text-xs font-medium underline underline-offset-4",children:"See who is behind"})]}),a?e.jsx(b,{children:e.jsxs(_,{className:"p-4",children:[e.jsx("div",{className:"h-4 w-40 bg-muted rounded animate-pulse"}),e.jsx("div",{className:"h-9 w-full max-w-xl bg-muted rounded animate-pulse mt-3"})]})}):!t&&!R?e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"No business goal is set for this month"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only an owner, admin or manager can set the business goal. Ask one of them to set it and your own number will appear here."})]})}):v?e.jsx(lr,{revenue:C,deals:E,suggestion:F,canManage:t,saving:u.isPending,learning:!(x!=null&&x.avgDealSize),onRevenueChange:$,onDealsChange:W,onSave:()=>Le(Number(C)||0,Number(E)||F.deals||0),onCancel:R?()=>j(!1):void 0}):e.jsx(or,{gap:H,deals:{target:o.target,actual:o.actual},workingDaysLeft:h.left,evidence:be,monthLabel:le(new Date,"MMMM"),canManage:t,onAdjust:()=>{$(String(r.target||"")),W(String(o.target||"")),j(!0)}}),i>0&&e.jsx(cr,{result:V,members:m,mode:T,canManage:t,saving:u.isPending,actuals:Ue,onModeChange:A,onManualChange:(Y,Z)=>{A("manual"),S(ee=>({...ee,[Y]:Z}))},onSave:()=>Le(i,p)}),e.jsx(ns,{label:"Weekly activity",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx($e,{className:"h-3.5 w-3.5 text-primary"}),"The work you expect every week - calls, tasks, meetings and follow-ups."]}),e.jsx(xa,{range:s,canManage:t})]})}),e.jsxs(ns,{label:"Change history",children:[e.jsx(ha,{}),e.jsx(qe,{title:"Business goal",subtitle:"Where the revenue goal shows up.",rows:ur}),e.jsx(qe,{title:"Weekly work",subtitle:"Where activity thresholds show up.",rows:xr})]})]})}function ne(s,t){if(t.length===0)return;const a=Object.keys(t[0]);Wa([a,...t.map(n=>a.map(r=>n[r]))],s)}function pr({range:s}){const t=X(),{data:a=[]}=fs(s),{data:n=[]}=js(s),{data:r}=He(30),{data:o=[]}=Zs(t,{dateRange:{start:new Date(s.start).toISOString(),end:new Date(s.end).toISOString()}}),[c,l]=f.useState("__all"),[d,x]=f.useState("__all"),m=f.useMemo(()=>Array.from(new Set(a.map(i=>i.role).filter(Boolean))),[a]),h=f.useMemo(()=>a.filter(i=>(c==="__all"||i.role===c)&&(d==="__all"||i.user_id===d)),[a,c,d]),u=`${s.start}_${s.end}`,S=[{key:"activity",title:"Activity Report",desc:"Tasks + calls per person.",icon:Je,run:()=>
1{if(h.length===0)return q.success("Nothing to export");ne(`activity-report-${u}.csv`,h.map(i=>({Name:i.full_name,Role:i.role,"Tasks completed":i.tasks_completed,"Calls logged":i.calls_logged})))}},{key:"kpi",title:"KPI Report",desc:"Target vs actual per role.",icon:ye,run:()=>{if(n.length===0)return q.success("Nothing to export");ne(`kpi-report-${u}.csv`,n.map(i=>({Metric:i.metric_name,Role:i.role,Period:i.period,Target:i.scaled_target,Actual:i.actual,"Completion %":i.achieved_pct,Status:i.status_color})))}},{key:"revenue",title:"Revenue Contribution",desc:"Revenue + deals per person.",icon:ye,run:()=>{if(h.length===0)return q.success("Nothing to export");ne(`revenue-contribution-${u}.csv`,h.map(i=>({Name:i.full_name,Role:i.role,Revenue:i.revenue,"Deals won":i.deals_closed})))}},{key:"conversion",title:"Conversion Report",desc:"Leads converted + conversion %.",icon:Je,run:()=>{if(h.length===0)return q.success("Nothing to export");ne(`conversion-report-${u}.csv`,h.map(i=>({Name:i.full_name,Role:i.role,"Leads converted":i.leads_converted,"Conversion %":i.conversion_rate})))}},{key:"team",title:"Team Performance",desc:"Full execution snapshot.",icon:ye,run:()=>{if(h.length===0)return q.success("Nothing to export");ne(`team-performance-${u}.csv`,h.map(i=>({Name:i.full_name,Role:i.role,Manager:i.manager_name||"",Revenue:i.revenue,"Deals won":i.deals_closed,"Tasks completed":i.tasks_completed,"Calls logged":i.calls_logged,"Conversion %":i.conversion_rate,"KPI score":i.kpi_score})))}},{key:"score",title:"Performance Report",desc:"Per-person score and band.",icon:ye,run:()=>{if(h.length===0)return q.success("Nothing to export");ne(`performance-score-${u}.csv`,h.map(i=>({Name:i.full_name,Role:i.role,"KPI score":i.kpi_score,Band:Ns(i.kpi_score),Revenue:i.revenue,"Deals won":i.deals_closed,"Tasks completed":i.tasks_completed,"Calls logged":i.calls_logged,"Conversion %":i.conversion_rate})))}},{key:"orghealth",title:"Business Health Snapshot",desc:"Current health score with all 4 pillars.",icon:Je,run:()=>{if(!r)return q.success("Org Health not available yet");const i=r.pillars;ne(`org-health-${u}.csv`,[{Score:r.score,Status:r.status,"Window days":r.window_days,Since:r.since,Responsiveness:`${i.responsiveness.score}/${i.responsiveness.max}`,"Pipeline Hygiene":`${i.pipeline_hygiene.score}/${i.pipeline_hygiene.max}`,"Follow-up Discipline":`${i.followup_discipline.score}/${i.followup_discipline.max}`,"Engagement Volume":`${i.engagement_volume.score}/${i.engagement_volume.max}`}])}},{key:"earnings",title:"Commission Earnings",desc:"Deals, revenue, commission earned, effective rate.",icon:ye,run:()=>{if(o.length===0)return q.success("No commissions in this period");const i={};o.forEach(p=>{const F=a.find(be=>be.user_id===p.user_id),V=p.user_id,H=i[V]??(i[V]={name:(F==null?void 0:F.full_name)||p.user_id,deals:0,revenue:0,earned:0,paid:0,approved:0,pending:0});H.deals+=1,H.revenue+=Number(p.deal_value||0),H.earned+=Number(p.commission_amount||0),p.status==="paid"?H.paid+=Number(p.commission_amount||0):p.status==="approved"?H.approved+=Number(p.commission_amount||0):p.status==="pending"&&(H.pending+=Number(p.commission_amount||0))}),ne(`commission-earnings-${u}.csv`,Object.values(i).map(p=>({Name:p.name,"Deals won":p.deals,Revenue:p.revenue,"Commission earned":p.earned,Paid:p.paid,Approved:p.approved,Pending:p.pending,"Effective rate %":p.revenue>0?Number((p.earned/p.revenue*100).toFixed(2)):0})))}},{key:"reconcile",title:"Score vs Earnings",desc:"Spot people earning without matching execution.",icon:ye,run:()=>{if(h.length===0)return q.success("Nothing to export");const i={};o.forEach(p=>{i[p.user_id]=(i[p.user_id]||0)+Number(p.commission_amount||0)}),ne(`score-vs-earnings-${u}.csv`,h.map(p=>{const F=i[p.user_id]||0,V=Number(p.revenue||0),H=F>0&&p.kpi_score<40?"Earning despite low score":F===0&&V>0?"Revenue without commission - check structure":"OK";return{Name:p.full_name,Role:p.role,"Performance Score":p.kpi_score,"Deals won":p.deals_closed,Revenue:V,"Commission earned":F,Flag:H}}))}}],L=h.reduce((i,p)=>i+Number(p.revenue||0),0),P=h.reduce((i,p)=>i+Number(p.deals_closed||0),0),R=h.reduce((i,p)=>i+Number(p.tasks_completed||0),0),v=h.length?Math.round(h.reduce((i,p)=>i+Number(p.conversion_rate||0),0)/h.length):0,z=[...h].sort((i,p)=>Number(p.revenue||0)-Number(i.revenue||0))[0],ie=[{label:"Revenue",value:w(L)},{label:"Deals won",value:String(P)},{label:"Conversion",value:`${v}%`},{label:"Tasks done",value:String(R)}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"What happened in this period"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.start," to ",s.end,z?` · Best month so far for ${z.full_name}`:""]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:ie.map(i=>e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:i.label}),e.jsx("p",{className:"text-lg font-semibold tabular-nums",children:i.value})]},i.label))}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[h.length," ",h.length===1?"person":"people"," included.",v>=30?" Conversion is healthy - keep the same follow-up rhythm.":" Conversion is the weakest link - more follow-ups on
1new leads will move it."]})]})}),e.jsxs(ns,{label:"Filter and download the detail",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(ve,{value:c,onValueChange:l,children:[e.jsx(fe,{className:"w-[200px]",children:e.jsx(je,{placeholder:"Team"})}),e.jsxs(Ne,{children:[e.jsx(G,{value:"__all",children:"All teams"}),m.map(i=>e.jsx(G,{value:i,children:i},i))]})]}),e.jsxs(ve,{value:d,onValueChange:x,children:[e.jsx(fe,{className:"w-[240px]",children:e.jsx(je,{placeholder:"Person"})}),e.jsxs(Ne,{children:[e.jsx(G,{value:"__all",children:"Everyone"}),a.map(i=>e.jsx(G,{value:i.user_id,children:i.full_name},i.user_id))]})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:S.map(i=>{const p=i.icon;return e.jsx(b,{children:e.jsxs(_,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(p,{className:"h-4 w-4 text-primary"})," ",i.title]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i.desc}),e.jsxs(y,{size:"sm",variant:"outline",onClick:i.run,className:"w-full",children:[e.jsx(st,{className:"h-3.5 w-3.5 mr-1"})," Download CSV"]})]})},i.key)})})]})]})}function gr({open:s,onOpenChange:t,range:a}){return e.jsx(hs,{open:s,onOpenChange:t,children:e.jsxs(ps,{size:"lg",className:"max-h-[85vh] overflow-y-auto",children:[e.jsxs(gs,{children:[e.jsx(vs,{children:"Export report"}),e.jsxs(Os,{children:["Download the numbers for ",a.start," to ",a.end,"."]})]}),e.jsx(pr,{range:a})]})})}const Ps=50,vr="event_id, org_id, actor_id, entity_type, entity_id, event_type, event_category, event_action, event_source, metadata, severity, created_at";function fr(s={}){const t=X(),a=$s(),n=["operational_event_feed",t,s],r=mt({queryKey:n,enabled:!!t,initialPageParam:null,queryFn:async({pageParam:o})=>{var x,m;let c=U.from("crm_operational_events").select(vr).eq("org_id",t).order("created_at",{ascending:!1}).order("event_id",{ascending:!1}).limit(Ps);if(o){const h=`"${o.createdAt}"`;c=c.or(`created_at.lt.${h},and(created_at.eq.${h},event_id.lt.${o.eventId})`)}s.actorId&&(c=c.eq("actor_id",s.actorId)),s.entityType&&(c=c.eq("entity_type",s.entityType)),s.entityId&&(c=c.eq("entity_id",s.entityId)),(x=s.categories)!=null&&x.length&&(c=c.in("event_category",s.categories)),(m=s.severities)!=null&&m.length&&(c=c.in("severity",s.severities)),s.excludeBackfill&&(c=c.neq("event_source","backfill"));const{data:l,error:d}=await c;if(d)throw d;return l??[]},getNextPageParam:o=>{if(o.length<Ps)return;const c=o[o.length-1];return{createdAt:c.created_at,eventId:c.event_id}},staleTime:15e3});return f.useEffect(()=>{if(!t)return;const o=U.channel(`ops_events:${t}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"crm_operational_events",filter:`org_id=eq.${t}`},c=>{var d,x;const l=c.new;s.actorId&&l.actor_id!==s.actorId||s.entityType&&l.entity_type!==s.entityType||s.entityId&&l.entity_id!==s.entityId||(d=s.categories)!=null&&d.length&&!s.categories.includes(l.event_category)||(x=s.severities)!=null&&x.length&&!s.severities.includes(l.severity)||s.excludeBackfill&&l.event_source==="backfill"||a.setQueryData(n,m=>{if(!m)return m;const h=[l,...m.pages[0]??[]];return{...m,pages:[h,...m.pages.slice(1)]}})}).subscribe();return()=>{U.removeChannel(o)}},[t,JSON.stringify(s)]),r}const jr=[{key:"all",label:"All"},{key:"sales",label:"Sales"},{key:"engagement",label:"Engagement"},{key:"task",label:"Tasks"},{key:"pipeline",label:"Pipeline"},{key:"meeting",label:"Meetings"}];function Nr({actorId:s,entityType:t,entityId:a}){const[n,r]=f.useState("all"),[o,c]=f.useState(!1),[l,d]=f.useState(!0),x=f.useMemo(()=>({actorId:s??void 0,entityType:t,entityId:a,categories:n==="all"?void 0:[n],severities:o?["warning","critical"].slice():void 0,excludeBackfill:l}),[s,t,a,n,o,l]),m=fr(x),h=f.useMemo(()=>{var C;return((C=m.data)==null?void 0:C.pages.flat())??[]},[m.data]),u=f.useMemo(()=>[...new Set(h.map(C=>C.actor_id).filter(Boolean))],[h]),k=kr(u),j=f.useMemo(()=>_r(h),[h]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(b,{className:"p-3 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx(Ha,{className:"h-3.5 w-3.5 text-muted-foreground mr-1"}),jr.map(C=>e.jsx(as,{active:n===C.key,onClick:()=>r(C.key),children:C.label},C.key)),e.jsx("span",{className:"w-px h-4 bg-border mx-1"}),e.jsxs(as,{active:o,onClick:()=>c(C=>!C),tone:"warning",children:[e.jsx(ue,{className:"h-3 w-3 mr-1 inline"})," Risk only"]}),e.jsx(as,{active:l,onClick:()=>d(C=>!C),children:"Hide backfill"})]}),e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>m.refetch(),disabled:m.isFetching,children:e.jsx(ms,{className:B("h-3.5 w-3.5",m.isFetching&&"animate-spin")})})]}),m.isLoading?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(_s,{className:"h-5 w-5 animate-spin text-primary"})}):h.length===0?e.jsxs(b,{className:"p-10 text-center",children:[e.jsx(zt,{className:"h-6 w-6 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm font-medium",children:"No events yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Operational events will stream here in realtime as your team works."})]}):e.jsx("div",{className:"space-y-5",children:j.map(([C,$])=>e.jsx(br,{day:C,items:$,actors:k},C))}),m.hasNextPage&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>m.fetchNextPage(),disabled:m.isFetchingNextPage,children:[m.isFetchingNextPage?e.jsx(_s,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}
1):null,"Load more"]})})]})}function br({day:s,items:t,actors:a}){return e.jsxs("section",{children:[e.jsx("h4",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2 px-1",children:s}),e.jsx(b,{className:"divide-y divide-border/40",children:t.map(n=>e.jsx(yr,{ev:n,actor:n.actor_id?a[n.actor_id]:void 0},n.event_id))})]})}function yr({ev:s,actor:t}){const a=pa[s.event_type],n=(a==null?void 0:a.sign)??"neutral",r=n==="positive"?"text-success bg-success/10":n==="negative"?"text-destructive bg-destructive/10":"text-muted-foreground bg-muted",o=new Date(s.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),c=s.metadata??{},l=Object.entries(c).filter(([d,x])=>x!=null&&typeof x!="object").slice(0,3);return e.jsxs("div",{className:"flex items-start gap-3 px-3 py-2.5 text-sm",children:[e.jsx("div",{className:B("rounded-full p-1.5 shrink-0",r),children:e.jsx(wr,{sign:n})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:(a==null?void 0:a.label)??s.event_type}),a&&e.jsx(O,{variant:"secondary",className:"text-[9px] py-0 px-1 h-4",children:a.category}),s.severity!=="info"&&e.jsxs(O,{variant:s.severity==="critical"?"destructive":"outline",className:"text-[9px] py-0 px-1 h-4 gap-0.5",children:[e.jsx(ue,{className:"h-2.5 w-2.5"})," ",s.severity]}),s.event_source==="backfill"&&e.jsx(O,{variant:"outline",className:"text-[9px] py-0 px-1 h-4 opacity-60",children:"backfilled"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(en,{actorId:s.actor_id,eventSource:s.event_source,eventType:s.event_type,size:"xs"}),e.jsxs("span",{children:["· ",s.entity_type]}),e.jsxs("span",{children:["· ",o]})]}),l.length>0&&e.jsx("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:l.map(([d,x])=>e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted/60 text-muted-foreground",children:[d,": ",e.jsx("span",{className:"text-foreground font-medium",children:String(x)})]},d))})]})]})}function wr({sign:s}){return s==="positive"?e.jsx(Ae,{className:"h-3 w-3"}):s==="negative"?e.jsx(us,{className:"h-3 w-3"}):e.jsx(Ya,{className:"h-3 w-3"})}function as({active:s,onClick:t,children:a,tone:n}){return e.jsx("button",{type:"button",onClick:t,className:B("px-2 py-0.5 rounded-full text-xs font-medium transition-colors",s?n==="warning"?"bg-warning/15 text-warning":"bg-primary/15 text-primary":"bg-muted/40 text-muted-foreground hover:bg-muted/70"),children:a})}function _r(s){const t=n=>{const r=new Date,o=new Date;o.setDate(r.getDate()-1);const c=(l,d)=>l.toDateString()===d.toDateString();return c(n,r)?"Today":c(n,o)?"Yesterday":n.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})},a=new Map;for(const n of s){const r=t(new Date(n.created_at)),o=a.get(r)??[];o.push(n),a.set(r,o)}return[...a.entries()]}function kr(s){const t=X(),{data:a}=oe({queryKey:["actor_map",t,[...s].sort().join(",")],enabled:!!t&&s.length>0,staleTime:5*6e4,queryFn:async()=>{if(s.length===0)return{};const{data:n}=await U.from("users").select("id, auth_id, full_name, first_name, last_name, avatar_url").or(`id.in.(${s.join(",")}),auth_id.in.(${s.join(",")})`),r={};return(n??[]).forEach(o=>{const c=o.full_name||[o.first_name,o.last_name].filter(Boolean).join(" ")||"Team Member";o.id&&(r[o.id]={name:c,avatar_url:o.avatar_url??null}),o.auth_id&&(r[o.auth_id]={name:c,avatar_url:o.avatar_url??null})}),r}});return a??{}}const Cr={task_completed:se.task_complete,task_overdue:se.overdue_task,deal_updated:se.deal_updated,deal_stage_moved:se.deal_updated,deal_stale:se.stale_deal,followup_completed:se.followup_done,followup_missed:se.missed_followup,call_logged:se.call_logged,lead_converted:se.lead_converted,meeting_attended:se.meeting_attended,meeting_missed:-3,contact_cold:-1},Sr=[{signal:"Task completed / overdue",individual:"Task Execution",org:"Follow-up Discipline"},{signal:"Deal updated / stale",individual:"Sales Activity",org:"Pipeline Hygiene"},{signal:"Follow-up done / missed",individual:"Workflow Discipline",org:"Follow-up Discipline"},{signal:"Call logged / meeting attended",individual:"Sales Activity",org:"Responsiveness"},{signal:"Lead converted / contact cold",individual:"Customer Engagement",org:"Engagement Volume"}];function Tr(){const s=X(),t=new Date(Date.now()-30*864e5).toISOString(),{data:a}=oe({queryKey:["activity_score_impact",s,t],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[{data:n},{data:r}]=await Promise.all([U.from("crm_operational_events").select("event_type").eq("org_id",s).gte("created_at",t).limit(1e4),U.from("commissions").select("commission_amount").eq("org_id",s).gte("created_at",t).limit(1e4)]);let o=0,c=0,l=0;
1(n??[]).forEach(x=>{const m=Cr[x.event_type];typeof m=="number"&&(m>=0?o+=m:c+=m),x.event_type==="deal_won"&&(l+=1)});const d=(r??[]).reduce((x,m)=>x+Number(m.commission_amount||0),0);return{pos:o,neg:c,net:o+c,count:(n==null?void 0:n.length)??0,dealsWon:l,earned:d}}});return e.jsx(b,{children:e.jsxs(_,{className:"p-4 flex items-center gap-4 flex-wrap",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last 30 days score impact"}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["(",(a==null?void 0:a.count)??0," events)"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-1 text-emerald-600",children:[e.jsx(Ae,{className:"h-3.5 w-3.5"})," +",(a==null?void 0:a.pos)??0]}),e.jsxs("span",{className:"flex items-center gap-1 text-rose-600",children:[e.jsx(us,{className:"h-3.5 w-3.5"})," ",(a==null?void 0:a.neg)??0]}),e.jsxs("span",{className:"font-medium tabular-nums",children:["Net ",(a==null?void 0:a.net)??0]})]}),((a==null?void 0:a.dealsWon)??0)>0&&e.jsxs("span",{className:"text-xs text-muted-foreground border-l pl-3 ml-1",children:[a==null?void 0:a.dealsWon," deal-won ",(a==null?void 0:a.dealsWon)===1?"event":"events"," -> â¦",((a==null?void 0:a.earned)??0).toLocaleString()," in commissions"]}),e.jsx("div",{className:"flex-1"}),e.jsx(y,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs(I,{to:"?tab=overview",children:["See scores ",e.jsx(xs,{className:"h-3.5 w-3.5 ml-1"})]})})]})})}function Dr(){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Activity Intelligence"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Realtime stream of every operational event in the CRM. Every event you see below is a signal that nudges the Individual Performance Score and Org Health Score up or down."})]}),e.jsx(Tr,{}),e.jsx(qe,{title:"Event -> score signal mapping",subtitle:"Use the Risk only filter to isolate events that are pulling the scores down.",rows:Sr}),e.jsx(Nr,{})]})}function Mr({open:s,onOpenChange:t}){const{hasPermission:a}=qt("performance.manage");return e.jsx(hs,{open:s,onOpenChange:t,children:e.jsxs(ps,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(gs,{children:[e.jsx(vs,{children:"Activity intelligence"}),e.jsx(Os,{children:"The work the numbers are built from - every recorded event, what it counted towards, and whether performance is being measured against anything."})]}),a?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ga,{}),e.jsx(Dr,{})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"You need permission to manage performance to inspect the activity stream."})]})})}const it=[{key:"overview",label:"Overview"},{key:"goals",label:"Goals"},{key:"team",label:"Team"}];function Pr(){const s=new Date,t=a=>`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`;return{start:t(new Date(s.getFullYear(),s.getMonth(),1)),end:t(new Date(s.getFullYear(),s.getMonth()+1,0))}}const $r={individual:"team",activity:"overview",kpis:"goals",targets:"goals",rewards:"team",recognition:"team",competitions:"team",earnings:"team",reports:"goals"};function Ar(s){const t=s||"overview",a=$r[t]||t;return it.some(n=>n.key===a)?a:"overview"}function Ql(){var L,P,R;const[s,t]=Be(),a=ut(),n=Ar(s.get("tab")),r=s.get("user"),{isAdminOrManager:o,isLoading:c}=ds(),l=o,d=Ye(),x=Bt(),[m,h]=f.useState(Pr()),[u,k]=f.useState(!1),[j,C]=f.useState(!1),[$,E]=f.useState(0),W=()=>{const v=new URLSearchParams(s);v.delete("user"),v.set("tab","team"),t(v,{replace:!0})},T=Xa({canManage:l,roleLoading:c,goalLoading:d.isLoading,hasGoal:((L=d.data)==null?void 0:L.hasTarget)??!1,needsAttention:!!((P=d.data)!=null&&P.hasTarget&&(((R=d.data)==null?void 0:R.overall)??100)<100),canReviewAttention:x.canOpen("deals")}),A=()=>{const v=new URLSearchParams(s);v.set("tab","goals"),v.delete("user"),t(v,{replace:!0}),E(z=>z+1)},g=()=>{if(T.intent==="review-pipeline-attention"){a("/pipeline?view=attention");return}A()},S=v=>{const z=new URLSearchParams(s);z.set("tab",v),v!=="team"&&z.delete("user"),t(z,{replace:!0})};return e.jsxs("div",{className:"p-page lg:p-page-lg max-w-[1400px] mx-auto
1space-y-5",children:[e.jsx(Qa,{title:"Performance",description:Ga("sales_performance"),module:"performance",primaryLabel:T.label,primaryIcon:e.jsx(pe,{className:"h-4 w-4"}),primaryAllowed:T.allowed,primaryDisabled:T.disabled,onPrimary:g,secondaryActions:Ua([{key:"performance.report.export",kind:"utility",label:"Export report",icon:e.jsx(st,{className:"h-4 w-4"}),onClick:()=>k(!0)},{key:"performance.activity",kind:"utility",label:"Activity intelligence",icon:e.jsx($e,{className:"h-4 w-4"}),onClick:()=>C(!0),when:l},{key:"performance.commissions",kind:"resource",label:"Commissions",icon:e.jsx(Za,{className:"h-4 w-4"}),onClick:()=>a("/commissions"),when:l}])}),e.jsxs(xt,{value:n,onValueChange:S,children:[e.jsx(ht,{className:"flex-wrap h-auto justify-start gap-1",children:it.map(v=>e.jsx(pt,{value:v.key,children:v.key==="team"&&!l?"My performance":v.label},v.key))}),e.jsx("div",{className:"mt-3",children:e.jsx(Js,{context:e.jsx(tn,{range:m,onChange:h})})}),e.jsx(Xe,{value:"overview",className:"mt-4",children:e.jsx(An,{range:m})}),e.jsx(Xe,{value:"team",className:"mt-4",children:l?r?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(y,{size:"sm",variant:"ghost",onClick:W,children:[e.jsx(Ja,{className:"h-4 w-4 mr-1"})," Back to team"]}),e.jsx(Ds,{range:m,canManage:l})]}):e.jsx(Jn,{range:m,canManage:l}):e.jsx(Ds,{range:m,canManage:!1})}),e.jsx(Xe,{value:"goals",className:"mt-4",children:e.jsx(hr,{range:m,canManage:l,roleLoading:c,openFormSignal:$})})]}),e.jsx(gr,{open:u,onOpenChange:k,range:m}),e.jsx(Mr,{open:j,onOpenChange:C})]})}export{$r as LEGACY_PERFORMANCE_TABS,it as PERFORMANCE_TABS,Pr as currentMonthRange,Ql as default,Ar as resolvePerformanceTab};
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.