@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / ac6ca6b
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 22:54 UTC ac6ca6ba850efdddd0500c80346ccc5b7ee3d00e
1 file changed +840 -1
index.html
+840 -1
@@ -1709,4 +1709,843 @@
1709 </tr>
1710 `).join('');
1711
1712 - const
1712 + const sellerIds = `${seller.national_id || '—'} / ${seller.reg_number || '—'}`;
1713 + const contactIds = `${contact.national_id || '—'} / ${contact.reg_number || '—'}`;
1714 + const cumSub = opt.cumulativeSubtotal || 0;
1715 + const cumDisc = opt.cumulativeDiscount || 0;
1716 + const cumVat = opt.cumulativeVat || 0;
1717 + const cumNet = opt.cumulativeNet || 0;
1718 + const subtotalLabel = isLast ? 'جمع کل اقلام:' : 'جمع اقلام تا این صفحه:';
1719 + const discountLabel = isLast ? 'مجموع تخفیف:' : 'مجموع تخفیف تا این صفحه:';
1720 + const vatLabel = isLast ? 'مالیات و عوارض ارزش افزوده:' : 'مالیات تا این صفحه:';
1721 + const netLabel = isLast ? 'مبلغ قابل پرداخت:' : 'جمع تا این صفحه:';
1722 + const wordsLabel = isLast ? 'مبلغ کل به حروف:' : 'مبلغ تا این صفحه به حروف:';
1723 +
1724 + const summaryBox = `
1725 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10.5px; margin-top:3px;">
1726 + <tr>
1727 + <td style="width:60%; border:1px solid #1e3a8a; padding:6px; vertical-align:top; background:#f8fafc;">
1728 + <div style="margin-bottom:4px;"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet, cur)}</div>
1729 + ${isLast ? `
1730 + <div style="margin-bottom:4px;"><strong>شرایط و نحوه پرداخت:</strong> نقدی ☑ &nbsp;&nbsp;&nbsp; غیرنقدی (نسیه/چک) ☐</div>
1731 + <div style="font-size:9.5px; color:#475569; line-height:1.5;"><strong>توضیحات:</strong> ${inv.description || seller.footer || 'تحویل کالا منوط به تسویه نهایی می‌باشد.'}</div>
1732 + ` : `
1733 + <div style="font-size:9.5px; color:#64748b; margin-top:4px;">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>
1734 + `}
1735 + </td>
1736 + <td style="width:40%; border:1px solid #1e3a8a; padding:0;">
1737 + <table style="width:100%; border-collapse:collapse; font-size:10.5px;">
1738 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">${subtotalLabel}</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${cumSub.toLocaleString('fa-IR')} ${cur}</td></tr>
1739 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">${discountLabel}</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${cumDisc.toLocaleString('fa-IR')} ${cur}</td></tr>
1740 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">${vatLabel}</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${cumVat.toLocaleString('fa-IR')} ${cur}</td></tr>
1741 + <tr style="background:#eff6ff; font-weight:bold; font-size:11.5px; color:#1e3a8a;">
1742 + <td style="padding:5px 8px;">${netLabel}</td>
1743 + <td style="padding:5px 8px; text-align:left;">${cumNet.toLocaleString('fa-IR')} ${cur}</td>
1744 + </tr>
1745 + </table>
1746 + </td>
1747 + </tr>
1748 + </table>
1749 + `;
1750 +
1751 + const signatures = isLast ? `
1752 + <table style="width:100%; border-collapse:collapse; border:1px solid #1e3a8a; margin-top:6px; text-align:center; font-size:10.5px;">
1753 + <tr>
1754 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #1e3a8a; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای فروشنده</div></td>
1755 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #1e3a8a; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای خریدار</div></td>
1756 + </tr>
1757 + </table>
1758 + ` : '';
1759 +
1760 + return `
1761 + <div class="invoice-a4-page landscape" style="background:#fff; padding:6mm 8mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1762 + <table style="width:100%; border-collapse:collapse; border:2px solid #1e3a8a; margin-bottom:3px;">
1763 + <tr>
1764 + <td style="width:28%; border:1px solid #1e3a8a; padding:5px; font-size:11px; vertical-align:middle;">
1765 + <div style="font-weight:bold; font-size:13px; color:#1e3a8a;">${seller.name || 'فروشگاه'}</div>
1766 + <div style="font-size:9.5px; color:#475569; margin-top:1px;">صادرکننده فاکتور رسمی</div>
1767 + </td>
1768 + <td style="width:44%; border:1px solid #1e3a8a; padding:6px; text-align:center; vertical-align:middle; background:#eff6ff;">
1769 + <h1 style="font-size:15px; margin:0; font-weight:bold; color:#1e3a8a;">صورتحساب فروش کالا و خدمات</h1>
1770 + <div style="font-size:10px; margin-top:2px;">(ماده ۱۶۹ مکرر قانون مالیات‌های مستقیم)</div>
1771 + </td>
1772 + <td style="width:28%; border:1px solid #1e3a8a; padding:5px; font-size:10.5px; vertical-align:middle; text-align:left;">
1773 + <div>شماره سریال: <strong style="color:#b91c1c;">${inv.number}</strong></div>
1774 + <div style="margin-top:1px;">تاریخ صدور: <strong>${inv.date}</strong></div>
1775 + <div style="margin-top:1px; color:#64748b; font-size:9.5px;">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1776 + </td>
1777 + </tr>
1778 + </table>
1779 +
1780 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px; margin-bottom:3px;">
1781 + <tr style="background:#f8fafc; font-weight:bold;"><td colspan="4" style="border:1px solid #1e3a8a; padding:2px 6px; color:#1e3a8a;">الف) مشخصات فروشنده</td></tr>
1782 + <tr>
1783 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">نام شخص حقیقی/حقوقی:</td>
1784 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;"><strong>${seller.name || '—'}</strong></td>
1785 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">شماره اقتصادی:</td>
1786 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;">${seller.economic_code || '—'}</td>
1787 + </tr>
1788 + <tr>
1789 + <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">شناسه ملی / شماره ثبت:</td>
1790 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${sellerIds}</td>
1791 + <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">کد پستی ۱۰ رقمی:</td>
1792 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${seller.postal_code || '—'}</td>
1793 + </tr>
1794 + <tr>
1795 + <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">نشانی و تلفن:</td>
1796 + <td colspan="3" style="border:1px solid #cbd5e1; padding:3px 6px;">${seller.address || '—'} ${seller.phone ? ' | تلفن: ' + seller.phone : ''}</td>
1797 + </tr>
1798 + </table>
1799 +
1800 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px; margin-bottom:3px;">
1801 + <tr style="background:#f8fafc; font-weight:bold;"><td colspan="4" style="border:1px solid #1e3a8a; padding:2px 6px; color:#1e3a8a;">ب) مشخصات خریدار</td></tr>
1802 + <tr>
1803 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">نام شخص حقیقی/حقوقی:</td>
1804 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;"><strong>${contact.name || inv.contactName}</strong></td>
1805 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:15%; background:#f1f5f9;">شماره اقتصادی:</td>
1806 + <td style="border:1px solid #cbd5e1; padding:3px 6px; width:35%;">${contact.economic_code || '—'}</td>
1807 + </tr>
1808 + <tr>
1809 + <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">شناسه ملی / شماره ثبت:</td>
1810 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${contactIds}</td>
1811 + <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">کد پستی ۱۰ رقمی:</td>
1812 + <td style="border:1px solid #cbd5e1; padding:3px 6px;">${contact.postal_code || '—'}</td>
1813 + </tr>
1814 + <tr>
1815 + <td style="border:1px solid #cbd5e1; padding:3px 6px; background:#f1f5f9;">نشانی و تلفن:</td>
1816 + <td colspan="3" style="border:1px solid #cbd5e1; padding:3px 6px;">${contact.address || '—'} ${contact.mobile ? ' | همراه: ' + contact.mobile : ''}</td>
1817 + </tr>
1818 + </table>
1819 +
1820 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px;">
1821 + <thead>
1822 + <tr style="background:#1e3a8a; color:#fff; font-weight:bold; text-align:center;">
1823 + <th style="border:1px solid #1e3a8a; padding:4px; width:28px;">ردیف</th>
1824 + <th style="border:1px solid #1e3a8a; padding:4px 6px; text-align:right;">شرح کالا یا خدمات</th>
1825 + <th style="border:1px solid #1e3a8a; padding:4px; width:42px;">تعداد</th>
1826 + <th style="border:1px solid #1e3a8a; padding:4px; width:42px;">واحد</th>
1827 + <th style="border:1px solid #1e3a8a; padding:4px; width:105px;">مبلغ واحد (${cur})</th>
1828 + <th style="border:1px solid #1e3a8a; padding:4px; width:110px;">مبلغ کل (${cur})</th>
1829 + <th style="border:1px solid #1e3a8a; padding:4px; width:80px;">تخفیف (${cur})</th>
1830 + <th style="border:1px solid #1e3a8a; padding:4px; width:90px;">مالیات (${cur})</th>
1831 + <th style="border:1px solid #1e3a8a; padding:4px; width:120px;">مبلغ نهایی (${cur})</th>
1832 + </tr>
1833 + </thead>
1834 + <tbody>
1835 + ${!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>` : ''}
1836 + ${rowsHtml}
1837 + </tbody>
1838 + </table>
1839 + ${summaryBox}
1840 + ${signatures}
1841 + </div>`;
1842 +}
1843 +
1844 +function buildNonFormalPage(items, seller, contact, inv, opt) {
1845 + const cur = inv.currencyLabel || 'ریال';
1846 + const isPre = inv.kind === 'pre_invoice';
1847 + const isLast = opt.isLastPage;
1848 + const hasVat = isPre && inv.vat > 0;
1849 + const title = isPre ? 'پیش‌فاکتور فروش کالا و خدمات' : 'فاکتور فروش کالا و خدمات';
1850 +
1851 + const rowsHtml = items.map(li => hasVat ? `
1852 + <tr style="text-align:center;">
1853 + <td style="border:1px solid #334155; padding:3px 5px; font-size:10px;">${li.rowNo.toLocaleString('fa-IR')}</td>
1854 + <td style="border:1px solid #334155; padding:3px 6px; text-align:right; font-size:10px; font-weight:600;">${li.prodName}</td>
1855 + <td style="border:1px solid #334155; padding:3px 5px; font-size:10px;">${li.unit}</td>
1856 + <td style="border:1px solid #334155; padding:3px 5px; font-size:10px;">${li.qty.toLocaleString('fa-IR')}</td>
1857 + <td style="border:1px solid #334155; padding:3px 5px; text-align:left; font-size:10px;">${li.price.toLocaleString('fa-IR')}</td>
1858 + <td style="border:1px solid #334155; padding:3px 5px; text-align:left; font-size:10px;">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1859 + <td style="border:1px solid #334155; padding:3px 5px; text-align:left; font-size:10px;">${li.lineVat.toLocaleString('fa-IR')}</td>
1860 + <td style="border:1px solid #334155; padding:3px 5px; text-align:left; font-size:10px; font-weight:bold;">${li.lineNet.toLocaleString('fa-IR')}</td>
1861 + </tr>
1862 + ` : `
1863 + <tr style="text-align:center;">
1864 + <td style="border:1px solid #334155; padding:4px 5px; font-size:10.5px;">${li.rowNo.toLocaleString('fa-IR')}</td>
1865 + <td style="border:1px solid #334155; padding:4px 8px; text-align:right; font-size:10.5px; font-weight:600;">${li.prodName}</td>
1866 + <td style="border:1px solid #334155; padding:4px 5px; font-size:10.5px;">${li.unit}</td>
1867 + <td style="border:1px solid #334155; padding:4px 5px; font-size:10.5px;">${li.qty.toLocaleString('fa-IR')}</td>
1868 + <td style="border:1px solid #334155; padding:4px 5px; text-align:left; font-size:10.5px;">${li.price.toLocaleString('fa-IR')}</td>
1869 + <td style="border:1px solid #334155; padding:4px 5px; text-align:left; font-size:10.5px; font-weight:bold;">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1870 + </tr>
1871 + `).join('');
1872 +
1873 + const cumSub = opt.cumulativeSubtotal || 0;
1874 + const cumDisc = opt.cumulativeDiscount || 0;
1875 + const cumVat = opt.cumulativeVat || 0;
1876 + const cumNet = opt.cumulativeNet || 0;
1877 +
1878 + const subtotalLabel = isLast ? 'قیمت کل اقلام:' : 'جمع اقلام تا این صفحه:';
1879 + const discountLabel = isLast ? 'تخفیف:' : 'تخفیف تا این صفحه:';
1880 + const vatLabel = isLast ? 'مالیات ارزش افزوده:' : 'مالیات تا این صفحه:';
1881 + const netLabel = isLast ? `مبلغ کل (${cur}):` : 'جمع تا این صفحه:';
1882 + const wordsLabel = isLast ? 'مبلغ به حروف:' : 'مبلغ تا این صفحه به حروف:';
1883 +
1884 + const summaryBox = `
1885 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px; margin-top:5px;">
1886 + <tr>
1887 + <td style="width:60%; border:1px solid #334155; padding:6px; vertical-align:top; background:#f8fafc;">
1888 + <div style="margin-bottom:4px;"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet, cur)}</div>
1889 + ${isLast ? `
1890 + <div style="font-size:9.5px; color:#475569; line-height:1.5;"><strong>توضیحات:</strong> ${inv.description || seller.footer || (isPre ? 'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.' : 'از خرید شما سپاسگزاریم.')}</div>
1891 + ` : `
1892 + <div style="font-size:9.5px; color:#64748b;">(ادامه در صفحه بعد...)</div>
1893 + `}
1894 + </td>
1895 + <td style="width:40%; border:1px solid #334155; padding:0;">
1896 + <table style="width:100%; border-collapse:collapse; font-size:10.5px;">
1897 + <tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">${subtotalLabel}</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${cumSub.toLocaleString('fa-IR')} ${cur}</td></tr>
1898 + ${cumDisc > 0 || inv.discount > 0 ? `<tr><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;">${discountLabel}</td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;">${cumDisc.toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1899 + ${hasVat ? `<tr style="background:#fffbeb;"><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px;"><strong>${vatLabel}</strong></td><td style="border-bottom:1px solid #cbd5e1; padding:3px 8px; text-align:left;"><strong>${cumVat.toLocaleString('fa-IR')} ${cur}</strong></td></tr>` : ''}
1900 + <tr style="background:#f1f5f9; font-weight:bold; font-size:11.5px;">
1901 + <td style="padding:5px 8px;">${netLabel}</td>
1902 + <td style="padding:5px 8px; text-align:left;">${cumNet.toLocaleString('fa-IR')} ${cur}</td>
1903 + </tr>
1904 + </table>
1905 + </td>
1906 + </tr>
1907 + </table>
1908 + `;
1909 +
1910 + const signatures = isLast ? `
1911 + <table style="width:100%; border-collapse:collapse; border:1px solid #334155; margin-top:6px; text-align:center; font-size:10.5px;">
1912 + <tr>
1913 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #334155; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای فروشنده</div></td>
1914 + <td style="width:50%; height:50px; vertical-align:top; border:1px solid #334155; padding:5px; background:#fff;"><div style="font-weight:bold;">مهر و امضای خریدار</div></td>
1915 + </tr>
1916 + </table>
1917 + ` : '';
1918 +
1919 + return `
1920 + <div class="invoice-a4-page landscape" style="background:#fff; padding:7mm 8mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
1921 + <table style="width:100%; border-collapse:collapse; border:2px solid #334155; margin-bottom:5px;">
1922 + <tr>
1923 + <td style="width:30%; border:1px solid #334155; padding:6px; vertical-align:middle;">
1924 + <div style="font-weight:bold; font-size:13px; color:#0f172a;">${seller.name || 'فروشگاه'}</div>
1925 + <div style="font-size:10px; color:#475569; margin-top:1px;">تلفن: ${seller.phone || '—'}</div>
1926 + </td>
1927 + <td style="width:40%; border:1px solid #334155; padding:6px; text-align:center; vertical-align:middle; background:#f8fafc;">
1928 + <h1 style="font-size:15px; margin:0; font-weight:bold; color:#0f172a;">${title}</h1>
1929 + </td>
1930 + <td style="width:30%; border:1px solid #334155; padding:6px; font-size:10.5px; vertical-align:middle; text-align:left;">
1931 + <div>شماره: <strong style="font-size:11.5px;">#${inv.number}</strong></div>
1932 + <div style="margin-top:1px;">تاریخ: <strong>${inv.date}</strong></div>
1933 + <div style="margin-top:1px; color:#64748b; font-size:9.5px;">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1934 + </td>
1935 + </tr>
1936 + </table>
1937 +
1938 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px; margin-bottom:5px;">
1939 + <tr>
1940 + <td style="width:50%; border:1px solid #334155; padding:5px; vertical-align:top; background:#f8fafc;">
1941 + <div style="font-weight:bold; color:#334155; margin-bottom:2px;">مشخصات فروشنده:</div>
1942 + <div>نام: <strong>${seller.name || '—'}</strong></div>
1943 + <div>نشانی: ${seller.address || '—'}</div>
1944 + <div>تلفن تماس: ${seller.phone || '—'}</div>
1945 + </td>
1946 + <td style="width:50%; border:1px solid #334155; padding:5px; vertical-align:top; background:#f8fafc;">
1947 + <div style="font-weight:bold; color:#334155; margin-bottom:2px;">مشخصات خریدار:</div>
1948 + <div>نام: <strong>${contact.name || inv.contactName}</strong></div>
1949 + <div>نشانی: ${contact.address || '—'}</div>
1950 + <div>شماره همراه: ${contact.mobile || '—'}</div>
1951 + </td>
1952 + </tr>
1953 + </table>
1954 +
1955 + <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px;">
1956 + <thead>
1957 + <tr style="background:#334155; color:#fff; font-weight:bold; text-align:center;">
1958 + <th style="border:1px solid #334155; padding:5px 4px; width:32px;">ردیف</th>
1959 + <th style="border:1px solid #334155; padding:5px 8px; text-align:right;">شرح کالا | خدمات</th>
1960 + <th style="border:1px solid #334155; padding:5px 4px; width:60px;">واحد</th>
1961 + <th style="border:1px solid #334155; padding:5px 4px; width:60px;">مقدار</th>
1962 + <th style="border:1px solid #334155; padding:5px 4px; width:${hasVat ? '110' : '150'}px; text-align:left;">قیمت واحد (${cur})</th>
1963 + <th style="border:1px solid #334155; padding:5px 4px; width:${hasVat ? '120' : '170'}px; text-align:left;">قیمت کل (${cur})</th>
1964 + ${hasVat ? `<th style="border:1px solid #334155; padding:5px 4px; width:110px; text-align:left;">مالیات (${cur})</th><th style="border:1px solid #334155; padding:5px 4px; width:130px; text-align:left;">مبلغ نهایی (${cur})</th>` : ''}
1965 + </tr>
1966 + </thead>
1967 + <tbody>
1968 + ${!opt.isFirstPage ? `<tr style="background:#fef3c7; font-weight:bold; font-size:9.5px;"><td colspan="${hasVat ? 6 : 5}" style="border:1px solid #334155; padding:3px; text-align:left;">نقل از صفحه قبل:</td><td colspan="${hasVat ? 2 : 1}" style="border:1px solid #334155; padding:3px; text-align:left;">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1969 + ${rowsHtml}
1970 + </tbody>
1971 + </table>
1972 + ${summaryBox}
1973 + ${signatures}
1974 + </div>`;
1975 +}
1976 +
1977 +function renderAndPrintDirect(invId) {
1978 + const inv = getMyInvoices().find(i => i.id === invId);
1979 + if (!inv) return;
1980 + const myCompanies = getMyCompanies();
1981 + const myContacts = getMyContacts();
1982 + const seller = myCompanies.find(c => c.id === inv.companyId) || myCompanies[0] || {};
1983 + const contact = myContacts.find(c => c.id === inv.contactId) || {};
1984 + const isFormal = (inv.kind === 'formal');
1985 + const builder = isFormal ? buildFormalPage : buildNonFormalPage;
1986 +
1987 + const allLines = computeInvoiceLines(inv);
1988 + const pageGroups = [];
1989 + let cumulativeSub = 0, cumulativeDisc = 0, cumulativeVat = 0;
1990 + for (let start = 0; start < allLines.length; start += MAX_ROWS_PER_PAGE) {
1991 + const pageItems = allLines.slice(start, start + MAX_ROWS_PER_PAGE);
1992 + const isFirstPage = (start === 0);
1993 + const isLastPage = (start + MAX_ROWS_PER_PAGE >= allLines.length);
1994 + const pageSub = pageItems.reduce((s, li) => s + li.lineSubtotal, 0);
1995 + const pageDisc = pageItems.reduce((s, li) => s + li.lineDiscount, 0);
1996 + const pageVat = pageItems.reduce((s, li) => s + li.lineVat, 0);
1997 + const cumSubAfter = cumulativeSub + pageSub;
1998 + const cumDiscAfter = cumulativeDisc + pageDisc;
1999 + const cumVatAfter = cumulativeVat + pageVat;
2000 + const cumNetAfter = cumSubAfter - cumDiscAfter + cumVatAfter;
2001 + pageGroups.push({
2002 + items: pageItems,
2003 + isFirstPage,
2004 + isLastPage,
2005 + cumulativeBefore: cumulativeSub,
2006 + cumulativeSubtotal: cumSubAfter,
2007 + cumulativeDiscount: cumDiscAfter,
2008 + cumulativeVat: cumVatAfter,
2009 + cumulativeNet: cumNetAfter
2010 + });
2011 + cumulativeSub = cumSubAfter;
2012 + cumulativeDisc = cumDiscAfter;
2013 + cumulativeVat = cumVatAfter;
2014 + }
2015 + const totalPages = pageGroups.length;
2016 + const containerHtml = pageGroups.map((g, idx) =>
2017 + builder(g.items, seller, contact, inv, {
2018 + pageNum: idx + 1, totalPages,
2019 + isFirstPage: g.isFirstPage, isLastPage: g.isLastPage,
2020 + cumulativeBefore: g.cumulativeBefore,
2021 + cumulativeSubtotal: g.cumulativeSubtotal,
2022 + cumulativeDiscount: g.cumulativeDiscount,
2023 + cumulativeVat: g.cumulativeVat,
2024 + cumulativeNet: g.cumulativeNet
2025 + })
2026 + ).join('');
2027 +
2028 + let orientationStyle = document.getElementById('dynamic-print-orientation');
2029 + if (!orientationStyle) {
2030 + orientationStyle = document.createElement('style');
2031 + orientationStyle.id = 'dynamic-print-orientation';
2032 + document.head.appendChild(orientationStyle);
2033 + }
2034 + orientationStyle.innerHTML = `@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
2035 +
2036 + const printContainer = document.getElementById('printable-invoice');
2037 + printContainer.innerHTML = containerHtml;
2038 + printContainer.style.display = 'block';
2039 + window.print();
2040 + printContainer.style.display = 'none';
2041 +}
2042 +
2043 +function commitSaveProduct() {
2044 + if (!currentUser) return;
2045 + const myProducts = getMyProducts();
2046 + const code = document.getElementById('prod-code-input').value || (myProducts.length + 1).toString();
2047 + const name = document.getElementById('prod-name-input').value;
2048 + const spec = document.getElementById('prod-spec-input').value || '';
2049 + const unit = document.getElementById('prod-unit-input').value || 'عدد';
2050 + const buy_price = parseFloat(document.getElementById('prod-buy-input').value) || 0;
2051 + const sale_price = parseFloat(document.getElementById('prod-sale-input').value) || 0;
2052 + if (!name) { alert('عنوان کالا الزامی است.'); return; }
2053 + datastore.products.push({
2054 + id: 'P_' + Date.now(), ownerUserId: currentUser.id,
2055 + code, name, spec, type: 'good', unit, buy_price, sale_price, stock: 0
2056 + });
2057 + saveDatastore();
2058 + alert('کالا ثبت شد.');
2059 + document.getElementById('prod-name-input').value = '';
2060 + document.getElementById('prod-spec-input').value = '';
2061 + refreshAllSurfaces();
2062 +}
2063 +
2064 +function renderProducts() {
2065 + const tbody = document.getElementById('products-catalog-table-body');
2066 + const myProducts = getMyProducts();
2067 + if (myProducts.length === 0) {
2068 + tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ کالایی ثبت نشده است.</td></tr>';
2069 + return;
2070 + }
2071 + tbody.innerHTML = myProducts.map(p => `
2072 + <tr>
2073 + <td>${p.code}</td>
2074 + <td><strong>${p.name}</strong></td>
2075 + <td>${p.spec || '—'}</td>
2076 + <td>${p.unit}</td>
2077 + <td>${p.sale_price.toLocaleString('fa-IR')}</td>
2078 + <td><button class="btn btn-danger btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="deleteProduct('${p.id}')">حذف</button></td>
2079 + </tr>`).join('');
2080 +}
2081 +
2082 +function deleteProduct(id) {
2083 + if (!currentUser) return;
2084 + if (confirm('حذف شود؟')) {
2085 + datastore.products = datastore.products.filter(p => !(p.id === id && p.ownerUserId === currentUser.id));
2086 + saveDatastore();
2087 + refreshAllSurfaces();
2088 + }
2089 +}
2090 +
2091 +function openQuickProductModal() { document.getElementById('modal-quick-product').classList.add('active'); }
2092 +function closeQuickProductModal() { document.getElementById('modal-quick-product').classList.remove('active'); }
2093 +
2094 +function saveQuickProduct() {
2095 + if (!currentUser) return;
2096 + const myProducts = getMyProducts();
2097 + const code = document.getElementById('quick-p-code').value || (myProducts.length + 1).toString();
2098 + const name = document.getElementById('quick-p-name').value;
2099 + const spec = document.getElementById('quick-p-spec').value || '';
2100 + const unit = document.getElementById('quick-p-unit').value || 'عدد';
2101 + const price = parseFloat(document.getElementById('quick-p-price').value) || 0;
2102 + if (!name) { alert('عنوان کالا الزامی است.'); return; }
2103 + const newId = 'P_' + Date.now();
2104 + datastore.products.push({
2105 + id: newId, ownerUserId: currentUser.id,
2106 + code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good'
2107 + });
2108 + saveDatastore();
2109 + closeQuickProductModal();
2110 + refreshAllSurfaces();
2111 + addInvoiceItemRow(newId, 1, price);
2112 +}
2113 +
2114 +function downloadProductsExcelTemplate() {
2115 + const ws_data = [
2116 + ["کد کالا", "نام کالا", "مشخصه و نوع", "واحد", "قیمت فروش (ریال)"],
2117 + ["1", "سوئیچ شبکه 24 پورت", "با 2 پاور", "عدد", 2180000000],
2118 + ["2", "هارد 2.5 اینچ سرور", "", "عدد", 37000000]
2119 + ];
2120 + const ws = XLSX.utils.aoa_to_sheet(ws_data);
2121 + const wb = XLSX.utils.book_new();
2122 + XLSX.utils.book_append_sheet(wb, ws, "کالاها");
2123 + XLSX.writeFile(wb, "نمونه_کالاها_ایزی_فاکتور.xlsx");
2124 +}
2125 +
2126 +function importProductsFromExcel(event) {
2127 + if (!currentUser) return;
2128 + const file = event.target.files[0];
2129 + if (!file) return;
2130 + const reader = new FileReader();
2131 + reader.onload = function(e) {
2132 + try {
2133 + const data = new Uint8Array(e.target.result);
2134 + const workbook = XLSX.read(data, { type: 'array' });
2135 + const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
2136 + const myProducts = getMyProducts();
2137 + rows.forEach((r, idx) => {
2138 + const name = r["نام کالا"] || r["عنوان"];
2139 + if (name) {
2140 + datastore.products.push({
2141 + id: 'P_' + Date.now() + '_' + idx, ownerUserId: currentUser.id,
2142 + code: (r["کد کالا"] || (myProducts.length + idx + 1)).toString(),
2143 + name: name.toString(),
2144 + spec: (r["مشخصه و نوع"] || '').toString(),
2145 + unit: (r["واحد"] || 'عدد').toString(),
2146 + buy_price: 0,
2147 + sale_price: parseFloat(r["قیمت فروش (ریال)"] || r["قیمت فروش"] || 0) || 0,
2148 + stock: 0, type: 'good'
2149 + });
2150 + }
2151 + });
2152 + saveDatastore();
2153 + refreshAllSurfaces();
2154 + alert('کالاها ایمپورت شدند.');
2155 + } catch(err) { alert('خطا در فایل اکسل!'); }
2156 + };
2157 + reader.readAsArrayBuffer(file);
2158 +}
2159 +
2160 +function commitSaveContact() {
2161 + if (!currentUser) return;
2162 + const entity_type = document.getElementById('contact-entity-type').value;
2163 + const custom_prefix = entity_type === 'natural' ? document.getElementById('contact-prefix-select')?.value : '';
2164 + const raw_name = document.getElementById('contact-name-input').value;
2165 + const role = document.getElementById('contact-role-input').value;
2166 + const mobile = document.getElementById('contact-mobile-input').value;
2167 + const national_id = document.getElementById('contact-national-input').value;
2168 + const economic_code = (entity_type === 'natural') ? '' : document.getElementById('contact-economic-input').value;
2169 + const reg_number = (entity_type === 'natural') ? '' : document.getElementById('contact-reg-input').value;
2170 + const postal_code = document.getElementById('contact-postal-input').value;
2171 + const address = document.getElementById('contact-address-input').value;
2172 + if (!raw_name.trim()) { alert('نام طرف حساب الزامی است.'); return; }
2173 + const formatted_name = formatEntityName(raw_name, entity_type, custom_prefix);
2174 + datastore.contacts.push({
2175 + id: 'C_' + Date.now(), ownerUserId: currentUser.id,
2176 + entity_type, name: formatted_name, role, mobile, national_id, economic_code,
2177 + reg_number, postal_code, address, balance: 0
2178 + });
2179 + saveDatastore();
2180 + alert('طرف حساب ثبت شد.');
2181 + document.getElementById('contact-name-input').value = '';
2182 + refreshAllSurfaces();
2183 +}
2184 +
2185 +function renderContacts() {
2186 + const tbody = document.getElementById('contacts-ledger-table-body');
2187 + const invSelect = document.getElementById('invoice-contact-id');
2188 + const chqSelect = document.getElementById('chq-contact-select');
2189 + const myContacts = getMyContacts();
2190 + if (myContacts.length === 0) {
2191 + tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ طرف حسابی ثبت نشده است.</td></tr>';
2192 + } else {
2193 + tbody.innerHTML = myContacts.map(c => `
2194 + <tr>
2195 + <td><strong>${c.name}</strong></td>
2196 + <td><span class="badge ${c.entity_type === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td>
2197 + <td>${c.national_id || '—'}</td>
2198 + <td>${c.economic_code || '—'}</td>
2199 + <td>${c.postal_code || '—'}</td>
2200 + <td>${c.mobile || '—'}</td>
2201 + <td>${Math.abs(c.balance || 0).toLocaleString('fa-IR')}</td>
2202 + <td><button class="btn btn-danger btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="deleteContact('${c.id}')">حذف</button></td>
2203 + </tr>`).join('');
2204 + }
2205 + const options = myContacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
2206 + if (invSelect) invSelect.innerHTML = options;
2207 + if (chqSelect) chqSelect.innerHTML = options;
2208 +}
2209 +
2210 +function deleteContact(id) {
2211 + if (!currentUser) return;
2212 + if (confirm('حذف شود؟')) {
2213 + datastore.contacts = datastore.contacts.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
2214 + saveDatastore();
2215 + refreshAllSurfaces();
2216 + }
2217 +}
2218 +
2219 +function openQuickContactModal() {
2220 + document.getElementById('modal-quick-contact').classList.add('active');
2221 + handleQuickCEntityChange();
2222 +}
2223 +function closeQuickContactModal() { document.getElementById('modal-quick-contact').classList.remove('active'); }
2224 +
2225 +function saveQuickContact() {
2226 + if (!currentUser) return;
2227 + const entity_type = document.getElementById('quick-c-entity').value;
2228 + const prefix = entity_type === 'natural' ? document.getElementById('quick-c-prefix')?.value : '';
2229 + const raw_name = document.getElementById('quick-c-name').value;
2230 + if (!raw_name.trim()) { alert('نام الزامی است.'); return; }
2231 + const newId = 'C_' + Date.now();
2232 + datastore.contacts.push({
2233 + id: newId, ownerUserId: currentUser.id, entity_type,
2234 + name: formatEntityName(raw_name, entity_type, prefix),
2235 + role: 'customer',
2236 + mobile: document.getElementById('quick-c-mobile').value,
2237 + national_id: document.getElementById('quick-c-national').value,
2238 + economic_code: (entity_type === 'natural') ? '' : document.getElementById('quick-c-economic').value,
2239 + reg_number: (entity_type === 'natural') ? '' : document.getElementById('quick-c-reg').value,
2240 + postal_code: document.getElementById('quick-c-postal').value,
2241 + address: document.getElementById('quick-c-address').value,
2242 + balance: 0
2243 + });
2244 + saveDatastore();
2245 + closeQuickContactModal();
2246 + refreshAllSurfaces();
2247 + document.getElementById('invoice-contact-id').value = newId;
2248 +}
2249 +
2250 +function downloadContactsExcelTemplate() {
2251 + const ws_data = [
2252 + ["نام شخص یا شرکت", "نوع (حقیقی/حقوقی)", "شماره همراه", "شناسه یا کد ملی", "کد اقتصادی", "شماره ثبت", "کد پستی", "نشانی"],
2253 + ["دانشگاه صنعتی شریف", "حقوقی", "02166165000", "14002830256", "14002830256", "", "1458889694", "طرشت محله تیموری پلاک 435"]
2254 + ];
2255 + const ws = XLSX.utils.aoa_to_sheet(ws_data);
2256 + const wb = XLSX.utils.book_new();
2257 + XLSX.utils.book_append_sheet(wb, ws, "اشخاص");
2258 + XLSX.writeFile(wb, "نمونه_اشخاص_ایزی_فاکتور.xlsx");
2259 +}
2260 +
2261 +function importContactsFromExcel(event) {
2262 + if (!currentUser) return;
2263 + const file = event.target.files[0];
2264 + if (!file) return;
2265 + const reader = new FileReader();
2266 + reader.onload = function(e) {
2267 + try {
2268 + const data = new Uint8Array(e.target.result);
2269 + const workbook = XLSX.read(data, { type: 'array' });
2270 + const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
2271 + rows.forEach((r, idx) => {
2272 + const raw_name = r["نام شخص یا شرکت"] || r["نام"];
2273 + if (raw_name) {
2274 + const entity_type = (r["نوع (حقیقی/حقوقی)"] || '').includes('حقوقی') ? 'legal' : 'natural';
2275 + datastore.contacts.push({
2276 + id: 'C_' + Date.now() + '_' + idx, ownerUserId: currentUser.id, entity_type,
2277 + name: formatEntityName(raw_name.toString(), entity_type, 'آقا/خانم'),
2278 + role: 'customer',
2279 + mobile: (r["شماره همراه"] || '').toString(),
2280 + national_id: (r["شناسه یا کد ملی"] || '').toString(),
2281 + economic_code: (entity_type === 'legal' ? (r["کد اقتصادی"] || '') : '').toString(),
2282 + reg_number: (entity_type === 'legal' ? (r["شماره ثبت"] || '') : '').toString(),
2283 + postal_code: (r["کد پستی"] || '').toString(),
2284 + address: (r["نشانی"] || '').toString(),
2285 + balance: 0
2286 + });
2287 + }
2288 + });
2289 + saveDatastore();
2290 + refreshAllSurfaces();
2291 + alert('اشخاص ایمپورت شدند.');
2292 + } catch(err) { alert('خطا در فایل اکسل!'); }
2293 + };
2294 + reader.readAsArrayBuffer(file);
2295 +}
2296 +
2297 +function commitSaveCheque() {
2298 + if (!currentUser) return;
2299 + const direction = document.getElementById('chq-direction-input').value;
2300 + const contactSelect = document.getElementById('chq-contact-select');
2301 + const contactName = contactSelect.options[contactSelect.selectedIndex]?.text || '';
2302 + const sayad_id = document.getElementById('chq-sayad-input').value;
2303 + const bank = document.getElementById('chq-bank-input').value;
2304 + const amount = parseFloat(document.getElementById('chq-amount-input').value) || 0;
2305 + if (!sayad_id || amount <= 0) { alert('اطلاعات چک نامعتبر است.'); return; }
2306 + datastore.cheques.push({
2307 + id: 'CHQ_' + Date.now(), ownerUserId: currentUser.id,
2308 + direction, contactName, sayad_id, bank, amount,
2309 + due_date: document.getElementById('chq-due-input').value,
2310 + status: document.getElementById('chq-status-input').value
2311 + });
2312 + saveDatastore();
2313 + alert('چک ثبت شد.');
2314 + refreshAllSurfaces();
2315 +}
2316 +
2317 +function renderCheques() {
2318 + const tbody = document.getElementById('cheques-ledger-table-body');
2319 + const myCheques = getMyCheques();
2320 + tbody.innerHTML = myCheques.length === 0 ? '<tr><td colspan="6" style="text-align:center; padding:20px; color:var(--text-muted);">چکی ثبت نشده است.</td></tr>' :
2321 + myCheques.map(c => `<tr><td>${c.direction === 'inbound' ? 'دریافتی' : 'پرداختی'}</td><td>${c.contactName}</td><td>${c.bank} - ${c.sayad_id}</td><td>${c.amount.toLocaleString('fa-IR')}</td><td>${c.due_date}</td><td>${c.status}</td></tr>`).join('');
2322 +}
2323 +
2324 +function commitSaveExpense() {
2325 + if (!currentUser) return;
2326 + const amount = parseFloat(document.getElementById('trx-amount-input').value) || 0;
2327 + if (amount <= 0) { alert('مبلغ معتبر نیست.'); return; }
2328 + datastore.expenses.push({
2329 + id: 'TRX_' + Date.now(), ownerUserId: currentUser.id,
2330 + kind: document.getElementById('trx-kind-input').value,
2331 + category: document.getElementById('trx-category-input').value,
2332 + amount, desc: document.getElementById('trx-desc-input').value
2333 + });
2334 + saveDatastore();
2335 + alert('سند ثبت شد.');
2336 + refreshAllSurfaces();
2337 +}
2338 +
2339 +function renderExpenses() {
2340 + const tbody = document.getElementById('expenses-ledger-table-body');
2341 + const myExpenses = getMyExpenses();
2342 + tbody.innerHTML = myExpenses.length === 0 ? '<tr><td colspan="4" style="text-align:center; padding:20px; color:var(--text-muted);">موردی ثبت نشده است.</td></tr>' :
2343 + 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('');
2344 +}
2345 +
2346 +function commitSaveCompany() {
2347 + if (!currentUser) return;
2348 + const entity_type = document.getElementById('company-entity-type').value;
2349 + const raw_name = document.getElementById('company-name-input').value;
2350 + if (!raw_name.trim()) { alert('نام شرکت الزامی است.'); return; }
2351 + const newComp = {
2352 + id: 'COMP_' + Date.now(), ownerUserId: currentUser.id, entity_type,
2353 + name: formatEntityName(raw_name, entity_type),
2354 + phone: document.getElementById('company-phone-input').value || '',
2355 + national_id: document.getElementById('company-national-input').value || '',
2356 + economic_code: document.getElementById('company-economic-input').value || '',
2357 + reg_number: document.getElementById('company-reg-input').value || '',
2358 + postal_code: document.getElementById('company-postal-input').value || '',
2359 + address: document.getElementById('company-address-input').value || '',
2360 + footer: document.getElementById('company-footer-input')?.value || 'از خرید شما سپاسگزاریم.'
2361 + };
2362 + datastore.companies.push(newComp);
2363 + const s = getMySettings();
2364 + s.default_company_id = newComp.id;
2365 + saveDatastore();
2366 + alert('شرکت با موفقیت ثبت و ذخیره شد و به عنوان فروشنده پیش‌فرض تنظیم گردید.');
2367 + ['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 => {
2368 + const el = document.getElementById(id);
2369 + if (el) el.value = '';
2370 + });
2371 + refreshAllSurfaces();
2372 +}
2373 +
2374 +function renderCompanies() {
2375 + const tbody = document.getElementById('companies-table-body');
2376 + const invoiceCompSelect = document.getElementById('invoice-company-id');
2377 + const filterCompSelect = document.getElementById('filter-invoice-company');
2378 + const myCompanies = getMyCompanies();
2379 + const mySettings = getMySettings();
2380 + const defCompId = mySettings.default_company_id || (myCompanies[0]?.id);
2381 + if (tbody) {
2382 + if (myCompanies.length === 0) {
2383 + tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
2384 + } else {
2385 + tbody.innerHTML = myCompanies.map(c => `
2386 + <tr>
2387 + <td><strong>${c.name}</strong></td>
2388 + <td>${c.national_id || '—'}</td>
2389 + <td>${c.economic_code || '—'}</td>
2390 + <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>
2391 + <td>${myCompanies.length > 1 ? `<button class="btn btn-danger btn-inline" style="padding:2px 8px; font-size:11px;" onclick="deleteCompany('${c.id}')">حذف</button>` : '—'}</td>
2392 + </tr>`).join('');
2393 + }
2394 + }
2395 + if (invoiceCompSelect) {
2396 + invoiceCompSelect.innerHTML = myCompanies.map(c => `<option value="${c.id}" ${c.id === defCompId ? 'selected' : ''}>${c.name}</option>`).join('');
2397 + if (defCompId) invoiceCompSelect.value = defCompId;
2398 + }
2399 + if (filterCompSelect) {
2400 + const currentVal = filterCompSelect.value || 'ALL';
2401 + filterCompSelect.innerHTML = `<option value="ALL">نمایش همه شرکت‌ها</option>` + myCompanies.map(c => `<option value="${c.id}">فقط ${c.name}</option>`).join('');
2402 + filterCompSelect.value = currentVal;
2403 + }
2404 +}
2405 +
2406 +function setDefaultCompany(id) {
2407 + const s = getMySettings();
2408 + s.default_company_id = id;
2409 + saveDatastore();
2410 + refreshAllSurfaces();
2411 +}
2412 +
2413 +function deleteCompany(id) {
2414 + if (!currentUser) return;
2415 + if (confirm('حذف شود؟')) {
2416 + datastore.companies = datastore.companies.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
2417 + const myCompanies = getMyCompanies();
2418 + const s = getMySettings();
2419 + if (s.default_company_id === id) s.default_company_id = myCompanies[0]?.id || '';
2420 + saveDatastore();
2421 + refreshAllSurfaces();
2422 + }
2423 +}
2424 +
2425 +function exportDataBlob() {
2426 + const userExport = {
2427 + user: currentUser?.username,
2428 + exportedAt: new Date().toISOString(),
2429 + companies: getMyCompanies(), contacts: getMyContacts(), products: getMyProducts(),
2430 + invoices: getMyInvoices(), cheques: getMyCheques(), expenses: getMyExpenses(),
2431 + settings: getMySettings()
2432 + };
2433 + const blobString = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(userExport, null, 2));
2434 + const anchor = document.createElement('a');
2435 + anchor.setAttribute("href", blobString);
2436 + anchor.setAttribute("download", `easy-factor-${currentUser?.username || 'data'}-${Date.now()}.json`);
2437 + document.body.appendChild(anchor);
2438 + anchor.click();
2439 + anchor.remove();
2440 +}
2441 +
2442 +function importDataBlob(event) {
2443 + if (!currentUser) return;
2444 + const file = event.target.files[0];
2445 + if (!file) return;
2446 + const reader = new FileReader();
2447 + reader.onload = function(e) {
2448 + try {
2449 + const imported = JSON.parse(e.target.result);
2450 + const userId = currentUser.id;
2451 + ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(key => {
2452 + if (Array.isArray(imported[key])) {
2453 + imported[key].forEach(item => { item.ownerUserId = userId; datastore[key].push(item); });
2454 + }
2455 + });
2456 + if (imported.settings) {
2457 + const s = getMySettings();
2458 + Object.assign(s, imported.settings, { ownerUserId: userId });
2459 + }
2460 + saveDatastore();
2461 + refreshAllSurfaces();
2462 + alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
2463 + } catch(err) { alert('فایل نامعتبر است.'); }
2464 + };
2465 + reader.readAsText(file);
2466 +}
2467 +
2468 +function numberToPersianWords(num, currencyLabel) {
2469 + const cur = currencyLabel || 'ریال';
2470 + if (!num || isNaN(num) || num == 0) return 'صفر ' + cur;
2471 + const yegan = ["", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"];
2472 + const dahgan = ["", "", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"];
2473 + const dah_ta_bist = ["ده", "یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"];
2474 + const sadgan = ["", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"];
2475 + const part_names = ["", "هزار", "میلیون", "میلیارد", "تریلیون"];
2476 + function threeDigitToWords(n) {
2477 + let c = Math.floor(n / 100);
2478 + let d = Math.floor((n % 100) / 10);
2479 + let y = n % 10;
2480 + let parts = [];
2481 + if (c > 0) parts.push(sadgan[c]);
2482 + if (d === 1) parts.push(dah_ta_bist[y]);
2483 + else {
2484 + if (d > 1) parts.push(dahgan[d]);
2485 + if (y > 0) parts.push(yegan[y]);
2486 + }
2487 + return parts.join(" و ");
2488 + }
2489 + let parts = [];
2490 + let chunkIdx = 0;
2491 + let temp = Math.abs(Math.round(num));
2492 + while (temp > 0) {
2493 + let chunk = temp % 1000;
2494 + if (chunk > 0) {
2495 + let w = threeDigitToWords(chunk);
2496 + if (part_names[chunkIdx]) w += " " + part_names[chunkIdx];
2497 + parts.unshift(w);
2498 + }
2499 + temp = Math.floor(temp / 1000);
2500 + chunkIdx++;
2501 + }
2502 + return parts.join(" و ") + " " + cur;
2503 +}
2504 +
2505 +window.addEventListener('DOMContentLoaded', () => { initAuthSystem(); });
2506 +</script>
2507 +
2508 +<style>
2509 +.form-control, textarea, select { direction: rtl; }
2510 +</style>
2511 +
2512 +<script>
2513 +(function(){
2514 + const oldSave = window.commitSaveInvoice;
2515 + window.commitSaveInvoice = function(){
2516 + const rows = document.querySelectorAll('#invoice-items-table-body tr');
2517 + if(!rows.length){
2518 + alert('حداقل یک ردیف کالا یا خدمت لازم است.');
2519 + return;
2520 + }
2521 + for(const row of rows){
2522 + const sel = row.querySelector('.row-product-select');
2523 + if(sel && !sel.value){
2524 + alert('لطفاً شرح کالا یا خدمت را از لیست انتخاب کنید.');
2525 + return;
2526 + }
2527 + const qty = parseFloat(row.querySelector('.row-quantity')?.value) || 0;
2528 + if(qty <= 0){
2529 + alert('مقدار کالا باید بزرگتر از صفر باشد.');
2530 + return;
2531 + }
2532 + }
2533 + if(typeof oldSave === 'function') return oldSave();
2534 + };
2535 +
2536 + window.EasyFactorHealth = {
2537 + version: '5.2-dev-info',
2538 + storage: 'localStorage',
2539 + checks(){
2540 + return {
2541 + rtl: document.documentElement.dir === 'rtl',
2542 + storage: !!window.localStorage,
2543 + printReady: !!document.getElementById('printable-invoice')
2544 + };
2545 + }
2546 + };
2547 +})();
2548 +</script>
2549 +
2550 +</body>
2551 +</html>