1import{i as js,u as ws,e as dt,r as m,l as T,ar as Ss,aV as C,q as me,j as e,C as mt,aY as Ds,T as ut,P as ue,b7 as pt,aq as Ps}from"./index-D0CLt0PK.js";import{E as Cs}from"./jspdf.es.min-wYFxySKW.js";import{c as wt,a as Ms,d as ks,b as Es}from"./environmentalLogCsv-D_NYCtK9.js";import{f}from"./format-B5tuBs_i.js";import{p as B}from"./parseISO-DVfrzFF6.js";import{p as Fs}from"./listPaging-iagHCs4P.js";import{L as Ls}from"./ListPageControls-CGqaOLUM.js";import{D as xt}from"./download-DknK7O33.js";import{F as Ie}from"./file-text-BrDHY82M.js";import{F as As}from"./file-type-DgLsqNKT.js";import{R as pe}from"./route-DAZ5xaAK.js";import{M as gt}from"./map-CWVcJiUG.js";import{P as Os}from"./plus-DvOHNqQB.js";import{M as Is}from"./map-pin-h5pirSvp.js";import{E as Ts}from"./external-link-QrEhwv-y.js";import{C as yt}from"./circle-x-BGHfc-FV.js";import{p as xe}from"./parse-Dkmbi2Np.js";import{i as $s}from"./isToday-DIrGL5W3.js";import"./addDays-BVyrAFpy.js";import"./isSameDay-Coj8geKz.js";/** 2 * @license lucide-react v0.544.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Rs=[["path",{d:"M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 4 0v-6.998a2 2 0 0 0-.59-1.42L18 5",key:"1wtuz0"}],["path",{d:"M14 21V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v16",key:"e09ifn"}],["path",{d:"M2 21h13",key:"1x0fut"}],["path",{d:"M3 9h11",key:"1p7c0w"}]],Bs=js("fuel",Rs);function ae(r){if(!r)return"";const n=[r.streetAddress,r.city,r.state,r.zipCode].filter(a=>a!=null&&String(a).trim()!=="").map(a=>String(a).trim());return n.length>0?n.join(", "):r.address!=null&&String(r.address).trim()!==""?String(r.address).trim():""}function Te(r){return String(r?.order?.fulfillmentType||"DELIVERY").toUpperCase()==="DELIVERY"}function ht(r=[]){return r.filter(Te)}function ye(r){const n=r?.snapshotDisplay;return n?.useSnapshot&&Array.isArray(n.items)&&n.items.length>0?n.items:r?.order?.items||[]}function $e(r){const n=r?.snapshotDisplay;if(n?.useSnapshot)return{totalPrice:n.totalPrice??0,customPrice:n.customPrice??null,customPriceNote:n.customPriceNote??null,notes:n.notes??null,useSnapshot:!0};const a=r?.order;return{totalPrice:a?.totalPrice??0,customPrice:a?.customPrice??null,customPriceNote:a?.customPriceNote??null,notes:a?.notes??null,useSnapshot:!1}}function ge(r){const n=$e(r);return n.customPrice!=null&&Number(n.customPrice)>0||Number(n.totalPrice)>0?!0:ye(r).reduce((l,u)=>l+(parseFloat(u.price)||0),0)>0}function re(r){return String(r??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function St(r){if(!r)return"â";try{return f(B(String(r).slice(0,10)),"MMM d, yyyy")}catch{return String(r).slice(0,10)||"â"}}function ft(r){if(!r)return"â";try{return f(new Date(r),"MMM d, yyyy h:mm a")}catch{return"â"}}function Dt(r){const n=[];for(const a of ye(r))a.crop?n.push(`${a.crop.cropName}: ${Number(a.quantity||0).toFixed(1)} oz`):a.blend&&n.push(`${a.blend.name}: ${Number(a.quantity||0).toFixed(1)} oz`);return n.length?n.join("; "):"â"}function zs(r){const n=$e(r);if(n.customPrice!=null){const a=n.customPriceNote?` (${n.customPriceNote})`:"";return`$${Number(n.customPrice).toFixed(2)} custom${a}`}return Number(n.totalPrice)>0?`$${Number(n.totalPrice).toFixed(2)}`:"â"}function Pt(r,n){const a=n?.[r?.id];return a?a.paid===!0?a.paymentMethod?`Paid · ${a.paymentMethod}`:"Paid":a.paymentMethod?`Unpaid · ${a.paymentMethod}`:"Unpaid":"Not paid"}function Ct(r,n){return n?n==="__manager__"?"Manager":r?.find(a=>a.id===n)?.name||"â":"â"}function Us(r,n){if(!n)return"â";const a=r?.find(l=>l.id===n);
6return a?[a.year,a.make,a.model,a.color].filter(Boolean).join(" ")||"Vehicle":"â"}function Vs(r,n){if(!n)return"â";const a=r?.find(u=>u.id===n);if(!a)return"â";const l=[a.contactName,a.phone,a.email].filter(Boolean).join(" · ");return l?`${a.name} (${l})`:a.name}function _s(r){return r?String(r).slice(0,10):""}function qs(r=[]){const n=f(new Date,"yyyy-MM-dd");let a=0,l=0,u=0;for(const v of r){const M=_s(v.date),w=String(v.status||"").toUpperCase();M&&M<n&&(a+=1,(w==="INCOMPLETE"||w==="FAILED"||w==="SCHEDULED"||w==="IN_PROGRESS")&&(u+=1)),w==="COMPLETED"&&(l+=1)}return{pastCount:a,completedCount:l,incompletePastCount:u}}function Mt(r=[]){const{pastCount:n,completedCount:a,incompletePastCount:l}=qs(r);return`${r.length} delivery record(s) · ${n} past · ${a} completed · ${l} past incomplete/unfulfilled. Includes batch IDs, packing items, assignments, payment, and delivery notes.`}function Gs(r,n){if(!Te(r)){const l=String(r?.order?.fulfillmentType||"").toUpperCase();return l==="PICKUP"?"N/A â pickup":l==="SHIPPING"?"N/A â shipping":"N/A"}const a=n?.[r?.id];return a?.milesFromDeparture!=null?`${Number(a.milesFromDeparture).toFixed(1)} mi from departure`:a?.legMilesFromPrevious!=null?`${Number(a.legMilesFromPrevious).toFixed(1)} mi from prev stop`:"â"}function kt(r=[],n={}){const{deliveryPaymentLog:a={},deliveryStaffAssignments:l={},deliveryVehicleAssignments:u={},deliveryThirdPartyAssignments:v={},staffMembers:M=[],deliveryVehicles:w=[],deliveryThirdPartyProviders:j=[],routeMilesByDeliveryId:y={},traceByDeliveryId:z={}}=n,K=["Delivery Date","Stop #","Customer","Business","Address","Status","Fulfillment","Delivery Batch ID","Order Batch ID(s)","Package Lot(s)","Items","Order Total","Payment","Paid At","Assigned Staff","Vehicle","3rd-Party Service","Miles","Completed At","Delivery Notes","Order Notes"],Y=[...r].sort((p,k)=>new Date(k.date)-new Date(p.date)||(p.route||0)-(k.route||0)).map(p=>{const k=z[p.id]||{},$=a[p.id],U=p.order?.customer,W=(k.packageLotNumbers?.length?k.packageLotNumbers:p.packageLotNumbers||[]).filter(Boolean);return[St(p.date),p.route>0?String(p.route):"â",U?.name||"â",U?.businessName||"â",ae(U)||"â",p.status||"â",p.order?.fulfillmentType==="PICKUP"?"Pickup":"Delivery",k.deliveryDisplayId||"â",(k.orderBatchIds||[]).length?k.orderBatchIds.join("; "):"â",W.length?W.join("; "):"â",Dt(p),zs(p),Pt(p,a),$?.paidAt?ft($.paidAt):"â",Ct(M,l[p.id]),Us(w,u[p.id]),Vs(j,v[p.id]),Gs(p,y),ft(p.completedAt),p.driverNotes||"â",p.order?.notes||"â"]});return[K,...Y]}function Hs({title:r,description:n,filename:a,rows:l}){const u=l.map((M,w)=>`<tr>${M.map(j=>w===0?`<th>${re(j)}</th>`:`<td>${re(j)}</td>`).join("")}</tr>`).join(""),v=`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${re(r)}</title> 7<style>body{font-family:Calibri,Arial,sans-serif;font-size:11pt}table{border-collapse:collapse;width:100%}th,td{border:1px solid #333;padding:6px;font-size:9pt}th{background:#dbeafe}</style> 8</head><body><h1>${re(r)}</h1><p>${re(n)}</p> 9<table>${u}</table><p><small>Exported ${new Date().toLocaleString()} â Deliveries</small></p></body></html>`;Es(a,new Blob(["\uFEFF",v],{type:"application/msword"}))}function Js({title:r,description:n,filename:a,rows:l}){const u=new Cs({orientation:"landscape",unit:"pt"});u.setFontSize(14),u.text(r,40,36),u.setFontSize(9),u.text(n,40,52,{maxWidth:720}),Ms(u,{startY:68,head:[l[0]||[]],body:l.slice(1),styles:{fontSize:6,cellPadding:2},headStyles:{fillColor:[37,99,235]}}),ks(a,u)}function Ks(r,n={}){const a=kt(r,n);a.length<=1&&a.push(["â","No delivery log entries","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â"]),Hs({title:"Deliveries Log",description:Mt(r),filename:"deliveries-log.doc",rows:a})}function Ys(r){const n=String(r?.order?.fulfillmentType||"").toUpperCase();return n==="PICKUP"?"Pickup":n==="SHIPPING"?"Shipping":"Delivery"}function Ws(r){const a=ye(r).reduce((l,u)=>l+(Number(u.quantity)||0),0);return a>0?a.toFixed(2):""}function Qs(r){const n=r?.lineSnapshots||[];if(!n.length)return"";const a=n.reduce((l,u)=>l+(Number(u.clamshellQtySnapshot)||0),0);return a>0?String(Math.ceil(a/4)):""}function Xs(r,n={}){const a=[];
9n.deliveryDisplayId&&a.push(n.deliveryDisplayId),Array.isArray(n.orderBatchIds)&&a.push(...n.orderBatchIds),Array.isArray(n.packageLotNumbers)?a.push(...n.packageLotNumbers):Array.isArray(r?.packageLotNumbers)&&a.push(...r.packageLotNumbers);for(const l of r?.lineSnapshots||[])l.batchId&&a.push(l.batchId),l.harvestLotId&&a.push(l.harvestLotId);return[...new Set(a.filter(Boolean))].join("; ")}function Et(r=[]){const n=new Date().toISOString().slice(0,10);return r.filter(a=>{const l=a?.date?String(a.date).slice(0,10):"";return l&&l<=n}).sort((a,l)=>{const u=String(a.date).slice(0,10);return String(l.date).slice(0,10).localeCompare(u)})}function Zs(r=[],n={}){const{deliveryPaymentLog:a={},deliveryStaffAssignments:l={},staffMembers:u=[],traceByDeliveryId:v={}}=n,M=["Delivery Date","Customer Name","Order ID","Crop / Product","Quantity (oz)","Trays","Lot Number","Driver / Delivered By","Delivery Method","Status","Payment Status","Notes"],w=Et(r).map(j=>{const y=v[j.id]||{},z=j.order?.customer,K=(y.orderBatchIds||[]).join("; ");return[St(j.date),z?.name||"",K||j.orderId||"",Dt(j),Ws(j),Qs(j),Xs(j,y),Ct(u,l[j.id]),Ys(j),j.status||"",Pt(j,a),[j.driverNotes,j.order?.notes].filter(Boolean).join(" | ")||""]});return[M,...w]}function er(r,n={}){const a=Et(r);if(!a.length)return{exported:!1};const l=Zs(a,n),u=`delivery-log-${new Date().toISOString().slice(0,10)}.csv`;return wt(u,l),{exported:!0,count:a.length}}function tr(r,n={}){const a=kt(r,n);a.length<=1&&a.push(["â","No delivery log entries","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â","â"]),Js({title:"Deliveries Log",description:Mt(r),filename:"deliveries-log.pdf",rows:a})}function sr(r){if(!r)return"";try{return new Date(r).toLocaleDateString("en-US")}catch{return""}}function bt(r){if(!r)return"";try{return new Date(r).toLocaleString("en-US")}catch{return""}}function rr(r){try{return JSON.parse(r||"[]").map(a=>`${a.productName}${a.variety?` (${a.variety})`:""} â ${a.quantity} ${a.unit||""}`.trim()).join("; ")}catch{return""}}function ar(r){const a=[["Delivery date","Customer","Items received","Status","Signer name","Signature method","Signed at","IP address","Requested by","Requested at"]];for(const l of r||[])a.push([sr(l.deliveryDateSnapshot),l.customerName||"",rr(l.itemsSnapshot),l.status||"",l.signerName||"",l.signatureMethod||"",bt(l.signedAt),l.ipAddress||"",l.createdBy||"",bt(l.createdAt)]);return a}function nr(r,n){return""}function ir(r,n,a){const l=ar(r),u=wt(`delivery-signatures${nr()}.csv`,l);return{exported:(r||[]).length>0,result:u}}function lr(){return typeof window>"u"||window.google?.maps?Promise.resolve():Promise.reject(new Error("VITE_GOOGLE_MAPS_API_KEY not set"))}const or=10,Nt="Roots & Shoots Microgreens Farm, Coral Springs, FL";function E(r){return r?.date?String(r.date).slice(0,10):""}function cr(r,n="asc"){const a=n==="desc"?-1:1;return[...r].sort((l,u)=>{const v=E(l)||"9999-99-99",M=E(u)||"9999-99-99",w=v.localeCompare(M);return w!==0?w*a:(Number(l.route)||9999)-(Number(u.route)||9999)})}function vt(r,n){const a=String(r.status||"").toUpperCase();if(["COMPLETED","CANCELLED","SKIPPED"].includes(a))return!1;if(a==="INCOMPLETE")return!0;const l=E(r);return!l||l>n?!1:a==="SCHEDULED"||a==="IN_PROGRESS"||a==="FAILED"}function jt(r,n,a){if(String(r.status||"").toUpperCase()==="CANCELLED"||!ge(r))return!1;const l=E(r);if(!l||l>a||String(r.status||"").toUpperCase()!=="COMPLETED")return!1;const u=n[r.id];return!u||u.paid!==!0}const Ir=()=>{const r=ws(),n=dt(t=>t.user),a=dt(t=>t.viewAsRole),[l,u]=m.useState([]),[v,M]=m.useState([]),[w,j]=m.useState(1),[y,z]=m.useState(f(new Date,"yyyy-MM-dd")),[K,Y]=m.useState(!1),[p,k]=m.useState(null),[$,U]=m.useState(!1),[W,Ft]=m.useState(0),[ne,V]=m.useState(0),[Lt,ie]=m.useState(!0),[x,O]=m.useState("upcoming"),[le,R]=m.useState(null),[he,At]=m.useState(!1),oe=m.useRef(null),fe=m.useRef(null),be=m.useRef(null),Ne=m.useRef(null),[Re,Ot]=m.useState(null),[ve,_]=m.useState({}),[dr,mr]=m.useState(!1),[ur,pr]=m.useState(""),[je,Be]=m.useState(""),[ze,Ue]=m.useState(!1),[It,Tt]=m.useState("PRO"),[Ve,_e]=m.useState([]),[ce,we]=m.useState({}),[qe,Ge]=m.useState([]),[Se,De]=m.useState({}),[Pe,Ce]=m.useState([]),[Me,ke]=m.useState({}),[$t,He]=m.useState({}),[F,Ee]=m.useState({}),[Q,q]=m.useState(!1),[Je,Ke]=m.useState(!1),[Rt,Ye]=m.useState({}),[L,G]=m.useState(null),[H,J]=m.useState(null),[A,X]=m.useState(null),Z=t=>xe(String(t||""),"yyyy-MM-dd",new Date);function We(t){return t?String(t).slice(0,10):""}
9function Bt(t){const s=E(t)||f(new Date,"yyyy-MM-dd"),i=f(new Date,"yyyy-MM-dd"),c=i>=s?i:s;G({delivery:t,completedDate:c,notes:t?.driverNotes||"",deliveredBy:""})}function Qe(t){const s=We(t.completedAt)||E(t)||f(new Date,"yyyy-MM-dd");J({delivery:t,completedDate:s,notes:t?.driverNotes||"",deliveredBy:t?.deliveredBy||""})}function Xe(t,s=null){const i=f(new Date,"yyyy-MM-dd");X({deliveryId:t,paymentMethod:s?.paymentMethod||"",paidDate:We(s?.paidAt)||i,isEdit:!!s?.paid})}const zt=async(t,s)=>{const i={...F,[t]:s};await T.update("deliveryPaymentLog",JSON.stringify(i)),Ee(i)},Fe=async()=>{try{const t=await C.getExportLog(),s=Array.isArray(t?.data)?t.data:[],i=new Map(s.map(c=>[c.id,c]));for(const c of l)i.has(c.id)||i.set(c.id,c);return[...i.values()]}catch(t){return console.warn("Delivery export log fetch failed, using in-memory deliveries:",t?.message||t),l}},Le=async()=>{let t={};try{t=(await C.getExportTraceMap())?.data?.byDeliveryId||{}}catch(s){console.warn("Delivery trace map unavailable for export:",s?.message||s)}return{deliveryPaymentLog:F,deliveryStaffAssignments:ce,deliveryVehicleAssignments:Se,deliveryThirdPartyAssignments:Me,staffMembers:Ve,deliveryVehicles:qe,deliveryThirdPartyProviders:Pe,routeMilesByDeliveryId:ve,traceByDeliveryId:t}},Ut=async()=>{try{q(!0);const[t,s]=await Promise.all([Fe(),Le()]);tr(t,s)}catch(t){console.error("Failed to export deliveries PDF:",t),alert("Failed to export deliveries log as PDF.")}finally{q(!1)}},Vt=async()=>{try{q(!0);const[t,s]=await Promise.all([Fe(),Le()]);Ks(t,s)}catch(t){console.error("Failed to export deliveries DOC:",t),alert("Failed to export deliveries log as DOC.")}finally{q(!1)}},_t=async()=>{try{Ke(!0);const t=await pt.getAll(),s=Array.isArray(t.data)?t.data:[],{exported:i}=ir(s);i||alert("No signature records to export.")}catch(t){console.error("Failed to export signatures CSV:",t),alert("Failed to export signature records as CSV.")}finally{Ke(!1)}},qt=async()=>{try{q(!0);const[t,s]=await Promise.all([Fe(),Le()]);er(t,s).exported||alert("No past delivery records to export.")}catch(t){console.error("Failed to export deliveries CSV:",t),alert("Failed to export deliveries log as CSV.")}finally{q(!1)}},Ze=()=>(je||"").trim()||Nt,et=async()=>{try{const s=(await me.getCostAssumptions()).data?.data;Be(s?.deliveryStartAddress||"")}catch(t){console.error("Failed to load departure address:",t)}};m.useEffect(()=>{et(),Gt(),lr().catch(()=>{})},[]);const Gt=async()=>{try{const s=(await T.getAll()).data||{};Tt(String(s.subscriptionPlan||"PRO").toUpperCase());try{_e(JSON.parse(s.staffMembers||"[]"))}catch{_e([])}try{we(JSON.parse(s.deliveryStaffAssignments||"{}"))}catch{we({})}try{Ge(JSON.parse(s.deliveryVehicles||"[]"))}catch{Ge([])}try{De(JSON.parse(s.deliveryVehicleAssignments||"{}"))}catch{De({})}try{Ce(JSON.parse(s.deliveryThirdPartyProviders||"[]"))}catch{Ce([])}try{ke(JSON.parse(s.deliveryThirdPartyAssignments||"{}"))}catch{ke({})}try{He(JSON.parse(s.orderTrackingMap||"{}"))}catch{He({})}try{Ee(JSON.parse(s.deliveryPaymentLog||"{}"))}catch{Ee({})}}catch(t){console.error("Failed to load staff settings:",t)}},Ht=String((n?.isOwnerAdmin?a:"")||n?.role||"").toUpperCase()==="ADMIN",Jt=Ss(It)||Ht,Kt=t=>{Xe(t,F[t]||null)},Yt=async()=>{if(!A?.deliveryId)return;const t=String(A.paymentMethod||"").trim();if(!t){alert("Payment method is required to mark as paid.");return}const s=String(A.paidDate||"").trim();if(!/^\d{4}-\d{2}-\d{2}$/.test(s)){alert("Please select a valid payment date.");return}await zt(A.deliveryId,{paid:!0,paidAt:new Date(`${s}T12:00:00`).toISOString(),paymentMethod:t}),X(null)},tt=t=>{t?.id&&u(s=>s.map(i=>i.id!==t.id?i:{...i,...t,order:t.order??i.order}))},Wt=async t=>{await T.update("deliveryStaffAssignments",JSON.stringify(t)),we(t)},Qt=async(t,s)=>{try{const i={...ce};s?i[t]=s:delete i[t],await Wt(i)}catch(i){console.error("Failed to assign delivery staff:",i),alert("Failed to save delivery assignment")}},Xt=async t=>{await T.update("deliveryVehicleAssignments",JSON.stringify(t)),De(t)},Zt=async(t,s)=>{try{const i={...Se};s?i[t]=s:delete i[t],await Xt(i)}catch(i){console.error("Failed to assign delivery vehicle:",i),alert("Failed to save vehicle assignment")}},es=async t=>{await T.update("deliveryThirdPartyProviders",JSON.stringify(t)),Ce(t)},ts=async t=>{await T.update("deliveryThirdPartyAssignments",JSON.stringify(t)),ke(t)},ss=async(t,s)=>{try{const i={...Me};s?i[t]=s:delete i[t],await ts(i)}catch(i){console.error("Failed to assign third-party provider:",i),alert("Failed to save third-party assignment")}},rs=async()=>{const t=window.prompt("Third-party service name (e.g., Uber Direct, DoorDash Drive):","");if(!t||!t.trim())return;
9const s=window.prompt("Contact name (optional):","")||"",i=window.prompt("Phone (optional):","")||"",c=window.prompt("Email (optional):","")||"",N=window.prompt("Notes (optional):","")||"",d={id:`tp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`,name:t.trim(),contactName:s.trim(),phone:i.trim(),email:c.trim(),notes:N.trim()},g=[...Pe,d];await es(g)};m.useEffect(()=>{de()},[y,x]),m.useEffect(()=>{is()},[ne]),m.useEffect(()=>{as()},[l,x,y,F,le]),m.useEffect(()=>{j(1)},[x,y,le,v.length]);const ee=m.useMemo(()=>Fs(v,w,or),[v,w]);m.useEffect(()=>{x==="date"||x==="today"?ns():(V(0),_({}))},[v,x]);const as=()=>{let t=l;const s=new Date;s.setHours(0,0,0,0);const i=f(s,"yyyy-MM-dd"),c=Z(y);c.setHours(0,0,0,0);const N=f(c,"yyyy-MM-dd"),d=new Date(s);d.setDate(d.getDate()+7);const g=f(d,"yyyy-MM-dd");switch(x){case"all":t=l;break;case"today":t=l.filter(b=>(b.date?String(b.date).slice(0,10):"")===i);break;case"upcoming":t=l.filter(b=>{const P=b.date?String(b.date).slice(0,10):"";return P>=i&&P<=g});break;case"past":t=l.filter(b=>(b.date?String(b.date).slice(0,10):"")<i);break;case"date":t=l.filter(b=>(b.date?String(b.date).slice(0,10):"")===N);break;case"unpaid":t=l.filter(b=>jt(b,F,i));break;case"paid":t=l.filter(b=>ge(b)?F[b.id]?.paid===!0:!1);break;case"incomplete":t=l.filter(b=>vt(b,i));break;default:t=l}const S=["past","all","incomplete","unpaid"].includes(x);t=cr(t,le??(S?"desc":"asc")),M(t)},de=async(t={})=>{const{skipOptimizedRouteFetch:s=!1,showLoading:i=!0}=t;try{i&&ie(!0);let c;c=await C.getAll(),u(c.data||[]);try{const d=await C.getExportTraceMap();Ye(d?.data?.byDeliveryId||{})}catch(d){console.warn("Delivery trace map unavailable:",d?.message||d),Ye({})}if(x==="today"||!x)try{const d=await C.getPackingList(y)}catch(d){console.error("Failed to get packing list:",d)}const N=ht((c.data||[]).filter(d=>d.date?String(d.date).slice(0,10)===y:!1));if(!s)if(N.length>0)try{const d=await C.getOptimizedRoute(y);V(d.data?.totalMiles??0);const g=Object.fromEntries((d.data?.route||[]).map(S=>[S.deliveryId,{milesFromDeparture:S.milesFromDeparture??null,legMilesFromPrevious:S.legMilesFromPrevious??null}]));_(g)}catch(d){console.error("Failed to fetch optimized route miles:",d),V(0),_({})}else V(0),_({});try{const d=await C.getPackingList(y);d.data&&k(d.data)}catch(d){console.error("Failed to get packing list:",d)}}catch(c){console.error("Failed to fetch deliveries:",c)}finally{ie(!1)}},ns=async()=>{try{const t=Array.from(new Set((v||[]).map(i=>i.date?String(i.date).slice(0,10):"").filter(Boolean))).slice(0,14);if(t.length===0)return;const s={...ve};for(const i of t)try{const c=await C.getOptimizedRoute(i),N=Object.fromEntries((c.data?.route||[]).map(d=>[d.deliveryId,{milesFromDeparture:d.milesFromDeparture??null,legMilesFromPrevious:d.legMilesFromPrevious??null}]));Object.assign(s,N)}catch(c){console.error(`Failed to hydrate route miles for ${i}:`,c)}_(s)}catch(t){console.error("Failed to hydrate route miles for visible deliveries:",t)}},is=async()=>{try{const t=await me.getCostAssumptions(),s=t.data.data?.fuelCostPerGallon??3.5,i=Math.max(t.data.data?.vehicleMpg??25,.001),c=ne/i;Ft(c*s)}catch(t){console.error("Failed to calculate fuel cost:",t)}},ls=async()=>{try{Ue(!0);const s=(await me.getCostAssumptions()).data?.data;if(!s)throw new Error("Cost assumptions not loaded");await me.updateCostAssumptions({...s,deliveryStartAddress:je.trim()||null}),await et(),await de()}catch(t){console.error("Failed to save departure address:",t),alert(t.response?.data?.error||t.message||"Failed to save departure address")}finally{Ue(!1)}},os=async()=>{try{ie(!0);const t=await C.syncFromOrders(y);await de(),await st(),l.length>0&&await Ae(),alert(t.data?.message||t?.data||`Synced deliveries for ${f(Z(y),"MMM d, yyyy")}`)}catch(t){console.error("Failed to sync deliveries:",t);const s=t.response?.data?.error||t.message||"Failed to sync deliveries from orders";alert(`Failed to sync deliveries: ${s}`)}finally{ie(!1)}},Ae=async()=>{try{U(!0);const t=await C.getOptimizedRoute(y);Ot(t.data),V(t.data.totalMiles||0);const s=Object.fromEntries((t.data?.route||[]).map(i=>[i.deliveryId,{milesFromDeparture:i.milesFromDeparture??null,legMilesFromPrevious:i.legMilesFromPrevious??null}]));_(s),await de({skipOptimizedRouteFetch:!0}),alert(`Route optimized! ${t.data.deliveries} stops, ${t.data.totalMiles} miles, ~${t.data.estimatedTimeHours} hours`)}catch(t){console.error("Failed to optimize route:",t),alert("Failed to optimize route")}finally{U(!1)}},cs=()=>{r("/settings?tab=notifications")},ds=()=>{const t=Ze(),s=l.filter(g=>g.date&&String(g.date).slice(0,10)===y).map(g=>
9ae(g.order?.customer)).filter(Boolean);if(s.length===0){alert("No delivery addresses found. Please make sure customer addresses are entered correctly.");return}const i=encodeURIComponent(s[s.length-1]),c=s.slice(0,-1).map(g=>encodeURIComponent(g)).join("|"),d=`https://www.google.com/maps/dir/?api=1&origin=${encodeURIComponent(t)}&destination=${i}&waypoints=${c}&travelmode=driving&dir_action=navigate`;console.log("Opening Google Maps with URL:",d),window.open(d,"_blank")},ms=()=>new Promise((t,s)=>{if(!window.google||!window.google.maps){s(new Error("Google Maps not loaded"));return}const i=Ze(),c=ht(l.filter(g=>g.date&&String(g.date).slice(0,10)===y)).map(g=>ae(g.order?.customer)).filter(Boolean);if(c.length===0){s(new Error("No delivery addresses found. Please ensure customer addresses are entered."));return}console.log("Optimizing route with addresses:",c),be.current||(be.current=new window.google.maps.DirectionsService);const N=c.slice(0,-1).map(g=>({location:g,stopover:!0})),d={origin:i,destination:c[c.length-1],waypoints:N,optimizeWaypoints:!0,travelMode:window.google.maps.TravelMode.DRIVING};be.current.route(d,(g,S)=>{if(S==="OK"){Ne.current&&Ne.current.setDirections(g);const D=g.routes[0];let b=0;D.legs.forEach(o=>{b+=o.distance.value});const P=b/1609.34;V(P),console.log("Optimized Stop Order:",D.waypoint_order),console.log("Total Distance:",P.toFixed(2),"miles"),t(g)}else console.error("Directions request failed:",S),s(new Error(`Directions request failed: ${S}`))})}),us=()=>{if(!window.google||!window.google.maps||!oe.current){console.warn("Google Maps not ready or map ref not available");return}fe.current||(fe.current=new window.google.maps.Map(oe.current,{zoom:10,center:{lat:26.2712,lng:-80.2706},mapTypeControl:!0,streetViewControl:!1,fullscreenControl:!0}),Ne.current=new window.google.maps.DirectionsRenderer({map:fe.current,suppressMarkers:!1,draggable:!1})),l.filter(s=>s.date&&String(s.date).slice(0,10)===y).length>0&&ms().catch(s=>{console.error("Failed to load initial route:",s)})};m.useEffect(()=>{he&&oe.current&&setTimeout(()=>{us()},100)},[he]);const st=async()=>{try{let t;x==="today"?t=f(new Date,"yyyy-MM-dd"):t=y,console.log("Generating packing list for:",t);const s=await C.getPackingList(t);if(console.log("Packing list response:",s.data),!s.data)throw new Error("No packing list data received");k(s.data),Y(!0)}catch(t){console.error("Failed to generate packing list:",t),alert(`Failed to generate packing list: ${t.message}`)}},te=async(t,s,i={})=>{try{const c=await C.update(t,{status:s,...i});return tt(c.data),c.data}catch(c){return console.error("Failed to update delivery status:",c),alert(c?.response?.data?.detail||c?.response?.data?.error||"Failed to update delivery"),null}},ps=async t=>{const s=window.prompt(`Why was this delivery incomplete? (required) 10 11Product for this batch will be logged as surplus for traceability.`,"");if(s===null)return;const i=String(s||"").trim();if(!i){alert("A reason is required to mark a delivery incomplete.");return}await te(t.id,"INCOMPLETE",{driverNotes:`Incomplete: ${i}`,incompleteReason:i})&&alert("Delivery marked incomplete. Surplus and trace records were updated for matching grow cycles.")},rt=t=>{Bt(t)},xs=async()=>{if(!L?.delivery)return;const{delivery:t,completedDate:s,notes:i,deliveredBy:c}=L,N=String(s||"").trim();if(!/^\d{4}-\d{2}-\d{2}$/.test(N)){alert("Please select a valid completion date.");return}const d={completedAt:new Date(`${N}T12:00:00`).toISOString(),deliveredBy:String(c||"").trim()||null},g=String(i||"").trim();g&&(d.driverNotes=g);const S=await te(t.id,"COMPLETED",d);if(G(null),!!S)try{const D=N,b=Re&&y===D&&parseFloat(Re.estimatedTimeHours)||null,P=b||1,o=new Date(`${D}T09:00:00`),h=new Date(o.getTime()+P*3600*1e3),I=t.order?.customer?.businessName||t.order?.customer?.name||"",se={taskType:"DELIVERY",taskDescription:`Delivery${I?` â ${I}`:""}`,startTime:o.toISOString(),endTime:h.toISOString(),customLaborCost:null,notes:b?`Auto-logged from delivery completion (est. route time: ${b}h)`:"Auto-logged from delivery completion â adjust time as needed"},it=await Ps.create(se),lt=it?.data?.data??it?.data,ot=ce[t.id];if(lt?.id&&ot){const vs=await T.getAll(),ct=(()=>{try{return JSON.parse(vs.data?.laborStaffAssignments||"{}")}catch{return{}}})();ct[lt.id]=ot,await T.update("laborStaffAssignments",JSON.stringify(ct))}}catch(D){console.error("Failed to auto-log delivery labor:",D)}},gs=async()=>
11{if(!H?.delivery)return;const{delivery:t,completedDate:s,notes:i,deliveredBy:c}=H,N=String(s||"").trim();if(!/^\d{4}-\d{2}-\d{2}$/.test(N)){alert("Please select a valid completion date.");return}try{const d=await C.update(t.id,{status:"COMPLETED",completedAt:new Date(`${N}T12:00:00`).toISOString(),driverNotes:String(i||"").trim()||null,deliveredBy:String(c||"").trim()||null});tt(d.data),J(null)}catch(d){console.error("Failed to update completed delivery:",d),alert(d?.response?.data?.detail||d?.response?.data?.error||"Failed to save changes")}};if(Lt)return e.jsx("div",{className:"flex justify-center items-center h-64",children:"Loading..."});const ys=l.filter(t=>t.date?$s(B(String(t.date).slice(0,10))):!1),Oe=f(new Date,"yyyy-MM-dd"),hs=["past","all","incomplete","unpaid"].includes(x),at=le??(hs?"desc":"asc"),nt=l.filter(t=>vt(t,Oe)).length,fs=(()=>{switch(x){case"today":return`Today â ${f(new Date,"MMM d, yyyy")}`;case"upcoming":return"Upcoming (next 7 days)";case"past":return"Past deliveries";case"incomplete":return"Needs action â incomplete or past due";case"unpaid":return"Unpaid completed deliveries";case"paid":return"Paid deliveries";case"all":return"All deliveries";case"date":return f(Z(y),"MMM d, yyyy");default:return f(Z(y),"MMM d, yyyy")}})(),bs=l.filter(t=>(t.date?String(t.date).slice(0,10):"")>=Oe).length,Ns={SCHEDULED:"bg-blue-100 text-blue-800",IN_PROGRESS:"bg-yellow-100 text-yellow-800",COMPLETED:"bg-green-100 text-green-800",INCOMPLETE:"bg-orange-100 text-orange-800",FAILED:"bg-red-100 text-red-800",SKIPPED:"bg-amber-100 text-amber-800"};return e.jsxs("div",{className:"space-y-6 min-w-0 max-w-full overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col gap-4 min-w-0",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:items-start xl:justify-between gap-4 min-w-0",children:[e.jsx("div",{className:"min-w-0 shrink flex-1",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between min-w-0",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-800",children:"Deliveries"}),e.jsx("p",{className:"text-gray-600 mt-1 text-sm sm:text-base",children:"Manage delivery routes and packing lists"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide w-full sm:w-auto sm:mr-1",children:"Export log"}),e.jsxs("button",{type:"button",onClick:qt,disabled:Q,className:"btn-secondary flex items-center gap-2 text-sm",title:"Export past delivery records as CSV (excludes future scheduled deliveries)",children:[e.jsx(xt,{className:"w-4 h-4"}),Q?"Exportingâ¦":"Export Log"]}),e.jsxs("button",{type:"button",onClick:_t,disabled:Je,className:"btn-secondary flex items-center gap-2 text-sm",title:"Export all delivery signature records as CSV",children:[e.jsx(xt,{className:"w-4 h-4"}),Je?"Exportingâ¦":"Export Signatures"]}),e.jsxs("button",{type:"button",onClick:Ut,disabled:Q,className:"btn-secondary flex items-center gap-2 text-sm",title:"Export full deliveries log as PDF (batch IDs, notes, payment, assignments)",children:[e.jsx(Ie,{className:"w-4 h-4"}),Q?"Exportingâ¦":"Export PDF"]}),e.jsxs("button",{type:"button",onClick:Vt,disabled:Q,className:"btn-secondary flex items-center gap-2 text-sm",title:"Export full deliveries log as Word-compatible DOC",children:[e.jsx(As,{className:"w-4 h-4"}),"Export DOC"]})]})]})}),e.jsxs("div",{className:"card p-4 w-full xl:max-w-md shrink-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 mb-2",children:"Route starts from"}),e.jsx("input",{type:"text",className:"input w-full text-sm",placeholder:Nt,value:je,onChange:t=>Be(t.target.value)}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Saved with your cost assumptions. Used for Maps links and mileage estimates (same defaults as Financials, Delivery and Fuel)."}),e.jsx("button",{type:"button",onClick:ls,disabled:ze,className:"btn-secondary mt-2 text-sm",children:ze?"Savingâ¦":"Save departure address"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row flex-wrap gap-2 items-stretch sm:items-center min-w-0",children:[e.jsx("input",{type:"date",value:y,onChange:t=>{z(t.target.value),O("date"),R(null)},className:"input w-full sm:w-auto min-w-0 shrink-0"}),e.jsxs("button",{onClick:os,className:"btn-secondary flex items-center justify-center gap-2 text-sm whitespace-nowrap",children:[e.jsx(mt,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:"Sync from Orders"})]}),e.jsxs("button",{onClick:Ae,disabled:v.length===0||$,className:"btn-primary flex items-center justify-center gap-2 bg-purple-600 hover:bg-purple-700 text-sm whitespace-nowrap",children:[e.jsx(pe,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:$?"Optimizing...":"Optimize Route"})]}),e.jsxs("button",{onClick:ds,disabled:v.length===0,className:"btn-primary flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 text-sm whitespace-nowrap",children:[e.jsx(gt,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:"Open in Maps"})]}),e.jsxs("button",{onClick:st,disabled:v.length===0,className:"btn-success flex items-center justify-center gap-2 text-sm whitespace-nowrap",children:[e.jsx(Ie,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:"Packing List"})]}),e.jsxs("button",{onClick:cs,className:"btn-primary flex items-center justify-center gap-2 bg-violet-600 hover:bg-violet-700 text-sm whitespace-nowrap",title:"Configure customer reminder notifications in Settings",children:[e.jsx(Ds,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:"Notification Settings"})]}),e.jsxs("button",{onClick:rs,className:"btn-secondary flex items-center justify-center gap-2 text-sm whitespace-nowrap",children:[e.jsx(Os,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:"Add 3rd-Party Service"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-6",children:[e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Scheduled Today"}),e.jsx("p",{className:"text-2xl font-bold text-gray-800",children:ys.length})]}),e.jsx(ut,{className:"w-8 h-8 text-blue-600"})]})}),e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:x==="all"?"All Deliveries":x==="today"?"Today's Deliveries":x==="upcoming"?"This Week":x==="past"?"Past Deliveries":x==="incomplete"?"Needs Action":x==="unpaid"?"Unpaid Deliveries":x==="paid"?"Paid Deliveries":x==="date"?"Selected Date":"Filtered Deliveries"}),e.jsx("p",{className:"text-2xl font-bold text-gray-800",children:x==="all"?bs:v.length})]}),e.jsx(ue,{className:"w-8 h-8 text-green-600"})]})}),e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Est. Miles"}),e.jsx("p",{className:"text-2xl font-bold text-gray-800",children:ne.toFixed(1)})]}),e.jsx(pe,{className:"w-8 h-8 text-purple-600"})]})}),e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Fuel Cost"}),e.jsxs("p",{className:"text-2xl font-bold text-gray-800",children:["$",W.toFixed(2)]})]}),e.jsx(Bs,{className:"w-8 h-8 text-orange-600"})]})})]}),e.jsxs("div",{className:"card min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row lg:justify-between lg:items-center gap-3 mb-4 min-w-0",children:[e.jsxs("h3",{className:"text-lg sm:text-xl font-semibold min-w-0 break-words pr-2",children:["Delivery Schedule â ",fs]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsx("button",{onClick:()=>{O("today"),z(f(new Date,"yyyy-MM-dd")),R(null)},className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="today"?"bg-primary-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:"Today"}),e.jsx("button",{onClick:()=>{O("upcoming"),R(null)},className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="upcoming"?"bg-primary-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:"Upcoming"}),e.jsx("button",{onClick:()=>{O("all"),R(null)},className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="all"?"bg-primary-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:"All"}),e.jsxs("button",{onClick:()=>{O("incomplete"),R(null)},className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="incomplete"?"bg-orange-600 text-white":"bg-orange-50 text-orange-700 hover:bg-orange-100 border border-orange-200"}`,children:["Needs action",nt>0?e.jsx("span",{className:"ml-1.5 bg-orange-500 text-white text-xs rounded-full px-1.5 py-0.5",children:nt}):null]}),e.jsx("button",{onClick:()=>{O("past"),R(null)},className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="past"?"bg-primary-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:"Past"}),e.jsxs("button",{onClick:()=>R(t=>t==="asc"?"desc":t==="desc"?"asc":at==="asc"?"desc":"asc"),className:"px-3 py-2 rounded-lg text-sm font-medium bg-gray-100 text-gray-700 hover:bg-gray-200",title:"Toggle sort by scheduled date",children:["Date ",at==="asc"?"â
11":"â"]}),e.jsxs("button",{onClick:()=>O("unpaid"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="unpaid"?"bg-orange-600 text-white":"bg-orange-50 text-orange-700 hover:bg-orange-100 border border-orange-200"}`,children:["Unpaid",(()=>{const t=l.filter(s=>jt(s,F,Oe)).length;return t>0?e.jsx("span",{className:"ml-1.5 bg-orange-500 text-white text-xs rounded-full px-1.5 py-0.5",children:t}):null})()]}),e.jsx("button",{onClick:()=>O("paid"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${x==="paid"?"bg-green-600 text-white":"bg-green-50 text-green-700 hover:bg-green-100 border border-green-200"}`,children:"Paid"}),x==="date"&&e.jsx("span",{className:"px-4 py-2 rounded-lg text-sm font-medium bg-blue-600 text-white",children:f(Z(y),"MMM d, yyyy")})]})]}),v.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500",children:[e.jsx(ut,{className:"w-16 h-16 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"text-lg",children:"No deliveries scheduled"}),e.jsx("p",{className:"text-sm",children:'Click "Sync from Orders" to create deliveries from active orders'})]}):e.jsxs("div",{className:"space-y-4",children:[ee.slice.map(t=>{const s=ye(t),i=$e(t),c={},N={};s.forEach(o=>{if(o.crop){const h=o.crop.cropName;c[h]||(c[h]=0),c[h]+=o.quantity||0}else if(o.blend){const h=o.blend.name;N[h]||(N[h]={blend:o.blend,quantity:0}),N[h].quantity+=o.quantity||0}});const d=String(t.status||"").toUpperCase()==="SKIPPED",g=String(t.status||"").toUpperCase()==="INCOMPLETE",S=!!ae(t.order?.customer),D=ve[t.id],P=t.order?.fulfillmentType==="PICKUP"?"N/A â pickup":D?.milesFromDeparture!=null?`${Number(D.milesFromDeparture).toFixed(1)} mi from departure`:D?.legMilesFromPrevious!=null?`${Number(D.legMilesFromPrevious).toFixed(1)} mi from prev stop`:S?Te(t)?"Calculating...":"N/A":"Add address in Customers";return e.jsx("div",{className:`border rounded-lg p-4 hover:shadow-md transition-shadow ${d?"opacity-60 bg-amber-50 border-amber-200":""} ${g?"bg-orange-50 border-orange-200":""}`,children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center flex-wrap gap-2 mb-2",children:[d&&e.jsx("span",{className:"bg-amber-100 text-amber-800 px-3 py-1 rounded-full text-sm font-semibold line-through",children:"SKIPPED"}),t.route>0&&!d&&e.jsxs("span",{className:"bg-primary-100 text-primary-800 px-3 py-1 rounded-full text-sm font-semibold",children:["Stop #",t.route]}),e.jsx("span",{className:`bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium ${d?"line-through":""}`,children:f(B(String(t.date).slice(0,10)),"MMM d, yyyy")}),e.jsx("h4",{className:`font-semibold text-lg ${d?"line-through text-gray-400":""}`,children:t.order?.customer?.name||"Unknown Customer"}),t.order?.fulfillmentType==="PICKUP"&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-amber-100 text-amber-800",children:"Pickup"}),t.order?.customer?.businessName&&e.jsxs("span",{className:"text-sm text-gray-600",children:["(",t.order.customer.businessName,")"]})]}),(()=>{const o=Rt[t.id],h=o?.orderBatchIds||[],I=o?.deliveryDisplayId,se=o?.packageLotNumbers?.length?o.packageLotNumbers:t.packageLotNumbers||[];return!h.length&&!I&&!se.length?null:e.jsxs("div",{className:"text-xs font-mono mb-2 space-y-1 bg-emerald-50 border border-emerald-100 rounded-lg px-3 py-2",children:[I&&e.jsxs("div",{className:"text-emerald-900",children:[e.jsx("span",{className:"text-gray-600 font-sans",children:"Delivery batch: "}),I]}),h.length>0&&e.jsxs("div",{className:"text-emerald-800",children:[e.jsx("span",{className:"text-gray-600 font-sans",children:"Order batch(es): "}),h.join(" · ")]}),se.length>0&&e.jsxs("div",{className:"text-emerald-800",children:[e.jsx("span",{className:"text-gray-600 font-sans",children:"Package lot(s): "}),se.join(" · ")]})]})})(),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm mb-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Is,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:`text-gray-600 ${d?"line-through":""}`,children:ae(t.order?.customer)||e.jsx("span",{className:"text-amber-600 italic",children:"No address set"})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ue,{className:"w-4 h-4 text-gray-500"}),e.jsxs("span",{className:"text-gray-600",children:[s.length," items"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(mt,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-gray-600",children:t.order?.customer?.deliveryTime||"Any time"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(pe,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:`${S?"text-gray-600":"text-amber-600 italic"}`,children:P})]}),(Number(i.totalPrice)>0||i.customPrice!=null)&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-gray-500 font-medium text-xs",children:"$"}),i.customPrice!=null?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-yellow-700 font-semibold",children:["$",Number(i.customPrice).toFixed(2)]}),e.jsxs("span",{className:"text-xs text-yellow-600",children:["(custom",i.customPriceNote?`: ${i.customPriceNote}`:"",")"]}),e.jsxs("span",{className:"text-xs text-gray-400 line-through",children:["$",Number(i.totalPrice).toFixed(2)]})]}):e.jsxs("span",{className:"text-gray-700 font-semibold",children:["$",Number(i.totalPrice).toFixed(2)]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:`px-3 py-1 rounded-full text-xs font-medium ${Ns[t.status]||"bg-gray-100 text-gray-800"}`,children:t.status}),ge(t)&&(()=>{const o=F[t.id];return o?o.paid===!0?e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-700",children:["â Paid",o.paymentMethod?` · ${o.paymentMethod}`:"",o.paidAt?` · ${f(B(String(o.paidAt).slice(0,10)),"MMM d, yyyy")}`:""]}):e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-semibold bg-orange-100 text-orange-700",children:["â³ Unpaid",o.paymentMethod?` · ${o.paymentMethod}`:""]}):e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500",children:"Not paid"})})(),ge(t)&&(()=>{const o=F[t.id];return o?.paid===!0?e.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),Xe(t.id,o)},className:"px-2 py-0.5 rounded text-xs font-semibold bg-green-50 text-green-800 border border-green-200 hover:bg-green-100 transition-colors",children:"Edit payment"}):e.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),Kt(t.id)},className:"px-2 py-0.5 rounded text-xs font-semibold bg-green-600 text-white hover:bg-green-700 transition-colors",children:"Mark as Paid"})})()]}),Jt&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 block mb-1",children:"Assigned Staff (Pro)"}),e.jsxs("select",{className:"input w-full text-sm",value:ce[t.id]||"",onChange:o=>Qt(t.id,o.target.value),children:[e.jsx("option",{value:"",children:"-- Unassigned --"}),e.jsx("option",{value:"__manager__",children:"Manager"}),Ve.map(o=>e.jsx("option",{value:o.id,children:o.name},o.id))]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 block mb-1",children:"Delivery Vehicle"}),e.jsxs("select",{className:"input w-full text-sm",value:Se[t.id]||"",onChange:o=>Zt(t.id,o.target.value),children:[e.jsx("option",{value:"",children:"-- Unassigned --"}),qe.map(o=>e.jsx("option",{value:o.id,children:[o.year,o.make,o.model,o.color].filter(
11Boolean).join(" ")||"Vehicle"},o.id))]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 block mb-1",children:"3rd-Party Delivery Service"}),e.jsxs("select",{className:"input w-full text-sm",value:Me[t.id]||"",onChange:o=>ss(t.id,o.target.value),children:[e.jsx("option",{value:"",children:"-- None / In-house --"}),Pe.map(o=>e.jsxs("option",{value:o.id,children:[o.name,o.contactName?` ⢠${o.contactName}`:"",o.phone?` ⢠${o.phone}`:""]},o.id))]})]})]}),d?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 p-3 rounded-lg mt-3",children:[e.jsx("p",{className:"text-sm text-amber-700 font-medium line-through",children:"This delivery has been skipped. Associated grow tasks and cycles are marked skipped."}),t.driverNotes&&e.jsx("p",{className:"text-xs text-amber-600 mt-1",children:t.driverNotes})]}):e.jsxs("div",{className:"bg-gray-50 p-3 rounded-lg mt-3",children:[e.jsx("h5",{className:"font-semibold text-sm mb-2 text-gray-700",children:"Packing List:"}),e.jsxs("div",{className:"space-y-1",children:[Object.entries(c).map(([o,h])=>e.jsxs("div",{className:"text-sm text-gray-700",children:["⢠",o,": ",h.toFixed(1)," oz"]},o)),Object.values(N).map((o,h)=>e.jsxs("div",{className:"text-sm text-gray-700",children:["⢠",o.blend.name,": ",o.quantity.toFixed(1)," oz",o.blend.items&&e.jsxs("span",{className:"text-gray-500 ml-2",children:["(",o.blend.items.map(I=>I.crop?.cropName).filter(Boolean).join(", "),")"]})]},h))]}),Object.keys(c).length===0&&Object.keys(N).length===0&&e.jsx("p",{className:"text-sm text-gray-500 italic",children:"No items"})]}),(i.notes||t.order?.notes)&&e.jsxs("p",{className:"text-sm text-gray-600 italic mt-2",children:["ð ",i.notes||t.order?.notes]}),(()=>{const o=t.order?.id;if(!o)return null;const h=$t[o];return h?.trackingUrl?e.jsxs("a",{href:h.trackingUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800 mt-2",children:[e.jsx(Ts,{className:"w-4 h-4"}),"Track Order"]}):null})(),(t.driverNotes||t.completedAt)&&e.jsxs("div",{className:"mt-2 text-sm text-gray-700 bg-green-50 border border-green-200 rounded p-2",children:[t.completedAt?e.jsxs("p",{children:["Completed: ",f(B(String(t.completedAt).slice(0,10)),"MMM d, yyyy"),E(t)&&E(t)!==String(t.completedAt).slice(0,10)?e.jsxs("span",{className:"text-gray-600",children:[" ","(scheduled ",f(B(E(t)),"MMM d, yyyy"),")"]}):null]}):null,t.driverNotes?e.jsxs("p",{children:["Delivery Notes: ",t.driverNotes]}):null,String(t.status||"").toUpperCase()==="COMPLETED"&&e.jsx("button",{type:"button",onClick:()=>Qe(t),className:"mt-2 text-xs font-semibold text-green-800 underline hover:text-green-950",children:"Edit completion date / notes"})]})]}),e.jsx("div",{className:"flex flex-col space-y-2 ml-4",children:d?e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-xs text-amber-600 font-medium bg-amber-50 border border-amber-200 px-2 py-1 rounded",children:"Skipped"}),e.jsx("button",{onClick:()=>te(t.id,"SCHEDULED"),className:"btn-secondary text-xs mt-1 w-full",children:"Restore"})]}):g?e.jsxs("div",{className:"text-center space-y-1",children:[e.jsx("span",{className:"text-xs text-orange-700 font-medium bg-orange-100 border border-orange-200 px-2 py-1 rounded block mb-1",children:"Incomplete"}),e.jsx("button",{type:"button",onClick:()=>rt(t),className:"btn-success text-xs w-full",children:"Complete"}),e.jsx("button",{type:"button",onClick:()=>te(t.id,"SCHEDULED",{driverNotes:null}),className:"btn-secondary text-xs w-full",children:"Restore to scheduled"})]}):String(t.status||"").toUpperCase()==="COMPLETED"?e.jsxs("div",{className:"text-center space-y-1",children:[e.jsx("span",{className:"text-xs text-green-700 font-medium bg-green-100 border border-green-200 px-2 py-1 rounded block mb-1",children:"Completed"}),e.jsx("button",{type:"button",onClick:()=>Qe(t),className:"btn-secondary text-xs w-full",children:"Edit date / notes"}),e.jsx("button",{type:"button",onClick:async()=>{try{const o=await pt.create(t.id),h=`${window.location.origin}/#/sign/${o.data.token}`;await navigator.clipboard.writeText(h).catch(()=>{}),window.prompt("Signature link created (copied to clipboard). Send this to the customer:",h)}catch(o){alert(o?.response?.data?.error||"Failed to create signature request")}},className:"btn-secondary text-xs w-full",children:"Send signature request"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>te(t.id,"IN_PROGRESS"),disabled:t.status==="COMPLETED"||t.status==="INCOMPLETE",className:"btn-secondary text-sm",children:"Start"}),e.jsx("button",{onClick:()=>rt(t),disabled:t.status==="COMPLETED"||t.status==="INCOMPLETE",className:"btn-success text-sm",children:t.order?.fulfillmentType==="PICKUP"?"Complete pickup":"Complete"}),e.jsx("button",{type:"button",onClick:()=>ps(t),disabled:t.status==="COMPLETED"||t.status==="INCOMPLETE",className:"btn-secondary text-sm border-orange-300 text-orange-800 hover:bg-orange-50",children:"Mark incomplete"})]})})]})},t.id)}),e.jsx(Ls,{page:ee.page,totalPages:ee.totalPages,total:ee.total,pageSize:ee.pageSize,onPageChange:j})]})]}),he&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"bg-white border-b px-6 py-4 flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold text-gray-800 flex items-center space-x-2",children:[e.jsx(gt,{className:"w-6 h-6 text-blue-600"}),e.jsx("span",{children:"Delivery Route Map"})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-1",children:["Optimized route for ",f(xe(y,"yyyy-MM-dd",new Date),"MMM d, yyyy")]})]}),e.jsx("button",{onClick:()=>At(!1),className:"text-gray-400 hover:text-gray-600",children:e.jsx(yt,{className:"w-6 h-6"})})]}),e.jsx("div",{className:"flex-1 p-4",children:e.jsx("div",{ref:oe,className:"w-full h-full rounded-xl border-2 border-gray-200",style:{minHeight:"500px"}})}),e.jsx("div",{className:"bg-gray-50 border-t px-6 py-4",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex space-x-6",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Total Distance:"}),e.jsxs("span",{className:"ml-2 text-lg font-bold text-blue-600",children:[ne.toFixed(2)," miles"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Estimated Fuel Cost:"}),e.jsxs("span",{className:"ml-2 text-lg font-bold text-green-600",children:["$",W.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Stops:"}),e.jsx("span",{className:"ml-2 text-lg font-bold text-purple-600",children:l.filter(t=>t.date&&String(t.date).slice(0,10)===y).length})]})]}),e.jsxs("button",{onClick:Ae,disabled:$,className:"btn-primary flex items-center space-x-2",children:[e.jsx(pe,{className:"w-4 h-4"}),e.jsx("span",{children:$?"Optimizing...":"Re-optimize Route"})]})]})})]})}),K&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-3 sm:p-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto min-w-0",children:[e.jsxs("div",{className:"sticky top-0 bg-white border-b px-6 py-4 rounded-t-2xl flex justify-between items-center",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-800",children:"ð¦ Packing List"}),e.jsx("button",{onClick:()=>Y(!1),className:"text-gray-400 hover:text-gray-600",children:e.jsx(yt,{className:"w-6 h-6"})})]}),p?p.deliveries===0?e.jsxs("div",{className:"p-6 text-center text-gray-500",children:[e.jsx(ue,{className:"w-16 h-16 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"text-lg font-medium",children:"No Deliveries Scheduled"}),e.jsxs("p",{className:"text-sm mt-2",children:["No packing list needed for ",f(xe(y,"yyyy-MM-dd",new Date),"MMM d, yyyy")]})]}):e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsx("div",{className:"bg-gradient-to-r from-blue-50 to-primary-50 p-4 rounded-lg border border-blue-200 min-w-0",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg text-gray-800",children:f(xe(y,"yyyy-MM-dd",new Date),"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-sm text-gray-600 mt-1",children:[p.deliveries," ",p.deliveries===1?"delivery":"deliveries"," scheduled"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase",children:"Total Needed"}),e.jsxs("p",{className:"text-2xl font-bold text-primary-600",children:[p.totals?.totalClamshells||0," containers"]})]})]})}),p.totals&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4 min-w-0",children:[e.jsxs("div",{className:"bg-green-50 p-4 rounded-lg border border-green-200",children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase mb-1",children:"Total Clamshells"}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:p.totals.totalClamshells})]}),e.jsxs("div",{className:"bg-blue-50 p-4 rounded-lg border border-blue-200",children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase mb-1",children:"Total Ounces"}),e.jsxs("p",{className:"text-2xl font-bold text-blue-700",children:[p.totals.totalOz," oz"]})]}),e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg border border-purple-200",children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase mb-1",children:"Est. Trays"}),e.jsx("p",{className:"text-2xl font-bold text-purple-700",children:p.totals.totalTrays})]})]}),(()=>{const t=p.byOrder?.length>0?p.byOrder:(p.byCustomer||[]).map(s=>({title:`Order â ${s.customer}`,stopNumber:null,items:s.items||[]}));return t.length?e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-bold text-lg mb-2 text-gray-800",children:"Pack by stop (per order)"}),e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Each block
11is one delivery. Pack these bags/boxes together for that drop-off. Order matches your route stop when optimized."}),e.jsx("div",{className:"space-y-4",children:t.map((s,i)=>e.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2 gap-y-1 mb-3 pb-2 border-b border-gray-200",children:[e.jsx("p",{className:"font-semibold text-gray-900 text-base break-words pr-2",children:s.title||`Order â ${s.customerName||"Customer"}`}),s.stopNumber!=null?e.jsxs("span",{className:"text-xs font-medium px-2 py-1 rounded-full bg-primary-100 text-primary-800 shrink-0",children:["Stop #",s.stopNumber]}):null]}),e.jsx("ul",{className:"space-y-2",children:(s.items||[]).map((c,N)=>e.jsxs("li",{className:"flex flex-wrap justify-between gap-x-4 gap-y-1 text-sm border-b border-gray-100 last:border-0 pb-2 last:pb-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"font-medium text-gray-800 break-words",children:c.name}),e.jsx("span",{className:`ml-2 text-xs px-1.5 py-0.5 rounded ${c.type==="crop"?"bg-green-100 text-green-800":"bg-purple-100 text-purple-800"}`,children:c.type==="crop"?"Crop":"Blend"}),c.type==="blend"&&c.breakdown&&c.breakdown.length>0&&e.jsx("div",{className:"mt-1 text-xs text-gray-600 space-y-0.5",children:c.breakdown.map((d,g)=>e.jsxs("p",{children:[d.name,": ",d.oz," oz (",d.percentage,"%)"]},g))})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("p",{className:"font-semibold text-gray-900 tabular-nums",children:[Number(c.quantity).toFixed(1)," oz"]}),e.jsxs("p",{className:"text-xs text-gray-500 tabular-nums",children:[c.clamshells," clamshell",c.clamshells===1?"":"s"]})]})]},c.orderItemId||`${s.orderId}-${N}`))})]},s.deliveryId||s.orderId||i))})]}):null})(),p.items&&p.items.length>0&&e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-bold text-lg mb-3 text-gray-800",children:"All items this day (totals)"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Combined quantities across every order (use for bulk harvest/pack totals)."}),e.jsx("div",{className:"space-y-2",children:p.items.map((t,s)=>e.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-3 flex flex-wrap justify-between gap-2 min-w-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"font-semibold text-gray-800 break-words",children:t.name}),e.jsx("span",{className:`ml-2 text-xs px-2 py-0.5 rounded ${t.type==="crop"?"bg-green-100 text-green-800":"bg-purple-100 text-purple-800"}`,children:t.type==="crop"?"Crop":"Blend"}),t.type==="blend"&&t.crops&&t.crops.length>0&&e.jsx("div",{className:"mt-2 text-xs text-gray-600 space-y-1",children:t.crops.map((i,c)=>e.jsxs("p",{className:"ml-1",children:[i.name,": ",i.percentage,"%"]},c))})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("p",{className:"text-lg font-bold text-primary-600 tabular-nums",children:[t.quantity," oz"]}),e.jsxs("p",{className:"text-xs text-gray-500",children:[t.clamshells," containers"]})]})]},s))})]}),e.jsxs("div",{className:"flex space-x-3 pt-4 border-t",children:[e.jsxs("button",{onClick:()=>window.print(),className:"btn-primary flex-1",children:[e.jsx(Ie,{className:"w-5 h-5 inline mr-2"}),"Print Packing List"]}),e.jsx("button",{onClick:()=>Y(!1),className:"btn-secondary flex-1",children:"Close"})]})]}):e.jsxs("div",{className:"p-6 text-center text-gray-500",children:[e.jsx(ue,{className:"w-16 h-16 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Loading packing list..."})]})]})}),L&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-md p-6 space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:L.delivery?.order?.fulfillmentType==="PICKUP"?"Complete pickup":"Complete delivery"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Scheduled:"," ",E(L.delivery)?f(B(E(L.delivery)),"MMM d, yyyy"):"â"]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Completion date"}),e.jsx("input",{type:"date",className:"input w-full",value:L.completedDate,onChange:t=>G(s=>({...s,completedDate:t.target.value}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Delivered by"}),e.jsx("input",{type:"text",className:"input w-full",value:L.deliveredBy,onChange:t=>G(s=>({...s,deliveredBy:t.target.value})),placeholder:"Who physically delivered this order?"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Delivery notes (optional)"}),e.jsx("textarea",{className:"input w-full min-h-[80px]",value:L.notes,onChange:t=>G(s=>({...s,notes:t.target.value})),placeholder:"Left at door, customer signature, etc."})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx("button",{type:"button",className:"btn-secondary flex-1",onClick:()=>G(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"btn-success flex-1",onClick:xs,children:"Save & complete"})]})]})}),H&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-md p-6 space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Edit completed delivery"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Update the actual completion date or notes if something was logged incorrectly. Trace records will sync to the corrected date."}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Completion date"}),e.jsx("input",{type:"date",className:"input w-full",value:H.completedDate,onChange:t=>J(s=>({...s,completedDate:t.target.value}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Delivered by"}),e.jsx("input",{type:"text",className:"input w-full",value:H.deliveredBy,onChange:t=>J(s=>({...s,deliveredBy:t.target.value})),placeholder:"Who physically delivered this order?"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Delivery notes"}),e.jsx("textarea",{className:"input w-full min-h-[80px]",value:H.notes,onChange:t=>J(s=>({...s,notes:t.target.value}))})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx("button",{type:"button",className:"btn-secondary flex-1",onClick:()=>J(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"btn-primary flex-1",onClick:gs,children:"Save changes"})]})]})}),A&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-md p-6 space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:A.isEdit?"Edit payment record":"Mark as paid"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Payment method"}),e.jsx("input",{type:"text",className:"input w-full",value:A.paymentMethod,onChange:t=>X(s=>({...s,paymentMethod:t.target.value})),placeholder:"Cash, Check, Venmo, Card, Invoiceâ¦"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Payment date"}),e.jsx("input",{type:"date",className:"input w-full",value:A.paidDate,onChange:t=>X(s=>({...s,paidDate:t.target.value}))})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx("button",{type:"button",className:"btn-secondary flex-1",onClick:()=>X(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"btn-success flex-1",onClick:Yt,children:A.isEdit?"Save payment":"Mark as paid"})]})]})})]})};export{Ir 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.