@davoodmehraban89 / Factor-easy / commits / 6322f70
Fork 0

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

Update fmt.Println message from 'Hello' to 'Goodbye'

davoodmehraban89 committed Sep 16, 2026 at 22:26 UTC 6322f70c3f9f7cbe7f374a0583e8ec60e9fc662d
1 file changed +726 -255
index.html
+726 -255
@@ -81,6 +81,12 @@
81 th, td { padding: 10px 10px; border-bottom: 1px solid var(--border); }
82 th { background: #f1f5f9; color: #334155; font-weight: 700; }
83
84 + /* ترتیب و نمایش صحیح جدول اقلام فاکتور در RTL */
85 + #invoice-items-table { direction: rtl; width: 100%; table-layout: auto; }
86 + #invoice-items-table th, #invoice-items-table td { text-align: right; }
87 + #invoice-items-table th:first-child, #invoice-items-table td:first-child { text-align: center; }
88 + #invoice-items-table th:last-child, #invoice-items-table td:last-child { text-align: center; }
89 +
90 .badge { display: inline-block; padding: 3px 8px; border-radius: 6px; font-size: 11px; font-weight: 600; }
91 .badge-success { background: #d1fae5; color: #065f46; }
92 .badge-warning { background: #fef3c7; color: #92400e; }
@@ -98,13 +104,52 @@
104 .accordion-body { padding: 16px; border-top: 1px solid var(--border); display: none; background: #fff; }
105 .accordion-item.open .accordion-body { display: block; }
106
107 + /* =========================================================================
108 + تنظیمات اختصاصی و کنترل دقیق چاپ فاکتور در اندازه A4 (رسمی و غیررسمی)
109 + ========================================================================= */
110 @media print {
102 - body { background: #fff; }
103 - .sidebar, .mobile-dock, .no-print { display: none !important; }
104 - .main-surface { margin: 0; padding: 0; max-width: 100%; }
105 - .card { border: none; box-shadow: none; padding: 0; }
106 - .invoice-page-break { page-break-after: always; break-after: page; display: block !important; margin-bottom: 30px; }
107 - .invoice-page-break:last-child { page-break-after: avoid; break-after: avoid; margin-bottom: 0; }
111 + @page {
112 + size: A4 portrait;
113 + margin: 8mm 10mm;
114 + }
115 + html, body {
116 + background: #fff !important;
117 + color: #000 !important;
118 + margin: 0 !important;
119 + padding: 0 !important;
120 + width: 100% !important;
121 + }
122 + .sidebar, .mobile-dock, .no-print, #auth-screen, .modal-backdrop {
123 + display: none !important;
124 + }
125 + .main-surface {
126 + margin: 0 !important;
127 + padding: 0 !important;
128 + max-width: 100% !important;
129 + width: 100% !important;
130 + }
131 + .card {
132 + border: none !important;
133 + box-shadow: none !important;
134 + padding: 0 !important;
135 + margin: 0 !important;
136 + }
137 + .invoice-a4-page {
138 + width: 100% !important;
139 + max-width: 190mm !important;
140 + margin: 0 auto !important;
141 + padding: 0 !important;
142 + page-break-after: always !important;
143 + break-after: page !important;
144 + box-sizing: border-box !important;
145 + }
146 + .invoice-a4-page:last-child {
147 + page-break-after: avoid !important;
148 + break-after: avoid !important;
149 + }
150 + #printable-invoice {
151 + display: block !important;
152 + }
153 }
154
155 @media (max-width: 768px) {
@@ -287,22 +332,23 @@
332 </div>
333 </div>
334
335 + <!-- بخش اقلام فاکتور با ترتیب ستون‌های کاملاً استاندارد و منطبق در RTL -->
336 <div style="margin: 16px 0;">
337 <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
338 <h4 style="font-size: 14px;">اقلام کالا یا خدمات</h4>
339 <button class="btn btn-secondary btn-inline" style="font-size:12px; min-height:34px; padding:4px 10px;" onclick="openQuickProductModal()">➕ کالای جدید</button>
340 </div>
341 <div class="table-responsive">
296 - <table>
342 + <table id="invoice-items-table">
343 <thead>
344 <tr style="background:#e2e8f0;">
345 <th style="width:40px; text-align:center;">#</th>
346 <th>شرح کالا | خدمات</th>
301 - <th style="width:90px;">واحد</th>
302 - <th style="width:100px;">مقدار</th>
303 - <th style="width:160px;">قیمت واحد (ریال)</th>
304 - <th style="width:170px;">قیمت کل (ریال)</th>
305 - <th style="width:50px;">حذف</th>
347 + <th style="width:90px; text-align:center;">واحد</th>
348 + <th style="width:100px; text-align:center;">مقدار</th>
349 + <th style="width:160px; text-align:left;">قیمت واحد (ریال)</th>
350 + <th style="width:170px; text-align:left;">قیمت کل (ریال)</th>
351 + <th style="width:50px; text-align:center;">حذف</th>
352 </tr>
353 </thead>
354 <tbody id="invoice-items-table-body"></tbody>
@@ -459,7 +505,7 @@
505 <option value="فروشگاه">فروشگاه</option>
506 </select>
507 </div>
462 - <div class="form-group" style="grid-column: span 2;">
508 + <div class="form-group" style="grid-column: span 2;" id="box-contact-name">
509 <label>نام طرف حساب</label>
510 <input type="text" id="contact-name-input" class="form-control" placeholder="دانشگاه صنعتی شریف..." />
511 </div>
@@ -674,7 +720,7 @@
720 </div>
721 </section>
722
677 - <!-- قالب پرینت چندصفحه‌ای استاندارد -->
723 + <!-- کانتینر چاپ فاکتور استاندارد A4 (چندصفحه‌ای هوشمند) -->
724 <div id="printable-invoice" style="display:none;"></div>
725
726 </main>
@@ -687,7 +733,7 @@
733 <div class="form-row">
734 <div class="form-group"><label>نوع</label><select id="quick-c-entity" class="form-control" onchange="handleQuickCEntityChange()"><option value="natural">شخص حقیقی</option><option value="legal">شخص حقوقی</option></select></div>
735 <div class="form-group" id="box-quick-c-prefix"><label>پیشوند</label><select id="quick-c-prefix" class="form-control"><option value="آقا/خانم">آقا / خانم</option><option value="فروشگاه">فروشگاه</option></select></div>
690 - <div class="form-group"><label>نام</label><input type="text" id="quick-c-name" class="form-control" /></div>
736 + <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>
737 </div>
738 <div class="form-row">
739 <div class="form-group"><label>شناسه ملی</label><input type="text" id="quick-c-national" class="form-control" /></div>
@@ -758,6 +804,137 @@
804 const STORAGE_KEY = 'easy_factor_commercial_v4_6';
805 const AUTH_KEY = 'easy_factor_auth_users_v4_6';
806
807 + /* =========================================================================
808 + معماری ذخیره‌سازی داده‌ها و آمادگی برای همگام‌سازی ابری (Cloud Sync Layer)
809 + -------------------------------------------------------------------------
810 + این لایه عملیات ذخیره و بازیابی محلی را مدیریت کرده و نقاط اتصال استاندارد
811 + برای هماهنگ‌سازی میان دستگاه‌های مختلف (آیفون، کامپیوتر و...) را فراهم می‌کند.
812 + ========================================================================= */
813 + const CLOUD_SYNC_CONFIG = {
814 + enabled: false, // پس از راه‌اندازی سرور به true تغییر دهید
815 + apiEndpoint: '', // به عنوان مثال: 'https://api.yourdomain.com/v1/sync'
816 + authToken: '',
817 + deviceId: localStorage.getItem('easy_factor_device_id') || (() => {
818 + const id = 'dev_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
819 + localStorage.setItem('easy_factor_device_id', id);
820 + return id;
821 + })()
822 + };
823 +
824 + /**
825 + * ذخیره پایگاه داده در حافظه محلی و فراخوانی همگام‌سازی ابری در صورت فعال بودن
826 + */
827 + async function saveDatastore() {
828 + try {
829 + localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
830 + if (CLOUD_SYNC_CONFIG.enabled && CLOUD_SYNC_CONFIG.apiEndpoint) {
831 + await syncDatastore('push');
832 + }
833 + return true;
834 + } catch (err) {
835 + console.error('Error saving datastore:', err);
836 + return false;
837 + }
838 + }
839 +
840 + // حفظ سازگاری توابع قبلی
841 + function persistDatastore() {
842 + return saveDatastore();
843 + }
844 +
845 + /**
846 + * بارگذاری پایگاه داده از حافظه محلی به همراه اصلاحات امنیتی و بررسی ابری
847 + */
848 + async function loadDatastore() {
849 + const persisted = localStorage.getItem(STORAGE_KEY);
850 + if (persisted) {
851 + try {
852 + datastore = JSON.parse(persisted);
853 + } catch (e) {
854 + console.error('Error parsing datastore:', e);
855 + }
856 + }
857 +
858 + // ساختارهای پیش‌فرض ایمن
859 + if (!datastore.default_settings) {
860 + datastore.default_settings = {};
861 + }
862 + if (!Array.isArray(datastore.companies)) {
863 + datastore.companies = [];
864 + }
865 + if (!Array.isArray(datastore.contacts)) {
866 + datastore.contacts = [];
867 + }
868 + if (!Array.isArray(datastore.products)) {
869 + datastore.products = [];
870 + }
871 + if (!Array.isArray(datastore.invoices)) {
872 + datastore.invoices = [];
873 + }
874 + if (!Array.isArray(datastore.cheques)) {
875 + datastore.cheques = [];
876 + }
877 + if (!Array.isArray(datastore.expenses)) {
878 + datastore.expenses = [];
879 + }
880 +
881 + // بررسی و تثبیت شرکت فعال پیش‌فرض
882 + if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
883 + datastore.default_settings.default_company_id = datastore.companies[0].id;
884 + }
885 +
886 + localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
887 +
888 + if (CLOUD_SYNC_CONFIG.enabled && CLOUD_SYNC_CONFIG.apiEndpoint) {
889 + await syncDatastore('pull');
890 + }
891 +
892 + return datastore;
893 + }
894 +
895 + /**
896 + * هوک همگام‌سازی ابری بین دستگاه‌ها (آیفون، کامپیوتر و...)
897 + * جهت اتصال به بک‌اند (REST API / Supabase / Firebase / Node.js)
898 + */
899 + async function syncDatastore(direction = 'merge') {
900 + /* =========================================================================
901 + [محل اتصال API همگام‌سازی ابری]
902 + جهت هماهنگ‌سازی آنی فاکتورها و شرکت‌ها بین گوشی و رایانه:
903 + ۱. CLOUD_SYNC_CONFIG.enabled را برابر true قرار دهید.
904 + ۲. آدرس وب‌سرویس خود را در CLOUD_SYNC_CONFIG.apiEndpoint تنظیم فرمایید.
905 + ۳. در این بخش درخواست HTTP به سرور ارسال و پاسخ در datastore جایگزین می‌شود.
906 + ========================================================================= */
907 + if (!CLOUD_SYNC_CONFIG.enabled || !CLOUD_SYNC_CONFIG.apiEndpoint) {
908 + return { status: 'offline_mode', message: 'حافظه محلی مرورگر فعال است.' };
909 + }
910 +
911 + try {
912 + /* نمونه کد جهت اتصال به سرور ابری در آینده:
913 + const response = await fetch(CLOUD_SYNC_CONFIG.apiEndpoint, {
914 + method: 'POST',
915 + headers: {
916 + 'Content-Type': 'application/json',
917 + 'Authorization': `Bearer ${CLOUD_SYNC_CONFIG.authToken}`,
918 + 'X-Device-ID': CLOUD_SYNC_CONFIG.deviceId
919 + },
920 + body: JSON.stringify({ direction, datastore, timestamp: Date.now() })
921 + });
922 + if (response.ok) {
923 + const resData = await response.json();
924 + if (resData && resData.datastore) {
925 + datastore = resData.datastore;
926 + localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
927 + refreshAllSurfaces();
928 + }
929 + }
930 + */
931 + return { status: 'synced' };
932 + } catch (err) {
933 + console.warn('Sync connection notice:', err);
934 + return { status: 'error', error: err };
935 + }
936 + }
937 +
938 let currentUser = null;
939 let usersDb = [
940 { username: 'admin', pass: 'admin123', role: 'admin', license_type: 'lifetime', expire_date: '2099-01-01' }
@@ -783,7 +960,7 @@
960 {
961 id: 'C-1',
962 entity_type: 'legal',
786 - name: 'دانشگاه صنعتی شریف',
963 + name: 'شرکت دانشگاه صنعتی شریف',
964 mobile: '02166165000',
965 national_id: '14002830256',
966 economic_code: '14002830256',
@@ -946,28 +1123,9 @@
1123 }
1124
1125 function initDatastore() {
949 - const persisted = localStorage.getItem(STORAGE_KEY);
950 - if (persisted) {
951 - try { datastore = JSON.parse(persisted); } catch(e) {}
952 - }
953 -
954 - // Safe migration logic
955 - if (!datastore.default_settings) {
956 - datastore.default_settings = {};
957 - }
958 - if (!Array.isArray(datastore.companies)) {
959 - datastore.companies = [];
960 - }
961 - if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
962 - datastore.default_settings.default_company_id = datastore.companies[0].id;
963 - }
964 -
965 - persistDatastore();
966 - refreshAllSurfaces();
967 - }
968 -
969 - function persistDatastore() {
970 - localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
1126 + loadDatastore().then(() => {
1127 + refreshAllSurfaces();
1128 + });
1129 }
1130
1131 function getJalaliDate() {
@@ -1001,8 +1159,10 @@
1159 }
1160
1161 function refreshAllSurfaces() {
1004 - document.getElementById('dashboard-date-display').innerText = getJalaliDate();
1005 - document.getElementById('invoice-date-input').value = getJalaliNumeric();
1162 + const dashDate = document.getElementById('dashboard-date-display');
1163 + if (dashDate) dashDate.innerText = getJalaliDate();
1164 + const invDate = document.getElementById('invoice-date-input');
1165 + if (invDate && !invDate.value) invDate.value = getJalaliNumeric();
1166
1167 renderCompanies();
1168 renderContacts();
@@ -1012,18 +1172,58 @@
1172 renderCheques();
1173 renderExpenses();
1174 applyDefaultSettingsToForm();
1175 + handleContactEntityChange();
1176 }
1177
1178 + /* =========================================================================
1179 + قواعد پیشوند و قالب‌بندی نام طرف حساب (شخص حقیقی / حقوقی)
1180 + ========================================================================= */
1181 function formatEntityName(rawName, entityType, customPrefix = '') {
1182 let trimmed = (rawName || '').trim();
1183 if (entityType === 'legal') {
1020 - if (!trimmed.startsWith('شرکت')) trimmed = 'شرکت ' + trimmed;
1184 + if (!trimmed.startsWith('شرکت') && !trimmed.startsWith('موسسه') && !trimmed.startsWith('سازمان') && !trimmed.startsWith('اداره')) {
1185 + trimmed = 'شرکت ' + trimmed;
1186 + }
1187 } else if (entityType === 'natural' && customPrefix) {
1022 - if (!trimmed.startsWith(customPrefix)) trimmed = customPrefix + ' ' + trimmed;
1188 + if (!trimmed.startsWith(customPrefix)) {
1189 + trimmed = customPrefix + ' ' + trimmed;
1190 + }
1191 }
1192 return trimmed;
1193 }
1194
1195 + function handleContactEntityChange() {
1196 + const entitySelect = document.getElementById('contact-entity-type');
1197 + if (!entitySelect) return;
1198 + const entity = entitySelect.value;
1199 + const prefixBox = document.getElementById('box-contact-prefix');
1200 + const nameBox = document.getElementById('box-contact-name');
1201 +
1202 + if (entity === 'legal') {
1203 + if (prefixBox) prefixBox.style.display = 'none';
1204 + if (nameBox) nameBox.style.gridColumn = 'span 3';
1205 + } else {
1206 + if (prefixBox) prefixBox.style.display = 'block';
1207 + if (nameBox) nameBox.style.gridColumn = 'span 2';
1208 + }
1209 + }
1210 +
1211 + function handleQuickCEntityChange() {
1212 + const entitySelect = document.getElementById('quick-c-entity');
1213 + if (!entitySelect) return;
1214 + const entity = entitySelect.value;
1215 + const prefixBox = document.getElementById('box-quick-c-prefix');
1216 + const nameBox = document.getElementById('box-quick-c-name');
1217 +
1218 + if (entity === 'legal') {
1219 + if (prefixBox) prefixBox.style.display = 'none';
1220 + if (nameBox) nameBox.style.gridColumn = 'span 3';
1221 + } else {
1222 + if (prefixBox) prefixBox.style.display = 'block';
1223 + if (nameBox) nameBox.style.gridColumn = 'span 2';
1224 + }
1225 + }
1226 +
1227 function handleInvoiceKindChange() {
1228 const kind = document.getElementById('invoice-kind').value;
1229 const vatModeSelect = document.getElementById('invoice-vat-mode');
@@ -1046,7 +1246,7 @@
1246 const rateBox = document.getElementById('box-invoice-vat-rate');
1247
1248 if (kind === 'formal' && mode === 'with_vat') {
1049 - rateBox.style.display = 'block';
1249 + rateBox.style.display = 'flex';
1250 } else {
1251 rateBox.style.display = 'none';
1252 }
@@ -1055,20 +1255,24 @@
1255
1256 function applyDefaultSettingsToForm() {
1257 const def = datastore.default_settings || { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10 };
1058 - document.getElementById('def-invoice-kind').value = def.invoice_kind;
1059 - document.getElementById('def-vat-mode').value = def.vat_mode;
1060 - document.getElementById('def-vat-rate').value = def.vat_rate;
1258 + const defKind = document.getElementById('def-invoice-kind');
1259 + const defVat = document.getElementById('def-vat-mode');
1260 + const defRate = document.getElementById('def-vat-rate');
1261 + if (defKind) defKind.value = def.invoice_kind || 'non_formal';
1262 + if (defVat) defVat.value = def.vat_mode || 'none';
1263 + if (defRate) defRate.value = def.vat_rate || 10;
1264 handleInvoiceKindChange();
1265 }
1266
1267 function commitSaveDefaultSettings() {
1065 - datastore.default_settings = {
1066 - invoice_kind: document.getElementById('def-invoice-kind').value,
1067 - vat_mode: document.getElementById('def-vat-mode').value,
1068 - vat_rate: parseFloat(document.getElementById('def-vat-rate').value) || 0,
1069 - default_company_id: datastore.default_settings?.default_company_id || (datastore.companies[0]?.id)
1070 - };
1071 - persistDatastore();
1268 + if (!datastore.default_settings) datastore.default_settings = {};
1269 + datastore.default_settings.invoice_kind = document.getElementById('def-invoice-kind').value;
1270 + datastore.default_settings.vat_mode = document.getElementById('def-vat-mode').value;
1271 + datastore.default_settings.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1272 + if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
1273 + datastore.default_settings.default_company_id = datastore.companies[0].id;
1274 + }
1275 + saveDatastore();
1276 alert('پیش‌فرض‌ها ذخیره شد.');
1277 }
1278
@@ -1083,28 +1287,35 @@
1287 if (inv.paymentMethod === 'credit') debtorsSum += inv.grandTotal;
1288 });
1289
1086 - document.getElementById('kpi-sales-sum').innerText = salesSum.toLocaleString('fa-IR') + ' ریال';
1087 - document.getElementById('kpi-settled-sum').innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ریال';
1088 - document.getElementById('kpi-debtors-sum').innerText = debtorsSum.toLocaleString('fa-IR') + ' ریال';
1089 - document.getElementById('kpi-cheques-count').innerText = datastore.cheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1290 + const salesEl = document.getElementById('kpi-sales-sum');
1291 + const settledEl = document.getElementById('kpi-settled-sum');
1292 + const debtorsEl = document.getElementById('kpi-debtors-sum');
1293 + const chequesEl = document.getElementById('kpi-cheques-count');
1294 +
1295 + if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ریال';
1296 + if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ریال';
1297 + if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ریال';
1298 + if (chequesEl) chequesEl.innerText = datastore.cheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1299
1300 const recentTbody = document.getElementById('dashboard-recent-table');
1092 - if (filteredInvoices.length === 0) {
1093 - recentTbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری صادر نشده است.</td></tr>';
1094 - return;
1095 - }
1301 + if (recentTbody) {
1302 + if (filteredInvoices.length === 0) {
1303 + recentTbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری صادر نشده است.</td></tr>';
1304 + return;
1305 + }
1306
1097 - recentTbody.innerHTML = filteredInvoices.slice(-5).reverse().map(inv => `
1098 - <tr>
1099 - <td><strong>#${inv.number}</strong></td>
1100 - <td>${inv.companyName || '—'}</td>
1101 - <td>${inv.contactName}</td>
1102 - <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1103 - <td>${inv.vat > 0 ? 'با ارزش افزوده' : 'بدون مالیات'}</td>
1104 - <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1105 - <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px; font-size:12px;" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
1106 - </tr>
1107 - `).join('');
1307 + recentTbody.innerHTML = filteredInvoices.slice(-5).reverse().map(inv => `
1308 + <tr>
1309 + <td><strong>#${inv.number}</strong></td>
1310 + <td>${inv.companyName || '—'}</td>
1311 + <td>${inv.contactName}</td>
1312 + <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1313 + <td>${inv.vat > 0 ? 'با ارزش افزوده' : 'بدون مالیات'}</td>
1314 + <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1315 + <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px; font-size:12px;" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
1316 + </tr>
1317 + `).join('');
1318 + }
1319 }
1320
1321 function onActiveCompanyFilterChange() {
@@ -1120,6 +1331,20 @@
1331 switchView('view-invoices');
1332 }
1333
1334 + /* =========================================================================
1335 + مدیریت اقلام فاکتور با چینش دقیق و تطابق کامل سرستون‌ها و خانه‌ها در RTL
1336 + ترتیب: # | شرح کالا | خدمات | واحد | مقدار | قیمت واحد | قیمت کل | حذف
1337 + ========================================================================= */
1338 + function updateInvoiceItemRowNumbers() {
1339 + const rows = document.querySelectorAll('#invoice-items-table-body tr');
1340 + rows.forEach((tr, index) => {
1341 + const numCell = tr.querySelector('.row-item-number');
1342 + if (numCell) {
1343 + numCell.innerText = (index + 1).toLocaleString('fa-IR');
1344 + }
1345 + });
1346 + }
1347 +
1348 function addInvoiceItemRow(selectedProdId = '', initialQty = 1, initialPrice = null) {
1349 const tbody = document.getElementById('invoice-items-table-body');
1350 const rowKey = 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 4);
@@ -1127,24 +1352,27 @@
1352 tr.id = rowKey;
1353
1354 const productOptions = datastore.products.map(p =>
1130 - `<option value="${p.id}" data-price="${p.sale_price}" ${p.id === selectedProdId ? 'selected' : ''}>${p.name} ${p.spec ? '(' + p.spec + ')' : ''}</option>`
1355 + `<option value="${p.id}" data-price="${p.sale_price}" data-unit="${p.unit || 'عدد'}" ${p.id === selectedProdId ? 'selected' : ''}>${p.name} ${p.spec ? '(' + p.spec + ')' : ''}</option>`
1356 ).join('');
1357
1358 tr.innerHTML = `
1359 + <td class="row-item-number" style="width:40px; text-align:center; font-weight:bold; vertical-align:middle;"></td>
1360 <td>
1361 <select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')">
1362 <option value="">-- انتخاب کالا / خدمات --</option>
1363 ${productOptions}
1364 </select>
1365 </td>
1140 - <td><input type="text" class="form-control row-unit-input" value="عدد" /></td>
1141 - <td><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" /></td>
1142 - <td><input type="number" class="form-control row-price" value="${initialPrice !== null ? initialPrice : 0}" oninput="recomputeTotals()" /></td>
1143 - <td class="row-linetotal" style="font-weight:bold; padding-top:16px;">۰</td>
1144 - <td><button class="btn btn-danger" style="min-height:38px; padding:4px 8px;" onclick="document.getElementById('${rowKey}').remove(); recomputeTotals();">✕</button></td>
1366 + <td style="width:90px;"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center;" /></td>
1367 + <td style="width:100px;"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center;" /></td>
1368 + <td style="width:160px;"><input type="number" class="form-control row-price" value="${initialPrice !== null ? initialPrice : 0}" oninput="recomputeTotals()" style="text-align:left;" /></td>
1369 + <td class="row-linetotal" style="width:170px; font-weight:bold; text-align:left; vertical-align:middle; direction:ltr;">۰</td>
1370 + <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>
1371 `;
1372 tbody.appendChild(tr);
1373
1374 + updateInvoiceItemRowNumbers();
1375 +
1376 if (selectedProdId && initialPrice === null) {
1377 onRowProductChange(rowKey);
1378 } else {
@@ -1154,27 +1382,34 @@
1382
1383 function onRowProductChange(rowKey) {
1384 const tr = document.getElementById(rowKey);
1385 + if (!tr) return;
1386 const sel = tr.querySelector('.row-product-select');
1387 const opt = sel.options[sel.selectedIndex];
1388 const prc = opt?.getAttribute('data-price') || 0;
1389 + const unt = opt?.getAttribute('data-unit');
1390 tr.querySelector('.row-price').value = prc;
1391 + if (unt) {
1392 + const unitInput = tr.querySelector('.row-unit-input');
1393 + if (unitInput) unitInput.value = unt;
1394 + }
1395 recomputeTotals();
1396 }
1397
1398 function recomputeTotals() {
1399 let subtotal = 0;
1400 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1167 - const qty = parseFloat(tr.querySelector('.row-quantity').value) || 0;
1168 - const prc = parseFloat(tr.querySelector('.row-price').value) || 0;
1401 + const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1402 + const prc = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1403 const line = qty * prc;
1170 - tr.querySelector('.row-linetotal').innerText = line.toLocaleString('fa-IR');
1404 + const lineEl = tr.querySelector('.row-linetotal');
1405 + if (lineEl) lineEl.innerText = line.toLocaleString('fa-IR');
1406 subtotal += line;
1407 });
1408
1174 - const fixedDiscount = parseFloat(document.getElementById('invoice-discount-fixed').value) || 0;
1175 - const kind = document.getElementById('invoice-kind').value;
1176 - const vatMode = document.getElementById('invoice-vat-mode').value;
1177 - const vatRate = parseFloat(document.getElementById('invoice-vat-rate-input').value) || 0;
1409 + const fixedDiscount = parseFloat(document.getElementById('invoice-discount-fixed')?.value) || 0;
1410 + const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1411 + const vatMode = document.getElementById('invoice-vat-mode')?.value || 'none';
1412 + const vatRate = parseFloat(document.getElementById('invoice-vat-rate-input')?.value) || 0;
1413
1414 const afterDiscount = Math.max(0, subtotal - fixedDiscount);
1415 let vatAmount = 0;
@@ -1183,10 +1418,15 @@
1418 }
1419 const grandTotal = afterDiscount + vatAmount;
1420
1186 - document.getElementById('summary-subtotal').innerText = subtotal.toLocaleString('fa-IR') + ' ریال';
1187 - document.getElementById('summary-vat').innerText = vatAmount.toLocaleString('fa-IR') + ' ریال';
1188 - document.getElementById('summary-grandtotal').innerText = grandTotal.toLocaleString('fa-IR') + ' ریال';
1189 - document.getElementById('summary-words').innerText = 'به حروف: ' + grandTotal.toLocaleString('fa-IR') + ' ریال';
1421 + const subtotalEl = document.getElementById('summary-subtotal');
1422 + const vatEl = document.getElementById('summary-vat');
1423 + const grandEl = document.getElementById('summary-grandtotal');
1424 + const wordsEl = document.getElementById('summary-words');
1425 +
1426 + if (subtotalEl) subtotalEl.innerText = subtotal.toLocaleString('fa-IR') + ' ریال';
1427 + if (vatEl) vatEl.innerText = vatAmount.toLocaleString('fa-IR') + ' ریال';
1428 + if (grandEl) grandEl.innerText = grandTotal.toLocaleString('fa-IR') + ' ریال';
1429 + if (wordsEl) wordsEl.innerText = 'به حروف: ' + numberToPersianWords(grandTotal);
1430
1431 return { subtotal, fixedDiscount, vatAmount, grandTotal, vatRate };
1432 }
@@ -1195,33 +1435,38 @@
1435 const companySelect = document.getElementById('invoice-company-id');
1436 const selectedCompanyId = companySelect ? companySelect.value : (datastore.default_settings?.default_company_id);
1437
1438 + // استخراج فروشنده فعال دقیقاً بر اساس شناسه انتخاب‌شده و عدم اتکا به ایندکس 0
1439 const sellerCompany = datastore.companies.find(
1440 company => company.id === selectedCompanyId
1441 ) || datastore.companies.find(
1442 company => company.id === datastore.default_settings?.default_company_id
1443 ) || datastore.companies[0];
1444
1204 - const companyId = sellerCompany ? sellerCompany.id : selectedCompanyId;
1205 - const companyName = sellerCompany ? sellerCompany.name : (companySelect?.options[companySelect.selectedIndex]?.text || '');
1445 + if (!sellerCompany) {
1446 + alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');
1447 + return;
1448 + }
1449 +
1450 + const companyId = sellerCompany.id;
1451 + const companyName = sellerCompany.name;
1452
1453 const contactSelect = document.getElementById('invoice-contact-id');
1208 - const contactId = contactSelect.value;
1209 - const contactName = contactSelect.options[contactSelect.selectedIndex]?.text || 'مشتری';
1210 - const number = document.getElementById('invoice-number').value || ('PINV-' + (datastore.invoices.length + 31));
1211 - const date = document.getElementById('invoice-date-input').value;
1212 - const kind = document.getElementById('invoice-kind').value;
1213 - const paymentMethod = document.getElementById('invoice-payment-method')?.value || 'cash';
1214 - const description = document.getElementById('invoice-desc-input').value;
1215 - const editId = document.getElementById('edit-invoice-id').value;
1454 + const contactId = contactSelect ? contactSelect.value : '';
1455 + const contactName = contactSelect?.options[contactSelect.selectedIndex]?.text || 'مشتری آزاد';
1456 + const number = document.getElementById('invoice-number')?.value.trim() || ('PINV-' + (datastore.invoices.length + 31));
1457 + const date = document.getElementById('invoice-date-input')?.value.trim() || getJalaliNumeric();
1458 + const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1459 + const description = document.getElementById('invoice-desc-input')?.value.trim() || '';
1460 + const editId = document.getElementById('edit-invoice-id')?.value;
1461
1462 const items = [];
1463 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1464 const sel = tr.querySelector('.row-product-select');
1220 - const prodId = sel.value;
1221 - const prodName = sel.options[sel.selectedIndex]?.text || '';
1222 - const unit = tr.querySelector('.row-unit-input').value || 'عدد';
1223 - const qty = parseFloat(tr.querySelector('.row-quantity').value) || 0;
1224 - const price = parseFloat(tr.querySelector('.row-price').value) || 0;
1465 + const prodId = sel ? sel.value : '';
1466 + const prodName = sel ? sel.options[sel.selectedIndex]?.text : '';
1467 + const unit = tr.querySelector('.row-unit-input')?.value || 'عدد';
1468 + const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1469 + const price = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1470
1471 if (prodId && qty > 0) {
1472 items.push({ prodId, prodName, unit, qty, price, lineTotal: qty * price });
@@ -1234,7 +1479,6 @@
1479 }
1480
1481 const totals = recomputeTotals();
1237 - const methodLabels = { cash: 'نقدی', credit: 'نسیه', cheque: 'چک صیاد', installment: 'اقساطی' };
1482 const kindLabels = { formal: 'رسمی', non_formal: 'غیررسمی', pre_invoice: 'پیش‌فاکتور' };
1483
1484 if (editId) {
@@ -1244,8 +1488,9 @@
1488 ...datastore.invoices[existingIndex],
1489 number, date, companyId, companyName, kind,
1490 kindLabel: kindLabels[kind],
1247 - contactId, contactName, paymentMethod,
1248 - paymentMethodLabel: methodLabels[paymentMethod],
1491 + contactId, contactName,
1492 + paymentMethod: 'cash',
1493 + paymentMethodLabel: 'نقدی',
1494 subtotal: totals.subtotal,
1495 discount: totals.fixedDiscount,
1496 vat: totals.vatAmount,
@@ -1262,8 +1507,9 @@
1507 id: 'INV_' + Date.now(),
1508 number, date, companyId, companyName, kind,
1509 kindLabel: kindLabels[kind],
1265 - contactId, contactName, paymentMethod,
1266 - paymentMethodLabel: methodLabels[paymentMethod],
1510 + contactId, contactName,
1511 + paymentMethod: 'cash',
1512 + paymentMethodLabel: 'نقدی',
1513 subtotal: totals.subtotal,
1514 discount: totals.fixedDiscount,
1515 vat: totals.vatAmount,
@@ -1278,7 +1524,7 @@
1524 renderAndPrintDirect(record.id);
1525 }
1526
1281 - persistDatastore();
1527 + saveDatastore();
1528 refreshAllSurfaces();
1529 }
1530
@@ -1299,8 +1545,6 @@
1545 document.getElementById('invoice-number').value = inv.number;
1546 document.getElementById('invoice-contact-id').value = inv.contactId;
1547 document.getElementById('invoice-date-input').value = inv.date;
1302 - const pmEl = document.getElementById('invoice-payment-method');
1303 - if (pmEl) pmEl.value = inv.paymentMethod;
1548 document.getElementById('invoice-discount-fixed').value = inv.discount || 0;
1549 document.getElementById('invoice-desc-input').value = inv.description || '';
1550
@@ -1311,8 +1555,11 @@
1555 inv.items.forEach(it => {
1556 addInvoiceItemRow(it.prodId, it.qty, it.price);
1557 const lastRow = tbody.lastElementChild;
1314 - if (lastRow) lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
1558 + if (lastRow) {
1559 + lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
1560 + }
1561 });
1562 + updateInvoiceItemRowNumbers();
1563 recomputeTotals();
1564 }
1565
@@ -1360,153 +1607,339 @@
1607 `).join('');
1608 }
1609
1610 + /* =========================================================================
1611 + سیستم چاپ حرفه‌ای A4 مطابق فایل‌های مرجع (رسمی.pdf و غیر رسمی.pdf)
1612 + با کنترل دقیق حداکثر ۱۰ ردیف کالا در هر صفحه و جلوگیری از سرریز امضا
1613 + ========================================================================= */
1614 function renderAndPrintDirect(invId) {
1615 const inv = datastore.invoices.find(i => i.id === invId);
1616 if (!inv) return;
1617
1367 - const seller = datastore.companies.find(c => c.id === inv.companyId) || datastore.companies.find(c => c.id === datastore.default_settings?.default_company_id) || datastore.companies[0] || {};
1618 + const seller = datastore.companies.find(c => c.id === inv.companyId) ||
1619 + datastore.companies.find(c => c.id === datastore.default_settings?.default_company_id) ||
1620 + datastore.companies[0] || {};
1621 const contact = datastore.contacts.find(c => c.id === inv.contactId) || {};
1622
1370 - const itemsPerPage = 10;
1623 + const isFormal = (inv.kind === 'formal');
1624 + const itemsPerPage = 10; // کنترل دقیق حداکثر ۱۰ ردیف در هر صفحه A4
1625 const totalPages = Math.ceil(inv.items.length / itemsPerPage) || 1;
1626 let containerHtml = '';
1627
1628 let runningSubtotal = 0;
1629 + let runningDiscount = 0;
1630 + let runningVat = 0;
1631
1632 for (let p = 0; p < totalPages; p++) {
1633 const pageItems = inv.items.slice(p * itemsPerPage, (p + 1) * itemsPerPage);
1378 - let pageSubtotal = 0;
1379 -
1380 - const rowsHtml = pageItems.map((it, idx) => {
1381 - const absoluteIndex = (p * itemsPerPage) + idx + 1;
1382 - pageSubtotal += it.lineTotal;
1383 - return `
1384 - <tr>
1385 - <td style="border:1px solid #000; padding:6px; text-align:center; font-size:11px;">${absoluteIndex}</td>
1386 - <td style="border:1px solid #000; padding:6px; text-align:right; font-size:11px;">${it.prodName}</td>
1387 - <td style="border:1px solid #000; padding:6px; text-align:center; font-size:11px;">${it.unit || 'عدد'}</td>
1388 - <td style="border:1px solid #000; padding:6px; text-align:center; font-size:11px;">${it.qty}</td>
1389 - <td style="border:1px solid #000; padding:6px; text-align:left; font-size:11px;">${it.price.toLocaleString('fa-IR')}</td>
1390 - <td style="border:1px solid #000; padding:6px; text-align:left; font-size:11px;">${it.lineTotal.toLocaleString('fa-IR')}</td>
1391 - </tr>
1392 - `;
1393 - }).join('');
1394 -
1395 - let cumulativeBefore = runningSubtotal;
1396 - runningSubtotal += pageSubtotal;
1397 - let cumulativeTotal = runningSubtotal;
1398 -
1634 const isLastPage = (p === totalPages - 1);
1635
1401 - containerHtml += `
1402 - <div class="invoice-page-break" style="background:#fff; padding:18px; border:2px solid #000; margin-bottom:20px;">
1403 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #000; margin-bottom:6px;">
1404 - <tr>
1405 - <td style="width:25%; border:1px solid #000; padding:6px; font-size:11px; vertical-align:top;">
1406 - <div>شماره: <strong>${inv.number}</strong></div>
1407 - <div style="margin-top:4px;">تاریخ: ${inv.date}</div>
1408 - <div style="margin-top:4px;">صفحه: ${p + 1} از ${totalPages}</div>
1409 - </td>
1410 - <td style="width:50%; border:1px solid #000; padding:8px; text-align:center; vertical-align:middle;">
1411 - <h2 style="font-size:16px; margin:0; font-weight:bold;">${inv.kind === 'formal' ? 'صورتحساب رسمی فروش کالا و خدمات' : 'پیش فاکتور فروش کالا و خدمات'}</h2>
1412 - <div style="font-size:11px; margin-top:4px; font-weight:600;">${seller.name || ''}</div>
1413 - </td>
1414 - <td style="width:25%; border:1px solid #000; padding:6px; font-size:11px; text-align:left; vertical-align:top;">
1415 - <div>تلفن: ${seller.phone || '—'}</div>
1416 - </td>
1417 - </tr>
1418 - </table>
1419 -
1420 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #000; font-size:11px; margin-bottom:6px;">
1421 - <tr>
1422 - <td style="border:1px solid #000; padding:5px; width:15%; background:#f1f5f9;">فروشنده:</td>
1423 - <td style="border:1px solid #000; padding:5px; width:35%;"><strong>${seller.name || '—'}</strong></td>
1424 - <td style="border:1px solid #000; padding:5px; width:15%; background:#f1f5f9;">شناسه ملی:</td>
1425 - <td style="border:1px solid #000; padding:5px; width:35%;"><span>${seller.national_id || '—'}</span></td>
1426 - </tr>
1427 - <tr>
1428 - <td style="border:1px solid #000; padding:5px; background:#f1f5f9;">کد اقتصادی:</td>
1429 - <td style="border:1px solid #000; padding:5px;"><span>${seller.economic_code || '—'}</span></td>
1430 - <td style="border:1px solid #000; padding:5px; background:#f1f5f9;">شماره ثبت:</td>
1431 - <td style="border:1px solid #000; padding:5px;"><span>${seller.reg_number || '—'}</span></td>
1636 + let pageSubtotal = 0;
1637 + let pageDiscount = 0;
1638 + let pageVat = 0;
1639 +
1640 + let rowsHtml = '';
1641 +
1642 + if (isFormal) {
1643 + // تولید سطرهای جدول قالب رسمی (۹ ستون مطابق استاندارد دارایی و رسمی.pdf)
1644 + rowsHtml = pageItems.map((it, idx) => {
1645 + const absoluteIndex = (p * itemsPerPage) + idx + 1;
1646 + const lineSubtotal = it.lineTotal;
1647 + pageSubtotal += lineSubtotal;
1648 +
1649 + const lineDiscount = (inv.subtotal > 0) ? Math.round((inv.discount || 0) * (lineSubtotal / inv.subtotal)) : 0;
1650 + pageDiscount += lineDiscount;
1651 +
1652 + const lineVat = (inv.subtotal > 0 && inv.vat > 0) ? Math.round((lineSubtotal - lineDiscount) * ((inv.vatRate || 10) / 100)) : 0;
1653 + pageVat += lineVat;
1654 +
1655 + const lineNet = lineSubtotal - lineDiscount + lineVat;
1656 +
1657 + return `
1658 + <tr style="text-align:center;">
1659 + <td style="border:1px solid #1e293b; padding:4px 6px; font-size:11px;">${absoluteIndex}</td>
1660 + <td style="border:1px solid #1e293b; padding:4px 6px; text-align:right; font-size:11px; font-weight:600;">${it.prodName}</td>
1661 + <td style="border:1px solid #1e293b; padding:4px 6px; font-size:11px;">${it.qty}</td>
1662 + <td style="border:1px solid #1e293b; padding:4px 6px; font-size:11px;">${it.unit || 'عدد'}</td>
1663 + <td style="border:1px solid #1e293b; padding:4px 6px; text-align:left; font-size:11px;">${it.price.toLocaleString('fa-IR')}</td>
1664 + <td style="border:1px solid #1e293b; padding:4px 6px; text-align:left; font-size:11px;">${lineSubtotal.toLocaleString('fa-IR')}</td>
1665 + <td style="border:1px solid #1e293b; padding:4px 6px; text-align:left; font-size:11px;">${lineDiscount.toLocaleString('fa-IR')}</td>
1666 + <td style="border:1px solid #1e293b; padding:4px 6px; text-align:left; font-size:11px;">${lineVat.toLocaleString('fa-IR')}</td>
1667 + <td style="border:1px solid #1e293b; padding:4px 6px; text-align:left; font-size:11px; font-weight:bold;">${lineNet.toLocaleString('fa-IR')}</td>
1668 </tr>
1433 - <tr>
1434 - <td style="border:1px solid #000; padding:5px; background:#f1f5f9;">کد پستی و نشانی:</td>
1435 - <td colspan="3" style="border:1px solid #000; padding:5px;">کد پستی: ${seller.postal_code || '—'} | آدرس: ${seller.address || '—'}</td>
1669 + `;
1670 + }).join('');
1671 + } else {
1672 + // تولید سطرهای جدول قالب غیررسمی / پیش‌فاکتور (۶ ستون استاندارد و شکیل مطابق غیر رسمی.pdf)
1673 + rowsHtml = pageItems.map((it, idx) => {
1674 + const absoluteIndex = (p * itemsPerPage) + idx + 1;
1675 + pageSubtotal += it.lineTotal;
1676 +
1677 + return `
1678 + <tr style="text-align:center;">
1679 + <td style="border:1px solid #334155; padding:5px 6px; font-size:11px;">${absoluteIndex}</td>
1680 + <td style="border:1px solid #334155; padding:5px 8px; text-align:right; font-size:11px; font-weight:600;">${it.prodName}</td>
1681 + <td style="border:1px solid #334155; padding:5px 6px; font-size:11px;">${it.unit || 'عدد'}</td>
1682 + <td style="border:1px solid #334155; padding:5px 6px; font-size:11px;">${it.qty}</td>
1683 + <td style="border:1px solid #334155; padding:5px 6px; text-align:left; font-size:11px;">${it.price.toLocaleString('fa-IR')}</td>
1684 + <td style="border:1px solid #334155; padding:5px 6px; text-align:left; font-size:11px; font-weight:bold;">${it.lineTotal.toLocaleString('fa-IR')}</td>
1685 </tr>
1437 - </table>
1686 + `;
1687 + }).join('');
1688 + }
1689
1439 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #000; font-size:11px; margin-bottom:6px;">
1440 - <tr>
1441 - <td style="border:1px solid #000; padding:5px; width:15%; background:#f1f5f9;">خریدار:</td>
1442 - <td style="border:1px solid #000; padding:5px; width:35%;"><strong>${contact.name || inv.contactName}</strong></td>
1443 - <td style="border:1px solid #000; padding:5px; width:15%; background:#f1f5f9;">شناسه ملی:</td>
1444 - <td style="border:1px solid #000; padding:5px; width:35%;"><span>${contact.national_id || '—'}</span></td>
1445 - </tr>
1446 - <tr>
1447 - <td style="border:1px solid #000; padding:5px; background:#f1f5f9;">کد اقتصادی:</td>
1448 - <td style="border:1px solid #000; padding:5px;"><span>${contact.economic_code || '—'}</span></td>
1449 - <td style="border:1px solid #000; padding:5px; background:#f1f5f9;">تلفن / ثبت:</td>
1450 - <td style="border:1px solid #000; padding:5px;"><span>${contact.mobile || '—'}</span> / ثبت: ${contact.reg_number || '—'}</td>
1451 - </tr>
1452 - <tr>
1453 - <td style="border:1px solid #000; padding:5px; background:#f1f5f9;">کد پستی و نشانی:</td>
1454 - <td colspan="3" style="border:1px solid #000; padding:5px;">کد پستی: ${contact.postal_code || '—'} | آدرس: ${contact.address || '—'}</td>
1455 - </tr>
1456 - </table>
1690 + const cumulativeBefore = runningSubtotal;
1691 + runningSubtotal += pageSubtotal;
1692 + runningDiscount += pageDiscount;
1693 + runningVat += pageVat;
1694 +
1695 + // ساخت ساختار صفحه کامل A4
1696 + if (isFormal) {
1697 + // ======================== قالب رسمی استاندارد A4 ========================
1698 + containerHtml += `
1699 + <div class="invoice-a4-page" style="background:#fff; padding:8mm 6mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1700 + <!-- سربرگ رسمی -->
1701 + <table style="width:100%; border-collapse:collapse; border:2px solid #1e3a8a; margin-bottom:4px;">
1702 + <tr>
1703 + <td style="width:28%; border:1px solid #1e3a8a; padding:6px; font-size:11px; vertical-align:middle;">
1704 + <div style="font-weight:bold; font-size:13px; color:#1e3a8a;">${seller.name || 'فروشگاه'}</div>
1705 + <div style="font-size:10px; color:#475569; margin-top:2px;">صادرکننده فاکتور رسمی</div>
1706 + </td>
1707 + <td style="width:44%; border:1px solid #1e3a8a; padding:8px; text-align:center; vertical-align:middle; background:#eff6ff;">
1708 + <h1 style="font-size:16px; margin:0; font-weight:bold; color:#1e3a8a;">صورتحساب فروش کالا و خدمات</h1>
1709 + <div style="font-size:11px; margin-top:3px;">(ماده ۱۶۹ مکرر قانون مالیات‌های مستقیم)</div>
1710 + </td>
1711 + <td style="width:28%; border:1px solid #1e3a8a; padding:6px; font-size:11px; vertical-align:middle; text-align:left;">
1712 + <div>شماره سریال: <strong style="color:#b91c1c;">${inv.number}</strong></div>
1713 + <div style="margin-top:2px;">تاریخ صدور: <strong>${inv.date}</strong></div>
1714 + <div style="margin-top:2px; color:#64748b; font-size:10px;">صفحه: ${p + 1} از ${totalPages}</div>
1715 + </td>
1716 + </tr>
1717 + </table>
1718
1458 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #000; font-size:11px;">
1459 - <thead>
1460 - <tr style="background:#e2e8f0; font-weight:bold; text-align:center;">
1461 - <th style="border:1px solid #000; padding:6px; width:35px;">ردیف</th>
1462 - <th style="border:1px solid #000; padding:6px; text-align:right;">شرح کالا | خدمات</th>
1463 - <th style="border:1px solid #000; padding:6px; width:55px;">واحد</th>
1464 - <th style="border:1px solid #000; padding:6px; width:55px;">مقدار</th>
1465 - <th style="border:1px solid #000; padding:6px; width:130px; text-align:left;">قیمت واحد (ریال)</th>
1466 - <th style="border:1px solid #000; padding:6px; width:140px; text-align:left;">قیمت کل (ریال)</th>
1719 + <!-- بخش الف: مشخصات فروشنده -->
1720 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10.5px; margin-bottom:4px;">
1721 + <tr style="background:#f8fafc; font-weight:bold;">
1722 + <td colspan="4" style="border:1px solid #1e3a8a; padding:3px 6px; color:#1e3a8a;">الف) مشخصات فروشنده</td>
1723 </tr>
1468 - </thead>
1469 - <tbody>
1470 - ${p > 0 ? `<tr><td colspan="5" style="border:1px solid #000; padding:6px; text-align:left; font-weight:bold; background:#f8fafc;">نقل از صفحه قبل:</td><td style="border:1px solid #000; padding:6px; text-align:left; font-weight:bold; background:#f8fafc;">${cumulativeBefore.toLocaleString('fa-IR')} ریال</td></tr>` : ''}
1471 - ${rowsHtml}
1724 <tr>
1473 - <td colspan="5" style="border:1px solid #000; padding:6px; text-align:left; font-weight:bold; background:#f1f5f9;">جمع کل این صفحه:</td>
1474 - <td style="border:1px solid #000; padding:6px; text-align:left; font-weight:bold; background:#f1f5f9;">${cumulativeTotal.toLocaleString('fa-IR')} ریال</td>
1725 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:15%; background:#f1f5f9;">نام شخص حقیقی/حقوقی:</td>
1726 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:35%;"><strong>${seller.name || '—'}</strong></td>
1727 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:15%; background:#f1f5f9;">شماره اقتصادی:</td>
1728 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:35%;"><span>${seller.economic_code || '—'}</span></td>
1729 </tr>
1476 - </tbody>
1477 - </table>
1730 + <tr>
1731 + <td style="border:1px solid #cbd5e1; padding:4px 6px; background:#f1f5f9;">شماره ثبت / شناسه ملی:</td>
1732 + <td style="border:1px solid #cbd5e1; padding:4px 6px;"><span>${seller.national_id || seller.reg_number || '—'}</span></td>
1733 + <td style="border:1px solid #cbd5e1; padding:4px 6px; background:#f1f5f9;">کد پستی ۱۰ رقمی:</td>
1734 + <td style="border:1px solid #cbd5e1; padding:4px 6px;"><span>${seller.postal_code || '—'}</span></td>
1735 + </tr>
1736 + <tr>
1737 + <td style="border:1px solid #cbd5e1; padding:4px 6px; background:#f1f5f9;">نشانی و تلفن:</td>
1738 + <td colspan="3" style="border:1px solid #cbd5e1; padding:4px 6px;">${seller.address || '—'} ${seller.phone ? ' | تلفن: ' + seller.phone : ''}</td>
1739 + </tr>
1740 + </table>
1741 +
1742 + <!-- بخش ب: مشخصات خریدار -->
1743 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10.5px; margin-bottom:4px;">
1744 + <tr style="background:#f8fafc; font-weight:bold;">
1745 + <td colspan="4" style="border:1px solid #1e3a8a; padding:3px 6px; color:#1e3a8a;">ب) مشخصات خریدار</td>
1746 + </tr>
1747 + <tr>
1748 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:15%; background:#f1f5f9;">نام شخص حقیقی/حقوقی:</td>
1749 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:35%;"><strong>${contact.name || inv.contactName}</strong></td>
1750 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:15%; background:#f1f5f9;">شماره اقتصادی:</td>
1751 + <td style="border:1px solid #cbd5e1; padding:4px 6px; width:35%;"><span>${contact.economic_code || '—'}</span></td>
1752 + </tr>
1753 + <tr>
1754 + <td style="border:1px solid #cbd5e1; padding:4px 6px; background:#f1f5f9;">شماره ثبت / شناسه ملی:</td>
1755 + <td style="border:1px solid #cbd5e1; padding:4px 6px;"><span>${contact.national_id || contact.reg_number || '—'}</span></td>
1756 + <td style="border:1px solid #cbd5e1; padding:4px 6px; background:#f1f5f9;">کد پستی ۱۰ رقمی:</td>
1757 + <td style="border:1px solid #cbd5e1; padding:4px 6px;"><span>${contact.postal_code || '—'}</span></td>
1758 + </tr>
1759 + <tr>
1760 + <td style="border:1px solid #cbd5e1; padding:4px 6px; background:#f1f5f9;">نشانی و تلفن:</td>
1761 + <td colspan="3" style="border:1px solid #cbd5e1; padding:4px 6px;">${contact.address || '—'} ${contact.mobile ? ' | همراه: ' + contact.mobile : ''}</td>
1762 + </tr>
1763 + </table>
1764 +
1765 + <!-- جدول اقلام کالا و خدمات رسمی -->
1766 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10.5px;">
1767 + <thead>
1768 + <tr style="background:#1e3a8a; color:#fff; font-weight:bold; text-align:center;">
1769 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:30px;">ردیف</th>
1770 + <th style="border:1px solid #1e3a8a; padding:5px 6px; text-align:right;">شرح کالا یا خدمات</th>
1771 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:45px;">تعداد</th>
1772 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:45px;">واحد</th>
1773 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:110px;">مبلغ واحد (ریال)</th>
1774 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:115px;">مبلغ کل (ریال)</th>
1775 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:85px;">تخفیف (ریال)</th>
1776 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:95px;">مالیات (ریال)</th>
1777 + <th style="border:1px solid #1e3a8a; padding:5px 4px; width:125px;">مبلغ نهایی (ریال)</th>
1778 + </tr>
1779 + </thead>
1780 + <tbody>
1781 + ${p > 0 ? `
1782 + <tr style="background:#fef3c7; font-weight:bold; font-size:10px;">
1783 + <td colspan="5" style="border:1px solid #1e293b; padding:4px; text-align:left;">نقل از صفحه قبل:</td>
1784 + <td colspan="4" style="border:1px solid #1e293b; padding:4px; text-align:left;">${cumulativeBefore.toLocaleString('fa-IR')} ریال</td>
1785 + </tr>
1786 + ` : ''}
1787 + ${rowsHtml}
1788 + ${!isLastPage ? `
1789 + <tr style="background:#f1f5f9; font-weight:bold; font-size:10px;">
1790 + <td colspan="5" style="border:1px solid #1e293b; padding:4px; text-align:left;">جمع این صفحه و نقل به صفحه بعد:</td>
1791 + <td colspan="4" style="border:1px solid #1e293b; padding:4px; text-align:left;">${runningSubtotal.toLocaleString('fa-IR')} ریال</td>
1792 + </tr>
1793 + ` : ''}
1794 + </tbody>
1795 + </table>
1796
1479 - ${isLastPage ? `
1480 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #000; font-size:11px; margin-top:6px;">
1797 + ${isLastPage ? `
1798 + <!-- بخش جمع‌بندی و تسویه در صفحه آخر -->
1799 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:11px; margin-top:4px;">
1800 + <tr>
1801 + <td style="width:60%; border:1px solid #1e3a8a; padding:8px; vertical-align:top; background:#f8fafc;">
1802 + <div style="margin-bottom:6px;"><strong>مبلغ کل به حروف:</strong> ${numberToPersianWords(inv.grandTotal)}</div>
1803 + <div style="margin-bottom:6px;"><strong>شرایط و نحوه پرداخت:</strong> نقدی ☑ &nbsp;&nbsp;&nbsp; غیرنقدی (نسیه/چک) ☐</div>
1804 + <div style="font-size:10px; color:#475569; line-height:1.6;"><strong>توضیحات:</strong> ${inv.description || seller.footer || 'تحویل کالا منوط به تسویه نهایی می‌باشد.'}</div>
1805 + </td>
1806 + <td style="width:40%; border:1px solid #1e3a8a; padding:0;">
1807 + <table style="width:100%; border-collapse:collapse; font-size:11px;">
1808 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px;">جمع کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ریال</td></tr>
1809 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px;">مجموع تخفیف:</td><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ریال</td></tr>
1810 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px;">مالیات و عوارض ارزش افزوده:</td><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px; text-align:left;">${inv.vat.toLocaleString('fa-IR')} ریال</td></tr>
1811 + <tr style="background:#eff6ff; font-weight:bold; font-size:12px; color:#1e3a8a;">
1812 + <td style="padding:6px 8px;">مبلغ قابل پرداخت:</td>
1813 + <td style="padding:6px 8px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ریال</td>
1814 + </tr>
1815 + </table>
1816 + </td>
1817 + </tr>
1818 + </table>
1819 +
1820 + <!-- امضا و تایید رسمی -->
1821 + <table style="width:100%; border-collapse:collapse; border:1px solid #1e3a8a; margin-top:8px; text-align:center; font-size:11px;">
1822 + <tr>
1823 + <td style="width:50%; height:75px; vertical-align:top; border:1px solid #1e3a8a; padding:6px; background:#fff;">
1824 + <div style="font-weight:bold;">مهر و امضای فروشنده</div>
1825 + </td>
1826 + <td style="width:50%; height:75px; vertical-align:top; border:1px solid #1e3a8a; padding:6px; background:#fff;">
1827 + <div style="font-weight:bold;">مهر و امضای خریدار</div>
1828 + </td>
1829 + </tr>
1830 + </table>
1831 + ` : `
1832 + <div style="margin-top:14px; text-align:center; font-size:11px; color:#64748b; font-weight:bold;">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>
1833 + `}
1834 + </div>
1835 + `;
1836 + } else {
1837 + // ======================== قالب غیررسمی / پیش‌فاکتور A4 ========================
1838 + containerHtml += `
1839 + <div class="invoice-a4-page" style="background:#fff; padding:8mm 6mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1840 + <!-- سربرگ شکیل پیش‌فاکتور / غیررسمی -->
1841 + <table style="width:100%; border-collapse:collapse; border:2px solid #334155; margin-bottom:6px;">
1842 <tr>
1482 - <td style="width:60%; border:1px solid #000; padding:8px; vertical-align:top;">
1483 - <div><strong>مبلغ به حروف:</strong> ${inv.grandTotal.toLocaleString('fa-IR')} ریال</div>
1484 - <div style="margin-top:6px; font-size:11px; color:#333;">${inv.description || seller.footer || ''}</div>
1843 + <td style="width:30%; border:1px solid #334155; padding:8px; vertical-align:middle;">
1844 + <div style="font-weight:bold; font-size:14px; color:#0f172a;">${seller.name || 'فروشگاه'}</div>
1845 + <div style="font-size:11px; color:#475569; margin-top:2px;">تلفن: ${seller.phone || '—'}</div>
1846 + </td>
1847 + <td style="width:40%; border:1px solid #334155; padding:8px; text-align:center; vertical-align:middle; background:#f8fafc;">
1848 + <h1 style="font-size:16px; margin:0; font-weight:bold; color:#0f172a;">${inv.kind === 'pre_invoice' ? 'پیش‌فاکتور فروش کالا و خدمات' : 'فاکتور فروش کالا و خدمات'}</h1>
1849 </td>
1486 - <td style="width:40%; border:1px solid #000; padding:0;">
1487 - <table style="width:100%; border-collapse:collapse; font-size:11px;">
1488 - <tr><td style="border-bottom:1px solid #000; padding:4px;">قیمت کل:</td><td style="border-bottom:1px solid #000; padding:4px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ریال</td></tr>
1489 - <tr><td style="border-bottom:1px solid #000; padding:4px;">تخفیف:</td><td style="border-bottom:1px solid #000; padding:4px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ریال</td></tr>
1490 - ${inv.vat > 0 ? `<tr><td style="border-bottom:1px solid #000; padding:4px;">مالیات (${inv.vatRate}٪):</td><td style="border-bottom:1px solid #000; padding:4px; text-align:left;">${inv.vat.toLocaleString('fa-IR')} ریال</td></tr>` : ''}
1491 - <tr style="background:#f1f5f9; font-weight:bold; font-size:12px;">
1492 - <td style="padding:6px;">مبلغ کل (ریال):</td>
1493 - <td style="padding:6px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ریال</td>
1494 - </tr>
1495 - </table>
1850 + <td style="width:30%; border:1px solid #334155; padding:8px; font-size:11px; vertical-align:middle; text-align:left;">
1851 + <div>شماره فاکتور: <strong style="font-size:12px;">#${inv.number}</strong></div>
1852 + <div style="margin-top:2px;">تاریخ: <strong>${inv.date}</strong></div>
1853 + <div style="margin-top:2px; color:#64748b; font-size:10px;">صفحه: ${p + 1} از ${totalPages}</div>
1854 </td>
1855 </tr>
1856 </table>
1499 - <table style="width:100%; margin-top:12px; text-align:center; font-size:12px;">
1857 +
1858 + <!-- جعبه مشخصات طرفین -->
1859 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:11px; margin-bottom:6px;">
1860 <tr>
1501 - <td style="width:50%; height:65px; vertical-align:top; border:1px solid #000; padding:6px;">مهر و امضای فروشنده</td>
1502 - <td style="width:50%; height:65px; vertical-align:top; border:1px solid #000; padding:6px;">مهر و امضای خریدار</td>
1861 + <td style="width:50%; border:1px solid #334155; padding:6px; vertical-align:top; background:#f8fafc;">
1862 + <div style="font-weight:bold; color:#334155; margin-bottom:3px;">مشخصات فروشنده:</div>
1863 + <div>نام: <strong>${seller.name || '—'}</strong></div>
1864 + <div>نشانی: ${seller.address || '—'}</div>
1865 + <div>تلفن تماس: ${seller.phone || '—'}</div>
1866 + </td>
1867 + <td style="width:50%; border:1px solid #334155; padding:6px; vertical-align:top; background:#f8fafc;">
1868 + <div style="font-weight:bold; color:#334155; margin-bottom:3px;">مشخصات خریدار:</div>
1869 + <div>نام: <strong>${contact.name || inv.contactName}</strong></div>
1870 + <div>نشانی: ${contact.address || '—'}</div>
1871 + <div>شماره همراه: ${contact.mobile || '—'}</div>
1872 + </td>
1873 </tr>
1874 </table>
1505 - ` : `
1506 - <div style="margin-top:15px; text-align:center; font-size:11px; color:#555;">(ادامه در صفحه بعد...)</div>
1507 - `}
1508 - </div>
1509 - `;
1875 +
1876 + <!-- جدول اقلام فاکتور غیررسمی (۶ ستون) -->
1877 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:11px;">
1878 + <thead>
1879 + <tr style="background:#334155; color:#fff; font-weight:bold; text-align:center;">
1880 + <th style="border:1px solid #334155; padding:6px 4px; width:35px;">ردیف</th>
1881 + <th style="border:1px solid #334155; padding:6px 8px; text-align:right;">شرح کالا | خدمات</th>
1882 + <th style="border:1px solid #334155; padding:6px 4px; width:65px;">واحد</th>
1883 + <th style="border:1px solid #334155; padding:6px 4px; width:65px;">مقدار</th>
1884 + <th style="border:1px solid #334155; padding:6px 4px; width:145px; text-align:left;">قیمت واحد (ریال)</th>
1885 + <th style="border:1px solid #334155; padding:6px 4px; width:160px; text-align:left;">قیمت کل (ریال)</th>
1886 + </tr>
1887 + </thead>
1888 + <tbody>
1889 + ${p > 0 ? `
1890 + <tr style="background:#fef3c7; font-weight:bold; font-size:10px;">
1891 + <td colspan="5" style="border:1px solid #334155; padding:4px; text-align:left;">نقل از صفحه قبل:</td>
1892 + <td style="border:1px solid #334155; padding:4px; text-align:left;">${cumulativeBefore.toLocaleString('fa-IR')} ریال</td>
1893 + </tr>
1894 + ` : ''}
1895 + ${rowsHtml}
1896 + ${!isLastPage ? `
1897 + <tr style="background:#f1f5f9; font-weight:bold; font-size:10px;">
1898 + <td colspan="5" style="border:1px solid #334155; padding:4px; text-align:left;">جمع این صفحه و نقل به صفحه بعد:</td>
1899 + <td style="border:1px solid #334155; padding:4px; text-align:left;">${runningSubtotal.toLocaleString('fa-IR')} ریال</td>
1900 + </tr>
1901 + ` : ''}
1902 + </tbody>
1903 + </table>
1904 +
1905 + ${isLastPage ? `
1906 + <!-- خلاصه فاکتور و امضاها -->
1907 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:11px; margin-top:6px;">
1908 + <tr>
1909 + <td style="width:60%; border:1px solid #334155; padding:8px; vertical-align:top; background:#f8fafc;">
1910 + <div style="margin-bottom:6px;"><strong>مبلغ به حروف:</strong> ${numberToPersianWords(inv.grandTotal)}</div>
1911 + <div style="font-size:10px; color:#475569; line-height:1.6;"><strong>توضیحات:</strong> ${inv.description || seller.footer || 'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.'}</div>
1912 + </td>
1913 + <td style="width:40%; border:1px solid #334155; padding:0;">
1914 + <table style="width:100%; border-collapse:collapse; font-size:11px;">
1915 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px;">قیمت کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px; text-align:left;">${inv.subtotal.toLocaleString('fa-IR')} ریال</td></tr>
1916 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px;">تخفیف:</td><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px; text-align:left;">${inv.discount.toLocaleString('fa-IR')} ریال</td></tr>
1917 + ${inv.vat > 0 ? `<tr><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px;">مالیات ارزش افزوده:</td><td style="border-bottom:1px solid #cbd5e1; padding:4px 8px; text-align:left;">${inv.vat.toLocaleString('fa-IR')} ریال</td></tr>` : ''}
1918 + <tr style="background:#f1f5f9; font-weight:bold; font-size:12px;">
1919 + <td style="padding:6px 8px;">مبلغ کل (ریال):</td>
1920 + <td style="padding:6px 8px; text-align:left;">${inv.grandTotal.toLocaleString('fa-IR')} ریال</td>
1921 + </tr>
1922 + </table>
1923 + </td>
1924 + </tr>
1925 + </table>
1926 +
1927 + <table style="width:100%; border-collapse:collapse; border:1px solid #334155; margin-top:8px; text-align:center; font-size:11px;">
1928 + <tr>
1929 + <td style="width:50%; height:75px; vertical-align:top; border:1px solid #334155; padding:6px; background:#fff;">
1930 + <div style="font-weight:bold;">مهر و امضای فروشنده</div>
1931 + </td>
1932 + <td style="width:50%; height:75px; vertical-align:top; border:1px solid #334155; padding:6px; background:#fff;">
1933 + <div style="font-weight:bold;">مهر و امضای خریدار</div>
1934 + </td>
1935 + </tr>
1936 + </table>
1937 + ` : `
1938 + <div style="margin-top:14px; text-align:center; font-size:11px; color:#64748b; font-weight:bold;">(ادامه در صفحه بعد...)</div>
1939 + `}
1940 + </div>
1941 + `;
1942 + }
1943 }
1944
1945 const printContainer = document.getElementById('printable-invoice');
@@ -1529,7 +1962,7 @@
1962 if (!name) { alert('عنوان کالا الزامی است.'); return; }
1963
1964 datastore.products.push({ id: 'P_' + Date.now(), code, name, spec, type, unit, buy_price, sale_price, stock: 0 });
1532 - persistDatastore();
1965 + saveDatastore();
1966 alert('کالا ثبت شد.');
1967 document.getElementById('prod-name-input').value = '';
1968 document.getElementById('prod-spec-input').value = '';
@@ -1553,7 +1986,7 @@
1986 function deleteProduct(id) {
1987 if (confirm('حذف شود؟')) {
1988 datastore.products = datastore.products.filter(p => p.id !== id);
1556 - persistDatastore();
1989 + saveDatastore();
1990 refreshAllSurfaces();
1991 }
1992 }
@@ -1571,7 +2004,7 @@
2004
2005 const newId = 'P_' + Date.now();
2006 datastore.products.push({ id: newId, code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good' });
1574 - persistDatastore();
2007 + saveDatastore();
2008 closeQuickProductModal();
2009 refreshAllSurfaces();
2010 addInvoiceItemRow(newId, 1, price);
@@ -1613,7 +2046,7 @@
2046 });
2047 }
2048 });
1616 - persistDatastore();
2049 + saveDatastore();
2050 refreshAllSurfaces();
2051 alert('کالاها ایمپورت شدند.');
2052 } catch(err) { alert('خطا در فایل اکسل!'); }
@@ -1624,7 +2057,7 @@
2057 // ۴. اشخاص
2058 function commitSaveContact() {
2059 const entity_type = document.getElementById('contact-entity-type').value;
1627 - const custom_prefix = entity_type === 'natural' ? document.getElementById('contact-prefix-select').value : '';
2060 + const custom_prefix = entity_type === 'natural' ? document.getElementById('contact-prefix-select')?.value : '';
2061 const raw_name = document.getElementById('contact-name-input').value;
2062 const role = document.getElementById('contact-role-input').value;
2063 const mobile = document.getElementById('contact-mobile-input').value;
@@ -1634,11 +2067,11 @@
2067 const postal_code = document.getElementById('contact-postal-input').value;
2068 const address = document.getElementById('contact-address-input').value;
2069
1637 - if (!raw_name) { alert('نام طرف حساب الزامی است.'); return; }
2070 + if (!raw_name.trim()) { alert('نام طرف حساب الزامی است.'); return; }
2071
2072 const formatted_name = formatEntityName(raw_name, entity_type, custom_prefix);
2073 datastore.contacts.push({ id: 'C_' + Date.now(), entity_type, name: formatted_name, role, mobile, national_id, economic_code, reg_number, postal_code, address, balance: 0 });
1641 - persistDatastore();
2074 + saveDatastore();
2075 alert('طرف حساب ثبت شد.');
2076 document.getElementById('contact-name-input').value = '';
2077 refreshAllSurfaces();
@@ -1663,28 +2096,26 @@
2096 `).join('');
2097
2098 const options = datastore.contacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
1666 - invSelect.innerHTML = options;
1667 - chqSelect.innerHTML = options;
2099 + if (invSelect) invSelect.innerHTML = options;
2100 + if (chqSelect) chqSelect.innerHTML = options;
2101 }
2102
2103 function deleteContact(id) {
2104 if (confirm('حذف شود؟')) {
2105 datastore.contacts = datastore.contacts.filter(c => c.id !== id);
1673 - persistDatastore();
2106 + saveDatastore();
2107 refreshAllSurfaces();
2108 }
2109 }
2110
1678 - function openQuickContactModal() { document.getElementById('modal-quick-contact').classList.add('active'); }
2111 + function openQuickContactModal() { document.getElementById('modal-quick-contact').classList.add('active'); handleQuickCEntityChange(); }
2112 function closeQuickContactModal() { document.getElementById('modal-quick-contact').classList.remove('active'); }
1680 - function handleQuickCEntityChange() {
1681 - document.getElementById('box-quick-c-prefix').style.display = document.getElementById('quick-c-entity').value === 'natural' ? 'block' : 'none';
1682 - }
2113 +
2114 function saveQuickContact() {
2115 const entity_type = document.getElementById('quick-c-entity').value;
1685 - const prefix = entity_type === 'natural' ? document.getElementById('quick-c-prefix').value : '';
2116 + const prefix = entity_type === 'natural' ? document.getElementById('quick-c-prefix')?.value : '';
2117 const raw_name = document.getElementById('quick-c-name').value;
1687 - if (!raw_name) { alert('نام الزامی است.'); return; }
2118 + if (!raw_name.trim()) { alert('نام الزامی است.'); return; }
2119
2120 const newId = 'C_' + Date.now();
2121 datastore.contacts.push({
@@ -1699,7 +2130,7 @@
2130 address: document.getElementById('quick-c-address').value,
2131 balance: 0
2132 });
1702 - persistDatastore();
2133 + saveDatastore();
2134 closeQuickContactModal();
2135 refreshAllSurfaces();
2136 document.getElementById('invoice-contact-id').value = newId;
@@ -1744,7 +2175,7 @@
2175 });
2176 }
2177 });
1747 - persistDatastore();
2178 + saveDatastore();
2179 refreshAllSurfaces();
2180 alert('اشخاص ایمپورت شدند.');
2181 } catch(err) { alert('خطا در فایل اکسل!'); }
@@ -1762,7 +2193,7 @@
2193 const amount = parseFloat(document.getElementById('chq-amount-input').value) || 0;
2194 if (!sayad_id || amount <= 0) { alert('اطلاعات چک نامعتبر است.'); return; }
2195 datastore.cheques.push({ id: 'CHQ_' + Date.now(), direction, contactName, sayad_id, bank, amount, due_date: document.getElementById('chq-due-input').value, status: document.getElementById('chq-status-input').value });
1765 - persistDatastore();
2196 + saveDatastore();
2197 alert('چک ثبت شد.');
2198 refreshAllSurfaces();
2199 }
@@ -1775,7 +2206,7 @@
2206 const amount = parseFloat(document.getElementById('trx-amount-input').value) || 0;
2207 if (amount <= 0) { alert('مبلغ معتبر نیست.'); return; }
2208 datastore.expenses.push({ id: 'TRX_' + Date.now(), kind: document.getElementById('trx-kind-input').value, category: document.getElementById('trx-category-input').value, amount, desc: document.getElementById('trx-desc-input').value });
1778 - persistDatastore();
2209 + saveDatastore();
2210 alert('سند ثبت شد.');
2211 refreshAllSurfaces();
2212 }
@@ -1789,7 +2220,7 @@
2220 function commitSaveCompany() {
2221 const entity_type = document.getElementById('company-entity-type').value;
2222 const raw_name = document.getElementById('company-name-input').value;
1792 - if (!raw_name) { alert('نام شرکت الزامی است.'); return; }
2223 + if (!raw_name.trim()) { alert('نام شرکت الزامی است.'); return; }
2224
2225 const newComp = {
2226 id: 'COMP_' + Date.now(),
@@ -1811,8 +2242,8 @@
2242 }
2243 datastore.default_settings.default_company_id = newComp.id;
2244
1814 - persistDatastore();
1815 - alert('شرکت با موفقیت ثبت و ذخیره شد.');
2245 + saveDatastore();
2246 + alert('شرکت با موفقیت ثبت و ذخیره شد و به عنوان فروشنده پیش‌فرض تنظیم گردید.');
2247 document.getElementById('company-name-input').value = '';
2248 document.getElementById('company-phone-input').value = '';
2249 document.getElementById('company-national-input').value = '';
@@ -1861,7 +2292,7 @@
2292 function setDefaultCompany(id) {
2293 if (!datastore.default_settings) datastore.default_settings = {};
2294 datastore.default_settings.default_company_id = id;
1864 - persistDatastore();
2295 + saveDatastore();
2296 refreshAllSurfaces();
2297 }
2298
@@ -1871,7 +2302,7 @@
2302 if (datastore.default_settings?.default_company_id === id) {
2303 datastore.default_settings.default_company_id = datastore.companies[0]?.id || null;
2304 }
1874 - persistDatastore();
2305 + saveDatastore();
2306 refreshAllSurfaces();
2307 }
2308 }
@@ -1898,7 +2329,7 @@
2329 if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
2330 datastore.default_settings.default_company_id = datastore.companies[0].id;
2331 }
1901 - persistDatastore();
2332 + saveDatastore();
2333 refreshAllSurfaces();
2334 alert('اطلاعات بازگردانی شد.');
2335 } catch(err) { alert('فایل نامعتبر است.'); }
@@ -1906,6 +2337,46 @@
2337 reader.readAsText(file);
2338 }
2339
2340 + // تبدیل ارقام به حروف فارسی استاندارد
2341 + function numberToPersianWords(num) {
2342 + if (!num || isNaN(num) || num == 0) return 'صفر ریال';
2343 + const yegan = ["", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"];
2344 + const dahgan = ["", "", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"];
2345 + const dah_ta_bist = ["ده", "یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"];
2346 + const sadgan = ["", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"];
2347 + const part_names = ["", "هزار", "میلیون", "میلیارد", "تریلیون"];
2348 +
2349 + function threeDigitToWords(n) {
2350 + let c = Math.floor(n / 100);
2351 + let d = Math.floor((n % 100) / 10);
2352 + let y = n % 10;
2353 + let parts = [];
2354 + if (c > 0) parts.push(sadgan[c]);
2355 + if (d === 1) {
2356 + parts.push(dah_ta_bist[y]);
2357 + } else {
2358 + if (d > 1) parts.push(dahgan[d]);
2359 + if (y > 0) parts.push(yegan[y]);
2360 + }
2361 + return parts.join(" و ");
2362 + }
2363 +
2364 + let parts = [];
2365 + let chunkIdx = 0;
2366 + let temp = Math.abs(Math.round(num));
2367 + while (temp > 0) {
2368 + let chunk = temp % 1000;
2369 + if (chunk > 0) {
2370 + let w = threeDigitToWords(chunk);
2371 + if (part_names[chunkIdx]) w += " " + part_names[chunkIdx];
2372 + parts.unshift(w);
2373 + }
2374 + temp = Math.floor(temp / 1000);
2375 + chunkIdx++;
2376 + }
2377 + return parts.join(" و ") + " ریال";
2378 + }
2379 +
2380 window.addEventListener('DOMContentLoaded', () => {
2381 initAuthSystem();
2382 });