PageSourceSearch

https://tire-track-loyalty-3a0d7f0a.base44.app/assets/FinancingDetail-SG5wjolN.js

js tire-track-loyalty-3a0d7f0a.base44.app collected 2026-10-03 03:11:58 UTC 52,483 bytes, 5 lines download raw bytes

1import{r as l,j as e,b as h,L as _t}from"./index-DdU35jPJ.js";import{c as bt}from"./index-CtlYlah8.js";import{B as b}from"./button-BfxMpK8P.js";import{I as H}from"./input-cpzcpc5y.js";import{S as Fe,a as Ye,b as Se,c as Pe,d as z}from"./select-CicXJDZx.js";import{h as x}from"./moment-BLMuvzoS.js";import{o as rt,F as jt}from"./financingOptions-CIAN_Bce.js";import{D as Ee,a as We,b as Be,c as Le,d as Ue,e as ze}from"./dialog-gVN6KGjC.js";import{L as $}from"./label-Bnj3FxlL.js";import{C as wt}from"./checkbox-BffsnfzW.js";import{T as tt}from"./triangle-alert-l3tEQyle.js";import{T as xt}from"./textarea-RCbb6gBZ.js";import{R as ht}from"./rotate-ccw-DX9Sab2l.js";import{A as Nt}from"./arrow-left-CoQakR5q.js";import{D as dt}from"./download-BAHbJTmZ.js";import{C as ot}from"./circle-check-big-B9divPaO.js";import{P as vt}from"./play-9cA92DrX.js";import{P as kt}from"./pause-ssDVY6Pp.js";import{S as Qe}from"./square-pen-C50_OfbT.js";import{P as Dt}from"./plus-Bux0BJlB.js";import{U as Ct}from"./upload-tj7WXC4r.js";import{F as Mt}from"./file-text-BIInLmy-.js";import{T as Ft}from"./trash-2-Bi9M4bD6.js";import{U as Yt}from"./user-TFtzTQfw.js";import{U as St}from"./undo-2-DmkaOErH.js";import"./index-gN4drEn4.js";import"./index-Dp3B9jqt.js";import"./clsx-B-dksMZM.js";import"./utils-DCmAa5as.js";import"./bundle-mjs-BTmSotT-.js";import"./index-12QbP6l0.js";import"./index-B1Cc5OXO.js";import"./index-BsvT06Lq.js";import"./index-9bdZCgcr.js";import"./index-BvvUEucZ.js";import"./index-7px4L8n5.js";import"./index-CkK8lBUI.js";import"./index-DGERrSaP.js";import"./chevron-down-DcLGbHop.js";import"./createLucideIcon-DMxicyrC.js";import"./check-BECSssz0.js";import"./chevron-up-w1zviHLx.js";import"./index-BhZ8ej-y.js";import"./index-Bwgqm7vL.js";import"./x-DAruoHhn.js";const Pt=["Zelle","Cashier's Check","Wire","Cash","Other"];function $t({open:c,onClose:n,financing:i,onConfirm:t,saving:u}){const[Y,A]=l.useState(""),[S,K]=l.useState(x().format("YYYY-MM-DD")),[r,m]=l.useState("Zelle"),[E,J]=l.useState("");l.useEffect(()=>{var w;c&&i&&(A((i.weekly_payment||0).toFixed(2)),K(x().format("YYYY-MM-DD")),m(((w=i.payment_methods)==null?void 0:w[0])||"Zelle"),J(""))},[c,i]);const V=()=>{!Y||!S||t({amount:parseFloat(Y),paid_date:S,payment_method:r,note:E.trim()})};if(!i)return null;const Q=(i.weeks_paid||0)+1;return e.jsx(Ee,{open:c,onOpenChange:w=>!w&&n(),children:e.jsxs(We,{className:"sm:max-w-md",children:[e.jsxs(Be,{children:[e.jsxs(Le,{children:["Record Payment — Week ",Q]}),e.jsxs(Ue,{children:["Manually record a payment for ",i.customer_name]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx($,{children:"Amount ($)"}),e.jsx(H,{type:"number",step:"0.01",value:Y,onChange:w=>A(w.target.value),placeholder:"0.00"}),e.jsxs("p",{className:"text-xs text-gray-400",children:["Default weekly payment: $",(i.weekly_payment||0).toFixed(2)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx($,{children:"Date Paid"}),e.jsx(H,{type:"date",value:S,onChange:w=>K(w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx($,{children:"Payment Method"}),e.jsxs(Fe,{value:r,onValueChange:m,children:[e.jsx(Ye,{className:"w-full",children:e.jsx(Se,{})}),e.jsx(Pe,{children:Pt.map(w=>e.jsx(z,{value:w,children:w},w))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx($,{children:"Note (optional)"}),e.jsx(H,{value:E,onChange:w=>J(w.target.value),placeholder:"e.g. Check #1234, reference confirmation..."})]})]}),e.jsxs(ze,{children:[e.jsx(b,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(b,{onClick:V,disabled:u||!Y||!S,className:"bg-emerald-600 hover:bg-emerald-700 text-white",children:u?"Saving...":"Confirm Payment"})]})]})})}const At=["Zelle","Cashier's Check","Wire","Cash","Other"],ct={1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday"},ve=c=>`$${(c||0).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`;function Rt(c){return x(c+"T12:00:00").isoWeekday()}function Tt({open:c,onClose:n,financing:i,payments:t,user:u,onDone:Y}){const A=t||(i==null?void 0:i._payments)||[],[S,K]=l.useState(""),[r,m]=l.useState(!0),[E,J]=l.useState(""),[V,Q]=l.useState(""),[w,ie]=l.useState("Cash"),[le,R]=l.useState(""),[W,fe]=l.useState(""),[te,$e]=l.useState(""),[X,Ae]=l.useState(""),[ye,Re]=l.useState(""),[ke,he]=l.useState(!0),[xe,_e]=l.useState(!1),[be,je]=l.useState(!1);l.useEffect(()=>{var M;if(!c||!i)return;const d=Number(i.financed_amount||0);K(d.toFixed(2)),Ae(Number(i.weekly_payment||0).toFixed(2));const D=A.find(g=>g.week_number===1&&g.status==="completed"),Z=!!D||(i.weeks_paid||0)>=1;if(m(Z),D){J(Number(D.amount||0).toFixed(2)),Q(D.paid_date||i.first_payment_date||x().format("YYYY-MM-DD"));const g=D.notes||"",L=g.indexOf(" — ");ie(L>=0?g.substring(0,L):"Cash"),R(L>=0?g.substring(L+3):"")}else J(Number(i.weekly_payment||0).toFixed(2)),Q(i.first_payment_date||x().format("YYYY-MM-DD")),ie(((M=i.payment_methods)==null?void 0:M[0])||"Cash"),R("");const B=A.filter(g=>g.status==="scheduled").sort((g,L)=>(g.scheduled_date||"").localeCompare(L.scheduled_date||"")).find(g=>g.week_number!==1);if(B!=null&&B.scheduled_date)fe(B.scheduled_date);else{const g=x(i.first_payment_date||x().format("YYYY-MM-DD")),L=i.payment_day_of_week||5,I=g.isoWeekday();let ce=L-I;ce<=0&&(ce+=7),fe(g.add(ce,"days").format("YYYY-MM-DD"))}const ee=Math.max(1,Math.ceil(i.total_weeks||1)-(Z?1:0));$e(String(ee)),he(!0)},[c,i]);const we=l.useMemo(()=>{const d=parseFloat(S)||0,D=r&&parseFloat(E)||0,Z=parseFloat(X)||0,G=parseInt(te,10)||0;if(G<=0)return 0;const B=d-D-Z*(G-1);return Math.round(B*100)/100},[S,r,E,X,te]),re=ke?we:parseFloat(ye)||0,oe=l.useMemo(()=>{const d=[];let D=0;r&&(D=1,d.push({wk:D,date:V,amount:parseFloat(E)||0,status:"completed",method:w}));const Z=parseInt(te,10)||0,G=W?new Date(W+"T00:00:00Z"):null;for(let ee=0;ee<Z&&G;ee++){const M=new Date(G.getTime()+ee*7*864e5),g=ee===Z-1;d.push({wk:++D,date:M.toISOString().slice(0,10),amount:g?re:parseFloat(X)||0,status:"scheduled"})}const B=d.reduce((ee,M)=>ee+(M.amount||0),0);return{rows:d,total:Math.round(B*100)/100}},[r,V,E,w,W,te,X,re]),Ne=Math.abs(oe.total-(parseFloat(S)||0))>=.01,pe=W?Rt(W):5,ge=!!W&&parseInt(te,10)>0&&!Ne&&!xe,Te=async()=>
1{if(!(!ge||!i)){_e(!0);try{const d=[],D=i.id,Z=i.customer_id,G=i.customer_name,B=(u==null?void 0:u.email)||"admin",ee=(u==null?void 0:u.full_name)||(u==null?void 0:u.email)||"Admin";let M=0,g=0;if(r){M=1;const me=Math.round((parseFloat(E)||0)*100)/100;d.push({financing_order_id:D,customer_id:Z,customer_name:G,customer_owner_email:String(i.customer_email||"").toLowerCase().trim(),amount:me,scheduled_date:V,status:"completed",paid_date:V,recorded_by:B,recorded_by_name:ee,recorded_at:new Date().toISOString(),week_number:1,notes:`${w}${le.trim()?` — ${le.trim()}`:""}`}),g=me}const L=parseInt(te,10)||0,I=new Date(W+"T00:00:00Z"),ce=Math.round((parseFloat(X)||0)*100)/100;for(let me=0;me<L;me++){const Ke=new Date(I.getTime()+me*7*864e5),qe=me===L-1;d.push({financing_order_id:D,customer_id:Z,customer_name:G,customer_owner_email:String(i.customer_email||"").toLowerCase().trim(),amount:qe?Math.round(re*100)/100:ce,scheduled_date:Ke.toISOString().slice(0,10),status:"scheduled",week_number:++M})}(await h.entities.FinancingPayment.filter({financing_order_id:D})).length&&await h.entities.FinancingPayment.deleteMany({financing_order_id:D}),await h.entities.FinancingPayment.bulkCreate(d);const De=d.length,Ie=r?1:0,Ce=Math.max(0,De-Ie),He=Math.max(0,(parseFloat(S)||0)-g),Ve=r?V:W,Ze=Ce>0?W:null,Ge={id:Date.now().toString(),timestamp:x().format("YYYY-MM-DD HH:mm:ss")+" CT",user_email:B,user_name:ee,action:"Schedule Rebuilt",details:`Manual rebuild: ${De} payments (${r?"initial + ":""}${L} weekly${L>0?` every ${ct[pe]||"week"}`:""}${Math.abs(re-ce)>=.01?`, final ${ve(re)}`:""}). Total ${ve(oe.total)}.`};await h.entities.FinancingOrder.update(D,{weekly_payment:ce,total_weeks:De,weeks_paid:Ie,weeks_remaining:Ce,total_collected:g,remaining_balance:He,financed_amount:Math.round((parseFloat(S)||0)*100)/100,first_payment_date:Ve,next_payment_date:Ze,payment_day_of_week:pe<=5?pe:5,status:Ce<=0?"completed":"active",payment_status:"current",missed_payments:0,audit_log:[...i.audit_log||[],Ge]}),Y&&Y(),n&&n()}finally{_e(!1),je(!1)}}};return i?e.jsx(Ee,{open:c,onOpenChange:d=>{!d&&!xe&&n&&n()},children:e.jsxs(We,{className:"sm:max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Be,{children:[e.jsx(Le,{children:"Rebuild Payment Schedule"}),e.jsxs(Ue,{children:["Manually define the payment plan for ",i.customer_name,". This replaces the entire existing schedule."]})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx($,{children:"Total Financed Amount ($)"}),e.jsx(H,{type:"number",step:"0.01",value:S,onChange:d=>K(d.target.value)}),e.jsx("p",{className:"text-xs text-gray-400",children:"The full amount to be repaid across all payments."})]}),e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-3 bg-gray-50/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{checked:r,onCheckedChange:d=>m(!!d),id:"inc-init"}),e.jsx($,{htmlFor:"inc-init",className:"font-semibold cursor-pointer",children:"Include initial / signing-day payment (Week 1)"})]}),r&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Initial Amount ($)"}),e.jsx(H,{type:"number",step:"0.01",value:E,onChange:d=>J(d.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Date Received"}),e.jsx(H,{type:"date",value:V,onChange:d=>Q(d.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Method"}),e.jsxs(Fe,{value:w,onValueChange:ie,children:[e.jsx(Ye,{className:"w-full",children:e.jsx(Se,{})}),e.jsx(Pe,{children:At.map(d=>e.jsx(z,{value:d,children:d},d))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Note (optional)"}),e.jsx(H,{value:le,onChange:d=>R(d.target.value),placeholder:"e.g. signing day"})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-3",children:[e.jsx("p",{className:"font-semibold text-sm text-gray-700",children:"Recurring Weekly Schedule"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"First Recurring Date"}),e.jsx(H,{type:"date",value:W,onChange:d=>fe(d.target.value)}),e.jsx("p",{className:"text-xs text-gray-400",children:W?`Every ${ct[pe]||"—"}`:""})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Number of Recurring Weeks"}),e.jsx(H,{type:"number",min:"1",value:te,onChange:d=>$e(d.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Weekly Amount ($)"}),e.jsx(H,{type:"number",step:"0.01",value:X,onChange:d=>Ae(d.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx($,{className:"text-xs",children:"Final Week Amount ($)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(H,{type:"number",step:"0.01",value:ke?we.toFixed(2):ye,disabled:ke,onChange:d=>{he(!1),Re(d.target.value)}}),e.jsx(b,{size:"sm",variant:"outline",type:"button",onClick:()=>he(!0),children:"Auto"})]})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-gray-200 overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-2 bg-gray-50 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500",children:["Preview — ",oe.rows.length," payments"]}),e.jsxs("span",{className:"text-sm font-bold text-gray-800",children:["Total ",ve(oe.total)]})]}),e.jsx("div",{className:"max-h-44 overflow-y-auto",children:e.jsx("table",{className:"w-full text-xs",children:e.jsx("tbody",{className:"divide-y divide-gray-50",children:oe.rows.map(d=>e.jsxs("tr",{className:d.status==="completed"?"bg-emerald-50/50":"",children:[e.jsxs("td",{className:"px-4 py-1.5 font-medium text-gray-700",children:["Wk ",d.wk,d.status==="completed"?" · paid":""]}),e.jsx("td",{className:"px-4 py-1.5 text-gray-600",children:d.date?x(d.date+"T00:00:00Z").format("ddd, MMM D, YYYY"):"—"}),e.jsx("td",{className:"px-4 py-1.5 text-right font-semibold text-gray-800",children:ve(d.amount)})]},d.wk))})})})]}),Ne&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg bg-amber-50 border border-amber-200 px-3 py-2 text-xs text-amber-800",children:[e.jsx(tt,{className:"w-4 h-4 shrink-0 mt-0.5"}),e.jsxs("span",{children:["Schedule total (",ve(oe.total),") does not match the Total Financed Amount (",ve(parseFloat(S)||0),"). Adjust the final-week amount or weekly amount so they match."]})]})]}),e.jsxs(ze,{children:[e.jsx(b,{variant:"outline",onClick:()=>n&&n(),disabled:xe,children:"Cancel"}),be?e.jsx(b,{onClick:Te,disabled:!ge,className:"bg-red-600 hover:bg-red-700 text-white",children:xe?"Rebuilding...":`Confirm — Replace All ${oe.rows.length} Payments`}):e.jsx(b,{onClick:()=>je(!0),disabled:!ge,className:"bg-[#0073ea] hover:bg-[#0060b9] text-white",children:"Rebuild Schedule"})]})]})}):null}const It=c=>
1`$${(c||0).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`;function Ot({open:c,onClose:n,payment:i,onConfirm:t,saving:u}){const[Y,A]=l.useState(x().format("YYYY-MM-DD")),[S,K]=l.useState("");if(l.useEffect(()=>{c&&(A(x().format("YYYY-MM-DD")),K(""))},[c,i==null?void 0:i.id]),!i)return null;const r=()=>t({bounce_date:Y,reason:S.trim()});return e.jsx(Ee,{open:c,onOpenChange:m=>!m&&n(),children:e.jsxs(We,{className:"sm:max-w-md",children:[e.jsxs(Be,{children:[e.jsx("div",{className:"mx-auto w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-3",children:e.jsx(tt,{className:"w-6 h-6 text-red-600"})}),e.jsx(Le,{className:"text-center",children:"Mark Payment Bounced"}),e.jsxs(Ue,{className:"text-center",children:["Week ",i.week_number," payment of ",It(i.amount)," will be marked as returned / NSF."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx($,{htmlFor:"bounce-date",children:"Date Bounced"}),e.jsx(H,{id:"bounce-date",type:"date",value:Y,max:x().format("YYYY-MM-DD"),onChange:m=>A(m.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx($,{htmlFor:"bounce-reason",children:"Reason (optional)"}),e.jsx(xt,{id:"bounce-reason",value:S,onChange:m=>K(m.target.value),placeholder:"e.g. ACH returned, check bounced, NSF...",className:"resize-none h-20"})]})]}),e.jsxs(ze,{children:[e.jsx(b,{variant:"outline",onClick:n,disabled:u,children:"Cancel"}),e.jsx(b,{onClick:r,disabled:u||!Y,className:"bg-red-600 hover:bg-red-700 text-white",children:u?"Saving...":"Confirm Bounce"})]})]})})}const Et=["Cash","Zelle","Wire","Cashier's Check","Card","Other"],mt=c=>`$${(c||0).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`;function Wt({open:c,onClose:n,payment:i,weeklyAmount:t,onConfirm:u,saving:Y}){const[A,S]=l.useState(x().format("YYYY-MM-DD")),[K,r]=l.useState(""),[m,E]=l.useState("Cash"),[J,V]=l.useState("");if(l.useEffect(()=>{c&&(S(x().format("YYYY-MM-DD")),r(""),E("Cash"),V(""))},[c,i==null?void 0:i.id]),!i)return null;const Q=t||i.amount||0,w=parseFloat(K)||0,ie=Q+w,le=()=>u({paid_date:A,recharge_fee:w,total_collected:ie,payment_method:m,note:J.trim()});return e.jsx(Ee,{open:c,onOpenChange:R=>!R&&n(),children:e.jsxs(We,{className:"sm:max-w-md",children:[e.jsxs(Be,{children:[e.jsx("div",{className:"mx-auto w-12 h-12 bg-emerald-100 rounded-full flex items-center justify-center mb-3",children:e.jsx(ht,{className:"w-6 h-6 text-emerald-600"})}),e.jsx(Le,{className:"text-center",children:"Recharge Bounced Payment"}),e.jsxs(Ue,{className:"text-center",children:["Record a replacement payment for Week ",i.week_number," (",mt(Q)," base)."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx($,{htmlFor:"recharge-date",children:"Date Collected"}),e.jsx(H,{id:"recharge-date",type:"date",value:A,max:x().format("YYYY-MM-DD"),onChange:R=>S(R.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx($,{htmlFor:"recharge-fee",children:"Recharge / NSF Fee"}),e.jsx(H,{id:"recharge-fee",type:"number",min:"0",step:"0.01",inputMode:"decimal",value:K,onChange:R=>r(R.target.value),placeholder:"0.00"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx($,{children:"Payment Method"}),e.jsxs(Fe,{value:m,onValueChange:E,children:[e.jsx(Ye,{className:"w-full",children:e.jsx(Se,{})}),e.jsx(Pe,{children:Et.map(R=>e.jsx(z,{value:R,children:R},R))})]})]}),e.jsxs("div",{className:"rounded-lg bg-gray-50 border border-gray-200 p-3 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Total Amount Collected"}),e.jsx("span",{className:"text-lg font-bold text-emerald-700",children:mt(ie)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx($,{htmlFor:"recharge-note",children:"Note (optional)"}),e.jsx(xt,{id:"recharge-note",value:J,onChange:R=>V(R.target.value),placeholder:"e.g. replacement check #1234...",className:"resize-none h-16"})]})]}),e.jsxs(ze,{children:[e.jsx(b,{variant:"outline",onClick:n,disabled:Y,children:"Cancel"}),e.jsx(b,{onClick:le,disabled:Y||!A,className:"bg-emerald-600 hover:bg-emerald-700 text-white",children:Y?"Saving...":"Record Recharge"})]})]})})}const k=c=>
1`$${(c||0).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Xe={1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday"};function pt(c,n){const i=x(c),t=i.isoWeekday();let u=n-t;return u<0&&(u+=7),i.add(u,"days").format("YYYY-MM-DD")}function ut(c,n){const i=x(c).add(7,"days");return pt(i.format("YYYY-MM-DD"),n)}function et(c){const n=x(c);for(;n.day()===0||n.day()===6;)n.add(1,"day");return n.format("YYYY-MM-DD")}function Pa(){var nt,it,lt;const c=new URLSearchParams(window.location.search).get("id"),[n,i]=l.useState(null),[t,u]=l.useState(null),[Y,A]=l.useState([]),[S,K]=l.useState(!0),[r,m]=l.useState(!1),[E,J]=l.useState(""),[V,Q]=l.useState(!1),[w,ie]=l.useState(!1),[le,R]=l.useState(""),[W,fe]=l.useState(!1),[te,$e]=l.useState("financing_agreement"),[X,Ae]=l.useState("overview"),[ye,Re]=l.useState(!1),[ke,he]=l.useState(!1),[xe,_e]=l.useState(""),[be,je]=l.useState(null),[we,re]=l.useState(""),[oe,Ne]=l.useState(null),[pe,ge]=l.useState(!1),[Te,d]=l.useState(!1),[D,Z]=l.useState(null),[G,B]=l.useState(null);l.useEffect(()=>{(async()=>{try{const s=await h.auth.me();if(i(s),!c)return;const[o,y]=await Promise.all([h.entities.FinancingOrder.filter({id:c}),h.entities.FinancingPayment.filter({financing_order_id:c},"-scheduled_date",200)]);o[0]&&(u(o[0]),R(o[0].next_payment_date||"")),A(y)}finally{K(!1)}})()},[c]);const M=["[email protected]","[email protected]","[email protected]","[email protected]"].includes((nt=n==null?void 0:n.email)==null?void 0:nt.toLowerCase()),g=((it=n==null?void 0:n.email)==null?void 0:it.toLowerCase())==="[email protected]",L=async()=>{var a,s,o,y;if(!ye){Re(!0);try{let f=null;if(t.order_id){const j=await h.entities.Invoice.filter({order_id:t.order_id});j[0]&&(f=j[0].id)}let N,T;if(f){const j=await h.functions.invoke("generateInvoicePDF",{invoice_id:f});N=(a=j.data)==null?void 0:a.pdf,T=(s=j.data)==null?void 0:s.filename}else{const j=await h.functions.invoke("generateInvoicePDF",{invoice_id:null,financing_order:{id:t.id,financing_option:t.financing_option,customer_name:t.customer_name,customer_owner_email:String(t.customer_email||"").toLowerCase().trim(),customer_phone:t.customer_phone,customer_email:t.customer_email,customer_id:t.customer_id,items:t.items,additional_services:t.additional_services,original_amount:t.original_amount,financed_amount:t.financed_amount,weekly_payment:t.weekly_payment,total_weeks:t.total_weeks,truck_number:t.truck_number,trailer_number:t.trailer_number,submitted_by_rep_name:t.submitted_by_rep_name,installation_date:t.installation_date,first_payment_date:t.first_payment_date}});N=(o=j.data)==null?void 0:o.pdf,T=(y=j.data)==null?void 0:y.filename}if(!N){alert("Could not generate invoice PDF.");return}const v=atob(N),C=new Uint8Array(v.length);for(let j=0;j<v.length;j++)C[j]=v.charCodeAt(j);const q=new Blob([C],{type:"application/pdf"}),U=URL.createObjectURL(q),P=document.createElement("a");P.href=U,P.download=T||`Financing_Invoice_${t.customer_name}.pdf`,P.click(),URL.revokeObjectURL(U)}finally{Re(!1)}}},I=async(a,s)=>{const o={id:Date.now().toString(),timestamp:x().format("YYYY-MM-DD HH:mm:ss")+" CT",user_email:n.email,user_name:n.full_name||n.email,action:a,details:s};return[...t.audit_log||[],o]},ce=async a=>{if(!t||r)return;m(!0);const s=x(),o=(t.weeks_paid||0)+1,y=t.total_weeks||52.143,f=Math.max(0,y-o),N=(t.total_collected||0)+a.amount,T=Math.max(0,(t.financed_amount||0)-N),v=f<=0,C=t.payment_day_of_week,q=t.next_payment_date||a.paid_date,U=C?ut(q,C):et(x(a.paid_date).add(7,"days").format("YYYY-MM-DD")),P=`Week ${o} payment of ${k(a.amount)} via ${a.payment_method}${a.note?` — ${a.note}`:""}`,j=await I("Payment Marked",P),p=await h.entities.FinancingOrder.update(t.id,{weeks_paid:o,weeks_remaining:f,total_collected:N,remaining_balance:T,next_payment_date:v?null:U,status:v?"completed":"active",payment_status:"current",missed_payments:0,commission_status:v?"earned":t.commission_status||"pending",audit_log:j}),O=`${a.payment_method}${a.note?` — ${a.note}`:""}`,F=Y.find(se=>se.week_number===o&&!se.paid_date);F?await h.entities.FinancingPayment.update(F.id,{amount:a.amount,paid_date:a.paid_date,status:"completed",notes:O,recorded_by:n.email,recorded_by_name:n.full_name||n.email,recorded_at:s.toISOString()}):await h.entities.FinancingPayment.create({financing_order_id:t.id,customer_id:t.customer_id,customer_name:t.customer_name,customer_owner_email:String(t.customer_email||"").toLowerCase().trim(),amount:a.amount,scheduled_date:t.
1next_payment_date||a.paid_date,paid_date:a.paid_date,status:"completed",week_number:o,notes:O,recorded_by:n.email,recorded_by_name:n.full_name||n.email,recorded_at:s.toISOString()}),u(p);const ae=await h.entities.FinancingPayment.filter({financing_order_id:c},"-scheduled_date",200);A(ae),m(!1),ge(!1)},at=async a=>{if(!a||r||!window.confirm(`Reverse the Week ${a.week_number} payment of ${k(a.amount)}?
2
3This will reduce weeks paid, deduct from total collected, and re-activate the schedule.`))return;m(!0);const s=Math.max(0,(t.weeks_paid||0)-1),o=Math.max(0,(t.total_collected||0)-(a.amount||0)),y=Math.max(0,(t.financed_amount||0)-o),f=t.total_weeks||52.143,N=Math.max(0,f-s),T=a.scheduled_date||t.next_payment_date,v=`Week ${a.week_number} payment of ${k(a.amount)} reversed by ${n.full_name||n.email}`,C=await I("Payment Reversed",v),q=await h.entities.FinancingOrder.update(t.id,{weeks_paid:s,weeks_remaining:N,total_collected:o,remaining_balance:y,next_payment_date:T,status:"active",payment_status:t.status==="completed"?"current":t.payment_status,commission_status:N>0&&t.commission_status==="earned"?"pending":t.commission_status,audit_log:C});await h.entities.FinancingPayment.delete(a.id),u(q);const U=await h.entities.FinancingPayment.filter({financing_order_id:c},"-scheduled_date",200);A(U),m(!1)},De=async(a,{bounce_date:s,reason:o}={})=>{if(!a||r)return;m(!0);const y=s||x().format("YYYY-MM-DD"),f=Math.max(0,(t.weeks_paid||0)-1),N=Math.max(0,(t.total_collected||0)-(a.amount||0)),T=Math.max(0,(t.financed_amount||0)-N),v=t.total_weeks||52.143,C=Math.max(0,v-f),q=a.scheduled_date||t.next_payment_date,U=a.notes||"",P=U.indexOf(" — "),j=P>=0?U.substring(0,P):"",p=`Week ${a.week_number} payment of ${k(a.amount)} BOUNCED/RETURNED on ${y}${o.trim()?` — ${o.trim()}`:""}`,O=await I("Payment Bounced",p),F=await h.entities.FinancingOrder.update(t.id,{weeks_paid:f,weeks_remaining:C,total_collected:N,remaining_balance:T,next_payment_date:q,status:"active",payment_status:"late",missed_payments:(t.missed_payments||0)+1,audit_log:O});await h.entities.FinancingPayment.create({financing_order_id:t.id,customer_id:t.customer_id,customer_name:t.customer_name,customer_owner_email:String(t.customer_email||"").toLowerCase().trim(),amount:a.amount,scheduled_date:a.scheduled_date,paid_date:y,status:"bounced",week_number:a.week_number,notes:`${j?j+" — ":""}BOUNCED${o.trim()?`: ${o.trim()}`:""}`,recorded_by:n.email,recorded_by_name:n.full_name||n.email,recorded_at:x().toISOString()}),u(F);const ae=await h.entities.FinancingPayment.filter({financing_order_id:c},"-scheduled_date",200);A(ae),m(!1)},Ie=async(a,{paid_date:s,recharge_fee:o,total_collected:y,payment_method:f,note:N}={})=>{if(!a||r)return;m(!0);const T=parseFloat(o)||0,v=parseFloat(y)||(a.amount||0)+T,C=a.amount||t.weekly_payment||0,q=x(),U=Math.max(0,t.weeks_paid||0)+1,P=t.total_weeks||52.143,j=Math.max(0,P-U),p=(t.total_collected||0)+v,O=Math.max(0,(t.financed_amount||0)-(p-T)),F=j<=0,ae=t.payment_day_of_week,se=t.next_payment_date||s,de=ae?ut(se,ae):et(x(s).add(7,"days").format("YYYY-MM-DD")),Oe=`Week ${a.week_number} RECHARGED: ${k(v)} via ${f} (${k(C)} + ${k(T)} fee)${N?` — ${N}`:""}`,_=await I("Payment Recharged",Oe),ne=await h.entities.FinancingOrder.update(t.id,{weeks_paid:U,weeks_remaining:j,total_collected:p,remaining_balance:O,next_payment_date:F?null:de,status:F?"completed":"active",payment_status:"current",missed_payments:Math.max(0,(t.missed_payments||0)-1),commission_status:F?"earned":t.commission_status||"pending",audit_log:_}),ue=`${f}${N?` — ${N}`:""}`;await h.entities.FinancingPayment.create({financing_order_id:t.id,customer_id:t.customer_id,customer_name:t.customer_name,customer_owner_email:String(t.customer_email||"").toLowerCase().trim(),amount:C,recharge_fee:T,scheduled_date:a.scheduled_date,paid_date:s,status:"completed",week_number:a.week_number,notes:ue,recorded_by:n.email,recorded_by_name:n.full_name||n.email,recorded_at:q.toISOString()}),u(ne);const Me=await h.entities.FinancingPayment.filter({financing_order_id:c},"-scheduled_date",200);A(Me),m(!1)},Ce=async()=>
3{if(!le||r)return;m(!0);const a=t.payment_day_of_week,s=a?pt(le,a):et(le),o=await I("Payment Date Changed",`Next payment rescheduled to ${s} (${a?Xe[a]:"business day"}) — was ${t.next_payment_date||"none"}`),y=await h.entities.FinancingOrder.update(t.id,{next_payment_date:s,audit_log:o});u(y),ie(!1),m(!1)},He=async()=>{if(r)return;m(!0);const a=t.status==="paused"?"active":"paused",s=await I(a==="paused"?"Financing Paused":"Financing Resumed",`Status changed to ${a}`),o=await h.entities.FinancingOrder.update(t.id,{status:a,audit_log:s});u(o),m(!1)},Ve=async()=>{if(r)return;m(!0);const a=await I("Financing Activated","Documents signed — agreement activated, weekly collections started"),s=await h.entities.FinancingOrder.update(t.id,{status:"active",audit_log:a});u(s),m(!1)},Ze=async()=>{if(r||!window.confirm(`Mark ${t.customer_name} as DEFAULTED? This stops the active schedule.`))return;m(!0);const a=await I("Financing Defaulted","Agreement manually marked as defaulted"),s=await h.entities.FinancingOrder.update(t.id,{status:"defaulted",audit_log:a});u(s),m(!1)},Ge=async()=>{if(r||!window.confirm(`Mark ${t.customer_name} as COMPLETED (paid off)?`))return;m(!0);const a=await I("Financing Completed","Agreement manually marked as completed"),s=await h.entities.FinancingOrder.update(t.id,{status:"completed",commission_status:t.commission_status==="paid"?"paid":"earned",audit_log:a});u(s),m(!1)},me=async()=>{if(!E.trim()||r)return;m(!0);const a=t.admin_notes?t.admin_notes+`
4
5`:"",s=x().format("MM/DD/YY h:mm A")+" CT",o=a+`[${s} - ${n.full_name||n.email}] ${E.trim()}`,y=await I("Note Added",E.trim()),f=await h.entities.FinancingOrder.update(t.id,{admin_notes:o,audit_log:y});u(f),J(""),Q(!1),m(!1)},Ke=async a=>{if(!a||W)return;fe(!0);const{file_url:s}=await h.integrations.Core.UploadFile({file:a}),o={id:Date.now().toString(),doc_type:te,file_url:s,file_name:a.name,uploaded_by:n.email,uploaded_by_name:n.full_name||n.email,uploaded_at:x().format("YYYY-MM-DD HH:mm")+" CT"},y=await I("Document Uploaded",`${te}: ${a.name}`),f=await h.entities.FinancingOrder.update(t.id,{documents:[...t.documents||[],o],audit_log:y});u(f),fe(!1)},qe=a=>{je(a.id),re(a.doc_type)},gt=async()=>{var y;if(!be||r)return;m(!0);const a=(t.documents||[]).map(f=>f.id===be?{...f,doc_type:we}:f),s=await I("Document Edited",`Changed type of "${(y=a.find(f=>f.id===be))==null?void 0:y.file_name}" to ${we.replace(/_/g," ")}`),o=await h.entities.FinancingOrder.update(t.id,{documents:a,audit_log:s});u(o),je(null),re(""),m(!1)},ft=async a=>{const s=(t.documents||[]).find(N=>N.id===a);if(!s||r)return;m(!0);const o=(t.documents||[]).filter(N=>N.id!==a),y=await I("Document Deleted",`Deleted "${s.file_name}" (${s.doc_type.replace(/_/g," ")})`),f=await h.entities.FinancingOrder.update(t.id,{documents:o,audit_log:y});u(f),Ne(null),m(!1)};if(S)return e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx("div",{className:"w-8 h-8 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin"})});if(!t)return e.jsx("div",{className:"p-8 text-gray-500",children:"Financing agreement not found."});const Je=t.total_weeks||52.143,st=Math.min(100,Math.round((t.weeks_paid||0)/Je*100));return t.status,e.jsx("div",{className:"min-h-screen bg-gray-50 p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(_t,{to:bt("FinancingDashboard"),
5children:e.jsx(b,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(Nt,{className:"w-5 h-5"})})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:t.customer_name}),e.jsxs("p",{className:"text-gray-500 text-sm",children:["Financing Agreement • ",t.customer_phone]}),t.financing_option&&e.jsx("span",{className:`mt-1 inline-block text-xs px-2 py-0.5 rounded-full font-semibold ${((lt=jt[t.financing_option])==null?void 0:lt.color)||"bg-gray-100 text-gray-700"}`,children:rt(t.financing_option)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{variant:"outline",onClick:L,disabled:ye,className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4"})," ",ye?"Loading...":"Invoice"]}),M&&!g&&(t.status==="pending_documents"?e.jsxs(b,{className:"bg-emerald-600 hover:bg-emerald-700 text-white flex items-center gap-2",onClick:Ve,disabled:r,children:[e.jsx(ot,{className:"w-4 h-4"})," Activate — Documents Signed"]}):e.jsxs(e.Fragment,{children:[(t.status==="active"||t.status==="paused")&&e.jsx(b,{variant:"outline",onClick:He,disabled:r,className:"flex items-center gap-2",children:t.status==="paused"?e.jsxs(e.Fragment,{children:[e.jsx(vt,{className:"w-4 h-4"})," Resume"]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4"})," Pause"]})}),t.status!=="completed"&&t.status!=="defaulted"&&e.jsxs(b,{className:"bg-emerald-600 hover:bg-emerald-700 text-white flex items-center gap-2",onClick:()=>ge(!0),disabled:r||t.status==="paused",children:[e.jsx(ot,{className:"w-4 h-4"})," Mark Payment"]})]}))]})]}),e.jsxs("div",{className:"flex gap-2 mb-6",children:[e.jsx("span",{className:`px-3 py-1 rounded-full text-sm font-semibold ${t.status==="active"?"bg-emerald-100 text-emerald-800":t.status==="completed"?"bg-blue-100 text-blue-800":t.status==="pending_documents"?"bg-slate-200 text-slate-700":t.status==="defaulted"?"bg-red-100 text-red-800":"bg-amber-100 text-amber-800"}`,children:t.status==="pending_documents"?"pending documents":t.status}),e.jsx("span",{className:`px-3 py-1 rounded-full text-sm font-semibold ${t.payment_status==="current"?"bg-emerald-100 text-emerald-800":"bg-red-100 text-red-800"}`,children:t.payment_status}),e.jsxs("span",{className:"px-3 py-1 rounded-full text-sm font-semibold bg-violet-100 text-violet-800",children:["Commission: ",t.commission_status||"pending"]})]}),M&&!g&&t.status!=="pending_documents"&&t.status!=="cancelled"&&e.jsxs("div",{className:"flex gap-2 mb-6",children:[t.status!=="defaulted"&&e.jsx("button",{onClick:Ze,disabled:r,className:"text-xs font-semibold text-red-600 hover:text-red-800 px-3 py-1.5 rounded-lg border border-red-200 hover:bg-red-50 transition-colors disabled:opacity-50",children:"Mark Defaulted"}),t.status!=="completed"&&e.jsx("button",{onClick:Ge,disabled:r,className:"text-xs font-semibold text-blue-600 hover:text-blue-800 px-3 py-1.5 rounded-lg border border-blue-200 hover:bg-blue-50 transition-colors disabled:opacity-50",children:"Mark Completed"})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-6 shadow-sm border border-gray-100 mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Payment Progress"}),e.jsxs("span",{className:"text-sm font-bold text-[#0073ea]",children:[st,"% Complete"]})]}),e.jsx("div",{className:"w-full bg-gray-100 rounded-full h-4 mb-2",children:e.jsx("div",{className:"bg-[#0073ea] h-4 rounded-full transition-all duration-500",style:{width:`${st}%`}})}),e.jsxs("div",{className:"flex justify-between text-xs text-gray-500",children:[e.jsxs("span",{children:["Paid: ",t.weeks_paid||0," / ",Math.ceil(Je)," weeks"]}),e.jsxs("span",{children:[Math.ceil(Math.max(0,Je-(t.weeks_paid||0)))," weeks remaining"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6",children:[{label:"Cash Price",value:k(t.original_amount),color:"text-gray-800"},...t.down_payment>0?[{label:"Down Payment",value:k(t.down_payment),color:"text-emerald-700"}]:[],...t.down_payment>0?[{label:"Amount Financed Base",value:k(t.amount_to_finance||t.original_amount-t.down_payment),color:"text-gray-700"}]:[],{label:"Total Financed",value:k(t.financed_amount),color:"text-violet-700"},{label:"Weekly Payment",value:k(t.weekly_payment),color:"text-[#0073ea]"},{label:"Remaining Balance",value:k(t.remaining_balance),color:"text-amber-600"}].map(({label:a,value:s,color:o})=>e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-gray-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-gray-400 mb-1",children:a}),e.jsx("p",{className:`text-xl font-bold ${o}`,children:s})]},a))}),e.jsx("div",{className:"flex gap-2 mb-4 bg-white rounded-xl p-1 shadow-sm border border-gray-100 w-fit",children:["overview","payments","documents","audit"].map(a=>e.jsx("button",{onClick:()=>Ae(a),className:`px-4 py-2 rounded-lg text-sm font-medium capitalize transition-all ${X===a?"bg-[#0073ea] text-white":"text-gray-500 hover:text-gray-700"}`,children:a},a))}),X==="overview"&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-white rounded-2xl p-6 shadow-sm border border-gray-100",children:[e.jsx("h3",{className:"font-bold text-gray-800 mb
5-4",children:"Agreement Details"}),e.jsxs("div",{className:"space-y-3 text-sm",children:[[["Sales Rep",t.submitted_by_rep_name],...t.down_payment>0?[["Down Payment Collected",k(t.down_payment)]]:[],...t.down_payment>0?[["Amount Financed Base",k(t.amount_to_finance||t.original_amount-t.down_payment)]]:[],["Payment Day",t.payment_day_of_week?`Every ${Xe[t.payment_day_of_week]}`:"—"],["First Payment",t.first_payment_date?x(t.first_payment_date).format("dddd, MMM D, YYYY"):"—"],["Next Payment",t.next_payment_date?x(t.next_payment_date).format("dddd, MMM D, YYYY"):"—"],["Installation Date",t.installation_date?x(t.installation_date).format("MMM D, YYYY"):"—"],["Financing Plan",rt(t.financing_option)],["Total Collected",k(t.total_collected)]].map(([a,s])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:a}),e.jsx("span",{className:"font-medium text-gray-800",children:s||"—"})]},a)),e.jsxs("div",{className:"flex justify-between items-start pt-1",children:[e.jsx("span",{className:"text-gray-500",children:"Commission"}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-medium text-gray-800",children:k(t.commission_amount)}),t.commission_status==="paid"?e.jsx("span",{className:"text-xs text-blue-600 font-semibold",children:"💰 Paid to rep"}):M?e.jsx("button",{onClick:()=>he(!0),className:"text-xs text-emerald-600 font-semibold hover:underline mt-0.5",children:t.commission_status==="earned"?"✅ Earned — Mark Paid":"⏳ Pending — Mark Paid"}):e.jsx("span",{className:"text-xs text-amber-600 font-semibold",children:t.commission_status==="earned"?"✅ Earned":"⏳ Pending"})]})]}),ke&&M&&e.jsxs("div",{className:"mt-3 p-4 bg-emerald-50 rounded-xl border border-emerald-200 space-y-2",children:[e.jsxs("p",{className:"text-sm font-semibold text-emerald-800",children:["Confirm paying ",k(t.commission_amount)," commission to ",t.submitted_by_rep_name]}),e.jsx("input",{type:"text",placeholder:"Optional note (e.g. Zelle, check #1234...)",value:xe,onChange:a=>_e(a.target.value),className:"w-full border border-emerald-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-400 bg-white"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{size:"sm",disabled:r,onClick:async()=>{m(!0);const a=await I("Commission Paid",`Commission of ${k(t.commission_amount)} marked as paid to ${t.submitted_by_rep_name}${xe?` — Note: ${xe}`:""}`),s=await h.entities.FinancingOrder.update(t.id,{commission_status:"paid",audit_log:a});u(s),he(!1),_e(""),m(!1)},className:"bg-emerald-600 hover:bg-emerald-700 text-white",children:"✓ Confirm Paid"}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>{he(!1),_e("")},children:"Cancel"})]})]})]}),M&&!g&&e.jsxs("div",{className:"mt-5 pt-4 border-t border-gray-100",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Change Next Payment Date"}),w?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{type:"date",value:le,onChange:a=>R(a.target.value),className:"flex-1"}),e.jsx(b,{size:"sm",onClick:Ce,disabled:r,className:"bg-[#0073ea] text-white",children:"Save"}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>ie(!1),children:"Cancel"})]}):e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>ie(!0),className:"flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"})," Edit Date"]})]})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-6 shadow-sm border border-gray-100",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-bold text-gray-800",children:"Notes"}),M&&!g&&!V&&e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>Q(!0),className:"flex items-center gap-1",children:[e.jsx(Dt,{className:"w-3 h-3"})," Add Note"]})]}),V&&e.jsxs("div",{className:"mb-4 space-y-2",children:[e.jsx("textarea",{value:E,onChange:a=>J(a.target.value),placeholder:"Enter note...",className:"w-full border border-gray-200 rounded-lg p-3 text-sm resize-none h-24 focus:ring-2 focus:ring-[#0073ea] focus:border-transparent outline-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{size:"sm",onClick:me,disabled:r,className:"bg-[#0073ea] text-white",children:"Save Note"}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>Q(!1),children:"Cancel"})]})]}),e.jsx("div",{className:"text-sm text-gray-600 whitespace-pre-wrap max-h-64 overflow-y-auto",children:t.admin_notes||e.jsx("span",{className:"text-gray-400 italic",children:"No notes yet."})})]})]}),X==="payments"&&(()=>{const a=Math.ceil(t.total_weeks||52.143),s=t.weekly_payment||0,o=t.first_payment_date,y=a>1?Math.round((t.financed_amount-s*(a-1))*100)/100:s,f=t.payment_day_of_week,N=Array.from({length:a},(T,v)=>{const C=v+1;let P=(Y||[]).filter(_=>_.week_number===C).map(_=>
5_.scheduled_date).filter(Boolean).sort()[0]||null;if(!P&&o)if(f)if(v===0)P=x(o).format("YYYY-MM-DD");else{const _=x(o),ne=_.isoWeekday();let ue=f-ne;ue<=0&&(ue+=7),P=_.add(ue+(v-1)*7,"days").format("YYYY-MM-DD")}else{let _=x(o).add(v*7,"days");for(;_.day()===0||_.day()===6;)_.add(1,"day");P=_.format("YYYY-MM-DD")}const j=x().format("YYYY-MM-DD"),O=(Y||[]).filter(_=>_.week_number===C).filter(_=>_.status==="completed"||_.status==="bounced").sort((_,ne)=>{const ue=_.recorded_at?new Date(_.recorded_at).getTime():0,Me=ne.recorded_at?new Date(ne.recorded_at).getTime():0;return ue-Me}),F=O.filter(_=>_.status==="completed").length,ae=O.filter(_=>_.status==="bounced").length,se=F-ae;let de="scheduled";return O.length?de=se>=1?"completed":ae>0?"bounced":"scheduled":P&&P<j&&(de=C<=(t.weeks_paid||0)?"completed":"missed"),{weekNum:C,scheduledDate:P,realPayments:O,status:de,scheduledAmount:C===a?y:s}});return x().format("YYYY-MM-DD"),e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-gray-800",children:"Full Payment Schedule"}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:[t.financing_option?`Option ${t.financing_option} • `:"",a," weeks total • ",k(s),"/week",f?` • Paid every ${Xe[f]}`:"",Math.abs(y-s)>=.01?` • Final: ${k(y)}`:""]})]}),e.jsxs("div",{className:"flex gap-3 items-center text-xs font-medium",children:[M&&!g&&e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>d(!0),disabled:r,className:"flex items-center gap-1 h-7 text-xs",children:[e.jsx(Qe,{className:"w-3 h-3"})," Rebuild Schedule"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-500 inline-block"})," Paid (",t.weeks_paid||0,")"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"})," Upcoming"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-red-400 inline-block"})," Bounced"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-red-400 inline-block"})," Missed"]})]})]}),e.jsx("div",{className:"overflow-x-auto max-h-[800px] overflow-y-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"sticky top-0 bg-white z-10 shadow-sm",children:e.jsxs("tr",{className:"border-b border-gray-100",children:[e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Week"}),e.jsx("th",{className:"text-right px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Amount"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Scheduled Date"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Date Paid"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Status"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Recorded By"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Method"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Notes"}),e.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:N.flatMap(({weekNum:T,scheduledDate:v,realPayments:C,status:q,scheduledAmount:U})=>{const P=v===t.next_payment_date&&q!=="completed",j=(p,O,F,ae)=>{const se=(p==null?void 0:p.notes)||"",de=se.indexOf(" — "),Oe=de>=0?se.substring(0,de):se,_=de>=0?se.substring(de+3):"",ne=P&&O===0,ue=F==="completed"?"bg-emerald-100 text-emerald-800":F==="bounced"||F==="missed"?"bg-red-100 text-red-800":ne?"bg-blue-100 text-blue-800":"bg-gray-100 text-gray-500",Me=F==="completed"?"Paid":F==="bounced"?"Bounced":F==="missed"?"Missed":ne?"Due Next":"Scheduled",yt=F==="completed"?"bg-emerald-50/40":F==="bounced"?"bg-red-50/50":ne?"bg-blue-50":"";return e.jsxs("tr",{className:`${yt} hover:bg-gray-50`,children:[e.jsxs("td",{className:"px-5 py-3 text-sm font-medium text-gray-700",children:[O===0?`Week ${T}`:e.jsxs("span",{className:"text-gray-400",children:["↳ Week ",T]}),ne&&e.jsx("span",{className:"ml-2 text-xs bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded-full font-semibold",children:"Next"})]}),e.jsxs("td",{className:"px-5 py-3 text-sm text-right font-semibold text-gray-800",children:[k((p==null?void 0:p.amount)||U),(p==null?void 0:p.recharge_fee)>0&&e.jsxs("div",{className:"text-xs text-emerald-600 font-medium",children:["+",k(p.recharge_fee)," fee"]})]}),e.jsx("td",{className:"px-5 py-3 text-sm text-gray-600",children:v?x(v).format("MMM D, YYYY"):"—"}),e.jsx("td",{className:"px-5 py-3 text-sm text-gray-600",children:p!=null&&p.paid_date?x(p.paid_date).format("MMM D, YYYY"):"—"}),e.jsx("td",{className:"px-5 py-3",children:e.jsx("span",{className:`text-xs px-2 py-1 rounded-full font-medium ${ue}`,children:Me})}),e.jsx("td",{className:"px-5 py-3 text-sm text-gray-400",children:(p==null?void 0:p.recorded_by_name)||"—"}),e.jsx("td",{className:"px-5 py-3 text-sm text-gray-600",children:Oe||"—"}),e.jsx("td",{className:"px-5 py-3 text-sm text-gray-500 max-w-[220px] truncate",title:_||"",children:_||"—"}),e.jsxs("td",{className:"px-5 py-3",children:[F==="completed"&&ae&&p&&M&&!g&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("button",{onClick:()=>at(p),disabled:r,className:"text-red-600 hover:text-red-800 text-xs font-semibold flex items-center gap-1 disabled:opacity-50",title:"Reverse this payment",children:[e.jsx(St,{className:"w-3 h-3"})," Reverse"]}
5),e.jsxs("button",{onClick:()=>Z(p),disabled:r,className:"text-amber-600 hover:text-amber-800 text-xs font-semibold flex items-center gap-1 disabled:opacity-50",title:"Mark as bounced / returned",children:[e.jsx(tt,{className:"w-3 h-3"})," Bounced"]})]}),F==="bounced"&&p&&M&&!g&&e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("button",{onClick:()=>B(p),disabled:r,className:"text-emerald-600 hover:text-emerald-800 text-xs font-semibold flex items-center gap-1 disabled:opacity-50",title:"Record a replacement payment for this bounced week",children:[e.jsx(ht,{className:"w-3 h-3"})," Recharge"]})})]})]},`${T}-${O}`)};return C.length?C.map((p,O)=>j(p,O,p.status,O===C.length-1)):[j(null,0,q,!0)]})})]})})]})})(),X==="documents"&&e.jsxs("div",{className:"space-y-4",children:[M&&!g&&e.jsxs("div",{className:"bg-white rounded-2xl p-6 shadow-sm border border-gray-100",children:[e.jsx("h3",{className:"font-bold text-gray-800 mb-4",children:"Upload Document"}),e.jsxs("div",{className:"flex gap-3 items-center flex-wrap",children:[e.jsxs(Fe,{value:te,onValueChange:$e,children:[e.jsx(Ye,{className:"w-56",children:e.jsx(Se,{})}),e.jsxs(Pe,{children:[e.jsx(z,{value:"financing_agreement",children:"Financing Agreement"}),e.jsx(z,{value:"customer_id",children:"Customer ID"}),e.jsx(z,{value:"customer_authorization",children:"Customer Authorization"}),e.jsx(z,{value:"void_check",children:"Void Check"}),e.jsx(z,{value:"bank_document",children:"Bank Document"}),e.jsx(z,{value:"other",children:"Other"})]})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",className:"hidden",onChange:a=>{var s;return((s=a.target.files)==null?void 0:s[0])&&Ke(a.target.files[0])},accept:"image/*,.pdf,.doc,.docx"}),e.jsx(b,{asChild:!0,disabled:W,variant:"outline",className:"flex items-center gap-2",children:e.jsxs("span",{children:[e.jsx(Ct,{className:"w-4 h-4"})," ",W?"Uploading...":"Choose File"]})})]})]})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden",children:[e.jsx("div",{className:"p-5 border-b border-gray-100",children:e.jsx("h3",{className:"font-bold text-gray-800",children:"Documents"})}),(t.documents||[]).length===0?e.jsx("div",{className:"p-10 text-center text-gray-400",children:"No documents uploaded yet."}):e.jsx("div",{className:"divide-y divide-gray-50",children:t.documents.map(a=>e.jsx("div",{className:"px-5 py-4",children:be===a.id?e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs(Fe,{value:we,onValueChange:re,children:[e.jsx(Ye,{className:"w-56",children:e.jsx(Se,{})}),e.jsxs(Pe,{children:[e.jsx(z,{value:"financing_agreement",children:"Financing Agreement"}),e.jsx(z,{value:"customer_id",children:"Customer ID"}),e.jsx(z,{value:"customer_authorization",children:"Customer Authorization"}),e.jsx(z,{value:"void_check",children:"Void Check"}),e.jsx(z,{value:"bank_document",children:"Bank Document"}),e.jsx(z,{value:"other",children:"Other"})]})]}),e.jsx(b,{size:"sm",onClick:gt,disabled:r,className:"bg-[#0073ea] text-white",children:"Save"}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>{je(null),re("")},children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Mt,{className:"w-8 h-8 text-[#0073ea] shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-gray-800 text-sm truncate",children:a.file_name}),e.jsxs("p",{className:"text-xs text-gray-400",children:[a.doc_type.replace(/_/g," ")," • ",a.uploaded_by_name," • ",a.uploaded_at]})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx("a",{href:a.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-[#0073ea] text-sm font-medium hover:underline",children:"View"}),e.jsxs("a",{href:a.file_url,download:a.file_name,className:"text-gray-500 text-sm font-medium hover:underline flex items-center gap-1",children:[e.jsx(dt,{className:"w-3 h-3"})," Download"]}),M&&!g&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>qe(a),className:"text-gray-500 hover:text-[#0073ea] transition-colors",title:"Edit type",children:e.jsx(Qe,{className:"w-4 h-4"})}),oe===a.id?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>ft(a.id),disabled:r,className:"text-red-600 text-xs font-semibold hover:underline",children:"Confirm"}),e.jsx("button",{onClick:()=>Ne(null),className:"text-gray-400 text-xs font-medium hover:underline",children:"Cancel"})]}):e.jsx("button",{onClick:()=>Ne(a.id),className:"text-gray-500 hover:text-red-600 transition-colors",title:"Delete",children:e.jsx(Ft,{className:"w-4 h-4"})})]})]})]})},a.id))})]})]}),X==="audit"&&e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden",children:[e.jsx("div",{className:"p-5 border-b border-gray-100",children:e.jsx("h3",{className:"font-bold text-gray-800",children:"Audit Log"})}),(t.audit_log||[]).length===0?e.jsx("div",{className:"p-10 text-center text-gray-400",children:"No audit entries yet."}):e.jsx("div",{className:"divide-y divide-gray-50",children:[...t.audit_log||[]].reverse().map(a=>e.jsxs("div",{className:"px-5 py-4 flex gap-4",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center shrink-0",children:e.jsx(Yt,{className:"w-4 h-4 text-gray-500"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-gray-800",children:a.user_name}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("span",{className:"text-xs text-[#0073ea] font-medium",children:a.action}),e.jsx("span",{className:"text-xs text-gray-400",children:a.timestamp})]}),e.jsx("p",{className:"text-sm text-gray-600 mt-0.5",children:a.details})]})]},a.id))})]}),pe&&e.jsx($t,{open:pe,onClose:()=>ge(!1),financing:t,onConfirm:ce,saving:r}),G&&e.jsx(Wt,{open:!!G,onClose:()=>B(null),payment:G,weeklyAmount:t.weekly_payment,onConfirm:a=>{const s=G;B(null),Ie(s,a)},saving:r}),D&&e.jsx(Ot,{open:!!D,onClose:()=>Z(null),payment:D,onConfirm:a=>{const s=D;Z(null),De(s,a)},saving:r}),Te&&e.jsx(Tt,{open:Te,onClose:()=>d(!1),financing:t,payments:Y,user:n,onDone:async()=>{const[a,s]=await Promise.all([h.entities.FinancingOrder.filter({id:c}),h.entities.FinancingPayment.filter({financing_order_id:c},"-scheduled_date",200)]);a[0]&&(u(a[0]),R(a[0].next_payment_date||"")),A(s)}})]})})}export{Pa as default};

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