@davoodmehraban89 / Factor-easy / commits / 427da54
Fork 0

سامانه صدور فاکتور و حسابداری

v7.0 - index.html

davoodmehraban89 committed Sep 21, 2026 at 12:41 UTC 427da542f120e733f815bcf927c174222d293593
1 file changed +422 -263
index.html
+422 -263
@@ -5,8 +5,10 @@
5 <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6 <title>فینورا | سامانه صدور فاکتور و مدیریت مالی</title>
7 <link rel="manifest" href="manifest.json" />
8 +<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net data:; img-src 'self' data: blob:; connect-src 'self' https://hcsixhqbyuhpshfwqpjx.supabase.co; object-src 'none'; base-uri 'none'; form-action 'self'" />
9 <meta name="apple-mobile-web-app-capable" content="yes" />
10 <meta name="theme-color" content="#2563eb" />
11 +<script src="vendor/supabase.js"></script>
12 <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
13 <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
14 <style>
@@ -114,8 +116,8 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
116 <p style="font-size:12px;color:var(--text-muted);margin-top:4px">ورود یا ثبت‌نام در سامانه</p>
117 </div>
118 <div id="auth-form-container">
117 -<div class="form-group"><label>نام کاربری یا شماره همراه</label><input type="text" id="auth-username" class="form-control" placeholder="admin یا شماره همراه" /></div>
118 -<div class="form-group"><label>رمز عبور</label><input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" /></div>
119 +<div class="form-group"><label>نام کاربری (حروف انگلیسی، عدد، نقطه یا _)</label><input type="text" id="auth-username" class="form-control" placeholder="مثلاً ali.rezaei" autocomplete="username" autocapitalize="none" dir="ltr" /></div>
120 +<div class="form-group"><label>رمز عبور</label><input type="password" id="auth-password" class="form-control" placeholder="حداقل ۸ کاراکتر" autocomplete="current-password" dir="ltr" /></div>
121 <div style="display:flex;gap:10px;margin-top:16px">
122 <button class="btn btn-primary" style="flex:1" onclick="handleLogin()">ورود</button>
123 <button class="btn btn-secondary" style="flex:1" onclick="switchToRegister()">ثبت‌نام</button>
@@ -124,6 +126,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
126 </div>
127 </div>
128
129 +<div id="sync-badge" style="display:none;position:fixed;bottom:80px;left:12px;z-index:9999;color:#fff;padding:6px 12px;border-radius:999px;font-size:12px;box-shadow:0 2px 8px rgba(0,0,0,.25)"></div>
130 <div class="app-root">
131 <aside class="sidebar">
132 <div class="brand-box">
@@ -458,7 +461,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
461 <div class="accordion-body">
462 <h3 style="font-size:16px;font-weight:bold">فینورا - Finora</h3>
463 <p style="color:var(--text-muted);font-size:13px;margin:6px 0 12px 0">سامانه ابری صدور فاکتور و مدیریت مالی چندکاربره</p>
461 -<p style="font-size:13px;margin-bottom:8px">نگارش فعال: <strong>نسخه ۶.۰</strong></p>
464 +<p style="font-size:13px;margin-bottom:8px">نگارش فعال: <strong>نسخه ۷.۰</strong></p>
465 <div class="about-dev-card">
466 <div class="about-dev-avatar">د.م</div>
467 <div class="about-dev-info">
@@ -488,15 +491,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
491 <div><h2 style="font-size:18px;color:var(--danger)">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2><p style="color:var(--text-muted);font-size:13px;margin-top:4px">تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.</p></div>
492 <button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
493 </div>
491 -<div style="background:#f8fafc;border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:20px">
492 -<h4 style="font-size:14px;margin-bottom:12px;color:#1e293b">➕ ایجاد حساب کاربری جدید</h4>
493 -<div class="form-row">
494 -<div class="form-group"><label>نام کاربری</label><input type="text" id="admin-new-username" class="form-control" placeholder="نام کاربری..." /></div>
495 -<div class="form-group"><label>رمز عبور</label><input type="password" id="admin-new-password" class="form-control" placeholder="رمز عبور..." /></div>
496 -<div class="form-group"><label>طرح اولیه لایسنس</label><select id="admin-new-subtype" class="form-control"><option value="trial">آزمایشی (۱۵ روزه)</option><option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option><option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option><option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option><option value="lifetime">اشتراک دائمی (Lifetime)</option></select></div>
497 -<div class="form-group" style="display:flex;align-items:flex-end"><button class="btn btn-success" style="width:100%;min-height:44px" onclick="adminCreateNewUser()">➕ ایجاد کاربر</button></div>
498 -</div>
499 -</div>
494 +<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">کاربران خودشان از صفحه‌ی ورود ثبت‌نام می‌کنند و ۱۵ روز آزمایشی می‌گیرند. در این پنل فقط لایسنس‌ها (فعال‌سازی، تمدید، تغییر طرح، لغو) مدیریت می‌شود و کنترل نهایی روی سرور انجام می‌شود.</div>
495 <div class="table-responsive">
496 <table><thead><tr><th>نام کاربری</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead><tbody id="admin-users-table-body"><tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr></tbody></table>
497 </div>
@@ -638,84 +633,131 @@ function getRemainingDays(endDateStr){
633 function addDaysToDate(baseDateStr,days){
634 let d;
635 if(baseDateStr){const parts=String(baseDateStr).split('T')[0].split('-');d=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),12,0,0);}
641 - else d=new Date();
636 + else{const tp=todayISO().split('-');d=new Date(parseInt(tp[0]),parseInt(tp[1])-1,parseInt(tp[2]),12,0,0);}
637 if(isNaN(d.getTime()))d=new Date();
638 d.setDate(d.getDate()+days);
639 return d.toISOString().split('T')[0];
640 }
641
642 +const SUPABASE_URL='https://hcsixhqbyuhpshfwqpjx.supabase.co';
643 +const SUPABASE_KEY='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D'; // publishable (public by design); access is enforced by RLS on the server
644 +const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:false}});
645 +const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
646 +const USERNAME_RE=/^[a-z0-9_.]{3,32}$/;
647 +const COLLS=['companies','contacts','products','invoices','cheques','expenses','settings'];
648 +
649 +function esc(v){return String(v==null?'':v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}
650 +function todayISO(){return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
651 +
652 let currentUser=null;
648 -let usersDb=[];
649 -
650 -const defaultAdminUser={
651 - id:'user_admin',username:'admin',pass:'admin123',role:'admin',
652 - createdAt:'2026-09-16T00:00:00.000Z',
653 - subscriptionType:'lifetime',subscriptionStart:'2026-09-16',subscriptionEnd:'2099-01-01',
654 - licenseStatus:'active',
655 - subscription:{type:'lifetime',startDate:'2026-09-16',endDate:'2099-01-01',status:'active'}
656 -};
657 -
658 -function loadUsers(){
659 - const saved=localStorage.getItem(AUTH_KEY);
660 - if(saved){try{usersDb=JSON.parse(saved);}catch(e){usersDb=[];}}
661 - if(!Array.isArray(usersDb)||usersDb.length===0){usersDb=[defaultAdminUser];persistUsers();}
662 - else{
663 - let modified=false;
664 - usersDb.forEach((u,idx)=>{
665 - if(!u.id){u.id=u.username==='admin'?'user_admin':'usr_'+Date.now()+'_'+idx;modified=true;}
666 - if(!u.createdAt){u.createdAt=new Date().toISOString();modified=true;}
667 - if(!u.subscription){
668 - u.subscription={type:u.subscriptionType||'trial',startDate:u.subscriptionStart||new Date().toISOString().split('T')[0],endDate:u.subscriptionEnd||addDaysToDate(null,15),status:(u.subscriptionType==='lifetime'||u.role==='admin')?'active':'trial'};
669 - modified=true;
670 - }
671 - u.subscriptionType=u.subscription.type;
672 - u.subscriptionStart=u.subscription.startDate;
673 - u.subscriptionEnd=u.subscription.endDate;
674 - u.licenseStatus=u.subscription.status;
675 - });
676 - if(modified)persistUsers();
677 - }
678 - return usersDb;
679 -}
680 -function persistUsers(){localStorage.setItem(AUTH_KEY,JSON.stringify(usersDb));}
653 +let authBusy=false;
654
682 -function initAuthSystem(){
683 - loadUsers();
684 - const activeSession=sessionStorage.getItem('easy_factor_session_v4_7');
685 - if(activeSession){const u=usersDb.find(x=>x.username===activeSession);if(u){loginSuccess(u);return;}}
655 +function toAuthEmail(u){return u+'@finora.example.com';}
656 +function normalizeUsername(raw){
657 + return String(raw||'').trim().toLowerCase()
658 + .replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
659 + .replace(/[٠-٩]/g,d=>'٠١٢٣٤٥٦٧٨٩'.indexOf(d));
660 +}
661 +function buildUserFromRows(profile,lic){
662 + const sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
663 + return {id:profile.id,username:profile.username,role:profile.role,subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
664 +}
665 +async function fetchCurrentUser(authUser){
666 + const [p,l]=await Promise.all([
667 + sb.from('profiles').select('id,username,role').eq('id',authUser.id).single(),
668 + sb.from('licenses').select('plan,status,starts_at,ends_at').eq('user_id',authUser.id).single()
669 + ]);
670 + if(p.error)throw p.error;
671 + if(l.error)throw l.error;
672 + return buildUserFromRows(p.data,l.data);
673 +}
674 +function canWrite(){
675 + if(!currentUser)return false;
676 + const s=currentUser.subscription||{};
677 + if(s.status!=='active'&&s.status!=='trial')return false;
678 + if(s.type==='lifetime')return true;
679 + return String(s.endDate||'')>=todayISO();
680 +}
681 +function requireWrite(){
682 + if(canWrite())return true;
683 + alert('اشتراک شما منقضی یا لغو شده است؛ امکان ثبت یا ویرایش اطلاعات وجود ندارد. اطلاعات قبلی شما همچنان قابل مشاهده و پشتیبان‌گیری است. برای تمدید با پشتیبانی تماس بگیرید.');
684 + return false;
685 +}
686 +function authMsg(err){
687 + const m=(err&&err.message)||'';
688 + if(/Invalid login credentials/i.test(m))return 'نام کاربری یا رمز عبور اشتباه است.';
689 + if(/Email not confirmed/i.test(m))return 'تأیید ایمیل در سرور فعال است؛ به مدیر سیستم اطلاع دهید.';
690 + if(/already registered|already been registered/i.test(m))return 'این نام کاربری قبلاً ثبت‌نام کرده است.';
691 + if(/Database error/i.test(m))return 'ثبت‌نام انجام نشد؛ نام کاربری تکراری یا نامعتبر است.';
692 + if(/rate limit|too many/i.test(m))return 'تعداد تلاش‌ها زیاد است؛ کمی بعد دوباره امتحان کنید.';
693 + if(/fetch|network/i.test(m))return 'اتصال اینترنت برقرار نیست.';
694 + return 'خطا: '+m;
695 +}
696 +function readAuthForm(forRegister){
697 + const user=normalizeUsername(document.getElementById('auth-username').value);
698 + const pass=document.getElementById('auth-password').value;
699 + if(!USERNAME_RE.test(user)){alert('نام کاربری باید ۳ تا ۳۲ کاراکتر و فقط شامل حروف انگلیسی، عدد، نقطه و خط زیر باشد.');return null;}
700 + if(!pass){alert('رمز عبور را وارد کنید.');return null;}
701 + if(forRegister&&pass.length<8){alert('رمز عبور باید حداقل ۸ کاراکتر باشد.');return null;}
702 + return {user,pass};
703 +}
704 +async function initAuthSystem(){
705 + // Remove the legacy plaintext user database that older versions kept in this browser.
706 + try{localStorage.removeItem(AUTH_KEY);}catch(e){}
707 + try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
708 + sb.auth.onAuthStateChange(ev=>{if(ev==='SIGNED_OUT'&&currentUser){window.location.reload();}});
709 + try{
710 + const {data}=await sb.auth.getSession();
711 + if(data&&data.session){await enterApp(data.session.user);return;}
712 + }catch(e){console.error(e);}
713 document.getElementById('auth-screen').style.display='flex';
714 }
688 -function handleLogin(){
689 - const user=document.getElementById('auth-username').value.trim();
690 - const pass=document.getElementById('auth-password').value.trim();
691 - loadUsers();
692 - const found=usersDb.find(x=>x.username===user&&x.pass===pass);
693 - if(!found){alert('نام کاربری یا رمز عبور اشتباه است.');return;}
694 - sessionStorage.setItem('easy_factor_session_v4_7',found.username);
695 - loginSuccess(found);
696 -}
697 -function switchToRegister(){
698 - const user=document.getElementById('auth-username').value.trim();
699 - const pass=document.getElementById('auth-password').value.trim();
700 - if(!user||!pass){alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');return;}
701 - loadUsers();
702 - if(usersDb.some(x=>x.username===user)){alert('این نام کاربری قبلاً ثبت‌نام کرده است.');return;}
703 - const today=new Date().toISOString().split('T')[0];
704 - const expireStr=addDaysToDate(today,15);
705 - const newUser={id:'usr_'+Date.now()+'_'+Math.random().toString(36).substr(2,5),username:user,pass:pass,role:'user',createdAt:new Date().toISOString(),subscriptionType:'trial',subscriptionStart:today,subscriptionEnd:expireStr,licenseStatus:'trial',subscription:{type:'trial',startDate:today,endDate:expireStr,status:'trial'}};
706 - usersDb.push(newUser);persistUsers();
707 - sessionStorage.setItem('easy_factor_session_v4_7',newUser.username);
708 - alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
709 - loginSuccess(newUser);
710 -}
711 -function loginSuccess(userObj){
712 - currentUser=userObj;
715 +async function handleLogin(){
716 + if(authBusy)return;
717 + const f=readAuthForm(false);if(!f)return;
718 + authBusy=true;
719 + try{
720 + const {data,error}=await sb.auth.signInWithPassword({email:toAuthEmail(f.user),password:f.pass});
721 + if(error)throw error;
722 + await enterApp(data.user);
723 + }catch(err){alert(authMsg(err));}
724 + finally{authBusy=false;}
725 +}
726 +async function switchToRegister(){
727 + if(authBusy)return;
728 + const f=readAuthForm(true);if(!f)return;
729 + authBusy=true;
730 + try{
731 + const {data,error}=await sb.auth.signUp({email:toAuthEmail(f.user),password:f.pass,options:{data:{username:f.user}}});
732 + if(error)throw error;
733 + if(!data.session){alert('ثبت‌نام انجام شد اما ورود خودکار ممکن نیست؛ مدیر سیستم باید «تأیید ایمیل» را در تنظیمات سرور خاموش کند.');return;}
734 + alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
735 + await enterApp(data.user);
736 + }catch(err){alert(authMsg(err));}
737 + finally{authBusy=false;}
738 +}
739 +async function enterApp(authUser){
740 + try{
741 + currentUser=await fetchCurrentUser(authUser);
742 + await pullAll();
743 + }catch(err){
744 + console.error(err);
745 + currentUser=null;
746 + alert('خطا در بارگذاری اطلاعات حساب. اتصال اینترنت را بررسی کنید.');
747 + document.getElementById('auth-screen').style.display='flex';
748 + return;
749 + }
750 document.getElementById('auth-screen').style.display='none';
714 - document.getElementById('logged-user-label').innerText='کاربر: '+userObj.username+(userObj.role==='admin'?' (مدیر سیستم)':'');
715 - document.getElementById('menu-admin-panel').style.display=(userObj.role==='admin')?'block':'none';
716 - initDatastore();
751 + document.getElementById('logged-user-label').innerText='کاربر: '+currentUser.username+(currentUser.role==='admin'?' (مدیر سیستم)':'');
752 + document.getElementById('menu-admin-panel').style.display=(currentUser.role==='admin')?'block':'none';
753 + refreshAllSurfaces();
754 + maybeMigrateLegacyData();
755 +}
756 +async function handleLogout(){
757 + if(syncPending&&!confirm('تغییرات ذخیره‌نشده وجود دارد. با خروج ممکن است از بین برود. خارج شوم؟'))return;
758 + try{await sb.auth.signOut();}catch(e){}
759 + window.location.reload();
760 }
718 -function handleLogout(){sessionStorage.removeItem('easy_factor_session_v4_7');window.location.reload();}
761
762 function updateLicenseDisplay(user){
763 if(!user)return;
@@ -737,111 +779,70 @@ function updateLicenseDisplay(user){
779 }
780 }
781
740 -function adminCreateNewUser(){
741 - const username=document.getElementById('admin-new-username').value.trim();
742 - const pass=document.getElementById('admin-new-password').value.trim();
743 - const plan=document.getElementById('admin-new-subtype').value;
744 - if(!username||!pass){alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');return;}
745 - loadUsers();
746 - if(usersDb.some(u=>u.username===username)){alert('این نام کاربری از قبل وجود دارد.');return;}
747 - const today=new Date().toISOString().split('T')[0];
748 - let endDate=today;let status='active';
749 - if(plan==='trial'){endDate=addDaysToDate(today,15);status='trial';}
750 - else if(plan==='monthly')endDate=addDaysToDate(today,30);
751 - else if(plan==='three_months')endDate=addDaysToDate(today,90);
752 - else if(plan==='annual')endDate=addDaysToDate(today,365);
753 - else if(plan==='lifetime')endDate='2099-01-01';
754 - const newUser={id:'usr_'+Date.now()+'_'+Math.random().toString(36).substr(2,5),username,pass,role:'user',createdAt:new Date().toISOString(),subscriptionType:plan,subscriptionStart:today,subscriptionEnd:endDate,licenseStatus:status,subscription:{type:plan,startDate:today,endDate:endDate,status:status}};
755 - usersDb.push(newUser);persistUsers();
756 - alert(`کاربر جدید "${username}" با موفقیت ایجاد شد.`);
757 - document.getElementById('admin-new-username').value='';
758 - document.getElementById('admin-new-password').value='';
759 - renderAdminPanel();
760 -}
761 -function refreshAdminPanel(){loadUsers();renderAdminPanel();}
762 -function renderAdminPanel(){
782 +let adminUsersCache=[];
783 +async function renderAdminPanel(){
784 const tbody=document.getElementById('admin-users-table-body');
764 - if(!tbody)return;
765 - loadUsers();
766 - if(usersDb.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
785 + if(!tbody||!currentUser||currentUser.role!=='admin')return;
786 + tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr>';
787 + const [p,l]=await Promise.all([
788 + sb.from('profiles').select('id,username,role,created_at').order('created_at',{ascending:false}),
789 + sb.from('licenses').select('user_id,plan,status,starts_at,ends_at')
790 + ]);
791 + if(p.error||l.error){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--danger)">خطا در دریافت لیست کاربران.</td></tr>';return;}
792 + const lic=new Map((l.data||[]).map(x=>[x.user_id,x]));
793 + adminUsersCache=(p.data||[]).map(u=>Object.assign({},u,{lic:lic.get(u.id)||null}));
794 + if(adminUsersCache.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
795 const planLabels={monthly:'طرح ۱ ماهه',three_months:'طرح ۳ ماهه',annual:'طرح ۱ ساله',lifetime:'دائمی (Lifetime)',trial:'آزمایشی (Trial)'};
768 - tbody.innerHTML=usersDb.map(u=>{
769 - const sub=u.subscription||{type:u.subscriptionType||'trial',startDate:u.subscriptionStart,endDate:u.subscriptionEnd,status:u.licenseStatus||'trial'};
796 + tbody.innerHTML=adminUsersCache.map(u=>{
797 + const sub=u.lic?{type:u.lic.plan,startDate:u.lic.starts_at,endDate:u.lic.ends_at,status:u.lic.status}:{type:'trial',startDate:'',endDate:'',status:'cancelled'};
798 const remDays=getRemainingDays(sub.endDate);
799 const isExp=remDays<=0&&sub.type!=='lifetime';
800 let statusBadge='';
801 if(sub.status==='cancelled')statusBadge='<span class="badge badge-danger">لغو شده</span>';
802 else if(sub.status==='active')statusBadge=isExp?'<span class="badge badge-danger">منقضی شده</span>':'<span class="badge badge-success">فعال</span>';
803 else statusBadge=isExp?'<span class="badge badge-danger">آزمایشی منقضی</span>':'<span class="badge badge-warning">آزمایشی</span>';
776 - const startJalali=formatToJalali(sub.startDate);
804 const endJalali=sub.type==='lifetime'?'نامحدود':formatToJalali(sub.endDate);
805 const remDaysText=sub.type==='lifetime'?'نامحدود':toPersianDigits(Math.max(0,remDays))+' روز';
779 - return `<tr><td><strong>${u.username}</strong> ${u.role==='admin'?'<span class="badge badge-info">مدیر</span>':''}</td><td>${statusBadge}</td><td>${planLabels[sub.type]||sub.type}</td><td>${startJalali}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${u.username}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${u.username}')">تغییر مدت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${u.username}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${u.username}')">لغو اشتراک</button>`:''}</td></tr>`;
806 + const uid=esc(u.id);
807 + return `<tr><td><strong>${esc(u.username)}</strong> ${u.role==='admin'?'<span class="badge badge-info">مدیر</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">تغییر مدت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
808 }).join('');
809 }
782 -function adminActivateLicense(username){
783 - loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
784 - const today=new Date().toISOString().split('T')[0];
785 - const endDate=addDaysToDate(today,30);
786 - u.subscription={type:'monthly',startDate:today,endDate:endDate,status:'active'};
787 - u.subscriptionType='monthly';u.subscriptionStart=today;u.subscriptionEnd=endDate;u.licenseStatus='active';
788 - persistUsers();
789 - if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
790 - alert(`لایسنس ۱ ماهه فعال برای کاربر ${username} ثبت شد.`);
810 +function refreshAdminPanel(){renderAdminPanel();}
811 +async function adminRpc(name,args,okMsg){
812 + const {error}=await sb.rpc(name,args);
813 + if(error){alert('خطا: '+(error.message||'عملیات ناموفق بود.'));return false;}
814 + if(okMsg)alert(okMsg);
815 + if(currentUser&&args.target===currentUser.id){try{currentUser=await fetchCurrentUser({id:currentUser.id});updateLicenseDisplay(currentUser);}catch(e){}}
816 renderAdminPanel();
817 + return true;
818 }
793 -function openLicenseEditModal(username){
794 - loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
795 - document.getElementById('modal-license-target-username').value=username;
796 - document.getElementById('modal-license-user-title').innerText=`تغییر مدت و نوع لایسنس: ${username}`;
797 - document.getElementById('modal-license-duration-select').value=u.subscription?.type||'monthly';
819 +function adminActivateLicense(uid){
820 + return adminRpc('admin_set_license',{target:uid,new_plan:'monthly',days:30,new_status:'active'},'لایسنس ۱ ماهه فعال شد.');
821 +}
822 +function openLicenseEditModal(uid){
823 + const u=adminUsersCache.find(x=>x.id===uid);if(!u)return;
824 + document.getElementById('modal-license-target-username').value=uid;
825 + document.getElementById('modal-license-user-title').innerText='تغییر مدت و نوع لایسنس: '+u.username;
826 + const cur=u.lic&&u.lic.plan!=='trial'?u.lic.plan:'monthly';
827 + document.getElementById('modal-license-duration-select').value=cur;
828 document.getElementById('modal-admin-license-edit').classList.add('active');
829 }
830 function closeLicenseEditModal(){document.getElementById('modal-admin-license-edit').classList.remove('active');}
831 function applyLicenseDurationChange(){
802 - const username=document.getElementById('modal-license-target-username').value;
832 + const uid=document.getElementById('modal-license-target-username').value;
833 const plan=document.getElementById('modal-license-duration-select').value;
804 - loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
805 - const today=new Date().toISOString().split('T')[0];
806 - let endDate=today;
807 - if(plan==='monthly')endDate=addDaysToDate(today,30);
808 - else if(plan==='three_months')endDate=addDaysToDate(today,90);
809 - else if(plan==='annual')endDate=addDaysToDate(today,365);
810 - else if(plan==='lifetime')endDate='2099-01-01';
811 - u.subscription={type:plan,startDate:today,endDate:endDate,status:'active'};
812 - u.subscriptionType=plan;u.subscriptionStart=today;u.subscriptionEnd=endDate;u.licenseStatus='active';
813 - persistUsers();
814 - if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
834 closeLicenseEditModal();
816 - alert(`طرح لایسنس کاربر ${username} با موفقیت به "${plan}" تغییر یافت.`);
817 - renderAdminPanel();
835 + return adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'طرح لایسنس کاربر تغییر یافت.');
836 }
819 -function adminExtendSubscription(username,days){
820 - loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
821 - let currentEnd=u.subscription?.endDate||new Date().toISOString().split('T')[0];
822 - if(currentEnd.startsWith('2099')){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
823 - const today=new Date().toISOString().split('T')[0];
824 - const base=(currentEnd<today)?today:currentEnd;
825 - const newEnd=addDaysToDate(base,days);
826 - if(!u.subscription)u.subscription={};
827 - u.subscription.endDate=newEnd;
828 - u.subscription.status='active';
829 - if(u.subscription.type==='trial')u.subscription.type='monthly';
830 - u.subscriptionType=u.subscription.type;u.subscriptionEnd=newEnd;u.licenseStatus='active';
831 - persistUsers();
832 - if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
833 - alert(`اشتراک کاربر ${username} به مدت ${days} روز تمدید گردید.`);
834 - renderAdminPanel();
837 +function adminExtendSubscription(uid,days){
838 + const u=adminUsersCache.find(x=>x.id===uid);
839 + if(u&&u.lic&&u.lic.plan==='lifetime'){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
840 + return adminRpc('admin_extend_license',{target:uid,days},'اشتراک کاربر '+days+' روز تمدید شد.');
841 }
836 -function adminCancelSubscription(username){
837 - if(!confirm(`آیا از لغو اشتراک کاربر ${username} اطمینان دارید؟`))return;
838 - loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
839 - if(!u.subscription)u.subscription={};
840 - u.subscription.status='cancelled';u.licenseStatus='cancelled';
841 - persistUsers();
842 - if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
843 - alert(`اشتراک کاربر ${username} لغو گردید.`);
844 - renderAdminPanel();
842 +function adminCancelSubscription(uid){
843 + const u=adminUsersCache.find(x=>x.id===uid);
844 + if(!confirm('آیا از لغو اشتراک کاربر '+(u?u.username:'')+' اطمینان دارید؟'))return;
845 + return adminRpc('admin_cancel_license',{target:uid},'اشتراک کاربر لغو شد.');
846 }
847
848 let datastore={companies:[],contacts:[],products:[],invoices:[],cheques:[],expenses:[],settings:[]};
@@ -860,29 +861,176 @@ function getMySettings(){
861 if(typeof s.currency_custom==='undefined')s.currency_custom='';
862 return s;
863 }
863 -function saveDatastore(){try{localStorage.setItem(STORAGE_KEY,JSON.stringify(datastore));return true;}catch(err){console.error('Error saving datastore:',err);return false;}}
864 -function loadDatastore(){
865 - const persisted=localStorage.getItem(STORAGE_KEY);
866 - if(persisted){try{datastore=JSON.parse(persisted);}catch(e){console.error(e);}}
867 - ['companies','contacts','products','invoices','cheques','expenses','settings'].forEach(k=>{if(!Array.isArray(datastore[k]))datastore[k]=[];});
868 - if(datastore.companies.length===0&&datastore.products.length===0){
869 - datastore.companies.push({id:'COMP-1',ownerUserId:'user_admin',entity_type:'legal',name:'آرا سپهر راستین',phone:'09124376991',national_id:'14008507476',economic_code:'14008507476',reg_number:'544926',postal_code:'1445956311',address:'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',footer:'از خرید شما سپاسگزاریم.'});
870 - datastore.contacts.push({id:'C-1',ownerUserId:'user_admin',entity_type:'legal',name:'شرکت دانشگاه صنعتی شریف',mobile:'02166165000',national_id:'14002830256',economic_code:'14002830256',reg_number:'',postal_code:'1458889694',address:'طرشت محله تیموری پلاک 435',balance:7978300000,role:'customer'});
871 - datastore.products.push(
872 - {id:'P-1',ownerUserId:'user_admin',code:'1',name:'سوئیچ شبکه 24 پورت فیبر نوری',spec:'با 2 پاور 350',unit:'عدد',buy_price:1800000000,sale_price:2180000000,stock:10,type:'good',internal_id:''},
873 - {id:'P-2',ownerUserId:'user_admin',code:'2',name:'هارد 2.5 اینچ سرور',spec:'',unit:'عدد',buy_price:30000000,sale_price:37000000,stock:10,type:'good',internal_id:''}
874 - );
875 - datastore.settings.push({ownerUserId:'user_admin',invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'COMP-1',currency_mode:'rial',currency_custom:''});
876 - saveDatastore();
877 - }else{
878 - let migrated=false;
879 - ['companies','contacts','products','invoices','cheques','expenses'].forEach(coll=>{datastore[coll].forEach(item=>{if(!item.ownerUserId){item.ownerUserId='user_admin';migrated=true;}});});
880 - datastore.settings.forEach(s=>{if(typeof s.currency_mode==='undefined'){s.currency_mode='rial';migrated=true;}if(typeof s.currency_custom==='undefined'){s.currency_custom='';migrated=true;}});
881 - if(migrated)saveDatastore();
864 +// ---------- Cloud data layer (Supabase). UI code keeps using `datastore`; this layer syncs it. ----------
865 +const syncSnap=new Map();
866 +let syncTimer=null,syncRunning=false,syncAgain=false,syncPending=false,syncFailCount=0;
867 +
868 +function keyOfRecord(coll,item){return coll==='settings'?'main':String(item&&item.id!=null?item.id:'');}
869 +function stripOwner(item){const c=Object.assign({},item);delete c.ownerUserId;return c;}
870 +function setSyncBadge(state){
871 + const el=document.getElementById('sync-badge');if(!el)return;
872 + const map={saved:['✔ ذخیره شد','#059669'],saving:['⏳ در حال ذخیره…','#d97706'],error:['⚠️ ذخیره نشد؛ تلاش مجدد…','#dc2626']};
873 + const m=map[state];if(!m)return;
874 + el.textContent=m[0];el.style.background=m[1];el.style.display='block';
875 + clearTimeout(setSyncBadge._t);
876 + if(state==='saved')setSyncBadge._t=setTimeout(()=>{el.style.display='none';},2000);
877 +}
878 +async function pullAll(){
879 + const uid=currentUser.id;
880 + const fresh={};COLLS.forEach(k=>{fresh[k]=[];});
881 + const snap=new Map();
882 + const page=1000;let from=0;
883 + for(;;){
884 + const {data,error}=await sb.from('records').select('collection,id,data').order('collection').order('id').range(from,from+page-1);
885 + if(error)throw error;
886 + (data||[]).forEach(r=>{
887 + if(!fresh[r.collection])return;
888 + const obj=(r.data&&typeof r.data==='object'&&!Array.isArray(r.data))?r.data:{};
889 + obj.id=r.id;
890 + snap.set(r.collection+'|'+r.id,JSON.stringify(stripOwner(obj)));
891 + obj.ownerUserId=uid;
892 + fresh[r.collection].push(obj);
893 + });
894 + if(!data||data.length<page)break;
895 + from+=page;
896 + }
897 + datastore=fresh;
898 + syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));
899 +}
900 +function computeDiff(){
901 + const uid=currentUser.id;const up=[];const seen=new Set();
902 + COLLS.forEach(coll=>{(datastore[coll]||[]).forEach(item=>{
903 + if(!item||item.ownerUserId!==uid)return;
904 + const id=keyOfRecord(coll,item);
905 + if(!ID_RE.test(id)){console.warn('skipped record with invalid id',coll,id);return;}
906 + const key=coll+'|'+id;seen.add(key);
907 + const payload=stripOwner(item);const s=JSON.stringify(payload);
908 + if(syncSnap.get(key)!==s)up.push({key,coll,id,payload,s});
909 + });});
910 + const del=[];syncSnap.forEach((v,k)=>{if(!seen.has(k))del.push(k);});
911 + return {up,del};
912 +}
913 +function scheduleSync(ms){clearTimeout(syncTimer);syncTimer=setTimeout(runSync,ms);}
914 +async function runSync(){
915 + if(!currentUser)return;
916 + if(syncRunning){syncAgain=true;return;}
917 + syncRunning=true;
918 + try{
919 + let guardLoops=0;
920 + do{
921 + syncAgain=false;
922 + const {up,del}=computeDiff();
923 + if(up.length===0&&del.length===0)break;
924 + setSyncBadge('saving');
925 + for(let i=0;i<up.length;i+=200){
926 + const chunk=up.slice(i,i+200);
927 + const {error}=await sb.from('records').upsert(chunk.map(r=>({owner_id:currentUser.id,collection:r.coll,id:r.id,data:r.payload})),{onConflict:'owner_id,collection,id'});
928 + if(error)throw error;
929 + chunk.forEach(r=>syncSnap.set(r.key,r.s));
930 + }
931 + const byColl={};
932 + del.forEach(k=>{const j=k.indexOf('|');const c=k.slice(0,j),id=k.slice(j+1);(byColl[c]=byColl[c]||[]).push(id);});
933 + for(const c of Object.keys(byColl)){
934 + const ids=byColl[c];
935 + for(let i=0;i<ids.length;i+=100){
936 + const part=ids.slice(i,i+100);
937 + const {error}=await sb.from('records').delete().eq('collection',c).in('id',part);
938 + if(error)throw error;
939 + part.forEach(id=>syncSnap.delete(c+'|'+id));
940 + }
941 + }
942 + syncFailCount=0;
943 + guardLoops++;
944 + }while(guardLoops<5);
945 + const d=computeDiff();
946 + syncPending=(d.up.length>0||d.del.length>0);
947 + if(syncPending){scheduleSync(500);}else{setSyncBadge('saved');}
948 + }catch(err){
949 + console.error('sync error',err);
950 + await handleSyncError(err);
951 + }finally{syncRunning=false;}
952 +}
953 +async function handleSyncError(err){
954 + const msg=String((err&&err.message)||'');
955 + if((err&&err.code==='42501')||/row-level security/i.test(msg)){
956 + setSyncBadge('error');
957 + syncPending=false;
958 + alert('اشتراک شما منقضی یا لغو شده است؛ تغییرات ثبت نشد. برای تمدید با پشتیبانی تماس بگیرید.');
959 + try{currentUser=await fetchCurrentUser({id:currentUser.id});await pullAll();}catch(e){console.error(e);}
960 + refreshAllSurfaces();
961 + return;
962 + }
963 + syncFailCount++;syncPending=true;setSyncBadge('error');
964 + scheduleSync(Math.min(30000,2000*syncFailCount));
965 +}
966 +function saveDatastore(){
967 + if(!currentUser)return false;
968 + if(!canWrite()){
969 + requireWrite();
970 + pullAll().then(()=>refreshAllSurfaces()).catch(()=>{});
971 + return false;
972 + }
973 + syncPending=true;setSyncBadge('saving');scheduleSync(300);
974 + return true;
975 +}
976 +window.addEventListener('beforeunload',e=>{if(syncPending){e.preventDefault();e.returnValue='';}});
977 +document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden'&&syncPending){clearTimeout(syncTimer);runSync();}});
978 +
979 +// ---------- Untrusted input handling (backup files, legacy local data) ----------
980 +function neutralize(v){
981 + if(typeof v==='string')return v.replace(/</g,'<').replace(/>/g,'>');
982 + if(Array.isArray(v))return v.map(neutralize);
983 + if(v&&typeof v==='object'){const o={};Object.keys(v).forEach(k=>{if(k==='__proto__'||k==='constructor'||k==='prototype')return;o[k]=neutralize(v[k]);});return o;}
984 + return v;
985 +}
986 +function safeId(raw,prefix){
987 + let s=String(raw==null?'':raw).replace(/[^A-Za-z0-9_-]/g,'_').slice(0,64);
988 + if(!s)s=prefix+'_'+Date.now().toString(36)+Math.random().toString(36).slice(2,6);
989 + return s;
990 +}
991 +function absorbRecords(imported){
992 + const uid=currentUser.id;let count=0;
993 + ['companies','contacts','products','invoices','cheques','expenses'].forEach(key=>{
994 + if(!Array.isArray(imported[key]))return;
995 + imported[key].forEach(raw=>{
996 + if(!raw||typeof raw!=='object')return;
997 + const item=neutralize(raw);
998 + item.id=safeId(item.id,key.slice(0,3));
999 + item.ownerUserId=uid;
1000 + const idx=datastore[key].findIndex(x=>x.id===item.id&&x.ownerUserId===uid);
1001 + if(idx>=0)datastore[key][idx]=item;else datastore[key].push(item);
1002 + count++;
1003 + });
1004 + });
1005 + if(imported.settings&&typeof imported.settings==='object'&&!Array.isArray(imported.settings)){
1006 + const s=getMySettings();Object.assign(s,neutralize(imported.settings),{ownerUserId:uid,id:'main'});
1007 }
883 - return datastore;
1008 + return count;
1009 +}
1010 +function maybeMigrateLegacyData(){
1011 + try{
1012 + const flag='finora_legacy_done_'+currentUser.id;
1013 + if(localStorage.getItem(flag))return;
1014 + const rawOld=localStorage.getItem(STORAGE_KEY);
1015 + if(!rawOld)return;
1016 + let old;try{old=JSON.parse(rawOld);}catch(e){return;}
1017 + const isSeed=it=>it&&it.ownerUserId==='user_admin'&&['COMP-1','C-1','P-1','P-2'].includes(it.id);
1018 + const clean={};let n=0;
1019 + ['companies','contacts','products','invoices','cheques','expenses'].forEach(k=>{
1020 + clean[k]=(old&&Array.isArray(old[k])?old[k]:[]).filter(it=>!isSeed(it));
1021 + n+=clean[k].length;
1022 + });
1023 + if(n===0){localStorage.setItem(flag,'1');return;}
1024 + if(!confirm('اطلاعات ذخیره‌شده‌ی نسخه‌ی قبلی در این مرورگر پیدا شد ('+n+' مورد). به حساب ابری شما منتقل شود؟')){return;}
1025 + if(!requireWrite())return;
1026 + absorbRecords(clean);
1027 + saveDatastore();refreshAllSurfaces();
1028 + localStorage.setItem(flag,'1');
1029 + alert('اطلاعات قبلی به حساب ابری منتقل شد. نسخه‌ی محلی روی این مرورگر دست‌نخورده باقی می‌ماند.');
1030 + }catch(e){console.error(e);}
1031 }
885 -function initDatastore(){loadDatastore();refreshAllSurfaces();}
1032 +function initDatastore(){refreshAllSurfaces();}
1033 +
1034 function getJalaliDate(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{dateStyle:'full'}).format(new Date());}
1035 function getJalaliNumeric(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
1036 function getCurrencyLabel(){const s=getMySettings();if(s.currency_mode==='toman')return 'تومان';if(s.currency_mode==='custom')return (s.currency_custom||'').trim()||'واحد پول';return 'ریال';}
@@ -912,7 +1060,6 @@ function refreshAllSurfaces(){
1060 handleContactEntityChange();
1061 handleCurrencyModeChange();
1062 refreshCurrencyLabels();
915 - if(currentUser&&currentUser.role==='admin')renderAdminPanel();
1063 }
1064 function formatEntityName(rawName,entityType,customPrefix=''){
1065 let trimmed=(rawName||'').trim();
@@ -1015,6 +1162,7 @@ function applyDefaultSettingsToForm(){
1162 }
1163 }
1164 function commitSaveDefaultSettings(){
1165 + if(!requireWrite())return;
1166 const s=getMySettings();
1167 s.invoice_kind=document.getElementById('def-invoice-kind').value;
1168 s.vat_mode=document.getElementById('def-vat-mode').value;
@@ -1048,10 +1196,10 @@ function renderDashboard(){
1196 if(filteredInvoices.length===0){recentTbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr>';return;}
1197 recentTbody.innerHTML=filteredInvoices.slice(-5).reverse().map(inv=>`
1198 <tr>
1051 - <td><strong>#${inv.number}</strong></td>
1052 - <td>${inv.companyName||'—'}</td>
1053 - <td>${inv.contactName}</td>
1054 - <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${inv.kindLabel}</span></td>
1199 + <td><strong>#${esc(inv.number)}</strong></td>
1200 + <td>${esc(inv.companyName||'—')}</td>
1201 + <td>${esc(inv.contactName)}</td>
1202 + <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${esc(inv.kindLabel)}</span></td>
1203 <td>${inv.vat>0?'با ارزش افزوده':'بدون مالیات'}</td>
1204 <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1205 <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px;font-size:12px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
@@ -1075,7 +1223,7 @@ function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
1223 const tr=document.createElement('tr');
1224 tr.id=rowKey;
1225 const myProducts=getMyProducts();
1078 - const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${p.sale_price}" data-unit="${p.unit||'عدد'}" ${p.id===selectedProdId?'selected':''}>${p.name} ${p.spec?'('+p.spec+')':''}</option>`).join('');
1226 + const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${esc(p.sale_price)}" data-unit="${esc(p.unit||'عدد')}" ${p.id===selectedProdId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
1227 tr.innerHTML=`
1228 <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
1229 <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
@@ -1158,7 +1306,7 @@ function openElectronicDocModal(){
1306 html+=`<div style="border:1px solid var(--border);border-radius:8px;padding:10px;margin-bottom:8px;background:#f8fafc">
1307 <div style="font-weight:bold;font-size:13px;margin-bottom:8px">ردیف ${toPersianDigits(idx+1)}: ${prodName||'—'}</div>
1308 <div class="form-row">
1161 - <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت داخلی</label><input type="text" class="form-control edoc-row-internal" data-row="${idx}" value="${prod.internal_id||''}" /></div>
1309 + <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت داخلی</label><input type="text" class="form-control edoc-row-internal" data-row="${idx}" value="${esc(prod.internal_id||'')}" /></div>
1310 <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت <span style="color:var(--danger)">*</span></label><input type="text" class="form-control edoc-row-official" data-row="${idx}" value="" /></div>
1311 </div>
1312 </div>`;
@@ -1256,6 +1404,7 @@ function saveElectronicDocToPending(){
1404 }
1405
1406 function commitSaveInvoice(){
1407 + if(!requireWrite())return;
1408 if(!currentUser)return;
1409 const myCompanies=getMyCompanies();
1410 const mySettings=getMySettings();
@@ -1398,11 +1547,11 @@ function renderInvoices(){
1547 if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
1548 tbody.innerHTML=list.map(inv=>`
1549 <tr>
1401 - <td><strong>#${inv.number}</strong></td>
1402 - <td>${inv.companyName||'—'}</td>
1403 - <td>${inv.contactName}</td>
1404 - <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${inv.kindLabel}</span></td>
1405 - <td>${inv.date}</td>
1550 + <td><strong>#${esc(inv.number)}</strong></td>
1551 + <td>${esc(inv.companyName||'—')}</td>
1552 + <td>${esc(inv.contactName)}</td>
1553 + <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${esc(inv.kindLabel)}</span></td>
1554 + <td>${esc(inv.date)}</td>
1555 <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1556 <td>
1557 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
@@ -1440,23 +1589,23 @@ function buildElectronicDocPage(inv,edoc,seller,contact){
1589 const edItem=(edoc.items&&edoc.items[idx])?edoc.items[idx]:{};
1590 return `<tr>
1591 <td style="border:1px solid #000;padding:4px;text-align:center">${toPersianDigits(idx+1)}</td>
1443 - <td style="border:1px solid #000;padding:4px">${it.prodName||''}</td>
1592 + <td style="border:1px solid #000;padding:4px">${esc(it.prodName||'')}</td>
1593 <td style="border:1px solid #000;padding:4px;text-align:center">${toPersianDigits(it.qty)}</td>
1445 - <td style="border:1px solid #000;padding:4px;text-align:center">${it.unit||''}</td>
1594 + <td style="border:1px solid #000;padding:4px;text-align:center">${esc(it.unit||'')}</td>
1595 <td style="border:1px solid #000;padding:4px;text-align:left">${it.price.toLocaleString('fa-IR')}</td>
1596 <td style="border:1px solid #000;padding:4px;text-align:left">${line.toLocaleString('fa-IR')}</td>
1597 <td style="border:1px solid #000;padding:4px;text-align:center">${toPersianDigits(rowVatRate)}٪</td>
1598 <td style="border:1px solid #000;padding:4px;text-align:left">${vat.toLocaleString('fa-IR')}</td>
1599 <td style="border:1px solid #000;padding:4px;text-align:left">${total.toLocaleString('fa-IR')}</td>
1451 - <td style="border:1px solid #000;padding:4px;text-align:center">${edItem.internalId||''}</td>
1452 - <td style="border:1px solid #000;padding:4px;text-align:center">${edItem.officialId||''}</td>
1600 + <td style="border:1px solid #000;padding:4px;text-align:center">${esc(edItem.internalId||'')}</td>
1601 + <td style="border:1px solid #000;padding:4px;text-align:center">${esc(edItem.officialId||'')}</td>
1602 </tr>`;
1603 }).join('');
1604
1605 let contractText='';
1606 if(edoc.pattern==='پیمانکاری'&&edoc.contractId){
1607 contractText=items.map((it,idx)=>
1459 - `+ شناسه یکتای ثبت قرارداد حق‌العمل‌کاری برای ردیف ${toPersianDigits(idx+1)}: ${edoc.contractId} است`
1608 + `+ شناسه یکتای ثبت قرارداد حق‌العمل‌کاری برای ردیف ${toPersianDigits(idx+1)}: ${esc(edoc.contractId)} است`
1609 ).join('<br>');
1610 }
1611
@@ -1473,8 +1622,8 @@ function buildElectronicDocPage(inv,edoc,seller,contact){
1622 <div style="font-size:9.5px;color:#475569;margin-top:2px">(مطابق استاندارد سامانه مودیان)</div>
1623 </td>
1624 <td style="width:20%;vertical-align:top;padding:4px;font-size:9.5px;text-align:left">
1476 - <div>${seller.name||''}</div>
1477 - <div style="color:#475569">${seller.phone||''}</div>
1625 + <div>${esc(seller.name||'')}</div>
1626 + <div style="color:#475569">${esc(seller.phone||'')}</div>
1627 </td>
1628 </tr>
1629 </table>
@@ -1482,31 +1631,31 @@ function buildElectronicDocPage(inv,edoc,seller,contact){
1631 <table style="width:100%;border-collapse:collapse;border:1px solid #000;font-size:10px;margin-bottom:4px">
1632 <tr>
1633 <td style="border:1px solid #000;padding:4px;background:#f1f5f9;width:30%"><strong>شماره منحصر به فرد صورتحساب الکترونیکی مالیاتی</strong></td>
1485 - <td style="border:1px solid #000;padding:4px;width:70%">${edoc.uniqueNumber||'—'}</td>
1634 + <td style="border:1px solid #000;padding:4px;width:70%">${esc(edoc.uniqueNumber||'—')}</td>
1635 </tr>
1636 <tr>
1637 <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>شماره مالیاتی مندرج در برگه تشخیص</strong></td>
1489 - <td style="border:1px solid #000;padding:4px">${edoc.taxNumber||'—'}</td>
1638 + <td style="border:1px solid #000;padding:4px">${esc(edoc.taxNumber||'—')}</td>
1639 </tr>
1640 <tr>
1641 <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>تاریخ و زمان صدور صورتحساب الکترونیکی</strong></td>
1493 - <td style="border:1px solid #000;padding:4px">${edoc.issueDateTime||'—'}</td>
1642 + <td style="border:1px solid #000;padding:4px">${esc(edoc.issueDateTime||'—')}</td>
1643 </tr>
1644 <tr>
1645 <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>تاریخ صورتحساب الکترونیکی اصلی</strong></td>
1497 - <td style="border:1px solid #000;padding:4px">${edoc.originalDate||'—'}</td>
1646 + <td style="border:1px solid #000;padding:4px">${esc(edoc.originalDate||'—')}</td>
1647 </tr>
1648 <tr>
1649 <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>شماره صورتحساب الکترونیکی اصلی</strong></td>
1501 - <td style="border:1px solid #000;padding:4px">${edoc.originalNumber||'—'}</td>
1650 + <td style="border:1px solid #000;padding:4px">${esc(edoc.originalNumber||'—')}</td>
1651 </tr>
1652 <tr>
1653 <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>نوع صورتحساب</strong></td>
1505 - <td style="border:1px solid #000;padding:4px">${edoc.kind||'—'}</td>
1654 + <td style="border:1px solid #000;padding:4px">${esc(edoc.kind||'—')}</td>
1655 </tr>
1656 <tr>
1657 <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>موضوع صورتحساب</strong></td>
1509 - <td style="border:1px solid #000;padding:4px">${edoc.pattern||'—'}</td>
1658 + <td style="border:1px solid #000;padding:4px">${esc(edoc.pattern||'—')}</td>
1659 </tr>
1660 </table>
1661
@@ -1514,15 +1663,15 @@ function buildElectronicDocPage(inv,edoc,seller,contact){
1663 <tr><td colspan="4" style="border:1px solid #000;padding:4px;background:#f1f5f9;font-weight:bold">مشخصات فروشنده</td></tr>
1664 <tr>
1665 <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">نام شخص</td>
1517 - <td style="border:1px solid #000;padding:4px;width:35%">${seller.name||'—'}</td>
1666 + <td style="border:1px solid #000;padding:4px;width:35%">${esc(seller.name||'—')}</td>
1667 <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">شماره اقتصادی فروشنده</td>
1519 - <td style="border:1px solid #000;padding:4px;width:35%">${seller.economic_code||'0000'}</td>
1668 + <td style="border:1px solid #000;padding:4px;width:35%">${esc(seller.economic_code||'0000')}</td>
1669 </tr>
1670 <tr>
1671 <td style="border:1px solid #000;padding:4px;background:#f8fafc">شماره ثبت / شناسه ملی</td>
1523 - <td style="border:1px solid #000;padding:4px">${seller.national_id||'—'}</td>
1672 + <td style="border:1px solid #000;padding:4px">${esc(seller.national_id||'—')}</td>
1673 <td style="border:1px solid #000;padding:4px;background:#f8fafc">کد پستی</td>
1525 - <td style="border:1px solid #000;padding:4px">${seller.postal_code||'—'}</td>
1674 + <td style="border:1px solid #000;padding:4px">${esc(seller.postal_code||'—')}</td>
1675 </tr>
1676 </table>
1677
@@ -1530,15 +1679,15 @@ function buildElectronicDocPage(inv,edoc,seller,contact){
1679 <tr><td colspan="4" style="border:1px solid #000;padding:4px;background:#f1f5f9;font-weight:bold">مشخصات خریدار</td></tr>
1680 <tr>
1681 <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">نام شخص</td>
1533 - <td style="border:1px solid #000;padding:4px;width:35%">${contact.name||inv.contactName}</td>
1682 + <td style="border:1px solid #000;padding:4px;width:35%">${esc(contact.name||inv.contactName)}</td>
1683 <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">شماره اقتصادی خریدار</td>
1535 - <td style="border:1px solid #000;padding:4px;width:35%">${contact.economic_code||'0000'}</td>
1684 + <td style="border:1px solid #000;padding:4px;width:35%">${esc(contact.economic_code||'0000')}</td>
1685 </tr>
1686 <tr>
1687 <td style="border:1px solid #000;padding:4px;background:#f8fafc">شماره ثبت / شناسه ملی</td>
1539 - <td style="border:1px solid #000;padding:4px">${contact.national_id||'—'}</td>
1688 + <td style="border:1px solid #000;padding:4px">${esc(contact.national_id||'—')}</td>
1689 <td style="border:1px solid #000;padding:4px;background:#f8fafc">کد پستی</td>
1541 - <td style="border:1px solid #000;padding:4px">${contact.postal_code||'—'}</td>
1690 + <td style="border:1px solid #000;padding:4px">${esc(contact.postal_code||'—')}</td>
1691 </tr>
1692 </table>
1693
@@ -1589,11 +1738,11 @@ function buildElectronicDocPage(inv,edoc,seller,contact){
1738 <tr>
1739 <td style="width:50%;border:1px solid #000;padding:8px;height:70px;vertical-align:top">
1740 <div style="font-weight:bold;margin-bottom:4px">مهر و امضای فروشنده</div>
1592 - <div style="font-size:9.5px;color:#475569">${seller.name||''}</div>
1741 + <div style="font-size:9.5px;color:#475569">${esc(seller.name||'')}</div>
1742 </td>
1743 <td style="width:50%;border:1px solid #000;padding:8px;height:70px;vertical-align:top">
1744 <div style="font-weight:bold;margin-bottom:4px">مهر و امضای خریدار</div>
1596 - <div style="font-size:9.5px;color:#475569">${contact.name||inv.contactName}</div>
1745 + <div style="font-size:9.5px;color:#475569">${esc(contact.name||inv.contactName)}</div>
1746 </td>
1747 </tr>
1748 </table>
@@ -1650,17 +1799,17 @@ function buildFormalPage(items,seller,contact,inv,opt){
1799 const rowsHtml=items.map(li=>`
1800 <tr style="text-align:center">
1801 <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1653 - <td style="border:1px solid #1e293b;padding:3px 6px;text-align:right;font-size:10.5px;font-weight:600">${li.prodName}</td>
1802 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:right;font-size:10.5px;font-weight:600">${esc(li.prodName)}</td>
1803 <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
1655 - <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.unit}</td>
1804 + <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${esc(li.unit)}</td>
1805 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
1806 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1807 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineDiscount.toLocaleString('fa-IR')}</td>
1808 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineVat.toLocaleString('fa-IR')}</td>
1809 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px;font-weight:bold">${li.lineNet.toLocaleString('fa-IR')}</td>
1810 </tr>`).join('');
1662 - const sellerIds=`${seller.national_id||'—'} / ${seller.reg_number||'—'}`;
1663 - const contactIds=`${contact.national_id||'—'} / ${contact.reg_number||'—'}`;
1811 + const sellerIds=`${esc(seller.national_id||'—')} / ${esc(seller.reg_number||'—')}`;
1812 + const contactIds=`${esc(contact.national_id||'—')} / ${esc(contact.reg_number||'—')}`;
1813 const cumSub=opt.cumulativeSubtotal||0;
1814 const cumDisc=opt.cumulativeDiscount||0;
1815 const cumVat=opt.cumulativeVat||0;
@@ -1675,7 +1824,7 @@ function buildFormalPage(items,seller,contact,inv,opt){
1824 <tr>
1825 <td style="width:60%;border:1px solid #1e3a8a;padding:6px;vertical-align:top;background:#f8fafc">
1826 <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet,cur)}</div>
1678 - ${isLast?`<div style="margin-bottom:4px"><strong>شرایط و نحوه پرداخت:</strong> نقدی ☑ &nbsp;&nbsp;&nbsp; غیرنقدی (نسیه/چک) ☐</div><div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${inv.description||seller.footer||'تحویل کالا منوط به تسویه نهایی می‌باشد.'}</div>`:`<div style="font-size:9.5px;color:#64748b;margin-top:4px">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>`}
1827 + ${isLast?`<div style="margin-bottom:4px"><strong>شرایط و نحوه پرداخت:</strong> نقدی ☑ &nbsp;&nbsp;&nbsp; غیرنقدی (نسیه/چک) ☐</div><div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${esc(inv.description||seller.footer||'تحویل کالا منوط به تسویه نهایی می‌باشد.')}</div>`:`<div style="font-size:9.5px;color:#64748b;margin-top:4px">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>`}
1828 </td>
1829 <td style="width:40%;border:1px solid #1e3a8a;padding:0">
1830 <table style="width:100%;border-collapse:collapse;font-size:10.5px">
@@ -1703,8 +1852,8 @@ function buildFormalPage(items,seller,contact,inv,opt){
1852 <h1 style="font-size:15px;margin:0;font-weight:bold;color:#1e3a8a">صورتحساب فروش کالا و خدمات</h1>
1853 </td>
1854 <td style="width:28%;padding:5px;font-size:10.5px;vertical-align:middle;text-align:left">
1706 - <div>شماره سریال: <strong style="color:#b91c1c">${inv.number}</strong></div>
1707 - <div style="margin-top:1px">تاریخ صدور: <strong>${inv.date}</strong></div>
1855 + <div>شماره سریال: <strong style="color:#b91c1c">${esc(inv.number)}</strong></div>
1856 + <div style="margin-top:1px">تاریخ صدور: <strong>${esc(inv.date)}</strong></div>
1857 <div style="margin-top:1px;color:#64748b;font-size:9.5px">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1858 </td>
1859 </tr>
@@ -1713,38 +1862,38 @@ function buildFormalPage(items,seller,contact,inv,opt){
1862 <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">مشخصات فروشنده</td></tr>
1863 <tr>
1864 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
1716 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${seller.name||'—'}</strong></td>
1865 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${esc(seller.name||'—')}</strong></td>
1866 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
1718 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${seller.economic_code||'—'}</td>
1867 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${esc(seller.economic_code||'—')}</td>
1868 </tr>
1869 <tr>
1870 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
1871 <td style="border:1px solid #cbd5e1;padding:3px 6px">${sellerIds}</td>
1872 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
1724 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${seller.postal_code||'—'}</td>
1873 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${esc(seller.postal_code||'—')}</td>
1874 </tr>
1875 <tr>
1876 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
1728 - <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${seller.address||'—'} ${seller.phone?' | تلفن: '+seller.phone:''}</td>
1877 + <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${esc(seller.address||'—')} ${esc(seller.phone?' | تلفن: '+seller.phone:'')}</td>
1878 </tr>
1879 </table>
1880 <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px;margin-bottom:3px">
1881 <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">مشخصات خریدار</td></tr>
1882 <tr>
1883 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
1735 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${contact.name||inv.contactName}</strong></td>
1884 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${esc(contact.name||inv.contactName)}</strong></td>
1885 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
1737 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${contact.economic_code||'—'}</td>
1886 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${esc(contact.economic_code||'—')}</td>
1887 </tr>
1888 <tr>
1889 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
1890 <td style="border:1px solid #cbd5e1;padding:3px 6px">${contactIds}</td>
1891 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
1743 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${contact.postal_code||'—'}</td>
1892 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${esc(contact.postal_code||'—')}</td>
1893 </tr>
1894 <tr>
1895 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
1747 - <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${contact.address||'—'} ${contact.mobile?' | تلفن: '+contact.mobile:''}</td>
1896 + <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${esc(contact.address||'—')} ${esc(contact.mobile?' | تلفن: '+contact.mobile:'')}</td>
1897 </tr>
1898 </table>
1899 <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px">
@@ -1779,8 +1928,8 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
1928 const rowsHtml=items.map(li=>hasVat?`
1929 <tr style="text-align:center">
1930 <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.rowNo.toLocaleString('fa-IR')}</td>
1782 - <td style="border:1px solid #334155;padding:3px 6px;text-align:right;font-size:10px;font-weight:600">${li.prodName}</td>
1783 - <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.unit}</td>
1931 + <td style="border:1px solid #334155;padding:3px 6px;text-align:right;font-size:10px;font-weight:600">${esc(li.prodName)}</td>
1932 + <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${esc(li.unit)}</td>
1933 <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.qty.toLocaleString('fa-IR')}</td>
1934 <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.price.toLocaleString('fa-IR')}</td>
1935 <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
@@ -1789,8 +1938,8 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
1938 </tr>`:`
1939 <tr style="text-align:center">
1940 <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1792 - <td style="border:1px solid #334155;padding:4px 8px;text-align:right;font-size:10.5px;font-weight:600">${li.prodName}</td>
1793 - <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.unit}</td>
1941 + <td style="border:1px solid #334155;padding:4px 8px;text-align:right;font-size:10.5px;font-weight:600">${esc(li.prodName)}</td>
1942 + <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${esc(li.unit)}</td>
1943 <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
1944 <td style="border:1px solid #334155;padding:4px 5px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
1945 <td style="border:1px solid #334155;padding:4px 5px;text-align:left;font-size:10.5px;font-weight:bold">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
@@ -1809,7 +1958,7 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
1958 <tr>
1959 <td style="width:60%;border:1px solid #334155;padding:6px;vertical-align:top;background:#f8fafc">
1960 <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet,cur)}</div>
1812 - ${isLast?`<div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${inv.description||seller.footer||(isPre?'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.':'از خرید شما سپاسگزاریم.')}</div>`:`<div style="font-size:9.5px;color:#64748b">(ادامه در صفحه بعد...)</div>`}
1961 + ${isLast?`<div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${esc(inv.description||seller.footer||(isPre?'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.':'از خرید شما سپاسگزاریم.'))}</div>`:`<div style="font-size:9.5px;color:#64748b">(ادامه در صفحه بعد...)</div>`}
1962 </td>
1963 <td style="width:40%;border:1px solid #334155;padding:0">
1964 <table style="width:100%;border-collapse:collapse;font-size:10.5px">
@@ -1837,8 +1986,8 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
1986 <h1 style="font-size:15px;margin:0;font-weight:bold;color:#0f172a">${title}</h1>
1987 </td>
1988 <td style="width:30%;padding:6px;font-size:10.5px;vertical-align:middle;text-align:left">
1840 - <div>شماره: <strong style="font-size:11.5px">#${inv.number}</strong></div>
1841 - <div style="margin-top:1px">تاریخ: <strong>${inv.date}</strong></div>
1989 + <div>شماره: <strong style="font-size:11.5px">#${esc(inv.number)}</strong></div>
1990 + <div style="margin-top:1px">تاریخ: <strong>${esc(inv.date)}</strong></div>
1991 <div style="margin-top:1px;color:#64748b;font-size:9.5px">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1992 </td>
1993 </tr>
@@ -1847,15 +1996,15 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
1996 <tr>
1997 <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
1998 <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات فروشنده:</div>
1850 - <div>نام: <strong>${seller.name||'—'}</strong></div>
1851 - <div>نشانی: ${seller.address||'—'}</div>
1852 - <div>تلفن تماس: ${seller.phone||'—'}</div>
1999 + <div>نام: <strong>${esc(seller.name||'—')}</strong></div>
2000 + <div>نشانی: ${esc(seller.address||'—')}</div>
2001 + <div>تلفن تماس: ${esc(seller.phone||'—')}</div>
2002 </td>
2003 <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
2004 <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات خریدار:</div>
1856 - <div>نام: <strong>${contact.name||inv.contactName}</strong></div>
1857 - <div>نشانی: ${contact.address||'—'}</div>
1858 - <div>تلفن: ${contact.mobile||'—'}</div>
2005 + <div>نام: <strong>${esc(contact.name||inv.contactName)}</strong></div>
2006 + <div>نشانی: ${esc(contact.address||'—')}</div>
2007 + <div>تلفن: ${esc(contact.mobile||'—')}</div>
2008 </td>
2009 </tr>
2010 </table>
@@ -1918,6 +2067,7 @@ function renderAndPrintDirect(invId){
2067 printContainer.style.display='none';
2068 }
2069 function commitSaveProduct(){
2070 + if(!requireWrite())return;
2071 if(!currentUser)return;
2072 const myProducts=getMyProducts();
2073 const code=document.getElementById('prod-code-input').value||(myProducts.length+1).toString();
@@ -1940,9 +2090,10 @@ function renderProducts(){
2090 const tbody=document.getElementById('products-catalog-table-body');
2091 const myProducts=getMyProducts();
2092 if(myProducts.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ کالایی ثبت نشده است.</td></tr>';return;}
1943 - tbody.innerHTML=myProducts.map(p=>`<tr><td>${p.code}</td><td><strong>${p.name}</strong></td><td>${p.spec||'—'}</td><td>${p.unit}</td><td>${p.sale_price.toLocaleString('fa-IR')}</td><td>${p.internal_id||'—'}</td><td><button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="deleteProduct('${p.id}')">حذف</button></td></tr>`).join('');
2093 + tbody.innerHTML=myProducts.map(p=>`<tr><td>${esc(p.code)}</td><td><strong>${esc(p.name)}</strong></td><td>${esc(p.spec||'—')}</td><td>${esc(p.unit)}</td><td>${p.sale_price.toLocaleString('fa-IR')}</td><td>${esc(p.internal_id||'—')}</td><td><button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="deleteProduct('${p.id}')">حذف</button></td></tr>`).join('');
2094 }
2095 function deleteProduct(id){
2096 + if(!requireWrite())return;
2097 if(!currentUser)return;
2098 if(confirm('حذف شود؟')){
2099 datastore.products=datastore.products.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
@@ -1952,6 +2103,7 @@ function deleteProduct(id){
2103 function openQuickProductModal(){document.getElementById('modal-quick-product').classList.add('active');}
2104 function closeQuickProductModal(){document.getElementById('modal-quick-product').classList.remove('active');}
2105 function saveQuickProduct(){
2106 + if(!requireWrite())return;
2107 if(!currentUser)return;
2108 const myProducts=getMyProducts();
2109 const code=document.getElementById('quick-p-code').value||(myProducts.length+1).toString();
@@ -1976,6 +2128,7 @@ function downloadProductsExcelTemplate(){
2128 XLSX.writeFile(wb,"نمونه_کالاها_فینورا.xlsx");
2129 }
2130 function importProductsFromExcel(event){
2131 + if(!requireWrite())return;
2132 if(!currentUser)return;
2133 const file=event.target.files[0];
2134 if(!file)return;
@@ -1999,6 +2152,7 @@ function importProductsFromExcel(event){
2152 reader.readAsArrayBuffer(file);
2153 }
2154 function commitSaveContact(){
2155 + if(!requireWrite())return;
2156 if(!currentUser)return;
2157 const entity_type=document.getElementById('contact-entity-type').value;
2158 const custom_prefix=entity_type==='natural'?document.getElementById('contact-prefix-select')?.value:'';
@@ -2026,13 +2180,14 @@ function renderContacts(){
2180 if(myContacts.length===0){
2181 tbody.innerHTML='<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">هیچ طرف حسابی ثبت نشده است.</td></tr>';
2182 }else{
2029 - tbody.innerHTML=myContacts.map(c=>`<tr><td><strong>${c.name}</strong></td><td><span class="badge ${c.entity_type==='legal'?'badge-warning':'badge-success'}">${c.entity_type==='legal'?'حقوقی':'حقیقی'}</span></td><td>${c.national_id||'—'}</td><td>${c.economic_code||'—'}</td><td>${c.postal_code||'—'}</td><td>${c.mobile||'—'}</td><td>${Math.abs(c.balance||0).toLocaleString('fa-IR')}</td><td><button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="deleteContact('${c.id}')">حذف</button></td></tr>`).join('');
2183 + tbody.innerHTML=myContacts.map(c=>`<tr><td><strong>${esc(c.name)}</strong></td><td><span class="badge ${c.entity_type==='legal'?'badge-warning':'badge-success'}">${c.entity_type==='legal'?'حقوقی':'حقیقی'}</span></td><td>${esc(c.national_id||'—')}</td><td>${esc(c.economic_code||'—')}</td><td>${esc(c.postal_code||'—')}</td><td>${esc(c.mobile||'—')}</td><td>${Math.abs(c.balance||0).toLocaleString('fa-IR')}</td><td><button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="deleteContact('${c.id}')">حذف</button></td></tr>`).join('');
2184 }
2031 - const options=myContacts.map(c=>`<option value="${c.id}">${c.name}</option>`).join('');
2185 + const options=myContacts.map(c=>`<option value="${c.id}">${esc(c.name)}</option>`).join('');
2186 if(invSelect)invSelect.innerHTML=options;
2187 if(chqSelect)chqSelect.innerHTML=options;
2188 }
2189 function deleteContact(id){
2190 + if(!requireWrite())return;
2191 if(!currentUser)return;
2192 if(confirm('حذف شود؟')){
2193 datastore.contacts=datastore.contacts.filter(c=>!(c.id===id&&c.ownerUserId===currentUser.id));
@@ -2042,6 +2197,7 @@ function deleteContact(id){
2197 function openQuickContactModal(){document.getElementById('modal-quick-contact').classList.add('active');handleQuickCEntityChange();}
2198 function closeQuickContactModal(){document.getElementById('modal-quick-contact').classList.remove('active');}
2199 function saveQuickContact(){
2200 + if(!requireWrite())return;
2201 if(!currentUser)return;
2202 const entity_type=document.getElementById('quick-c-entity').value;
2203 const prefix=entity_type==='natural'?document.getElementById('quick-c-prefix')?.value:'';
@@ -2062,6 +2218,7 @@ function downloadContactsExcelTemplate(){
2218 XLSX.writeFile(wb,"نمونه_اشخاص_فینورا.xlsx");
2219 }
2220 function importContactsFromExcel(event){
2221 + if(!requireWrite())return;
2222 if(!currentUser)return;
2223 const file=event.target.files[0];
2224 if(!file)return;
@@ -2085,6 +2242,7 @@ function importContactsFromExcel(event){
2242 reader.readAsArrayBuffer(file);
2243 }
2244 function commitSaveCheque(){
2245 + if(!requireWrite())return;
2246 if(!currentUser)return;
2247 const direction=document.getElementById('chq-direction-input').value;
2248 const contactSelect=document.getElementById('chq-contact-select');
@@ -2101,9 +2259,10 @@ function commitSaveCheque(){
2259 function renderCheques(){
2260 const tbody=document.getElementById('cheques-ledger-table-body');
2261 const myCheques=getMyCheques();
2104 - tbody.innerHTML=myCheques.length===0?'<tr><td colspan="6" style="text-align:center;padding:20px;color:var(--text-muted)">چکی ثبت نشده است.</td></tr>':myCheques.map(c=>`<tr><td>${c.direction==='inbound'?'دریافتی':'پرداختی'}</td><td>${c.contactName}</td><td>${c.bank} - ${c.sayad_id}</td><td>${c.amount.toLocaleString('fa-IR')}</td><td>${c.due_date}</td><td>${c.status}</td></tr>`).join('');
2262 + tbody.innerHTML=myCheques.length===0?'<tr><td colspan="6" style="text-align:center;padding:20px;color:var(--text-muted)">چکی ثبت نشده است.</td></tr>':myCheques.map(c=>`<tr><td>${c.direction==='inbound'?'دریافتی':'پرداختی'}</td><td>${esc(c.contactName)}</td><td>${esc(c.bank)} - ${esc(c.sayad_id)}</td><td>${c.amount.toLocaleString('fa-IR')}</td><td>${esc(c.due_date)}</td><td>${esc(c.status)}</td></tr>`).join('');
2263 }
2264 function commitSaveExpense(){
2265 + if(!requireWrite())return;
2266 if(!currentUser)return;
2267 const amount=parseFloat(document.getElementById('trx-amount-input').value)||0;
2268 if(amount<=0){alert('مبلغ معتبر نیست.');return;}
@@ -2115,9 +2274,10 @@ function commitSaveExpense(){
2274 function renderExpenses(){
2275 const tbody=document.getElementById('expenses-ledger-table-body');
2276 const myExpenses=getMyExpenses();
2118 - tbody.innerHTML=myExpenses.length===0?'<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">موردی ثبت نشده است.</td></tr>':myExpenses.map(e=>`<tr><td>${e.kind}</td><td>${e.category}</td><td>${e.desc}</td><td>${e.amount.toLocaleString('fa-IR')}</td></tr>`).join('');
2277 + tbody.innerHTML=myExpenses.length===0?'<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">موردی ثبت نشده است.</td></tr>':myExpenses.map(e=>`<tr><td>${esc(e.kind)}</td><td>${esc(e.category)}</td><td>${esc(e.desc)}</td><td>${e.amount.toLocaleString('fa-IR')}</td></tr>`).join('');
2278 }
2279 function commitSaveCompany(){
2280 + if(!requireWrite())return;
2281 if(!currentUser)return;
2282 const entity_type=document.getElementById('company-entity-type').value;
2283 const raw_name=document.getElementById('company-name-input').value;
@@ -2142,21 +2302,22 @@ function renderCompanies(){
2302 if(myCompanies.length===0){
2303 tbody.innerHTML='<tr><td colspan="5" style="text-align:center;color:var(--text-muted);padding:20px">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
2304 }else{
2145 - tbody.innerHTML=myCompanies.map(c=>`<tr><td><strong>${c.name}</strong></td><td>${c.national_id||'—'}</td><td>${c.economic_code||'—'}</td><td>${c.id===defCompId?'<span class="badge badge-success">پیش‌فرض</span>':`<button class="btn btn-secondary btn-inline" style="padding:2px 8px;font-size:11px" onclick="setDefaultCompany('${c.id}')">انتخاب</button>`}</td><td>${myCompanies.length>1?`<button class="btn btn-danger btn-inline" style="padding:2px 8px;font-size:11px" onclick="deleteCompany('${c.id}')">حذف</button>`:'—'}</td></tr>`).join('');
2305 + tbody.innerHTML=myCompanies.map(c=>`<tr><td><strong>${esc(c.name)}</strong></td><td>${esc(c.national_id||'—')}</td><td>${esc(c.economic_code||'—')}</td><td>${c.id===defCompId?'<span class="badge badge-success">پیش‌فرض</span>':`<button class="btn btn-secondary btn-inline" style="padding:2px 8px;font-size:11px" onclick="setDefaultCompany('${c.id}')">انتخاب</button>`}</td><td>${myCompanies.length>1?`<button class="btn btn-danger btn-inline" style="padding:2px 8px;font-size:11px" onclick="deleteCompany('${c.id}')">حذف</button>`:'—'}</td></tr>`).join('');
2306 }
2307 }
2308 if(invoiceCompSelect){
2149 - invoiceCompSelect.innerHTML=myCompanies.map(c=>`<option value="${c.id}" ${c.id===defCompId?'selected':''}>${c.name}</option>`).join('');
2309 + invoiceCompSelect.innerHTML=myCompanies.map(c=>`<option value="${c.id}" ${c.id===defCompId?'selected':''}>${esc(c.name)}</option>`).join('');
2310 if(defCompId)invoiceCompSelect.value=defCompId;
2311 }
2312 if(filterCompSelect){
2313 const currentVal=filterCompSelect.value||'ALL';
2154 - filterCompSelect.innerHTML=`<option value="ALL">نمایش همه شرکت‌ها</option>`+myCompanies.map(c=>`<option value="${c.id}">فقط ${c.name}</option>`).join('');
2314 + filterCompSelect.innerHTML=`<option value="ALL">نمایش همه شرکت‌ها</option>`+myCompanies.map(c=>`<option value="${c.id}">فقط ${esc(c.name)}</option>`).join('');
2315 filterCompSelect.value=currentVal;
2316 }
2317 }
2158 -function setDefaultCompany(id){const s=getMySettings();s.default_company_id=id;saveDatastore();refreshAllSurfaces();}
2318 +function setDefaultCompany(id){if(!requireWrite())return;const s=getMySettings();s.default_company_id=id;saveDatastore();refreshAllSurfaces();}
2319 function deleteCompany(id){
2320 + if(!requireWrite())return;
2321 if(!currentUser)return;
2322 if(confirm('حذف شود؟')){
2323 datastore.companies=datastore.companies.filter(c=>!(c.id===id&&c.ownerUserId===currentUser.id));
@@ -2177,6 +2338,7 @@ function exportDataBlob(){
2338 anchor.remove();
2339 }
2340 function importDataBlob(event){
2341 + if(!requireWrite())return;
2342 if(!currentUser)return;
2343 const file=event.target.files[0];
2344 if(!file)return;
@@ -2184,11 +2346,8 @@ function importDataBlob(event){
2346 reader.onload=function(e){
2347 try{
2348 const imported=JSON.parse(e.target.result);
2187 - const userId=currentUser.id;
2188 - ['companies','contacts','products','invoices','cheques','expenses'].forEach(key=>{
2189 - if(Array.isArray(imported[key])){imported[key].forEach(item=>{item.ownerUserId=userId;datastore[key].push(item);});}
2190 - });
2191 - if(imported.settings){const s=getMySettings();Object.assign(s,imported.settings,{ownerUserId:userId});}
2349 + if(!imported||typeof imported!=='object')throw new Error('bad');
2350 + absorbRecords(imported);
2351 saveDatastore();refreshAllSurfaces();
2352 alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
2353 }catch(err){alert('فایل نامعتبر است.');}
@@ -2253,8 +2412,8 @@ window.addEventListener('DOMContentLoaded',()=>{initAuthSystem();});
2412 if(typeof oldSave === 'function') return oldSave();
2413 };
2414 window.FinoraHealth = {
2256 - version: '6.0-finora',
2257 - storage: 'localStorage',
2415 + version: '7.0-finora',
2416 + storage: 'supabase',
2417 checks(){ return { rtl: document.documentElement.dir === 'rtl', storage: !!window.localStorage, printReady: !!document.getElementById('printable-invoice') }; }
2418 };
2419 })();