PageSourceSearch

https://deliverimates-production.up.railway.app/assets/Payroll-X-S6kqYf.js

js deliverimates-production.up.railway.app collected 2026-10-03 12:12:09 UTC 64,200 bytes, 1 lines download raw bytes

1import{c as Lt,v as bs,o as qs,s as Gs,a8 as Ks,q as os,l as Ws,r as l,z as Qs,w as ss,j as e,L as xs,J as ts,an as as,K as ns,M as is,N as Rt,ac as Ve,B as J,ad as Js,ae as Xs,af as Zs,ag as et,ah as ys,ak as Ss,al as Ds,T as Se,am as Ls,a6 as ws,g as _t,i as st,C as vs,D as It,aa as At,t as Et,I as $e,a9 as Mt,b as Rs,aE as _s,U as Is,R as Pt,d as Tt,e as Ut,aF as Ot}from"./index-Db4qfLtJ.js";import{u as tt}from"./use-payroll-uploads-BFx7I1mU.js";import{u as at}from"./use-payroll-violations-DCxWlOdb.js";import{p as nt}from"./payroll-driver-match-access-mPSUuYGT.js";import{u as it,a as ot,b as rt,L as lt,c as Ft}from"./use-link-da-Dcv52Gyw.js";import{b as ct}from"./use-drivers-viEKgcBv.js";import{B as dt}from"./BulkSmsDrawer-8gogrweV.js";import{M as zt}from"./MonoValue-K8CjOq_0.js";import{C as As,R as Es,a as Ms,b as Ps}from"./RuleCard-Cb3E5TYZ.js";import{c as $t,A as ee,E as Ts,S as Ht,b as fs}from"./overlays-DOpP7ZKe.js";import{P as Vt,C as Bt}from"./layout-D6zeVp_v.js";import{s as js,Q as Us}from"./QueryErrorPanel-B1gDa5_u.js";import{t as Os,C as Yt,a as qt,V as Fs}from"./violation-checklist-config-mWXPZHna.js";import{l as Le,P as Gt}from"./PayrollTabsInk-DFY962GQ.js";import{f as Be}from"./format-DyStx0k9.js";import{e as zs}from"./export-csv-C1JN8RIJ.js";import{T as rs,a as ls,b as X,c as M,d as cs,e as S}from"./table-CDUJ619m.js";import{B as Y}from"./badge-B13RZfEt.js";import{T as Kt,a as Wt,b as $s,c as Hs}from"./tabs-C0SDnV8_.js";import{S as De}from"./skeleton-8NjDJt9K.js";import{M as ce}from"./MetricCard-DTTtRifH.js";import{l as mt,G as ut}from"./GlossaryTerm-DHragS6J.js";import{C as Qt}from"./chevron-right-D4zIy9sL.js";import{C as Jt}from"./ConfirmActionDialog-COVjcmTM.js";import{u as Xt,H as Zt,a as ea}from"./HelpPanel-CFzkYqKF.js";import{u as sa}from"./use-column-mappings-DiTWoRTD.js";import{u as ta}from"./use-extension-bridge-C6-MGhoM.js";import{U as aa}from"./upload-BJ-_IMcl.js";import{C as na}from"./circle-alert-DtE7BSGF.js";import{D as ia}from"./dollar-sign-Dd_koKVA.js";import{D as Vs}from"./download-CboRdteu.js";import{C as oa}from"./circle-x-Dgr4cywE.js";import"./use-company-stations-BCs9zpu9.js";import"./use-station-scoped-query-DTYNhmkw.js";import"./SmsSuccessOverlay-DXCimrmt.js";import"./sms-segments-BY9ukeHt.js";import"./sms-time-format-JI3MblTm.js";import"./sms-variables-CmcTt9MZ.js";import"./use-scheduled-sms-D79ayTKp.js";import"./clipboard-list-BV57WbME.js";import"./send-BKG_37I8.js";import"./external-link-BdKUXdmw.js";import"./circle-question-mark-CvQXntU2.js";import"./zap-BZn7f7MY.js";const ra=[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]],la=Lt("arrow-left-right",ra);function ht(a,r=null){const w=bs(),p=[...new Set(a.filter(Boolean))].sort(),_=nt(w.data);return qs({queryKey:os.payroll.driverMatches(p,r,_),queryFn:async()=>{if(w.isError||!w.data)throw w.error instanceof Error?w.error:new Error("Unable to verify payroll access");const{data:{session:I}}=await Gs.auth.getSession();if(!I)throw new Error("Not authenticated");const i=await fetch(`${Ks}/api/payroll/driver-matches`,{method:"POST",headers:{Authorization:`Bearer ${I.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({names:p,...r?{upload_id:r}:{}})});if(!i.ok){let u={error:"Fetch failed"};try{u=await i.json()}catch(o){console.error("[payroll driver matches] failed to parse error response",o)}throw new Error(u.error||"Failed to resolve driver matches")}const U=await i.json(),y={};for(const[u,o]of Object.entries(U.matches||{}))y[u]={daId:o.da_id,fullName:o.full_name,phone:o.phone,stationCode:o.station_code??null,matchConfidence:o.match_confidence,matchMethod:o.match_method};return y},enabled:!w.isPending&&p.length>0,staleTime:300*1e3,refetchOnMount:"always"})}const es=2,ca={NON_LUNCH_MOBILE_PUNCH:"Mobile punch outside lunch",PAYROLL_NOT_IN_FLEX:"Paid but not on a route",UNDER_6HR_PER_DAY:"Under six hours in a day",MISSING_MEAL_PUNCH:"Meal punch missing",DELIVERY_LUNCH_GAP_OVER_1HR:"Delivery gap over an hour",MISSING_OUT_PUNCH:"Never punched out",SKIPPED_LUNCH_FIRST_5HR:"No lunch in the first five hours",FLEX_PAYROLL_LUNCH_MISMATCH:"Lunch does not match Amazon",LUNCH_OVER_1HR:"Lunch over an hour",OVER_12HR_PER_DAY:"Over twelve hours in a day",INSUFFICIENT_REST:"Less than ten hours rest",OVER_60HR_ROLLING:"Over sixty hours in a rolling week",LUNCH_UNDER_3
10_MIN:"Meal break under thirty minutes",CONSECUTIVE_7_DAYS:"Seven consecutive workdays"},gs=["LUNCH_UNDER_30_MIN","MISSING_MEAL_PUNCH","SKIPPED_LUNCH_FIRST_5HR","FLEX_PAYROLL_LUNCH_MISMATCH","LUNCH_OVER_1HR","DELIVERY_LUNCH_GAP_OVER_1HR","OVER_12HR_PER_DAY","OVER_60HR_ROLLING","CONSECUTIVE_7_DAYS","INSUFFICIENT_REST","UNDER_6HR_PER_DAY","PAYROLL_NOT_IN_FLEX","MISSING_OUT_PUNCH","NON_LUNCH_MOBILE_PUNCH"],da=new Set(["LUNCH_UNDER_30_MIN","MISSING_MEAL_PUNCH","SKIPPED_LUNCH_FIRST_5HR","FLEX_PAYROLL_LUNCH_MISMATCH","LUNCH_OVER_1HR","DELIVERY_LUNCH_GAP_OVER_1HR"]),ma=new Set(["OVER_12HR_PER_DAY","OVER_60HR_ROLLING","CONSECUTIVE_7_DAYS","INSUFFICIENT_REST","UNDER_6HR_PER_DAY","PAYROLL_NOT_IN_FLEX"]),ua=new Set(["MISSING_OUT_PUNCH","NON_LUNCH_MOBILE_PUNCH"]),Bs=new Set(["MISSING_MEAL_PUNCH","FLEX_PAYROLL_LUNCH_MISMATCH","DELIVERY_LUNCH_GAP_OVER_1HR","PAYROLL_NOT_IN_FLEX"]),ha={NON_LUNCH_MOBILE_PUNCH:"paid time started away from the station",PAYROLL_NOT_IN_FLEX:"hours with no route behind them",MISSING_MEAL_PUNCH:"premium owed",SKIPPED_LUNCH_FIRST_5HR:"premium owed",LUNCH_OVER_1HR:"unpaid time counted as paid",MISSING_OUT_PUNCH:"the day cannot be closed",OVER_12HR_PER_DAY:"wage-hour exposure",INSUFFICIENT_REST:"unsafe to dispatch",OVER_60HR_ROLLING:"can't dispatch tomorrow"};function He(a){return ca[a]??a.toLowerCase().replace(/_/g," ")}const pa=a=>`$${a.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`;function Ns(a){return a instanceof Error?a.message:"Please try again."}function xa(){const a=bs(),{toast:r}=Ws(),w=it(),p=ot(),_=l.useRef(null),[g]=Qs(),I=g.get("date"),i=/^\d{4}-\d{2}-\d{2}$/.test(I??"")?I:null,{uploads:U,isLoading:y,isError:u,isUnavailable:o,refetch:T}=tt(null,!0,i),x=i?U.find(t=>t.status==="completed"&&t.dateRangeStart<=i&&t.dateRangeEnd>=i)??null:U[0]??null,D=!!(i&&U.length>0&&!x),j=x?`/dashboard/payroll?view=full&upload_id=${encodeURIComponent(x.id)}`:"/dashboard/payroll?view=full",{allViolations:d,isLoading:C,isError:A,refetch:O}=at(x?.id??null),L=l.useMemo(()=>i?d.filter(t=>t.violationDate===i):d,[d,i]),ne=l.useMemo(()=>[...new Set(L.map(t=>t.daName).filter(Boolean))],[L]),{data:$,isError:Re,refetch:Ye}=ht(ne,x?.id??null),[E,ye]=l.useState(null),[P,se]=l.useState(null),[ve,_e]=l.useState(""),te=rt(),{allDrivers:je,isLoading:Ie,isError:de,isAccessDenied:ds,refetch:R}=ct({enabled:E!==null}),qe=l.useMemo(()=>{const t=new Map;for(const f of d){if(!f.positionId)continue;const m=t.get(f.daName)??new Set;m.add(f.positionId),t.set(f.daName,m)}return new Map([...t].map(([f,m])=>[f,m.size===1?[...m][0]:null]))},[d]),W=l.useMemo(()=>{const t=ve.trim().toLowerCase(),f=je.filter(N=>N.isActive),m=t?f.filter(N=>N.fullName.toLowerCase().includes(t)):f,b=E?Le(E.daName):"";return[...m].sort((N,c)=>{const v=b&&Le(N.fullName)===b?0:1,B=b&&Le(c.fullName)===b?0:1;return v-B||N.fullName.localeCompare(c.fullName)}).slice(0,50)},[je,ve,E]),me=(t,f="link")=>{_e(""),se(null),ye({daName:t,positionId:qe.get(t)??null,intent:f})},be=t=>{E?.positionId&&te.mutate({positionId:E.positionId,amazonAssociateId:t.associateId},{onSuccess:()=>{r({title:E.intent==="relink"?"Driver relinked":"Driver linked",description:`${E.daName} → ${t.fullName}`}),se(null),ye(null)},onError:f=>{r({title:"Link failed",description:Ns(f),variant:"destructive"})}})},we=t=>ss(a.data,"payroll.manage",{stationCode:t,operation:"mutate"})&&ss(a.data,"messages.payroll.send",{stationCode:t,operation:"mutate"}),Ge=(a.data?.stations??[]).some(t=>we(t.station_code)),ue=(a.data?.stations??[]).some(t=>ss(a.data,"payroll.manage",{stationCode:t.station_code,operation:"mutate"})),Ce=a.data?.company_scope?.payroll_manage===!0,Ae=(a.data?.stations??[]).filter(t=>we(t.station_code)).map(t=>t.station_code.trim().toUpperCase()).sort((t,f)=>t.localeCompare(f)).join("|"),he=[a.data?.user.id??"__no_user__",a.data?.user.access_version??0,Ae,a.isPending?"pending":a.isError?"error":"ready"].join(":"),ie=a.isPending?"Checking payroll messaging permission":a.isError||!a.data?"Couldn't verify payroll messaging permission":Ge?null:"You need Payroll manager and messaging permissions to message drivers",Ee=ne.length===0?"These findings carry no driver name":$?null:Re?"Roster matching unavailable — use Retry roster matching above":"Checking who these names match on the roster",[V,oe]=l.useState(null),[pe,Me]=l.useState(()=>new Set),Pe=async t=>
1{if(t){if(!t.name.toLowerCase().endsWith(".csv")){r({title:"Choose an ADP CSV file",variant:"destructive"});return}try{const f=await w.mutateAsync({file:t,systemName:"ADP"});r({title:"Payroll analyzed",description:`${f.summary.totalDAs} drivers checked · ${f.summary.totalViolations+f.summary.totalWarnings} flags`})}catch(f){r({title:"Upload failed",description:Ns(f),variant:"destructive"})}finally{_.current&&(_.current.value="")}}},Ke=async()=>{if(x)try{const t=await p.mutateAsync(x.id);r({title:"Payroll re-analyzed",description:`${t.summary.totalDAs} drivers checked · ${t.summary.totalViolations+t.summary.totalWarnings} flags`})}catch(t){r({title:"Re-analysis failed",description:Ns(t),variant:"destructive"})}};l.useEffect(()=>{o&&(oe(null),se(null),ye(null),Me(new Set))},[o]),l.useEffect(()=>{!V||V.accessScopeKey===he||oe(null)},[he,V]);const F=js(A||u,L),ms=l.useMemo(()=>{const t=new Map;for(const m of L){const b=t.get(m.type);b?b.push(m):t.set(m.type,[m])}const f=[...t.entries()].map(([m,b])=>{const N=new Map;for(const c of b){const v=N.get(c.daName);v?(v.count+=1,v.fines+=c.fineAmount||0,v.findings.push(c),(c.violationDate??"")>
1(v.latest.violationDate??"")&&(v.latest=c)):N.set(c.daName,{name:c.daName,count:1,fines:c.fineAmount||0,latest:c,findings:[c]})}return{type:m,blocking:b.some(c=>c.severity==="VIOLATION"),total:b.length,fines:b.reduce((c,v)=>c+(v.fineAmount||0),0),drivers:[...N.values()].sort((c,v)=>v.count-c.count)}});return f.sort((m,b)=>m.blocking!==b.blocking?m.blocking?-1:1:m.fines!==b.fines?b.fines-m.fines:b.total-m.total),f},[L]),q=new Set(L.map(t=>t.type)),ae=Array.isArray(x?.summaryJson?.missingSigninDates)?x.summaryJson.missingSigninDates.filter(t=>typeof t=="string"):[],G=x?.summaryJson?.crossReferenceAvailable!==!0||(i?ae.includes(i):ae.length>0),z=G?gs.filter(t=>Bs.has(t)&&!q.has(t)).map(He):[],Te=gs.filter(t=>!q.has(t)&&!(G&&Bs.has(t))).map(He),We=gs.length-z.length,Ue=x?.summaryJson?.crossReferenceAvailable!==!0?"Amazon cross-reference data was unavailable for this upload.":i?`Amazon coverage is missing for ${i}.`:`Amazon coverage is missing for ${ae.length} ${ae.length===1?"day":"days"} in this period.`,K=L.filter(t=>da.has(t.type)).length,xe=L.filter(t=>ma.has(t.type)).length,Qe=L.filter(t=>ua.has(t.type)).length,Je=K+xe+Qe,us=[{label:"meal breaks",value:K,tone:"blocking"},{label:"hours & overtime",value:xe,tone:"drifting"},{label:"punch integrity",value:Qe,tone:"neutral"},...Je<L.length?[{label:"other checks",value:L.length-Je,tone:"info"}]:[]],fe=$?ne.filter(t=>!$[t]?.daId&&$[t]?.matchMethod!=="inactive"):[],re=t=>!t?.daId||!t.phone?!1:t.stationCode?we(t.stationCode):Ge,Oe=(t,f)=>{const m=$?.[t.name];if(!m?.daId||!m.phone||!re(m))return null;const b=t.findings.flatMap(v=>{const B=v.detailsJson?.action;return typeof B=="string"&&B.trim()?[v.violationDate?`${v.violationDate}: ${B.trim()}`:B.trim()]:typeof v.message=="string"&&v.message.trim()?[v.message.trim()]:[]}),N=t.latest.detailsJson?.durationMin,c=typeof N=="number"&&Number.isFinite(N)?N:null;return{daId:m.daId,fullName:m.fullName||t.name,phone:m.phone,alertLevel:t.latest.severity==="VIOLATION"?"critical":"warning",violationReason:f,actionText:[...new Set(b)].join("; ")||void 0,date:t.latest.violationDate??void 0,minutes:c}},ge=(t,f)=>{const m=new Map;for(const b of t){const N=Oe(b,f);if(!N?.daId)continue;const c=m.get(N.daId);if(!c){m.set(N.daId,N);continue}const v=N.date&&(!c.date||N.date>c.date)?N:c,B=[...new Set([c.actionText,N.actionText].filter(Boolean))].join("; ");m.set(N.daId,{...v,alertLevel:c.alertLevel==="critical"||N.alertLevel==="critical"?"critical":"warning",actionText:B||void 0})}return[...m.values()]},Xe=t=>new Set(t.flatMap(f=>{const m=$?.[f.name];return m?.daId&&m.phone?[m.daId]:[]})).size,Fe=(t,f,m)=>{const b=He(f),N=ge(t,b);N.length!==0&&oe({recipients:N,mode:m,ruleName:b,templateKey:Os(f),accessScopeKey:he})},Z=ue?x?p.isPending?"Payroll is being analyzed":null:"Upload payroll first":"Payroll manager permission required",Ne=ue?w.isPending?"Payroll is being uploaded":null:"Payroll manager permission required";return e.jsxs("div",{className:"mx-auto max-w-[1000px] px-6 py-6",children:[e.jsx(Vt,{title:"Payroll",action:e.jsxs("div",{className:"flex items-center gap-2",children:[Z?e.jsx(ee,{disabled:!0,disabledReason:Z,children:p.isPending?"Analyzing…":"Re-analyze"}):e.jsx(ee,{onClick:()=>{Ke()},children:"Re-analyze"}),Ne?e.jsx(ee,{variant:"accent",disabled:!0,disabledReason:Ne,children:w.isPending?"Uploading…":"Upload ADP CSV"}):e.jsx(ee,{variant:"accent",onClick:()=>_.current?.click(),children:"Upload ADP CSV"}),e.jsx("input",{ref:_,type:"file",accept:".csv,text/csv",className:"sr-only","aria-label":"Upload ADP CSV",onChange:t=>{Pe(t.target.files?.[0])}})]}),scope:y||C?e.jsx("span",{className:"text-faint",children:"counting…"}):o?e.jsx("span",{children:"Upload history unavailable for this access scope"}):F?e.jsx("span",{children:"Payroll check unavailable"}):x?e.jsxs("span",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsxs("span",{children:["Period ",Be(new Date(`${x.dateRangeStart}T12:00:00`),"MMM d")," – ",Be(new Date(`${x.dateRangeEnd}T12:00:00`),"MMM d")]}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsxs("span",{children:[x.totalDAs," drivers on timecards"]}
1),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsxs("span",{children:["analyzed ",Be(new Date(x.createdAt),"h:mm a")]}),(u||A)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx($t,{freshness:"stale",asOf:Be(new Date(x.createdAt),"MMM d, h:mm a")})]})]}):D?e.jsxs("span",{children:["No completed upload covers ",i]}):e.jsx("span",{children:"No payroll uploaded yet"})}),i&&e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-hairline bg-sunk px-4 py-3 text-s4 text-subtle",role:"status",children:[e.jsx("span",{children:D?e.jsxs(e.Fragment,{children:["No completed payroll upload covers ",e.jsx("span",{className:"font-semibold text-ink",children:i}),"."]}):e.jsxs(e.Fragment,{children:["Showing findings for ",e.jsx("span",{className:"font-semibold text-ink",children:i})," only."]})}),e.jsx(xs,{className:"inline-flex min-h-11 items-center font-semibold text-ink underline hover:text-action",to:j,children:D?"View existing uploads":"View full upload"})]}),e.jsx(Gt,{active:"precheck",count:y||C||F||o?void 0:L.length}),x&&!o&&!F&&!(y||C)&&e.jsxs("div",{className:"mb-6 max-w-[640px]",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("span",{className:"font-ink-mono text-[26px] font-semibold leading-none text-ink",children:L.length}),e.jsxs("span",{className:"text-s4 text-subtle",children:["flags this period · ",Te.length," of ",We," executed rules came back clean",z.length>0?` · ${z.length} not verified`:""]})]}),e.jsx(Bt,{className:"mt-3",segments:us})]}),(F||o)&&e.jsx(Ts,{reason:o?"Payroll uploads are unavailable under the current access scope.":u&&A?"Couldn't load payroll upload history or findings.":u?"Couldn't load payroll upload history.":"Couldn't load payroll findings.",onRetry:()=>{(u||o)&&T(),A&&O()},className:"mb-4"}),!o&&!F&&(u||A)&&L.length>0&&e.jsx(Ts,{reason:u?"Payroll upload history may be out of date. The last loaded check remains visible.":"Payroll findings may be out of date. The last loaded check remains visible.",onRetry:()=>{u&&T(),A&&O()},className:"mb-4"}),(y||C)&&L.length===0?e.jsx("div",{className:"overflow-hidden rounded-xl border border-hairline bg-surface",children:e.jsx(Ht,{rows:6})}):o||F?null:D?e.jsx(fs,{kind:"filtered",title:`No payroll findings available for ${i}`,detail:"Existing payroll uploads remain available, but none of the completed uploads covers this date.",action:e.jsx(xs,{className:"text-s4 underline text-subtle hover:text-ink",to:"/dashboard/payroll?view=full",children:"View existing uploads"})}):x?L.length===0?e.jsxs("div",{className:"space-y-4",children:[e.jsx(fs,{kind:z.length>0?"filtered":"clear",title:z.length>0?"Payroll checks are partially verified":"Payroll is ready to review",detail:z.length>0?`${x.totalDAs} drivers checked — no flags found in ${We} executed rules. ${Ue}`:`${x.totalDAs} drivers checked — no wage-hour flags found.`}),e.jsx(As,{names:Te}),z.length>0&&e.jsxs("div",{className:"rounded-xl border border-hairline bg-sunk px-4 py-3 text-s3 text-subtle",role:"status",children:[e.jsxs("span",{className:"font-semibold text-ink",children:[z.length," ",z.length===1?"rule was":"rules were"," not verified"]})," — ",z.join(", "),". ",Ue]})]}):e.jsxs("div",{className:"space-y-4",children:[Re&&!$&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-hairline bg-sunk px-4 py-3",role:"alert",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-s3 font-semibold text-ink",children:"Couldn’t match payroll names to the roster"}),e.jsx("p",{className:"mt-1 text-s4 text-subtle",children:"Retry to restore Message actions. Names with no confident match will then show Link driver beside the name."})]}),e.jsx(ee,{onClick:()=>{Ye()},children:"Retry roster matching"})]}),ms.map(t=>{const m=Os(t.type)===void 0,b=ie?Xe(t.drivers):ge(t.drivers,He(t.type)).length,N=`Message${b>0?` ${b}`:""}${m?" · pick wording":""}`;return e.jsxs(Es,{name:He(t.type),count:t.total,tone:t.blocking?"blocking":"drifting",consequence:ha[t.type],metricLabel:"Findings",action:ie||Ee?e.jsx(ee,{size:"sm",disabled:!0,disabledReason:ie??Ee,children:N}):b===0?e.jsx(ee,{size:"sm",disabled:!0,disabledReason:"No driver here has both a roster match and a phone number",children:N}):e.jsx(ee,{size:"sm",onClick:()=>Fe(t.drivers,t.type,"bulk"),children:N}),children:[(pe.has(t.type)?t.drivers:t.drivers.slice(0,es)).map(c=>{const v=$?.[c.name],B=ie??Ee??(v?.matchMethod==="inactive"?"Roster record 
1is inactive":v?.daId?v.phone?re(v)?null:"You can't message this driver's station":"No phone number on file":"Link this ADP name to a roster driver first");return e.jsx(Ms,{evidence:c.fines>0?`${pa(c.fines)} · ${c.latest.message}`:c.latest.message,metric:e.jsx(zt,{tone:t.blocking?"blocking":"drifting",children:c.count}),action:B?e.jsx(ee,{size:"sm",disabled:!0,disabledReason:B,children:"Message"}):e.jsx(ee,{size:"sm",onClick:()=>Fe([c],t.type,"single"),children:"Message"}),children:e.jsxs("span",{children:[c.name,Ce&&$&&!v?.daId&&v?.matchMethod==="inactive"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-s5 font-semibold text-subtle",children:"Inactive roster record"}),e.jsx("button",{type:"button",className:"ml-2 font-semibold text-ink underline hover:text-action",onClick:()=>me(c.name,"relink"),children:"Relink driver"})]}),Ce&&$&&!v?.daId&&v?.matchMethod!=="inactive"&&e.jsx("button",{type:"button",className:"ml-2 font-semibold text-ink underline hover:text-action",onClick:()=>me(c.name),children:"Link driver"})]})},`${t.type}-${c.name}`)}),!pe.has(t.type)&&e.jsx(Ps,{count:Math.max(0,t.drivers.length-es),onClick:()=>Me(c=>new Set(c).add(t.type))})]},t.type)}),fe.length>0&&e.jsxs(Es,{name:"ADP name doesn’t match any roster driver",count:fe.length,tone:"drifting",consequence:"flags can’t reach a driver record until linked",children:[(pe.has("__unmatched__")?fe:fe.slice(0,es)).map(t=>e.jsx(Ms,{evidence:"no roster match · one link fixes future uploads",action:Ce?e.jsx("button",{type:"button",className:"rounded-md border border-hairline bg-surface px-2.5 py-1 text-s5 font-semibold text-ink",onClick:()=>me(t),children:"Link driver"}):void 0,children:t},t)),!pe.has("__unmatched__")&&e.jsx(Ps,{count:Math.max(0,fe.length-es),onClick:()=>Me(t=>new Set(t).add("__unmatched__"))})]}),e.jsx(As,{names:Te}),z.length>0&&e.jsxs("div",{className:"rounded-xl border border-hairline bg-sunk px-4 py-3 text-s3 text-subtle",role:"status",children:[e.jsxs("span",{className:"font-semibold text-ink",children:[z.length," ",z.length===1?"rule was":"rules were"," not verified"]})," — ",z.join(", "),". ",Ue]})]}):e.jsx(fs,{kind:"never-connected",title:"No payroll has been uploaded yet",detail:"Upload an ADP timecard export to check it against the wage-hour rules before you run payroll.",action:e.jsx(xs,{className:"text-s4 underline text-subtle hover:text-ink",to:"/dashboard/payroll?view=full",children:"Upload a timecard"})}),e.jsx(ts,{open:E!==null&&!o,onOpenChange:t=>{t||(se(null),ye(null))},children:e.jsxs(as,{className:"max-w-sm",children:[e.jsxs(ns,{children:[e.jsx(is,{children:E?.intent==="relink"?`Relink "${E.daName}" to an active driver`:`Link "${E?.daName}" to a driver`}),e.jsx(Rt,{children:E?.positionId?E.intent==="relink"?e.jsxs(e.Fragment,{children:["Choose the active driver this payroll name now refers to. Confirming replaces the inactive payroll link for Position ID ",e.jsx("span",{className:"font-ink-mono",children:E.positionId}),"."]}):e.jsxs(e.Fragment,{children:["Select the driver this payroll name refers to (Position ID: ",e.jsx("span",{className:"font-ink-mono",children:E.positionId}),")."]}):"This payroll name does not have one unambiguous position ID to link."})]}),E?.positionId?e.jsx(e.Fragment,{children:ds?e.jsx("p",{className:"rounded-md border border-hairline bg-sunk px-3 py-4 text-sm text-subtle",role:"status",children:"Driver directory unavailable. Drivers access is required to link this payroll row."}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{placeholder:"Search drivers…",value:ve,onChange:t=>_e(t.target.value),autoFocus:!0,disabled:Ie||de}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-md border border-hairline divide-y divide-hairline","aria-live":"polite",children:Ie?e.jsx("p",{className:"py-4 text-center text-sm text-subtle",children:"Loading authorized drivers…"}):de?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-3 py-4 text-center",children:[e.jsx("p",{className:"text-sm text-subtle",children:"Driver directory couldn’t be loaded."}),e.jsx(J,{type:"button",variant:"outline",size:"sm",onClick:()=>{R()},children:"Try again"})]}):e.jsxs(e.Fragment,{children:[W.map(t=>e.jsxs("button",{type:"button","aria-pressed":E?.intent==="relink"?P?.associateId===t.associateId:void 0,className:`flex w-full items-center justify-between gap-3 px-3 py-2.5 text-left text-sm transition-colors hover:bg-sunk ${P?.associateId===t.associateId?"bg-sunk":""}`,onClick:()=>{E?.intent==="relink"?se({associateId:t.associateId,fullName:t.fullName}):be(t)},disabled:te.isPending,children:[e.jsx("span",{className:"font-medium text-ink",children:t.fullName}),t.phone&&e.jsx("span",{className:"shrink-0 font-ink-mono text-xs text-subtle",children:t.phone})]},t.id)),W.length===0&&e.jsx("p",{className:"py-4 text-center text-sm text-subtle",children:je.filter(t=>
1t.isActive).length===0?"No drivers are available in your authorized stations":"No drivers match that search"})]})}),E?.intent==="relink"&&P&&e.jsxs("div",{className:"rounded-md border border-hairline bg-sunk px-3 py-3 text-sm text-subtle",children:[e.jsxs("p",{children:["Replace the inactive link for ",e.jsx("span",{className:"font-medium text-ink",children:E.daName})," with"," ",e.jsx("span",{className:"font-medium text-ink",children:P.fullName}),"?"]}),e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx(J,{type:"button",size:"sm",disabled:te.isPending,onClick:()=>be(P),children:te.isPending?"Relinking…":`Confirm relink to ${P.fullName}`})})]})]})}):e.jsx("p",{className:"text-sm text-subtle",role:"status",children:"Re-upload the ADP CSV if this is unexpected."})]})}),V&&!o&&e.jsx(dt,{open:!0,onClose:()=>oe(null),recipients:V.recipients,sourcePage:"payroll",mode:V.mode,defaultMessageType:V.templateKey,templateMatch:V.templateKey?"mapped":"unmapped",drawerTitle:`Payroll pre-check · ${V.ruleName}`,drawerSubtitle:`${V.recipients.length} ${V.recipients.length===1?"driver":"drivers"}`})]})}function pt({violation:a,onSmsRow:r}){return r?e.jsxs(J,{variant:"ghost",size:"sm",className:"h-7 px-2 gap-1 text-muted-foreground hover:text-foreground","aria-label":`Preview SMS to ${a.daName}`,onClick:w=>{w.stopPropagation(),r(a)},children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"SMS"]}):null}function xt({violation:a,isUnmatched:r,onLinkDriver:w,isLinked:p,onUnlinkDriver:_}){const g=r?.(a.daName)??!1,I=!g&&(p?.(a.daName)??!1);return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[a.daName,g&&w&&e.jsxs(Ss,{children:[e.jsx(Ds,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-warning-solid hover:text-warning-deep","aria-label":`Link ${a.daName} to a driver`,onClick:i=>{i.stopPropagation(),w(a)},children:e.jsx(Se,{className:"h-3.5 w-3.5"})})}),e.jsx(Ls,{children:"Not matched to a driver — click to link"})]}),I&&_&&e.jsxs(Ss,{children:[e.jsx(Ds,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-info-solid hover:text-info-deep","aria-label":`Unlink ${a.daName}`,onClick:i=>{i.stopPropagation(),_(a)},children:e.jsx(lt,{className:"h-3.5 w-3.5"})})}),e.jsx(Ls,{children:"Manually linked to a driver — click to unlink"})]})]})}function fa({violations:a,onSmsRow:r,isUnmatched:w,onLinkDriver:p,isLinked:_,onUnlinkDriver:g}){const[I,i]=l.useState("New"),U=a;return e.jsxs("div",{className:"max-h-80 overflow-y-auto border-t",children:[e.jsx("div",{className:"flex items-center gap-3 px-3 py-2 border-b bg-white",children:e.jsxs(Js,{value:I,onValueChange:i,children:[e.jsx(Xs,{className:"w-[100px] h-7 text-xs",children:e.jsx(Zs,{})}),e.jsxs(et,{children:[e.jsx(ys,{value:"New",children:"New"}),e.jsx(ys,{value:"All",children:"All"})]})]})}),e.jsxs(rs,{children:[e.jsx(ls,{children:e.jsxs(X,{className:"bg-slate-50/80",children:[e.jsx(M,{className:"text-xs font-medium w-10"}),e.jsx(M,{className:"text-xs font-medium",children:"Driver"}),e.jsx(M,{className:"text-xs font-medium w-[110px]",children:"Date"}),e.jsx(M,{className:"text-xs font-medium",children:"Violation"}),e.jsx(M,{className:"text-xs font-medium",children:"Action"}),e.jsx(M,{className:"text-xs font-medium w-[80px]",children:"Status"}),e.jsx(M,{className:"text-xs font-medium w-[70px]"})]})}),e.jsx(cs,{children:U.map(y=>{const u=y.detailsJson||{},o=typeof u.deliveriesDuringAdpLunch=="number"?u.deliveriesDuringAdpLunch:0,T=o>0?e.jsxs(e.Fragment,{children:["Delivered ",e.jsx("span",{className:"font-semibold",children:o})," ","package",o!==1?"s":""," during payroll meal break"]}):e.jsxs(e.Fragment,{children:["Payroll meal break doesn't match"," ",e.jsx("span",{className:"font-semibold",children:"Amazon Flex"})]}),x=u.action||"Review payroll meal time",D=x.match(/^(Change payroll )(meal time)( to )(.+)$/),j=D?e.jsxs(e.Fragment,{children:[D[1],e.jsx("span",{className:"font-semibold",children:D[2]}),D[3],e.jsx("span",{className:"font-semibold",children:D[4]})]}):x;return e.jsxs(X,{"data-payroll-violation-id":y.id,tabIndex:-1,className:"even:bg-slate-50/50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-warning-solid",children:[e.jsx(S,{className:"py-2",children:e.jsx("input",{type:"checkbox",className:"h-4 w-4 roun
1ded border-slate-300"})}),e.jsx(S,{className:"text-sm font-medium py-2",children:e.jsx(xt,{violation:y,isUnmatched:w,onLinkDriver:p,isLinked:_,onUnlinkDriver:g})}),e.jsx(S,{className:"text-sm py-2",children:y.violationDate?new Date(y.violationDate+"T12:00:00").toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"numeric"}):"—"}),e.jsx(S,{className:"text-sm py-2",children:T}),e.jsx(S,{className:"text-sm py-2",children:j}),e.jsx(S,{className:"py-2",children:e.jsx(Y,{variant:"outline",className:"text-xs font-normal bg-blue-50 text-blue-700 border-blue-200",children:"New"})}),e.jsx(S,{className:"py-2 text-right",children:e.jsx(pt,{violation:y,onSmsRow:r})})]},y.id)})})]})]})}function ga({violations:a,typeKey:r,onSmsRow:w,isUnmatched:p,onLinkDriver:_,isLinked:g,onUnlinkDriver:I}){return a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No matching violations"}):r==="FLEX_PAYROLL_LUNCH_MISMATCH"?e.jsx(fa,{violations:a,onSmsRow:w,isUnmatched:p,onLinkDriver:_,isLinked:g,onUnlinkDriver:I}):e.jsx("div",{className:"max-h-64 overflow-y-auto border-t",children:e.jsxs(rs,{children:[e.jsx(ls,{children:e.jsxs(X,{className:"bg-slate-50/80",children:[e.jsx(M,{className:"text-xs font-medium",children:"Driver"}),e.jsx(M,{className:"text-xs font-medium w-[100px]",children:"Date"}),e.jsx(M,{className:"text-xs font-medium",children:"Details"}),e.jsx(M,{className:"text-xs font-medium w-[80px] text-right",children:"Fine"}),e.jsx(M,{className:"text-xs font-medium w-[90px]",children:"Code"}),e.jsx(M,{className:"text-xs font-medium w-[70px]"})]})}),e.jsx(cs,{children:a.map(i=>e.jsxs(X,{"data-payroll-violation-id":i.id,tabIndex:-1,className:"even:bg-slate-50/50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-warning-solid",children:[e.jsx(S,{className:"text-sm font-medium py-2",children:e.jsx(xt,{violation:i,isUnmatched:p,onLinkDriver:_,isLinked:g,onUnlinkDriver:I})}),e.jsx(S,{className:"text-sm py-2",children:i.violationDate||"—"}),e.jsx(S,{className:"text-sm py-2 max-w-xs",children:i.message}),e.jsx(S,{className:"text-sm py-2 text-right font-medium",children:i.fineAmount>0?`$${i.fineAmount.toFixed(2)}`:"—"}),e.jsx(S,{className:"text-sm py-2 text-muted-foreground",children:i.fineCode?mt(i.fineCode)?e.jsx(ut,{term:i.fineCode,children:i.fineCode}):i.fineCode:"—"}),e.jsx(S,{className:"py-2 text-right",children:e.jsx(pt,{violation:i,onSmsRow:w})})]},i.id))})]})})}function Na({typeKey:a,label:r,passLabel:w,fineCode:p,count:_,violations:g,isExpanded:I,onToggle:i,onSms:U,onSmsRow:y,isUnmatched:u,onLinkDriver:o,isLinked:T,onUnlinkDriver:x}){const D=_>0;return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 ${D?"cursor-pointer hover:bg-slate-50":""}`,onClick:D?i:void 0,children:[D?I?e.jsx(_t,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(st,{className:"h-5 w-5 text-success-solid shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:`font-medium ${D?"text-slate-900":"text-slate-500"}`,children:D?r:w}),D&&e.jsx(Y,{variant:"outline",children:_})]})}),U&&e.jsxs(J,{variant:"outline",size:"sm",className:"gap-1 shrink-0",onClick:j=>{j.stopPropagation(),U()},children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"Preview SMS"]}),p&&e.jsx(Y,{variant:"outline",className:"text-xs text-muted-foreground font-normal shrink-0",children:mt(p)?e.jsx(ut,{term:p,children:p}):p})]}),D&&e.jsx("div",{className:`grid transition-all duration-200 ease-out ${I?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:e.jsx("div",{className:"overflow-hidden",children:e.jsx("div",{className:"px-4 pb-3",children:e.jsx(ga,{violations:g,typeKey:a,onSmsRow:y,isUnmatched:u,onLinkDriver:o,isLinked:T,onUnlinkDriver:x})})})})]})}function ya({label:a,icon:r,iconColor:w,totalIssues:p,types:_,expandedTypes:g,onToggleType:I,onSmsByType:i,onSmsRow:U,isUnmatched:y,onLinkDriver:u,isLinked:o,onUnlinkDriver:T,severity:x="violation"}){const D=p>0,j=D?x==="warning"?"border-l-warning-solid":"border-l-danger-solid":"border-l-success-solid";return e.jsxs(vs,{className:`border-l-4 ${j} overflow-hidden`,children:[e.jsxs("div",{className:"flex items-center gap-3 bg-muted/30 px-4 py-3",children:[e.jsx(r,{className:`h-5 w-5 ${w} shrink-0`}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold",children:a}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?`${p} item${p===1?"":"s"} to review`:"No matching items"})]}),D?x==="warning"?e.jsx(Y,{variant:"outline",className:"rounded-full border-warning-solid/25 bg-warning-tint text-warning-deep",children:p}):e.jsx(Y,{variant:"destructive",className:"rounded-full",children:p}):e.jsx(Y,{variant:"outline",className:"text-success-deep border-success-solid/25 bg-success-tint",children:"All clear"})]}),e.jsx("div",{className:"divide-y",children:_.map(d=>e.jsx(Na,{typeKey:d.typeKey,label:d.label,passLabel:d.passLabel,fineCode:d.fineCode,count:d.count,violations:d.violations,isExpanded:g.has(d.typeKey),onToggle:()=>I(d.typeKey),onSms:i&&d.count>0?()=>
1i(d.typeKey):void 0,onSmsRow:U,isUnmatched:y,onLinkDriver:u,isLinked:o,onUnlinkDriver:T},d.typeKey))})]})}function va({allViolations:a,filteredViolations:r,isLoading:w,onSmsByType:p,onSmsRow:_,isUnmatched:g,onLinkDriver:I,isLinked:i,onUnlinkDriver:U,focusViolationId:y}){const[u,o]=l.useState(new Set),T=!!(y&&!a.some(d=>d.id===y)),x=l.useMemo(()=>Yt.map(d=>{const C=qt[d],A=Object.entries(C.types).map(([O,L])=>{const ne=r.filter($=>$.type===O);return{typeKey:O,label:L.label,passLabel:L.passLabel,fineCode:L.fineCode,count:ne.length,violations:ne}});return{category:d,label:C.label,icon:C.icon,iconColor:C.iconColor,totalIssues:A.reduce((O,L)=>O+L.count,0),types:A,severity:d==="WARNING"?"warning":"violation"}}),[r]),D=l.useMemo(()=>{const d=new Set(u);if(y){const C=r.find(A=>A.id===y);C&&d.add(C.type)}return d},[r,y,u]),j=d=>{o(C=>{const A=new Set(C);return A.has(d)?A.delete(d):A.add(d),A})};return l.useEffect(()=>{if(!y)return;const d=r.find(A=>A.id===y);if(!d||!D.has(d.type))return;const C=requestAnimationFrame(()=>{const O=Array.from(document.querySelectorAll("[data-payroll-violation-id]")).find(L=>L.dataset.payrollViolationId===y);O&&(O.scrollIntoView({block:"center",behavior:"smooth"}),O.focus({preventScroll:!0}))});return()=>cancelAnimationFrame(C)},[D,r,y]),w?e.jsxs("div",{className:"space-y-4",children:[e.jsx(De,{className:"h-32"}),e.jsx(De,{className:"h-48"}),e.jsx(De,{className:"h-24"}),e.jsx(De,{className:"h-20"})]}):e.jsxs("div",{className:"space-y-4",children:[T&&e.jsxs("div",{role:"alert",className:"flex items-start gap-3 rounded-md border border-warning-solid/25 bg-warning-tint px-4 py-3 text-sm text-warning-deep",children:[e.jsx(Se,{className:"mt-0.5 h-4 w-4 shrink-0 text-warning-solid","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Linked payroll violation is unavailable"}),e.jsx("p",{className:"mt-0.5",children:"The cited violation may have been replaced by a reanalysis. The upload shown below contains its current results."})]})]}),x.map(d=>e.jsx(ya,{label:d.label,icon:d.icon,iconColor:d.iconColor,totalIssues:d.totalIssues,types:d.types,expandedTypes:D,onToggleType:j,onSmsByType:p,onSmsRow:_,isUnmatched:g,onLinkDriver:I,isLinked:i,onUnlinkDriver:U,severity:d.severity},d.category))]})}function ja(a){const[r,w]=l.useState("all"),[p,_]=l.useState(""),{data:g,isLoading:I}=qs({queryKey:os.payroll.comparison(a||""),queryFn:async()=>{const{data:{session:u}}=await Gs.auth.getSession();if(!u)throw new Error("Not authenticated");const o=await fetch(`${Ks}/api/payroll/uploads/${a}/comparison`,{headers:{Authorization:`Bearer ${u.access_token}`}});if(!o.ok){const T=await o.json().catch(()=>({error:"Fetch failed"}));throw new Error(T.error||"Failed to load comparison")}return o.json()},enabled:!!a,staleTime:300*1e3}),i=l.useMemo(()=>{if(!g?.comparison)return[];let u=g.comparison;if(r==="matched"?u=u.filter(o=>o.matchConfidence>0&&o.matchMethod!=="unmatched"&&o.matchMethod!=="amazon-only"&&o.matchMethod!=="no-sync-data"):r==="unmatched"?u=u.filter(o=>o.matchMethod==="unmatched"||o.matchMethod==="amazon-only"||o.matchMethod==="no-sync-data"):r==="discrepancy"&&(u=u.filter(o=>o.discrepancy!=null&&Math.abs(o.discrepancy)>=1)),p){const o=p.toLowerCase();u=u.filter(T=>T.daName&&T.daName.toLowerCase().includes(o)||T.amazonName&&T.amazonName.toLowerCase().includes(o)||T.positionId&&T.positionId.toLowerCase().includes(o))}return u},[g?.comparison,r,p]),U=l.useMemo(()=>g?.comparison?g.comparison.filter(u=>u.matchMethod==="amazon-only"):[],[g?.comparison]),y=rt();return{rows:i,allRows:g?.comparison||[],unmatchedAmazonDAs:U,summary:g?.summary||{matched:0,unmatched:0,discrepancies:0,total:0},syncSession:g?.syncSession||null,isLoading:I,filter:r,setFilter:w,searchQuery:p,setSearchQuery:_,linkDA:y}}function Ys({method:a,confidence:r}){return a==="unmatched"||a==="amazon-only"||a==="no-sync-data"?e.jsx(Y,{variant:"outline",className:"text-xs text-danger-deep border-danger-solid/25",children:"No match"}):a==="position-id-link"?e.jsx(Y,{variant:"outline",className:"text-xs text-success-deep border-success-solid/25",children:"ID Link"}):a==="nickname"?e.jsx(Y,{variant:"outline",className:"text-xs text-success-deep border-success-solid/25",children:"Nickname ✓"}):r>=.95?e.jsx(Y,{variant:"outline",className:"text-xs text-success-deep border-success-solid/25",children:"Name ✓"}):r>
1=.85?e.jsxs(Y,{variant:"outline",className:"text-xs text-warning-deep border-warning-solid/25",children:["~Name ",Math.round(r*100),"%"]}):e.jsxs(Y,{variant:"outline",className:"text-xs text-warning-deep border-warning-solid/25",children:["~Name ",Math.round(r*100),"%"]})}function ba(){const a=new URLSearchParams(window.location.search),r=a.get("upload_id"),w=a.get("violation_id"),p=Xt("payroll"),_=At(),{uploads:g,isLoading:I,isError:i,isUnavailable:U,refetch:y}=tt(r),u=it(),o=ot(),{mappings:T}=sa(),{isConnected:x,triggerPayrollHoursFetch:D,batchSyncProgress:j,triggerBatchSigninSync:d}=ta(),[C,A]=l.useState(null),[O,L]=l.useState(null),ne=Ft(),{allDrivers:$,isLoading:Re,isError:Ye,isAccessDenied:E,refetch:ye}=ct({enabled:C!==null}),{toast:P}=Ws(),{data:se}=bs(),ve=nt(se),{selectedStationCode:_e}=Et(),te=l.useRef(null),[je,Ie]=l.useState(null),[de,ds]=l.useState("ADP"),[R,qe]=l.useState(null),[W,me]=l.useState(null),be=l.useRef(null),we=l.useRef(null),[Ge,ue]=l.useState(!1),[Ce,Ae]=l.useState([]),[he,ie]=l.useState("bulk"),[Ee,V]=l.useState(),[oe,pe]=l.useState(""),[Me,Pe]=l.useState(null),Ke=r&&g.some(s=>s.id===r)?r:null,F=je||Ke||(!r&&g.length>0?g[0]?.id??null:null),ms=g.find(s=>s.id===F),q=Me??ms?.summaryJson?.missingSigninDates??[];l.useEffect(()=>{Pe(null)},[F]);const{violations:ae,allViolations:G,summary:z,isLoading:Te,isError:We,refetch:Ue,severityFilter:K,setSeverityFilter:xe,searchQuery:Qe,setSearchQuery:Je}=at(F),us=js(We,G),fe=js(i||U,g),{rows:re,unmatchedAmazonDAs:Oe,summary:ge,syncSession:Xe,isLoading:Fe,filter:Z,setFilter:Ne,searchQuery:t,setSearchQuery:f,linkDA:m}=ja(F),b=l.useRef(!1);l.useEffect(()=>{if(b.current&&!j.isRunning){const{completedDates:s,failedDates:n}=j;s.length===0&&n.length>0?P({title:"Sync failed",description:`Could not sync ${n.length} date(s). Make sure an Amazon Logistics tab is open.`,variant:"destructive"}):F&&(be.current=null,(async()=>{try{const h=await o.mutateAsync(F);Pe(h.missingSigninDates||[]),P({title:"Amazon data synced",description:`Synced ${s.length} date(s). ${h.summary.totalViolations} violations found.${n.length>0?` ${n.length} date(s) failed.`:""}`})}catch(h){P({title:"Re-analysis failed",description:$e(h),variant:"destructive"})}})())}b.current=j.isRunning},[j.isRunning]),l.useEffect(()=>{if(!j.isRunning)return;const s=j.totalDates*45e3+3e4,n=setTimeout(()=>{P({title:"Sync taking longer than expected",description:"Make sure you have an Amazon Logistics tab open and the extension is active.",variant:"destructive"})},s);return()=>clearTimeout(n)},[j.isRunning,j.totalDates]);const N=async()=>{const s=te.current?.files?.[0];if(!s){P({title:"No file selected",description:"Please choose a CSV file first.",variant:"destructive"});return}if(!s.name.endsWith(".csv")){P({title:"Invalid file",description:"Please upload a .csv file.",variant:"destructive"});return}try{be.current={file:s,systemName:de},we.current={file:s,systemName:de};const n=await u.mutateAsync({file:s,systemName:de});Ie(n.upload_id),Pe(n.missingSigninDates||[]);let h=`${n.summary.totalDAs} drivers analyzed. ${n.summary.totalViolations} violations, ${n.summary.totalWarnings} warnings found.`;if(n.replaced&&(h+=` Replaced previous upload "${n.replaced.file_name}".`),P({title:"Upload complete",description:h}),te.current&&(te.current.value=""),x&&n.summary.dateRange){const[k,H]=n.summary.dateRange.split(" to ");k&&H&&D(k,H),n.missingSigninDates&&n.missingSigninDates.length>0&&(d(n.missingSigninDates),P({title:"Syncing Amazon data...",description:`Fetching sign-ins for ${n.missingSigninDates.length} missing date(s).`}))}}catch(n){be.current=null,we.current=null,P({title:"Upload failed",description:$e(n),variant:"destructive"})}},c=g.find(s=>
1s.id===F),v=!!_e&&ss(se,"payroll.export",{stationCode:_e,operation:"mutate"})&&Mt(se,"sensitive"),B=l.useMemo(()=>[...new Set(G.filter(n=>n.severity==="VIOLATION").map(n=>n.daName))],[G]),hs=l.useMemo(()=>[...new Set(G.map(n=>n.daName).filter(Boolean))],[G]),{data:le}=ht(hs,F),ft=l.useCallback(s=>le?.[s]??null,[le]);function ps(s){const n=new Map;for(const h of s){n.has(h.daName)||n.set(h.daName,{daName:h.daName,types:[],actions:[]});const k=n.get(h.daName);k.types.push(h.type);const H=h.detailsJson?.action,Q=typeof H=="string"&&H.trim()?H.trim():null,ke=typeof h.message=="string"&&h.message.trim()?h.message.trim():null,Ze=h.violationDate;Q&&Ze?k.actions.push(`${Ze}: ${Q}`):Q?k.actions.push(Q):ke&&k.actions.push(ke)}return[...n.values()].map(h=>{const k=ft(h.daName);return{daId:k?.daId??null,fullName:h.daName,phone:k?.phone??null,alertLevel:"critical",violationReason:[...new Set(h.types)].join(", "),actionText:h.actions.join("; ")}})}function gt(){const s=G.filter(h=>h.severity==="VIOLATION"),n=ps(s);Ae(n),ie(n.length===1?"single":"bulk"),V(void 0),ue(!0)}function Nt(s){const n=G.filter(k=>k.type===s),h=ps(n);Ae(h),ie(h.length===1?"single":"bulk"),V(Fs[s]),ue(!0)}function yt(s){const n=ps([s]);Ae(n),ie("single"),V(Fs[s.type]),ue(!0)}const vt=l.useCallback(s=>le?!le[s]?.daId:!1,[le]),jt=l.useCallback(s=>le?.[s]?.matchMethod==="position-id-link",[le]);function bt(s){pe(""),A({daName:s.daName,positionId:s.positionId})}function wt(s){const n=le?.[s.daName];n?.daId&&L({daName:s.daName,daId:n.daId,linkedName:n.fullName||"this driver"})}const Cs=l.useMemo(()=>{const s=oe.trim().toLowerCase(),n=s?$.filter(k=>k.fullName?.toLowerCase().includes(s)):$,h=C?Le(C.daName):"";return[...n].sort((k,H)=>{const Q=h&&Le(k.fullName)===h?0:1,ke=h&&Le(H.fullName)===h?0:1;return Q-ke||k.fullName.localeCompare(H.fullName)}).slice(0,50)},[$,oe,C]);function Ct(s){C?.positionId&&m.mutate({positionId:C.positionId,amazonAssociateId:s.associateId},{onSuccess:()=>{P({title:"Driver linked",description:`${C.daName} → ${s.fullName}`}),_.setQueryData(os.payroll.driverMatches(hs,F,ve),n=>({...n||{},[C.daName]:{daId:s.id,fullName:s.fullName,phone:s.phone,stationCode:s.stationCode??null,matchConfidence:1,matchMethod:"position-id-link"}})),_.invalidateQueries({queryKey:os.payroll.driverMatches(hs,F,ve)}),A(null)},onError:n=>{P({title:"Link failed",description:$e(n),variant:"destructive"})}})}const kt=l.useCallback(()=>{q.length!==0&&d(q)},[q,d]),St=l.useMemo(()=>{if(q.length===0)return"";const s=[...q].sort(),n=new Date(s[0]+"T12:00:00"),h=new Date(s[s.length-1]+"T12:00:00"),k=H=>H.toLocaleDateString("en-US",{month:"short",day:"numeric"});return n.getTime()===h.getTime()?k(n):`${k(n)} – ${k(h)}`},[q]),Dt=["ADP",...T.map(s=>s.system_name)];return e.jsxs("div",{className:"space-y-4 relative",children:[p.content&&e.jsx(Zt,{onClick:p.openHelp,className:"top-0 right-0"}),e.jsx(ea,{isOpen:p.isOpen,onClose:p.closeHelp,content:p.content}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Payroll Pre-Check"}),e.jsx("p",{className:"text-muted-foreground mt-1 pr-12",children:"Upload payroll CSV to detect violations and compare with Amazon relay hours"})]}),e.jsx(vs,{children:e.jsxs(Rs,{className:"pt-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-end",children:[e.jsxs("div",{className:"space-y-1 md:w-[140px]",children:[e.jsx(_s,{htmlFor:"payroll-precheck-system",className:"text-xs text-muted-foreground",children:"Payroll system"}),e.jsxs(Js,{value:de,onValueChange:ds,children:[e.jsx(Xs,{id:"payroll-precheck-system",className:"w-full",children:e.jsx(Zs,{})}),e.jsx(et,{children:Dt.map(s=>e.jsx(ys,{value:s,children:s},s))})]})]}),e.jsxs("div",{className:"space-y-1 md:max-w-sm md:flex-1",children:[e.jsx(_s,{htmlFor:"payroll-precheck-csv",className:"text-xs text-muted-foreground",children:"Timecard CSV"}),e.jsx(Ve,{id:"payroll-precheck-csv",ref:te,type:"file",accept:".csv"})]}),e.jsxs(J,{onClick:N,disabled:u.isPending,className:"gap-2 md:w-auto",children:[e.jsx(aa,{className:"h-4 w-4"}),u.isPending?"Analyzing...":"Upload & Analyze"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Export the Timecard Report from ADP as CSV — uploads here and in Daily Reconciliation use the same file."}),u.isPending&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Parsing CSV and running violation checks..."})]})}),r&&!I&&!i&&!U&&!Ke&&!je&&e.jsxs("div",{role:"alert",className:"flex items-start gap-3 rounded-md border border-warning-solid/25 bg-warning-tint px-4 py-3 text-sm text-warning-deep",children:[e.jsx(Se,{className:"mt-0.5 h-4 w-4 shrink-0 text-warning-solid"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Linked payroll evidence is unavailable"}),e.jsx("p",{className:"mt-0.5",children:"The cited upload may have been replaced or is outside your current access. Choose another upload from history to continue."})]})]}),F&&c&&e.jsxs(Kt,{defaultValue:"violations",children:[e.jsxs(Wt,{children:[e.jsx($s,{value:"violations",children:"Upload & Violations"}),e.jsxs($s,{value:"comparison",className:"gap-1.5",children:[e.jsx(la,{className:"h-3.5 w-3.5"}),"Hours Comparison"]})]}),e.jsx(Hs,{value:"violations",className:"space-y-4",children:us?e.jsx(Us,{title:"Couldn't load violation results",onRetry:()=>Ue()}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ce,{title:"Violations",value:z.totalViolations,icon:Se,iconColor:"text-danger-solid",tooltip:"
1CA labor law violations requiring immediate attention. Click to filter.",onClick:()=>xe(K==="VIOLATION"?"All":"VIOLATION"),active:K==="VIOLATION"}),e.jsx(ce,{title:"Warnings",value:z.totalWarnings,icon:na,iconColor:"text-warning-solid",tooltip:"Issues that may lead to violations. Click to filter.",onClick:()=>xe(K==="WARNING"?"All":"WARNING"),active:K==="WARNING"}),e.jsx(ce,{title:"Drivers with Issues",value:z.dasWithIssues,icon:Is,iconColor:"text-danger-solid",tooltip:"Unique drivers who have at least one violation. Click to filter.",onClick:()=>xe(K==="VIOLATION"?"All":"VIOLATION"),active:K==="VIOLATION"}),e.jsx(ce,{title:"Est. Fines",value:`$${z.totalFines.toLocaleString("en-US",{minimumFractionDigits:2})}`,icon:ia,iconColor:"text-danger-solid",tooltip:"Estimated total penalties based on CA labor code fine schedules",onClick:()=>xe("All"),active:K==="All"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing results for ",e.jsx("span",{className:"font-medium",children:c.fileName})," ","(",c.dateRangeStart," to ",c.dateRangeEnd,")"," ","· ",c.totalDAs," drivers analyzed"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(Ve,{placeholder:"Search by driver name...",value:Qe,onChange:s=>Je(s.target.value),className:"w-full sm:max-w-xs"}),e.jsxs("span",{className:"text-sm text-muted-foreground sm:ml-auto",children:[ae.length," of ",G.length," issues",K!=="All"&&e.jsxs(e.Fragment,{children:[" — showing ",e.jsx("span",{className:"font-medium",children:K==="VIOLATION"?"violations only":"warnings only"})]})]}),B.length>0&&e.jsxs(J,{size:"sm",variant:"outline",className:"gap-1",onClick:gt,children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"Text ",B.length," drivers…"]}),v&&e.jsxs(J,{variant:"outline",size:"sm",className:"gap-1","aria-label":"Export payroll violations CSV",onClick:()=>{zs(ae.map(s=>({"Driver Name":s.daName,Date:s.violationDate||"",Category:s.category,Type:s.type,Violation:s.message,Fine:s.fineAmount>0?`$${s.fineAmount.toFixed(2)}`:"",Code:s.fineCode||"",Severity:s.severity})),"payroll-violations.csv")},disabled:ae.length===0,children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Export"]})]}),(q.length>0||j.isRunning)&&e.jsxs("div",{className:"flex items-center gap-3 bg-warning-tint border border-warning-solid/25 rounded-md px-4 py-3",children:[e.jsx(Se,{className:"h-4 w-4 text-warning-solid shrink-0"}),e.jsx("div",{className:"flex-1",children:j.isRunning?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("p",{className:"text-sm text-warning-deep",children:["Syncing date ",e.jsxs("span",{className:"font-semibold",children:[j.completedDates.length+1," of ",j.totalDates]}),j.currentDate&&e.jsxs("span",{className:"ml-1",children:["(",new Date(j.currentDate+"T12:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"}),")"]})]}),e.jsx("div",{className:"w-full bg-warning-solid/20 rounded-full h-1.5",children:e.jsx("div",{className:"bg-warning-solid h-1.5 rounded-full transition-all duration-500",style:{width:`${j.completedDates.length/j.totalDates*100}%`}})})]}):e.jsxs("p",{className:"text-sm text-warning-deep",children:["Missing Amazon data for ",e.jsxs("span",{className:"font-semibold",children:[q.length," date",q.length!==1?"s":""]})," ","(",St,"). Sync to detect meal break violations."]})}),e.jsxs(J,{size:"sm",variant:"outline",className:"gap-1.5 border-warning-solid/25 text-warning-deep hover:bg-warning-tint shrink-0",onClick:kt,disabled:!x||j.isRunning,children:[e.jsx(Pt,{className:`h-3.5 w-3.5 ${j.isRunning?"animate-spin":""}`}),j.isRunning?`${j.completedDates.length}/${j.totalDates}`:"Sync Now"]}),!x&&!j.isRunning&&e.jsx("span",{className:"text-xs text-warning-solid",children:"Extension not connected"})]}),e.jsx(va,{allViolations:G,filteredViolations:ae,isLoading:Te,onSmsByType:Nt,onSmsRow:yt,isUnmatched:vt,onLinkDriver:bt,isLinked:jt,onUnlinkDriver:wt,focusViolationId:F===r?w:null})]})}),e.jsxs(Hs,{value:"comparison",className:"space-y-4",children:[Xe?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Comparing payroll hours with Amazon data from ",e.jsx("span",{className:"font-medium",children:Xe.weekLabel})]}):!Fe&&e.jsx("div",{className:"bg-warning-tint border border-warning-solid/25 rounded-md p-3 text-sm text-warning-deep",children:"No Amazon relay data found for this payroll period. Sync from the Chrome Extension first."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ce,{title:"Total Drivers",value:ge.total,icon:Is,iconColor:"text-info-solid",tooltip:"Total drivers from both payroll and Amazon sources",onClick:()=>Ne("all"),active:Z==="all"}),e.jsx(ce,{title:"Matched",value:ge.matched,icon:st,iconColor:"text-success-solid",tooltip:"Drivers matched between payroll and Amazon by name. Click to filter.",onClick:()=>Ne(Z==="matched"?"all":"matched"),active:Z==="matched"}),e.jsx(ce,{title:"Unmatched",value:ge.unmatched,icon:oa,iconColor:"text-danger-solid",tooltip:"Drivers in payroll without a match in Amazon, or vice versa. Click to filter.",onClick:()=>Ne(Z==="unmatched"?"all":"unmatched"),active:Z==="unmatched"}),e.jsx(ce,{title:"Discrepancies",value:ge.discrepancies,icon:Se,iconColor:"text-warning-solid",tooltip:"Matched drivers where payroll vs Amazon hours differ by 1+ hours. Click to filter.",onClick:()=>Ne(Z==="discrepancy"?"all":"discrepancy"),active:Z==="discrepancy"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(Ve,{placeholder:"Search by name or position ID...",value:t,onChange:s=>
1f(s.target.value),className:"w-full sm:max-w-xs"}),e.jsxs("span",{className:"text-sm text-muted-foreground sm:ml-auto",children:[re.length," results"]}),v&&e.jsxs(J,{variant:"outline",size:"sm",className:"gap-1","aria-label":"Export payroll comparison CSV",onClick:()=>zs(re.map(s=>({"Payroll Name":s.daName||"","Position ID":s.positionId||"","Amazon Name":s.amazonName||"","Payroll Total":s.payrollTotal??"","Amazon Total":s.amazonTotal??"",Discrepancy:s.discrepancy??"","Name Match":s.matchMethod,"Name Confidence":Math.round((s.matchConfidence||0)*100)+"%"})),"hours-comparison.csv"),disabled:re.length===0,children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"CSV"]})]}),Fe?e.jsx(De,{className:"h-96"}):e.jsx("div",{className:"border rounded-md bg-white overflow-auto",children:e.jsxs(rs,{children:[e.jsx(ls,{children:e.jsxs(X,{children:[e.jsx(M,{children:"Payroll Name"}),e.jsx(M,{children:"Amazon Name"}),e.jsx(M,{className:"w-[90px] text-center",children:"Payroll Hrs"}),e.jsx(M,{className:"w-[90px] text-center",children:"Amazon Hrs"}),e.jsx(M,{className:"w-[90px] text-center",children:"Diff"}),e.jsx(M,{className:"w-[100px]",children:"Name Match"})]})}),e.jsxs(cs,{children:[re.map((s,n)=>{const h=s.discrepancy!=null&&Math.abs(s.discrepancy)>=1;return e.jsxs(X,{className:`cursor-pointer ${h?"bg-warning-tint":""} ${!s.daName||!s.amazonName?"bg-danger-tint/50":""}`,onClick:()=>qe(s),children:[e.jsxs(S,{className:"font-medium",children:[s.daName||e.jsx("span",{className:"text-muted-foreground italic",children:"—"}),s.positionId&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1.5 font-mono",children:s.positionId})]}),e.jsx(S,{children:s.amazonName||e.jsx("span",{className:"text-muted-foreground italic",children:"—"})}),e.jsx(S,{className:"text-center font-medium",children:s.payrollTotal!=null?s.payrollTotal.toFixed(1):"—"}),e.jsx(S,{className:"text-center font-medium",children:s.amazonTotal!=null?s.amazonTotal.toFixed(1):"—"}),e.jsx(S,{className:`text-center font-medium ${h?"text-warning-deep":""}`,children:s.discrepancy!=null?e.jsxs(e.Fragment,{children:[s.discrepancy>0?"+":"",s.discrepancy.toFixed(1)]}):"—"}),e.jsx(S,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ys,{method:s.matchMethod,confidence:s.matchConfidence}),s.matchMethod==="unmatched"&&s.positionId&&Oe.length>0&&e.jsx(J,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-info-solid hover:text-info-deep hover:bg-info-tint",title:"Link to Amazon Driver",onClick:k=>{k.stopPropagation(),me(s)},children:e.jsx(lt,{className:"h-3.5 w-3.5"})})]})})]},n)}),re.length===0&&e.jsx(X,{children:e.jsx(S,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No comparison data available."})})]})]})})]})]}),e.jsxs(vs,{children:[e.jsxs(Tt,{children:[e.jsx(Ut,{className:"text-lg",children:"Upload History"}),e.jsx(Ot,{children:"Previous payroll pre-check results"})]}),e.jsx(Rs,{children:I?e.jsx(De,{className:"h-24"}):fe?e.jsx(Us,{title:U?"Upload history is unavailable for this access scope":"Couldn't load upload history",onRetry:()=>y()}):g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No uploads yet. Upload a payroll CSV above to get started."}):e.jsx("div",{className:"space-y-2",children:g.map(s=>e.jsxs("button",{onClick:()=>Ie(s.id),className:`w-full text-left px-3 py-2 rounded-md text-sm flex items-center justify-between transition-colors ${F===s.id?"bg-slate-100 border border-slate-300":"hover:bg-slate-50 border border-transparent"}`,children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:s.fileName}),e.jsxs("span",{className:"text-muted-foreground ml-2",children:[s.dateRangeStart," to ",s.dateRangeEnd]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{children:[s.totalDAs," Drivers"]}),s.totalViolations>0&&e.jsxs(Y,{variant:"destructive",className:"text-xs",children:[s.totalViolations," violations"]}),s.totalWarnings>0&&e.jsxs(Y,{className:"bg-warning-tint text-warning-deep text-xs hover:bg-warning-tint",children:[s.totalWarnings," warnings"]}),s.totalFines>0&&e.jsxs("span",{className:"text-danger-deep font-medium font-mono tabular-nums",children:["$",s.totalFines.toLocaleStr
1ing("en-US",{minimumFractionDigits:2})]}),e.jsx("span",{className:"text-xs",children:Be(new Date(s.createdAt),"MMM d, h:mm a")})]})]},s.id))})})]}),e.jsx(ts,{open:!!W,onOpenChange:()=>me(null),children:e.jsxs(as,{className:"max-w-sm",children:[e.jsx(ns,{children:e.jsxs(is,{children:['Link "',W?.daName,'" to Amazon Driver']})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select the matching Amazon Driver for ",e.jsx("span",{className:"font-medium",children:W?.daName}),W?.positionId&&e.jsxs(e.Fragment,{children:[" (Position ID: ",e.jsx("span",{className:"font-mono",children:W.positionId}),")"]})]}),e.jsxs("div",{className:"max-h-64 overflow-y-auto border rounded-md divide-y",children:[Oe.map(s=>e.jsxs("button",{className:"w-full text-left px-3 py-2.5 text-sm hover:bg-info-tint transition-colors flex items-center justify-between",onClick:()=>{!W?.positionId||!s.amazonId||m.mutate({positionId:W.positionId,amazonAssociateId:s.amazonId},{onSuccess:()=>{P({title:"Driver linked",description:`${W.daName} → ${s.amazonName}`}),me(null)},onError:n=>{P({title:"Link failed",description:$e(n),variant:"destructive"})}})},disabled:m.isPending,children:[e.jsx("span",{className:"font-medium",children:s.amazonName}),s.amazonTotal!=null&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:[s.amazonTotal.toFixed(1)," hrs"]})]},s.amazonId)),Oe.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No unmatched Amazon Drivers available"})]})]})}),e.jsx(ts,{open:!!C,onOpenChange:s=>{s||A(null)},children:e.jsxs(as,{className:"max-w-sm",children:[e.jsx(ns,{children:e.jsxs(is,{children:['Link "',C?.daName,'" to a driver']})}),C?.positionId?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select the driver ",e.jsx("span",{className:"font-medium",children:C.daName})," refers to"," ","(Position ID: ",e.jsx("span",{className:"font-mono",children:C.positionId}),")"]}),E?e.jsx("p",{className:"rounded-md border border-border bg-muted/40 px-3 py-4 text-sm text-muted-foreground",role:"status",children:"Driver directory unavailable. Drivers access is required to link this payroll row."}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{placeholder:"Search drivers…",value:oe,onChange:s=>pe(s.target.value),autoFocus:!0,disabled:Re||Ye}),e.jsx("div",{className:"max-h-64 overflow-y-auto border rounded-md divide-y","aria-live":"polite",children:Re?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading authorized drivers…"}):Ye?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-3 py-4 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Driver directory couldn’t be loaded."}),e.jsx(J,{type:"button",variant:"outline",size:"sm",onClick:()=>ye(),children:"Try again"})]}):e.jsxs(e.Fragment,{children:[Cs.map(s=>e.jsxs("button",{className:"w-full text-left px-3 py-2.5 text-sm hover:bg-info-tint transition-colors flex items-center justify-between",onClick:()=>Ct(s),disabled:m.isPending,children:[e.jsx("span",{className:"font-medium",children:s.fullName}),s.phone&&e.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:s.phone})]},s.id)),Cs.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:$.length===0?"No drivers are available in your authorized stations":"No drivers match that search"})]})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This payroll row has no position ID to link — re-upload the timecard CSV if this is unexpected."})]})}),e.jsx(Jt,{open:!!O,onOpenChange:s=>{s||L(null)},title:`Unlink "${O?.daName}"?`,consequence:e.jsxs(e.Fragment,{children:["This removes the manual link between"," ",e.jsx("span",{className:"font-medium",children:O?.daName})," and"," ",e.jsx("span",{className:"font-medium",children:O?.linkedName}),". Future payroll uploads will fall back to automatic name matching for this driver until it's linked again."]}),confirmLabel:"Unlink",destructive:!1,onConfirm:async()=>{if(O)try{await ne.mutateAsync({daId:O.daId}),P({title:"Driver unlinked",description:`${O.daName} is no longer linked to ${O.linkedName}`})}catch(s){throw P({title:"Unlink failed",description:$e(s),variant:"destructive"}),s}}}),e.jsx(dt,{open:Ge,onClose:()=>ue(!1),recipients:Ce,sourcePage:"payroll",mode:he,defaultMessageType:Ee,drawerTitle:he==="bulk"?`SMS to ${Ce.length}
1 drivers with violations`:void 0,drawerSubtitle:he==="bulk"?"Send payroll correction notices":void 0}),e.jsx(ts,{open:!!R,onOpenChange:()=>qe(null),children:e.jsxs(as,{className:"max-w-lg",children:[e.jsx(ns,{children:e.jsx(is,{children:R?.daName||R?.amazonName||"Driver Details"})}),R&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Payroll Name:"})," ",e.jsx("span",{className:"font-medium",children:R.daName||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Amazon Name:"})," ",e.jsx("span",{className:"font-medium",children:R.amazonName||"—"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{method:R.matchMethod,confidence:R.matchConfidence}),R.positionId&&e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["ID: ",R.positionId]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Daily Hours Breakdown"}),e.jsx("div",{className:"border rounded-md overflow-hidden",children:e.jsxs(rs,{children:[e.jsx(ls,{children:e.jsxs(X,{children:[e.jsx(M,{className:"w-[100px]",children:"Day"}),e.jsx(M,{className:"text-center",children:"Payroll"}),e.jsx(M,{className:"text-center",children:"Amazon"}),e.jsx(M,{className:"text-center",children:"Diff"})]})}),e.jsxs(cs,{children:[(()=>{const s=new Set;R.payrollHours&&Object.keys(R.payrollHours).forEach(h=>s.add(h)),R.amazonHours&&Object.keys(R.amazonHours).forEach(h=>s.add(h));const n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return s.size>0?[...s].sort().map(k=>{const H=R.payrollHours?.[k]??null,Q=R.amazonHours?.[k]??null,ke=new Date(k+"T12:00:00"),Ze=n[ke.getDay()],ze=H!=null&&Q!=null?parseFloat((H-Q).toFixed(2)):null,ks=ze!=null&&Math.abs(ze)>=.5;return e.jsxs(X,{className:ks?"bg-warning-tint":"",children:[e.jsxs(S,{className:"text-sm",children:[k," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",Ze,")"]})]}),e.jsx(S,{className:"text-center text-sm font-medium",children:H!=null?H.toFixed(1):"—"}),e.jsx(S,{className:"text-center text-sm font-medium",children:Q!=null?Q.toFixed(1):"—"}),e.jsx(S,{className:`text-center text-sm font-medium ${ks?"text-warning-deep":""}`,children:ze!=null?`${ze>0?"+":""}${ze.toFixed(1)}`:"—"})]},k)}):e.jsx(X,{children:e.jsx(S,{colSpan:4,className:"text-center text-sm text-muted-foreground py-4",children:"No daily breakdown available"})})})(),e.jsxs(X,{className:"border-t-2 font-bold",children:[e.jsx(S,{children:"Total"}),e.jsx(S,{className:"text-center",children:R.payrollTotal!=null?R.payrollTotal.toFixed(1):"—"}),e.jsx(S,{className:"text-center",children:R.amazonTotal!=null?R.amazonTotal.toFixed(1):"—"}),e.jsx(S,{className:`text-center ${R.discrepancy!=null&&Math.abs(R.discrepancy)>=1?"text-warning-deep":""}`,children:R.discrepancy!=null?`${R.discrepancy>0?"+":""}${R.discrepancy.toFixed(1)}`:"—"})]})]})]})})]})]})]})})]})}function pn(){const[a]=Qs(),{screens:r}=It();return r&&a.get("view")!=="full"?e.jsx(xa,{}):e.jsx(ba,{})}export{pn as default};

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