/* ============ Number / formatting helpers ============ */ const faDigitsMap = {"0":"۰","1":"۱","2":"۲","3":"۳","4":"۴","5":"۵","6":"۶","7":"۷","8":"۸","9":"۹"}; const toFa = (val) => String(val ?? "").replace(/[0-9]/g, d => faDigitsMap[d]); // `nd` = localized digits for counts / readings / dates (per original convention) const nd = (lang) => (val) => lang === "dari" ? toFa(val) : String(val ?? ""); /* ===== Jalali (Solar Hijri / Afghan) calendar helpers ===== The whole app's dates (e.g. "1404-11-01") are Afghan calendar dates, not Gregorian, so a native can't be used. These helpers let the date picker compute correct month lengths and weekday alignment. */ const jalaliMonthNamesFa = ["حمل","ثور","جوزا","سرطان","اسد","سنبله","میزان","عقرب","قوس","جدی","دلو","حوت"]; const jalaliMonthNamesEn = ["Hamal","Sawr","Jawza","Saratan","Asad","Sonbola","Mizan","Aqrab","Qaws","Jadi","Dalw","Hut"]; const jalaliWeekdaysFa = ["ش","ی","د","س","چ","پ","ج"]; // starts Saturday, matches Afghan week // Common 33-year-cycle approximation — accurate enough for a UI date picker. const isLeapJalaliYear = (jy) => [1,5,9,13,17,22,26,30].includes(((jy % 33) + 33) % 33); const jalaliMonthLength = (jy, jm) => jm <= 6 ? 31 : (jm <= 11 ? 30 : (isLeapJalaliYear(jy) ? 30 : 29)); // Converts a Jalali Y/M/D to a JS Date (Gregorian) — standard algorithm, used // here purely to compute which weekday a Jalali month starts on. const jalaliToGregorian = (jy, jm, jd) => { jy = Number(jy) + 1595; let days = -355668 + (365*jy) + (Math.floor(jy/33)*8) + Math.floor(((jy%33)+3)/4) + jd + (jm < 7 ? (jm-1)*31 : ((jm-7)*30)+186); let gy = 400 * Math.floor(days/146097); days %= 146097; if(days > 36524){ gy += 100*Math.floor(--days/36524); days %= 36524; if(days >= 365) days++; } gy += 4*Math.floor(days/1461); days %= 1461; if(days > 365){ gy += Math.floor((days-1)/365); days = (days-1)%365; } let gd = days+1; const isG_leap = (y) => (y%4===0 && y%100!==0) || y%400===0; const sal = [0,31, isG_leap(gy)?29:28, 31,30,31,30,31,31,30,31,30,31]; let gm = 0; for(gm=1; gm<=12; gm++){ if(gd <= sal[gm]) break; gd -= sal[gm]; } return new Date(gy, gm-1, gd); }; // Today's date expressed in the Jalali calendar — approximate via a fixed // known anchor (Jalali 1403-01-01 = Gregorian 2024-03-20) plus day offset. const todayJalali = () => { const anchorG = new Date(2024, 2, 20); // 1403-01-01 const diffDays = Math.round((new Date(new Date().toDateString()) - anchorG) / 86400000); let jy = 1403, remaining = diffDays; while(true){ const yearLen = isLeapJalaliYear(jy) ? 366 : 365; if(remaining < yearLen) break; remaining -= yearLen; jy++; } while(remaining < 0){ jy--; remaining += isLeapJalaliYear(jy) ? 366 : 365; } let jm = 1; while(true){ const len = jalaliMonthLength(jy, jm); if(remaining < len) break; remaining -= len; jm++; } return { y: jy, m: jm, d: remaining+1 }; }; const parseDateStr = (s) => { if(!s || !/^\d{4}-\d{1,2}-\d{1,2}$/.test(s)) return null; const [y,m,d] = s.split("-").map(n=>parseInt(n,10)); return { y, m, d }; }; const formatDateStr = (y,m,d) => `${y}-${String(m).padStart(2,"0")}-${String(d).padStart(2,"0")}`; // money always renders in western grouped digits, regardless of language const fmtMoney = (n) => { const num = Number(n)||0; return num.toLocaleString("en-US"); }; // Receipts created before payment tracking existed have no `paid` field — // treat that as "not confirmed paid" rather than silently assuming paid. const isPaid = (r) => r && r.paid === true; const isPartiallyPaid = (r) => r && !r.paid && (r.paidAmount||0) > 0 && (r.paidAmount||0) < (r.total||0); const paidAmount = (r) => r ? (r.paidAmount !== undefined ? r.paidAmount : (r.paid ? (r.total||0) : 0)) : 0; // Unpaid part of a receipt — this is what moves to باقیمانده قبلی of the next month. const receiptRemaining = (r) => { if(!r || isPaid(r)) return 0; return Math.max(0, (Number(r.total)||0) - (Number(r.paidAmount)||0)); }; // باقیداری انشعاب and حق الامتیاز (سالانه) — the unpaid part is carried to the // next month in its own field (depositCarried / franchiseCarried), separate // from the amount newly charged on that receipt, so the existing totals and // lists that sum disconnectionDeposit never count the same money twice. const FRANCHISE_FEE_PER_YEAR = 1000; const depositTotalOf = (r) => r ? (Number(r.disconnectionDeposit)||0) + (Number(r.depositCarried)||0) : 0; const depositPaidOf = (r) => { const t = depositTotalOf(r); if(!r || t <= 0) return 0; if(r.depositPaid) return t; // same rule as before: marked "unpaid" with a full amount entered = unpaid const amt = Math.max(0, Number(r.depositPaidAmount)||0); return amt < t ? amt : 0; }; const depositRemainingOf = (r) => Math.max(0, depositTotalOf(r) - depositPaidOf(r)); const franchiseTotalOf = (r) => r ? (r.franchiseYears||[]).length * FRANCHISE_FEE_PER_YEAR + (Number(r.franchiseCarried)||0) : 0; const franchisePaidOf = (r) => { const t = franchiseTotalOf(r); if(!r || t <= 0) return 0; if(r.franchisePaid) return t; const amt = Math.max(0, Number(r.franchisePaidAmount)||0); return amt < t ? amt : 0; }; const franchiseRemainingOf = (r) => Math.max(0, franchiseTotalOf(r) - franchisePaidOf(r)); // Re-carry the unpaid deposit / franchise into a later receipt. Only receipts // that already use carry-over (field present) are touched; paid amounts are // never changed. const recarry = (r, prev) => { let out = r; if(r.depositCarried !== undefined){ const c = depositRemainingOf(prev); if(c !== (Number(r.depositCarried)||0)){ out = {...out, depositCarried: c}; if(out.depositPaidAmount !== undefined){ const t = depositTotalOf(out); out.depositPaid = t > 0 ? (Number(out.depositPaidAmount)||0) >= t : !!out.depositPaid; } } } if(r.franchiseCarried !== undefined){ const c = franchiseRemainingOf(prev); if(c !== (Number(r.franchiseCarried)||0)){ out = out === r ? {...out} : out; out.franchiseCarried = c; if(out.franchisePaidAmount !== undefined){ const t = franchiseTotalOf(out); out.franchisePaid = t > 0 ? (Number(out.franchisePaidAmount)||0) >= t : !!out.franchisePaid; } } } return out; }; // After a receipt changes, every later month of the same customer gets its // باقیمانده قبلی = the unpaid part of the month before it (and its total is // adjusted by the same difference). Earlier months are never touched. const cascadeArrears = (receipts, changedId) => { if(!Array.isArray(receipts) || !receipts.length) return receipts; const key = (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; }; const order = receipts.map((r,i)=>({r,i})).sort((a,b)=>(key(a.r)-key(b.r)) || (a.i-b.i)); const start = order.findIndex(x=>x.r.id===changedId); if(start < 0) return receipts; const out = receipts.slice(); let prev = out[order[start].i]; for(let k=start+1; k 0 ? (Number(r.paidAmount)||0) >= total : !!r.paid; out[idx] = next; } out[idx] = recarry(out[idx], prev); prev = out[idx]; } return out; }; const initials = (name) => { if(!name) return "?"; const parts = name.trim().split(/\s+/); return parts.length>1 ? parts[0][0]+parts[1][0] : parts[0].slice(0,2); }; /* ============ Jalali (Afghan) Calendar Date Picker ============ A self-contained popover calendar for the Afghan Solar Hijri calendar. `value`/`onChange` use the same "YYYY-MM-DD" western-digit string already stored everywhere in this app (e.g. "1404-11-01"); only the on-screen digits/labels switch with `lang`. */ function JalaliDatePicker({ value, onChange, lang, placeholder }){ const f = nd(lang); const isDari = lang === "dari"; const monthNames = isDari ? jalaliMonthNamesFa : jalaliMonthNamesEn; const parsed = parseDateStr(value); const today = todayJalali(); const [open, setOpen] = useState(false); const [popPos, setPopPos] = useState({top:0, left:0}); const [viewY, setViewY] = useState(parsed ? parsed.y : today.y); const [viewM, setViewM] = useState(parsed ? parsed.m : today.m); const wrapRef = useRef(null); const btnRef = useRef(null); useEffect(()=>{ const p = parseDateStr(value); if(p){ setViewY(p.y); setViewM(p.m); } }, [value]); useEffect(()=>{ if(!open) return; const handler = (e) => { if(wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); }; document.addEventListener("pointerdown", handler, true); return ()=>document.removeEventListener("pointerdown", handler, true); }, [open]); const openPicker = () => { if(btnRef.current){ const rect = btnRef.current.getBoundingClientRect(); setPopPos({ top: rect.bottom + 6, left: rect.left }); } setOpen(o=>!o); }; const monthLen = jalaliMonthLength(viewY, viewM); const firstWeekday = (jalaliToGregorian(viewY, viewM, 1).getDay() + 1) % 7; // 0=Saturday const cells = []; for(let i=0;i { if(viewM===1){ setViewY(viewY-1); setViewM(12);} else setViewM(viewM-1); }; const goNextMonth = () => { if(viewM===12){ setViewY(viewY+1); setViewM(1);} else setViewM(viewM+1); }; const pick = (d) => { onChange(formatDateStr(viewY, viewM, d)); setOpen(false); }; const setToday = () => { onChange(formatDateStr(today.y, today.m, today.d)); setOpen(false); }; const display = parsed ? f(formatDateStr(parsed.y, parsed.m, parsed.d)) : ""; return (
{open && (
e.stopPropagation()} onPointerDown={e=>e.stopPropagation()}>
{jalaliWeekdaysFa.map((w,i)=>(
{w}
))}
{cells.map((d,i)=>{ if(d===null) return
; const isSelected = parsed && parsed.y===viewY && parsed.m===viewM && parsed.d===d; const isToday = today.y===viewY && today.m===viewM && today.d===d; return ( ); })}
{value && }
)}
); } /* ============ Jalali Month Picker (calendar-style, month only) ============ */ function JalaliMonthPicker({ value, onChange, lang, placeholder }){ const f = nd(lang); const isDari = lang === "dari"; const monthNames = isDari ? jalaliMonthNamesFa : jalaliMonthNamesEn; const [open, setOpen] = useState(false); const [popPos, setPopPos] = useState({top:0, left:0}); const wrapRef = useRef(null); const btnRef = useRef(null); useEffect(()=>{ if(!open) return; const handler = (e) => { if(wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); }; document.addEventListener("pointerdown", handler, true); return ()=>document.removeEventListener("pointerdown", handler, true); }, [open]); const openPicker = () => { if(btnRef.current){ const rect = btnRef.current.getBoundingClientRect(); setPopPos({ top: rect.bottom + 6, left: rect.left }); } setOpen(o=>!o); }; const pick = (i) => { onChange(String(i+1).padStart(2,"0")); setOpen(false); }; const selectedIdx = value ? parseInt(value,10)-1 : -1; const display = selectedIdx>=0 ? monthNames[selectedIdx] : ""; return (
{open && (
e.stopPropagation()} onPointerDown={e=>e.stopPropagation()}>
{monthNames.map((mn,i)=>( ))}
)}
); } /* ============ Login Page ============ */ const MAX_LOGIN_ATTEMPTS = 5; const LOCKOUT_MINUTES = 5;