/* ══════════ باقیداری انشعاب / حق الامتیاز (سالانه) — shared panels ══════════ Used by ثبت رسیدها (PaymentRegistrationPage) and the receipt editor (ویرایش), so both show the same design and behave the same way. Props of both panels: r the receipt being edited (draft) customer its customer (all receipts, for the per-year history) lang onChange (patch) => void — merges `patch` into the receipt onKeyDown optional, put on the inputs (Enter = save in ثبت رسیدها) Data (all existing fields are kept and still used everywhere else): disconnectionDeposit, depositCarried, depositPaidAmount, depositPaid franchiseYears, franchiseCarried, franchisePaidAmount, franchisePaid New, optional: franchiseYearPaid { "1405": 500, ... } — how much of each year's fee was paid on this receipt. franchisePaidAmount is always kept equal to its sum, so totals / carry-over work as before. */ const FRANCHISE_YEAR_OPTIONS = [1403,1404,1405,1406,1407,1408,1409,1410,1411,1412,1413,1414,1415]; // same chronological order as cascadeArrears (year, then month, then position) const receiptSortKey = (r) => { const parts = (r.date||"").split("-"); const y = parseInt(parts[0],10) || 0; const m = parseInt(r.receiptMonth || parts[1], 10) || 0; return y*100 + m; }; // The customer's receipts with the receipt being edited in place of its stored copy. const receiptsWithDraft = (customer, r) => { const list = (customer && customer.receipts) ? customer.receipts : []; if(!r) return list; const i = r.id ? list.findIndex(x => x.id === r.id) : -1; if(i >= 0){ const out = list.slice(); out[i] = r; return out; } return [...list, r]; }; /* Per-year ledger of حق الامتیاز for one customer. Receipts with franchiseYearPaid say exactly which year each payment was for. Older receipts (only a total paid amount) are allocated to the oldest unpaid year first — nothing that was registered is lost or changed. */ function franchiseLedger(receipts){ const years = {}; // year -> { fee, paid, charges:[{rid,r}], payments:[{rid,r,amount}] } const perReceipt = {}; // receiptKey -> { year: amount } const Y = (y) => (years[y] = years[y] || { fee:0, paid:0, charges:[], payments:[] }); const keyOf = (r) => r.id || "__draft"; const order = receipts.map((r,i)=>({r,i})).sort((a,b)=>(receiptSortKey(a.r)-receiptSortKey(b.r)) || (a.i-b.i)); order.forEach(({r})=>{ const rk = keyOf(r); (r.franchiseYears||[]).forEach(y => { const e = Y(y); e.fee += FRANCHISE_FEE_PER_YEAR; e.charges.push({rid:rk, r}); }); const pay = (y, amount) => { if(!(amount > 0)) return; const e = Y(y); e.paid += amount; e.payments.push({rid:rk, r, amount}); perReceipt[rk] = perReceipt[rk] || {}; perReceipt[rk][y] = (perReceipt[rk][y]||0) + amount; }; if(r.franchiseYearPaid && typeof r.franchiseYearPaid === "object"){ Object.keys(r.franchiseYearPaid).forEach(y => pay(Number(y), Number(r.franchiseYearPaid[y])||0)); } else { let left = franchisePaidOf(r); Object.keys(years).map(Number).sort((a,b)=>a-b).forEach(y => { if(left <= 0) return; const e = years[y]; const open = Math.max(0, e.fee - e.paid); const amt = Math.min(open, left); if(amt > 0){ pay(y, amt); left -= amt; } }); } }); return { years, perReceipt, keyOf }; } const monthLabelOf = (r, isDari) => { const m = parseInt(r.receiptMonth || ((r.date||"").split("-")[1]), 10); if(!(m >= 1 && m <= 12)) return "—"; return isDari ? jalaliMonthNamesFa[m-1] : jalaliMonthNamesEn[m-1]; }; /* ───────── shared compact look (same for both sections) ───────── */ const PAY_GREEN = "#15803d", PAY_ORANGE = "#b45309", PAY_PURPLE = "#7c3aed", PAY_TEAL = "#0FA4AF"; const payPanelStyles = { card: (c) => ({ background:"var(--paper-card)", border:"1px solid var(--line-strong)", borderInlineStart:`3px solid ${c}`, borderRadius:"10px", padding:"10px 12px", marginBottom:"8px" }), head: { display:"flex", alignItems:"center", gap:"8px", marginBottom:"8px", flexWrap:"wrap" }, title: { fontSize:"13px", fontWeight:800, color:"var(--navy)", whiteSpace:"nowrap" }, grid: (n) => ({ display:"grid", gridTemplateColumns:`repeat(${n}, minmax(0,1fr))`, gap:"6px" }), cell: { minWidth:0 }, cap: { fontSize:"12px", fontWeight:700, color:"var(--muted)", marginBottom:"2px", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }, val: (c) => ({ height:"30px", display:"flex", alignItems:"center", padding:"0 8px", borderRadius:"7px", background:c+"10", color:c, fontSize:"13.5px", fontWeight:800, fontFamily:"var(--font-mono)", whiteSpace:"nowrap", overflow:"hidden" }), input: (c) => ({ width:"100%", height:"30px", boxSizing:"border-box", padding:"0 8px", borderRadius:"7px", border:`1px solid ${c ? c+"66" : "var(--line-strong)"}`, background:"var(--paper)", color: c || "var(--ink)", fontSize:"13.5px", fontWeight:800, fontFamily:"var(--font-mono)", outline:"none" }), select: { height:"28px", padding:"0 6px", borderRadius:"7px", border:`1px solid ${"#0FA4AF"}66`, background:"var(--paper)", color:"var(--navy)", fontSize:"12.5px", fontWeight:800, fontFamily:"var(--font-mono)", outline:"none", cursor:"pointer" }, barWrap: { height:"3px", borderRadius:"99px", background:"var(--line-strong)", overflow:"hidden", marginTop:"8px" }, bar: (pct, c) => ({ width:`${Math.max(0,Math.min(100,pct))}%`, height:"100%", background:c, transition:"width .2s" }), badge: (c) => ({ fontSize:"12px", fontWeight:700, padding:"2px 8px", borderRadius:"99px", background:c+"18", color:c, whiteSpace:"nowrap" }), btn: (c, solid) => ({ height:"26px", padding:"0 10px", borderRadius:"7px", border: solid ? "none" : `1px solid ${c}55`, background: solid ? c : "transparent", color: solid ? "#fff" : c, cursor:"pointer", fontSize:"12px", fontWeight:700, whiteSpace:"nowrap" }), small: { fontSize:"12px", color:"var(--muted)", fontWeight:600 }, foot: { display:"flex", alignItems:"center", gap:"8px", flexWrap:"wrap", marginTop:"8px", paddingTop:"8px", borderTop:"1px dashed var(--line-strong)", fontSize:"12px", color:"var(--muted)", fontWeight:600 }, }; function PayStatusBadge({ total, paid, isDari }){ const remaining = Math.max(0, total - paid); const [txt, c] = total <= 0 ? [isDari?"بدون مبلغ":"No amount", "#5A6B72"] : remaining === 0 ? [isDari?"✓ کامل":"✓ Paid", PAY_GREEN] : paid > 0 ? [isDari?"قسمی":"Partly", PAY_ORANGE] : [isDari?"پرداخت نشده":"Unpaid", PAY_ORANGE]; return {txt}; } const PayBar = ({ total, paid }) => { const s = payPanelStyles; const pct = total > 0 ? (paid/total)*100 : 0; return
= 100 ? PAY_GREEN : PAY_TEAL)}/>
; }; /* ───────── باقیداری انشعاب ───────── */ function DepositPanel({ r, lang, onChange, onKeyDown }){ const isDari = lang === "dari"; const f = nd(lang); const s = payPanelStyles; const total = depositTotalOf(r); const carried = Number(r.depositCarried)||0; const paid = depositPaidOf(r); const remaining = depositRemainingOf(r); const setNew = (v) => { const next = {...r, disconnectionDeposit: v}; const t = depositTotalOf(next); const patch = { disconnectionDeposit: v }; // keep the paid flag in step with the new total (same as entering a paid amount) if(r.depositPaidAmount !== undefined && !r.depositPaid) patch.depositPaid = t > 0 && (Number(r.depositPaidAmount)||0) >= t; onChange(patch); }; const setPaid = (v) => { const amt = Math.max(0, Math.min(Number(v)||0, total)); onChange({ depositPaidAmount: amt, depositPaid: amt >= total && total > 0 }); }; const togglePaid = () => { if(r.depositPaid) onChange({ depositPaid:false }); else onChange({ depositPaid:true, depositPaidAmount: total }); }; return (
{isDari?"باقیداری انشعاب":"Connection Deposit"} {total > 0 && }
{total > 0 && ( )}
0 ? 4 : 1)}>
{isDari?"مبلغ جدید":"New amount"}
setNew(e.target.value)} onKeyDown={onKeyDown} placeholder="0" style={s.input()}/>
{total > 0 && (<>
{isDari?"مبلغ کل":"Total"}{carried > 0 && ({isDari?"قبلی ":"prev "}{f(fmtMoney(carried))})}
{f(fmtMoney(total))}
{isDari?"پرداخت شده":"Paid"}
setPaid(e.target.value)} onKeyDown={onKeyDown} style={s.input(PAY_GREEN)}/>
{isDari?"باقیمانده":"Remaining"}{remaining > 0 && → {isDari?"ماه بعد":"next"}}
0 ? PAY_ORANGE : PAY_GREEN)}>{f(fmtMoney(remaining))}
)}
{total > 0 && }
); } /* ───────── حق الامتیاز (سالانه) — one year dropdown, the chosen year's figures ───────── */ function FranchisePanel({ r, customer, lang, onChange, onKeyDown }){ const isDari = lang === "dari"; const f = nd(lang); const currency = STR[lang].dash.currency; const s = payPanelStyles; const [showHistory, setShowHistory] = useState(false); const all = receiptsWithDraft(customer, r); const ledger = franchiseLedger(all); const myKey = ledger.keyOf(r); const myYears = r.franchiseYears || []; const myPay = (r.franchiseYearPaid && typeof r.franchiseYearPaid === "object") ? r.franchiseYearPaid : (ledger.perReceipt[myKey] || {}); // default year: one charged on this receipt, else the oldest still-unpaid year, else this year const openYears = Object.keys(ledger.years).map(Number).filter(y => ledger.years[y].fee - ledger.years[y].paid > 0).sort((a,b)=>a-b); const thisYear = todayJalali().y; const defaultYear = myYears[0] || openYears[0] || (FRANCHISE_YEAR_OPTIONS.includes(thisYear) ? thisYear : FRANCHISE_YEAR_OPTIONS[0]); const [year, setYear] = useState(defaultYear); // a different receipt was loaded → jump to its default year useEffect(()=>{ setYear(defaultYear); /* eslint-disable-next-line */ }, [r.id, r.receiptMonth, customer && customer.id]); // this receipt (what moves to the next month) const total = franchiseTotalOf(r); const carried = Number(r.franchiseCarried)||0; const paid = franchisePaidOf(r); const remaining = franchiseRemainingOf(r); // the chosen year const ye = ledger.years[year] || { fee:0, paid:0, charges:[], payments:[] }; const yearRemaining = Math.max(0, ye.fee - ye.paid); const onThisReceipt = myYears.includes(year); const chargedElsewhere = ye.charges.filter(c => c.rid !== myKey); const myYearAmount = Number(myPay[year])||0; const maxForYear = Math.max(0, ye.fee - (ye.paid - myYearAmount)); // write a per-year map and keep the existing totals / paid flag in step with it const applyPay = (map, years) => { const clean = {}; Object.keys(map).forEach(k => { const v = Number(map[k])||0; if(v > 0) clean[k] = v; }); const sum = Object.values(clean).reduce((a,b)=>a+b, 0); const t = franchiseTotalOf({...r, franchiseYears: years}); onChange({ franchiseYears: years, franchiseYearPaid: clean, franchisePaidAmount: Math.min(sum, t), franchisePaid: t > 0 && sum >= t }); }; const setYearPaid = (v) => { const amt = Math.max(0, Math.min(Number(v)||0, maxForYear)); applyPay({...myPay, [year]: amt}, myYears); }; const addYear = () => applyPay({...myPay}, [...myYears, year].sort((a,b)=>a-b)); const removeYear = () => { const m = {...myPay}; delete m[year]; applyPay(m, myYears.filter(y => y !== year)); }; const payAll = () => { // only years charged on this receipt or earlier ones (never a later month's charge) const myOrder = receiptSortKey(r); const upTo = franchiseLedger(all.filter(x => x === r || receiptSortKey(x) <= myOrder)); const m = {...myPay}; Object.keys(upTo.years).forEach(y => { const e = upTo.years[y]; const open = Math.max(0, e.fee - e.paid); if(open > 0) m[y] = (Number(m[y])||0) + open; }); applyPay(m, myYears); }; const unpayAll = () => onChange({ franchiseYearPaid: {}, franchisePaidAmount: 0, franchisePaid: false }); return (
{/* the single dropdown named حق الامتیاز (سالانه) */}
{ye.fee > 0 && }
{onThisReceipt ? ( ) : chargedElsewhere.length === 0 ? ( ) : ( {isDari?"برج ":""}{chargedElsewhere.map(c => monthLabelOf(c.r, isDari)).join("، ")} )}
{ye.fee > 0 ? ( <>
{isDari?"فیس سال":"Fee"}
{f(fmtMoney(ye.fee))}
{isDari?"پرداخت شده":"Paid"}
{f(fmtMoney(ye.paid))}
{isDari?"در این قبض":"This receipt"}
setYearPaid(e.target.value)} onKeyDown={onKeyDown} style={s.input(PAY_GREEN)}/>
{isDari?"باقیمانده":"Remaining"}
0 ? PAY_ORANGE : PAY_GREEN)}>{f(fmtMoney(yearRemaining))}
) : (
{isDari?"فیس این سال ثبت نشده — ":"Not charged — "}{f(fmtMoney(FRANCHISE_FEE_PER_YEAR))} {currency}
)} {/* this receipt in total (moves to the next month) + history toggle */} {(total > 0 || ye.payments.length > 0) && (
{total > 0 && ( {isDari?"این قبض: ":"Receipt: "}{f(fmtMoney(total))} {carried > 0 && <> ({isDari?"قبلی ":"prev "}{f(fmtMoney(carried))})} {" · "}{isDari?"پرداخت ":"paid "}{f(fmtMoney(paid))} {" · "}{isDari?"باقی ":"left "} 0 ? PAY_ORANGE : PAY_GREEN}}>{f(fmtMoney(remaining))} {remaining > 0 && <> → {isDari?"ماه بعد":"next"}} )}
{ye.payments.length > 0 && ( )} {total > 0 && (remaining > 0 ? : )}
)} {/* payment history of the chosen year (collapsed by default) */} {showHistory && ye.payments.length > 0 && (
{ye.payments.map((p,i) => (
{monthLabelOf(p.r, isDari)} · {f(p.r.date || "—")} {p.rid === myKey && · {isDari?"این قبض":"this receipt"}} {f(fmtMoney(p.amount))}
))}
)}
); }