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

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

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

Synced Dec 3, 17:00 UTC

Update index.html

davoodmehraban89 committed Sep 17, 2026 at 21:51 UTC 9caa279b74529dbfd34dd7beaead00ff174286eb
1 file changed +403 -793
index.html
+403 -793
@@ -2,7 +2,7 @@
2 <html lang="fa" dir="rtl">
3 <head>
4 <meta charset="UTF-8" />
5 - <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
5 + <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6 <title>ایزی فاکتور | سامانه صدور فاکتور و مدیریت مالی</title>
7
8 <link rel="manifest" href="manifest.json" />
@@ -107,7 +107,7 @@
107
108 @media print {
109 @page {
110 - size: A4 portrait; /* پیش‌فرض؛ برای فاکتور رسمی به‌صورت پویا با تگ style تزریقی به landscape تغییر می‌کند */
110 + size: A4 landscape;
111 margin: 8mm 10mm;
112 }
113 html, body {
@@ -120,9 +120,7 @@
120 .sidebar, .mobile-dock, .no-print, #auth-screen, .modal-backdrop {
121 display: none !important;
122 }
123 - .view-pane {
124 - display: none !important;
125 - }
123 + .view-pane { display: none !important; }
124 .main-surface {
125 margin: 0 !important;
126 padding: 0 !important;
@@ -137,23 +135,18 @@
135 }
136 .invoice-a4-page {
137 width: 100% !important;
140 - max-width: 190mm !important;
138 + max-width: 277mm !important;
139 margin: 0 auto !important;
140 padding: 0 !important;
141 page-break-after: always !important;
142 break-after: page !important;
143 box-sizing: border-box !important;
144 }
147 - .invoice-a4-page.landscape {
148 - max-width: 277mm !important; /* فاکتور رسمی: افقی — عرض قابل‌چاپ A4 landscape منهای حاشیه‌ها */
149 - }
145 .invoice-a4-page:last-child {
146 page-break-after: avoid !important;
147 break-after: avoid !important;
148 }
154 - #printable-invoice {
155 - display: block !important;
156 - }
149 + #printable-invoice { display: block !important; }
150 }
151
152 @media (max-width: 768px) {
@@ -195,13 +188,12 @@
188 </div>
189
190 <div class="app-root">
198 - <!-- منوی کناری دسکتاپ -->
191 <aside class="sidebar">
192 <div class="brand-box">
193 <div class="brand-icon">ایزی</div>
194 <div>
195 <h2 style="font-size: 15px; font-weight: bold;">ایزی فاکتور</h2>
204 - <small style="color: var(--text-muted); font-size: 11px;">نسخه چندکاربره ۴.۷</small>
196 + <small style="color: var(--text-muted); font-size: 11px;">نسخه چندکاربره ۴.۸</small>
197 </div>
198 </div>
199 <ul class="sidebar-menu">
@@ -220,7 +212,6 @@
212 </div>
213 </aside>
214
223 - <!-- محتوای اصلی -->
215 <main class="main-surface">
216
217 <!-- ۱. داشبورد -->
@@ -236,14 +227,13 @@
227 </div>
228 </div>
229
239 - <!-- جزئیات لایسنس و اشتراک کاربر بر اساس اولویت سیستم لایسنس -->
230 <div id="dashboard-license-details"></div>
231
232 <div class="grid-kpi">
233 <div class="kpi-unit">
234 <div class="kpi-icon" style="background:#eff6ff; color:var(--primary);">💰</div>
235 <div>
246 - <div class="kpi-lbl">مجموع فروش ثبت‌شده (ریال)</div>
236 + <div class="kpi-lbl">مجموع فروش ثبت‌شده (<span class="cur-label">ریال</span>)</div>
237 <div class="kpi-val" id="kpi-sales-sum">۰ ریال</div>
238 </div>
239 </div>
@@ -281,7 +271,7 @@
271 <th>خریدار</th>
272 <th>نوع فاکتور</th>
273 <th>ارزش افزوده</th>
284 - <th>مبلغ کل (ریال)</th>
274 + <th>مبلغ کل (<span class="cur-label">ریال</span>)</th>
275 <th>عملیات</th>
276 </tr>
277 </thead>
@@ -339,7 +329,6 @@
329 </div>
330 </div>
331
342 - <!-- اقلام کالا -->
332 <div style="margin: 16px 0;">
333 <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
334 <h4 style="font-size: 14px;">اقلام کالا یا خدمات</h4>
@@ -353,8 +342,8 @@
342 <th>شرح کالا | خدمات</th>
343 <th style="width:90px; text-align:center;">واحد</th>
344 <th style="width:100px; text-align:center;">مقدار</th>
356 - <th style="width:160px; text-align:left;">قیمت واحد (ریال)</th>
357 - <th style="width:170px; text-align:left;">قیمت کل (ریال)</th>
345 + <th style="width:160px; text-align:left;">قیمت واحد (<span class="cur-label">ریال</span>)</th>
346 + <th style="width:170px; text-align:left;">قیمت کل (<span class="cur-label">ریال</span>)</th>
347 <th style="width:50px; text-align:center;">حذف</th>
348 </tr>
349 </thead>
@@ -367,7 +356,7 @@
356 <div class="form-row" style="background:#f1f5f9; padding:14px; border-radius:10px; margin-top:12px;">
357 <div class="form-group" style="background:#fff; padding:12px; border-radius:8px; border:1px solid var(--border); margin-bottom:0;">
358 <label style="font-weight:bold; border-bottom:1px solid #eee; padding-bottom:6px; margin-bottom:8px;">مالیات و تخفیف</label>
370 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
359 + <div id="box-invoice-vat-mode-row" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
360 <span>مالیات ارزش افزوده</span>
361 <select id="invoice-vat-mode" class="form-control" style="width:140px; min-height:36px;" onchange="handleVatModeChange()">
362 <option value="none">غیرفعال</option>
@@ -438,7 +427,7 @@
427 <th>خریدار</th>
428 <th>نوع</th>
429 <th>تاریخ</th>
441 - <th>قابل پرداخت (ریال)</th>
430 + <th>قابل پرداخت (<span class="cur-label">ریال</span>)</th>
431 <th>عملیات</th>
432 </tr>
433 </thead>
@@ -468,8 +457,8 @@
457 <div class="form-group"><label>واحد</label><input type="text" id="prod-unit-input" class="form-control" value="عدد" /></div>
458 </div>
459 <div class="form-row">
471 - <div class="form-group"><label>قیمت خرید (ریال)</label><input type="number" id="prod-buy-input" class="form-control" value="0" /></div>
472 - <div class="form-group"><label>قیمت فروش (ریال)</label><input type="number" id="prod-sale-input" class="form-control" value="0" /></div>
460 + <div class="form-group"><label>قیمت خرید (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-buy-input" class="form-control" value="0" /></div>
461 + <div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-sale-input" class="form-control" value="0" /></div>
462 </div>
463 <button class="btn btn-success" onclick="commitSaveProduct()">➕ ثبت کالا</button>
464 </div>
@@ -484,7 +473,7 @@
473 <th>نام کالا</th>
474 <th>مشخصه</th>
475 <th>واحد</th>
487 - <th>قیمت فروش (ریال)</th>
476 + <th>قیمت فروش (<span class="cur-label">ریال</span>)</th>
477 <th>عملیات</th>
478 </tr>
479 </thead>
@@ -530,11 +519,11 @@
519 <div class="form-row">
520 <div class="form-group"><label>نقش</label><select id="contact-role-input" class="form-control"><option value="customer">مشتری</option><option value="supplier">تامین‌کننده</option></select></div>
521 <div class="form-group"><label>همراه</label><input type="text" id="contact-mobile-input" class="form-control" /></div>
533 - <div class="form-group"><label>شناسه / کد ملی</label><input type="text" id="contact-national-input" class="form-control" /></div>
534 - <div class="form-group"><label>کد اقتصادی</label><input type="text" id="contact-economic-input" class="form-control" /></div>
522 + <div class="form-group"><label id="label-contact-national">شناسه ملی</label><input type="text" id="contact-national-input" class="form-control" /></div>
523 + <div class="form-group" id="box-contact-economic"><label>کد اقتصادی</label><input type="text" id="contact-economic-input" class="form-control" /></div>
524 </div>
525 <div class="form-row">
537 - <div class="form-group"><label>شماره ثبت</label><input type="text" id="contact-reg-input" class="form-control" /></div>
526 + <div class="form-group" id="box-contact-reg"><label>شماره ثبت</label><input type="text" id="contact-reg-input" class="form-control" /></div>
527 <div class="form-group"><label>کد پستی</label><input type="text" id="contact-postal-input" class="form-control" /></div>
528 <div class="form-group" style="grid-column: span 2;"><label>نشانی</label><input type="text" id="contact-address-input" class="form-control" /></div>
529 </div>
@@ -549,11 +538,11 @@
538 <tr>
539 <th>نام</th>
540 <th>نوع</th>
552 - <th>شناسه ملی</th>
541 + <th>شناسه / کد ملی</th>
542 <th>کد اقتصادی</th>
543 <th>کد پستی</th>
544 <th>همراه</th>
556 - <th>مانده (ریال)</th>
545 + <th>مانده (<span class="cur-label">ریال</span>)</th>
546 <th>عملیات</th>
547 </tr>
548 </thead>
@@ -574,7 +563,7 @@
563 <div class="form-group"><label>بانک</label><input type="text" id="chq-bank-input" class="form-control" /></div>
564 </div>
565 <div class="form-row">
577 - <div class="form-group"><label>مبلغ (ریال)</label><input type="number" id="chq-amount-input" class="form-control" /></div>
566 + <div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="chq-amount-input" class="form-control" /></div>
567 <div class="form-group"><label>سررسید</label><input type="text" id="chq-due-input" class="form-control" placeholder="1405/06/30" /></div>
568 <div class="form-group"><label>وضعیت</label><select id="chq-status-input" class="form-control"><option value="registered">در جریان</option><option value="cleared">وصول شده</option></select></div>
569 </div>
@@ -584,7 +573,7 @@
573 <h3 style="font-size: 15px; margin-bottom: 12px;">لیست چک‌ها</h3>
574 <div class="table-responsive">
575 <table>
587 - <thead><tr><th>نوع</th><th>طرف حساب</th><th>بانک / صیاد</th><th>مبلغ (ریال)</th><th>سررسید</th><th>وضعیت</th></tr></thead>
576 + <thead><tr><th>نوع</th><th>طرف حساب</th><th>بانک / صیاد</th><th>مبلغ (<span class="cur-label">ریال</span>)</th><th>سررسید</th><th>وضعیت</th></tr></thead>
577 <tbody id="cheques-ledger-table-body"></tbody>
578 </table>
579 </div>
@@ -598,7 +587,7 @@
587 <div class="form-row">
588 <div class="form-group"><label>نوع</label><select id="trx-kind-input" class="form-control"><option value="expense">هزینه</option><option value="income">درآمد</option></select></div>
589 <div class="form-group"><label>سرفصل</label><select id="trx-category-input" class="form-control"><option value="قبوض">قبوض</option><option value="حقوق">حقوق</option><option value="سایر">سایر</option></select></div>
601 - <div class="form-group"><label>مبلغ (ریال)</label><input type="number" id="trx-amount-input" class="form-control" /></div>
590 + <div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="trx-amount-input" class="form-control" /></div>
591 <div class="form-group"><label>شرح</label><input type="text" id="trx-desc-input" class="form-control" /></div>
592 </div>
593 <button class="btn btn-success" onclick="commitSaveExpense()">➕ ثبت سند</button>
@@ -607,7 +596,7 @@
596 <h3 style="font-size: 15px; margin-bottom: 12px;">گردش هزینه و درآمد</h3>
597 <div class="table-responsive">
598 <table>
610 - <thead><tr><th>نوع</th><th>سرفصل</th><th>شرح</th><th>مبلغ (ریال)</th></tr></thead>
599 + <thead><tr><th>نوع</th><th>سرفصل</th><th>شرح</th><th>مبلغ (<span class="cur-label">ریال</span>)</th></tr></thead>
600 <tbody id="expenses-ledger-table-body"></tbody>
601 </table>
602 </div>
@@ -667,6 +656,7 @@
656 <select id="def-invoice-kind" class="form-control">
657 <option value="non_formal">فاکتور غیررسمی</option>
658 <option value="formal">فاکتور رسمی</option>
659 + <option value="pre_invoice">پیش‌فاکتور فروش</option>
660 </select>
661 </div>
662 <div class="form-group">
@@ -681,6 +671,20 @@
671 <input type="number" id="def-vat-rate" class="form-control" value="10" />
672 </div>
673 </div>
674 + <div class="form-row">
675 + <div class="form-group">
676 + <label>واحد پول</label>
677 + <select id="def-currency-mode" class="form-control" onchange="handleCurrencyModeChange()">
678 + <option value="rial">ریال</option>
679 + <option value="toman">تومان</option>
680 + <option value="custom">سایر (دلخواه)</option>
681 + </select>
682 + </div>
683 + <div class="form-group" id="box-currency-custom" style="display:none;">
684 + <label>نام واحد پول دلخواه</label>
685 + <input type="text" id="def-currency-custom" class="form-control" placeholder="مثلاً: یورو، دلار، درهم..." />
686 + </div>
687 + </div>
688 <button class="btn btn-primary" onclick="commitSaveDefaultSettings()">ذخیره پیش‌فرض‌ها</button>
689 </div>
690 </div>
@@ -709,7 +713,7 @@
713 <div class="accordion-body">
714 <h3 style="font-size:16px; font-weight:bold;">ایزی فاکتور - EasyFactor</h3>
715 <p style="color:var(--text-muted); font-size:13px; margin:6px 0 12px 0;">سامانه ابری صدور فاکتور و مدیریت مالی چندکاربره</p>
712 - <p style="font-size:13px; margin-bottom:14px;">نگارش فعال: <strong>نسخه ۴.۷ (ایزولاسیون کامل داده و مدیریت مرکزی لایسنس)</strong></p>
716 + <p style="font-size:13px; margin-bottom:14px;">نگارش فعال: <strong>نسخه ۴.۸ (Landscape + Currency + Entity-aware)</strong></p>
717 <div style="display:flex; gap:10px;">
718 <button class="btn btn-primary" onclick="alert('آخرین نگارش نصب است.')">بررسی آپدیت</button>
719 <button class="btn btn-secondary" onclick="alert('پشتیبانی فعال است.')">گزارش باگ</button>
@@ -719,7 +723,7 @@
723
724 </section>
725
722 - <!-- بخش ادمین کل و مدیریت کاربران و لایسنس‌ها -->
726 + <!-- بخش ادمین -->
727 <section id="view-admin" class="view-pane">
728 <div class="card">
729 <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; flex-wrap:wrap; gap:10px;">
@@ -732,7 +736,6 @@
736 <button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
737 </div>
738
735 - <!-- فرم تعریف کاربر جدید توسط ادمین -->
739 <div style="background:#f8fafc; border:1px solid var(--border); border-radius:10px; padding:16px; margin-bottom:20px;">
740 <h4 style="font-size:14px; margin-bottom:12px; color:#1e293b;">➕ ایجاد حساب کاربری جدید</h4>
741 <div class="form-row">
@@ -760,7 +763,6 @@
763 </div>
764 </div>
765
763 - <!-- جدول کاربران و لایسنس‌ها با ستون‌های الزامی -->
766 <div class="table-responsive">
767 <table>
768 <thead>
@@ -782,7 +784,6 @@
784 </div>
785 </section>
786
785 - <!-- کانتینر چاپ فاکتور استاندارد A4 (چندصفحه‌ای هوشمند) -->
787 <div id="printable-invoice" style="display:none;"></div>
788
789 </main>
@@ -798,9 +799,9 @@
799 <div class="form-group" style="grid-column: span 2;" id="box-quick-c-name"><label>نام</label><input type="text" id="quick-c-name" class="form-control" /></div>
800 </div>
801 <div class="form-row">
801 - <div class="form-group"><label>شناسه ملی</label><input type="text" id="quick-c-national" class="form-control" /></div>
802 - <div class="form-group"><label>کد اقتصادی</label><input type="text" id="quick-c-economic" class="form-control" /></div>
803 - <div class="form-group"><label>شماره ثبت</label><input type="text" id="quick-c-reg" class="form-control" /></div>
802 + <div class="form-group"><label id="label-quick-c-national">شناسه ملی</label><input type="text" id="quick-c-national" class="form-control" /></div>
803 + <div class="form-group" id="box-quick-c-economic"><label>کد اقتصادی</label><input type="text" id="quick-c-economic" class="form-control" /></div>
804 + <div class="form-group" id="box-quick-c-reg"><label>شماره ثبت</label><input type="text" id="quick-c-reg" class="form-control" /></div>
805 </div>
806 <div class="form-row">
807 <div class="form-group"><label>کد پستی</label><input type="text" id="quick-c-postal" class="form-control" /></div>
@@ -825,7 +826,7 @@
826 </div>
827 <div class="form-row">
828 <div class="form-group"><label>واحد</label><input type="text" id="quick-p-unit" class="form-control" value="عدد" /></div>
828 - <div class="form-group"><label>قیمت فروش (ریال)</label><input type="number" id="quick-p-price" class="form-control" value="0" /></div>
829 + <div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="quick-p-price" class="form-control" value="0" /></div>
830 </div>
831 <div style="display:flex; gap:10px; margin-top:12px;">
832 <button class="btn btn-success" onclick="saveQuickProduct()">ذخیره و افزودن</button>
@@ -834,7 +835,7 @@
835 </div>
836 </div>
837
837 - <!-- مودال تغییر مدت و لایسنس توسط ادمین -->
838 + <!-- مودال تغییر مدت و لایسنس -->
839 <div class="modal-backdrop" id="modal-admin-license-edit">
840 <div class="modal-card">
841 <h3 style="font-size:16px; margin-bottom:12px;" id="modal-license-user-title">تغییر مدت و لایسنس کاربر</h3>
@@ -884,12 +885,10 @@
885 </nav>
886
887 <script>
887 - const STORAGE_KEY = 'easy_factor_commercial_v4_6';
888 - const AUTH_KEY = 'easy_factor_auth_users_v4_6';
888 + const STORAGE_KEY = 'easy_factor_commercial_v4_7';
889 + const AUTH_KEY = 'easy_factor_auth_users_v4_7';
890
890 - /* =========================================================================
891 - توابع کمکی تبدیل و قالب‌بندی تاریخ خورشیدی و اعداد فارسی
892 - ========================================================================= */
891 + /* ---------- توابع تاریخ و اعداد ---------- */
892 function toPersianDigits(str) {
893 if (str === null || str === undefined) return '';
894 return String(str).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
@@ -913,9 +912,7 @@
912 }
913 if (isNaN(dateObj.getTime())) return toPersianDigits(String(dateInput));
914 return new Intl.DateTimeFormat('fa-IR-u-ca-persian', {
916 - year: 'numeric',
917 - month: '2-digit',
918 - day: '2-digit'
915 + year: 'numeric', month: '2-digit', day: '2-digit'
916 }).format(dateObj);
917 }
918
@@ -944,39 +941,22 @@
941 return d.toISOString().split('T')[0];
942 }
943
947 - /* =========================================================================
948 - سیستم مرکزی کاربران و احراز هویت (Central User Management)
949 - ========================================================================= */
944 + /* ---------- کاربران و احراز هویت ---------- */
945 let currentUser = null;
946 let usersDb = [];
947
948 const defaultAdminUser = {
954 - id: 'user_admin',
955 - username: 'admin',
956 - pass: 'admin123',
957 - role: 'admin',
949 + id: 'user_admin', username: 'admin', pass: 'admin123', role: 'admin',
950 createdAt: '2026-09-16T00:00:00.000Z',
959 - subscriptionType: 'lifetime',
960 - subscriptionStart: '2026-09-16',
961 - subscriptionEnd: '2099-01-01',
951 + subscriptionType: 'lifetime', subscriptionStart: '2026-09-16', subscriptionEnd: '2099-01-01',
952 licenseStatus: 'active',
963 - subscription: {
964 - type: 'lifetime',
965 - startDate: '2026-09-16',
966 - endDate: '2099-01-01',
967 - status: 'active'
968 - }
953 + subscription: { type: 'lifetime', startDate: '2026-09-16', endDate: '2099-01-01', status: 'active' }
954 };
955
956 function loadUsers() {
957 const saved = localStorage.getItem(AUTH_KEY);
958 if (saved) {
974 - try {
975 - usersDb = JSON.parse(saved);
976 - } catch (e) {
977 - console.error('Error parsing users:', e);
978 - usersDb = [];
979 - }
959 + try { usersDb = JSON.parse(saved); } catch (e) { usersDb = []; }
960 }
961 if (!Array.isArray(usersDb) || usersDb.length === 0) {
962 usersDb = [defaultAdminUser];
@@ -984,20 +964,14 @@
964 } else {
965 let modified = false;
966 usersDb.forEach((u, idx) => {
987 - if (!u.id) {
988 - u.id = u.username === 'admin' ? 'user_admin' : 'usr_' + Date.now() + '_' + idx;
989 - modified = true;
990 - }
991 - if (!u.createdAt) {
992 - u.createdAt = new Date().toISOString();
993 - modified = true;
994 - }
967 + if (!u.id) { u.id = u.username === 'admin' ? 'user_admin' : 'usr_' + Date.now() + '_' + idx; modified = true; }
968 + if (!u.createdAt) { u.createdAt = new Date().toISOString(); modified = true; }
969 if (!u.subscription) {
970 u.subscription = {
997 - type: u.subscriptionType || u.license_type || 'trial',
971 + type: u.subscriptionType || 'trial',
972 startDate: u.subscriptionStart || new Date().toISOString().split('T')[0],
999 - endDate: u.subscriptionEnd || u.expire_date || addDaysToDate(null, 15),
1000 - status: (u.license_type === 'lifetime' || u.subscriptionType === 'lifetime' || u.role === 'admin') ? 'active' : 'trial'
973 + endDate: u.subscriptionEnd || addDaysToDate(null, 15),
974 + status: (u.subscriptionType === 'lifetime' || u.role === 'admin') ? 'active' : 'trial'
975 };
976 modified = true;
977 }
@@ -1011,20 +985,14 @@
985 return usersDb;
986 }
987
1014 - function persistUsers() {
1015 - localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb));
1016 - }
988 + function persistUsers() { localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb)); }
989
990 function initAuthSystem() {
991 loadUsers();
1020 -
1021 - const activeSession = sessionStorage.getItem('easy_factor_session_v4_6');
992 + const activeSession = sessionStorage.getItem('easy_factor_session_v4_7');
993 if (activeSession) {
994 const u = usersDb.find(x => x.username === activeSession);
1024 - if (u) {
1025 - loginSuccess(u);
1026 - return;
1027 - }
995 + if (u) { loginSuccess(u); return; }
996 }
997 document.getElementById('auth-screen').style.display = 'flex';
998 }
@@ -1034,55 +1002,29 @@
1002 const pass = document.getElementById('auth-password').value.trim();
1003 loadUsers();
1004 const found = usersDb.find(x => x.username === user && x.pass === pass);
1037 -
1038 - if (!found) {
1039 - alert('نام کاربری یا رمز عبور اشتباه است.');
1040 - return;
1041 - }
1042 -
1043 - sessionStorage.setItem('easy_factor_session_v4_6', found.username);
1005 + if (!found) { alert('نام کاربری یا رمز عبور اشتباه است.'); return; }
1006 + sessionStorage.setItem('easy_factor_session_v4_7', found.username);
1007 loginSuccess(found);
1008 }
1009
1010 function switchToRegister() {
1011 const user = document.getElementById('auth-username').value.trim();
1012 const pass = document.getElementById('auth-password').value.trim();
1050 -
1051 - if (!user || !pass) {
1052 - alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');
1053 - return;
1054 - }
1055 -
1013 + if (!user || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
1014 loadUsers();
1057 - if (usersDb.some(x => x.username === user)) {
1058 - alert('این نام کاربری قبلاً ثبت‌نام کرده است.');
1059 - return;
1060 - }
1061 -
1015 + if (usersDb.some(x => x.username === user)) { alert('این نام کاربری قبلاً ثبت‌نام کرده است.'); return; }
1016 const today = new Date().toISOString().split('T')[0];
1017 const expireStr = addDaysToDate(today, 15);
1064 -
1018 const newUser = {
1019 id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
1067 - username: user,
1068 - pass: pass,
1069 - role: 'user',
1070 - createdAt: new Date().toISOString(),
1071 - subscriptionType: 'trial',
1072 - subscriptionStart: today,
1073 - subscriptionEnd: expireStr,
1020 + username: user, pass: pass, role: 'user', createdAt: new Date().toISOString(),
1021 + subscriptionType: 'trial', subscriptionStart: today, subscriptionEnd: expireStr,
1022 licenseStatus: 'trial',
1075 - subscription: {
1076 - type: 'trial',
1077 - startDate: today,
1078 - endDate: expireStr,
1079 - status: 'trial'
1080 - }
1023 + subscription: { type: 'trial', startDate: today, endDate: expireStr, status: 'trial' }
1024 };
1082 -
1025 usersDb.push(newUser);
1026 persistUsers();
1085 - sessionStorage.setItem('easy_factor_session_v4_6', newUser.username);
1027 + sessionStorage.setItem('easy_factor_session_v4_7', newUser.username);
1028 alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
1029 loginSuccess(newUser);
1030 }
@@ -1091,56 +1033,30 @@
1033 currentUser = userObj;
1034 document.getElementById('auth-screen').style.display = 'none';
1035 document.getElementById('logged-user-label').innerText = 'کاربر: ' + userObj.username + (userObj.role === 'admin' ? ' (مدیر سیستم)' : '');
1094 -
1036 const adminMenu = document.getElementById('menu-admin-panel');
1096 - if (userObj.role === 'admin') {
1097 - adminMenu.style.display = 'block';
1098 - } else {
1099 - adminMenu.style.display = 'none';
1100 - }
1101 -
1037 + adminMenu.style.display = (userObj.role === 'admin') ? 'block' : 'none';
1038 initDatastore();
1039 }
1040
1041 function handleLogout() {
1106 - sessionStorage.removeItem('easy_factor_session_v4_6');
1042 + sessionStorage.removeItem('easy_factor_session_v4_7');
1043 window.location.reload();
1044 }
1045
1110 - /* =========================================================================
1111 - منطق لایسنس و اولویت‌بندی نمایش (License System Logic)
1112 - اولویت ۱: اشتراک فعال (Active Subscription) -> هرگز Trial نمایش داده نمی‌شود.
1113 - اولویت ۲: نسخه آزمایشی (Trial Version) یا منقضی شده.
1114 - ========================================================================= */
1046 + /* ---------- لایسنس ---------- */
1047 function updateLicenseDisplay(user) {
1048 if (!user) return;
1049 const badge = document.getElementById('user-license-status-badge');
1050 const detailsBox = document.getElementById('dashboard-license-details');
1119 -
1120 - // دیگر بنر توضیحی جدا نمایش داده نمی‌شود؛ همه‌چیز در همین یک برچسب کوچک بالا-سمت‌چپ خلاصه می‌شود.
1051 if (detailsBox) { detailsBox.style.display = 'none'; detailsBox.innerHTML = ''; }
1122 -
1123 - const sub = user.subscription || {
1124 - type: user.subscriptionType || 'trial',
1125 - startDate: user.subscriptionStart || user.createdAt,
1126 - endDate: user.subscriptionEnd,
1127 - status: user.licenseStatus || 'trial'
1128 - };
1129 -
1052 + const sub = user.subscription || { type: user.subscriptionType || 'trial', startDate: user.subscriptionStart || user.createdAt, endDate: user.subscriptionEnd, status: user.licenseStatus || 'trial' };
1053 const remDays = getRemainingDays(sub.endDate);
1054 const isExpired = remDays <= 0 && sub.type !== 'lifetime';
1055 const hasActiveLicense = (sub.status === 'active') && (sub.type === 'lifetime' || !isExpired) && (sub.type !== 'trial');
1133 -
1056 if (!badge) return;
1135 -
1057 if (hasActiveLicense) {
1137 - if (sub.type === 'lifetime') {
1138 - badge.className = 'badge badge-success';
1139 - badge.innerText = 'وضعیت اشتراک : نامحدود';
1140 - } else {
1141 - badge.className = 'badge badge-success';
1142 - badge.innerText = `وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
1143 - }
1058 + badge.className = 'badge badge-success';
1059 + badge.innerText = (sub.type === 'lifetime') ? 'وضعیت اشتراک : نامحدود' : `وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
1060 } else if (isExpired || sub.status === 'cancelled') {
1061 badge.className = 'badge badge-danger';
1062 badge.innerText = 'وضعیت اشتراک : منقضی شده';
@@ -1150,115 +1066,54 @@
1066 }
1067 }
1068
1153 - /* =========================================================================
1154 - مدیریت مرکزی کاربران توسط ادمین (Admin Central User & License Management)
1155 - ========================================================================= */
1069 + /* ---------- پنل ادمین ---------- */
1070 function adminCreateNewUser() {
1071 const username = document.getElementById('admin-new-username').value.trim();
1072 const pass = document.getElementById('admin-new-password').value.trim();
1073 const plan = document.getElementById('admin-new-subtype').value;
1160 -
1161 - if (!username || !pass) {
1162 - alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');
1163 - return;
1164 - }
1165 -
1074 + if (!username || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
1075 loadUsers();
1167 - if (usersDb.some(u => u.username === username)) {
1168 - alert('این نام کاربری از قبل وجود دارد.');
1169 - return;
1170 - }
1171 -
1076 + if (usersDb.some(u => u.username === username)) { alert('این نام کاربری از قبل وجود دارد.'); return; }
1077 const today = new Date().toISOString().split('T')[0];
1173 - let endDate = today;
1174 - let status = 'active';
1175 -
1176 - if (plan === 'trial') {
1177 - endDate = addDaysToDate(today, 15);
1178 - status = 'trial';
1179 - } else if (plan === 'monthly') {
1180 - endDate = addDaysToDate(today, 30);
1181 - } else if (plan === 'three_months') {
1182 - endDate = addDaysToDate(today, 90);
1183 - } else if (plan === 'annual') {
1184 - endDate = addDaysToDate(today, 365);
1185 - } else if (plan === 'lifetime') {
1186 - endDate = '2099-01-01';
1187 - }
1188 -
1078 + let endDate = today; let status = 'active';
1079 + if (plan === 'trial') { endDate = addDaysToDate(today, 15); status = 'trial'; }
1080 + else if (plan === 'monthly') endDate = addDaysToDate(today, 30);
1081 + else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
1082 + else if (plan === 'annual') endDate = addDaysToDate(today, 365);
1083 + else if (plan === 'lifetime') endDate = '2099-01-01';
1084 const newUser = {
1085 id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
1191 - username,
1192 - pass,
1193 - role: 'user',
1194 - createdAt: new Date().toISOString(),
1195 - subscriptionType: plan,
1196 - subscriptionStart: today,
1197 - subscriptionEnd: endDate,
1198 - licenseStatus: status,
1199 - subscription: {
1200 - type: plan,
1201 - startDate: today,
1202 - endDate: endDate,
1203 - status: status
1204 - }
1086 + username, pass, role: 'user', createdAt: new Date().toISOString(),
1087 + subscriptionType: plan, subscriptionStart: today, subscriptionEnd: endDate, licenseStatus: status,
1088 + subscription: { type: plan, startDate: today, endDate: endDate, status: status }
1089 };
1206 -
1090 usersDb.push(newUser);
1091 persistUsers();
1209 - alert(`کاربر جدید "${username}" با موفقیت ایجاد شد و اطلاعات وی خالی می‌باشد.`);
1092 + alert(`کاربر جدید "${username}" با موفقیت ایجاد شد.`);
1093 document.getElementById('admin-new-username').value = '';
1094 document.getElementById('admin-new-password').value = '';
1095 renderAdminPanel();
1096 }
1097
1215 - function refreshAdminPanel() {
1216 - loadUsers();
1217 - renderAdminPanel();
1218 - }
1098 + function refreshAdminPanel() { loadUsers(); renderAdminPanel(); }
1099
1100 function renderAdminPanel() {
1101 const tbody = document.getElementById('admin-users-table-body');
1102 if (!tbody) return;
1223 -
1103 loadUsers();
1225 - if (usersDb.length === 0) {
1226 - tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding:20px;">هیچ کاربری یافت نشد.</td></tr>';
1227 - return;
1228 - }
1229 -
1230 - const planLabels = {
1231 - monthly: 'طرح ۱ ماهه',
1232 - three_months: 'طرح ۳ ماهه',
1233 - annual: 'طرح ۱ ساله',
1234 - lifetime: 'دائمی (Lifetime)',
1235 - trial: 'آزمایشی (Trial)'
1236 - };
1237 -
1104 + if (usersDb.length === 0) { tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding:20px;">هیچ کاربری یافت نشد.</td></tr>'; return; }
1105 + const planLabels = { monthly: 'طرح ۱ ماهه', three_months: 'طرح ۳ ماهه', annual: 'طرح ۱ ساله', lifetime: 'دائمی (Lifetime)', trial: 'آزمایشی (Trial)' };
1106 tbody.innerHTML = usersDb.map(u => {
1239 - const sub = u.subscription || {
1240 - type: u.subscriptionType || 'trial',
1241 - startDate: u.subscriptionStart,
1242 - endDate: u.subscriptionEnd,
1243 - status: u.licenseStatus || 'trial'
1244 - };
1245 -
1107 + const sub = u.subscription || { type: u.subscriptionType || 'trial', startDate: u.subscriptionStart, endDate: u.subscriptionEnd, status: u.licenseStatus || 'trial' };
1108 const remDays = getRemainingDays(sub.endDate);
1109 const isExp = remDays <= 0 && sub.type !== 'lifetime';
1248 -
1110 let statusBadge = '';
1250 - if (sub.status === 'cancelled') {
1251 - statusBadge = '<span class="badge badge-danger">لغو شده</span>';
1252 - } else if (sub.status === 'active') {
1253 - statusBadge = isExp ? '<span class="badge badge-danger">منقضی شده</span>' : '<span class="badge badge-success">فعال</span>';
1254 - } else {
1255 - statusBadge = isExp ? '<span class="badge badge-danger">آزمایشی منقضی</span>' : '<span class="badge badge-warning">آزمایشی</span>';
1256 - }
1257 -
1111 + if (sub.status === 'cancelled') statusBadge = '<span class="badge badge-danger">لغو شده</span>';
1112 + else if (sub.status === 'active') statusBadge = isExp ? '<span class="badge badge-danger">منقضی شده</span>' : '<span class="badge badge-success">فعال</span>';
1113 + else statusBadge = isExp ? '<span class="badge badge-danger">آزمایشی منقضی</span>' : '<span class="badge badge-warning">آزمایشی</span>';
1114 const startJalali = formatToJalali(sub.startDate);
1115 const endJalali = sub.type === 'lifetime' ? 'نامحدود' : formatToJalali(sub.endDate);
1116 const remDaysText = sub.type === 'lifetime' ? 'نامحدود' : toPersianDigits(Math.max(0, remDays)) + ' روز';
1261 -
1117 return `
1118 <tr>
1119 <td><strong>${u.username}</strong> ${u.role === 'admin' ? '<span class="badge badge-info">مدیر</span>' : ''}</td>
@@ -1273,8 +1128,7 @@
1128 <button class="btn btn-secondary btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="adminExtendSubscription('${u.username}', 30)">+۳۰ روز</button>
1129 ${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>` : ''}
1130 </td>
1276 - </tr>
1277 - `;
1131 + </tr>`;
1132 }).join('');
1133 }
1134
@@ -1282,26 +1136,12 @@
1136 loadUsers();
1137 const u = usersDb.find(x => x.username === username);
1138 if (!u) return;
1285 -
1139 const today = new Date().toISOString().split('T')[0];
1140 const endDate = addDaysToDate(today, 30);
1288 -
1289 - u.subscription = {
1290 - type: 'monthly',
1291 - startDate: today,
1292 - endDate: endDate,
1293 - status: 'active'
1294 - };
1295 - u.subscriptionType = 'monthly';
1296 - u.subscriptionStart = today;
1297 - u.subscriptionEnd = endDate;
1298 - u.licenseStatus = 'active';
1299 -
1141 + u.subscription = { type: 'monthly', startDate: today, endDate: endDate, status: 'active' };
1142 + u.subscriptionType = 'monthly'; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
1143 persistUsers();
1301 - if (currentUser && currentUser.username === username) {
1302 - currentUser = u;
1303 - updateLicenseDisplay(currentUser);
1304 - }
1144 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1145 alert(`لایسنس ۱ ماهه فعال برای کاربر ${username} ثبت شد.`);
1146 renderAdminPanel();
1147 }
@@ -1315,10 +1155,7 @@
1155 document.getElementById('modal-license-duration-select').value = u.subscription?.type || 'monthly';
1156 document.getElementById('modal-admin-license-edit').classList.add('active');
1157 }
1318 -
1319 - function closeLicenseEditModal() {
1320 - document.getElementById('modal-admin-license-edit').classList.remove('active');
1321 - }
1158 + function closeLicenseEditModal() { document.getElementById('modal-admin-license-edit').classList.remove('active'); }
1159
1160 function applyLicenseDurationChange() {
1161 const username = document.getElementById('modal-license-target-username').value;
@@ -1326,31 +1163,16 @@
1163 loadUsers();
1164 const u = usersDb.find(x => x.username === username);
1165 if (!u) return;
1329 -
1166 const today = new Date().toISOString().split('T')[0];
1167 let endDate = today;
1332 -
1168 if (plan === 'monthly') endDate = addDaysToDate(today, 30);
1169 else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
1170 else if (plan === 'annual') endDate = addDaysToDate(today, 365);
1171 else if (plan === 'lifetime') endDate = '2099-01-01';
1337 -
1338 - u.subscription = {
1339 - type: plan,
1340 - startDate: today,
1341 - endDate: endDate,
1342 - status: 'active'
1343 - };
1344 - u.subscriptionType = plan;
1345 - u.subscriptionStart = today;
1346 - u.subscriptionEnd = endDate;
1347 - u.licenseStatus = 'active';
1348 -
1172 + u.subscription = { type: plan, startDate: today, endDate: endDate, status: 'active' };
1173 + u.subscriptionType = plan; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
1174 persistUsers();
1350 - if (currentUser && currentUser.username === username) {
1351 - currentUser = u;
1352 - updateLicenseDisplay(currentUser);
1353 - }
1175 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1176 closeLicenseEditModal();
1177 alert(`طرح لایسنس کاربر ${username} با موفقیت به "${plan}" تغییر یافت.`);
1178 renderAdminPanel();
@@ -1360,32 +1182,18 @@
1182 loadUsers();
1183 const u = usersDb.find(x => x.username === username);
1184 if (!u) return;
1363 -
1185 let currentEnd = u.subscription?.endDate || new Date().toISOString().split('T')[0];
1365 - if (currentEnd.startsWith('2099')) {
1366 - alert('این حساب دائمی است و نیازی به تمدید ندارد.');
1367 - return;
1368 - }
1186 + if (currentEnd.startsWith('2099')) { alert('این حساب دائمی است و نیازی به تمدید ندارد.'); return; }
1187 const today = new Date().toISOString().split('T')[0];
1188 const base = (currentEnd < today) ? today : currentEnd;
1189 const newEnd = addDaysToDate(base, days);
1372 -
1190 if (!u.subscription) u.subscription = {};
1191 u.subscription.endDate = newEnd;
1192 u.subscription.status = 'active';
1376 - if (u.subscription.type === 'trial') {
1377 - u.subscription.type = 'monthly';
1378 - }
1379 -
1380 - u.subscriptionType = u.subscription.type;
1381 - u.subscriptionEnd = newEnd;
1382 - u.licenseStatus = 'active';
1383 -
1193 + if (u.subscription.type === 'trial') u.subscription.type = 'monthly';
1194 + u.subscriptionType = u.subscription.type; u.subscriptionEnd = newEnd; u.licenseStatus = 'active';
1195 persistUsers();
1385 - if (currentUser && currentUser.username === username) {
1386 - currentUser = u;
1387 - updateLicenseDisplay(currentUser);
1388 - }
1196 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1197 alert(`اشتراک کاربر ${username} به مدت ${days} روز تمدید گردید.`);
1198 renderAdminPanel();
1199 }
@@ -1395,204 +1203,129 @@
1203 loadUsers();
1204 const u = usersDb.find(x => x.username === username);
1205 if (!u) return;
1398 -
1206 if (!u.subscription) u.subscription = {};
1207 u.subscription.status = 'cancelled';
1208 u.licenseStatus = 'cancelled';
1402 -
1209 persistUsers();
1404 - if (currentUser && currentUser.username === username) {
1405 - currentUser = u;
1406 - updateLicenseDisplay(currentUser);
1407 - }
1210 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1211 alert(`اشتراک کاربر ${username} لغو گردید.`);
1212 renderAdminPanel();
1213 }
1214
1412 - /* =========================================================================
1413 - تفکیک کامل داده‌ها بر اساس مالکیت کاربر (Multi-User Data Isolation)
1414 - قانون: هر رکورد شامل ownerUserId بوده و کاربر فقط به داده‌های خود دسترسی دارد.
1415 - ========================================================================= */
1416 - let datastore = {
1417 - companies: [],
1418 - contacts: [],
1419 - products: [],
1420 - invoices: [],
1421 - cheques: [],
1422 - expenses: [],
1423 - settings: []
1424 - };
1215 + /* ---------- Datastore ---------- */
1216 + let datastore = { companies: [], contacts: [], products: [], invoices: [], cheques: [], expenses: [], settings: [] };
1217
1426 - function getMyProducts() {
1427 - if (!currentUser) return [];
1428 - return datastore.products.filter(p => p.ownerUserId === currentUser.id);
1429 - }
1430 - function getMyContacts() {
1431 - if (!currentUser) return [];
1432 - return datastore.contacts.filter(c => c.ownerUserId === currentUser.id);
1433 - }
1434 - function getMyCompanies() {
1435 - if (!currentUser) return [];
1436 - return datastore.companies.filter(c => c.ownerUserId === currentUser.id);
1437 - }
1438 - function getMyInvoices() {
1439 - if (!currentUser) return [];
1440 - return datastore.invoices.filter(i => i.ownerUserId === currentUser.id);
1441 - }
1442 - function getMyCheques() {
1443 - if (!currentUser) return [];
1444 - return datastore.cheques.filter(c => c.ownerUserId === currentUser.id);
1445 - }
1446 - function getMyExpenses() {
1447 - if (!currentUser) return [];
1448 - return datastore.expenses.filter(e => e.ownerUserId === currentUser.id);
1449 - }
1218 + function getMyProducts() { return !currentUser ? [] : datastore.products.filter(p => p.ownerUserId === currentUser.id); }
1219 + function getMyContacts() { return !currentUser ? [] : datastore.contacts.filter(c => c.ownerUserId === currentUser.id); }
1220 + function getMyCompanies() { return !currentUser ? [] : datastore.companies.filter(c => c.ownerUserId === currentUser.id); }
1221 + function getMyInvoices() { return !currentUser ? [] : datastore.invoices.filter(i => i.ownerUserId === currentUser.id); }
1222 + function getMyCheques() { return !currentUser ? [] : datastore.cheques.filter(c => c.ownerUserId === currentUser.id); }
1223 + function getMyExpenses() { return !currentUser ? [] : datastore.expenses.filter(e => e.ownerUserId === currentUser.id); }
1224 function getMySettings() {
1451 - if (!currentUser) return { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '' };
1225 + if (!currentUser) return { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
1226 if (!Array.isArray(datastore.settings)) datastore.settings = [];
1227 let s = datastore.settings.find(item => item.ownerUserId === currentUser.id);
1228 if (!s) {
1455 - s = { ownerUserId: currentUser.id, invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '' };
1229 + s = { ownerUserId: currentUser.id, invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
1230 datastore.settings.push(s);
1231 }
1232 + if (typeof s.currency_mode === 'undefined') s.currency_mode = 'rial';
1233 + if (typeof s.currency_custom === 'undefined') s.currency_custom = '';
1234 return s;
1235 }
1236
1237 function saveDatastore() {
1462 - try {
1463 - localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
1464 - return true;
1465 - } catch (err) {
1466 - console.error('Error saving datastore:', err);
1467 - return false;
1468 - }
1469 - }
1470 -
1471 - function persistDatastore() {
1472 - return saveDatastore();
1238 + try { localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore)); return true; }
1239 + catch (err) { console.error('Error saving datastore:', err); return false; }
1240 }
1241
1242 function loadDatastore() {
1243 const persisted = localStorage.getItem(STORAGE_KEY);
1477 - if (persisted) {
1478 - try {
1479 - datastore = JSON.parse(persisted);
1480 - } catch (e) {
1481 - console.error('Error parsing datastore:', e);
1482 - }
1483 - }
1244 + if (persisted) { try { datastore = JSON.parse(persisted); } catch (e) { console.error(e); } }
1245 + ['companies','contacts','products','invoices','cheques','expenses','settings'].forEach(k => { if (!Array.isArray(datastore[k])) datastore[k] = []; });
1246
1485 - if (!Array.isArray(datastore.companies)) datastore.companies = [];
1486 - if (!Array.isArray(datastore.contacts)) datastore.contacts = [];
1487 - if (!Array.isArray(datastore.products)) datastore.products = [];
1488 - if (!Array.isArray(datastore.invoices)) datastore.invoices = [];
1489 - if (!Array.isArray(datastore.cheques)) datastore.cheques = [];
1490 - if (!Array.isArray(datastore.expenses)) datastore.expenses = [];
1491 - if (!Array.isArray(datastore.settings)) datastore.settings = [];
1492 -
1493 - // اگر برای اولین بار برنامه باز شده است، داده‌های اولیه صرفاً متعلق به کاربر admin است
1247 if (datastore.companies.length === 0 && datastore.products.length === 0) {
1248 datastore.companies.push({
1496 - id: 'COMP-1',
1497 - ownerUserId: 'user_admin',
1498 - entity_type: 'legal',
1499 - name: 'آرا سپهر راستین',
1500 - phone: '09124376991',
1501 - national_id: '14008507476',
1502 - economic_code: '14008507476',
1503 - reg_number: '544926',
1504 - postal_code: '1445956311',
1249 + id: 'COMP-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'آرا سپهر راستین',
1250 + phone: '09124376991', national_id: '14008507476', economic_code: '14008507476',
1251 + reg_number: '544926', postal_code: '1445956311',
1252 address: 'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',
1253 footer: 'از خرید شما سپاسگزاریم.'
1254 });
1255 datastore.contacts.push({
1509 - id: 'C-1',
1510 - ownerUserId: 'user_admin',
1511 - entity_type: 'legal',
1512 - name: 'شرکت دانشگاه صنعتی شریف',
1513 - mobile: '02166165000',
1514 - national_id: '14002830256',
1515 - economic_code: '14002830256',
1516 - reg_number: '',
1517 - postal_code: '1458889694',
1518 - address: 'طرشت محله تیموری پلاک 435',
1519 - balance: 7978300000,
1520 - role: 'customer'
1256 + id: 'C-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'شرکت دانشگاه صنعتی شریف',
1257 + mobile: '02166165000', national_id: '14002830256', economic_code: '14002830256',
1258 + reg_number: '', postal_code: '1458889694', address: 'طرشت محله تیموری پلاک 435',
1259 + balance: 7978300000, role: 'customer'
1260 });
1261 datastore.products.push(
1262 { id: 'P-1', ownerUserId: 'user_admin', code: '1', name: 'سوئیچ شبکه 24 پورت فیبر نوری', spec: 'با 2 پاور 350', unit: 'عدد', buy_price: 1800000000, sale_price: 2180000000, stock: 10, type: 'good' },
1263 { id: 'P-2', ownerUserId: 'user_admin', code: '2', name: 'هارد 2.5 اینچ سرور', spec: '', unit: 'عدد', buy_price: 30000000, sale_price: 37000000, stock: 10, type: 'good' }
1264 );
1265 datastore.settings.push({
1527 - ownerUserId: 'user_admin',
1528 - invoice_kind: 'non_formal',
1529 - vat_mode: 'none',
1530 - vat_rate: 10,
1531 - default_company_id: 'COMP-1'
1266 + ownerUserId: 'user_admin', invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10,
1267 + default_company_id: 'COMP-1', currency_mode: 'rial', currency_custom: ''
1268 });
1269 saveDatastore();
1270 } else {
1535 - // مهاجرت امن: رکوردهای قدیمی بدون شناسه مالک به ادمین نسبت داده می‌شوند
1271 let migrated = false;
1272 ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(coll => {
1538 - datastore[coll].forEach(item => {
1539 - if (!item.ownerUserId) {
1540 - item.ownerUserId = 'user_admin';
1541 - migrated = true;
1542 - }
1543 - });
1273 + datastore[coll].forEach(item => { if (!item.ownerUserId) { item.ownerUserId = 'user_admin'; migrated = true; } });
1274 + });
1275 + datastore.settings.forEach(s => {
1276 + if (typeof s.currency_mode === 'undefined') { s.currency_mode = 'rial'; migrated = true; }
1277 + if (typeof s.currency_custom === 'undefined') { s.currency_custom = ''; migrated = true; }
1278 });
1279 if (migrated) saveDatastore();
1280 }
1547 -
1281 return datastore;
1282 }
1283
1551 - function initDatastore() {
1552 - loadDatastore();
1553 - refreshAllSurfaces();
1554 - }
1284 + function initDatastore() { loadDatastore(); refreshAllSurfaces(); }
1285
1286 function getJalaliDate() {
1287 return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { dateStyle: 'full' }).format(new Date());
1288 }
1559 -
1289 function getJalaliNumeric() {
1290 return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date());
1291 }
1292
1293 + /* ---------- واحد پول ---------- */
1294 + function getCurrencyLabel() {
1295 + const s = getMySettings();
1296 + if (s.currency_mode === 'toman') return 'تومان';
1297 + if (s.currency_mode === 'custom') return (s.currency_custom || '').trim() || 'واحد پول';
1298 + return 'ریال';
1299 + }
1300 +
1301 + function refreshCurrencyLabels() {
1302 + const label = getCurrencyLabel();
1303 + document.querySelectorAll('.cur-label').forEach(el => { el.innerText = label; });
1304 + }
1305 +
1306 + function handleCurrencyModeChange() {
1307 + const mode = document.getElementById('def-currency-mode').value;
1308 + document.getElementById('box-currency-custom').style.display = (mode === 'custom') ? 'block' : 'none';
1309 + }
1310 +
1311 function switchView(viewId) {
1312 document.querySelectorAll('.view-pane').forEach(el => el.classList.remove('active'));
1313 const target = document.getElementById(viewId);
1314 if (target) target.classList.add('active');
1568 -
1569 - document.querySelectorAll('.nav-link').forEach(btn => {
1570 - btn.classList.toggle('active', btn.getAttribute('data-view') === viewId);
1571 - });
1572 -
1315 + document.querySelectorAll('.nav-link').forEach(btn => btn.classList.toggle('active', btn.getAttribute('data-view') === viewId));
1316 const dockViews = ['view-dashboard', 'view-invoices', 'view-products', 'view-contacts', 'view-cheques', 'view-settings'];
1574 - document.querySelectorAll('.dock-tab').forEach((dock, idx) => {
1575 - dock.classList.toggle('active', dockViews[idx] === viewId);
1576 - });
1577 -
1578 - if (viewId === 'view-admin') {
1579 - renderAdminPanel();
1580 - }
1581 -
1317 + document.querySelectorAll('.dock-tab').forEach((dock, idx) => { dock.classList.toggle('active', dockViews[idx] === viewId); });
1318 + if (viewId === 'view-admin') renderAdminPanel();
1319 window.scrollTo({ top: 0, behavior: 'smooth' });
1320 }
1321
1585 - function toggleAccordion(headerEl) {
1586 - const item = headerEl.parentElement;
1587 - item.classList.toggle('open');
1588 - }
1322 + function toggleAccordion(headerEl) { headerEl.parentElement.classList.toggle('open'); }
1323
1324 function refreshAllSurfaces() {
1325 const dashDate = document.getElementById('dashboard-date-display');
1326 if (dashDate) dashDate.innerText = getJalaliDate();
1327 const invDate = document.getElementById('invoice-date-input');
1328 if (invDate && !invDate.value) invDate.value = getJalaliNumeric();
1595 -
1329 updateLicenseDisplay(currentUser);
1330 renderCompanies();
1331 renderContacts();
@@ -1603,14 +1336,12 @@
1336 renderExpenses();
1337 applyDefaultSettingsToForm();
1338 handleContactEntityChange();
1606 - if (currentUser && currentUser.role === 'admin') {
1607 - renderAdminPanel();
1608 - }
1339 + handleCurrencyModeChange();
1340 + refreshCurrencyLabels();
1341 + if (currentUser && currentUser.role === 'admin') renderAdminPanel();
1342 }
1343
1611 - /* =========================================================================
1612 - قواعد پیشوند و نام طرف‌حساب
1613 - ========================================================================= */
1344 + /* ---------- نام و پیشوند شخص ---------- */
1345 function formatEntityName(rawName, entityType, customPrefix = '') {
1346 let trimmed = (rawName || '').trim();
1347 if (entityType === 'legal') {
@@ -1618,57 +1349,82 @@
1349 trimmed = 'شرکت ' + trimmed;
1350 }
1351 } else if (entityType === 'natural' && customPrefix) {
1621 - if (!trimmed.startsWith(customPrefix)) {
1622 - trimmed = customPrefix + ' ' + trimmed;
1623 - }
1352 + if (!trimmed.startsWith(customPrefix)) trimmed = customPrefix + ' ' + trimmed;
1353 }
1354 return trimmed;
1355 }
1356
1628 - function handleContactEntityChange() {
1629 - const entitySelect = document.getElementById('contact-entity-type');
1630 - if (!entitySelect) return;
1631 - const entity = entitySelect.value;
1632 - const prefixBox = document.getElementById('box-contact-prefix');
1633 - const nameBox = document.getElementById('box-contact-name');
1357 + /* ---------- رفتار فرم طرف‌حساب بر اساس نوع شخص ---------- */
1358 + function applyEntityTypeToForm(entity, opts) {
1359 + const { prefixId, nameId, econId, regId, nationalLabelId } = opts;
1360 + const prefixBox = document.getElementById(prefixId);
1361 + const nameBox = document.getElementById(nameId);
1362 + const econBox = document.getElementById(econId);
1363 + const regBox = document.getElementById(regId);
1364 + const natLabel = document.getElementById(nationalLabelId);
1365
1366 if (entity === 'legal') {
1367 if (prefixBox) prefixBox.style.display = 'none';
1368 if (nameBox) nameBox.style.gridColumn = 'span 3';
1369 + if (econBox) econBox.style.display = 'block';
1370 + if (regBox) regBox.style.display = 'block';
1371 + if (natLabel) natLabel.innerText = 'شناسه ملی';
1372 } else {
1373 if (prefixBox) prefixBox.style.display = 'block';
1374 if (nameBox) nameBox.style.gridColumn = 'span 2';
1375 + if (econBox) econBox.style.display = 'none';
1376 + if (regBox) regBox.style.display = 'none';
1377 + if (natLabel) natLabel.innerText = 'کد ملی';
1378 }
1379 }
1380
1381 + function handleContactEntityChange() {
1382 + const entitySelect = document.getElementById('contact-entity-type');
1383 + if (!entitySelect) return;
1384 + applyEntityTypeToForm(entitySelect.value, {
1385 + prefixId: 'box-contact-prefix', nameId: 'box-contact-name',
1386 + econId: 'box-contact-economic', regId: 'box-contact-reg',
1387 + nationalLabelId: 'label-contact-national'
1388 + });
1389 + }
1390 +
1391 function handleQuickCEntityChange() {
1392 const entitySelect = document.getElementById('quick-c-entity');
1393 if (!entitySelect) return;
1647 - const entity = entitySelect.value;
1648 - const prefixBox = document.getElementById('box-quick-c-prefix');
1649 - const nameBox = document.getElementById('box-quick-c-name');
1650 -
1651 - if (entity === 'legal') {
1652 - if (prefixBox) prefixBox.style.display = 'none';
1653 - if (nameBox) nameBox.style.gridColumn = 'span 3';
1654 - } else {
1655 - if (prefixBox) prefixBox.style.display = 'block';
1656 - if (nameBox) nameBox.style.gridColumn = 'span 2';
1657 - }
1394 + applyEntityTypeToForm(entitySelect.value, {
1395 + prefixId: 'box-quick-c-prefix', nameId: 'box-quick-c-name',
1396 + econId: 'box-quick-c-economic', regId: 'box-quick-c-reg',
1397 + nationalLabelId: 'label-quick-c-national'
1398 + });
1399 }
1400
1401 + /* ---------- رفتار فرم فاکتور: قالب سند ---------- */
1402 function handleInvoiceKindChange() {
1661 - // توجه: قبلاً مالیات فقط برای فاکتور «رسمی» مجاز بود. طبق نمونه واقعی مرجع
1662 - // (پیش‌فاکتور غیررسمی که مالیات ۱۰٪ در آن محاسبه شده بود) این محدودیت با
1663 - // رفتار واقعی مرجع در تناقض بود، پس حذف شد: مالیات برای هر نوع سند قابل فعال‌سازی است.
1403 + const kind = document.getElementById('invoice-kind').value;
1404 + const vatModeRow = document.getElementById('box-invoice-vat-mode-row');
1405 + const vatModeSelect = document.getElementById('invoice-vat-mode');
1406 +
1407 + // فاکتور غیررسمی: مالیات ارزش افزوده به هیچ عنوان قابل فعال‌سازی نیست.
1408 + if (kind === 'non_formal') {
1409 + if (vatModeRow) vatModeRow.style.display = 'none';
1410 + if (vatModeSelect) vatModeSelect.value = 'none';
1411 + } else {
1412 + if (vatModeRow) vatModeRow.style.display = 'flex';
1413 + }
1414 handleVatModeChange();
1415 recomputeTotals();
1416 }
1417
1418 function handleVatModeChange() {
1419 const mode = document.getElementById('invoice-vat-mode').value;
1420 + const kind = document.getElementById('invoice-kind').value;
1421 const rateBox = document.getElementById('box-invoice-vat-rate');
1671 - rateBox.style.display = (mode === 'with_vat') ? 'flex' : 'none';
1422 + if (kind === 'non_formal') {
1423 + rateBox.style.display = 'none';
1424 + document.getElementById('invoice-vat-mode').value = 'none';
1425 + } else {
1426 + rateBox.style.display = (mode === 'with_vat') ? 'flex' : 'none';
1427 + }
1428 recomputeTotals();
1429 }
1430
@@ -1682,8 +1438,8 @@
1438 function handleDiscountTypeChange() {
1439 const type = document.getElementById('invoice-discount-type').value;
1440 const label = document.getElementById('label-invoice-discount-value');
1685 - const input = document.getElementById('invoice-discount-fixed');
1686 - label.innerText = (type === 'percent') ? 'درصد تخفیف (٪)' : 'مبلغ تخفیف (ریال)';
1441 + const cur = getCurrencyLabel();
1442 + label.innerText = (type === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${cur})`;
1443 input.value = 0;
1444 recomputeTotals();
1445 }
@@ -1693,10 +1449,27 @@
1449 const defKind = document.getElementById('def-invoice-kind');
1450 const defVat = document.getElementById('def-vat-mode');
1451 const defRate = document.getElementById('def-vat-rate');
1452 + const defCurMode = document.getElementById('def-currency-mode');
1453 + const defCurCustom = document.getElementById('def-currency-custom');
1454 if (defKind) defKind.value = def.invoice_kind || 'non_formal';
1455 if (defVat) defVat.value = def.vat_mode || 'none';
1456 if (defRate) defRate.value = def.vat_rate || 10;
1699 - handleInvoiceKindChange();
1457 + if (defCurMode) defCurMode.value = def.currency_mode || 'rial';
1458 + if (defCurCustom) defCurCustom.value = def.currency_custom || '';
1459 + handleCurrencyModeChange();
1460 +
1461 + // اعمال پیش‌فرض‌ها روی فرم فاکتور جدید (اگر در حالت ویرایش نیستیم)
1462 + const editId = document.getElementById('edit-invoice-id')?.value;
1463 + if (!editId) {
1464 + const kindEl = document.getElementById('invoice-kind');
1465 + if (kindEl) kindEl.value = def.invoice_kind || 'non_formal';
1466 + handleInvoiceKindChange();
1467 + if ((def.invoice_kind || 'non_formal') !== 'non_formal') {
1468 + document.getElementById('invoice-vat-mode').value = def.vat_mode || 'none';
1469 + document.getElementById('invoice-vat-rate-input').value = def.vat_rate || 10;
1470 + handleVatModeChange();
1471 + }
1472 + }
1473 }
1474
1475 function commitSaveDefaultSettings() {
@@ -1704,24 +1477,23 @@
1477 s.invoice_kind = document.getElementById('def-invoice-kind').value;
1478 s.vat_mode = document.getElementById('def-vat-mode').value;
1479 s.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1480 + s.currency_mode = document.getElementById('def-currency-mode').value;
1481 + s.currency_custom = document.getElementById('def-currency-custom').value || '';
1482 saveDatastore();
1483 + refreshCurrencyLabels();
1484 alert('پیش‌فرض‌ها ذخیره شد.');
1485 }
1486
1711 - /* =========================================================================
1712 - داشبورد تحلیلی با فیلتر دقیق کاربر فعلی (currentUser.id)
1713 - ========================================================================= */
1487 + /* ---------- داشبورد ---------- */
1488 function renderDashboard() {
1715 - let salesSum = 0;
1716 - let debtorsSum = 0;
1489 + let salesSum = 0; let debtorsSum = 0;
1490 const myInvoices = getMyInvoices();
1491 const myCheques = getMyCheques();
1719 -
1492 const myCompanies = getMyCompanies();
1493 const mySettings = getMySettings();
1494 const activeCompId = mySettings.default_company_id || document.getElementById('invoice-company-id')?.value || (myCompanies[0]?.id);
1723 -
1495 const filteredInvoices = activeCompId ? myInvoices.filter(inv => inv.companyId === activeCompId) : myInvoices;
1496 + const cur = getCurrencyLabel();
1497
1498 filteredInvoices.forEach(inv => {
1499 salesSum += inv.grandTotal;
@@ -1732,10 +1504,9 @@
1504 const settledEl = document.getElementById('kpi-settled-sum');
1505 const debtorsEl = document.getElementById('kpi-debtors-sum');
1506 const chequesEl = document.getElementById('kpi-cheques-count');
1735 -
1736 - if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ریال';
1737 - if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ریال';
1738 - if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ریال';
1507 + if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ' + cur;
1508 + if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ' + cur;
1509 + if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ' + cur;
1510 if (chequesEl) chequesEl.innerText = myCheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1511
1512 const recentTbody = document.getElementById('dashboard-recent-table');
@@ -1744,7 +1515,6 @@
1515 recentTbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری صادر نشده است.</td></tr>';
1516 return;
1517 }
1747 -
1518 recentTbody.innerHTML = filteredInvoices.slice(-5).reverse().map(inv => `
1519 <tr>
1520 <td><strong>#${inv.number}</strong></td>
@@ -1772,16 +1542,12 @@
1542 switchView('view-invoices');
1543 }
1544
1775 - /* =========================================================================
1776 - جدول اقلام فاکتور با چینش استاندارد و شماره‌گذاری خودکار در RTL
1777 - ========================================================================= */
1545 + /* ---------- اقلام فاکتور ---------- */
1546 function updateInvoiceItemRowNumbers() {
1547 const rows = document.querySelectorAll('#invoice-items-table-body tr');
1548 rows.forEach((tr, index) => {
1549 const numCell = tr.querySelector('.row-item-number');
1782 - if (numCell) {
1783 - numCell.innerText = (index + 1).toLocaleString('fa-IR');
1784 - }
1550 + if (numCell) numCell.innerText = (index + 1).toLocaleString('fa-IR');
1551 });
1552 }
1553
@@ -1790,12 +1556,10 @@
1556 const rowKey = 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 4);
1557 const tr = document.createElement('tr');
1558 tr.id = rowKey;
1793 -
1559 const myProducts = getMyProducts();
1795 - const productOptions = myProducts.map(p =>
1560 + const productOptions = myProducts.map(p =>
1561 `<option value="${p.id}" data-price="${p.sale_price}" data-unit="${p.unit || 'عدد'}" ${p.id === selectedProdId ? 'selected' : ''}>${p.name} ${p.spec ? '(' + p.spec + ')' : ''}</option>`
1562 ).join('');
1798 -
1563 tr.innerHTML = `
1564 <td class="row-item-number" style="width:40px; text-align:center; font-weight:bold; vertical-align:middle;"></td>
1565 <td>
@@ -1811,14 +1575,9 @@
1575 <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>
1576 `;
1577 tbody.appendChild(tr);
1814 -
1578 updateInvoiceItemRowNumbers();
1816 -
1817 - if (selectedProdId && initialPrice === null) {
1818 - onRowProductChange(rowKey);
1819 - } else {
1820 - recomputeTotals();
1821 - }
1579 + if (selectedProdId && initialPrice === null) onRowProductChange(rowKey);
1580 + else recomputeTotals();
1581 }
1582
1583 function onRowProductChange(rowKey) {
@@ -1850,9 +1609,10 @@
1609 const discountType = document.getElementById('invoice-discount-type')?.value || 'fixed';
1610 const discountInput = parseFloat(document.getElementById('invoice-discount-fixed')?.value) || 0;
1611 const rawDiscount = (discountType === 'percent') ? Math.round(subtotal * (discountInput / 100)) : discountInput;
1853 - const fixedDiscount = Math.max(0, Math.min(rawDiscount, subtotal)); // تخفیف هرگز نباید از جمع کل بیشتر شود
1612 + const fixedDiscount = Math.max(0, Math.min(rawDiscount, subtotal));
1613
1855 - const vatMode = document.getElementById('invoice-vat-mode')?.value || 'none';
1614 + const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1615 + const vatMode = (kind === 'non_formal') ? 'none' : (document.getElementById('invoice-vat-mode')?.value || 'none');
1616 const vatType = document.getElementById('invoice-vat-type')?.value || 'percent';
1617 const vatRate = parseFloat(document.getElementById('invoice-vat-rate-input')?.value) || 0;
1618
@@ -1863,15 +1623,15 @@
1623 }
1624 const grandTotal = afterDiscount + vatAmount;
1625
1626 + const cur = getCurrencyLabel();
1627 const subtotalEl = document.getElementById('summary-subtotal');
1628 const vatEl = document.getElementById('summary-vat');
1629 const grandEl = document.getElementById('summary-grandtotal');
1630 const wordsEl = document.getElementById('summary-words');
1870 -
1871 - if (subtotalEl) subtotalEl.innerText = subtotal.toLocaleString('fa-IR') + ' ریال';
1872 - if (vatEl) vatEl.innerText = vatAmount.toLocaleString('fa-IR') + ' ریال';
1873 - if (grandEl) grandEl.innerText = grandTotal.toLocaleString('fa-IR') + ' ریال';
1874 - if (wordsEl) wordsEl.innerText = 'به حروف: ' + numberToPersianWords(grandTotal);
1631 + if (subtotalEl) subtotalEl.innerText = subtotal.toLocaleString('fa-IR') + ' ' + cur;
1632 + if (vatEl) vatEl.innerText = vatAmount.toLocaleString('fa-IR') + ' ' + cur;
1633 + if (grandEl) grandEl.innerText = grandTotal.toLocaleString('fa-IR') + ' ' + cur;
1634 + if (wordsEl) wordsEl.innerText = 'به حروف: ' + numberToPersianWords(grandTotal, cur);
1635
1636 return { subtotal, fixedDiscount, discountType, discountInput, vatAmount, vatType, grandTotal, vatRate };
1637 }
@@ -1880,19 +1640,12 @@
1640 if (!currentUser) return;
1641 const myCompanies = getMyCompanies();
1642 const mySettings = getMySettings();
1883 -
1643 const companySelect = document.getElementById('invoice-company-id');
1644 const selectedCompanyId = companySelect ? companySelect.value : mySettings.default_company_id;
1886 -
1887 - const sellerCompany = myCompanies.find(c => c.id === selectedCompanyId) ||
1888 - myCompanies.find(c => c.id === mySettings.default_company_id) ||
1645 + const sellerCompany = myCompanies.find(c => c.id === selectedCompanyId) ||
1646 + myCompanies.find(c => c.id === mySettings.default_company_id) ||
1647 myCompanies[0];
1890 -
1891 - if (!sellerCompany) {
1892 - alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');
1893 - return;
1894 - }
1895 -
1648 + if (!sellerCompany) { alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.'); return; }
1649 const companyId = sellerCompany.id;
1650 const companyName = sellerCompany.name;
1651
@@ -1905,6 +1658,10 @@
1658 const description = document.getElementById('invoice-desc-input')?.value.trim() || '';
1659 const editId = document.getElementById('edit-invoice-id')?.value;
1660
1661 + if (kind === 'non_formal') {
1662 + document.getElementById('invoice-vat-mode').value = 'none';
1663 + }
1664 +
1665 const items = [];
1666 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1667 const sel = tr.querySelector('.row-product-select');
@@ -1913,71 +1670,51 @@
1670 const unit = tr.querySelector('.row-unit-input')?.value || 'عدد';
1671 const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1672 const price = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1916 -
1673 if (prodId && qty > 0) {
1674 items.push({ prodId, prodName, unit, qty, price, lineTotal: qty * price });
1675 }
1676 });
1677
1922 - if (items.length === 0) {
1923 - alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');
1924 - return;
1925 - }
1678 + if (items.length === 0) { alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.'); return; }
1679
1680 const totals = recomputeTotals();
1681 const kindLabels = { formal: 'رسمی', non_formal: 'غیررسمی', pre_invoice: 'پیش‌فاکتور' };
1682 + const cur = getCurrencyLabel();
1683
1684 if (editId) {
1685 const existingIndex = datastore.invoices.findIndex(i => i.id === editId && i.ownerUserId === currentUser.id);
1686 if (existingIndex !== -1) {
1687 datastore.invoices[existingIndex] = {
1688 ...datastore.invoices[existingIndex],
1935 - ownerUserId: currentUser.id,
1936 - number, date, companyId, companyName, kind,
1937 - kindLabel: kindLabels[kind],
1938 - contactId, contactName,
1939 - paymentMethod: 'cash',
1940 - paymentMethodLabel: 'نقدی',
1941 - subtotal: totals.subtotal,
1942 - discount: totals.fixedDiscount,
1943 - discountType: totals.discountType,
1944 - discountInput: totals.discountInput,
1945 - vat: totals.vatAmount,
1946 - vatType: totals.vatType,
1947 - vatRate: totals.vatRate,
1948 - grandTotal: totals.grandTotal,
1949 - description,
1950 - items
1689 + ownerUserId: currentUser.id, number, date, companyId, companyName, kind,
1690 + kindLabel: kindLabels[kind], contactId, contactName,
1691 + paymentMethod: 'cash', paymentMethodLabel: 'نقدی',
1692 + subtotal: totals.subtotal, discount: totals.fixedDiscount,
1693 + discountType: totals.discountType, discountInput: totals.discountInput,
1694 + vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate,
1695 + grandTotal: totals.grandTotal, description, items,
1696 + currencyLabel: cur
1697 };
1698 alert('فاکتور با موفقیت ویرایش شد.');
1699 }
1700 cancelInvoiceEdit();
1701 } else {
1702 const record = {
1957 - id: 'INV_' + Date.now(),
1958 - ownerUserId: currentUser.id,
1703 + id: 'INV_' + Date.now(), ownerUserId: currentUser.id,
1704 number, date, companyId, companyName, kind,
1960 - kindLabel: kindLabels[kind],
1961 - contactId, contactName,
1962 - paymentMethod: 'cash',
1963 - paymentMethodLabel: 'نقدی',
1964 - subtotal: totals.subtotal,
1965 - discount: totals.fixedDiscount,
1966 - discountType: totals.discountType,
1967 - discountInput: totals.discountInput,
1968 - vat: totals.vatAmount,
1969 - vatType: totals.vatType,
1970 - vatRate: totals.vatRate,
1971 - grandTotal: totals.grandTotal,
1972 - description,
1973 - items
1705 + kindLabel: kindLabels[kind], contactId, contactName,
1706 + paymentMethod: 'cash', paymentMethodLabel: 'نقدی',
1707 + subtotal: totals.subtotal, discount: totals.fixedDiscount,
1708 + discountType: totals.discountType, discountInput: totals.discountInput,
1709 + vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate,
1710 + grandTotal: totals.grandTotal, description, items,
1711 + currencyLabel: cur
1712 };
1713 datastore.invoices.push(record);
1714 alert('فاکتور با موفقیت ثبت شد.');
1715 cancelInvoiceEdit();
1716 renderAndPrintDirect(record.id);
1717 }
1980 -
1718 saveDatastore();
1719 refreshAllSurfaces();
1720 }
@@ -1985,13 +1722,11 @@
1722 function editInvoice(invId) {
1723 const inv = getMyInvoices().find(i => i.id === invId);
1724 if (!inv) return;
1988 -
1725 switchView('view-invoices');
1726 document.getElementById('edit-invoice-id').value = inv.id;
1727 document.getElementById('invoice-form-title').innerText = `✏️ ویرایش فاکتور #${inv.number}`;
1728 document.getElementById('btn-cancel-edit').style.display = 'inline-flex';
1729 document.getElementById('btn-save-invoice').innerText = '💾 ذخیره تغییرات';
1994 -
1730 document.getElementById('invoice-company-id').value = inv.companyId;
1731 document.getElementById('invoice-kind').value = inv.kind;
1732 document.getElementById('invoice-vat-mode').value = inv.vat > 0 ? 'with_vat' : 'none';
@@ -2001,10 +1736,9 @@
1736 document.getElementById('invoice-contact-id').value = inv.contactId;
1737 document.getElementById('invoice-date-input').value = inv.date;
1738 document.getElementById('invoice-discount-type').value = inv.discountType || 'fixed';
2004 - document.getElementById('label-invoice-discount-value').innerText = (inv.discountType === 'percent') ? 'درصد تخفیف (٪)' : 'مبلغ تخفیف (ریال)';
1739 + document.getElementById('label-invoice-discount-value').innerText = (inv.discountType === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${getCurrencyLabel()})`;
1740 document.getElementById('invoice-discount-fixed').value = (inv.discountType === 'percent') ? (inv.discountInput || 0) : (inv.discount || 0);
1741 document.getElementById('invoice-desc-input').value = inv.description || '';
2007 -
1742 handleInvoiceKindChange();
1743
1744 const tbody = document.getElementById('invoice-items-table-body');
@@ -2012,9 +1746,7 @@
1746 inv.items.forEach(it => {
1747 addInvoiceItemRow(it.prodId, it.qty, it.price);
1748 const lastRow = tbody.lastElementChild;
2015 - if (lastRow) {
2016 - lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
2017 - }
1749 + if (lastRow) lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
1750 });
1751 updateInvoiceItemRowNumbers();
1752 recomputeTotals();
@@ -2028,7 +1760,7 @@
1760 document.getElementById('invoice-items-table-body').innerHTML = '';
1761 document.getElementById('invoice-number').value = '';
1762 document.getElementById('invoice-discount-type').value = 'fixed';
2031 - document.getElementById('label-invoice-discount-value').innerText = 'مبلغ تخفیف (ریال)';
1763 + document.getElementById('label-invoice-discount-value').innerText = `مبلغ تخفیف (${getCurrencyLabel()})`;
1764 document.getElementById('invoice-discount-fixed').value = 0;
1765 document.getElementById('invoice-vat-type').value = 'percent';
1766 document.getElementById('invoice-desc-input').value = '';
@@ -2040,17 +1772,12 @@
1772 const tbody = document.getElementById('invoice-archive-table-body');
1773 const filterSelect = document.getElementById('filter-invoice-company');
1774 const selectedFilter = filterSelect?.value || document.getElementById('invoice-company-id')?.value || 'ALL';
2043 -
1775 let list = getMyInvoices();
2045 - if (selectedFilter !== 'ALL') {
2046 - list = list.filter(i => i.companyId === selectedFilter);
2047 - }
2048 -
1776 + if (selectedFilter !== 'ALL') list = list.filter(i => i.companyId === selectedFilter);
1777 if (list.length === 0) {
1778 tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری ثبت نشده است.</td></tr>';
1779 return;
1780 }
2053 -
1781 tbody.innerHTML = list.map(inv => `
1782 <tr>
1783 <td><strong>#${inv.number}</strong></td>
@@ -2068,21 +1795,10 @@
1795 }
1796
1797 /* =========================================================================
2071 - سیستم چاپ فاکتور رسمی/غیررسمی
2072 - (تغییر مهم: سیستم قبلی بر اساس اندازه‌گیری ارتفاع واقعی در مرورگر تصمیم
2073 - می‌گرفت چند ردیف در هر صفحه جا شود — اما همین حدس زدنِ آستانه‌ی ارتفاع دو بار
2074 - غلط از آب درآمد: یک‌بار صفحه‌ی اضافه‌ی خالی ساخت، بار بعد زودتر از موعد
2075 - (ردیف ۷ به‌جای ۱۰) صفحه را شکست. طبق قرار صریح شما، این حدس‌زدن کنار گذاشته
2076 - شد: قانون الان قطعی و ثابت است — دقیقاً حداکثر ۱۰ ردیف در هر صفحه، نه یک
2077 - ردیف بیشتر، نه بر اساس اندازه‌گیری. فاکتور رسمی هم اکنون به‌صورت افقی
2078 - (landscape) چاپ می‌شود تا ستون «شرح کالا» جا باز کند و ردیف‌ها تک‌خطی بمانند.)
1798 + چاپ فاکتور — همه‌ی قالب‌ها Landscape، حداکثر ۱۰ ردیف در هر صفحه
1799 ========================================================================= */
1800 + const MAX_ROWS_PER_PAGE = 10;
1801
2081 - const MAX_ROWS_PER_PAGE = 10; // قانون ثابت و قطعی — قابل تغییر فقط با تغییر همین عدد
2082 -
2083 -
2084 - // محاسبه ردیف‌به‌ردیف تخفیف/مالیات با اصلاح باقیمانده روی آخرین ردیف،
2085 - // تا جمع ردیف‌ها همیشه دقیقاً با جمع کل فاکتور یکی باشد (نه فقط تقریبی).
1802 function computeInvoiceLines(inv) {
1803 const n = inv.items.length;
1804 const afterDiscountTotal = Math.max(0, (inv.subtotal || 0) - (inv.discount || 0));
@@ -2107,6 +1823,7 @@
1823 }
1824
1825 function buildFormalPage(items, seller, contact, inv, opt) {
1826 + const cur = inv.currencyLabel || 'ریال';
1827 const rowsHtml = items.map(li => `
1828 <tr style="text-align:center;">
1829 <td style="border:1px solid #1e293b; padding:3px 6px; font-size:10.5px;">${li.rowNo.toLocaleString('fa-IR')}</td>
@@ -2120,15 +1837,10 @@
1837 <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>
1838 </tr>
1839 `).join('');
2123 -
1840 const pageSubtotal = items.reduce((s, li) => s + li.lineSubtotal, 0);
1841 const cumulativeAfter = (opt.cumulativeBefore || 0) + pageSubtotal;
2126 -
2127 - // «شناسه ملی» و «شماره ثبت» دو مقدار جدا هستند و باید هر دو چاپ شوند —
2128 - // قبلاً با || فقط یکی نمایش داده می‌شد و دیگری از سند رسمی حذف می‌شد.
1842 const sellerIds = `${seller.national_id || '—'} / ${seller.reg_number || '—'}`;
1843 const contactIds = `${contact.national_id || '—'} / ${contact.reg_number || '—'}`;
2131 -
1844 return `
1845 <div class="invoice-a4-page landscape" style="background:#fff; padding:6mm 8mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1846 <table style="width:100%; border-collapse:collapse; border:2px solid #1e3a8a; margin-bottom:3px;">
@@ -2148,51 +1860,44 @@
1860 </td>
1861 </tr>
1862 </table>
2151 -
1863 <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px; margin-bottom:3px;">
2153 - <tr style="background:#f8fafc; font-weight:bold;">
2154 - <td colspan="4" style="border:1px solid #1e3a8a; padding:2px 6px; color:#1e3a8a;">الف) مشخصات فروشنده</td>
2155 - </tr>
1864 + <tr style="background:#f8fafc; font-weight:bold;"><td colspan="4" style="border:1px solid #1e3a8a; padding:2px 6px; color:#1e3a8a;">الف) مشخصات فروشنده</td></tr>
1865 <tr>
1866 <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">نام شخص حقیقی/حقوقی:</td>
1867 <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;"><strong>${seller.name || '—'}</strong></td>
1868 <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">شماره اقتصادی:</td>
2160 - <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;"><span>${seller.economic_code || '—'}</span></td>
1869 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;">${seller.economic_code || '—'}</td>
1870 </tr>
1871 <tr>
1872 <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">شناسه ملی / شماره ثبت:</td>
2164 - <td style="border:1px solid #cbd5e1; padding:3px 6px;"><span>${sellerIds}</span></td>
1873 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${sellerIds}</td>
1874 <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">کد پستی ۱۰ رقمی:</td>
2166 - <td style="border:1px solid #cbd5e1; padding:3px 6px;"><span>${seller.postal_code || '—'}</span></td>
1875 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${seller.postal_code || '—'}</td>
1876 </tr>
1877 <tr>
1878 <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">نشانی و تلفن:</td>
1879 <td colspan="3" style="border:1px solid #cbd5e1; padding:3px 6px;">${seller.address || '—'} ${seller.phone ? ' | تلفن: ' + seller.phone : ''}</td>
1880 </tr>
1881 </table>
2173 -
1882 <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px; margin-bottom:3px;">
2175 - <tr style="background:#f8fafc; font-weight:bold;">
2176 - <td colspan="4" style="border:1px solid #1e3a8a; padding:2px 6px; color:#1e3a8a;">ب) مشخصات خریدار</td>
2177 - </tr>
1883 + <tr style="background:#f8fafc; font-weight:bold;"><td colspan="4" style="border:1px solid #1e3a8a; padding:2px 6px; color:#1e3a8a;">ب) مشخصات خریدار</td></tr>
1884 <tr>
1885 <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">نام شخص حقیقی/حقوقی:</td>
1886 <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;"><strong>${contact.name || inv.contactName}</strong></td>
1887 <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">شماره اقتصادی:</td>
2182 - <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;"><span>${contact.economic_code || '—'}</span></td>
1888 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;">${contact.economic_code || '—'}</td>
1889 </tr>
1890 <tr>
1891 <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">شناسه ملی / شماره ثبت:</td>
2186 - <td style="border:1px solid #cbd5e1; padding:3px 6px;"><span>${contactIds}</span></td>
1892 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${contactIds}</td>
1893 <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">کد پستی ۱۰ رقمی:</td>
2188 - <td style="border:1px solid #cbd5e1; padding:3px 6px;"><span>${contact.postal_code || '—'}</span></td>
1894 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${contact.postal_code || '—'}</td>
1895 </tr>
1896 <tr>
1897 <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">نشانی و تلفن:</td>
1898 <td colspan="3" style="border:1px solid #cbd5e1; padding:3px 6px;">${contact.address || '—'} ${contact.mobile ? ' | همراه: ' + contact.mobile : ''}</td>
1899 </tr>
1900 </table>
2195 -
1901 <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px;">
1902 <thead>
1903 <tr style="background:#1e3a8a; color:#fff; font-weight:bold; text-align:center;">
@@ -2200,46 +1905,35 @@
1905 <th style="border:1px solid #1e3a8a; padding:4px 6px; text-align:right;">شرح کالا یا خدمات</th>
1906 <th style="border:1px solid #1e3a8a; padding:4px; width:42px;">تعداد</th>
1907 <th style="border:1px solid #1e3a8a; padding:4px; width:42px;">واحد</th>
2203 - <th style="border:1px solid #1e3a8a; padding:4px; width:105px;">مبلغ واحد (ریال)</th>
2204 - <th style="border:1px solid #1e3a8a; padding:4px; width:110px;">مبلغ کل (ریال)</th>
2205 - <th style="border:1px solid #1e3a8a; padding:4px; width:80px;">تخفیف (ریال)</th>
2206 - <th style="border:1px solid #1e3a8a; padding:4px; width:90px;">مالیات (ریال)</th>
2207 - <th style="border:1px solid #1e3a8a; padding:4px; width:120px;">مبلغ نهایی (ریال)</th>
1908 + <th style="border:1px solid #1e3a8a; padding:4px; width:105px;">مبلغ واحد (${cur})</th>
1909 + <th style="border:1px solid #1e3a8a; padding:4px; width:110px;">مبلغ کل (${cur})</th>
1910 + <th style="border:1px solid #1e3a8a; padding:4px; width:80px;">تخفیف (${cur})</th>
1911 + <th style="border:1px solid #1e3a8a; padding:4px; width:90px;">مالیات (${cur})</th>
1912 + <th style="border:1px solid #1e3a8a; padding:4px; width:120px;">مبلغ نهایی (${cur})</th>
1913 </tr>
1914 </thead>
1915 <tbody>
2211 - ${!opt.isFirstPage ? `
2212 - <tr style="background:#fef3c7; font-weight:bold; font-size:9.5px;">
2213 - <td colspan="5" style="border:1px solid #1e293b; padding:3px; text-align:left;">نقل از صفحه قبل:</td>
2214 - <td colspan="4" style="border:1px solid #1e293b; padding:3px; text-align:left;">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ریال</td>
2215 - </tr>
2216 - ` : ''}
1916 + ${!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>` : ''}
1917 ${rowsHtml}
2218 - ${!opt.isLastPage ? `
2219 - <tr style="background:#f1f5f9; font-weight:bold; font-size:9.5px;">
2220 - <td colspan="5" style="border:1px solid #1e293b; padding:3px; text-align:left;">جمع این صفحه و نقل به صفحه بعد:</td>
2221 - <td colspan="4" style="border:1px solid #1e293b; padding:3px; text-align:left;">${cumulativeAfter.toLocaleString('fa-IR')} ریال</td>
2222 - </tr>
2223 - ` : ''}
1918 + ${!opt.isLastPage ? `<tr style="background:#f1f5f9; 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;">${cumulativeAfter.toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1919 </tbody>
1920 </table>
2226 -
1921 ${opt.isLastPage ? `
1922 <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10.5px; margin-top:3px;">
1923 <tr>
1924 <td style="width:60%; border:1px solid #1e3a8a; padding:6px; vertical-align:top; background:#f8fafc;">
2231 - <div style="margin-bottom:4px;"><strong>مبلغ کل به حروف:</strong> ${numberToPersianWords(inv.grandTotal)}</div>
1925 + <div style="margin-bottom:4px;"><strong>مبلغ کل به حروف:</strong> ${numberToPersianWords(inv.grandTotal, cur)}</div>
1926 <div style="margin-bottom:4px;"><strong>شرایط و نحوه پرداخت:</strong> نقدی ☑ &nbsp;&nbsp;&nbsp; غیرنقدی (نسیه/چک) ☐</div>
1927 <div style="font-size:9.5px; color:#475569; line-height:1.5;"><strong>توضیحات:</strong> ${inv.description || seller.footer || 'تحویل کالا منوط به تسویه نهایی می‌باشد.'}</div>
1928 </td>
1929 <td style="width:40%; border:1px solid #1e3a8a; padding:0;">
1930 <table style="width:100%; border-collapse:collapse; font-size:10.5px;">
2237 - <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">جمع کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ریال</td></tr>
2238 - <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">مجموع تخفیف:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ریال</td></tr>
2239 - <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">مالیات و عوارض ارزش افزوده:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.vat.toLocaleString('fa-IR')} ریال</td></tr>
1931 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">جمع کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ${cur}</td></tr>
1932 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">مجموع تخفیف:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ${cur}</td></tr>
1933 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">مالیات و عوارض ارزش افزوده:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.vat.toLocaleString('fa-IR')} ${cur}</td></tr>
1934 <tr style="background:#eff6ff; font-weight:bold; font-size:11.5px; color:#1e3a8a;">
1935 <td style="padding:5px 8px;">مبلغ قابل پرداخت:</td>
2242 - <td style="padding:5px 8px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ریال</td>
1936 + <td style="padding:5px 8px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ${cur}</td>
1937 </tr>
1938 </table>
1939 </td>
@@ -2247,22 +1941,19 @@
1941 </table>
1942 <table style="width:100%; border-collapse:collapse; border:1px solid #1e3a8a; margin-top:6px; text-align:center; font-size:10.5px;">
1943 <tr>
2250 - <td style="width:50%; height:50px; vertical-align:top; border:1px solid #1e3a8a; padding:5px; background:#fff;">
2251 - <div style="font-weight:bold;">مهر و امضای فروشنده</div>
2252 - </td>
2253 - <td style="width:50%; height:50px; vertical-align:top; border:1px solid #1e3a8a; padding:5px; background:#fff;">
2254 - <div style="font-weight:bold;">مهر و امضای خریدار</div>
2255 - </td>
1944 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #1e3a8a; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای فروشنده</div></td>
1945 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #1e3a8a; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای خریدار</div></td>
1946 </tr>
1947 </table>
2258 - ` : `
2259 - <div style="margin-top:8px; text-align:center; font-size:10.5px; color:#64748b; font-weight:bold;">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>
2260 - `}
2261 - </div>
2262 - `;
1948 + ` : `<div style="margin-top:8px; text-align:center; font-size:10.5px; color:#64748b; font-weight:bold;">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>`}
1949 + </div>`;
1950 }
1951
1952 function buildNonFormalPage(items, seller, contact, inv, opt) {
1953 + const cur = inv.currencyLabel || 'ریال';
1954 + const isPre = inv.kind === 'pre_invoice';
1955 + const title = isPre ? 'پیش‌فاکتور فروش کالا و خدمات' : 'فاکتور فروش کالا و خدمات';
1956 +
1957 const rowsHtml = items.map(li => `
1958 <tr style="text-align:center;">
1959 <td style="border:1px solid #334155; padding:4px 6px; font-size:10.5px;">${li.rowNo.toLocaleString('fa-IR')}</td>
@@ -2277,8 +1968,12 @@
1968 const pageSubtotal = items.reduce((s, li) => s + li.lineSubtotal, 0);
1969 const cumulativeAfter = (opt.cumulativeBefore || 0) + pageSubtotal;
1970
1971 + // پیش‌فاکتور: مالیات در صورت فعال بودن نمایش داده می‌شود.
1972 + // فاکتور غیررسمی: inv.vat همیشه صفر است، پس ردیف مالیات نمایش داده نمی‌شود.
1973 + const showVatRow = isPre && inv.vat > 0;
1974 +
1975 return `
2281 - <div class="invoice-a4-page" style="background:#fff; padding:7mm 6mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1976 + <div class="invoice-a4-page landscape" style="background:#fff; padding:7mm 8mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1977 <table style="width:100%; border-collapse:collapse; border:2px solid #334155; margin-bottom:5px;">
1978 <tr>
1979 <td style="width:30%; border:1px solid #334155; padding:6px; vertical-align:middle;">
@@ -2286,16 +1981,15 @@
1981 <div style="font-size:10px; color:#475569; margin-top:1px;">تلفن: ${seller.phone || '—'}</div>
1982 </td>
1983 <td style="width:40%; border:1px solid #334155; padding:6px; text-align:center; vertical-align:middle; background:#f8fafc;">
2289 - <h1 style="font-size:15px; margin:0; font-weight:bold; color:#0f172a;">${inv.kind === 'pre_invoice' ? 'پیش‌فاکتور فروش کالا و خدمات' : 'فاکتور فروش کالا و خدمات'}</h1>
1984 + <h1 style="font-size:15px; margin:0; font-weight:bold; color:#0f172a;">${title}</h1>
1985 </td>
1986 <td style="width:30%; border:1px solid #334155; padding:6px; font-size:10.5px; vertical-align:middle; text-align:left;">
2292 - <div>شماره فاکتور: <strong style="font-size:11.5px;">#${inv.number}</strong></div>
1987 + <div>شماره: <strong style="font-size:11.5px;">#${inv.number}</strong></div>
1988 <div style="margin-top:1px;">تاریخ: <strong>${inv.date}</strong></div>
1989 <div style="margin-top:1px; color:#64748b; font-size:9.5px;">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1990 </td>
1991 </tr>
1992 </table>
2298 -
1993 <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px; margin-bottom:5px;">
1994 <tr>
1995 <td style="width:50%; border:1px solid #334155; padding:5px; vertical-align:top; background:#f8fafc;">
@@ -2312,7 +2006,6 @@
2006 </td>
2007 </tr>
2008 </table>
2315 -
2009 <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px;">
2010 <thead>
2011 <tr style="background:#334155; color:#fff; font-weight:bold; text-align:center;">
@@ -2320,42 +2013,31 @@
2013 <th style="border:1px solid #334155; padding:5px 8px; text-align:right;">شرح کالا | خدمات</th>
2014 <th style="border:1px solid #334155; padding:5px 4px; width:60px;">واحد</th>
2015 <th style="border:1px solid #334155; padding:5px 4px; width:60px;">مقدار</th>
2323 - <th style="border:1px solid #334155; padding:5px 4px; width:135px; text-align:left;">قیمت واحد (ریال)</th>
2324 - <th style="border:1px solid #334155; padding:5px 4px; width:150px; text-align:left;">قیمت کل (ریال)</th>
2016 + <th style="border:1px solid #334155; padding:5px 4px; width:150px; text-align:left;">قیمت واحد (${cur})</th>
2017 + <th style="border:1px solid #334155; padding:5px 4px; width:170px; text-align:left;">قیمت کل (${cur})</th>
2018 </tr>
2019 </thead>
2020 <tbody>
2328 - ${!opt.isFirstPage ? `
2329 - <tr style="background:#fef3c7; font-weight:bold; font-size:9.5px;">
2330 - <td colspan="5" style="border:1px solid #334155; padding:3px; text-align:left;">نقل از صفحه قبل:</td>
2331 - <td style="border:1px solid #334155; padding:3px; text-align:left;">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ریال</td>
2332 - </tr>
2333 - ` : ''}
2021 + ${!opt.isFirstPage ? `<tr style="background:#fef3c7; font-weight:bold; font-size:9.5px;"><td colspan="5" style="border:1px solid #334155; padding:3px; text-align:left;">نقل از صفحه قبل:</td><td style="border:1px solid #334155; padding:3px; text-align:left;">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
2022 ${rowsHtml}
2335 - ${!opt.isLastPage ? `
2336 - <tr style="background:#f1f5f9; font-weight:bold; font-size:9.5px;">
2337 - <td colspan="5" style="border:1px solid #334155; padding:3px; text-align:left;">جمع این صفحه و نقل به صفحه بعد:</td>
2338 - <td style="border:1px solid #334155; padding:3px; text-align:left;">${cumulativeAfter.toLocaleString('fa-IR')} ریال</td>
2339 - </tr>
2340 - ` : ''}
2023 + ${!opt.isLastPage ? `<tr style="background:#f1f5f9; font-weight:bold; font-size:9.5px;"><td colspan="5" style="border:1px solid #334155; padding:3px; text-align:left;">جمع این صفحه و نقل به صفحه بعد:</td><td style="border:1px solid #334155; padding:3px; text-align:left;">${cumulativeAfter.toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
2024 </tbody>
2025 </table>
2343 -
2026 ${opt.isLastPage ? `
2027 <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px; margin-top:5px;">
2028 <tr>
2029 <td style="width:60%; border:1px solid #334155; padding:6px; vertical-align:top; background:#f8fafc;">
2348 - <div style="margin-bottom:4px;"><strong>مبلغ به حروف:</strong> ${numberToPersianWords(inv.grandTotal)}</div>
2349 - <div style="font-size:9.5px; color:#475569; line-height:1.5;"><strong>توضیحات:</strong> ${inv.description || seller.footer || 'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.'}</div>
2030 + <div style="margin-bottom:4px;"><strong>مبلغ به حروف:</strong> ${numberToPersianWords(inv.grandTotal, cur)}</div>
2031 + <div style="font-size:9.5px; color:#475569; line-height:1.5;"><strong>توضیحات:</strong> ${inv.description || seller.footer || (isPre ? 'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.' : 'از خرید شما سپاسگزاریم.')}</div>
2032 </td>
2033 <td style="width:40%; border:1px solid #334155; padding:0;">
2034 <table style="width:100%; border-collapse:collapse; font-size:10.5px;">
2353 - <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">قیمت کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ریال</td></tr>
2354 - <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">تخفیف:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ریال</td></tr>
2355 - ${inv.vat > 0 ? `<tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">مالیات ارزش افزوده:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.vat.toLocaleString('fa-IR')} ریال</td></tr>` : ''}
2035 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">قیمت کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ${cur}</td></tr>
2036 + ${inv.discount > 0 ? `<tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">تخفیف:</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
2037 + ${showVatRow ? `<tr style="background:#fffbeb;"><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;"><strong>مالیات ارزش افزوده:</strong></td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;"><strong>${inv.vat.toLocaleString('fa-IR')} ${cur}</strong></td></tr>` : ''}
2038 <tr style="background:#f1f5f9; font-weight:bold; font-size:11.5px;">
2357 - <td style="padding:5px 8px;">مبلغ کل (ریال):</td>
2358 - <td style="padding:5px 8px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ریال</td>
2039 + <td style="padding:5px 8px;">مبلغ کل (${cur}):</td>
2040 + <td style="padding:5px 8px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ${cur}</td>
2041 </tr>
2042 </table>
2043 </td>
@@ -2363,25 +2045,17 @@
2045 </table>
2046 <table style="width:100%; border-collapse:collapse; border:1px solid #334155; margin-top:6px; text-align:center; font-size:10.5px;">
2047 <tr>
2366 - <td style="width:50%; height:50px; vertical-align:top; border:1px solid #334155; padding:5px; background:#fff;">
2367 - <div style="font-weight:bold;">مهر و امضای فروشنده</div>
2368 - </td>
2369 - <td style="width:50%; height:50px; vertical-align:top; border:1px solid #334155; padding:5px; background:#fff;">
2370 - <div style="font-weight:bold;">مهر و امضای خریدار</div>
2371 - </td>
2048 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #334155; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای فروشنده</div></td>
2049 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #334155; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای خریدار</div></td>
2050 </tr>
2051 </table>
2374 - ` : `
2375 - <div style="margin-top:8px; text-align:center; font-size:10.5px; color:#64748b; font-weight:bold;">(ادامه در صفحه بعد...)</div>
2376 - `}
2377 - </div>
2378 - `;
2052 + ` : `<div style="margin-top:8px; text-align:center; font-size:10.5px; color:#64748b; font-weight:bold;">(ادامه در صفحه بعد...)</div>`}
2053 + </div>`;
2054 }
2055
2056 function renderAndPrintDirect(invId) {
2057 const inv = getMyInvoices().find(i => i.id === invId);
2058 if (!inv) return;
2384 -
2059 const myCompanies = getMyCompanies();
2060 const myContacts = getMyContacts();
2061 const seller = myCompanies.find(c => c.id === inv.companyId) || myCompanies[0] || {};
@@ -2390,8 +2064,6 @@
2064 const builder = isFormal ? buildFormalPage : buildNonFormalPage;
2065
2066 const allLines = computeInvoiceLines(inv);
2393 -
2394 - // تقسیم قطعی: دقیقاً حداکثر ۱۰ ردیف در هر صفحه — بدون حدس، بدون اندازه‌گیری.
2067 const pageGroups = [];
2068 let cumulative = 0;
2069 for (let start = 0; start < allLines.length; start += MAX_ROWS_PER_PAGE) {
@@ -2401,28 +2073,23 @@
2073 pageGroups.push({ items: pageItems, isFirstPage, isLastPage, cumulativeBefore: cumulative });
2074 cumulative += pageItems.reduce((s, li) => s + li.lineSubtotal, 0);
2075 }
2404 -
2076 const totalPages = pageGroups.length;
2077 const containerHtml = pageGroups.map((g, idx) =>
2078 builder(g.items, seller, contact, inv, {
2408 - pageNum: idx + 1,
2409 - totalPages,
2410 - isFirstPage: g.isFirstPage,
2411 - isLastPage: g.isLastPage,
2079 + pageNum: idx + 1, totalPages,
2080 + isFirstPage: g.isFirstPage, isLastPage: g.isLastPage,
2081 cumulativeBefore: g.cumulativeBefore
2082 })
2083 ).join('');
2084
2416 - // جهت صفحه را پویا تزریق می‌کنیم: فاکتور رسمی افقی (landscape)، غیررسمی عمودی (portrait).
2417 - // این کار با به‌روزرسانی همان تگ <style> در هر بار چاپ انجام می‌شود، نه با
2418 - // یک @page ثابت که برای هر دو نوع فاکتور یکسان باشد.
2085 + // همه قالب‌ها Landscape چاپ می‌شوند.
2086 let orientationStyle = document.getElementById('dynamic-print-orientation');
2087 if (!orientationStyle) {
2088 orientationStyle = document.createElement('style');
2089 orientationStyle.id = 'dynamic-print-orientation';
2090 document.head.appendChild(orientationStyle);
2091 }
2425 - orientationStyle.innerHTML = `@media print { @page { size: A4 ${isFormal ? 'landscape' : 'portrait'}; margin: 8mm 10mm; } }`;
2092 + orientationStyle.innerHTML = `@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
2093
2094 const printContainer = document.getElementById('printable-invoice');
2095 printContainer.innerHTML = containerHtml;
@@ -2431,9 +2098,7 @@
2098 printContainer.style.display = 'none';
2099 }
2100
2434 - /* =========================================================================
2435 - مدیریت کالاها با تفکیک دقیق کاربر (ownerUserId)
2436 - ========================================================================= */
2101 + /* ---------- کالاها ---------- */
2102 function commitSaveProduct() {
2103 if (!currentUser) return;
2104 const myProducts = getMyProducts();
@@ -2443,12 +2108,9 @@
2108 const unit = document.getElementById('prod-unit-input').value || 'عدد';
2109 const buy_price = parseFloat(document.getElementById('prod-buy-input').value) || 0;
2110 const sale_price = parseFloat(document.getElementById('prod-sale-input').value) || 0;
2446 -
2111 if (!name) { alert('عنوان کالا الزامی است.'); return; }
2448 -
2112 datastore.products.push({
2450 - id: 'P_' + Date.now(),
2451 - ownerUserId: currentUser.id,
2113 + id: 'P_' + Date.now(), ownerUserId: currentUser.id,
2114 code, name, spec, type: 'good', unit, buy_price, sale_price, stock: 0
2115 });
2116 saveDatastore();
@@ -2473,8 +2135,7 @@
2135 <td>${p.unit}</td>
2136 <td>${p.sale_price.toLocaleString('fa-IR')}</td>
2137 <td><button class="btn btn-danger btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="deleteProduct('${p.id}')">حذف</button></td>
2476 - </tr>
2477 - `).join('');
2138 + </tr>`).join('');
2139 }
2140
2141 function deleteProduct(id) {
@@ -2488,6 +2149,7 @@
2149
2150 function openQuickProductModal() { document.getElementById('modal-quick-product').classList.add('active'); }
2151 function closeQuickProductModal() { document.getElementById('modal-quick-product').classList.remove('active'); }
2152 +
2153 function saveQuickProduct() {
2154 if (!currentUser) return;
2155 const myProducts = getMyProducts();
@@ -2496,13 +2158,10 @@
2158 const spec = document.getElementById('quick-p-spec').value || '';
2159 const unit = document.getElementById('quick-p-unit').value || 'عدد';
2160 const price = parseFloat(document.getElementById('quick-p-price').value) || 0;
2499 -
2161 if (!name) { alert('عنوان کالا الزامی است.'); return; }
2501 -
2162 const newId = 'P_' + Date.now();
2163 datastore.products.push({
2504 - id: newId,
2505 - ownerUserId: currentUser.id,
2164 + id: newId, ownerUserId: currentUser.id,
2165 code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good'
2166 });
2167 saveDatastore();
@@ -2538,8 +2197,7 @@
2197 const name = r["نام کالا"] || r["عنوان"];
2198 if (name) {
2199 datastore.products.push({
2541 - id: 'P_' + Date.now() + '_' + idx,
2542 - ownerUserId: currentUser.id,
2200 + id: 'P_' + Date.now() + '_' + idx, ownerUserId: currentUser.id,
2201 code: (r["کد کالا"] || (myProducts.length + idx + 1)).toString(),
2202 name: name.toString(),
2203 spec: (r["مشخصه و نوع"] || '').toString(),
@@ -2558,9 +2216,7 @@
2216 reader.readAsArrayBuffer(file);
2217 }
2218
2561 - /* =========================================================================
2562 - مدیریت اشخاص و طرف‌حساب‌ها با تفکیک دقیق کاربر (ownerUserId)
2563 - ========================================================================= */
2219 + /* ---------- اشخاص ---------- */
2220 function commitSaveContact() {
2221 if (!currentUser) return;
2222 const entity_type = document.getElementById('contact-entity-type').value;
@@ -2569,18 +2225,16 @@
2225 const role = document.getElementById('contact-role-input').value;
2226 const mobile = document.getElementById('contact-mobile-input').value;
2227 const national_id = document.getElementById('contact-national-input').value;
2572 - const economic_code = document.getElementById('contact-economic-input').value;
2573 - const reg_number = document.getElementById('contact-reg-input').value;
2228 + const economic_code = (entity_type === 'natural') ? '' : document.getElementById('contact-economic-input').value;
2229 + const reg_number = (entity_type === 'natural') ? '' : document.getElementById('contact-reg-input').value;
2230 const postal_code = document.getElementById('contact-postal-input').value;
2231 const address = document.getElementById('contact-address-input').value;
2576 -
2232 if (!raw_name.trim()) { alert('نام طرف حساب الزامی است.'); return; }
2578 -
2233 const formatted_name = formatEntityName(raw_name, entity_type, custom_prefix);
2234 datastore.contacts.push({
2581 - id: 'C_' + Date.now(),
2582 - ownerUserId: currentUser.id,
2583 - entity_type, name: formatted_name, role, mobile, national_id, economic_code, reg_number, postal_code, address, balance: 0
2235 + id: 'C_' + Date.now(), ownerUserId: currentUser.id,
2236 + entity_type, name: formatted_name, role, mobile, national_id, economic_code,
2237 + reg_number, postal_code, address, balance: 0
2238 });
2239 saveDatastore();
2240 alert('طرف حساب ثبت شد.');
@@ -2593,7 +2247,6 @@
2247 const invSelect = document.getElementById('invoice-contact-id');
2248 const chqSelect = document.getElementById('chq-contact-select');
2249 const myContacts = getMyContacts();
2596 -
2250 if (myContacts.length === 0) {
2251 tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ طرف حسابی ثبت نشده است.</td></tr>';
2252 } else {
@@ -2607,10 +2260,8 @@
2260 <td>${c.mobile || '—'}</td>
2261 <td>${Math.abs(c.balance || 0).toLocaleString('fa-IR')}</td>
2262 <td><button class="btn btn-danger btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="deleteContact('${c.id}')">حذف</button></td>
2610 - </tr>
2611 - `).join('');
2263 + </tr>`).join('');
2264 }
2613 -
2265 const options = myContacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
2266 if (invSelect) invSelect.innerHTML = options;
2267 if (chqSelect) chqSelect.innerHTML = options;
@@ -2625,27 +2276,27 @@
2276 }
2277 }
2278
2628 - function openQuickContactModal() { document.getElementById('modal-quick-contact').classList.add('active'); handleQuickCEntityChange(); }
2279 + function openQuickContactModal() {
2280 + document.getElementById('modal-quick-contact').classList.add('active');
2281 + handleQuickCEntityChange();
2282 + }
2283 function closeQuickContactModal() { document.getElementById('modal-quick-contact').classList.remove('active'); }
2630 -
2284 +
2285 function saveQuickContact() {
2286 if (!currentUser) return;
2287 const entity_type = document.getElementById('quick-c-entity').value;
2288 const prefix = entity_type === 'natural' ? document.getElementById('quick-c-prefix')?.value : '';
2289 const raw_name = document.getElementById('quick-c-name').value;
2290 if (!raw_name.trim()) { alert('نام الزامی است.'); return; }
2637 -
2291 const newId = 'C_' + Date.now();
2292 datastore.contacts.push({
2640 - id: newId,
2641 - ownerUserId: currentUser.id,
2642 - entity_type,
2293 + id: newId, ownerUserId: currentUser.id, entity_type,
2294 name: formatEntityName(raw_name, entity_type, prefix),
2295 role: 'customer',
2296 mobile: document.getElementById('quick-c-mobile').value,
2297 national_id: document.getElementById('quick-c-national').value,
2647 - economic_code: document.getElementById('quick-c-economic').value,
2648 - reg_number: document.getElementById('quick-c-reg').value,
2298 + economic_code: (entity_type === 'natural') ? '' : document.getElementById('quick-c-economic').value,
2299 + reg_number: (entity_type === 'natural') ? '' : document.getElementById('quick-c-reg').value,
2300 postal_code: document.getElementById('quick-c-postal').value,
2301 address: document.getElementById('quick-c-address').value,
2302 balance: 0
@@ -2682,15 +2333,13 @@
2333 if (raw_name) {
2334 const entity_type = (r["نوع (حقیقی/حقوقی)"] || '').includes('حقوقی') ? 'legal' : 'natural';
2335 datastore.contacts.push({
2685 - id: 'C_' + Date.now() + '_' + idx,
2686 - ownerUserId: currentUser.id,
2687 - entity_type,
2336 + id: 'C_' + Date.now() + '_' + idx, ownerUserId: currentUser.id, entity_type,
2337 name: formatEntityName(raw_name.toString(), entity_type, 'آقا/خانم'),
2338 role: 'customer',
2339 mobile: (r["شماره همراه"] || '').toString(),
2340 national_id: (r["شناسه یا کد ملی"] || '').toString(),
2692 - economic_code: (r["کد اقتصادی"] || '').toString(),
2693 - reg_number: (r["شماره ثبت"] || '').toString(),
2341 + economic_code: (entity_type === 'legal' ? (r["کد اقتصادی"] || '') : '').toString(),
2342 + reg_number: (entity_type === 'legal' ? (r["شماره ثبت"] || '') : '').toString(),
2343 postal_code: (r["کد پستی"] || '').toString(),
2344 address: (r["نشانی"] || '').toString(),
2345 balance: 0
@@ -2705,9 +2354,7 @@
2354 reader.readAsArrayBuffer(file);
2355 }
2356
2708 - /* =========================================================================
2709 - مدیریت چک‌ها و هزینه‌ها با تفکیک دقیق کاربر (ownerUserId)
2710 - ========================================================================= */
2357 + /* ---------- چک و هزینه ---------- */
2358 function commitSaveCheque() {
2359 if (!currentUser) return;
2360 const direction = document.getElementById('chq-direction-input').value;
@@ -2718,8 +2365,7 @@
2365 const amount = parseFloat(document.getElementById('chq-amount-input').value) || 0;
2366 if (!sayad_id || amount <= 0) { alert('اطلاعات چک نامعتبر است.'); return; }
2367 datastore.cheques.push({
2721 - id: 'CHQ_' + Date.now(),
2722 - ownerUserId: currentUser.id,
2368 + id: 'CHQ_' + Date.now(), ownerUserId: currentUser.id,
2369 direction, contactName, sayad_id, bank, amount,
2370 due_date: document.getElementById('chq-due-input').value,
2371 status: document.getElementById('chq-status-input').value
@@ -2739,12 +2385,10 @@
2385 const amount = parseFloat(document.getElementById('trx-amount-input').value) || 0;
2386 if (amount <= 0) { alert('مبلغ معتبر نیست.'); return; }
2387 datastore.expenses.push({
2742 - id: 'TRX_' + Date.now(),
2743 - ownerUserId: currentUser.id,
2388 + id: 'TRX_' + Date.now(), ownerUserId: currentUser.id,
2389 kind: document.getElementById('trx-kind-input').value,
2390 category: document.getElementById('trx-category-input').value,
2746 - amount,
2747 - desc: document.getElementById('trx-desc-input').value
2391 + amount, desc: document.getElementById('trx-desc-input').value
2392 });
2393 saveDatastore();
2394 alert('سند ثبت شد.');
@@ -2757,19 +2401,14 @@
2401 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('');
2402 }
2403
2760 - /* =========================================================================
2761 - مدیریت شرکت‌ها و فروشگاه‌ها با تفکیک دقیق کاربر (ownerUserId)
2762 - ========================================================================= */
2404 + /* ---------- شرکت‌ها ---------- */
2405 function commitSaveCompany() {
2406 if (!currentUser) return;
2407 const entity_type = document.getElementById('company-entity-type').value;
2408 const raw_name = document.getElementById('company-name-input').value;
2409 if (!raw_name.trim()) { alert('نام شرکت الزامی است.'); return; }
2768 -
2410 const newComp = {
2770 - id: 'COMP_' + Date.now(),
2771 - ownerUserId: currentUser.id,
2772 - entity_type,
2411 + id: 'COMP_' + Date.now(), ownerUserId: currentUser.id, entity_type,
2412 name: formatEntityName(raw_name, entity_type),
2413 phone: document.getElementById('company-phone-input').value || '',
2414 national_id: document.getElementById('company-national-input').value || '',
@@ -2779,24 +2418,15 @@
2418 address: document.getElementById('company-address-input').value || '',
2419 footer: document.getElementById('company-footer-input')?.value || 'از خرید شما سپاسگزاریم.'
2420 };
2782 -
2421 datastore.companies.push(newComp);
2784 -
2422 const s = getMySettings();
2423 s.default_company_id = newComp.id;
2787 -
2424 saveDatastore();
2425 alert('شرکت با موفقیت ثبت و ذخیره شد و به عنوان فروشنده پیش‌فرض تنظیم گردید.');
2790 - document.getElementById('company-name-input').value = '';
2791 - document.getElementById('company-phone-input').value = '';
2792 - document.getElementById('company-national-input').value = '';
2793 - document.getElementById('company-economic-input').value = '';
2794 - document.getElementById('company-reg-input').value = '';
2795 - document.getElementById('company-postal-input').value = '';
2796 - document.getElementById('company-address-input').value = '';
2797 - if (document.getElementById('company-footer-input')) {
2798 - document.getElementById('company-footer-input').value = '';
2799 - }
2426 + ['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 => {
2427 + const el = document.getElementById(id);
2428 + if (el) el.value = '';
2429 + });
2430 refreshAllSurfaces();
2431 }
2432
@@ -2807,7 +2437,6 @@
2437 const myCompanies = getMyCompanies();
2438 const mySettings = getMySettings();
2439 const defCompId = mySettings.default_company_id || (myCompanies[0]?.id);
2810 -
2440 if (tbody) {
2441 if (myCompanies.length === 0) {
2442 tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
@@ -2819,18 +2448,13 @@
2448 <td>${c.economic_code || '—'}</td>
2449 <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>
2450 <td>${myCompanies.length > 1 ? `<button class="btn btn-danger btn-inline" style="padding:2px 8px; font-size:11px;" onclick="deleteCompany('${c.id}')">حذف</button>` : '—'}</td>
2822 - </tr>
2823 - `).join('');
2451 + </tr>`).join('');
2452 }
2453 }
2826 -
2454 if (invoiceCompSelect) {
2455 invoiceCompSelect.innerHTML = myCompanies.map(c => `<option value="${c.id}" ${c.id === defCompId ? 'selected' : ''}>${c.name}</option>`).join('');
2829 - if (defCompId) {
2830 - invoiceCompSelect.value = defCompId;
2831 - }
2456 + if (defCompId) invoiceCompSelect.value = defCompId;
2457 }
2833 -
2458 if (filterCompSelect) {
2459 const currentVal = filterCompSelect.value || 'ALL';
2460 filterCompSelect.innerHTML = `<option value="ALL">نمایش همه شرکت‌ها</option>` + myCompanies.map(c => `<option value="${c.id}">فقط ${c.name}</option>`).join('');
@@ -2851,9 +2475,7 @@
2475 datastore.companies = datastore.companies.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
2476 const myCompanies = getMyCompanies();
2477 const s = getMySettings();
2854 - if (s.default_company_id === id) {
2855 - s.default_company_id = myCompanies[0]?.id || '';
2856 - }
2478 + if (s.default_company_id === id) s.default_company_id = myCompanies[0]?.id || '';
2479 saveDatastore();
2480 refreshAllSurfaces();
2481 }
@@ -2863,12 +2485,8 @@
2485 const userExport = {
2486 user: currentUser?.username,
2487 exportedAt: new Date().toISOString(),
2866 - companies: getMyCompanies(),
2867 - contacts: getMyContacts(),
2868 - products: getMyProducts(),
2869 - invoices: getMyInvoices(),
2870 - cheques: getMyCheques(),
2871 - expenses: getMyExpenses(),
2488 + companies: getMyCompanies(), contacts: getMyContacts(), products: getMyProducts(),
2489 + invoices: getMyInvoices(), cheques: getMyCheques(), expenses: getMyExpenses(),
2490 settings: getMySettings()
2491 };
2492 const blobString = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(userExport, null, 2));
@@ -2889,13 +2507,9 @@
2507 try {
2508 const imported = JSON.parse(e.target.result);
2509 const userId = currentUser.id;
2892 -
2510 ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(key => {
2511 if (Array.isArray(imported[key])) {
2895 - imported[key].forEach(item => {
2896 - item.ownerUserId = userId;
2897 - datastore[key].push(item);
2898 - });
2512 + imported[key].forEach(item => { item.ownerUserId = userId; datastore[key].push(item); });
2513 }
2514 });
2515 if (imported.settings) {
@@ -2910,29 +2524,27 @@
2524 reader.readAsText(file);
2525 }
2526
2913 - function numberToPersianWords(num) {
2914 - if (!num || isNaN(num) || num == 0) return 'صفر ریال';
2527 + function numberToPersianWords(num, currencyLabel) {
2528 + const cur = currencyLabel || 'ریال';
2529 + if (!num || isNaN(num) || num == 0) return 'صفر ' + cur;
2530 const yegan = ["", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"];
2531 const dahgan = ["", "", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"];
2532 const dah_ta_bist = ["ده", "یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"];
2533 const sadgan = ["", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"];
2534 const part_names = ["", "هزار", "میلیون", "میلیارد", "تریلیون"];
2920 -
2535 function threeDigitToWords(n) {
2536 let c = Math.floor(n / 100);
2537 let d = Math.floor((n % 100) / 10);
2538 let y = n % 10;
2539 let parts = [];
2540 if (c > 0) parts.push(sadgan[c]);
2927 - if (d === 1) {
2928 - parts.push(dah_ta_bist[y]);
2929 - } else {
2541 + if (d === 1) parts.push(dah_ta_bist[y]);
2542 + else {
2543 if (d > 1) parts.push(dahgan[d]);
2544 if (y > 0) parts.push(yegan[y]);
2545 }
2546 return parts.join(" و ");
2547 }
2935 -
2548 let parts = [];
2549 let chunkIdx = 0;
2550 let temp = Math.abs(Math.round(num));
@@ -2946,25 +2558,18 @@
2558 temp = Math.floor(temp / 1000);
2559 chunkIdx++;
2560 }
2949 - return parts.join(" و ") + " ریال";
2561 + return parts.join(" و ") + " " + cur;
2562 }
2563
2952 - window.addEventListener('DOMContentLoaded', () => {
2953 - initAuthSystem();
2954 - });
2564 + window.addEventListener('DOMContentLoaded', () => { initAuthSystem(); });
2565 </script>
2566
2567 <style>
2958 -/* Final hardening patch */
2568 .form-control, textarea, select { direction: rtl; }
2960 -/* توجه: قانون قبلی اینجا هر صفحه چاپ را با min-height:277mm!important به‌زور
2961 - تقریباً هم‌قد کل صفحه A4 می‌کرد — این دقیقاً همان چیزی بود که سیستم
2962 - صفحه‌بندی هوشمند (بر اساس اندازه‌گیری واقعی ارتفاع) را بی‌اثر می‌کرد و
2963 - باعث می‌شد حتی فاکتور یک‌ردیفی هم به ۲ صفحه فیزیکی چاپ شود. حذف شد.
2964 - عرض صفحه (190mm / 277mm افقی) هم دیگر اینجا نیست؛ در بلوک اصلی @media print
2965 - بالای فایل و به‌صورت شرطی (کلاس landscape برای فاکتور رسمی) مدیریت می‌شود. */
2569 </style>
2570 +
2571 <script>
2572 +/* ولیدیشن نهایی روی ثبت فاکتور */
2573 (function(){
2574 const oldSave = window.commitSaveInvoice;
2575 window.commitSaveInvoice = function(){
@@ -2974,9 +2579,14 @@
2579 return;
2580 }
2581 for(const row of rows){
2977 - const name = row.querySelector('input');
2978 - if(name && !name.value.trim()){
2979 - alert('شرح کالا یا خدمت را کامل کنید.');
2582 + const sel = row.querySelector('.row-product-select');
2583 + if(sel && !sel.value){
2584 + alert('لطفاً شرح کالا یا خدمت را از لیست انتخاب کنید.');
2585 + return;
2586 + }
2587 + const qty = parseFloat(row.querySelector('.row-quantity')?.value) || 0;
2588 + if(qty <= 0){
2589 + alert('مقدار کالا باید بزرگتر از صفر باشد.');
2590 return;
2591 }
2592 }
@@ -2984,8 +2594,8 @@
2594 };
2595
2596 window.EasyFactorHealth = {
2987 - version:'4.8-fixed',
2988 - storage:'localStorage',
2597 + version: '4.8-landscape-currency',
2598 + storage: 'localStorage',
2599 checks(){
2600 return {
2601 rtl: document.documentElement.dir === 'rtl',