1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SendPackDialog-Bdl95I2n.js","assets/index-ZIqlhysh.js","assets/index-CRC5oYtn.css","assets/textarea-B8Qcuo4j.js","assets/label-CWiBKcul.js","assets/checkbox-BvWpVLm8.js","assets/minus-DiRG9OCe.js","assets/useTemplatePacks-CUplEpLs.js","assets/useDocumentTypes-B6f7HSuF.js","assets/systemLibraryIds-BfIM5uK3.js","assets/useKnowledgeLibraryRows-CpApANsg.js","assets/sharedRealtimeInvalidation-C-cCdLq0.js","assets/scale-BUna4Gf7.js","assets/triangle-alert-Ca5eKo1j.js","assets/leaf-lyNmISoa.js","assets/globe-Cv7Lk7Ec.js","assets/tram-front-BnCR614S.js","assets/truck-BXCxCCDJ.js","assets/plane-BBzCZuJx.js","assets/tag-R2rxq7pE.js","assets/organizationsBulkRead-BoGKlShR.js","assets/useOrganizationsLibraryId-CTPtxI5c.js","assets/normalizeLibraryFieldSchema-BrhNpvhV.js","assets/useOrganizationRoles-DJbfuBt2.js","assets/partyRoleSlots-DazCTK9B.js","assets/abnValidation-BEt_6_Hu.js","assets/identifierInput-Mi7Gz1Zd.js","assets/bundleSectionStorage-CYspxYpc.js","assets/workflowRequiredDocuments-BwWHvAn6.js","assets/mail-CPyEX-_Q.js","assets/arrow-left-BXkwSA_n.js","assets/link-2-CI5bkY4P.js","assets/plus-5DHDX40z.js","assets/copy-CgYlQCVc.js","assets/send-CUIyMkfw.js","assets/circle-check-C0TTyAIF.js","assets/circle-x-C9JYP_Ox.js"])))=>i.map(i=>d[i]); 2import{en as i,e2 as e,bq as Rs,as as ye,k as A,ay as J,cr as Q,aV as Ya,aY as Xa,aX as Za,K as Ja,O as er,Q as tr,M as ys,P as ws,g as te,w as Is,a0 as tt,a1 as st,a4 as at,a5 as rt,br as zt,bz as Bt,bA as Gt,bs as qt,bu as Be,a3 as Ut,f1 as $,p as le,x as Ve,ag as pe,z as zs,c0 as Ke,b_ as Qe,c1 as He,b$ as Ye,dY as Tt,bR as ve,bp as Et,u as Xe,aj as Ze,eq as Bs,d3 as Lt,eW as _e,q as be,b7 as Re,aw as gt,t as Mt,D as Ns,bB as $t,c9 as Gs,H as qs,J as Us,I as Ws,a2 as Wt,b as jt,c as bt,cZ as Vs,ft as Ks,fu as Qs,dd as Vt,ev as sr,dE as ar,fo as rr,d1 as nr,fp as ir,fr as lr,fC as or,cb as cr,az as dr,dL as mr,cR as ur,dT as pr}from"./index-ZIqlhysh.js";import{T as xr,a as _s}from"./toggle-group-C_DwpRw3.js";import{D as Kt,l as Qt,b as Ht,d as vt,i as hr,k as fr,e as gr,j as jr,a as yt,h as Cs,c as wt,f as br,g as vr}from"./dropdown-menu-BrP2luMC.js";import{f as yr}from"./fuelSurfaces-Dluy32C3.js";import{Q as wr,al as Nr,aC as _r}from"./useServiceReadinessInputs-BfiXN0SW.js";import{u as Ce}from"./useDocumentTypes-B6f7HSuF.js";import{F as Cr}from"./filter-BbuOMR5r.js";import{E as ks,a as Ds,u as kr}from"./index-DD97QxDD.js";import{bK as Dr,ag as Nt,$ as Ss,af as _t,ai as Hs,ae as Sr,as as Fr,W as Ar,r as Tr,bv as Er,ax as Fs,bz as Lr,bL as Mr,a_ as Ct,ah as $r,M as Or}from"./NewShipment-DR32cfzO.js";import{L as ie}from"./label-CWiBKcul.js";import{F as Ot}from"./tag-R2rxq7pE.js";import{C as Pr}from"./chevrons-up-down-BNN33Cs8.js";import{P as Pt}from"./plus-5DHDX40z.js";import{I as Rr}from"./SendPackDialog-Bdl95I2n.js";import{U as Ee}from"./upload-CZvWNitV.js";import{g as Ys,k as Ir}from"./useShipmentData-BY53hGa6.js";import{A as Yt,c as Xt,f as Zt,g as Jt,d as es,e as ts,b as ss,a as as,h as zr}from"./alert-dialog-BfaJqwbb.js";import{F as Br}from"./file-image-C4t54P6X.js";import{F as Gr}from"./file-spreadsheet-BQIm4Jhx.js";import{E as qr}from"./ellipsis-vertical-DhiXei1s.js";import{D as nt}from"./download-C6qhC9ZT.js";import{T as rs}from"./trash-2-CbYuD1zm.js";import{C as Xs}from"./clock-rbNnud8E.js";import{W as Je}from"./workflow-BShHLKbs.js";import{M as ns}from"./mail-CPyEX-_Q.js";import{B as Ur}from"./ban--_EZjs42.js";import{R as Wr}from"./rotate-ccw-FOzdvjBU.js";import{A as Vr}from"./thumbs-up-CBG3alYU.js";import{L as Kr}from"./list-DqwLPk3u.js";import{L as Qr}from"./layout-grid-ZCx84JQp.js";import{a3 as Hr,D as Yr,H as Xr,i as Zr,N as Jr}from"./OrganizationDialog-D6pmjJXi.js";import{B as en}from"./building-2-D0jdxETl.js";import{S as tn}from"./shield-check-M0yZvgRC.js";import{u as sn,D as an}from"./useDocumentPreviewLoad-BzyG_kFw.js";import{T as is}from"./textarea-B8Qcuo4j.js";import{T as rn,b as nn,c as kt,a as Dt}from"./tabs-DDYRWQC9.js";import{P as ln}from"./progress-DqblotiO.js";import{C as As}from"./circle-x-C9JYP_Ox.js";import{C as Ie}from"./circle-check-C0TTyAIF.js";import{T as et}from"./triangle-alert-Ca5eKo1j.js";import{P as on}from"./pen-P7M9u5oM.js";import{o as cn,r as Rt}from"./pdfjsWorker-CNktViMz.js";import{S as dn}from"./send-CUIyMkfw.js";import{P as mn}from"./pencil-D8eTXomX.js";import{I as un}from"./info-BZjpOoEy.js";import{L as Ts}from"./layers-E-IxxF9p.js";import{c as ze,p as pn,a as Es}
2from"./workflowRequiredDocuments-BwWHvAn6.js";import{G as xn}from"./GoogleDriveReconnectBanner-DEiN5Vhi.js";import{A as hn}from"./AccessDenied-zERC5v6p.js";import{a as fn,d as gn,h as jn}from"./useFuel-BlwAP4Y6.js";import{s as bn}from"./useOperationalWorkflowTemplates-BPWMq4fI.js";import{W as vn,x as yn,z as wn,f as We}from"./useWorkflowInstances-C0HRLKtx.js";import{b as Nn}from"./useShipmentQuotes-DRUsGq1P.js";import{R as _n,a as Cn}from"./radio-group-BFEeEPlJ.js";import{C as kn}from"./CustomFieldsHost-hDeq000s.js";import"./index-C6hDRvPu.js";import"./circle-DvkMqUft.js";import"./hash-CvA09OYX.js";import"./bot-D4-01ynC.js";import"./route-NJSfzG3K.js";import"./file-chart-column-increasing-BydOzFT8.js";import"./scan-search-BOgXxHQk.js";import"./IcsValidationIssuesPanel-B6-wNAhV.js";import"./WorkflowService-C5EQtDB_.js";import"./circle-check-big-C3EWDRAW.js";import"./arrow-right-DUcVW6J3.js";import"./zap-DDYHz229.js";import"./bundleSectionStorage-CYspxYpc.js";import"./serviceCategoryGrouping-BdiS39vo.js";import"./systemLibraryIds-BfIM5uK3.js";import"./useKnowledgeLibraryRows-CpApANsg.js";import"./sharedRealtimeInvalidation-C-cCdLq0.js";import"./scale-BUna4Gf7.js";import"./leaf-lyNmISoa.js";import"./globe-Cv7Lk7Ec.js";import"./tram-front-BnCR614S.js";import"./truck-BXCxCCDJ.js";import"./plane-BBzCZuJx.js";import"./index-4uyLK18b.js";import"./AppMainPageHeaderRow-FnABIjBI.js";import"./arrow-left-BXkwSA_n.js";import"./arrow-up-right-pj4WIaT-.js";import"./plug-iHcUxSrM.js";import"./ShipmentService-CxDZu_l6.js";import"./abfRejectionText-Cdk-X9zu.js";import"./icsDeclarationKinds-B3aBAaNU.js";import"./message-square-CaWi7IU-.js";import"./umbrella-C0Tdil2W.js";import"./file-check-cZjbtqiZ.js";import"./receipt-D-6LxDPI.js";import"./warehouse-DOIl_ygp.js";import"./map-pin-CzI1UOFo.js";import"./anchor-CN2vTmtH.js";import"./calendar-check-CahCZxbu.js";import"./shipmentDetailLoader-Ccgkg0N-.js";import"./auditLog-CxKsVV8e.js";import"./useOrganizationRoles-DJbfuBt2.js";import"./partyRoleSlots-DazCTK9B.js";import"./sortable.esm-jv9VAigA.js";import"./shipmentEta-CRPgPvvR.js";import"./table-og_XypMw.js";import"./useOrganizationNames-CuS8EwZx.js";import"./PortCombobox-FQ6UWOxQ.js";import"./use-debounce-dPI8N1JY.js";import"./useOrganizationsLibraryId-CTPtxI5c.js";import"./normalizeLibraryFieldSchema-BrhNpvhV.js";import"./abnValidation-BEt_6_Hu.js";import"./identifierInput-Mi7Gz1Zd.js";import"./useOrganizations-DRkIOZsU.js";import"./organizationsBulkRead-BoGKlShR.js";import"./useTableConfig-CmYdDoKc.js";import"./dnd.esm-V7gDcHqm.js";import"./index-MYj6Ox-y.js";import"./index-B81MHRHA.js";import"./with-selector-D2T12JAb.js";import"./tiny-invariant-CopsF_GD.js";import"./restoredQueryCache-BLlBuHvV.js";import"./switch-DoX9MkWL.js";import"./calendar-D4iY5dRe.js";import"./checkbox-BvWpVLm8.js";import"./minus-DiRG9OCe.js";import"./copy-CgYlQCVc.js";import"./useTableRowNavigation-ZlKO6keI.js";import"./save-status-indicator-IJ8rxxLk.js";import"./shipmentTabFieldCatalog-itEh6E6N.js";import"./customFieldRules-BbD-wYae.js";import"./smartTemplateEngine-whTtWdkf.js";import"./database-DnPWoHsg.js";import"./useCustomFields-1GM_xrTK.js";import"./useShipmentFieldRegistry-D3GrnunC.js";import"./shipmentFieldRegistry-DbzCeMW7.js";import"./aiModelOptions-3HBihR1b.js";import"./type-DjcW6oCo.js";import"./square-check-big-DY8yx9ys.js";import"./FieldBindingDropdown-CaqgQZ5D.js";import"./columns-3-Y5SE7JHt.js";import"./eye-off-D8H0fXcc.js";import"./grip-vertical-yzxKzAOa.js";import"./save-CMT0R-Iq.js";import"./shipmentTabDeepLink-nIF_zSMC.js";import"./DomainStatusMenuItems-jvFa_7gq.js";import"./history-Bz43fO1b.js";import"./cog-BtfDAumN.js";import"./clipboard-list-DMDDMo8V.js";import"./useArchiveShipments-DE1UM2UP.js";import"./external-link-BW2Cpoe8.js";import"./avatar-CzAYfWVi.js";import"./user-round-gVTw7NgD.js";import"./useCrewMembers-6XsQGCDF.js";import"./useCrewRoles-C1BB0svU.js";import"./workflowTemplateTiers-D9GlqIAe.js";import"./StepServiceChips-Bj4lSH5C.js";import"./workflowTemplate-kYcYSN6D.js";import"./workflowTemplatePresets-DNglblKn.js";import"./AgentActionRejectForm-CGFQ3hjM.js";import"./workflowConditionGroup-C_hR82CS.js";import"./skip-forward-VGyCy2Jw.js";import"./git-branch-CO8vVlro.js";import"./shield-alert-Ctaqv7e8.js";import"./undo-2-CpKltbMF.js";import"./circle-dashed-9HzK3-St.js";
2import"./circle-play-DgF5_CIz.js";import"./message-square-reply-DxFee4UB.js";import"./TransferPolicySummary-C18cEwbu.js";import"./TransferPolicyEditor-pIFNaMIS.js";import"./arrow-down-left-CBPa4r7p.js";import"./usePartnerServiceExtras-8qX-iwoe.js";import"./usePlatformServiceFee-kJgGyJ1k.js";import"./useTemplatePacks-CUplEpLs.js";import"./AgentMonitoredInboxes-DCZM71Bu.js";import"./index-B0U_QVqF.js";import"./inbox-CvrCT4HK.js";import"./connectedPartners-DK_L2mzG.js";import"./starshipCode-2o_Pe3CQ.js";import"./star-DvkvH-MA.js";import"./play-Jq19KfmQ.js";import"./settings-2-D5ZMRm9H.js";import"./agentPortraits-DqWrJdUV.js";import"./billing-BvFqD39q.js";import"./useDefaultCurrency-BloiuTZx.js";import"./archive-DQ2KVEz1.js";import"./split-Dx1-ZoIk.js";import"./pen-line-SLZVlzU9.js";import"./ellipsis-CHDVNYPd.js";import"./useCopyToClipboard-DESIqURR.js";import"./inboundEmailDomain-DM-VkVpl.js";import"./link-2-CI5bkY4P.js";import"./journeyEnds-BgyVh1xe.js";import"./countryCodes-BryVfONX.js";import"./countries-BMU44kQF.js";import"./organizationSiteOptions-BCOAYOvd.js";import"./useWorkspaceTermsLabels-D14I0ocA.js";import"./XeroAccountCombobox-BD8ILuGb.js";import"./paperclip-CJpCjCGM.js";import"./user-check-B8GN5Dzt.js";import"./websiteUrl-nmtfSJvj.js";import"./banknote-ILxUBIp8.js";import"./dollar-sign-yoaruvm-.js";import"./pdf-D-3QHYxT.js";import"./pdf.worker.min-DZ2iKPB6.js";import"./zoom-out-C9RLkEAM.js";import"./zoom-in-GH13nShV.js";import"./documentPopoutContent-BK6ViEuN.js";import"./cloud-zae5N_Nf.js";import"./stableStringify-Dwss7shX.js";import"./queryDataActivity-C_FgJUKn.js";import"./text-cursor-input-DdV_GGm9.js";function Dn({onSearch:t}){const[s,a]=i.useState("");return i.useEffect(()=>{const r=setTimeout(()=>{t(s)},300);return()=>clearTimeout(r)},[s,t]),e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search documents...",value:s,onChange:r=>a(r.target.value),className:"pl-9"})]})}const ls=[{value:"uploaded",label:"Uploaded",color:"default",dotClass:"bg-slate-400"},{value:"processing",label:"Processing",color:"secondary",dotClass:"bg-blue-500"},{value:"pending_review",label:"Pending Review",color:"default",dotClass:"bg-amber-500"},{value:"approved",label:"Approved",color:"default",dotClass:"bg-green-500"},{value:"rejected",label:"Rejected",color:"destructive",dotClass:"bg-red-500"},{value:"missing_info",label:"Missing Info",color:"destructive",dotClass:"bg-orange-500"},{value:"error",label:"Error",color:"destructive",dotClass:"bg-red-500"}],Zs=[{value:"consignor",label:"Consignor"},{value:"consignee",label:"Consignee"},{value:"notify_party",label:"Notify Party"},{value:"customs_broker",label:"Customs Broker"},{value:"wholesale_customs_broker",label:"Wholesale Customs Broker"},{value:"carrier",label:"Carrier"},{value:"freight_forwarder",label:"Freight Forwarder"},{value:"warehouse",label:"Warehouse"},{value:"insurance",label:"Insurance"}];function Sn({selectedTypes:t,onTypesChange:s,selectedStatuses:a,onStatusesChange:r,selectedStakeholders:n,onStakeholdersChange:l}){const{documentTypesByCategory:o,categories:p,loading:g}=Ce(),u=c=>{t.includes(c)?s(t.filter(d=>d!==c)):s([...t,c])},x=c=>{a.includes(c)?r(a.filter(d=>d!==c)):r([...a,c])},C=c=>{n.includes(c)?l(n.filter(d=>d!==c)):l([...n,c])},f=t.length+a.length+n.length,b=c=>c.charAt(0).toUpperCase()+c.slice(1);return e.jsxs(Kt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsxs(A,{variant:"outline",size:"sm",children:[e.jsx(Cr,{className:"h-4 w-4 mr-2"}),"Filter",f>0&&e.jsx("span",{className:"ml-2 px-1.5 py-0.5 text-xs bg-primary text-primary-foreground rounded-full",children:f})]})}),e.jsxs(Ht,{align:"end",className:"w-64",children:[e.jsx(vt,{children:"Document Type"}),g?e.jsx("div",{className:"flex items-center justify-center p-2",children:e.jsx(J,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):p.map(c=>{var d;return e.jsxs(hr,{children:[e.jsxs(fr,{children:[b(c),t.filter(v=>{var F;return(F=o[c])==null?void 0:F.some(E=>E.name===v)}).length>0&&e.jsx("span",{className:"ml-auto text-xs text-primary",children:t.filter(v=>{var F;return(F=o[c])==null?void 0:F.some(E=>E.name===v)}).length})]}),e.jsx(gr,{children:e.jsx(jr,{className:"max-h-[300px] overflow-y-auto",children:(d=o[c])==null?void 0:d.map(v=>e.jsxs(yt,{checked:t.includes(v.name),onCheckedChange:()=>u(v.name),children:[e.jsx("span",{className:"truncate",children:v.title}),e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:v.name})]},v.id))})})]},c)}),e.jsx(Cs,{}),e.jsx(vt,{children:"Status"}),ls.map(c=>e.jsx(yt,{checked:a.includes(c.value),onCheckedChange:()=>
2x(c.value),children:c.label},c.value)),e.jsx(Cs,{}),e.jsx(vt,{children:"Stakeholder"}),Zs.map(c=>e.jsx(yt,{checked:n.includes(c.value),onCheckedChange:()=>C(c.value),children:c.label},c.value))]})]})}const Ne="other";function Ls(t){const s=t.trim().split(/\s+/).filter(Boolean);return s.length===0?"":s.length===1?s[0].toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10):s.map(a=>a[0]).join("").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10)}function Js({value:t,onSelect:s,disabled:a=!1,includeOther:r=!0,allowCreate:n=!0,trigger:l,placeholder:o="Select document type",className:p}){const{documentTypes:g,getDocumentIcon:u,categories:x,loading:C}=Ce(),{createType:f}=Dr(),[b,c]=i.useState(!1),[d,v]=i.useState(""),[F,E]=i.useState(!1),[O,B]=i.useState(""),[G,D]=i.useState(""),[K,S]=i.useState(!1),[j,m]=i.useState("");i.useEffect(()=>{K||D(Ls(O))},[O,K]);const N=i.useMemo(()=>{const k=new Set(g.map(se=>se.name.toUpperCase()));return k.add(Ne.toUpperCase()),k},[g]),U=i.useMemo(()=>x.filter(k=>k&&k!==Ne),[x]),H=i.useMemo(()=>{const k=g.map(se=>({code:se.name,title:se.title,icon:u(se),isCustom:!!se.isCustom,isOther:!1}));return r&&k.push({code:Ne,title:"Other",icon:Ot,isCustom:!1,isOther:!0}),k},[g,u,r]),z=i.useMemo(()=>{const k=d.trim().toLowerCase();return k?H.filter(se=>se.title.toLowerCase().includes(k)||se.code.toLowerCase().includes(k)):H},[H,d]),Y=t?g.find(k=>k.name===t):void 0,T=(Y==null?void 0:Y.title)??(t===Ne?"Other":void 0),M=Y?u(Y):t===Ne?Ot:void 0,R=k=>{s(k),c(!1),v("")},P=k=>{c(!1),B(k),D(Ls(k)),S(!1),m(""),E(!0)},L=O.trim(),ee=G.trim().toUpperCase(),oe=!!ee&&N.has(ee),X=!!L&&!!ee&&!oe&&!f.isPending,W=async()=>{if(X)try{const k=await f.mutateAsync({document_code:ee,document_name:L,category:j||null});E(!1),R(k)}catch{}},xe=e.jsxs(A,{variant:"outline",role:"combobox","aria-expanded":b,disabled:a,className:Q("w-full justify-between font-normal",p),children:[T?e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[M&&e.jsx(M,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:T})]}):e.jsx("span",{className:"text-muted-foreground",children:o}),e.jsx(Pr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]});return e.jsxs(e.Fragment,{children:[e.jsxs(Ya,{open:b,onOpenChange:c,children:[e.jsx(Xa,{asChild:!0,disabled:a,children:l??xe}),e.jsx(Za,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Ja,{shouldFilter:!1,children:[e.jsx(er,{placeholder:"Search by name or codeâ¦",value:d,onValueChange:v}),e.jsx(tr,{children:C?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Loadingâ¦"}):e.jsxs(e.Fragment,{children:[z.length===0&&e.jsxs("div",{className:"space-y-2 px-2 py-6 text-center text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:"No document types found."}),n&&d.trim()&&e.jsxs("button",{type:"button",className:"mx-auto flex items-center gap-1 rounded px-2 py-1 text-sm text-primary hover:underline",onClick:()=>P(d.trim()),children:[e.jsx(Pt,{className:"h-4 w-4"}),'Create "',d.trim(),'"â¦']})]}),z.length>0&&e.jsx(ys,{children:z.map(k=>{const se=k.icon;return e.jsxs(ws,{value:`${k.title} ${k.code}`,onSelect:()=>R(k.code),className:"flex items-center gap-2",children:[e.jsx(se,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:k.title}),!k.isOther&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",k.code,")"]}),k.isCustom&&e.jsx(te,{variant:"outline",className:"ml-1 px-1 py-0 text-[10px] font-normal",children:"Custom"}),e.jsx(Is,{className:Q("ml-auto h-4 w-4 shrink-0",t===k.code?"opacity-100":"opacity-0")})]},k.code)})}),n&&e.jsx(ys,{className:"border-t",children:e.jsxs(ws,{value:"__create_document_type__","data-quick-entry-action":"true",onSelect:()=>P(d.trim()),children:[e.jsx(Pt,{className:"mr-2 h-4 w-4"}),"New document typeâ¦"]})})]})})]})})]}),n&&e.jsx(tt,{open:F,onOpenChange:k=>{E(k)},children:e.jsxs(st,{className:"max-w-sm",children:[e.jsx(at,{children:e.jsx(rt,{children:"New document type"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ie,{htmlFor:"doc-type-name",children:"Name"}),e.jsx(ye,{id:"doc-type-name",value:O,onChange:k=>B(k.target.value),placeholder:"e.g. Delivery Order",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ie,{htmlFor:"doc-type-code",children:"Code"}),e.jsx(ye,{id:"doc-type-code",value:G,onChange:k=>{S(!0),D(k.target.value.toUpperCase())},placeholder:"e.g. DO",className:"uppercase"}),oe?e.jsxs("p",{className:"text-xs text-destructive",children:['Code "',ee,'" already exists. Choose another.']}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Short unique code used on documents and forms."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ie,{htmlFor:"doc-type-category",children:"Category"}),e.jsxs(zt,{value:j||Ne,onValueChange:k=>m(k===Ne?"":k),children:[e.jsx(Bt,{id:"doc-type-category",children:e.jsx(Gt,{})}),e.jsxs(qt,{children:[U.map(k=>e.jsx(Be,{value:k,children:k.charAt(0).toUpperCase()+k.slice(1)},k)),e.jsx(Be,{value:Ne,children:"Other"})]})]})]})]}),e.jsxs(Ut,{children:[e.jsx(A,{variant:"outline",onClick:()=>E(!1),disabled:f.isPending,children:"Cancel"}),e.jsx(A,{onClick:W,disabled:!X,children:f.isPending?"Addingâ¦":"Add type"})]})]})})]})}const ea={"application/pdf":[".pdf"],"image/*":[".png",".jpg",".jpeg",".webp"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"],"application/vnd.ms-excel":[".xls",".csv"],"text/csv":[".csv"],"application/csv":[".csv"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":[".docx"],"application/msword":[".doc"],"application/xml":[".xml"],"text/xml":[".xml"],"message/rfc822":[".eml"],"application/vnd.ms-outlook":[".msg"]},ta=Object.entries(ea).flatMap(([t,s])=>[t,...s]).join(",");function Fn({onUpload:t,isUploading:s,variant:a="default",children:r,aiTypeDetectionAvailable:n=!0,storageMode:l,uploadProgress:o}){const{detectTypeFromFilename:p,loading:g}=Ce(),[u,x]=i.useState([]),C=ea,f=ta,b=Rr(l),[c,d]=i.useState(!1),v=u[0]??null,F=async(T,M)=>{await t(T,M),x(R=>R.slice(1))},E=()=>x(T=>T.slice(1)),O=i.useCallback(async T=>{const M=[];for(const R of T){const P=p(R.name),L=R.type==="application/pdf"||R.name.toLowerCase().endsWith(".pdf");P&&P.code!=="other"?await t(R,P.code):L&&n?await t(R,"other"):M.push(R)}M.length>0&&x(R=>[...R,...M])},[t,p,n]),B=i.useCallback(T=>{T.length>0&&O(T)},[O]),G=i.useCallback(T=>{if(T.length!==0){for(const{file:M,errors:R}of T.slice(0,3)){const P=M.name||"File";R.some(L=>L.code===ks.FileInvalidType)?$.error(`"${P}" is not supported. Use PDF, images, Excel, CSV, Word, XML, or email (.eml/.msg).`):R.some(L=>L.code===ks.FileTooLarge)?$.error(`"${P}" is over the ${Math.round((b.maxBytes??0)/(1024*1024))}MB limit.`):$.error(`Could not upload "${P}".`)}T.length>3&&$.error(`${T.length-3} more file(s) were skipped.`)}},[]),D=i.useCallback(async T=>{const M=T;if(Nt(M))return;T.preventDefault(),d(!1);const R=await Ss(M);if(R.length===0){_t(M)&&$.error("Could not read this Gmail/Outlook attachment. Drag it to your desktop first, then onto this zoneâor download from Gmail.");return}const P=[];for(const L of R)Ds(L,f)?b.maxBytes!=null&&L.size>b.maxBytes?$.error(`"${L.name}" is over the ${Math.round(b.maxBytes/(1024*1024))}MB limit.`):P.push(L):$.error(`"${L.name}" is not supported. Use PDF, images, Excel, CSV, or Word.`);P.length>0&&await O(P)},[O,f]),K=i.useCallback(async T=>{var oe;const M=T.target,R=M==null?void 0:M.tagName;if(R==="INPUT"||R==="TEXTAREA"||R==="SELECT"||M!=null&&M.isContentEditable)return;const L=Array.from(((oe=T.clipboardData)==null?void 0:oe.items)??[]).filter(X=>X.kind==="file").map(X=>X.getAsFile()).filter(X=>!!X);if(L.length===0)return;const ee=[];for(const X of L){const W=X.name&&X.name!=="image.png"?X:new File([X],`pasted-${new Date().toISOString().replace(/[:.]/g,"-")}
2.png`,{type:X.type||"image/png"});Ds(W,f)?b.maxBytes!=null&&W.size>b.maxBytes?$.error(`Pasted "${W.name}" is over the ${Math.round(b.maxBytes/(1024*1024))}MB limit.`):ee.push(W):$.error(`Pasted "${W.name}" is not a supported file type.`)}ee.length!==0&&(T.preventDefault(),$.info(`Uploading ${ee.length} pasted file${ee.length===1?"":"s"}â¦`),await O(ee))},[f,b.maxBytes,O]);i.useEffect(()=>{if(s)return;const T=M=>void K(M);return document.addEventListener("paste",T),()=>document.removeEventListener("paste",T)},[K,s]);const S=a==="panel",{getRootProps:j,getInputProps:m,isDragActive:N,open:U}=kr({onDrop:B,onDropRejected:G,noClick:S,noKeyboard:S,getFilesFromEvent:T=>Ss(T),accept:C,maxSize:b.maxBytes??void 0,disabled:s,multiple:!0}),H=j({onDragEnter:T=>{const M=T;_t(M)&&!Nt(M)&&d(!0)},onDragLeave:()=>d(!1),onDragOver:T=>{const M=T;_t(M)&&!Nt(M)&&(T.preventDefault(),T.dataTransfer&&(T.dataTransfer.dropEffect="copy"))},onDrop:D}),z=a==="compact",Y=v&&e.jsx(le,{className:"mt-2 p-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Select document type for:",u.length>1&&e.jsxs("span",{className:"ml-1 font-normal text-muted-foreground",children:["(1 of ",u.length,")"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:v.name})]}),e.jsx(Js,{disabled:g||s,onSelect:T=>void F(v,T),trigger:e.jsxs(A,{variant:"outline",disabled:g||s,children:["Select Type",e.jsx(Ve,{className:"ml-2 h-4 w-4"})]})}),e.jsx(A,{variant:"ghost",size:"sm",onClick:E,disabled:s,children:u.length>1?"Skip":"Cancel"})]})});return S?e.jsxs("div",{...H,className:Q("relative flex min-h-0 flex-1 flex-col rounded-md border-2 border-dashed border-transparent transition-colors",(N||c)&&"border-primary bg-primary/5"),children:[e.jsx("input",{...m()}),e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b px-2 py-1.5 text-xs text-muted-foreground",children:s?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 shrink-0 animate-pulse"}),e.jsxs("span",{className:"truncate",children:["Uploading",typeof o=="number"?` ${Math.round(o*100)}%`:"â¦"]}),typeof o=="number"&&e.jsx("div",{className:"h-0.5 min-w-[60px] flex-1 overflow-hidden rounded bg-muted",children:e.jsx("div",{className:"h-full rounded bg-primary transition-all",style:{width:`${Math.round(o*100)}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:N||c?"Drop documents anywhere in this list":"Drop files anywhere here, or paste with Ctrl+V"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"ml-auto h-6 shrink-0 px-2 text-xs",onClick:U,disabled:s,children:"Browse"})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:r}),(N||c)&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-md bg-primary/10 backdrop-blur-[1px]",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-background px-3 py-1.5 shadow",children:[e.jsx(Ee,{className:"h-4 w-4"}),e.jsxs("span",{className:"text-sm font-medium",children:["Drop to upload (",b.hint,")"]})]})}),Y]}):e.jsxs(e.Fragment,{children:[e.jsx(le,{...H,className:Q("border-2 border-dashed transition-colors cursor-pointer hover:border-primary",(N||c)&&"border-primary bg-primary/5",s&&"opacity-50 cursor-not-allowed"),children:e.jsxs("div",{className:Q("text-center",z?"p-2.5":"p-8"),children:[e.jsx("input",{...m()}),e.jsx("div",{className:Q("flex items-center gap-3",z?"flex-row justify-center":"flex-col"),children:s?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:Q("text-muted-foreground animate-pulse",z?"h-5 w-5":"h-12 w-12")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Uploading",typeof o=="number"?` ${Math.round(o*100)}%`:"..."]}),typeof o=="number"&&e.jsx("div",{className:"mt-1.5 h-0.5 w-full max-w-[220px] overflow-hidden rounded bg-muted",children:e.jsx("div",{className:"h-full rounded bg-primary transition-all",style:{width:`${Math.round(o*100)}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:Q("text-muted-foreground",z?"h-5 w-5":"h-12 w-12")}),e.jsxs("div",{className:z?"":"text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:N||c?"Drop documents here":z?"Drop files here or click to upload":"Drag & drop documents here"}),z&&e.jsx("p",{className:"text-xs text-muted-foreground",children:b.hint}),!z&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["or click to browse ⢠select or drop several at once ⢠drag attachments from Gmail or Outlook (",b.hint,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:n?"Document type will be auto-detected using AI":"AI is unavailable â you'll be asked to pick a type for each file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Some browsers (e.g. Safari with desktop Outlook) may still require saving the file first"})]})]})]})})]})}),Y]})}const sa={pdf:{icon:pe,tint:"bg-red-100 text-red-600 dark:bg-red-950/50 dark:text-red-400",label:"PDF"},excel:{icon:Gr,tint:"bg-green-100 text-green-600 dark:bg-green-950/50 dark:text-green-400",label:"Excel"}
2,word:{icon:pe,tint:"bg-blue-100 text-blue-600 dark:bg-blue-950/50 dark:text-blue-400",label:"Word"},image:{icon:Br,tint:"bg-purple-100 text-purple-600 dark:bg-purple-950/50 dark:text-purple-400",label:"Image"},xml:{icon:pe,tint:"bg-amber-100 text-amber-700 dark:bg-amber-950/50 dark:text-amber-400",label:"XML"},email:{icon:pe,tint:"bg-sky-100 text-sky-700 dark:bg-sky-950/50 dark:text-sky-400",label:"Email"},other:{icon:Ot,tint:"bg-slate-100 text-slate-600 dark:bg-slate-800/50 dark:text-slate-400",label:"File"}};function aa(t,s){const a=(t==null?void 0:t.toLowerCase())??"",r=(s==null?void 0:s.toLowerCase().split(".").pop())??"";return a==="application/pdf"||r==="pdf"?"pdf":a.includes("spreadsheet")||a.includes("ms-excel")||["xlsx","xls","csv"].includes(r)?"excel":a.includes("wordprocessing")||a.includes("msword")||["docx","doc"].includes(r)?"word":a.startsWith("image/")||["png","jpg","jpeg","webp","gif"].includes(r)?"image":a.includes("xml")||r==="xml"?"xml":a==="message/rfc822"||a==="application/vnd.ms-outlook"||["eml","msg"].includes(r)?"email":"other"}function An(t,s){return sa[aa(t,s)].label}function ra({fileName:t,mimeType:s,className:a}){const{icon:r,tint:n}=sa[aa(s,t)];return e.jsx("div",{className:Q("flex h-8 w-8 shrink-0 items-center justify-center rounded-md",n,a),children:e.jsx(r,{className:"h-4 w-4"})})}function na({status:t,showLabel:s=!0,labelClassName:a,className:r}){const n=ls.find(l=>l.value===t);return n?e.jsxs("span",{className:Q("flex items-center gap-1.5",r),children:[e.jsx("span",{className:Q("h-2 w-2 shrink-0 rounded-full",n.dotClass,t==="processing"&&"animate-pulse")}),s&&e.jsx("span",{className:Q("text-xs text-muted-foreground whitespace-nowrap",a),children:n.label})]}):null}function ia(t){return t?t.includes("GEMINI_QUOTA_EXCEEDED")||t.toLowerCase().includes("quota exceeded")||/\b429\b/.test(t):!1}function la(t){return!!t&&t.includes("EMPTY_EXTRACTION")}function Tn(t){if(t<=0)return"soon";if(t<90)return`~${t}s`;const s=Math.ceil(t/60);return s===1?"~1 min":`~${s} min`}function En(t,s=Date.now()){if(!t)return null;const a=Date.parse(t);return Number.isFinite(a)?Math.max(0,Math.ceil((a-s)/1e3)):null}function Ln(t){var g,u,x;const s=t.retryCount??0,a=5,r=ia(t.error),n=!r&&la(t.error),l=r?"Quota limit":n?"No data read":"AI busy",o=En(t.retryAfter,t.nowMs);if(o!=null&&o>0)return`${l} â retry ${s}/${a} in ${Tn(o)}`;const p=(x=(u=(g=t.summary)==null?void 0:g.match(/retry \d+\/\d+[^â¦]*/i))==null?void 0:u[0])==null?void 0:x.trim();return p?`${l} â ${p}â¦`:`${l} â retry ${s}/${a}â¦`}function oa(t){const[s,a]=i.useState(()=>Date.now()),r=t.ai_extraction_status==="retry_pending";return i.useEffect(()=>{if(!r)return;const n=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(n)},[r,t.gemini_retry_after]),r?Ln({retryCount:t.gemini_retry_count,retryAfter:t.gemini_retry_after,error:t.ai_extraction_error,summary:t.summary,nowMs:s}):null}function it(t,s=40){if(!t||t.length<=s)return t;const a=t.lastIndexOf("."),r=a>0?t.slice(a):"",n=r?t.slice(0,a):t,l=s-r.length-1;if(l<6)return`${t.slice(0,s-1)}â¦`;const o=Math.ceil(l*.55),p=l-o;return`${n.slice(0,o)}â¦${n.slice(-p)}${r}`}function ca(t,s){const a=t.match(/-part(\d+)(\.[^.]+)?$/i);if(a)return`part${a[1]}${a[2]??""}`;if(s!=null&&Number.isFinite(s)){const r=t.includes(".")?t.slice(t.lastIndexOf(".")):".pdf";return`part${s+1}${r}`}return it(t,36)}function da({fullName:t,displayName:s,className:a}){return s===t?e.jsx("span",{className:a,title:t,children:s}):e.jsx(Ke,{children:e.jsxs(Qe,{children:[e.jsx(He,{asChild:!0,children:e.jsx("span",{className:a,children:s})}),e.jsx(Ye,{side:"bottom",className:"max-w-md break-all",children:e.jsx("p",{className:"text-xs",children:t})})]})})}function Mn(t){switch(t.source_type){case"workflow_email":return{icon:ns,label:"From email",tooltip:t.original_email_from?`From: ${t.original_email_from}`:"Received via email service"};case"workflow_api":return{icon:Je,label:"API",tooltip:"Received via API service"};case"generated":return{icon:ve,label:"Generated",tooltip:"Auto-generated document"};case"manual":default:return{icon:Ee,label:"Uploaded",tooltip:"Manually uploaded"}}}function ma({document:t,documentTypeInfo:s,childCount:a}){const r=oa(t),n=t.ai_extraction_status==="retry_pending";if((t.ai_extraction_status==="pending"||t.ai_extraction_status==="processing"||n)&&!t.is_split_parent)return e.jsxs("span",{className:"flex items-center gap-1.5 text-muted-foreground min-w-0",children:[n?e.jsx(Xs,{className:"h-3 w-3 shrink-0 text-amber-600"}):e.jsx(J,{className:"h-3 w-3 shrink-0 animate-spin"}),e.jsx("span",{className:"truncate",children:n?r??`AI busy â retry ${t.gemini_retry_count??0}/5â¦`:t.ai_extraction_status==="pending"?"Detecting type...":t.document_type?"Extracting data...":"Detecting type..."})]});if(t.is_split_parent){const o=it(t.file_name,32);return e.jsx("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:e.jsx(da,{fullName:t.file_name,displayName:o,className:"min-w-0 truncate"})})}return t.parent_document_id&&t.page_start!=null&&t.page_end!=null?e.jsx("span",{className:"flex items-center gap-1.5 min-w-0",children:e.jsx("span",{className:"truncate",children:(s==null?void 0:s.title)||t.document_type||"Segment"})}):e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"truncate",children:(s==null?void 0:s.title)||t.document_type||"Document"}),((s==null?void 0:s.edoc_code)||t.document_type)&&e.jsx(te,{variant:"outline",className:"text-[10px] px-1 py-0 font-normal shrink-0",children:(s==null?void 0:s.edoc_code)||t.document_type})]})}function ua({document:t,childCount:s}){return t.is_split_parent?e.jsxs(e.Fragment,{children:[e.jsx(te,{variant:"secondary",className:"shrink-0 px-1 py-0 text-[10px] font-normal",children:"Original upload"}),(s??0)>0&&e.jsxs(te,{variant:"outline",className:"shrink-0 px-1 py-0 text-[10px] font-normal",children:[s," segment",s===1?"":"s"]})]}):t.parent_document_id&&t.page_start!=null&&t.page_end!=null?e.jsxs(te,{variant:"outline",className:"shrink-0 px-1 py-0 text-[10px] font-normal",children:["p.",t.page_start,"â",t.page_end]}):null}function $n(t){const s=t.ai_extraction_status;return s==="type_detected"?{label:"Start extraction",kind:"start"}:s==="failed"||s==="retry_pending"?{label:"Retry extraction",kind:"retry"}:t.status==="error"?{label:"Retry extraction",kind:"retry"}:null}function pa({document:t,canDelete:s,onDelete:a,onDownload:r,onStartExtraction:n,onRetryExtraction:l,className:o}){const[p,g]=i.useState(!1),u=$n(t),x=(u==null?void 0:u.kind)==="start"?n:l,C=!!u&&!!x;return!r&&!C&&!(s&&a)?null:e.jsxs(e.Fragment,{children:[e.jsxs(Kt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsx(A,{variant:"ghost",size:"icon",className:Q("h-7 w-7 shrink-0",o),onClick:f=>f.stopPropagation(),"aria-label":"Document actions",children:e.jsx(qr,{className:"h-4 w-4"})})}),e.jsxs(Ht,{align:"end",onClick:f=>f.stopPropagation(),children:[C&&u&&e.jsxs(wt,{onClick:()=>x==null?void 0:x(t.id),children:[e.jsx(ve,{className:"h-4 w-4 mr-2"}),u.label]}),r&&e.jsxs(wt,{onClick:()=>r(t),children:[e.jsx(nt,{className:"h-4 w-4 mr-2"}),"Download"]}),s&&a&&e.jsxs(wt,{className:"text-destructive focus:text-destructive",onClick:()=>g(!0),children:[e.jsx(rs,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]}),s&&a&&e.jsx(Yt,{open:p,onOpenChange:g,children:e.jsxs(Xt,{onClick:f=>f.stopPropagation(),children:[e.jsxs(Zt,{children:[e.jsx(Jt,{children:"Delete Document"}),e.jsxs(es,{children:['Are you sure you want to delete "',t.file_name,'"? This will permanently remove the file and cannot be undone.']})]}),e.jsxs(ts,{children:[e.jsx(ss,{children:"Cancel"}),e.jsx(as,{onClick:()=>a(t.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function On({document:t,documentTypeInfo:s,isSelected:a,onClick:r,indentLevel:n=0,childCount:l,isCollapsed:o,onToggleCollapse:p,c
2anDelete:g,onDelete:u,onDownload:x,onStartExtraction:C,onRetryExtraction:f,aiFuelAvailable:b=!1,density:c="regular"}){const{formatDate:d,formatShortDate:v}=Ys(),F=c==="compact",E=Mn(t),O=E.icon,G=!!t.is_split_parent&&typeof p=="function"&&(l??0)>0,D=Hs(t.ai_extraction_error,{fuelAvailable:b}),K=Sr(t),S=(D==null?void 0:D.text)||K,j=t.parent_document_id?ca(t.file_name,t.split_segment_index):it(t.file_name,36);return e.jsxs("div",{className:Q("group flex cursor-pointer items-center gap-2.5 overflow-hidden rounded-md px-2 py-2 transition-colors hover:bg-accent",a&&"bg-accent ring-1 ring-primary/40",n>0&&"ml-6 border-l-2 border-l-primary/30 pl-2"),onClick:r,children:[G?e.jsx("button",{type:"button","aria-label":o?"Expand bundle segments":"Collapse bundle segments","aria-expanded":!o,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:m=>{m.stopPropagation(),p(t.id)},children:o?e.jsx(zs,{className:"h-4 w-4"}):e.jsx(Ve,{className:"h-4 w-4"})}):e.jsx(ra,{fileName:t.file_name,mimeType:t.mime_type}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:Q("font-medium",F?"text-xs":"text-sm"),children:e.jsx(ma,{document:t,documentTypeInfo:s,childCount:l})}),S?e.jsx(Ke,{children:e.jsxs(Qe,{children:[e.jsx(He,{asChild:!0,children:e.jsx("p",{className:Q("truncate text-xs",(D==null?void 0:D.kind)==="paused"||K&&!D?"text-amber-600 dark:text-amber-500":"text-destructive/90"),title:D!=null&&D.humanized?D.raw:void 0,children:S})}),e.jsx(Ye,{side:"bottom",className:"max-w-sm",children:e.jsx("p",{className:"text-xs",children:S})})]})}):e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden text-xs text-muted-foreground",children:[!t.is_split_parent&&e.jsx(da,{fullName:t.file_name,displayName:j,className:"min-w-0 truncate"}),e.jsx(ua,{document:t,childCount:l}),e.jsx(Ke,{children:e.jsxs(Qe,{children:[e.jsx(He,{asChild:!0,children:e.jsx(O,{className:"h-3 w-3 shrink-0"})}),e.jsx(Ye,{side:"top",children:e.jsx("p",{className:"text-xs",children:E.tooltip})})]})})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 pl-1",children:[!F&&Tt(t.storage_location)&&e.jsx(te,{variant:"outline",className:"whitespace-nowrap text-[10px] text-muted-foreground",children:"Awaiting transfer"}),e.jsx(na,{status:t.status,showLabel:!F}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",title:F?d(t.created_at):void 0,children:v(t.created_at,{withYear:!F})}),e.jsx(pa,{document:t,canDelete:g,onDelete:u,onDownload:x,onStartExtraction:C,onRetryExtraction:f,className:"opacity-0 group-hover:opacity-100 focus-within:opacity-100 data-[state=open]:opacity-100"})]})]})}function Pn({document:t,documentTypeInfo:s,isSelected:a,onClick:r,childCount:n,canDelete:l,onDelete:o,onDownload:p}){const{formatDate:g,formatShortDate:u}=Ys();return e.jsxs("div",{className:Q("group flex cursor-pointer flex-col gap-2 rounded-lg border p-3 transition-colors hover:bg-accent",a&&"bg-accent ring-1 ring-primary/40"),onClick:r,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(ra,{fileName:t.file_name,mimeType:t.mime_type}),e.jsx(pa,{document:t,canDelete:l,onDelete:o,onDownload:p,className:"opacity-0 group-hover:opacity-100 focus-within:opacity-100 data-[state=open]:opacity-100"})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:e.jsx(ma,{document:t,documentTypeInfo:s,childCount:n})}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",title:t.file_name,children:t.parent_document_id?ca(t.file_name,t.split_segment_index):it(t.file_name,36)}),e.jsx("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:e.jsx(ua,{document:t,childCount:n})})]}),e.jsxs("div",{className:"mt-auto flex items-center justify-between gap-2",children:[e.jsx(na,{status:t.status}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",title:g(t.created_at),children:u(t.created_at,{withYear:!1})})]})]})}const Rn={missing:{text:"Missing",className:"border-amber-500/40 text-amber-600 dar
2k:text-amber-500"},optional:{text:"Optional",className:"text-muted-foreground"},waived:{text:"Not required",className:"text-muted-foreground"}};function Ms({layout:t,label:s,status:a,uploadCode:r,isUploading:n,onUpload:l,onGenerate:o,onWaive:p,onRestore:g,density:u="regular",statusHint:x}){const C=i.useRef(null),f=Rn[a],b=a==="missing",c=u==="regular",d=B=>{var D;const G=(D=B.target.files)==null?void 0:D[0];B.target.value="",G&&l(G,r)},v=e.jsx("span",{className:Q("h-4 w-4 shrink-0 rounded-full border-2",b?"border-amber-500":"border-muted-foreground/40"),"aria-hidden":!0}),F=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:C,type:"file",accept:ta,className:"hidden",onChange:d}),e.jsxs(A,{variant:"ghost",size:"sm",className:"h-7 shrink-0 px-2",disabled:n,onClick:()=>{var B;return(B=C.current)==null?void 0:B.click()},title:"Upload",children:[e.jsx(Ee,{className:"h-3.5 w-3.5"}),c&&e.jsx("span",{className:"ml-1.5",children:"Upload"})]}),o&&e.jsxs(A,{variant:"ghost",size:"sm",className:"h-7 shrink-0 px-2",onClick:o,title:"Generate",children:[e.jsx(pe,{className:"h-3.5 w-3.5"}),c&&e.jsx("span",{className:"ml-1.5",children:"Generate"})]}),p&&e.jsxs(A,{variant:"ghost",size:"sm",className:"h-7 shrink-0 px-2 text-muted-foreground",onClick:p,title:"Mark as not required",children:[e.jsx(Ur,{className:"h-3.5 w-3.5"}),c&&e.jsx("span",{className:"ml-1.5",children:"Not required"})]}),g&&e.jsxs(A,{variant:"ghost",size:"sm",className:"h-7 shrink-0 px-2 text-muted-foreground",onClick:g,title:"Restore requirement",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),c&&e.jsx("span",{className:"ml-1.5",children:"Restore"})]})]}),E=e.jsx("span",{className:Q("block truncate text-sm",a==="missing"?"text-foreground":"text-muted-foreground",a==="waived"&&"line-through"),title:s,children:s}),O=e.jsx(te,{variant:"outline",className:Q("shrink-0 px-1.5 py-0 text-[10px] font-normal",f.className),title:x,children:x&&a==="optional"?"Not needed here":f.text});return t==="tile"?e.jsxs("div",{className:Q("flex flex-col gap-2 rounded-lg border border-dashed p-3",b&&"border-amber-500/40 bg-amber-50/40 dark:bg-amber-950/10"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[v,O]}),e.jsx("div",{className:"min-w-0",children:E}),e.jsx("div",{className:"flex items-center gap-1",children:F})]}):e.jsxs("div",{className:Q("flex items-center gap-2.5 overflow-hidden rounded-md border border-dashed px-2 py-2",b?"border-amber-500/40 bg-amber-50/40 dark:bg-amber-950/10":"border-transparent"),children:[v,e.jsx("div",{className:"min-w-0 flex-1",children:E}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1 pl-1",children:[O,F]})]})}function In({listItems:t,requirementActions:s,density:a="regular",selectedDocumentId:r,onSelectDocument:n,onToggleBundleCollapsed:l,viewMode:o="list",canDelete:p,onDeleteDocument:g,onDownloadDocument:u,onStartExtraction:x,onRetryExtraction:C,aiFuelAvailable:f=!1}){const{getDocumentTypeByCode:b}=Ce();if(t.length===0)return e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsx("p",{className:"text-sm",children:"No documents found"})});const c=d=>({label:d.requirement.label||d.requirement.code,status:d.status,statusHint:d.requirement.notRequiredReason,uploadCode:d.uploadCode,isUploading:s==null?void 0:s.isUploading,density:a,onUpload:(s==null?void 0:s.onUpload)??(()=>{}),onGenerate:d.canGenerate&&s?()=>s.onGenerate(d):void 0,onWaive:s!=null&&s.canWaive&&d.status==="missing"?()=>s.onWaive(d):void 0,onRestore:s!=null&&s.canWaive&&d.status==="waived"?()=>s.onRestore(d):void 0});return o==="grid"?e.jsx(Et,{className:"h-full min-h-0",children:e.jsx("div",{className:"grid grid-cols-2 gap-2 p-1",children:t.map(d=>d.kind==="requirement"?e.jsx(Ms,{layout:"tile",...c(d)},d.key):e.jsx(Pn,{document:d.document,documentTypeInfo:b(d.document.document_type),isSelected:d.document.id===r,onClick:()=>n(d.document.id),childCount:d.childCount,canDelete:p,onDelete:g,onDownload:u},d.key))})}):e.jsx(Et,{className:"h-full min-h-0",children:e.jsx("div",{className:"space-y-0.5 p-1",children:t.map(d=>d.kind==="requirement"?e.jsx(Ms,{layout:"row",...c(d)},d.key):e.jsx(On,{document:d.document,documentTypeInfo:b(d.document.document_type),isSelected:d.document.id===r,onClick:()=>n(d.document.id),indentLevel:d.indentLevel,childCount:d.childCount,isCollapsed:d.isCollapsed,density:a,onToggleCollapse:l,canDelete:p,onDelete:g,onDownload:u,onStartExtraction:x,onRetryExtraction:C,aiFuelAvailable:f},d.key))})})}const zn=620;function Bn(t){return!Number.isFinite(t)||t<=0?"regular":t<zn?"compact":"regular"}function Gn(t){const[s,a]=i.useState("regular"),r=i.useRef("regular"),n=l=>{const o=Bn(l);o!==r.current&&(r.current=o,a(o))};return i.useLayoutEffect(()=>{const l=t.current;l&&n(l.getBoundingClientRect().width)}),i.useEffect(()=>{const l=t.current;if(!l||typeof ResizeObserver>"u")return;const o=new ResizeObserver(p=>{const g=p[0];g&&n(g.contentRect.width)});return o.observe(l),()=>o.disconnect()},[t]),s}const St={newest:"Newest first",oldest:"Oldest first",name:"Name AâZ",type:"Type"};function qn({documentCount:t,extractionFuel:s,listItems:a,requirementActions:r,selectedDocumentId:n,onSelectDocument:l,onToggleBundleCollapsed:o,onSearch:p,selectedTypes:g,onTypesChange:u,selectedStatuses:x,onStatusesChange:C,selectedStakeholders:f,onStakeholdersChange:b,sortBy:c,onSortChange:d,viewMode:v,onViewModeChange:F,onUpload:E,isUploading:O,canCreate:B,canDelete:G,onDeleteDocument:D,onDownloadDocument:K,onStartExtraction:S,onRetryExtraction:j,onOpenGenerateDialog:m,isGenerating:N,onDownloadAll:U,isDownloadingAll:H,fuelPausedCount:z,aiFuelAvailable:Y,onExtractPaused:T,isExtractingPaused:M,aiTypeDetectionAvailable:R,storageMode:P,uploadProgress:L}){const ee=i.useRef(null),oe=Gn(ee),X=e.jsx(In,{listItems:a,requirementActions:r,density:oe,selectedDocumentId:n,onSelectDocument:l,onToggleBundleCollapsed:o,viewMode:v,canDelete:G,onDeleteDocument:D,onDownloadDocument:K,onStartExtraction:S,onRetryExtraction:j,aiFuelAvailable:Y});return e.jsxs(le,{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 px-4 pb-2 pt-3",children:[e.jsxs(Xe,{className:"text-sm",children:["Documents (",t,")"]}),s!==void 0&&s>0&&e.jsxs(te,{variant:"outline",className:"h-5 shrink-0 gap-1 px-1.5 text-[10px] font-normal text-muted-foreground",title:"AI Fuel used extracting this job's documents",children:[e.jsx(Ze,{className:"h-3 w-3"}),yr(s)," Fuel"]})]}),e.jsx("div",{className:"shrink-0 px-4 pb-2",children:e.jsx(Dn,{onSearch:p})}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 px-4 pb-2",children:[e.jsx(Sn,{selectedTypes:g,onTypesChange:u,selectedStatuses:x,onStatusesChange:C,selectedStakeholders:f,onStakeholdersChange:b}),e.jsxs(Kt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsxs(A,{variant:"outline",size:"sm",children:[e.jsx(Vr,{className:"h-4 w-4 mr-2"}),St[c]]})}),e.jsx(Ht,{align:"start",children:e.jsx(br,{value:c,onValueChange:W=>d(W),children:Object.keys(St).map(W=>e.jsx(vr,{value:W,children:St[W]},W))})})]}),B&&e.jsxs(A,{size:"sm",onClick:m,disabled:N,children:[e.jsx(pe,{className:"h-4 w-4 mr-2"}),N?"Generating...":"Generate"]}),U&&t>0&&e.jsxs(A,{variant:"outline",size:"sm",onClick:U,disabled:H,children:[e.jsx(nt,{className:"h-4 w-4 mr-2"}),H?"Preparing...":"Download all"]}),e.jsxs(xr,{type:"single",size:"sm",className:"ml-auto",value:v,onValueChange:W=>{W&&F(W)},children:[e.jsx(_s,{value:"list","aria-label":"List view",className:"h-8 w-8 p-0",children:e.jsx(Kr,{className:"h-4 w-4"})}),e.jsx(_s,{value:"grid","aria-label":"Grid view",className:"h-8 w-8 p-0",children:e.jsx(Qr,{className:"h-4 w-4"})})]})]}),(()=>{const W=wr(z,Y);if(W==="hidden")return null;const xe=`${z} document${z===1?" is":"s are"} waiting to be extracted.`;return e.jsx("div",{className:"shrink-0 px-4 pb-2",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50/60 p-2.5 dark:border-amber-900 dark:bg-amber-950/20",children:[e.jsx(Ze,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs font-medium",children:W==="out_of_fuel"?"AI extraction paused â out of AI Fuel":"AI extraction paused â Fuel available"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W==="out_of_fuel"?e.jsxs(e.Fragment,{children:["Uploading still works and every file is stored â you'll be asked to pick each document's type instead of AI detecting it."," ",xe]}):e.jsxs(e.Fragment,{children:["Extra Fuel has been added. Uploaded files are stored â run extraction to continue."," ",xe]})})]}),W==="out_of_fuel"?e.jsx(A,{variant:"outline",size:"sm",className:"h-7 shrink-0",onClick:Bs,children:"Top up"}):T&&e.jsx(A,{variant:"outline",size:"sm",className:"h-7 shrink-0",onClick:T,disabled:M,children:M?"Extractingâ¦":"Extract now"})]})})})(),e.jsx("div",{ref:ee,className:"flex min-h-0 flex-1 flex-col px-2 pb-2",children:B?e.jsx(Fn,{onUpload:E,isUploading:O,storageMode:P,uploadProgress:L,variant:"panel",aiTypeDetectionAvailable:R,children:X}):X})]})}const Un="shipment-documents";function xa(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function Wn(t){var s;return((s=Jr(t))==null?void 0:s.label)??xa(t)}function Vn(t){return xa(t)}function Kn({shipmentId:t,className:s}){const{documents:a,isLoading:r}=Hr(t,{types:Zr}),[n,l]=i.useState(null);if(!t||!r&&a.length===0)return null;const o=async p=>{l(p.id);try{const{data:g,error:u}=await _e.storage.from(Un).createSignedUrl(p.file_path,3600);if(u||!(g!=null&&g.signedUrl))throw u??new Error("No download link");window.open(g.signedUrl,"_blank","noopener")}catch(g){$.error("Only the uploader can open this file from here",{description:`Ask whoever attached "${p.name}" to the organisation to share it, or open it from the organisation record.`}),console.warn("[OrganizationDocumentsGroup] signed URL failed:",g)}finally{l(null)}};return e.jsxs("div",{className:Q("rounded-md border bg-muted/20",s),"data-testid":"organization-documents-group",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-1.5",children:[e.jsx(en,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-xs font-medium",children:"From organisation"}),r?e.jsx(J,{className:"h-3 w-3 animate-spin text-muted-foreground"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:a.length})]}),a.length>0&&e.jsx("ul",{className:"divide-y",children:a.map(p=>e.jsxs("li",{className:"flex items-center gap-2 px-3 py-1.5",children:[e.jsx(pe,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-sm",title:p.file_name,children:p.name}),p.verified&&e.jsx(tn,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600","aria-label":"Verified","data-verified":"true"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Wn(p.document_type)," · ",p.organizationName||"Organisation"," (",Vn(p.partyRole),")"]}
2),e.jsx(Yr,{validity:p.validity,expiresAt:p.effectiveExpiresAt,derived:Xr(p)}),p.verified&&p.verified_at&&e.jsxs("span",{title:`Verified ${Lt(p.verified_at)}`,children:["· verified ",Lt(p.verified_at)]})]})]}),e.jsx(A,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",title:"Open",disabled:n===p.id,onClick:()=>void o(p),children:n===p.id?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(nt,{className:"h-3.5 w-3.5"})})]},`${p.organizationId}:${p.id}`))})]})}function Ft(t){return t.toLocaleString("en-AU",{minimumFractionDigits:2,maximumFractionDigits:2})}function Qn(t){const s=t.currency?`${t.currency} `:"",a=t.invoiceNumber?`Invoice ${t.invoiceNumber}`:"The invoice",r=t.lineCount===1?"the 1 line read from it adds up":`the ${t.lineCount} lines read from it add up`,n=t.charges>0?` (${s}${Ft(t.statedTotal-t.charges)} after charges)`:"";return`${a} totals ${s}${Ft(t.statedTotal)}${n} but ${r} to ${s}${Ft(t.lineSum)}`}function Hn(t){const s=t==null?void 0:t.line_shortfalls;return Array.isArray(s)?s.filter(a=>!!a&&typeof a=="object"&&typeof a.statedTotal=="number"&&typeof a.lineSum=="number"&&typeof a.lineCount=="number").map(a=>({invoiceNumber:typeof a.invoiceNumber=="string"?a.invoiceNumber:null,statedTotal:a.statedTotal,charges:typeof a.charges=="number"?a.charges:0,lineSum:a.lineSum,lineCount:a.lineCount,currency:typeof a.currency=="string"?a.currency:null})):[]}const It=80;function Yn(t){const s=t.trim();if(s.startsWith("[")&&s.endsWith("]")||s.startsWith("{")&&s.endsWith("}"))try{const a=JSON.parse(s);if(Array.isArray(a))return{kind:"array",raw:t,parsed:a};if(a!==null&&typeof a=="object")return{kind:"object",raw:t,parsed:a}}catch{}return{kind:"primitive",raw:t}}function Xn(t){if(t.kind==="array"){const s=t.parsed.length;if(s===0)return"Empty array";const a=t.parsed[0];if(a!==null&&typeof a=="object"&&!Array.isArray(a)){const r=Object.keys(a),n=r.slice(0,4).join(", ");return`Array (${s} item${s===1?"":"s"}) · ${n}${r.length>4?"â¦":""}`}return`Array (${s} item${s===1?"":"s"})`}if(t.kind==="object"){const s=Object.keys(t.parsed),a=s.slice(0,4).join(", ");return`Object (${s.length} key${s.length===1?"":"s"}) · ${a}${s.length>4?"â¦":""}`}return t.raw.length<=It?t.raw:`${t.raw.slice(0,It)}â¦`}function Zn(t){return t.kind==="array"||t.kind==="object"?JSON.stringify(t.parsed,null,2):t.raw}function Jn(t){return t.kind==="array"||t.kind==="object"?!0:t.raw.length>It}function ei({documentId:t,extractionResult:s,confidenceScore:a,aiDetectedType:r,aiTypeConfidence:n,aiTypeReasoning:l,aiExtractionStatus:o,aiExtractionError:p,geminiRetryCount:g,geminiRetryAfter:u,isVerified:x,onVerify:C,onApplyToShipment:f,onRetryExtraction:b,isRetrying:c,onStartExtraction:d,isStartingExtraction:v,isApplyingToShipment:F,appliedToShipment:E,extractionApplied:O,appliedAt:B,canEdit:G=!0,aiExtractionAvailable:D=!0,aiFuelAvailable:K=!1,isExtractableDocument:S=!1}){const j=oa({ai_extraction_status:o,gemini_retry_count:g,gemini_retry_after:u,ai_extraction_error:p}),[m,N]=i.useState(!0),[U,H]=i.useState(null),[z,Y]=i.useState({}),[T,M]=i.useState(!1),[R,P]=i.useState({}),L=_=>{P(Z=>({...Z,[_]:!Z[_]}))};if(o==="split_bundle")return e.jsx(le,{className:"border-dashed",children:e.jsxs(be,{className:"py-4 space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground",children:"PDF bundle"}),e.jsx("p",{children:"This document row is the original upload. Open a segment in the list to view extraction results."})]})});if(o==="processing"||o==="pending"){const _=!r,Z=_?"Detecting Document Type":"AI Extraction in Progress",y=_?"Identifying the document type...":"Analyzing document and extracting fields...";return e.jsx(le,{className:"border-dashed border-primary/50",children:e.jsxs(be,{className:"py-6 text-center",children:[e.jsx(J,{className:"h-8 w-8 mx-auto mb-2 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:Z}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y})]})})}if(o==="retry_pending"){const _=g??0,Z=ia(p),y=!Z&&la(p),V=Z?"Gemini API quota or rate limit reached":y?"No fields extracted yet â retrying":"AI models temporarily busy",re=p?p.replace(/^GEMINI_[A-Z_]+:\s*/,""):null;return e.jsx(le,{className:"border-dashed border-amber-200 bg-amber-50/30",children:e.jsxs(be,{className:"py-6 text-center",children:[e.jsx(Xs,{className:"h-8 w-8 mx-auto mb-2 text-amber-600"}),e.jsx("p",{className:"text-sm font-medium",children:V}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j??`Attempt ${_}
2/5 · background retry may run in ~1 minute`}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y?"The AI returned no fields from this document. It is retried automatically (up to 5 attempts) â use Retry Extraction to run it now.":"Gemini is under high demand â automatic retries use exponential backoff (up to ~30 min)."}),re&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 max-w-md mx-auto line-clamp-4",children:re}),D&&G&&b&&e.jsx(A,{variant:"outline",size:"sm",className:"mt-3",onClick:b,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}),"Retrying..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"h-4 w-4 mr-1"}),"Retry Extraction"]})})]})})}if(o==="type_detected")return e.jsx(le,{className:"border-dashed border-blue-200 bg-blue-50/30",children:e.jsxs(be,{className:"py-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"h-5 w-5 text-blue-500"}),e.jsx("span",{className:"font-medium text-sm",children:"Document Type Detected"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(te,{variant:"outline",className:"capitalize",children:(r||"unknown").replace(/_/g," ")}),n!=null&&e.jsxs(te,{variant:n>=.8?"default":"secondary",className:"text-xs",children:[Math.round(n*100),"% confident"]})]}),l&&e.jsx("p",{className:"text-xs text-muted-foreground italic bg-muted/50 p-2 rounded",children:l}),D&&G&&d&&e.jsx(A,{onClick:d,className:"w-full",disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-2 animate-spin"}),"Starting Extraction..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"h-4 w-4 mr-2"}),"Start AI Extraction"]})}),!D&&e.jsxs("p",{className:"text-xs text-muted-foreground rounded-md bg-muted/50 p-2",children:["AI extraction requires an"," ",e.jsx(gt,{to:"/account",className:"text-primary underline font-medium",children:"Autopilot or Fleet Command"})," ","subscription."]})]})});if(o==="failed"){const _=Hs(p,{fuelAvailable:K});return(_==null?void 0:_.kind)==="paused"?e.jsx(le,{className:"border-dashed border-amber-300 bg-amber-50/40 dark:border-amber-900 dark:bg-amber-950/20",children:e.jsxs(be,{className:"py-6 text-center",children:[e.jsx(Ze,{className:"h-8 w-8 mx-auto mb-2 text-amber-600"}),e.jsx("p",{className:"text-sm font-medium",children:"AI extraction paused"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 max-w-md mx-auto",children:K?"Fuel is available. The document is uploaded and stored â run the extraction to continue.":"This workspace is out of AI Fuel. The document is uploaded and stored â top up, then run the extraction."}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[!K&&e.jsxs(A,{size:"sm",onClick:Bs,children:[e.jsx(Ze,{className:"h-4 w-4 mr-1"}),"Top up Fuel"]}),D&&G&&b&&e.jsx(A,{variant:K?"default":"outline",size:"sm",onClick:b,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}),"Retrying..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"h-4 w-4 mr-1"}),"Retry Extraction"]})})]})]})}):e.jsx(le,{className:"border-destructive bg-destructive/5",children:e.jsxs(be,{className:"py-6 text-center",children:[e.jsx(As,{className:"h-8 w-8 mx-auto mb-2 text-destructive"}),e.jsx("p",{className:"text-sm font-medium text-destructive",children:"AI Extraction Failed"}),_&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 max-w-md mx-auto",title:_.humanized?_.raw:void 0,children:_.text}),D&&G&&b&&e.jsx(A,{variant:"outline",size:"sm",className:"mt-3",onClick:b,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}),"Retrying..."]}):"Retry Extraction"}),!D&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-3 max-w-xs mx-auto",children:["Retry requires an"," ",e.jsx(gt,{to:"/account",className:"text-primary underline font-medium",children:"Autopilot or Fleet Command"})," ","plan."]})]})})}if(!s)return D?e.jsx(le,{className:"border-dashed",children:e.jsxs(be,{className:"py-6 text-center text-muted-foreground",children:[e.jsx(ve,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No AI extraction data available"}),e.jsx("p",{className:"text-xs mt-1",children:S?"This file type supports AI extraction â start it below.":"Upload a document to extract data automatically"}),S&&D&&G&&d&&e.jsx(A,{onClick:d,className:"mt-4",disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-2 animate-spin"}),"Starting Extraction..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"h-4 w-4 mr-2"}),"Start AI Extraction"]})})]})}):e.jsx(le,{className:"border-dashed",children:e.jsxs(be,{className:"space-y-3 py-6",children:[e.jsx(ve,{className:"mx-auto h-8 w-8 op
2acity-50 text-muted-foreground"}),e.jsx("p",{className:"text-center text-sm font-medium",children:"AI extraction is not on your current plan"}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"Upgrade to Autopilot or Fleet Command to classify documents and extract shipment fields automatically."}),e.jsx(A,{variant:"outline",size:"sm",className:"w-full",asChild:!0,children:e.jsx(gt,{to:"/account",children:"View subscription plans"})})]})});const ee=_=>_>=.8?"text-green-600":_>=.5?"text-yellow-600":"text-red-600",oe=_=>_>=.8?{variant:"default",label:"High"}:_>=.5?{variant:"secondary",label:"Medium"}:{variant:"destructive",label:"Low"},X=(_,Z)=>{Y(y=>({...y,[_]:Z}))},W=async()=>{M(!0);try{if(f&&s.suggested_shipment_data){const _={...s.suggested_shipment_data};Object.entries(z).forEach(([Z,y])=>{const V=Z.toLowerCase().replace(/ /g,"_");V in _&&(_[V]=y)}),await f(_)}await C(t,!0,z),$.success("Extraction verified and applied to shipment")}catch{$.error("Failed to verify extraction")}finally{M(!1)}},xe=async()=>{M(!0);try{await C(t,!1),$.info("Extraction marked for re-processing")}catch{$.error("Failed to update document")}finally{M(!1)}},k=async()=>{if(f&&s.suggested_shipment_data){const _={...s.suggested_shipment_data};Object.entries(z).forEach(([Z,y])=>{const V=Z.toLowerCase().replace(/ /g,"_");V in _&&(_[V]=y)}),await f(_),$.success("Data applied to shipment fields")}},se=a??s.confidence_score,he=oe(se),Fe=Hn(s);return e.jsxs(le,{className:x?"border-green-200 bg-green-50/30":"",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Xe,{className:"text-sm flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4 text-primary"}),"AI Extraction Results",x&&e.jsxs(te,{variant:"outline",className:"bg-green-100 text-green-700 border-green-300",children:[e.jsx(Ie,{className:"h-3 w-3 mr-1"}),"Verified"]})]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>N(!m),children:m?e.jsx(Ns,{className:"h-4 w-4"}):e.jsx(Ve,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-1 mt-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Confidence"}),e.jsxs("span",{className:ee(se),children:[Math.round(se*100),"%"]})]}),e.jsx(ln,{value:se*100,className:"h-2"}),e.jsxs(te,{variant:he.variant,className:"text-xs",children:[he.label," Confidence"]})]})]}),Fe.length>0&&e.jsx(be,{className:"pt-0 pb-3",children:e.jsx("div",{role:"alert",className:"rounded-md border border-amber-300 bg-amber-50 p-3 text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-100",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(et,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"A line may be missing from this invoice"}),Fe.map((_,Z)=>e.jsxs("p",{className:"text-xs",children:[Qn(_),"."]},Z)),e.jsx("p",{className:"text-xs",children:"It was not applied automatically. Retry the extraction, or apply it below and add the missing line yourself."}),D&&G&&b&&e.jsx(A,{variant:"outline",size:"sm",className:"mt-1 border-amber-400 bg-transparent text-amber-900 hover:bg-amber-100 dark:border-amber-700 dark:text-amber-100 dark:hover:bg-amber-900/40",onClick:b,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}),"Retrying..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"h-4 w-4 mr-1"}),"Retry Extraction"]})})]})]})})}),m&&e.jsxs(be,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{className:"text-xs text-muted-foreground",children:"AI-Detected Document Type"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(te,{variant:"outline",className:"capitalize",children:(r||s.ai_detected_type||s.document_type).replace(/_/g," ")}),(n??s.ai_type_confidence)!==void 0&&e.jsxs(te,{variant:(n??s.ai_type_confidence??0)>=.8?"default":"secondary",className:"text-xs",children:[Math.round((n??s.ai_type_confidence??0)*100),"% confident"]})]}),(l||s.ai_type_reasoning)&&e.jsx("p",{className:"text-xs text-muted-foreground italic bg-muted/50 p-2 rounded",children:l||s.ai_type_reasoning})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ie,{className:"text-xs text-muted-foreground",children:"AI Summary"}),e.jsx("p",{className:"text-sm bg-muted p-2 rounded-md",children:s.summary})]}),e.jsx($t,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ie,{className:"text-xs text-muted-foreground",children:["Extracted Fields (",s.extracted_fields.length,")"]}),e.jsx("div",{className:"space-y-2 max-h-[420px] overflow-y-auto pr-1",children:s.extracted_fields.map((_,Z)=>{const y=`${_.field_name}:${Z}`,V=z[_.field_name]??_.field_value,re=Yn(V),Le=Jn(re),Me=R[y]??!1,lt=Zn(re),we=U===_.field_name,Ge=!x&&_.confidence<.7,ot=we?e.jsxs("div",{className:"flex flex-col gap-1 mt-2",children:[Le?e.jsx(is,{value:V,onChange:ce=>X(_.field_name,ce.target.value),className:"min-h-[120px] text-xs font-mono",autoF
2ocus:!0}):e.jsx(ye,{value:V,onChange:ce=>X(_.field_name,ce.target.value),className:"h-7 text-sm",autoFocus:!0}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(A,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>H(null),children:e.jsx(Is,{className:"h-3 w-3"})}),e.jsx(A,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>{Y(ce=>{const fe={...ce};return delete fe[_.field_name],fe}),H(null)},children:e.jsx(Gs,{className:"h-3 w-3"})})]})]}):Le?e.jsx(qs,{open:Me,onOpenChange:ce=>P(fe=>({...fe,[y]:ce})),children:e.jsxs("div",{className:"mt-1 space-y-1",children:[!Me&&e.jsx(Us,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-left text-xs text-muted-foreground hover:text-foreground break-words w-full",children:Xn(re)})}),e.jsx(Ws,{children:e.jsx("pre",{className:`text-xs font-mono whitespace-pre-wrap break-words rounded border bg-background p-2 overflow-auto max-h-56 ${z[_.field_name]?"line-through text-muted-foreground":""}`,children:lt})})]})}):e.jsx("p",{className:`mt-1 text-xs break-words ${z[_.field_name]?"line-through text-muted-foreground":""}`,children:V});return e.jsxs("div",{className:"flex items-start gap-2 p-2 bg-muted/50 rounded-md text-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-xs text-muted-foreground break-all",children:_.field_name}),e.jsxs(te,{variant:_.confidence>=.7?"default":"secondary",className:"text-[10px] px-1 py-0 shrink-0",children:[Math.round(_.confidence*100),"%"]}),Le&&!we&&e.jsx(A,{variant:"ghost",size:"sm",className:"h-6 px-2 ml-auto shrink-0 text-xs text-muted-foreground",onClick:()=>L(y),children:Me?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3 w-3 mr-1"}),"Collapse"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"h-3 w-3 mr-1"}),"Expand"]})}),Ge&&!we&&e.jsx(A,{size:"icon",variant:"ghost",className:"h-6 w-6 shrink-0",onClick:()=>H(_.field_name),children:e.jsx(on,{className:"h-3 w-3"})})]}),ot,z[_.field_name]&&!we&&e.jsx("pre",{className:"mt-1 text-xs font-mono whitespace-pre-wrap break-words rounded border border-green-200 bg-green-50 p-2 text-green-700 overflow-auto max-h-56",children:z[_.field_name]})]}),_.confidence<.5&&e.jsx(et,{className:"h-4 w-4 text-yellow-500 flex-shrink-0 mt-0.5"})]},y)})})]}),e.jsx($t,{}),O&&!E&&!x&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-primary/30 bg-primary/5 p-2 text-xs text-muted-foreground",children:[e.jsx(J,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-primary"}),"Applying the extracted data to the shipment automaticallyâ¦"]}),G&&!x&&D&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(A,{size:"sm",onClick:W,disabled:T,className:"flex-1",children:[T?e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ie,{className:"h-4 w-4 mr-1"}),"Apply and Verify"]}),e.jsxs(A,{size:"sm",variant:"outline",onClick:xe,disabled:T,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Reject"]})]}),D&&G&&b&&e.jsx(A,{size:"sm",variant:"ghost",onClick:b,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}),"Re-extracting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"h-4 w-4 mr-1"}),x?"Re-extract":"Reparse"]})}),D&&G&&f&&s.suggested_shipment_data&&e.jsxs("div",{className:"space-y-2",children:[E&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 px-3 bg-green-50 border border-green-200 rounded-md",children:[e.jsx(Ie,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm text-green-700 font-medium",children:"Data Applied to Shipment"}),B&&e.jsxs("span",{className:"text-xs text-green-600",children:["(",Lt(B),")"]})]}),e.jsx(A,{size:"sm",variant:E?"outline":"secondary",onClick:k,className:"w-full",disabled:F,children:F?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-1 animate-spin"}),E?"Reapplying...":"Applying to Shipment..."]}):E?e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"h-4 w-4 mr-1"}),"Reapply to Shipment"]}):"Apply to Shipment Fields"})]})]})]})}async function ti(t){if(!t)throw new Error("Missing file path");const{data:s,error:a}=await _e.storage.from("shipment-documents").download(t);if(a||!s)throw a??new Error("Failed to download PDF");const r=await s.arrayBuffer(),{pdf:n}=await cn(r);return n.numPages}function At(){return`seg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function $s({open:t,onOpenChange:s,parent:a,children:r,onSave:n,isSaving:l=!1}){const{documentTypeOptions:o,loading:p}=Ce(),g=r.length===0,u=i.useMemo(()=>{let j=0;for(const m of r)typeof m.page_end=="number"&&m.page_end>j&&(j=m.page_end);return j},[r]),[x,C]=i.useState(null),[f,b]=i.useState(null),[c,d]=i.useState(!1),v=g?x??0:u,[F,E]=i.useState([]);i.useEffect(()=>{t&&(C(null),b(null),E([]))},[t]),i.useEffect(()=>{if(!t||!g)return;let j=!1;const m=a.file_path;if(!m){b("This document has no stored file; cannot load page count.");return}return d(!0),b(null),ti(m).then(N=>{j||C(N)}).catch(N=>{j||b(N instanceof Error?N.message:"Could not load PDF page count.")}).finally(()=>{j||d(!1)}),()=>{j=!0}},[t,g,a.file_path]),i.useEffect(()=>{if(!t)return;if(g){x&&x>0&&F.length===0&&E([{uid:At(),start:1,end:x,document_code:a.document_type||"other"}]);return}const j=[...r].filter(m=>typeof m.page_start=="number"&&typeof m.page_end=="number").sort((m,N)=>(m.split_segment_index??0)-(N.split_segment_index??0)).map(m=>({uid:At(),start:m.page_start,end:m.page_end,document_code:m.document_type||"other"}));E(j)},[t,g,r,x,a.document_type,F.length]);const O=i.useMemo(()=>
2{if(F.length===0)return{valid:!1,message:"Add at least one segment."};if(v<1)return{valid:!1,message:"Could not determine PDF page count."};if(g&&F.length===1&&F[0].start===1&&F[0].end===v)return{valid:!1,message:"Add at least one more segment to split this PDF into multiple documents."};const j=[...F].sort((N,U)=>N.start-U.start);let m=1;for(const N of j){if(!Number.isInteger(N.start)||!Number.isInteger(N.end))return{valid:!1,message:"Page numbers must be whole numbers."};if(N.start<1)return{valid:!1,message:`Segment starts at page ${N.start}; must be >= 1.`};if(N.end>v)return{valid:!1,message:`Segment ends at page ${N.end}; document has only ${v} pages.`};if(N.end<N.start)return{valid:!1,message:`Segment with start ${N.start} ends before it starts (end ${N.end}).`};if(N.start!==m)return{valid:!1,message:`Gap or overlap before page ${N.start}. Segments must be contiguous starting at page 1.`};if(!N.document_code)return{valid:!1,message:"Every segment needs a document type."};m=N.end+1}return m!==v+1?{valid:!1,message:`Segments cover pages 1..${m-1}; document has ${v} pages total.`}:{valid:!0,message:""}},[F,v,g]),B=(j,m)=>{E(N=>N.map(U=>U.uid===j?{...U,...m}:U))},G=j=>{E(m=>m.filter(N=>N.uid!==j))},D=()=>{E(j=>{const m=[...j].sort((z,Y)=>z.start-Y.start),N=m.length>0?m[m.length-1].end:0,U=Math.min(N+1,Math.max(1,v)),H=Math.min(v,U);return[...j,{uid:At(),start:U,end:H,document_code:"other"}]})},K=()=>{if(!O.valid)return;const j=[...F].sort((m,N)=>m.start-N.start).map(m=>({start:m.start,end:m.end,document_code:m.document_code}));n(j)},S=i.useMemo(()=>[...F].sort((j,m)=>j.start-m.start),[F]);return e.jsx(tt,{open:t,onOpenChange:s,children:e.jsxs(st,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(at,{children:[e.jsx(rt,{children:g?"Split into segments":"Edit page ranges"}),e.jsx(Wt,{children:g?e.jsxs(e.Fragment,{children:["Define page ranges for each document inside"," ",e.jsx("span",{className:"font-medium",children:a.file_name}),". Segments must be contiguous and cover all ",v||"?"," pages. Saving converts this upload into a multi-document bundle."]}):e.jsxs(e.Fragment,{children:["Adjust which pages of ",e.jsx("span",{className:"font-medium",children:a.file_name})," belong to each document type. Segments must be contiguous and cover all ",v||"?"," pages. Saving will rebuild every segment and re-run AI extraction on each."]})})]}),g&&c&&e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-sm text-muted-foreground",children:[e.jsx(J,{className:"h-4 w-4 animate-spin"}),"Loading PDF page countâ¦"]}),g&&f&&e.jsxs(jt,{variant:"destructive",className:"mt-3",children:[e.jsx(et,{className:"h-4 w-4"}),e.jsx(bt,{children:f})]}),!g&&e.jsxs(jt,{variant:"default",className:"mt-2",children:[e.jsx(et,{className:"h-4 w-4"}),e.jsx(bt,{children:"Existing extraction results for these segments will be wiped and re-extracted."})]}),(!g||(x??0)>0)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-[80px_80px_1fr_40px] gap-2 text-xs font-medium text-muted-foreground px-1",children:[e.jsx("div",{children:"Start"}),e.jsx("div",{children:"End"}),e.jsx("div",{children:"Document type"}),e.jsx("div",{})]}),S.map(j=>e.jsxs("div",{className:"grid grid-cols-[80px_80px_1fr_40px] gap-2 items-center",children:[e.jsx(ye,{type:"number",min:1,max:v,value:j.start,onChange:m=>B(j.uid,{start:Number(m.target.value)||0})}),e.jsx(ye,{type:"number",min:1,max:v,value:j.end,onChange:m=>B(j.uid,{end:Number(m.target.value)||0})}),e.jsxs(zt,{value:j.document_code,onValueChange:m=>B(j.uid,{document_code:m}),disabled:p,children:[e.jsx(Bt,{children:e.jsx(Gt,{placeholder:"Select type"})}),e.jsxs(qt,{children:[o.map(m=>{const N=m.icon;return e.jsx(Be,{value:m.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:m.label}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",m.value,")"]})]})},m.value)}),e.jsx(Be,{value:"other",children:"Other"})]})]}),e.jsx(A,{variant:"ghost",size:"icon",onClick:()=>G(j.uid),disabled:F.length<=1,"aria-label":"Remove segment",children:e.jsx(rs,{className:"h-4 w-4"})})]},j.uid)),e.jsxs(A,{type:"button",variant:"outline",size:"sm",onClick:D,className:"mt-2",children:[e.jsx(Pt,{className:"h-4 w-4 mr-1"}),"Add segment"]})]}),!O.valid&&e.jsx(jt,{variant:"destructive",className:"mt-3",children:e.jsx(bt,{children:O.message})}),v>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ie,{className:"text-xs text-muted-foreground",children:"Coverage preview"}),e.jsx("div",{className:"mt-1 flex gap-px overflow-hidden rounded-sm border border-border",children:Array.from({length:v},(j,m)=>m+1).map(j=>{const m=S.find(N=>j>=N.start&&j<=N.end);return e.jsx("div",{title:m?`Page ${j} â ${m.document_code}`:`Page ${j} â unassigned`,className:m?"h-4 flex-1 bg-primary/70":"h-4 flex-1 bg-destructive/30"},j)})}),e.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:"Hover a cell to see which segment owns that page."})]})]}),e.jsxs(Ut,{className:"mt-4",children:[e.jsx(A,{variant:"outline",onClick:()=>s(!1),disabled:l,children:"Cancel"}),e.jsx(A,{onClick:K,disabled:!O.valid||l||c||!!f,children:l?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-2 animate-spin"}),"Savingâ¦"]}):g?"Save segments":"Save & re-extract"})]})]})})}const Os={workflow_email:{icon:ns,label:"Received via email service"},workflow_api:{icon:Je,label:"Received via API service"},workflow_form:{icon:Je,label:"Completed on a form link"},generated:{icon:ve,label:"Auto-generated"},manual:{icon:Ee,label:"Manually uploaded"}};function si({document:t}){const s=Os[t.source_type??"manual"]??Os.manual,a=[{key:"uploaded",icon:s.icon,label:"Document added",detail
2:s.label,timestamp:t.created_at}];return t.applied_to_shipment&&t.applied_at&&a.push({key:"applied",icon:dn,label:"Extraction applied to shipment",timestamp:t.applied_at}),t.extraction_verified&&a.push({key:"verified",icon:Ie,label:"Extraction verified",timestamp:null}),t.updated_at&&new Date(t.updated_at).getTime()-new Date(t.created_at).getTime()>6e4&&a.push({key:"updated",icon:mn,label:"Last updated",timestamp:t.updated_at}),a.sort((r,n)=>r.timestamp?n.timestamp?new Date(r.timestamp).getTime()-new Date(n.timestamp).getTime():-1:1),e.jsx("div",{className:"space-y-0",children:a.map((r,n)=>{const l=r.icon,o=n===a.length-1;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted",children:e.jsx(l,{className:"h-3 w-3 text-muted-foreground"})}),!o&&e.jsx("div",{className:"w-px flex-1 bg-border"})]}),e.jsxs("div",{className:o?"pb-1":"pb-4",children:[e.jsx("p",{className:"text-xs font-medium leading-6",children:r.label}),r.detail&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r.detail}),r.timestamp&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Vs(new Date(r.timestamp),"MMM d, yyyy HH:mm")})]})]},r.key)})})}function De({label:t,children:s}){return e.jsxs("div",{className:"flex items-start justify-between gap-3 py-1.5 text-sm",children:[e.jsx("span",{className:"shrink-0 text-muted-foreground",children:t}),e.jsx("span",{className:"min-w-0 text-right font-medium break-words",children:s})]})}function ai({document:t,onUpdate:s,onDelete:a,isDeleting:r,onRetryExtraction:n,isRetrying:l,onStartExtraction:o,isStartingExtraction:p,onApplyToShipment:g,isApplyingToShipment:u,canDelete:x=!0,canEdit:C=!0,aiExtractionAvailable:f=!0,aiFuelAvailable:b=!1,splitChildren:c=[],onUpdateSplitSegments:d,isUpdatingSegments:v,shipmentReference:F,pageCount:E,onDownload:O}){const{getDocumentTypeByCode:B,loading:G}=Ce(),[D,K]=i.useState(""),[S,j]=i.useState([]),[m,N]=i.useState(""),[U,H]=i.useState([]),[z,Y]=i.useState(""),[T,M]=i.useState(!1),[R,P]=i.useState(!1),L=t!=null&&t.document_type?B(t.document_type):null,ee=!!t&&!t.is_split_parent&&!t.parent_document_id&&t.mime_type==="application/pdf"&&C&&!!d;if(i.useEffect(()=>{t&&(K(t.notes||""),j(t.tags||[]),H(t.stakeholder_relevance||[]),Y(t.expiry_date||""))},[t]),!t)return e.jsxs(le,{className:"h-full min-h-0",children:[e.jsx(Mt,{children:e.jsx(Xe,{className:"text-sm",children:"Document Metadata"})}),e.jsx("div",{className:"px-6 pb-6",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a document to edit metadata"})})]});const oe=y=>{s(t.id,{status:y})},X=y=>{s(t.id,{document_type:y})},W=y=>{Y(y),s(t.id,{expiry_date:y||null})},xe=()=>{D!==t.notes&&s(t.id,{notes:D})},k=()=>{if(m.trim()&&!S.includes(m.trim())){const y=[...S,m.trim()];j(y),s(t.id,{tags:y}),N("")}},se=y=>{const V=S.filter(re=>re!==y);j(V),s(t.id,{tags:V})},he=y=>{const V=U.includes(y)?U.filter(re=>re!==y):[...U,y];H(V),s(t.id,{stakeholder_relevance:V})},Fe=(y,V,re)=>{s(y,{extraction_verified:V,verified_at:V?new Date().toISOString():null,status:V?"approved":"pending_review",...re&&Object.keys(re).length>0&&{ai_extraction_corrections:re}})},_=t.file_size>=1024*1024?`${(t.file_size/(1024*1024)).toFixed(1)} MB`:`${(t.file_size/1024).toFixed(1)} KB`,Z=t.source_type==="workflow_email"?"Email Service":t.source_type==="workflow_api"?"API Service":t.source_type==="workflow_form"?"Form Link":t.source_type==="generated"?"Auto-Generated":"Manual Upload";return e.jsxs(le,{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs(Mt,{className:"flex shrink-0 flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Xe,{className:"text-sm",children:"Document Metadata"}),t&&a&&x&&e.jsxs(Yt,{children:[e.jsx(zr,{asChild:!0,children:e.jsx(A,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(rs,{className:"h-4 w-4"})})}),e.jsxs(Xt,{children:[e.jsxs(Zt,{children:[e.jsx(Jt,{children:"Delete Document"}),e.jsxs(es,{children:['Are you sure you want to delete "',t.file_name,'"? This will permanently remove the file and cannot be undone.']})]}),e.jsxs(ts,{children:[e.jsx(ss,{children:"Cancel"}),e.jsx(as,{onClick:()=>a(t.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:r,children:r?"Deleting...":"Delete"})]})]})]})]}),e.jsxs(rn,{defaultValue:"basic",className:"flex min-h-0 flex-1 flex-col",children:[e.jsxs(nn,{className:"mx-4 grid shrink-0 grid-cols-3",children:[e.jsx(kt,{value:"basic",className:"text-xs",children:"Basic Info"}),e.jsx(kt,{value:"extraction",className:"text-xs",children:"AI Extraction"}),e.jsx(kt,{value:"activity",className:"text-xs",children:"Activity"})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-3 pt-3",children:[e.jsxs(Dt,{value:"basic",className:"mt-0 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{children:"Document Type"}),!t.is_split_parent&&(L==null?void 0:L.ai_verification_instructions)&&e.jsx(Ke,{children:e.jsxs(Qe,{children:[e.jsx(He,{children:e.jsx(un,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs(Ye,{side:"left",className:"max-w-sm",children:[e.jsx("p",{className:"text-xs font-medium mb-1",children:"AI Verification Instru
2ctions:"}),e.jsx("p",{className:"text-xs",children:L.ai_verification_instructions})]})]})})]}),t.is_split_parent?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted/50",children:[e.jsx(Ts,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["PDF bundle",c.length>0?` · ${c.length} segments`:""]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Each segment has its own document type. Select a segment below to edit its type."})]}):t.ai_extraction_status==="pending"||t.ai_extraction_status==="processing"||t.ai_extraction_status==="retry_pending"?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted/50",children:[e.jsx(J,{className:"h-4 w-4 animate-spin text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is detecting document type..."})]}):e.jsx(Js,{value:t.document_type,onSelect:X,disabled:G||!C,allowCreate:C}),!t.is_split_parent&&(L==null?void 0:L.required_for)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Required for: ",L.required_for]}),ee&&e.jsxs(e.Fragment,{children:[e.jsx(A,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-2 animate-spin"}),"Splittingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"h-4 w-4 mr-2"}),"Split into segments"]})}),e.jsx($s,{open:R,onOpenChange:P,parent:t,children:[],onSave:y=>{d==null||d({documentId:t.id,segments:y}),P(!1)},isSaving:!!v})]})]}),e.jsxs("div",{className:"rounded-md border px-3 py-1",children:[L&&e.jsxs(De,{label:"Document Code",children:[L.name,L.edoc_code?` (${L.edoc_code})`:""]}),F&&e.jsx(De,{label:"Linked Shipment",children:e.jsx("span",{className:"text-primary",children:F})}),e.jsx(De,{label:"Source",children:Z}),e.jsx(De,{label:"Uploaded Date",children:Vs(new Date(t.created_at),"MMM d, yyyy HH:mm")}),e.jsx(De,{label:"File Type",children:An(t.mime_type,t.file_name)}),e.jsx(De,{label:"File Size",children:_}),E!=null&&e.jsx(De,{label:"Pages",children:E})]}),(t.original_email_from||t.original_email_subject)&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[t.source_type==="workflow_email"&&e.jsx(ns,{className:"h-4 w-4 text-primary"}),t.source_type==="workflow_api"&&e.jsx(Je,{className:"h-4 w-4 text-primary"}),t.source_type==="generated"&&e.jsx(ve,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:Z})]}),t.original_email_from&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"From:"})," ",t.original_email_from]}),t.original_email_subject&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",t.original_email_subject]})]}),!t.is_split_parent&&t.ai_extraction_status!=="pending"&&t.ai_extraction_status!=="processing"&&t.ai_extraction_status!=="retry_pending"&&(L==null?void 0:L.required_fields)&&L.required_fields.length>0&&e.jsxs(qs,{open:T,onOpenChange:M,children:[e.jsx(Us,{asChild:!0,children:e.jsxs(A,{variant:"outline",size:"sm",className:"w-full justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"h-4 w-4"}),"Verification Checklist"]}),e.jsxs(te,{variant:"secondary",className:"ml-2",children:[L.required_fields.length," fields"]})]})}),e.jsx(Ws,{className:"mt-2",children:e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:["Required fields for ",L.title,":"]}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:L.required_fields.map((y,V)=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-primary/50"}),e.jsx("span",{className:"capitalize",children:y.replace(/_/g," ")})]},V))})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Status"}),e.jsxs(zt,{value:t.status,onValueChange:oe,disabled:!C||t.is_split_parent,children:[e.jsx(Bt,{children:e.jsx(Gt,{})}),e.jsx(qt,{children:ls.map(y=>e.jsx(Be,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Expiry date"}),e.jsx(ye,{type:"date",value:z,onChange:y=>W(y.target.value),disabled:!C}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"For certificates, licenses, or permits. Drives the Document Expiry Alert service."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Stakeholder Relevance"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Zs.map(y=>e.jsx(te,{variant:U.includes(y.value)?"default":"outline",className:C?"cursor-pointer":"cursor-default opacity-70",onClick:C?()=>he(y.value):void 0,children:y.label},y.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Tags"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ye,{placeholder:"Add tag...",value:m,onChange:y=>N(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),k())},disabled:!C})}),S.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:S.map(y=>e.jsxs(te,{variant:"secondary",children:[y,C&&e.jsx(Gs,{className:"h-3 w-3 ml-1 cursor-pointer",onClick:()=>se(y)})]},y))})]}),e.jsx($t,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Notes"}),e.jsx(is,{placeholder:"Add notes about this document...",value:D,onChange:y=>K(y.target.value),onBlur:xe,rows:4,disabled:!C})]})]}),e.jsxs(Dt,{value:"extraction",className:"mt-0 space-y-4",children:[t.is_split_parent?e.jsxs("div",{className:"rounded-md border border-dashed bg-muted/30 p-4 text-sm text-muted-foreground space-y-3",children:[e.jsx("p",{className:"font-medium text-foreground",children:"PDF bundle"}),e.jsx("p",{children:"This row is the original multi-page upload. Extraction runs on each segment listed below it in the document list â open a segment to review AI results or apply to the shipment."}),C&&d&&c.length>0&&e.jsx(A,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-2 animate-spin"}),"Rebuildingâ¦"]}):"Edit page ranges"}),d&&c.length>0&&e.jsx($s,{open:R,onOpenChange:P,parent:t,children:c,onSave:y=>{d({documentId:t.id,segments:y}),P(!1)},isSaving:!!v})]}):e.jsx(ei,{documentId:t.id,extractionResult:t.ai_extraction_result,confidenceScore:t.ai_confidence_score??null,aiDetectedType:t.ai_detected_type,aiTypeConfidence:t.ai_type_confidence,aiTypeReasoning:t.ai_type_reasoning,aiExtractionStatus:t.ai_extraction_status,aiExtractionError:t.ai_extraction_error,geminiRetryCount:t.gemini_retry_count,geminiRetryAfter:t.gemini_retry_after,isVerified:t.extraction_verified??!1,onVerify:Fe,onApplyToShipment:g,onRetryExtraction:n?()=>n(t.id):void 0,isRetrying:l,onStartExtraction:o?()=>o(t.id):void 0,isStartingExtraction:p,isApplyingToShipment:u,appliedToShipment:t.applied_to_shipment,extractionApplied:t.extraction_applied,appliedAt:t.applied_at,canEdit:C,aiExtractionAvailable:f,aiFuelAvailable:b,isExtractableDocument:!t.is_split_parent&&Fr(t.mime_type,t.file_name)}),t.summary&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:t.ai_extraction_result?"AI Summary & Apply Notes":"AI Summary"}),e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-md whitespace-pre-line",children:t.summary})]})]}),e.jsx(Dt,{value:"activity",className:"mt-0",children:e.jsx(si,{document:t})})]})]}),O&&e.jsx("div",{className:"flex shrink-0 gap-2 border-t px-4 py-2",children:e.jsxs(A,{variant:"outline",size:"sm",className:"flex-1",onClick:O,children:[e.jsx(nt,{className:"h-4 w-4 mr-2"}),"Download"]})})]})}function ri(t,s){return["shipment-document-detail",t??null,s??null]}function ni(t,s){return Ks({queryKey:ri(t,s),queryFn:async()=>
2{if(!t)return null;const{data:a,error:r}=await _e.from("shipment_documents").select("id, ai_extraction_result, extracted_data").eq("id",t).maybeSingle();if(r)throw r;return a??null},enabled:!!t,staleTime:6e4,placeholderData:(a,r)=>(r==null?void 0:r.queryKey[1])===t?a:void 0})}const ii=["form-templates","published"];function ha(t){const s=Ks({queryKey:ii,queryFn:async()=>{const{data:a,error:r}=await _e.from("form_templates").select("id, name, description, document_type, field_count, is_published").eq("is_published",!0).is("deleted_at",null).order("name");if(r)throw r;return a??[]},enabled:(t==null?void 0:t.enabled)??!0,staleTime:6e4});return{templates:s.data??[],isLoading:s.isLoading,refetch:s.refetch}}const li={commercial:"Commercial",transport:"Transport",customs:"Customs",certificates:"Certificates",financial:"Financial",hazmat:"Compliance",quarantine:"Quarantine"},oi=["Commercial","Transport","Customs","Certificates","Financial","Quarantine","Compliance","Other"];function ci({open:t,onOpenChange:s,onGenerate:a,isGenerating:r,restrictToDocCodes:n,restrictLabel:l}){const[o,p]=i.useState(!1),{templates:g,isLoading:u}=ha({enabled:t}),[x,C]=i.useState(""),[f,b]=i.useState(null),{documentTypes:c,getDocumentTypeByCode:d}=Ce(),v=i.useCallback(S=>d(Rt({name:S.name,document_type:S.document_type},c)),[d,c]),F=i.useCallback(S=>{var j;return((j=v(S))==null?void 0:j.title)??S.document_type},[v]),E=i.useMemo(()=>{if(!(n!=null&&n.length)||o)return g;const S=new Set(n.map(j=>ze(j)));return g.filter(j=>{const m=Rt({name:j.name,document_type:j.document_type},c);return!!m&&S.has(ze(m))})},[g,n,o,c]),O=i.useMemo(()=>{if(!x)return E;const S=x.toLowerCase();return E.filter(j=>{var m;return j.name.toLowerCase().includes(S)||((m=j.description)==null?void 0:m.toLowerCase().includes(S))||j.document_type.toLowerCase().includes(S)||F(j).toLowerCase().includes(S)})},[E,x,F]);i.useEffect(()=>{!t||o||n!=null&&n.length&&E.length===1&&b(E[0].id)},[t,o,n,E]),i.useEffect(()=>{t||(p(!1),b(null))},[t]);const B=!!(n!=null&&n.length)&&!o,G=i.useMemo(()=>{var m;const S={};for(const N of O){const U=(m=v(N))==null?void 0:m.category,H=U&&li[U]||"Other";S[H]||(S[H]=[]),S[H].push(N)}const j={};for(const N of oi)S[N]&&(j[N]=S[N]);return j},[O,v]),D=g.find(S=>S.id===f),K=()=>{D&&a(D.id,D.name)};return e.jsx(tt,{open:t,onOpenChange:s,children:e.jsxs(st,{className:"max-w-2xl max-h-[80vh]",children:[e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"h-5 w-5"}),"Generate Document"]}),e.jsx(Wt,{children:"Select a template to generate a document pre-filled with shipment data"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search templates...",value:x,onChange:S=>C(S.target.value),className:"pl-9"})]}),B&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"truncate",children:["Showing templates for ",l||"the selected document"]}),e.jsx(A,{variant:"ghost",size:"sm",className:"h-6 shrink-0 px-2 text-xs",onClick:()=>p(!0),children:"Show all"})]}),e.jsx(Et,{className:"h-[400px] border rounded-md",children:u?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(J,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):Object.keys(G).length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground p-6",children:[e.jsx(pe,{className:"h-12 w-12 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No published templates found"}),e.jsx("p",{className:"text-xs",children:"Create and publish templates in Form Builder"})]}):e.jsx("div",{className:"p-2 space-y-4",children:Object.entries(G).map(([S,j])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:S}),e.jsx("div",{className:"space-y-1",children:j.map(m=>e.jsx("button",{onClick:()=>b(m.id),className:Q("w-full text-left p-3 rounded-md transition-colors","hover:bg-accent",f===m.id?"bg-primary/10 border border-primary":"border border-transparent"),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:m.name}),e.jsxs(te,{variant:"secondary",className:"text-xs",children:[m.field_count??0," fields"]})]}),m.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-1",children:m.description})]}),e.jsx(zs,{className:Q("h-4 w-4 text-muted-foreground transition-transform",f===m.id&&"text-primary")})]})},m.id))})]},S))})}),D&&e.jsxs("div",{className:"p-3 bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:D.name}),D.document_type&&e.jsx(te,{variant:"outline",className:"text-xs",children:F(D)})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:D.description||"No description"}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[D.field_count??0," fields will be populated from shipment data"]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(A,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(A,{onClick:K,disabled:!f||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 mr-2"}),"Generate Document"]})})]})]})]})})}function di(t){if(!t||t.length===0)return"";const s={};for(const a of t){const r=(a==null?void 0:a.action)??"flagged";r!=="kept_with_warning"&&(s[r]=(s[r]??0)+1)}return Object.entries(s).map(([a,r])=>`${r} ${a}`).join(", ")}function mi(){const t=Qs(),[s,a]=i.useState(!1),r=l=>{ar(t,l)};return{applyExtraction:async({shipmentId:l,documentId:o,extractedData:p,documentType:g})=>{a(!0);const u={mainShipment:0,parties:0,containers:0,packingLines:0,routingLegs:0,invoices:0,customFields:0,billingLines:0,purchaseOrders:0,purchaseOrderLines:0,bookingReference:0,packingBill:0};try{const{data:{user:x}}=await Vt();if(!x)throw new Error("User not authenticated");let C;try{const v=await sr(x.id)??x.id,{data:F}=await _e.from("ai_agents").select("id").eq("user_id",v).eq("agent_type","document_processor").eq("status","active").is("paused_at",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();C=F==null?void 0:F.id}catch{}const{data:f,error:b}=await _e.functions.invoke("document-extraction-agent",{body:{action:"apply",document_id:o,...C?{agent_id:C}:{},extracted_data:p,document_type:g??null}}),c=f;if(!b&&(c!=null&&c.applied)&&!c.fallback){r(l);const v=c.appliedFields??{},F=Object.values(v).reduce((O,B)=>O+(typeof B=="number"?B:0),0),E=di(c.validationWarnings);return $.success(`Applied ${F} fields to shipment`,{description:`Nova${E?` ⢠${E}`:""}`}),{success:!0,appliedFields:{...u,...v}}}if(c!=null&&c.capped||c!=null&&c.fallback)return r(l),$.info("Apply queued",{description:"Nova is at a limit right now (daily cap, concurrency, AI Fuel, or paused). The document stays extracted and applies automatically as soon as she can run again."}),{success:!1,appliedFields:u};const d=(b==null?void 0:b.message)??(c==null?void 0:c.error)??"Server apply unavailable";throw console.warn("[ApplyExtraction] server apply failed",{error:b==null?void 0:b.message,reason:d}),new Error(d)}catch(x){return console.error("Error applying extraction to shipment:",x),$.error("Failed to apply extraction data",{description:x instanceof Error?x.message:"Unknown error"}),{success:!1,appliedFields:u}}finally{a(!1)}},isApplying:s}}function ui({open:t,label:s,onOpenChange:a,onConfirm:r,isPending:n}){const[l,o]=i.useState("");return i.useEffect(()=>{t&&o("")},[t]),e.jsx(Yt,{open:t,onOpenChange:p=>!n&&a(p),children:e.jsxs(Xt,{children:[e.jsxs(Zt,{children:[e.jsxs(Jt,{children:["Mark ",s??"this document"," as not required?"]}),e.jsx(es,{children:"This shipment's workflow will stop waiting for it, and any step held up only by this document will continue. Recorded against the workflow, and you can restore the requirement later."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{htmlFor:"waive-reason",children:"Reason (optional)"}
2),e.jsx(is,{id:"waive-reason",value:l,onChange:p=>o(p.target.value),placeholder:"e.g. supplier ships under a delivery note",rows:3})]}),e.jsxs(ts,{children:[e.jsx(ss,{disabled:n,children:"Cancel"}),e.jsx(as,{disabled:n,onClick:p=>{p.preventDefault(),r(l.trim()?l.trim():void 0)},children:n?"Savingâ¦":"Mark not required"})]})]})})}function pi({documents:t,sortBy:s,collapsedBundles:a,requirements:r}){const n=new Set(t.map(u=>u.id)),l=new Map;for(const u of t)if(u.parent_document_id){const x=l.get(u.parent_document_id)??[];x.push(u),l.set(u.parent_document_id,x)}for(const u of l.values())u.sort((x,C)=>(x.split_segment_index??0)-(C.split_segment_index??0));const o=t.filter(u=>!u.parent_document_id);o.sort((u,x)=>{switch(s){case"oldest":return new Date(u.created_at).getTime()-new Date(x.created_at).getTime();case"name":return u.file_name.localeCompare(x.file_name);case"type":return(u.document_type??"").localeCompare(x.document_type??"")||u.file_name.localeCompare(x.file_name);case"newest":default:return new Date(x.created_at).getTime()-new Date(u.created_at).getTime()}});const p=t.filter(u=>u.parent_document_id&&!n.has(u.parent_document_id));p.sort((u,x)=>(u.split_segment_index??0)-(x.split_segment_index??0));const g=[...r??[]];for(const u of o)if(u.is_split_parent){const x=l.get(u.id)??[],C=a.has(u.id);if(g.push({kind:"document",key:u.id,document:u,indentLevel:0,childCount:x.length,isCollapsed:C}),!C)for(const f of x)g.push({kind:"document",key:f.id,document:f,indentLevel:1})}else g.push({kind:"document",key:u.id,document:u,indentLevel:0});for(const u of p)g.push({kind:"document",key:u.id,document:u,indentLevel:1});return g}function xi(){const t=Qs();return rr({mutationFn:async({shipmentId:s,code:a,alternatives:r,label:n,waive:l,reason:o})=>{const{data:{user:p}}=await Vt();if(!p)throw new Error("You must be signed in to change document requirements");const{data:g,error:u}=await _e.from("workflow_instances").select("id, required_documents, status").eq("shipment_id",s);if(u)throw u;const x=(g??[]).filter(b=>!Ar.has((b.status??"").toLowerCase())),C={userId:p.id,at:new Date().toISOString(),reason:o},f=[];for(const b of x){const{next:c,changed:d}=Tr(b.required_documents,{code:a,alternatives:r},l,C);if(!d)continue;const{error:v}=await _e.from("workflow_instances").update({required_documents:c}).eq("id",b.id);if(v)throw v;f.push(b.id)}if(f.length===0)throw new Error("That requirement is no longer on an active workflow");for(const b of f)bn(l?"document_requirement_waived":"document_requirement_restored","workflow_instance",b,{code:a,label:n,alternatives:r,reason:(o==null?void 0:o.trim())||null});return{updatedInstanceIds:f}},onSuccess:(s,{shipmentId:a})=>{t.invalidateQueries({queryKey:["shipment-required-documents",a]}),t.invalidateQueries({queryKey:vn})}})}const hi=t=>t==="accepted"?"default":t==="draft"?"secondary":"outline";function fi({open:t,onOpenChange:s,quotes:a,defaultQuoteId:r,onConfirm:n,isGenerating:l,documentName:o}){var C;const[p,g]=i.useState(r??((C=a[0])==null?void 0:C.id)??""),u=i.useRef(!1);i.useEffect(()=>{var f;t&&!u.current&&g(r??((f=a[0])==null?void 0:f.id)??""),u.current=t},[t,r,a]);const x=new Set(a.map(f=>f.currency).filter(Boolean));return e.jsx(tt,{open:t,onOpenChange:s,children:e.jsxs(st,{className:"max-w-lg",children:[e.jsxs(at,{children:[e.jsx(rt,{children:"Which quote?"}),e.jsxs(Wt,{children:["This shipment has ",a.length," saved quotes.",x.size>1?" They are not all in the same currency, so the one you pick decides every figure on the document.":" Pick the one this document should show."]})]}),e.jsx(_n,{value:p,onValueChange:g,className:"max-h-80 gap-2 overflow-y-auto",children:a.map(f=>e.jsxs(ie,{htmlFor:`quote-${f.id}`,className:"flex cursor-pointer items-start gap-3 rounded-md border p-3 hover:bg-muted/50 has-[:checked]:border-primary",children:[e.jsx(Cn,{value:f.id,id:`quote-${f.id}`,className:"mt-1"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:f.quote_reference||"Unreferenced quote"}),e.jsx(te,{variant:hi(f.status),className:"text-[10px]",children:f.status}),f.version_number?e.jsxs("span",{className:"text-xs text-muted-foreground",children:["v",f.version_number]}):null,f.id===r?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"(suggested)"}):null]}),e.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground",children:[nr(f.total_sell??0,f.currency),f.customer_name?` · ${f.customer_name}`:"",f.quote_date?` · ${new Date(f.quote_date).toLocaleDateString()}`:""]})]})]},f.id))}),e.jsxs(Ut,{children:[e.jsx(A,{variant:"outline",onClick:()=>s(!1),disabled:l,children:"Cancel"}),e.jsx(A,{onClick:()=>n(p),disabled:!p||l,children:l?"Generatingâ¦":`Generate${o?` ${o}`:""}`})]})]})})}const Se=t=>t==null?"":String(t),Ps=t=>{if(t==null||t==="")return 0;const s=typeof t=="number"?t:Number(t);return Number.isFinite(s)?s:0};function gi(t){const s=(t??[]).filter(l=>l&&typeof l=="object");
2if(s.length===0)return null;const a=new Set(s.map(l=>Se(l.id)).filter(Boolean)),r=l=>{const o=Se(l.superseded_by);return!!o&&a.has(o)},n=l=>{if(r(l))return 0;const o=Se(l.status).toLowerCase();return o==="accepted"?3:o==="rejected"||o==="expired"?1:2};return[...s].sort((l,o)=>{const p=n(o)-n(l);if(p!==0)return p;const g=Ps(o.version_number)-Ps(l.version_number);if(g!==0)return g;const u=C=>{const f=Date.parse(Se(C.updated_at)||Se(C.created_at));return Number.isFinite(f)?f:0},x=u(o)-u(l);return x!==0?x:Se(l.id).localeCompare(Se(o.id))})[0]??null}function md({shipmentId:t,mode:s,userRole:a,onShipmentCreated:r}){const n=ir(),{can:l}=lr(),{subscribed:o,processingLevel:p,aiFuelOverageOptIn:g}=or(),u=fn(),x=$r(o,p),C=l("documents","view"),f=l("documents","create"),b=l("documents","edit"),c=l("documents","delete"),{documents:d,isLoading:v,uploadDocumentAsync:F,uploadProgress:E,isUploading:O,updateDocument:B,deleteDocument:G,isDeleting:D,retryExtraction:K,retryExtractionAsync:S,isRetrying:j,startExtraction:m,isStartingExtraction:N,updateSplitSegments:U,isUpdatingSegments:H,getSignedUrl:z,downloadDocumentBlob:Y,needsGoogleDriveReconnect:T,clearGoogleDriveError:M}=Er(t),R=h=>{G(h),L(null)},[P,L]=i.useState(null),[ee,oe]=i.useState(()=>new Set),X=h=>{oe(w=>{const I=new Set(w);return I.has(h)?I.delete(h):I.add(h),I})},[W,xe]=i.useState(null),[k,se]=i.useState(""),[he,Fe]=i.useState([]),[_,Z]=i.useState([]),[y,V]=i.useState([]),[re,Le]=i.useState("newest"),[Me,lt]=i.useState("list"),[we,Ge]=i.useState(!1),[ot,ce]=i.useState(!1),[fe,ct]=i.useState(null),{rawShipment:de}=Ir(t),{data:ji=[]}=Nr(t),{applyExtraction:fa,isApplying:ga}=mi(),ja=async h=>{if(!x){$.error("AI extraction requires an Autopilot or Fleet Command subscription");return}if(!t||!P){$.error("No shipment or document selected");return}const w=d.find(q=>q.id===P);if(w!=null&&w.is_split_parent){$.error("Apply extraction from a segment document, not the original bundle row.");return}const I=(w==null?void 0:w.document_type)||(w==null?void 0:w.ai_detected_type)||void 0;await fa({shipmentId:t,documentId:P,extractedData:h,documentType:I})},me=i.useMemo(()=>d.find(h=>h.id===P)||null,[d,P]),{data:$e}=ni(me==null?void 0:me.id,me==null?void 0:me.updated_at),ue=i.useMemo(()=>me?!$e||$e.id!==me.id?me:{...me,ai_extraction_result:$e.ai_extraction_result,extracted_data:$e.extracted_data??me.extracted_data??null}:null,[me,$e]),{pdfBlob:ba,imageUrl:va,textContent:ya,spreadsheetData:wa,docxHtml:Na,downloadUrl:_a,isLoadingPreview:Ca,unavailableReason:ka,reloadPreview:Da,getFileBlob:Sa}=sn(ue,z,Y);i.useEffect(()=>{xe(null)},[ue==null?void 0:ue.id]);const Fa=()=>{Da()},os=async h=>{if(Tt(h.storage_location)){$.info("This document is still being copied from the linked job",{description:"It will open once the transfer finishes â usually within a minute."});return}try{if(!pr(h.storage_location)){const ae=await z(h.file_path,h.storage_location,h.external_file_id);if(ae){window.open(ae,"_blank","noopener");return}}const w=await Y(h.id);if(!w){$.error("Could not generate a download link for this document");return}const I=URL.createObjectURL(w),q=window.document.createElement("a");q.href=I,q.download=h.file_name||"document",window.document.body.appendChild(q),q.click(),q.remove(),setTimeout(()=>URL.revokeObjectURL(I),6e4)}catch(w){console.error("Failed to download document:",w),$.error("Failed to download document")}},[Aa,cs]=i.useState(!1),Ta=i.useCallback(async()=>{const{selectDocumentsToMerge:h,mergeDocumentsToPdf:w,mergedFileName:I}=await cr(async()=>{const{selectDocumentsToMerge:ne,mergeDocumentsToPdf:ge,mergedFileName:ke}=await import("./SendPackDialog-Bdl95I2n.js").then(je=>je.p);return{selectDocumentsToMerge:ne,mergeDocumentsToPdf:ge,mergedFileName:ke}},__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,36])),{include:q,skipped:ae}=h(d,{isPendingTransfer:Tt});if(q.length===0){$.info("Nothing to combine",{description:"None of these documents are PDFs or images."});return}cs(!0);try{const ne=await w(q,async Pe=>{const vs=await Y(Pe.id);return vs?await vs.arrayBuffer():null});if(!ne){$.error("Could not combine these documents");return}const ge=new Blob([ne.bytes.slice()],{type:"application/pdf"}),ke=URL.createObjectURL(ge),je=window.document.createElement("a");je.href=ke,je.download=I(de==null?void 0:de.reference_number),window.document.body.appendChild(je),je.click(),je.remove(),setTimeout(()=>URL.revokeObjectURL(ke),6e4);const bs=[...ae.filter(Pe=>Pe.reason!=="bundle").map(Pe=>Pe.name),...ne.failed];
2$.success(`Combined ${ne.mergedCount} document${ne.mergedCount===1?"":"s"}`,{description:bs.length>0?`Not included: ${bs.join(", ")}`:void 0})}catch(ne){console.error("Failed to combine documents:",ne),$.error("Failed to combine documents")}finally{cs(!1)}},[d,Y,de==null?void 0:de.reference_number]),dt=i.useMemo(()=>{let h=d;if(k){const w=k.toLowerCase();h=h.filter(I=>{var q,ae;return I.file_name.toLowerCase().includes(w)||((q=I.summary)==null?void 0:q.toLowerCase().includes(w))||((ae=I.notes)==null?void 0:ae.toLowerCase().includes(w))})}return he.length>0&&(h=h.filter(w=>he.includes(w.document_type))),_.length>0&&(h=h.filter(w=>_.includes(w.status))),y.length>0&&(h=h.filter(w=>{var I;return(I=w.stakeholder_relevance)==null?void 0:I.some(q=>y.includes(q))})),h},[d,k,he,_,y]),Ea=i.useMemo(()=>d.filter(h=>Fs(h.ai_extraction_error)).length,[d]),[La,ds]=i.useState(!1),Ma=i.useCallback(async()=>{const h=d.filter(w=>Fs(w.ai_extraction_error)&&!w.is_split_parent).map(w=>w.id);if(h.length!==0){ds(!0);try{for(const w of h)try{await S(w)}catch(I){if(I instanceof Error&&I.message==="Out of fuel")break;break}}finally{ds(!1)}}},[d,S]),{data:Ae}=gn(t),$a=jn(),Oe=_r({grant:(Ae==null?void 0:Ae.grant)??null,poolRemaining:$a,overageEnabled:u,workspaceOptedIn:g}),Oa=x&&Oe;i.useEffect(()=>{Oe&&Or()},[Oe]);const Pa=i.useMemo(()=>d.flatMap(h=>pn(h)),[d]),{requirements:ms,missing:Ra}=Lr(t??"",Pa),{documentTypes:us,getDocumentTypeByCode:mt}=Ce(),{templates:ut}=ha(),{data:qe=[]}=Nn(t),Ia=i.useMemo(()=>{var h;return(h=gi(qe))==null?void 0:h.id},[qe]),pt=xi(),za=l("workflows","edit"),{data:xt}=yn(t??null),{data:ps=[]}=wn((xt==null?void 0:xt.id)??null),{markComplete:Ba}=Mr(t??void 0),xs=i.useMemo(()=>ps.find(h=>h.status!=="in_progress"?!1:(h.step_config??{}).completionRule==="required_documents_received"),[ps]),[Ue,ht]=i.useState(null),[Te,ft]=i.useState(null),hs=!!k||he.length>0||_.length>0||y.length>0,fs=i.useMemo(()=>ms.filter(h=>!h.satisfied).map(h=>{var ne,ge;const w=h.alternatives??[],I=Es(h.code,w,ze),q=ut.some(ke=>{const je=Rt({name:ke.name,document_type:ke.document_type},us);return!!je&&I.includes(ze(je))}),ae=((ne=mt(h.code))==null?void 0:ne.name)??((ge=mt(h.code.toUpperCase()))==null?void 0:ge.name)??h.code;return{kind:"requirement",key:`req:${Ct(h.code,w)}`,requirement:h,status:h.waived?"waived":h.isRequired===!1?"optional":"missing",canGenerate:q,uploadCode:ae}}),[ms,ut,us,mt]),Ga=h=>ht(h),qa=h=>{const w=Ue;if(!w||!t)return;const I=w.requirement.alternatives??[],q=Ct(w.requirement.code,I);pt.mutate({shipmentId:t,code:w.requirement.code,alternatives:I,label:We(w.requirement),waive:!0,reason:h},{onSuccess:()=>{ht(null),$.success("Marked as not required");const ae=Ra.filter(ne=>Ct(ne.code,ne.alternatives??[])!==q);xs&&ae.length===0&&Ba(xs.id)},onError:ae=>$.error((ae==null?void 0:ae.message)??"Could not update the requirement")})},Ua=h=>{t&&pt.mutate({shipmentId:t,code:h.requirement.code,alternatives:h.requirement.alternatives??[],label:We(h.requirement),waive:!1},{onSuccess:()=>$.success("Requirement restored"),onError:w=>$.error((w==null?void 0:w.message)??"Could not restore the requirement")})},Wa=h=>{const w=Es(h.requirement.code,h.requirement.alternatives??[],ze);ft({codes:w,label:We(h.requirement)}),ce(!0)},Va=i.useMemo(()=>pi({documents:dt,sortBy:re,collapsedBundles:ee,requirements:hs?[]:fs}),[dt,ee,re,hs,fs]),Ka=async()=>{if(t)return t;throw new Error("No shipment ID available - please wait for draft to be created")},Qa=async(h,w)=>{if(!t){$.error("Please save the shipment before generating documents");return}const I=ut.find(q=>q.id===h);if((I==null?void 0:I.document_type)==="QUOT"&&qe.length>1){ct({templateId:h,templateName:w}),ce(!1);return}await gs(h,w)},gs=async(h,w,I)=>{if(t){Ge(!0),ce(!1);try{const{data:{user:q}}=await Vt(),{data:ae,error:ne}=await mr("generate-document",{retryOnTransportFailure:!1,body:{shipmentId:t,templateId:h,userId:q==null?void 0:q.id,...I?{quoteId:I}:{}}});if(ne)throw new Error(await ur(ne,"Document generation failed"));$.success(`${w} generated successfully`);const ge=Array.isArray(ae==null?void 0:ae.warnings)?ae.warnings:[];ge.includes("tax_invoice_missing_bank_details")&&$.warning("This Tax Invoice has no bank details",{description:"The customer has no way to pay it. Add your bank account under Account â Bank Details, then regenerate.",duration:1e4}),ge.includes("tax_invoice_missing_abn")&&$.warning("This Tax Invoice has no ABN",{description:"An Australian tax invoice must show the supplierâs ABN. Add your Tax ID under Account â Business information, then regenerate.",duration:1e4}),ge.includes("tax_invoice_missing_gst_number")&&$.warning("This Tax Invoice has no GST number",{description:"A New Zealand tax invoice must show the supplierâs GST number â an NZBN does not satisfy it. Add your GST number as the Tax ID under Account â Business information, then regenerate.",duration:1e4})}catch(q){console.error("Document generation failed:",q),$.error(q instanceof Error?q.message:"Failed to generate document")}finally{Ge(!1)}}},js=(h,w)=>F({file:h,documentType:w,onShipmentCreate:Ka}).then(()=>{},()=>{}),Ha=()=>{M(),n("/dock?tab=business-apps")};return C?v?e.jsx(dr,{size:"md",text:"Loading...",className:"pt-6"}):e.jsxs("div",{className:"space-y-4",children:[T&&e.jsx(xn,{onReconnect:Ha}),f&&e.jsx(ci,{open:ot,onOpenChange:h=>{ce(h),h||ft(null)},onGenerate:Qa,isGenerating:we,restrictToDocCodes:Te==null?void 0:Te.codes,restrictLabel:Te==null?void 0:Te.label}),e.jsx(fi,{open:!!fe,onOpenChange:h=>!h&&ct(null),quotes:qe,defaultQuoteId:Ia,documentName:fe==null?void 0:fe.templateName,isGenerating:we,onConfirm:async h=>{const w=fe;ct(null),w&&await gs(w.templateId,w.templateName,h)}}),e.jsx(ui,{open:!!Ue,label:Ue?We(Ue.requirement):null,onOpenChange:h=>!h&&ht(null),onConfirm:qa,isPending:pt.isPending}),e.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 lg:h-[calc(100vh-260px)] lg:min-h-[600px] lg:grid-cols-12",children:[e.jsxs("div",{className:"flex max-h-[420px] min-h-0 flex-col lg:col-span-4 lg:max-h-none",children:[e.jsx(qn,{documentCount:dt.length,extractionFuel:Ae==null?void 0:Ae.extractionFuel,listItems:Va,fuelPausedCount:Ea,aiFuelAvailable:Oe,onExtractPaused:x?Ma:void 0,isExtractingPaused:La,aiTypeDetectionAvailable:Oa,selectedDocumentId:P,onSelectDocument:L,onToggleBundleCollapsed:X,onSearch:se,selectedTypes:he,onTypesChange:Fe,selectedStatuses:_,onStatusesChange:Z,selectedStakeholders:y,onStakeholdersChange:V,sortBy:re,onSortChange:Le,viewMode:Me,onViewModeChange:lt,onUpload:js,isUploading:O,storageMode:(de==null?void 0:de.storage_mode)??null,uploadProgress:E,canCreate:f,canDelete:c,onDeleteDocument:R,onDownloadDocument:os,onStartExtraction:x?m:void 0,onRetryExtraction:x?K:void 0,onOpenGenerateDialog:()=>{ft(null),ce(!0)},onDownloadAll:Ta,isDownloadingAll:Aa,requirementActions:t?{onUpload:js,onGenerate:Wa,onWaive:Ga,onRestore:Ua,canWaive:za,isUploading:O}:void 0,isGenerating:we}),e.jsx(Kn,{shipmentId:t,className:"mt-2 shrink-0"})]}),e.jsx("div",{className:"flex h-[500px] min-h-0 min-w-0 flex-col lg:col-span-5 lg:h-auto",children:e.jsx(an,{document:ue,pdfBlob:ba,imageUrl:va,downloadUrl:_a,textContent:ya,spreadsheetData:wa,docxHtml:Na,isLoadingPreview:Ca,unavailableReason:ka,getFileBlob:Sa,onRetryLoad:
2Fa,onClose:()=>L(null),onPdfLoaded:xe})}),e.jsx("div",{className:"flex min-h-0 min-w-0 flex-col lg:col-span-3",children:e.jsx(ai,{document:ue,onUpdate:(h,w)=>B({documentId:h,updates:w}),onDelete:R,isDeleting:D,onRetryExtraction:x?K:void 0,isRetrying:j,onStartExtraction:x?m:void 0,isStartingExtraction:N,onApplyToShipment:x?ja:void 0,isApplyingToShipment:ga,aiExtractionAvailable:x,aiFuelAvailable:Oe,canDelete:c,canEdit:b,splitChildren:ue!=null&&ue.is_split_parent?d.filter(h=>h.parent_document_id===ue.id):[],onUpdateSplitSegments:x?U:void 0,isUpdatingSegments:H,shipmentReference:(de==null?void 0:de.reference_number)??null,pageCount:W,onDownload:ue?()=>os(ue):void 0})})]}),e.jsx(kn,{tabId:"documents",shipmentId:t})]}):e.jsx(hn,{areaName:"Documents"})}export{md as DocumentsTab};
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.