PageSourceSearch

https://www.menubrain.ai/assets/js/DataCenterPage-2_t03PG7.js

js menubrain.ai collected 2026-10-05 13:31:05 UTC 201,490 bytes, 3 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/js/onboarding-CryYNyDg.js","assets/js/ui-vendor-CzcNn6SD.js","assets/js/react-vendor-BRXY0zL1.js","assets/js/query-vendor-DrUFZEd1.js","assets/js/vendor-misc-BHwpSTVC.js","assets/js/supabase-vendor-BrPA4caR.js"])))=>i.map(i=>d[i]);
2!function(){try{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{}).SENTRY_RELEASE={id:"3d629276bea5e88869c8100128741c6d108b87d4"}}catch(e){}}();try{e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},(t=(new e.Error).stack)&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7be4874-8512-48e9-aed9-534715546c01",e._sentryDebugIdIdentifier="sentry-dbid-f7be4874-8512-48e9-aed9-534715546c01")}catch(e){}var e,t;import{j as s}from"./ui-vendor-CzcNn6SD.js";import{r as a,R as n,L as r,d as i}from"./react-vendor-BRXY0zL1.js";import{aE as c,q as l,h as o,aD as d,a as m,bk as u,bl as x,B as h,bm as p,bn as g,bs as f,x as j,y,z as v,u as _,a0 as N,a1 as w,a2 as b,a3 as k,ax as C,L as S,I as D,n as I,r as T,t as E,v as M,w as z,b1 as A,s as q,A as F,T as P,K as L,M as R,N as O,O as U,Q as $,ay as V,C as B,H as W,J as H,ap as G,j as Y,aA as K,aB as X,aC as J,F as Q,b6 as Z,bt as ee,b2 as te,b3 as se,b4 as ae,bu as ne,bv as re,bw as ie,k as ce,at as le,au as oe,av as de,aw as me,l as ue,E as xe,bx as he,aq as pe,as as ge,be as fe,by as je,bz as ye,$ as ve,bA as _e,bB as Ne,bC as we,bD as be,bE as ke,bF as Ce,bG as Se,bH as De,aR as Ie,a4 as Te,bI as Ee,bf as Me,P as ze,bJ as Ae,bK as qe,bL as Fe,bM as Pe,a5 as Le,b7 as Re,b8 as Oe,b9 as Ue,ba as $e,bb as Ve,bc as Be}from"./onboarding-CryYNyDg.js";import{d as We,e as He,g as Ge,i as Ye}from"./index-BD4pkqiM.js";import{u as Ke}from"./useIntegrations-CWAUl6fp.js";import{u as Xe,a as Je}from"./query-vendor-DrUFZEd1.js";import{C as Qe}from"./calendar-BBVqpL04.js";import{$ as Ze,ag as et,am as tt,ad as st,ae as at,ah as nt,ai as rt,an as it,b1 as ct,J as lt,c as ot,t as dt,b9 as mt,ba as ut,bb as xt,p as ht,k as pt,at as gt,av as ft,T as jt,x as yt,F as vt,v as _t,o as Nt,bc as wt,h as bt,d as kt,L as Ct,u as St,B as Dt,w as It,a_ as Tt,e as Et,G as Mt,r as zt,q as At,s as qt,K as Ft,N as Pt,O as Lt,a as Rt,C as Ot,Z as Ut,Q as $t,V as Vt,W as Bt,Y as Wt,j as Ht,bd as Gt,y as Yt,n as Kt,X as Xt,b as Jt,D as Qt,be as Zt,aq as es,a1 as ts,_ as ss,l as as,m as ns,E as rs,bf as is,z as cs,bg as ls,az as os,A as ds}from"./vendor-misc-BHwpSTVC.js";import{f as ms}from"./fuzzySearch-78yteFsP.js";import{S as us}from"./dashboard-BVpi9SDK.js";import"./supabase-vendor-BrPA4caR.js";const xs=()=>Xe({queryKey:c.list(),queryFn:async()=>{const e=await o();return e?d(e):[]},staleTime:l.bankAccounts.staleTime,gcTime:l.bankAccounts.gcTime}),hs=e=>{const t=new Date;let s,a=tt(t);switch(e){case"today":s=it(t),a=tt(t);break;case"thisWeek":case"custom":s=st(t,{weekStartsOn:0}),a=at(t,{weekStartsOn:0});break;case"thisMonth":s=nt(t),a=rt(t)}return{startDate:et(s,"yyyy-MM-dd"),endDate:et(a,"yyyy-MM-dd")}},ps=({onDateChange:e,defaultPreset:t="thisWeek",className:n})=>{const[r,i]=a.useState(t),[c,l]=a.useState(),[o,d]=a.useState(),[_,N]=a.useState(!1),[w,b]=a.useState(!1);a.useEffect(()=>{const s=hs(t);e({preset:t,startDate:s.startDate,endDate:s.endDate})},[]);const k=t=>{if(i(t),"custom"===t)return b(!1),void N(!0);const s=hs(t);e({preset:t,startDate:s.startDate,endDate:s.endDate}),b(!1)},C=(e,t)=>{"start"===t?(l(e),e&&o&&e>o&&d(void 0)):d(e)};return s.jsxs("div",{className:m("flex items-center gap-2",n),children:[s.jsxs(u,{open:w,onOpenChange:b,children:[s.jsx(x,{asChild:!0,children:s.jsxs(h,{variant:"outline",className:"h-8 rounded-full border border-border bg-background px-3 py-1.5 text-sm font-normal hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[s.jsx(Ze,{className:"mr-1.5 h-3.5 w-3.5"}),s.jsx("span",{children:"custom"===r&&c&&o?`${et(c,"MMM d")} - ${et(o,"MMM d, yyyy")}`:(e=>{switch(e){case"today":return"Today";case"thisWeek":return"This Week";case"thisMonth":return"This Month";
2case"custom":return"Custom Date Range"}})(r)})]})}),s.jsxs(p,{align:"start",className:"w-48",children:[s.jsx(g,{onClick:()=>k("today"),className:m("cursor-pointer","today"===r&&"bg-accent"),children:"Today"}),s.jsx(g,{onClick:()=>k("thisWeek"),className:m("cursor-pointer","thisWeek"===r&&"bg-accent"),children:"This Week"}),s.jsx(g,{onClick:()=>k("thisMonth"),className:m("cursor-pointer","thisMonth"===r&&"bg-accent"),children:"This Month"}),s.jsx(f,{}),s.jsx(g,{onClick:()=>k("custom"),className:m("cursor-pointer","custom"===r&&"bg-accent"),children:"Custom Date Range"})]})]}),"custom"===r&&s.jsxs(j,{open:_,onOpenChange:N,children:[s.jsx(y,{asChild:!0,children:s.jsx(h,{variant:"outline",size:"sm",className:"h-8 rounded-full border border-border bg-background px-3 py-1.5 text-sm font-normal",children:c&&o?`${et(c,"MMM d")} - ${et(o,"MMM d, yyyy")}`:"Select dates"})}),s.jsx(v,{className:"w-auto p-0",align:"start",children:s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-sm font-medium",children:"Start Date"}),s.jsx(Qe,{mode:"single",selected:c,onSelect:e=>C(e,"start"),disabled:e=>e>new Date,initialFocus:!0})]}),c&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-sm font-medium",children:"End Date"}),s.jsx(Qe,{mode:"single",selected:o,onSelect:e=>C(e,"end"),disabled:e=>e<c||e>new Date,initialFocus:!0})]}),c&&o&&s.jsx(h,{onClick:()=>{if(c&&o){const t={preset:"custom",startDate:et(it(c),"yyyy-MM-dd"),endDate:et(tt(o),"yyyy-MM-dd")};i("custom"),e(t),N(!1),b(!1)}},className:"w-full",size:"sm",children:"Apply"})]})})]})]})},gs=({isOpen:e,onClose:t,onRuleCreated:n,description:r,companyId:i,categories:c,buckets:l})=>{const[o,d]=a.useState(`Auto rule for ${null==r?void 0:r.substring(0,30)}...`),[m,u]=a.useState(r||""),[x,p]=a.useState(""),[g,f]=a.useState(""),[j,y]=a.useState(""),[v,F]=a.useState("5"),[P,L]=a.useState(!1),{toast:R}=_();return s.jsx(N,{open:e,onOpenChange:t,children:s.jsxs(w,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsx(k,{children:"Create Categorization Rule"}),s.jsx(C,{children:"Create a new rule to automatically categorize similar transactions"})]}),s.jsxs("div",{className:"grid gap-4",children:[s.jsxs("div",{className:"grid gap-2",children:[s.jsx(S,{htmlFor:"ruleName",children:"Rule Name"}),s.jsx(D,{id:"ruleName",value:o,onChange:e=>d(e.target.value),placeholder:"e.g., Uber Eats Transactions"})]}),s.jsxs("div",{className:"grid gap-2",children:[s.jsx(S,{htmlFor:"pattern",children:"Pattern (Text to Match)"}),s.jsx(D,{id:"pattern",value:m,onChange:e=>u(e.target.value),placeholder:"e.g., UBER EATS"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit the pattern to match similar transactions"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"grid gap-2",children:[s.jsx(S,{htmlFor:"category",children:"Category"}),s.jsxs(I,{value:x,onValueChange:p,children:[s.jsx(T,{id:"category",children:s.jsx(E,{placeholder:"Select category"})}),s.jsxs(M,{children:[c.map(e=>s.jsx(z,{value:e,children:e},e)),s.jsx(z,{value:"__new__",children:"+ Add New Category"})]})]}),"__new__"===x&&s.jsx(D,{placeholder:"Enter new category",onChange:e=>p(e.target.value),className:"mt-2"})]}),s.jsxs("div",{className:"grid gap-2",children:[s.jsx(S,{htmlFor:"bucket",children:"Bucket"}),s.jsxs(I,{value:g,onValueChange:f,children:[s.jsx(T,{id:"bucket",children:s.jsx(E,{placeholder:"Select bucket"})}),s.jsxs(M,{children:[l.map(e=>s.jsx(z,{value:e,children:e},e)),s.jsx(z,{value:"__new__",children:"+ Add New Bucket"})]})]}),"__new__"===g&&s.jsx(D,{placeholder:"Enter new bucket",onChange:e=>f(e.target.value),className:"mt-2"})]})]}),s.jsxs("div",{className:"grid gap-2",children:[s.jsx(S,{htmlFor:"detailSource",children:"Detail Source (Optional)"}),s.jsx(D,{id:"detailSource",value:j,onChange:e=>y(e.target.value),placeholder:"e.g., Food Delivery"})]}),s.jsxs("div",{className:"grid gap-2",children:[s.jsx(S,{htmlFor:"priority",children:"Priority"}
2),s.jsx(D,{id:"priority",type:"number",value:v,onChange:e=>F(e.target.value),placeholder:"5",min:"0",max:"10"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Higher priority rules are applied first (0-10)"})]})]}),s.jsxs(A,{children:[s.jsx(h,{variant:"outline",onClick:t,children:"Cancel"}),s.jsx(h,{onClick:async()=>{if(m&&x&&g){L(!0);try{const{error:e}=await q.from("bank_transaction_rules").insert({company_id:i,rule_name:o,pattern:m,category_type:x,subcategory:g,detail_source:j||null,priority:parseInt(v),is_active:!0});if(e)throw e;R({title:"Rule created",description:"The categorization rule has been created successfully."}),n(),t()}catch(e){R({title:"Error creating rule",description:e.message,variant:"destructive"})}finally{L(!1)}}else R({title:"Missing fields",description:"Please fill in rule name, pattern, category, and bucket.",variant:"destructive"})},disabled:P,children:P?"Creating...":"Create Rule"})]})]})})},fs=({isOpen:e,onClose:t,onConfirm:n,records:r,fileName:i,onRecordsUpdate:c})=>{const[l,o]=a.useState(r),[d,m]=a.useState(null),[u,x]=a.useState("asc"),[p,g]=a.useState(1),[f,j]=a.useState([]),[y,v]=a.useState([]),[S,V]=a.useState(new Map),[B,W]=a.useState(!1),[H,G]=a.useState(null),[Y,K]=a.useState(""),[X,J]=a.useState(!1),{toast:Q}=_(),Z=50;a.useEffect(()=>{o(r),g(1)},[r]),a.useEffect(()=>{e&&(async()=>{try{const{data:e}=await q.auth.getUser();if(!e.user)return;const{data:t}=await q.from("profiles").select("company_id").eq("user_id",e.user.id).single();if(!(null==t?void 0:t.company_id))return;K(t.company_id);const s=new Set,a=new Set,{data:n}=await q.from("bank_statements").select("category, bucket").eq("company_id",t.company_id).not("category","is",null).not("bucket","is",null);n&&n.forEach(e=>{e.category&&s.add(e.category),e.bucket&&a.add(e.bucket)});const{data:i}=await q.from("bank_transactions").select("category_type, subcategory").eq("company_id",t.company_id).not("category_type","is",null).not("subcategory","is",null);i&&i.forEach(e=>{e.category_type&&s.add(e.category_type),e.subcategory&&a.add(e.subcategory)});const{data:c}=await q.from("bank_transaction_rules").select("category_type, subcategory").or(`company_id.is.null,company_id.eq.${t.company_id}`).eq("is_active",!0);c&&c.forEach(e=>{e.category_type&&s.add(e.category_type),e.subcategory&&a.add(e.subcategory)}),r.forEach(e=>{e.category&&s.add(e.category),e.bucket&&a.add(e.bucket)}),j(Array.from(s).sort()),v(Array.from(a).sort())}catch(e){}})()},[e,r]);const ee=e=>{if(!e||0===e)return null;let t="secondary",a="";return e>=90?(t="default",a="High"):e>=70?(t="secondary",a="Medium"):(t="outline",a="Low"),s.jsxs(F,{variant:t,className:"text-xs",children:[a," (",e,"%)"]})},te=e=>{d===e?x("asc"===u?"desc":"asc"):(m(e),x("asc"))},se=a.useMemo(()=>d?[...l].sort((e,t)=>{const s=e[d],a=t[d];if(null==s)return 1;if(null==a)return-1;let n=0;return n="number"==typeof s&&"number"==typeof a?s-a:String(s).localeCompare(String(a)),"asc"===u?n:-n}):l,[l,d,u]),ae=Math.ceil(se.length/Z),ne=a.useMemo(()=>{const e=(p-1)*Z;return se.slice(e,e+Z)},[se,p]),re=(e,t,s)=>{const a=(p-1)*Z+e,n=[...l],r={...n[a]};if(n[a]={...n[a],[t]:s},o(n),["category","bucket","type"].includes(t)&&r[t]!==s){const e=new Map(S),n=e.get(a)||{original:{...r},corrected:{}};e.set(a,{original:n.original,corrected:{...n.corrected,[t]:s}}),V(e)}},ie=e=>d!==e?s.jsx(mt,{className:"h-3 w-3 ml-1 inline"}):"asc"===u?s.jsx(ut,{className:"h-3 w-3 ml-1 inline"}):s.jsx(xt,{className:"h-3 w-3 ml-1 inline"}),ce=async()=>{if(0===S.size)return;const e=Array.from(S.entries()).map(async([e,{original:t,corrected:s}])=>{const a=l[e];if(!s.category&&!s.bucket)return;const n=(e=>{if(!e)return"";const t=e.replace(/\d{2}\/\d{2}\/\d{4}/g,"").replace(/\d{4}-\d{2}-\d{2}/g,"").replace(/\b\d{6,}\b/g,"").replace(/\bTRACE#:\s*\d+/gi,"").replace(/\bREF#:\s*\w+/gi,"").replace(/\bID:\s*\w+/gi,"").replace(/\bORIG ID:\s*\w+/gi,"").replace(/\b(SEC|CCD|PPD):\s*\w+/gi,"").replace(/DESC DATE:\s*\w+\s*\d+/gi,"").replace(/EED:\s*\d+/gi,"").replace(/\s+/g," ").trim().split(" ").filter(e=>e.length>2);return t.slice(0,Math.min(5,t.length)).join(" ").toLowerCase()})(a.description||"");if(n)try{const{data:e}=await q.from("bank_transaction_rules").select("id").or(`company_id.is.null,company_id.eq.${Y}`).eq("pattern",n).limit(1);e&&0!==e.length||(await q.from("bank_transaction_rules").insert({company_id:Y,rule_name:`Auto-learned: ${n}`,pattern:n,category_type:s.category||a.category,subcategory:s.bucket||a.bucket,is_active:!0,priority:50}
2),Q({title:"Rule learned",description:`Created rule for pattern: "${n}"`}))}catch(r){}});await Promise.all(e),S.size>0&&Q({title:"Learning complete",description:`Processed ${S.size} correction${S.size>1?"s":""} and created new categorization rules.`}),V(new Map)},le=r.filter(e=>e.autoClassified).length;return s.jsxs(N,{open:e,onOpenChange:t,children:[s.jsxs(w,{className:"max-w-6xl max-h-[80vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsx(k,{children:"Review Bank Statements"}),s.jsxs(C,{children:["Preview and edit parsed data from ",i," before importing"]})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-muted rounded-lg",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ct,{className:"h-5 w-5 text-green-600"}),s.jsxs("span",{className:"text-sm font-medium",children:[r.length," records found"]})]}),le>0&&s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs(F,{variant:"secondary",children:[le," auto-categorized"]})}),s.jsxs("div",{className:"ml-auto text-sm text-muted-foreground",children:["Page ",p," of ",ae]})]}),s.jsx("div",{className:"border rounded-lg overflow-hidden",children:s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[s.jsx(O,{className:"w-[100px]",children:s.jsxs(h,{variant:"ghost",size:"sm",className:"h-8 px-2 hover:bg-transparent",onClick:()=>te("transaction_date"),children:["Date",ie("transaction_date")]})}),s.jsx(O,{className:"w-[200px]",children:"Description"}),s.jsx(O,{className:"w-[120px]",children:s.jsxs(h,{variant:"ghost",size:"sm",className:"h-8 px-2 hover:bg-transparent",onClick:()=>te("category"),children:["Category",ie("category")]})}),s.jsx(O,{className:"w-[120px]",children:s.jsxs(h,{variant:"ghost",size:"sm",className:"h-8 px-2 hover:bg-transparent",onClick:()=>te("bucket"),children:["Bucket",ie("bucket")]})}),s.jsx(O,{className:"w-[100px]",children:"Type"}),s.jsx(O,{className:"w-[100px]",children:s.jsxs(h,{variant:"ghost",size:"sm",className:"h-8 px-2 hover:bg-transparent",onClick:()=>te("amount"),children:["Amount",ie("amount")]})}),s.jsx(O,{className:"w-[100px]",children:"Card"}),s.jsx(O,{className:"w-[120px]",children:"Confidence"}),s.jsx(O,{className:"w-[100px]",children:"Actions"})]})}),s.jsx(U,{children:ne.map((e,t)=>s.jsxs(R,{children:[s.jsx($,{className:"text-xs",children:e.transaction_date}),s.jsx($,{children:s.jsx(D,{value:e.description||"",onChange:e=>re(t,"description",e.target.value),className:"text-xs h-8",placeholder:"Description"})}),s.jsx($,{children:s.jsxs(I,{value:e.category||"",onValueChange:e=>re(t,"category",e),children:[s.jsx(T,{className:"text-xs h-8",children:s.jsx(E,{placeholder:"Category"})}),s.jsx(M,{children:f.map(e=>s.jsx(z,{value:e,className:"text-xs",children:e},e))})]})}),s.jsx($,{children:s.jsxs(I,{value:e.bucket||"",onValueChange:e=>re(t,"bucket",e),children:[s.jsx(T,{className:"text-xs h-8",children:s.jsx(E,{placeholder:"Bucket"})}),s.jsx(M,{children:y.map(e=>s.jsx(z,{value:e,className:"text-xs",children:e},e))})]})}),s.jsx($,{children:s.jsx(D,{value:e.type||"",onChange:e=>re(t,"type",e.target.value),className:"text-xs h-8",placeholder:"Type"})}),s.jsxs($,{className:"text-xs font-medium "+(e.amount<0?"text-destructive":"text-green-600"),children:["$",Math.abs(e.amount).toFixed(2)]}),s.jsx($,{className:"text-xs",children:e.card||"-"}),s.jsx($,{children:s.jsxs("div",{className:"flex flex-col gap-1",children:[e.autoClassified&&ee(e.confidence),!e.autoClassified&&s.jsx(F,{variant:"outline",className:"text-xs",children:"Manual"})]})}),s.jsx($,{children:!e.autoClassified&&s.jsx(h,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>(e=>{G(e),W(!0)})(e),children:"Create Rule"})})]},t))})]})}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"text-sm text-muted-foreground",children:["Showing ",(p-1)*Z+1," to ",Math.min(p*Z,se.length)," of ",se.length," records"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>g(e=>Math.max(1,e-1)),disabled:1===p,children:[s.jsx(lt,{className:"h-4 w-4"}),"Previous"]}),s.jsxs("div",{className:"flex items-center gap-2 px-3 text-sm",children:["Page ",p," of ",ae]}),s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>g(e=>Math.min(ae,e+1)),disabled:p===ae,children:["Next",s.jsx(ot,{className:"h-4 w-4"})]})]})]}),le>0&&s.jsxs("div",{className:"flex items-start gap-2 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:[s.jsx(dt,{className:"h-4 w-4 text-blue-600 mt-0.5"}),s.jsxs("div",{className:"text-xs text-blue-900",children:[s.jsx("p",{className:"font-medium mb-1",children:"Auto-categorization applied"}),s.jsxs("p",{className:"text-blue-700",children:[le," transactions were automatically categorized based on your rules. Review and edit if needed before importing."]})]})]})]}),s.jsxs(A,{className:"gap-2",children:[S.size>0&&s.jsxs("span",{className:"text-sm text-muted-foreground mr-auto",children:[S.size," correction",S.size>1?"s":""," will be learned"]}),s.jsx(h,{variant:"outline",onClick:t,disabled:X,children:"Cancel"}),s.jsx(h,{onClick:async()=>{J(!0);try{S.size>0&&await ce(),await n(l),t()}catch(e){}finally{J(!1)}},disabled:X,children:X?"Importing...":`Import ${l.length} Records`})]})]}),s.jsx(gs,{isOpen:B,onClose:()=>{W(!1),G(null)},onRuleCreated:async()=>{const{data:e}=await q.from("bank_transactions").select("category_type, subcategory").eq("company_id",Y).not("category_type","is",null).not("subcategory","is",null);if(e){const t=[...new Set(e.map(e=>
2e.category_type).filter(Boolean))],s=[...new Set(e.map(e=>e.subcategory).filter(Boolean))];j(t),v(s)}c&&c(l)},description:(null==H?void 0:H.description)||"",companyId:Y,categories:f,buckets:y})]})},js=()=>{const[e,t]=a.useState([]),[n,r]=a.useState(!1),[i,c]=a.useState(null),[l,d]=a.useState({rule_name:"",pattern:"",category_type:"",subcategory:"",detail_source:"",priority:0}),{toast:m}=_();a.useEffect(()=>{u()},[]);const u=async()=>{try{const e=await o();if(!e)return;const{data:s,error:a}=await q.from("bank_transaction_rules").select("*").or(`company_id.is.null,company_id.eq.${e}`).order("priority",{ascending:!1});if(a)throw a;t(s||[])}catch(e){m({title:"Error loading rules",description:e.message,variant:"destructive"})}},x=()=>{d({rule_name:"",pattern:"",category_type:"",subcategory:"",detail_source:"",priority:0}),c(null)};return s.jsxs(V,{children:[s.jsxs(B,{className:"w-full",children:[s.jsx(W,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(H,{className:"flex items-center gap-2",children:[s.jsx(ht,{className:"h-5 w-5 text-primary"}),"Auto-Categorization Rules"]}),s.jsx(G,{children:"Create rules to automatically categorize bank transactions based on description patterns"})]}),s.jsxs(h,{onClick:()=>{x(),r(!0)},children:[s.jsx(pt,{className:"h-4 w-4 mr-2"}),"Add Rule"]})]})}),s.jsx(Y,{children:0===e.length?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx("p",{children:"No categorization rules yet"}),s.jsx("p",{className:"text-sm mt-1",children:"Create rules to automatically categorize your bank statements"})]}):s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[s.jsx(O,{children:"Rule Name"}),s.jsx(O,{children:s.jsxs("div",{className:"flex items-center gap-1.5",children:["Pattern",s.jsxs(K,{children:[s.jsx(X,{asChild:!0,children:s.jsx(gt,{className:"h-3.5 w-3.5 text-muted-foreground cursor-help"})}),s.jsx(J,{className:"max-w-xs",children:s.jsx("p",{className:"text-xs",children:"Text pattern to match in transaction descriptions. Use keywords that uniquely identify the transaction type."})})]})]})}),s.jsx(O,{children:"Category"}),s.jsx(O,{children:"Subcategory"}),s.jsx(O,{children:s.jsxs("div",{className:"flex items-center gap-1.5",children:["Priority",s.jsxs(K,{children:[s.jsx(X,{asChild:!0,children:s.jsx(gt,{className:"h-3.5 w-3.5 text-muted-foreground cursor-help"})}),s.jsx(J,{className:"max-w-xs",children:s.jsx("p",{className:"text-xs",children:"Higher priority rules (larger numbers) are applied first. Use this to override more general rules with specific ones."})})]})]})}),s.jsx(O,{children:"Active"}),s.jsx(O,{})]})}),s.jsx(U,{children:e.map(t=>{const a=null===t.company_id;return s.jsxs(R,{children:[s.jsx($,{className:"font-medium",children:s.jsxs("div",{className:"flex items-center gap-2",children:[t.rule_name,a&&s.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"Default"})]})}),s.jsx($,{className:"font-mono text-xs",children:t.pattern}),s.jsx($,{children:t.category_type}),s.jsx($,{children:t.subcategory}),s.jsx($,{children:t.priority}),s.jsx($,{children:s.jsx(Q,{checked:t.is_active,onCheckedChange:()=>(async(t,s)=>{try{const a=e.find(e=>e.id===t);if(a&&null===a.company_id)return void m({title:"Cannot modify default rule",description:"Default rules cannot be toggled. You can create a custom rule to override them.",variant:"destructive"});const{error:n}=await q.from("bank_transaction_rules").update({is_active:!s}).eq("id",t);if(n)throw n;u()}catch(a){m({title:"Error updating rule",description:a.message,variant:"destructive"})}})(t.id,t.is_active),disabled:a})}),s.jsx($,{children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(h,{variant:"ghost",size:"sm",onClick:()=>(e=>{null!==e.company_id?(c(e),d({rule_name:e.rule_name,pattern:e.pattern,category_type:e.category_type,subcategory:e.subcategory,detail_source:e.detail_source||"",priority:e.priority}),r(!0)):m({title:"Cannot edit default rule",description:"Default rules cannot be edited. You can create a custom rule to override them.",variant:"destructive"})})(t),disabled:a,title:a?"Default rules cannot be edited":"Edit rule",children:s.jsx(ft,{className:"h-4 w-4"})}),s.jsx(h,{variant:"ghost",size:"sm",onClick:()=>(async t=>{try{const s=e.find(e=>e.id===t);if(s&&null===s.company_id)return void m({title:"Cannot delete default rule",description:"Default rules cannot be deleted. You can only delete custom rules you created.",variant:"destructive"});const{error:a}=await q.from("bank_transaction_rules").delete().eq("id",t);if(a)throw a;m({title:"Rule deleted",description:"Categorization rule has been deleted."}),u()}catch(s){m({title:"Error deleting rule",description:s.message,variant:"destructive"})}})(t.id),disabled:a,title:a?"Default rules cannot be deleted":"Delete rule",children:s.jsx(jt,{className:"h-4 w-4"})})]})})]},t.id)})})]})})]}),s.jsx(N,{open:n,onOpenChange:r,children:s.jsxs(w,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsx(k,{children:i?"Edit Rule":"Create Categorization Rule"}),s.jsx(C,{children:"Define a pattern to automatically categorize bank transactions"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(S,{htmlFor:"rule_name",children:"Rule Name"}),s.jsx(D,{id:"rule_name",value:l.rule_name,onChange:e=>d({...l,rule_name:e.target.value}),placeholder:"e.g., Amazon Purchases"})]}),s.jsxs("div",{children:[s.jsx(S,{htmlFor:"pattern",children:"Pattern (case-insensitive)"}),s.jsx(D,{id:"pattern",value:l.pattern,onChange:e=>d({...l,pattern:e.target.value}),placeholder:"e.g., amazon, amzn"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Transactions containing this text will be categorized"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(S,{htmlFor:"category_type",children:"Category Type"}
2),s.jsx(D,{id:"category_type",value:l.category_type,onChange:e=>d({...l,category_type:e.target.value}),placeholder:"e.g., Expense"})]}),s.jsxs("div",{children:[s.jsx(S,{htmlFor:"subcategory",children:"Subcategory"}),s.jsx(D,{id:"subcategory",value:l.subcategory,onChange:e=>d({...l,subcategory:e.target.value}),placeholder:"e.g., Shopping"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(S,{htmlFor:"detail_source",children:"Detail Source (Optional)"}),s.jsx(D,{id:"detail_source",value:l.detail_source,onChange:e=>d({...l,detail_source:e.target.value}),placeholder:"e.g., Online"})]}),s.jsxs("div",{children:[s.jsx(S,{htmlFor:"priority",children:"Priority (0-100)"}),s.jsx(D,{id:"priority",type:"number",value:l.priority,onChange:e=>d({...l,priority:parseInt(e.target.value)||0}),placeholder:"0"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Higher priority rules are applied first"})]})]})]}),s.jsxs(A,{children:[s.jsx(h,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsxs(h,{onClick:async()=>{try{const e=await o();if(!e)throw new Error("No company found");if(i){const{error:e}=await q.from("bank_transaction_rules").update({...l,updated_at:(new Date).toISOString()}).eq("id",i.id);if(e)throw e}else{const{error:t}=await q.from("bank_transaction_rules").insert({...l,company_id:e,is_active:!0});if(t)throw t}m({title:"Success",description:`Rule ${i?"updated":"created"} successfully.`}),r(!1),x(),u()}catch(e){m({title:"Error saving rule",description:e.message,variant:"destructive"})}},children:[i?"Update":"Create"," Rule"]})]})]})})]})},ys=()=>{const[e,t]=a.useState([]),[n,r]=a.useState([]),[i,c]=a.useState(""),[l,d]=a.useState(!1),[m,u]=a.useState(!1),[x,p]=a.useState(!1),[g,f]=a.useState([]),[j,y]=a.useState(""),[v,A]=a.useState(1),[F,W]=a.useState(0),H=()=>{const e=new Date;return{startDate:st(e,{weekStartsOn:0}),endDate:at(e,{weekStartsOn:0})}},G=H(),[Y,Q]=a.useState(G.startDate),[ne,re]=a.useState(G.endDate),[ie,ce]=a.useState(""),[le,oe]=a.useState(""),[de,me]=a.useState(!1),[ue,xe]=a.useState(!1),[he,pe]=a.useState(!1),[ge,fe]=a.useState(null),[je,ye]=a.useState({category:"",bucket:"",type:"",description:"",amount:0,transaction_date:""}),[ve,_e]=a.useState(!1),{toast:Ne}=_(),we=e=>{if(!e.auto_classified||!e.confidence)return null;const t=e.confidence;let a="",n="",r="";return t>=80?(a="bg-green-100 dark:bg-green-900/30",n="text-green-700 dark:text-green-400",r="High"):t>=60?(a="bg-yellow-100 dark:bg-yellow-900/30",n="text-yellow-700 dark:text-yellow-400",r="Medium"):(a="bg-red-100 dark:bg-red-900/30",n="text-red-700 dark:text-red-400",r="Low"),s.jsx(V,{children:s.jsxs(K,{children:[s.jsx(X,{asChild:!0,children:s.jsxs("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${a} ${n} cursor-help`,children:[t,"%"]})}),s.jsx(J,{children:s.jsxs("div",{className:"text-xs",children:[s.jsxs("div",{className:"font-semibold",children:[r," Confidence"]}),e.matched_rule&&s.jsxs("div",{className:"text-muted-foreground",children:["Rule: ",e.matched_rule]})]})})]})})};a.useEffect(()=>{ke()},[v,Y,ne,ie,le]);const{data:be=[]}=xs();a.useEffect(()=>{const e=be.map(e=>({id:e.id,account_name:e.account_name,bank_name:e.bank_name||"",account_type:e.account_type,is_active:e.is_active}));r(e)},[be]);const ke=async()=>{try{const e=await o();if(!e)return;const s=Y?et(Y,"yyyy-MM-dd"):null,a=ne?et(ne,"yyyy-MM-dd"):null,n=ie?parseFloat(ie):null,r=le?parseFloat(le):null;let i=q.from("bank_transactions").select("\n          id,\n          transaction_date,\n          amount,\n          description,\n          merchant_name,\n          category_type,\n          subcategory,\n          detail_source,\n          account_id,\n          auto_categorized,\n          classification_confidence,\n          bank_accounts:account_id (\n            account_name,\n            bank_name\n          )\n        ").eq("company_id",e);s&&(i=i.gte("transaction_date",s)),a&&(i=i.lte("transaction_date",a)),null!=n&&(i=i.gte("amount",n)),null!=r&&(i=i.lte("amount",r));let c=q.from("bank_statements").select("\n          id,\n          transaction_date,\n          amount,\n          description,\n          category,\n          bucket,\n          type,\n          bank_account_id,\n          confidence,\n          auto_classified,\n          matched_rule,\n          bank_accounts:bank_account_id (\n            account_name,\n            bank_name\n          )\n        ").eq("company_id",e);s&&(c=c.gte("transaction_date",s)),a&&(c=c.lte("transaction_date",a)),null!=n&&(c=c.gte("amount",n)),null!=r&&(c=c.lte("amount",r));const[l,d]=await Promise.all([i.order("transaction_date",{ascending:!1}).limit(2e3),c.order("transaction_date",{ascending:!1}).limit(2e3)]);if(l.error)throw l.error;if(d.error)throw d.error;const m=(l.data||[]).map(e=>({id:e.id,transaction_date:e.transaction_date,amount:e.amount,description:e.description||e.merchant_name,category:e.category_type,bucket:e.subcategory,type:e.detail_source,bank_account_id:e.account_id,auto_classified:e.auto_categorized,confidence:null!=e.classification_confidence?Math.round(100*Number(e.classification_confidence)):null,matched_rule:null,bank_accounts:e.bank_accounts||{account_name:"Unknown",bank_name:"Unknown"},_source:"bank_transactions"})),u=(d.data||[]).map(e=>({id:e.id,transaction_date:e.transaction_date,amount:e.amount,description:e.description??"",category:e.category,bucket:e.bucket??"",type:e.type??"",bank_account_id:e.bank_account_id,auto_classified:!!e.auto_classified,confidence:null!=e.confidence?Math.round(Number(e.confidence)):null,matched_rule:e.matched_rule,bank_accounts:e.bank_accounts||{account_name:"Unknown",bank_name:"Unknown"},_source:"bank_statements"})),x=[...m,...u].sort((e,t)=>
2(t.transaction_date||"").localeCompare(e.transaction_date||""));W(x.length);const h=50*(v-1);t(x.slice(h,h+50))}catch(e){Ne({title:"Error loading statements",description:e.message,variant:"destructive"})}},Ce=async e=>{var t;if(!i)return void Ne({title:"No bank account selected",description:"Please select a bank account first.",variant:"destructive"});const s=Array.from(e).filter(e=>{var t;const s=null==(t=e.name.split(".").pop())?void 0:t.toLowerCase();return"csv"===s||"xlsx"===s||"xls"===s});if(0!==s.length){u(!0);try{const e=await o();if(!e)throw new Error("No company found");for(const a of s){const s=null==(t=a.name.split(".").pop())?void 0:t.toLowerCase();let n=[];"csv"===s?n=await De(a):"xlsx"!==s&&"xls"!==s||(n=await Te(a));const r=await Se(n,e);f(r),y(a.name),p(!0);break}}catch(a){Ne({title:"Error parsing files",description:a.message,variant:"destructive"})}finally{u(!1)}}else Ne({title:"Invalid file type",description:"Please upload CSV or Excel (.xlsx, .xls) files only.",variant:"destructive"})},Se=async(e,t)=>{try{const{data:s,error:a}=await q.from("bank_transaction_rules").select("id, pattern, category_type, subcategory, detail_source, priority, is_active, match_pattern, exception_patterns, confidence_score, account_id, company_id").or(`company_id.is.null,company_id.eq.${t}`).eq("is_active",!0).order("priority",{ascending:!1});if(a)throw a;const{data:n,error:r}=await q.from("bank_statements").select("description, category, bucket, type").eq("company_id",t).not("description","is",null).not("category","is",null);if(r)throw r;return e.map(e=>{if(!e.description)return e;let t=null,a=0,r="";if(null==n||n.forEach(s=>{if(s.description){const n=ms(e.description,s.description);n>a&&n>.6&&(a=n,t={category:s.category,bucket:s.bucket||"",type:s.type||""},r="Fuzzy Match")}}),t&&a>.8)return{...e,category:t.category,bucket:t.bucket,type:t.type,autoClassified:!0,matchedRule:`${r} (${Math.round(100*a)}%)`,confidence:Math.round(100*a)};const i=null==s?void 0:s.find(t=>e.description.toLowerCase().includes(t.pattern.toLowerCase()));return i?{...e,category:i.category_type,bucket:i.subcategory,type:e.type,autoClassified:!0,matchedRule:i.rule_name,confidence:85}:t?{...e,category:t.category,bucket:t.bucket,type:t.type,autoClassified:!0,matchedRule:`${r} (${Math.round(100*a)}%)`,confidence:Math.round(100*a)}:{...e,confidence:0}})}catch(s){return e}},De=async e=>new Promise((t,s)=>{te.parse(e,{header:!0,complete:e=>{const s=e.data.filter(e=>e["Transaction Date"]&&e.Amount).map(e=>({location:e.Location||null,category:e.Category||null,bucket:e.Bucket||null,type:e.Type||null,detail:e.Detail||null,card:e.Card||null,transaction_date:Ie(e["Transaction Date"]),amount:parseFloat(e.Amount)||0,description:e.Description||null}));t(s)},error:e=>s(e)})}),Ie=e=>{if(!e)return"";if("number"==typeof e){const t=new Date(1899,11,30);return new Date(t.getTime()+864e5*e).toISOString().split("T")[0]}const t=new Date(e);return isNaN(t.getTime())?"string"==typeof e&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:e.toString():t.toISOString().split("T")[0]},Te=async e=>new Promise((t,s)=>{const a=new FileReader;a.onload=e=>{var a;try{const s=null==(a=e.target)?void 0:a.result,n=se(s,{type:"binary",cellDates:!0}),r=n.SheetNames[0],i=n.Sheets[r],c=ae.sheet_to_json(i,{header:1,raw:!1}),l=c[0],o=c.slice(1),d=e=>l.findIndex(t=>t&&t.toString().toLowerCase().includes(e.toLowerCase())),m=d("location"),u=d("category"),x=d("bucket"),h=d("type"),p=d("detail"),g=d("card"),f=d("transaction date"),j=d("amount"),y=d("description"),v=o.filter(e=>e[f]&&e[j]).map(e=>({location:m>=0?e[m]:null,category:u>=0?e[u]:null,bucket:x>=0?e[x]:null,type:h>=0?e[h]:null,detail:p>=0?e[p]:null,card:g>=0?e[g]:null,transaction_date:Ie(e[f]),amount:parseFloat(e[j])||0,description:y>=0?e[y]:null}));t(v)}catch(n){s(n)}},a.onerror=e=>s(e),a.readAsBinaryString(e)});return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(N,{open:de,onOpenChange:me,children:[s.jsx(Z,{asChild:!0,children:s.jsxs(h,{children:[s.jsx(yt,{className:"mr-2 h-4 w-4"}),"Upload Bank Statements"]})}),s.jsxs(w,{className:"max-w-2xl",children:[s.jsxs(b,{children:[s.jsx(k,{children:"Upload Bank Statements"}),s.jsx(C,{children:"Upload CSV or Excel files containing your bank transactions."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Select Bank Account"}),s.jsxs(I,{value:i,onValueChange:c,children:[s.jsx(T,{children:s.jsx(E,{placeholder:"Select Bank Account"})}),s.jsx(M,{children:n.map(e=>s.jsxs(z,{value:e.id,children:[e.bank_name," - ",e.account_name]},e.id))})]})]}),s.jsx(B,{className:"p-8 border-2 border-dashed "+(l?"bg-muted/50 border-primary":""),onDragOver:e=>{e.preventDefault(),d(!0)},onDragLeave:()=>d(!1),onDrop:e=>{e.preventDefault(),d(!1),e.dataTransfer.files&&Ce(e.dataTransfer.files)},children:s.jsxs("div",{className:"text-center",children:[s.jsx(yt,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Drop CSV or Excel files here or click to browse"}),s.jsx("p",{className:"text-xs text-muted-foreground mb-4",children:"Columns: Location, Category, Bucket, Type, Detail, Card, Transaction Date, Amount, Description"}),s.jsxs(h,{onClick:()=>{var e;
2return null==(e=document.getElementById("bank-file-input"))?void 0:e.click()},disabled:!i||m,children:[s.jsx(vt,{className:"mr-2 h-4 w-4"}),m?"Processing...":"Choose Files"]}),s.jsx("input",{id:"bank-file-input",type:"file",multiple:!0,accept:".csv,.xlsx,.xls",className:"hidden",onChange:e=>{e.target.files&&(Ce(e.target.files),me(!1))}})]})})]})]})]}),s.jsxs(N,{open:ue,onOpenChange:xe,children:[s.jsx(Z,{asChild:!0,children:s.jsxs(h,{variant:"outline","data-tour":"categorization-rules",children:[s.jsx(_t,{className:"mr-2 h-4 w-4"}),"Categorization Rules"]})}),s.jsxs(w,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsx(k,{children:"Categorization Rules"}),s.jsx(C,{children:"Manage rules for automatically categorizing bank transactions."})]}),s.jsx(js,{})]})]})]}),s.jsx(B,{className:"p-6",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsx("h3",{className:"text-lg font-semibold",children:"Recent Transactions"}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-end",children:[s.jsx(ps,{onDateChange:e=>{Q(new Date(e.startDate)),re(new Date(e.endDate)),A(1)}}),s.jsxs("div",{className:"flex flex-col",children:[s.jsx("label",{className:"text-xs font-medium mb-1",children:"Min Amount"}),s.jsx("input",{type:"number",placeholder:"0.00",value:ie,onChange:e=>{ce(e.target.value),A(1)},step:"0.01",className:"h-9 px-3 rounded-md border border-input bg-background text-sm",style:{width:"120px"}})]}),s.jsxs("div",{className:"flex flex-col",children:[s.jsx("label",{className:"text-xs font-medium mb-1",children:"Max Amount"}),s.jsx("input",{type:"number",placeholder:"0.00",value:le,onChange:e=>{oe(e.target.value),A(1)},step:"0.01",className:"h-9 px-3 rounded-md border border-input bg-background text-sm",style:{width:"120px"}})]}),(ie||le)&&s.jsx(h,{variant:"ghost",size:"sm",onClick:()=>{const e=H();Q(e.startDate),re(e.endDate),ce(""),oe(""),A(1)},children:"Clear Filters"})]})]}),0===e.length?s.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No transactions found"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[s.jsx(O,{children:"Date"}),s.jsx(O,{children:"Category"}),s.jsx(O,{children:"Bucket"}),s.jsx(O,{children:"Type"}),s.jsx(O,{children:"Confidence"}),s.jsx(O,{children:"Bank Account"}),s.jsx(O,{children:"Description"}),s.jsx(O,{children:"Amount"}),s.jsx(O,{children:"Uploaded"}),s.jsx(O,{})]})}),s.jsx(U,{children:e.map(e=>s.jsxs(R,{children:[s.jsx($,{children:et(new Date(e.transaction_date),"MMM dd, yyyy")}),s.jsx($,{children:s.jsx("span",{className:"font-medium",children:e.category})}),s.jsx($,{children:e.bucket}),s.jsx($,{children:e.type}),s.jsx($,{children:e.auto_classified?we(e):s.jsx("span",{className:"text-xs text-muted-foreground",children:"Manual"})}),s.jsx($,{children:s.jsxs("div",{className:"text-sm",children:[s.jsx("div",{className:"font-medium",children:e.bank_accounts.bank_name}),s.jsx("div",{className:"text-muted-foreground text-xs",children:e.bank_accounts.account_name})]})}),s.jsx($,{className:"max-w-xs",children:s.jsx(V,{children:s.jsxs(K,{delayDuration:200,children:[s.jsx(X,{asChild:!0,children:s.jsx("div",{className:"truncate cursor-help",children:e.description})}),s.jsx(J,{className:"max-w-md bg-popover text-popover-foreground border border-border shadow-lg z-50 p-3",sideOffset:5,children:s.jsx("p",{className:"whitespace-normal break-words",children:e.description})})]})})}),s.jsxs($,{className:e.amount<0?"text-destructive":"text-green-600",children:["$",Math.abs(e.amount).toFixed(2)]}),s.jsx($,{className:"text-xs text-muted-foreground",children:e.uploaded_at?et(new Date(e.uploaded_at),"MMM dd, yyyy"):"—"}),s.jsx($,{children:s.jsx(h,{variant:"ghost",size:"sm",onClick:()=>(e=>{fe(e),ye({category:e.category||"",bucket:e.bucket||"",type:e.type||"",description:e.description||"",amount:e.amount,transaction_date:e.transaction_date}),pe(!0)})(e),children:s.jsx(Nt,{className:"h-4 w-4"})})})]},e.id))})]})}),s.jsxs("div",{className:"flex items-center justify-between mt-4",children:[s.jsxs("div",{className:"text-sm text-muted-foreground",children:["Page ",v," ",F>0&&`(of ${Math.ceil(F/50)})`]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>A(e=>Math.max(1,e-1)),disabled:1===v,children:[s.jsx(lt,{className:"h-4 w-4"}),"Previous"]}),s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>A(e=>e+1),disabled:50*v>=F,children:["Next",s.jsx(ot,{className:"h-4 w-4"})]})]})]})]})]})}),s.jsx(fs,{isOpen:x,onClose:()=>{p(!1),f([]),y("")},onConfirm:async e=>{try{const t=await o();if(!t)throw new Error("No company found");const{data:{user:s}}=await q.auth.getUser();if(!s)throw new Error("User not authenticated");const a=e.map(e=>({company_id:t,bank_account_id:i,location:e.location,category:e.category,bucket:e.bucket,type:e.type,detail:e.detail,card:e.card,transaction_date:e.transaction_date,amount:e.amount,description:e.description,uploaded_by:s.id,confidence:e.confidence||null,auto_classified:e.autoClassified||!1,matched_rule:e.matchedRule||null})),{error:n}=await q.from("bank_statements").insert(a);if(n)throw n;Ne({title:"Success",description:`Imported ${e.length} transactions successfully.`}),p(!1),f([]),ke()}
2catch(t){Ne({title:"Error importing records",description:t.message,variant:"destructive"})}},records:g,fileName:j,onRecordsUpdate:async()=>{const e=await o();if(!e)return;const t=await Se(g,e);f(t)}}),s.jsx(N,{open:he,onOpenChange:pe,children:s.jsxs(w,{className:"max-w-lg",children:[s.jsxs(b,{children:[s.jsx(k,{children:"Edit Transaction"}),s.jsx(C,{children:"Update the details of this transaction."})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"edit-date",children:"Transaction Date"}),s.jsx(D,{id:"edit-date",type:"date",value:je.transaction_date,onChange:e=>ye(t=>({...t,transaction_date:e.target.value}))})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"edit-amount",children:"Amount"}),s.jsx(D,{id:"edit-amount",type:"number",step:"0.01",value:je.amount,onChange:e=>ye(t=>({...t,amount:parseFloat(e.target.value)||0}))})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"edit-description",children:"Description"}),s.jsx(D,{id:"edit-description",value:je.description,onChange:e=>ye(t=>({...t,description:e.target.value})),placeholder:"Transaction description"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"edit-category",children:"Category"}),s.jsxs(I,{value:je.category,onValueChange:e=>ye(t=>({...t,category:e})),children:[s.jsx(T,{id:"edit-category",children:s.jsx(E,{placeholder:"Select category"})}),s.jsxs(M,{children:[s.jsx(z,{value:"expenses",children:"Expenses"}),s.jsx(z,{value:"income",children:"Income"}),s.jsx(z,{value:"transfer",children:"Transfer"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"edit-bucket",children:"Bucket"}),s.jsxs(I,{value:je.bucket,onValueChange:e=>ye(t=>({...t,bucket:e})),children:[s.jsx(T,{id:"edit-bucket",children:s.jsx(E,{placeholder:"Select bucket"})}),s.jsxs(M,{children:[s.jsx(z,{value:"cogs",children:"COGS"}),s.jsx(z,{value:"opex",children:"OPEX"}),s.jsx(z,{value:"payroll",children:"Payroll"}),s.jsx(z,{value:"tax",children:"Tax"}),s.jsx(z,{value:"other",children:"Other"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"edit-type",children:"Type"}),s.jsx(D,{id:"edit-type",value:je.type,onChange:e=>ye(t=>({...t,type:e.target.value})),placeholder:"e.g., Utilities, Rent"})]})]})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(h,{variant:"outline",onClick:()=>{pe(!1),fe(null)},children:"Cancel"}),s.jsx(h,{onClick:async()=>{if(ge){_e(!0);try{const t=await o();if(!t)throw new Error("No company found");if("bank_statements"===ge._source){const{error:e}=await q.from("bank_statements").update({category:je.category||null,bucket:je.bucket||null,type:je.type||null,description:je.description||null,amount:je.amount,transaction_date:je.transaction_date,auto_classified:!1}).eq("id",ge.id).eq("company_id",t);if(e)throw e}else{const{error:e}=await q.from("bank_transactions").update({category_type:je.category||null,subcategory:je.bucket||null,detail_source:je.type||null,description:je.description||null,amount:je.amount,transaction_date:je.transaction_date,auto_categorized:!1}).eq("id",ge.id);if(e)throw e}const s=["revenue","expenses","balance_sheet"];if(je.category&&je.bucket&&s.includes(je.category))try{const e={id:ge.id,transaction_date:ge.transaction_date,amount:ge.amount,description:ge.description||"",merchant_name:ge.description||void 0,category_type:je.category,subcategory:je.bucket,detail_source:je.type||void 0,location_id:void 0};await ee(e,t,ge.bank_account_id)}catch(e){}Ne({title:"Transaction updated",description:"The transaction has been updated successfully."}),pe(!1),fe(null),ke()}catch(t){Ne({title:"Error updating transaction",description:t.message,variant:"destructive"})}finally{_e(!1)}}},disabled:ve,children:ve?"Saving...":"Save Changes"})]})]})})]})},vs=({status:e})=>{if(!e)return s.jsxs(F,{variant:"secondary",children:[s.jsx(Ze,{className:"h-3 w-3 mr-1"}),"Unknown"]});switch(e){case"connected":return s.jsxs(F,{variant:"default",className:"bg-green-600 hover:bg-green-700",children:[s.jsx(bt,{className:"h-3 w-3 mr-1"}),"Connected"]});case"manual_upload":return s.jsxs(F,{variant:"secondary",children:[s.jsx(yt,{className:"h-3 w-3 mr-1"}),"Manual Upload"]});
2case"pending_selection":return s.jsxs(F,{variant:"outline",className:"border-yellow-500 text-yellow-700 dark:text-yellow-400",children:[s.jsx(dt,{className:"h-3 w-3 mr-1"}),"Pending Selection"]});case"failed":return s.jsxs(F,{variant:"destructive",children:[s.jsx(wt,{className:"h-3 w-3 mr-1"}),"Failed"]});default:return s.jsxs(F,{variant:"outline",children:[s.jsx(wt,{className:"h-3 w-3 mr-1"}),"Not Connected"]})}},_s=({status:e="not_started",progress:t=0})=>{switch(e){case"completed":return s.jsxs(F,{variant:"default",className:"bg-green-600 hover:bg-green-700",children:[s.jsx(bt,{className:"h-3 w-3 mr-1"}),"Trained"]});case"in_progress":return s.jsxs(F,{variant:"secondary",children:[s.jsx(Ct,{className:"h-3 w-3 mr-1 animate-spin"}),"Training (",t,"%)"]});default:return s.jsxs(F,{variant:"outline",children:[s.jsx(kt,{className:"h-3 w-3 mr-1"}),"Not Trained"]})}};async function Ns(e,t){const{companyId:s,accountId:a,accountName:n,onProgress:r}=t;if(0===e.length)return 0;const i=await async function(e,t,s){const a=e.map(e=>e.teller_transaction_id).filter(Boolean);if(0===a.length)return e;const n=new Set;for(let r=0;r<a.length;r+=200){const e=a.slice(r,r+200),{data:i}=await q.from("bank_transactions").select("teller_transaction_id").eq("account_id",t).eq("company_id",s).in("teller_transaction_id",e);if(i)for(const t of i)t.teller_transaction_id&&n.add(t.teller_transaction_id)}return e.filter(e=>!e.teller_transaction_id||!n.has(e.teller_transaction_id))}(e,a,s);if(0===i.length)return null==r||r(100),0;let c=0;for(let l=0;l<i.length;l+=50){const e=i.slice(l,l+50),o=await Promise.all(e.map(async n=>{try{if(t.skipClassification)return{...n,category_type:null,auto_categorized:!1,needs_review:!0};const r=await ne({id:`sync-${l}-${e.indexOf(n)}`,transaction_date:n.transaction_date,amount:n.amount,description:n.description||"",merchant_name:n.merchant_name,account_id:a,company_id:s,location_id:void 0}),i={...n,category_type:r.category_type,subcategory:r.subcategory,detail_source:r.detail_source,classification_confidence:r.confidence,classification_method:r.method,auto_categorized:r.confidence>=.8,needs_review:r.needsReview||r.confidence<.8};return"payroll"===r.subcategory&&(i.payroll_assignment_status="unassigned"),i}catch(r){return n}})),{data:d,error:m}=await q.from("bank_transactions").insert(o).select("id, category_type, needs_review, classification_confidence, transaction_date, amount, merchant_name, description");if(m);else if(d){c+=d.length;for(const e of d)re({category_type:e.category_type,needs_review:e.needs_review,classification_confidence:e.classification_confidence})&&ie(s,e.id,{merchant:e.merchant_name??e.description??null,amount:e.amount,date:e.transaction_date,source:n||"Bank Account"}).catch(e=>{})}r&&r(Math.round((l+e.length)/i.length*100))}return c}async function ws(e){var t;const{accountId:s,companyId:a,endDate:n,accountName:r,onProgress:i}=e,c=await async function(e,t,s){const{data:a}=await q.from("bank_transactions").select("transaction_date").eq("account_id",e).eq("company_id",t).order("transaction_date",{ascending:!1}).limit(1).single();if(null==a?void 0:a.transaction_date){const e=a.transaction_date;return e<s?e:s}return s}(s,a,e.startDate),l=await q.functions.invoke("teller-fetch-transactions",{body:{account_id:s,start_date:c,end_date:n}});if(l.error)throw l.error;if(!(null==(t=l.data)?void 0:t.transactions))throw new Error("No transactions returned from Teller");const o=l.data.transactions,d=o.map(e=>({...e,company_id:a,account_id:s,period_flag:"ytd",source:"bank"})),m=await Ns(d,{companyId:a,accountId:s,accountName:r,onProgress:i});return await q.from("bank_accounts").update({last_synced_at:(new Date).toISOString()}).eq("id",s),{total:o.length,persisted:m}}const bs=({syncEnabled:e,lastSyncedAt:t,onToggleSync:a,onManualSync:n,isSyncing:r=!1,connectionStatus:i})=>{const c="connected"===i&&e,l="connected"===i;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(S,{htmlFor:"sync-toggle",className:"text-sm font-medium",children:"Automatic Sync"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"connected"===i?"New transactions will be automatically imported daily":"Connect via Teller to enable automatic sync"})]}),s.jsx(Q,{id:"sync-toggle",checked:e,onCheckedChange:a,disabled:"connected"!==i})]}),t&&s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ze,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"text-muted-foreground",children:"Last synced:"}),s.jsx(V,{children:s.jsxs(K,{children:[s.jsx(X,{asChild:!0,children:s.jsx("span",{className:"font-medium cursor-help",children:et(new Date(t),"MMM dd, yyyy HH:mm")}
2)}),s.jsx(J,{children:s.jsx("p",{children:et(new Date(t),"PPpp")})})]})})]}),c&&s.jsxs(F,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200 dark:bg-green-950 dark:text-green-400",children:[s.jsx(bt,{className:"h-3 w-3 mr-1"}),"Active"]})]}),!t&&"connected"===i&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s.jsx(wt,{className:"h-4 w-4"}),s.jsx("span",{children:"Never synced"})]}),l&&s.jsxs(h,{variant:"outline",size:"sm",onClick:n,disabled:r,className:"w-full",children:[s.jsx(St,{className:"h-4 w-4 mr-2 "+(r?"animate-spin":"")}),r?"Syncing...":"Sync Now"]})]})},ks=({open:e,onClose:t,accountId:n,onUpdate:r})=>{var i,c,l,d;const{toast:m}=_(),[u,x]=a.useState(null),[p,g]=a.useState(!0),[f,j]=a.useState(!1),[y,v]=a.useState(!1);a.useEffect(()=>{e&&n&&S()},[e,n]);const S=async()=>{try{g(!0);const e=await o();if(!e)return;const{data:t,error:s}=await q.from("bank_accounts").select("*").eq("id",n).eq("company_id",e).single();if(s)throw s;const{data:a}=await q.from("bank_account_training_progress").select("status").eq("account_id",n).eq("company_id",e).single(),{data:r}=await q.from("bank_transactions").select("period_flag").eq("account_id",n).eq("company_id",e),i={training_window:(null==r?void 0:r.filter(e=>"training_window"===e.period_flag).length)||0,ytd:(null==r?void 0:r.filter(e=>"ytd"===e.period_flag).length)||0,live:(null==r?void 0:r.filter(e=>"live"===e.period_flag).length)||0,total:(null==r?void 0:r.length)||0},{count:c}=await q.from("bank_transaction_rules").select("*",{count:"exact",head:!0}).eq("account_id",n).eq("company_id",e);x({...t,training_status:(null==a?void 0:a.status)||"not_started",transaction_counts:i,rules_count:c||0})}catch(e){m({title:"Error",description:"Failed to load account details",variant:"destructive"})}finally{g(!1)}};return p||!u?s.jsx(N,{open:e,onOpenChange:t,children:s.jsxs(w,{children:[s.jsxs(b,{children:[s.jsx(ce,{className:"h-6 w-48"}),s.jsx(ce,{className:"h-4 w-96"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(ce,{className:"h-5 w-32"}),s.jsx(ce,{className:"h-24 w-full"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(ce,{className:"h-5 w-32"}),s.jsx(ce,{className:"h-24 w-full"})]})]})]})}):s.jsx(N,{open:e,onOpenChange:t,children:s.jsxs(w,{className:"sm:max-w-3xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsxs(k,{className:"flex items-center gap-2",children:[s.jsx(Dt,{className:"h-5 w-5"}),u.account_name]}),s.jsx(C,{children:"View and manage account details, sync settings, and transaction data"})]}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs(B,{children:[s.jsx(W,{children:s.jsx(H,{className:"text-lg",children:"Account Information"})}),s.jsx(Y,{className:"space-y-4",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Bank Name"}),s.jsx("p",{className:"font-medium",children:u.bank_name||"—"})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Account Type"}),s.jsx("p",{className:"font-medium capitalize",children:u.account_type.replace("_"," ")})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Connection Status"}),s.jsx(vs,{status:u.connection_status})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Training Status"}),s.jsx(_s,{status:u.training_status})]})]})})]}),"connected"===u.connection_status&&s.jsxs(B,{children:[s.jsx(W,{children:s.jsx(H,{className:"text-lg",children:"Teller Connection"})}),s.jsxs(Y,{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[u.teller_enrollment_id&&s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Enrollment ID"}),s.jsx("p",{className:"font-mono text-sm",children:u.teller_enrollment_id})]}),u.teller_account_id&&s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Teller Account ID"}),s.jsx("p",{className:"font-mono text-sm",children:u.teller_account_id})]})]}),s.jsxs(h,{variant:"destructive",size:"sm",onClick:async()=>
2{if(u&&confirm("Are you sure you want to disconnect this account? This will stop automatic syncing."))try{v(!0);const{error:e}=await q.from("bank_accounts").update({connection_status:"not_connected",teller_enrollment_id:null,teller_access_token:null,teller_account_id:null,sync_enabled:!1}).eq("id",n);if(e)throw e;m({title:"Success",description:"Account disconnected successfully"}),await S(),null==r||r()}catch(e){m({title:"Error",description:e.message||"Failed to disconnect account",variant:"destructive"})}finally{v(!1)}},disabled:y,children:[s.jsx(It,{className:"h-4 w-4 mr-2"}),y?"Disconnecting...":"Disconnect Teller"]})]})]}),s.jsxs(B,{children:[s.jsx(W,{children:s.jsx(H,{className:"text-lg",children:"Sync Settings"})}),s.jsx(Y,{children:s.jsx(bs,{syncEnabled:u.sync_enabled,lastSyncedAt:u.last_synced_at,onToggleSync:async e=>{if(u)try{const{error:t}=await q.from("bank_accounts").update({sync_enabled:e}).eq("id",n);if(t)throw t;x({...u,sync_enabled:e}),m({title:"Success",description:"Automatic sync "+(e?"enabled":"disabled")}),null==r||r()}catch(t){m({title:"Error",description:t.message||"Failed to update sync settings",variant:"destructive"})}},onManualSync:async()=>{if(u&&"connected"===u.connection_status)try{j(!0);const e=await o();if(!e)throw new Error("Company not found");const{persisted:t}=await ws({accountId:n,companyId:e,accountName:u.account_name,startDate:u.last_synced_at?new Date(u.last_synced_at).toISOString().split("T")[0]:new Date(Date.now()-7776e6).toISOString().split("T")[0],endDate:(new Date).toISOString().split("T")[0]});m({title:"Success",description:`Synced ${t} transactions`}),await S(),null==r||r()}catch(e){m({title:"Error",description:e.message||"Failed to sync transactions",variant:"destructive"})}finally{j(!1)}},isSyncing:f,connectionStatus:u.connection_status})})]}),s.jsxs(B,{children:[s.jsx(W,{children:s.jsx(H,{className:"text-lg",children:"Transaction Statistics"})}),s.jsxs(Y,{children:[s.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Training Window"}),s.jsx("p",{className:"text-2xl font-bold",children:(null==(i=u.transaction_counts)?void 0:i.training_window)||0})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"YTD"}),s.jsx("p",{className:"text-2xl font-bold",children:(null==(c=u.transaction_counts)?void 0:c.ytd)||0})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Live"}),s.jsx("p",{className:"text-2xl font-bold",children:(null==(l=u.transaction_counts)?void 0:l.live)||0})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Total"}),s.jsx("p",{className:"text-2xl font-bold",children:(null==(d=u.transaction_counts)?void 0:d.total)||0})]})]}),s.jsx(us,{className:"my-4"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Rules Created"}),s.jsx("p",{className:"text-2xl font-bold",children:u.rules_count||0})]})]})]})]})]})})},Cs=({open:e,onClose:t,accountId:n,accountName:r,connectionStatus:i,tellerAccessToken:c,onSuccess:l})=>{const{toast:d}=_(),[m,u]=a.useState("teller"),[x,p]=a.useState(!1),[g,f]=a.useState(0),j=a.useRef(null),[y,v]=a.useState(()=>{const e=new Date;return e.setMonth(e.getMonth()-3),e.toISOString().split("T")[0]}),[I,T]=a.useState(()=>(new Date).toISOString().split("T")[0]),E="connected"===i&&c,M=e=>{if(!e)return"";if("number"==typeof e){const t=new Date(1899,11,30);return new Date(t.getTime()+864e5*e).toISOString().split("T")[0]}const t=new Date(e);return isNaN(t.getTime())?"string"==typeof e&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:e.toString():t.toISOString().split("T")[0]},z=async e=>{var s;try{p(!0),f(0);const a=await o();if(!a)throw new Error("Company ID not found");f(10);const i=null==(s=e.name.split(".").pop())?void 0:s.toLowerCase();let c=[];if("csv"===i)c=await(async e=>new Promise((t,s)=>{te.parse(e,{header:!0,complete:e=>{const s=e.data.filter(e=>e["Transaction Date"]&&e.Amount).map(e=>({transaction_date:M(e["Transaction Date"]),amount:parseFloat(e.Amount)||0,description:e.Description||null,merchant_name:e.Merchant||e.Detail||null}));t(s)},error:e=>s(e)})}))(e);
2else{if("xlsx"!==i&&"xls"!==i)throw new Error("Unsupported file format. Please upload CSV or Excel files.");c=await(async e=>new Promise((t,s)=>{const a=new FileReader;a.onload=e=>{var a;try{const s=null==(a=e.target)?void 0:a.result,n=se(s,{type:"binary",cellDates:!0}),r=n.SheetNames[0],i=n.Sheets[r],c=ae.sheet_to_json(i,{header:1,raw:!1}),l=c[0],o=c.slice(1),d=e=>l.findIndex(t=>t&&t.toString().toLowerCase().includes(e.toLowerCase())),m=d("transaction date"),u=d("amount"),x=d("description"),h=d("merchant"),p=o.filter(e=>e[m]&&e[u]).map(e=>({transaction_date:M(e[m]),amount:parseFloat(e[u])||0,description:x>=0?e[x]:null,merchant_name:h>=0?e[h]:null}));t(p)}catch(n){s(n)}},a.onerror=e=>s(e),a.readAsBinaryString(e)}))(e)}if(0===c.length)throw new Error("No valid transactions found in file.");f(30);const m=c.map(e=>({company_id:a,account_id:n,transaction_date:e.transaction_date,amount:e.amount,description:e.description,merchant_name:e.merchant_name,period_flag:"ytd",source:"bank"}));f(40);const u=await Ns(m,{companyId:a,accountId:n,accountName:r,onProgress:e=>f(40+Math.round(.55*e))});f(100),xe(a).catch(console.error),d({title:"Success",description:`Imported ${u} transactions to ${r}`}),null==l||l(),t()}catch(a){d({title:"Error",description:a.message||"Failed to process file",variant:"destructive"})}finally{p(!1),f(0)}};return s.jsx(N,{open:e,onOpenChange:t,children:s.jsxs(w,{className:"sm:max-w-2xl",children:[s.jsxs(b,{children:[s.jsx(k,{children:"Import Transactions"}),s.jsxs(C,{children:["Import transactions for ",r]})]}),s.jsxs(le,{value:m,onValueChange:e=>u(e),children:[s.jsxs(oe,{className:"grid w-full grid-cols-2",children:[s.jsxs(de,{value:"teller",disabled:!E,children:[s.jsx(Tt,{className:"h-4 w-4 mr-2"}),"Teller Sync"]}),s.jsxs(de,{value:"manual",children:[s.jsx(yt,{className:"h-4 w-4 mr-2"}),"Manual Upload"]})]}),s.jsx(me,{value:"teller",className:"space-y-4 mt-4",children:E?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"space-y-4",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"start-date",children:"Start Date"}),s.jsx(D,{id:"start-date",type:"date",value:y,onChange:e=>v(e.target.value),disabled:x})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"end-date",children:"End Date"}),s.jsx(D,{id:"end-date",type:"date",value:I,onChange:e=>T(e.target.value),disabled:x,max:(new Date).toISOString().split("T")[0]})]})]})}),x&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{children:"Importing transactions..."}),s.jsxs("span",{children:[g,"%"]})]}),s.jsx(ue,{value:g})]}),s.jsx(h,{onClick:async()=>{var e;if(E)try{p(!0),f(0);const{data:{session:s}}=await q.auth.getSession();if(!s)throw new Error("Not authenticated");f(10);const a=await o();if(!a)throw new Error("Company ID not found");f(20);const i=await q.functions.invoke("teller-fetch-transactions",{body:{account_id:n,start_date:y,end_date:I}});if(i.error)throw i.error;if(!(null==(e=i.data)?void 0:e.transactions))throw new Error("No transactions returned");f(40);const c=new Date((new Date).getFullYear(),0,1).toISOString().split("T")[0],m=i.data.transactions.map(e=>{const t=new Date(e.transaction_date),s=new Date(c),r=new Date(y),i=new Date(I);let l="pre_ytd";return t>=s&&(l=t>=r&&t<=i?"training_window":"ytd"),{...e,company_id:a,account_id:n,period_flag:l,source:"bank"}}),u=e=>"training_window"===e.period_flag,x=m.filter(u),h=m.filter(e=>!u(e));let g=0;x.length>0&&(g+=await Ns(x,{companyId:a,accountId:n,accountName:r,skipClassification:!0,onProgress:e=>f(40+Math.round(.15*e))})),h.length>0&&(g+=await Ns(h,{companyId:a,accountId:n,accountName:r,onProgress:e=>f(55+Math.round(.4*e))})),await q.from("bank_accounts").update({last_synced_at:(new Date).toISOString()}).eq("id",n),f(100),xe(a).catch(console.error),d({title:"Success",description:`Imported ${g} transactions from ${r}`}),null==l||l(),t()}catch(s){d({title:"Error",description:s.message||"Failed to import transactions",variant:"destructive"})}finally{p(!1),f(0)}else d({title:"Error",description:"Account is not connected via Teller",variant:"destructive"})},disabled:x||!y||!I,className:"w-full",children:x?s.jsxs(s.Fragment,{children:[s.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Importing..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Tt,{className:"h-4 w-4 mr-2"}),"Import from Teller"]})})]}):s.jsx(B,{children:s.jsx(Y,{className:"pt-6",children:s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"This account is not connected via Teller. Please connect it first to use Teller sync."})})})}
2),s.jsxs(me,{value:"manual",className:"space-y-4 mt-4",children:[s.jsx(B,{className:"border-2 border-dashed p-8 text-center cursor-pointer hover:border-primary transition-colors",onClick:()=>{var e;return!x&&(null==(e=j.current)?void 0:e.click())},children:s.jsxs(Y,{className:"pt-6",children:[s.jsx(yt,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),s.jsx("p",{className:"text-sm font-medium mb-2",children:"Upload CSV or Excel file"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported formats: CSV, XLSX, XLS"}),s.jsx("input",{ref:j,type:"file",accept:".csv,.xlsx,.xls",className:"hidden",onChange:e=>{var t;const s=null==(t=e.target.files)?void 0:t[0];s&&z(s)},disabled:x})]})}),x&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{children:"Processing file..."}),s.jsxs("span",{children:[g,"%"]})]}),s.jsx(ue,{value:g})]})]})]})]})})},Ss=({open:e,accounts:t,saving:a,onSelect:n,onClose:r})=>{const i=e=>{switch(null==e?void 0:e.toLowerCase()){case"depository":return"🏦";case"credit":return"💳";default:return"💰"}};return s.jsx(N,{open:e,onOpenChange:e=>!e&&!a&&r(),children:s.jsxs(w,{className:"sm:max-w-lg",children:[s.jsxs(b,{className:"space-y-3",children:[s.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-amber-100",children:s.jsx(Et,{className:"h-6 w-6 text-amber-600"})}),s.jsx(k,{className:"text-center text-xl",children:"Select Bank Account"}),s.jsxs(C,{className:"text-center",children:["Your bank is connected! We found ",t.length," account",t.length>1?"s":"",".",s.jsx("br",{}),s.jsx("span",{className:"font-medium text-foreground",children:"Please select which account to use for transaction syncing:"})]})]}),s.jsx("div",{className:"space-y-3 mt-4 max-h-[300px] overflow-y-auto pr-1",children:t.map(e=>{var t,r,c;return s.jsx(B,{className:"cursor-pointer border-2 transition-all hover:border-primary hover:shadow-md "+(a?"opacity-50 pointer-events-none":""),onClick:()=>!a&&n(e.id),children:s.jsx(Y,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("div",{className:"text-2xl",children:i(e.type)}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h4",{className:"font-semibold truncate",children:e.name}),e.last_four&&s.jsxs("span",{className:"text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded",children:["••••",e.last_four]})]}),s.jsxs("p",{className:"text-sm text-muted-foreground",children:[null==(t=e.institution)?void 0:t.name," • ",(r=e.type,c=e.subtype,c?c.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()):(null==r?void 0:r.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))||"Account")]})]}),s.jsx(Et,{className:"h-5 w-5 text-muted-foreground flex-shrink-0"})]})})},e.id)})}),a&&s.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-muted-foreground py-2",children:[s.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-primary border-t-transparent rounded-full"}),s.jsx("span",{children:"Connecting account..."})]}),s.jsx("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t",children:s.jsx(h,{variant:"outline",onClick:r,disabled:a,children:"Cancel"})})]})})},Ds=({config:e,accountId:t,onSuccess:n,onExit:r})=>{const{toast:i}=_(),[c,l]=a.useState(!1),[o,d]=a.useState([]),[m,u]=a.useState(null),[x,h]=a.useState(!1),p=a.useRef(null),g=a.useRef(!1),f=a.useCallback(async(e,s,a)=>{var c,o;try{h(!0);const{data:{session:r}}=await q.auth.getSession();if(!r)throw new Error("Not authenticated");const m=await q.functions.invoke("teller-save-enrollment",{body:{accessToken:e.accessToken,enrollment:e.enrollment,account_id:t,selected_teller_account_id:s,selected_teller_account_name:a}});if(m.error)throw m.error;if((null==(c=m.data)?void 0:c.requires_selection)&&(null==(o=m.data)?void 0:o.accounts))return d(m.data.accounts),u(e),l(!0),void h(!1);i({title:"Success",description:"Bank account connected successfully"}),l(!1),u(null),n()}catch(m){i({title:"Error",description:m.message||"Failed to connect account",variant:"destructive"}),h(!1),r()}},[t,n,r,i]);return a.useEffect(()=>{if(g.current)return;const t=window.TellerConnect;if(!t)return i({title:"Error",description:"Teller Connect script not loaded",variant:"destructive"}),void r();if(window.__tellerConnectInstance){try{const e=window.__tellerConnectInstance;"function"==typeof e.destroy?e.destroy():"function"==typeof e.close&&e.close()}catch(s){}delete window.__tellerConnectInstance}if(p.current){try{"function"==typeof p.current.destroy?p.current.destroy():"function"==typeof p.current.close&&p.current.close()}catch(s){}p.current=null}try{const s=t.setup({applicationId:e.applicationId,products:e.products,selectAccount:"disabled",onSuccess:async e=>{const t={accessToken:e.accessToken,enrollment:e.enrollment||e};await f(t)},onExit:()=>{g.current=!1,p.current=null,window.__tellerConnectInstance&&delete window.__tellerConnectInstance,r()}});p.current=s,window.__tellerConnectInstance=s,g.current=!0,s.open()}catch(s){s.message&&s.message.includes("single Teller Connect embed")?i({title:"Error",description:"Teller Connect is already open. Please close the existing connection and try again.",variant:"destructive"}):i({title:"Error",description:"Failed to initialize Teller Connect. Please refresh the page and try again.",variant:"destructive"}),g.current=!1,p.current=null,window.__tellerConnectInstance&&delete window.__tellerConnectInstance,r()}return()=>{if(g.current=!1,p.current){try{"function"==typeof p.current.destroy?p.current.destroy():"function"==typeof p.current.close&&p.current.close()}catch(s){}p.current=null}window.__tellerConnectInstance&&delete window.__tellerConnectInstance}},[e.applicationId,e.products,f,r,i]),s.jsx(s.Fragment,{children:s.jsx(Ss,{open:c,accounts:o,saving:x,onSelect:async e=>{if(!m)return;const t=o.find(t=>
2t.id===e);await f(m,e,null==t?void 0:t.name)},onClose:()=>{l(!1),u(null),r()}})})},Is=e=>e.is_credit_card?e.amount>=0?"expenses":"balance_sheet":e.amount>=0?"revenue":"expenses",Ts=e=>e.toLowerCase().replace(/[0-9#*]+/g,"").replace(/\s+/g," ").replace(/[^a-z\s]/g,"").trim().substring(0,50),Es=({open:e,onClose:t,accountId:n,onComplete:r})=>{const{toast:i}=_(),[c,l]=a.useState(!0),[d,u]=a.useState(!1),[x,p]=a.useState([]),[g,f]=a.useState(0),[j,y]=a.useState(!1),[v,D]=a.useState(!1),[A,V]=a.useState(!1),[G,K]=a.useState(!1),[X,J]=a.useState(new Set),[Q,Z]=a.useState(new Set),[te,se]=a.useState("expenses"),[ae,re]=a.useState(""),[ie,le]=a.useState(""),oe=a.useCallback(async()=>{try{l(!0),V(!1),f(0);const e=await o();if(!e)return l(!1),void V(!0);const{data:t,error:s}=await q.from("bank_transactions").select("id, transaction_date, amount, description, merchant_name, category_type, subcategory, detail_source, location_id, period_flag, account_id").eq("company_id",e).eq("account_id",n).is("category_type",null).order("transaction_date",{ascending:!1});if(s)throw s;if(!t||0===t.length)return p([]),l(!1),void V(!0);const a=[...new Set(t.map(e=>e.account_id))],{data:r}=await q.from("bank_accounts").select("id, account_name, account_type").in("id",a),i=new Map((r||[]).map(e=>{var t,s,a;return[e.id,{name:e.account_name,type:e.account_type,isCreditCard:"credit"===e.account_type||(null==(t=e.account_name)?void 0:t.toLowerCase().includes("credit"))||(null==(s=e.account_name)?void 0:s.toLowerCase().includes(" cc"))||(null==(a=e.account_name)?void 0:a.toLowerCase().endsWith(" cc"))}]})),c=t.map(e=>{const t=i.get(e.account_id)||{name:"Unknown Account",isCreditCard:!1};return{...e,account_name:t.name,is_credit_card:t.isCreditCard}});c.sort((e,t)=>new Date(t.transaction_date).getTime()-new Date(e.transaction_date).getTime());const d=he(c,!1),m=e=>e.is_credit_card?e.amount>0?"expense":"revenue":e.amount>=0?"revenue":"expense",u=d.filter(e=>{if(0===e.transactions.length)return!1;const t=m(e.transactions[0]);return e.transactions.every(e=>m(e)===t)}).map(e=>({...e,isTrained:!1}));if(p(u),l(!1),V(!0),u.length>0){const t=u[0],s=t.transactions[0];se(Is(s)),re(""),le(""),de(t,0,e)}}catch(e){i({title:"Error",description:"Failed to load transactions",variant:"destructive"}),l(!1),V(!0)}},[n,i]);a.useEffect(()=>{e&&oe()},[e,oe]);const de=async(e,t,s)=>{var a;if(null==(a=e.transactions[0])?void 0:a.account_id){D(!0);try{const a=s||await o();if(!a)return void D(!1);const n=e.transactions[0],r=await ne({id:n.id,transaction_date:n.transaction_date,amount:n.amount,description:n.description||"",merchant_name:n.merchant_name,account_id:n.account_id,company_id:a,location_id:n.location_id});p(e=>e.map((e,s)=>s===t?{...e,suggestion:r}:e)),t===g&&r.category_type&&(se(r.category_type),re(r.subcategory||""),le(r.detail_source||""))}catch(n){}finally{D(!1)}}},me=async()=>{if(ae){u(!0);try{const e=await o();if(!e)throw new Error("Company ID not found");const t=x[g],s=t.transactions.map(e=>e.id),a={category_type:te,subcategory:ae,detail_source:ie||null,auto_categorized:!1,needs_review:!1},{error:n}=await q.from("bank_transactions").update(a).in("id",s);if("payroll"===ae&&await q.from("bank_transactions").update({payroll_assignment_status:"unassigned"}).in("id",s).neq("payroll_assignment_status","assigned"),n)throw n;if(ie&&ie.trim()&&ae)try{["platform","cash","check","wire","collected","remitted","federal","state","local","bank","investment","w2","tax","1099","base","utilities","percentage","cam","loan","credit_card","loc","doordash","ubereats","grubhub","toast","square","stripe","internal","external","principal","interest","advance","draw","contribution","distribution"].some(e=>e.toLowerCase()===ie.trim().toLowerCase())||await q.from("custom_detail_values").upsert({company_id:e,subcategory:ae.toLowerCase(),detail_value:ie.trim(),updated_at:(new Date).toISOString()},{onConflict:"company_id,subcategory,detail_value"})}catch{}const r=t.transactions[0];try{await ee({id:r.id,transaction_date:r.transaction_date,amount:r.amount,description:r.description||"",merchant_name:r.merchant_name,category_type:te,subcategory:ae,detail_source:ie||void 0,location_id:r.location_id||void 0},e,r.account_id)}catch{}const c=x.map((e,t)=>t===g?{...e,isTrained:!0}:e);p(c),i({title:"Saved!",description:`Categorized ${t.transactions.length} transaction${t.transactions.length>
21?"s":""}`}),xe(c)}catch(e){i({title:"Error",description:e.message||"Failed to save",variant:"destructive"})}finally{u(!1)}}else i({title:"Subcategory Required",description:"Please select or enter a subcategory",variant:"destructive"})},xe=async e=>{var t;const s=e.findIndex((e,t)=>t>g&&!e.isTrained);if(-1!==s){f(s);const a=e[s],n=a.transactions[0];(null==(t=a.suggestion)?void 0:t.category_type)?(se(a.suggestion.category_type),re(a.suggestion.subcategory||""),le(a.suggestion.detail_source||"")):(se(Is(n)),re(""),le(""),a.suggestion||de(a,s)),y(!1),K(!1),J(new Set),Z(new Set)}},ve=()=>{var e;if(g>0){const t=g-1;f(t);const s=x[t],a=s.transactions[0];(null==(e=s.suggestion)?void 0:e.category_type)?(se(s.suggestion.category_type),re(s.suggestion.subcategory||""),le(s.suggestion.detail_source||"")):(se(Is(a)),re(""),le("")),y(!1),K(!1),J(new Set),Z(new Set)}},_e=()=>{var e;if(g<x.length-1){const t=g+1;f(t);const s=x[t],a=s.transactions[0];(null==(e=s.suggestion)?void 0:e.category_type)?(se(s.suggestion.category_type),re(s.suggestion.subcategory||""),le(s.suggestion.detail_source||"")):(se(Is(a)),re(""),le(""),de(s,t)),y(!1),K(!1),J(new Set),Z(new Set)}},Ne=()=>{const e=x[g];(null==e?void 0:e.suggestion)&&(e.suggestion.category_type&&se(e.suggestion.category_type),re(e.suggestion.subcategory||""),le(e.suggestion.detail_source||""))},we=()=>{var e;if(0===X.size)return;const t=x[g],s=t.transactions.filter(e=>X.has(e.id)),a=t.transactions.filter(e=>!X.has(e.id));if(0===a.length)return void i({title:"Cannot ungroup all",description:"At least one transaction must remain",variant:"destructive"});const n=[...x];n[g]={...t,transactions:a,descriptionPattern:(null==(e=a[0])?void 0:e.description)?Ts(a[0].description):t.descriptionPattern};const r=s[0],c=!!r&&(r.is_credit_card?r.amount<0:r.amount>=0);n.splice(g+1,0,{descriptionPattern:(null==r?void 0:r.description)?Ts(r.description):"Ungrouped",transactions:s,isTrained:!1,isRevenue:c}),p(n),J(new Set),K(!1),Z(new Set),i({title:"Ungrouped",description:`${s.length} transaction(s) moved to a new group`})},be=x.length,ke=x.filter(e=>e.isTrained).length,Ce=x.reduce((e,t)=>e+t.transactions.length,0),Se=x.filter(e=>e.isTrained).reduce((e,t)=>e+t.transactions.length,0),De=be-ke,Ie=()=>{null==r||r(),t()};return s.jsx(N,{open:e,onOpenChange:t,children:s.jsxs(w,{className:"sm:max-w-4xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsxs(k,{className:"flex items-center gap-2",children:[s.jsx(Mt,{className:"h-5 w-5"}),"Train AI Categorization"]}),s.jsx(C,{children:Ce>0?`${Ce} uncategorized transaction${1!==Ce?"s":""} need categorization. Categorize one and the AI learns the pattern.`:"Review and categorize transactions to train the AI."})]}),s.jsx("div",{className:"mt-2",children:(()=>{var e;if(c)return s.jsxs("div",{className:"space-y-4",children:[s.jsx(ce,{className:"h-12 w-full"}),s.jsx(ce,{className:"h-48 w-full"}),s.jsx(ce,{className:"h-32 w-full"})]});if(A&&0===x.length)return s.jsxs("div",{className:"text-center py-12 space-y-4",children:[s.jsx("div",{className:"h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto",children:s.jsx(bt,{className:"h-8 w-8 text-emerald-600"})}),s.jsxs("div",{children:[s.jsx("h4",{className:"font-semibold text-lg",children:"All Caught Up!"}),s.jsx("p",{className:"text-muted-foreground",children:"No uncategorized transactions remaining for this account."})]}),s.jsx(h,{onClick:Ie,children:"Done"})]});if(A&&0===De)return s.jsxs("div",{className:"text-center py-12 space-y-4",children:[s.jsx("div",{className:"h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto",children:s.jsx(bt,{className:"h-8 w-8 text-emerald-600"})}),s.jsxs("div",{children:[s.jsx("h4",{className:"font-semibold text-lg",children:"Training Complete!"}),s.jsxs("p",{className:"text-muted-foreground",children:["Categorized ",Se," transactions across ",ke," unique patterns."]})]}),s.jsx(h,{onClick:Ie,children:"Done"})]});const t=x[g];if(!t)return null;const a=t.transactions[0],n=t.transactions.length;return s.jsxs("div",{className:"space-y-5",children:[s.jsx(B,{className:"bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200",children:s.jsxs(Y,{className:"pt-4 pb-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Mt,{className:"h-5 w-5 text-blue-600"}),s.jsx("span",{className:"font-medium text-sm",children:"Training Progress"})]}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:[ke,"/",be," patterns · ",Se," transactions"]})]}),s.jsx(ue,{value:be>0?ke/be*100:0,className:"h-2"})]})}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(h,{variant:"outline",size:"sm",onClick:ve,disabled:0===g,children:[s.jsx(lt,{className:"h-4 w-4 mr-1"})," Previous"]}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["Pattern ",g+1," of ",be]}),s.jsxs(h,{variant:"outline",size:"sm",onClick:_e,disabled:g===be-1,children:["Next ",s.jsx(ot,{className:"h-4 w-4 ml-1"})]})]}),s.jsxs(B,{className:m("border-2 transition-colors",t.isTrained?"border-emerald-300 bg-emerald-50/30":"border-primary/30"),children:[s.jsx(W,{className:"pb-4",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs(H,{
2className:"text-lg flex items-center gap-2",children:[(a.is_credit_card?a.amount>=0:a.amount<0)?s.jsx(zt,{className:"h-5 w-5 text-red-600"}):s.jsx(At,{className:"h-5 w-5 text-emerald-600"}),s.jsxs("span",{className:m("text-2xl font-bold",a.is_credit_card?a.amount>=0?"text-red-600":"text-emerald-600":a.amount>=0?"text-emerald-600":"text-red-600"),children:[a.amount>=0?"+":"","$",Math.abs(a.amount).toFixed(2)]})]}),s.jsxs("div",{className:"mt-1 flex items-center gap-2 text-sm text-muted-foreground",children:[a.account_name&&s.jsxs(F,{variant:"outline",className:"text-xs",children:[s.jsx(Et,{className:"h-3 w-3 mr-1"}),a.account_name]}),s.jsx("span",{children:new Date(a.transaction_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",year:"numeric"})})]})]}),t.isTrained&&s.jsxs(F,{className:"bg-emerald-500",children:[s.jsx(bt,{className:"h-3 w-3 mr-1"})," Trained"]})]})}),s.jsxs(Y,{className:"space-y-5",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Full Description"}),s.jsx("div",{className:"bg-muted/50 p-4 rounded-lg font-mono text-sm",children:a.description})]}),n>1&&s.jsxs(pe,{className:"border-blue-200 bg-blue-50",children:[s.jsx(qt,{className:"h-4 w-4 text-blue-600"}),s.jsxs(ge,{className:"flex items-center justify-between",children:[s.jsxs("span",{children:[s.jsxs("strong",{className:"text-blue-700",children:[n," transactions"]})," match this pattern. Categorizing applies to all."]}),s.jsxs(h,{variant:"outline",size:"sm",className:"ml-4",onClick:()=>{y(!j),j&&(K(!1),J(new Set),Z(new Set))},children:[j?s.jsx(Ft,{className:"h-4 w-4 mr-1"}):s.jsx(Pt,{className:"h-4 w-4 mr-1"}),j?"Hide":"Show"]})]})]}),j&&n>1&&s.jsxs(B,{className:"border-dashed",children:[s.jsxs(W,{className:"pb-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(H,{className:"text-sm",children:["Similar Transactions (",n,")"]}),s.jsxs(h,{variant:G?"default":"outline",size:"sm",onClick:()=>{K(!G),G&&J(new Set)},className:"h-7 text-xs",children:[s.jsx(Lt,{className:"h-3 w-3 mr-1"})," ",G?"Cancel":"Ungroup"]})]}),G&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsxs(h,{size:"sm",onClick:we,disabled:0===X.size,className:"h-7 text-xs",children:["Ungroup Selected (",X.size,")"]}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"Select transactions to separate"})]})]}),s.jsx(Y,{children:s.jsx("div",{className:"max-h-[300px] overflow-y-auto",children:s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[G&&s.jsx(O,{className:"text-xs w-10",children:s.jsx(fe,{checked:X.size===t.transactions.length,onCheckedChange:e=>{J(e?new Set(t.transactions.map(e=>e.id)):new Set)}})}),s.jsx(O,{className:"text-xs w-20",children:"Date"}),s.jsx(O,{className:"text-xs w-24",children:"Amount"}),s.jsx(O,{className:"text-xs",children:"Description"})]})}),s.jsx(U,{children:t.transactions.map(e=>{const t=e.description||"",a=Q.has(e.id);return s.jsxs(R,{children:[G&&s.jsx($,{className:"py-2",children:s.jsx(fe,{checked:X.has(e.id),onCheckedChange:()=>{const t=new Set(X);t.has(e.id)?t.delete(e.id):t.add(e.id),J(t)}})}),s.jsx($,{className:"text-xs py-2 whitespace-nowrap",children:new Date(e.transaction_date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs($,{className:m("text-xs py-2 font-mono whitespace-nowrap",e.is_credit_card?e.amount>=0?"text-red-600":"text-emerald-600":e.amount>=0?"text-emerald-600":"text-red-600"),children:["$",Math.abs(e.amount).toFixed(2)]}),s.jsx($,{className:"text-xs py-2",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:m("font-mono break-all",!a&&"line-clamp-2"),children:a?t:t.length>60?t.substring(0,60)+"...":t}),t.length>60&&s.jsx(h,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 flex-shrink-0",onClick:()=>{const t=new Set(Q);t.has(e.id)?t.delete(e.id):t.add(e.id),Z(t)},children:a?s.jsx(Rt,{className:"h-3 w-3"}):s.jsx(Ot,{className:"h-3 w-3"})})]})})]},e.id)})})]})})})]}),v?s.jsxs("div",{className:"flex items-center gap-3 p-4 bg-primary/5 rounded-lg border border-primary/20",children:[s.jsx(Ct,{className:"h-5 w-5 animate-spin text-primary"}),s.jsx("span",{className:"text-sm",children:"AI is analyzing this transaction..."})]}):(null==(e=t.suggestion)?void 0:e.category_type)?s.jsx("div",{className:"p-4 bg-gradient-to-r from-purple-50 to-blue-50 rounded-lg border border-purple-200",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"h-10 w-10 rounded-full bg-gradient-to-br from-purple-500 to-blue-500 flex items-center justify-center",children:s.jsx(ht,{className:"h-5 w-5 text-white"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-purple-900",children:"AI Suggestion"}),s.jsxs("p",{className:"text-sm text-purple-700",children:[s.jsx("span",{className:"font-semibold",children:t.suggestion.category_type})," → ",s.jsx("span",{className:"font-semibold",children:t.suggestion.subcategory}),t.suggestion.detail_source&&s.jsxs(s.Fragment,{children:[" → ",s.jsx("span",{children:t.suggestion.detail_source})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(F,{variant:t.suggestion.confidence>=.85?"default":t.suggestion.confidence>=.7?"secondary":"outline",children:[Math.round(100*t.suggestion.confidence),"%"]}),s.jsxs(h,{size:"sm",onClick:Ne,children:[s.jsx(Ut,{className:"h-4 w-4 mr-1"})," Use"]})]})]})}):s.jsxs(pe,{variant:"default",className:"border-amber-200 bg-amber-50",children:[s.jsx($t,{className:"h-4 w-4 text-amber-600"}),s.jsx(ge,{className:"text-amber-800",children:"No AI suggestion available. Please categorize manually."})]}),s.jsx("div",{className:"space-y-4 pt-4 border-t",children:s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{children:"Category Type *"}),s.jsxs(I,{value:te,onValueChange:e=>{se(e),re(""),le("")},children:[s.jsx(T,{children:s.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[s.jsx(Vt,{className:"h-4 w-4 opacity-50"})," ",s.jsx(E,{})]})}),s.jsxs(M,{children:[s.jsx(z,{value:"revenue",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(At,{className:"h-4 w-4 text-emerald-600"})," Revenue"]})}),s.jsx(z,{value:"expenses",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(zt,{className:"h-4 w-4 text-red-600"})," Expenses"]})}),s.jsx(z,{value:"balance_sheet",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Et,{className:"h-4 w-4 text-blue-600"})," Balance Sheet"]})})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{children:"Subcategory *"}),s.jsx(je,{categoryType:te,value:ae,onValueChange:e=>{re(e),le("")},placeholder:"Select or type..."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{children:"Detail"}),s.jsx(ye,{subcategory:ae,value:ie,onValueChange:le,placeholder:"Select or type..."})]})]})})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(h,{variant:"ghost",onClick:()=>xe(x),disabled:d,children:"Skip for Now"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(h,{variant:"outline",onClick:Ie,children:"Done"}),s.jsx(h,{onClick:me,disabled:d||!ae,children:d?s.jsxs(s.Fragment,{children:[s.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Saving..."]}):s.jsxs(s.Fragment,{children:[s.jsx(bt,{className:"h-4 w-4 mr-2"})," Save ",n>1?`${n}
2 Transactions`:"Transaction"]})})]})]})]})})()})]})})},Ms=({open:e,onClose:t,accountId:n,onComplete:r})=>{const{toast:i}=_(),[c,l]=a.useState([]),[d,u]=a.useState(!0),[x,p]=a.useState("all"),[g,f]=a.useState(!1),[S,D]=a.useState(!1),[A,W]=a.useState(1),H=25;a.useEffect(()=>{e&&G()},[e,n]);const G=async()=>{try{u(!0);const e=await o();if(!e)return;const{data:t,error:s}=await q.from("bank_transactions").select("id, transaction_date, amount, description, merchant_name, category_type, subcategory, detail_source, location_id, period_flag, account_id, auto_categorized, needs_review, rule_applied_id").eq("company_id",e).eq("account_id",n).order("transaction_date",{ascending:!1});if(s)throw s;const a=[...new Set((t||[]).map(e=>e.account_id))],{data:r}=await q.from("bank_accounts").select("id, account_name, account_type").in("id",a),i=new Map((r||[]).map(e=>{var t,s,a;return[e.id,{name:e.account_name,type:e.account_type,isCreditCard:"credit"===e.account_type||(null==(t=e.account_name)?void 0:t.toLowerCase().includes("credit"))||(null==(s=e.account_name)?void 0:s.toLowerCase().includes(" cc"))||(null==(a=e.account_name)?void 0:a.toLowerCase().endsWith(" cc"))}]})),c=(t||[]).map(e=>{const t=i.get(e.account_id)||{name:"Unknown Account",type:null,isCreditCard:!1};let s;return s=t.isCreditCard?e.amount>=0?"expenses":"balance_sheet":e.amount>=0?"revenue":"expenses",{...e,account_name:t.name,is_credit_card:t.isCreditCard,isSelected:!1,isDirty:!1,editValues:{category_type:e.category_type||s,subcategory:e.subcategory||"",detailSource:e.detail_source||""}}});c.sort((e,t)=>new Date(t.transaction_date).getTime()-new Date(e.transaction_date).getTime()),l(c),u(!1)}catch(e){i({title:"Error",description:"Failed to load transactions",variant:"destructive"}),u(!1)}},Q=(e,t,s)=>{l(a=>a.map(a=>{if(a.id!==e)return a;let n={...a.editValues,[t]:s};"category_type"===t&&(n={...n,subcategory:"",detailSource:""}),"subcategory"===t&&(n={...n,detailSource:""});const r=n.category_type!==(a.category_type||(a.amount>=0?"revenue":"expenses"))||n.subcategory!==(a.subcategory||"")||n.detailSource!==(a.detail_source||"");return{...a,editValues:n,isDirty:r}}))},Z=a.useMemo(()=>{switch(x){case"uncategorized":return c.filter(e=>!e.category_type);case"categorized":return c.filter(e=>e.category_type);default:return c}},[c,x]),te=a.useMemo(()=>{const e=(A-1)*H;return Z.slice(e,e+H)},[Z,A,H]),se=Math.ceil(Z.length/H),ae=a.useMemo(()=>{const e=c.length,t=c.filter(e=>e.category_type).length;return{total:e,categorized:t,uncategorized:e-t}},[c]),ne=c.filter(e=>e.isSelected).length,re=c.filter(e=>e.isDirty).length;return s.jsx(N,{open:e,onOpenChange:t,children:s.jsxs(w,{className:"sm:max-w-[95vw] lg:max-w-6xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(b,{children:[s.jsxs(k,{className:"flex items-center gap-2",children:[s.jsx(Pt,{className:"h-5 w-5"}),"Review Transactions"]}),s.jsx(C,{children:"Review and edit transaction categorizations for this account."})]}),s.jsx("div",{className:"mt-2 space-y-4",children:d?s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"grid grid-cols-4 gap-3",children:[1,2,3,4].map(e=>s.jsx(ce,{className:"h-16"},e))}),Array.from({length:5}).map((e,t)=>s.jsx(ce,{className:"h-12 w-full"},t))]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[s.jsx(B,{className:"border-l-4 border-l-blue-500",children:s.jsxs(Y,{className:"py-3 px-4",children:[s.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Total"}),s.jsx("p",{className:"text-xl font-bold",children:ae.total})]})}),s.jsx(B,{className:"border-l-4 border-l-emerald-500",children:s.jsxs(Y,{className:"py-3 px-4",children:[s.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Categorized"}),s.jsx("p",{className:"text-xl font-bold text-emerald-600",children:ae.categorized})]})}),s.jsx(B,{className:"border-l-4 border-l-amber-500",children:s.jsxs(Y,{className:"py-3 px-4",children:[s.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Uncategorized"}),s.jsx("p",{className:"text-xl font-bold text-amber-600",children:ae.uncategorized})]})}),s.jsx(B,{className:"border-l-4 border-l-purple-500",children:s.jsxs(Y,{className:"py-3 px-4",children:[s.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Completion"}),s.jsxs("p",{className:"text-xl font-bold text-purple-600",children:[ae.total>0?Math.round(ae.categorized/ae.total*100):0,"%"]})]})})]}),ae.uncategorized>0&&s.jsxs(pe,{className:"border-amber-500 bg-amber-50",children:[s.jsx($t,{className:"h-4 w-4 text-amber-600"}),s.jsxs(ge,{className:"text-amber-800",children:[s.jsxs("strong",{children:[ae.uncategorized," uncategorized transaction",1!==ae.uncategorized?"s":"","."]})," ","Use Train AI to categorize them in bulk, or edit them individually here."]})]}),s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 bg-muted/30 px-4 py-3 rounded-lg",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Bt,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs(I,{value:x,onValueChange:e=>{p(e),W(1)},children:[s.jsx(T,{className:"w-[180px] h-8",children:s.jsx(E,{})}),s.jsxs(M,{children:[s.jsxs(z,{value:"all",children:["All (",ae.total,")"]}),s.jsxs(z,{value:"uncategorized",children:["Uncategorized (",ae.uncategorized,")"]}),s.jsxs(z,{value:"categorized",children:["Categorized (",ae.categorized,")"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[re>0&&s.jsxs("span",{className:"text-sm text-amber-600",children:[re," unsaved"]}),ne>0&&s.jsxs(h,{size:"sm",onClick:async()=>{const e=c.filter(e=>e.isSelected&&e.editValues.subcategory);if(0===e.length)return void i({title:"No valid selections",description:"Select transactions with subcategory values to save",variant:"destructive"});D(!0);let t=0;try{const a=await o();if(!a)throw new Error("Missing company ID");for(const n of e)try{const e={category_type:n.editValues.category_type,subcategory:n.editValues.subcategory,detail_source:n.editValues.detailSource||null,auto_categorized:!1,needs_review:!1};await q.from("bank_transactions").update(e).eq("id",n.id),"payroll"===n.editValues.subcategory&&await q.from("bank_transactions").update({payroll_assignment_status:"unassigned"}).eq("id",n.id).neq("payroll_assignment_status","assigned");try{await ee({id:n.id,transaction_date:n.transaction_date,amount:n.amount,description:n.description||"",merchant_name:n.merchant_name,category_type:n.editValues.category_type,subcategory:n.editValues.subcategory,detail_source:n.editValues.detailSource||void 0,location_id:n.location_id||void 0},a,n.account_id)}catch{}t++}catch(s){}l(t=>t.map(t=>e.find(e=>
2e.id===t.id)?{...t,category_type:t.editValues.category_type,subcategory:t.editValues.subcategory,detail_source:t.editValues.detailSource||null,isSelected:!1,isDirty:!1}:t)),i({title:"Batch Save Complete",description:`Updated ${t} transactions`}),f(!1)}catch(s){i({title:"Error",description:s.message||"Batch save failed",variant:"destructive"})}finally{D(!1)}},disabled:S,children:[S?s.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):s.jsx(Wt,{className:"h-4 w-4 mr-2"}),"Save Selected (",ne,")"]})]})]}),0===c.length&&s.jsxs("div",{className:"text-center py-12",children:[s.jsx(bt,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground/50"}),s.jsx("h4",{className:"text-lg font-medium mb-2",children:"No Transactions"}),s.jsx("p",{className:"text-muted-foreground",children:"No transactions found for this account."})]}),Z.length>0&&s.jsx("div",{className:"w-full overflow-x-auto border rounded-lg",children:s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{className:"bg-muted/50",children:[s.jsx(O,{className:"w-10 px-3",children:s.jsx(fe,{checked:g,onCheckedChange:e=>{f(e);const t=new Set(te.map(e=>e.id));l(s=>s.map(s=>t.has(s.id)?{...s,isSelected:e}:s))}})}),s.jsx(O,{className:"w-20 px-2",children:"Date"}),s.jsx(O,{className:"w-[180px] px-2",children:"Description"}),s.jsx(O,{className:"w-24 px-2 text-right",children:"Amount"}),s.jsx(O,{className:"w-32 px-2",children:"Category"}),s.jsx(O,{className:"min-w-[160px] px-2",children:"Subcategory"}),s.jsx(O,{className:"min-w-[160px] px-2",children:"Detail"}),s.jsx(O,{className:"w-24 px-2",children:"Confidence"}),s.jsx(O,{className:"w-14 px-2"})]})}),s.jsx(U,{children:te.map(e=>{var t,a;return s.jsxs(R,{className:m("group",e.isSelected&&"bg-primary/5",e.isDirty&&"bg-amber-50",!e.category_type&&!e.isDirty&&"bg-slate-50/50",e.isSaving&&"opacity-50"),children:[s.jsx($,{className:"px-3",children:s.jsx(fe,{checked:e.isSelected,onCheckedChange:()=>{return t=e.id,void l(e=>e.map(e=>e.id===t?{...e,isSelected:!e.isSelected}:e));var t}})}),s.jsx($,{className:"px-2 text-xs text-muted-foreground whitespace-nowrap",children:new Date(e.transaction_date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsx($,{className:"px-2",children:s.jsx(V,{children:s.jsxs(K,{children:[s.jsxs(j,{children:[s.jsx(y,{asChild:!0,children:s.jsx(X,{asChild:!0,children:s.jsxs("button",{className:"flex items-center gap-1 text-left text-xs hover:text-primary transition-colors w-full",children:[s.jsxs("span",{className:"truncate max-w-[140px]",children:[null==(t=e.description)?void 0:t.substring(0,25),e.description&&e.description.length>25?"...":""]}),s.jsx(Ot,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})})}),s.jsx(v,{side:"bottom",align:"start",className:"w-[400px] p-3",children:s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[s.jsx(vt,{className:"h-3 w-3"})," Full Description"]}),s.jsx("p",{className:"text-sm font-mono bg-muted p-2 rounded break-all",children:e.description})]})})]}),s.jsx(J,{side:"top",className:"max-w-[350px]",children:s.jsx("p",{className:"text-xs break-all",children:e.description})})]})})}),s.jsx($,{className:"px-2 text-right font-mono text-sm",children:s.jsxs("span",{className:e.is_credit_card?e.amount>=0?"text-red-600":"text-emerald-600":e.amount>=0?"text-emerald-600":"text-red-600",children:[e.amount>=0?"+":"","$",Math.abs(e.amount).toFixed(2)]})}),s.jsx($,{className:"px-2",children:s.jsxs(I,{value:e.editValues.category_type,onValueChange:t=>Q(e.id,"category_type",t),children:[s.jsx(T,{className:"h-8 text-xs w-full",children:s.jsx(E,{})}),s.jsxs(M,{children:[s.jsx(z,{value:"revenue",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(At,{className:"h-3 w-3 text-emerald-600"})," Revenue"]})}),s.jsx(z,{value:"expenses",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(zt,{className:"h-3 w-3 text-red-600"})," Expenses"]})}),s.jsx(z,{value:"balance_sheet",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Et,{className:"h-3 w-3 text-blue-600"})," Balance Sheet"]})})]})]})}),s.jsx($,{className:"px-2",children:s.jsx(je,{categoryType:e.editValues.category_type,value:e.editValues.subcategory,onValueChange:t=>Q(e.id,"subcategory",t),placeholder:"Select...",size:"sm"})}),s.jsx($,{className:"px-2",children:s.jsx(ye,{subcategory:e.editValues.subcategory,value:e.editValues.detailSource,onValueChange:t=>Q(e.id,"detailSource",t),placeholder:"Select...",size:"sm"})}),s.jsx($,{className:"px-2",children:(a=e.classification_confidence,a?a>=.85?s.jsxs(F,{className:"bg-emerald-500 text-xs whitespace-nowrap",children:["High ",Math.round(100*a),"%"]}):a>=.7?s.jsxs(F,{className:"bg-amber-500 text-xs whitespace-nowrap",children:["Med ",Math.round(100*a),"%"]}):s.jsxs(F,{variant:"outline",className:"text-xs whitespace-nowrap",children:["Low ",Math.round(100*a),"%"]}):s.jsx(F,{variant:"outline",className:"text-xs whitespace-nowrap",children:"Manual"}))}),s.jsx($,{className:"px-2",children:(e.isDirty||!e.category_type)&&e.editValues.subcategory&&s.jsx(h,{size:"sm",variant:e.isDirty?"default":"outline",onClick:()=>(async e=>{if(e.editValues.subcategory){l(t=>t.map(t=>
2t.id===e.id?{...t,isSaving:!0}:t));try{const t=await o();if(!t)throw new Error("Missing company ID");await q.from("bank_transactions").update({category_type:e.editValues.category_type,subcategory:e.editValues.subcategory,detail_source:e.editValues.detailSource||null,auto_categorized:!1,needs_review:!1}).eq("id",e.id);try{await ee({id:e.id,transaction_date:e.transaction_date,amount:e.amount,description:e.description||"",merchant_name:e.merchant_name,category_type:e.editValues.category_type,subcategory:e.editValues.subcategory,detail_source:e.editValues.detailSource||void 0,location_id:e.location_id||void 0},t,e.account_id)}catch{}l(t=>t.map(t=>t.id===e.id?{...t,category_type:e.editValues.category_type,subcategory:e.editValues.subcategory,detail_source:e.editValues.detailSource||null,isSaving:!1,isDirty:!1}:t)),i({title:"Saved",description:"Transaction updated"})}catch(t){i({title:"Error",description:t.message||"Failed to save",variant:"destructive"}),l(t=>t.map(t=>t.id===e.id?{...t,isSaving:!1}:t))}}else i({title:"Error",description:"Subcategory is required",variant:"destructive"})})(e),disabled:e.isSaving||!e.editValues.subcategory,className:"h-7 w-7 p-0",children:e.isSaving?s.jsx(Ct,{className:"h-3 w-3 animate-spin"}):s.jsx(Ht,{className:"h-3 w-3"})})})]},e.id)})})]})}),se>1&&s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",(A-1)*H+1," - ",Math.min(A*H,Z.length)," of ",Z.length]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(h,{variant:"outline",size:"sm",onClick:()=>W(e=>Math.max(1,e-1)),disabled:1===A,children:"Previous"}),s.jsxs("span",{className:"text-sm px-2",children:[A," / ",se]}),s.jsx(h,{variant:"outline",size:"sm",onClick:()=>W(e=>Math.min(se,e+1)),disabled:A===se,children:"Next"})]})]}),s.jsx("div",{className:"flex justify-end pt-2 border-t",children:s.jsx(h,{onClick:()=>{null==r||r(),t()},children:"Done"})})]})})]})})},zs=({embedded:e=!1})=>{var t,n,r,i,c,l;const d=Je(),{data:m=[],isLoading:f,error:j}=xs();a.useEffect(()=>{j&&ve.error("Failed to fetch bank accounts")},[j]);const[y,v]=a.useState(!1),[_,V]=a.useState(null),[G,K]=a.useState(""),[X,J]=a.useState(null),[Q,ee]=a.useState(!1),[te,se]=a.useState(!1),[ae,ne]=a.useState(!1),[re,ie]=a.useState(null),[ue,he]=a.useState(null),[pe,ge]=a.useState(null),[fe,je]=a.useState([]),[ye,_e]=a.useState(!1),[Ne,we]=a.useState(!1),[be,ke]=a.useState(!1),[Ce,Se]=a.useState({account_name:"",bank_name:"",account_type:"checking",is_active:!0,connection_status:"manual_upload"});a.useEffect(()=>{Ie()},[]);const De=()=>{d.invalidateQueries({queryKey:["bank-accounts"]})},Ie=async()=>{try{const e=await o();e&&K(e)}catch(e){}},Te=async e=>{var t,s;try{(()=>{if(window.TellerConnect)return;if(document.querySelector('script[src*="teller.io/connect/connect.js"]'))return;const e=document.createElement("script");e.src="https://cdn.teller.io/connect/connect.js",e.async=!0,e.id="teller-connect-script",e.onload=()=>{},document.head.appendChild(e)})();const{data:{session:a}}=await q.auth.getSession();if(!a)throw new Error("Not authenticated");const n=await q.functions.invoke("teller-connect-config",{body:{}});if(n.error){if(null==(t=n.error.message)?void 0:t.includes("not configured"))throw new Error("Teller integration not configured. Please contact support.");throw n.error}if(!(null==(s=n.data)?void 0:s.applicationId))throw new Error("Failed to get Teller Connect configuration");he({applicationId:n.data.applicationId,products:n.data.products||["verify"]}),ie(e),ne(!0)}catch(a){ve.error(a.message||"Failed to initialize Teller connection")}},Ee=async()=>{ne(!1),he(null),ie(null),De()},Me=()=>{ne(!1),he(null),ie(null)},ze=async e=>{if(pe)try{const t=m.find(e=>e.id===pe);if(!t||!t.teller_access_token)throw new Error("Account connection data not found");const{data:{session:s}}=await q.auth.getSession();if(!s)throw new Error("Not authenticated");const a=fe.find(t=>t.id===e),n=await q.functions.invoke("teller-save-enrollment",{body:{accessToken:t.teller_access_token,enrollment:{id:t.teller_enrollment_id,institution:{name:t.bank_name}},account_id:pe,selected_teller_account_id:e,selected_teller_account_name:null==a?void 0:a.name}});if(n.error)throw n.error;ve.success("Bank account linked successfully"),_e(!1),ge(null),je([]),De()}catch(t){ve.error(t.message||"Failed to link account")}},Ae=e=>{e?(V(e),Se({account_name:e.account_name,bank_name:e.bank_name||"",account_type:e.account_type,is_active:e.is_active})):(V(null),Se({account_name:"",bank_name:"",account_type:"checking",is_active:!0})),v(!0)},qe=()=>{v(!1),V(null),Se({account_name:"",bank_name:"",account_type:"checking",is_active:!0})},Fe=s.jsxs(B,{children:[s.jsx(W,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(H,{children:"Bank Accounts"}),s.jsxs(N,{open:y,onOpenChange:v,children:[s.jsx(Z,{asChild:!0,children:s.jsxs(h,{onClick:()=>Ae(),children:[s.jsx(pt,{className:"mr-2 h-4 w-4"}),"Add Bank Account"]})}),s.jsxs(w,{children:[s.jsxs(b,{children:[s.jsx(k,{children:_?"Edit Bank Account":"Add New Bank Account"}
2),s.jsx(C,{children:_?"Update the bank account information below.":"Fill in the details for the new bank account."})]}),s.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),_){const{error:e}=await q.from("bank_accounts").update(Ce).eq("id",_.id);e?ve.error("Failed to update bank account"):(ve.success("Bank account updated successfully"),De(),qe())}else{const{error:e}=await q.from("bank_accounts").insert([{...Ce,company_id:G,connection_status:Ce.connection_status||"manual_upload"}]);e?ve.error("Failed to create bank account"):(ve.success("Bank account created successfully"),De(),qe())}},children:[s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"account_name",children:"Account Name *"}),s.jsx(D,{id:"account_name",placeholder:"e.g., Main Checking",value:Ce.account_name,onChange:e=>Se({...Ce,account_name:e.target.value}),required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"bank_name",children:"Bank Name"}),s.jsx(D,{id:"bank_name",placeholder:"e.g., Chase Bank",value:Ce.bank_name,onChange:e=>Se({...Ce,bank_name:e.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"account_type",children:"Account Type *"}),s.jsxs(I,{value:Ce.account_type,onValueChange:e=>Se({...Ce,account_type:e}),children:[s.jsx(T,{children:s.jsx(E,{})}),s.jsxs(M,{children:[s.jsx(z,{value:"checking",children:"Checking"}),s.jsx(z,{value:"savings",children:"Savings"}),s.jsx(z,{value:"credit_card",children:"Credit Card"}),s.jsx(z,{value:"other",children:"Other"})]})]})]}),!_&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"connection_status",children:"Connection Method"}),s.jsxs(I,{value:Ce.connection_status,onValueChange:e=>Se({...Ce,connection_status:e}),children:[s.jsx(T,{children:s.jsx(E,{})}),s.jsxs(M,{children:[s.jsx(z,{value:"manual_upload",children:"Manual Upload"}),s.jsx(z,{value:"not_connected",children:"Connect via Teller Later"})]})]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"You can connect via Teller after creating the account"})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx("input",{type:"checkbox",id:"is_active",checked:Ce.is_active,onChange:e=>Se({...Ce,is_active:e.target.checked}),className:"h-4 w-4"}),s.jsx(S,{htmlFor:"is_active",children:"Active Account"})]})]}),s.jsxs(A,{children:[s.jsx(h,{type:"button",variant:"outline",onClick:qe,children:"Cancel"}),s.jsx(h,{type:"submit",children:_?"Update":"Create"})]})]})]})]})]})}),s.jsx(Y,{children:f?s.jsx("div",{className:"space-y-3 py-8",children:Array.from({length:3}).map((e,t)=>s.jsx(ce,{className:"h-20 w-full"},t))}):0===m.length?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Dt,{className:"mx-auto h-12 w-12 mb-2 opacity-50"}),s.jsx("p",{children:"No bank accounts found."}),s.jsx("p",{className:"text-sm mt-1",children:"Add your first bank account to get started."})]}):s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[s.jsx(O,{children:"Account Name"}),s.jsx(O,{children:"Bank Name"}),s.jsx(O,{children:"Account Type"}),s.jsx(O,{children:"Connection"}),s.jsx(O,{children:"Sync Status"}),s.jsx(O,{children:"Training"}),s.jsx(O,{className:"text-right",children:"Actions"})]})}),s.jsx(U,{children:m.map(e=>s.jsxs(R,{children:[s.jsx($,{className:"font-medium",children:e.account_name}),s.jsx($,{children:e.bank_name||"—"}),s.jsx($,{className:"capitalize",children:e.account_type.replace("_"," ")}),s.jsx($,{children:s.jsx(vs,{status:e.connection_status})}),s.jsx($,{children:s.jsxs("div",{className:"flex flex-col gap-1",children:[e.sync_enabled?s.jsx(F,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200 dark:bg-green-950 dark:text-green-400 w-fit",children:"Sync Enabled"}):s.jsx(F,{variant:"outline",className:"w-fit",children:"Sync Disabled"}),e.last_synced_at&&s.jsx("span",{className:"text-xs text-muted-foreground",children:et(new Date(e.last_synced_at),"MMM dd, yyyy")})]})}),s.jsx($,{children:s.jsx(_s,{status:e.training_status})}),s.jsx($,{className:"text-right",children:s.jsx("div",{className:"flex justify-end gap-1",children:s.jsxs(u,{children:[s.jsx(x,{asChild:!0,children:s.jsx(h,{variant:"ghost",size:"sm",children:s.jsx(Gt,{className:"h-4 w-4"})})}),s.jsxs(p,{align:"end",className:"w-56",children:[s.jsxs(g,{onClick:()=>{J(e.id),ee(!0)},children:[s.jsx(Pt,{className:"h-4 w-4 mr-2"}),"View Details"]}
2),"connected"!==e.connection_status&&s.jsxs(g,{onClick:()=>Te(e.id),children:[s.jsx(Yt,{className:"h-4 w-4 mr-2"}),"Connect via Teller"]}),"pending_selection"===e.connection_status&&s.jsxs(g,{onClick:()=>(async e=>{var t,s,a;const n=m.find(t=>t.id===e);if(n&&n.teller_access_token)try{const{data:{session:r}}=await q.auth.getSession();if(!r)throw new Error("Not authenticated");const i=await q.functions.invoke("teller-save-enrollment",{body:{accessToken:n.teller_access_token,enrollment:{id:n.teller_enrollment_id,institution:{name:n.bank_name}},account_id:e}});if(i.error)throw i.error;(null==(t=i.data)?void 0:t.requires_selection)&&(null==(s=i.data)?void 0:s.accounts)?(je(i.data.accounts),ge(e),_e(!0)):(null==(a=i.data)?void 0:a.success)&&(ve.success("Bank account linked successfully"),De())}catch(r){ve.error(r.message||"Failed to fetch accounts")}else ve.error("Account connection data not found. Please reconnect.")})(e.id),children:[s.jsx(_t,{className:"h-4 w-4 mr-2"}),"Select Account"]}),s.jsxs(g,{onClick:()=>{J(e.id),se(!0)},children:[s.jsx(yt,{className:"h-4 w-4 mr-2"}),"Import Data"]}),s.jsxs(g,{onClick:()=>{J(e.id),we(!0)},children:[s.jsx(Mt,{className:"h-4 w-4 mr-2"}),"Train AI"]}),s.jsxs(g,{onClick:()=>{J(e.id),ke(!0)},children:[s.jsx(Pt,{className:"h-4 w-4 mr-2"}),"Review Transactions"]}),"connected"===e.connection_status&&e.sync_enabled&&s.jsxs(g,{onClick:async()=>{try{const t=await o();if(!t)throw new Error("Company not found");const{persisted:s}=await ws({accountId:e.id,companyId:t,accountName:e.account_name,startDate:e.last_synced_at?new Date(e.last_synced_at).toISOString().split("T")[0]:new Date(Date.now()-7776e6).toISOString().split("T")[0],endDate:(new Date).toISOString().split("T")[0]});ve.success(`Synced ${s} transactions`),De(),xe(t).catch(console.error)}catch(t){ve.error(t.message||"Failed to sync")}},children:[s.jsx(St,{className:"h-4 w-4 mr-2"}),"Sync Now"]}),s.jsxs(g,{onClick:()=>Ae(e),children:[s.jsx(Nt,{className:"h-4 w-4 mr-2"}),"Edit"]}),s.jsxs(g,{onClick:()=>(async e=>{if(!confirm("Are you sure you want to delete this bank account?"))return;const{error:t}=await q.from("bank_accounts").delete().eq("id",e);t?ve.error("Failed to delete bank account"):(ve.success("Bank account deleted successfully"),De())})(e.id),className:"text-destructive",children:[s.jsx(jt,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})})]},e.id))})]})})]});return e?s.jsxs("div",{className:"space-y-6",children:[Fe,X&&s.jsxs(s.Fragment,{children:[s.jsx(ks,{open:Q,onClose:()=>{ee(!1),J(null)},accountId:X,onUpdate:De}),s.jsx(Cs,{open:te,onClose:()=>{se(!1),J(null)},accountId:X,accountName:(null==(t=m.find(e=>e.id===X))?void 0:t.account_name)||"",connectionStatus:(null==(n=m.find(e=>e.id===X))?void 0:n.connection_status)||null,tellerAccessToken:(null==(r=m.find(e=>e.id===X))?void 0:r.teller_access_token)||void 0,onSuccess:De})]}),ue&&re&&ae&&s.jsx(Ds,{config:ue,accountId:re,onSuccess:Ee,onExit:Me}),s.jsx(Ss,{open:ye,accounts:fe,saving:!1,onSelect:ze,onClose:()=>{_e(!1),ge(null),je([])}}),X&&s.jsxs(s.Fragment,{children:[s.jsx(Es,{open:Ne,onClose:()=>{we(!1),J(null)},accountId:X,onComplete:De}),s.jsx(Ms,{open:be,onClose:()=>{ke(!1),J(null)},accountId:X,onComplete:De})]})]}):s.jsxs("div",{className:"space-y-6",children:[s.jsx("div",{className:"flex items-center justify-between",children:s.jsxs("div",{children:[s.jsxs("h1",{className:"text-3xl font-bold flex items-center gap-2",children:[s.jsx(Kt,{className:"h-8 w-8"}),"Bank Management"]}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage your bank accounts and statements"})]})}),s.jsxs(le,{defaultValue:"accounts",className:"w-full",children:[s.jsxs(oe,{className:"grid w-full max-w-md grid-cols-2",children:[s.jsxs(de,{value:"accounts",className:"flex items-center gap-2",children:[s.jsx(Dt,{className:"h-4 w-4"}),"Bank Accounts"]}),s.jsxs(de,{value:"statements",className:"flex items-center gap-2",children:[s.jsx(vt,{className:"h-4 w-4"}),"Bank Statements"]})]}),s.jsx(me,{value:"accounts",className:"mt-6",children:Fe}),s.jsx(me,{value:"statements",className:"mt-6",children:s.jsx(ys,{})})]}
2),X&&s.jsxs(s.Fragment,{children:[s.jsx(ks,{open:Q,onClose:()=>{ee(!1),J(null)},accountId:X,onUpdate:De}),s.jsx(Cs,{open:te,onClose:()=>{se(!1),J(null)},accountId:X,accountName:(null==(i=m.find(e=>e.id===X))?void 0:i.account_name)||"",connectionStatus:(null==(c=m.find(e=>e.id===X))?void 0:c.connection_status)||null,tellerAccessToken:(null==(l=m.find(e=>e.id===X))?void 0:l.teller_access_token)||void 0,onSuccess:De})]}),ue&&re&&ae&&s.jsx(Ds,{config:ue,accountId:re,onSuccess:Ee,onExit:Me}),s.jsx(Ss,{open:ye,accounts:fe,saving:!1,onSelect:ze,onClose:()=>{_e(!1),ge(null),je([])}}),X&&s.jsxs(s.Fragment,{children:[s.jsx(Es,{open:Ne,onClose:()=>{we(!1),J(null)},accountId:X,onComplete:De}),s.jsx(Ms,{open:be,onClose:()=>{ke(!1),J(null)},accountId:X,onComplete:De})]})]})};function As(e){return new Date(e+"T12:00:00Z").getUTCDay()}function qs(e){var t;const s=null==(t=e.split(".").pop())?void 0:t.toLowerCase();return"xlsx"===s||"xls"===s?"excel":"csv"}function Fs({compact:e,embed:t}){var n;const[r,i]=a.useState(null),[c,l]=a.useState(!1),[d,m]=a.useState(!1),u=a.useRef(null),{toast:x}=_(),p=(null==(n=null==r?void 0:r.dates)?void 0:n.length)?1===r.dates.length?et(new Date(r.dates[0]),"MMM d, yyyy"):`${et(new Date(r.dates[0]),"MMM d")} – ${et(new Date(r.dates[r.dates.length-1]),"MMM d, yyyy")}`:"",g=s.jsx("div",{className:"space-y-4 "+(e||t?"flex-1 flex flex-col pt-0":""),children:r?s.jsxs("div",{className:"rounded-lg border bg-muted/30 space-y-3 "+(e?"p-3":"p-4 space-y-4"),children:[s.jsx("div",{className:"flex items-start justify-between gap-2",children:s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"h-8 w-8 shrink-0 rounded-lg bg-primary/10 flex items-center justify-center",children:s.jsx(vt,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-medium truncate "+(e?"text-sm":""),children:r.file.name}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[s.jsx(F,{variant:"secondary",className:e?"text-xs":void 0,children:r.platform}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:[r.recordCount," record",1!==r.recordCount?"s":""]}),p&&!e&&s.jsxs("span",{className:"text-sm text-muted-foreground",children:["• ",p]})]})]})]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>{i(null)},disabled:d,children:[s.jsx(Xt,{className:"h-4 w-4 mr-1"}),"Cancel"]}),s.jsxs(h,{size:"sm",onClick:async()=>{var e,t,s,a,n;if(!r)return;const c=await o();if(c){m(!0);try{const l=r.file;if("payouts"===r.kind){const a=await we(l),{data:n,error:i}=await q.from("file_uploads").insert({filename:l.name,file_type:qs(l.name),file_size:l.size,processing_status:"completed",company_id:c,records_imported:a.length}).select("id").single();if(i||!(null==n?void 0:n.id))throw i??new Error("Failed to create file upload record");const o=a.map(e=>({...Ce(e),company_id:c})),d=o.map(e=>e.order_date||e.sale_date).filter(Boolean),m=d.sort()[0],u=d.sort().pop(),h=(null==(e=o[0])?void 0:e.platform)||"Unknown";let p=!1;if(m&&u){const{count:e}=await q.from("sales_transactions").select("id",{count:"exact",head:!0}).eq("company_id",c).eq("platform",h).gte("order_date",m).lte("order_date",u);e&&e>0&&(p=!0)}if(!p){const{error:e}=await q.from("sales_transactions").upsert(o,{onConflict:"company_id,platform,order_date,order_time,shop_id",ignoreDuplicates:!1});if(e)throw e}Se(c,o).catch(e=>{});const g=new Map;a.forEach(e=>{const t=null!=e.payout_date?"string"==typeof e.payout_date?e.payout_date:new Date(e.payout_date).toISOString().split("T")[0]:null;if(!t)return;const s=`${t}-${e.platform}`;g.has(s)||g.set(s,{date:t,platform:e.platform,total_gross_sales:0,total_net_sales:0,total_sales_tax:0,total_tips:0,total_tickets:0});const a=g.get(s),n=e.net_deposit_amount??e.net_payout_amount??0;a.total_gross_sales+=n,a.total_net_sales+=n,a.total_tickets+=e.total_number_of_payments??1});const f=Array.from(g.values());if(f.length>0){const e=f.map(e=>({...e,company_id:c,day_of_week:String(As(e.date)),file_upload_id:n.id})),{error:a}=await q.from("daily_sales_summary").insert(e);if(a&&!(null==(t=a.message)?void 0:t.includes("duplicate key"))&&!(null==(s=a.message)?void 0:s.includes("unique constraint")))throw a}x({title:"Import complete",description:`Imported ${a.length} payout records from ${r.platform}`})}else{const e=await be(c),t=await ke(l,e),{data:s,error:i}=await q.from("file_uploads").insert({filename:l.name,file_type:qs(l.name),file_size:l.size,processing_status:"completed",company_id:c,records_imported:t.length}).select("id").single();if(i||!(null==s?void 0:s.id))throw i??new Error("Failed to create file upload record");const o=t.map(e=>{const{payout_time:t,...s}=e;return{...s,company_id:c}}),d=new Map;for(const a of o){const e=`${a.company_id}|${a.platform}|${a.order_date??a.sale_date}|${a.order_time??a.sale_time??""}|${a.shop_id??""}`,t=d.get(e);if(t){const e=["gross_sales","subtotal_before_discounts","tip_amount","commission","marketing_fees","net_payout_amount","transaction_fees","net_deposit_amount","merchant_promotions","price_adjustments","uber_promotion_credit","uber_commission","miscellaneous_deductions","total_payout_amount","total_payments_amount","taxable_subtotal","promotions_on_delivery"];for(const s of e)null!=a[s]&&(t[s]=(Number(t[s])||0)+(Number(a[s])||0))}else d.set(e,{...a}
2)}const m=Array.from(d.values());for(let a=0;a<m.length;a+=500){const e=m.slice(a,a+500),{error:t}=await q.from("sales_transactions").upsert(e,{onConflict:"company_id,platform,order_date,order_time,shop_id",ignoreDuplicates:!1});if(t)throw t}Se(c,m).catch(e=>{});const u=(await De(l)).map(e=>({...e,company_id:c,day_of_week:String(As(e.date)),file_upload_id:s.id})),{error:h}=await q.from("daily_sales_summary").insert(u);if(h&&!(null==(a=h.message)?void 0:a.includes("duplicate key"))&&!(null==(n=h.message)?void 0:n.includes("unique constraint")))throw h;x({title:"Import complete",description:`Imported ${t.length} detailed transactions from ${r.platform}`})}xe(c).catch(e=>{}),i(null)}catch(l){let e="Failed to import. Please try again.";l instanceof Error?e=l.message:l&&"object"==typeof l&&"message"in l&&(e=String(l.message)),(e.includes("duplicate key")||e.includes("unique constraint"))&&(e="Some records already exist. Try uploading a file with new data, or the data may already be imported."),x({title:"Import failed",description:e,variant:"destructive"})}finally{m(!1)}}else x({title:"Error",description:"Company not found.",variant:"destructive"})},disabled:d,children:[d?s.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):s.jsx(Jt,{className:"h-4 w-4 mr-1"}),d?"Importing…":"Import"]})]})]}):s.jsxs("div",{className:"border-2 border-dashed rounded-lg text-center hover:border-primary/50 transition-colors cursor-pointer flex flex-col items-center justify-center "+(e?"min-h-[120px] p-4":"p-8"),onClick:()=>{var e;return null==(e=u.current)?void 0:e.click()},children:[s.jsx("input",{ref:u,type:"file",accept:".csv,.xlsx,.xls",className:"hidden",onChange:async e=>{var t,s,a;const n=null==(t=e.target.files)?void 0:t[0];if(n){l(!0),i(null);try{const e=await async function(e){var t;const s=null==(t=e.name.split(".").pop())?void 0:t.toLowerCase();if("csv"===s){const t=await e.text(),s=(await Ie(async()=>{const{default:e}=await import("./onboarding-CryYNyDg.js").then(e=>e.p);return{default:e}},__vite__mapDeps([0,1,2,3,4,5]))).default;return s.parse(t,{header:!1}).data.slice(0,2)}if("xlsx"===s||"xls"===s){const t=await Ie(()=>import("./onboarding-CryYNyDg.js").then(e=>e.c2),__vite__mapDeps([0,1,2,3,4,5])),s=await e.arrayBuffer(),a=t.read(s),n=a.Sheets[a.SheetNames[0]];return t.utils.sheet_to_json(n,{header:1}).slice(0,2)}return[]}(n),t=e[0]||[],r=e[1],c=_e(t,r),l=c?null:Ne(t,r);if(c){const e=await we(n);if(0===e.length)return void x({title:"No data found",description:"The payouts file appears to be empty or in an unexpected format.",variant:"destructive"});const t=[...new Set(e.map(e=>null!=e.payout_date?"string"==typeof e.payout_date?e.payout_date:new Date(e.payout_date).toISOString().split("T")[0]:null).filter(Boolean))].sort();i({kind:"payouts",file:n,recordCount:e.length,platform:(null==(s=e[0])?void 0:s.platform)||"Unknown",dates:t})}else if(l){const e=await o(),t=e?await be(e):void 0,s=await ke(n,t);if(0===s.length)return void x({title:"No data found",description:"The file appears to be empty or in an unexpected format.",variant:"destructive"});const r=[...new Set(s.map(e=>e.payout_date||e.sale_date||e.order_date).filter(Boolean))].sort();i({kind:"payments",file:n,recordCount:s.length,platform:(null==(a=s[0])?void 0:a.platform)||"Unknown",dates:r})}else{const e=t.slice(0,6).map(e=>String(e??"").substring(0,25)).join(", ");x({title:"Unrecognized file",description:`Could not detect Payments or Payouts format. Use Toast, DoorDash, or Uber Eats files. Headers: ${e}...`,variant:"destructive"})}}catch(r){x({title:"Parse failed",description:r instanceof Error?r.message:"Failed to parse file.",variant:"destructive"})}finally{l(!1),u.current&&(u.current.value="")}}}}),c?s.jsxs(s.Fragment,{children:[s.jsx(Ct,{className:"mx-auto text-muted-foreground animate-spin "+(e?"h-8 w-8":"h-10 w-10")}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Reading…"})]}):s.jsxs(s.Fragment,{children:[s.jsx(yt,{className:"mx-auto text-muted-foreground "+(e?"h-8 w-8":"h-10 w-10")}),s.jsx("p",{className:"font-medium mt-2 "+(e?"text-xs":"text-sm"),children:"Choose file"}),!e&&s.jsx("p",{className:"text-xs text-muted-foreground",children:"Any payments or payouts report — auto-detected"})]})]})});return t?s.jsx("div",{className:"h-full flex flex-col min-h-[120px]",children:g}):s.jsxs(B,{className:e?"h-full flex flex-col border bg-card/50 shadow-sm":void 0,children:[s.jsxs(W,{className:e?"pb-2":void 0,children:[s.jsxs(H,{
2className:"flex items-center gap-2 "+(e?"text-base":""),children:[s.jsx("div",{className:e?"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center":void 0,children:s.jsx(Qt,{className:e?"h-4 w-4 text-primary":"h-5 w-5 text-primary"})}),"Sales & Deposits"]}),!e&&s.jsx(G,{children:"Upload Toast, DoorDash, or Uber Eats payments or payouts files. Preview then import."}),e&&s.jsx(G,{className:"text-xs",children:"CSV or Excel — payments or payouts"})]}),s.jsx(Y,{className:e?"flex-1 flex flex-col pt-0":"",children:g})]})}function Ps({compact:t,embed:n}){const[r,i]=a.useState(null),[c,l]=a.useState(!1),[d,m]=a.useState(!1),[u,x]=a.useState(!1),[p,g]=a.useState(null),[f,j]=a.useState(""),[y,v]=a.useState(()=>(new Date).toISOString().split("T")[0]),I=a.useRef(null),{toast:T}=_(),E=async(e,t,s)=>{const a=await Ae(e,s);if(0===a.length)return null;const n=a.slice(0,5).map(e=>({item_name:e.item_name,quantity_sold:e.quantity_sold,revenue:e.revenue||0}));return{file:e,platform:t,dateOverride:s,recordCount:a.length,sampleItems:n}},M=async()=>{if(p&&f){x(!1),l(!0);try{const e=await E(p,f,y);e&&i(e)}catch(e){T({title:"Parse failed",description:e instanceof Error?e.message:"Failed to parse file.",variant:"destructive"})}finally{l(!1),g(null),j("")}}},z=s.jsx("div",{className:"space-y-4 "+(t||n?"flex-1 flex flex-col pt-0":""),children:r?s.jsxs("div",{className:"rounded-lg border bg-muted/30 space-y-3 "+(t?"p-3":"p-4 space-y-4"),children:[s.jsx("div",{className:"flex items-start justify-between gap-2",children:s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"h-8 w-8 shrink-0 rounded-lg bg-primary/10 flex items-center justify-center",children:s.jsx(vt,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-medium truncate "+(t?"text-sm":""),children:r.file.name}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[s.jsx(F,{variant:"secondary",className:t?"text-xs":void 0,children:`${Te(r.platform)} - Manual`}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:[r.recordCount," item",1!==r.recordCount?"s":""]})]}),!t&&r.sampleItems.length>0&&s.jsx("ul",{className:"text-xs text-muted-foreground mt-2 space-y-0.5",children:r.sampleItems.map((e,t)=>s.jsxs("li",{children:[e.item_name," — qty ",e.quantity_sold,", $",e.revenue.toFixed(2)]},t))})]})]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>{i(null)},disabled:d,children:[s.jsx(Xt,{className:"h-4 w-4 mr-1"}),"Cancel"]}),s.jsxs(h,{size:"sm",onClick:async()=>{if(!r)return;const t=await o();if(t){m(!0);try{const s=await Ae(r.file,r.dateOverride),a=`${Te(r.platform)} - Manual`,{data:n}=await q.from("menu_performance").select("item_name, category").eq("company_id",t).not("category","is",null),c=new Map;null==n||n.forEach(e=>{e.category&&!c.has(e.item_name)&&c.set(e.item_name,e.category)});let l=[];try{l=await qe(t,Me(r.platform))}catch(e){}const o=new Map;l.forEach(e=>{o.set(e.pos_item_name.toLowerCase(),e),o.set(e.pos_item_identifier.toLowerCase(),e)});const d=s.map(e=>{const s=o.get(e.item_name.toLowerCase());return{company_id:t,date:e.date,item_name:e.item_name,quantity_sold:e.quantity_sold,revenue:e.revenue||0,category:e.category||c.get(e.item_name)||null,source:a,mapped_item_id:(null==s?void 0:s.mapped_item_id)||null,mapped_type:(null==s?void 0:s.mapped_type)||null}}),{error:m}=await q.from("menu_performance").insert(d);if(m)throw m;const u=d.filter(e=>e.mapped_item_id).length;T({title:"Import complete",description:`Imported ${s.length} items from ${a}${u>0?` (${u} auto-mapped)`:""}`}),i(null)}catch(s){let e="Failed to import. Please try again.";s instanceof Error?e=s.message:s&&"object"==typeof s&&"message"in s&&(e=String(s.message)),T({title:"Import failed",description:e,variant:"destructive"})}finally{m(!1)}}else T({title:"Error",description:"Company not found.",variant:"destructive"})},disabled:d,children:[d?s.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):s.jsx(Jt,{className:"h-4 w-4 mr-1"}),d?"Importing…":"Import"]})]})]}):s.jsxs("div",{className:"border-2 border-dashed rounded-lg text-center hover:border-primary/50 transition-colors cursor-pointer flex flex-col items-center justify-center "+(t?"min-h-[120px] p-4":"p-8"),onClick:()=>{var e;return null==(e=I.current)?void 0:e.click()},children:[s.jsx("input",{ref:I,type:"file",accept:".csv,.xlsx,.xls",className:"hidden",onChange:async e=>{var t,s;const a=null==(t=e.target.files)?void 0:t[0];if(a){l(!0),i(null);try{const e=await(async e=>{var t;const s=null==(t=e.name.split(".").pop())?void 0:t.toLowerCase();if("csv"===s){const t=await e.text(),s=(await Ie(async()=>{const{default:e}=await import("./onboarding-CryYNyDg.js").then(e=>e.p);return{default:e}},__vite__mapDeps([0,1,2,3,4,5]))).default;return s.parse(t,{header:!1}).data}if("xlsx"===s||"xls"===s){const t=await Ie(()=>import("./onboarding-CryYNyDg.js").then(e=>e.c2),__vite__mapDeps([0,1,2,3,4,5])),s=await e.arrayBuffer(),a=t.read(s),n=a.Sheets[a.SheetNames[0]];return t.utils.sheet_to_json(n,{header:1})}return[]})(a),t=Ee(e[0]||[],null==(s=e[0])?void 0:s[0]);if(!t)return void T({title:"Invalid file",description:"Could not detect platform from file headers. Use Toast, DoorDash, or Uber Eats quantity file.",variant:"destructive"});if(Me(t)===ze.UBER)g(a),j(t),v((new Date).toISOString().split("T")[0]),x(!0);else{const e=await E(a,t);e&&i(e)}}catch(n){T({title:"Parse failed",description:n instanceof Error?n.message:"Failed to parse file.",variant:"destructive"})}finally{l(!1),I.current&&(I.current.value="")}}}}),c?s.jsxs(s.Fragment,{children:[s.jsx(Ct,{className:"mx-auto text-muted-foreground animate-spin "+(t?"h-8 w-8":"h-10 w-10")}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Reading…"})]}):s.jsxs(s.Fragment,{children:[s.jsx(yt,{className:"mx-auto text-muted-foreground "+(t?"h-8 w-8":"h-10 w-10")}
2),s.jsx("p",{className:"font-medium mt-2 "+(t?"text-xs":"text-sm"),children:"Choose file"}),!t&&s.jsx("p",{className:"text-xs text-muted-foreground",children:"Any item qty / product mix report — auto-detected"})]})]})});return n?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"h-full flex flex-col min-h-[120px]",children:z}),s.jsx(N,{open:u,onOpenChange:x,children:s.jsxs(w,{children:[s.jsxs(b,{children:[s.jsx(k,{children:"Select date for Uber Eats data"}),s.jsx(C,{children:"Uber Eats files don't include dates. Choose the date this data represents."})]}),s.jsx("div",{className:"space-y-4 py-4",children:s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"qty-date",children:"Date"}),s.jsx(D,{id:"qty-date",type:"date",value:y,onChange:e=>v(e.target.value)})]})}),s.jsxs(A,{children:[s.jsx(h,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),s.jsx(h,{onClick:M,children:"Preview"})]})]})})]}):s.jsxs(s.Fragment,{children:[s.jsxs(B,{className:t?"h-full flex flex-col border bg-card/50 shadow-sm":void 0,children:[s.jsxs(W,{className:t?"pb-2":void 0,children:[s.jsxs(H,{className:"flex items-center gap-2 "+(t?"text-base":""),children:[s.jsx("div",{className:t?"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center":void 0,children:s.jsx(Zt,{className:t?"h-4 w-4 text-primary":"h-5 w-5 text-primary"})}),"Sales Quantities"]}),!t&&s.jsx(G,{children:"Upload menu item quantity files from Toast, DoorDash, or Uber Eats. Preview then import."}),t&&s.jsx(G,{className:"text-xs",children:"CSV or Excel — product mix / quantities"})]}),s.jsx(Y,{className:t?"flex-1 flex flex-col pt-0":"",children:z})]}),s.jsx(N,{open:u,onOpenChange:x,children:s.jsxs(w,{children:[s.jsxs(b,{children:[s.jsx(k,{children:"Select date for Uber Eats data"}),s.jsx(C,{children:"Uber Eats files don't include dates. Choose the date this data represents."})]}),s.jsx("div",{className:"space-y-4 py-4",children:s.jsxs("div",{className:"space-y-2",children:[s.jsx(S,{htmlFor:"qty-date",children:"Date"}),s.jsx(D,{id:"qty-date",type:"date",value:y,onChange:e=>v(e.target.value)})]})}),s.jsxs(A,{children:[s.jsx(h,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),s.jsx(h,{onClick:M,children:"Preview"})]})]})})]})}function Ls(e,t=""){const s=function(e,t=""){const s=t.toLowerCase().split(".").pop()||"";return e.includes("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")||e.includes("application/vnd.ms-excel")||"xlsx"===s||"xls"===s?"excel":e.includes("text/csv")||"csv"===s?"csv":e.includes("application/pdf")||"pdf"===s?"pdf":e.startsWith("image/")||["jpg","jpeg","png","gif","bmp","webp"].includes(s)?"image":e.includes("text/")||"txt"===s?"text":"other"}(e,t);return["excel","csv","pdf","image","text"].includes(s)}const Rs=["sub-total","subtotal","tax","total","payment","balance"];async function Os(e,t,s){const a=function(e){const t=e.trim(),s=t.match(/^\d+(\.\d+)?\s*[x×]\s*(.+)$/i);return s?s[2].trim():t}((n=s).description||n.name||"").replace(/\s+/g," ").toLowerCase().trim();var n;if(!a||function(e){const t=(e||"").toLowerCase();return Rs.some(e=>t.includes(e))}(a))return{mappingId:null,ingredientId:null,ingredientName:null,mapping:null,source:null};const{data:r,error:i}=await q.from("vendor_ingredient_mappings").select("id, ingredient_id, vendor_product_description, category").eq("company_id",e).eq("vendor_id",t);if(!i&&r&&r.length>0){const e=r.find(e=>(e.vendor_product_description||""||"").replace(/\s+/g," ").toLowerCase().trim()===a);if(e){const t=await Us(e.ingredient_id);return{mappingId:e.id,ingredientId:e.ingredient_id??null,ingredientName:t,mapping:e,source:"exact_description"}}const t=s.description||s.name||"";let n=null;for(const s of r){const e=s.vendor_product_description||"",a=Fe({name:t},{name:e});a>=.85&&(!n||a>n.similarity)&&(n={mapping:s,similarity:a})}if(n){const e=await Us(n.mapping.ingredient_id);return{mappingId:n.mapping.id,ingredientId:n.mapping.ingredient_id??null,ingredientName:e,mapping:n.mapping,source:"exact_description"}}}const c=await Pe(e,t,s,.85);if(!c)return{mappingId:null,ingredientId:null,ingredientName:null,mapping:null,source:null};const{data:l}=await q.from("vendor_ingredient_mappings").select("id, ingredient_id, category").eq("id",c.mappingId).single();if(!l)return{mappingId:null,ingredientId:null,ingredientName:null,mapping:null,source:null};const o=await Us(l.ingredient_id);return{mappingId:l.id,ingredientId:l.ingredient_id??null,ingredientName:o,mapping:l,source:"cluster"}}async function Us(e){if(!e)return null;const{data:t}=await q.from("ingredients").select("name").eq("id",e).maybeSingle();return(null==t?void 0:t.name)??null}async function $s(e,t,s){const a=[];
2for(const n of s){const s=await Os(e,t,n);a.push({lineItem:n,mappingId:s.mappingId,ingredientId:s.ingredientId,ingredientName:s.ingredientName,source:s.source})}return a}const Vs=e=>{if(!e)return"";let t="string"==typeof e?e:JSON.stringify(e,null,2);return t=t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),t.replace(/("(\\u[\da-fA-F]{4}|\\[^u]|[^\\"])*"(?:\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,e=>{let t="text-slate-100";return t=/^"/.test(e)?/:$/.test(e)?"text-sky-400":"text-emerald-300":/true|false/.test(e)?"text-purple-300":/null/.test(e)?"text-slate-400 italic":"text-orange-300",`<span class="${t}">${e}</span>`})},Bs=({open:t,onOpenChange:r,extractedData:i,fileName:c,previewUrl:l,fileType:d,taggunRaw:u,category:x,onConfirm:p,onCancel:g,duplicateWarnings:f=[],vendorSuggestions:C=[],initialVendorId:V,initialEnrichedLineItems:B,onEnrichedLineItems:W})=>{var H;const[G,Y]=a.useState(i),[K,X]=a.useState(x),[J,Q]=a.useState(V),[Z,ee]=a.useState([]),[te,se]=a.useState(""),[ae,ne]=a.useState(!1),[re,ie]=a.useState(null),[ce,le]=a.useState(!1),[oe,de]=a.useState(""),[me,ue]=a.useState(""),[xe,he]=a.useState(""),[pe,ge]=a.useState(""),[fe,je]=a.useState(!1),[ye,ve]=a.useState(!1),[_e,Ne]=a.useState(!1),[we,be]=a.useState([]),[ke,Ce]=a.useState(null),{toast:Se}=_();a.useEffect(()=>{if(!t)return;let e=!1;return(async()=>{try{const t=await o();if(!t||e)return;const{data:s,error:a}=await q.from("ingredients").select("id, name, standard_unit").eq("company_id",t).order("name");a||!s||e||be(s.map(e=>({id:e.id,name:e.name,standard_unit:e.standard_unit})))}catch{}})(),()=>{e=!0}},[t]);const De=async(e,t)=>{if(!G)return;const s=G.line_items[e];if(ie(s=>{if(!s)return s;const a=[...s];return a[e]={...a[e],ingredientId:t.id,ingredientName:t.name,source:"exact_description"},a}),J)try{const e=await o();if(!e)return;await q.from("vendor_ingredient_mappings").upsert({company_id:e,vendor_id:J,ingredient_id:t.id,vendor_product_description:s.description,normalized_name:t.name,category:K||"COGS",is_cogs:!0},{onConflict:"company_id,vendor_id,cluster_id",ignoreDuplicates:!0})}catch{}Ce(null)},[Ie,Te]=a.useState([]);a.useEffect(()=>{const e=new Set;Z.forEach(t=>{t.vendorCategory&&e.add(t.vendorCategory)});const t=["COGS","OPEX","Payroll","Rent",...Array.from(e)],s=Array.from(new Set(t));Te(s)},[Z]),a.useEffect(()=>{i&&(Y(i),i.vendor&&se(i.vendor))},[i]),a.useEffect(()=>{X(x)},[x]),a.useEffect(()=>{Q(V)},[V]),a.useEffect(()=>{if(!t)return;(async()=>{ne(!0);try{const e=await o();if(!e)return;const{data:t,error:s}=await q.from("vendors").select("id, name, category").eq("company_id",e).eq("is_active",!0).order("name");if(s)return void Se({title:"Error loading vendors",description:"Failed to load vendor list. Please try again.",variant:"destructive"});ee((t||[]).map(e=>({id:e.id,name:e.name,vendorCategory:e.category||null})))}catch(e){}finally{ne(!1)}})()},[t]),a.useEffect(()=>{if(ae||!(null==G?void 0:G.vendor)||0===Z.length)return;if(J)return;const e=G.vendor.trim();if(!e)return;te||se(e);const t=e.toLowerCase(),s=Z.filter(e=>{const s=e.name.toLowerCase();return s===t||s.includes(t)||t.includes(s)});if(0!==s.length||ce){if(s.length>0){const e=s.find(e=>e.name.toLowerCase()===t)||s[0];Q(e.id),le(!1)}}else le(!0),Q(void 0),de(e),ue(G.vendor_address||G.merchant_raw_text||""),he(G.vendor_phone||""),ge(G.vendor_email||"")},[Z,ae,G,te,ce,J]),a.useEffect(()=>{if(!J||!Z.length)return;const e=Z.find(e=>e.id===J);(null==e?void 0:e.vendorCategory)&&!K&&X(e.vendorCategory)},[J,Z,K]),a.useEffect(()=>{if(!te.trim()){if(""===te&&(null==G?void 0:G.vendor))return;return void le(!1)}if(ae)return;if(0===Z.length)return;if(J)return void le(!1);const e=te.toLowerCase(),t=Z.filter(t=>t.name.toLowerCase().includes(e)||e.includes(t.name.toLowerCase()));0!==t.length||ce?t.length>0&&le(!1):(le(!0),Q(void 0),de(te),ue((null==G?void 0:G.vendor_address)||(null==G?void 0:G.merchant_raw_text)||""),he((null==G?void 0:G.vendor_phone)||""),ge((null==G?void 0:G.vendor_email)||""))},[te,Z,ae,ce,G,J]),a.useEffect(()=>{var e;if(!t||!(null==(e=null==G?void 0:G.line_items)?void 0:e.length)||!B||B.length!==G.line_items.length)return;const s=G.line_items.map((e,t)=>({lineItem:e,mappingId:null,ingredientId:null,ingredientName:B[t].mapped_ingredient_name??null,source:"exact_description"}));ie(s)},[t,null==G?void 0:G.line_items,B]);const Ee=n.useRef(null==G?void 0:G.line_items);if(Ee.current=null==G?void 0:G.line_items,a.useEffect(()=>{if(!t||!J)return void((null==B?void 0:B.length)||ie(null));const s=Ee.current;if(!(null==s?void 0:s.length))return void ie(null);if((null==B?void 0:B.length)===s.length&&V&&J===V){const e=s.map((e,t)=>({lineItem:e,mappingId:null,ingredientId:null,ingredientName:B[t].mapped_ingredient_name??null,source:"exact_description"}));return void ie(e)}let a=!1;return(async()=>{try{const e=await o();if(!e||a)return;const t=await $s(e,J,s);if(a)return;ie(t),null==W||W(t.map(e=>({description:e.lineItem.description,quantity:e.lineItem.quantity,unit_price:e.lineItem.unit_price,total_price:e.lineItem.total_price,mapped_ingredient_name:e.ingredientName??void 0})))}catch(e){a||ie(null)}})(),()=>{a=!0}},[t,J,V,null==(H=null==G?void 0:G.line_items)?void 0:H.length,W,B]),!G)return null;const Me=(e,t)=>{Y(s=>s?{...s,[e]:t}:null)},ze=(e,t,s)=>{Y(a=>{if(!a)return null;const n=[...a.line_items];return n[e]={...n[e],[t]:s},{...a,line_items:n}})},Ae=Z.find(e=>e.id===J),qe=Z.filter(e=>e.name.toLowerCase().includes(te.toLowerCase()));return s.jsx(N,{open:t,onOpenChange:r,children:s.jsxs(w,{className:"max-w-5xl w-[90vw] max-h-[90vh]",children:[s.jsxs(b,{children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs(k,{className:"flex items-center gap-2",children:[s.jsx(es,{className:"h-5 w-5"}),"Confirm Receipt Data"]}),u&&s.jsx(h,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ve(!0),title:"View response from AI vendor recognition system",children:s.jsx(ts,{className:"h-4 w-4"})})]}),s.jsx("p",{className:"text-sm text-muted-foreground",children:c})]}),s.jsx(Le,{className:"max-h-[60vh] pr-4",children:s.jsxs("div",{className:"space-y-4",children:[f.length>0&&s.jsxs("div",{className:"p-4 bg-yellow-50 border border-yellow-200 rounded-lg space-y-2",children:[s.jsx("div",{className:"flex items-center gap-2 text-yellow-800 font-semibold",children:s.jsx(F,{variant:"secondary",className:"bg-yellow-100",children:"⚠️ Potential Duplicates Found"})}),s.jsx("p",{className:"text-sm text-yellow-700",children:"Similar receipt(s) found in the system:"}),s.jsx("div",{className:"space-y-2",children:f.map(e=>s.jsx("div",{className:"text-sm p-2 bg-white rounded border border-yellow-200",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-gray-900",children:e.vendor}),s.jsxs("p",{className:"text-gray-600",children:["$",e.amount.toFixed(2)," • ",new Date(e.date).toLocaleDateString()]})]}),s.jsxs(F,{variant:"outline",className:"text-xs",children:[e.matchScore,"% match"]})]})},e.id))}),s.jsx("p",{className:"text-xs text-yellow-600",children:"Please verify this is not a duplicate entry before confirming."})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[s.jsxs("div",{className:"space-y-2 md:col-span-1",children:[s.jsx(S,{children:"Receipt Preview"}),l?(null==d?void 0:d.startsWith("image/"))||c.match(/\.(jpg|jpeg|png|gif|webp|bmp)$/i)?s.jsx("div",{className:"w-full border rounded-md overflow-hidden bg-background",children:s.jsx("img",{src:l,alt:c,className:"h-[360px] w-full object-contain bg-black/5",onError:e=>{const t=e.target;t.style.display="none";const s=t.parentElement;if(s){const e=document.createElement("button");e.className="w-full p-2 border rounded text-sm",e.textContent="Click to open receipt",e.onclick=()=>window.open(l,"_blank"),s.appendChild(e)}}})}):s.jsxs(h,{variant:"outline",size:"sm",className:"w-full",onClick:()=>window.open(l,"_blank"),children:[s.jsx(es,{className:"h-4 w-4 mr-2"}),"Open receipt file"]}):s.jsx("div",{className:"w-full border rounded-md p-8 bg-muted/30 flex items-center justify-center",children:s.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Preview not available for this file type."})})]}),s.jsxs("div",{className:"space-y-4 md:col-span-2",children:[G.confidence&&s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs(F,{variant:G.confidence>.8?"default":"secondary",children:[Math.round(100*G.confidence),"% Confidence"]})}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(S,{className:"flex items-center gap-2",children:[s.jsx(ss,{className:"h-4 w-4"}),"Vendor"]}),s.jsxs(j,{open:_e,onOpenChange:Ne,children:[s.jsx(y,{asChild:!0,children:s.jsxs(h,{variant:"outline",role:"combobox","aria-expanded":_e,className:"w-full justify-between",children:[Ae?Ae.name:G.vendor||"Search or select vendor...",s.jsx(as,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),s.jsx(v,{className:"w-full p-0",align:"start",children:s.jsxs(Re,{children:[s.jsx(Oe,{placeholder:"Search vendors...",value:te||(null==G?void 0:G.vendor)||"",onValueChange:e=>{se(e),Me("vendor",e),e.trim()||le(!1)}}),s.jsxs(Ue,{children:[s.jsx($e,{children:te&&s.jsxs("div",{className:"py-2 px-3",children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No vend
2or found. Create new vendor?"}),s.jsxs(h,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{le(!0),Ne(!1),de(te),ue((null==G?void 0:G.vendor_address)||(null==G?void 0:G.merchant_raw_text)||""),he((null==G?void 0:G.vendor_phone)||""),ge((null==G?void 0:G.vendor_email)||"")},children:['Create "',te,'"']})]})}),s.jsx(Ve,{children:qe.map(e=>s.jsxs(Be,{value:`${e.name} ${e.id}`,onSelect:()=>{Q(e.id),Me("vendor",e.name),se(e.name),le(!1),Ne(!1)},children:[s.jsx(Jt,{className:m("mr-2 h-4 w-4",J===e.id?"opacity-100":"opacity-0")}),e.name]},e.id))})]})]})})]}),(G.vendor_address||G.vendor_city||G.vendor_postal_code)&&s.jsx("div",{className:"text-xs text-muted-foreground pl-2",children:[G.vendor_address,G.vendor_city,G.vendor_postal_code].filter(Boolean).join(", ")}),C.length>0&&!ce&&s.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:C.map(e=>s.jsxs("button",{type:"button",onClick:()=>{Q(e.id),Me("vendor",e.name),se(e.name),le(!1)},className:"px-2 py-0.5 rounded-full text-[10px] border "+(J===e.id?"border-primary bg-primary/5 text-primary":"border-muted-foreground/20 hover:bg-muted"),children:[e.name," · ",e.score,"%"]},e.id))}),ce&&s.jsxs("div",{className:"space-y-2 border rounded-md p-3 bg-muted/30 mt-2",children:[s.jsx(S,{className:"text-xs font-semibold",children:"Create New Vendor"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(S,{className:"text-xs",children:"Vendor Name"}),s.jsx(D,{value:oe,onChange:e=>de(e.target.value),className:"h-8 text-xs",placeholder:"Enter vendor name"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(S,{className:"text-xs",children:"Address (optional)"}),s.jsx(D,{value:me,onChange:e=>ue(e.target.value),className:"h-8 text-xs",placeholder:"Address, city, etc."})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(S,{className:"text-xs",children:"Phone (optional)"}),s.jsx(D,{value:xe,onChange:e=>he(e.target.value),className:"h-8 text-xs",placeholder:"Phone number"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(S,{className:"text-xs",children:"Email (optional)"}),s.jsx(D,{type:"email",value:pe,onChange:e=>ge(e.target.value),className:"h-8 text-xs",placeholder:"Email address"})]})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(S,{className:"text-xs",children:"Vendor Category"}),s.jsxs(I,{value:K||"",onValueChange:e=>X(e),children:[s.jsx(T,{className:"h-8 text-xs",children:s.jsx(E,{placeholder:"Select category"})}),s.jsx(M,{children:Ie.length>0?Ie.map(e=>s.jsx(z,{value:e,children:e},e)):["COGS","OPEX","Payroll","Rent"].map(e=>s.jsx(z,{value:e,children:e},e))})]})]})]}),s.jsx("p",{className:"text-[10px] text-muted-foreground pt-1",children:"This vendor will be saved and linked to this receipt."})]})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(S,{className:"flex items-center gap-2",children:[s.jsx(ns,{className:"h-4 w-4"}),"Date"]}),s.jsx(D,{type:"date",value:G.date||"",onChange:e=>Me("date",e.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(S,{className:"flex items-center gap-2",children:[s.jsx(rs,{className:"h-4 w-4"}),"Expense Category"]}),s.jsxs(I,{value:K||"",onValueChange:e=>X(e),children:[s.jsx(T,{children:s.jsx(E,{placeholder:"Select category"})}),s.jsx(M,{children:Ie.length>0?Ie.map(e=>s.jsx(z,{value:e,children:e},e)):["COGS","OPEX","Payroll","Rent"].map(e=>s.jsx(z,{value:e,children:e},e))})]})]})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(S,{children:["Line Items (",G.line_items.length,")"]}),s.jsx("div",{className:"border rounded-lg overflow-hidden",children:s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[s.jsx(O,{children:"Description"}),s.jsx(O,{className:"w-[80px]",children:"Qty"}),s.jsx(O,{className:"w-[120px]",children:"Unit Price"}),s.jsx(O,{className:"w-[120px]",children:"Line Total"})]})}),s.jsx(U,{children:G.line_items.map((e,t)=>{const a=null==re?void 0:re[t],n=(null==a?void 0:a.ingredientName)??e.description,r=Boolean(null==a?void 0:a.ingredientName);return s.jsxs(R,{children:[s.jsx($,{children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("p",{className:"font-medium text-foreground",children:n}),s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[10px] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-600/20",children:[s.jsx(Jt,{className:"h-2.5 w-2.5"}),"Auto-matched"]}),s.jsxs(j,{open:ke===t,onOpenChange:e=>Ce(e?t:null),children:[s.jsx(y,{asChild:!0,children:s.jsx("button",{type:"button",className:"text-[10px] text-muted-foreground hover:text-primary transition-colors underline underline-offset-2",children:"Change"})}),s.jsx(v,{className:"w-[260px] p-0",align:"start",side:"bottom",children:s.jsxs(Re,{children:[s.jsx(Oe,{placeholder:"Search ingredients..."}),s.jsxs(Ue,{children:[s.jsx($e,{children:"No ingredient found."}),s.jsx(Ve,{children:we.map(e=>s.jsxs(Be,{value:e.name,onSelect:()=>De(t,e),children:[s.jsx(Jt,{className:m("mr-2 h-3 w-3",(null==a?void 0:a.ingredientId)===e.id?"opacity-100":"opacity-0")}),s.jsx("span",{className:"truncate",children:e.name}),e.standard_unit&&s.jsx("span",{className:"ml-auto text-[10px] text-muted-foreground shrink-0",children:e.standard_unit})]},e.id))})]})]})})]})]}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Receipt: ",e.description]}),s.jsx(D,{value:e.description,onChange:e=>
2ze(t,"description",e.target.value),placeholder:"Raw description",className:"font-normal text-muted-foreground h-8 text-xs mt-1","aria-label":"Edit raw receipt description"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(D,{value:e.description,onChange:e=>ze(t,"description",e.target.value),placeholder:"Item description",className:"font-medium"}),re&&!(null==a?void 0:a.ingredientName)&&s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-medium text-amber-700 ring-1 ring-inset ring-amber-600/20 whitespace-nowrap shrink-0",children:[s.jsx(Yt,{className:"h-2.5 w-2.5"}),"Needs mapping"]})]}),re&&!(null==a?void 0:a.ingredientName)?s.jsxs(j,{open:ke===t,onOpenChange:e=>Ce(e?t:null),children:[s.jsx(y,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-primary hover:text-primary/80 hover:underline transition-colors",children:[s.jsx(Yt,{className:"h-3 w-3"}),"Attach item"]})}),s.jsx(v,{className:"w-[260px] p-0",align:"start",side:"bottom",children:s.jsxs(Re,{children:[s.jsx(Oe,{placeholder:"Search ingredients..."}),s.jsxs(Ue,{children:[s.jsx($e,{children:"No ingredient found."}),s.jsx(Ve,{children:we.map(e=>s.jsxs(Be,{value:e.name,onSelect:()=>De(t,e),children:[s.jsx("span",{className:"truncate",children:e.name}),e.standard_unit&&s.jsx("span",{className:"ml-auto text-[10px] text-muted-foreground shrink-0",children:e.standard_unit})]},e.id))})]})]})})]}):null]})})}),s.jsx($,{children:s.jsx(D,{type:"number",step:"0.01",value:e.quantity??1,onChange:e=>ze(t,"quantity",""===e.target.value?void 0:parseFloat(e.target.value))})}),s.jsx($,{children:s.jsx(D,{type:"number",step:"0.01",value:e.unit_price??0,onChange:e=>ze(t,"unit_price",""===e.target.value?void 0:parseFloat(e.target.value))})}),s.jsx($,{children:s.jsx(D,{type:"number",step:"0.01",value:e.total_price,onChange:e=>ze(t,"total_price",""===e.target.value?0:parseFloat(e.target.value))})})]},t)})})]})})]}),s.jsx("div",{className:"flex justify-end pt-4 border-t mt-4",children:s.jsxs("div",{className:"w-full md:w-[320px] space-y-3",children:[s.jsxs("div",{className:"flex justify-between items-center gap-4",children:[s.jsx(S,{className:"text-sm text-muted-foreground",children:"Subtotal"}),s.jsx(D,{type:"number",step:"0.01",value:G.subtotal??0,onChange:e=>Me("subtotal",""===e.target.value?void 0:parseFloat(e.target.value)),className:"w-[140px] text-right font-medium"})]}),s.jsxs("div",{className:"flex justify-between items-center gap-4",children:[s.jsx(S,{className:"text-sm text-muted-foreground",children:"Tax"}),s.jsx(D,{type:"number",step:"0.01",value:G.tax??0,onChange:e=>Me("tax",""===e.target.value?void 0:parseFloat(e.target.value)),className:"w-[140px] text-right font-medium"})]}),s.jsxs("div",{className:"flex justify-between items-center gap-4 pt-2 border-t",children:[s.jsx(S,{className:"text-base font-semibold",children:"Total"}),s.jsx(D,{type:"number",step:"0.01",value:G.total,onChange:e=>Me("total",""===e.target.value?0:parseFloat(e.target.value)),className:"w-[140px] text-right font-bold text-lg"})]})]})})]})}),s.jsxs(A,{className:"flex-col sm:flex-row gap-2",children:[s.jsxs("div",{className:"flex-1 text-xs text-muted-foreground",children:[s.jsx("p",{children:"After saving, this receipt will be:"}),s.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[s.jsx("li",{children:"Added to your expense records"}),s.jsx("li",{children:"Linked to the selected vendor (if applicable)"}),s.jsx("li",{children:"Available in the Expenses section for reporting"})]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(h,{variant:"outline",onClick:g,children:"Cancel"}),s.jsx(h,{onClick:()=>{if(!G||fe)return;const e=e=>{p(G,K,e),r(!1),je(!1)};if(ce&&oe.trim()){(async()=>{try{je(!0);const t=await o();if(!t)return Se({title:"Error",description:"Unable to determine company. Please try again.",variant:"destructive"}),void je(!1);const s=[me||G.vendor_address,G.vendor_city,G.vendor_postal_code].filter(Boolean).join(", ")||null,a=oe.trim();if(!a)return Se({title:"Error",description:"Vendor name is required. Please enter a vendor name.",variant:"destructive"}),void je(!1);const n={company_id:t,name:a};s&&s.trim()&&(n.address=s.trim());const r=xe||G.vendor_phone;r&&r.trim()&&(n.phone=r.trim());const i=pe||G.vendor_email;i&&i.trim()&&(n.email=i.trim()),K&&K.trim()&&(n.vendor_category=K.trim());const{data:c,error:l}=await q.from("vendors").insert(n).select("id").single();if(l)return Se({title:"Failed to Create Vendor",description:l.message||"An error occurred while creating the vendor. Please try again.",variant:"destructive"}),void je(!1);if(!(null==c?void 0:c.id))return Se({title:"Error",description:"Vendor was created but we couldn't retrieve its ID. Please try again.",variant:"destructive"}),void je(!1);const d=c.id;Se({title:"Vendor Created",description:`Vendor "${oe.trim()}" has been created successfully.`}),Q(d),Me("vendor",""),e(d)}catch(t){Se({title:"Error",description:t instanceof Error?t.message:"An unexpected error occurred while creating the vendor.",variant:"destructive"}),je(!1)}})()}else je(!0),e(J)},disabled:fe,children:fe?"Saving...":"Save Receipt"})]})]}),ye&&u&&s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"max-w-4xl w-[85vw] max-h-[85vh] bg-background rounded-lg shadow-lg border flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ts,{className:"h-4 w-4"}),s.jsx("span",{className:"text-sm font-semibold",children:"Raw Response (pretty JSON)"})]}),s.jsx(h,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>ve(!1),title:"Close",children:s.jsx(Xt,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Le,{className:"h-[70vh]",children:s.jsx("pre",{className:"text-xs font-mono text-left whitespace-pre px-4 py-3 bg-slate-950",dangerouslySetInnerHTML:{__html:Vs(u)}})})})]})})]})})},Ws=({compact:t=!1,embed:n=!1})=>{var r,i,c,l,o,d,m,u,x;const[p,g]=a.useState([]),[f,j]=a.useState(!1),[y,v]=a.useState(!1),[S,D]=a.use
2State({open:!1,file:null,data:null}),[I,T]=a.useState([]),[E,M]=a.useState(new Map),[z,A]=a.useState(!1),[P,L]=a.useState(null),{toast:R}=_(),O=p.find(e=>e.id===P)??null,U=e=>{const t=Array.from(e);if(0===t.length)return;const s=t.filter(e=>{var t;const s=Ls(e.type,e.name),a=(null==(t=e.name.split(".").pop())?void 0:t.toLowerCase())||"",n=["pdf","jpg","jpeg","png","gif","heic","xlsx","xls","csv"].includes(a);return!s&&!n});if(s.length>0&&(R({title:"Unsupported file type",description:`Please upload PDF or image files only. Invalid: ${s.map(e=>e.name).join(", ")}`,variant:"destructive"}),s.length===t.length))return;const a=t.filter(e=>{var t;const s=Ls(e.type,e.name),a=(null==(t=e.name.split(".").pop())?void 0:t.toLowerCase())||"";return s||["pdf","jpg","jpeg","png","gif","heic","xlsx","xls","csv"].includes(a)}).map(e=>{const t=URL.createObjectURL(e);return{id:Math.random().toString(36).substr(2,9),file:e,category:"",status:"pending",previewUrl:t}});0!==a.length&&(g(e=>{const t=[...e,...a];return K(t),t}),A(!0))},$=(e,t)=>{g(s=>s.map(s=>s.id===e?{...s,...t}:s))};a.useEffect(()=>()=>{p.forEach(e=>{e.previewUrl&&URL.revokeObjectURL(e.previewUrl)})}
2,[p]);const V=async(e,t,s,a)=>{try{const{data:{user:n}}=await q.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:r}=await q.from("profiles").select("company_id").eq("user_id",n.id).single();if(!(null==r?void 0:r.company_id))throw new Error("No company found");const i=await(async(e,t)=>{try{const s=e.date||(new Date).toISOString().split("T")[0],a=Math.abs(e.total),n=new Date(s);n.setDate(n.getDate()-3);const r=new Date(s);r.setDate(r.getDate()+3);const{data:i}=await q.from("bank_statements").select("*").eq("company_id",t).gte("transaction_date",n.toISOString().split("T")[0]).lte("transaction_date",r.toISOString().split("T")[0]).lt("amount",0);if(!i)return null;const c=i.reduce((e,t)=>Math.abs(Math.abs(t.amount)-a)<(e?Math.abs(Math.abs(e.amount)-a):1/0)?t:e,null);return c&&Math.abs(Math.abs(c.amount)-a)<=5?c:null}catch(s){return null}})(e,r.company_id);i&&(R({title:"Match Found!",description:`This receipt matches a bank transaction from ${i.description}`}),M(e=>new Map(e).set(s,i)));let c=null,l=0;if(a&&e.line_items&&e.line_items.length>0){const t=await $s(r.company_id,a,e.line_items);c=t.map((e,t)=>({description:e.lineItem.description,quantity:e.lineItem.quantity,unit_price:e.lineItem.unit_price,total_price:e.lineItem.total_price,line_item_ref:`line-${t}`,...e.mappingId&&{mapping_id:e.mappingId},...e.ingredientId&&{ingredient_id:e.ingredientId},...e.ingredientName&&{mapped_ingredient_name:e.ingredientName}})),l=t.filter(e=>null!=e.mappingId||null!=e.ingredientId).length}else e.line_items&&e.line_items.length>0&&(c=e.line_items.map((e,t)=>({description:e.description,quantity:e.quantity,unit_price:e.unit_price,total_price:e.total_price,line_item_ref:`line-${t}`})));const o={company_id:r.company_id,description:e.vendor,amount:Math.abs(e.total),expense_date:e.date||(new Date).toISOString().split("T")[0],category:t||"Uncategorized",subtotal:e.subtotal||null,tax:e.tax||null,total:e.total||null,currency:e.currency||"USD",payment_method:e.payment_method||null,line_items:c,source:"receipt_upload",uploaded_by:n.id};a&&(o.vendor_id=a);const{data:d,error:m}=await q.from("expenses").insert(o).select().single();if(m)throw m;const u=(c||[]).filter(e=>e.description&&(e.quantity??1)>0);u.length>0&&await(async(e,t)=>{try{const{data:s}=await q.from("ingredients").select("id, name, standard_unit, receipt_description").eq("company_id",t);for(const a of e){const e=a.quantity??1;if(!(e>0))continue;const n="ingredient_id"in a&&a.ingredient_id?a.ingredient_id:null;if(n&&s){const{data:a}=await q.from("inventory_items").select("id, current_quantity").eq("company_id",t).eq("ingredient_id",n).maybeSingle(),r=s.find(e=>e.id===n);if(!r)continue;a?await q.from("inventory_items").update({current_quantity:a.current_quantity+e,last_counted_at:(new Date).toISOString()}).eq("id",a.id):await q.from("inventory_items").insert({company_id:t,ingredient_id:r.id,name:r.name,unit:r.standard_unit,current_quantity:e,last_counted_at:(new Date).toISOString()});continue}if(!s)continue;const r=s.find(e=>{var t;return e.name.toLowerCase().includes((a.description||"").toLowerCase())||(a.description||"").toLowerCase().includes(e.name.toLowerCase())||(null==(t=e.receipt_description)?void 0:t.toLowerCase())===(a.description||"").toLowerCase()});if(!r)continue;const{data:i}=await q.from("inventory_items").select("id, current_quantity").eq("company_id",t).eq("ingredient_id",r.id).maybeSingle();i?await q.from("inventory_items").update({current_quantity:i.current_quantity+e,last_counted_at:(new Date).toISOString()}).eq("id",i.id):await q.from("inventory_items").insert({company_id:t,ingredient_id:r.id,name:r.name,unit:r.standard_unit,current_quantity:e,last_counted_at:(new Date).toISOString()})}}catch(s){}})(u,r.company_id),R({title:"Receipt Added Successfully",description:l>0?`Expense recorded. ${l} line item(s) matched to COGS mappings; inventory updated.`:`Expense recorded and inventory updated for ${e.vendor}`}),$(s,{status:"added-to-expenses"})}catch(n){R({title:"Failed to Add",description:n instanceof Error?n.message:"Failed to add to expenses",variant:"destructive"})}},G=()=>{T(e=>{const t=e.slice(1);return t.length>0?D({open:!0,file:t[0],data:t[0].extractedData||null}):D({open:!1,file:null,data:null}),t})},K=async t=>{const s=(t??p).filter(e=>"pending"===e.status);if(0===s.length)return void R({title:"No files to process",description:"Please upload receipt files first.",variant:"destructive"});v(!0);const{data:{user:a}}=await q.auth.getUser();if(!a)return R({title:"Authentication required",description:"Please log in to process receipts",variant:"destructive"}),void v(!1);const{data:n}=await q.from("profiles").select("company_id").eq("user_id",a.id).single();if(!(null==n?void 0:n.company_id))return R({title:"Company required",description:"Please set up your company profile first",variant:"destructive"}),void v(!1);const r=n.company_id,{data:i}=await q.from("vendors").select("id, name").eq("company_id",r).eq("is_active",!0).order("name"),c=i||[],l=s.map(async t=>{try{$(t.id,{status:"processing"});const s=await(e=>new Promise((t,s)=>{const a=new FileReader;a.onload=()=>t(a.result),a.onerror=s,a.readAsDataURL(e)}))(t.file),{data:a,error:n}=await q.functions.invoke("analyze-receipt",{body:{imageData:s}});if(n)throw n;if(!a||!a.data)throw new Error("No data returned from receipt analysis");const i=a.data,l=a.raw,o=await(async(e,t)=>{var s,a;
2try{const n=e.date||(new Date).toISOString().split("T")[0],r=Math.abs(e.total),i=new Date(n);i.setDate(i.getDate()-7);const c=new Date(n);c.setDate(c.getDate()+7);const{data:l}=await q.from("bank_statements").select("*").eq("company_id",t).gte("transaction_date",i.toISOString().split("T")[0]).lte("transaction_date",c.toISOString().split("T")[0]).lt("amount",0);if(!l||0===l.length)return[];const o=[];for(const t of l){const i=Math.abs(t.amount),c=Math.abs(i-r)<=5,l=new Date(t.transaction_date),d=new Date(n),m=Math.abs((l.getTime()-d.getTime())/864e5)<=3,u=(null==(s=t.description)?void 0:s.toLowerCase().includes(e.vendor.toLowerCase()))||e.vendor.toLowerCase().includes((null==(a=t.description)?void 0:a.toLowerCase())||"");let x=0;c&&(x+=40),m&&(x+=30),u&&(x+=30),x>=70&&o.push({id:t.id,vendor:t.description||"Unknown",amount:i,date:t.transaction_date,matchScore:x})}return o}catch(n){return[]}})(i,r),d=(e=>{if(!e)return[];const t=e.toLowerCase().trim();return t?c.map(e=>{const s=e.name.toLowerCase();let a=0;return s===t?a=100:s.includes(t)||t.includes(s)?a=85:s.split(" ")[0]===t.split(" ")[0]?a=70:(s.startsWith(t)||t.startsWith(s))&&(a=60),{id:e.id,name:e.name,score:a}}).filter(e=>e.score>=50).sort((e,t)=>t.score-e.score).slice(0,5):[]})(i.vendor),m=d[0];let u,x=t.vendorId||(null==m?void 0:m.id),h=null;if(i.line_items&&i.line_items.length>0)try{if(x){u=(await $s(r,x,i.line_items)).map(e=>({description:e.lineItem.description,quantity:e.lineItem.quantity,unit_price:e.lineItem.unit_price,total_price:e.lineItem.total_price,mapped_ingredient_name:e.ingredientName??void 0}))}else{const e=await async function(e,t,s){if(!t.length)return null;const{data:a}=await q.from("vendor_ingredient_mappings").select("vendor_id").eq("company_id",e);if(!(null==a?void 0:a.length))return null;const n=[...new Set(a.map(e=>e.vendor_id).filter(Boolean))];if(!n.length)return null;const{data:r}=await q.from("vendors").select("id, name").in("id",n),i=new Map;for(const o of r||[])i.set(o.id,o.name??null);const c=n.map(e=>({id:e,name:i.get(e)??null}));if(null==s?void 0:s.trim()){const e=s.toLowerCase().trim();c.sort((t,s)=>{const a=(t.name||"").toLowerCase(),n=(s.name||"").toLowerCase(),r=a===e||a.includes(e)||e.includes(a)?1:0,i=n===e||n.includes(e)||e.includes(n)?1:0;return r!==i?i-r:0})}let l=null;for(let o=0;o<Math.min(c.length,10);o++){const s=c[o],a=await $s(e,s.id,t),n=a.filter(e=>null!=e.mappingId||null!=e.ingredientId).length;n>0&&(!l||n>l.matchedCount)&&(l={vendorId:s.id,vendorName:s.name,results:a,matchedCount:n})}return l}(r,i.line_items,i.vendor);e&&e.matchedCount>0&&(x=e.vendorId,h=e.vendorName,u=e.results.map(e=>({description:e.lineItem.description,quantity:e.lineItem.quantity,unit_price:e.lineItem.unit_price,total_price:e.lineItem.total_price,mapped_ingredient_name:e.ingredientName??void 0})))}}catch(e){}const p=x&&!d.some(e=>e.id===x)?[{id:x,name:h??i.vendor??"Vendor",score:80},...d]:d,g={...t,status:"completed",extractedData:i,estimatedAmount:i.total,confidence:i.confidence,vendorName:i.vendor||t.vendorName,duplicateWarnings:o,vendorSuggestions:p,vendorId:x,taggunRaw:l,enrichedLineItems:u??void 0};return $(t.id,g),{success:!0,fileId:t.id,file:g}}catch(s){const e=s instanceof Error?s.message:"Failed to process receipt";return $(t.id,{status:"error",extractedData:void 0}),R({title:"Processing Failed",description:`${t.file.name}: ${e}`,variant:"destructive"}),{success:!1,fileId:t.id,error:s}}}),o=await Promise.all(l);v(!1);const d=o.filter(e=>e.success),m=o.filter(e=>!e.success),u=d.filter(e=>e.success&&e.file).map(e=>e.file);u.length>0?(T(u),D({open:!0,file:u[0],data:u[0].extractedData||null}),m.length>0?R({title:"Partially Complete",description:`Processed ${u.length} receipt(s) successfully. ${m.length} failed - check the files marked with error status.`}):R({title:"Processing Complete",description:`Successfully processed ${u.length} receipt(s). Please review the extracted data.`})):m.length>0&&R({title:"Processing Failed",description:`Failed to process ${m.length} receipt(s). Please check the error messages and try again.`,variant:"destructive"})},X=e=>{switch(e){case"completed":return"bg-green-500";case"processing":return"bg-blue-500";case"error":return"bg-red-500";case"added-to-expenses":return"bg-emerald-500";default:return"bg-gray-400"}},J=e=>"added-to-expenses"===e?"Added":e,Q=a.useCallback(()=>{L(null),A(!0)},[]),Z=p.filter(e=>"completed"===e.status).length,ee=p.filter(e=>"processing"===e.status).length,te=s.jsxs("div",{className:`border-2 border-dashed rounded-lg text-center transition-colors cursor-pointer flex flex-col items-center justify-center ${f?"border-primary bg-primary/5":"border-muted-foreground
2/30 hover:border-primary/50"} ${t||n?"min-h-[80px] p-3":"p-4"}`,onDrop:e=>{e.preventDefault(),j(!1);const t=e.dataTransfer.files;t.length>0&&U(t)},onDragOver:e=>{e.preventDefault(),j(!0)},onDragLeave:()=>j(!1),onClick:()=>{var e;return null==(e=document.getElementById("receipts-file-input"))?void 0:e.click()},children:[s.jsx("input",{id:"receipts-file-input",type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png,.gif,.heic,image/*,application/pdf",onChange:e=>e.target.files&&U(e.target.files),className:"hidden"}),s.jsx(yt,{className:"mx-auto text-muted-foreground "+(t?"h-6 w-6 mb-1":"h-8 w-8 mb-2")}),s.jsx("p",{className:t?"text-xs font-medium":"text-sm font-medium",children:"Drop or choose files"}),!t&&s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PDF, images (JPG, PNG)"})]}),se=s.jsxs("div",{className:"space-y-3 "+(t||n?"flex-1 flex flex-col pt-0":""),children:[te,p.length>0&&s.jsxs(h,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:Q,children:[s.jsx(Pt,{className:"h-3.5 w-3.5"}),"View Receipts (",p.length,")",ee>0&&s.jsxs(F,{variant:"secondary",className:"ml-1 text-[10px] px-1.5 py-0",children:[s.jsx(ht,{className:"h-2.5 w-2.5 mr-0.5 animate-pulse"}),ee," processing"]}),Z>0&&s.jsxs(F,{variant:"default",className:"ml-1 text-[10px] px-1.5 py-0",children:[Z," ready"]})]}),y&&s.jsx(ue,{value:66,className:"w-full"})]}),ae=s.jsx("div",{className:"space-y-1",children:p.map(e=>s.jsx("button",{type:"button",onClick:()=>L(e.id),className:"w-full text-left rounded-lg border p-3 transition-all hover:bg-accent/50 "+(P===e.id?"border-primary bg-accent ring-1 ring-primary/20":"border-border"),children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"h-10 w-10 rounded-md bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:e.previewUrl&&e.file.type.startsWith("image/")?s.jsx("img",{src:e.previewUrl,alt:"",className:"h-full w-full object-cover"}):s.jsx(vt,{className:"h-5 w-5 text-muted-foreground"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-medium truncate",children:e.file.name}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${X(e.status)}`}),s.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:J(e.status)}),null!=e.estimatedAmount&&s.jsxs("span",{className:"text-xs font-medium",children:["$",e.estimatedAmount.toFixed(2)]})]}),e.vendorName&&s.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:e.vendorName})]}),s.jsx(ot,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})},e.id))}),ne=O?s.jsxs("div",{className:"space-y-6",children:[s.jsxs("button",{type:"button",onClick:()=>L(null),className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors md:hidden",children:[s.jsx(lt,{className:"h-4 w-4"}),"Back to list"]}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"font-semibold text-base truncate",children:O.file.name}),s.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[s.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${X(O.status)}`}),s.jsxs(F,{variant:"completed"===O.status?"default":"error"===O.status?"destructive":"added-to-expenses"===O.status?"default":"secondary",children:["processing"===O.status&&s.jsx(ht,{className:"h-3 w-3 mr-1 animate-pulse"}),J(O.status)]}),null!=O.confidence&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(100*O.confidence),"% confidence"]}),E.has(O.id)&&s.jsxs(F,{variant:"outline",className:"flex items-center gap-1 text-xs",children:[s.jsx(is,{className:"h-3 w-3"}),"Bank matched"]})]})]}),s.jsxs("div",{className:"flex gap-1.5 shrink-0",children:["completed"===O.status&&O.extractedData&&s.jsx(h,{size:"sm",onClick:()=>D({open:!0,file:O,data:O.extractedData}),children:"Review & Add"}),"added-to-expenses"===O.status&&s.jsx(h,{size:"sm",variant:"secondary",disabled:!0,children:"Added ✓"}),s.jsx(h,{size:"sm",variant:"ghost",onClick:()=>{var e;e=O.id,g(t=>{const s=t.find(t=>
2t.id===e);return(null==s?void 0:s.previewUrl)&&URL.revokeObjectURL(s.previewUrl),t.filter(t=>t.id!==e)}),L(null)},disabled:"processing"===O.status,children:s.jsx(jt,{className:"h-4 w-4"})})]})]}),O.previewUrl&&s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium mb-2",children:"Receipt Preview"}),O.file.type.startsWith("image/")?s.jsxs("button",{type:"button",className:"block w-full max-w-md border rounded-lg overflow-hidden bg-muted/30",onClick:()=>window.open(O.previewUrl,"_blank"),children:[s.jsx("img",{src:O.previewUrl,alt:O.file.name,className:"max-h-60 w-full object-contain"}),s.jsx("span",{className:"block text-xs text-muted-foreground py-1.5 text-center",children:"Click to open full size"})]}):s.jsxs(h,{variant:"outline",size:"sm",onClick:()=>window.open(O.previewUrl,"_blank"),children:[s.jsx(vt,{className:"h-4 w-4 mr-2"}),"Open receipt file"]})]}),O.extractedData&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium mb-2",children:"Receipt Details"}),s.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2 text-sm",children:[s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Vendor"}),s.jsx("span",{className:"font-medium",children:O.extractedData.vendor})]}),O.extractedData.date&&s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Date"}),s.jsx("span",{children:O.extractedData.date})]}),null!=O.extractedData.subtotal&&s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Subtotal"}),s.jsxs("span",{children:["$",O.extractedData.subtotal.toFixed(2)]})]}),null!=O.extractedData.tax&&s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Tax"}),s.jsxs("span",{children:["$",O.extractedData.tax.toFixed(2)]})]}),s.jsxs("div",{className:"flex justify-between font-medium pt-2 border-t",children:[s.jsx("span",{children:"Total"}),s.jsxs("span",{children:["$",O.extractedData.total.toFixed(2)]})]})]})]}),(()=>{const e=O.enrichedLineItems??O.extractedData.line_items;return e&&0!==e.length?s.jsxs("div",{children:[s.jsxs("p",{className:"text-sm font-medium mb-2",children:["Line Items (",e.length,")"]}),s.jsx("div",{className:"rounded-lg border divide-y",children:e.map((e,t)=>{const a="mapped_ingredient_name"in e&&e.mapped_ingredient_name?e.mapped_ingredient_name:e.description;return s.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2 text-sm",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"truncate block",children:[e.quantity?`${e.quantity}x `:"",a]}),null!=e.unit_price&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:["@ $",e.unit_price.toFixed(2)," each"]})]}),s.jsxs("span",{className:"font-medium whitespace-nowrap shrink-0",children:["$",e.total_price.toFixed(2)]})]},t)})})]}):null})()]}),"processing"===O.status&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(ht,{className:"h-8 w-8 text-primary animate-pulse mb-3"}),s.jsx("p",{className:"text-sm font-medium",children:"Analyzing receipt..."}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Extracting vendor, amounts, and line items"})]}),"error"===O.status&&s.jsxs("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-center",children:[s.jsx("p",{className:"text-sm font-medium text-destructive",children:"Processing failed"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try re-uploading this receipt"})]}),s.jsxs("div",{className:"text-xs text-muted-foreground pt-2 border-t space-y-0.5",children:[s.jsxs("p",{children:["Size: ",(O.file.size/1024/1024).toFixed(2)," MB"]}),s.jsxs("p",{children:["Type: ",O.file.type||"Unknown"]})]})]}):null,re=s.jsx(N,{open:z,onOpenChange:e=>{A(e),e||L(null)},children:s.jsxs(w,{className:"max-w-6xl w-[95vw] max-h-[85vh] p-0 gap-0 overflow-hidden",children:[s.jsxs(b,{className:"px-6 pt-6 pb-4 border-b shrink-0",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(k,{className:"flex items-center gap-2",children:[s.jsx(es,{className:"h-5 w-5 text-primary"}),"Uploaded Receipts (",p.length,")"]}),s.jsx(C,{className:"mt-1",children:'Click a receipt to view details, or use "Review & Add" to save to expenses.'})]}),s.jsxs("div",{className:"border-2 border-dashed rounded-lg px-3 py-2 cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-colors",onClick:()=>{var e;
2return null==(e=document.getElementById("receipts-file-input-modal"))?void 0:e.click()},children:[s.jsx("input",{id:"receipts-file-input-modal",type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png,.gif,.heic,image/*,application/pdf",onChange:e=>e.target.files&&U(e.target.files),className:"hidden"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(yt,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"text-xs font-medium",children:"Add more"})]})]})]}),y&&s.jsx(ue,{value:66,className:"mt-3"})]}),s.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",style:{height:"calc(85vh - 120px)"},children:[s.jsx("div",{className:"border-r shrink-0 "+(P?"hidden md:block":""),style:{width:P?"320px":"100%",maxWidth:P?"320px":void 0},children:s.jsx(Le,{className:"h-full",children:s.jsx("div",{className:"p-3",children:0===p.length?s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(es,{className:"h-10 w-10 text-muted-foreground/40 mb-3"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No receipts yet"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload files to get started"})]}):ae})})}),P&&s.jsx("div",{className:"flex-1 min-w-0 "+(P?"":"hidden"),children:s.jsx(Le,{className:"h-full",children:s.jsx("div",{className:"p-6",children:ne})})}),!P&&p.length>0&&s.jsx("div",{className:"hidden md:flex flex-1 items-center justify-center text-center p-6",children:s.jsxs("div",{children:[s.jsx(Pt,{className:"h-10 w-10 text-muted-foreground/30 mx-auto mb-3"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a receipt to view details"})]})})]})]})}),ie=s.jsx(Bs,{open:S.open,onOpenChange:e=>!e&&G(),extractedData:S.data,fileName:(null==(r=S.file)?void 0:r.file.name)||"",previewUrl:null==(i=S.file)?void 0:i.previewUrl,fileType:null==(c=S.file)?void 0:c.file.type,taggunRaw:null==(l=S.file)?void 0:l.taggunRaw,category:(null==(o=S.file)?void 0:o.category)||"",onConfirm:async(e,t,s)=>{S.file&&(await V(e,t,S.file.id,s),T(e=>{const t=e.slice(1);return t.length>0?D({open:!0,file:t[0],data:t[0].extractedData||null}):D({open:!1,file:null,data:null}),t}))},onCancel:G,duplicateWarnings:null==(d=S.file)?void 0:d.duplicateWarnings,vendorSuggestions:null==(m=S.file)?void 0:m.vendorSuggestions,initialVendorId:null==(u=S.file)?void 0:u.vendorId,initialEnrichedLineItems:(null==(x=S.file)?void 0:x.enrichedLineItems)??void 0,onEnrichedLineItems:e=>{S.file&&$(S.file.id,{enrichedLineItems:e})}});return n?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"h-full flex flex-col min-h-[80px]",children:se}),re,ie]}):s.jsx("div",{className:t?"h-full":"space-y-6",children:s.jsxs(B,{className:t?"h-full flex flex-col border bg-card/50 shadow-sm shadow-card":"shadow-card",children:[s.jsxs(W,{className:t?"pb-2":void 0,children:[s.jsxs(H,{className:"flex items-center gap-2 "+(t?"text-base":""),children:[s.jsx("div",{className:t?"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center":void 0,children:s.jsx(es,{className:t?"h-4 w-4 text-primary":"h-5 w-5 text-primary"})}),"Receipt Uploads"]}),s.jsx("p",{className:t?"text-xs text-muted-foreground":"text-sm text-muted-foreground",children:t?"PDF or images — AI expense tracking":"Upload receipts for AI-powered expense tracking, categorization, and inventory updates"})]}),s.jsx(Y,{className:t?"flex-1 flex flex-col pt-0":"",children:se}),re,ie]})})},Hs=()=>{var e;const[t,n]=a.useState(!1),[i,c]=a.useState(0),{data:l,isLoading:d}=Ke(),{data:u=[],isLoading:x}=xs(),{data:p,isLoading:g}=Xe({queryKey:["data-center-stats"],queryFn:async()=>{const e=await o();if(!e)return{totalTransactions:0,totalSalesRecords:0,totalReceipts:0,categorizedTransactions:0,uncategorizedTransactions:0,syncedAccounts:0,manualAccounts:0,trainedAccounts:0,untranedAccounts:0,lastSyncDate:null,thisMonthImports:0,lastMonthImports:0};const[t,s,a,n]=await Promise.all([q.from("bank_transactions").select("id",{count:"exact",head:!0}).eq("company_id",e),q.from("bank_transactions").select("id",{count:"exact",head:!0}).eq("company_id",e).not("category_type","is",null),q.from("sales_transactions").select("id",{count:"exact",head:!0}).eq("company_id",e),q.from("bank_account_training_progress").select("account_id, status").eq("company_id",e)]),r=t.count||0,i=s.count||0;return{totalTransactions:r,totalSalesRecords:a.count||0,totalReceipts:0,categorizedTransactions:i,uncategorizedTransactions:r-i,syncedAccounts:0,manualAccounts:0,trainedAccounts:(n.data||[]).filter(e=>"completed"===e.status).length,untranedAccounts:0,lastSyncDate:null,thisMonthImports:0,lastMonthImports:0}},staleTime:12e4}),{data:f=[]}=Xe({queryKey:["recent-sync-jobs"],queryFn:async()=>{const e=await o();if(!e)return[];const{data:t,error:s}=await q.from("sync_jobs").select("id, platform, sync_type, status, created_at, records_imported, error_message").eq("company_id",e).order("created_at",{ascending:!1}).limit(5);if(s)throw s;return t||[]}}),{data:j=[]}=Xe({queryKey:["recent-data-activity"],queryFn:async()=>{const e=await o();if(!e)return[];const t=q.from("sync_jobs").select("id, created_at, sync_type, platform, status, records_imported").eq("company_id",e).order("created_at",{ascending:!1}).limit(50),s=(async()=>{try{const t=await q.from("file_uploads").select("id, filename, file_type, processing_status, created_at, upload_date, records_imported").eq("company_id",e).order("upload_date",{ascending:!1}).limit(50);return t.error?await q.from("file_uploads").select("id, filename, file_type, processing_status, created_at, upload_date").eq("company_id",e).order("upload_date",{ascending:!1}).limit(50):t}catch{return{data:[],error:null}}})(),[a,n]=await Promise.all([t,s]);return[...(a.data||[]).map(e=>({id:e.id,date:e.created_at,type:"sync",description:`${e.platform??"Sync"} ${(e.sync_type??"").replace(/_/g," ")}`.trim(),platform:e.platform,status:e.status,records:e.records_imported})),...(n.error?[]:n.data||[]).map(e=>({id:e.id,date:e.created_at??e.upload_date??(new Date).toISOString(),type:"upload",description:e.filename??"File import",platform:void 0,status:e.processing_status??"completed",records:e.records_imported||void 0}))].sort((e,t)=>
2new Date(t.date).getTime()-new Date(e.date).getTime())}}),y={total:u.length,connected:u.filter(e=>"connected"===e.connection_status).length,manual:u.filter(e=>"manual_upload"===e.connection_status||!e.connection_status).length,syncEnabled:u.filter(e=>e.sync_enabled).length,trained:u.filter(e=>"completed"===e.training_status).length,lastSynced:null==(e=u.filter(e=>e.last_synced_at).sort((e,t)=>new Date(t.last_synced_at).getTime()-new Date(e.last_synced_at).getTime())[0])?void 0:e.last_synced_at},v=e=>{const t=null==l?void 0:l.find(t=>t.integration_type===e);return{isActive:(null==t?void 0:t.is_active)||!1,hasCredentials:!!t&&Object.keys(t.config||{}).length>0}},_=v("doordash"),N=v("ubereats"),w=v("toast");v("teller");const b=_.isActive||N.isActive||w.isActive,k=y.connected>0,C=d||x||g,S=p&&p.totalTransactions>0?Math.round(p.categorizedTransactions/p.totalTransactions*100):0,D=y.total>0?Math.round(y.trained/y.total*100):0,I=e=>{switch(e){case"completed":return s.jsx(ct,{className:"h-4 w-4 text-green-500"});case"running":case"pending":return s.jsx(Ct,{className:"h-4 w-4 text-blue-500 animate-spin"});case"failed":return s.jsx(wt,{className:"h-4 w-4 text-red-500"});default:return s.jsx(Ze,{className:"h-4 w-4 text-muted-foreground"})}};return C?s.jsxs("div",{className:"space-y-8",children:[s.jsxs("div",{className:"text-center space-y-3",children:[s.jsx(ce,{className:"h-10 w-64 mx-auto"}),s.jsx(ce,{className:"h-5 w-96 mx-auto"})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[1,2,3,4].map(e=>s.jsx(ce,{className:"h-32"},e))}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsx(ce,{className:"h-80"}),s.jsx(ce,{className:"h-80"})]})]}):s.jsxs("div",{className:"space-y-8",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"flex flex-wrap items-center justify-between gap-4",children:s.jsxs("div",{className:"text-center md:text-left space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-center md:justify-start gap-3",children:[s.jsx(cs,{className:"h-8 w-8 text-primary"}),s.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Data Center"})]}),s.jsx("p",{className:"text-muted-foreground max-w-2xl",children:"Central hub for all your data imports, bank syncing, and AI training. Monitor data flow and keep your financial intelligence up to date."})]})}),s.jsxs("div",{className:"flex items-center justify-center gap-3 flex-wrap",children:[k&&s.jsxs(F,{variant:"secondary",className:"gap-1.5 py-1",children:[s.jsx(Ut,{className:"h-3.5 w-3.5 text-green-500"}),y.connected," Bank",1!==y.connected?"s":""," Connected"]}),b&&s.jsxs(F,{variant:"secondary",className:"gap-1.5 py-1",children:[s.jsx(ls,{className:"h-3.5 w-3.5 text-blue-500"}),"POS Integrations Active"]}),y.trained>0&&s.jsxs(F,{variant:"secondary",className:"gap-1.5 py-1",children:[s.jsx(Mt,{className:"h-3.5 w-3.5 text-purple-500"}),y.trained," Account",1!==y.trained?"s":""," Trained"]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[s.jsx(B,{className:"border-l-4 border-l-blue-500",children:s.jsx(Y,{className:"pt-6",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Bank Transactions"}),s.jsx("p",{className:"text-3xl font-bold mt-1",children:(null==p?void 0:p.totalTransactions.toLocaleString())||0}),s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(ue,{value:S,className:"h-2 flex-1"}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:[S,"%"]})]}),s.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[null==p?void 0:p.categorizedTransactions.toLocaleString()," categorized"]})]}),s.jsx("div",{className:"h-10 w-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center",children:s.jsx(Kt,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})})]})})}),s.jsx(B,{className:"border-l-4 border-l-green-500",children:s.jsx(Y,{className:"pt-6",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Sales Records"}),s.jsx("p",{className:"text-3xl font-bold mt-1",children:(null==p?void 0:p.totalSalesRecords.toLocaleStr
2ing())||0}),s.jsx("div",{className:"flex items-center gap-1.5 mt-2",children:b?s.jsxs(s.Fragment,{children:[s.jsx(Ut,{className:"h-3.5 w-3.5 text-green-500"}),s.jsx("span",{className:"text-xs text-green-600 dark:text-green-400",children:"Auto-synced"})]}):s.jsxs(s.Fragment,{children:[s.jsx(yt,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"Manual upload"})]})})]}),s.jsx("div",{className:"h-10 w-10 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center",children:s.jsx(Qt,{className:"h-5 w-5 text-green-600 dark:text-green-400"})})]})})}),s.jsx(B,{className:"border-l-4 border-l-amber-500",children:s.jsx(Y,{className:"pt-6",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Receipts Processed"}),s.jsx("p",{className:"text-3xl font-bold mt-1",children:(null==p?void 0:p.totalReceipts.toLocaleString())||0}),s.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"OCR-powered extraction"})]}),s.jsx("div",{className:"h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center",children:s.jsx(es,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"})})]})})}),s.jsx(B,{className:"border-l-4 border-l-purple-500",children:s.jsx(Y,{className:"pt-6",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"This Month Imports"}),s.jsx("p",{className:"text-3xl font-bold mt-1",children:(null==p?void 0:p.thisMonthImports)||0}),s.jsx("div",{className:"flex items-center gap-1.5 mt-2",children:p&&p.thisMonthImports>p.lastMonthImports?s.jsxs(s.Fragment,{children:[s.jsx(At,{className:"h-3.5 w-3.5 text-green-500"}),s.jsxs("span",{className:"text-xs text-green-600 dark:text-green-400",children:["+",p.thisMonthImports-p.lastMonthImports," vs last month"]})]}):s.jsxs("span",{className:"text-xs text-muted-foreground",children:[(null==p?void 0:p.lastMonthImports)||0," last month"]})})]}),s.jsx("div",{className:"h-10 w-10 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center",children:s.jsx(vt,{className:"h-5 w-5 text-purple-600 dark:text-purple-400"})})]})})})]}),s.jsxs("div",{id:"quick-uploads",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[s.jsx(B,{id:"sales-deposits",className:"scroll-mt-8 overflow-hidden border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10 hover:shadow-md transition-all hover:border-primary/40 h-full flex flex-col min-w-0 min-h-[240px]",children:s.jsxs(Y,{className:"p-5 flex-1 flex flex-col gap-0 min-h-0",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3 shrink-0",children:[s.jsx("div",{className:"h-10 w-10 shrink-0 rounded-lg bg-primary/10 flex items-center justify-center",children:s.jsx(Qt,{className:"h-5 w-5 text-primary"})}),b&&s.jsxs(F,{variant:"secondary",className:"text-xs gap-1 shrink-0",children:[s.jsx(Ut,{className:"h-3 w-3"}),"Auto"]})]}),s.jsx("h3",{className:"font-semibold text-base shrink-0",children:"Sales & Deposits"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1 shrink-0",children:b?"Auto-synced from POS":"Toast, DoorDash, or Uber Eats payments & payouts"}),s.jsx("div",{className:"mt-4 flex-1 flex flex-col min-h-0 overflow-hidden",children:s.jsx(Fs,{compact:!0,embed:!0})})]})}),s.jsx(B,{id:"sales-quantities",className:"scroll-mt-8 overflow-hidden border-secondary/20 bg-gradient-to-br from-secondary/5 to-secondary/10 hover:shadow-md transition-all hover:border-secondary/40 h-full flex flex-col min-w-0 min-h-[240px]",children:s.jsxs(Y,{className:"p-5 flex-1 flex flex-col gap-0 min-h-0",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3 shrink-0",children:[s.jsx("div",{className:"h-10 w-10 shrink-0 rounded-lg bg-secondary/10 flex items-center justify-center",children:s.jsx(os,{className:"h-5 w-5 text-secondary-foreground"})}),b&&s.jsxs(F,{variant:"secondary",className:"text-xs gap-1 shrink-0",children:[s.jsx(Ut,{className:"h-3 w-3"}),"Auto"]})]}),s.jsx("h3",{className:"font-semibold text-base shrink-0",children:"Sales Quantities"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1 shrink-0",children:b?"Auto-synced from POS":"Toast, DoorDash, or Uber Eats item qty reports"}),s.jsx("div",{className:"mt-4 flex-1 flex flex-col min-h-0 overflow-hidden",children:s.jsx(Ps,{compact:!0,embed:!0})})]})}),s.jsx(B,{id:"receipts",className:"scroll-mt-8 overflow-hidden border-amber-500/20 bg-gradient-to-br from-amber-500/5 to-amber-500/10 hover:shadow-md transition-all hover:border-amber-500/40 h-full flex flex-col min-w-0 min-h-[240px]",children:s.jsxs(Y,{className:"p-5 flex-1 flex flex-col gap-0 min-h-0",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3 shrink-0",children:[s.jsx("div",{className:"h-10 w-10 shrink-0 rounded-lg bg-amber-500/10 flex items-center justify-center",children:s.jsx(es,{className:"h-5 w-5 text-amber-600 dar
2k:text-amber-400"})}),s.jsx(F,{variant:"outline",className:"text-xs shrink-0",children:"Manual"})]}),s.jsx("h3",{className:"font-semibold text-base shrink-0",children:"Receipt Uploads"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1 shrink-0",children:"OCR & inventory tracking"}),s.jsx("div",{className:"mt-4 flex-1 flex flex-col min-h-0 overflow-auto",children:s.jsx(Ws,{compact:!0,embed:!0})})]})}),s.jsx(B,{className:"overflow-hidden border border-border/50 bg-card shadow-sm hover:shadow-md transition-all hover:border-muted-foreground/30 h-full flex flex-col min-h-[240px]",children:s.jsxs(Y,{className:"p-5 flex-1 flex flex-col min-h-0",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3 shrink-0",children:[s.jsx("div",{className:"h-10 w-10 shrink-0 rounded-lg bg-muted flex items-center justify-center",children:s.jsx(_t,{className:"h-5 w-5 text-muted-foreground"})}),l&&l.filter(e=>e.is_active).length>0&&s.jsxs(F,{variant:"secondary",className:"text-xs shrink-0",children:[l.filter(e=>e.is_active).length," Active"]})]}),s.jsx("h3",{className:"font-semibold text-base shrink-0",children:"Integrations"}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1 shrink-0",children:"Connect POS & banks"}),s.jsx("div",{className:"flex-1 min-h-[60px]","aria-hidden":!0}),s.jsx("div",{className:"shrink-0 pt-2",children:s.jsx(r,{to:"/dashboard/integrations",className:"inline-block",children:s.jsxs(h,{variant:"default",size:"sm",className:"gap-2",children:[s.jsx(_t,{className:"h-3.5 w-3.5"}),"Manage integrations"]})})})]})})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsxs(B,{children:[s.jsx(W,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(H,{className:"flex items-center gap-2",children:[s.jsx(St,{className:"h-5 w-5"}),"Bank Sync Status"]}),s.jsx(G,{children:"Connected accounts and sync activity"})]}),s.jsxs(h,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>n(!0),children:["Manage",s.jsx(ds,{className:"h-3.5 w-3.5"})]})]})}),s.jsxs(Y,{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{className:"text-center p-3 rounded-lg bg-muted/50",children:[s.jsx("p",{className:"text-2xl font-bold",children:y.total}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Accounts"})]}),s.jsxs("div",{className:"text-center p-3 rounded-lg bg-green-50 dark:bg-green-900/20",children:[s.jsx("p",{className:"text-2xl font-bold text-green-600 dark:text-green-400",children:y.connected}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Auto-Synced"})]}),s.jsxs("div",{className:"text-center p-3 rounded-lg bg-blue-50 dark:bg-blue-900/20",children:[s.jsx("p",{className:"text-2xl font-bold text-blue-600 dark:text-blue-400",children:y.manual}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Manual Upload"})]})]}),u.length>0?s.jsxs("div",{className:"space-y-2",children:[u.slice(0,4).map(e=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:m("h-8 w-8 rounded-full flex items-center justify-center","connected"===e.connection_status?"bg-green-100 dark:bg-green-900/30":"bg-muted"),children:s.jsx(Kt,{className:m("h-4 w-4","connected"===e.connection_status?"text-green-600 dark:text-green-400":"text-muted-foreground")})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium",children:e.account_name}),s.jsx("p",{className:"text-xs text-muted-foreground",children:e.bank_name||"Bank Account"})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:["connected"===e.connection_status?s.jsxs(F,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800",children:[s.jsx(Ut,{className:"h-3 w-3 mr-1"}),"Auto"]}):s.jsxs(F,{variant:"outline",children:[s.jsx(yt,{className:"h-3 w-3 mr-1"}),"Manual"]}),"completed"===e.training_status&&s.jsxs(F,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800",children:[s.jsx(Mt,{className:"h-3 w-3 mr-1"}),"Trained"]})]})]},e.id)),u.length>4&&s.jsxs(h,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>n(!0),children:["View all ",u.length," accounts"]})]}):s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Kt,{className:"h-12 w-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{children:"No bank accounts connected"}),s.jsx(h,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>n(!0),children:"Add Bank Account"})]}),y.lastSynced&&s.jsxs("div",{className:"flex items-center justify-between pt-3 border-t text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Last sync:"}),s.jsx("span",{className:"font-medium",children:et(new Date(y.lastSynced),"MMM dd, yyyy 'at' h:mm a")})]})]})]}),s.jsxs(B,{children:[s.jsx(W,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(H,{
2className:"flex items-center gap-2",children:[s.jsx(Mt,{className:"h-5 w-5"}),"AI Training Status"]}),s.jsx(G,{children:"Transaction categorization intelligence"})]}),s.jsx(r,{to:"/dashboard/data-center/ai-training",children:s.jsxs(h,{variant:"outline",size:"sm",className:"gap-1.5",children:["Train AI",s.jsx(ds,{className:"h-3.5 w-3.5"})]})})]})}),s.jsxs(Y,{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Accounts Trained"}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:[y.trained," of ",y.total]})]}),s.jsx(ue,{value:D,className:"h-3"}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[D,"% of accounts have trained AI categorization"]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ct,{className:"h-4 w-4 text-green-500"}),s.jsx("span",{className:"text-sm font-medium",children:"Categorized"})]}),s.jsx("p",{className:"text-2xl font-bold text-green-600 dark:text-green-400",children:(null==p?void 0:p.categorizedTransactions.toLocaleString())||0}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"transactions"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(dt,{className:"h-4 w-4 text-amber-500"}),s.jsx("span",{className:"text-sm font-medium",children:"Needs Review"})]}),s.jsx("p",{className:"text-2xl font-bold text-amber-600 dark:text-amber-400",children:(null==p?void 0:p.uncategorizedTransactions.toLocaleString())||0}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"transactions"})]})]}),s.jsx("div",{className:"p-4 rounded-lg bg-gradient-to-br from-purple-50 to-blue-50 dark:from-purple-900/20 dark:to-blue-900/20 border border-purple-100 dark:border-purple-800",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"h-8 w-8 rounded-full bg-purple-100 dark:bg-purple-900/50 flex items-center justify-center shrink-0",children:s.jsx(Mt,{className:"h-4 w-4 text-purple-600 dark:text-purple-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium",children:"Train your AI for better accuracy"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Review and categorize transactions to improve automatic categorization. The more you train, the smarter it gets."})]})]})})]})]})]}),(()=>{const e=Math.max(1,Math.ceil(j.length/10)),t=Math.min(i,e-1),a=j.slice(10*t,10*(t+1));return s.jsxs(B,{children:[s.jsx(W,{children:s.jsx("div",{className:"flex items-center justify-between",children:s.jsxs("div",{children:[s.jsxs(H,{className:"flex items-center gap-2",children:[s.jsx(ls,{className:"h-5 w-5"}),"Recent Activity"]}),s.jsx(G,{children:"Latest data imports and sync operations"})]})})}),s.jsxs(Y,{className:"space-y-4",children:[s.jsxs(P,{children:[s.jsx(L,{children:s.jsxs(R,{children:[s.jsx(O,{children:"Date"}),s.jsx(O,{children:"Type"}),s.jsx(O,{children:"Description"}),s.jsx(O,{children:"Platform"}),s.jsx(O,{children:"Status"}),s.jsx(O,{className:"text-right",children:"Records"})]})}),s.jsx(U,{children:a.length>0?a.map(e=>{return s.jsxs(R,{children:[s.jsx($,{className:"text-sm",children:et(new Date(e.date),"MMM dd, yyyy HH:mm")}),s.jsx($,{children:s.jsx(F,{variant:"outline",className:"text-xs gap-1",children:"sync"===e.type?s.jsxs(s.Fragment,{children:[s.jsx(St,{className:"h-3 w-3"}),"Auto Sync"]}):s.jsxs(s.Fragment,{children:[s.jsx(yt,{className:"h-3 w-3"}),"Upload"]})})}),s.jsx($,{className:"text-sm font-medium",children:e.description}),s.jsx($,{children:e.platform?s.jsxs(F,{variant:"secondary",className:"text-xs gap-1",children:[s.jsx(Ut,{className:"h-3 w-3"}),e.platform]}):s.jsx("span",{className:"text-xs text-muted-foreground",children:"Manual"})}),s.jsx($,{children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[I(e.status),(t=e.status,s.jsx(F,{className:m("text-xs",{completed:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",running:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",pending:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",failed:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"}[t]||"bg-muted text-muted-foreground"),children:t}))]})}),s.jsx($,{className:"text-right text-sm",children:e.records?s.jsx("span",{className:"font-medium",children:e.records.toLocaleStr
2ing()}):s.jsx("span",{className:"text-muted-foreground",children:"—"})})]},e.id);var t}):s.jsx(R,{children:s.jsxs($,{colSpan:6,className:"text-center text-muted-foreground py-12",children:[s.jsx(cs,{className:"h-12 w-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{children:"No recent activity"}),s.jsx("p",{className:"text-sm mt-1",children:"Start by uploading data or connecting integrations"})]})})})]}),e>1&&s.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[s.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",10*t+1,"–",Math.min(10*(t+1),j.length)," of ",j.length]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(h,{variant:"outline",size:"sm",disabled:0===t,onClick:()=>c(e=>Math.max(0,e-1)),children:s.jsx(lt,{className:"h-4 w-4"})}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",t+1," of ",e]}),s.jsx(h,{variant:"outline",size:"sm",disabled:t>=e-1,onClick:()=>c(t=>Math.min(e-1,t+1)),children:s.jsx(ot,{className:"h-4 w-4"})})]})]})]})]})})(),s.jsx(We,{open:t,onOpenChange:n,children:s.jsxs(He,{side:"right",className:"sm:max-w-4xl w-full overflow-y-auto",children:[s.jsx(Ge,{children:s.jsx(Ye,{children:"Bank accounts"})}),s.jsx("div",{className:"mt-6",children:s.jsx(zs,{embedded:!0})})]})})]})};function Gs(){const{hash:e}=i();return a.useEffect(()=>{if(e){const t=e.replace("#",""),s=document.getElementById(t);s&&s.scrollIntoView({behavior:"smooth",block:"start"})}},[e]),s.jsx("div",{className:"space-y-10",children:s.jsx(Hs,{})})}export{Gs as DataCenterPage};
3//# sourceMappingURL=DataCenterPage-2_t03PG7.js.map

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.