1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SMSUpdateModal-HLILNO-U.js","assets/index-DdU35jPJ.js","assets/index-ziLDO-qt.css","assets/button-BfxMpK8P.js","assets/index-gN4drEn4.js","assets/index-Dp3B9jqt.js","assets/clsx-B-dksMZM.js","assets/utils-DCmAa5as.js","assets/bundle-mjs-BTmSotT-.js","assets/textarea-RCbb6gBZ.js","assets/label-Bnj3FxlL.js","assets/index-9bdZCgcr.js","assets/select-CicXJDZx.js","assets/index-12QbP6l0.js","assets/index-B1Cc5OXO.js","assets/index-BsvT06Lq.js","assets/index-BvvUEucZ.js","assets/index-7px4L8n5.js","assets/index-CkK8lBUI.js","assets/index-DGERrSaP.js","assets/chevron-down-DcLGbHop.js","assets/createLucideIcon-DMxicyrC.js","assets/check-BECSssz0.js","assets/chevron-up-w1zviHLx.js","assets/dialog-gVN6KGjC.js","assets/index-BhZ8ej-y.js","assets/index-Bwgqm7vL.js","assets/x-DAruoHhn.js","assets/dialog-BvzTRZmc.css","assets/smsFoundation-dRMYUQFS.js","assets/message-square-UZdUIYzB.js","assets/phone-BiN9hL5_.js","assets/shield-check-CvVcm_Fy.js","assets/triangle-alert-l3tEQyle.js","assets/loader-circle-B5Ydjp3O.js","assets/send-DYuvBuIV.js","assets/CreateOrderModal-BOj8sSRk.js","assets/orderPricing-JUAz4I2_.js","assets/pricingAudienceShared-BAeBaCzb.js","assets/requestId-CdjlQxMD.js","assets/orderSubmitError-6ymLp80n.js","assets/input-cpzcpc5y.js","assets/calendar-BlFR5j33.js","assets/startOfMonth-aJYsEbmh.js","assets/format-C-2FZrE-.js","assets/endOfMonth-AtYoJfID.js","assets/subDays-B3NSHfXz.js","assets/chevron-right-PZEH6lk6.js","assets/chevron-left-BcAcL8kJ.js","assets/popover-ClbGMMC3.js","assets/search-8uT820HJ.js","assets/user-TFtzTQfw.js","assets/package-DYJogmeO.js","assets/plus-Bux0BJlB.js","assets/minus-Cyk10VU5.js","assets/trash-2-Bi9M4bD6.js","assets/calendar-WJIH9OsN.js","assets/users-ecdZz2CG.js","assets/SendToOperationsModal-CUpow1UF.js","assets/AdminOrderEmailHelper-BfgRFZI6.js","assets/index-CtlYlah8.js"])))=>i.map(i=>d[i]); 2import{j as e,r as c,t as o,b as A,R as as,C as fs,_ as Ue}from"./index-DdU35jPJ.js";import{C as Tt}from"./CustomerTaxExemptionBadge-CjeilImV.js";import{C as $t,A as Lt}from"./AdvancedOrderFilters-bKRWAlTg.js";import{M as Pt,u as Rt}from"./permissions-BiBV8RVM.js";import{B as y}from"./button-BfxMpK8P.js";import{B as ge}from"./badge-O5l_SoDq.js";import{S as cs,a as os,b as ds,c as ms,d as _e}from"./select-CicXJDZx.js";import{I as Qe}from"./input-cpzcpc5y.js";import{D as Mt,a as qt,b as It,c as zt}from"./dialog-gVN6KGjC.js";import{C as Vt}from"./CustomerTaxExemptionPanel-B2eWsG69.js";import{P as Wt}from"./PartnerJourneyPanel-BC5F3Iox.js";import{W as xs}from"./warehouse-Byif8V9M.js";import{M as We}from"./map-pin-CKcF86VS.js";import{C as Pe}from"./circle-check-big-B9divPaO.js";import{T as Re}from"./truck-BQgQtOKT.js";import{P as Gt}from"./pen-line-CZqV1b9o.js";import{L as ne}from"./loader-circle-B5Ydjp3O.js";import{T as Le}from"./triangle-alert-l3tEQyle.js";import{R as Ht}from"./rotate-ccw-DX9Sab2l.js";import{C as Qt}from"./check-BECSssz0.js";import{S as rs}from"./save-BVu4epSf.js";import{X as is}from"./x-DAruoHhn.js";import{T as Ut}from"./textarea-RCbb6gBZ.js";import{B as ps}from"./bell-U-Ryz8Hr.js";import{C as Ee}from"./circle-x-QpU72J1I.js";import{G as Vs}from"./gift-iZbsnbdF.js";import{U as Yt}from"./users-ecdZz2CG.js";import{U as Xt}from"./user-plus-CQvFDEfi.js";import{D as gs}from"./download-BAHbJTmZ.js";import{M as Zs}from"./message-square-UZdUIYzB.js";import{S as Zt}from"./send-DYuvBuIV.js";import{c as Js}from"./createLucideIcon-DMxicyrC.js";import{T as Me}from"./trash-2-Bi9M4bD6.js";import Jt from"./OrderChat-BppPICB2.js";import{S as Kt}from"./store-DhlvJUoL.js";import{C as ea}from"./circle-check-DIcqODlT.js";import{S as Ks}from"./shield-check-CvVcm_Fy.js";import{P as sa}from"./PartnerProfitSummary-ZG1pXeKA.js";import{C as et}from"./chevron-down-DcLGbHop.js";import{R as ta}from"./refresh-cw-2pM8p9DH.js";import{P as hs}from"./package-DYJogmeO.js";import{P as aa}from"./pencil-BFgvU9po.js";import{M as Ws}from"./minus-Cyk10VU5.js";import{P as Ge}from"./plus-Bux0BJlB.js";import{D as ra}from"./dollar-sign-Ca60MLZ3.js";import{U as us}from"./user-TFtzTQfw.js";import{C as ia}from"./credit-card-BsmBHB--.js";
2import{F as na}from"./file-text-BIInLmy-.js";import{S as Gs}from"./search-8uT820HJ.js";import{A as la}from"./activity-ku4ROF69.js";import{C as ca}from"./chevron-up-w1zviHLx.js";import{C as oa}from"./chevron-left-BcAcL8kJ.js";import{C as da}from"./chevron-right-PZEH6lk6.js";import{C as Hs}from"./clock-D8ofwCOI.js";import"./popover-ClbGMMC3.js";import"./index-12QbP6l0.js";import"./index-gN4drEn4.js";import"./index-BsvT06Lq.js";import"./index-9bdZCgcr.js";import"./index-BvvUEucZ.js";import"./index-7px4L8n5.js";import"./index-CkK8lBUI.js";import"./index-Bwgqm7vL.js";import"./utils-DCmAa5as.js";import"./clsx-B-dksMZM.js";import"./bundle-mjs-BTmSotT-.js";import"./calendar-BlFR5j33.js";import"./startOfMonth-aJYsEbmh.js";import"./format-C-2FZrE-.js";import"./endOfMonth-AtYoJfID.js";import"./subDays-B3NSHfXz.js";import"./collapsible-CfsL_e9Z.js";import"./filter-BeAXHBRV.js";import"./arrow-up-down-C_o5Ncnx.js";import"./calendar-WJIH9OsN.js";import"./building-2-DLUiP0-v.js";import"./fuel-jKEn7Rtr.js";import"./shopping-cart-vZlzvnWl.js";import"./tag-CE_kSim7.js";import"./layout-dashboard-CLdGowQs.js";import"./shopping-bag-CrDvW2T1.js";import"./history-D4MjbF_b.js";import"./house-Bm2jn5Fi.js";import"./users-round-B2qLimgb.js";import"./shield-CNFEkWQF.js";import"./target-BtQDcMxu.js";import"./clipboard-list-DNU_XDsB.js";import"./user-check-VNuyOprd.js";import"./gauge-HW9tC7ES.js";import"./trending-up-D6tLkDJM.js";import"./chart-column-BE0xtxdl.js";import"./briefcase-sHV214ND.js";import"./square-pen-C50_OfbT.js";import"./coins-Cv3X5RCl.js";import"./headset-DiWixqCE.js";import"./zap-R8goDiXI.js";import"./sticky-note-__P8x4dM.js";import"./star-CyYMnC7h.js";import"./book-open-DRLFh2Pr.js";import"./sparkles-BfFbpu9e.js";import"./boxes-CDlYyPs0.js";import"./banknote-DkgjxqGg.js";import"./index-Dp3B9jqt.js";import"./index-B1Cc5OXO.js";import"./index-DGERrSaP.js";import"./index-BhZ8ej-y.js";import"./external-link-eHzPPC2B.js";import"./upload-tj7WXC4r.js";import"./partnerJourneyUi-CZLXIO3m.js";import"./TimezoneHelper-CKaUc9lx.js";import"./index-CpcvuyT9.js";import"./index-CGPMVT10.js";/** 3 * @license lucide-react v0.475.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const ma=[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]],xa=Js("MessageSquareWarning",ma);/** 8 * @license lucide-react v0.475.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const pa=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],He=Js("RefreshCcw",pa);function ha({opsOrder:s,orderStatus:i}){var F;if(!((F=s==null?void 0:s.pick_details)!=null&&F.length))return null;const h=i==="completed";return e.jsxs("div",{className:`rounded-xl p-4 ${h?"bg-[#00c875]/10 border border-[#00c875]/30":"bg-[#f6f7fb] border border-[#e6e9ef]"}`,children:[e.jsxs("h4",{className:`text-sm uppercase tracking-wider mb-3 flex items-center gap-2 ${h?"text-[#00c875]":"text-[#676879]"}`,children:[e.jsx(xs,{className:"w-4 h-4"}),h?"Inventory Deducted From:":"Pick Details (Inventory)"]}),e.jsx("div",{className:"space-y-2",children:s.pick_details.map((C,k)=>e.jsxs("div",{className:`flex items-center justify-between rounded-lg p-3 ${h?"bg-white/70 border border-[#00c875]/20":"bg-white border border-[#e6e9ef]"}`,children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-[#323338] font-medium",children:[C.tire_brand," ",C.tire_model&&`${C.tire_model} `,C.tire_ply_rating&&`${C.tire_ply_rating} `]}),e.jsxs("p",{className:"text-[#676879] text-sm",children:[C.tire_size,C.tire_position&&e.jsxs("span",{children:[" ⢠",C.tire_position]})]}),C.location_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(We,{className:"w-3 h-3 text-[#0073ea]"}),e.jsx("p",{className:`text-sm font-medium ${h?"text-[#00c875]":"text-[#0073ea]"}`,children:C.location_name})]})]}),e.jsxs(ge,{className:`${h?"bg-[#00c875] text-white border-0":"bg-[#0073ea] text-white border-0"}`,children:[C.quantity,"x"]})]},k))}),s.inventory_deducted&&e.jsxs("p",{className:"text-[#00c875] text-xs mt-3 flex items-center gap-1 font-medium",children:[e.jsx(Pe,{className:"w-4 h-4"})," Inventory successfully deducted"]})]})}let ns=null,Ve=null;function ua({order:s,operationsOrders:i,onOrderUpdated:h}){var ue,be;const[F,C]=c.useState(!1),[k,X]=c.useState(""),[T,$]=c.useState(!1),[l,W]=c.useState(!1),[B,R]=c.useState(""),[p,_]=c.useState(!1),[L,J]=c.useState([]),[G,oe]=c.useState(!1),[ae,le]=c.useState(!1),[O,K]=c.useState(!1),[ee,me]=c.useState([]),[H,pe]=c.useState(!1),Q=v=>{me(E=>E.includes(v)?[]:[v])}
12,he=i==null?void 0:i[s.id],b=()=>{if(ns){J(ns),le(!1);return}if(Ve){oe(!0),Ve.then(se=>{J(se),le(!1)}).catch(()=>{}).finally(()=>oe(!1));return}oe(!0),le(!1);const v=se=>new Promise(te=>setTimeout(te,se));Ve=(async(se=2)=>{for(let te=0;te<=se;te++)try{const w=(await A.entities.InventoryLocation.list()||[]).filter(Se=>Se.is_active!==!1);return ns=w,J(w),le(!1),w}catch(Z){if(te===se)throw Z;const w=String((Z==null?void 0:Z.detail)||(Z==null?void 0:Z.message)||"").match(/retry after (\d+)/i);await v(((w?+w[1]:3)+1)*1e3)}})().catch(()=>{le(!0)}).finally(()=>{Ve=null,oe(!1)})},z=()=>b(),U=async()=>{if(ee.length===0){o.error("Please select at least one location");return}pe(!0);try{const v=ee[0];if(!(he!=null&&he.id))throw new Error("Send this order to Operations before changing its inventory source");const E=L.find(w=>w.name===v);if(!E)throw new Error("Selected inventory location was not found");const se=(s.items||[]).map(w=>({location_id:E.id,location_name:E.name,tire_brand:w.brand,tire_model:w.model||"",tire_ply_rating:w.ply_rating||"",tire_size:w.size,tire_position:w.position||"",quantity:Number(w.quantity)||0})),te=await A.functions.invoke("saveAllocation",{ops_order_id:he.id,pick_details:se,pick_locations:[E.name],preferred_pick_location:E.name}),Z=(te==null?void 0:te.data)||te;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Inventory allocation rejected");o.success("â Pick locations updated everywhere"),K(!1),me([]),h()}catch(v){console.error(v),o.error("Failed to update pick locations")}pe(!1)},q=async()=>{if(!k){o.error("Please select a date");return}$(!0);try{const v=await A.functions.invoke("updateOrderMetadata",{order_id:s.id,changes:{fulfillment_date:k},reason:`Fulfillment date changed to ${new Date(k+"T12:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`}),E=(v==null?void 0:v.data)||v;if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Metadata update rejected");o.success("â Fulfillment date updated everywhere"),C(!1),X(""),h()}catch(v){console.error(v),o.error("Failed to update fulfillment date")}$(!1)},xe=async()=>{if(!B.trim()){o.error("Please enter an address");return}_(!0);try{const v=await A.functions.invoke("updateOrderMetadata",{order_id:s.id,changes:{delivery_address:B.trim()},reason:"Delivery address updated"}),E=(v==null?void 0:v.data)||v;if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Metadata update rejected");o.success("â Delivery address updated everywhere"),W(!1),R(""),h()}catch(v){console.error(v),o.error("Failed to update delivery address")}_(!1)};return e.jsxs("div",{className:"bg-[#f6f7fb] rounded-xl p-4 flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-[#0073ea]"}),e.jsx("h4",{className:"text-sm text-[#676879] uppercase tracking-wider",children:"Fulfillment"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!F&&e.jsxs("button",{onClick:()=>{C(!0),X(s.fulfillment_date||"")},className:"text-[#0073ea] text-xs hover:underline flex items-center gap-1",children:[e.jsx(Gt,{className:"w-3 h-3"}),"Edit date"]}),s.fulfillment_type==="delivery"&&!l&&e.jsxs("button",{onClick:()=>{W(!0),R(s.delivery_address||"")},className:"text-[#0073ea] text-xs hover:underline flex items-center gap-1 ml-2",children:[e.jsx(We,{className:"w-3 h-3"}),"Edit address"]}),!O&&e.jsxs("button",{onClick:()=>{K(!0);const v=Array.isArray(s.preferred_pick_locations)&&s.preferred_pick_locations.length>0?s.preferred_pick_locations:s.preferred_pick_location?[s.preferred_pick_location]:[];me(v.length?[v[0]]:[]),b()},className:"text-[#0073ea] text-xs hover:underline flex items-center gap-1 ml-2",children:[e.jsx(xs,{className:"w-3 h-3"}),"Edit pick locations"]})]})]}),O?e.jsxs("div",{className:"mt-2 space-y-2",children:[G&&e.jsxs("p",{className:"text-[#676879] text-xs flex items-center gap-1.5 py-1",children:[e.jsx(ne,{className:"w-3 h-3 animate-spin"})," Loading locationsâ¦"]}),ae&&!G&&e.jsxs("div",{className:"flex items-center gap-2 py-1",children:[e.jsxs("p",{className:"text-[#e2445c] text-xs flex items-center gap-1.5",children:[e.jsx(Le,{className:"w-3 h-3"})," Couldn't load locations"]}),e.jsxs("button",{onClick:z,className:"text-[#0073ea] text-xs hover:underline flex items-center gap-1",children:[e.jsx(Ht,{className:"w-3 h-3"})," Retry"]})]}),!G&&!ae&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[L.map(v=>{const E=ee.includes(v.name);return e.jsxs("button",{type:"button",onClick:()=>Q(v.name),className:`flex items-center gap-1.5 rounded-lg px-3 py-2 transition-all border-2 text-xs ${E?"bg-[#0073ea]/10 border-[#0073ea] text-[#0073ea]":"bg-white border-[#e6e9ef] text-[#676879] hover:border-[#0073ea]/40"}`,children:[E?e.jsx(Qt,{className:"w-3 h-3"}):e.jsx(We,{className:"w-3 h-3"}),v.name]},v.id)}),L.length===0&&e.jsx("p",{className:"text-[#676879] text-xs",children:"No active locations foun
12d"})]}),ee.length>0&&e.jsxs("p",{className:"text-[#676879] text-xs",children:[ee.length," selected ⢠Primary: ",ee[0]]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{size:"sm",onClick:U,disabled:H,className:"flex-1 bg-[#0073ea] hover:bg-[#0060b9] text-white text-xs h-8",children:H?e.jsx(ne,{className:"w-3 h-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"w-3 h-3 mr-1"}),"Save"]})}),e.jsxs(y,{size:"sm",onClick:()=>{K(!1),me([])},className:"flex-1 border border-[#e6e9ef] bg-white text-[#676879] text-xs h-8",children:[e.jsx(is,{className:"w-3 h-3 mr-1"}),"Cancel"]})]})]}):(((ue=s.preferred_pick_locations)==null?void 0:ue.length)>0||s.preferred_pick_location)&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(xs,{className:"w-4 h-4 text-[#0073ea]"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#676879] text-xs",children:"Pick Location(s)"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-0.5",children:(((be=s.preferred_pick_locations)==null?void 0:be.length)>0?s.preferred_pick_locations:[s.preferred_pick_location]).map((v,E)=>{var se;return e.jsxs("span",{className:"text-[#323338] font-semibold text-sm",children:[v,E<(((se=s.preferred_pick_locations)==null?void 0:se.length)>0?s.preferred_pick_locations:[s.preferred_pick_location]).length-1?", ":""]},E)})})]})]}),e.jsx("p",{className:"text-[#323338] font-medium capitalize",children:s.fulfillment_type||"Not specified"}),F?e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("input",{type:"date",value:k,onChange:v=>X(v.target.value),className:"w-full rounded-lg border border-[#e6e9ef] bg-white px-3 py-2 text-sm text-[#323338]"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{size:"sm",onClick:q,disabled:T,className:"flex-1 bg-[#0073ea] hover:bg-[#0060b9] text-white text-xs h-8",children:T?e.jsx(ne,{className:"w-3 h-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"w-3 h-3 mr-1"}),"Save"]})}),e.jsxs(y,{size:"sm",onClick:()=>{C(!1),X("")},className:"flex-1 border border-[#e6e9ef] bg-white text-[#676879] text-xs h-8",children:[e.jsx(is,{className:"w-3 h-3 mr-1"}),"Cancel"]})]})]}):e.jsxs("p",{className:"text-[#676879] text-sm mt-1",children:[s.fulfillment_date?new Date(s.fulfillment_date+"T12:00:00").toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}):"No date selected",s.fulfillment_time&&e.jsxs("span",{children:[" ⢠",s.fulfillment_time]})]}),s.fulfillment_type==="delivery"&&e.jsx("div",{className:"mt-2 pt-2 border-t border-[#e6e9ef]",children:l?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:B,onChange:v=>R(v.target.value),rows:2,placeholder:"Enter delivery address...",className:"w-full rounded-lg border border-[#e6e9ef] bg-white px-3 py-2 text-sm text-[#323338] resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{size:"sm",onClick:xe,disabled:p,className:"flex-1 bg-[#0073ea] hover:bg-[#0060b9] text-white text-xs h-8",children:p?e.jsx(ne,{className:"w-3 h-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"w-3 h-3 mr-1"}),"Save"]})}),e.jsxs(y,{size:"sm",onClick:()=>{W(!1),R("")},className:"flex-1 border border-[#e6e9ef] bg-white text-[#676879] text-xs h-8",children:[e.jsx(is,{className:"w-3 h-3 mr-1"}),"Cancel"]})]})]}):s.delivery_address?e.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-start gap-2 mb-3",children:[e.jsx(We,{className:"w-4 h-4 text-[#676879] mt-0.5"}),e.jsx("p",{className:"text-[#323338] text-sm",children:s.delivery_address})]}),e.jsx("div",{className:"w-full flex-1 rounded-lg overflow-hidden border border-[#e6e9ef] min-h-[150px]",children:e.jsx("iframe",{title:"Delivery Location",width:"100%",height:"100%",frameBorder:"0",style:{border:0},src:`https://maps.google.com/maps?q=${encodeURIComponent(s.delivery_address)}&t=&z=13&ie=UTF8&iwloc=&output=embed`,allowFullScreen:!0})})]}):null})]})}function fa({order:s,customer:i,salesReps:h,customers:F,setCustomers:C,creditsToAdd:k,setCreditsToAdd:X,addingCredits:T,addCreditsToCustomer:$,updatingOrder:l,updateOrderStatus:W,customFeeOpen:B,setCustomFeeOpen:R,updateDeliveryFee:p,updateAdminNotes:_,moveToTrash:L,restoreFromTrash:J,exportToXLS:G,setSmsOrder:oe,setSmsCustomer:ae,setSmsModalOpen:le,setOpsOrder:O,setOpsCustomer:K,setShowOpsModal:ee,getCreditsEarnedStatusBadge:me}){var H,pe,Q,he;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 pt-6 border-t border-[#e6e9ef]",children:[e.jsxs("div",{className:"md:col-span-2 bg-[#f6f7fb] rounded-xl p-4 border border-[#e6e9ef]",children:[e.jsx("label",{className:"text-sm text-[#676879] mb-4 block uppercase tracking-wider font-semibold",children:"Order Status Workflow"}),e.jsxs("div",{className:"flex items-center justify-between mb-6 relative",children:[e.jsx("div",{className:"absolute left-0 right-0 top-1/2 h-0.5 bg-[#e6e9ef] -z-10"}),[{id:"pending",label:"Pending",Ic:ps},{id:"in_progress",label:"In Progress",Ic:ne},{id:"completed",label:"Completed",Ic:Pe}].map(({id:b,label:z,Ic:U},q)=>{const xe=s.status===b,ue=["pending","in_progress","completed"].indexOf(s.status)>q,be=["pending","in_progress","completed"].indexOf(s.status)<q;return e.jsxs("div",{className:"flex flex-col items-center gap-2 bg-[#f6f7fb] px-2",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all 13 ${xe?"bg-[#0073ea] border-[#0073ea] text-white scale-110 shadow-lg shadow-[#0073ea]/30":""} 14 ${ue?"bg-[#0073ea]/20 border-[#0073ea] text-[#0073ea]":""} 15 ${be?"bg-white border-[#e6e9ef] text-[#9699a6]":""} 16 ${s.status==="cancelled"?"opacity-50 grayscale":""} 17 `,children:e.jsx(U,{className:"w-5 h-5"})}),e.jsx("span",{className:`text-xs font-medium ${xe?"text-[#323338]":"text-[#9699a6]"}`,children:z})]},b)})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[s.status==="pending"&&e.jsxs(y,{onClick:()=>W(s.id,"in_progress"),disabled:l===s.id,className:"flex-1 bg-[#0073ea] hover:bg-[#0060b9] text-white",children:[l===s.id?e.jsx(ne,{className:"w-4 h-4 animate-spin mr-2"}):null,"Move to In Progress"]}),s.status==="in_progress"&&e.jsxs(y,{onClick:()=>W(s.id,"completed"),disabled:l===s.id,className:"flex-1 bg-[#00c875] hover:bg-[#00b461] text-white",children:[l===s.id?e.jsx(ne,{className:"w-4 h-4 animate-spin mr-2"}):null,"Mark as Completed"]}),e.jsxs(cs,{value:s.status,onValueChange:b=>W(s.id,b),disabled:l===s.id,children:[e.jsx(os,{className:"w-[140px] bg-white border-[#e6e9ef] text-[#323338]",children:e.jsx(ds,{placeholder:"Override"})}
17),e.jsxs(ms,{className:"bg-white border-[#e6e9ef]",children:[e.jsx(_e,{value:"pending",children:"Pending"}),e.jsx(_e,{value:"in_progress",children:"In Progress"}),e.jsx(_e,{value:"on_the_way",children:"On The Way"}),e.jsx(_e,{value:"completed",children:"Completed"}),e.jsx(_e,{value:"cancelled",children:"Cancelled"})]})]}),s.status!=="cancelled"&&s.status!=="completed"&&e.jsxs(y,{onClick:()=>W(s.id,"cancelled"),disabled:l===s.id,variant:"outline",className:"border-[#e2445c]/30 text-[#e2445c] hover:bg-[#e2445c]/10",children:[l===s.id?e.jsx(ne,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(Ee,{className:"w-4 h-4 mr-2"}),"Cancel Order"]})]})]}),e.jsxs("div",{className:"bg-[#f6f7fb] rounded-xl p-4 border border-[#e6e9ef]",children:[e.jsx("label",{className:"text-sm text-[#676879] mb-3 block uppercase tracking-wider font-semibold",children:"Delivery Fee"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-white cursor-pointer",onClick:()=>{p(s.id,0),R(b=>({...b,[s.id]:!1}))},children:[e.jsx("input",{type:"radio",name:`delivery-fee-${s.id}`,checked:s.delivery_fee===0&&!B[s.id],onChange:()=>{},className:"bg-white border-[#e6e9ef] text-[#0073ea]"}),e.jsx("label",{className:"text-[#323338] text-sm cursor-pointer flex-1 font-medium",children:"FREE Delivery"}),e.jsx("span",{className:"text-[#00c875] text-xs font-bold bg-[#00c875]/10 px-2 py-0.5 rounded",children:"NO CHARGE"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-white cursor-pointer",onClick:()=>R(b=>({...b,[s.id]:!0})),children:[e.jsx("input",{type:"radio",name:`delivery-fee-${s.id}`,checked:(s.delivery_fee||0)>0||B[s.id],onChange:()=>{},className:"bg-white border-[#e6e9ef] text-[#0073ea]"}),e.jsx("label",{className:"text-[#323338] text-sm cursor-pointer font-medium",children:"Custom Amount"})]}),((s.delivery_fee||0)>0||B[s.id])&&e.jsxs("div",{className:"ml-8 relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#676879]",children:"$"}),e.jsx(Qe,{type:"number",min:"0",step:"0.01",placeholder:"0.00",defaultValue:(s.delivery_fee||0)>0?s.delivery_fee:"",onBlur:b=>p(s.id,b.target.value),className:"pl-6 bg-white border-[#e6e9ef] text-[#323338] h-10 w-full",autoFocus:B[s.id]&&(s.delivery_fee||0)===0}),e.jsx("p",{className:"text-xs text-[#9699a6] mt-1",children:"Enter amount and click away to save"})]})]})]}),s.delivery_fee_reason&&e.jsxs("p",{className:"text-xs text-[#676879] mt-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"font-semibold uppercase tracking-wider",children:"Reason:"}),e.jsx("span",{children:{free_30_plus:"Free â 30+ tires",free_tier_2_plus:"Free â Tier 2+",mileage_based:`Mileage-based${s.delivery_fee?` ($${Number(s.delivery_fee).toFixed(2)})`:""}`,pickup:"Pickup â no delivery fee",manual_override:`Staff override${s.delivery_fee?` ($${Number(s.delivery_fee).toFixed(2)})`:""}`}[s.delivery_fee_reason]||s.delivery_fee_reason})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-[#676879] mb-2 block uppercase tracking-wider font-semibold",children:"Internal Notes"}),e.jsx(Ut,{defaultValue:s.admin_notes||"",placeholder:"Add private notes about this order...",className:"bg-white border-[#e6e9ef] text-[#323338] min-h-[130px] resize-none",onBlur:b=>{b.target.value!==(s.admin_notes||"")&&_(s.id,b.target.value)}})]})]}),s.status==="completed"&&s.credits_earned_status!=="added"&&e.jsxs("div",{className:"bg-[#0073ea]/10 rounded-xl p-4 border border-[#0073ea]/20",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vs,{className:"w-4 h-4 text-[#0073ea]"}),e.jsx("h4",{className:"text-sm text-[#0073ea] uppercase tracking-wider",children:"Add Credits for This Order"})]}),e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[#676879] text-xs mb-1 block",children:"Credits Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#676879]",children:"$"}),e.jsx(Qe,{type:"number",step:"0.01",min:"0",placeholder:(((H=s.items)==null?void 0:H.reduce((b,z)=>b+z.quantity,0))*((i==null?void 0:i.credit_per_tire)??.5)).toLocaleStr
17ing("en-US",{minimumFractionDigits:2}),value:k[s.id]??"",onChange:b=>X(z=>({...z,[s.id]:b.target.value})),className:"pl-7 bg-white border-[#e6e9ef] text-[#323338]"})]}),e.jsxs("p",{className:"text-[#9699a6] text-xs mt-1",children:["Suggested: $",(((pe=s.items)==null?void 0:pe.reduce((b,z)=>b+z.quantity,0))*((i==null?void 0:i.credit_per_tire)??.5)).toLocaleString("en-US",{minimumFractionDigits:2})]})]}),e.jsx(y,{onClick:()=>$(s),disabled:T===s.id,className:"bg-[#0073ea] hover:bg-[#0060b9] text-white",children:T===s.id?e.jsx(ne,{className:"w-4 h-4 animate-spin"}):"Add Credits"})]})]}),(s.status==="completed"||s.credits_earned_status)&&e.jsxs("div",{className:`rounded-xl p-4 border ${s.credits_earned_status==="added"?"bg-[#00c875]/10 border-[#00c875]/30":"bg-[#f6f7fb] border-[#e6e9ef]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4 text-[#0073ea]"}),e.jsx("span",{className:"text-[#676879] text-sm",children:"Credits Earned Status:"}),me(s.credits_earned_status||"pending")]}),s.credits_earned>0&&s.credits_earned_status==="added"&&e.jsxs("span",{className:"text-[#00c875] font-bold text-lg",children:["+$",(Q=s.credits_earned)==null?void 0:Q.toLocaleString("en-US",{minimumFractionDigits:2})]})]}),s.credits_earned_status==="added"&&e.jsxs("div",{className:"text-xs text-[#00c875] mt-2 space-y-1",children:[e.jsx("p",{children:"â Credits added to customer's account"}),i&&e.jsxs("p",{children:["Current balance: $",(he=i.credit_balance)==null?void 0:he.toLocaleString("en-US",{minimumFractionDigits:2})]})]}),s.status==="completed"&&s.credits_earned_status==="pending"&&e.jsx("p",{className:"text-[#fdab3d] text-xs mt-2",children:"â³ Credits will be awarded automatically"})]}),e.jsxs("div",{className:"bg-[#f6f7fb] rounded-xl p-4 border border-[#e6e9ef]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Yt,{className:"w-4 h-4 text-[#0073ea]"}),e.jsx("h4",{className:"text-sm text-[#676879] uppercase tracking-wider",children:"Assign to Sales Rep"})]}),e.jsx("p",{className:"text-[#9699a6] text-xs mb-3",children:"Assigning a customer to a sales rep automatically shares all their orders with that rep."}),i?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-[#676879]",children:"Current:"}),(()=>{const b=(i.assigned_rep_ids||[]).map(z=>{var U;return(U=h.find(q=>q.id===z))==null?void 0:U.name}).filter(Boolean);return b.length>0?e.jsx("span",{className:"text-[#0073ea] font-medium",children:b.join(", ")}):e.jsx("span",{className:"text-[#9699a6] italic",children:"No rep"})})()]}),e.jsxs(cs,{value:"",onValueChange:async b=>{var U;if(!b)return;const z=i.assigned_rep_ids||[];if(z.includes(b)){o.info("Already assigned");return}try{const q=[...z,b];await A.entities.Customer.update(i.id,{assigned_rep_ids:q}),C(xe=>({...xe,[i.id]:{...i,assigned_rep_ids:q}})),o.success(`${(U=h.find(xe=>xe.id===b))==null?void 0:U.name} assigned`)}catch{o.error("Failed")}},children:[e.jsx(os,{className:"bg-white border-[#e6e9ef] text-[#323338]",children:e.jsx(ds,{placeholder:"+ Add Sales Rep"})}),e.jsx(ms,{className:"bg-white border-[#e6e9ef]",children:h.map(b=>e.jsx(_e,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"w-3 h-3"}),b.name,e.jsxs("span",{className:"text-[#9699a6] text-xs",children:["(",b.rep_role||"sales",")"]})]})},b.id))})]}),(i.assigned_rep_ids||[]).length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:(i.assigned_rep_ids||[]).map(b=>{const z=h.find(U=>U.id===b);return z?e.jsxs(ge,{className:"bg-[#0073ea] text-white border-0 flex items-center gap-1 pr-1",children:[z.name,e.jsx("button",{onClick:async()=>{const U=(i.assigned_rep_ids||[]).filter(q=>q!==b);try{await A.entities.Customer.update(i.id,{assigned_rep_ids:U}),C(q=>
17({...q,[i.id]:{...i,assigned_rep_ids:U}})),o.success(`${z.name} removed`)}catch{o.error("Failed")}},className:"ml-1 hover:bg-white/20 rounded p-0.5",children:e.jsx(Ee,{className:"w-3 h-3"})})]},b):null})})]}):e.jsx("p",{className:"text-[#9699a6] text-sm",children:"Customer not found"})]}),e.jsx("div",{className:"flex items-center justify-end flex-wrap gap-3",children:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(y,{size:"sm",className:"bg-[#323338] text-white hover:bg-[#272a2f] border-none",onClick:b=>{b.stopPropagation(),G(s,`order-${s.id}.xls`)},children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Export Order"]}),e.jsxs(y,{variant:"outline",size:"sm",className:"border-[#0073ea]/30 text-[#0073ea] hover:bg-[#0073ea]/10",onClick:b=>{b.stopPropagation(),oe(s),ae(i),le(!0)},children:[e.jsx(Zs,{className:"w-4 h-4 mr-2"}),"Send SMS"]}),e.jsxs(y,{variant:"outline",size:"sm",className:"border-[#ff9349]/30 text-[#ff9349] hover:bg-[#ff9349]/10",onClick:b=>{b.stopPropagation(),O(s),K(i),ee(!0)},children:[e.jsx(Zt,{className:"w-4 h-4 mr-2"}),"Send to Operations"]}),s.in_trash?e.jsxs(y,{variant:"ghost",size:"sm",className:"text-[#00c875] hover:bg-[#00c875]/10",onClick:()=>J(s.id),children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Restore"]}):e.jsxs(y,{variant:"ghost",size:"sm",className:"text-[#e2445c] hover:bg-[#e2445c]/10",onClick:()=>L(s.id),children:[e.jsx(Me,{className:"w-4 h-4 mr-2"}),"Move to Trash"]})]})})]})}const Qs=s=>Number(s||0).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2}),Us={cancelled:{label:"Cancellation recorded â verify linked accounting below",cls:"bg-amber-100 text-amber-800 border-amber-300"},pending_review:{label:"Pending Main Admin Review",cls:"bg-amber-100 text-amber-800 border-amber-300"},changes_requested:{label:"Changes Requested",cls:"bg-violet-100 text-violet-800 border-violet-300"},approved:{label:"Approved · In Fulfillment",cls:"bg-emerald-100 text-emerald-800 border-emerald-300"},declined:{label:"Declined",cls:"bg-red-100 text-red-800 border-red-300"},completed:{label:"Completed",cls:"bg-blue-100 text-blue-800 border-blue-300"}};function ga({order:s,onUpdated:i}){var ae,le;const[h,F]=c.useState(null),[C,k]=c.useState(null),[X,T]=c.useState(!0),[$,l]=c.useState(""),[W,B]=c.useState(""),[R,p]=c.useState(""),_=async()=>{T(!0);try{const O=await A.entities.PartnerSaleLink.filter({supply_order_id:s.id},"-created_date",1),K=Array.isArray(O)?O[0]:O;F(K||null),K!=null&&K.shop_customer_order_id&&k(await A.entities.ShopCustomerOrder.get(K.shop_customer_order_id))}catch(O){console.error("Partner sale review load failed",O),o.error("Could not load the linked partner sale")}finally{T(!1)}};c.useEffect(()=>{_()},[s.id]);const L=async O=>{var ee,me;if((O==="request_changes"||O==="decline")&&!R.trim()){o.error("Add a reason first");return}const K=O==="approve"?"Approve this partner sale and create its Operations order?":O==="decline"?"Decline this sale? Its reservation will be released and the customer invoice will be voided.":"Send this order back to the shop for changes?";if(window.confirm(K)){l(O);try{const H=await A.functions.invoke("reviewPartnerSale",{order_id:s.id,action:O,notes:W.trim(),reason:R.trim()}),pe=(H==null?void 0:H.data)||H||{};if(pe.error)throw new Error(pe.error);o.success(O==="approve"?"Partner sale approved and sent to Operations":O==="decline"?"Partner sale declined and reservation released":"Changes requested"),await _(),await(i==null?void 0:i())}catch(H){o.error(((me=(ee=H==null?void 0:H.response)==null?void 0:ee.data)==null?void 0:me.error)||(H==null?void 0:H.message)||"Review action failed")}finally{l("")}}},J=(h==null?void 0:h.status)||s.partner_approval_status||"pending_review",G=Us[J]||Us.pending_review,oe=J==="approved"||J==="completed"||J==="declined"||J==="cancelled";return e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-orange-200 bg-gradient-to-br from-orange-50 via-white to-blue-50 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-orange-200 bg-gradient-to-r from-orange-500 to-orange-400 px-5 py-4 text-white md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-white/20",children:e.jsx(Re,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-[0.12em] text-orange-100",children:"Partner Sale"}),e.jsx("h3",{className:"text-lg font-bold",children:"Purchased from Truck Haters for the shop's customer"})]})]}),e.jsx(ge,{className:`w-fit border ${G.cls}`,children:G.label})]}),e.jsx("div",{className:"p-5",children:X?e.jsxs("div",{className:"flex items-center gap-2 py-5 text-sm text-slate-500",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"}),"Loading linked saleâ¦"]}):h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border bg-white p-3",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-500",children:"Partner shop"}),e.jsx("p",{className:"mt-1 font-semibold text-slate-900",children:((ae=s._customer)==null?void 0:ae.company_name)||((le=s._customer)==null?void 0:le.contact_name)||s.customer_owner_email||"Partner shop"}),e.jsx("p",{className:"text-xs text-slate-500",children:s.customer_owner_email})]}),e.jsxs("div",{className:"rounded-xl border bg-white p-3",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-500",children:"Shop's customer"}),e.jsx("p",{className:"mt-1 font-semibold text-slate-900",children:h.end_customer_company||h.end_customer_name||"Customer"}),e.jsx("p",{className:"text-xs text-slate-500",children:h.end_customer_name})]}),e.jsxs("div",{className:"rounded-xl border bg-white p-3",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-500",children:"Truck Haters total"}),e.jsx("p",{className:"mt-1 text-lg font-bold text-orange-700",children:Qs(h.th_grand_total)}),e.jsx("p",{className:"text-xs text-slate-500",children:"Manual payment arrangement"})]}),e.jsxs("div",{className:"rounded-xl border bg-white p-3",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-500",children:"Customer invoice"}),e.jsx("p",{className:"mt-1 text-lg font-bold text-blue-700",children:Qs(h.customer_invoice_total)}),e.jsx("p",{className:"text-xs text-slate-500",children:(C==null?void 0:C.invoice_number)||"Draft invoice"})]})]}),e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"flex gap-3 rounded-xl border bg-white p-3",children:[e.jsx(Kt,{className:"mt-0.5 h-4 w-4 shrink-0 text-blue-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold uppercase text-slate-500",children:"Linked
17shop order"}),e.jsx("p",{className:"font-medium text-slate-900",children:h.shop_customer_order_number})]})]}),e.jsxs("div",{className:"flex gap-3 rounded-xl border bg-white p-3",children:[e.jsx(Re,{className:"mt-0.5 h-4 w-4 shrink-0 text-orange-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold uppercase text-slate-500",children:"Direct delivery"}),e.jsxs("p",{className:"font-medium text-slate-900",children:[h.end_customer_street,", ",h.end_customer_city,", ",h.end_customer_state," ",h.end_customer_zip]})]})]})]}),!oe&&e.jsxs("div",{className:"mt-4 rounded-xl border border-slate-200 bg-white p-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("label",{className:"text-sm font-medium text-slate-700",children:["Admin notes (optional)",e.jsx("textarea",{value:W,onChange:O=>B(O.target.value),rows:2,className:"mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm",placeholder:"Internal review notes"})]}),e.jsxs("label",{className:"text-sm font-medium text-slate-700",children:["Reason (required for changes/decline)",e.jsx("textarea",{value:R,onChange:O=>p(O.target.value),rows:2,className:"mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm",placeholder:"What needs to change, or why declined"})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row",children:[e.jsxs(y,{onClick:()=>L("approve"),disabled:!!$,className:"bg-emerald-600 text-white hover:bg-emerald-700",children:[$==="approve"?e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ea,{className:"mr-2 h-4 w-4"}),"Approve & Send to Operations"]}),e.jsxs(y,{onClick:()=>L("request_changes"),disabled:!!$,variant:"outline",className:"border-violet-300 text-violet-700",children:[e.jsx(xa,{className:"mr-2 h-4 w-4"}),"Request Changes"]}),e.jsxs(y,{onClick:()=>L("decline"),disabled:!!$,variant:"outline",className:"border-red-300 text-red-700",children:[e.jsx(Ee,{className:"mr-2 h-4 w-4"}),"Decline"]})]})]}),oe&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-900",children:[e.jsx(Ks,{className:"mt-0.5 h-5 w-5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold",children:G.label}),e.jsx("p",{children:h.approval_notes||h.decline_reason||"The review decision is recorded in the immutable partner-sale history."})]})]})]}):e.jsx("p",{className:"text-sm text-red-700",children:"The PartnerSaleLink record is missing. Do not fulfill until the link is repaired."})})]})}const $e=s=>s==null?"Unavailable":Number(s).toLocaleString("en-US",{style:"currency",currency:"USD"}),de=s=>s==null||s===""?"Unavailable":String(s).replaceAll("_"," ");function ba({bundle:s}){var i,h,F,C,k,X,T,$,l,W,B,R;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{role:"alert",className:"rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-950",children:[e.jsx("p",{className:"font-semibold",children:"Release blocked â payment/cancellation race remains open"}),e.jsx("p",{children:"This is a read-only observation, not a repair or settlement. Matching displayed fields do not certify reconciliation while the stale-payment-write blocker remains unresolved."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Ys,{title:"Seller",name:(i=s.seller)==null?void 0:i.name,detail:(h=s.seller)==null?void 0:h.email}),e.jsx(Ys,{title:"Sellerâs customer",name:((F=s.customer)==null?void 0:F.company)||((C=s.customer)==null?void 0:C.name),detail:(k=s.customer)==null?void 0:k.name})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-4",children:[e.jsx("h4",{className:"font-semibold text-slate-900",children:"Linked records"}),e.jsx("dl",{className:"mt-2 grid gap-2 sm:grid-cols-2 text-sm",children:Object.entries(s.references||{}).map(([p,_])=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("dt",{className:"text-slate-600",children:de(p)}),e.jsx("dd",{className:"break-all font-medium text-slate-900",children:_||"Missing"})]},p))})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(Xs,{title:"Customer â Seller",data:s.customer_to_seller}),e.jsx(Xs,{title:"Seller â Truck Haters",data:s.seller_to_th})]}),e.jsx(sa,{profit:s.profit}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-4 space-y-3",children:[e.jsx("h4",{className:"font-semibold text-slate-900",children:"Frozen terms and parity"}),e.jsx("p",{className:"text-sm text-slate-700",children:(X=s.parity)!=null&&X.matches?"Frozen terms match the observed linked records.":"Frozen terms are missing or inconsistent."}),e.jsx("dl",{className:"grid gap-2 sm:grid-cols-2 text-sm",children:Object.entries(s.frozen_terms||{}).map(([p,_])=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("dt",{className:"text-slate-600",children:de(p)}),e.jsx("dd",{className:"break-all font-medium text-slate-900",children:typeof _=="number"?$e(_):de(_)})]},p))}),!!(($=(T=s.parity)==null?void 0:T.errors)!=null&&$.length)&&e.jsx("ul",{className:"space-y-1 text-sm text-red-800",children:s.parity.errors.map((p,_)=>e.jsx("li",{children:p},_))})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-4 space-y-3",children:[e.jsx("h4",{className:"font-semibold text-slate-900",children:"Lifecycle and recovery"}),e.jsx("dl",{className:"grid gap-2 sm:grid-cols-2 text-sm",children:Object.entries(s.lifecycle||{}).filter(([,p])=>!Array.isArray(p)).map(([p,_])=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-slate-600",children:de(p)}),e.jsx("dd",{className:"font-medium text-slate-900",children:de(_)})]},p))}),(((l=s.lifecycle)==null?void 0:l.operations)||[]).map(p=>e.jsxs("p",{className:"text-sm text-slate-700 break-all",children:["Operations ",p.id," · ",de(p.completion_status)," · inventory ",de(p.inventory_resolution_status)," · cycle ",p.cycle_id||"none"," · reopen ",de(p.reopen_status)," · prior reopened cycle ",p.last_reopened_cycle_id||"none"]},p.id)),(((W=s.lifecycle)==null?void 0:W.completion_cycles)||[]).map((p,_)=>e.jsxs("p",{className:"text-sm text-slate-700 break-all",children:["Completion ",p.operation_id," · ",de(p.status)," · ",p.completed_at||"not completed"]},`${p.operation_id}-${_}`)),(((B=s.lifecycle)==null?void 0:B.cancellation_operations)||[]).map((p,_)=>e.jsxs("div",{className:"text-sm text-slate-700 break-all",children:[e.jsxs("p",{children:["Cancellation ",p.operation_id," · ",de(p.status)]}),p.steps.map((L,J)=>e.jsxs("p",{children:[de(L.step),": ",de(L.status)]},J))]},`${p.operation_id}-${_}`))]}),e.jsxs("div",{role:"status",className:"rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-800",children:[e.jsx("p",{className:"font-semibold",children:(R=s.discrepancies)!=null&&R.length?"Unresolved discrepancies":"Observed fields match â release still blocked"}),(s.discrepancies||[]).map((p,_)=>e.jsx("p",{className:"break-words",children:de(p)},_)),e.jsxs("p",{className:"mt-2 text-xs",children:["Observed at ",s.as_of_utc,". Multi-record reads are not an atomic database snapshot."]})]})]})}function Ys({title:s,name:i,detail:h}){return e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-4",children:[e.jsx("h4",{className:"text-sm font-medium text-slate-600",children:s}),e.jsx("p",{className:"font-semibold text-slate-900",children:i||"Identity unavailable"}),e.jsx("p",{className:"text-sm text-slate-600 break-all",children:h||"â"})]})}function Xs({title:s,data:i}){var F;const h=[["Original invoice","original_invoice_total"],["Confirmed payments, net of corrections","net_confirmed_payments"],["Remaining receivable","remaining_receivable"],["Confirmed refunds","confirmed_refunds"],["Remaining refund obligation","remaining_refund_obligation"]];return e.jsxs("section",{className:"rounded-xl border border-slate-200 bg-white p-4 space-y-3",children:[e.jsx("h4",{className:"font-semibold text-slate-900",children:s}),!(i!=null&&i.available)&&e.jsx("p",{className:"text-sm text-red-800",children:"Accounting evidence is incomplete. Do not interpret unavailable values as zero."}),e.jsx("dl",{className:"space-y-2",children:h.map(([C,k])=>e.jsxs("div",{className:"flex items-start justify-between gap-3 text-sm",children:[e.jsx("dt",{className:"text-slate-600",children:C}),e.jsx("dd",{className:"font-semibold text-slate-900 text-right",children:$e(i==null?void 0:i[k])})]},k))}),e.jsxs("p",{className:"text-xs text-slate-600",children:["Complete payment history: ",(i==null?void 0:i.payment_event_count)??"unavailable"," events. Refund audit: ",(i==null?void 0:i.refund_event_c
17ount)??"unavailable"," events."]}),!!((F=i==null?void 0:i.issues)!=null&&F.length)&&e.jsxs("div",{className:"rounded-lg bg-red-50 p-3 text-sm text-red-800",children:[i.issues.map((C,k)=>e.jsx("p",{children:de(C)},k)),e.jsxs("p",{className:"mt-2",children:["Stored paid ",$e(i.stored_amount_paid)," · stored receivable ",$e(i.stored_receivable)," · stored refund due ",$e(i.stored_refund_due)]})]})]})}function ja({orderId:s,currentUser:i}){const h=Pt.includes(String((i==null?void 0:i.email)||"").trim().toLowerCase()),[F,C]=c.useState(!1),[k,X]=c.useState(0),[T,$]=c.useState({key:"",bundle:null,loading:!1,error:""});if(c.useEffect(()=>{if(!h||!F||!s){$({key:"",bundle:null,loading:!1,error:""});return}let B=!0;$({key:s,bundle:null,loading:!0,error:""});const R=setTimeout(()=>{B&&(B=!1,$({key:s,bundle:null,loading:!1,error:"Financial verification timed out. Retry."}))},15e3);return A.functions.invoke("getPartnerFinancialReconciliation",{order_id:s}).then(p=>{const _=(p==null?void 0:p.data)||p;if(_!=null&&_.error||!(_!=null&&_.bundle))throw new Error((_==null?void 0:_.error)||"Financial bundle unavailable");B&&$({key:s,bundle:_.bundle,loading:!1,error:""})}).catch(p=>{var _,L;B&&$({key:s,bundle:null,loading:!1,error:((L=(_=p==null?void 0:p.response)==null?void 0:_.data)==null?void 0:L.error)||p.message||"Financial evidence unavailable"})}).finally(()=>clearTimeout(R)),()=>{B=!1,clearTimeout(R)}},[h,i==null?void 0:i.id,s,F,k]),!h)return null;const l=T.key===s?T.bundle:null,W=()=>{if(!l)return;const B=new Blob([JSON.stringify(l,null,2)],{type:"application/json"}),R=URL.createObjectURL(B),p=document.createElement("a");p.href=R,p.download=`partner-reconciliation-${s}.json`,p.click(),URL.revokeObjectURL(R)};return e.jsxs("section",{className:"rounded-2xl border border-blue-200 bg-slate-50 p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(y,{variant:"outline",className:"whitespace-normal text-left text-blue-900",onClick:()=>C(B=>!B),"aria-expanded":F,children:[e.jsx(Ks,{className:"mr-2 h-4 w-4 shrink-0"}),"Main Admin financial reconciliation",e.jsx(et,{className:"ml-2 h-4 w-4 shrink-0"})]}),F&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{variant:"outline",disabled:T.loading,onClick:()=>X(B=>B+1),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),"Refresh"]}),e.jsxs(y,{variant:"outline",disabled:!l,onClick:W,children:[e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Export"]})]})]}),F&&T.loading&&e.jsxs("p",{role:"status",className:"flex items-center gap-2 text-sm text-slate-700",children:[e.jsx(ne,{className:"h-4 w-4 th-inline-spinner"}),"Verifying linked financial evidenceâ¦"]}),F&&T.key===s&&T.error&&e.jsx("p",{role:"alert",className:"rounded-lg bg-red-50 p-3 text-sm text-red-800",children:T.error}),F&&l&&e.jsx(ba,{bundle:l})]})}function De({icon:s,label:i,accent:h="#2563EB",meta:F}){return e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${h}14`},children:e.jsx(s,{className:"w-4 h-4",style:{color:h}})}),e.jsx("h4",{className:"text-[11px] uppercase tracking-[0.08em] font-semibold text-[#64748B]",children:i})]}),F]})}function Te({className:s="",children:i}){return e.jsx("div",{className:`bg-white rounded-xl border border-[#E5E7EB] p-4 md:p-5 ${s}`,children:i})}function _a({order:s,customer:i,ctx:h}){var qe,we;const{salesReps:F,customers:C,operationsOrders:k,currentUser:X,editingOrder:T,editedItems:$,editedServices:l,saving:W,startEditOrder:B,updateItemQuantity:R,updateItemPrice:p,removeItem:_,openAddTireModal:L,addServiceToEdit:J,updateEditedService:G,removeEditedService:oe,standardServicePrices:ae,saveOrderChanges:le,setEditingOrder:O,setEditedServices:K,getEffectiveStatus:ee,getStatusBadge:me,setOrders:H,creditsToAdd:pe,setCreditsToAdd:Q,addingCredits:he,addCreditsToCustomer:b,updatingOrder:z,updateOrderStatus:U,customFeeOpen:q,setCustomFeeOpen:xe,updateDeliveryFee:ue,updateAdminNotes:be,moveToTrash:v,restoreFromTrash:E,exportToXLS:se,setSmsOrder:te,setSmsCustomer:Z,setSmsModalOpen:w,setOpsOrder:Se,setOpsCustomer:je,setShowOpsModal:Ye,getCreditsEarnedStatusBadge:Xe,onOrderUpdated:ve}=h,Ne=T===s.id,V=Ne&&s.status==="completed";
17return e.jsxs("div",{className:"border-t border-[#E5E7EB] p-4 md:p-5 space-y-4 bg-[#FAFBFC]",children:[s.partner_sale===!0&&e.jsxs(e.Fragment,{children:[e.jsx(ga,{order:s,onUpdated:ve}),e.jsx(Wt,{orderId:s.id}),e.jsx(ja,{orderId:s.id,currentUser:X})]}),e.jsxs(Te,{children:[e.jsx(De,{icon:hs,label:"Order Items",meta:!Ne&&!s.partner_sale&&e.jsxs(y,{size:"sm",onClick:()=>B(s),className:"bg-[#2563EB] text-white hover:bg-[#1D4ED8] border-0 font-semibold h-8",children:[e.jsx(aa,{className:"w-3 h-3 mr-1.5"}),"Edit Items"]})}),e.jsx("div",{className:"space-y-2",children:(qe=Ne?$:s.items)==null?void 0:qe.map((d,N)=>{var D;return e.jsxs("div",{className:"flex justify-between items-center bg-[#F9FAFB] rounded-lg p-3 border border-[#F1F5F9]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-[#17213A] font-medium truncate",children:[d.brand," ",d.model||""]}),e.jsxs("p",{className:"text-[#64748B] text-sm",children:[d.ply_rating&&e.jsxs("span",{className:"font-medium",children:[d.ply_rating," ⢠"]}),d.size,d.position&&e.jsxs("span",{children:[" ⢠",d.position]})]})]}),Ne?e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{size:"icon",variant:"outline",className:"h-8 w-8 border-[#
17E5E7EB] text-[#17213A] hover:bg-[#F3F4F6]",onClick:()=>R(N,-1),disabled:V||d.quantity<=1,children:e.jsx(Ws,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-[#17213A] w-8 text-center",children:d.quantity}),e.jsx(y,{size:"icon",variant:"outline",className:"h-8 w-8 border-[#E5E7EB] text-[#17213A] hover:bg-[#F3F4F6]",onClick:()=>R(N,1),disabled:V,children:e.jsx(Ge,{className:"w-4 h-4"})})]}),e.jsx("span",{className:"text-[#64748B] text-sm",children:"Ã"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[#64748B] text-sm",children:"$"}),e.jsx("input",{type:"number",step:"0.01",value:d.price,onChange:Y=>p(N,Y.target.value),className:"w-20 text-right bg-white border border-[#E5E7EB] rounded px-2 py-1 text-[#17213A] text-sm"})]}),e.jsxs("span",{className:"text-[#2563EB] font-bold text-sm",children:["$",(d.quantity*d.price).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-8 w-8 text-[#DC2626] hover:text-[#B91C1C] hover:bg-[#DC2626]/10",onClick:()=>_(N),disabled:V,children:e.jsx(Me,{className:"w-4 h-4"})})]}):e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("p",{className:"text-[#17213A]",children:[d.quantity," Ã $",(D=d.price)==null?void 0:D.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("p",{className:"text-[#64748B] text-sm",children:["$",(d.quantity*d.price).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})]},N)})}),Ne&&e.jsxs("div",{className:"mt-3 space-y-3",children:[V&&e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border border-amber-300 bg-amber-50 px-3 py-2.5",children:[e.jsx(Le,{className:"w-4 h-4 text-amber-600 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-amber-800",children:[e.jsx("p",{className:"font-semibold",children:"Main Admin price correction"}),e.jsx("p",{className:"mt-0.5",children:"This order is completed. Quantities, SKUs, services, and fulfillment locations are locked â only selling prices can be changed. Inventory and EST QTY are not touched."})]})]}),e.jsxs(y,{variant:"outline",onClick:()=>L(s.id),className:"w-full border-dashed border-[#E5E7EB] text-[#64748B] hover:text-[#17213A] hover:bg-[#F9FAFB]",disabled:V,children:[e.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Add Tire to Order"]}),e.jsxs("div",{className:"bg-purple-50 rounded-xl p-4 border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("h5",{className:"text-purple-700 text-sm font-semibold flex items-center gap-2",children:[e.jsx(ra,{className:"w-4 h-4"}),"Additional Services"]})}),l.length>0&&e.jsx("div",{className:"space-y-2 mb-3",children:l.map((d,N)=>{var Y;const D=d.service_type==="transaction_fee";return e.jsxs("div",{className:`flex items-center gap-2 bg-white rounded-lg p-3 border-2 ${D?"border-orange-300":"border-purple-300"}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-[#17213A] font-medium text-sm capitalize",children:[d.service_type.replace(/_/g," "),D&&e.jsx("span",{className:"ml-2 text-orange-600 text-xs",children:"(5% of subtotal)"})]}),e.jsx("p",{className:"text-[#64748B] text-xs",children:D?`Auto-calculated: 5% of $${($.reduce((re,P)=>re+P.quantity*P.price,0)+l.filter(re=>re.service_type!=="transaction_fee").reduce((re,P)=>re+P.total_price,0)).toFixed(2)}`:`Standard: $${((Y=ae[d.service_type])==null?void 0:Y.toFixed(2))||"0.00"}`})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[!D&&e.jsxs("div",{className:"flex items-center gap-1 bg-[#F9FAFB] rounded-lg px-2 py-1",children:[e.jsx(y,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:()=>G(N,"quantity",Math.max(1,d.quantity-1)),disabled:d.quantity<=1,children:e.jsx(Ws,{className:"w-3 h-3"})}),e.jsx("input",{type:"number",value:d.quantity,onChange:re=>G(N,"quantity",parseInt(re.target.value)||1),className:"w-12 text-center bg-transparent border-0 text-[#17213A] text-sm",min:"1"}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:()=>G(N,"quantity",d.quantity+1),children:e.jsx(Ge,{className:"w-3 h-3"})})]}),!D&&e.jsx("span",{className:"text-[#64748B] text-sm",children:"Ã"}),e.jsxs("div",{className:"flex items-center gap-1",children:[!D&&e.jsx("span",{className:"text-[#64748B] text-sm",children:"$"}),e.jsx("input",{type:"number",step:"0.01",value:d.price_per_unit,onChange:re=>G(N,"price_per_unit",parseFloat(re.target.value)||0),className:`w-20 text-right bg-[#F9FAFB] border border-[#
17E5E7EB] rounded px-2 py-1 text-[#17213A] text-sm ${D?"font-bold":""}`,placeholder:D?"Override":"",title:D?"Override transaction fee amount":""})]}),e.jsxs("span",{className:`font-bold text-sm w-20 text-right ${D?"text-orange-600":"text-purple-600"}`,children:["$",d.total_price.toFixed(2)]}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-8 w-8 text-[#DC2626] hover:bg-[#DC2626]/10",onClick:()=>oe(N),disabled:V,children:e.jsx(Me,{className:"w-4 h-4"})})]})]},N)})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:Object.entries(ae).map(([d,N])=>{const D=l.some(re=>re.service_type===d),Y=d==="transaction_fee";return e.jsxs("button",{onClick:()=>J(d),disabled:D||V,className:`flex flex-col items-center justify-center p-3 rounded-lg border transition-all ${D?"bg-gray-100 border-gray-300 opacity-50 cursor-not-allowed":Y?"bg-white border-orange-300 hover:bg-orange-50 hover:border-orange-400":"bg-white border-purple-300 hover:bg-purple-50 hover:border-purple-400"}`,children:[e.jsx("span",{className:"text-[#17213A] font-medium text-xs capitalize",children:d.replace(/_/g," ")}),e.jsx("span",{className:`font-bold text-sm mt-1 ${Y?"text-orange-600":"text-purple-600"}`,children:Y?`${N}%`:`$${N.toFixed(2)}`}),D&&e.jsx("span",{className:"text-[#16A34A] text-xs mt-1",children:"â Added"})]},d)})}),l.length>0&&e.jsx("div",{className:"mt-3 pt-3 border-t border-purple-300",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-purple-700 font-medium text-sm",children:"Services Total:"}),e.jsxs("span",{className:"text-purple-600 font-bold text-lg",children:["$",l.reduce((d,N)=>d+N.total_price,0).toFixed(2)]})]})})]}),e.jsxs("div",{className:"pt-3 border-t border-[#E5E7EB]",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-[#64748B] font-medium",children:"Tires Subtotal:"}),e.jsxs("span",{className:"text-[#17213A] font-semibold",children:["$",$.reduce((d,N)=>d+N.quantity*N.price,0).toFixed(2)]})]}),l.filter(d=>d.service_type!=="transaction_fee").length>0&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-[#64748B] font-medium",children:"Services Subtotal:"}),e.jsxs("span",{className:"text-[#17213A] font-semibold",children:["$",l.filter(d=>d.service_type!=="transaction_fee").reduce((d,N)=>d+N.total_price,0).toFixed(2)]})]}),l.some(d=>d.service_type==="transaction_fee")&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-orange-600 font-medium",children:"Transaction Fee:"}),e.jsxs("span",{className:"text-orange-600 font-semibold",children:["$",l.find(d=>d.service_type==="transaction_fee").total_price.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between items-center pt-2 border-t border-[#2563EB]/20",children:[e.jsx("span",{className:"text-[#2563EB] font-bold",children:"Grand Total:"}),e.jsxs("span",{className:"text-[#2563EB] font-bold text-xl",children:["$",($.reduce((d,N)=>d+N.quantity*N.price,0)+l.reduce((d,N)=>d+N.total_price,0)).toFixed(2)]})]})]}),e.jsx("p",{className:"text-[#94A3B8] text-xs mt-2",children:"Tax, delivery fee, and credits will be calculated on save"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(y,{onClick:()=>le(s.id),disabled:W,className:"flex-1 bg-[#2563EB] hover:bg-[#1D4ED8] text-white",children:[W?e.jsx(ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Save Changes"]}),e.jsx(y,{variant:"ghost",onClick:()=>{O(null),K([])},className:"text-[#64748B] hover:text-[#17213A]",children:"Cancel"})]})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs(Te,{children:[e.jsx(De,{icon:us,label:"Customer Details"}),e.jsx("div",{className:"mb-4",children:e.jsx(Vt,{customerId:s.customer_id,canManage:!0})}),i?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[#17213A] font-medium",children:i.contact_name}),e.jsx("p",{className:"text-[#64748B] text-sm",children:i.company_name})]}
17),e.jsxs("div",{className:"pt-2 border-t border-[#E5E7EB] space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[#64748B] text-sm",children:"Email:"}),e.jsx("a",{href:`mailto:${i.user_email}`,className:"text-[#2563EB] hover:underline text-sm truncate ml-2",children:i.user_email})]}),i.phone_number&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[#64748B] text-sm",children:"Phone:"}),e.jsx("a",{href:`tel:${i.phone_number}`,className:"text-[#17213A] hover:underline text-sm",children:i.phone_number})]}),(i.address||i.state)&&e.jsxs("div",{className:"flex items-start justify-between mt-1",children:[e.jsx("span",{className:"text-[#64748B] text-sm shrink-0 mr-2",children:"Address:"}),e.jsx("span",{className:"text-[#17213A] text-sm text-right",children:[i.address,i.state].filter(Boolean).join(", ")})]}),(()=>{const d=((i==null?void 0:i.assigned_rep_ids)||[]).map(P=>F.find(ke=>ke.id===P)).filter(Boolean),N=[];i!=null&&i.sales_rep_1_name&&N.push({name:i.sales_rep_1_name,phone:i.sales_rep_1_phone,email:i.sales_rep_1_email}),i!=null&&i.sales_rep_2_name&&N.push({name:i.sales_rep_2_name,phone:i.sales_rep_2_phone,email:i.sales_rep_2_email});const D=[...d,...N],Y=[],re=new Set;return D.forEach(P=>{P.name&&!re.has(P.name)&&(re.add(P.name),Y.push(P))}),Y.length>0?e.jsxs("div",{className:"pt-4 mt-4 border-t border-[#E5E7EB]",children:[e.jsx("span",{className:"text-[#64748B] text-xs uppercase tracking-wider font-semibold block mb-3",children:"Account Representatives"}),e.jsx("div",{className:"space-y-3",children:Y.map((P,ke)=>e.jsxs("div",{className:"flex items-start gap-3 bg-[#F9FAFB] p-3 rounded-lg border border-[#E5E7EB]",children:[P.photo_url?e.jsx("img",{src:P.photo_url,alt:P.name,className:"w-10 h-10 rounded-full object-cover border border-[#E5E7EB]"}):e.jsx("div",{className:"w-10 h-10 bg-[#2563EB]/10 rounded-full flex items-center justify-center text-[#2563EB]",children:e.jsx(us,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#17213A] font-medium text-sm",children:P.name}),e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[P.phone&&e.jsxs("a",{href:`tel:${P.phone}`,className:"text-[#64748B] text-xs hover:text-[#2563EB] flex items-center gap-1.5",children:[e.jsx("span",{className:"opacity-70",children:"ð"})," ",P.phone]}),P.email&&e.jsxs("a",{href:`mailto:${P.email}`,className:"text-[#64748B] text-xs hover:text-[#2563EB] flex items-center gap-1.5",children:[e.jsx("span",{className:"opacity-70",children:"âï¸"})," ",P.email]})]})]})]},ke))})]}):null})()]})]}):e.jsx("p",{className:"text-[#94A3B8] text-sm",children:"Customer information unavailable"})]}),e.jsx(ua,{order:s,operationsOrders:k,onOrderUpdated:h.onOrderUpdated}),e.jsxs(Te,{children:[e.jsx(De,{icon:ia,label:"Payment Method(s)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:((we=s.payment_methods)==null?void 0:we.map((d,N)=>e.jsx(ge,{variant:"outline",className:"border-[#E5E7EB] text-[#17213A]",children:d},N)))||e.jsx("p",{className:"text-[#64748B] text-sm",children:"Not specified"})})]})]}),e.jsx(ha,{opsOrder:k[s.id],orderStatus:s.status}),(s.status==="pending"||s.status==="in_progress")&&X&&e.jsxs(Te,{children:[e.jsx(De,{icon:Zs,label:"Order Chat",accent:"#7C3AED"}),e.jsx(Jt,{order:s,currentUser:X,userType:"admin",onMessageSent:d=>{H(N=>N.map(D=>D.id===s.id?{...D,chat_messages:d}:D))}})]}),s.customer_notes&&e.jsxs(Te,{children:[e.jsx(De,{icon:na,label:"Customer Notes",accent:"#0891B2"}),e.jsx("p",{className:"text-[#17213A] text-sm whitespace-pre-wrap",children:s.customer_notes})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#E5E7EB] overflow-hidden",children:[e.jsx("div",{className:"h-1 bg-[#2563EB]"}),e.jsx("div",{className:"p-4 md:p-5",children:e.jsx(fa,{order:s,customer:i,salesReps:F,customers:C,setCustomers:h.setCustomers,creditsToAdd:pe,setCreditsToAdd:Q,addingCredits:he,addCreditsToCustomer:b,updatingOrder:z,updateOrderStatus:U,customFeeOpen:q,setCustomFeeOpen:xe,updateDeliveryFee:ue,updateAdminNotes:be,moveToTrash:v,restoreFromTrash:E,exportToXLS:se,setSmsOrder:te,setSmsCustomer:Z,setSmsModalOpen:w,setOpsOrder:Se,setOpsCustomer:je,setShowOpsModal:Ye,getCreditsEarnedStatusBadge:Xe})})]})]})}const va=fs(()=>Ue(()=>import("./SMSUpdateModal-HLILNO-U.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]))),Na=fs(()=>Ue(()=>import("./CreateOrderModal-BOj8sSRk.js"),__vite__mapDeps([36,1,2,37,38,39,40,3,4,5,6,7,8,41,9,12,13,14,15,11,16,17,18,19,20,21,22,23,42,43,44,45,46,47,48,49,26,24,25,27,28,50,51,34,52,53,54,55,56,57]))),ya=fs(()=>Ue(()=>import("./SendToOperationsModal-CUpow1UF.js"),__vite__mapDeps([58,1,2,3,4,5,6,7,8,9,24,25,13,15,11,16,26,27,21,28,34,35]))),st=50,wa=3,Ca=[3e3,1e4,25e3],ls={page:1,page_size:st,status_filter:"all",search:"",sales_rep_id:null,date_from:null,date_to:null,brands:[],sizes:[],customer_id:null,min_total:null,max_total:null,sort_by:"created_date",sort_order:"desc"};function Bi(){var qs,Is;const{gatedInvoke:s}=Rt(),[i,h]=c.useState([]),[F,C]=c.useState({}),[k,X]=c.useState([]),[T,$]=c.useState({}),[l,W]=c.useState(null),[B,R]=c.useState([]),[p,_]=c.useState(1),[L,J]=c.useState("all"),[G,oe]=c.useState("all"),[ae,le]=c.useState(()=>{try{return new URLSearchParams(window.location.search).get("search")||""}catch{return""}}),[O,K]=c.useState(null),[ee,me]=c.useState(0),[H,pe]=c.useState(!1),[Q,he]=c.useState({pen
17ding:0,in_progress:0,on_the_way:0,completed:0,cancelled:0,all:0,trash:0}),[b,z]=c.useState(!0),[U,q]=c.useState(!1),[xe,ue]=c.useState(!1),[be,v]=c.useState(!1),[E,se]=c.useState(!1),[te,Z]=c.useState(null),[w,Se]=c.useState(null),[je,Ye]=c.useState(!1),[Xe,ve]=c.useState(null),[Ne,V]=c.useState(null),[qe,we]=c.useState(null),[d,N]=c.useState([]),[D,Y]=c.useState([]),[re,P]=c.useState(!1),[ke,Ze]=c.useState(!1),[Je,bs]=c.useState(""),[Fa,tt]=c.useState(null),[Ke,at]=c.useState({}),[rt,js]=c.useState(null),[_s,vs]=c.useState(!1),[it,nt]=c.useState(null),[lt,ct]=c.useState(null),[ot,dt]=c.useState({}),[Ns,ys]=c.useState(!1),[ws,Cs]=c.useState(!1),[mt,xt]=c.useState(null),[pt,ht]=c.useState(null),es=c.useRef(0),ss=c.useRef(0),Ie=c.useRef(0),Ae=c.useRef(null),Fs=c.useRef(0),Ce=c.useRef(null),fe=c.useCallback((t={})=>{const a=(()=>{if(G==="all")return null;const r=k.find(n=>n.name===G);return(r==null?void 0:r.id)||null})();return{...O,status_filter:L,search:ae.trim(),sales_rep_id:a,...t}},[L,G,ae,O,k]),ye=c.useCallback(async(t,{bust:a=!1,isRefresh:r=!1}={})=>{const n=++Fs.current;es.current++,r?q(!0):ue(!0);let m=!1;const g=()=>{if(ss.current===0&&Ie.current<wa){const f=Ie.current;return Ie.current++,m=!0,setTimeout(()=>ye(t,{bust:a,isRefresh:r}),Ca[f]??1e4),!0}return!1},u=()=>{ue(!0),ss.current>0?(v(!0),se(!1)):(v(!1),se(!0))};try{const x=(await s("queryAdminOrders",{...ls,...t,bust:a})).data||{};if(n!==Fs.current)return;const I=x.rows||[];if(x.degraded){g()||u();return}h(I),ss.current=I.length,Ie.current=0,x.total_count!=null&&me(x.total_count),pe(!!x.has_more),x.metrics&&Se(x.metrics);const S={},j={};for(const M of I)M._customer&&(S[M.customer_id]=M._customer),M._ops_order&&(j[M.id]=M._ops_order);C(M=>({...M,...S})),$(M=>({...M,...j})),x.user&&W(x.user),Z(new Date),ue(!1),v(!1),se(!1)}catch(f){console.error("queryAdminOrders failed:",f),g()||(u(),o.error("Failed to load orders"))}finally{es.current=Math.max(0,es.current-1),q(!1),m||z(!1)}},[]),Fe=c.useCallback(async(t,{bust:a=!1}={})=>{try{const n=(await s("getAdminOrderCounts",{...ls,...t,bust:a})).data||{};n.counts&&he(n.counts),n.total_count!=null&&me(n.total_count)}catch(r){console.error("getAdminOrderCounts failed:",r),ue(!0)}},[]),ts=c.useCallback(async(t={})=>{var a;try{const n=(await s("getAdminOrderFilterMeta",{with_customers:t.with_customers!==!1})).data||{};if((a=n.customers)!=null&&a.length){const m={};for(const g of n.customers)m[g.id]=g;C(g=>({...g,...m}))}n.sales_reps&&X(n.sales_reps)}catch(r){console.error("getAdminOrderFilterMeta failed:",r)}},[]),Es=c.useRef(!1),ut=c.useCallback(()=>{Es.current||(Es.current=!0,ts({with_customers:!0}))},[ts]);c.useEffect(()=>{ye(fe());const t=setTimeout(()=>{Fe(fe()),ts({with_customers:!1})},1200);let a=null;const r=u=>{if(document.visibilityState==="hidden"){a=u;return}Ce.current&&clearTimeout(Ce.current),Ce.current=setTimeout(()=>{Ce.current=null,u()},1500)},n=()=>
17{if(document.visibilityState!=="visible"||!a)return;const u=a;a=null,r(u)},m=A.entities.Order.subscribe(u=>{u.type==="update"&&u.data?(h(f=>f.map(x=>x.id===u.id?{...x,...u.data}:x)),u.data.status&&r(()=>Fe(fe(),{bust:!0}))):(u.type==="create"||u.type==="delete")&&r(()=>{ye(fe(),{bust:!0,isRefresh:!0}),Fe(fe(),{bust:!0})})}),g=A.entities.OperationsOrder.subscribe(u=>{u.type==="update"&&u.data&&$(f=>{const x=Object.keys(f).find(I=>f[I].id===u.id);return x?{...f,[x]:{...f[x],...u.data}}:f})});return document.addEventListener("visibilitychange",n),()=>{try{m()}catch{}try{g()}catch{}document.removeEventListener("visibilitychange",n),clearTimeout(t),Ce.current&&clearTimeout(Ce.current)}},[]),c.useEffect(()=>{if(!je)return;const t=fe({page:1});_(1);const a=setTimeout(()=>{ye(t),Fe(t)},180);return()=>clearTimeout(a)},[L,G,O]),c.useEffect(()=>{if(je)return Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>{ye(fe({page:1})),Fe(fe({page:1}))},300),()=>{Ae.current&&clearTimeout(Ae.current)}},[ae]);const Ss=t=>{t<1||(_(t),ye(fe({page:t})))};c.useEffect(()=>{te&&!je&&Ye(!0)},[te,je]);const ks=c.useRef(!1);c.useEffect(()=>{if(!(ks.current||!je||i.length===0))try{const t=new URLSearchParams(window.location.search).get("order_id");if(!t)return;const a=i.find(r=>r.id===t);a&&(ks.current=!0,ve(a.id),setTimeout(()=>{const r=document.getElementById(`admin-order-row-${a.id}`);r&&r.scrollIntoView({behavior:"smooth",block:"center"})},100))}catch{}},[je,i]);const Be=(t,a)=>{h(r=>r.map(n=>n.id===t?{...n,...a}:n))},ie=()=>{ye(fe(),{bust:!0,isRefresh:!0}),Fe(fe(),{bust:!0})},As=(t,a="orders-export.xls")=>{const r=Array.isArray(t)?t:[t],n=["Order ID","Date (CT)","Status","Customer Name","Company","Email","Phone","Fulfillment Type","Delivery Address","Payment Methods","Items List","Order Subtotal","Credits Applied","Delivery Fee","Final Amount","Admin Notes","Customer Notes"];let m='<html xmlns:x="urn:schemas-microsoft-com:office:excel"><head><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table border="1"><thead><tr>';n.forEach(x=>{m+=`<th style="background-color:#f0f0f0;font-weight:bold;">${x}</th>`}),m+="</tr></thead><tbody>",r.forEach(x=>{var M;const I=F[x.customer_id]||{},S=new Date(x.order_date||x.created_date).toLocaleDateString("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",year:"numeric"}),j=(x.items||[]).map(ce=>{var zs;return`${ce.quantity}x ${ce.brand||""} ${ce.size||""} @ $${(zs=ce.price)==null?void 0:zs.toLocaleString("en-US",{minimumFractionDigits:2})} (Total: $${((ce.quantity||0)*(ce.price||0)).toLocaleString("en-US",{minimumFractionDigits:2})})`}).join(` 18`);m+="<tr>",[x.id,S,x.status,I.contact_name||"",I.company_name||"",I.user_email||"",I.phone_number||"",x.fulfillment_type||"",x.delivery_address||"",((M=x.payment_methods)==null?void 0:M.join(" | "))||"",j,x.total_amount||0,x.credits_applied||0,x.delivery_fee||0,x.final_amount||x.total_amount||0,x.admin_notes||"",x.customer_notes||""].forEach(ce=>{m+=`<td style="white-space:pre-wrap;">${ce}</td>`}),m+="</tr>"}),m+="</tbody></table></body></html>";const g=new Blob([m],{type:"application/vnd.ms-excel"}),u=document.createElement("a"),f=URL.createObjectURL(g);u.setAttribute("href",f),u.setAttribute("download",a),u.style.visibility="hidden",document.body.appendChild(u),u.click(),document.body.removeChild(u)},ft=async(t,a)=>{V(t);try{const r=i.find(S=>S.id===t),n=F[r==null?void 0:r.customer_id],m=r==null?void 0:r.status,g=T[t],u=new Date().toISOString().split("T")[0],f=S=>S&&S.data?S.data:S;if(m===a){o.success("Status unchanged"),V(null);return}if(a==="completed"&&m!=="completed"){if(!g){o.error("No operations order is linked to this order. Send it to operations first."),V(null);return}const S=await A.functions.invoke("completeOperationsOrderV2",{ops_order_id:g.id,completion_date:u}),j=f(S);if(j!=null&&j.already_completed)o.success("Order was already completed");else if(j!=null&&j.already_in_progress)o.error("A completion for this order is already in progress â please wait.");else if(j!=null&&j.error){o.error(j.error),V(null);return}else o.success(`Order completed${j!=null&&j.credits_awarded?` · $${Number(j.credits_awarded).toFixed(2)} credits awarded`:""}`);
18if(ie(),n!=null&&n.user_email)try{const{sendOrderCompletedEmail:M}=await Ue(async()=>{const{sendOrderCompletedEmail:ce}=await import("./AdminOrderEmailHelper-BfgRFZI6.js");return{sendOrderCompletedEmail:ce}},__vite__mapDeps([59,1,2,60]));await M(n,r,t),o.success("Detailed confirmation sent to customer")}catch(M){console.error("Failed to send email:",M)}V(null);return}if(m==="completed"&&a!=="completed"){if(a==="cancelled"){const M=await A.functions.invoke("cancelCustomerOrder",{order_id:t}),ce=f(M);if(ce!=null&&ce.error){o.error(ce.error),V(null);return}o.success("Order cancelled"),ie(),V(null);return}if(!g){o.error("No operations order is linked â cannot reopen."),V(null);return}const S=await A.functions.invoke("reopenCompletedOrder",{ops_order_id:g.id,reason:`Admin status change: completed â ${a}`}),j=f(S);if(j!=null&&j.already_open)o.success("Order already open");else if(j!=null&&j.error){o.error(j.error),V(null);return}else o.success("Order reopened (inventory + credits reversed)");if(j!=null&&j.success&&a!=="in_progress")try{await A.functions.invoke("setOrderStatus",{order_id:t,new_status:a})}catch{}ie(),V(null);return}if(a==="cancelled"){const S=await A.functions.invoke("cancelCustomerOrder",{order_id:t}),j=f(S);if(j!=null&&j.error){o.error(j.error),V(null);return}o.success("Order cancelled"),ie(),V(null);return}const x=await A.functions.invoke("setOrderStatus",{order_id:t,new_status:a}),I=f(x);if(I!=null&&I.error){o.error(I.error),V(null);return}if(g){const j={pending:"received",in_progress:"in_progress",on_the_way:"on_the_way"}[a];if(j)try{await A.functions.invoke("setOperationsOrderStatus",{ops_order_id:g.id,new_status:j})}catch{}}if(o.success("Status updated"),Be(t,{status:a}),L!=="all"&&L!==a&&ie(),n!=null&&n.user_email&&a==="in_progress")try{await A.integrations.Core.SendEmail({to:n.user_email,subject:"Order Update - In Progress",body:`Hi ${n.company_name}, 19 20Great news! Your order #${t.slice(-6).toUpperCase()} is now being processed. 21 22Thank you, 23Truck Haters Team`}),o.success("Customer notified via email")}catch(S){console.error("Failed to send email:",S)}}catch(r){console.error("updateOrderStatus failed:",r),o.error("Failed to update status")}V(null)},gt=async(t,a)=>{try{const r=await A.functions.invoke("updateOrderAdminNotes",{order_id:t,admin_notes:a,actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),n=r&&r.data?r.data:r;if(n!=null&&n.error){o.error(n.error);return}n!=null&&n.order?Be(t,n.order):Be(t,{admin_notes:a}),o.success(n!=null&&n.th_credit_changed?"Notes saved · totals recomputed":"Notes saved")}catch{o.error("Failed to save notes")}},bt=async t=>{if(confirm("Move this order to trash?"))try{const a=await A.functions.invoke("archiveOrder",{order_id:t,action:"trash",actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),r=a&&a.data?a.data:a;if(r!=null&&r.error){o.error(r.error);return}ve(null),ie(),o.success("Order moved to trash")}catch{o.error("Failed to move to trash")}},jt=async t=>{try{const a=await A.functions.invoke("archiveOrder",{order_id:t,action:"restore",actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),r=a&&a.data?a.data:a;if(r!=null&&r.error){o.error(r.error);return}ie(),o.success("Order restored")}catch{o.error("Failed to restore order")}},_t=async t=>{if(confirm("This will PERMANENTLY delete this order. This action cannot be undone. Continue?"))try{const a=await A.functions.invoke("deleteOrder",{order_ids:[t],actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),r=a&&a.data?a.data:a;if(r!=null&&r.error){o.error(r.error);return}ve(null),ie(),o.success("Order permanently deleted")}catch{o.error("Failed to delete order")}},Bs=async()=>{var a;let t=[];try{t=(((a=(await s("queryAdminOrders",{...ls,status_filter:"trash",page_size:500,bust:!0})).data)==null?void 0:a.rows)||[]).map(n=>n.id)}catch{}if(t.length!==0&&confirm(`Are you sure you want to permanently delete ${t.length} orders from the trash? This cannot be undone.`)){q(!0);try{const r=await A.functions.invoke("deleteOrder",{order_ids:t,actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),n=r&&r.data?r.data:r;if(n!=null&&n.error){o.error(n.error),q(!1);return}o.success(`Trash emptied (${(n==null?void 0:n.deleted_count)||0} orders deleted)`),ie()}catch{o.error("Failed to empty trash")}q(!1)}},vt=async(t,a)=>{const r=parseFloat(a);if((isNaN(r)||r<0)&&a!=="")return;const n=a===""?0:r;try{const m=await A.functions.invoke("updateOrderDeliveryFee",{order_id:t,delivery_fee:n,actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),g=m&&m.data?m.data:m;if(g!=null&&g.error){o.error(g.error);return}g!=null&&g.order&&Be(t,g.order),o.success("Delivery fee updated")}catch{o.error("Failed to update delivery fee")}},Nt=t=>{we(t.id),N([...t.items]),Y([...t.additional_services||[]]),ve(t.id)},Os={disposal:6,rotation:30,mount_dismount:49,valve:6,tire_patch:59,transaction_fee:5},yt=t=>{if(D.findIndex(r=>r.service_type===t)>=0){o.info("Service already added");return}if(t==="transaction_fee"){const r=d.reduce((u,f)=>u+f.quantity*f.price,0),n=D.reduce((u,f)=>u+(f.total_price||0),0),g=(r+n)*.05;Y(u=>[...u,{service_type:"transaction_fee",quantity:1,price_per_unit:g,total_price:g}]),o.success("Transaction fee added (5%)")}else{const r=Os[t]||0;Y(n=>[...n,{service_type:t,quantity:1,price_per_unit:r,total_price:r}]),o.success("Service added")}},wt=(t,a,r)=>{Y(n=>{const m=[...n];return m[t]={...m[t],[a]:r},(a==="quantity"||a==="price_per_unit")&&(m[t].total_price=m[t].quantity*m[t].price_per_unit),m})},Ct=t=>Y(a=>a.filter((r,n)=>n!==t)),Ds=(t,a)=>{N(r=>{const n=[...r],m=n[t].quantity+a;if(m<1)return r;const g={...n[t],quantity:m},u=(g.location_quantities||[]).filter(f=>Number(f.quantity)>0).map(f=>({...f}));if(u.length>0){const f=u.reduce((S,j)=>S+(Number(j.quantity)||0),0);let x=m;g.location_quantities=u.map((S,j)=>{if(j===u.length-1)return{...S,quantity:x};const M=f>0?Math.max(0,Math.floor(m*(Number(S.quantity)||0)/f)):0;return x-=M,{...S,quantity:M}});const I=g.location_quantities.find(S=>Number(S.quantity)>0);I&&(g.source_type="internal",g.source_location_id=I.location_id||"",g.source_location_name=I.location_name||"")}return n[t]=g,n})},Ft=(t,a)=>{N(r=>{const n=[...r];return n[t]={...n[t],price:parseFloat(a)||0},n})},Et=t=>{if(d.length<=1){o.error("Cannot remove all items. Delete the order instead.");return}N(a=>a.filter((r,n)=>n!==t))},Ts=c.useRef(!1),St=t=>{tt(t),bs(""),Ze(!0),Ts.current||(Ts.current=!0,A.entities.TirePricingRecord.list("-updated_date",1e3).then(a=>R(a||[])).catch(()=>{}))}
23,kt=t=>{const a=d.findIndex(r=>r.tire_id===t.id);a>=0?Ds(a,1):N(r=>[...r,{tire_id:t.id,tire_pricing_record_id:t.id,brand:t.brand,model:t.model||"",ply_rating:t.ply_rating||"",size:t.size,position:t.position||"",quantity:1,price:t.price_1_29??null}]),Ze(!1),o.success("Tire added to order")},At=async t=>{if(d.length===0){o.error("Order must have at least one item");return}P(!0);try{const a=i.find(g=>g.id===t),r=(a==null?void 0:a.status)==="completed",n=r?await A.functions.invoke("correctOrderPricing",{order_id:t,items:d,additional_services:D,actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name,reason:"Admin price correction"}):await A.functions.invoke("editOrder",{order_id:t,items:d,additional_services:D,actor_email:l==null?void 0:l.email,actor_name:l==null?void 0:l.full_name}),m=n&&n.data?n.data:n;if(m!=null&&m.error){o.error(m.error),P(!1);return}m!=null&&m.order&&Be(t,m.order),we(null),Y([]),r?m!=null&&m.recovery_required?o.error("Price correction failed and rollback was incomplete. A financial-sync recovery record was created and Main Admin was notified.",{duration:8e3}):m!=null&&m.overpayment_review?o.success("â Price correction synced to Order, Invoice & Operations",{description:"â Overpayment review flagged: corrected total is below the amount already paid. Main Admin notified. Quantity, inventory & EST QTY untouched.",duration:8e3}):o.success("â Main Admin price correction saved â synced to Order, Invoice, Operations & Gross Profit",{description:"Quantity, inventory & EST QTY untouched. All views refreshed.",duration:5e3}):o.success("â Order updated across ALL systems",{description:"Changes reflected in: Orders, Invoices, Gross Profit, Operations, Office Admin, and all Dashboards",duration:5e3})}catch(a){console.error("Order update failed:",a),o.error(`Failed to update order: ${(a==null?void 0:a.message)||"Unknown error"}`)}P(!1)},$s=B.filter(t=>{var a,r;return((a=t.brand)==null?void 0:a.toLowerCase().includes(Je.toLowerCase()))||((r=t.size)==null?void 0:r.toLowerCase().includes(Je.toLowerCase()))}),Bt=async t=>{var u;const a=t.id,r=F[t.customer_id];if(!r){o.error("Customer not found");return}const n=((u=t.items)==null?void 0:u.reduce((f,x)=>f+x.quantity,0))||0,m=r.credit_per_tire??.5,g=Ke[a]!==void 0?parseFloat(Ke[a]):n*m;if(isNaN(g)||g<0){o.error("Invalid credit amount");return}js(a);try{const f=await A.functions.invoke("awardOrderCredits",{order_id:a,amount:g}),x=f&&f.data?f.data:f;x!=null&&x.already_awarded?o.info("Credits were already awarded for this order"):x!=null&&x.error?o.error(x.error):o.success(`Added $${Number(x.credits_earned??g).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} credits to ${r.company_name}`),ie()}catch{o.error("Failed to add credits")}js(null)},Ot=t=>{const a={pending:{color:"bg-[#FFFBEB] text-[#B45309] border-[#FDE68A]",label:"Pending"},added:{color:"bg-[#ECFDF5] text-[#047857] border-[#A7F3D0]",label:"Added"},order_cancelled:{color:"bg-[#FEF2F2] text-[#B91C1C] border-[#FECACA]",label:"Order Cancelled"}},{color:r,label:n}=a[t]||a.pending;return e.jsx(ge,{className:`${r} border`,children:n})},Ls=t=>{const a=T[t.id];return a&&a.status!=="received"?a.status==="assigned_to_technician"?"in_progress":a.status:t.status},Ps=(t,a)=>{const r=T[a];let n=t,m=null;r&&r.status!=="received"&&(r.status==="assigned_to_technician"?(n="in_progress",m="Technician Assigned"):r.status==="on_the_way"?(n="on_the_way",m="On The Way"):r.status==="in_progress"?(n="in_progress",m="In Progress"):r.status==="completed"&&(n="completed",m="Completed"));const g={pending:"bg-[#FFFBEB] text-[#B45309] border-[#FDE68A]",in_progress:"bg-[#EFF6FF] text-[#1D4ED8] border-[#BFDBFE]",on_the_way:"bg-[#EFF6FF] text-[#1D4ED8] border-[#BFDBFE]",completed:"bg-[#ECFDF5] text-[#047857] border-[#A7F3D0]",cancelled:"bg-[#FEF2F2] text-[#B91C1C] border-[#FECACA]"},u={pending:Hs,in_progress:ne,on_the_way:Re,completed:Pe,cancelled:Ee},f={pending:"Pending",in_progress:"In Progress",on_the_way:"On The Way",completed:"Completed",cancelled:"Cancelled"},x=u[n]||Hs;return e.jsxs(ge,{className:`${g[n]||g.pending} border flex items-center gap-1`,children:[e.jsx(x,{className:`w-3 h-3 ${n==="in_progress"?"animate-spin":""}`}),m||f[n]||n]})};if(b)return e.jsx("div",{className:"min-h-screen bg-[#F9FAFB] flex items-center justify-center",children:e.jsx("div",{className:"w-8 h-8 border-2 border-[#2563EB] border-t-transparent roun
23ded-full animate-spin"})});const Oe=p,ze=(Oe-1)*st,Rs=ee!=null?Math.min(ze+i.length,ee):ze+i.length,Ms=k.map(t=>t.name).filter(Boolean).sort(),Dt={salesReps:k,customers:F,operationsOrders:T,currentUser:l,editingOrder:qe,editedItems:d,editedServices:D,saving:re,startEditOrder:Nt,updateItemQuantity:Ds,updateItemPrice:Ft,removeItem:Et,openAddTireModal:St,addServiceToEdit:yt,updateEditedService:wt,removeEditedService:Ct,standardServicePrices:Os,saveOrderChanges:At,setEditingOrder:we,setEditedServices:Y,getEffectiveStatus:Ls,getStatusBadge:Ps,setOrders:h,creditsToAdd:Ke,setCreditsToAdd:at,addingCredits:rt,addCreditsToCustomer:Bt,updatingOrder:Ne,updateOrderStatus:ft,customFeeOpen:ot,setCustomFeeOpen:dt,updateDeliveryFee:vt,updateAdminNotes:gt,moveToTrash:bt,restoreFromTrash:jt,deletePermanently:_t,emptyTrash:Bs,exportToXLS:As,setSmsOrder:nt,setSmsCustomer:ct,setSmsModalOpen:vs,setOpsOrder:xt,setOpsCustomer:ht,setShowOpsModal:Cs,getCreditsEarnedStatusBadge:Ot,setCustomers:C,onOrderUpdated:ie};return e.jsxs("div",{className:"min-h-screen bg-[#F9FAFB] p-4 lg:p-10",children:[e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold mb-2 text-[#17213A]",children:"Customer Orders"}),e.jsx("p",{className:"text-[#64748B]",children:"Manage and track customer orders"})]}),e.jsxs("div",{className:"flex gap-3",children:[Q.pending>0&&e.jsxs("div",{className:"bg-white border border-[#E5E7EB] rounded-xl px-4 py-3 flex items-center gap-3 shadow-sm",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ps,{className:"w-5 h-5 text-[#B45309]"}),e.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-[#B45309] rounded-full text-xs flex items-center justify-center text-white font-bold",children:Q.pending})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#17213A] font-semibold text-sm",children:"New Orders"}),e.jsxs("p",{className:"text-[#64748B] text-xs",children:[Q.pending," awaiting action"]})]})]}),Q.in_progress>0&&e.jsxs("div",{className:"bg-white border border-[#E5E7EB] rounded-xl px-4 py-3 flex items-center gap-3 shadow-sm",children:[e.jsx(ne,{className:"w-5 h-5 text-[#2563EB] animate-spin"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#17213A] font-semibold text-sm",children:"In Progress"}),e.jsxs("p",{className:"text-[#64748B] text-xs",children:[Q.in_progress," order(s)"]})]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs(y,{onClick:()=>ys(!0),className:"bg-[#2563EB] hover:bg-[#1D4ED8] text-white border-none font-semibold",children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Create Manual Order"]}),e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Gs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#64748B]"}),e.jsx(Qe,{placeholder:"Search by company, name, or order #...",value:ae,onChange:t=>le(t.target.value),className:"pl-10 bg-white border-[#E5E7EB] text-[#17213A] h-11 shadow-sm"}),ae&&e.jsx("button",{onClick:()=>le(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-[#64748B] hover:text-[#17213A]",children:e.jsx(Ee,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("button",{onClick:ie,className:"flex items-center gap-1.5 text-[#64748B] hover:text-[#17213A] px-2.5 py-1.5 rounded-lg hover:bg-white border border-transparent hover:border-[#E5E7EB] transition-colors",title:"Refresh",children:[e.jsx(He,{className:`w-3.5 h-3.5 ${U?"animate-spin":""}`}),te?te.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"â",xe&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#F59E0B] animate-pulse",title:"Refreshingâ¦"})]}),w&&e.jsxs("div",{className:"hidden md:flex items-center gap-2 text-[#94A3B8] px-2.5 py-1.5 rounded-lg bg-white/60 border border-[#E5E7EB]",title:`DB ${w.db_path==="pure"?"skip/limit":"in-memory scan"} · scanned ${w.rows_scanned} · matched ${w.rows_matched} · rows did ${w.counts_blocked?"not":""} wait on counts`,children:[e.jsx(la,{className:"w-3.5 h-3.5"}),w.execution_ms,"ms",e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-semibold ${w.db_path==="pure"?"bg-[#EFF6FF] text-[#1D4ED8]":"bg-[#FFFBEB] text-[#B45309]"}`,children:w.db_path==="pure"?"DB page":"mixed"}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-semibold ${w.cache_hit?"bg-[#ECFDF5] text-[#047857]":"bg-[#F1F5F9] text-[#64748B]"}
23`,children:w.cache_hit?"counts cached":"counts fresh"}),xe&&e.jsx("span",{className:"px-1.5 py-0.5 rounded-full text-[10px] font-semibold bg-[#FEF3C7] text-[#B45309]",children:"counts stale"}),w.results_truncated&&e.jsx("span",{className:"px-1.5 py-0.5 rounded-full text-[10px] font-semibold bg-[#FEF2F2] text-[#B91C1C]",title:`Scan reached the ${w.scan_limit} row limit â results may be incomplete. See scaling plan.`,children:"scan limit hit"})]})]})]}),e.jsxs("div",{className:"mt-8 mb-6 flex flex-wrap items-center justify-between gap-4",children:[Ms.length>0?e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(us,{className:"w-5 h-5 text-[#64748B]"}),e.jsx("span",{className:"text-[#64748B] text-sm font-medium",children:"Filter by Sales Rep:"}),e.jsxs(cs,{value:G,onValueChange:oe,children:[e.jsx(os,{className:"w-56 bg-white border-[#E5E7EB] text-[#17213A] h-12 shadow-sm",children:e.jsx(ds,{placeholder:"All Sales Reps"})}),e.jsxs(ms,{className:"bg-white border-[#E5E7EB]",children:[e.jsx(_e,{value:"all",children:"All Sales Reps"}),Ms.map(t=>e.jsx(_e,{value:t,children:t},t))]})]}),G!=="all"&&e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>oe("all"),className:"text-[#64748B] hover:text-[#17213A] h-10",children:"Clear"})]}):e.jsx("div",{}),e.jsxs(y,{onClick:()=>As(i,`orders-export-${new Date().toISOString().split("T")[0]}.xls`),className:"bg-[#2563EB] hover:bg-[#1D4ED8] text-white border-none font-semibold",title:"Export the current page",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Export Page (XLS)"]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(Lt,{orders:i,customers:F,onFilteredOrders:()=>{},onFilterStateChange:K,onFiltersOpen:ut,pageKey:"admin_orders",showCustomerFilter:!0,showTireFilter:!0,showDateFilter:!0,showSortOptions:!0,serverSide:!0})}),e.jsx("div",{className:"mt-8 bg-[#F9FAFB] p-1 rounded-xl inline-flex flex-wrap gap-1 border border-[#E5E7EB]",children:[{value:"pending",label:"Pending",count:Q.pending,badge:"bg-[#FFFBEB] text-[#B45309] border-[#FDE68A]"},{value:"in_progress",label:"In Progress",count:Q.in_progress,badge:"bg-[#EFF6FF] text-[#1D4ED8] border-[#BFDBFE]"},{value:"on_the_way",label:"On The Way",count:Q.on_the_way,badge:"bg-[#EFF6FF] text-[#1D4ED8] border-[#BFDBFE]"},{value:"completed",label:"Completed",count:Q.completed,badge:"bg-[#ECFDF5] text-[#047857] border-[#A7F3D0]"},{value:"all",label:"All Orders",count:Q.all,badge:"bg-[#F1F5F9] text-[#475569] border-[#E5E7EB]"},{value:"cancelled",label:"Cancelled",count:Q.cancelled,badge:"bg-[#FEF2F2] text-[#B91C1C] border-[#FECACA]"},{value:"trash",label:"Trash",count:Q.trash,badge:"bg-[#F1F5F9] text-[#64748B] border-[#E5E7EB]",icon:Me}].map(t=>e.jsxs("button",{onClick:()=>{J(t.value),_(1)},className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-all flex items-center gap-2 ${L===t.value?"bg-white text-[#17213A] shadow-sm":"bg-transparent text-[#64748B] hover:text-[#17213A] hover:bg-white/50"}`,children:[t.icon&&e.jsx(t.icon,{className:"w-4 h-4"}),t.label,e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-semibold border ${L===t.value?"bg-white text-[#17213A] border-[#E5E7EB]":t.badge}`,children:t.count})]},t.value))}),L==="trash"&&Q.trash>0&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-xs text-[#94A3B8] flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-[#B45309]"}),"Orders are archived here safely and are never permanently deleted."]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:Bs,className:"text-[#B91C1C] border-[#FECACA] hover:bg-[#FEF2F2]",children:[e.jsx(Me,{className:"w-3.5 h-3.5 mr-1.5"})," Empty Trash"]})]})]}),(w==null?void 0:w.results_truncated)&&e.jsxs("div",{className:"flex items-start gap-3 px-4 py-3 mb-4 rounded-xl border border-[#FECACA] bg-[#FEF2F2]",children:[e.jsx(Le,{className:"w-5 h-5 text-[#B91C1C] shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#991B1B] font-semibold text-sm",children:"Search results may be incomplete"}),e.jsxs("p",{className:"text-[#B91C1C] text-xs mt-0.5",children:["The in-memory scan reached the ",(qs=w==null?void 0:w.scan_limit)==null?void 0:qs.toLocaleStr
23ing(),"-order limit. Some older orders may not be shown for this search. Narrow the date range or sales rep to reduce the result set. (Scaling plan: move search/brand/size filters onto a denormalized DB index before the catalog reaches ",(Is=w==null?void 0:w.scan_limit)==null?void 0:Is.toLocaleString()," orders.)"]})]})]}),be&&e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 mb-4 rounded-xl border border-[#FDE68A] bg-[#FFFBEB]",children:[e.jsx(Le,{className:"w-5 h-5 text-[#B45309] shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[#B45309] font-semibold text-sm",children:"Couldn't refresh orders â showing last good data"}),e.jsx("p",{className:"text-[#B45309]/80 text-xs",children:"The latest read failed (this is usually momentary). Your current list is preserved."})]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:ie,className:"border-[#FDE68A] text-[#B45309] hover:bg-[#FEF3C7]",children:[e.jsx(He,{className:"w-3.5 h-3.5 mr-1.5"})," Retry"]})]}),E?e.jsxs("div",{className:"text-center py-16 bg-white rounded-xl border border-[#FECACA] shadow-sm",children:[e.jsx(Le,{className:"w-12 h-12 text-[#B91C1C] mx-auto mb-4"}),e.jsx("p",{className:"text-[#17213A] font-medium",children:"Couldn't load orders"}),e.jsx("p",{className:"text-[#64748B] text-sm mb-4",children:"The read failed â this is usually momentary. Your data is safe."}),e.jsxs(y,{onClick:ie,className:"bg-[#2563EB] hover:bg-[#1D4ED8] text-white",children:[e.jsx(He,{className:"w-4 h-4 mr-2"})," Try again"]})]}):i.length===0?e.jsxs("div",{className:"text-center py-16 bg-white rounded-xl border border-[#E5E7EB] shadow-sm",children:[e.jsx(hs,{className:"w-12 h-12 text-[#94A3B8] mx-auto mb-4"}),e.jsx("p",{className:"text-[#17213A] font-medium",children:"No orders match the current filters"}),e.jsx("p",{className:"text-[#64748B] text-sm",children:"Try selecting a different filter or clearing the search"})]}):e.jsxs("div",{className:"space-y-4",children:[i.map(t=>{var m,g;const a=F[t.customer_id]||t._customer,r=t._customer_display,n=Xe===t.id;return e.jsxs("div",{id:`admin-order-row-${t.id}`,className:"bg-white rounded-xl border border-[#E5E7EB] shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"p-4 md:p-5 flex flex-col md:flex-row md:items-center justify-between gap-4 cursor-pointer hover:bg-[#F9FAFB] transition-colors",onClick:()=>ve(n?null:t.id),children:[e.jsxs("div",{className:"flex items-center gap-4",children:[(()=>{const u=Ls(t),f={pending:{bg:"bg-[#FFFBEB]",icon:ps,color:"text-[#B45309]"},in_progress:{bg:"bg-[#EFF6FF]",icon:ne,color:"text-[#1D4ED8]",spin:!0},on_the_way:{bg:"bg-[#EFF6FF]",icon:Re,color:"text-[#1D4ED8]"},completed:{bg:"bg-[#ECFDF5]",icon:Pe,color:"text-[#047857]"},cancelled:{bg:"bg-[#FEF2F2]",icon:Ee,color:"text-[#B91C1C]"}},x=f[u]||f.pending,I=x.icon;return e.jsx("div",{className:`w-12 h-12 rounded-xl flex items-center justify-center ${x.bg}`,children:e.jsx(I,{className:`w-6 h-6 ${x.color} ${x.spin?"animate-spin":""}`})})})(),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#17213A] font-semibold",children:(()=>{if(r!=null&&r.broken&&!a)return e.jsxs("span",{className:"text-[#B91C1C]",children:["Customer record missing",e.jsxs("span",{className:"text-[#94A3B8] font-normal text-xs ml-1",children:["#",t.id.slice(-6).toUpperCase()]})]});const u=(r==null?void 0:r.display_name)||(a==null?void 0:a.company_name)||(a==null?void 0:a.contact_name);if(u){const f=(r==null?void 0:r.contact_name)||(a==null?void 0:a.contact_name);return e.jsxs(e.Fragment,{children:[u,f&&u!==f&&e.jsxs("span",{className:"text-[#64748B] font-normal",children:[" ⢠",f]})]})}return e.jsx("span",{className:"text-[#94A3B8]",children:"â"})})()}),e.jsx(Tt,{customerId:t.customer_id,className:"mt-2"}),t.partner_sale===!0&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.jsx(ge,{className:"border border-orange-300 bg-orange-100 text-orange-800 hover:bg-orange-100",children:"Partner Sale · Fulfilled by Truck Haters"}),(t.partner_approval_status||"pending_review")==="pending_review"?e.jsx(ge,{className:"border border-red-300 bg-red-100 text-red-800 hover:bg-red-100 font-bold uppercase tracking-wide",children:"Partner Order â Approval Required"}):e.jsx(ge,{variant:"outline",className:"border-slate-300 text-slate-600",children:(t.partner_approval_status||"pending_review").replaceAll("_"," ")})]}),e.jsxs("p",{className:"text-[#64748B] text-sm",children:[new Date(t.order_date||t.created_date).toLocaleDateString("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})," CT"]}),(()=>{const u=((a==null?void 0:a.assigned_rep_ids)||[]).map(I=>{var S;return(S=k.find(j=>j.id===I))==null?void 0:S.name}
23).filter(Boolean),f=[a==null?void 0:a.sales_rep_1_name,a==null?void 0:a.sales_rep_2_name].filter(Boolean),x=[...new Set([...u,...f])];return x.length>0?e.jsxs("p",{className:"text-[#2563EB] text-xs mt-0.5",children:["Rep: ",x.join(", ")]}):null})()]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-[#17213A] font-bold text-lg",children:["$",(m=t.final_amount??t.total_amount)==null?void 0:m.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("p",{className:"text-[#64748B] text-sm",children:[((g=t.items)==null?void 0:g.reduce((u,f)=>u+f.quantity,0))||0," tire(s)"]})]}),Ps(t.status,t.id),n?e.jsx(ca,{className:"w-5 h-5 text-[#64748B]"}):e.jsx(et,{className:"w-5 h-5 text-[#64748B]"})]})]}),n&&e.jsx(_a,{order:t,customer:a,ctx:Dt})]},t.id)}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3 pt-2",children:[e.jsx("p",{className:"text-sm text-[#64748B]",children:ee!=null?e.jsxs(e.Fragment,{children:["Showing ",e.jsxs("span",{className:"font-semibold text-[#17213A]",children:[ze+1,"â",Rs]})," of ",e.jsx("span",{className:"font-semibold text-[#17213A]",children:ee.toLocaleString()})]}):e.jsxs(e.Fragment,{children:["Showing ",e.jsxs("span",{className:"font-semibold text-[#17213A]",children:[ze+1,"â",Rs]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(y,{size:"sm",variant:"outline",disabled:Oe<=1||U,onClick:()=>Ss(Oe-1),className:"bg-white border-[#E5E7EB] text-[#17213A] hover:bg-[#F9FAFB]",children:[e.jsx(oa,{className:"w-4 h-4 mr-1"})," Prev"]}),e.jsxs("span",{className:"text-sm text-[#64748B] px-2",children:["Page ",Oe]}),e.jsxs(y,{size:"sm",variant:"outline",disabled:!H||U,onClick:()=>Ss(Oe+1),className:"bg-white border-[#E5E7EB] text-[#17213A] hover:bg-[#F9FAFB]",children:["Next ",e.jsx(da,{className:"w-4 h-4 ml-1"})]})]})]})]})]}),_s&&e.jsx(as.Suspense,{fallback:null,children:e.jsx(va,{open:_s,onOpenChange:vs,order:it,customer:lt})}),Ns&&e.jsx(as.Suspense,{fallback:null,children:e.jsx(Na,{open:Ns,onOpenChange:ys,customers:F,salesReps:k,onOrderCreated:ie})}),ws&&e.jsx(as.Suspense,{fallback:null,children:e.jsx(ya,{open:ws,onOpenChange:Cs,order:mt,customer:pt,senderName:(l==null?void 0:l.full_name)||"Admin",senderEmail:l==null?void 0:l.email,onSuccess:ie})}),e.jsx(Mt,{open:ke,onOpenChange:Ze,children:e.jsxs(qt,{className:"bg-white border-[#E5E7EB] sm:max-w-lg max-h-[80vh]",children:[e.jsx(It,{children:e.jsx(zt,{className:"text-[#17213A]",children:"Add Tire to Order"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#64748B]"}),e.jsx(Qe,{placeholder:"Search tires...",value:Je,onChange:t=>bs(t.target.value),className:"pl-10 bg-white border-[#E5E7EB] text-[#17213A]"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto space-y-2",children:[$s.map(t=>{var a;return e.jsxs("div",{onClick:()=>kt(t),className:"flex items-center justify-between bg-[#F9FAFB] rounded-lg p-3 cursor-pointer hover:bg-[#E5E7EB] transition-colors border border-[#E5E7EB]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[t.tire_image_url||(a=t.image_urls)!=null&&a[0]?e.jsx("img",{src:t.tire_image_url||t.image_urls[0],alt:t.brand,className:"w-10 h-10 rounded object-contain bg-white"}):e.jsx("div",{className:"w-10 h-10 bg-white rounded flex items-center justify-center",children:e.jsx(hs,{className:"w-5 h-5 text-[#94A3B8]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[#17213A] font-medium",children:t.brand}),e.jsxs("p",{className:"text-[#64748B] text-sm",children:[t.size," · ",t.position]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-[#17213A] font-bold",children:["$",t.price_1_29!=null?t.price_1_29.toLocaleString("en-US",{minimumFractionDigits:2}):"â"]}),e.jsxs(y,{size:"sm",className:"mt-1 bg-[#2563EB] hover:bg-[#1D4ED8] text-white h-7 px-2 text-xs",children:[e.jsx(Ge,{className:"w-3 h-3 mr-1"})," Add"]})]})]},t.id)}),$s.length===0&&e.jsx("p",{className:"text-center text-[#94A3B8] py-8",children:"No tires found"})]})]})]})})]})}export{Bi 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.