@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / f1922a9
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 17:00 UTC

Update index.html

davoodmehraban89 committed Sep 18, 2026 at 01:18 UTC f1922a934a2e6a6d6660f277d352f4f7a28a4e84
1 file changed +860 -1116
index.html
+860 -1116
@@ -3,7 +3,7 @@
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6 -<title>ایزی فاکتور | سامانه صدور فاکتور و مدیریت مالی</title>
6 +<title>فینورا | سامانه صدور فاکتور و مدیریت مالی</title>
7 <link rel="manifest" href="manifest.json" />
8 <meta name="apple-mobile-web-app-capable" content="yes" />
9 <meta name="theme-color" content="#2563eb" />
@@ -19,7 +19,7 @@ body{background-color:var(--bg);color:var(--text);font-size:14px}
19 .app-root{display:flex;min-height:100vh;width:100%;max-width:100%;overflow-x:hidden}
20 .sidebar{width:var(--sidebar-w);background:var(--card-bg);border-left:1px solid var(--border);display:flex;flex-direction:column;position:fixed;top:0;bottom:0;right:0;z-index:100}
21 .brand-box{padding:20px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--border)}
22 -.brand-icon{width:40px;height:40px;background:var(--primary);border-radius:10px;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold;font-size:18px}
22 +.brand-icon{width:40px;height:40px;background:var(--primary);border-radius:10px;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold;font-size:14px}
23 .sidebar-menu{list-style:none;padding:16px 8px;flex:1;overflow-y:auto}
24 .sidebar-menu li a{display:flex;align-items:center;gap:12px;padding:12px 16px;color:var(--text);text-decoration:none;border-radius:8px;margin-bottom:4px;font-size:14px;font-weight:500;transition:all .2s;cursor:pointer}
25 .sidebar-menu li a:hover,.sidebar-menu li a.active{background:#eff6ff;color:var(--primary);font-weight:bold}
@@ -109,8 +109,8 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
109 <div id="auth-screen">
110 <div class="auth-card">
111 <div style="text-align:center;margin-bottom:20px">
112 -<div style="width:50px;height:50px;background:var(--primary);color:#fff;font-weight:bold;font-size:24px;border-radius:12px;display:inline-flex;align-items:center;justify-content:center;margin-bottom:10px">ایزی</div>
113 -<h2 style="font-size:20px;font-weight:bold;color:var(--text)">سامانه ایزی فاکتور</h2>
112 +<div style="width:50px;height:50px;background:var(--primary);color:#fff;font-weight:bold;font-size:18px;border-radius:12px;display:inline-flex;align-items:center;justify-content:center;margin-bottom:10px">فینورا</div>
113 +<h2 style="font-size:20px;font-weight:bold;color:var(--text)">سامانه فینورا</h2>
114 <p style="font-size:12px;color:var(--text-muted);margin-top:4px">ورود یا ثبت‌نام در سامانه</p>
115 </div>
116 <div id="auth-form-container">
@@ -127,8 +127,8 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
127 <div class="app-root">
128 <aside class="sidebar">
129 <div class="brand-box">
130 -<div class="brand-icon">ایزی</div>
131 -<div><h2 style="font-size:15px;font-weight:bold">ایزی فاکتور</h2><small style="color:var(--text-muted);font-size:11px">نسخه چندکاربره ۵.۲</small></div>
130 +<div class="brand-icon">فینورا</div>
131 +<div><h2 style="font-size:15px;font-weight:bold">فینورا</h2><small style="color:var(--text-muted);font-size:11px">نسخه چندکاربره ۶.۰</small></div>
132 </div>
133 <ul class="sidebar-menu">
134 <li><a href="#" class="nav-link" data-view="view-dashboard" onclick="switchView('view-dashboard');return false">📊 داشبورد تحلیلی</a></li>
@@ -146,7 +146,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
146 </div>
147 </aside>
148
149 -<a class="whatsapp-support no-print" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener" title="پشتیبانی واتس‌اپ">
149 +<a class="whatsapp-support no-print" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20فینورا%20سؤال%20داشتم." target="_blank" rel="noopener" title="پشتیبانی واتس‌اپ">
150 <svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
151 <span>پشتیبانی واتس‌اپ</span>
152 </a>
@@ -155,7 +155,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
155
156 <section id="view-dashboard" class="view-pane active">
157 <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
158 -<div><h1 style="font-size:20px;font-weight:bold">سامانه ایزی فاکتور</h1><p style="color:var(--text-muted);font-size:13px" id="dashboard-date-display"></p></div>
158 +<div><h1 style="font-size:20px;font-weight:bold">سامانه فینورا</h1><p style="color:var(--text-muted);font-size:13px" id="dashboard-date-display"></p></div>
159 <div style="display:flex;align-items:center;gap:10px">
160 <span id="user-license-status-badge" class="badge badge-warning">در حال بررسی...</span>
161 <button class="btn btn-inline no-print" onclick="startNewInvoice()">➕ فاکتور جدید</button>
@@ -188,7 +188,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
188 </div>
189 <div><h3 style="font-size:15px;color:#166534">پشتیبانی سریع</h3><p style="font-size:12.5px;color:#475569;margin-top:2px">سؤالی دارید؟ از طریق واتس‌اپ با ما در تماس باشید.</p></div>
190 </div>
191 -<a href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener" class="btn btn-inline" style="background:linear-gradient(135deg,#25D366,#128C7E)">💬 گفتگو در واتس‌اپ</a>
191 +<a href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20فینورا%20سؤال%20داشتم." target="_blank" rel="noopener" class="btn btn-inline" style="background:linear-gradient(135deg,#25D366,#128C7E)">💬 گفتگو در واتس‌اپ</a>
192 </div>
193 </div>
194 </section>
@@ -200,7 +200,6 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
200 <button class="btn btn-secondary btn-inline" style="display:none;padding:4px 10px;font-size:12px" id="btn-cancel-edit" onclick="cancelInvoiceEdit()">انصراف از ویرایش</button>
201 </div>
202 <input type="hidden" id="edit-invoice-id" value="" />
203 -
203 <div class="form-row" style="background:#f1f5f9;padding:12px;border-radius:10px;margin-bottom:14px">
204 <div class="form-group" style="margin-bottom:0"><label>تاریخ فاکتور</label><input type="text" id="invoice-date-input" class="form-control" /></div>
205 <div class="form-group" style="margin-bottom:0"><label>شماره فاکتور</label><input type="text" id="invoice-number" class="form-control" placeholder="PINV-31" /></div>
@@ -213,7 +212,6 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
212 </select>
213 </div>
214 </div>
216 -
215 <div class="form-row">
216 <div class="form-group"><label>فروشنده (سربرگ شرکت)</label><select id="invoice-company-id" class="form-control" onchange="onActiveCompanyFilterChange()"></select></div>
217 <div class="form-group">
@@ -224,7 +222,6 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
222 </div>
223 </div>
224 </div>
227 -
225 <div style="margin:16px 0">
226 <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
227 <h4 style="font-size:14px">اقلام کالا یا خدمات</h4>
@@ -238,7 +235,6 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
235 </div>
236 <button class="btn btn-secondary btn-inline" style="margin-top:10px;width:100%;border:1.5px dashed var(--primary);color:var(--primary);background:#eff6ff" onclick="addInvoiceItemRow()">+ افزودن ردیف</button>
237 </div>
241 -
238 <div class="form-row" style="background:#f1f5f9;padding:14px;border-radius:10px;margin-top:12px">
239 <div class="form-group" style="background:#fff;padding:12px;border-radius:8px;border:1px solid var(--border);margin-bottom:0">
240 <label style="font-weight:bold;border-bottom:1px solid #eee;padding-bottom:6px;margin-bottom:8px">مالیات و تخفیف</label>
@@ -267,11 +263,9 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
263 <div style="font-size:11px;color:var(--text-muted);margin-top:4px" id="summary-words">به حروف: صفر ریال</div>
264 </div>
265 </div>
270 -
266 <div class="form-row" style="margin-top:14px">
267 <div class="form-group" style="margin-bottom:0"><label>توضیحات فاکتور</label><textarea id="invoice-desc-input" class="form-control" rows="2" placeholder="توضیحات تکمیلی..."></textarea></div>
268 </div>
274 -
269 <div style="display:flex;gap:10px;margin-top:16px;flex-wrap:wrap">
270 <button class="btn btn-success" id="btn-save-invoice" onclick="commitSaveInvoice()">💾 ثبت فاکتور</button>
271 </div>
@@ -454,9 +448,9 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
448 <div class="accordion-item">
449 <div class="accordion-header" onclick="toggleAccordion(this)"><span>ℹ️ درباره نرم‌افزار</span><span>▼</span></div>
450 <div class="accordion-body">
457 -<h3 style="font-size:16px;font-weight:bold">ایزی فاکتور - EasyFactor</h3>
451 +<h3 style="font-size:16px;font-weight:bold">فینورا - Finora</h3>
452 <p style="color:var(--text-muted);font-size:13px;margin:6px 0 12px 0">سامانه ابری صدور فاکتور و مدیریت مالی چندکاربره</p>
459 -<p style="font-size:13px;margin-bottom:8px">نگارش فعال: <strong>نسخه ۵.۲</strong></p>
453 +<p style="font-size:13px;margin-bottom:8px">نگارش فعال: <strong>نسخه ۶.۰</strong></p>
454 <div class="about-dev-card">
455 <div class="about-dev-avatar">د.م</div>
456 <div class="about-dev-info">
@@ -465,7 +459,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
459 <p>📱 <span dir="ltr" style="font-family:Tahoma">0912-437-6991</span></p>
460 </div>
461 <div class="about-dev-actions">
468 -<a class="btn-wa" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener">
462 +<a class="btn-wa" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20فینورا%20سؤال%20داشتم." target="_blank" rel="noopener">
463 <svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
464 واتس‌اپ
465 </a>
@@ -574,697 +568,550 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
568 const STORAGE_KEY = 'easy_factor_commercial_v4_7';
569 const AUTH_KEY = 'easy_factor_auth_users_v4_7';
570
577 -function toPersianDigits(str) {
578 - if (str === null || str === undefined) return '';
579 - return String(str).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
580 -}
581 -
582 -function formatToJalali(dateInput) {
583 - if (!dateInput) return '—';
571 +function toPersianDigits(str){if(str===null||str===undefined)return '';return String(str).replace(/[0-9]/g,d=>'۰۱۲۳۴۵۶۷۸۹'[d]);}
572 +function formatToJalali(dateInput){
573 + if(!dateInput)return '—';
574 let dateObj;
585 - if (dateInput instanceof Date) dateObj = dateInput;
586 - else if (typeof dateInput === 'string' && dateInput.includes('/')) return toPersianDigits(dateInput);
587 - else {
588 - const str = String(dateInput).split('T')[0];
589 - const parts = str.split('-');
590 - if (parts.length === 3) dateObj = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
591 - else dateObj = new Date(dateInput);
592 - }
593 - if (isNaN(dateObj.getTime())) return toPersianDigits(String(dateInput));
594 - return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(dateObj);
595 -}
596 -
597 -function getRemainingDays(endDateStr) {
598 - if (!endDateStr) return 0;
599 - if (String(endDateStr).startsWith('2099')) return Infinity;
600 - const str = String(endDateStr).split('T')[0];
601 - const parts = str.split('-');
602 - if (parts.length !== 3) return 0;
603 - const end = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 23, 59, 59);
604 - const now = new Date();
605 - return Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
606 -}
607 -
608 -function addDaysToDate(baseDateStr, days) {
575 + if(dateInput instanceof Date)dateObj=dateInput;
576 + else if(typeof dateInput==='string'&&dateInput.includes('/'))return toPersianDigits(dateInput);
577 + else{const str=String(dateInput).split('T')[0];const parts=str.split('-');if(parts.length===3)dateObj=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),12,0,0);else dateObj=new Date(dateInput);}
578 + if(isNaN(dateObj.getTime()))return toPersianDigits(String(dateInput));
579 + return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(dateObj);
580 +}
581 +function getRemainingDays(endDateStr){
582 + if(!endDateStr)return 0;
583 + if(String(endDateStr).startsWith('2099'))return Infinity;
584 + const str=String(endDateStr).split('T')[0];const parts=str.split('-');
585 + if(parts.length!==3)return 0;
586 + const end=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),23,59,59);
587 + return Math.ceil((end.getTime()-new Date().getTime())/(1000*60*60*24));
588 +}
589 +function addDaysToDate(baseDateStr,days){
590 let d;
610 - if (baseDateStr) {
611 - const parts = String(baseDateStr).split('T')[0].split('-');
612 - d = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
613 - } else d = new Date();
614 - if (isNaN(d.getTime())) d = new Date();
615 - d.setDate(d.getDate() + days);
591 + 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);}
592 + else d=new Date();
593 + if(isNaN(d.getTime()))d=new Date();
594 + d.setDate(d.getDate()+days);
595 return d.toISOString().split('T')[0];
596 }
597
619 -let currentUser = null;
620 -let usersDb = [];
598 +let currentUser=null;
599 +let usersDb=[];
600
622 -const defaultAdminUser = {
623 - id: 'user_admin', username: 'admin', pass: 'admin123', role: 'admin',
624 - createdAt: '2026-09-16T00:00:00.000Z',
625 - subscriptionType: 'lifetime', subscriptionStart: '2026-09-16', subscriptionEnd: '2099-01-01',
626 - licenseStatus: 'active',
627 - subscription: { type: 'lifetime', startDate: '2026-09-16', endDate: '2099-01-01', status: 'active' }
601 +const defaultAdminUser={
602 + id:'user_admin',username:'admin',pass:'admin123',role:'admin',
603 + createdAt:'2026-09-16T00:00:00.000Z',
604 + subscriptionType:'lifetime',subscriptionStart:'2026-09-16',subscriptionEnd:'2099-01-01',
605 + licenseStatus:'active',
606 + subscription:{type:'lifetime',startDate:'2026-09-16',endDate:'2099-01-01',status:'active'}
607 };
608
630 -function loadUsers() {
631 - const saved = localStorage.getItem(AUTH_KEY);
632 - if (saved) { try { usersDb = JSON.parse(saved); } catch (e) { usersDb = []; } }
633 - if (!Array.isArray(usersDb) || usersDb.length === 0) {
634 - usersDb = [defaultAdminUser]; persistUsers();
635 - } else {
636 - let modified = false;
637 - usersDb.forEach((u, idx) => {
638 - if (!u.id) { u.id = u.username === 'admin' ? 'user_admin' : 'usr_' + Date.now() + '_' + idx; modified = true; }
639 - if (!u.createdAt) { u.createdAt = new Date().toISOString(); modified = true; }
640 - if (!u.subscription) {
641 - u.subscription = {
642 - type: u.subscriptionType || 'trial',
643 - startDate: u.subscriptionStart || new Date().toISOString().split('T')[0],
644 - endDate: u.subscriptionEnd || addDaysToDate(null, 15),
645 - status: (u.subscriptionType === 'lifetime' || u.role === 'admin') ? 'active' : 'trial'
646 - };
647 - modified = true;
609 +function loadUsers(){
610 + const saved=localStorage.getItem(AUTH_KEY);
611 + if(saved){try{usersDb=JSON.parse(saved);}catch(e){usersDb=[];}}
612 + if(!Array.isArray(usersDb)||usersDb.length===0){usersDb=[defaultAdminUser];persistUsers();}
613 + else{
614 + let modified=false;
615 + usersDb.forEach((u,idx)=>{
616 + if(!u.id){u.id=u.username==='admin'?'user_admin':'usr_'+Date.now()+'_'+idx;modified=true;}
617 + if(!u.createdAt){u.createdAt=new Date().toISOString();modified=true;}
618 + if(!u.subscription){
619 + 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'};
620 + modified=true;
621 }
649 - u.subscriptionType = u.subscription.type;
650 - u.subscriptionStart = u.subscription.startDate;
651 - u.subscriptionEnd = u.subscription.endDate;
652 - u.licenseStatus = u.subscription.status;
622 + u.subscriptionType=u.subscription.type;
623 + u.subscriptionStart=u.subscription.startDate;
624 + u.subscriptionEnd=u.subscription.endDate;
625 + u.licenseStatus=u.subscription.status;
626 });
654 - if (modified) persistUsers();
627 + if(modified)persistUsers();
628 }
629 return usersDb;
630 }
631 +function persistUsers(){localStorage.setItem(AUTH_KEY,JSON.stringify(usersDb));}
632
659 -function persistUsers() { localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb)); }
660 -
661 -function initAuthSystem() {
633 +function initAuthSystem(){
634 loadUsers();
663 - const activeSession = sessionStorage.getItem('easy_factor_session_v4_7');
664 - if (activeSession) {
665 - const u = usersDb.find(x => x.username === activeSession);
666 - if (u) { loginSuccess(u); return; }
667 - }
668 - document.getElementById('auth-screen').style.display = 'flex';
635 + const activeSession=sessionStorage.getItem('easy_factor_session_v4_7');
636 + if(activeSession){const u=usersDb.find(x=>x.username===activeSession);if(u){loginSuccess(u);return;}}
637 + document.getElementById('auth-screen').style.display='flex';
638 }
670 -
671 -function handleLogin() {
672 - const user = document.getElementById('auth-username').value.trim();
673 - const pass = document.getElementById('auth-password').value.trim();
639 +function handleLogin(){
640 + const user=document.getElementById('auth-username').value.trim();
641 + const pass=document.getElementById('auth-password').value.trim();
642 loadUsers();
675 - const found = usersDb.find(x => x.username === user && x.pass === pass);
676 - if (!found) { alert('نام کاربری یا رمز عبور اشتباه است.'); return; }
677 - sessionStorage.setItem('easy_factor_session_v4_7', found.username);
643 + const found=usersDb.find(x=>x.username===user&&x.pass===pass);
644 + if(!found){alert('نام کاربری یا رمز عبور اشتباه است.');return;}
645 + sessionStorage.setItem('easy_factor_session_v4_7',found.username);
646 loginSuccess(found);
647 }
680 -
681 -function switchToRegister() {
682 - const user = document.getElementById('auth-username').value.trim();
683 - const pass = document.getElementById('auth-password').value.trim();
684 - if (!user || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
648 +function switchToRegister(){
649 + const user=document.getElementById('auth-username').value.trim();
650 + const pass=document.getElementById('auth-password').value.trim();
651 + if(!user||!pass){alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');return;}
652 loadUsers();
686 - if (usersDb.some(x => x.username === user)) { alert('این نام کاربری قبلاً ثبت‌نام کرده است.'); return; }
687 - const today = new Date().toISOString().split('T')[0];
688 - const expireStr = addDaysToDate(today, 15);
689 - const newUser = {
690 - id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
691 - username: user, pass: pass, role: 'user', createdAt: new Date().toISOString(),
692 - subscriptionType: 'trial', subscriptionStart: today, subscriptionEnd: expireStr,
693 - licenseStatus: 'trial',
694 - subscription: { type: 'trial', startDate: today, endDate: expireStr, status: 'trial' }
695 - };
696 - usersDb.push(newUser);
697 - persistUsers();
698 - sessionStorage.setItem('easy_factor_session_v4_7', newUser.username);
653 + if(usersDb.some(x=>x.username===user)){alert('این نام کاربری قبلاً ثبت‌نام کرده است.');return;}
654 + const today=new Date().toISOString().split('T')[0];
655 + const expireStr=addDaysToDate(today,15);
656 + 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'}};
657 + usersDb.push(newUser);persistUsers();
658 + sessionStorage.setItem('easy_factor_session_v4_7',newUser.username);
659 alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
660 loginSuccess(newUser);
661 }
702 -
703 -function loginSuccess(userObj) {
704 - currentUser = userObj;
705 - document.getElementById('auth-screen').style.display = 'none';
706 - document.getElementById('logged-user-label').innerText = 'کاربر: ' + userObj.username + (userObj.role === 'admin' ? ' (مدیر سیستم)' : '');
707 - const adminMenu = document.getElementById('menu-admin-panel');
708 - adminMenu.style.display = (userObj.role === 'admin') ? 'block' : 'none';
662 +function loginSuccess(userObj){
663 + currentUser=userObj;
664 + document.getElementById('auth-screen').style.display='none';
665 + document.getElementById('logged-user-label').innerText='کاربر: '+userObj.username+(userObj.role==='admin'?' (مدیر سیستم)':'');
666 + document.getElementById('menu-admin-panel').style.display=(userObj.role==='admin')?'block':'none';
667 initDatastore();
668 }
711 -
712 -function handleLogout() {
713 - sessionStorage.removeItem('easy_factor_session_v4_7');
714 - window.location.reload();
715 -}
716 -
717 -function updateLicenseDisplay(user) {
718 - if (!user) return;
719 - const badge = document.getElementById('user-license-status-badge');
720 - const detailsBox = document.getElementById('dashboard-license-details');
721 - if (detailsBox) { detailsBox.style.display = 'none'; detailsBox.innerHTML = ''; }
722 - const sub = user.subscription || { type: user.subscriptionType || 'trial', startDate: user.subscriptionStart || user.createdAt, endDate: user.subscriptionEnd, status: user.licenseStatus || 'trial' };
723 - const remDays = getRemainingDays(sub.endDate);
724 - const isExpired = remDays <= 0 && sub.type !== 'lifetime';
725 - const hasActiveLicense = (sub.status === 'active') && (sub.type === 'lifetime' || !isExpired) && (sub.type !== 'trial');
726 - if (!badge) return;
727 - if (hasActiveLicense) {
728 - badge.className = 'badge badge-success';
729 - badge.innerText = (sub.type === 'lifetime') ? 'وضعیت اشتراک : نامحدود' : `وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
730 - } else if (isExpired || sub.status === 'cancelled') {
731 - badge.className = 'badge badge-danger';
732 - badge.innerText = 'وضعیت اشتراک : منقضی شده';
733 - } else {
734 - badge.className = 'badge badge-warning';
735 - badge.innerText = `وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
669 +function handleLogout(){sessionStorage.removeItem('easy_factor_session_v4_7');window.location.reload();}
670 +
671 +function updateLicenseDisplay(user){
672 + if(!user)return;
673 + const badge=document.getElementById('user-license-status-badge');
674 + const detailsBox=document.getElementById('dashboard-license-details');
675 + if(detailsBox){detailsBox.style.display='none';detailsBox.innerHTML='';}
676 + const sub=user.subscription||{type:user.subscriptionType||'trial',startDate:user.subscriptionStart||user.createdAt,endDate:user.subscriptionEnd,status:user.licenseStatus||'trial'};
677 + const remDays=getRemainingDays(sub.endDate);
678 + const isExpired=remDays<=0&&sub.type!=='lifetime';
679 + const hasActiveLicense=(sub.status==='active')&&(sub.type==='lifetime'||!isExpired)&&(sub.type!=='trial');
680 + if(!badge)return;
681 + if(hasActiveLicense){
682 + badge.className='badge badge-success';
683 + badge.innerText=(sub.type==='lifetime')?'وضعیت اشتراک : نامحدود':`وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
684 + }else if(isExpired||sub.status==='cancelled'){
685 + badge.className='badge badge-danger';badge.innerText='وضعیت اشتراک : منقضی شده';
686 + }else{
687 + badge.className='badge badge-warning';badge.innerText=`وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
688 }
689 }
690
739 -function adminCreateNewUser() {
740 - const username = document.getElementById('admin-new-username').value.trim();
741 - const pass = document.getElementById('admin-new-password').value.trim();
742 - const plan = document.getElementById('admin-new-subtype').value;
743 - if (!username || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
691 +function adminCreateNewUser(){
692 + const username=document.getElementById('admin-new-username').value.trim();
693 + const pass=document.getElementById('admin-new-password').value.trim();
694 + const plan=document.getElementById('admin-new-subtype').value;
695 + if(!username||!pass){alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');return;}
696 loadUsers();
745 - if (usersDb.some(u => u.username === username)) { alert('این نام کاربری از قبل وجود دارد.'); return; }
746 - const today = new Date().toISOString().split('T')[0];
747 - let endDate = today; let status = 'active';
748 - if (plan === 'trial') { endDate = addDaysToDate(today, 15); status = 'trial'; }
749 - else if (plan === 'monthly') endDate = addDaysToDate(today, 30);
750 - else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
751 - else if (plan === 'annual') endDate = addDaysToDate(today, 365);
752 - else if (plan === 'lifetime') endDate = '2099-01-01';
753 - const newUser = {
754 - id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
755 - username, pass, role: 'user', createdAt: new Date().toISOString(),
756 - subscriptionType: plan, subscriptionStart: today, subscriptionEnd: endDate, licenseStatus: status,
757 - subscription: { type: plan, startDate: today, endDate: endDate, status: status }
758 - };
759 - usersDb.push(newUser); persistUsers();
697 + if(usersDb.some(u=>u.username===username)){alert('این نام کاربری از قبل وجود دارد.');return;}
698 + const today=new Date().toISOString().split('T')[0];
699 + let endDate=today;let status='active';
700 + if(plan==='trial'){endDate=addDaysToDate(today,15);status='trial';}
701 + else if(plan==='monthly')endDate=addDaysToDate(today,30);
702 + else if(plan==='three_months')endDate=addDaysToDate(today,90);
703 + else if(plan==='annual')endDate=addDaysToDate(today,365);
704 + else if(plan==='lifetime')endDate='2099-01-01';
705 + 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}};
706 + usersDb.push(newUser);persistUsers();
707 alert(`کاربر جدید "${username}" با موفقیت ایجاد شد.`);
761 - document.getElementById('admin-new-username').value = '';
762 - document.getElementById('admin-new-password').value = '';
708 + document.getElementById('admin-new-username').value='';
709 + document.getElementById('admin-new-password').value='';
710 renderAdminPanel();
711 }
765 -
766 -function refreshAdminPanel() { loadUsers(); renderAdminPanel(); }
767 -
768 -function renderAdminPanel() {
769 - const tbody = document.getElementById('admin-users-table-body');
770 - if (!tbody) return;
712 +function refreshAdminPanel(){loadUsers();renderAdminPanel();}
713 +function renderAdminPanel(){
714 + const tbody=document.getElementById('admin-users-table-body');
715 + if(!tbody)return;
716 loadUsers();
772 - if (usersDb.length === 0) { tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>'; return; }
773 - const planLabels = { monthly: 'طرح ۱ ماهه', three_months: 'طرح ۳ ماهه', annual: 'طرح ۱ ساله', lifetime: 'دائمی (Lifetime)', trial: 'آزمایشی (Trial)' };
774 - tbody.innerHTML = usersDb.map(u => {
775 - const sub = u.subscription || { type: u.subscriptionType || 'trial', startDate: u.subscriptionStart, endDate: u.subscriptionEnd, status: u.licenseStatus || 'trial' };
776 - const remDays = getRemainingDays(sub.endDate);
777 - const isExp = remDays <= 0 && sub.type !== 'lifetime';
778 - let statusBadge = '';
779 - if (sub.status === 'cancelled') statusBadge = '<span class="badge badge-danger">لغو شده</span>';
780 - else if (sub.status === 'active') statusBadge = isExp ? '<span class="badge badge-danger">منقضی شده</span>' : '<span class="badge badge-success">فعال</span>';
781 - else statusBadge = isExp ? '<span class="badge badge-danger">آزمایشی منقضی</span>' : '<span class="badge badge-warning">آزمایشی</span>';
782 - const startJalali = formatToJalali(sub.startDate);
783 - const endJalali = sub.type === 'lifetime' ? 'نامحدود' : formatToJalali(sub.endDate);
784 - const remDaysText = sub.type === 'lifetime' ? 'نامحدود' : toPersianDigits(Math.max(0, remDays)) + ' روز';
785 - 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>`;
717 + if(usersDb.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
718 + const planLabels={monthly:'طرح ۱ ماهه',three_months:'طرح ۳ ماهه',annual:'طرح ۱ ساله',lifetime:'دائمی (Lifetime)',trial:'آزمایشی (Trial)'};
719 + tbody.innerHTML=usersDb.map(u=>{
720 + const sub=u.subscription||{type:u.subscriptionType||'trial',startDate:u.subscriptionStart,endDate:u.subscriptionEnd,status:u.licenseStatus||'trial'};
721 + const remDays=getRemainingDays(sub.endDate);
722 + const isExp=remDays<=0&&sub.type!=='lifetime';
723 + let statusBadge='';
724 + if(sub.status==='cancelled')statusBadge='<span class="badge badge-danger">لغو شده</span>';
725 + else if(sub.status==='active')statusBadge=isExp?'<span class="badge badge-danger">منقضی شده</span>':'<span class="badge badge-success">فعال</span>';
726 + else statusBadge=isExp?'<span class="badge badge-danger">آزمایشی منقضی</span>':'<span class="badge badge-warning">آزمایشی</span>';
727 + const startJalali=formatToJalali(sub.startDate);
728 + const endJalali=sub.type==='lifetime'?'نامحدود':formatToJalali(sub.endDate);
729 + const remDaysText=sub.type==='lifetime'?'نامحدود':toPersianDigits(Math.max(0,remDays))+' روز';
730 + 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>`;
731 }).join('');
732 }
788 -
789 -function adminActivateLicense(username) {
790 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
791 - const today = new Date().toISOString().split('T')[0];
792 - const endDate = addDaysToDate(today, 30);
793 - u.subscription = { type: 'monthly', startDate: today, endDate: endDate, status: 'active' };
794 - u.subscriptionType = 'monthly'; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
733 +function adminActivateLicense(username){
734 + loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
735 + const today=new Date().toISOString().split('T')[0];
736 + const endDate=addDaysToDate(today,30);
737 + u.subscription={type:'monthly',startDate:today,endDate:endDate,status:'active'};
738 + u.subscriptionType='monthly';u.subscriptionStart=today;u.subscriptionEnd=endDate;u.licenseStatus='active';
739 persistUsers();
796 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
740 + if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
741 alert(`لایسنس ۱ ماهه فعال برای کاربر ${username} ثبت شد.`);
742 renderAdminPanel();
743 }
800 -
801 -function openLicenseEditModal(username) {
802 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
803 - document.getElementById('modal-license-target-username').value = username;
804 - document.getElementById('modal-license-user-title').innerText = `تغییر مدت و نوع لایسنس: ${username}`;
805 - document.getElementById('modal-license-duration-select').value = u.subscription?.type || 'monthly';
744 +function openLicenseEditModal(username){
745 + loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
746 + document.getElementById('modal-license-target-username').value=username;
747 + document.getElementById('modal-license-user-title').innerText=`تغییر مدت و نوع لایسنس: ${username}`;
748 + document.getElementById('modal-license-duration-select').value=u.subscription?.type||'monthly';
749 document.getElementById('modal-admin-license-edit').classList.add('active');
750 }
808 -function closeLicenseEditModal() { document.getElementById('modal-admin-license-edit').classList.remove('active'); }
809 -
810 -function applyLicenseDurationChange() {
811 - const username = document.getElementById('modal-license-target-username').value;
812 - const plan = document.getElementById('modal-license-duration-select').value;
813 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
814 - const today = new Date().toISOString().split('T')[0];
815 - let endDate = today;
816 - if (plan === 'monthly') endDate = addDaysToDate(today, 30);
817 - else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
818 - else if (plan === 'annual') endDate = addDaysToDate(today, 365);
819 - else if (plan === 'lifetime') endDate = '2099-01-01';
820 - u.subscription = { type: plan, startDate: today, endDate: endDate, status: 'active' };
821 - u.subscriptionType = plan; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
751 +function closeLicenseEditModal(){document.getElementById('modal-admin-license-edit').classList.remove('active');}
752 +function applyLicenseDurationChange(){
753 + const username=document.getElementById('modal-license-target-username').value;
754 + const plan=document.getElementById('modal-license-duration-select').value;
755 + loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
756 + const today=new Date().toISOString().split('T')[0];
757 + let endDate=today;
758 + if(plan==='monthly')endDate=addDaysToDate(today,30);
759 + else if(plan==='three_months')endDate=addDaysToDate(today,90);
760 + else if(plan==='annual')endDate=addDaysToDate(today,365);
761 + else if(plan==='lifetime')endDate='2099-01-01';
762 + u.subscription={type:plan,startDate:today,endDate:endDate,status:'active'};
763 + u.subscriptionType=plan;u.subscriptionStart=today;u.subscriptionEnd=endDate;u.licenseStatus='active';
764 persistUsers();
823 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
765 + if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
766 closeLicenseEditModal();
767 alert(`طرح لایسنس کاربر ${username} با موفقیت به "${plan}" تغییر یافت.`);
768 renderAdminPanel();
769 }
828 -
829 -function adminExtendSubscription(username, days) {
830 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
831 - let currentEnd = u.subscription?.endDate || new Date().toISOString().split('T')[0];
832 - if (currentEnd.startsWith('2099')) { alert('این حساب دائمی است و نیازی به تمدید ندارد.'); return; }
833 - const today = new Date().toISOString().split('T')[0];
834 - const base = (currentEnd < today) ? today : currentEnd;
835 - const newEnd = addDaysToDate(base, days);
836 - if (!u.subscription) u.subscription = {};
837 - u.subscription.endDate = newEnd;
838 - u.subscription.status = 'active';
839 - if (u.subscription.type === 'trial') u.subscription.type = 'monthly';
840 - u.subscriptionType = u.subscription.type; u.subscriptionEnd = newEnd; u.licenseStatus = 'active';
770 +function adminExtendSubscription(username,days){
771 + loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
772 + let currentEnd=u.subscription?.endDate||new Date().toISOString().split('T')[0];
773 + if(currentEnd.startsWith('2099')){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
774 + const today=new Date().toISOString().split('T')[0];
775 + const base=(currentEnd<today)?today:currentEnd;
776 + const newEnd=addDaysToDate(base,days);
777 + if(!u.subscription)u.subscription={};
778 + u.subscription.endDate=newEnd;
779 + u.subscription.status='active';
780 + if(u.subscription.type==='trial')u.subscription.type='monthly';
781 + u.subscriptionType=u.subscription.type;u.subscriptionEnd=newEnd;u.licenseStatus='active';
782 persistUsers();
842 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
783 + if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
784 alert(`اشتراک کاربر ${username} به مدت ${days} روز تمدید گردید.`);
785 renderAdminPanel();
786 }
846 -
847 -function adminCancelSubscription(username) {
848 - if (!confirm(`آیا از لغو اشتراک کاربر ${username} اطمینان دارید؟`)) return;
849 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
850 - if (!u.subscription) u.subscription = {};
851 - u.subscription.status = 'cancelled'; u.licenseStatus = 'cancelled';
787 +function adminCancelSubscription(username){
788 + if(!confirm(`آیا از لغو اشتراک کاربر ${username} اطمینان دارید؟`))return;
789 + loadUsers();const u=usersDb.find(x=>x.username===username);if(!u)return;
790 + if(!u.subscription)u.subscription={};
791 + u.subscription.status='cancelled';u.licenseStatus='cancelled';
792 persistUsers();
853 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
793 + if(currentUser&&currentUser.username===username){currentUser=u;updateLicenseDisplay(currentUser);}
794 alert(`اشتراک کاربر ${username} لغو گردید.`);
795 renderAdminPanel();
796 }
797
858 -let datastore = { companies: [], contacts: [], products: [], invoices: [], cheques: [], expenses: [], settings: [] };
859 -
860 -function getMyProducts() { return !currentUser ? [] : datastore.products.filter(p => p.ownerUserId === currentUser.id); }
861 -function getMyContacts() { return !currentUser ? [] : datastore.contacts.filter(c => c.ownerUserId === currentUser.id); }
862 -function getMyCompanies() { return !currentUser ? [] : datastore.companies.filter(c => c.ownerUserId === currentUser.id); }
863 -function getMyInvoices() { return !currentUser ? [] : datastore.invoices.filter(i => i.ownerUserId === currentUser.id); }
864 -function getMyCheques() { return !currentUser ? [] : datastore.cheques.filter(c => c.ownerUserId === currentUser.id); }
865 -function getMyExpenses() { return !currentUser ? [] : datastore.expenses.filter(e => e.ownerUserId === currentUser.id); }
866 -
867 -function getMySettings() {
868 - if (!currentUser) return { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
869 - if (!Array.isArray(datastore.settings)) datastore.settings = [];
870 - let s = datastore.settings.find(item => item.ownerUserId === currentUser.id);
871 - if (!s) {
872 - s = { ownerUserId: currentUser.id, invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
873 - datastore.settings.push(s);
874 - }
875 - if (typeof s.currency_mode === 'undefined') s.currency_mode = 'rial';
876 - if (typeof s.currency_custom === 'undefined') s.currency_custom = '';
798 +let datastore={companies:[],contacts:[],products:[],invoices:[],cheques:[],expenses:[],settings:[]};
799 +function getMyProducts(){return !currentUser?[]:datastore.products.filter(p=>p.ownerUserId===currentUser.id);}
800 +function getMyContacts(){return !currentUser?[]:datastore.contacts.filter(c=>c.ownerUserId===currentUser.id);}
801 +function getMyCompanies(){return !currentUser?[]:datastore.companies.filter(c=>c.ownerUserId===currentUser.id);}
802 +function getMyInvoices(){return !currentUser?[]:datastore.invoices.filter(i=>i.ownerUserId===currentUser.id);}
803 +function getMyCheques(){return !currentUser?[]:datastore.cheques.filter(c=>c.ownerUserId===currentUser.id);}
804 +function getMyExpenses(){return !currentUser?[]:datastore.expenses.filter(e=>e.ownerUserId===currentUser.id);}
805 +function getMySettings(){
806 + if(!currentUser)return{invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'',currency_mode:'rial',currency_custom:''};
807 + if(!Array.isArray(datastore.settings))datastore.settings=[];
808 + let s=datastore.settings.find(item=>item.ownerUserId===currentUser.id);
809 + if(!s){s={ownerUserId:currentUser.id,invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'',currency_mode:'rial',currency_custom:''};datastore.settings.push(s);}
810 + if(typeof s.currency_mode==='undefined')s.currency_mode='rial';
811 + if(typeof s.currency_custom==='undefined')s.currency_custom='';
812 return s;
813 }
879 -
880 -function saveDatastore() {
881 - try { localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore)); return true; }
882 - catch (err) { console.error('Error saving datastore:', err); return false; }
883 -}
884 -
885 -function loadDatastore() {
886 - const persisted = localStorage.getItem(STORAGE_KEY);
887 - if (persisted) { try { datastore = JSON.parse(persisted); } catch (e) { console.error(e); } }
888 - ['companies','contacts','products','invoices','cheques','expenses','settings'].forEach(k => { if (!Array.isArray(datastore[k])) datastore[k] = []; });
889 -
890 - if (datastore.companies.length === 0 && datastore.products.length === 0) {
891 - datastore.companies.push({
892 - id: 'COMP-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'آرا سپهر راستین',
893 - phone: '09124376991', national_id: '14008507476', economic_code: '14008507476',
894 - reg_number: '544926', postal_code: '1445956311',
895 - address: 'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',
896 - footer: 'از خرید شما سپاسگزاریم.'
897 - });
898 - datastore.contacts.push({
899 - id: 'C-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'شرکت دانشگاه صنعتی شریف',
900 - mobile: '02166165000', national_id: '14002830256', economic_code: '14002830256',
901 - reg_number: '', postal_code: '1458889694', address: 'طرشت محله تیموری پلاک 435',
902 - balance: 7978300000, role: 'customer'
903 - });
814 +function saveDatastore(){try{localStorage.setItem(STORAGE_KEY,JSON.stringify(datastore));return true;}catch(err){console.error('Error saving datastore:',err);return false;}}
815 +function loadDatastore(){
816 + const persisted=localStorage.getItem(STORAGE_KEY);
817 + if(persisted){try{datastore=JSON.parse(persisted);}catch(e){console.error(e);}}
818 + ['companies','contacts','products','invoices','cheques','expenses','settings'].forEach(k=>{if(!Array.isArray(datastore[k]))datastore[k]=[];});
819 + if(datastore.companies.length===0&&datastore.products.length===0){
820 + 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:'از خرید شما سپاسگزاریم.'});
821 + 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'});
822 datastore.products.push(
905 - { id: 'P-1', ownerUserId: 'user_admin', code: '1', name: 'سوئیچ شبکه 24 پورت فیبر نوری', spec: 'با 2 پاور 350', unit: 'عدد', buy_price: 1800000000, sale_price: 2180000000, stock: 10, type: 'good' },
906 - { id: 'P-2', ownerUserId: 'user_admin', code: '2', name: 'هارد 2.5 اینچ سرور', spec: '', unit: 'عدد', buy_price: 30000000, sale_price: 37000000, stock: 10, type: 'good' }
823 + {id:'P-1',ownerUserId:'user_admin',code:'1',name:'سوئیچ شبکه 24 پورت فیبر نوری',spec:'با 2 پاور 350',unit:'عدد',buy_price:1800000000,sale_price:2180000000,stock:10,type:'good'},
824 + {id:'P-2',ownerUserId:'user_admin',code:'2',name:'هارد 2.5 اینچ سرور',spec:'',unit:'عدد',buy_price:30000000,sale_price:37000000,stock:10,type:'good'}
825 );
908 - datastore.settings.push({
909 - ownerUserId: 'user_admin', invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10,
910 - default_company_id: 'COMP-1', currency_mode: 'rial', currency_custom: ''
911 - });
826 + 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:''});
827 saveDatastore();
913 - } else {
914 - let migrated = false;
915 - ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(coll => {
916 - datastore[coll].forEach(item => { if (!item.ownerUserId) { item.ownerUserId = 'user_admin'; migrated = true; } });
917 - });
918 - datastore.settings.forEach(s => {
919 - if (typeof s.currency_mode === 'undefined') { s.currency_mode = 'rial'; migrated = true; }
920 - if (typeof s.currency_custom === 'undefined') { s.currency_custom = ''; migrated = true; }
921 - });
922 - if (migrated) saveDatastore();
828 + }else{
829 + let migrated=false;
830 + ['companies','contacts','products','invoices','cheques','expenses'].forEach(coll=>{datastore[coll].forEach(item=>{if(!item.ownerUserId){item.ownerUserId='user_admin';migrated=true;}});});
831 + 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;}});
832 + if(migrated)saveDatastore();
833 }
834 return datastore;
835 }
926 -
927 -function initDatastore() { loadDatastore(); refreshAllSurfaces(); }
928 -
929 -function getJalaliDate() { return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { dateStyle: 'full' }).format(new Date()); }
930 -function getJalaliNumeric() { return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); }
931 -
932 -function getCurrencyLabel() {
933 - const s = getMySettings();
934 - if (s.currency_mode === 'toman') return 'تومان';
935 - if (s.currency_mode === 'custom') return (s.currency_custom || '').trim() || 'واحد پول';
936 - return 'ریال';
937 -}
938 -
939 -function refreshCurrencyLabels() {
940 - const label = getCurrencyLabel();
941 - document.querySelectorAll('.cur-label').forEach(el => { el.innerText = label; });
942 -}
943 -
944 -function handleCurrencyModeChange() {
945 - const mode = document.getElementById('def-currency-mode').value;
946 - document.getElementById('box-currency-custom').style.display = (mode === 'custom') ? 'block' : 'none';
947 -}
948 -
949 -function switchView(viewId) {
950 - document.querySelectorAll('.view-pane').forEach(el => el.classList.remove('active'));
951 - const target = document.getElementById(viewId);
952 - if (target) target.classList.add('active');
953 - document.querySelectorAll('.nav-link').forEach(btn => btn.classList.toggle('active', btn.getAttribute('data-view') === viewId));
954 - const dockViews = ['view-dashboard', 'view-invoices', 'view-products', 'view-contacts', 'view-cheques', 'view-settings'];
955 - document.querySelectorAll('.dock-tab').forEach((dock, idx) => { dock.classList.toggle('active', dockViews[idx] === viewId); });
956 - if (viewId === 'view-admin') renderAdminPanel();
957 - window.scrollTo({ top: 0, behavior: 'smooth' });
958 -}
959 -
960 -function toggleAccordion(headerEl) { headerEl.parentElement.classList.toggle('open'); }
961 -
962 -function refreshAllSurfaces() {
963 - const dashDate = document.getElementById('dashboard-date-display');
964 - if (dashDate) dashDate.innerText = getJalaliDate();
965 - const invDate = document.getElementById('invoice-date-input');
966 - if (invDate && !invDate.value) invDate.value = getJalaliNumeric();
836 +function initDatastore(){loadDatastore();refreshAllSurfaces();}
837 +function getJalaliDate(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{dateStyle:'full'}).format(new Date());}
838 +function getJalaliNumeric(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
839 +function getCurrencyLabel(){const s=getMySettings();if(s.currency_mode==='toman')return 'تومان';if(s.currency_mode==='custom')return (s.currency_custom||'').trim()||'واحد پول';return 'ریال';}
840 +function refreshCurrencyLabels(){const label=getCurrencyLabel();document.querySelectorAll('.cur-label').forEach(el=>{el.innerText=label;});}
841 +function handleCurrencyModeChange(){const mode=document.getElementById('def-currency-mode').value;document.getElementById('box-currency-custom').style.display=(mode==='custom')?'block':'none';}
842 +
843 +function switchView(viewId){
844 + document.querySelectorAll('.view-pane').forEach(el=>el.classList.remove('active'));
845 + const target=document.getElementById(viewId);
846 + if(target)target.classList.add('active');
847 + document.querySelectorAll('.nav-link').forEach(btn=>btn.classList.toggle('active',btn.getAttribute('data-view')===viewId));
848 + const dockViews=['view-dashboard','view-invoices','view-products','view-contacts','view-cheques','view-settings'];
849 + document.querySelectorAll('.dock-tab').forEach((dock,idx)=>{dock.classList.toggle('active',dockViews[idx]===viewId);});
850 + if(viewId==='view-admin')renderAdminPanel();
851 + window.scrollTo({top:0,behavior:'smooth'});
852 +}
853 +function toggleAccordion(headerEl){headerEl.parentElement.classList.toggle('open');}
854 +function refreshAllSurfaces(){
855 + const dashDate=document.getElementById('dashboard-date-display');
856 + if(dashDate)dashDate.innerText=getJalaliDate();
857 + const invDate=document.getElementById('invoice-date-input');
858 + if(invDate&&!invDate.value)invDate.value=getJalaliNumeric();
859 updateLicenseDisplay(currentUser);
968 - renderCompanies(); renderContacts(); renderProducts(); renderInvoices();
969 - renderDashboard(); renderCheques(); renderExpenses();
860 + renderCompanies();renderContacts();renderProducts();renderInvoices();
861 + renderDashboard();renderCheques();renderExpenses();
862 applyDefaultSettingsToForm();
863 handleContactEntityChange();
864 handleCurrencyModeChange();
865 refreshCurrencyLabels();
974 - if (currentUser && currentUser.role === 'admin') renderAdminPanel();
975 -}
976 -
977 -function formatEntityName(rawName, entityType, customPrefix = '') {
978 - let trimmed = (rawName || '').trim();
979 - if (entityType === 'legal') {
980 - if (!trimmed.startsWith('شرکت') && !trimmed.startsWith('موسسه') && !trimmed.startsWith('سازمان') && !trimmed.startsWith('اداره')) trimmed = 'شرکت ' + trimmed;
981 - } else if (entityType === 'natural' && customPrefix) {
982 - if (!trimmed.startsWith(customPrefix)) trimmed = customPrefix + ' ' + trimmed;
866 + if(currentUser&&currentUser.role==='admin')renderAdminPanel();
867 +}
868 +function formatEntityName(rawName,entityType,customPrefix=''){
869 + let trimmed=(rawName||'').trim();
870 + if(entityType==='legal'){
871 + if(!trimmed.startsWith('شرکت')&&!trimmed.startsWith('موسسه')&&!trimmed.startsWith('سازمان')&&!trimmed.startsWith('اداره'))trimmed='شرکت '+trimmed;
872 + }else if(entityType==='natural'&&customPrefix){
873 + if(!trimmed.startsWith(customPrefix))trimmed=customPrefix+' '+trimmed;
874 }
875 return trimmed;
876 }
986 -
987 -function applyEntityTypeToForm(entity, opts) {
988 - const { prefixId, nameId, econId, regId, nationalLabelId } = opts;
989 - const prefixBox = document.getElementById(prefixId);
990 - const nameBox = document.getElementById(nameId);
991 - const econBox = document.getElementById(econId);
992 - const regBox = document.getElementById(regId);
993 - const natLabel = document.getElementById(nationalLabelId);
994 - if (entity === 'legal') {
995 - if (prefixBox) prefixBox.style.display = 'none';
996 - if (nameBox) nameBox.style.gridColumn = 'span 3';
997 - if (econBox) econBox.style.display = 'block';
998 - if (regBox) regBox.style.display = 'block';
999 - if (natLabel) natLabel.innerText = 'شناسه ملی';
1000 - } else {
1001 - if (prefixBox) prefixBox.style.display = 'block';
1002 - if (nameBox) nameBox.style.gridColumn = 'span 2';
1003 - if (econBox) econBox.style.display = 'none';
1004 - if (regBox) regBox.style.display = 'none';
1005 - if (natLabel) natLabel.innerText = 'کد ملی';
877 +function applyEntityTypeToForm(entity,opts){
878 + const {prefixId,nameId,econId,regId,nationalLabelId}=opts;
879 + const prefixBox=document.getElementById(prefixId);
880 + const nameBox=document.getElementById(nameId);
881 + const econBox=document.getElementById(econId);
882 + const regBox=document.getElementById(regId);
883 + const natLabel=document.getElementById(nationalLabelId);
884 + if(entity==='legal'){
885 + if(prefixBox)prefixBox.style.display='none';
886 + if(nameBox)nameBox.style.gridColumn='span 3';
887 + if(econBox)econBox.style.display='block';
888 + if(regBox)regBox.style.display='block';
889 + if(natLabel)natLabel.innerText='شناسه ملی';
890 + }else{
891 + if(prefixBox)prefixBox.style.display='block';
892 + if(nameBox)nameBox.style.gridColumn='span 2';
893 + if(econBox)econBox.style.display='none';
894 + if(regBox)regBox.style.display='none';
895 + if(natLabel)natLabel.innerText='کد ملی';
896 }
897 }
1008 -
1009 -function handleContactEntityChange() {
1010 - const el = document.getElementById('contact-entity-type'); if (!el) return;
1011 - applyEntityTypeToForm(el.value, { prefixId: 'box-contact-prefix', nameId: 'box-contact-name', econId: 'box-contact-economic', regId: 'box-contact-reg', nationalLabelId: 'label-contact-national' });
1012 -}
1013 -function handleQuickCEntityChange() {
1014 - const el = document.getElementById('quick-c-entity'); if (!el) return;
1015 - applyEntityTypeToForm(el.value, { prefixId: 'box-quick-c-prefix', nameId: 'box-quick-c-name', econId: 'box-quick-c-economic', regId: 'box-quick-c-reg', nationalLabelId: 'label-quick-c-national' });
1016 -}
1017 -
1018 -function handleInvoiceKindChange() {
1019 - const kind = document.getElementById('invoice-kind').value;
1020 - const vatModeRow = document.getElementById('box-invoice-vat-mode-row');
1021 - const vatModeSelect = document.getElementById('invoice-vat-mode');
1022 - if (kind === 'non_formal') {
1023 - if (vatModeRow) vatModeRow.style.display = 'none';
1024 - if (vatModeSelect) vatModeSelect.value = 'none';
1025 - } else {
1026 - if (vatModeRow) vatModeRow.style.display = 'flex';
898 +function handleContactEntityChange(){const el=document.getElementById('contact-entity-type');if(!el)return;applyEntityTypeToForm(el.value,{prefixId:'box-contact-prefix',nameId:'box-contact-name',econId:'box-contact-economic',regId:'box-contact-reg',nationalLabelId:'label-contact-national'});}
899 +function handleQuickCEntityChange(){const el=document.getElementById('quick-c-entity');if(!el)return;applyEntityTypeToForm(el.value,{prefixId:'box-quick-c-prefix',nameId:'box-quick-c-name',econId:'box-quick-c-economic',regId:'box-quick-c-reg',nationalLabelId:'label-quick-c-national'});}
900 +function handleInvoiceKindChange(){
901 + const kind=document.getElementById('invoice-kind').value;
902 + const vatModeRow=document.getElementById('box-invoice-vat-mode-row');
903 + const vatModeSelect=document.getElementById('invoice-vat-mode');
904 + if(kind==='non_formal'){
905 + if(vatModeRow)vatModeRow.style.display='none';
906 + if(vatModeSelect)vatModeSelect.value='none';
907 + }else{
908 + if(vatModeRow)vatModeRow.style.display='flex';
909 }
910 handleVatModeChange();
911 recomputeTotals();
912 }
1031 -
1032 -function handleVatModeChange() {
1033 - const mode = document.getElementById('invoice-vat-mode').value;
1034 - const kind = document.getElementById('invoice-kind').value;
1035 - const rateBox = document.getElementById('box-invoice-vat-rate');
1036 - if (kind === 'non_formal') { rateBox.style.display = 'none'; document.getElementById('invoice-vat-mode').value = 'none'; }
1037 - else { rateBox.style.display = (mode === 'with_vat') ? 'flex' : 'none'; }
1038 - recomputeTotals();
1039 -}
1040 -
1041 -function handleVatTypeChange() {
1042 - const type = document.getElementById('invoice-vat-type').value;
1043 - document.getElementById('invoice-vat-rate-input').value = (type === 'percent') ? 10 : 0;
913 +function handleVatModeChange(){
914 + const mode=document.getElementById('invoice-vat-mode').value;
915 + const kind=document.getElementById('invoice-kind').value;
916 + const rateBox=document.getElementById('box-invoice-vat-rate');
917 + if(kind==='non_formal'){rateBox.style.display='none';document.getElementById('invoice-vat-mode').value='none';}
918 + else{rateBox.style.display=(mode==='with_vat')?'flex':'none';}
919 recomputeTotals();
920 }
1046 -
1047 -function handleDiscountTypeChange() {
1048 - const type = document.getElementById('invoice-discount-type').value;
1049 - const label = document.getElementById('label-invoice-discount-value');
1050 - const cur = getCurrencyLabel();
1051 - label.innerText = (type === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${cur})`;
1052 - document.getElementById('invoice-discount-fixed').value = 0;
921 +function handleVatTypeChange(){const type=document.getElementById('invoice-vat-type').value;document.getElementById('invoice-vat-rate-input').value=(type==='percent')?10:0;recomputeTotals();}
922 +function handleDiscountTypeChange(){
923 + const type=document.getElementById('invoice-discount-type').value;
924 + const label=document.getElementById('label-invoice-discount-value');
925 + const cur=getCurrencyLabel();
926 + label.innerText=(type==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${cur})`;
927 + document.getElementById('invoice-discount-fixed').value=0;
928 recomputeTotals();
929 }
1055 -
1056 -function applyDefaultSettingsToForm() {
1057 - const def = getMySettings();
1058 - const defKind = document.getElementById('def-invoice-kind');
1059 - const defVat = document.getElementById('def-vat-mode');
1060 - const defRate = document.getElementById('def-vat-rate');
1061 - const defCurMode = document.getElementById('def-currency-mode');
1062 - const defCurCustom = document.getElementById('def-currency-custom');
1063 - if (defKind) defKind.value = def.invoice_kind || 'non_formal';
1064 - if (defVat) defVat.value = def.vat_mode || 'none';
1065 - if (defRate) defRate.value = def.vat_rate || 10;
1066 - if (defCurMode) defCurMode.value = def.currency_mode || 'rial';
1067 - if (defCurCustom) defCurCustom.value = def.currency_custom || '';
930 +function applyDefaultSettingsToForm(){
931 + const def=getMySettings();
932 + const defKind=document.getElementById('def-invoice-kind');
933 + const defVat=document.getElementById('def-vat-mode');
934 + const defRate=document.getElementById('def-vat-rate');
935 + const defCurMode=document.getElementById('def-currency-mode');
936 + const defCurCustom=document.getElementById('def-currency-custom');
937 + if(defKind)defKind.value=def.invoice_kind||'non_formal';
938 + if(defVat)defVat.value=def.vat_mode||'none';
939 + if(defRate)defRate.value=def.vat_rate||10;
940 + if(defCurMode)defCurMode.value=def.currency_mode||'rial';
941 + if(defCurCustom)defCurCustom.value=def.currency_custom||'';
942 handleCurrencyModeChange();
1069 -
1070 - const editId = document.getElementById('edit-invoice-id')?.value;
1071 - if (!editId) {
1072 - const kindEl = document.getElementById('invoice-kind');
1073 - if (kindEl) kindEl.value = def.invoice_kind || 'non_formal';
943 + const editId=document.getElementById('edit-invoice-id')?.value;
944 + if(!editId){
945 + const kindEl=document.getElementById('invoice-kind');
946 + if(kindEl)kindEl.value=def.invoice_kind||'non_formal';
947 handleInvoiceKindChange();
1075 - if ((def.invoice_kind || 'non_formal') !== 'non_formal') {
1076 - document.getElementById('invoice-vat-mode').value = def.vat_mode || 'none';
1077 - document.getElementById('invoice-vat-rate-input').value = def.vat_rate || 10;
948 + if((def.invoice_kind||'non_formal')!=='non_formal'){
949 + document.getElementById('invoice-vat-mode').value=def.vat_mode||'none';
950 + document.getElementById('invoice-vat-rate-input').value=def.vat_rate||10;
951 handleVatModeChange();
952 }
953 }
954 }
1082 -
1083 -function commitSaveDefaultSettings() {
1084 - const s = getMySettings();
1085 - s.invoice_kind = document.getElementById('def-invoice-kind').value;
1086 - s.vat_mode = document.getElementById('def-vat-mode').value;
1087 - s.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1088 - s.currency_mode = document.getElementById('def-currency-mode').value;
1089 - s.currency_custom = document.getElementById('def-currency-custom').value || '';
955 +function commitSaveDefaultSettings(){
956 + const s=getMySettings();
957 + s.invoice_kind=document.getElementById('def-invoice-kind').value;
958 + s.vat_mode=document.getElementById('def-vat-mode').value;
959 + s.vat_rate=parseFloat(document.getElementById('def-vat-rate').value)||0;
960 + s.currency_mode=document.getElementById('def-currency-mode').value;
961 + s.currency_custom=document.getElementById('def-currency-custom').value||'';
962 saveDatastore();
963 refreshCurrencyLabels();
964 alert('پیش‌فرض‌ها ذخیره شد.');
965 }
1094 -
1095 -function renderDashboard() {
1096 - let salesSum = 0; let debtorsSum = 0;
1097 - const myInvoices = getMyInvoices();
1098 - const myCheques = getMyCheques();
1099 - const myCompanies = getMyCompanies();
1100 - const mySettings = getMySettings();
1101 - const activeCompId = mySettings.default_company_id || document.getElementById('invoice-company-id')?.value || (myCompanies[0]?.id);
1102 - const filteredInvoices = activeCompId ? myInvoices.filter(inv => inv.companyId === activeCompId) : myInvoices;
1103 - const cur = getCurrencyLabel();
1104 - filteredInvoices.forEach(inv => {
1105 - salesSum += inv.grandTotal;
1106 - if (inv.paymentMethod === 'credit') debtorsSum += inv.grandTotal;
1107 - });
1108 - const salesEl = document.getElementById('kpi-sales-sum');
1109 - const settledEl = document.getElementById('kpi-settled-sum');
1110 - const debtorsEl = document.getElementById('kpi-debtors-sum');
1111 - const chequesEl = document.getElementById('kpi-cheques-count');
1112 - if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ' + cur;
1113 - if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ' + cur;
1114 - if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ' + cur;
1115 - if (chequesEl) chequesEl.innerText = myCheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1116 - const recentTbody = document.getElementById('dashboard-recent-table');
1117 - if (recentTbody) {
1118 - if (filteredInvoices.length === 0) {
1119 - recentTbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr>';
1120 - return;
1121 - }
1122 - recentTbody.innerHTML = filteredInvoices.slice(-5).reverse().map(inv => `
966 +function renderDashboard(){
967 + let salesSum=0;let debtorsSum=0;
968 + const myInvoices=getMyInvoices();
969 + const myCheques=getMyCheques();
970 + const myCompanies=getMyCompanies();
971 + const mySettings=getMySettings();
972 + const activeCompId=mySettings.default_company_id||document.getElementById('invoice-company-id')?.value||(myCompanies[0]?.id);
973 + const filteredInvoices=activeCompId?myInvoices.filter(inv=>inv.companyId===activeCompId):myInvoices;
974 + const cur=getCurrencyLabel();
975 + filteredInvoices.forEach(inv=>{salesSum+=inv.grandTotal;if(inv.paymentMethod==='credit')debtorsSum+=inv.grandTotal;});
976 + const salesEl=document.getElementById('kpi-sales-sum');
977 + const settledEl=document.getElementById('kpi-settled-sum');
978 + const debtorsEl=document.getElementById('kpi-debtors-sum');
979 + const chequesEl=document.getElementById('kpi-cheques-count');
980 + if(salesEl)salesEl.innerText=salesSum.toLocaleString('fa-IR')+' '+cur;
981 + if(settledEl)settledEl.innerText=(salesSum-debtorsSum).toLocaleString('fa-IR')+' '+cur;
982 + if(debtorsEl)debtorsEl.innerText=debtorsSum.toLocaleString('fa-IR')+' '+cur;
983 + if(chequesEl)chequesEl.innerText=myCheques.filter(c=>c.status==='registered').length.toLocaleString('fa-IR')+' فقره';
984 + const recentTbody=document.getElementById('dashboard-recent-table');
985 + if(recentTbody){
986 + if(filteredInvoices.length===0){recentTbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr>';return;}
987 + recentTbody.innerHTML=filteredInvoices.slice(-5).reverse().map(inv=>`
988 <tr>
989 <td><strong>#${inv.number}</strong></td>
1125 - <td>${inv.companyName || '—'}</td>
990 + <td>${inv.companyName||'—'}</td>
991 <td>${inv.contactName}</td>
1127 - <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1128 - <td>${inv.vat > 0 ? 'با ارزش افزوده' : 'بدون مالیات'}</td>
992 + <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${inv.kindLabel}</span></td>
993 + <td>${inv.vat>0?'با ارزش افزوده':'بدون مالیات'}</td>
994 <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
995 <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px;font-size:12px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
1131 - </tr>
1132 - `).join('');
996 + </tr>`).join('');
997 }
998 }
1135 -
1136 -function onActiveCompanyFilterChange() {
1137 - const activeCompId = document.getElementById('invoice-company-id').value;
1138 - const filterSelect = document.getElementById('filter-invoice-company');
1139 - if (filterSelect) filterSelect.value = activeCompId;
1140 - renderInvoices(); renderDashboard();
1141 -}
1142 -
1143 -function startNewInvoice() { cancelInvoiceEdit(); switchView('view-invoices'); }
1144 -
1145 -function updateInvoiceItemRowNumbers() {
1146 - const rows = document.querySelectorAll('#invoice-items-table-body tr');
1147 - rows.forEach((tr, index) => {
1148 - const numCell = tr.querySelector('.row-item-number');
1149 - if (numCell) numCell.innerText = (index + 1).toLocaleString('fa-IR');
1150 - });
1151 -}
1152 -
1153 -function addInvoiceItemRow(selectedProdId = '', initialQty = 1, initialPrice = null) {
1154 - const tbody = document.getElementById('invoice-items-table-body');
1155 - const rowKey = 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 4);
1156 - const tr = document.createElement('tr');
1157 - tr.id = rowKey;
1158 - const myProducts = getMyProducts();
1159 - 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('');
1160 - tr.innerHTML = `
999 +function onActiveCompanyFilterChange(){
1000 + const activeCompId=document.getElementById('invoice-company-id').value;
1001 + const filterSelect=document.getElementById('filter-invoice-company');
1002 + if(filterSelect)filterSelect.value=activeCompId;
1003 + renderInvoices();renderDashboard();
1004 +}
1005 +function startNewInvoice(){cancelInvoiceEdit();switchView('view-invoices');}
1006 +function updateInvoiceItemRowNumbers(){
1007 + const rows=document.querySelectorAll('#invoice-items-table-body tr');
1008 + rows.forEach((tr,index)=>{const numCell=tr.querySelector('.row-item-number');if(numCell)numCell.innerText=(index+1).toLocaleString('fa-IR');});
1009 +}
1010 +function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
1011 + const tbody=document.getElementById('invoice-items-table-body');
1012 + const rowKey='item_'+Date.now()+'_'+Math.random().toString(36).substr(2,4);
1013 + const tr=document.createElement('tr');
1014 + tr.id=rowKey;
1015 + const myProducts=getMyProducts();
1016 + 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('');
1017 + tr.innerHTML=`
1018 <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
1019 <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
1020 <td style="width:90px"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center" /></td>
1021 <td style="width:100px"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center" /></td>
1165 - <td style="width:160px"><input type="number" class="form-control row-price" value="${initialPrice !== null ? initialPrice : 0}" oninput="recomputeTotals()" style="text-align:left" /></td>
1022 + <td style="width:160px"><input type="number" class="form-control row-price" value="${initialPrice!==null?initialPrice:0}" oninput="recomputeTotals()" style="text-align:left" /></td>
1023 <td class="row-linetotal" style="width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr">۰</td>
1167 - <td style="width:50px;text-align:center;vertical-align:middle"><button class="btn btn-danger btn-inline" style="min-height:36px;padding:4px 10px" onclick="document.getElementById('${rowKey}').remove();updateInvoiceItemRowNumbers();recomputeTotals()">✕</button></td>
1168 - `;
1024 + <td style="width:50px;text-align:center;vertical-align:middle"><button class="btn btn-danger btn-inline" style="min-height:36px;padding:4px 10px" onclick="document.getElementById('${rowKey}').remove();updateInvoiceItemRowNumbers();recomputeTotals()">✕</button></td>`;
1025 tbody.appendChild(tr);
1026 updateInvoiceItemRowNumbers();
1171 - if (selectedProdId && initialPrice === null) onRowProductChange(rowKey);
1027 + if(selectedProdId&&initialPrice===null)onRowProductChange(rowKey);
1028 else recomputeTotals();
1029 }
1174 -
1175 -function onRowProductChange(rowKey) {
1176 - const tr = document.getElementById(rowKey);
1177 - if (!tr) return;
1178 - const sel = tr.querySelector('.row-product-select');
1179 - const opt = sel.options[sel.selectedIndex];
1180 - const prc = opt?.getAttribute('data-price') || 0;
1181 - const unt = opt?.getAttribute('data-unit');
1182 - tr.querySelector('.row-price').value = prc;
1183 - if (unt) {
1184 - const unitInput = tr.querySelector('.row-unit-input');
1185 - if (unitInput) unitInput.value = unt;
1186 - }
1030 +function onRowProductChange(rowKey){
1031 + const tr=document.getElementById(rowKey);if(!tr)return;
1032 + const sel=tr.querySelector('.row-product-select');
1033 + const opt=sel.options[sel.selectedIndex];
1034 + const prc=opt?.getAttribute('data-price')||0;
1035 + const unt=opt?.getAttribute('data-unit');
1036 + tr.querySelector('.row-price').value=prc;
1037 + if(unt){const unitInput=tr.querySelector('.row-unit-input');if(unitInput)unitInput.value=unt;}
1038 recomputeTotals();
1039 }
1189 -
1190 -function recomputeTotals() {
1191 - let subtotal = 0;
1192 - document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1193 - const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1194 - const prc = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1195 - const line = qty * prc;
1196 - const lineEl = tr.querySelector('.row-linetotal');
1197 - if (lineEl) lineEl.innerText = line.toLocaleString('fa-IR');
1198 - subtotal += line;
1040 +function recomputeTotals(){
1041 + let subtotal=0;
1042 + document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
1043 + const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
1044 + const prc=parseFloat(tr.querySelector('.row-price')?.value)||0;
1045 + const line=qty*prc;
1046 + const lineEl=tr.querySelector('.row-linetotal');
1047 + if(lineEl)lineEl.innerText=line.toLocaleString('fa-IR');
1048 + subtotal+=line;
1049 });
1200 - const discountType = document.getElementById('invoice-discount-type')?.value || 'fixed';
1201 - const discountInput = parseFloat(document.getElementById('invoice-discount-fixed')?.value) || 0;
1202 - const rawDiscount = (discountType === 'percent') ? Math.round(subtotal * (discountInput / 100)) : discountInput;
1203 - const fixedDiscount = Math.max(0, Math.min(rawDiscount, subtotal));
1204 - const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1205 - const vatMode = (kind === 'non_formal') ? 'none' : (document.getElementById('invoice-vat-mode')?.value || 'none');
1206 - const vatType = document.getElementById('invoice-vat-type')?.value || 'percent';
1207 - const vatRate = parseFloat(document.getElementById('invoice-vat-rate-input')?.value) || 0;
1208 - const afterDiscount = Math.max(0, subtotal - fixedDiscount);
1209 - let vatAmount = 0;
1210 - if (vatMode === 'with_vat') {
1211 - vatAmount = (vatType === 'fixed') ? Math.max(0, Math.round(vatRate)) : Math.round(afterDiscount * (vatRate / 100));
1212 - }
1213 - const grandTotal = afterDiscount + vatAmount;
1214 - const cur = getCurrencyLabel();
1215 - const subtotalEl = document.getElementById('summary-subtotal');
1216 - const vatEl = document.getElementById('summary-vat');
1217 - const grandEl = document.getElementById('summary-grandtotal');
1218 - const wordsEl = document.getElementById('summary-words');
1219 - if (subtotalEl) subtotalEl.innerText = subtotal.toLocaleString('fa-IR') + ' ' + cur;
1220 - if (vatEl) vatEl.innerText = vatAmount.toLocaleString('fa-IR') + ' ' + cur;
1221 - if (grandEl) grandEl.innerText = grandTotal.toLocaleString('fa-IR') + ' ' + cur;
1222 - if (wordsEl) wordsEl.innerText = 'به حروف: ' + numberToPersianWords(grandTotal, cur);
1223 - return { subtotal, fixedDiscount, discountType, discountInput, vatAmount, vatType, grandTotal, vatRate };
1224 -}
1225 -
1226 -function commitSaveInvoice() {
1227 - if (!currentUser) return;
1228 - const myCompanies = getMyCompanies();
1229 - const mySettings = getMySettings();
1230 - const companySelect = document.getElementById('invoice-company-id');
1231 - const selectedCompanyId = companySelect ? companySelect.value : mySettings.default_company_id;
1232 - const sellerCompany = myCompanies.find(c => c.id === selectedCompanyId) || myCompanies.find(c => c.id === mySettings.default_company_id) || myCompanies[0];
1233 - if (!sellerCompany) { alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.'); return; }
1234 - const companyId = sellerCompany.id;
1235 - const companyName = sellerCompany.name;
1236 - const contactSelect = document.getElementById('invoice-contact-id');
1237 - const contactId = contactSelect ? contactSelect.value : '';
1238 - const contactName = contactSelect?.options[contactSelect.selectedIndex]?.text || 'مشتری آزاد';
1239 - const number = document.getElementById('invoice-number')?.value.trim() || ('PINV-' + (getMyInvoices().length + 31));
1240 - const date = document.getElementById('invoice-date-input')?.value.trim() || getJalaliNumeric();
1241 - const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1242 - const description = document.getElementById('invoice-desc-input')?.value.trim() || '';
1243 - const editId = document.getElementById('edit-invoice-id')?.value;
1244 - if (kind === 'non_formal') { document.getElementById('invoice-vat-mode').value = 'none'; }
1245 - const items = [];
1246 - document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1247 - const sel = tr.querySelector('.row-product-select');
1248 - const prodId = sel ? sel.value : '';
1249 - const prodName = sel ? sel.options[sel.selectedIndex]?.text : '';
1250 - const unit = tr.querySelector('.row-unit-input')?.value || 'عدد';
1251 - const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1252 - const price = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1253 - if (prodId && qty > 0) { items.push({ prodId, prodName, unit, qty, price, lineTotal: qty * price }); }
1050 + const discountType=document.getElementById('invoice-discount-type')?.value||'fixed';
1051 + const discountInput=parseFloat(document.getElementById('invoice-discount-fixed')?.value)||0;
1052 + const rawDiscount=(discountType==='percent')?Math.round(subtotal*(discountInput/100)):discountInput;
1053 + const fixedDiscount=Math.max(0,Math.min(rawDiscount,subtotal));
1054 + const kind=document.getElementById('invoice-kind')?.value||'non_formal';
1055 + const vatMode=(kind==='non_formal')?'none':(document.getElementById('invoice-vat-mode')?.value||'none');
1056 + const vatType=document.getElementById('invoice-vat-type')?.value||'percent';
1057 + const vatRate=parseFloat(document.getElementById('invoice-vat-rate-input')?.value)||0;
1058 + const afterDiscount=Math.max(0,subtotal-fixedDiscount);
1059 + let vatAmount=0;
1060 + if(vatMode==='with_vat'){vatAmount=(vatType==='fixed')?Math.max(0,Math.round(vatRate)):Math.round(afterDiscount*(vatRate/100));}
1061 + const grandTotal=afterDiscount+vatAmount;
1062 + const cur=getCurrencyLabel();
1063 + const subtotalEl=document.getElementById('summary-subtotal');
1064 + const vatEl=document.getElementById('summary-vat');
1065 + const grandEl=document.getElementById('summary-grandtotal');
1066 + const wordsEl=document.getElementById('summary-words');
1067 + if(subtotalEl)subtotalEl.innerText=subtotal.toLocaleString('fa-IR')+' '+cur;
1068 + if(vatEl)vatEl.innerText=vatAmount.toLocaleString('fa-IR')+' '+cur;
1069 + if(grandEl)grandEl.innerText=grandTotal.toLocaleString('fa-IR')+' '+cur;
1070 + if(wordsEl)wordsEl.innerText='به حروف: '+numberToPersianWords(grandTotal,cur);
1071 + return {subtotal,fixedDiscount,discountType,discountInput,vatAmount,vatType,grandTotal,vatRate};
1072 +}
1073 +function commitSaveInvoice(){
1074 + if(!currentUser)return;
1075 + const myCompanies=getMyCompanies();
1076 + const mySettings=getMySettings();
1077 + const companySelect=document.getElementById('invoice-company-id');
1078 + const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;
1079 + const sellerCompany=myCompanies.find(c=>c.id===selectedCompanyId)||myCompanies.find(c=>c.id===mySettings.default_company_id)||myCompanies[0];
1080 + if(!sellerCompany){alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');return;}
1081 + const companyId=sellerCompany.id;
1082 + const companyName=sellerCompany.name;
1083 + const contactSelect=document.getElementById('invoice-contact-id');
1084 + const contactId=contactSelect?contactSelect.value:'';
1085 + const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
1086 + const number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
1087 + const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
1088 + const kind=document.getElementById('invoice-kind')?.value||'non_formal';
1089 + const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
1090 + const editId=document.getElementById('edit-invoice-id')?.value;
1091 + if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
1092 + const items=[];
1093 + document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
1094 + const sel=tr.querySelector('.row-product-select');
1095 + const prodId=sel?sel.value:'';
1096 + const prodName=sel?sel.options[sel.selectedIndex]?.text:'';
1097 + const unit=tr.querySelector('.row-unit-input')?.value||'عدد';
1098 + const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
1099 + const price=parseFloat(tr.querySelector('.row-price')?.value)||0;
1100 + if(prodId&&qty>0){items.push({prodId,prodName,unit,qty,price,lineTotal:qty*price});}
1101 });
1255 - if (items.length === 0) { alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.'); return; }
1256 - const totals = recomputeTotals();
1257 - const kindLabels = { formal: 'رسمی', non_formal: 'غیررسمی', pre_invoice: 'پیش‌فاکتور' };
1258 - const cur = getCurrencyLabel();
1259 - if (editId) {
1260 - const existingIndex = datastore.invoices.findIndex(i => i.id === editId && i.ownerUserId === currentUser.id);
1261 - if (existingIndex !== -1) {
1262 - datastore.invoices[existingIndex] = { ...datastore.invoices[existingIndex], ownerUserId: currentUser.id, number, date, companyId, companyName, kind, kindLabel: kindLabels[kind], contactId, contactName, paymentMethod: 'cash', paymentMethodLabel: 'نقدی', subtotal: totals.subtotal, discount: totals.fixedDiscount, discountType: totals.discountType, discountInput: totals.discountInput, vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate, grandTotal: totals.grandTotal, description, items, currencyLabel: cur };
1102 + if(items.length===0){alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');return;}
1103 + const totals=recomputeTotals();
1104 + const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور'};
1105 + const cur=getCurrencyLabel();
1106 + if(editId){
1107 + const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
1108 + if(existingIndex!==-1){
1109 + datastore.invoices[existingIndex]={...datastore.invoices[existingIndex],ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,paymentMethod:'cash',paymentMethodLabel:'نقدی',subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur};
1110 alert('فاکتور با موفقیت ویرایش شد.');
1111 }
1112 cancelInvoiceEdit();
1266 - } else {
1267 - const record = { id: 'INV_' + Date.now(), ownerUserId: currentUser.id, number, date, companyId, companyName, kind, kindLabel: kindLabels[kind], contactId, contactName, paymentMethod: 'cash', paymentMethodLabel: 'نقدی', subtotal: totals.subtotal, discount: totals.fixedDiscount, discountType: totals.discountType, discountInput: totals.discountInput, vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate, grandTotal: totals.grandTotal, description, items, currencyLabel: cur };
1113 + }else{
1114 + const record={id:'INV_'+Date.now(),ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,paymentMethod:'cash',paymentMethodLabel:'نقدی',subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur};
1115 datastore.invoices.push(record);
1116 alert('فاکتور با موفقیت ثبت شد.');
1117 cancelInvoiceEdit();
@@ -1273,110 +1120,99 @@ function commitSaveInvoice() {
1120 saveDatastore();
1121 refreshAllSurfaces();
1122 }
1276 -
1277 -function editInvoice(invId) {
1278 - const inv = getMyInvoices().find(i => i.id === invId);
1279 - if (!inv) return;
1123 +function editInvoice(invId){
1124 + const inv=getMyInvoices().find(i=>i.id===invId);
1125 + if(!inv)return;
1126 switchView('view-invoices');
1281 - document.getElementById('edit-invoice-id').value = inv.id;
1282 - document.getElementById('invoice-form-title').innerText = `✏️ ویرایش فاکتور #${inv.number}`;
1283 - document.getElementById('btn-cancel-edit').style.display = 'inline-flex';
1284 - document.getElementById('btn-save-invoice').innerText = '💾 ذخیره تغییرات';
1285 - document.getElementById('invoice-company-id').value = inv.companyId;
1286 - document.getElementById('invoice-kind').value = inv.kind;
1287 - document.getElementById('invoice-vat-mode').value = inv.vat > 0 ? 'with_vat' : 'none';
1288 - document.getElementById('invoice-vat-type').value = inv.vatType || 'percent';
1289 - document.getElementById('invoice-vat-rate-input').value = inv.vatRate || 10;
1290 - document.getElementById('invoice-number').value = inv.number;
1291 - document.getElementById('invoice-contact-id').value = inv.contactId;
1292 - document.getElementById('invoice-date-input').value = inv.date;
1293 - document.getElementById('invoice-discount-type').value = inv.discountType || 'fixed';
1294 - document.getElementById('label-invoice-discount-value').innerText = (inv.discountType === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${getCurrencyLabel()})`;
1295 - document.getElementById('invoice-discount-fixed').value = (inv.discountType === 'percent') ? (inv.discountInput || 0) : (inv.discount || 0);
1296 - document.getElementById('invoice-desc-input').value = inv.description || '';
1127 + document.getElementById('edit-invoice-id').value=inv.id;
1128 + document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
1129 + document.getElementById('btn-cancel-edit').style.display='inline-flex';
1130 + document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
1131 + document.getElementById('invoice-company-id').value=inv.companyId;
1132 + document.getElementById('invoice-kind').value=inv.kind;
1133 + document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
1134 + document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
1135 + document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
1136 + document.getElementById('invoice-number').value=inv.number;
1137 + document.getElementById('invoice-contact-id').value=inv.contactId;
1138 + document.getElementById('invoice-date-input').value=inv.date;
1139 + document.getElementById('invoice-discount-type').value=inv.discountType||'fixed';
1140 + document.getElementById('label-invoice-discount-value').innerText=(inv.discountType==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${getCurrencyLabel()})`;
1141 + document.getElementById('invoice-discount-fixed').value=(inv.discountType==='percent')?(inv.discountInput||0):(inv.discount||0);
1142 + document.getElementById('invoice-desc-input').value=inv.description||'';
1143 handleInvoiceKindChange();
1298 - const tbody = document.getElementById('invoice-items-table-body');
1299 - tbody.innerHTML = '';
1300 - inv.items.forEach(it => {
1301 - addInvoiceItemRow(it.prodId, it.qty, it.price);
1302 - const lastRow = tbody.lastElementChild;
1303 - if (lastRow) lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
1144 + const tbody=document.getElementById('invoice-items-table-body');
1145 + tbody.innerHTML='';
1146 + inv.items.forEach(it=>{
1147 + addInvoiceItemRow(it.prodId,it.qty,it.price);
1148 + const lastRow=tbody.lastElementChild;
1149 + if(lastRow)lastRow.querySelector('.row-unit-input').value=it.unit||'عدد';
1150 });
1151 updateInvoiceItemRowNumbers();
1152 recomputeTotals();
1153 }
1308 -
1309 -function cancelInvoiceEdit() {
1310 - document.getElementById('edit-invoice-id').value = '';
1311 - document.getElementById('invoice-form-title').innerText = 'صدور فاکتور جدید';
1312 - document.getElementById('btn-cancel-edit').style.display = 'none';
1313 - document.getElementById('btn-save-invoice').innerText = '💾 ثبت فاکتور';
1314 - document.getElementById('invoice-items-table-body').innerHTML = '';
1315 - document.getElementById('invoice-number').value = '';
1316 - document.getElementById('invoice-discount-type').value = 'fixed';
1317 - document.getElementById('label-invoice-discount-value').innerText = `مبلغ تخفیف (${getCurrencyLabel()})`;
1318 - document.getElementById('invoice-discount-fixed').value = 0;
1319 - document.getElementById('invoice-vat-type').value = 'percent';
1320 - document.getElementById('invoice-desc-input').value = '';
1154 +function cancelInvoiceEdit(){
1155 + document.getElementById('edit-invoice-id').value='';
1156 + document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
1157 + document.getElementById('btn-cancel-edit').style.display='none';
1158 + document.getElementById('btn-save-invoice').innerText='💾 ثبت فاکتور';
1159 + document.getElementById('invoice-items-table-body').innerHTML='';
1160 + document.getElementById('invoice-number').value='';
1161 + document.getElementById('invoice-discount-type').value='fixed';
1162 + document.getElementById('label-invoice-discount-value').innerText=`مبلغ تخفیف (${getCurrencyLabel()})`;
1163 + document.getElementById('invoice-discount-fixed').value=0;
1164 + document.getElementById('invoice-vat-type').value='percent';
1165 + document.getElementById('invoice-desc-input').value='';
1166 addInvoiceItemRow();
1167 applyDefaultSettingsToForm();
1168 }
1324 -
1325 -function renderInvoices() {
1326 - const tbody = document.getElementById('invoice-archive-table-body');
1327 - const filterSelect = document.getElementById('filter-invoice-company');
1328 - const selectedFilter = filterSelect?.value || document.getElementById('invoice-company-id')?.value || 'ALL';
1329 - let list = getMyInvoices();
1330 - if (selectedFilter !== 'ALL') list = list.filter(i => i.companyId === selectedFilter);
1331 - if (list.length === 0) {
1332 - tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';
1333 - return;
1334 - }
1335 - tbody.innerHTML = list.map(inv => `
1169 +function renderInvoices(){
1170 + const tbody=document.getElementById('invoice-archive-table-body');
1171 + const filterSelect=document.getElementById('filter-invoice-company');
1172 + const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
1173 + let list=getMyInvoices();
1174 + if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
1175 + if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
1176 + tbody.innerHTML=list.map(inv=>`
1177 <tr>
1178 <td><strong>#${inv.number}</strong></td>
1338 - <td>${inv.companyName || '—'}</td>
1179 + <td>${inv.companyName||'—'}</td>
1180 <td>${inv.contactName}</td>
1340 - <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1181 + <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${inv.kindLabel}</span></td>
1182 <td>${inv.date}</td>
1183 <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1184 <td>
1185 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
1186 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
1187 </td>
1347 - </tr>
1348 - `).join('');
1349 -}
1350 -
1351 -const MAX_ROWS_PER_PAGE = 10;
1352 -
1353 -function computeInvoiceLines(inv) {
1354 - const n = inv.items.length;
1355 - const afterDiscountTotal = Math.max(0, (inv.subtotal || 0) - (inv.discount || 0));
1356 - let usedDiscount = 0, usedVat = 0;
1357 - return inv.items.map((it, idx) => {
1358 - const lineSubtotal = it.lineTotal;
1359 - const isLastItem = (idx === n - 1);
1360 - let lineDiscount, lineVat;
1361 - if (isLastItem) {
1362 - lineDiscount = Math.max(0, (inv.discount || 0) - usedDiscount);
1363 - lineVat = Math.max(0, (inv.vat || 0) - usedVat);
1364 - } else {
1365 - lineDiscount = (inv.subtotal > 0) ? Math.round((inv.discount || 0) * (lineSubtotal / inv.subtotal)) : 0;
1366 - const lineAfterDiscount = lineSubtotal - lineDiscount;
1367 - lineVat = (afterDiscountTotal > 0 && inv.vat > 0) ? Math.round((inv.vat || 0) * (lineAfterDiscount / afterDiscountTotal)) : 0;
1188 + </tr>`).join('');
1189 +}
1190 +const MAX_ROWS_PER_PAGE=10;
1191 +function computeInvoiceLines(inv){
1192 + const n=inv.items.length;
1193 + const afterDiscountTotal=Math.max(0,(inv.subtotal||0)-(inv.discount||0));
1194 + let usedDiscount=0,usedVat=0;
1195 + return inv.items.map((it,idx)=>{
1196 + const lineSubtotal=it.lineTotal;
1197 + const isLastItem=(idx===n-1);
1198 + let lineDiscount,lineVat;
1199 + if(isLastItem){
1200 + lineDiscount=Math.max(0,(inv.discount||0)-usedDiscount);
1201 + lineVat=Math.max(0,(inv.vat||0)-usedVat);
1202 + }else{
1203 + lineDiscount=(inv.subtotal>0)?Math.round((inv.discount||0)*(lineSubtotal/inv.subtotal)):0;
1204 + const lineAfterDiscount=lineSubtotal-lineDiscount;
1205 + lineVat=(afterDiscountTotal>0&&inv.vat>0)?Math.round((inv.vat||0)*(lineAfterDiscount/afterDiscountTotal)):0;
1206 }
1369 - usedDiscount += lineDiscount;
1370 - usedVat += lineVat;
1371 - const lineNet = lineSubtotal - lineDiscount + lineVat;
1372 - return { rowNo: idx + 1, prodName: it.prodName, qty: it.qty, unit: it.unit || 'عدد', price: it.price, lineSubtotal, lineDiscount, lineVat, lineNet };
1207 + usedDiscount+=lineDiscount;usedVat+=lineVat;
1208 + const lineNet=lineSubtotal-lineDiscount+lineVat;
1209 + return {rowNo:idx+1,prodName:it.prodName,qty:it.qty,unit:it.unit||'عدد',price:it.price,lineSubtotal,lineDiscount,lineVat,lineNet};
1210 });
1211 }
1375 -
1376 -function buildFormalPage(items, seller, contact, inv, opt) {
1377 - const cur = inv.currencyLabel || 'ریال';
1378 - const isLast = opt.isLastPage;
1379 - const rowsHtml = items.map(li => `
1212 +function buildFormalPage(items,seller,contact,inv,opt){
1213 + const cur=inv.currencyLabel||'ریال';
1214 + const isLast=opt.isLastPage;
1215 + const rowsHtml=items.map(li=>`
1216 <tr style="text-align:center">
1217 <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1218 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:right;font-size:10.5px;font-weight:600">${li.prodName}</td>
@@ -1387,25 +1223,24 @@ function buildFormalPage(items, seller, contact, inv, opt) {
1223 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineDiscount.toLocaleString('fa-IR')}</td>
1224 <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineVat.toLocaleString('fa-IR')}</td>
1225 <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>
1390 - </tr>
1391 - `).join('');
1392 - const sellerIds = `${seller.national_id || '—'} / ${seller.reg_number || '—'}`;
1393 - const contactIds = `${contact.national_id || '—'} / ${contact.reg_number || '—'}`;
1394 - const cumSub = opt.cumulativeSubtotal || 0;
1395 - const cumDisc = opt.cumulativeDiscount || 0;
1396 - const cumVat = opt.cumulativeVat || 0;
1397 - const cumNet = opt.cumulativeNet || 0;
1398 - const subtotalLabel = isLast ? 'جمع کل اقلام:' : 'جمع اقلام تا این صفحه:';
1399 - const discountLabel = isLast ? 'مجموع تخفیف:' : 'مجموع تخفیف تا این صفحه:';
1400 - const vatLabel = isLast ? 'مالیات و عوارض ارزش افزوده:' : 'مالیات تا این صفحه:';
1401 - const netLabel = isLast ? 'مبلغ قابل پرداخت:' : 'جمع تا این صفحه:';
1402 - const wordsLabel = isLast ? 'مبلغ کل به حروف:' : 'مبلغ تا این صفحه به حروف:';
1403 - const summaryBox = `
1226 + </tr>`).join('');
1227 + const sellerIds=`${seller.national_id||'—'} / ${seller.reg_number||'—'}`;
1228 + const contactIds=`${contact.national_id||'—'} / ${contact.reg_number||'—'}`;
1229 + const cumSub=opt.cumulativeSubtotal||0;
1230 + const cumDisc=opt.cumulativeDiscount||0;
1231 + const cumVat=opt.cumulativeVat||0;
1232 + const cumNet=opt.cumulativeNet||0;
1233 + const subtotalLabel=isLast?'جمع کل اقلام:':'جمع اقلام تا این صفحه:';
1234 + const discountLabel=isLast?'مجموع تخفیف:':'مجموع تخفیف تا این صفحه:';
1235 + const vatLabel=isLast?'مالیات و عوارض ارزش افزوده:':'مالیات تا این صفحه:';
1236 + const netLabel=isLast?'مبلغ قابل پرداخت:':'جمع تا این صفحه:';
1237 + const wordsLabel=isLast?'مبلغ کل به حروف:':'مبلغ تا این صفحه به حروف:';
1238 + const summaryBox=`
1239 <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10.5px;margin-top:3px">
1240 <tr>
1241 <td style="width:60%;border:1px solid #1e3a8a;padding:6px;vertical-align:top;background:#f8fafc">
1407 - <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet, cur)}</div>
1408 - ${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>`}
1242 + <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet,cur)}</div>
1243 + ${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>`}
1244 </td>
1245 <td style="width:40%;border:1px solid #1e3a8a;padding:0">
1246 <table style="width:100%;border-collapse:collapse;font-size:10.5px">
@@ -1416,22 +1251,20 @@ function buildFormalPage(items, seller, contact, inv, opt) {
1251 </table>
1252 </td>
1253 </tr>
1419 - </table>
1420 - `;
1421 - const signatures = isLast ? `
1254 + </table>`;
1255 + const signatures=isLast?`
1256 <table style="width:100%;border-collapse:collapse;border:1px solid #1e3a8a;margin-top:6px;text-align:center;font-size:10.5px">
1257 <tr>
1258 <td style="width:50%;height:50px;vertical-align:top;border:1px solid #1e3a8a;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
1259 <td style="width:50%;height:50px;vertical-align:top;border:1px solid #1e3a8a;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
1260 </tr>
1427 - </table>
1428 - ` : '';
1261 + </table>`:'';
1262 return `
1263 <div class="invoice-a4-page landscape" style="background:#fff;padding:6mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif">
1264 <table style="width:100%;border-collapse:collapse;border:2px solid #1e3a8a;margin-bottom:3px">
1265 <tr>
1266 <td style="width:28%;border:1px solid #1e3a8a;padding:5px;font-size:11px;vertical-align:middle">
1434 - <div style="font-weight:bold;font-size:13px;color:#1e3a8a">${seller.name || 'فروشگاه'}</div>
1267 + <div style="font-weight:bold;font-size:13px;color:#1e3a8a">${seller.name||'فروشگاه'}</div>
1268 <div style="font-size:9.5px;color:#475569;margin-top:1px">صادرکننده فاکتور رسمی</div>
1269 </td>
1270 <td style="width:44%;border:1px solid #1e3a8a;padding:6px;text-align:center;vertical-align:middle;background:#eff6ff">
@@ -1449,38 +1282,38 @@ function buildFormalPage(items, seller, contact, inv, opt) {
1282 <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">الف) مشخصات فروشنده</td></tr>
1283 <tr>
1284 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
1452 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${seller.name || '—'}</strong></td>
1285 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${seller.name||'—'}</strong></td>
1286 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
1454 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${seller.economic_code || '—'}</td>
1287 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${seller.economic_code||'—'}</td>
1288 </tr>
1289 <tr>
1290 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
1291 <td style="border:1px solid #cbd5e1;padding:3px 6px">${sellerIds}</td>
1292 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
1460 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${seller.postal_code || '—'}</td>
1293 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${seller.postal_code||'—'}</td>
1294 </tr>
1295 <tr>
1296 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
1464 - <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${seller.address || '—'} ${seller.phone ? ' | تلفن: ' + seller.phone : ''}</td>
1297 + <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${seller.address||'—'} ${seller.phone?' | تلفن: '+seller.phone:''}</td>
1298 </tr>
1299 </table>
1300 <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px;margin-bottom:3px">
1301 <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">ب) مشخصات خریدار</td></tr>
1302 <tr>
1303 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
1471 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${contact.name || inv.contactName}</strong></td>
1304 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${contact.name||inv.contactName}</strong></td>
1305 <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
1473 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${contact.economic_code || '—'}</td>
1306 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${contact.economic_code||'—'}</td>
1307 </tr>
1308 <tr>
1309 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
1310 <td style="border:1px solid #cbd5e1;padding:3px 6px">${contactIds}</td>
1311 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
1479 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${contact.postal_code || '—'}</td>
1312 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${contact.postal_code||'—'}</td>
1313 </tr>
1314 <tr>
1315 <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
1483 - <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${contact.address || '—'} ${contact.mobile ? ' | همراه: ' + contact.mobile : ''}</td>
1316 + <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${contact.address||'—'} ${contact.mobile?' | همراه: '+contact.mobile:''}</td>
1317 </tr>
1318 </table>
1319 <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px">
@@ -1498,7 +1331,7 @@ function buildFormalPage(items, seller, contact, inv, opt) {
1331 </tr>
1332 </thead>
1333 <tbody>
1501 - ${!opt.isFirstPage ? `<tr style="background:#fef3c7;font-weight:bold;font-size:9.5px"><td colspan="5" style="border:1px solid #1e293b;padding:3px;text-align:left">نقل از صفحه قبل:</td><td colspan="4" style="border:1px solid #1e293b;padding:3px;text-align:left">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1334 + ${!opt.isFirstPage?`<tr style="background:#fef3c7;font-weight:bold;font-size:9.5px"><td colspan="5" style="border:1px solid #1e293b;padding:3px;text-align:left">نقل از صفحه قبل:</td><td colspan="4" style="border:1px solid #1e293b;padding:3px;text-align:left">${(opt.cumulativeBefore||0).toLocaleString('fa-IR')} ${cur}</td></tr>`:''}
1335 ${rowsHtml}
1336 </tbody>
1337 </table>
@@ -1506,14 +1339,13 @@ function buildFormalPage(items, seller, contact, inv, opt) {
1339 ${signatures}
1340 </div>`;
1341 }
1509 -
1510 -function buildNonFormalPage(items, seller, contact, inv, opt) {
1511 - const cur = inv.currencyLabel || 'ریال';
1512 - const isPre = inv.kind === 'pre_invoice';
1513 - const isLast = opt.isLastPage;
1514 - const hasVat = isPre && inv.vat > 0;
1515 - const title = isPre ? 'پیش‌فاکتور فروش کالا و خدمات' : 'فاکتور فروش کالا و خدمات';
1516 - const rowsHtml = items.map(li => hasVat ? `
1342 +function buildNonFormalPage(items,seller,contact,inv,opt){
1343 + const cur=inv.currencyLabel||'ریال';
1344 + const isPre=inv.kind==='pre_invoice';
1345 + const isLast=opt.isLastPage;
1346 + const hasVat=isPre&&inv.vat>0;
1347 + const title=isPre?'پیش‌فاکتور فروش کالا و خدمات':'فاکتور فروش کالا و خدمات';
1348 + const rowsHtml=items.map(li=>hasVat?`
1349 <tr style="text-align:center">
1350 <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.rowNo.toLocaleString('fa-IR')}</td>
1351 <td style="border:1px solid #334155;padding:3px 6px;text-align:right;font-size:10px;font-weight:600">${li.prodName}</td>
@@ -1523,8 +1355,7 @@ function buildNonFormalPage(items, seller, contact, inv, opt) {
1355 <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1356 <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineVat.toLocaleString('fa-IR')}</td>
1357 <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px;font-weight:bold">${li.lineNet.toLocaleString('fa-IR')}</td>
1526 - </tr>
1527 - ` : `
1358 + </tr>`:`
1359 <tr style="text-align:center">
1360 <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1361 <td style="border:1px solid #334155;padding:4px 8px;text-align:right;font-size:10.5px;font-weight:600">${li.prodName}</td>
@@ -1532,50 +1363,47 @@ function buildNonFormalPage(items, seller, contact, inv, opt) {
1363 <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
1364 <td style="border:1px solid #334155;padding:4px 5px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
1365 <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>
1535 - </tr>
1536 - `).join('');
1537 - const cumSub = opt.cumulativeSubtotal || 0;
1538 - const cumDisc = opt.cumulativeDiscount || 0;
1539 - const cumVat = opt.cumulativeVat || 0;
1540 - const cumNet = opt.cumulativeNet || 0;
1541 - const subtotalLabel = isLast ? 'قیمت کل اقلام:' : 'جمع اقلام تا این صفحه:';
1542 - const discountLabel = isLast ? 'تخفیف:' : 'تخفیف تا این صفحه:';
1543 - const vatLabel = isLast ? 'مالیات ارزش افزوده:' : 'مالیات تا این صفحه:';
1544 - const netLabel = isLast ? `مبلغ کل (${cur}):` : 'جمع تا این صفحه:';
1545 - const wordsLabel = isLast ? 'مبلغ به حروف:' : 'مبلغ تا این صفحه به حروف:';
1546 - const summaryBox = `
1366 + </tr>`).join('');
1367 + const cumSub=opt.cumulativeSubtotal||0;
1368 + const cumDisc=opt.cumulativeDiscount||0;
1369 + const cumVat=opt.cumulativeVat||0;
1370 + const cumNet=opt.cumulativeNet||0;
1371 + const subtotalLabel=isLast?'قیمت کل اقلام:':'جمع اقلام تا این صفحه:';
1372 + const discountLabel=isLast?'تخفیف:':'تخفیف تا این صفحه:';
1373 + const vatLabel=isLast?'مالیات ارزش افزوده:':'مالیات تا این صفحه:';
1374 + const netLabel=isLast?`مبلغ کل (${cur}):`:'جمع تا این صفحه:';
1375 + const wordsLabel=isLast?'مبلغ به حروف:':'مبلغ تا این صفحه به حروف:';
1376 + const summaryBox=`
1377 <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px;margin-top:5px">
1378 <tr>
1379 <td style="width:60%;border:1px solid #334155;padding:6px;vertical-align:top;background:#f8fafc">
1550 - <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet, cur)}</div>
1551 - ${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>`}
1380 + <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet,cur)}</div>
1381 + ${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>`}
1382 </td>
1383 <td style="width:40%;border:1px solid #334155;padding:0">
1384 <table style="width:100%;border-collapse:collapse;font-size:10.5px">
1385 <tr><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px">${subtotalLabel}</td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left">${cumSub.toLocaleString('fa-IR')} ${cur}</td></tr>
1556 - ${cumDisc > 0 || inv.discount > 0 ? `<tr><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px">${discountLabel}</td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left">${cumDisc.toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1557 - ${hasVat ? `<tr style="background:#fffbeb"><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px"><strong>${vatLabel}</strong></td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left"><strong>${cumVat.toLocaleString('fa-IR')} ${cur}</strong></td></tr>` : ''}
1386 + ${cumDisc>0||inv.discount>0?`<tr><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px">${discountLabel}</td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left">${cumDisc.toLocaleString('fa-IR')} ${cur}</td></tr>`:''}
1387 + ${hasVat?`<tr style="background:#fffbeb"><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px"><strong>${vatLabel}</strong></td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left"><strong>${cumVat.toLocaleString('fa-IR')} ${cur}</strong></td></tr>`:''}
1388 <tr style="background:#f1f5f9;font-weight:bold;font-size:11.5px"><td style="padding:5px 8px">${netLabel}</td><td style="padding:5px 8px;text-align:left">${cumNet.toLocaleString('fa-IR')} ${cur}</td></tr>
1389 </table>
1390 </td>
1391 </tr>
1562 - </table>
1563 - `;
1564 - const signatures = isLast ? `
1392 + </table>`;
1393 + const signatures=isLast?`
1394 <table style="width:100%;border-collapse:collapse;border:1px solid #334155;margin-top:6px;text-align:center;font-size:10.5px">
1395 <tr>
1396 <td style="width:50%;height:50px;vertical-align:top;border:1px solid #334155;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
1397 <td style="width:50%;height:50px;vertical-align:top;border:1px solid #334155;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
1398 </tr>
1570 - </table>
1571 - ` : '';
1399 + </table>`:'';
1400 return `
1401 <div class="invoice-a4-page landscape" style="background:#fff;padding:7mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif">
1402 <table style="width:100%;border-collapse:collapse;border:2px solid #334155;margin-bottom:5px">
1403 <tr>
1404 <td style="width:30%;border:1px solid #334155;padding:6px;vertical-align:middle">
1577 - <div style="font-weight:bold;font-size:13px;color:#0f172a">${seller.name || 'فروشگاه'}</div>
1578 - <div style="font-size:10px;color:#475569;margin-top:1px">تلفن: ${seller.phone || '—'}</div>
1405 + <div style="font-weight:bold;font-size:13px;color:#0f172a">${seller.name||'فروشگاه'}</div>
1406 + <div style="font-size:10px;color:#475569;margin-top:1px">تلفن: ${seller.phone||'—'}</div>
1407 </td>
1408 <td style="width:40%;border:1px solid #334155;padding:6px;text-align:center;vertical-align:middle;background:#f8fafc">
1409 <h1 style="font-size:15px;margin:0;font-weight:bold;color:#0f172a">${title}</h1>
@@ -1591,15 +1419,15 @@ function buildNonFormalPage(items, seller, contact, inv, opt) {
1419 <tr>
1420 <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
1421 <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات فروشنده:</div>
1594 - <div>نام: <strong>${seller.name || '—'}</strong></div>
1595 - <div>نشانی: ${seller.address || '—'}</div>
1596 - <div>تلفن تماس: ${seller.phone || '—'}</div>
1422 + <div>نام: <strong>${seller.name||'—'}</strong></div>
1423 + <div>نشانی: ${seller.address||'—'}</div>
1424 + <div>تلفن تماس: ${seller.phone||'—'}</div>
1425 </td>
1426 <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
1427 <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات خریدار:</div>
1600 - <div>نام: <strong>${contact.name || inv.contactName}</strong></div>
1601 - <div>نشانی: ${contact.address || '—'}</div>
1602 - <div>شماره همراه: ${contact.mobile || '—'}</div>
1428 + <div>نام: <strong>${contact.name||inv.contactName}</strong></div>
1429 + <div>نشانی: ${contact.address||'—'}</div>
1430 + <div>شماره همراه: ${contact.mobile||'—'}</div>
1431 </td>
1432 </tr>
1433 </table>
@@ -1610,13 +1438,13 @@ function buildNonFormalPage(items, seller, contact, inv, opt) {
1438 <th style="border:1px solid #334155;padding:5px 8px;text-align:right">شرح کالا | خدمات</th>
1439 <th style="border:1px solid #334155;padding:5px 4px;width:60px">واحد</th>
1440 <th style="border:1px solid #334155;padding:5px 4px;width:60px">مقدار</th>
1613 - <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat ? '110' : '150'}px;text-align:left">قیمت واحد (${cur})</th>
1614 - <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat ? '120' : '170'}px;text-align:left">قیمت کل (${cur})</th>
1615 - ${hasVat ? `<th style="border:1px solid #334155;padding:5px 4px;width:110px;text-align:left">مالیات (${cur})</th><th style="border:1px solid #334155;padding:5px 4px;width:130px;text-align:left">مبلغ نهایی (${cur})</th>` : ''}
1441 + <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat?'110':'150'}px;text-align:left">قیمت واحد (${cur})</th>
1442 + <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat?'120':'170'}px;text-align:left">قیمت کل (${cur})</th>
1443 + ${hasVat?`<th style="border:1px solid #334155;padding:5px 4px;width:110px;text-align:left">مالیات (${cur})</th><th style="border:1px solid #334155;padding:5px 4px;width:130px;text-align:left">مبلغ نهایی (${cur})</th>`:''}
1444 </tr>
1445 </thead>
1446 <tbody>
1619 - ${!opt.isFirstPage ? `<tr style="background:#fef3c7;font-weight:bold;font-size:9.5px"><td colspan="${hasVat ? 6 : 5}" style="border:1px solid #334155;padding:3px;text-align:left">نقل از صفحه قبل:</td><td colspan="${hasVat ? 2 : 1}" style="border:1px solid #334155;padding:3px;text-align:left">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1447 + ${!opt.isFirstPage?`<tr style="background:#fef3c7;font-weight:bold;font-size:9.5px"><td colspan="${hasVat?6:5}" style="border:1px solid #334155;padding:3px;text-align:left">نقل از صفحه قبل:</td><td colspan="${hasVat?2:1}" style="border:1px solid #334155;padding:3px;text-align:left">${(opt.cumulativeBefore||0).toLocaleString('fa-IR')} ${cur}</td></tr>`:''}
1448 ${rowsHtml}
1449 </tbody>
1450 </table>
@@ -1624,439 +1452,355 @@ function buildNonFormalPage(items, seller, contact, inv, opt) {
1452 ${signatures}
1453 </div>`;
1454 }
1627 -
1628 -function renderAndPrintDirect(invId) {
1629 - const inv = getMyInvoices().find(i => i.id === invId);
1630 - if (!inv) return;
1631 - const myCompanies = getMyCompanies();
1632 - const myContacts = getMyContacts();
1633 - const seller = myCompanies.find(c => c.id === inv.companyId) || myCompanies[0] || {};
1634 - const contact = myContacts.find(c => c.id === inv.contactId) || {};
1635 - const isFormal = (inv.kind === 'formal');
1636 - const builder = isFormal ? buildFormalPage : buildNonFormalPage;
1637 - const allLines = computeInvoiceLines(inv);
1638 - const pageGroups = [];
1639 - let cumulativeSub = 0, cumulativeDisc = 0, cumulativeVat = 0;
1640 - for (let start = 0; start < allLines.length; start += MAX_ROWS_PER_PAGE) {
1641 - const pageItems = allLines.slice(start, start + MAX_ROWS_PER_PAGE);
1642 - const isFirstPage = (start === 0);
1643 - const isLastPage = (start + MAX_ROWS_PER_PAGE >= allLines.length);
1644 - const pageSub = pageItems.reduce((s, li) => s + li.lineSubtotal, 0);
1645 - const pageDisc = pageItems.reduce((s, li) => s + li.lineDiscount, 0);
1646 - const pageVat = pageItems.reduce((s, li) => s + li.lineVat, 0);
1647 - const cumSubAfter = cumulativeSub + pageSub;
1648 - const cumDiscAfter = cumulativeDisc + pageDisc;
1649 - const cumVatAfter = cumulativeVat + pageVat;
1650 - const cumNetAfter = cumSubAfter - cumDiscAfter + cumVatAfter;
1651 - pageGroups.push({ items: pageItems, isFirstPage, isLastPage, cumulativeBefore: cumulativeSub, cumulativeSubtotal: cumSubAfter, cumulativeDiscount: cumDiscAfter, cumulativeVat: cumVatAfter, cumulativeNet: cumNetAfter });
1652 - cumulativeSub = cumSubAfter;
1653 - cumulativeDisc = cumDiscAfter;
1654 - cumulativeVat = cumVatAfter;
1655 - }
1656 - const totalPages = pageGroups.length;
1657 - const containerHtml = pageGroups.map((g, idx) => builder(g.items, seller, contact, inv, {
1658 - pageNum: idx + 1, totalPages,
1659 - isFirstPage: g.isFirstPage, isLastPage: g.isLastPage,
1660 - cumulativeBefore: g.cumulativeBefore,
1661 - cumulativeSubtotal: g.cumulativeSubtotal,
1662 - cumulativeDiscount: g.cumulativeDiscount,
1663 - cumulativeVat: g.cumulativeVat,
1664 - cumulativeNet: g.cumulativeNet
1665 - })).join('');
1666 - let orientationStyle = document.getElementById('dynamic-print-orientation');
1667 - if (!orientationStyle) {
1668 - orientationStyle = document.createElement('style');
1669 - orientationStyle.id = 'dynamic-print-orientation';
1670 - document.head.appendChild(orientationStyle);
1455 +function renderAndPrintDirect(invId){
1456 + const inv=getMyInvoices().find(i=>i.id===invId);
1457 + if(!inv)return;
1458 + const myCompanies=getMyCompanies();
1459 + const myContacts=getMyContacts();
1460 + const seller=myCompanies.find(c=>c.id===inv.companyId)||myCompanies[0]||{};
1461 + const contact=myContacts.find(c=>c.id===inv.contactId)||{};
1462 + const isFormal=(inv.kind==='formal');
1463 + const builder=isFormal?buildFormalPage:buildNonFormalPage;
1464 + const allLines=computeInvoiceLines(inv);
1465 + const pageGroups=[];
1466 + let cumulativeSub=0,cumulativeDisc=0,cumulativeVat=0;
1467 + for(let start=0;start<allLines.length;start+=MAX_ROWS_PER_PAGE){
1468 + const pageItems=allLines.slice(start,start+MAX_ROWS_PER_PAGE);
1469 + const isFirstPage=(start===0);
1470 + const isLastPage=(start+MAX_ROWS_PER_PAGE>=allLines.length);
1471 + const pageSub=pageItems.reduce((s,li)=>s+li.lineSubtotal,0);
1472 + const pageDisc=pageItems.reduce((s,li)=>s+li.lineDiscount,0);
1473 + const pageVat=pageItems.reduce((s,li)=>s+li.lineVat,0);
1474 + const cumSubAfter=cumulativeSub+pageSub;
1475 + const cumDiscAfter=cumulativeDisc+pageDisc;
1476 + const cumVatAfter=cumulativeVat+pageVat;
1477 + const cumNetAfter=cumSubAfter-cumDiscAfter+cumVatAfter;
1478 + pageGroups.push({items:pageItems,isFirstPage,isLastPage,cumulativeBefore:cumulativeSub,cumulativeSubtotal:cumSubAfter,cumulativeDiscount:cumDiscAfter,cumulativeVat:cumVatAfter,cumulativeNet:cumNetAfter});
1479 + cumulativeSub=cumSubAfter;cumulativeDisc=cumDiscAfter;cumulativeVat=cumVatAfter;
1480 }
1672 - orientationStyle.innerHTML = `@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
1673 - const printContainer = document.getElementById('printable-invoice');
1674 - printContainer.innerHTML = containerHtml;
1675 - printContainer.style.display = 'block';
1481 + const totalPages=pageGroups.length;
1482 + const containerHtml=pageGroups.map((g,idx)=>builder(g.items,seller,contact,inv,{pageNum:idx+1,totalPages,isFirstPage:g.isFirstPage,isLastPage:g.isLastPage,cumulativeBefore:g.cumulativeBefore,cumulativeSubtotal:g.cumulativeSubtotal,cumulativeDiscount:g.cumulativeDiscount,cumulativeVat:g.cumulativeVat,cumulativeNet:g.cumulativeNet})).join('');
1483 + let orientationStyle=document.getElementById('dynamic-print-orientation');
1484 + if(!orientationStyle){orientationStyle=document.createElement('style');orientationStyle.id='dynamic-print-orientation';document.head.appendChild(orientationStyle);}
1485 + orientationStyle.innerHTML=`@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
1486 + const printContainer=document.getElementById('printable-invoice');
1487 + printContainer.innerHTML=containerHtml;
1488 + printContainer.style.display='block';
1489 window.print();
1677 - printContainer.style.display = 'none';
1678 -}
1679 -
1680 -function commitSaveProduct() {
1681 - if (!currentUser) return;
1682 - const myProducts = getMyProducts();
1683 - const code = document.getElementById('prod-code-input').value || (myProducts.length + 1).toString();
1684 - const name = document.getElementById('prod-name-input').value;
1685 - const spec = document.getElementById('prod-spec-input').value || '';
1686 - const unit = document.getElementById('prod-unit-input').value || 'عدد';
1687 - const buy_price = parseFloat(document.getElementById('prod-buy-input').value) || 0;
1688 - const sale_price = parseFloat(document.getElementById('prod-sale-input').value) || 0;
1689 - if (!name) { alert('عنوان کالا الزامی است.'); return; }
1690 - datastore.products.push({ id: 'P_' + Date.now(), ownerUserId: currentUser.id, code, name, spec, type: 'good', unit, buy_price, sale_price, stock: 0 });
1490 + printContainer.style.display='none';
1491 +}
1492 +function commitSaveProduct(){
1493 + if(!currentUser)return;
1494 + const myProducts=getMyProducts();
1495 + const code=document.getElementById('prod-code-input').value||(myProducts.length+1).toString();
1496 + const name=document.getElementById('prod-name-input').value;
1497 + const spec=document.getElementById('prod-spec-input').value||'';
1498 + const unit=document.getElementById('prod-unit-input').value||'عدد';
1499 + const buy_price=parseFloat(document.getElementById('prod-buy-input').value)||0;
1500 + const sale_price=parseFloat(document.getElementById('prod-sale-input').value)||0;
1501 + if(!name){alert('عنوان کالا الزامی است.');return;}
1502 + datastore.products.push({id:'P_'+Date.now(),ownerUserId:currentUser.id,code,name,spec,type:'good',unit,buy_price,sale_price,stock:0});
1503 saveDatastore();
1504 alert('کالا ثبت شد.');
1693 - document.getElementById('prod-name-input').value = '';
1694 - document.getElementById('prod-spec-input').value = '';
1505 + document.getElementById('prod-name-input').value='';
1506 + document.getElementById('prod-spec-input').value='';
1507 refreshAllSurfaces();
1508 }
1697 -
1698 -function renderProducts() {
1699 - const tbody = document.getElementById('products-catalog-table-body');
1700 - const myProducts = getMyProducts();
1701 - if (myProducts.length === 0) { tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:var(--text-muted);padding:20px">هیچ کالایی ثبت نشده است.</td></tr>'; return; }
1702 - 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><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('');
1703 -}
1704 -
1705 -function deleteProduct(id) {
1706 - if (!currentUser) return;
1707 - if (confirm('حذف شود؟')) {
1708 - datastore.products = datastore.products.filter(p => !(p.id === id && p.ownerUserId === currentUser.id));
1709 - saveDatastore(); refreshAllSurfaces();
1509 +function renderProducts(){
1510 + const tbody=document.getElementById('products-catalog-table-body');
1511 + const myProducts=getMyProducts();
1512 + if(myProducts.length===0){tbody.innerHTML='<tr><td colspan="6" style="text-align:center;color:var(--text-muted);padding:20px">هیچ کالایی ثبت نشده است.</td></tr>';return;}
1513 + 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><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('');
1514 +}
1515 +function deleteProduct(id){
1516 + if(!currentUser)return;
1517 + if(confirm('حذف شود؟')){
1518 + datastore.products=datastore.products.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
1519 + saveDatastore();refreshAllSurfaces();
1520 }
1521 }
1712 -
1713 -function openQuickProductModal() { document.getElementById('modal-quick-product').classList.add('active'); }
1714 -function closeQuickProductModal() { document.getElementById('modal-quick-product').classList.remove('active'); }
1715 -
1716 -function saveQuickProduct() {
1717 - if (!currentUser) return;
1718 - const myProducts = getMyProducts();
1719 - const code = document.getElementById('quick-p-code').value || (myProducts.length + 1).toString();
1720 - const name = document.getElementById('quick-p-name').value;
1721 - const spec = document.getElementById('quick-p-spec').value || '';
1722 - const unit = document.getElementById('quick-p-unit').value || 'عدد';
1723 - const price = parseFloat(document.getElementById('quick-p-price').value) || 0;
1724 - if (!name) { alert('عنوان کالا الزامی است.'); return; }
1725 - const newId = 'P_' + Date.now();
1726 - datastore.products.push({ id: newId, ownerUserId: currentUser.id, code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good' });
1522 +function openQuickProductModal(){document.getElementById('modal-quick-product').classList.add('active');}
1523 +function closeQuickProductModal(){document.getElementById('modal-quick-product').classList.remove('active');}
1524 +function saveQuickProduct(){
1525 + if(!currentUser)return;
1526 + const myProducts=getMyProducts();
1527 + const code=document.getElementById('quick-p-code').value||(myProducts.length+1).toString();
1528 + const name=document.getElementById('quick-p-name').value;
1529 + const spec=document.getElementById('quick-p-spec').value||'';
1530 + const unit=document.getElementById('quick-p-unit').value||'عدد';
1531 + const price=parseFloat(document.getElementById('quick-p-price').value)||0;
1532 + if(!name){alert('عنوان کالا الزامی است.');return;}
1533 + const newId='P_'+Date.now();
1534 + datastore.products.push({id:newId,ownerUserId:currentUser.id,code,name,spec,unit,buy_price:0,sale_price:price,stock:0,type:'good'});
1535 saveDatastore();
1536 closeQuickProductModal();
1537 refreshAllSurfaces();
1730 - addInvoiceItemRow(newId, 1, price);
1731 -}
1732 -
1733 -function downloadProductsExcelTemplate() {
1734 - const ws_data = [["کد کالا","نام کالا","مشخصه و نوع","واحد","قیمت فروش (ریال)"],["1","سوئیچ شبکه 24 پورت","با 2 پاور","عدد",2180000000],["2","هارد 2.5 اینچ سرور","","عدد",37000000]];
1735 - const ws = XLSX.utils.aoa_to_sheet(ws_data);
1736 - const wb = XLSX.utils.book_new();
1737 - XLSX.utils.book_append_sheet(wb, ws, "کالاها");
1738 - XLSX.writeFile(wb, "نمونه_کالاها_ایزی_فاکتور.xlsx");
1739 -}
1740 -
1741 -function importProductsFromExcel(event) {
1742 - if (!currentUser) return;
1743 - const file = event.target.files[0];
1744 - if (!file) return;
1745 - const reader = new FileReader();
1746 - reader.onload = function(e) {
1747 - try {
1748 - const data = new Uint8Array(e.target.result);
1749 - const workbook = XLSX.read(data, { type: 'array' });
1750 - const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
1751 - const myProducts = getMyProducts();
1752 - rows.forEach((r, idx) => {
1753 - const name = r["نام کالا"] || r["عنوان"];
1754 - if (name) {
1755 - datastore.products.push({
1756 - id: 'P_' + Date.now() + '_' + idx, ownerUserId: currentUser.id,
1757 - code: (r["کد کالا"] || (myProducts.length + idx + 1)).toString(),
1758 - name: name.toString(),
1759 - spec: (r["مشخصه و نوع"] || '').toString(),
1760 - unit: (r["واحد"] || 'عدد').toString(),
1761 - buy_price: 0,
1762 - sale_price: parseFloat(r["قیمت فروش (ریال)"] || r["قیمت فروش"] || 0) || 0,
1763 - stock: 0, type: 'good'
1764 - });
1538 + addInvoiceItemRow(newId,1,price);
1539 +}
1540 +function downloadProductsExcelTemplate(){
1541 + const ws_data=[["کد کالا","نام کالا","مشخصه و نوع","واحد","قیمت فروش (ریال)"],["1","سوئیچ شبکه 24 پورت","با 2 پاور","عدد",2180000000],["2","هارد 2.5 اینچ سرور","","عدد",37000000]];
1542 + const ws=XLSX.utils.aoa_to_sheet(ws_data);
1543 + const wb=XLSX.utils.book_new();
1544 + XLSX.utils.book_append_sheet(wb,ws,"کالاها");
1545 + XLSX.writeFile(wb,"نمونه_کالاها_فینورا.xlsx");
1546 +}
1547 +function importProductsFromExcel(event){
1548 + if(!currentUser)return;
1549 + const file=event.target.files[0];
1550 + if(!file)return;
1551 + const reader=new FileReader();
1552 + reader.onload=function(e){
1553 + try{
1554 + const data=new Uint8Array(e.target.result);
1555 + const workbook=XLSX.read(data,{type:'array'});
1556 + const rows=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
1557 + const myProducts=getMyProducts();
1558 + rows.forEach((r,idx)=>{
1559 + const name=r["نام کالا"]||r["عنوان"];
1560 + if(name){
1561 + datastore.products.push({id:'P_'+Date.now()+'_'+idx,ownerUserId:currentUser.id,code:(r["کد کالا"]||(myProducts.length+idx+1)).toString(),name:name.toString(),spec:(r["مشخصه و نوع"]||'').toString(),unit:(r["واحد"]||'عدد').toString(),buy_price:0,sale_price:parseFloat(r["قیمت فروش (ریال)"]||r["قیمت فروش"]||0)||0,stock:0,type:'good'});
1562 }
1563 });
1767 - saveDatastore(); refreshAllSurfaces();
1564 + saveDatastore();refreshAllSurfaces();
1565 alert('کالاها ایمپورت شدند.');
1769 - } catch(err) { alert('خطا در فایل اکسل!'); }
1566 + }catch(err){alert('خطا در فایل اکسل!');}
1567 };
1568 reader.readAsArrayBuffer(file);
1569 }
1773 -
1774 -function commitSaveContact() {
1775 - if (!currentUser) return;
1776 - const entity_type = document.getElementById('contact-entity-type').value;
1777 - const custom_prefix = entity_type === 'natural' ? document.getElementById('contact-prefix-select')?.value : '';
1778 - const raw_name = document.getElementById('contact-name-input').value;
1779 - const role = document.getElementById('contact-role-input').value;
1780 - const mobile = document.getElementById('contact-mobile-input').value;
1781 - const national_id = document.getElementById('contact-national-input').value;
1782 - const economic_code = (entity_type === 'natural') ? '' : document.getElementById('contact-economic-input').value;
1783 - const reg_number = (entity_type === 'natural') ? '' : document.getElementById('contact-reg-input').value;
1784 - const postal_code = document.getElementById('contact-postal-input').value;
1785 - const address = document.getElementById('contact-address-input').value;
1786 - if (!raw_name.trim()) { alert('نام طرف حساب الزامی است.'); return; }
1787 - const formatted_name = formatEntityName(raw_name, entity_type, custom_prefix);
1788 - datastore.contacts.push({ id: 'C_' + Date.now(), ownerUserId: currentUser.id, entity_type, name: formatted_name, role, mobile, national_id, economic_code, reg_number, postal_code, address, balance: 0 });
1570 +function commitSaveContact(){
1571 + if(!currentUser)return;
1572 + const entity_type=document.getElementById('contact-entity-type').value;
1573 + const custom_prefix=entity_type==='natural'?document.getElementById('contact-prefix-select')?.value:'';
1574 + const raw_name=document.getElementById('contact-name-input').value;
1575 + const role=document.getElementById('contact-role-input').value;
1576 + const mobile=document.getElementById('contact-mobile-input').value;
1577 + const national_id=document.getElementById('contact-national-input').value;
1578 + const economic_code=(entity_type==='natural')?'':document.getElementById('contact-economic-input').value;
1579 + const reg_number=(entity_type==='natural')?'':document.getElementById('contact-reg-input').value;
1580 + const postal_code=document.getElementById('contact-postal-input').value;
1581 + const address=document.getElementById('contact-address-input').value;
1582 + if(!raw_name.trim()){alert('نام طرف حساب الزامی است.');return;}
1583 + const formatted_name=formatEntityName(raw_name,entity_type,custom_prefix);
1584 + datastore.contacts.push({id:'C_'+Date.now(),ownerUserId:currentUser.id,entity_type,name:formatted_name,role,mobile,national_id,economic_code,reg_number,postal_code,address,balance:0});
1585 saveDatastore();
1586 alert('طرف حساب ثبت شد.');
1791 - document.getElementById('contact-name-input').value = '';
1587 + document.getElementById('contact-name-input').value='';
1588 refreshAllSurfaces();
1589 }
1794 -
1795 -function renderContacts() {
1796 - const tbody = document.getElementById('contacts-ledger-table-body');
1797 - const invSelect = document.getElementById('invoice-contact-id');
1798 - const chqSelect = document.getElementById('chq-contact-select');
1799 - const myContacts = getMyContacts();
1800 - if (myContacts.length === 0) {
1801 - tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">هیچ طرف حسابی ثبت نشده است.</td></tr>';
1802 - } else {
1803 - 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('');
1590 +function renderContacts(){
1591 + const tbody=document.getElementById('contacts-ledger-table-body');
1592 + const invSelect=document.getElementById('invoice-contact-id');
1593 + const chqSelect=document.getElementById('chq-contact-select');
1594 + const myContacts=getMyContacts();
1595 + if(myContacts.length===0){
1596 + tbody.innerHTML='<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">هیچ طرف حسابی ثبت نشده است.</td></tr>';
1597 + }else{
1598 + 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('');
1599 }
1805 - const options = myContacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
1806 - if (invSelect) invSelect.innerHTML = options;
1807 - if (chqSelect) chqSelect.innerHTML = options;
1808 -}
1809 -
1810 -function deleteContact(id) {
1811 - if (!currentUser) return;
1812 - if (confirm('حذف شود؟')) {
1813 - datastore.contacts = datastore.contacts.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
1814 - saveDatastore(); refreshAllSurfaces();
1600 + const options=myContacts.map(c=>`<option value="${c.id}">${c.name}</option>`).join('');
1601 + if(invSelect)invSelect.innerHTML=options;
1602 + if(chqSelect)chqSelect.innerHTML=options;
1603 +}
1604 +function deleteContact(id){
1605 + if(!currentUser)return;
1606 + if(confirm('حذف شود؟')){
1607 + datastore.contacts=datastore.contacts.filter(c=>!(c.id===id&&c.ownerUserId===currentUser.id));
1608 + saveDatastore();refreshAllSurfaces();
1609 }
1610 }
1817 -
1818 -function openQuickContactModal() { document.getElementById('modal-quick-contact').classList.add('active'); handleQuickCEntityChange(); }
1819 -function closeQuickContactModal() { document.getElementById('modal-quick-contact').classList.remove('active'); }
1820 -
1821 -function saveQuickContact() {
1822 - if (!currentUser) return;
1823 - const entity_type = document.getElementById('quick-c-entity').value;
1824 - const prefix = entity_type === 'natural' ? document.getElementById('quick-c-prefix')?.value : '';
1825 - const raw_name = document.getElementById('quick-c-name').value;
1826 - if (!raw_name.trim()) { alert('نام الزامی است.'); return; }
1827 - const newId = 'C_' + Date.now();
1828 - datastore.contacts.push({
1829 - id: newId, ownerUserId: currentUser.id, entity_type,
1830 - name: formatEntityName(raw_name, entity_type, prefix),
1831 - role: 'customer',
1832 - mobile: document.getElementById('quick-c-mobile').value,
1833 - national_id: document.getElementById('quick-c-national').value,
1834 - economic_code: (entity_type === 'natural') ? '' : document.getElementById('quick-c-economic').value,
1835 - reg_number: (entity_type === 'natural') ? '' : document.getElementById('quick-c-reg').value,
1836 - postal_code: document.getElementById('quick-c-postal').value,
1837 - address: document.getElementById('quick-c-address').value,
1838 - balance: 0
1839 - });
1611 +function openQuickContactModal(){document.getElementById('modal-quick-contact').classList.add('active');handleQuickCEntityChange();}
1612 +function closeQuickContactModal(){document.getElementById('modal-quick-contact').classList.remove('active');}
1613 +function saveQuickContact(){
1614 + if(!currentUser)return;
1615 + const entity_type=document.getElementById('quick-c-entity').value;
1616 + const prefix=entity_type==='natural'?document.getElementById('quick-c-prefix')?.value:'';
1617 + const raw_name=document.getElementById('quick-c-name').value;
1618 + if(!raw_name.trim()){alert('نام الزامی است.');return;}
1619 + const newId='C_'+Date.now();
1620 + datastore.contacts.push({id:newId,ownerUserId:currentUser.id,entity_type,name:formatEntityName(raw_name,entity_type,prefix),role:'customer',mobile:document.getElementById('quick-c-mobile').value,national_id:document.getElementById('quick-c-national').value,economic_code:(entity_type==='natural')?'':document.getElementById('quick-c-economic').value,reg_number:(entity_type==='natural')?'':document.getElementById('quick-c-reg').value,postal_code:document.getElementById('quick-c-postal').value,address:document.getElementById('quick-c-address').value,balance:0});
1621 saveDatastore();
1622 closeQuickContactModal();
1623 refreshAllSurfaces();
1843 - document.getElementById('invoice-contact-id').value = newId;
1844 -}
1845 -
1846 -function downloadContactsExcelTemplate() {
1847 - const ws_data = [["نام شخص یا شرکت","نوع (حقیقی/حقوقی)","شماره همراه","شناسه یا کد ملی","کد اقتصادی","شماره ثبت","کد پستی","نشانی"],["دانشگاه صنعتی شریف","حقوقی","02166165000","14002830256","14002830256","","1458889694","طرشت محله تیموری پلاک 435"]];
1848 - const ws = XLSX.utils.aoa_to_sheet(ws_data);
1849 - const wb = XLSX.utils.book_new();
1850 - XLSX.utils.book_append_sheet(wb, ws, "اشخاص");
1851 - XLSX.writeFile(wb, "نمونه_اشخاص_ایزی_فاکتور.xlsx");
1852 -}
1853 -
1854 -function importContactsFromExcel(event) {
1855 - if (!currentUser) return;
1856 - const file = event.target.files[0];
1857 - if (!file) return;
1858 - const reader = new FileReader();
1859 - reader.onload = function(e) {
1860 - try {
1861 - const data = new Uint8Array(e.target.result);
1862 - const workbook = XLSX.read(data, { type: 'array' });
1863 - const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
1864 - rows.forEach((r, idx) => {
1865 - const raw_name = r["نام شخص یا شرکت"] || r["نام"];
1866 - if (raw_name) {
1867 - const entity_type = (r["نوع (حقیقی/حقوقی)"] || '').includes('حقوقی') ? 'legal' : 'natural';
1868 - datastore.contacts.push({
1869 - id: 'C_' + Date.now() + '_' + idx, ownerUserId: currentUser.id, entity_type,
1870 - name: formatEntityName(raw_name.toString(), entity_type, 'آقا/خانم'),
1871 - role: 'customer',
1872 - mobile: (r["شماره همراه"] || '').toString(),
1873 - national_id: (r["شناسه یا کد ملی"] || '').toString(),
1874 - economic_code: (entity_type === 'legal' ? (r["کد اقتصادی"] || '') : '').toString(),
1875 - reg_number: (entity_type === 'legal' ? (r["شماره ثبت"] || '') : '').toString(),
1876 - postal_code: (r["کد پستی"] || '').toString(),
1877 - address: (r["نشانی"] || '').toString(),
1878 - balance: 0
1879 - });
1624 + document.getElementById('invoice-contact-id').value=newId;
1625 +}
1626 +function downloadContactsExcelTemplate(){
1627 + const ws_data=[["نام شخص یا شرکت","نوع (حقیقی/حقوقی)","شماره همراه","شناسه یا کد ملی","کد اقتصادی","شماره ثبت","کد پستی","نشانی"],["دانشگاه صنعتی شریف","حقوقی","02166165000","14002830256","14002830256","","1458889694","طرشت محله تیموری پلاک 435"]];
1628 + const ws=XLSX.utils.aoa_to_sheet(ws_data);
1629 + const wb=XLSX.utils.book_new();
1630 + XLSX.utils.book_append_sheet(wb,ws,"اشخاص");
1631 + XLSX.writeFile(wb,"نمونه_اشخاص_فینورا.xlsx");
1632 +}
1633 +function importContactsFromExcel(event){
1634 + if(!currentUser)return;
1635 + const file=event.target.files[0];
1636 + if(!file)return;
1637 + const reader=new FileReader();
1638 + reader.onload=function(e){
1639 + try{
1640 + const data=new Uint8Array(e.target.result);
1641 + const workbook=XLSX.read(data,{type:'array'});
1642 + const rows=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
1643 + rows.forEach((r,idx)=>{
1644 + const raw_name=r["نام شخص یا شرکت"]||r["نام"];
1645 + if(raw_name){
1646 + const entity_type=(r["نوع (حقیقی/حقوقی)"]||'').includes('حقوقی')?'legal':'natural';
1647 + datastore.contacts.push({id:'C_'+Date.now()+'_'+idx,ownerUserId:currentUser.id,entity_type,name:formatEntityName(raw_name.toString(),entity_type,'آقا/خانم'),role:'customer',mobile:(r["شماره همراه"]||'').toString(),national_id:(r["شناسه یا کد ملی"]||'').toString(),economic_code:(entity_type==='legal'?(r["کد اقتصادی"]||''):'').toString(),reg_number:(entity_type==='legal'?(r["شماره ثبت"]||''):'').toString(),postal_code:(r["کد پستی"]||'').toString(),address:(r["نشانی"]||'').toString(),balance:0});
1648 }
1649 });
1882 - saveDatastore(); refreshAllSurfaces();
1650 + saveDatastore();refreshAllSurfaces();
1651 alert('اشخاص ایمپورت شدند.');
1884 - } catch(err) { alert('خطا در فایل اکسل!'); }
1652 + }catch(err){alert('خطا در فایل اکسل!');}
1653 };
1654 reader.readAsArrayBuffer(file);
1655 }
1888 -
1889 -function commitSaveCheque() {
1890 - if (!currentUser) return;
1891 - const direction = document.getElementById('chq-direction-input').value;
1892 - const contactSelect = document.getElementById('chq-contact-select');
1893 - const contactName = contactSelect.options[contactSelect.selectedIndex]?.text || '';
1894 - const sayad_id = document.getElementById('chq-sayad-input').value;
1895 - const bank = document.getElementById('chq-bank-input').value;
1896 - const amount = parseFloat(document.getElementById('chq-amount-input').value) || 0;
1897 - if (!sayad_id || amount <= 0) { alert('اطلاعات چک نامعتبر است.'); return; }
1898 - datastore.cheques.push({ id: 'CHQ_' + Date.now(), ownerUserId: currentUser.id, direction, contactName, sayad_id, bank, amount, due_date: document.getElementById('chq-due-input').value, status: document.getElementById('chq-status-input').value });
1656 +function commitSaveCheque(){
1657 + if(!currentUser)return;
1658 + const direction=document.getElementById('chq-direction-input').value;
1659 + const contactSelect=document.getElementById('chq-contact-select');
1660 + const contactName=contactSelect.options[contactSelect.selectedIndex]?.text||'';
1661 + const sayad_id=document.getElementById('chq-sayad-input').value;
1662 + const bank=document.getElementById('chq-bank-input').value;
1663 + const amount=parseFloat(document.getElementById('chq-amount-input').value)||0;
1664 + if(!sayad_id||amount<=0){alert('اطلاعات چک نامعتبر است.');return;}
1665 + datastore.cheques.push({id:'CHQ_'+Date.now(),ownerUserId:currentUser.id,direction,contactName,sayad_id,bank,amount,due_date:document.getElementById('chq-due-input').value,status:document.getElementById('chq-status-input').value});
1666 saveDatastore();
1667 alert('چک ثبت شد.');
1668 refreshAllSurfaces();
1669 }
1903 -
1904 -function renderCheques() {
1905 - const tbody = document.getElementById('cheques-ledger-table-body');
1906 - const myCheques = getMyCheques();
1907 - 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('');
1670 +function renderCheques(){
1671 + const tbody=document.getElementById('cheques-ledger-table-body');
1672 + const myCheques=getMyCheques();
1673 + 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('');
1674 }
1909 -
1910 -function commitSaveExpense() {
1911 - if (!currentUser) return;
1912 - const amount = parseFloat(document.getElementById('trx-amount-input').value) || 0;
1913 - if (amount <= 0) { alert('مبلغ معتبر نیست.'); return; }
1914 - datastore.expenses.push({ id: 'TRX_' + Date.now(), ownerUserId: currentUser.id, kind: document.getElementById('trx-kind-input').value, category: document.getElementById('trx-category-input').value, amount, desc: document.getElementById('trx-desc-input').value });
1675 +function commitSaveExpense(){
1676 + if(!currentUser)return;
1677 + const amount=parseFloat(document.getElementById('trx-amount-input').value)||0;
1678 + if(amount<=0){alert('مبلغ معتبر نیست.');return;}
1679 + datastore.expenses.push({id:'TRX_'+Date.now(),ownerUserId:currentUser.id,kind:document.getElementById('trx-kind-input').value,category:document.getElementById('trx-category-input').value,amount,desc:document.getElementById('trx-desc-input').value});
1680 saveDatastore();
1681 alert('سند ثبت شد.');
1682 refreshAllSurfaces();
1683 }
1919 -
1920 -function renderExpenses() {
1921 - const tbody = document.getElementById('expenses-ledger-table-body');
1922 - const myExpenses = getMyExpenses();
1923 - 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('');
1924 -}
1925 -
1926 -function commitSaveCompany() {
1927 - if (!currentUser) return;
1928 - const entity_type = document.getElementById('company-entity-type').value;
1929 - const raw_name = document.getElementById('company-name-input').value;
1930 - if (!raw_name.trim()) { alert('نام شرکت الزامی است.'); return; }
1931 - const newComp = {
1932 - id: 'COMP_' + Date.now(), ownerUserId: currentUser.id, entity_type,
1933 - name: formatEntityName(raw_name, entity_type),
1934 - phone: document.getElementById('company-phone-input').value || '',
1935 - national_id: document.getElementById('company-national-input').value || '',
1936 - economic_code: document.getElementById('company-economic-input').value || '',
1937 - reg_number: document.getElementById('company-reg-input').value || '',
1938 - postal_code: document.getElementById('company-postal-input').value || '',
1939 - address: document.getElementById('company-address-input').value || '',
1940 - footer: document.getElementById('company-footer-input')?.value || 'از خرید شما سپاسگزاریم.'
1941 - };
1684 +function renderExpenses(){
1685 + const tbody=document.getElementById('expenses-ledger-table-body');
1686 + const myExpenses=getMyExpenses();
1687 + 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('');
1688 +}
1689 +function commitSaveCompany(){
1690 + if(!currentUser)return;
1691 + const entity_type=document.getElementById('company-entity-type').value;
1692 + const raw_name=document.getElementById('company-name-input').value;
1693 + if(!raw_name.trim()){alert('نام شرکت الزامی است.');return;}
1694 + const newComp={id:'COMP_'+Date.now(),ownerUserId:currentUser.id,entity_type,name:formatEntityName(raw_name,entity_type),phone:document.getElementById('company-phone-input').value||'',national_id:document.getElementById('company-national-input').value||'',economic_code:document.getElementById('company-economic-input').value||'',reg_number:document.getElementById('company-reg-input').value||'',postal_code:document.getElementById('company-postal-input').value||'',address:document.getElementById('company-address-input').value||'',footer:document.getElementById('company-footer-input')?.value||'از خرید شما سپاسگزاریم.'};
1695 datastore.companies.push(newComp);
1943 - const s = getMySettings();
1944 - s.default_company_id = newComp.id;
1696 + const s=getMySettings();
1697 + s.default_company_id=newComp.id;
1698 saveDatastore();
1699 alert('شرکت با موفقیت ثبت و ذخیره شد و به عنوان فروشنده پیش‌فرض تنظیم گردید.');
1947 - ['company-name-input','company-phone-input','company-national-input','company-economic-input','company-reg-input','company-postal-input','company-address-input','company-footer-input'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; });
1700 + ['company-name-input','company-phone-input','company-national-input','company-economic-input','company-reg-input','company-postal-input','company-address-input','company-footer-input'].forEach(id=>{const el=document.getElementById(id);if(el)el.value='';});
1701 refreshAllSurfaces();
1702 }
1950 -
1951 -function renderCompanies() {
1952 - const tbody = document.getElementById('companies-table-body');
1953 - const invoiceCompSelect = document.getElementById('invoice-company-id');
1954 - const filterCompSelect = document.getElementById('filter-invoice-company');
1955 - const myCompanies = getMyCompanies();
1956 - const mySettings = getMySettings();
1957 - const defCompId = mySettings.default_company_id || (myCompanies[0]?.id);
1958 - if (tbody) {
1959 - if (myCompanies.length === 0) {
1960 - tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:var(--text-muted);padding:20px">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
1961 - } else {
1962 - 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('');
1703 +function renderCompanies(){
1704 + const tbody=document.getElementById('companies-table-body');
1705 + const invoiceCompSelect=document.getElementById('invoice-company-id');
1706 + const filterCompSelect=document.getElementById('filter-invoice-company');
1707 + const myCompanies=getMyCompanies();
1708 + const mySettings=getMySettings();
1709 + const defCompId=mySettings.default_company_id||(myCompanies[0]?.id);
1710 + if(tbody){
1711 + if(myCompanies.length===0){
1712 + tbody.innerHTML='<tr><td colspan="5" style="text-align:center;color:var(--text-muted);padding:20px">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
1713 + }else{
1714 + 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('');
1715 }
1716 }
1965 - if (invoiceCompSelect) {
1966 - invoiceCompSelect.innerHTML = myCompanies.map(c => `<option value="${c.id}" ${c.id === defCompId ? 'selected' : ''}>${c.name}</option>`).join('');
1967 - if (defCompId) invoiceCompSelect.value = defCompId;
1717 + if(invoiceCompSelect){
1718 + invoiceCompSelect.innerHTML=myCompanies.map(c=>`<option value="${c.id}" ${c.id===defCompId?'selected':''}>${c.name}</option>`).join('');
1719 + if(defCompId)invoiceCompSelect.value=defCompId;
1720 }
1969 - if (filterCompSelect) {
1970 - const currentVal = filterCompSelect.value || 'ALL';
1971 - filterCompSelect.innerHTML = `<option value="ALL">نمایش همه شرکت‌ها</option>` + myCompanies.map(c => `<option value="${c.id}">فقط ${c.name}</option>`).join('');
1972 - filterCompSelect.value = currentVal;
1721 + if(filterCompSelect){
1722 + const currentVal=filterCompSelect.value||'ALL';
1723 + filterCompSelect.innerHTML=`<option value="ALL">نمایش همه شرکت‌ها</option>`+myCompanies.map(c=>`<option value="${c.id}">فقط ${c.name}</option>`).join('');
1724 + filterCompSelect.value=currentVal;
1725 }
1726 }
1975 -
1976 -function setDefaultCompany(id) { const s = getMySettings(); s.default_company_id = id; saveDatastore(); refreshAllSurfaces(); }
1977 -
1978 -function deleteCompany(id) {
1979 - if (!currentUser) return;
1980 - if (confirm('حذف شود؟')) {
1981 - datastore.companies = datastore.companies.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
1982 - const myCompanies = getMyCompanies();
1983 - const s = getMySettings();
1984 - if (s.default_company_id === id) s.default_company_id = myCompanies[0]?.id || '';
1985 - saveDatastore(); refreshAllSurfaces();
1727 +function setDefaultCompany(id){const s=getMySettings();s.default_company_id=id;saveDatastore();refreshAllSurfaces();}
1728 +function deleteCompany(id){
1729 + if(!currentUser)return;
1730 + if(confirm('حذف شود؟')){
1731 + datastore.companies=datastore.companies.filter(c=>!(c.id===id&&c.ownerUserId===currentUser.id));
1732 + const myCompanies=getMyCompanies();
1733 + const s=getMySettings();
1734 + if(s.default_company_id===id)s.default_company_id=myCompanies[0]?.id||'';
1735 + saveDatastore();refreshAllSurfaces();
1736 }
1737 }
1988 -
1989 -function exportDataBlob() {
1990 - const userExport = { user: currentUser?.username, exportedAt: new Date().toISOString(), companies: getMyCompanies(), contacts: getMyContacts(), products: getMyProducts(), invoices: getMyInvoices(), cheques: getMyCheques(), expenses: getMyExpenses(), settings: getMySettings() };
1991 - const blobString = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(userExport, null, 2));
1992 - const anchor = document.createElement('a');
1993 - anchor.setAttribute("href", blobString);
1994 - anchor.setAttribute("download", `easy-factor-${currentUser?.username || 'data'}-${Date.now()}.json`);
1738 +function exportDataBlob(){
1739 + const userExport={user:currentUser?.username,exportedAt:new Date().toISOString(),companies:getMyCompanies(),contacts:getMyContacts(),products:getMyProducts(),invoices:getMyInvoices(),cheques:getMyCheques(),expenses:getMyExpenses(),settings:getMySettings()};
1740 + const blobString="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(userExport,null,2));
1741 + const anchor=document.createElement('a');
1742 + anchor.setAttribute("href",blobString);
1743 + anchor.setAttribute("download",`finora-${currentUser?.username||'data'}-${Date.now()}.json`);
1744 document.body.appendChild(anchor);
1745 anchor.click();
1746 anchor.remove();
1747 }
1999 -
2000 -function importDataBlob(event) {
2001 - if (!currentUser) return;
2002 - const file = event.target.files[0];
2003 - if (!file) return;
2004 - const reader = new FileReader();
2005 - reader.onload = function(e) {
2006 - try {
2007 - const imported = JSON.parse(e.target.result);
2008 - const userId = currentUser.id;
2009 - ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(key => {
2010 - if (Array.isArray(imported[key])) {
2011 - imported[key].forEach(item => { item.ownerUserId = userId; datastore[key].push(item); });
2012 - }
1748 +function importDataBlob(event){
1749 + if(!currentUser)return;
1750 + const file=event.target.files[0];
1751 + if(!file)return;
1752 + const reader=new FileReader();
1753 + reader.onload=function(e){
1754 + try{
1755 + const imported=JSON.parse(e.target.result);
1756 + const userId=currentUser.id;
1757 + ['companies','contacts','products','invoices','cheques','expenses'].forEach(key=>{
1758 + if(Array.isArray(imported[key])){imported[key].forEach(item=>{item.ownerUserId=userId;datastore[key].push(item);});}
1759 });
2014 - if (imported.settings) { const s = getMySettings(); Object.assign(s, imported.settings, { ownerUserId: userId }); }
2015 - saveDatastore(); refreshAllSurfaces();
1760 + if(imported.settings){const s=getMySettings();Object.assign(s,imported.settings,{ownerUserId:userId});}
1761 + saveDatastore();refreshAllSurfaces();
1762 alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
2017 - } catch(err) { alert('فایل نامعتبر است.'); }
1763 + }catch(err){alert('فایل نامعتبر است.');}
1764 };
1765 reader.readAsText(file);
1766 }
2021 -
2022 -function numberToPersianWords(num, currencyLabel) {
2023 - const cur = currencyLabel || 'ریال';
2024 - if (!num || isNaN(num) || num == 0) return 'صفر ' + cur;
2025 - const yegan = ["", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"];
2026 - const dahgan = ["", "", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"];
2027 - const dah_ta_bist = ["ده", "یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"];
2028 - const sadgan = ["", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"];
2029 - const part_names = ["", "هزار", "میلیون", "میلیارد", "تریلیون"];
2030 - function threeDigitToWords(n) {
2031 - let c = Math.floor(n / 100);
2032 - let d = Math.floor((n % 100) / 10);
2033 - let y = n % 10;
2034 - let parts = [];
2035 - if (c > 0) parts.push(sadgan[c]);
2036 - if (d === 1) parts.push(dah_ta_bist[y]);
2037 - else {
2038 - if (d > 1) parts.push(dahgan[d]);
2039 - if (y > 0) parts.push(yegan[y]);
1767 +function numberToPersianWords(num,currencyLabel){
1768 + const cur=currencyLabel||'ریال';
1769 + if(!num||isNaN(num)||num==0)return 'صفر '+cur;
1770 + const yegan=["","یک","دو","سه","چهار","پنج","شش","هفت","هشت","نه"];
1771 + const dahgan=["","","بیست","سی","چهل","پنجاه","شصت","هفتاد","هشتاد","نود"];
1772 + const dah_ta_bist=["ده","یازده","دوازده","سیزده","چهارده","پانزده","شانزده","هفده","هجده","نوزده"];
1773 + const sadgan=["","صد","دویست","سیصد","چهارصد","پانصد","ششصد","هفتصد","هشتصد","نهصد"];
1774 + const part_names=["","هزار","میلیون","میلیارد","تریلیون"];
1775 + function threeDigitToWords(n){
1776 + let c=Math.floor(n/100);
1777 + let d=Math.floor((n%100)/10);
1778 + let y=n%10;
1779 + let parts=[];
1780 + if(c>0)parts.push(sadgan[c]);
1781 + if(d===1)parts.push(dah_ta_bist[y]);
1782 + else{
1783 + if(d>1)parts.push(dahgan[d]);
1784 + if(y>0)parts.push(yegan[y]);
1785 }
1786 return parts.join(" و ");
1787 }
2043 - let parts = [];
2044 - let chunkIdx = 0;
2045 - let temp = Math.abs(Math.round(num));
2046 - while (temp > 0) {
2047 - let chunk = temp % 1000;
2048 - if (chunk > 0) {
2049 - let w = threeDigitToWords(chunk);
2050 - if (part_names[chunkIdx]) w += " " + part_names[chunkIdx];
1788 + let parts=[];
1789 + let chunkIdx=0;
1790 + let temp=Math.abs(Math.round(num));
1791 + while(temp>0){
1792 + let chunk=temp%1000;
1793 + if(chunk>0){
1794 + let w=threeDigitToWords(chunk);
1795 + if(part_names[chunkIdx])w+=" "+part_names[chunkIdx];
1796 parts.unshift(w);
1797 }
2053 - temp = Math.floor(temp / 1000);
1798 + temp=Math.floor(temp/1000);
1799 chunkIdx++;
1800 }
2056 - return parts.join(" و ") + " " + cur;
1801 + return parts.join(" و ")+" "+cur;
1802 }
2058 -
2059 -window.addEventListener('DOMContentLoaded', () => { initAuthSystem(); });
1803 +window.addEventListener('DOMContentLoaded',()=>{initAuthSystem();});
1804 </script>
1805
1806 <style>
@@ -2077,8 +1821,8 @@ window.addEventListener('DOMContentLoaded', () => { initAuthSystem(); });
1821 }
1822 if(typeof oldSave === 'function') return oldSave();
1823 };
2080 - window.EasyFactorHealth = {
2081 - version: '5.2-dev-info',
1824 + window.FinoraHealth = {
1825 + version: '6.0-finora',
1826 storage: 'localStorage',
1827 checks(){ return { rtl: document.documentElement.dir === 'rtl', storage: !!window.localStorage, printReady: !!document.getElementById('printable-invoice') }; }
1828 };