PageSourceSearch

https://bizvanguard.ai/assets/StatementsPage-D0-MHb80.js

js bizvanguard.ai collected 2026-10-05 13:48:28 UTC 95,592 bytes, 4 lines download raw bytes

1import{u as X,j as e,r as N,t as me,v as at,R as Es}from"./vendor-react-zwv87yMD.js";import{u as ke}from"./authStore-Bv6p2Ne2.js";import{T as xs,a as hs,b as ue,c as Rs}from"./tabs-Dd8Qm6LV.js";import{u as qe,b as G,a as de}from"./vendor-query-DYq8g7OI.js";import{c as _,g as As,a as Qs,b as nt,d as rt,f as xe,e as it,h as lt,i as dt}from"./credit-cards-BnCVDKkT.js";import{u as Ve}from"./useOrgTimezone-C1UagyKl.js";import{a as z,d as ct,g as ot}from"./timezoneFormatters-Lg56xFv0.js";import{B as w}from"./button-DlBDuKbo.js";import{B as ye}from"./badge-QivbhJml.js";import{L as Pe}from"./label-CSUA9GMO.js";import{D as Ne,a as be,b as Ce,c as ve,d as Bs,e as mt}from"./dialog-CCoQRIQ_.js";import{A as ut,a as xt,b as ht,c as pt,d as gt,e as ft,f as jt,g as Nt}from"./alert-dialog-P2RRIvov.js";import{S as ws}from"./select-D2pLZtG9.js";import{v as Y,O as Je,F as ps,R as bt,aN as js,s as Ws,t as ms,b as Ct,h as vt,g as Ls,x as _s,ao as yt,ap as kt,ay as wt,J as St,T as cs,d as Dt,y as $s}from"./vendor-icons-bLSWzydc.js";import{a as Is}from"./apiError-3JmRUUhQ.js";import{I as Ze}from"./input-C9cRIRX4.js";import{p as Tt,h as Hs,i as Gs,w as us,j as Ys,k as Et,l as At,n as Pt,e as Ft,q as Lt,r as Os}from"./app-entry-CaCir6v3.js";import{D as It,a as Mt,b as Rt,e as Us}from"./dropdown-menu-DJoX9NOt.js";import{c as Ps}from"./utils-BXSzAfFa.js";import{m as gs}from"./monthKeyFromPeriod-tJ6EjOLJ.js";import{b as Ns,c as Xs,L as ze}from"./vendor-router-DimZLiZb.js";import{d as ae,p as Bt}from"./document-ai-CL0R1wiL.js";import{C as _t,u as $t}from"./useCheckAnalysis-DahXp-SP.js";import{c as Zs,f as B,s as fs,g as te,e as os,D as Ot,d as Ut}from"./DocumentUploadDialog-CYSQB-CN.js";import{a as Kt,U as Ks}from"./UseForMatchingButton-D8Lxsqw3.js";import{R as zt,a as qt}from"./radio-group-BoJeumSx.js";import{u as Vt}from"./usePermissions-CBDKNj1w.js";import"./vendor-charts-CtrTLS4K.js";import"./vendor-i18n-BdYkS11p.js";import"./vendor-ui-CfDMlrKu.js";import"./vendor-pdf-DQuePnfN.js";import"./vendor-state-ByI9XJey.js";import"./vendor-editor-C_dhmuey.js";import"./api-client-wl3SCNAO.js";import"./i18n-CwjSIy0a.js";import"./employeeAuthStore-lYSKMuhw.js";import"./legal-documents-DjQ2iB_Z.js";import"./RichTextContent-CRaB6axZ.js";import"./navigation-CBv1MCGY.js";import"./Logo-CcvH_fVs.js";function Qt({card:s,onClose:i,onImport:r,isImportOpen:n}){const{t:c}=X("bills"),o=qe(),{currentOrganizationId:x}=ke(),h=Ve(),u=G({mutationFn:_.reconcileStatement,onSuccess:()=>{o.invalidateQueries({queryKey:["credit-cards"]}),o.invalidateQueries({queryKey:["transactions"]}),o.invalidateQueries({queryKey:["credit-card",s==null?void 0:s.id]})}}),{data:j,isLoading:D}=de({queryKey:["credit-card",x,s==null?void 0:s.id],queryFn:()=>_.getCard(s.id),enabled:!!s&&!n});if(!s)return null;const M=(j==null?void 0:j.statements)||[];return e.jsx(Ne,{open:!!s&&!n,onOpenChange:i,children:e.jsxs(be,{className:"max-w-2xl",children:[e.jsx(Ce,{children:e.jsx(ve,{children:s.name})}),D?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Y,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:`${As(s.color)} rounded-lg p-4 text-white`,children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-white/80 text-sm",children:s.bankName||Qs(s.cardType)}),e.jsxs("p",{className:"font-mono text-lg",children:["•••• •••• •••• ",s.lastFourDigits]})]}),e.jsxs(w,{variant:"secondary",size:"sm",onClick:r,children:[e.jsx(Je,{className:"h-4 w-4 mr-2"}),c("creditCards.importTransactions")]})]})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"Statements"}),M.length===0?e.jsxs("div",{className:"text-center py-8 bg-muted/50 rounded-lg",children:[e.jsx(ps,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No statements imported yet"})]}):e.jsx("div",{className:"border rounded-lg divide-y",children:M.map(y=>e.jsxs("div",{className:"p-4 flex items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[z(y.periodStart,h,{month:"short",day:"numeric"})," ","- ",z(y.periodEnd,h)]}),e.jsx(ye,{className:rt(y.status),children:nt(y.status)})]}),e.jsxs("div",{className:"flex gap-4 text-sm text-muted-foreground mt-1",children:[e.jsxs("span",{children:[y.transactionCount," transactions"]}),e.jsxs("span",{children:[y.matchedCount," matched"]}),y.unmatchedCount>0&&e.jsxs("span",{className:"text-red-500",children:[y.unmatchedCount," unmatched"]})]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"font-semibold",children:xe(y.totalAmount)})}),y.status!=="RECONCILED"&&y.unmatchedCount>0&&e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>u.mutate(y.id),disabled:u.isPending,children:[u.isPending?e.jsx(Y,{className:"h-4 w-4 animate-spin"}):e.jsx(bt,{className:"h-4 w-4 mr-1"}),"Reconcile"]})]},y.id))})]})]})]})})}const Wt=["UNMATCHED","DISPUTED","REVIEWED"];function Js({transaction:s,mode:i="charge",onClose:r}){var b;const{t:n}=X("bills"),c=Ve(),o=qe(),{permissions:x,currentOrganizationId:h}=ke(),u=x.includes("MANAGE_CREDIT_CARDS"),j=x.includes("MANAGE_RECEIPTS"),[D,M]=N.useState("");N.useEffect(()=>{M("")},[s==null?void 0:s.id]);const y=!!s&&Wt.includes(s.matchStatus),{data:A,isLoading:P}=de({queryKey:["cc-match-suggestions",s==null?void 0:s.id,h],queryFn:()=>_.getSuggestedMatches(s.id),enabled:!!(s!=null&&s.id)&&!!h&&y&&i!=="return"}),S=()=>{o.invalidateQueries({queryKey:["transactions"]}),o.invalidateQueries({queryKey:["transactions-unmatched"]}),o.invalidateQueries({queryKey:["cc-match-suggestions"]}),o.invalidateQueries({queryKey:["cc-work-list",h]}),o.invalidateQueries({queryKey:["receipts"]}),o.invalidateQueries({queryKey:["bills-kpi-summary"]}),o.invalidateQueries({queryKey:["bills-payment-mix"]}),o.invalidateQueries({queryKey:["bills-ai-summary"]})},p=F=>{me.error(Is(F,n("creditCards.importDialog.failed")))},g=G({mutationFn:F=>_.matchTransaction(s.id,F),onSuccess:()=>{S(),r()},onError:p}),L=G({mutationFn:()=>_.unmatchTransaction(s.id),onSuccess:()=>{S(),r()},onError:p}),I=G({mutationFn:()=>_.createStub(s.id),onSuccess:()=>{S(),r()},onError:p}),k=G({mutationFn:()=>_.ignoreTransaction(s.id,D),onSuccess:()=>{S(),r()},onError:p}),f=g.isPending||L.isPending||I.isPending||k.isPending,O=(s==null?void 0:s.matchStatus)==="AUTO_MATCHED"||(s==null?void 0:s.matchStatus)==="MANUAL_MATCHED",T=i==="return"?["PERSONAL","REFUND"]:i==="issuer_fee"?["PERSONAL"]:["PERSONAL","CARD_PAYMENT","REFUND","NOT_AN_EXPENSE"],d=F=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-2 rounded-lg border bg-background",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:F.label}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n("creditCards.matchSheet.confidence",{percent:Math.round(F.confidence*100)}),F.reasons[0]?` · ${F.reasons[0]}`:""]})]}),u&&e.jsx(w,{size:"sm",variant:"outline",disabled:f,onClick:()=>g.mutate(F.type==="bill"?{billId:F.id}:{receiptId:F.id}),children:n("creditCards.matchSheet.attach")})]},`${F.type}-${F.id}`);return e.jsx(Ne,{open:!!s,onOpenChange:F=>!F&&r(),children:e.jsxs(be,{className:"max-w-md max-h-[90vh] overflow-y-auto sm:max-h-[85vh]",children:[e.jsx(Ce,{children:e.jsx(ve,{children:n("creditCards.matchSheet.title")})}),s&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.merchantName}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[z(s.transactionDate,c),(b=s.statement)!=null&&b.creditCardAccount?` · **** ${s.statement.credit
1CardAccount.lastFourDigits}`:""]}),e.jsxs("p",{className:"text-lg font-semibold mt-1",children:[s.isCredit?"+":"-",xe(s.amount)]}),s.matchedReceipt&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:n("creditCards.matchedAmount",{amount:xe(s.matchedReceipt.totalAmount)})}),s.matchedBill&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:n("creditCards.matchedBill",{billNumber:s.matchedBill.billNumber,vendor:s.matchedBill.vendorName})})]}),O&&u&&e.jsxs(w,{variant:"outline",className:"w-full",disabled:f,onClick:()=>L.mutate(),children:[e.jsx(js,{className:"h-4 w-4 mr-2"}),n("creditCards.matchSheet.unmatch")]}),y&&u&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[j&&!s.isCredit&&i==="charge"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:n("creditCards.matchSheet.createReceiptHint")}),e.jsx(w,{className:"w-full",disabled:f,onClick:()=>I.mutate(),children:n("creditCards.matchSheet.createReceipt")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:n("creditCards.matchSheet.ignore")}),T.map(F=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"radio",name:"ignore-reason",checked:D===F,onChange:()=>M(F)}),n(`creditCards.matchSheet.ignoreReasons.${F}`)]},F)),e.jsx(w,{variant:"outline",className:"w-full",disabled:f||!D,onClick:()=>k.mutate(),children:n("creditCards.matchSheet.ignoreConfirm")})]})]}),y&&i!=="return"&&(P?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Y,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[((A==null?void 0:A.bills.length)||0)>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:n("creditCards.matchSheet.bills")}),A.bills.map(d)]}),i!=="issuer_fee"&&((A==null?void 0:A.receipts.length)||0)>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:n("creditCards.matchSheet.receipts")}),A.receipts.map(d)]}),!(A!=null&&A.bills.length)&&!(A!=null&&A.receipts.length)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.matchSheet.empty")})]}))]})]})})}function Ht({monthKind:s,year:i,month:r}){const{t:n}=X("bills"),c=Ve(),o=qe(),{permissions:x,currentOrganizationId:h}=ke(),u=x.includes("MANAGE_CREDIT_CARDS"),j=x.includes("MANAGE_BILLS"),D=x.includes("APPROVE_FINANCIAL_DOCUMENTS"),[M,y]=N.useState(null),A=s==="month"&&i!=null&&r!=null,P=de({queryKey:["cc-work-list",h,i,r],queryFn:()=>_.getWorkList({year:i,month:r}),enabled:!!h&&A}),S=()=>{o.invalidateQueries({queryKey:["cc-work-list",h]}),o.invalidateQueries({queryKey:["transactions"]})},p=d=>{me.error(Is(d,n("creditCards.workList.error")))},g=G({mutationFn:d=>_.createCardFeeBill(d),onSuccess:S,onError:p}),L=G({mutationFn:d=>_.ignoreTransaction(d.id,d.reason),onSuccess:S,onError:p}),I=G({mutationFn:d=>_.tieCardPayment(d.transactionId,d.bankTransactionId),onSuccess:S,onError:p}),k=G({mutationFn:d=>_.untieCardPayment(d),onSuccess:S,onError:p});if(!A)return e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.pickMonth")});if(P.isLoading)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Y,{className:"h-8 w-8 animate-spin text-muted-foreground"})});if(P.isError)return e.jsxs("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive",children:[e.jsx("p",{className:"text-sm",children:n("creditCards.workList.error")}),e.jsx(w,{variant:"outline",className:"mt-3 w-full sm:w-auto",onClick:()=>P.refetch(),children:n("creditCards.workList.tryAgain")})]});const f=P.data;if(!f||f.statements.length===0)return e.jsxs("div",{className:"rounded-lg border bg-white py-12 text-center",children:[e.jsx(ps,{className:"mx-auto mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-medium",children:n("creditCards.workList.emptyTitle")}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n("creditCards.workList.emptyBody")})]});const O=d=>{var b,F;return g.isPending&&g.variables===d||L.isPending&&((b=L.variables)==null?void 0:b.id)===d||I.isPending&&((F=I.variables)==null?void 0:F.transactionId)===d||k.isPending&&k.variables===d},T=(d,b)=>{y({mode:b,transaction:{id:d.id,merchantName:d.merchantName,transactionDate:d.transactionDate,amount:d.amountDollars,isCredit:d.isCredit,matchStatus:d.matchStatus,statement:{credit
1CardAccount:{lastFourDigits:d.lastFour}},matchedBill:d.matchedBill?{id:d.matchedBill.id,billNumber:d.matchedBill.billNumber,vendorName:d.matchedBill.vendorName,totalAmount:d.matchedBill.totalAmountCents/100}:null,matchedReceipt:d.matchedReceipt?{id:d.matchedReceipt.id,vendorName:d.matchedReceipt.vendorName,totalAmount:d.matchedReceipt.totalAmountDollars,receiptDate:d.transactionDate}:null}})};return e.jsxs("div",{className:"space-y-4",children:[f.statements.map(d=>d.tieOut.status==="failed"?e.jsxs("div",{className:"flex gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Ws,{className:"mt-0.5 h-4 w-4 flex-shrink-0"}),e.jsx("p",{children:n("creditCards.workList.tieFailed",{lastFour:d.lastFour,diff:xe(Math.abs(d.tieOut.diffCents??0)/100)})})]},d.id):d.tieOut.status==="unavailable"?e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:n("creditCards.workList.tieUnavailable",{lastFour:d.lastFour})},d.id):e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.tieOk",{lastFour:d.lastFour})},d.id)),f.allClear&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 p-4",children:[e.jsx(ms,{className:"h-5 w-5 text-green-600"}),e.jsx("p",{className:"font-medium",children:n("creditCards.workList.allClear")})]}),!f.allClear&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"font-medium",children:n("creditCards.workList.sections.charges")}),f.paperwork.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.sectionClear")}):e.jsx("div",{className:"divide-y rounded-lg border bg-white",children:f.paperwork.map(d=>e.jsx(Ss,{row:d,timezone:c,actions:u?e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:flex-wrap",children:[e.jsx(w,{variant:"outline",className:"w-full sm:w-auto",disabled:O(d.id),onClick:()=>T(d,d.kind==="issuer_fee"?"issuer_fee":"charge"),children:n("creditCards.workList.match")}),d.kind==="issuer_fee"&&(j?e.jsxs(w,{className:"w-full sm:w-auto",disabled:O(d.id),onClick:()=>g.mutate(d.id),children:[g.isPending&&g.variables===d.id?e.jsx(Y,{className:"mr-2 h-4 w-4 animate-spin"}):null,n("creditCards.workList.recordFee")]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.needBillsPermission")})),e.jsx(w,{variant:"outline",className:"w-full sm:w-auto",disabled:O(d.id),onClick:()=>L.mutate({id:d.id,reason:"PERSONAL"}),children:n("creditCards.workList.markPersonal")})]}):null,extra:d.kind==="issuer_fee"&&u&&j?e.jsx("p",{className:"text-xs text-muted-foreground",children:n("creditCards.workList.feeNotAlwaysInMonth")}):null},d.id))})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"font-medium",children:n("creditCards.workList.sections.returns")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.returnsHint")}),f.returns.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.sectionClear")}):e.jsx("div",{className:"divide-y rounded-lg border bg-white",children:f.returns.map(d=>{var b;return e.jsx(Ss,{row:d,timezone:c,actions:u?e.jsx(Gt,{row:d,pending:O(d.id),canApprove:D,onPersonal:()=>L.mutate({id:d.id,reason:"PERSONAL"}),onReturn:()=>L.mutate({id:d.id,reason:"REFUND"}),onTie:F=>I.mutate({transactionId:d.id,bankTransactionId:F}),tying:I.isPending&&((b=I.variables)==null?void 0:b.transactionId)===d.id}):null},d.id)})})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"font-medium",children:n("creditCards.workList.sections.payment")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.paymentHint")}
1),!f.bankDetailsVisible&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.bankHidden")}),f.payments.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:n("creditCards.workList.sectionClear")}):e.jsx("div",{className:"divide-y rounded-lg border bg-white",children:f.payments.map(d=>{var b;return e.jsx(Ss,{row:d,timezone:c,actions:u?e.jsx(Yt,{row:d,pending:O(d.id),canApprove:D,onTie:F=>I.mutate({transactionId:d.id,bankTransactionId:F}),onUntie:()=>k.mutate(d.id),tying:I.isPending&&((b=I.variables)==null?void 0:b.transactionId)===d.id,untying:k.isPending&&k.variables===d.id}):null},d.id)})})]})]}),e.jsx(Js,{transaction:(M==null?void 0:M.transaction)??null,mode:(M==null?void 0:M.mode)??"charge",onClose:()=>y(null)})]})}function Ss({row:s,timezone:i,actions:r,extra:n}){const{t:c}=X("bills");return e.jsxs("div",{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"truncate font-medium",children:s.merchantName}),s.kind==="issuer_fee"&&e.jsx(ye,{children:c("creditCards.workList.feeBadge")}),s.kind==="payment"&&e.jsx(ye,{children:c("creditCards.workList.paymentBadge")})]}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[z(s.transactionDate,i)," · **** ",s.lastFour]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[z(s.periodStart,i)," – ",z(s.periodEnd,i)]})]}),e.jsxs("p",{className:`text-lg font-semibold ${s.isCredit?"text-green-600":""}`,children:[s.isCredit?"+":"-",xe(s.amountDollars)]})]}),r,n]})}function Fs({candidate:s}){const{t:i}=X("bills"),r=s.hints.filter(n=>n!=="used");return e.jsxs("div",{className:"text-sm",children:[e.jsxs("p",{children:[z(s.transactionDate,"UTC"),s.description?` · ${s.description}`:""," ·"," ",it(s.amountCents)]}),s.hints.includes("used")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:i("creditCards.workList.usedWithdrawal")}),r.length>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r.join(", ")})]})}function Gt({row:s,pending:i,canApprove:r,onPersonal:n,onReturn:c,onTie:o,tying:x}){const{t:h}=X("bills"),u=(s.candidates??[]).filter(j=>j.selectable);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:flex-wrap",children:[e.jsx(w,{variant:"outline",className:"w-full sm:w-auto",disabled:i,onClick:c,children:h("creditCards.workList.markReturn")}),e.jsx(w,{variant:"outline",className:"w-full sm:w-auto",disabled:i,onClick:n,children:h("creditCards.workList.markPersonal")})]}),s.creditClass==="unknown"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:h("creditCards.workList.markPayment")}),s.assignment==="ambiguous"&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.paymentAmbiguous")}),s.assignment==="none"&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.paymentNone")}),u.map(j=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{candidate:j}),r?e.jsxs(w,{className:"w-full sm:w-auto",disabled:i,onClick:()=>o(j.id),children:[x?e.jsx(Y,{className:"mr-2 h-4 w-4 animate-spin"}):null,h("creditCards.workList.tie")]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.needBankPermission")})]},j.id))]})]})}function Yt({row:s,pending:i,canApprove:r,onTie:n,onUntie:c,tying:o,untying:x}){const{t:h}=X("bills"),u=s.candidates.filter(j=>j.selectable);return e.jsxs("div",{className:"space-y-2",children:[s.assignment==="ambiguous"&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.paymentAmbiguous")}),s.assignment==="none"&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.paymentNone")}),s.assignment==="tied"&&e.jsxs(e.Fragment,{children:[s.pairingUnique?e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.paymentTied")}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.paymentTiedAmount")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.untieAmbiguous")})]}),s.pairingUnique&&s.candidates.map(j=>e.jsx(Fs,{candidate:j},j.id))]}),s.assignment!=="tied"&&u.map(j=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{candidate:j}),r?e.jsxs(w,{className:"w-full sm:w-auto",disabled:i,onClick:()=>n(j.id),children:[o?e.jsx(Y,{className:"mr-2 h-4 w-4 animate-spin"}):null,h("creditCards.workList.tie")]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.needBankPermission")})]},j.id)),s.assignment==="tied"&&(r?e.jsxs(w,{variant:"outline",className:"w-full sm:w-auto",disabled:i,onClick:c,children:[x?e.jsx(Y,{className:"mr-2 h-4 w-4 animate-spin"}):null,h("creditCards.workList.untie")]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:h("creditCards.workList.needBankPermission")}))]})}const Xt=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function Ds(s){return String(s).padStart(2,"0")}function Zt(s,i,r){return new Date(Date.UTC(s,i-1,1)).toLocaleStr
1ing(r,{month:"long",year:"numeric",timeZone:"UTC"})}function Jt(s,i,r){return new Date(Date.UTC(s,i-1,1)).toLocaleString(r,{month:"long",timeZone:"UTC"})}function et({value:s,monthsWithData:i,reviewCounts:r,onChange:n,showReviewBadge:c=!1}){const{t:o,i18n:x}=X("financialDocuments"),h=N.useMemo(()=>{const g=new Set;return i.forEach(L=>g.add(Number(L.slice(0,4)))),Array.from(g).sort()},[i]),u=h[h.length-1],j=s==="all"?"all":`${s.year}-${Ds(s.month)}`,[D,M]=N.useState(()=>(s==="all"?u:s.year)||u||new Date().getUTCFullYear());N.useEffect(()=>{if(j==="all"){u&&M(u);return}M(Number(j.slice(0,4)))},[j,u]);const y=s==="all"?null:s.year,A=s==="all"?null:s.month,P=s==="all"?o("months.all"):o("monthPicker.trigger",{label:Zt(s.year,s.month,x.language)}),S=[...h].reverse().find(g=>g<D),p=h.find(g=>g>D);return e.jsxs(It,{children:[e.jsx(Mt,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border bg-background px-3 py-1.5 text-sm font-medium","aria-haspopup":"menu","aria-label":o("monthPicker.chooseMonth"),children:[P,e.jsx(Ct,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Rt,{align:"start",className:"w-[18rem] p-2",children:[e.jsxs("div",{className:"flex items-center justify-between px-1 pb-2",children:[e.jsx("button",{type:"button",className:"rounded p-1 hover:bg-muted disabled:opacity-30",disabled:!S,onClick:()=>S&&M(S),"aria-label":String(S||""),children:e.jsx(vt,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium tabular-nums",children:D}),e.jsx("button",{type:"button",className:"rounded p-1 hover:bg-muted disabled:opacity-30",disabled:!p,onClick:()=>p&&M(p),"aria-label":String(p||""),children:e.jsx(Ls,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:Xt.map((g,L)=>{const I=L+1,k=`${D}-${Ds(I)}`,f=i.has(k),O=c&&(r==null?void 0:r.get(k))||0,T=y===D&&A===I;return e.jsx(Us,{disabled:!f,onClick:()=>{f&&n(`${D}-${Ds(I)}`)},className:Ps("h-10 justify-center px-1 text-center",T&&f&&"bg-muted font-semibold",!f&&"opacity-40"),"aria-label":Jt(D,I,x.language),children:e.jsxs("span",{className:"flex flex-col items-center leading-tight",children:[e.jsx("span",{children:o(`months.${g}`)}),O>0&&e.jsx(ye,{variant:"secondary",className:"mt-0.5 h-4 px-1 text-[10px] font-normal",title:o("monthPicker.reviewCount",{count:O}),children:O})]})},k)})}),e.jsx(Us,{className:"mt-1 justify-center font-medium",onClick:()=>n("all"),children:o("months.all")})]})]})}function ea(s,i){return s.filter(r=>gs(r.periodStart,r.periodEnd)===i).map(r=>({cardId:r.creditCardAccountId,statementId:r.id}))}function sa(s,i){const r=new Map(i.map(c=>[c.id,c])),n=[];for(const c of s){const o=r.get(c.creditCardAccountId)??null;for(const x of c.transactions||[])n.push({...x,statement:{id:c.id,creditCardAccountId:c.creditCardAccountId,periodStart:c.periodStart,periodEnd:c.periodEnd,creditCardAccount:o}})}return n}const ta=".csv,.pdf,text/csv,application/pdf",aa=12,na=2;function st(s){var r;if(((r=s.result)==null?void 0:r.detectedFormat)!=="pdf")return!1;const i=s.result.cards||[];return i.length===0||i.every(n=>n.lastFourDigits==="0000")}function ra(s){return!st(s)||s.assignedCardId?!0:/^\d{4}$/.test(s.assignedLastFour||"")}function zs(s){return s.name.toLowerCase().endsWith(".zip")||s.type==="application/zip"||s.type==="application/x-zip-compressed"}function qs(s){return s.name.toLowerCase().endsWith(".csv")||s.type==="text/csv"}function ia(s){return s.name.toLowerCase().endsWith(".pdf")||s.type==="application/pdf"}function la(s){return s.code==="ECONNABORTED"||/timeout of \d+ms exceeded/i.test(s.message||"")}function Vs(s,i,r){var c,o;if(r&&la(s))return r;const n=(o=(c=s.response)==null?void 0:c.data)==null?void 0:o.message;return Array.isArray(n)?n.join(", "):typeof n=="string"&&n?n:s.message||i}function da(s){const i=new Map;let r=0,n=0,c=0,o=0;const x=new Set;for(const h of s){r+=h.summary.totalTransactions,n+=h.summary.totalAmount,c+=h.summary.newCardsCreated,o+=h.summary.duplicatesSkipped,h.summary.detectedFormat&&x.add(h.summary.detectedFormat);for(const u of h.cards){const j=i.get(u.id);j?i.set(u.id,{...j,transactionCount:j.transactionCount+u.transactionCount,amount:j.amount+u.amount,isNew:j.isNew||u.isNew}):i.set(u.id,{...u})}}return{summary:{totalTransactions:r,totalAmount:n,cardsFound:i.size,newCardsCreated:c,detectedFormat:[...x].join(", ")||"generic",duplicatesSkipped:o},cards:[...i.values()]}}function ca(){var a;const{t:s}=X("bills"),i=qe(),{permissions:r,currentOrganizationId:n}=ke(),c=Ve(),o=r.includes("MANAGE_CREDIT_CARDS"),[x,h]=Ns(),{subTab:u,transactionFilter:j}=Tt(x),D=t=>us(h,t,j),M=t=>us(h,u,t),y=N.useRef(null),[A,P]=N.useState(null),[S,p]=N.useState(null),[g,L]=N.useState(!1),[I,k]=N.useState(!1),[f,O]=N.useState(null),[T,d]=N.useState([]),[b,F]=N.useState(null),[C,ce]=N.useState(!1),[E,ee]=N.useState(null),[Z,ne]=N.useState(!1),[q,he]=N.useState([]),[_e,es]=N.useState(!1),[Qe,we]=N.useState(null),[Se,pe]=N.useState(null),[U,re]=N.useState({name:"",cardholderName:"",bankName:"",cardType:"OTHER_CARD",color:""}),[W,De]=N.useState(null),[We,ge]=N.useState(null),[bs,Te]=N.useState(!1),[oe,He]=N.useState(""),[Ee,ss]=N.useState("generic"),{data:ie,isLoading:Fe}=de({queryKey:["credit-cards",n],queryFn:_.getAllCards,enabled:!!n}),$=(ie==null?void 0:ie.data)||[],Q=Hs(x),V=Gs(x),fe=Q.kind==="month"?`${Q.year}-${String(Q.month).padStart(2,"0")}`:"all",Cs=Q.kind==="month"?{year:Q.year,month:Q.month}:"all",Ge=de({queryKey:["credit-cards",n,"statements-index"],queryFn:async()=>(await Promise.all($.map(l=>_.getStatements(l.id)))).flat(),enabled:!!n&&$.length>0,staleTime:6e4}),$e=Ge.data??[],Oe=N.useMemo(()=>{const t=new Set;for(const l of $e){const m=gs(l.periodStart,l.periodEnd);m&&t.add(m)}return t},[$e]),{data:Ae,isLoading:vs}=de({queryKey:["transactions",j,n,fe,(V==null?void 0:V.from)??"",(V==null?void 0:V.to)??""],queryFn:async()=>{const t=j==="unmatched"?"UNMATCHED":j==="matched"?"AUTO_MATCHED":void 0;if(V)return _.getAllTransactions({limit:100,startDate:V.from,endDate:V.to,matchStatus:t});if(fe==="all")return _.getAllTransactions({limit:50,matchStatus:t});const l=ea($e,fe);if(l.length===0)return{data:[],pagination:{page:1,limit:0,total:0,totalPages:0}};const m=await Promise.all(l.map(({cardId:R,statementId:K})=>
1_.getStatement(R,K,!0)));let v=sa(m,$);return j==="unmatched"?v=v.filter(R=>R.matchStatus==="UNMATCHED"):j==="matched"&&(v=v.filter(R=>R.matchStatus==="AUTO_MATCHED"||R.matchStatus==="MANUAL_MATCHED")),v.sort((R,K)=>new Date(K.transactionDate).getTime()-new Date(R.transactionDate).getTime()),{data:v,pagination:{page:1,limit:v.length,total:v.length,totalPages:1}}},enabled:!!n&&u==="transactions"&&j!=="work"&&(V!=null||fe==="all"||Ge.isFetched&&!Ge.isFetching||!Fe&&$.length===0)}),le=(Ae==null?void 0:Ae.data)||[],H=((a=Ae==null?void 0:Ae.pagination)==null?void 0:a.total)??le.length,J=G({mutationFn:_.deleteCard,onSuccess:()=>{i.invalidateQueries({queryKey:["credit-cards",n]}),i.invalidateQueries({queryKey:["transactions"]}),i.invalidateQueries({queryKey:["expense-stats"]}),ts()}}),Ye=async t=>{var l,m,v,R,K;F(t),He(""),De(null),ge(null),Te(!0);try{const se=await _.getCardDeletionDetails(t);De(se)}catch(se){const je=se;((l=je.response)==null?void 0:l.status)===403?ge(((v=(m=je.response)==null?void 0:m.data)==null?void 0:v.message)||s("creditCards.errors.noDeletePermission")):ge(((K=(R=je.response)==null?void 0:R.data)==null?void 0:K.message)||je.message||s("creditCards.errors.loadDeletionDetails"))}finally{Te(!1)}},ts=()=>{F(null),De(null),ge(null),He("")},Le=G({mutationFn:({cardId:t,data:l})=>_.updateCard(t,l),onSuccess:()=>{i.invalidateQueries({queryKey:["credit-cards"]}),pe(null)}}),Ie=t=>{re({name:t.name,cardholderName:t.cardholderName||"",bankName:t.bankName||"",cardType:t.cardType,color:t.color||""}),pe(t)},ys=()=>{Se&&Le.mutate({cardId:Se.id,data:{name:U.name,cardholderName:U.cardholderName||void 0,bankName:U.bankName||void 0,cardType:U.cardType,color:U.color||void 0}})},as=async t=>{const l=t.filter(zs),m=t.filter(K=>!zs(K));if(l.length>0&&me.error(s("creditCards.errors.zipNotAllowed")),m.length===0)return;if(m.length>aa){me.error(s("creditCards.errors.tooManyFiles"));return}ee(null),es(!0),we({done:0,total:m.length});const v=new Array(m.length),R=m.some(ia)?1:na;try{for(let K=0;K<m.length;K+=R){const se=m.slice(K,K+R);(await Promise.allSettled(se.map(Ke=>_.previewImport(Ke,{format:qs(Ke)?Ee:void 0})))).forEach((Ke,ks)=>{const Ms=se[ks];if(Ke.status==="fulfilled")v[K+ks]={file:Ms,result:Ke.value};else{const tt=Ke.reason;v[K+ks]={file:Ms,error:Vs(tt,s("creditCards.errors.analyzeFile"),s("creditCards.errors.readTimeout"))}}}),we({done:Math.min(K+se.length,m.length),total:m.length})}}finally{es(!1),we(null)}he(v.filter(Boolean)),L(!1),ne(!0)},Me=async t=>{const l=Array.from(t.target.files??[]);y.current&&(y.current.value=""),l.length!==0&&await as(l)},Re=async t=>{t.preventDefault();const l=Array.from(t.dataTransfer.files??[]);l.length!==0&&await as(l)},Be=q.filter(t=>{var l;return(l=t.result)==null?void 0:l.canImport}),ns=q.filter(t=>t.error),rs=Be.reduce((t,l)=>{var m;return t+(((m=l.result)==null?void 0:m.newTransactions)||0)},0),Xe=q.reduce((t,l)=>{var m;return t+(((m=l.result)==null?void 0:m.duplicateTransactions)||0)},0),Ue=Be.length>0,is=Ue&&Be.every(t=>ra(t)),ls=async()=>{if(!is)return;ce(!0),ee(null),d([]);const t=[],l=[];try{for(const m of Be)try{t.push(await _.importStatement(m.file,{format:qs(m.file)?Ee:void 0,cardId:m.assignedCardId,lastFourDigits:m.assignedCardId?void 0:m.assignedLastFour}))}catch(v){l.push(s("creditCards.preview.fileFailed",{name:m.file.name,error:Vs(v,s("creditCards.errors.import"),s("creditCards.errors.readTimeout"))}))}}finally{ce(!1)}i.invalidateQueries({queryKey:["credit-cards"]}),i.invalidateQueries({queryKey:["transactions"]}),i.invalidateQueries({queryKey:["expense-stats"]}),i.invalidateQueries({queryKey:["transactions-unmatched"]}),ne(!1),he([]),t.length>0?(O(da(t)),d(l),k(!0)):(ee(l.join(`
2`)||s("creditCards.errors.import")),L(!0))},ds=()=>{ne(!1),he([])};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(xs,{value:u,onValueChange:t=>D(t),children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(hs,{className:"grid w-full grid-cols-2 sm:w-auto 
2sm:inline-flex",children:[e.jsx(ue,{value:"cards",children:s("creditCards.tabs.cards")}),e.jsx(ue,{value:"transactions",children:s("creditCards.tabs.transactions")})]}),Oe.size>0&&e.jsx(et,{value:Cs,monthsWithData:Oe,onChange:t=>Ys(h,t)})]}),o&&e.jsxs(w,{className:"w-full sm:w-auto",onClick:()=>{ee(null),L(!0)},children:[e.jsx(Je,{className:"h-4 w-4 mr-2"}),e.jsx("span",{className:"sm:hidden",children:s("creditCards.importTransactionsShort")}),e.jsx("span",{className:"hidden sm:inline",children:s("creditCards.importTransactions")})]})]}),e.jsx(Rs,{value:"cards",className:"mt-4",children:Fe?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Y,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):$.length===0?e.jsxs("div",{className:"text-center py-12 bg-white rounded-lg border",children:[e.jsx(_s,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium",children:s("creditCards.empty.title")}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-md mx-auto",children:s("creditCards.empty.description")}),o&&e.jsxs(w,{className:"mt-4",onClick:()=>{ee(null),L(!0)},children:[e.jsx(Je,{className:"h-4 w-4 mr-2"}),s("creditCards.importTransactions")]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:$.map(t=>{var l;return e.jsxs("div",{className:"relative rounded-xl overflow-hidden cursor-pointer transition-transform hover:scale-[1.02]",onClick:()=>P(t),children:[e.jsxs("div",{className:`${As(t.color)} p-6 text-white h-[200px] flex flex-col`,children:[e.jsxs("div",{className:"flex justify-between items-start gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-white/80 text-sm",children:t.bankName||s("creditCards.card.defaultBank")}),e.jsx("h3",{className:"font-bold text-lg truncate",title:t.name,children:t.name})]}),e.jsx(ye,{variant:"outline",className:"bg-white/20 border-white/30 text-white flex-shrink-0",children:Qs(t.cardType)})]}),e.jsx("div",{className:"mt-auto",children:e.jsxs("p",{className:"text-2xl font-mono tracking-wider",children:["**** **** **** ",t.lastFourDigits]})}),e.jsxs("div",{className:"mt-4 flex justify-between items-end",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-white/60 text-xs",children:s("creditCards.card.cardholder")}),e.jsx("p",{className:"font-medium truncate",title:t.cardholderName||s("creditCards.card.notSpecified"),children:t.cardholderName||s("creditCards.card.notSpecified")})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("p",{className:"text-white/60 text-xs",children:s("creditCards.card.statements")}),e.jsx("p",{className:"font-medium",children:((l=t._count)==null?void 0:l.statements)||0})]})]})]}),o&&e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 hover:opacity-100 transition-opacity",children:[e.jsx(w,{size:"sm",variant:"secondary",className:"h-8 w-8 p-0",onClick:m=>{m.stopPropagation(),Ie(t)},children:e.jsx(yt,{className:"h-4 w-4"})}),e.jsx(w,{size:"sm",variant:"secondary",className:"h-8 w-8 p-0 text-destructive",onClick:m=>{m.stopPropagation(),Ye(t.id)},children:e.jsx(kt,{className:"h-4 w-4"})})]})]},t.id)})})}),e.jsxs(Rs,{value:"transactions",className:"mt-4 space-y-4",children:[e.jsx(xs,{value:j,onValueChange:t=>M(t),children:e.jsxs(hs,{children:[e.jsx(ue,{value:"work",children:s("creditCards.filter.toVerify")}),e.jsx(ue,{value:"all",children:s("creditCards.filter.all")}),e.jsx(ue,{value:"unmatched",children:s("creditCards.filter.unmatched")}),e.jsx(ue,{value:"matched",children:s("creditCards.filter.matched")})]})}),j==="work"?e.jsx(Ht,{monthKind:Q.kind,year:Q.kind==="month"?Q.year:null,month:Q.kind==="month"?Q.month:null}):e.jsxs(e.Fragment,{children:[V&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s("txnRange.hint",{from:V.from,to:V.to}),H>le.length?` ${s("txnRange.truncated",{shown:le.length,total:H})}`:""]}),vs?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Y,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):le.length===0?e.jsxs("div",{className:"text-center py-12 bg-white rounded-lg border",children:[e.jsx(ps,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium",children:s("creditCards.noTransactions.title")}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s("creditCards.noTransactions.description")})]}):e.jsx("div",{className:"bg-white rounded-lg border divide-y",children:le.map(t=>{var l;return e.jsxs("div",{className:"p-4 hover:bg-muted/50 flex items-center gap-4 cursor-pointer",onClick:()=>p(t),children:[e.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 bg-muted",children:t.matchStatus==="UNMATCHED"?e.jsx(js,{className:"h-5 w-5 text-red-500"}):t.matchStatus==="AUTO_MATCHED"||t.matchStatus==="MANUAL_MATCHED"?e.jsx(wt,{className:"h-5 w-5 text-green-500"}):t.matchStatus==="DISPUTED"?e.jsx(Ws,{className:"h-5 w-5 text-orange-500"}):e.jsx(ps,{className:"h-5 w-5 text-blue-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-medium truncate",children:t.merchantName}),e.jsx(ye,{className:dt(t.matchStatus),children:lt(t.matchStatus)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(St,{className:"h-3 w-3"}),z(t.transactionDate,c)]}),t.merchantCategory&&e.jsx("span",{children:t.merchantCategory}),((l=t.statement)==null?void 0:l.creditCardAccount)&&e.jsxs("span",{children:["**** ",t.statement.credit
2CardAccount.lastFourDigits]})]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsxs("p",{className:`text-lg font-semibold ${t.isCredit?"text-green-600":""}`,children:[t.isCredit?"+":"-",xe(t.amount)]}),t.matchedReceipt&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s("creditCards.matchedAmount",{amount:xe(t.matchedReceipt.totalAmount)})}),t.matchedBill&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s("creditCards.matchedBill",{billNumber:t.matchedBill.billNumber,vendor:t.matchedBill.vendorName})})]}),e.jsx(w,{variant:"ghost",size:"sm",children:e.jsx(Ls,{className:"h-4 w-4"})})]},t.id)})})]})]})]}),e.jsx(Ne,{open:g,onOpenChange:L,children:e.jsxs(be,{children:[e.jsx(Ce,{children:e.jsx(ve,{children:s("creditCards.importDialog.title")})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("creditCards.importDialog.description")}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{children:s("creditCards.importDialog.bankFormat")}),e.jsxs(ws,{value:Ee,onChange:t=>ss(t.target.value),children:[e.jsx("option",{value:"generic",children:s("creditCards.importDialog.autoDetect")}),e.jsx("option",{value:"chase",children:"Chase"}),e.jsx("option",{value:"amex",children:"American Express"}),e.jsx("option",{value:"capital_one",children:"Capital One"}),e.jsx("option",{value:"bank_of_america",children:"Bank of America"}),e.jsx("option",{value:"wells_fargo",children:"Wells Fargo"}),e.jsx("option",{value:"citi",children:"Citi"})]})]}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",onDragOver:t=>t.preventDefault(),onDrop:Re,children:[e.jsx("input",{ref:y,type:"file",accept:ta,multiple:!0,onChange:Me,className:"hidden"}),e.jsx(Je,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:s("creditCards.importDialog.dropHint")}),e.jsxs(w,{type:"button",variant:"outline",onClick:()=>{var t;return(t=y.current)==null?void 0:t.click()},disabled:_e,children:[_e?e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Je,{className:"h-4 w-4 mr-2"}),_e?Qe&&Qe.total>1?s("creditCards.importDialog.analyzingProgress",Qe):s("creditCards.importDialog.analyzing"):s("creditCards.importDialog.selectFile")]})]}),E&&e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-3 rounded-lg text-sm",children:[e.jsx("p",{className:"font-medium",children:s("creditCards.importDialog.failed")}),e.jsx("p",{className:"mt-1",children:E})]}),e.jsxs("div",{className:"text-xs text-muted-foreground bg-muted p-3 rounded-lg",children:[e.jsx("p",{className:"font-medium mb-1",children:s("creditCards.importDialog.supportedBanks")}),e.jsxs("ul",{className:"list-disc list-inside space-y-1",children:[e.jsx("li",{children:"Chase, American Express, Capital One"}),e.jsx("li",{children:"Bank of America, Wells Fargo, Citi"}),e.jsx("li",{children:s("creditCards.importDialog.anyCsv")}),e.jsx("li",{children:s("creditCards.importDialog.anyPdf")})]}),e.jsx("p",{className:"mt-2 text-muted-foreground/80",children:s("creditCards.importDialog.exportHint")})]})]})]})}),e.jsx(Ne,{open:I,onOpenChange:k,children:e.jsxs(be,{className:"max-w-md",children:[e.jsx(Ce,{children:e.jsxs(ve,{className:"flex items-center gap-2",children:[T.length>0?e.jsx(cs,{className:"h-5 w-5 text-amber-500"}):e.jsx(ms,{className:"h-5 w-5 text-green-500"}),s("creditCards.result.title")]})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-muted p-3 rounded-lg text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:f.summary.totalTransactions}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("creditCards.result.transactions")})]}),e.jsxs("div",{className:"bg-muted p-3 rounded-lg text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:xe(f.summary.totalAmount)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("creditCards.result.totalAmount")})]})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium mb-2",children:[s("creditCards.result.cardsFound",{count:f.summary.cardsFound}),f.summary.newCardsCreated>0&&e.jsx("span",{className:"text-muted-foreground ml-1",children:s("creditCards.result.newCount",{count:f.summary.newCardsCreated})})]}),e.jsx("div",{className:"space-y-2",children:f.cards.map(t=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"font-mono",children:["**** ",t.lastFourDigits]}),t.isNew&&e.jsxs(ye,{variant:"secondary",className:"text-xs",children:[e.jsx(Dt,{className:"h-3 w-3 mr-1"}),s("creditCards.result.new")]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-medium",children:xe(t.amount)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("creditCards.result.transactionCount",{count:t.transactionCount})})]})]},t.id))})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[f.summary.duplicatesSkipped>0&&e.jsx("p",{className:"text-amber-600",children:s("creditCards.result.duplicatesSkipped",{count:f.summary.duplicatesSkipped})}),T.length>0&&e.jsx("ul",{className:"text-red-600 space-y-1",children:T.map(t=>e.jsx("li",{children:t},t))}),e.jsx("p",{children:s("creditCards.result.detectedFormat",{format:f.summary.detectedFormat})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{className:"w-full",onClick:()=>{k(!1),us(h,"transactions","work")},children:s("creditCards.result.reviewCharges")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("creditCards.result.noPrintedTotals")}),e.jsx(w,{variant:"outline",className:"w-full",onClick:()=>k(!1),children:s("creditCards.result.done")})]})]})]})}),e.jsx(Ne,{open:Z,onOpenChange:t=>!t&&ds(),children:e.jsxs(be,{className:"max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsx(Ce,{children:e.jsx(ve,{className:"flex items-center gap-2",children:Ue?Xe>0?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"h-5 w-5 text-amber-500"}),s("creditCards.preview.duplicatesDetected")]}):e.jsxs(e.Fragment,{children:[e.jsx(ms,{className:"h-5 w-5 text-green-500"}),s("creditCards.preview.readyToImport")]}):e.jsxs(e.Fragment,{children:[e.jsx($s,{className:"h-5 w-5 text-red-500"}),s("creditCards.preview.cannotImport")]})})}),q.length>0&&e.jsxs("div",{className:"space-y-4",children:[ns.length>0&&e.jsx("p",{className:"text-sm text-red-600",children:s("creditCards.preview.filesFailed",{count:ns.length})}),Ue&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-green-50 border border-green-200 p-3 rounded-lg text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-green-700",children:rs}),e.jsx("p",{className:"text-xs text-green-600",children:s("creditCards.preview.newTransactions")})]}),Xe>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 p-3 rounded-lg text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-700",children:Xe}),e.jsx("p",{className:"text-xs text-amber-600",children:s("creditCards.preview.duplicatesSkip")})]})]}),e.jsx("div",{className:"space-y-2",children:q.map((t,l)=>{var m;return e.jsxs("div",{className:"p-2 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"font-medium truncate",children:t.file.name}),t.error?e.jsx($s,{className:"h-4 w-4 text-red-500 flex-shrink-0"}):(m=t.result)!=null&&m.canImport?e.jsx(ms,{className:"h-4 w-4 text-green-500 flex-shrink-0"}):e.jsx(cs,{className:"h-4 w-4 text-amber-500 flex-shrink-0"})]}),t.error?e.jsx("p",{className:"text-xs text-red-600 mt-1",children:t.error}):t.result?e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t.result.message}):null,st(t)&&e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("p",{className:"text-xs text-amber-700",children:s("creditCards.preview.lastFourRequired")}),$.length>0&&e.jsxs(ws,{value:t.assignedCardId||"",onChange:v=>{const R=v.target.value||void 0;he(K=>K.map((se,je)=>je===l?{...se,assignedCardId:R,assignedLastFour:""}:se))},children:[e.jsx("option",{value:"",children:s("creditCards.preview.chooseCard")}),$.map(v=>e.jsxs("option",{value:v.id,children:["**** ",v.lastFourDigits,v.name?` · ${v.name}`:""]},v.id))]}),!t.assignedCardId&&e.jsx(Ze,{inputMode:"numeric",maxLength:4,placeholder:s("creditCards.preview.lastFourPlaceholder"),value:t.assignedLastFour||"",onChange:v=>{const R=v.target.value.replace(/\D/g,"").slice(0,4);he(K=>K.map((se,je)=>je===l?{...se,assignedLastFour:R}:se))}})]})]},`${l}-${t.file.name}-${t.file.size}`)})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(w,{variant:"outline",onClick:ds,children:s("creditCards.preview.cancel")}),Ue&&e.jsxs(w,{onClick:ls,disabled:C||!is,children:[C?e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}):null,q.length>1?s("creditCards.preview.importFiles",{count:Be.length}):s("creditCards.preview.importCount",{count:rs})]})]})]})]})}),e.jsx(Js,{transaction:S,onClose:()=>p(null)}),e.jsx(Qt,{card:A,onClose:()=>P(null),onImport:()=>L(!0),isImportOpen:g}),e.jsx(ut,{open:!!b,onOpenChange:ts,children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(pt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(cs,{className:"h-5 w-5"}),s("creditCards.delete.title")]}),e.jsx(gt,{asChild:!0,children:e.jsx("div",{className:"space-y-4 text-left",children:bs?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Y,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):We?e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:[e.jsx("p",{className:"font-medium",children:s("creditCards.delete.cannotDelete")}),e.jsx("p",{className:"text-sm mt-1",children:We})]}):W?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-muted p-3 rounded-lg",children:[e.jsx("p",{className:"font-medium",children:W.card.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["**** ",W.card.lastFourDigits,W.card.cardholderName&&` - ${W.card.cardholderName}`]})]}),e.jsxs("div",{className:"bg-destructive/5 border border-destructive/20 rounded-lg p-4 space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive text-sm",children:s("creditCards.delete.willDelete")}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground",children:[e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{children:s("creditCards.delete.statements")}),e.jsx("span",{className:"font-medium text-foreground",children:W.statementCount})]}),e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{children:s("creditCards.delete.transactions")}),e.jsx("span",{className:"font-medium text-foreground",children:W.transactionCount})]}),e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{children:s("creditCards.delete.totalAmount")}),e.jsx("span",{className:"font-medium text-foreground",children:xe(W.totalAmount)})]}),W.dateRange.start&&W.dateRange.end&&e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{children:s("creditCards.delete.dateRange")}),e.jsxs("span",{className:"font-medium text-foreground",children:[z(W.dateRange.start,c)," -"," ",z(W.dateRange.end,c)]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{className:"text-sm",children:e.jsx(at,{t:s,i18nKey:"creditCards.delete.confirmPrompt",components:{code:e.jsx("span",{className:"font-mono font-bold"})}})}),e.jsx(Ze,{value:oe,onChange:t=>He(t.target.value),placeholder:"DELETE",className:"font-mono"})]})]}):null})})]}),e.jsxs(ft,{children:[e.jsx(jt,{children:s("creditCards.delete.cancel")}),e.jsxs(Nt,{onClick:()=>b&&J.mutate(b),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:!W||oe!=="DELETE"||J.isPending,children:[J.isPending?e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}):null,s("creditCards.delete.confirm")]})]})]})}),e.jsx(Ne,{open:!!Se,onOpenChange:()=>pe(null),children:e.jsxs(be,{children:[e.jsx(Ce,{children:e.jsx(ve,{children:s("creditCards.edit.title")})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{children:s("creditCards.edit.cardName")}),e.jsx(Ze,{value:U.name,onChange:t=>re({...U,name:t.target.value}),placeholder:s("creditCards.edit.cardNamePlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{children:s("creditCards.edit.cardholderName")}),e.jsx(Ze,{value:U.cardholderName,onChange:t=>re({...U,cardholderName:t.target.value}),placeholder:s("creditCards.edit.cardholderPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{children:s("creditCards.edit.bankName")}),e.jsx(Ze,{value:U.bankName,onChange:t=>re({...U,bankName:t.target.value}),placeholder:s("creditCards.edit.bankNamePlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{children:s("creditCards.edit.cardType")}
2),e.jsxs(ws,{value:U.cardType,onChange:t=>re({...U,cardType:t.target.value}),children:[e.jsx("option",{value:"VISA",children:"Visa"}),e.jsx("option",{value:"MASTERCARD",children:"Mastercard"}),e.jsx("option",{value:"AMEX",children:"American Express"}),e.jsx("option",{value:"DISCOVER",children:"Discover"}),e.jsx("option",{value:"OTHER_CARD",children:s("creditCards.edit.cardTypeOther")})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Pe,{children:s("creditCards.edit.color")}),e.jsx("div",{className:"flex gap-2",children:["blue","green","purple","red","orange","gold"].map(t=>e.jsx("button",{type:"button",className:`w-8 h-8 rounded-full transition-transform ${U.color===t?"ring-2 ring-offset-2 ring-primary scale-110":""} ${As(t)}`,onClick:()=>re({...U,color:t})},t))})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(w,{variant:"outline",onClick:()=>pe(null),children:s("creditCards.edit.cancel")}),e.jsxs(w,{onClick:ys,disabled:Le.isPending,children:[Le.isPending?e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}):null,s("creditCards.edit.saveChanges")]})]})]})]})})]})}function oa({embedded:s=!1}){var x;const{t:i}=X("bills"),{currentOrganizationId:r}=ke(),[,n]=Ns(),{data:c}=de({queryKey:["transactions-unmatched",r],queryFn:()=>_.getAllTransactions({matchStatus:"UNMATCHED",limit:1}),enabled:!!r}),o=((x=c==null?void 0:c.pagination)==null?void 0:x.total)||0;return e.jsxs("div",{className:s?"space-y-4 sm:space-y-6":"p-4 sm:p-6 space-y-4 sm:space-y-6",children:[!s&&e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold",children:i("creditCards.pageTitle")}),e.jsx("p",{className:"hidden sm:block text-sm text-muted-foreground",children:i("creditCards.pageSubtitle")})]}),o>0&&e.jsxs("button",{type:"button",onClick:()=>us(n,"transactions","unmatched"),className:"flex w-full items-center gap-3 rounded-lg border bg-card px-3 py-2.5 text-left hover:bg-muted/50",children:[e.jsx("div",{className:"p-1.5 bg-red-100 dark:bg-red-900/30 rounded-md shrink-0",children:e.jsx(js,{className:"h-4 w-4 text-red-600 dark:text-red-400"})}),e.jsx("p",{className:"text-sm text-muted-foreground min-w-0",children:i("creditCards.unmatchedTransactions")}),e.jsx("p",{className:"ml-auto text-lg font-semibold tabular-nums",children:o}),e.jsx(Ls,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsx(ca,{})]})}function ma(s,i){const r={};return s.forEach(n=>{var o;const c=((o=n.salesChannel)==null?void 0:o.name)||n.vendor||i;if(r[c]||(r[c]={vendor:c,documents:[],totals:{deposits:0,withdrawals:0,fees:0}}),r[c].documents.push(n),n.status==="APPROVED"||n.status==="NEEDS_REVIEW"){const x=te(n.extractedData),h=n.type==="BANK_STATEMENT";r[c].totals.deposits+=h?(x==null?void 0:x.totalDeposits)??0:(x==null?void 0:x.newCharges)??0,r[c].totals.withdrawals+=h?(x==null?void 0:x.totalWithdrawals)??0:(x==null?void 0:x.payments)??0,r[c].totals.fees+=h?(x==null?void 0:x.totalFees)??0:(x==null?void 0:x.fees)??0}}),Object.values(r).sort((n,c)=>c.totals.deposits-n.totals.deposits)}function ua(s){if(!s.periodStart)return null;const i=z(s.periodStart,"UTC");return!s.periodEnd||s.periodEnd===s.periodStart?i:`${i} – ${z(s.periodEnd,"UTC")}`}function xa(s){const i=te(s.extractedData);return s.type==="BANK_STATEMENT"?(i==null?void 0:i.totalDeposits)??0:(i==null?void 0:i.newCharges)??0}function ha(s){const i=te(s.extractedData);return s.type==="BANK_STATEMENT"?(i==null?void 0:i.totalWithdrawals)??0:(i==null?void 0:i.payments)??0}function pa(s){const i=te(s.extractedData);return s.type==="BANK_STATEMENT"?i==null?void 0:i.endingBalance:i==null?void 0:i.newBalance}function ga(s){return s.filter(r=>r.status==="APPROVED"||r.status==="NEEDS_REVIEW").reduce((r,n)=>{const c=te(n.extractedData),o=n.type==="BANK_STATEMENT";return{deposits:r.deposits+(o?(c==null?void 0:c.totalDeposits)??0:(c==null?void 0:c.newCharges)??0),withdrawals:r.withdrawals+(o?(c==null?void 0:c.totalWithdrawals)??0:(c==null?void 0:c.payments)??0),fees:r.fees+(o?(c==null?void 0:c.totalFees)??0:(c==null?void 0:c.fees)??0)}},{deposits:0,withdrawals:0,fees:0})}function fa({documents:s,selectedIds:i,selectedDocId:r,sortField:n,sortDirection:c,monthNames:o,selectedYear:x,selectedMonth:h,pe
2ndingCount:u,collapsedVendors:j,onToggleSelect:D,onToggleSelectAll:M,onSort:y,onRowClick:A,onToggleVendor:P,renderRowActions:S,renderExpand:p}){const{t:g}=X("financialDocuments"),L=Zs(g),I=g("bankingGroup.unknown"),k=ma(s,I),f=ga(s),O=s.length>1,T=({field:b})=>e.jsx("span",{className:"ml-1 inline-block",children:n===b?c==="asc"?"↑":"↓":e.jsx("span",{className:"text-muted-foreground/30",children:"↕"})}),d=h?g("totals.monthYear",{month:o[h-1].toUpperCase(),year:x}):x?g("totals.year",{year:x}):g("totals.all");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"xl:hidden divide-y",children:[u>0&&e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:i.size>0&&i.size===u,onChange:M,className:"rounded"}),g("table.document")]}),k.map(b=>{const F=j.has(b.vendor);return e.jsxs("div",{className:"p-3",children:[e.jsxs("button",{type:"button",className:"w-full flex items-start justify-between gap-2 text-left",onClick:()=>P(b.vendor),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-semibold truncate",children:[F?"▶ ":"▼ ",b.vendor]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g("bankingGroup.statementCount",{count:b.documents.length})})]}),e.jsxs("div",{className:"text-right shrink-0 text-sm",children:[e.jsx("p",{className:"text-green-600",children:b.totals.deposits>0?`+${B(b.totals.deposits)}`:"—"}),e.jsx("p",{className:"text-red-600",children:b.totals.withdrawals>0?`-${B(b.totals.withdrawals)}`:"—"})]})]}),!F&&e.jsx("div",{className:"mt-2 space-y-2",children:b.documents.map(C=>{const ce=xa(C),E=ha(C),ee=C.status==="NEEDS_REVIEW";return e.jsxs("div",{className:Ps("rounded-md border p-3 space-y-2",r===C.id&&"ring-1 ring-primary"),children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("input",{type:"checkbox",checked:i.has(C.id),disabled:!ee,onChange:()=>D(C.id),onClick:Z=>Z.stopPropagation(),className:"rounded mt-1 shrink-0"}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>A(C.id),children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium break-words",children:C.displayTitle||C.originalName}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ua(C)||"—"})]}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium shrink-0 ${fs[C.status]}`,children:L[C.status]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-muted-foreground leading-tight",children:g("table.depositsCharges")}),e.jsx("p",{className:"font-medium tabular-nums text-green-600",children:ce>0?`+${B(ce)}`:"—"})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-muted-foreground leading-tight",children:g("table.withdrawalsPayments")}),e.jsx("p",{className:"font-medium tabular-nums text-red-600",children:E>0?`-${B(E)}`:"—"})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-muted-foreground leading-tight",children:g("table.balance")}),e.jsx("p",{className:"font-medium tabular-nums",children:B(pa(C))})]})]})]})]}),S!=null&&S(C)?e.jsx("div",{className:"flex justify-end",children:S(C)}):null,r===C.id&&(p==null?void 0:p(C))]},C.id)})})]},b.vendor)}),O?e.jsxs("div",{className:"p-3 text-sm bg-muted/40",children:[e.jsxs("p",{className:"font-medium",children:[d," ",g("bankingGroup.statementCount",{count:s.length})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-2 gap-x-3 gap-y-1 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:g("table.depositsCharges")}),e.jsx("span",{className:"text-right text-green-600",children:f.deposits>0?`+${B(f.deposits)}`:"—"}),e.jsx("span",{className:"text-muted-foreground",children:g("table.withdrawalsPayments")}),e.jsx("span",{className:"text-right text-red-600",children:f.withdrawals>0?`-${B(f.withdrawals)}`:"—"}),e.jsx("span",{className:"text-muted-foreground",children:g("table.fees")}),e.jsx("span",{className:"text-right text-amber-600",children:f.fees>0?B(f.fees):"—"}),e.jsx("span",{className:"font-medium",children:g("totals.netPrefix")}),e.jsx("span",{className:"text-right font-semibold",children:B(f.deposits-f.withdrawals-f.fees)})]})]}):null]}),e.jsx("div",{className:"hidden xl:block overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2 py-3 text-left text-sm font-medium w-8",children:e.jsx("input",{type:"checkbox",checked:i.size>0&&i.size===u,onChange:M,disabled:u===0,className:"rounded"})}),e.jsxs("th",{className:"px-4 py-3 text-left text-sm font-medium cursor-pointer hover:bg-muted/80",onClick:()=>y("name"),children:[g("table.document")," ",e.jsx(T,{field:"name"})]}),e.jsxs("th",{className:"px-4 py-3 text-left text-sm font-medium cursor-pointer hover:bg-muted/80",onClick:()=>y("period"),children:[g("table.period")," ",e.jsx(T,{field:"period"})]}),e.jsxs("th",{className:"px-4 py-3 text-right text-sm font-medium cursor-pointer hover:bg-muted/80",onClick:()=>y("deposits"),children:[g("table.depositsCharges")," ",e.jsx(T,{field:"deposits"})]}),e.jsxs("th",{className:"px-4 py-3 text-right text-sm font-medium cursor-pointer hover:bg-muted/80",onClick:()=>y("withdrawals"),children:[g("table.withdrawalsPayments")," ",e.jsx(T,{field:"withdrawals"})]}),e.jsx("th",{className:"px-4 py-3 text-right text-sm font-medium",children:g("table.fees")}),e.jsxs("th",{className:"px-4 py-3 text-right text-sm font-medium cursor-pointer hover:bg-muted/80",onClick:()=>y("balance"),children:[g("table.balance")," ",e.jsx(T,{field:"balance"})]}),e.jsxs("th",{className:"px-4 py-3 text-left text-sm font-medium cursor-pointer hover:bg-muted/80",onClick:()=>y("status"),children:[g("table.status")," ",e.jsx(T,{field:"status"})]}),S?e.jsx("th",{className:"px-4 py-3 text-right text-sm font-medium"}):null]})}),e.jsx("tbody",{children:k.map(b=>{const F=j.has(b.vendor);return e.jsxs(Es.Fragment,{children:[e.jsxs("tr",{className:"bg-muted/60 cursor-pointer hover:bg-muted/80 border-b",onClick:()=>
2P(b.vendor),children:[e.jsx("td",{className:"px-2 py-2 text-muted-foreground",children:F?"▶":"▼"}),e.jsx("td",{colSpan:2,className:"px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:b.vendor}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g("bankingGroup.statementCount",{count:b.documents.length})})]})}),e.jsx("td",{className:"px-4 py-2 text-sm text-right text-green-600 font-semibold",children:b.totals.deposits>0?`+${B(b.totals.deposits)}`:"—"}),e.jsx("td",{className:"px-4 py-2 text-sm text-right text-red-600 font-semibold",children:b.totals.withdrawals>0?`-${B(b.totals.withdrawals)}`:"—"}),e.jsx("td",{className:"px-4 py-2 text-sm text-right text-amber-600 font-semibold",children:b.totals.fees>0?B(b.totals.fees):"—"}),e.jsx("td",{className:"px-4 py-2"}),e.jsx("td",{className:"px-4 py-2"}),S?e.jsx("td",{className:"px-4 py-2"}):null]}),!F&&b.documents.map(C=>{const ce=i.has(C.id),E=te(C.extractedData),ee=C.status==="NEEDS_REVIEW",Z=C.type==="BANK_STATEMENT",ne=S?9:8;return e.jsxs(Es.Fragment,{children:[e.jsxs("tr",{className:Ps("border-b last:border-0 cursor-pointer hover:bg-muted/30",r===C.id&&"bg-blue-50 dark:bg-blue-950/30",C.isLocked&&"opacity-75"),onClick:()=>A(C.id),children:[e.jsx("td",{className:"px-2 py-3",onClick:q=>q.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:ce,onChange:()=>D(C.id),disabled:!ee,className:"rounded"})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[C.isLocked&&e.jsx("span",{title:g("table.locked"),children:"🔒"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:C.displayTitle||C.originalName}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g(Z?"docLabel.bankStatement":"docLabel.creditCard")})]})]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:C.periodStart?(()=>{const q=z(C.periodStart,"UTC");if(!C.periodEnd||C.periodEnd===C.periodStart)return q;const he=z(C.periodEnd,"UTC");return`${q} – ${he}`})():e.jsx("span",{className:"text-muted-foreground/50",children:"—"})}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-green-600 font-medium",children:Z?E!=null&&E.totalDeposits?`+${B(E.totalDeposits)}`:"—":E!=null&&E.newCharges?`+${B(E.newCharges)}`:"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-red-600",children:Z?E!=null&&E.totalWithdrawals?`-${B(E.totalWithdrawals)}`:"—":E!=null&&E.payments?`-${B(E.payments)}`:"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-amber-600",children:(()=>{const q=Z?E==null?void 0:E.totalFees:E==null?void 0:E.fees;return q&&q>0?B(q):"—"})()}),e.jsx("td",{className:"px-4 py-3 text-sm text-right font-medium",children:Z?B(E==null?void 0:E.endingBalance):B(E==null?void 0:E.newBalance)}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium ${fs[C.status]}`,children:[(C.status==="PENDING"||C.status==="PROCESSING")&&e.jsxs("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),L[C.status]]})}),S?e.jsx("td",{className:"px-4 py-3 text-right",onClick:q=>q.stopPropagation(),children:S(C)}):null]}),r===C.id&&p?e.jsx("tr",{className:"border-b bg-muted/10",children:e.jsx("td",{colSpan:ne,className:"p-0",children:p(C)})}):null]},C.id)})]},b.vendor)})}),O?e.jsx("tfoot",{className:"bg-muted/50 font-medium",children:e.jsxs("tr",{className:"border-t",children:[e.jsxs("td",{colSpan:3,className:"px-4 py-3 text-sm",children:[h?g("totals.monthYear",{month:o[h-1].toUpperCase(),year:x}):x?g("totals.year",{year:x}):g("totals.all")," ",g("bankingGroup.statementCount",{count:s.length})]}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-green-600",children:f.deposits>0?`+${B(f.deposits)}`:"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-red-600",children:f.withdrawals>0?`-${B(f.withdrawals)}`:"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-amber-600",children:f.fees>0?B(f.fees):"—"}),e.jsxs("td",{className:"px-4 py-3 text-sm text-right font-semibold",children:[g("totals.netPrefix")," ",B(f.deposits-f.withdrawals-f.fees)]}),e.jsx("td",{className:"px-4 py-3"}),S?e.jsx("td",{className:"px-4 py-3"}):null]})}):null]})})]})}function ja(s){const{documents:i,startDate:r,endDate:n,unknownVendor:c,filenamePrefix:o="banking-report"}=s,x=new Date(r),h=new Date(n),u=i.filter(P=>{if(!P.periodStart)return!1;const S=new Date(P.periodStart),p=P.periodEnd?new Date(P.periodEnd):S;return S<=h&&p>=x});if(u.length===0)return!1;const j=[];j.push(["Account/Card","Type","Period","Deposits/Charges","Withdrawals/Payments","Fees","Ending Balance","Status"]),u.forEach(P=>{var I;
2const S=((I=P.salesChannel)==null?void 0:I.name)||P.vendor||c,p=te(P.extractedData),g=P.type==="BANK_STATEMENT",L=P.periodStart?`${z(P.periodStart,"UTC")}${P.periodEnd?` - ${z(P.periodEnd,"UTC")}`:""}`:"";j.push([S,g?"Bank Statement":"Credit Card",L,os(g?p==null?void 0:p.totalDeposits:p==null?void 0:p.newCharges),os(g?p==null?void 0:p.totalWithdrawals:p==null?void 0:p.payments),os(g?p==null?void 0:p.totalFees:p==null?void 0:p.fees),os(g?p==null?void 0:p.endingBalance:p==null?void 0:p.newBalance),P.status])});const D=j.map(P=>P.map(S=>{const p=String(S).replace(/"/g,'""');return p.includes(",")||p.includes('"')||p.includes(`
3`)?`"${p}"`:p}).join(",")).join(`
4`),M=new Blob([D],{type:"text/csv;charset=utf-8;"}),y=URL.createObjectURL(M),A=document.createElement("a");return A.href=y,A.setAttribute("download",`${o}-${r}-to-${n}.csv`),document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(y),!0}function Na(s,i,r){return s==="FEE"?"fee":s==="INCOME"||s==="REFUND"?r==="card"?"payment":"deposit":s==="EXPENSE"||s==="TAX_PAID"?r==="card"?"charge":"withdrawal":s==="TRANSFER"?r==="card"?"payment":i>=0?"deposit":"withdrawal":i>=0?r==="card"?"payment":"deposit":r==="card"?"charge":"withdrawal"}function ba({doc:s,kind:i,onApprove:r,onViewPdf:n,onReprocess:c,checks:o,isApproving:x,isReprocessing:h}){const{t:u}=X("financialDocuments"),j=Xs(),D=!!o&&o.documentId===s.id,M=o==null?void 0:o.watch;N.useEffect(()=>{i!=="bank"||!M||s.status==="PENDING"||s.status==="PROCESSING"||M(s.id)},[i,s.id,s.status,M]);const{currentOrganizationId:y}=ke(),{data:A,isLoading:P}=de({queryKey:["financial-document",y,s.id],queryFn:()=>ae.getDocument(s.id),enabled:!!y&&!!s.id}),S=(A==null?void 0:A.transactions)||[],p=s.status==="PENDING"||s.status==="PROCESSING",g=s.status==="NEEDS_REVIEW"&&!s.isLocked,L=!s.isLocked&&s.status!=="PENDING",I=i==="bank",k=N.useRef(null);N.useEffect(()=>{var T;(T=k.current)==null||T.scrollIntoView({block:"nearest",behavior:"smooth"})},[]);const f="h-auto min-h-8 w-full whitespace-normal px-2 min-w-0 lg:h-9 lg:w-auto lg:whitespace-nowrap lg:px-3",O=e.jsxs("div",{className:"grid grid-cols-2 gap-2 lg:flex lg:flex-wrap [&>*:last-child:nth-child(odd)]:col-span-2 lg:[&>*:last-child:nth-child(odd)]:col-span-1",children:[g&&e.jsx(w,{className:f,size:"sm",onClick:r,disabled:x,children:u("actions.approve")}),e.jsx(w,{className:f,variant:"outline",size:"sm",onClick:n,children:u("actions.viewPdf")}),L&&e.jsx(w,{className:f,variant:"outline",size:"sm",onClick:c,disabled:h,children:u(h?"actions.reprocessing":"actions.reprocess")}),I&&!s.isLocked&&o?e.jsx(w,{className:f,variant:"outline",size:"sm",onClick:()=>void o.start(s.id),disabled:o.running&&o.documentId===s.id,children:o.running&&o.documentId===s.id?u("actions.analyzingChecks"):u("actions.analyzeChecks")}):null,e.jsx(ze,{className:"min-w-0",to:`/dashboard/financial-documents/${s.id}?from=statements`,children:e.jsx(w,{className:f,variant:"outline",size:"sm",children:u("actions.fullDetails")})})]});return e.jsxs("div",{ref:k,className:"space-y-2 p-2 sm:p-3 bg-muted/20",children:[O,I&&D&&o&&e.jsx(_t,{running:o.running,progress:o.progress,result:o.result,error:o.error,elapsed:o.elapsed,onSelectCheck:T=>{const d=new URLSearchParams({from:"statements",check:T.checkNumber});T.transactionId&&d.set("txn",T.transactionId),j(`/dashboard/financial-documents/${s.id}?${d.toString()}`)}}),P?e.jsx("p",{className:"text-sm text-muted-foreground",children:u("expand.processing")}):S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:u(p?"expand.processing":"exp
4and.empty")}):e.jsxs("div",{className:"max-w-4xl",children:[e.jsxs("div",{className:"hidden lg:grid lg:grid-cols-[7.5rem_minmax(0,1fr)_7rem_6.5rem] lg:gap-x-3 border-b pb-1 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{children:u("expand.col.date")}),e.jsx("span",{children:u("expand.col.description")}),e.jsx("span",{children:u("expand.col.direction")}),e.jsx("span",{className:"text-right",children:u("expand.col.amount")})]}),e.jsx("div",{children:S.map(T=>{const d=Na(T.type,T.amount,i),b=T.amount>=0?"text-green-600":"text-red-600";return e.jsxs("div",{className:"border-b py-2 last:border-0 lg:grid lg:grid-cols-[7.5rem_minmax(0,1fr)_7rem_6.5rem] lg:items-start lg:gap-x-3 lg:py-1.5",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3 lg:block",children:[e.jsx("span",{className:"text-sm whitespace-nowrap",children:z(T.date,"UTC")}),e.jsx("span",{className:`text-sm font-medium lg:hidden ${b}`,children:B(T.amount)})]}),e.jsxs("div",{className:"mt-0.5 min-w-0 text-sm lg:mt-0",children:[e.jsx("div",{className:"break-words",children:T.description}),T.checkPayee&&!T.description.includes(T.checkPayee)?e.jsx("div",{className:"text-xs text-muted-foreground",children:T.checkPayee}):null,T.checkNumber&&!T.checkPayee&&T.checkImageStorageKey?e.jsx("div",{className:"text-xs text-amber-700",children:u("checkAnalysis.nameUnreadable")}):null,e.jsx("div",{className:"text-xs text-muted-foreground lg:hidden",children:u(`expand.${d}`)})]}),e.jsx("div",{className:"hidden text-sm lg:block",children:u(`expand.${d}`)}),e.jsx("div",{className:`hidden text-right text-sm font-medium lg:block ${b}`,children:B(T.amount)})]},T.id)})})]})]})}const Ca=["TRANSFER","OWNER_DRAW","CARD_PAYMENT","PAYROLL","PERSONAL","NOT_AN_EXPENSE"];function va({transaction:s,onClose:i}){const{t:r}=X("salesTaxPeriod"),n=Ve(),c=qe(),{currentOrganizationId:o}=ke(),{hasPermission:x}=Vt(),h=x("APPROVE_FINANCIAL_DOCUMENTS"),[u,j]=N.useState("");N.useEffect(()=>{j("")},[s==null?void 0:s.id]);const{data:D,isLoading:M}=de({queryKey:["bank-match-suggestions",s==null?void 0:s.id,o],queryFn:()=>ae.getBankMatchSuggestions(s.id),enabled:!!(s!=null&&s.id)&&!!o}),y=()=>{c.invalidateQueries({queryKey:["bank-transactions-unmatched"]}),c.invalidateQueries({queryKey:["bank-match-suggestions"]}),c.invalidateQueries({queryKey:["books-statements"]}),c.invalidateQueries({queryKey:["bills-payment-mix"]}),c.invalidateQueries({queryKey:["bills-ai-summary"]})},A=G({mutationFn:k=>ae.matchBankTransaction(s.id,k),onSuccess:()=>{y(),i()}}),P=G({mutationFn:()=>ae.unmatchBankTransaction(s.id),onSuccess:()=>{y(),i()}}),S=G({mutationFn:()=>ae.ignoreBankTransaction(s.id,u),onSuccess:()=>{y(),i()}}),p=A.isPending||P.isPending||S.isPending,g=(s==null?void 0:s.matchStatus)==="AUTO_MATCHED"||(s==null?void 0:s.matchStatus)==="MANUAL_MATCHED",L=(s==null?void 0:s.matchStatus)==="UNMATCHED",I=k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-2 rounded-lg border bg-background",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:k.label}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r("books.matchSheet.confidence",{percent:Math.round(k.confidence*100)}),k.reasons[0]?` · ${k.reasons[0]}`:""]})]}),h&&e.jsx(w,{size:"sm",variant:"outline",disabled:p,onClick:()=>A.mutate(k.type==="bill_payment"?{billPaymentId:k.id}:{receiptId:k.id}),children:r("books.matchSheet.attach")})]},`${k.type}-${k.id}`);return e.jsx(Ne,{open:!!s,onOpenChange:k=>!k&&i(),children:e.jsxs(be,{className:"max-w-md max-h-[90vh] overflow-y-auto sm:max-h-[85vh]",children:[e.jsx(Ce,{children:e.jsx(ve,{children:r("books.matchSheet.title")})}),s&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:r("books.matchSheet.copy")}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.description}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[z(s.transactionDate,n),s.checkNumber?` · #${s.checkNumber}`:""]}),e.jsx("p",{className:"text-lg font-semibold mt-1",children:B(s.amount)})]}),g&&h&&e.jsxs(w,{variant:"outline",className:"w-full",disabled:p,onClick:()=>P.mutate(),children:[e.jsx(js,{className:"h-4 w-4 mr-2"}),r("books.matchSheet.unmatch")]}),L&&h&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx("p",{className:"text-sm font-medium",children:r("books.matchSheet.ignore")}),e.jsx(zt,{value:u,onValueChange:k=>j(k),name:"bank-ignore-reason",className:"space-y-2",children:Ca.map(k=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(qt,{value:k,id:`bank-ignore-${k}`}),e.jsx(Pe,{htmlFor:`bank-ignore-${k}`,className:"font-normal",children:r(`books.matchSheet.ignoreReasons.${k}`)})]},k))}),e.jsx(w,{variant:"outline",className:"w-full",disabled:p||!u,onClick:()=>S.mutate(),children:r("books.matchSheet.ignoreConfirm")})]}),L&&(M?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Y,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[((D==null?void 0:D.billPayments.length)||0)>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:r("books.matchSheet.billPayments")}),D.billPayments.map(I)]}),((D==null?void 0:D.receipts.length)||0)>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:r("books.matchSheet.receipts")}),D.receipts.map(I)]}),!(D!=null&&D.billPayments.length)&&!(D!=null&&D.receipts.length)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r("books.matchSheet.empty")})]}))]})]})})}
4const ya=["BANK_STATEMENT","CREDIT_CARD_STATEMENT"];function Ts(s){s.invalidateQueries({queryKey:["books-statements"]}),s.invalidateQueries({queryKey:["financial-documents"]}),s.invalidateQueries({queryKey:["month-close"]}),s.invalidateQueries({queryKey:["bank-transactions-unmatched"]}),s.invalidateQueries({queryKey:["bills-payment-mix"]}),s.invalidateQueries({queryKey:["bills-ai-summary"]})}function ka({embedded:s=!1}){const i=$t(),{t:r}=X("salesTaxPeriod"),{t:n}=X("financialDocuments"),c=qe(),o=Xs(),[x,h]=Ns(),{currentOrganizationId:u}=ke(),j=Ve(),D=Zs(n),[M,y]=N.useState(!1),[A,P]=N.useState("BANK_STATEMENT"),[S,p]=N.useState([]),[g,L]=N.useState(null),[I,k]=N.useState(null),[f,O]=N.useState(""),[T,d]=N.useState(""),[b,F]=N.useState("period"),[C,ce]=N.useState("desc"),[E,ee]=N.useState(null),[Z,ne]=N.useState(new Set),[q,he]=N.useState(new Set),[_e,es]=N.useState(!0),[Qe,we]=N.useState(!1),[Se,pe]=N.useState(""),[U,re]=N.useState(""),[W,De]=N.useState(null),[We,ge]=N.useState(""),[bs,Te]=N.useState(null),oe=Et(x),He=a=>{Pt(h,a)},{data:Ee,isLoading:ss}=de({queryKey:["books-statements","BANK_STATEMENT",f,u],queryFn:()=>ae.listDocuments({types:ya,status:f||void 0}),enabled:!!u,staleTime:6e4,refetchInterval:a=>{const t=a.state.data;return t&&t.some(m=>m.status==="PENDING"||m.status==="PROCESSING")?3e3:!1}}),ie=N.useMemo(()=>(Ee||[]).filter(a=>a.type==="BANK_STATEMENT"),[Ee]),Fe=N.useMemo(()=>(Ee||[]).filter(a=>a.type==="CREDIT_CARD_STATEMENT"&&!a.promotedCreditCardStatement),[Ee]),$=Gs(x),{data:Q}=de({queryKey:["bank-transactions-unmatched",u,($==null?void 0:$.from)??"",($==null?void 0:$.to)??""],queryFn:()=>ae.listBankTransactions({matchStatus:"UNMATCHED",isDeposit:!1,limit:100,...$?{startDate:$.from,endDate:$.to}:{}}),enabled:!!u,staleTime:3e4}),V=(Q==null?void 0:Q.data)??[],fe=(Q==null?void 0:Q.total)??0,Cs=N.useMemo(()=>{const a=new Set;return ie.forEach(t=>{var m;const l=((m=t.salesChannel)==null?void 0:m.name)||t.vendor;l&&a.add(l)}),Array.from(a).sort()},[ie]),Ge=[n("months.jan"),n("months.feb"),n("months.mar"),n("months.apr"),n("months.may"),n("months.jun"),n("months.jul"),n("months.aug"),n("months.sep"),n("months.oct"),n("months.nov"),n("months.dec")],$e=a=>gs(a.periodStart,a.periodEnd),{monthsWithData:Oe,reviewCounts:Ae}=N.useMemo(()=>{const a=new Set,t=new Map,l=m=>{const v=$e(m);v&&(a.add(v),m.status==="NEEDS_REVIEW"&&t.set(v,(t.get(v)||0)+1))};return ie.forEach(l),Fe.forEach(l),{monthsWithData:a,reviewCounts:t}},[ie,Fe]),vs=Hs(x),le=At(vs,Oe),H=le==="all"?0:le.year,J=le==="all"?0:le.month,Ye=N.useMemo(()=>Fe.filter(a=>{const t=gs(a.periodStart,a.periodEnd);if(!t||!H)return!0;const[l,m]=t.split("-").map(Number);return!(l!==H||J&&m!==J)}),[Fe,H,J]),ts=async a=>{try{const t=await ae.downloadDocumentBlob(a.id,!0),l=URL.createObjectURL(t),m=document.createElement("a");m.href=l,m.target="_blank",m.rel="noopener",document.body.appendChild(m),m.click(),document.body.removeChild(m),setTimeout(()=>URL.revokeObjectURL(l),1e4)}catch{me.error(n("toast.openPdfFailed"))}},Le=(a,t)=>{var l;return e.jsx(ba,{doc:a,kind:t,onApprove:()=>Me.mutate(a.id),onViewPdf:()=>void ts(a),onReprocess:()=>De(a.id),checks:t==="bank"?i:void 0,isApproving:Me.isPending&&Me.variables===a.id,isReprocessing:Re.isPending&&((l=Re.variables)==null?void 0:l.id)===a.id})},Ie=N.useMemo(()=>{let a=[...ie];return T&&(a=a.filter(t=>{var l;return(((l=t.salesChannel)==null?void 0:l.name)||t.vendor)===T})),H&&(a=a.filter(t=>{const l=$e(t);if(!l)return!0;const[m,v]=l.split("-").map(Number);return!(m!==H||J&&v!==J)})),a.sort((t,l)=>{let m=0;switch(b){case"name":m=(t.displayTitle||t.originalName).localeCompare(l.displayTitle||l.originalName);break;case"period":{const v=t.periodStart?new Date(t.periodStart).getTime():0,R=l.periodStart?new Date(l.periodStart).getTime():0;m=v-R;break}case"status":m=t.status.localeCompare(l.status);break;case"deposits":{const v=te(t.extractedData),R=te(l.extractedData);m=((v==null?void 0:v.totalDeposits)??0)-((R==null?void 0:R.totalDeposits)??0);break}case"withdrawals":{const v=te(t.extractedData),R=te(l.extractedData);m=((v==null?void 0:v.totalWithdrawals)??0)-((R==null?void 0:R.totalWithdrawals)??0);break}case"balance":{const v=te(t.extractedData),R=te(l.extractedData);m=((v==null?void 0:v.endingBalance)??0)-((R==null?void 0:R.endingBalance)??0);break}}return C==="asc"?m:-m}),a},[ie,T,H,J,b,C]),ys=Ie.filter(a=>a.status==="NEEDS_REVIEW").length,as=G({mutationFn:a=>ae.uploadDocument(a,{type:"BANK_STATEMENT",autoDetect:!1,inbox:"books"}),onSuccess:()=>Ts(c)}),Me=G({mutationFn:a=>ae.approveDocument(a),onSuccess:()=>Ts(c)}),Re=G({mutationFn:({id:a,additionalPrompt:t})=>ae.reprocessDocument(a,t),onSuccess:()=>{Ts(c),De(null),ge(""),me.success(n("toast.reprocessStarted"))},onError:a=>{var t,l;me.error(((l=(t=a==null?void 0:a.response)==null?void 0:t.data)==null?void 0:l.message)||(a==null?void 0:a.message)||n("toast.reprocessFailed"))}}),Be=async()=>
4{if(S.length!==0){L({current:0,total:S.length});for(let a=0;a<S.length;a++){L({current:a+1,total:S.length});const t=S[a];try{const l=await ae.checkDuplicate(t);if(l.isDuplicate&&l.existingDocument){const m=await new Promise(v=>{k({file:t,existingTitle:l.existingDocument.displayTitle||l.existingDocument.originalName,existingStatus:l.existingDocument.status,resolve:v})});if(k(null),!m)continue}}catch(l){console.warn("Duplicate check failed, proceeding with upload:",l)}try{await as.mutateAsync(t)}catch(l){const m=Bt(l);if(m){me.error(m.message),L(null),y(!1),o(Ft(m.destination));return}me.error(Is(l,n("toast.uploadFailed",{name:t.name})))}}L(null),y(!1),p([])}},ns=a=>{b===a?ce(t=>t==="asc"?"desc":"asc"):(F(a),ce("desc"))},rs=a=>{ne(t=>{const l=new Set(t);return l.has(a)?l.delete(a):l.add(a),l})},Xe=()=>{const a=Ie.filter(t=>t.status==="NEEDS_REVIEW");Z.size===a.length?ne(new Set):ne(new Set(a.map(t=>t.id)))},Ue=async()=>{for(const a of Z)try{await Me.mutateAsync(a)}catch(t){console.error(`Failed to approve ${a}:`,t)}ne(new Set)},is=()=>{if(!Se||!U)return;if(!ja({documents:Ie,startDate:Se,endDate:U,unknownVendor:n("bankingGroup.unknown")})){me.error(n("toast.noDocsInRange"));return}we(!1)},ls=!ss&&Ie.length===0,ds=()=>{if(H&&J){const a=new Date(H,J,0).getDate();pe(`${H}-${String(J).padStart(2,"0")}-01`),re(`${H}-${String(J).padStart(2,"0")}-${a}`)}else H&&(pe(`${H}-01-01`),re(`${H}-12-31`));we(!0)};return e.jsxs("div",{className:"space-y-3 min-w-0",children:[!s&&e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:r("books.title")}),e.jsx("p",{className:"text-muted-foreground",children:r("books.subtitle")})]}),e.jsx("div",{className:"statements-tools",children:e.jsxs("div",{className:"statements-tools-row",children:[e.jsx(xs,{className:"statements-tools-tabs w-full",value:oe,onValueChange:a=>He(a),children:e.jsxs(hs,{className:"grid h-9 w-full grid-cols-2",children:[e.jsx(ue,{value:"statements",children:r("books.tabs.statements")}),e.jsxs(ue,{value:"withdrawals",children:[r("books.tabs.unmatched"),fe>0?e.jsx(ye,{variant:"secondary",className:"ml-2",children:fe}):null]})]})}),oe==="statements"&&Oe.size>0&&e.jsx("div",{className:"statements-tools-month",children:e.jsx(et,{value:le,monthsWithData:Oe,reviewCounts:Ae,showReviewBadge:!0,onChange:a=>Ys(h,a)})}),oe==="statements"&&e.jsxs("div",{className:"statements-tools-pair statements-tools-filters",children:[e.jsxs("select",{value:T,onChange:a=>d(a.target.value),className:"h-9 min-w-0 rounded-md border bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:n("filters.allPlatforms")}),Cs.map(a=>e.jsx("option",{value:a,children:a},a))]}),e.jsxs("select",{value:f,onChange:a=>O(a.target.value),className:"h-9 min-w-0 rounded-md border bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:n("filters.allStatuses")}),Object.entries(D).map(([a,t])=>e.jsx("option",{value:a,children:t},a))]})]}),e.jsxs("div",{className:"statements-tools-pair statements-tools-actions",children:[e.jsx(w,{variant:"outline",className:"h-9",onClick:ds,disabled:ie.length===0,children:n("header.exportCsv")}),e.jsxs(w,{className:"h-9",onClick:()=>{P("BANK_STATEMENT"),y(!0)},children:[e.jsx("span",{className:"statements-upload-short",children:r("books.uploadBankStatementsShort")}),e.jsx("span",{className:"statements-upload-full",children:r("books.uploadBankStatements")})]})]})]})}),oe==="statements"&&e.jsx("div",{className:"rounded-lg border bg-card overflow-hidden",children:ss?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:r("books.loading")}):ls?e.jsxs("div",{className:"p-8 text-center text-muted-foreground space-y-2",children:[e.jsx("p",{children:r("books.empty")}),e.jsxs("p",{className:"text-sm",children:[e.jsx(ze,{to:"/dashboard/statements?tab=cards",className:"underline",children:r("books.openCreditCards")})," · ",e.jsx(ze,{to:"/dashboard/financial-documents",className:"underline",children:r("books.inboxLink")})]})]}):e.jsx(fa,{documents:Ie,selectedIds:Z,selectedDocId:E,sortField:b,sortDirection:C,timezone:j,monthNames:Ge,selectedYear:H,selectedMonth:J,pendingCount:ys,collapsedVendors:q,onToggleSelect:rs,onToggleSelectAll:Xe,onSort:ns,onRowClick:a=>ee(a===E?null:a),renderExpand:a=>Le(a,"bank"),onToggleVendor:a=>{he(t=>{const l=new Set(t);return l.has(a)?l.delete(a):l.add(a),l})},renderRowActions:a=>{if(a.status!=="APPROVED")return null;if(!a.promotedBankStatement)return e.jsx(Kt,{documentId:a.id,size:"sm"});const t=a.promotedBankStatement.unmatchedCount??0;return t<=0?null:e.jsx(ye,{variant:"secondary",children:r("books.unmatchedBadge",{count:t})})}})}),oe==="withdrawals"&&e.jsxs("div",{className:"rounded-lg border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b space-y-1",children:[e.jsx("p",{className:"font-medium",children:r("books.unmatchedTitle")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r("books.unmatchedHint")}),$&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r("books.unmatchedPeriod",{from:$.from,to:$.to}),fe>V.length?` ${r("books.unmatchedTruncated",{shown:V.length,total:fe})}`:""]})]}),V.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:r("books.withdrawalsEmpty")}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"xl:hidden divide-y",children:V.map(a=>e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:z(a.transactionDate,
4j)}),e.jsx("p",{className:"text-sm truncate",children:a.description}),a.checkNumber?e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r("books.col.checkNumber")," ",a.checkNumber]}):null]}),e.jsx("p",{className:"text-sm font-semibold shrink-0",children:B(a.amount)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>Te(a),children:r("books.attach")}),e.jsx(w,{size:"sm",variant:"ghost",className:"flex-1",onClick:()=>Te(a),children:r("books.ignore")})]})]},a.id))}),e.jsx("div",{className:"hidden xl:block overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-4 py-2 text-left text-sm font-medium",children:r("books.col.date")}),e.jsx("th",{className:"px-4 py-2 text-left text-sm font-medium",children:r("books.col.description")}),e.jsx("th",{className:"px-4 py-2 text-left text-sm font-medium",children:r("books.col.checkNumber")}),e.jsx("th",{className:"px-4 py-2 text-right text-sm font-medium",children:r("books.col.amount")}),e.jsx("th",{className:"px-4 py-2 text-right text-sm font-medium"})]})}),e.jsx("tbody",{children:V.map(a=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"px-4 py-3 text-sm",children:z(a.transactionDate,
4j)}),e.jsx("td",{className:"px-4 py-3 text-sm",children:a.description}),e.jsx("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:a.checkNumber||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-right font-medium",children:B(a.amount)}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",onClick:()=>Te(a),children:r("books.attach")}),e.jsx(w,{size:"sm",variant:"ghost",onClick:()=>Te(a),children:r("books.ignore")})]})})]},a.id))})]})})]})]}),oe==="statements"&&Ye.length>0&&e.jsxs("div",{className:"rounded-lg border bg-card",children:[e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between px-4 py-3 text-left",onClick:()=>es(a=>!a),children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold",children:r("books.leftoverTitle")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r("books.leftoverHint")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r("books.leftoverCashFlowHint")})]}),e.jsx("span",{className:"text-muted-foreground",children:_e?"▼":"▶"})]}),_e&&e.jsxs("div",{className:"border-t",children:[e.jsx("div",{className:"xl:hidden divide-y",children:Ye.map(a=>e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{type:"button",className:"w-full text-left",onClick:()=>ee(a.id===E?null:a.id),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-medium break-words",children:a.displayTitle||a.originalName}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium shrink-0 ${fs[a.status]}`,children:D[a.status]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:a.periodStart?a.periodStart.substring(0,10):"—"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(Ks,{documentId:a.id,size:"sm"})}),E===a.id&&Le(a,"card")]},a.id))}),e.jsxs("table",{className:"hidden xl:table w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-4 py-2 text-left text-sm font-medium",children:n("table.document")}),e.jsx("th",{className:"px-4 py-2 text-left text-sm font-medium",children:n("table.period")}),e.jsx("th",{className:"px-4 py-2 text-left text-sm font-medium",children:n("table.status")}),e.jsx("th",{className:"px-4 py-2 text-right text-sm font-medium"})]})}),e.jsx("tbody",{children:Ye.map(a=>e.jsxs(Es.Fragment,{children:[e.jsxs("tr",{className:"border-b last:border-0 cursor-pointer hover:bg-muted/30",onClick:()=>ee(a.id===E?null:a.id),children:[e.jsx("td",{className:"px-4 py-3 text-sm",children:a.displayTitle||a.originalName}),e.jsx("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:a.periodStart?a.periodStart.substring(0,10):"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-1 text-xs font-medium ${fs[a.status]}`,children:D[a.status]})}),e.jsx("td",{className:"px-4 py-3 text-right",onClick:t=>t.stopPropagation(),children:e.jsxs("div",{className:"flex items-center justify-end gap-3",children:[e.jsx(Ks,{documentId:a.id,size:"sm"}),e.jsx(ze,{to:`/dashboard/financial-documents/${a.id}?from=statements`,className:"text-sm underline",children:r("books.review")})]})})]}),E===a.id?e.jsx("tr",{className:"border-b bg-muted/10",children:e.jsx("td",{colSpan:4,className:"p-0",children:Le(a,"card")})}):null]},a.id))})]}),e.jsx("div",{className:"px-4 py-3 border-t",children:e.jsx(ze,{to:"/dashboard/statements?tab=cards",children:e.jsx(w,{variant:"outline",size:"sm",children:r("books.openCreditCards")})})})]})]}),!(oe==="statements"&&ls)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:e.jsx(ze,{to:"/dashboard/financial-documents",className:"underline",children:r("books.inboxLink")})}),Z.size>0&&e.jsxs("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 bg-card border rounded-lg shadow-lg px-4 py-3 flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:n("batch.selectedCount",{count:Z.size})}),e.jsx(w,{size:"sm",onClick:Ue,disabled:Me.isPending,className:"bg-green-600 hover:bg-green-700",children:n("batch.approveSelected")}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>ne(new Set),children:n("common.cancel")})]}),e.jsx(Ot,{inbox:"books",open:M,onOpenChange:y,typeOptions:[{value:"BANK_STATEMENT",label:n("docType.bankStatement")}],typeDescriptions:{BANK_STATEMENT:n("docTypeDesc.bankStatement")},selectedType:A,onSelectedTypeChange:P,autoDetect:!1,onAutoDetectChange:()=>{},files:S,onFilesChange:p,progress:g,onSubmit:Be}
4),e.jsx(Ut,{duplicateConfirm:I,onResolve:a=>{I==null||I.resolve(a),k(null)}}),e.jsx(Ne,{open:Qe,onOpenChange:we,children:e.jsxs(be,{children:[e.jsx(Ce,{children:e.jsx(ve,{children:n("export.titleBanking")})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:n("export.descBanking")}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:n("export.startDate")}),e.jsx("input",{type:"date",value:Se,onChange:a=>pe(a.target.value),className:"w-full rounded-md border px-3 py-2"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:n("export.endDate")}),e.jsx("input",{type:"date",value:U,onChange:a=>re(a.target.value),className:"w-full rounded-md border px-3 py-2"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsx("button",{type:"button",onClick:()=>{const a=ct(new Date,j);pe(`${a.year}-01-01`),re(ot(j))},className:"text-xs px-2 py-1 rounded border hover:bg-muted",children:n("export.yearToDate")})})]}),e.jsxs(Bs,{children:[e.jsx(w,{variant:"outline",onClick:()=>we(!1),children:n("common.cancel")}),e.jsx(w,{onClick:is,disabled:!Se||!U,children:n("header.exportCsv")})]})]})}),e.jsx(Ne,{open:!!W,onOpenChange:a=>{a||(De(null),ge(""))},children:e.jsxs(be,{className:"sm:max-w-md",children:[e.jsxs(Ce,{children:[e.jsx(ve,{children:n("reprocess.title")}),e.jsx(mt,{children:n("reprocess.description")})]}),e.jsx("div",{className:"py-2",children:e.jsx("textarea",{className:"w-full rounded-md border px-3 py-2 text-sm resize-none",rows:3,maxLength:1e3,placeholder:n("reprocess.instructionsPlaceholder"),value:We,onChange:a=>ge(a.target.value)})}),e.jsxs(Bs,{children:[e.jsx(w,{variant:"outline",onClick:()=>{De(null),ge("")},children:n("common.cancel")}),e.jsx(w,{onClick:()=>{W&&Re.mutate({id:W,additionalPrompt:We.trim()||void 0})},disabled:Re.isPending,children:Re.isPending?n("actions.reprocessing"):n("actions.reprocess")})]})]})}),e.jsx(va,{transaction:bs,onClose:()=>Te(null)})]})}function un(){const{t:s}=X("bills"),{permissions:i}=ke(),[r,n]=Ns(),c=i.includes("VIEW_CREDIT_CARDS"),o=i.includes("VIEW_FINANCIAL_DOCUMENTS"),x=Lt(r,{canCards:c,canBank:o}),h=r.get("tab");return N.useEffect(()=>{h!==x&&Os(n,x)},[h,x,n]),e.jsxs("div",{className:"space-y-3 min-w-0 max-w-full",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("h1",{className:"text-xl font-bold leading-tight",children:s("statements.pageTitle")}),c&&o&&e.jsx(xs,{className:"shrink-0",value:x,onValueChange:u=>Os(n,u),children:e.jsxs(hs,{children:[e.jsx(ue,{value:"cards",children:s("statements.tabs.cards")}),e.jsx(ue,{value:"bank",children:s("statements.tabs.bank")})]})})]}),e.jsx("p",{className:"hidden xl:block text-sm text-muted-foreground",children:s("statements.pageSubtitle")})]}),x==="cards"&&c?e.jsx(oa,{embedded:!0}):null,x==="bank"&&o?e.jsx(ka,{embedded:!0}):null]})}export{un as default};

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