function EmployeesPage({ employees, setEmployees, lang }){ const t = STR[lang]; const te = t.employees; const f = nd(lang); const [form, setForm] = useState({ fullName:"", position:"", phone:"", notes:"" }); const [confirmId, setConfirmId] = useState(null); const addEmployee = () => { if(!form.fullName.trim()){ alert(te.needName); return; } setEmployees([...employees, { ...form, id:"emp"+Date.now() }]); setForm({ fullName:"", position:"", phone:"", notes:"" }); }; const removeEmployee = (id) => { setEmployees(employees.filter(e=>e.id!==id)); setConfirmId(null); }; return (

{te.title}

{te.sub}

{employees.length === 0 ? (

{te.emptyTitle}

{te.emptySub}

) : (
{employees.map(e=>( ))}
{te.colName}{te.colPosition}{te.colPhone}{te.colNotes}
{e.fullName} {e.position || "—"} {f(e.phone || "—")} {e.notes || "—"} {confirmId===e.id ? (
) : ( )}
)}

{te.addTitle}

setForm({...form, fullName:e.target.value})} placeholder={te.fullNamePh}/>
setForm({...form, position:e.target.value})} placeholder={te.positionPh}/>
setForm({...form, phone:e.target.value})} placeholder={te.phonePh}/>
setForm({...form, notes:e.target.value})} placeholder={te.notesPh}/>
); } /* ============ Expense / Purchases Page (generic, used for all 3 categories) ============ */ function ExpensePage({ items, setItems, lang, categoryTitle, categorySub }){ const t = STR[lang]; const tx = t.expenses; const f = nd(lang); const [form, setForm] = useState({ title:"", amount:"", date:"", notes:"" }); const total = items.reduce((s,it)=>s+(Number(it.amount)||0),0); const addItem = () => { if(!form.title.trim()){ alert(tx.needTitle); return; } setItems([...items, { ...form, amount:Number(form.amount)||0, id:"exp"+Date.now() }]); setForm({ title:"", amount:"", date:"", notes:"" }); }; const removeItem = (id) => { if(window.confirm(tx.deleteConfirm)) setItems(items.filter(it=>it.id!==id)); }; return (

{categoryTitle}

{categorySub}

{items.length === 0 ? (

{tx.emptyTitle}

{tx.emptySub}

) : (
{items.map(it=>( ))}
{tx.colTitle}{tx.colDate}{tx.colNotes}{tx.colAmount}
{it.title} {f(it.date || "—")} {it.notes || "—"} {f(fmtMoney(it.amount))} {tx.currency}
{tx.total}: {f(fmtMoney(total))} {tx.currency}
)}

{tx.addTitle}

setForm({...form, title:e.target.value})} placeholder={tx.titlePh}/>
setForm({...form, amount:e.target.value})} placeholder={tx.amountPh}/>
setForm({...form, date:v})} lang={lang} placeholder={tx.datePh}/>
setForm({...form, notes:e.target.value})} placeholder={tx.notesPh}/>
); } /* ============ Settings Page ============ */ function CloudSyncSection({ isDari }){ const [status, setStatus] = useState(""); const [busy, setBusy] = useState(false); const pushToCloud = async () => { setBusy(true); setStatus(isDari?"در حال آپلود...":"Uploading..."); try{ await FBStore.pushAll(); setStatus(isDari?`آپلود شد ✓ ${new Date().toLocaleTimeString()}`:`Uploaded ✓ ${new Date().toLocaleTimeString()}`); }catch(e){ setStatus((isDari?"خطای شبکه: ":"Network error: ")+((e&&e.message)||e)); } setBusy(false); }; const pullFromCloud = async () => { setBusy(true); setStatus(isDari?"در حال دریافت...":"Downloading..."); try{ FBStore.freeze(); // do not write the current on-screen copy back while reloading setStatus(isDari?"دریافت شد ✓ در حال بارگذاری مجدد...":"Downloaded ✓ Reloading..."); setTimeout(()=>window.location.reload(),1500); }catch(e){ setStatus((isDari?"خطا: ":"Error: ")+((e&&e.message)||e)); } setBusy(false); }; // Read-only check: is everything from the built-in data files // (data/customers.js, data/lists.js, data/code-lists.js) stored in Firestore? // Only when it is can those files safely stop being published. const [check, setCheck] = useState(null); // { ok, lines[] } const runCloudCheck = async () => { setBusy(true); setCheck(null); try{ const { app, customerIds } = await FBStore.checkCloud(); const lines = []; let ok = true; const add = (good, text) => { if(!good) ok = false; lines.push((good ? "✓ " : "✗ ") + text); }; if(!BUILTIN.hasCustomers && !BUILTIN.hasLists && !BUILTIN.hasCodeBase){ lines.push(isDari ? "فایل‌های داده داخلی دیگر بارگذاری نمی‌شوند." : "The built-in data files are no longer loaded."); } lines.push((isDari ? "مشتریان در ابر: " : "Customers in cloud: ") + customerIds.size); if(BUILTIN.hasCustomers){ const deleted = ((app.tombstones || {}).customers) || {}; const missing = BUILTIN.customers.filter(c => !customerIds.has(String(c.id)) && !deleted[c.id]); add(missing.length === 0, isDari ? `مشتریان فایل داخلی: ${BUILTIN.customers.length} - موجود در ابر یا حذف‌شده: ${BUILTIN.customers.length - missing.length} - کمبود: ${missing.length}` : `Built-in customers: ${BUILTIN.customers.length} - in cloud or deleted: ${BUILTIN.customers.length - missing.length} - missing: ${missing.length}`); } const cb = app.codeBase; const cbOk = !!(cb && Array.isArray(cb.zamin) && Array.isArray(cb.omomi) && Array.isArray(cb.mawaqat)); if(BUILTIN.hasCodeBase){ const same = cbOk && ["zamin","omomi","mawaqat"].every(k => cb[k].length === BUILTIN.codeBase[k].length); add(same, isDari ? `لست‌های کد (ضامن/عمومی/موقت) در ابر: ${cbOk ? `${cb.zamin.length}/${cb.omomi.length}/${cb.mawaqat.length}` : "ندارد"} - فایل داخلی: ${BUILTIN.codeBase.zamin.length}/${BUILTIN.codeBase.omomi.length}/${BUILTIN.codeBase.mawaqat.length}` : `Code lists (zamin/omomi/mawaqat) in cloud: ${cbOk ? `${cb.zamin.length}/${cb.omomi.length}/${cb.mawaqat.length}` : "missing"} - built-in: ${BUILTIN.codeBase.zamin.length}/${BUILTIN.codeBase.omomi.length}/${BUILTIN.codeBase.mawaqat.length}`); } else { add(cbOk, (isDari ? "لست‌های کد در ابر: " : "Code lists in cloud: ") + (cbOk ? `${cb.zamin.length}/${cb.omomi.length}/${cb.mawaqat.length}` : (isDari ? "ندارد" : "missing"))); } if(BUILTIN.hasLists){ const cl = app.consumptionLists || {}; const clKeys = Object.keys(BUILTIN.lists.consumptionLists); const clOk = clKeys.every(k => Array.isArray(cl[k])); add(clOk, (isDari ? "لست‌های مصرف در ابر: " : "Consumption lists in cloud: ") + clKeys.filter(k => Array.isArray(cl[k])).length + "/" + clKeys.length); const empOk = !!(app.expenses && Array.isArray(app.expenses.employee)); add(empOk, (isDari ? "مصارف کارمندان در ابر: " : "Employee expenses in cloud: ") + (empOk ? app.expenses.employee.length : (isDari ? "ندارد" : "missing"))); } lines.push(ok ? (isDari ? "✅ همه چیز در ابر است." : "✅ Everything is stored in the cloud.") : (isDari ? "⚠ هنوز همه چیز در ابر نیست. چند ثانیه صبر کنید و دوباره بررسی کنید." : "⚠ Not everything is in the cloud yet. Wait a few seconds and check again.")); setCheck({ ok, lines }); }catch(e){ setCheck({ ok:false, lines:[(isDari?"خطا: ":"Error: ")+((e&&(e.code||e.message))||e)] }); } setBusy(false); }; return (

{isDari?"ذخیره ابری (Firebase)":"Cloud Sync (Firebase)"}

{isDari?"اطلاعات به‌طور خودکار در Firebase (Google) ذخیره و همگام‌سازی می‌شوند.\nهمه کاربران به یک پایگاه داده مشترک وصل هستند.":"Data is saved and synced automatically with Firebase (Google).\nAll users share the same cloud database."}

{check && (
{check.lines.map((l,i)=>
{l}
)}
)} {status && (
{status}
)}
⚡ {isDari?"سیستم بروزرسانی‌های کاربران دیگر را بلافاصله دریافت می‌کند":"The system receives other users' updates in real time"}
💡 {isDari?"توصیه: هر روز قبل از بستن، بکاپ بگیرید":"Tip: Export a backup daily before closing"}
); } function SettingsPage({ company, setCompany, users, setUsers, currentUser, lang, setLang, theme, setTheme, initialTab }){ const t = STR[lang]; const ts = t.settings; const isDari = lang === "dari"; const [activeSettings, setActiveSettings] = useState(initialTab||"company"); useEffect(()=>{ if(initialTab) setActiveSettings(initialTab); }, [initialTab]); const [companyForm, setCompanyForm] = useState({...company}); const [savedCo, setSavedCo] = useState(false); const [newUser, setNewUser] = useState({ username:"", password:"", fullName:"", role:"operator", phone:"" }); const [pwForm, setPwForm] = useState({ current:"", next:"" }); const [pwMsg, setPwMsg] = useState(""); useEffect(()=>{ setCompanyForm({...company}); }, [company]); const saveCompany = () => { setCompany(companyForm); setSavedCo(true); setTimeout(()=>setSavedCo(false), 2000); }; const [userMsg, setUserMsg] = useState(""); const addUser = async () => { const emailNorm = newUser.username.trim().toLowerCase(); if(!emailNorm || !newUser.fullName.trim()){ alert(ts.needAllFields); return; } if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailNorm)){ alert(isDari?"لطفاً یک ایمیل معتبر وارد کنید.":"Please enter a valid email address."); return; } if(users.some(u=>(u.username||"").toLowerCase()===emailNorm)){ alert(ts.usernameTaken); return; } try{ await FBStore.setMember(emailNorm, { fullName: newUser.fullName.trim(), email: emailNorm, role: newUser.role, active: true }); }catch(e){ alert((isDari?"خطا در تایید کاربر: ":"Error approving user: ")+((e&&e.message)||e)); return; } setUsers([...users, { id:"u"+Date.now(), username: emailNorm, fullName: newUser.fullName.trim(), role: newUser.role }]); setNewUser({ username:"", password:"", fullName:"", role:"operator" }); setUserMsg(isDari?"کاربر تایید شد. حالا می‌تواند از صفحه ورود، حساب خودش را با همین ایمیل بسازد.":"User approved. They can now create their account with this email from the sign-in screen."); setTimeout(()=>setUserMsg(""), 5000); }; const removeUser = async (id) => { if(id === currentUser.id){ alert(t.cust.noUserDeleteSelf); return; } if(users.length<=1){ alert(ts.keepOneUser); return; } if(!window.confirm(ts.removeUserConfirm)) return; const u = users.find(x=>x.id===id); if(u && u.username){ try{ await FBStore.removeMember(u.username); } catch(e){ alert((isDari?"خطا در لغو دسترسی: ":"Error revoking access: ")+((e&&e.message)||e)); return; } } setUsers(users.filter(u=>u.id!==id)); }; const [pwBusy, setPwBusy] = useState(false); const changePassword = async () => { if(!pwForm.current.trim()){ setPwMsg(ts.pwWrong); return; } if(!pwForm.next.trim() || pwForm.next.length < 6){ setPwMsg(isDari?"رمز عبور جدید باید حداقل ۶ کاراکتر باشد.":"New password must be at least 6 characters."); return; } setPwBusy(true); try{ await FBStore.changePassword(pwForm.current, pwForm.next); setPwMsg(ts.pwOk); setPwForm({current:"", next:""}); }catch(e){ setPwMsg(mapAuthError(e && e.code, isDari) || ts.pwWrong); } setPwBusy(false); setTimeout(()=>setPwMsg(""), 3500); }; return (

{ts.title}

{ts.sub}

{/* CONTENT AREA */}
{/* COMPANY INFO */} {activeSettings==="company" && (

{ts.coInfo}

setCompanyForm({...companyForm, nameDari:e.target.value})}/>
setCompanyForm({...companyForm, nameEn:e.target.value})}/>
setCompanyForm({...companyForm, address:e.target.value})} placeholder={ts.coAddressPh}/>
setCompanyForm({...companyForm, phone:e.target.value})} placeholder={ts.coPhonePh}/>
{savedCo && {ts.saved}}
)} {/* PASSWORD */} {activeSettings==="password" && (

{ts.pwTitle}

setPwForm({...pwForm, current:e.target.value})}/>
setPwForm({...pwForm, next:e.target.value})}/>
{pwMsg &&

{pwMsg}

}
)} {/* USERS */} {activeSettings==="users" && (

{ts.usersTitle}

{users.map(u=>( ))}
{ts.colFullName}{isDari?"ایمیل":"Email"}{ts.colRole}
{u.fullName} {u.username} {ts.roles[u.role] || u.role}

{ts.addUserTitle}

{isDari ? "کاربر را با ایمیل او تایید کنید. او می‌تواند بعداً با همین ایمیل، حساب خودش را از صفحه ورود بسازد و رمز عبور خودش را انتخاب کند." : "Approve the user by their email. They can then create their own account with that email from the sign-in screen and choose their own password."}

setNewUser({...newUser, fullName:e.target.value})}/>
setNewUser({...newUser, username:e.target.value})} placeholder="name@company.com"/>
{newUser.role==="admin" && (isDari?"دسترسی به همه صفحات، تنظیمات، کارمندان و هزینه‌ها":"Access to all pages, settings, employees and expenses")} {newUser.role==="cashier" && (isDari?"فقط ثبت رسید، مشاهده مشتریان و مدیریت قبض‌ها":"Receipt entry, customer view and bill management only")} {newUser.role==="viewer" && (isDari?"فقط مشاهده — نمی‌تواند رسید اضافه، ویرایش یا حذف کند":"View only — cannot add, edit or delete receipts")}
{userMsg &&

{userMsg}

}
)} {/* LANGUAGE */} {activeSettings==="language" && (

{t.language}

)} {/* THEME */} {activeSettings==="theme" && (

🎨 {isDari?(theme==="dark"?"حالت تاریک":"حالت روشن"):(theme==="dark"?"Dark Mode":"Light Mode")}

)} {activeSettings==="cloud" && ( )} {activeSettings==="backup" && (

{isDari?"بکاپ‌گیری و بازیابی داده‌ها":"Backup & Restore Data"}

{isDari?"داده‌ها در فضای ابری Firebase ذخیره می‌شوند. برای جلوگیری از از دست دادن اطلاعات، به طور منظم بکاپ بگیرید.":"Data is stored in the cloud (Firebase). Export regularly to prevent data loss."}

{/* Export */}
{isDari?"صدور بکاپ":"Export Backup"}

{isDari?"یک فایل JSON از تمام داده‌های شما دانلود می‌شود":"Downloads a JSON file with all your data"}

{/* Import */}
📂 {isDari?"بازیابی از بکاپ":"Restore from Backup"}

⚠️ {isDari?"این عمل داده‌های فعلی را جایگزین می‌کند":"This will replace all current data"}

{ const file = e.target.files[0]; if(!file) return; const reader = new FileReader(); reader.onload = (ev)=>{ try{ const parsed = JSON.parse(ev.target.result); if(!parsed.customers){ alert(isDari?"فایل نامعتبر است":"Invalid backup file"); return; } FBStore.restore(ev.target.result).then(()=>{ alert(isDari?"بازیابی موفق بود. صفحه بارگذاری مجدد می‌شود.":"Restore successful. Page will reload."); window.location.reload(); }).catch((e2)=>{ alert((isDari?"خطا در بازیابی: ":"Restore failed: ")+((e2&&e2.message)||e2)); }); }catch(err){ alert(isDari?"خطا در خواندن فایل":"Error reading file"); } }; reader.readAsText(file); e.target.value = ""; }}/>
{/* Storage info */}
ℹ️ {isDari?"وضعیت ذخیره‌سازی":"Storage Status"}
{(()=>{ const raw = FBStore.exportRaw(); const kb = raw ? (raw.length/1024).toFixed(1) : "0"; return isDari ? `حجم داده: ${kb} کیلوبایت · محل ذخیره: ابر (Firebase Firestore) · توصیه: هر هفته بکاپ بگیرید` : `Data size: ${kb} KB · Storage: Cloud (Firebase Firestore) · Tip: Back up weekly`; })()}
{/* Danger zone — admin only, requires being logged in (unlike the old pre-login reset link) */} {currentUser.role === "admin" && (
⚠️ {isDari?"منطقه خطر":"Danger Zone"}

{isDari?"بازنشانی سیستم تمام داده‌های ذخیره شده را حذف می‌کند. این کار قابل بازگشت نیست — قبل از انجام آن حتماً بکاپ بگیرید.":"Resetting the system deletes all saved data. This cannot be undone — export a backup first."}

)}
)}
); }