PageSourceSearch

https://willowcommerce.com/assets/index-Dni71UEt.js

js willowcommerce.com collected 2026-10-04 03:02:58 UTC 67,329 bytes, 17 lines download raw bytes

1import{C as Wr,E as Hr,c as Gr,b as Jr,a as Xr,P as Yr,u as Zr}from"./CreatePickListDialog-7L-_bFkN.js";import{u as at,a as rt,b as nt,c as vs}from"./PickingInterface-ByhE72au.js";import{P as sn}from"./PickingInterface-ByhE72au.js";import{r as d,w as R,v as O,j as e,C as Z,f as ee,T as ps,I as Ie,B as k,aI as Se,d as Ne,y as we,bp as Me,aR as _e,D as T,a8 as hs,eS as Be,cc as Re,bw as it,bX as fs,eT as ks,eU as Cs,S as Ps,o as Ss,p as Ls,q as Is,s as Ue,z as Ve,l as gs,m as xe,ba as bs,R as Ts,aD as lt,bE as js,aG as ct,aq as ot,ar as dt,ae as mt,af as ut,ag as xt,ah as pt,ai as ht,bU as ft,aj as gt,ak as bt,cd as Ns,dU as jt,eV as Nt,en as wt,dm as _t,eW as yt,bL as vt,cB as kt,K as $e,aH as Ct,bx as Pt,a0 as St,a1 as Lt,a2 as qe,a3 as ue,a5 as It,a6 as ce,a4 as Tt,dR as Et,am as zt,aB as At}from"./index-Cz3wH2jj.js";import{a as Dt,u as Es}from"./usePickLists-CfJ4AKJR.js";import{u as zs}from"./useSalesOrders-Jg6bgaxQ.js";import{u as Ft}from"./SelectPackStationDialog-DJUQxqEF.js";import{u as Ot}from"./ShippingCarriersView-DLR6eDdo.js";import{u as Rt}from"./usePrinterDevices-BzkfKTkP.js";import{u as $t,O as ws}from"./OrderDetailDialog--k9M7GEC.js";import{S as Te}from"./scan-DJ52Z638.js";import{P as Pe}from"./printer-CMZ783hw.js";import{O as an}from"./OrderSelectionGrid-DPxEPmpf.js";import{S as qt}from"./square-x-NhfeYh_2.js";import{S as Mt}from"./square-check-big-BRvy1nZm.js";import{P as Bt}from"./package-open-B7JO9_-j.js";import{M as nn,S as ln}from"./useShippingOrders-DshL_rWf.js";import"./BarcodeSvg-BokD2q02.js";import"./timer-DoPzwd2X.js";import"./user-check-DIP-Z2h3.js";import"./skip-forward-CvKPYZ1g.js";import"./locationSort-DavtV_P2.js";import"./useWarehouseCarts-Co5aERME.js";import"./toggle-group-CCPJ4Vsa.js";import"./HandheldShell-h4f5kEQ_.js";import"./smartphone-ZokIx9nP.js";import"./monitor-C3TPbcQD.js";import"./useWarehouseBins-C0UVL6CT.js";import"./scroll-text-P8JOHlHU.js";import"./scale-DYM2IbwO.js";import"./package-2-C66bd1JW.js";import"./check-check-lanwAFox.js";import"./createFbaPlanFromTransfer-F_OuCq0f.js";import"./units-DnVDdWlp.js";import"./zod-Cz-O99-5.js";import"./form-DuGnUKh8.js";import"./types-rAbasHIg.js";import"./standard-dialog-CyKzQ0vA.js";import"./ban-DddfeW4t.js";import"./ellipsis-vertical-DpBCmT7s.js";import"./usePickPackExceptions-BTcd2rQD.js";import"./PickerAdjustmentQueue-B6PJror1.js";import"./usePickerAdjustments-BDprTThb.js";import"./clipboard-check-nJBaPlTL.js";import"./usePickPackPerformance-CSKBOovR.js";import"./route-PHGICptc.js";import"./scan-barcode-C48k92QE.js";import"./list-checks-CI0k8m0X.js";import"./trophy-CcVUta1S.js";import"./crown-CwahpLCJ.js";import"./useDashboardLayout-N7nF7S1S.js";import"./settings-2-CWk8A5Nm.js";import"./useTeamMembers-B0EeVyqg.js";import"./ChangeLocationPopover-D5_1DAUv.js";import"./useAddProductIdentifier-BFeY6oP5.js";import"./syncWosInventoryForProducts-Uuz_xdK3.js";import"./minus-sHCjS052.js";import"./calculator-BmChq74A.js";import"./undo-2-D-ew8PdV.js";import"./serpentinePickSort-Bj6BBqfN.js";import"./pickLocationSelection-D3QgN-ka.js";import"./arrow-left-YuNqz00t.js";import"./ManufactureFromOrderDialog-DUJlQqNZ.js";import"./wrench-Cq7hJgmc.js";import"./useGridPreferences-Bzna3nEl.js";import"./ColumnCustomizer-BBSYFSof.js";import"./columns-2-C1OwegFq.js";import"./parallelBatch-DaCMqYNu.js";import"./useCancelOrderWithVoid-CoofJwey.js";import"./SalesOrderImportDialog-CAMUtHOY.js";import"./index-Bf7LSJqy.js";import"./index-D6Gg4-sY.js";import"./useGoogleSheetsOAuth-DIO-5dUW.js";import"./xlsx-B6sNpj_1.js";import"./link-BwidNLVR.js";import"./address-autocomplete-CrYfZ21V.js";import"./useCustomers-B7PEwYCJ.js";import"./useDefaultWarehouse-CLwXdvWq.js";import"./subWeeks-DIE1pl_Y.js";import"./formatDimension-DQRwnMZd.js";import"./sticky-note-5NkDhdLq.js";import"./house-Dc3aD1ke.js";import"./veeqo-small-CuXdeh8b.js";import"./fetchShippingRates-DwMRCeqx.js";import"./useShippingCarriers-DDgsHdLb.js";import"./star-RwLsruqg.js";import"./exportTable-D7D6sNPu.js";import"./FieldMappingSelector-yU5L_Jo4.js";import"./star-off-BLAmh9jr.js";import"./WeightDimsImportDialog-CvB9fVdi.js";import"./file-down-lZMwNUu4.js";import"./useFinancialVisibility-pKV39oLM.js";import"./financialFieldPermissions-B9OwEMtD.js";import"./useScopedWarehouses-BsHWwzre.js";import"./folder-plus-COv7fIVj.js";import"./circle-dot-DFmqtCFM.js";import"./folder-open-BkpTQP0w.js";import"./archive-ReyHp6qZ.js";import"./useProductionStatusCounts-DCagBQZi.js";import"./useWebUsbPrinter-Cf00O3UL.js";import"./file-warning-DpIGqlCl.js";import"./packingSlipPdf-Da1JcnRO.js";import"./TagManagementPopover-7E7nMnDm.js";import"./circle-play-Cf0X6d5o.js";import"./ruler-Ej9R4Eze.js";import"./useSalesOrderItems-DgfDPot3.js";import"./phone-L9YC2jcI.js";
1function Ut(w){const[f,L]=d.useState(new Set),[c,x]=d.useState(!1),v=[...w].sort().join("|");return d.useEffect(()=>{if(w.length===0){L(new Set);return}let A=!1;x(!0),(async()=>{const[{data:E},{data:N}]=await Promise.all([R.from("pick_pack_label_jobs").select("sales_order_id, printed_at").in("sales_order_id",w).not("printed_at","is",null),R.from("sales_orders").select("id, status").in("id",w)]);if(A)return;const g=new Set;(E||[]).forEach(b=>{b.sales_order_id&&g.add(b.sales_order_id)}),(N||[]).forEach(b=>{(b.status==="shipped"||b.status==="delivered")&&g.add(b.id)}),L(g),x(!1)})();const V=R.channel(`printed-orders-${v.slice(0,32)}`).on("postgres_changes",{event:"*",schema:"public",table:"pick_pack_label_jobs"},E=>{var g,b;const N=((g=E.new)==null?void 0:g.sales_order_id)||((b=E.old)==null?void 0:b.sales_order_id);N&&w.includes(N)&&queueMicrotask(()=>{A||R.from("pick_pack_label_jobs").select("printed_at").eq("sales_order_id",N).not("printed_at","is",null).limit(1).maybeSingle().then(({data:y})=>{A||L(B=>{const D=new Set(B);return y!=null&&y.printed_at?D.add(N):D.delete(N),D})})})}).subscribe();return()=>{A=!0,R.removeChannel(V)}},[v]),{printedIds:f,loading:c}}const Qe="pack_station_printer_setup";function Vt(){try{const w=sessionStorage.getItem(Qe);return w?JSON.parse(w):null}catch{return null}}async function _s(w){try{const v=await fetch(w,{mode:"cors"});if(v.ok)return await v.blob();console.warn(`[useBrowserPrinter] direct fetch failed (${v.status}), falling back to proxy`)}catch(v){console.warn("[useBrowserPrinter] direct fetch threw, falling back to proxy",v)}const{data:{session:f}}=await R.auth.getSession(),L="https://yzjxiqztjpijxnpzxpav.supabase.co",c="sb_publishable_sgchamm9hLEN6RdMRu2pyg_iz5OOJ1S",x=await fetch(`${L}/functions/v1/label-proxy`,{method:"POST",headers:{"Content-Type":"application/json",apikey:c,Authorization:`Bearer ${(f==null?void 0:f.access_token)||c}`},body:JSON.stringify({url:w})});if(!x.ok){const v=await x.text().catch(()=>"");throw new Error(`Label proxy error (${x.status}): ${v}`)}return await x.blob()}function Qt(){const[w,f]=d.useState(Vt),L=d.useRef(null);d.useEffect(()=>{let N=document.getElementById("__pack_print_frame");N||(N=document.createElement("iframe"),N.id="__pack_print_frame",N.style.cssText="position:fixed;width:0;height:0;border:none;left:-9999px;top:-9999px;",document.body.appendChild(N)),L.current=N},[]);const c=d.useCallback(N=>{const g={isSetup:!0,printerName:N,setupAt:new Date().toISOString()};sessionStorage.setItem(Qe,JSON.stringify(g)),f(g)},[]),x=d.useCallback(()=>{sessionStorage.removeItem(Qe),f(null)},[]),v=d.useCallback(async N=>new Promise(g=>{const b=document.createElement("iframe");b.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;border:none;";const y=URL.createObjectURL(N);let B=!1;const D=I=>{B||(B=!0,setTimeout(()=>{try{b.remove()}catch{}try{URL.revokeObjectURL(y)}catch{}},6e4),g(I))};b.onload=()=>{setTimeout(()=>{var I,$;try{(I=b.contentWindow)==null||I.focus(),($=b.contentWindow)==null||$.print(),D(!0)}catch(oe){console.warn("[useBrowserPrinter] print failed",oe),D(!1)}},500)},b.onerror=()=>D(!1),b.src=y,document.body.appendChild(b),setTimeout(()=>D(!1),3e4)}),[]),A=d.useCallback(async N=>{try{const g=await _s(N);return await v(g)}catch(g){return console.error("[useBrowserPrinter] printPdfFromUrl error",(g==null?void 0:g.message)||g),!1}},[v]),V=d.useCallback(async N=>{var B;if(N.pdfUrl)return await A(N.pdfUrl);const g=L.current;if(!g||!N.html)return!1;const b=g.contentDocument||((B=g.contentWindow)==null?void 0:B.document);if(!b)return!1;const y=N.paperSize==="4x6"?"@page { size: 4in 6in; margin: 0; }":"@page { size: letter; margin: 0.5in; }";return b.open(),b.write(`<!DOCTYPE html><html><head><style>${y}</style></head><body>${N.html}</body></html>`),b.close(),new Promise(D=>{setTimeout(()=>{var I;try{(I=g.contentWindow)==null||I.print(),D(!0)}catch{D(!1)}},300)})},[A]),E=d.useCallback(()=>{var b;const N=L.current;if(!N)return;const g=N.contentDocument||((b=N.contentWindow)==null?void 0:b.document);g&&(g.open(),g.write(`<!DOCTYPE html><html><head><style>
2      @page { size: 4in 6in; margin: 0.25in; }
3      body { font-family: system-ui, sans-serif; padding: 0.25in; }
4      h1 { font-size: 18px; margin-bottom: 8px; }
5      p { font-size: 12px; color: #666; margin: 4px 0; }
6      .box { border: 2px dashed #ccc; padding: 12px; margin-top: 12px; text-align: center; }
7      .check { font-size: 32px; color: #22c55e; }
8    </style></head><body>
9      <h1>🖨️ Printer Test Page</h1>
10      <p>Pack Station - Printer Setup</p>
11      <p>
11${new Date().toLocaleString()}</p>
12      <div class="box">
13        <div class="check">✓</div>
14        <p><strong>If you can read this, your printer is set up correctly.</strong></p>
15        <p>Tip: launch Chrome with <code>--kiosk-printing</code> for fully silent printing.</p>
16      </div>
17    </body></html>`),g.close(),setTimeout(()=>{var y;try{(y=N.contentWindow)==null||y.print()}catch{}},300))},[]);return{isSetup:(w==null?void 0:w.isSetup)||!1,printerName:(w==null?void 0:w.printerName)||"",markSetup:c,resetSetup:x,openTestPrint:E,printContent:V,printPdfFromUrl:A,fetchLabelBlob:_s}}function Br({orderId:w,pickListId:f,onComplete:L,selectedStation:c}){var ls,cs,os,ds,ms,us;const[x,v]=d.useState(w),[A,V]=d.useState(""),[E,N]=d.useState(!0),[g,b]=d.useState(!1),[y,B]=d.useState(null),[D,I]=d.useState(null),[$,oe]=d.useState(!0),[H,ye]=d.useState("free"),[z,G]=d.useState(new Map),[p,_]=d.useState([]),[P,q]=d.useState(""),[h,F]=d.useState(null),[U,J]=d.useState(null),re=d.useRef(null),fe=d.useRef(null),{orders:Q,updateOrderStatus:ge}=Dt(f),{salesOrders:o}=zs(),{pickLists:C}=Es(),{packStations:X,updatePackStation:K}=Ft(),{data:ve}=$t(),pe=d.useMemo(()=>{if(!ve||!o)return[];const s=new Set,t=[];for(const a of ve){if(!a.voided_at||!a.sales_order_id||s.has(a.sales_order_id))continue;const r=o.find(i=>i.id===a.sales_order_id);r&&(r.status==="shipped"||r.status==="delivered"||r.status==="cancelled"||(s.add(a.sales_order_id),t.push({order:r,voidedAt:a.voided_at})))}return t.sort((a,r)=>new Date(r.voidedAt).getTime()-new Date(a.voidedAt).getTime()).slice(0,25).map(a=>a.order)},[ve,o]),{createLabelsForOrders:Ke,isProcessing:Kt}=Ot(),{isSetup:ke,printerName:As,markSetup:Ds,resetSetup:Fs,openTestPrint:We,printContent:Os,printPdfFromUrl:He,fetchLabelBlob:Rs}=Qt(),{devices:Ee}=Rt(),{data:Y=[]}=at(f),$s=rt(),qs=nt(),se=(c==null?void 0:c.auto_print_label)||!1,ne=(c==null?void 0:c.auto_print_packing_slip)||!1,Ge=(c==null?void 0:c.require_pack_scan_before_print)||!1,Je=(c==null?void 0:c.printer_device_id)||null,ze=(c==null?void 0:c.printer_id)||null,Xe=(c==null?void 0:c.slip_printer_id)||ze,Ye=(c==null?void 0:c.label_page_size)||"4x6",Ze=(c==null?void 0:c.slip_page_size)||"letter",te=Je?Ee==null?void 0:Ee.find(s=>s.id===Je):null,ie=!!(te!=null&&te.is_online),he=ie||ke,Ms=s=>{var t,a;return s?((a=(t=te==null?void 0:te.printers)==null?void 0:t.find(r=>r.id===s))==null?void 0:a.printer_name)??null:null},es=d.useCallback(async({url:s,source:t,printerName:a,deviceId:r,pageSize:i})=>{const{data:{session:m}}=await R.auth.getSession();if(!m)throw new Error("Not authenticated");const l=s.split("?")[0].toLowerCase(),u=l.endsWith(".zpl")?"zpl":l.endsWith(".png")?"png":l.endsWith(".gif")?"gif":l.endsWith(".jpg")||l.endsWith(".jpeg")?"jpg":"pdf",{error:n}=await R.functions.invoke("zpl-print-queue/enqueue",{body:{zpl_contents:[""],source:t,device_id:r||void 0,printer_name:a||void 0,copies:1,metadata:{document_url:s,format:u,document_format:u,page_size:i}},headers:{Authorization:`Bearer ${m.access_token}`}});if(n)throw n},[]),de=d.useCallback(async(s,t="label",a)=>{if(console.log("[PIPELINE:print] start",{kind:t,orderId:a,url:s,hasStation:!!c,stationId:c==null?void 0:c.id,useNativePrinter:ie,linkedDeviceOnline:te==null?void 0:te.is_online}),ie&&te){const r=t==="packing_slip"?Xe:ze,i=t==="packing_slip"?Ze:Ye;try{return await es({url:s,source:t==="packing_slip"?"pack-station-packing-slip":"pack-station-label",deviceId:te.id,printerName:Ms(r),pageSize:i}),console.info("[PIPELINE:print] queued for Printer Connect agent",{kind:t,printerId:r}),!0}catch(m){console.warn("[PIPELINE:print] native print queue failed, falling back to browser",(m==null?void 0:m.message)||m)}}return console.info("[PIPELINE:print] using browser fallback (will show OS dialog)",{kind:t}),await He(s)},[c,ie,te,ze,Xe,Ye,Ze,es,He]),Bs=!!ie,ss=d.useRef(new Set);d.useEffect(()=>{if(console.log("[PIPELINE:auto-print] effect tick",{jobs:(Y==null?void 0:Y.length)||0,stationAutoPrintLabel:se,stationAutoPrintSlip:ne,isPrinterReady:he,useNativePrinter:ie,hasSelectedStation:!!c,stationId:c==null?void 0:c.id,jobs_summary:(Y||[]).map(s=>{var t;return{id:s.id.slice(0,8),order:(t=s.sales_order_id)==null?void 0:t.slice(0,8),status:s.status,has_label:!!s.label_url}})}),!se||!he){Y!=null&&Y.some(s=>s.status==="label_created"&&s.label_url)&&console.warn("[PIPELINE:auto-print] SKIP — gating off",{stationAutoPrintLabel:se,isPrinterReady:he,reason:se?"no printer ready":"station auto_print_label=false"});return}if(!(!Y||Y.length===0))for(const s of Y){if(ss.current.has(s.id)||!s.label_url||s.status!=="label_created")continue;const t=s.pack_station_id||null;if(c!=null&&c.id&&t&&t!==c.id){console.info("[PIPELINE:auto-print] SKIP — job belongs to a different pack station",{jobId:s.id,jobStationId:t,activeStationId:c.id});continue}if(Ge&&s.pack_status!=="packed"){console.info("[PIPELINE:auto-print] HOLDING — waiting for pack-scan verification",{jobId:s.id,orderId:s.sales_order_id,pack_status:s.pack_status});continue}ss.current.add(s.id),console.info("[PIPELINE:auto-print] dispatching label to printer",{jobId:s.id,orderId:s.sales_order_id,url:s.label_url}),_(a=>a.find(r=>r.orderId===s.sales_order_id)?a:[...a,{orderId:s.sales_order_id,orderNumber:s.sales_order_id.slice(0,8),labelUrl:s.label_url||void 0}]),de(s.label_url,"label",s.sales_order_id).then(a=>console.log("[PIPELINE:auto-print] dispatch result",{jobId:s.id,ok:a})).catch(a=>console.warn("[PIPELINE:auto-print] dispatch failed",a)),s.packing_slip_url&&ne&&de(s.packing_slip_url,"packing_slip",s.sales_order_id).catch(()=>{})}},[Y,se,ne,Ge,he,de,ie,c]);const Us=f&&Q?Q.map(s=>o==null?void 0:o.find(a=>
17a.id===s.sales_order_id)).filter(Boolean):(o==null?void 0:o.filter(s=>s.status==="awaiting_shipment"))||[],[Vs,Le]=d.useState([]),ts=(()=>{if(!h)return f?Us:[];if(h.type==="order"){const s=(o||[]).find(t=>(t.order_number||"").toLowerCase()===h.orderNumber.toLowerCase());return s?[s]:[]}return Vs})(),{printedIds:me}=Ut(ts.map(s=>s.id)),W=ts.filter(s=>!me.has(s.id));d.useEffect(()=>{if(!h||h.type!=="cart"){Le([]);return}let s=!1;return(async()=>{const{data:t,error:a}=await R.from("pick_list_items").select("sales_order_id").in("pick_list_id",h.pickListIds);if(s||a||!(t!=null&&t.length)){!s&&a&&O.error("Failed to load cart orders"),Le([]);return}const r=Array.from(new Set(t.map(n=>n.sales_order_id).filter(Boolean))),i=n=>({...n,items:((n==null?void 0:n.items)||[]).filter(j=>!(j!=null&&j.is_backorder_line))}),m=n=>{var j;return(((j=n==null?void 0:n.items)==null?void 0:j.length)??0)>0&&(n==null?void 0:n.status)!=="on_hold"},l=(o||[]).filter(n=>r.includes(n.id)).map(i).filter(m),u=r.filter(n=>!l.find(j=>j.id===n));if(u.length){const{data:n}=await R.from("sales_orders").select("*, items:sales_order_items(*, product:products(sku, upc, gtin, barcode))").in("id",u);if(!s){const j=[...l,...(n||[]).map(i).filter(m)];Le(j),j.forEach(S=>Fe(S.id,S.order_number||S.id.slice(0,8)))}}else s||(Le(l),l.forEach(n=>Fe(n.id,n.order_number||n.id.slice(0,8))))})(),()=>{s=!0}},[h,o]);const Qs=d.useCallback(async s=>{const t=s.trim();if(!t)return;const a=(X||[]).find(l=>l.barcode&&l.barcode.toLowerCase()===t.toLowerCase()||l.station_code&&l.station_code.toLowerCase()===t.toLowerCase());if(a&&(!c||c.id!==a.id)){O.success(`Station ${a.station_name} scanned. Select it from the cards above.`),q("");return}const r=new Set(["draft","ready","in_progress","completed"]);let i=(C||[]).filter(l=>l.cart_code&&l.cart_code.toLowerCase()===t.toLowerCase()&&r.has((l.status||"").toLowerCase()));if(!i.length){const{data:l}=await R.from("warehouse_carts").select("id, barcode, name").or(`barcode.ilike.${t},name.ilike.${t}`).limit(5),u=(l||[]).map(n=>n.id);if(u.length&&(i=(C||[]).filter(n=>n.cart_id&&u.includes(n.cart_id)&&r.has((n.status||"").toLowerCase())),!i.length)){const{data:n}=await R.from("pick_list_carts").select("pick_list_id").in("cart_uuid",u),j=new Set((n||[]).map(S=>S.pick_list_id));j.size&&(i=(C||[]).filter(S=>j.has(S.id)&&r.has((S.status||"").toLowerCase())))}}if(i.length||(i=(C||[]).filter(l=>(l.pick_list_number||"").toLowerCase()===t.toLowerCase()&&r.has((l.status||"").toLowerCase()))),!i.length){const l=Array.from(r),{data:u}=await R.from("pick_lists").select("id, pick_list_number, status, cart_code, cart_id, created_at").ilike("cart_code",t).in("status",l).order("created_at",{ascending:!1}).limit(5);let n=u||[];if(!n.length){const{data:j}=await R.from("warehouse_carts").select("id").or(`barcode.ilike.${t},name.ilike.${t}`).limit(5),S=(j||[]).map(je=>je.id);if(S.length){const{data:je}=await R.from("pick_lists").select("id, pick_list_number, status, cart_code, cart_id, created_at").in("cart_id",S).in("status",l).order("created_at",{ascending:!1}).limit(5);n=je||[]}}if(!n.length){const{data:j}=await R.from("pick_lists").select("id, pick_list_number, status, cart_code, cart_id, created_at").ilike("pick_list_number",t).in("status",l).limit(5);n=j||[]}n.length&&(i=n)}if(f){const l=i.filter(u=>u.id===f);l.length&&(i=l)}if(i.length>1&&(i=[...i].sort((l,u)=>{const n=new Date(l.created_at||0).getTime();return new Date(u.created_at||0).getTime()-n}).slice(0,1)),i.length){F({type:"cart",cartId:i[0].cart_id||"",cartCode:t,pickListIds:i.map(l=>l.id)}),q(""),O.success(`Cart ${t}: ${i[0].pick_list_number||"pick list"} loaded`);return}const m=(o||[]).find(l=>(l.order_number||"").toLowerCase()===t.toLowerCase());if(m){F({type:"order",orderNumber:m.order_number||t}),q(""),v(m.id),O.success(`Order ${m.order_number} loaded`),setTimeout(()=>Fe(m.id,m.order_number||t),50);return}O.error(`No cart or order found for "${t}"`)},[C,o,X,c,f]),as=()=>{F(null),Le([]),v(null),G(new Map),setTimeout(()=>{var s;return(s=fe.current)==null?void 0:s.focus()},50)};d.useEffect(()=>{const s=new Map;for(const t of W){const a=z.get(t.id);a?s.set(t.id,a):s.set(t.id,{orderId:t.id,orderNumber:t.order_number||t.id.slice(0,8),items:(t.items||[]).map(r=>{var i,m,l,u,n;
17return{id:r.id,product_id:r.product_id||((i=r.product)==null?void 0:i.id)||null,product_name:r.product_name,product_sku:r.product_sku||((m=r.product)==null?void 0:m.sku),product_upc:((l=r.product)==null?void 0:l.upc)||((u=r.product)==null?void 0:u.gtin)||((n=r.product)==null?void 0:n.barcode),quantity:r.quantity,verified:!1,quantity_verified:0}}),allVerified:!1,labelCreating:!1,labelCreated:!1})}G(s)},[W.length]);const M=x?z.get(x):null,le=x?W.find(s=>s.id===x):null,ae=(M==null?void 0:M.items)||[];ae.length>0&&ae.every(s=>s.verified);const Ks=ae.length?ae.filter(s=>s.verified).length/ae.length*100:0;d.useEffect(()=>{re.current&&re.current.focus()},[x,y]),d.useEffect(()=>{if(y&&y!=="label_creating"){const s=setTimeout(()=>B(null),1500);return()=>clearTimeout(s)}},[y]);const be=d.useCallback(s=>{if($)try{const t=new AudioContext,a=t.createOscillator(),r=t.createGain();a.connect(r),r.connect(t.destination),a.frequency.value=s==="success"?800:300,r.gain.value=.1,a.start(),a.stop(t.currentTime+(s==="success"?.15:.3))}catch{}},[$]),Ae=async(s,t=12e3,a=800)=>{const r=Date.now(),i=r+t;let m=0;for(console.info("[FastPack][LabelPoll] start",{orderId:s,timeoutMs:t,intervalMs:a});Date.now()<=i;){m+=1;const{data:l,error:u}=await R.from("carrier_shipments").select("label_s3_url, tracking_number, created_at").eq("sales_order_id",s).not("label_s3_url","is",null).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(u&&console.warn("[FastPack][LabelPoll] query error",{orderId:s,attempt:m,error:u.message}),l!=null&&l.label_s3_url)return console.info("[FastPack][LabelPoll] HIT",{orderId:s,attempts:m,elapsedMs:Date.now()-r,tracking:l.tracking_number}),{url:l.label_s3_url,tracking:l.tracking_number||void 0};if(t===0)break;await new Promise(n=>setTimeout(n,a))}return console.info("[FastPack][LabelPoll] MISS",{orderId:s,attempts:m,elapsedMs:Date.now()-r}),null},De=async(s,t)=>{try{const a=await Rs(s),r=URL.createObjectURL(a),i=document.createElement("a");i.href=r,i.download=`label-${t}.pdf`,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>URL.revokeObjectURL(r),6e4)}catch(a){console.warn("[PackStation] Download failed",(a==null?void 0:a.message)||a),O.error("Could not download label — try Print instead.")}},Ws=d.useCallback(async(s,t)=>{if(!t){console.info("[FastPack][TrackingPush] skip — no tracking number",{orderId:s});return}const a=Date.now();console.info("[FastPack][TrackingPush] start",{orderId:s,tracking:t});try{const{data:r,error:i}=await R.functions.invoke("marketplace-tracking-push",{body:{salesOrderId:s,trackingNumber:t}});i?console.warn("[FastPack][TrackingPush] error response",{orderId:s,error:i.message,elapsedMs:Date.now()-a}):console.info("[FastPack][TrackingPush] OK",{orderId:s,elapsedMs:Date.now()-a,response:r})}catch(r){console.warn("[FastPack][TrackingPush] FAILED (will retry via sync queue)",{orderId:s,error:(r==null?void 0:r.message)||r})}},[]),Fe=d.useCallback(async(s,t)=>{var r;const a=Date.now();console.info("[FastPack][PrePrint] check",{orderId:s,orderNumber:t,autoPrintLabel:se,autoPrintSlip:ne,printerSetup:ke});try{const i=await Ae(s,0,0);if(!(i!=null&&i.url))return console.info("[FastPack][PrePrint] no pre-existing label",{orderId:s,orderNumber:t,elapsedMs:Date.now()-a}),!1;if(console.info("[FastPack][PrePrint] FOUND label",{orderId:s,orderNumber:t,url:i.url,tracking:i.tracking,elapsedMs:Date.now()-a}),G(m=>{const l=new Map(m),u=l.get(s);return u&&!u.labelCreated&&l.set(s,{...u,labelCreated:!0,labelError:void 0}),l}),_(m=>m.find(l=>l.orderId===s)?m:[...m,{orderId:s,orderNumber:t,tracking:i.tracking,labelUrl:i.url}]),se&&he){if(console.info("[FastPack][PrePrint] sending label to printer",{orderId:s,orderNumber:t,native:ie}),await de(i.url,"label"),ne)try{const m=await R.auth.getSession(),l=await fetch("https://yzjxiqztjpijxnpzxpav.supabase.co/functions/v1/get-shipment-document-urls",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(r=m.data.session)==null?void 0:r.access_token}`},body:JSON.stringify({salesOrderId:s,documentTypes:["packing_slip"]})});if(l.ok){const u=await l.json();u!=null&&u.packing_slip_url&&(console.info("[FastPack][PrePrint] sending packing slip to printer",{orderId:s}),await de(u.packing_slip_url,"packing_slip"))}}catch(m){console.warn("[FastPack][PrePrint] packing slip error:",(m==null?void 0:m.message)||m)}O.success(`🖨️ Pre-printed label for ${t}`,{duration:2e3})}return!0}catch(i){return console.warn("[FastPack][PrePrint] ERROR",{orderId:s,error:(i==null?void 0:i.message)||String(i)}),!1}},[se,ne,he,ie,de]),Ce=d.useCallback(async s=>{var a;const t=W.find(r=>r.id===s);if(t){G(r=>{const i=new Map(r),m=i.get(s);return m&&i.set(s,{...m,labelCreating:!0,labelError:void 0}),i}),B("label_creating");try{const r=await Ae(s,0,0);let i=r==null?void 0:r.url,m=r==null?void 0:r.tracking;if(i)O.success(`Label already exists for ${t.order_number}`,{duration:2e3});else{const u=t,n=[];if(!t.carrier&&!u.service_code&&u.rate_status!=="success"&&n.push("carrier/service"),!u.weight_oz&&!u.package_weight_oz&&((t.items||[]).reduce((je,Oe)=>{var xs;const tt=Oe.weight_oz||((xs=Oe.product)==null?void 0:xs.weight_oz)||0;return je+tt*(Oe.quantity||1)},0)||n.push("weight")),n.length>0)throw new Error(`Missing ${n.join(", ")} — open order to fix`);
17if(O.info(`Creating label for ${t.order_number}...`),f){const S=Q==null?void 0:Q.find(je=>je.sales_order_id===s);S&&ge.mutate({orderId:S.id,status:"packed",label_created:!0})}await Ke([t]);const j=await Ae(s);if(!(j!=null&&j.url))throw new Error("Label was not generated — check carrier credentials and try again");i=j.url,m=j.tracking}if(G(u=>{const n=new Map(u),j=n.get(s);return j&&n.set(s,{...j,labelCreating:!1,labelCreated:!0,labelError:void 0}),n}),_(u=>[...u,{orderId:s,orderNumber:t.order_number||s.slice(0,8),tracking:m,labelUrl:i}]),m&&Ws(s,m),O.success(`Label created for ${t.order_number}!`,{duration:3e3}),be("success"),B("complete"),se&&he?(O.info(ie?"Sending label to printer…":"Auto-printing label..."),await de(i,"label")):await De(i,t.order_number||s.slice(0,8)),ne&&he)try{const u=await fetch("https://yzjxiqztjpijxnpzxpav.supabase.co/functions/v1/get-shipment-document-urls",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(a=(await R.auth.getSession()).data.session)==null?void 0:a.access_token}`},body:JSON.stringify({salesOrderId:s,documentTypes:["packing_slip"]})});if(u.ok){const n=await u.json();n!=null&&n.packing_slip_url&&await de(n.packing_slip_url,"packing_slip")}}catch(u){console.warn("Auto-print packing slip failed:",u)}const l=W.find(u=>{if(u.id===s)return!1;const n=z.get(u.id);return n&&!n.allVerified&&!n.labelCreated});l&&v(l.id)}catch(r){G(i=>{const m=new Map(i),l=m.get(s);return l&&m.set(s,{...l,labelCreating:!1,labelError:r.message}),m}),O.error(`Label failed for ${t.order_number}: ${r.message}`,{action:{label:"Fix order",onClick:()=>J(s)},duration:8e3}),J(s),be("error"),B("mismatch")}}},[W,Q,f,z,Ke,ge,be,se,ne,ke,Os]),rs=d.useRef(null),Hs=800,ns=d.useCallback(async s=>{if(!s.trim())return;const t=s.trim(),a=t.toLowerCase(),r=Date.now(),i=rs.current;if(i&&i.value===a&&r-i.at<Hs){console.info("[PackStation] duplicate scan ignored",{value:a,deltaMs:r-i.at}),V("");return}let m=null;try{const{data:n,error:j}=await R.rpc("match_product_by_identifier",{_scanned_value:t});if(!j){const S=Array.isArray(n)?n[0]:n;m=(S==null?void 0:S.product_id)??null}}catch(n){console.warn("[PackStation] match_product_by_identifier failed",n)}let l=!1,u=null;if(H==="order"&&x){const n=z.get(x);n&&is(n,a,m)&&(l=!0,u=x)}else{const n=x?[x,...Array.from(z.keys()).filter(j=>j!==x)]:Array.from(z.keys());for(const j of n){const S=z.get(j);if(!(!S||S.labelCreated||S.labelCreating||S.allVerified)&&is(S,a,m)){l=!0,u=j,j!==x&&(v(j),I(j));break}}}l||(B("mismatch"),be("error"),O.error(`No matching item found: ${s}`,{duration:2e3})),rs.current={value:a,at:r,matchedOrderId:u},V("")},[H,x,z,be]),is=(s,t,a)=>{const r=s.items.findIndex(i=>{var u,n;if(i.verified)return!1;if(a&&i.product_id&&i.product_id===a)return!0;const m=((u=i.product_sku)==null?void 0:u.toLowerCase())===t,l=((n=i.product_upc)==null?void 0:n.toLowerCase())===t;return m||l});return r===-1?!1:(G(i=>{const m=new Map(i),l={...m.get(s.orderId)},u=[...l.items],n={...u[r]};n.quantity_verified+=1,n.quantity_verified>=n.quantity&&(n.verified=!0),u[r]=n;const j=u.every(S=>S.verified);return l.items=u,l.allVerified=j,m.set(s.orderId,l),j&&E?setTimeout(()=>Ce(s.orderId),500):j&&b(!0),m}),s.items[r].quantity_verified+1>=s.items[r].quantity?(B("complete"),be("success"),O.success(`✓ ${s.items[r].product_name} verified!`)):(B("success"),be("success"),O.success(`${s.items[r].quantity_verified+1}/${s.items[r].quantity} scanned`,{duration:1500})),!0)};vs(ns);const Gs=s=>{s.key==="Enter"&&A.trim()&&ns(A.trim())},Js=()=>{x&&(G(s=>{const t=new Map(s),a=t.get(x);return a&&t.set(x,{...a,items:a.items.map(r=>({...r,verified:!0,quantity_verified:r.quantity})),allVerified:!0}),t}),E?setTimeout(()=>Ce(x),500):b(!0))},Xs=async()=>{x&&(b(!1),await Ce(x))},Ys=async()=>{if(!x)return;if(f){const t=Q==null?void 0:Q.find(a=>a.sales_order_id===x);t&&ge.mutate({orderId:t.id,status:"packed"})}O.success("Order added to packing queue"),b(!1);const s=W.find(t=>{if(t.id===x)return!1;const a=z.get(t.id);return a&&!a.allVerified&&!a.labelCreated});s?v(s.id):L()},Zs=W.length,et=Array.from(z.values()).filter(s=>s.allVerified).length,st=p.length;return!f&&!h?e.jsx(Z,{className:"border-2 border-dashed",children:e.jsxs(ee,{className:"py-12 md:py-16 text-center max-w-xl mx-auto",children:[e.jsx(ps,{className:"h-10 w-10 md:h-12 md:w-12 text-primary mx-auto"}),e.jsx("h3",{className:"mt-4 text-lg font-semibold",children:"Scan Cart or Order to Begin"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Scan a cart barcode to load all orders assigned to that cart, or scan an order number to pack a single order."}),e.jsxs("div",{className:"mt-6 relative",children:[e.jsx(Te,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(Ie,{ref:fe,autoFocus:!0,value:P,onChange:s=>q(s.target.value),onKeyDown:s=>{s.key==="Enter"&&(s.preventDefault(),Qs(P))},placeholder:"Scan cart barcode or order number...",className:"pl-10 h-14 text-base scanner-input",autoComplete:"off"})]}),e.jsx(k,{variant:"ghost",className:"mt-4 text-xs",onClick:L,children:"Return to Overview"})]})}):W.length===0&&!x?e.jsxs(e.Fragment,{children:[e.jsx(Z,{children:e.jsxs(ee,{className:"py-12 md:py-16 text-center",children:[e.jsx(Se,{className:"h-10 w-10 md:h-12 md:w-12 text-muted-foreground mx-auto"}),e.jsx("h3",{className:"mt-4 text-lg font-semibold",children:"No Orders Found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(h==null?void 0:h.type)==="cart"?`No active orders for cart ${h.cartCode}`:(h==null?void 0:h.type)==="order"?`Order ${h.orderNumber} not found or already shipped`:"Complete picking first or select an order from the shipping queue"}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[h&&e.jsx(k,{variant:"outline",onClick:as,children:"Scan Different Cart/Order"}),e.jsx(k,{onClick:L,children:"Return to Overview"})]})]})}),pe.length>0&&e.jsxs(Z,{className:"mt-4",children:[e.jsxs(Ne,{className:"pb-3",children:[e.jsxs(we,{className:"text-base flex items-center gap-2",children:[e.jsx(Me,{className:"h-4 w-4 text-destructive"}),"Recently Voided Orders (",pe.length,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tap an order to edit it — same details popup as the shipping orders grid."})]}),e.jsx(ee,{className:"p-0",children:e.jsx(_e,{className:"max-h-[420px]",children:e.jsx("div",{className:"divide-y",children:pe.map(s=>e.jsxs("button",{type:"button",onClick:()=>J(s.id),className:"w-full text-left px-4 py-3 hover:bg-muted/50 transition-colors flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:s.order_number||s.id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[s.customer_name||"—",s.source?` · ${s.source}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(T,{variant:"outline",className:"text-xs",children:s.status||"voided"}),e.jsx(hs,{className:"h-4 w-4 text-muted-foreground"})]})]},s.id))})})})]}),(()=>{const s=U&&(pe.find(t=>
17t.id===U)||(o==null?void 0:o.find(t=>t.id===U)))||null;return e.jsx(ws,{order:s,open:!!U&&!!s,onOpenChange:t=>{t||J(null)},allOrders:o||[]})})()]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 via-background to-background p-3 md:p-4 space-y-3",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm md:text-base",children:[h.type==="cart"?e.jsx(ps,{className:"h-5 w-5 text-primary"}):e.jsx(Be,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-semibold",children:h.type==="cart"?`Cart ${h.cartCode}`:`Order ${h.orderNumber}`}),me.size>0&&e.jsxs(T,{className:"text-[10px] gap-1 bg-emerald-600 hover:bg-emerald-600 text-white",children:[e.jsx(Re,{className:"h-3 w-3"})," ",me.size," already printed — hidden"]})]}),e.jsxs(k,{variant:"ghost",size:"sm",className:"h-8 text-xs gap-1",onClick:as,children:[e.jsx(it,{className:"h-3.5 w-3.5"})," Change cart"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 md:gap-3",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-2.5 md:p-3 text-center",children:[e.jsx("div",{className:"text-[10px] md:text-xs uppercase tracking-wide text-muted-foreground",children:"Remaining"}),e.jsx("div",{className:"text-xl md:text-2xl font-bold tabular-nums",children:Zs})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-2.5 md:p-3 text-center",children:[e.jsx("div",{className:"text-[10px] md:text-xs uppercase tracking-wide text-muted-foreground",children:"Verified"}),e.jsx("div",{className:"text-xl md:text-2xl font-bold tabular-nums text-primary",children:et})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-2.5 md:p-3 text-center",children:[e.jsx("div",{className:"text-[10px] md:text-xs uppercase tracking-wide text-muted-foreground",children:"Labeled"}),e.jsx("div",{className:"text-xl md:text-2xl font-bold tabular-nums text-emerald-600",children:st})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(T,{variant:E?"default":"outline",className:"cursor-pointer text-xs h-7 px-2.5",onClick:()=>N(!E),children:[e.jsx(fs,{className:"h-3 w-3 mr-1"}),E?"Auto-Label ON":"Auto-Label OFF"]}),e.jsxs(T,{variant:H==="free"?"default":"outline",className:"cursor-pointer text-xs h-7 px-2.5",onClick:()=>ye(H==="free"?"order":"free"),children:[e.jsx(Te,{className:"h-3 w-3 mr-1"}),H==="free"?"Free Scan":"Order Scan"]}),e.jsx(k,{variant:"ghost",size:"icon",className:"h-7 w-7 ml-auto",onClick:()=>oe(!$),children:$?e.jsx(ks,{className:"h-3.5 w-3.5"}):e.jsx(Cs,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[e.jsx(Z,{children:e.jsx(ee,{className:"p-3 md:p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsx("div",{className:"flex-1",children:e.jsxs(Ps,{value:x||"",onValueChange:v,children:[e.jsx(Ss,{className:"h-10 md:h-9",children:e.jsx(Ls,{placeholder:"Select order to pack"})}),e.jsx(Is,{children:W.map(s=>{var a;const t=z.get(s.id);return e.jsx(Ue,{value:s.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:s.order_number}),(t==null?void 0:t.labelCreated)&&e.jsx(T,{variant:"default",className:"text-[10px]",children:"Labeled"}),(t==null?void 0:t.allVerified)&&!(t!=null&&t.labelCreated)&&e.jsx(T,{variant:"secondary",className:"text-[10px]",children:"Verified"}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:[((a=s.items)==null?void 0:a.length)||0," items"]})]})},s.id)})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(T,{variant:"secondary",className:"text-xs",children:[ae.filter(s=>s.verified).length,"/",ae.length," verified"]}),e.jsx(Ve,{value:Ks,className:"w-20 md:w-24 h-2"})]})]})})}),e.jsx(Z,{className:`border-2 transition-colors ${y==="success"||y==="complete"?"border-primary bg-primary/5":y==="mismatch"?"border-destructive bg-destructive/5":y==="label_creating"?"border-amber-500 bg-amber-50 dark:bg-amber-900/20":"border-border"}`,children:e.jsxs(ee,{className:"p-4 md:p-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Te,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(Ie,{ref:re,value:A,onChange:s=>V(s.target.value),onKeyDown:Gs,placeholder:H==="free"?"Scan any item — order auto-detected...":"Scan item for selected order...",className:"pl-10 h-12 md:h-14 text-base md:text-lg scanner-input",autoFocus:!0,autoComplete:"off"})]}),y==="label_creating"&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 p-3 rounded-lg bg-amber-100 dar
17k:bg-amber-900/30 text-amber-800 dark:text-amber-200",children:[e.jsx(gs,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"font-medium",children:"Creating shipping label..."})]}),y&&y!=="label_creating"&&e.jsx("div",{className:`mt-3 flex items-center gap-2 p-3 rounded-lg ${y==="success"||y==="complete"?"bg-primary/10 text-primary":"bg-destructive/10 text-destructive"}`,children:y==="success"||y==="complete"?e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"h-5 w-5"}),e.jsx("span",{children:y==="complete"?"Item fully verified!":"Scan successful!"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Me,{className:"h-5 w-5"}),e.jsx("span",{children:"Item not found or already verified"})]})}),D&&D!==x&&e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["↳ Item matched to order ",(ls=z.get(D))==null?void 0:ls.orderNumber]})]})}),M&&e.jsxs(Z,{children:[e.jsx(Ne,{className:"p-3 md:p-4 pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(we,{className:"text-sm md:text-base flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),M.orderNumber,M.labelCreated&&e.jsxs(T,{variant:"default",className:"text-[10px]",children:[e.jsx(xe,{className:"h-3 w-3 mr-1"})," Label Created"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!M.allVerified&&!M.labelCreated&&e.jsx(k,{variant:"outline",size:"sm",onClick:Js,className:"text-xs h-7",children:"Verify All"}),M.allVerified&&!M.labelCreated&&!M.labelCreating&&e.jsxs(k,{size:"sm",onClick:()=>Ce(M.orderId),className:"text-xs h-7 gap-1",children:[e.jsx(Pe,{className:"h-3 w-3"})," Create & Download Label"]}),M.labelCreated&&(()=>{const s=p.find(t=>t.orderId===M.orderId);return s!=null&&s.labelUrl?e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>De(s.labelUrl,M.orderNumber),className:"text-xs h-7 gap-1",children:[e.jsx(bs,{className:"h-3 w-3"})," Download Label"]}):null})(),M.labelError&&!me.has(M.orderId)&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>J(M.orderId),className:"text-xs h-7 gap-1",children:[e.jsx(hs,{className:"h-3 w-3"})," Fix Order"]}),e.jsxs(k,{size:"sm",onClick:()=>Ce(M.orderId),className:"text-xs h-7 gap-1",children:[e.jsx(Ts,{className:"h-3 w-3"})," Retry Label"]})]}),me.has(M.orderId)&&e.jsxs(T,{variant:"default",className:"text-[10px] gap-1 bg-emerald-600 hover:bg-emerald-600 text-white",children:[e.jsx(Re,{className:"h-3 w-3"})," Locked — Void label to edit"]})]})]})}),e.jsx(ee,{className:"p-3 md:p-4 pt-0 space-y-2",children:ae.map(s=>e.jsxs("div",{className:`flex items-center gap-3 md:gap-4 p-3 rounded-lg border transition-colors ${s.verified?"bg-primary/10 border-primary":"bg-muted/50 border-transparent"}`,children:[e.jsx("div",{className:"flex-shrink-0",children:s.verified?e.jsx(xe,{className:"h-5 w-5 md:h-6 md:w-6 text-primary"}):e.jsx("div",{className:"h-5 w-5 md:h-6 md:w-6 rounded-full border-2 border-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium text-sm md:text-base truncate",children:s.product_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["SKU: ",s.product_sku||"N/A",s.product_upc&&` • UPC: ${s.product_upc}`]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("div",{className:"text-lg md:text-2xl font-bold",children:[s.quantity_verified,"/",s.quantity]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"verified"})]})]},s.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Z,{className:ke?"border-primary/30":"border-amber-500/50",children:[e.jsx(Ne,{className:"p-3 pb-2",children:e.jsxs(we,{className:"text-sm flex items-center gap-2",children:[e.jsx(Pe,{className:"h-4 w-4"}),"Printer Setup",ke?e.jsx(T,{variant:"default",className:"text-[10px] ml-auto",children:"Connected"}):e.jsx(T,{variant:"outline",className:"text-[10px] ml-auto border-amber-500 text-amber-600",children:"Not Set"})]})}),e.jsx(ee,{className:"p-3 pt-0 space-y-2",children:ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Printer: ",e.jsx("span",{className:"font-medium text-foreground",children:As||"Browser Default"})]}
17),Bs?e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px]",children:[e.jsxs(T,{variant:"default",className:"text-[10px] gap-1",children:[e.jsx(fs,{className:"h-2.5 w-2.5"})," Silent print ready"]}),e.jsx("span",{className:"text-muted-foreground",children:"— no dialog"})]}):e.jsxs("div",{className:"flex items-start gap-1.5 text-[10px] text-amber-600 dark:text-amber-500",children:[e.jsx(lt,{className:"h-3 w-3 shrink-0 mt-0.5"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Browser fallback only"})," — auto-print will open the system print dialog. To print silently, pair a USB printer in Brand → Label Printing or link a Printer Connect device in pack-station settings."]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[se&&e.jsx(T,{variant:"secondary",className:"text-[10px]",children:"Auto Labels"}),ne&&e.jsx(T,{variant:"secondary",className:"text-[10px]",children:"Auto Slips"}),!se&&!ne&&e.jsx("span",{children:"Auto-print disabled — enable in station settings"})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(k,{variant:"outline",size:"sm",className:"h-7 text-xs flex-1",onClick:We,children:"Test Print"}),e.jsx(k,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:Fs,children:"Reset"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set up your printer to enable auto-printing of labels and packing slips."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ie,{placeholder:"Printer name (e.g. Zebra ZD420)",className:"h-8 text-xs",id:"printer-name-input"}),e.jsxs(k,{size:"sm",className:"w-full h-8 text-xs",onClick:()=>{const s=document.getElementById("printer-name-input"),t=(s==null?void 0:s.value)||"Browser Printer";We(),Ds(t),O.success("Printer configured! Select your printer in the print dialog.")},children:[e.jsx(Pe,{className:"h-3 w-3 mr-1.5"}),"Setup Printer & Test"]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"A test page will print. Select your label printer in the browser dialog. Setup resets on page refresh."})]})})]}),Y.length>0&&e.jsxs(Z,{children:[e.jsx(Ne,{className:"p-3 pb-2",children:e.jsxs(we,{className:"text-sm flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4"}),"Auto-print queue",e.jsx(T,{variant:"outline",className:"ml-auto",children:Y.length})]})}),e.jsx(ee,{className:"p-0",children:e.jsx(_e,{className:"max-h-48",children:e.jsx("div",{className:"px-3 pb-3 space-y-2",children:Y.slice(0,8).map(s=>{const t=s.status==="printed"?"default":s.status==="failed"?"destructive":s.status==="label_created"?"secondary":"outline";return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(T,{variant:t,className:"capitalize shrink-0",children:s.status.replace("_"," ")}),e.jsx("span",{className:"truncate font-mono text-muted-foreground",children:s.sales_order_id.slice(0,8)}),s.error_message&&e.jsx("span",{className:"text-destructive truncate",title:s.error_message,children:s.error_message.slice(0,40)}),s.status==="failed"&&e.jsxs("div",{className:"ml-auto flex gap-1",children:[e.jsx(k,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:()=>$s.mutate(s.id),children:"Retry"}),e.jsx(k,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:()=>qs.mutate(s.id),children:"Skip"})]})]},s.id)})})})})]}),p.length>0&&e.jsxs(Z,{children:[e.jsx(Ne,{className:"p-3 pb-2",children:e.jsxs(we,{className:"text-sm flex items-center gap-2",children:[e.jsx(Pe,{className:"h-4 w-4"}),"Labels Created (",p.length,")"]})}),e.jsx(ee,{className:"p-3 pt-0",children:e.jsx(_e,{className:"max-h-48",children:e.jsx("div",{className:"space-y-1",children:p.map((s,t)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs p-1.5 rounded bg-primary/5",children:[e.jsx(xe,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"font-mono",children:s.orderNumber}),s.tracking&&e.jsx("span",{className:"text-muted-foreground truncate flex-1",children:s.tracking}),s.labelUrl&&e.jsxs("div",{className:"flex items-center gap-1 ml-auto shrink-0",children:[e.jsxs(k,{size:"sm",variant:"ghost",className:"h-6 px-1.5 text-[10px] gap-1",title:"Re-print label",onClick:()=>de(s.labelUrl,"label"),children:[e.jsx(Pe,{className:"h-3 w-3"})," Print"]}),e.jsxs(k,{size:"sm",variant:"ghost",className:"h-6 px-1.5 text-[10px] gap-1",title:"Download label",onClick:()=>De(s.labelUrl,s.orderNumber),children:[e.jsx(bs,{className:"h-3 w-3"})," Save"]})]})]},t))})})})]}),e.jsxs(Z,{children:[e.jsx(Ne,{className:"p-3 pb-2",children:e.jsx(we,{className:"text-sm",children:"Order Details"})}),e.jsx(ee,{className:"p-3 pt-0 space-y-3",children:le?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Ship To"}),e.jsx("div",{className:"font-medium text-sm",children:le.customer_name}),e.jsxs("div",{className:"text-xs",children:[(cs=le.shipping_address)==null?void 0:cs.address1,((os=le.shipping_address)==null?void 0:os.address2)&&e.jsxs(e.Fragment,{children:[", ",le.shipping_address.address2]})]}),e.jsxs("div",{className:"text-xs",children:[(ds=le.shipping_address)==null?void 0:ds.city,", ",(ms=le.shipping_address)==null?void 0:ms.state," ",(us=le.shipping_address)==null?void 0:us.postal_code]})]}),e.jsx(js,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Items"}),e.jsx("span",{className:"font-medium",children:ae.length})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total Qty"}),e.jsx("span",{className:"font-medium",children:ae.reduce((s,t)=>s+t.quantity,0)})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Verified"}),e.jsxs("span",{className:"font-medium text-primary",children:[ae.filter(s=>s.verified).length,"/",ae.length]})]}),le.total_amount&&e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Order Total"}),e.jsx("span",{className:"font-medium",children:ct(Number(le.total_amount),{decimals:2})})]})]}),e.jsx(js,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(k,{variant:"outline",className:"w-full h-8 text-xs",size:"sm",children:[e.jsx(ot,{className:"h-3 w-3 mr-1.5"}),"Print Packing Slip"]}),e.jsxs(k,{variant:"outline",className:"w-full h-8 text-xs",size:"sm",children:[e.jsx(dt,{className:"h-3 w-3 mr-1.5"}),"Print Pick Ticket"]})]})]}):e.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[e.jsx(Se,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-xs",children:"Select an order or scan an item"})]})})]}),e.jsxs(Z,{children:[e.jsxs(Ne,{className:"p-3 pb-2 flex-row items-center justify-between space-y-0",children:[e.jsxs(we,{className:"text-sm flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4"}),"Order Queue"]}),e.jsxs(T,{variant:"secondary",className:"text-[10px] tabular-nums",children:[W.length," to pack"]})]}),e.jsxs(ee,{className:"p-2 pt-0",children:[e.jsx(_e,{className:"max-h-[22rem]",children:e.jsxs("div",{className:"space-y-1.5",children:[W.length===0&&e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(xe,{className:"h-8 w-8 mx-auto mb-2 text-emerald-500"}),e.jsx("p",{className:"text-xs font-medium",children:"All caught up"}),e.jsx("p",{className:"text-[10px]",children:"No orders left to pack on this cart."})]}),W.map(s=>{const t=z.get(s.id),a=s.id===x,r=(t==null?void 0:t.items.length)||0,i=(t==null?void 0:t.items.filter(l=>l.verified).length)||0,m=r>0&&i===r;return e.jsxs("button",{onClick:()=>v(s.id),className:`w-full text-left p-2.5 md:p-3 rounded-lg border text-xs transition-all ${a?"bg-primary/10 border-primary shadow-sm ring-1 ring-primary/40":t!=null&&t.labelCreated?"bg-emerald-500/5 border-emerald-500/30 opacity-80":"bg-card hover:bg-muted/50 border-border"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono font-semibold text-[11px] md:text-xs truncate",children:s.order_number}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[(t==null?void 0:t.labelCreating)&&e.jsx(gs,{className:"h-3.5 w-3.5 animate-spin text-amber-500"}),t!=null&&t.labelCreated?e.jsxs(T,{className:"text-[9px] gap-1 bg-emerald-600 hover:bg-emerald-600 text-white",children:[e.jsx(xe,{className:"h-3 w-3"})," Labeled"]}):m?e.jsx(T,{variant:"default",className:"text-[9px]",children:"Ready"}):e.jsxs(T,{variant:"outline",className:"text-[9px] tabular-nums",children:[i,"/",r]})]})]}),e.jsx("div",{className:"text-muted-foreground truncate mt-0.5",children:s.customer_name}),r>0&&!(t!=null&&t.labelCreated)&&e.jsx(Ve,{value:i/r*100,className:"h-1 mt-1.5"})]},s.id)})]})}),me.size>0&&e.jsxs("div",{className:"mt-2 pt-2 border-t flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx(Re,{className:"h-3 w-3 text-emerald-600"}),me.size," printed this run — hidden & locked"]})]})]})]})]}),e.jsx(mt,{open:g,onOpenChange:b,children:e.jsxs(ut,{children:[e.jsxs(xt,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"h-5 w-5 text-primary"}),"All Items Verified"]}),e.jsx(ht,{children:"All items for this order have been scanned and verified. Create a shipping label now?"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 py-4",children:[e.jsxs(k,{variant:"outline",className:"h-20 md:h-24 flex-col gap-2",onClick:Ys,children:[e.jsx(ft,{className:"h-6 w-6 md:h-8 md:w-8"}),e.jsx("span",{className:"text-xs md:text-sm",children:"Add to Queue"})]}),e.jsxs(k,{className:"h-20 md:h-24 flex-col gap-2",onClick:Xs,children:[e.jsx(Pe,{className:"h-6 w-6 md:h-8 md:w-8"}),e.jsx("span",{className:"text-xs md:text-sm",children:"Create Label"})]})]}),e.jsx(gt,{children:e.jsx(bt,{children:"Cancel"})})]})}),(()=>{const s=U&&(W.find(a=>a.id===U)||pe.find(a=>a.id===U)||(o==null?void 0:o.find(a=>
17a.id===U)))||null,t=!!U&&me.has(U)&&!pe.some(a=>a.id===U);return e.jsx(ws,{order:t?null:s,open:!!U&&!t&&!!s,onOpenChange:a=>{a||J(null)},onCreateShipment:async a=>{const r=(a==null?void 0:a.id)||U;J(null),r&&!me.has(r)&&await Ce(r)},allOrders:W})})()]})}function Ur({mode:w,items:f,batchName:L,onItemScanned:c,onComplete:x,onExit:v}){const[A,V]=d.useState(""),[E,N]=d.useState(0),[g,b]=d.useState(null),[y,B]=d.useState(!0),[D,I]=d.useState(!1),[$,oe]=d.useState([]),[H,ye]=d.useState(!1),[z,G]=d.useState(!1),p=d.useRef(null),_=f.reduce((o,C)=>o+C.quantity,0),P=f.reduce((o,C)=>o+C.scannedQty,0),q=_>0?P/_*100:0,h=P>=_,F=f[E],U=F?F.quantity-F.scannedQty:0;d.useEffect(()=>{p.current&&!H&&p.current.focus()},[E,g,H]),d.useEffect(()=>{if(g){const o=setTimeout(()=>b(null),1500);return()=>clearTimeout(o)}},[g]);const J=d.useCallback(o=>{if(y)try{const C=new AudioContext,X=C.createOscillator(),K=C.createGain();X.connect(K),K.connect(C.destination),X.frequency.value=o==="success"?800:300,K.gain.value=.1,X.start(),X.stop(C.currentTime+(o==="success"?.15:.3))}catch{}},[y]),re=d.useCallback(o=>{if(!o.trim())return;const C=f.find(K=>K.barcode===o||K.sku===o||K.sku.toLowerCase()===o.toLowerCase()),X=new Date().toLocaleTimeString();if(C&&C.scannedQty<C.quantity){if(c(C.id,C.scannedQty+1),b("success"),J("success"),oe(K=>[{sku:C.sku,result:"OK",time:X},...K.slice(0,49)]),C.scannedQty+1>=C.quantity){const K=f.findIndex((ve,pe)=>pe!==E&&ve.scannedQty<ve.quantity);K!==-1&&N(K)}}else b("mismatch"),J("error"),oe(K=>[{sku:o,result:C?"OVER":"NOT FOUND",time:X},...K.slice(0,49)]),O.error(C?"Item already fully scanned":`No match for: ${o}`);V("")},[f,E,c,J]);vs(re);const fe=o=>{o.key==="Enter"&&A.trim()&&re(A.trim())},Q=()=>{document.fullscreenElement?(document.exitFullscreen().catch(()=>{}),I(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),I(!0))},ge=o=>{N(o),ye(!1)};return e.jsxs("div",{className:"fixed inset-0 z-50 bg-background flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b bg-card shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{variant:"ghost",size:"sm",onClick:v,className:"gap-1",children:[e.jsx(Ns,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Exit"})]}),e.jsx(T,{variant:w==="pick"?"default":"secondary",className:"text-xs",children:w==="pick"?"PICKING":"PACKING"}),L&&e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:L})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(k,{variant:z?"default":"ghost",size:"icon",className:"h-8 w-8",onClick:()=>G(!z),children:e.jsx(jt,{className:"h-4 w-4"})}),e.jsx(k,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>ye(!H),children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(k,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>B(!y),children:y?e.jsx(ks,{className:"h-4 w-4"}):e.jsx(Cs,{className:"h-4 w-4"})}),e.jsx(k,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:Q,children:D?e.jsx(wt,{className:"h-4 w-4"}):e.jsx(_t,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"px-3 py-2 border-b shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[e.jsxs("span",{className:"font-medium",children:[P," / ",_," items"]}),e.jsxs("span",{className:"text-muted-foreground",children:[Math.round(q),"%"]})]}),e.jsx(Ve,{value:q,className:"h-2"})]}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0 overflow-hidden",children:[H&&e.jsx("div",{className:"w-full md:w-72 border-b md:border-b-0 md:border-r shrink-0 max-h-[40vh] md:max-h-full",children:e.jsx(_e,{className:"h-full",children:e.jsx("div",{className:"p-2 space-y-1",children:f.map((o,C)=>{const X=o.scannedQty>=o.quantity;return e.jsxs("button",{onClick:()=>ge(C),className:`w-full text-left p-2 rounded-md text-sm transition-colors ${C===E?"bg-primary/10 border border-primary/30":X?"bg-muted/50 opacity-60":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`font-mono text-xs ${X?"line-through":""}`,children:o.sku}),e.jsxs(T,{variant:X?"default":"outline",className:"text-[10px]",children:[o.scannedQty,"/",o.quantity]})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:o.name}),o.location&&e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:["📍 ",o.location]})]},o.id)})})})}),e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center p-4 min-h-0",children:h?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mx-auto",children:e.jsx(xe,{className:"h-10 w-10 text-primary"})}),e.jsxs("h2",{className:"text-2xl font-bold",children:["All Items ",w==="pick"?"Picked":"Packed","!"]}),e.jsxs("p",{className:"text-muted-foreground",children:[P," items completed"]}),e.jsx(k,{size:"lg",onClick:x,className:"mt-4",children:w==="pick"?"Proceed to Packing":"Complete"})]}):F?e.jsxs("div",{className:"w-full max-w-lg space-y-6",children:[e.jsx(Z,{className:`transition-all duration-300 ${g==="success"?"ring-2 ring-green-500 bg-green-50 dark:bg-green-900/20":g==="mismatch"?"ring-2 ring-red-500 bg-red-50 dark:bg-red-900/20":""}`,children:e.jsxs(ee,{className:"p-6 text-center",children:[g==="success"&&e.jsx("div",{className:"mb-4",children:e.jsx(xe,{className:"h-12 w-12 text-green-500 mx-auto animate-bounce"})}),g==="mismatch"&&e.jsx("div",{className:"mb-4",children:e.jsx(Me,{className:"h-12 w-12 text-red-500 mx-auto animate-shake"})}),!g&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3",children:e.jsx(Te,{className:"h-10 w-10 text-primary mx-auto opacity-50"})}),e.jsx("h3",{className:"text-xl md:text-2xl font-bold font-mono",children:F.sku}),e.jsx("p",{className:"text-base text-muted-foreground mt-1 line-clamp-2",children:F.name}),F.location&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1 px-3 py-1 rounded-full bg-muted text-sm",children:["📍 ",F.location]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold text-primary",children:U}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Remaining"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold",children:F.scannedQty}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Scanned"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold text-muted-foreground",children:F.quantity}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total"})]})]})]})]})}),z&&e.jsx(yt,{isActive:z,onScan:o=>{re(o)},onClose:()=>G(!1),className:"aspect-video max-h-40"}),e.jsxs("div",{className:"relative",children:[e.jsx(Te,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(Ie,{ref:p,value:A,onChange:o=>{V(o.target.value),o.target.value&&z&&G(!1)},onKeyDown:fe,placeholder:"Scan barcode or type SKU...",className:"h-14 text-lg pl-10 scanner-input",autoFocus:!0,autoComplete:"off"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(k,{variant:"outline",size:"lg",className:"h-12",onClick:()=>{E>0&&N(o=>o-1)},disabled:E===0,children:[e.jsx(Ns,{className:"h-4 w-4 mr-1"})," Previous"]}),e.jsxs(k,{variant:"outline",size:"lg",className:"h-12",onClick:()=>{E<f.length-1&&N(o=>o+1)},disabled:E>=f.length-1,children:["Next ",e.jsx(vt,{className:"h-4 w-4 ml-1"})]})]}),e.jsx("div",{className:"rounded-lg border border-amber-300 bg-amber-50 p-3 text-center text-sm font-medium text-amber-900",children:"Scan the exact item barcode to confirm each unit."})]}):null}),e.jsx("div",{className:"hidden md:block w-56 border-l shrink-0",children:e.jsxs("div",{className:"p-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-muted-foreground mb-2",children:"Scan History"}),e.jsx(_e,{className:"h-[calc(100vh-200px)]",children:e.jsxs("div",{className:"space-y-1",children:[$.map((o,C)=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] p-1 rounded bg-muted/30",children:[e.jsx("span",{className:"font-mono truncate",children:o.sku}),e.jsx(T,{variant:o.result==="OK"?"default":"destructive",className:"text-[9px] ml-1",children:o.result})]},C)),$.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground text-center py-4",children:"No scans yet"})]})})]})})]})]})}const ys={pack_one:{label:"Pack One",description:"Single-item orders, 1 line per order",icon:Se,maxOrders:80,filterFn:w=>{var c,x;const f=((c=w.items)==null?void 0:c.length)||0,L=((x=w.items)==null?void 0:x.reduce((v,A)=>v+(A.quantity||1),0))||0;return f===1&&L===1}},multi_order:{label:"Multi Orders",description:"Multi-line or multi-qty orders",icon:At,maxOrders:30,filterFn:w=>{var c,x;const f=((c=w.items)==null?void 0:c.length)||0,L=((x=w.items)==null?void 0:x.reduce((v,A)=>v+(A.quantity||1),0))||0;return f>1||L>1}},bundle_dtg:{label:"Bundle / DTG",description:"Kit/bundle items needing assembly",icon:Bt,maxOrders:20,filterFn:w=>{var f;return((f=w.items)==null?void 0:f.some(L=>{var c;return L.is_kit||((c=L.kit_components)==null?void 0:c.length)>0||(L.product_name||"").toLowerCase().includes("bundle")}))||!1}},custom:{label:"Custom",description:"Select any orders manually",icon:Be,maxOrders:100,filterFn:()=>!0}};function Vr({onBatchCreated:w}
17){const[f,L]=d.useState("pack_one"),[c,x]=d.useState(new Set),[v,A]=d.useState(""),[V,E]=d.useState("all"),[N,g]=d.useState(!1),{salesOrders:b,isLoading:y}=zs(),{createPickList:B}=Es(),{warehouses:D}=kt(),I=ys[f],$=d.useMemo(()=>{let _=(b||[]).filter(P=>P.status==="awaiting_shipment"||P.status==="pending");if(f!=="custom"&&(_=_.filter(I.filterFn)),V!=="all"&&(_=_.filter(P=>{var q;return(((q=P.marketplace_connection)==null?void 0:q.store_name)||"").toLowerCase().includes(V.toLowerCase())})),v){const P=v.toLowerCase();_=_.filter(q=>{var h;return(q.order_number||"").toLowerCase().includes(P)||(q.customer_name||"").toLowerCase().includes(P)||((h=q.items)==null?void 0:h.some(F=>(F.product_sku||"").toLowerCase().includes(P)||(F.product_name||"").toLowerCase().includes(P)))})}return _},[b,f,V,v,I.filterFn]),oe=d.useMemo(()=>{const p=new Set;return(b||[]).forEach(_=>{var P;(P=_.marketplace_connection)!=null&&P.store_name&&p.add(_.marketplace_connection.store_name)}),Array.from(p).sort()},[b]),H=$.length>0&&$.every(p=>c.has(p.id)),ye=()=>{if(H)x(new Set);else{const p=Math.min($.length,I.maxOrders);x(new Set($.slice(0,p).map(_=>_.id)))}},z=p=>{const _=new Set(c);if(_.has(p))_.delete(p);else{if(_.size>=I.maxOrders){O.warning(`Max ${I.maxOrders} orders per ${I.label} batch`);return}_.add(p)}x(_)},G=async()=>{var p,_;if(c.size!==0){g(!0);try{const q=((p=$.filter(F=>c.has(F.id))[0])==null?void 0:p.warehouse_id)||((_=D==null?void 0:D[0])==null?void 0:_.id),h=await B.mutateAsync({picking_method:f==="pack_one"?"single_order":"batch",warehouse_id:q,order_ids:Array.from(c),notes:`${I.label} batch - ${c.size} orders`,batch_type:f,batch_size_limit:I.maxOrders});O.success(`${I.label} batch created with ${c.size} orders`),x(new Set),w==null||w(h.id)}catch(P){O.error(`Failed to create batch: ${P.message}`)}finally{g(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Object.entries(ys).map(([p,_])=>{const P=_.icon,q=(b||[]).filter(h=>(h.status==="awaiting_shipment"||h.status==="pending")&&_.filterFn(h)).length;return e.jsxs("button",{onClick:()=>{L(p),x(new Set)},className:$e("flex flex-col items-center gap-1.5 p-3 rounded-lg border-2 transition-all text-center",f===p?"border-primary bg-primary/5 shadow-sm":"border-border hover:border-muted-foreground/30 hover:bg-muted/30"),children:[e.jsx(P,{className:$e("h-5 w-5",f===p?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:"text-sm font-medium",children:_.label}),e.jsx(T,{variant:"secondary",className:"text-xs",children:q})]},p)})}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground bg-muted/30 rounded-lg px-3 py-2",children:[e.jsx("span",{children:I.description}),e.jsxs("span",{className:"font-medium",children:["Max ",I.maxOrders," per batch"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ct,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ie,{placeholder:"Search orders, SKUs, customers...",value:v,onChange:p=>A(p.target.value),className:"pl-9 h-9"})]}),oe.length>1&&e.jsxs(Ps,{value:V,onValueChange:E,children:[e.jsx(Ss,{className:"w-[160px] h-9",children:e.jsx(Ls,{placeholder:"Channel"})}),e.jsxs(Is,{children:[e.jsx(Ue,{value:"all",children:"All Channels"}),oe.map(p=>e.jsx(Ue,{value:p,children:p},p))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(k,{variant:"ghost",size:"sm",onClick:ye,className:"h-7 text-xs",children:H?e.jsxs(e.Fragment,{children:[e.jsx(qt,{className:"h-3.5 w-3.5 mr-1"})," Deselect All"]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"h-3.5 w-3.5 mr-1"})," Select All (",Math.min($.length,I.maxOrders),")"]})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[$.length," unassigned orders"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(T,{variant:"outline",className:"font-medium",children:[c.size," selected"]}),e.jsxs(k,{size:"sm",onClick:G,disabled:c.size===0||N,children:[N?e.jsx(Ts,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Pt,{className:"h-3.5 w-3.5 mr-1"}),"Batch (",c.size,")"]})]})]}),e.jsx(Z,{children:e.jsx(ee,{className:"p-0",children:e.jsx(_e,{className:"h-[400px]",children:e.jsxs(St,{children:[e.jsx(Lt,{className:"sticky top-0 bg-background z-10",children:e.jsxs(qe,{children:[e.jsx(ue,{className:"w-10"}),e.jsx(ue,{children:"Order #"}),e.jsx(ue,{children:"Channel"}),e.jsx(ue,{className:"text-center",children:"Lines"}),e.jsx(ue,{className:"text-center",children:"Total Qty"}),e.jsx(ue,{children:"Item"}),e.jsx(ue,{children:"Category"}),e.jsx(ue,{children:"Location"}),e.jsx(ue,{children:"Date"})]})}),e.jsx(It,{children:$.length===0?e.jsx(qe,{children:e.jsxs(ce,{colSpan:9,className:"h-32 text-center",children:[e.jsx(Se,{className:"h-8 w-8 text-muted-foreground mx-auto mb-2"}),e.jsxs("p",{className:"text-muted-foreground",children:["No unassigned ",I.label," orders"]})]})}):$.map(p=>{var U,J,re,fe;const _=c.has(p.id),P=((U=p.items)==null?void 0:U.length)||0,q=((J=p.items)==null?void 0:J.reduce((Q,ge)=>Q+(ge.quantity||1),0))||0,h=(re=p.items)==null?void 0:re[0],F=((fe=p.marketplace_connection)==null?void 0:fe.store_name)||"-";return e.jsxs(qe,{className:$e("cursor-pointer",_&&"bg-primary/5"),onClick:()=>z(p.id),children:[e.jsx(ce,{onClick:Q=>Q.stopPropagation(),children:e.jsx(Tt,{checked:_,onCheckedChange:()=>z(p.id)})}),e.jsx(ce,{className:"font-mono text-sm font-medium",children:p.order_number}),e.jsx(ce,{children:e.jsx(T,{variant:"outline",className:"text-xs",children:F})}),e.jsx(ce,{className:"text-center",children:P}),e.jsx(ce,{className:"text-center font-medium",children:q}),e.jsx(ce,{className:"max-w-[200px] truncate text-sm",children:P>1?"(Multiple)":(h==null?void 0:h.product_name)||"-"}),e.jsx(ce,{className:"text-sm text-muted-foreground",children:(h==null?void 0:h.item_category)||"-"}),e.jsx(ce,{className:"text-sm text-muted-foreground font-mono",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[(h==null?void 0:h.warehouse_location)||"-",(h==null?void 0:h.warehouse_location)&&e.jsx(Et,{code:h.warehouse_location,size:12})]})}),e.jsx(ce,{className:"text-xs text-muted-foreground",children:p.order_date?zt(new Date(p.order_date),"MM/dd"):"-"})]}
17,p.id)})})]})})})})]})}export{Vr as BatchBuildPanel,Wr as CreatePickListDialog,Hr as EnhancedTabletPicking,nn as MANUFACTURER_BATCH_TYPES,an as OrderSelectionGrid,Br as PackStation,Gr as PackingVerification,Jr as PickListDetailDialog,Xr as PickListsTable,Yr as PickPackDashboard,sn as PickingInterface,ln as SHIPPING_EXCLUDED_BATCH_TYPES,Ur as TabletScanMode,Zr as usePickListPrint};

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.