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

Update index.html

davoodmehraban89 committed Sep 17, 2026 at 23:04 UTC 2e09acaa088c2dd042000aa9de99d089c860c8a1
1 file changed +1488 -1950
index.html
+1488 -1950
@@ -1,1715 +1,1395 @@
1 <!DOCTYPE html>
2 <html lang="fa" dir="rtl">
3 <head>
4 - <meta charset="UTF-8" />
5 - <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6 - <title>ایزی فاکتور | سامانه صدور فاکتور و مدیریت مالی</title>
7 -
8 - <link rel="manifest" href="manifest.json" />
9 - <meta name="apple-mobile-web-app-capable" content="yes" />
10 - <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
11 - <meta name="apple-mobile-web-app-title" content="ایزی فاکتور" />
12 - <meta name="theme-color" content="#2563eb" />
13 -
14 - <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
15 - <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
16 -
17 - <style>
18 - :root {
19 - --primary: #2563eb; --primary-hover: #1d4ed8; --accent: #2563eb;
20 - --bg: #f8fafc; --card-bg: #ffffff; --text: #0f172a; --text-muted: #64748b;
21 - --border: #cbd5e1; --danger: #dc2626; --success: #059669; --warning: #d97706;
22 - --sidebar-w: 240px; --nav-h: 70px;
23 - }
24 - html, body { width: 100%; max-width: 100%; overflow-x: hidden !important; position: relative; }
25 - * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Vazirmatn FD', -apple-system, BlinkMacSystemFont, Tahoma, sans-serif; -webkit-tap-highlight-color: transparent; }
26 - body { background-color: var(--bg); color: var(--text); font-size: 14px; }
27 -
28 - #auth-screen { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient(135deg, #1e3a8a, #2563eb); z-index: 9999; display: flex; align-items: center; justify-content: center; padding: 20px; }
29 - .auth-card { background: #fff; border-radius: 16px; max-width: 420px; width: 100%; padding: 30px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); text-align: right; }
30 -
31 - .app-root { display: flex; min-height: 100vh; width: 100%; max-width: 100%; overflow-x: hidden; }
32 - .sidebar { width: var(--sidebar-w); background: var(--card-bg); border-left: 1px solid var(--border); display: flex; flex-direction: column; position: fixed; top: 0; bottom: 0; right: 0; z-index: 100; }
33 - .brand-box { padding: 20px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--border); }
34 - .brand-icon { width: 40px; height: 40px; background: var(--primary); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: bold; font-size: 18px; }
35 - .sidebar-menu { list-style: none; padding: 16px 8px; flex: 1; overflow-y: auto; }
36 - .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 16px; color: var(--text); text-decoration: none; border-radius: 8px; margin-bottom: 4px; font-size: 14px; font-weight: 500; transition: all 0.2s; cursor: pointer; }
37 - .sidebar-menu li a:hover, .sidebar-menu li a.active { background: #eff6ff; color: var(--primary); font-weight: bold; }
38 - .sidebar-footer { padding: 12px; border-top: 1px solid var(--border); font-size: 12px; color: var(--text-muted); text-align: center; display:flex; flex-direction:column; gap:6px; }
39 - .main-surface { flex: 1; margin-right: var(--sidebar-w); padding: 20px; padding-bottom: 100px; max-width: calc(100% - var(--sidebar-w)); overflow-x: hidden; }
40 - .mobile-dock { display: none; position: fixed; bottom: 0; left: 0; right: 0; height: var(--nav-h); background: rgba(255,255,255,0.98); backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); border-top: 1px solid #cbd5e1; z-index: 200; justify-content: space-around; align-items: center; padding-bottom: env(safe-area-inset-bottom); box-shadow: 0 -4px 12px rgba(0,0,0,0.06); }
41 - .dock-tab { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; color: #475569; text-decoration: none; font-size: 10.5px; font-weight: 600; flex: 1; height: 100%; cursor: pointer; }
42 - .dock-tab.active { color: var(--primary); font-weight: 800; }
43 - .dock-tab svg { width: 20px; height: 20px; stroke-width: 2; }
44 -
45 - /* دکمه شناور پشتیبانی واتس‌اپ */
46 - .whatsapp-support {
47 - position: fixed;
48 - bottom: 90px;
49 - left: 20px;
50 - z-index: 250;
51 - display: flex;
52 - align-items: center;
53 - gap: 8px;
54 - background: linear-gradient(135deg, #25D366, #128C7E);
55 - color: #fff;
56 - text-decoration: none;
57 - padding: 10px 16px 10px 12px;
58 - border-radius: 50px;
59 - box-shadow: 0 8px 24px rgba(37, 211, 102, 0.4);
60 - font-weight: 700;
61 - font-size: 13px;
62 - transition: all 0.25s ease;
63 - cursor: pointer;
64 - }
65 - .whatsapp-support:hover {
66 - transform: translateY(-3px);
67 - box-shadow: 0 12px 28px rgba(37, 211, 102, 0.55);
68 - }
69 - .whatsapp-support svg { width: 22px; height: 22px; flex-shrink: 0; }
70 - .whatsapp-support .label { white-space: nowrap; }
71 -
72 - @media (max-width: 768px) {
73 - .whatsapp-support {
74 - bottom: 84px;
75 - left: 12px;
76 - padding: 8px 12px 8px 10px;
77 - font-size: 11.5px;
78 - }
79 - .whatsapp-support svg { width: 18px; height: 18px; }
80 - }
81 -
82 - @media print {
83 - .whatsapp-support { display: none !important; }
84 - }
85 -
86 - .card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 12px; padding: 18px; margin-bottom: 18px; box-shadow: 0 1px 3px rgba(0,0,0,0.03); width: 100%; max-width: 100%; overflow: hidden; }
87 - .grid-kpi { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; margin-bottom: 18px; }
88 - .kpi-unit { background: var(--card-bg); border: 1px solid var(--border); border-radius: 10px; padding: 16px; display: flex; align-items: center; gap: 14px; }
89 - .kpi-icon { width: 44px; height: 44px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
90 - .kpi-val { font-size: 17px; font-weight: bold; margin-top: 4px; }
91 - .kpi-lbl { color: var(--text-muted); font-size: 12px; font-weight: 500; }
92 -
93 - .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 44px; padding: 8px 16px; background: var(--primary); color: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 600; transition: background 0.2s; }
94 - .btn:hover { background: var(--primary-hover); }
95 - .btn-secondary { background: #e2e8f0; color: var(--text); }
96 - .btn-secondary:hover { background: #cbd5e1; }
97 - .btn-success { background: var(--success); }
98 - .btn-danger { background: var(--danger); }
99 - .btn-warning { background: var(--warning); color: #fff; }
100 -
101 - .form-group { margin-bottom: 14px; width: 100%; }
102 - .form-group label { display: block; margin-bottom: 6px; font-size: 13px; font-weight: 600; color: #334155; }
103 - .form-control { width: 100%; min-height: 44px; padding: 8px 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 14px; outline: none; background: #fff; transition: border-color 0.2s; }
104 - .form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(37,99,235,0.15); }
105 - .form-control:disabled { background-color: #f1f5f9; color: #94a3b8; cursor: not-allowed; }
106 - .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; width: 100%; }
107 -
108 - .table-responsive { width: 100%; max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; border: 1px solid var(--border); border-radius: 8px; }
109 - table { width: 100%; border-collapse: collapse; text-align: right; font-size: 13px; min-width: 500px; }
110 - th, td { padding: 10px 10px; border-bottom: 1px solid var(--border); }
111 - th { background: #f1f5f9; color: #334155; font-weight: 700; }
112 -
113 - #invoice-items-table { direction: rtl; width: 100%; table-layout: auto; }
114 - #invoice-items-table th, #invoice-items-table td { text-align: right; }
115 - #invoice-items-table th:first-child, #invoice-items-table td:first-child { text-align: center; }
116 - #invoice-items-table th:last-child, #invoice-items-table td:last-child { text-align: center; }
117 -
118 - .badge { display: inline-block; padding: 3px 8px; border-radius: 6px; font-size: 11px; font-weight: 600; }
119 - .badge-success { background: #d1fae5; color: #065f46; }
120 - .badge-warning { background: #fef3c7; color: #92400e; }
121 - .badge-danger { background: #fee2e2; color: #991b1b; }
122 - .badge-info { background: #e0f2fe; color: #0369a1; }
123 -
124 - .view-pane { display: none; }
125 - .view-pane.active { display: block; }
126 -
127 - .modal-backdrop { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(15,23,42,0.6); backdrop-filter: blur(4px); z-index: 999; align-items: center; justify-content: center; padding: 16px; }
128 - .modal-backdrop.active { display: flex; }
129 - .modal-card { background: #fff; border-radius: 14px; max-width: 600px; width: 100%; max-height: 90vh; overflow-y: auto; padding: 20px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
130 -
131 - .accordion-item { border: 1px solid var(--border); border-radius: 10px; margin-bottom: 12px; overflow: hidden; background: #fff; }
132 - .accordion-header { padding: 14px 18px; background: #f8fafc; font-weight: bold; display: flex; justify-content: space-between; align-items: center; cursor: pointer; user-select: none; }
133 - .accordion-body { padding: 16px; border-top: 1px solid var(--border); display: none; background: #fff; }
134 - .accordion-item.open .accordion-body { display: block; }
135 -
136 - .about-dev-card {
137 - background: linear-gradient(135deg, #eff6ff, #f8fafc);
138 - border: 1.5px solid #bfdbfe;
139 - border-radius: 12px;
140 - padding: 16px 18px;
141 - margin: 14px 0;
142 - display: flex;
143 - align-items: center;
144 - gap: 14px;
145 - flex-wrap: wrap;
146 - }
147 - .about-dev-avatar {
148 - width: 52px; height: 52px;
149 - background: linear-gradient(135deg, var(--primary), #1e40af);
150 - color: #fff; border-radius: 50%;
151 - display: flex; align-items: center; justify-content: center;
152 - font-size: 20px; font-weight: bold;
153 - flex-shrink: 0;
154 - }
155 - .about-dev-info { flex: 1; min-width: 180px; }
156 - .about-dev-info h4 { font-size: 15px; color: #1e293b; margin-bottom: 4px; }
157 - .about-dev-info p { font-size: 12.5px; color: #64748b; margin-bottom: 2px; }
158 - .about-dev-actions { display: flex; gap: 8px; flex-wrap: wrap; }
159 - .about-dev-actions a {
160 - display: inline-flex; align-items: center; gap: 6px;
161 - padding: 8px 14px; border-radius: 8px;
162 - font-size: 12.5px; font-weight: 700;
163 - text-decoration: none;
164 - transition: all 0.2s;
165 - }
166 - .about-dev-actions .btn-wa {
167 - background: linear-gradient(135deg, #25D366, #128C7E);
168 - color: #fff;
169 - }
170 - .about-dev-actions .btn-wa:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(37,211,102,0.4); }
171 - .about-dev-actions .btn-call {
172 - background: var(--primary); color: #fff;
173 - }
174 - .about-dev-actions .btn-call:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(37,99,235,0.4); }
175 -
176 - @media print {
177 - @page { size: A4 landscape; margin: 8mm 10mm; }
178 - html, body { background: #fff !important; color: #000 !important; margin: 0 !important; padding: 0 !important; width: 100% !important; }
179 - .sidebar, .mobile-dock, .no-print, #auth-screen, .modal-backdrop, .whatsapp-support { display: none !important; }
180 - .view-pane { display: none !important; }
181 - .main-surface { margin: 0 !important; padding: 0 !important; max-width: 100% !important; width: 100% !important; }
182 - .card { border: none !important; box-shadow: none !important; padding: 0 !important; margin: 0 !important; }
183 - .invoice-a4-page { width: 100% !important; max-width: 277mm !important; margin: 0 auto !important; padding: 0 !important; page-break-after: always !important; break-after: page !important; box-sizing: border-box !important; }
184 - .invoice-a4-page:last-child { page-break-after: avoid !important; break-after: avoid !important; }
185 - #printable-invoice { display: block !important; }
186 - }
187 -
188 - @media (max-width: 768px) {
189 - .sidebar { display: none; }
190 - .main-surface { margin-right: 0; padding: 12px; padding-bottom: calc(var(--nav-h) + 20px); max-width: 100%; }
191 - .mobile-dock { display: flex; }
192 - .btn { width: 100%; }
193 - .btn-inline { width: auto; }
194 - .form-row { grid-template-columns: 1fr; }
195 - }
196 - </style>
4 +<meta charset="UTF-8" />
5 +<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6 +<title>ایزی فاکتور | سامانه صدور فاکتور و مدیریت مالی</title>
7 +<link rel="manifest" href="manifest.json" />
8 +<meta name="apple-mobile-web-app-capable" content="yes" />
9 +<meta name="theme-color" content="#2563eb" />
10 +<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
11 +<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
12 +<style>
13 +:root{--primary:#2563eb;--primary-hover:#1d4ed8;--bg:#f8fafc;--card-bg:#fff;--text:#0f172a;--text-muted:#64748b;--border:#cbd5e1;--danger:#dc2626;--success:#059669;--warning:#d97706;--sidebar-w:240px;--nav-h:70px}
14 +html,body{width:100%;max-width:100%;overflow-x:hidden!important;position:relative}
15 +*{box-sizing:border-box;margin:0;padding:0;font-family:'Vazirmatn FD',-apple-system,BlinkMacSystemFont,Tahoma,sans-serif;-webkit-tap-highlight-color:transparent}
16 +body{background-color:var(--bg);color:var(--text);font-size:14px}
17 +#auth-screen{position:fixed;top:0;left:0;right:0;bottom:0;background:linear-gradient(135deg,#1e3a8a,#2563eb);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px}
18 +.auth-card{background:#fff;border-radius:16px;max-width:420px;width:100%;padding:30px;box-shadow:0 25px 50px -12px rgba(0,0,0,.25);text-align:right}
19 +.app-root{display:flex;min-height:100vh;width:100%;max-width:100%;overflow-x:hidden}
20 +.sidebar{width:var(--sidebar-w);background:var(--card-bg);border-left:1px solid var(--border);display:flex;flex-direction:column;position:fixed;top:0;bottom:0;right:0;z-index:100}
21 +.brand-box{padding:20px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--border)}
22 +.brand-icon{width:40px;height:40px;background:var(--primary);border-radius:10px;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold;font-size:18px}
23 +.sidebar-menu{list-style:none;padding:16px 8px;flex:1;overflow-y:auto}
24 +.sidebar-menu li a{display:flex;align-items:center;gap:12px;padding:12px 16px;color:var(--text);text-decoration:none;border-radius:8px;margin-bottom:4px;font-size:14px;font-weight:500;transition:all .2s;cursor:pointer}
25 +.sidebar-menu li a:hover,.sidebar-menu li a.active{background:#eff6ff;color:var(--primary);font-weight:bold}
26 +.sidebar-footer{padding:12px;border-top:1px solid var(--border);font-size:12px;color:var(--text-muted);text-align:center;display:flex;flex-direction:column;gap:6px}
27 +.main-surface{flex:1;margin-right:var(--sidebar-w);padding:20px;padding-bottom:100px;max-width:calc(100% - var(--sidebar-w));overflow-x:hidden}
28 +.mobile-dock{display:none;position:fixed;bottom:0;left:0;right:0;height:var(--nav-h);background:rgba(255,255,255,.98);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);border-top:1px solid #cbd5e1;z-index:200;justify-content:space-around;align-items:center;padding-bottom:env(safe-area-inset-bottom);box-shadow:0 -4px 12px rgba(0,0,0,.06)}
29 +.dock-tab{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;color:#475569;text-decoration:none;font-size:10.5px;font-weight:600;flex:1;height:100%;cursor:pointer}
30 +.dock-tab.active{color:var(--primary);font-weight:800}
31 +.dock-tab svg{width:20px;height:20px;stroke-width:2}
32 +.whatsapp-support{position:fixed;bottom:90px;left:20px;z-index:250;display:flex;align-items:center;gap:8px;background:linear-gradient(135deg,#25D366,#128C7E);color:#fff;text-decoration:none;padding:10px 16px 10px 12px;border-radius:50px;box-shadow:0 8px 24px rgba(37,211,102,.4);font-weight:700;font-size:13px;transition:all .25s ease}
33 +.whatsapp-support:hover{transform:translateY(-3px);box-shadow:0 12px 28px rgba(37,211,102,.55)}
34 +.whatsapp-support svg{width:22px;height:22px;flex-shrink:0}
35 +.card{background:var(--card-bg);border:1px solid var(--border);border-radius:12px;padding:18px;margin-bottom:18px;box-shadow:0 1px 3px rgba(0,0,0,.03);width:100%;max-width:100%;overflow:hidden}
36 +.grid-kpi{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;margin-bottom:18px}
37 +.kpi-unit{background:var(--card-bg);border:1px solid var(--border);border-radius:10px;padding:16px;display:flex;align-items:center;gap:14px}
38 +.kpi-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:20px}
39 +.kpi-val{font-size:17px;font-weight:bold;margin-top:4px}
40 +.kpi-lbl{color:var(--text-muted);font-size:12px;font-weight:500}
41 +.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:14px;font-weight:600;transition:background .2s;text-decoration:none}
42 +.btn:hover{background:var(--primary-hover)}
43 +.btn-secondary{background:#e2e8f0;color:var(--text)}
44 +.btn-secondary:hover{background:#cbd5e1}
45 +.btn-success{background:var(--success)}
46 +.btn-danger{background:var(--danger)}
47 +.btn-warning{background:var(--warning);color:#fff}
48 +.form-group{margin-bottom:14px;width:100%}
49 +.form-group label{display:block;margin-bottom:6px;font-size:13px;font-weight:600;color:#334155}
50 +.form-control{width:100%;min-height:44px;padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:14px;outline:none;background:#fff;transition:border-color .2s;direction:rtl}
51 +.form-control:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.15)}
52 +.form-control:disabled{background-color:#f1f5f9;color:#94a3b8;cursor:not-allowed}
53 +.form-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;width:100%}
54 +.table-responsive{width:100%;max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;border:1px solid var(--border);border-radius:8px}
55 +table{width:100%;border-collapse:collapse;text-align:right;font-size:13px;min-width:500px}
56 +th,td{padding:10px 10px;border-bottom:1px solid var(--border)}
57 +th{background:#f1f5f9;color:#334155;font-weight:700}
58 +#invoice-items-table{direction:rtl;width:100%;table-layout:auto}
59 +#invoice-items-table th,#invoice-items-table td{text-align:right}
60 +#invoice-items-table th:first-child,#invoice-items-table td:first-child{text-align:center}
61 +#invoice-items-table th:last-child,#invoice-items-table td:last-child{text-align:center}
62 +.badge{display:inline-block;padding:3px 8px;border-radius:6px;font-size:11px;font-weight:600}
63 +.badge-success{background:#d1fae5;color:#065f46}
64 +.badge-warning{background:#fef3c7;color:#92400e}
65 +.badge-danger{background:#fee2e2;color:#991b1b}
66 +.badge-info{background:#e0f2fe;color:#0369a1}
67 +.view-pane{display:none}
68 +.view-pane.active{display:block}
69 +.modal-backdrop{display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(15,23,42,.6);backdrop-filter:blur(4px);z-index:999;align-items:center;justify-content:center;padding:16px}
70 +.modal-backdrop.active{display:flex}
71 +.modal-card{background:#fff;border-radius:14px;max-width:600px;width:100%;max-height:90vh;overflow-y:auto;padding:20px;box-shadow:0 20px 25px -5px rgba(0,0,0,.1)}
72 +.accordion-item{border:1px solid var(--border);border-radius:10px;margin-bottom:12px;overflow:hidden;background:#fff}
73 +.accordion-header{padding:14px 18px;background:#f8fafc;font-weight:bold;display:flex;justify-content:space-between;align-items:center;cursor:pointer;user-select:none}
74 +.accordion-body{padding:16px;border-top:1px solid var(--border);display:none;background:#fff}
75 +.accordion-item.open .accordion-body{display:block}
76 +.about-dev-card{background:linear-gradient(135deg,#eff6ff,#f8fafc);border:1.5px solid #bfdbfe;border-radius:12px;padding:16px 18px;margin:14px 0;display:flex;align-items:center;gap:14px;flex-wrap:wrap}
77 +.about-dev-avatar{width:52px;height:52px;background:linear-gradient(135deg,var(--primary),#1e40af);color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:bold;flex-shrink:0}
78 +.about-dev-info{flex:1;min-width:180px}
79 +.about-dev-info h4{font-size:15px;color:#1e293b;margin-bottom:4px}
80 +.about-dev-info p{font-size:12.5px;color:#64748b;margin-bottom:2px}
81 +.about-dev-actions{display:flex;gap:8px;flex-wrap:wrap}
82 +.about-dev-actions a{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;border-radius:8px;font-size:12.5px;font-weight:700;text-decoration:none;transition:all .2s}
83 +.about-dev-actions .btn-wa{background:linear-gradient(135deg,#25D366,#128C7E);color:#fff}
84 +.about-dev-actions .btn-call{background:var(--primary);color:#fff}
85 +@media print{
86 +@page{size:A4 landscape;margin:8mm 10mm}
87 +html,body{background:#fff!important;color:#000!important;margin:0!important;padding:0!important;width:100%!important}
88 +.sidebar,.mobile-dock,.no-print,#auth-screen,.modal-backdrop,.whatsapp-support{display:none!important}
89 +.view-pane{display:none!important}
90 +.main-surface{margin:0!important;padding:0!important;max-width:100%!important;width:100%!important}
91 +.card{border:none!important;box-shadow:none!important;padding:0!important;margin:0!important}
92 +.invoice-a4-page{width:100%!important;max-width:277mm!important;margin:0 auto!important;padding:0!important;page-break-after:always!important;break-after:page!important;box-sizing:border-box!important}
93 +.invoice-a4-page:last-child{page-break-after:avoid!important;break-after:avoid!important}
94 +#printable-invoice{display:block!important}
95 +}
96 +@media (max-width:768px){
97 +.sidebar{display:none}
98 +.main-surface{margin-right:0;padding:12px;padding-bottom:calc(var(--nav-h) + 20px);max-width:100%}
99 +.mobile-dock{display:flex}
100 +.btn{width:100%}
101 +.btn-inline{width:auto}
102 +.form-row{grid-template-columns:1fr}
103 +.whatsapp-support{bottom:84px;left:12px;padding:8px 12px 8px 10px;font-size:11.5px}
104 +}
105 +</style>
106 </head>
107 <body>
108
200 - <div id="auth-screen">
201 - <div class="auth-card">
202 - <div style="text-align:center; margin-bottom:20px;">
203 - <div style="width:50px; height:50px; background:var(--primary); color:#fff; font-weight:bold; font-size:24px; border-radius:12px; display:inline-flex; align-items:center; justify-content:center; margin-bottom:10px;">ایزی</div>
204 - <h2 style="font-size:20px; font-weight:bold; color:var(--text);">سامانه ایزی فاکتور</h2>
205 - <p style="font-size:12px; color:var(--text-muted); margin-top:4px;">ورود یا ثبت‌نام در سامانه</p>
206 - </div>
207 - <div id="auth-form-container">
208 - <div class="form-group">
209 - <label>نام کاربری یا شماره همراه</label>
210 - <input type="text" id="auth-username" class="form-control" placeholder="admin یا شماره همراه" />
211 - </div>
212 - <div class="form-group">
213 - <label>رمز عبور</label>
214 - <input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" />
215 - </div>
216 - <div style="display:flex; gap:10px; margin-top:16px;">
217 - <button class="btn btn-primary" style="flex:1;" onclick="handleLogin()">ورود</button>
218 - <button class="btn btn-secondary" style="flex:1;" onclick="switchToRegister()">ثبت‌نام</button>
219 - </div>
220 - </div>
221 - </div>
222 - </div>
223 -
224 - <div class="app-root">
225 - <aside class="sidebar">
226 - <div class="brand-box">
227 - <div class="brand-icon">ایزی</div>
228 - <div>
229 - <h2 style="font-size: 15px; font-weight: bold;">ایزی فاکتور</h2>
230 - <small style="color: var(--text-muted); font-size: 11px;">نسخه چندکاربره ۵.۱</small>
231 - </div>
232 - </div>
233 - <ul class="sidebar-menu">
234 - <li><a href="#" class="nav-link" data-view="view-dashboard" onclick="switchView('view-dashboard'); return false;">📊 داشبورد تحلیلی</a></li>
235 - <li><a href="#" class="nav-link" data-view="view-invoices" onclick="switchView('view-invoices'); return false;">🧾 صدور فاکتور و اسناد</a></li>
236 - <li><a href="#" class="nav-link" data-view="view-products" onclick="switchView('view-products'); return false;">📦 کالاها و خدمات</a></li>
237 - <li><a href="#" class="nav-link" data-view="view-contacts" onclick="switchView('view-contacts'); return false;">👥 طرف‌حساب‌ها و معین</a></li>
238 - <li><a href="#" class="nav-link" data-view="view-cheques" onclick="switchView('view-cheques'); return false;">💳 چک‌ها و صیاد</a></li>
239 - <li><a href="#" class="nav-link" data-view="view-expenses" onclick="switchView('view-expenses'); return false;">💰 هزینه‌ها و درآمد</a></li>
240 - <li><a href="#" class="nav-link" data-view="view-settings" onclick="switchView('view-settings'); return false;">⚙️ تنظیمات و شرکت‌ها</a></li>
241 - <li id="menu-admin-panel" style="display:none;"><a href="#" class="nav-link" data-view="view-admin" onclick="switchView('view-admin'); return false;" style="background:#fef2f2; color:#dc2626; font-weight:bold;">👑 مدیریت کاربران و لایسنس</a></li>
242 - </ul>
243 - <div class="sidebar-footer">
244 - <span id="logged-user-label">کاربر</span>
245 - <button class="btn btn-danger btn-inline" style="padding:4px 10px; font-size:11px; min-height:28px; width:100%; margin-top:4px;" onclick="handleLogout()">🚪 خروج از حساب کاربری</button>
246 - </div>
247 - </aside>
248 -
249 - <!-- دکمه شناور پشتیبانی واتس‌اپ -->
250 - <a class="whatsapp-support no-print" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener" title="پشتیبانی واتس‌اپ: ۰۹۱۲۴۳۷۶۹۹۱">
251 - <svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
252 - <span class="label">پشتیبانی واتس‌اپ</span>
253 - </a>
254 -
255 - <main class="main-surface">
256 -
257 - <section id="view-dashboard" class="view-pane active">
258 - <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; gap: 10px;">
259 - <div>
260 - <h1 style="font-size: 20px; font-weight: bold;">سامانه ایزی فاکتور</h1>
261 - <p style="color: var(--text-muted); font-size: 13px;" id="dashboard-date-display"></p>
262 - </div>
263 - <div style="display:flex; align-items:center; gap:10px;">
264 - <span id="user-license-status-badge" class="badge badge-warning">در حال بررسی...</span>
265 - <button class="btn btn-inline no-print" onclick="startNewInvoice()">➕ فاکتور جدید</button>
266 - </div>
267 - </div>
268 - <div id="dashboard-license-details"></div>
269 -
270 - <div class="grid-kpi">
271 - <div class="kpi-unit">
272 - <div class="kpi-icon" style="background:#eff6ff; color:var(--primary);">💰</div>
273 - <div><div class="kpi-lbl">مجموع فروش ثبت‌شده (<span class="cur-label">ریال</span>)</div><div class="kpi-val" id="kpi-sales-sum">۰ ریال</div></div>
274 - </div>
275 - <div class="kpi-unit">
276 - <div class="kpi-icon" style="background:#ecfdf5; color:var(--success);">📥</div>
277 - <div><div class="kpi-lbl">دریافت وصول شده</div><div class="kpi-val" id="kpi-settled-sum">۰ ریال</div></div>
278 - </div>
279 - <div class="kpi-unit">
280 - <div class="kpi-icon" style="background:#fffbeb; color:var(--warning);">⏳</div>
281 - <div><div class="kpi-lbl">مانده مطالبات نسیه</div><div class="kpi-val" id="kpi-debtors-sum">۰ ریال</div></div>
282 - </div>
283 - <div class="kpi-unit">
284 - <div class="kpi-icon" style="background:#fef2f2; color:var(--danger);">💳</div>
285 - <div><div class="kpi-lbl">چک‌های باز صیادی</div><div class="kpi-val" id="kpi-cheques-count">۰ فقره</div></div>
286 - </div>
287 - </div>
288 -
289 - <div class="card">
290 - <h3 style="font-size: 15px; margin-bottom: 12px;">آخرین فاکتورهای صادر شده</h3>
291 - <div class="table-responsive">
292 - <table>
293 - <thead>
294 - <tr><th>شماره</th><th>فروشنده (شرکت)</th><th>خریدار</th><th>نوع فاکتور</th><th>ارزش افزوده</th><th>مبلغ کل (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr>
295 - </thead>
296 - <tbody id="dashboard-recent-table">
297 - <tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری صادر نشده است.</td></tr>
298 - </tbody>
299 - </table>
300 - </div>
301 - </div>
302 -
303 - <!-- کارت پشتیبانی سریع در انتهای داشبورد -->
304 - <div class="card no-print" style="background: linear-gradient(135deg, #ecfdf5, #f0fdf4); border-color:#bbf7d0;">
305 - <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap; justify-content:space-between;">
306 - <div style="display:flex; align-items:center; gap:12px;">
307 - <div style="width:44px; height:44px; border-radius:50%; background:linear-gradient(135deg,#25D366,#128C7E); display:flex; align-items:center; justify-content:center; color:#fff;">
308 - <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
309 - </div>
310 - <div>
311 - <h3 style="font-size:15px; color:#166534;">پشتیبانی سریع</h3>
312 - <p style="font-size:12.5px; color:#475569; margin-top:2px;">سؤالی دارید؟ از طریق واتس‌اپ با ما در تماس باشید.</p>
313 - </div>
314 - </div>
315 - <a href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener" class="btn btn-inline" style="background:linear-gradient(135deg,#25D366,#128C7E); text-decoration:none;">
316 - 💬 گفتگو در واتس‌اپ
317 - </a>
318 - </div>
319 - </div>
320 - </section>
321 -
322 - <section id="view-invoices" class="view-pane">
323 - <div class="card no-print">
324 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:14px;">
325 - <h2 style="font-size: 17px;" id="invoice-form-title">صدور فاکتور جدید</h2>
326 - <button class="btn btn-secondary btn-inline" style="display:none; padding:4px 10px; font-size:12px;" id="btn-cancel-edit" onclick="cancelInvoiceEdit()">انصراف از ویرایش</button>
327 - </div>
328 - <input type="hidden" id="edit-invoice-id" value="" />
329 -
330 - <div class="form-row" style="background:#f1f5f9; padding:12px; border-radius:10px; margin-bottom:14px;">
331 - <div class="form-group" style="margin-bottom:0;"><label>تاریخ فاکتور</label><input type="text" id="invoice-date-input" class="form-control" /></div>
332 - <div class="form-group" style="margin-bottom:0;"><label>شماره فاکتور</label><input type="text" id="invoice-number" class="form-control" placeholder="PINV-31" /></div>
333 - <div class="form-group" style="margin-bottom:0;">
334 - <label>قالب و نوع سند</label>
335 - <select id="invoice-kind" class="form-control" onchange="handleInvoiceKindChange()">
336 - <option value="non_formal">فاکتور غیررسمی</option>
337 - <option value="formal">فاکتور رسمی</option>
338 - <option value="pre_invoice">پیش‌فاکتور فروش</option>
339 - </select>
340 - </div>
341 - </div>
342 -
343 - <div class="form-row">
344 - <div class="form-group"><label>فروشنده (سربرگ شرکت)</label><select id="invoice-company-id" class="form-control" onchange="onActiveCompanyFilterChange()"></select></div>
345 - <div class="form-group">
346 - <label style="display:flex; justify-content:space-between;">
347 - <span>نام خریدار را وارد یا انتخاب کنید</span>
348 - <a href="#" style="color:var(--primary); text-decoration:none;" onclick="openQuickContactModal()">➕ شخص جدید</a>
349 - </label>
350 - <div style="display:flex; gap:8px;">
351 - <select id="invoice-contact-id" class="form-control" style="flex:1;"></select>
352 - <button class="btn btn-secondary btn-inline" type="button" onclick="openQuickContactModal()" style="padding:0 12px; min-height:42px;">➕</button>
353 - </div>
354 - </div>
355 - </div>
356 -
357 - <div style="margin: 16px 0;">
358 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
359 - <h4 style="font-size: 14px;">اقلام کالا یا خدمات</h4>
360 - <button class="btn btn-secondary btn-inline" style="font-size:12px; min-height:34px; padding:4px 10px;" onclick="openQuickProductModal()">➕ کالای جدید</button>
361 - </div>
362 - <div class="table-responsive">
363 - <table id="invoice-items-table">
364 - <thead>
365 - <tr style="background:#e2e8f0;">
366 - <th style="width:40px; text-align:center;">#</th>
367 - <th>شرح کالا | خدمات</th>
368 - <th style="width:90px; text-align:center;">واحد</th>
369 - <th style="width:100px; text-align:center;">مقدار</th>
370 - <th style="width:160px; text-align:left;">قیمت واحد (<span class="cur-label">ریال</span>)</th>
371 - <th style="width:170px; text-align:left;">قیمت کل (<span class="cur-label">ریال</span>)</th>
372 - <th style="width:50px; text-align:center;">حذف</th>
373 - </tr>
374 - </thead>
375 - <tbody id="invoice-items-table-body"></tbody>
376 - </table>
377 - </div>
378 - <button class="btn btn-secondary btn-inline" style="margin-top: 10px; width:100%; border: 1.5px dashed var(--primary); color:var(--primary); background:#eff6ff;" onclick="addInvoiceItemRow()">+ افزودن ردیف</button>
379 - </div>
380 -
381 - <div class="form-row" style="background:#f1f5f9; padding:14px; border-radius:10px; margin-top:12px;">
382 - <div class="form-group" style="background:#fff; padding:12px; border-radius:8px; border:1px solid var(--border); margin-bottom:0;">
383 - <label style="font-weight:bold; border-bottom:1px solid #eee; padding-bottom:6px; margin-bottom:8px;">مالیات و تخفیف</label>
384 - <div id="box-invoice-vat-mode-row" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
385 - <span>مالیات ارزش افزوده</span>
386 - <select id="invoice-vat-mode" class="form-control" style="width:140px; min-height:36px;" onchange="handleVatModeChange()">
387 - <option value="none">غیرفعال</option>
388 - <option value="with_vat">فعال</option>
389 - </select>
390 - </div>
391 - <div id="box-invoice-vat-rate" style="display:none; justify-content:space-between; align-items:center; margin-bottom:8px; gap:8px;">
392 - <select id="invoice-vat-type" class="form-control" style="width:110px; min-height:36px;" onchange="handleVatTypeChange()">
393 - <option value="percent">درصدی</option>
394 - <option value="fixed">مبلغ ثابت</option>
395 - </select>
396 - <input type="number" id="invoice-vat-rate-input" class="form-control" style="width:100px; min-height:36px;" value="10" oninput="recomputeTotals()" />
397 - </div>
398 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px; gap:8px;">
399 - <span>تخفیف کلی فاکتور</span>
400 - <select id="invoice-discount-type" class="form-control" style="width:110px; min-height:36px;" onchange="handleDiscountTypeChange()">
401 - <option value="fixed">مبلغ ثابت</option>
402 - <option value="percent">درصدی</option>
403 - </select>
404 - </div>
405 - <div style="display:flex; justify-content:space-between; align-items:center;">
406 - <span id="label-invoice-discount-value">مبلغ تخفیف (ریال)</span>
407 - <input type="number" id="invoice-discount-fixed" class="form-control" style="width:140px; min-height:36px;" value="0" oninput="recomputeTotals()" />
408 - </div>
409 - </div>
410 -
411 - <div class="form-group" style="background:#fff; padding:12px; border-radius:8px; border:1px solid var(--border); margin-bottom:0;">
412 - <label style="font-weight:bold; border-bottom:1px solid #eee; padding-bottom:6px; margin-bottom:8px;">جمع‌بندی نهایی</label>
413 - <div style="display:flex; justify-content:space-between; margin-bottom:6px; font-size:13px;"><span>جمع کل:</span><span id="summary-subtotal" style="font-weight:bold;">۰ ریال</span></div>
414 - <div style="display:flex; justify-content:space-between; margin-bottom:6px; font-size:13px;"><span>مالیات:</span><span id="summary-vat" style="font-weight:bold;">۰ ریال</span></div>
415 - <div style="display:flex; justify-content:space-between; margin-bottom:6px; font-size:14px; border-top:1px solid #eee; padding-top:6px;">
416 - <span style="font-weight:bold; color:var(--primary);">قابل پرداخت:</span>
417 - <span id="summary-grandtotal" style="font-weight:bold; color:var(--primary);">۰ ریال</span>
418 - </div>
419 - <div style="font-size:11px; color:var(--text-muted); margin-top:4px;" id="summary-words">به حروف: صفر ریال</div>
420 - </div>
421 - </div>
422 -
423 - <div class="form-row" style="margin-top:14px;">
424 - <div class="form-group" style="margin-bottom:0;">
425 - <label>توضیحات فاکتور</label>
426 - <textarea id="invoice-desc-input" class="form-control" rows="2" placeholder="توضیحات تکمیلی..."></textarea>
427 - </div>
428 - </div>
429 -
430 - <div style="display:flex; gap:10px; margin-top: 16px; flex-wrap:wrap;">
431 - <button class="btn btn-success" id="btn-save-invoice" onclick="commitSaveInvoice()">💾 ثبت فاکتور</button>
432 - </div>
433 - </div>
434 -
435 - <div class="card no-print">
436 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; flex-wrap:wrap; gap:10px;">
437 - <h3 style="font-size: 15px;">دفتر بایگانی فاکتورها</h3>
438 - <select id="filter-invoice-company" class="form-control" style="width:200px; min-height:36px;" onchange="renderInvoices()"></select>
439 - </div>
440 - <div class="table-responsive">
441 - <table>
442 - <thead>
443 - <tr><th>شماره</th><th>فروشنده</th><th>خریدار</th><th>نوع</th><th>تاریخ</th><th>قابل پرداخت (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr>
444 - </thead>
445 - <tbody id="invoice-archive-table-body"></tbody>
446 - </table>
447 - </div>
448 - </div>
449 - </section>
450 -
451 - <section id="view-products" class="view-pane">
452 - <div class="card no-print">
453 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; flex-wrap:wrap; gap:10px;">
454 - <h2 style="font-size: 17px;">تعریف کالا / خدمت جدید</h2>
455 - <div style="display:flex; gap:8px;">
456 - <label class="btn btn-secondary btn-inline" style="min-height:36px; padding:4px 12px; font-size:13px;">
457 - 📥 ورود از اکسل
458 - <input type="file" id="excel-import-products" style="display:none;" onchange="importProductsFromExcel(event)" accept=".xlsx, .xls" />
459 - </label>
460 - <button class="btn btn-secondary btn-inline" style="min-height:36px; padding:4px 12px; font-size:13px;" onclick="downloadProductsExcelTemplate()">📄 نمونه اکسل</button>
461 - </div>
462 - </div>
463 - <div class="form-row">
464 - <div class="form-group"><label>کد کالا</label><input type="text" id="prod-code-input" class="form-control" placeholder="101" /></div>
465 - <div class="form-group"><label>عنوان کالا</label><input type="text" id="prod-name-input" class="form-control" placeholder="هارد سرور..." /></div>
466 - <div class="form-group"><label>مشخصه / مدل</label><input type="text" id="prod-spec-input" class="form-control" placeholder="2.5 اینچ SAS" /></div>
467 - <div class="form-group"><label>واحد</label><input type="text" id="prod-unit-input" class="form-control" value="عدد" /></div>
468 - </div>
469 - <div class="form-row">
470 - <div class="form-group"><label>قیمت خرید (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-buy-input" class="form-control" value="0" /></div>
471 - <div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-sale-input" class="form-control" value="0" /></div>
472 - </div>
473 - <button class="btn btn-success" onclick="commitSaveProduct()">➕ ثبت کالا</button>
474 - </div>
475 - <div class="card">
476 - <h3 style="font-size: 15px; margin-bottom: 12px;">کالاهای ثبت‌شده</h3>
477 - <div class="table-responsive">
478 - <table>
479 - <thead><tr><th>کد</th><th>نام کالا</th><th>مشخصه</th><th>واحد</th><th>قیمت فروش (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr></thead>
480 - <tbody id="products-catalog-table-body"></tbody>
481 - </table>
482 - </div>
483 - </div>
484 - </section>
485 -
486 - <section id="view-contacts" class="view-pane">
487 - <div class="card no-print">
488 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; flex-wrap:wrap; gap:10px;">
489 - <h2 style="font-size: 17px;">ثبت طرف حساب جدید</h2>
490 - <div style="display:flex; gap:8px;">
491 - <label class="btn btn-secondary btn-inline" style="min-height:36px; padding:4px 12px; font-size:13px;">
492 - 📥 ورود از اکسل
493 - <input type="file" id="excel-import-contacts" style="display:none;" onchange="importContactsFromExcel(event)" accept=".xlsx, .xls" />
494 - </label>
495 - <button class="btn btn-secondary btn-inline" style="min-height:36px; padding:4px 12px; font-size:13px;" onclick="downloadContactsExcelTemplate()">📄 نمونه اکسل</button>
496 - </div>
497 - </div>
498 - <div class="form-row">
499 - <div class="form-group">
500 - <label>نوع شخص</label>
501 - <select id="contact-entity-type" class="form-control" onchange="handleContactEntityChange()">
502 - <option value="natural">شخص حقیقی</option>
503 - <option value="legal">شخص حقوقی</option>
504 - </select>
505 - </div>
506 - <div class="form-group" id="box-contact-prefix">
507 - <label>پیشوند</label>
508 - <select id="contact-prefix-select" class="form-control">
509 - <option value="آقا/خانم">آقا / خانم</option>
510 - <option value="فروشگاه">فروشگاه</option>
511 - </select>
512 - </div>
513 - <div class="form-group" style="grid-column: span 2;" id="box-contact-name">
514 - <label>نام طرف حساب</label>
515 - <input type="text" id="contact-name-input" class="form-control" placeholder="دانشگاه صنعتی شریف..." />
516 - </div>
517 - </div>
518 - <div class="form-row">
519 - <div class="form-group"><label>نقش</label><select id="contact-role-input" class="form-control"><option value="customer">مشتری</option><option value="supplier">تامین‌کننده</option></select></div>
520 - <div class="form-group"><label>همراه</label><input type="text" id="contact-mobile-input" class="form-control" /></div>
521 - <div class="form-group"><label id="label-contact-national">شناسه ملی</label><input type="text" id="contact-national-input" class="form-control" /></div>
522 - <div class="form-group" id="box-contact-economic"><label>کد اقتصادی</label><input type="text" id="contact-economic-input" class="form-control" /></div>
523 - </div>
524 - <div class="form-row">
525 - <div class="form-group" id="box-contact-reg"><label>شماره ثبت</label><input type="text" id="contact-reg-input" class="form-control" /></div>
526 - <div class="form-group"><label>کد پستی</label><input type="text" id="contact-postal-input" class="form-control" /></div>
527 - <div class="form-group" style="grid-column: span 2;"><label>نشانی</label><input type="text" id="contact-address-input" class="form-control" /></div>
528 - </div>
529 - <button class="btn btn-success" onclick="commitSaveContact()">➕ ثبت طرف حساب</button>
530 - </div>
531 - <div class="card">
532 - <h3 style="font-size: 15px; margin-bottom: 12px;">دفتر اشخاص</h3>
533 - <div class="table-responsive">
534 - <table>
535 - <thead><tr><th>نام</th><th>نوع</th><th>شناسه / کد ملی</th><th>کد اقتصادی</th><th>کد پستی</th><th>همراه</th><th>مانده (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr></thead>
536 - <tbody id="contacts-ledger-table-body"></tbody>
537 - </table>
538 - </div>
539 - </div>
540 - </section>
541 -
542 - <section id="view-cheques" class="view-pane">
543 - <div class="card">
544 - <h2 style="font-size: 17px; margin-bottom: 14px;">ثبت چک صیادی</h2>
545 - <div class="form-row">
546 - <div class="form-group"><label>نوع</label><select id="chq-direction-input" class="form-control"><option value="inbound">دریافتی</option><option value="outbound">پرداختی</option></select></div>
547 - <div class="form-group"><label>طرف حساب</label><select id="chq-contact-select" class="form-control"></select></div>
548 - <div class="form-group"><label>شناسه صیادی</label><input type="text" id="chq-sayad-input" class="form-control" /></div>
549 - <div class="form-group"><label>بانک</label><input type="text" id="chq-bank-input" class="form-control" /></div>
550 - </div>
551 - <div class="form-row">
552 - <div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="chq-amount-input" class="form-control" /></div>
553 - <div class="form-group"><label>سررسید</label><input type="text" id="chq-due-input" class="form-control" placeholder="1405/06/30" /></div>
554 - <div class="form-group"><label>وضعیت</label><select id="chq-status-input" class="form-control"><option value="registered">در جریان</option><option value="cleared">وصول شده</option></select></div>
555 - </div>
556 - <button class="btn btn-success" onclick="commitSaveCheque()">➕ ثبت چک</button>
557 - </div>
558 - <div class="card">
559 - <h3 style="font-size: 15px; margin-bottom: 12px;">لیست چک‌ها</h3>
560 - <div class="table-responsive">
561 - <table>
562 - <thead><tr><th>نوع</th><th>طرف حساب</th><th>بانک / صیاد</th><th>مبلغ (<span class="cur-label">ریال</span>)</th><th>سررسید</th><th>وضعیت</th></tr></thead>
563 - <tbody id="cheques-ledger-table-body"></tbody>
564 - </table>
565 - </div>
566 - </div>
567 - </section>
568 -
569 - <section id="view-expenses" class="view-pane">
570 - <div class="card">
571 - <h2 style="font-size: 17px; margin-bottom: 14px;">ثبت هزینه / درآمد</h2>
572 - <div class="form-row">
573 - <div class="form-group"><label>نوع</label><select id="trx-kind-input" class="form-control"><option value="expense">هزینه</option><option value="income">درآمد</option></select></div>
574 - <div class="form-group"><label>سرفصل</label><select id="trx-category-input" class="form-control"><option value="قبوض">قبوض</option><option value="حقوق">حقوق</option><option value="سایر">سایر</option></select></div>
575 - <div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="trx-amount-input" class="form-control" /></div>
576 - <div class="form-group"><label>شرح</label><input type="text" id="trx-desc-input" class="form-control" /></div>
577 - </div>
578 - <button class="btn btn-success" onclick="commitSaveExpense()">➕ ثبت سند</button>
579 - </div>
580 - <div class="card">
581 - <h3 style="font-size: 15px; margin-bottom: 12px;">گردش هزینه و درآمد</h3>
582 - <div class="table-responsive">
583 - <table>
584 - <thead><tr><th>نوع</th><th>سرفصل</th><th>شرح</th><th>مبلغ (<span class="cur-label">ریال</span>)</th></tr></thead>
585 - <tbody id="expenses-ledger-table-body"></tbody>
586 - </table>
587 - </div>
588 - </div>
589 - </section>
590 -
591 - <section id="view-settings" class="view-pane">
592 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:14px;">
593 - <h2 style="font-size:17px;">⚙️ تنظیمات و شرکت‌ها</h2>
594 - <button class="btn btn-danger btn-inline no-print" style="padding:6px 12px; font-size:12px; min-height:32px;" onclick="handleLogout()">🚪 خروج از حساب کاربری</button>
595 - </div>
596 -
597 - <div class="accordion-item open">
598 - <div class="accordion-header" onclick="toggleAccordion(this)"><span>🏢 اطلاعات فروشگاه و چاپ (مدیریت شرکت‌ها)</span><span>▼</span></div>
599 - <div class="accordion-body">
600 - <div class="form-row">
601 - <div class="form-group"><label>نوع شخص</label><select id="company-entity-type" class="form-control"><option value="legal">حقوقی</option><option value="natural">حقیقی</option></select></div>
602 - <div class="form-group"><label>نام شرکت / فروشگاه</label><input type="text" id="company-name-input" class="form-control" placeholder="آرا سپهر راستین" /></div>
603 - <div class="form-group"><label>تلفن</label><input type="text" id="company-phone-input" class="form-control" /></div>
604 - </div>
605 - <div class="form-row">
606 - <div class="form-group"><label>شناسه ملی</label><input type="text" id="company-national-input" class="form-control" /></div>
607 - <div class="form-group"><label>کد اقتصادی</label><input type="text" id="company-economic-input" class="form-control" /></div>
608 - <div class="form-group"><label>شماره ثبت</label><input type="text" id="company-reg-input" class="form-control" /></div>
609 - <div class="form-group"><label>کد پستی</label><input type="text" id="company-postal-input" class="form-control" /></div>
610 - </div>
611 - <div class="form-group"><label>نشانی کامل</label><input type="text" id="company-address-input" class="form-control" /></div>
612 - <div class="form-group"><label>پاورقی فاکتور</label><textarea id="company-footer-input" class="form-control" rows="2"></textarea></div>
613 - <button class="btn btn-success" onclick="commitSaveCompany()">➕ ثبت شرکت جدید</button>
614 - <div style="margin-top:16px;">
615 - <h4 style="font-size:14px; margin-bottom:8px;">لیست شرکت‌های ثبت‌شده</h4>
616 - <div class="table-responsive">
617 - <table>
618 - <thead><tr><th>نام</th><th>شناسه ملی</th><th>کد اقتصادی</th><th>پیش‌فرض</th><th>عملیات</th></tr></thead>
619 - <tbody id="companies-table-body"></tbody>
620 - </table>
621 - </div>
622 - </div>
623 - </div>
624 - </div>
625 -
626 - <div class="accordion-item">
627 - <div class="accordion-header" onclick="toggleAccordion(this)"><span>⚙️ مالیات، تخفیف و واحد پول (پیش‌فرض فاکتور جدید)</span><span>▼</span></div>
628 - <div class="accordion-body">
629 - <div class="form-row">
630 - <div class="form-group">
631 - <label>قالب پیش‌فرض فاکتور</label>
632 - <select id="def-invoice-kind" class="form-control">
633 - <option value="non_formal">فاکتور غیررسمی</option>
634 - <option value="formal">فاکتور رسمی</option>
635 - <option value="pre_invoice">پیش‌فاکتور فروش</option>
636 - </select>
637 - </div>
638 - <div class="form-group">
639 - <label>وضعیت پیش‌فرض ارزش افزوده</label>
640 - <select id="def-vat-mode" class="form-control">
641 - <option value="none">بدون ارزش افزوده</option>
642 - <option value="with_vat">با ارزش افزوده</option>
643 - </select>
644 - </div>
645 - <div class="form-group">
646 - <label>نرخ ارزش افزوده (درصد)</label>
647 - <input type="number" id="def-vat-rate" class="form-control" value="10" />
648 - </div>
649 - </div>
650 - <div class="form-row">
651 - <div class="form-group">
652 - <label>واحد پول</label>
653 - <select id="def-currency-mode" class="form-control" onchange="handleCurrencyModeChange()">
654 - <option value="rial">ریال</option>
655 - <option value="toman">تومان</option>
656 - <option value="custom">سایر (دلخواه)</option>
657 - </select>
658 - </div>
659 - <div class="form-group" id="box-currency-custom" style="display:none;">
660 - <label>نام واحد پول دلخواه</label>
661 - <input type="text" id="def-currency-custom" class="form-control" placeholder="مثلاً: یورو، دلار، درهم..." />
662 - </div>
663 - </div>
664 - <button class="btn btn-primary" onclick="commitSaveDefaultSettings()">ذخیره پیش‌فرض‌ها</button>
665 - </div>
666 - </div>
667 -
668 - <div class="accordion-item">
669 - <div class="accordion-header" onclick="toggleAccordion(this)"><span>💾 دیتابیس و پشتیبان‌گیری</span><span>▼</span></div>
670 - <div class="accordion-body">
671 - <p style="font-size:13px; color:var(--text-muted); margin-bottom:12px;">وضعیت دیتابیس: <span class="badge badge-success">تفکیک کاربر فعال</span></p>
672 - <div style="display:flex; gap:10px; flex-wrap:wrap;">
673 - <button class="btn btn-secondary" onclick="exportDataBlob()">📥 دانلود فایل پشتیبان (JSON)</button>
674 - <label class="btn btn-secondary" style="margin-bottom:0;">📤 بازگردانی فایل<input type="file" id="import-json-file" style="display:none;" onchange="importDataBlob(event)" accept=".json" /></label>
675 - </div>
676 - </div>
677 - </div>
678 -
679 - <div class="accordion-item">
680 - <div class="accordion-header" onclick="toggleAccordion(this)"><span>ℹ️ درباره نرم‌افزار</span><span>▼</span></div>
681 - <div class="accordion-body">
682 - <h3 style="font-size:16px; font-weight:bold;">ایزی فاکتور - EasyFactor</h3>
683 - <p style="color:var(--text-muted); font-size:13px; margin:6px 0 12px 0;">سامانه ابری صدور فاکتور و مدیریت مالی چندکاربره</p>
684 - <p style="font-size:13px; margin-bottom:14px;">نگارش فعال: <strong>نسخه ۵.۱</strong></p>
685 -
686 - <!-- کارت توسعه‌دهنده -->
687 - <div class="about-dev-card">
688 - <div class="about-dev-avatar">د.م</div>
689 - <div class="about-dev-info">
690 - <h4>داود مهربان</h4>
691 - <p>طراح و توسعه‌دهنده نرم‌افزار</p>
692 - <p>📱 <span dir="ltr" style="font-family:Tahoma;">0912-437-6991</span></p>
693 - </div>
694 - <div class="about-dev-actions">
695 - <a class="btn-wa" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener">
696 - <svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
697 - واتس‌اپ
698 - </a>
699 - <a class="btn-call" href="tel:+989124376991">
700 - 📞 تماس
701 - </a>
702 - </div>
703 - </div>
704 -
705 - <div style="display:flex; gap:10px; margin-top:10px;">
706 - <button class="btn btn-primary" onclick="alert('آخرین نگارش نصب است.')">بررسی آپدیت</button>
707 - <button class="btn btn-secondary" onclick="alert('پشتیبانی فعال است.')">گزارش باگ</button>
708 - </div>
709 - </div>
710 - </div>
711 - </section>
712 -
713 - <section id="view-admin" class="view-pane">
714 - <div class="card">
715 - <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; flex-wrap:wrap; gap:10px;">
716 - <div>
717 - <h2 style="font-size: 18px; color:var(--danger);">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2>
718 - <p style="color:var(--text-muted); font-size:13px; margin-top:4px;">تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.</p>
719 - </div>
720 - <button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
721 - </div>
722 -
723 - <div style="background:#f8fafc; border:1px solid var(--border); border-radius:10px; padding:16px; margin-bottom:20px;">
724 - <h4 style="font-size:14px; margin-bottom:12px; color:#1e293b;">➕ ایجاد حساب کاربری جدید</h4>
725 - <div class="form-row">
726 - <div class="form-group"><label>نام کاربری</label><input type="text" id="admin-new-username" class="form-control" placeholder="نام کاربری..." /></div>
727 - <div class="form-group"><label>رمز عبور</label><input type="password" id="admin-new-password" class="form-control" placeholder="رمز عبور..." /></div>
728 - <div class="form-group">
729 - <label>طرح اولیه لایسنس</label>
730 - <select id="admin-new-subtype" class="form-control">
731 - <option value="trial">آزمایشی (۱۵ روزه)</option>
732 - <option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option>
733 - <option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option>
734 - <option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option>
735 - <option value="lifetime">اشتراک دائمی (Lifetime)</option>
736 - </select>
737 - </div>
738 - <div class="form-group" style="display:flex; align-items:flex-end;">
739 - <button class="btn btn-success" style="width:100%; min-height:44px;" onclick="adminCreateNewUser()">➕ ایجاد کاربر</button>
740 - </div>
741 - </div>
742 - </div>
743 -
744 - <div class="table-responsive">
745 - <table>
746 - <thead><tr><th>نام کاربری</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead>
747 - <tbody id="admin-users-table-body">
748 - <tr><td colspan="7" style="text-align:center; padding:20px;">در حال بارگذاری کاربران...</td></tr>
749 - </tbody>
750 - </table>
751 - </div>
752 - </div>
753 - </section>
754 -
755 - <div id="printable-invoice" style="display:none;"></div>
756 - </main>
757 - </div>
758 -
759 - <div class="modal-backdrop" id="modal-quick-contact">
760 - <div class="modal-card">
761 - <h3 style="font-size:16px; margin-bottom:12px;">➕ تعریف سریع خریدار</h3>
762 - <div class="form-row">
763 - <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>
764 - <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>
765 - <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>
766 - </div>
767 - <div class="form-row">
768 - <div class="form-group"><label id="label-quick-c-national">شناسه ملی</label><input type="text" id="quick-c-national" class="form-control" /></div>
769 - <div class="form-group" id="box-quick-c-economic"><label>کد اقتصادی</label><input type="text" id="quick-c-economic" class="form-control" /></div>
770 - <div class="form-group" id="box-quick-c-reg"><label>شماره ثبت</label><input type="text" id="quick-c-reg" class="form-control" /></div>
771 - </div>
772 - <div class="form-row">
773 - <div class="form-group"><label>کد پستی</label><input type="text" id="quick-c-postal" class="form-control" /></div>
774 - <div class="form-group"><label>تلفن</label><input type="text" id="quick-c-mobile" class="form-control" /></div>
775 - </div>
776 - <div class="form-group"><label>نشانی</label><input type="text" id="quick-c-address" class="form-control" /></div>
777 - <div style="display:flex; gap:10px; margin-top:12px;">
778 - <button class="btn btn-success" onclick="saveQuickContact()">ذخیره و انتخاب</button>
779 - <button class="btn btn-secondary" onclick="closeQuickContactModal()">انصراف</button>
780 - </div>
781 - </div>
782 - </div>
783 -
784 - <div class="modal-backdrop" id="modal-quick-product">
785 - <div class="modal-card">
786 - <h3 style="font-size:16px; margin-bottom:12px;">➕ تعریف سریع کالا</h3>
787 - <div class="form-row">
788 - <div class="form-group"><label>کد</label><input type="text" id="quick-p-code" class="form-control" /></div>
789 - <div class="form-group"><label>عنوان</label><input type="text" id="quick-p-name" class="form-control" /></div>
790 - <div class="form-group"><label>مشخصه</label><input type="text" id="quick-p-spec" class="form-control" /></div>
791 - </div>
792 - <div class="form-row">
793 - <div class="form-group"><label>واحد</label><input type="text" id="quick-p-unit" class="form-control" value="عدد" /></div>
794 - <div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="quick-p-price" class="form-control" value="0" /></div>
795 - </div>
796 - <div style="display:flex; gap:10px; margin-top:12px;">
797 - <button class="btn btn-success" onclick="saveQuickProduct()">ذخیره و افزودن</button>
798 - <button class="btn btn-secondary" onclick="closeQuickProductModal()">انصراف</button>
799 - </div>
800 - </div>
801 - </div>
802 -
803 - <div class="modal-backdrop" id="modal-admin-license-edit">
804 - <div class="modal-card">
805 - <h3 style="font-size:16px; margin-bottom:12px;" id="modal-license-user-title">تغییر مدت و لایسنس کاربر</h3>
806 - <input type="hidden" id="modal-license-target-username" />
807 - <div class="form-group">
808 - <label>انتخاب مدت و نوع لایسنس جدید</label>
809 - <select id="modal-license-duration-select" class="form-control">
810 - <option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option>
811 - <option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option>
812 - <option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option>
813 - <option value="lifetime">اشتراک دائمی (Lifetime)</option>
814 - </select>
815 - </div>
816 - <div style="display:flex; gap:10px; margin-top:16px;">
817 - <button class="btn btn-success" style="flex:1;" onclick="applyLicenseDurationChange()">تایید و اعمال لایسنس</button>
818 - <button class="btn btn-secondary" style="flex:1;" onclick="closeLicenseEditModal()">انصراف</button>
819 - </div>
820 - </div>
821 - </div>
822 -
823 - <nav class="mobile-dock">
824 - <div class="dock-tab active" onclick="switchView('view-dashboard')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path></svg><span>داشبورد</span></div>
825 - <div class="dock-tab" onclick="switchView('view-invoices')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg><span>فاکتورها</span></div>
826 - <div class="dock-tab" onclick="switchView('view-products')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path></svg><span>کالاها</span></div>
827 - <div class="dock-tab" onclick="switchView('view-contacts')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg><span>اشخاص</span></div>
828 - <div class="dock-tab" onclick="switchView('view-cheques')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path></svg><span>چک‌ها</span></div>
829 - <div class="dock-tab" onclick="switchView('view-settings')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg><span>تنظیمات</span></div>
830 - </nav>
831 -
832 - <script>
833 - const STORAGE_KEY = 'easy_factor_commercial_v4_7';
834 - const AUTH_KEY = 'easy_factor_auth_users_v4_7';
835 -
836 - function toPersianDigits(str) {
837 - if (str === null || str === undefined) return '';
838 - return String(str).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
839 - }
109 +<div id="auth-screen">
110 +<div class="auth-card">
111 +<div style="text-align:center;margin-bottom:20px">
112 +<div style="width:50px;height:50px;background:var(--primary);color:#fff;font-weight:bold;font-size:24px;border-radius:12px;display:inline-flex;align-items:center;justify-content:center;margin-bottom:10px">ایزی</div>
113 +<h2 style="font-size:20px;font-weight:bold;color:var(--text)">سامانه ایزی فاکتور</h2>
114 +<p style="font-size:12px;color:var(--text-muted);margin-top:4px">ورود یا ثبت‌نام در سامانه</p>
115 +</div>
116 +<div id="auth-form-container">
117 +<div class="form-group"><label>نام کاربری یا شماره همراه</label><input type="text" id="auth-username" class="form-control" placeholder="admin یا شماره همراه" /></div>
118 +<div class="form-group"><label>رمز عبور</label><input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" /></div>
119 +<div style="display:flex;gap:10px;margin-top:16px">
120 +<button class="btn btn-primary" style="flex:1" onclick="handleLogin()">ورود</button>
121 +<button class="btn btn-secondary" style="flex:1" onclick="switchToRegister()">ثبت‌نام</button>
122 +</div>
123 +</div>
124 +</div>
125 +</div>
126 +
127 +<div class="app-root">
128 +<aside class="sidebar">
129 +<div class="brand-box">
130 +<div class="brand-icon">ایزی</div>
131 +<div><h2 style="font-size:15px;font-weight:bold">ایزی فاکتور</h2><small style="color:var(--text-muted);font-size:11px">نسخه چندکاربره ۵.۲</small></div>
132 +</div>
133 +<ul class="sidebar-menu">
134 +<li><a href="#" class="nav-link" data-view="view-dashboard" onclick="switchView('view-dashboard');return false">📊 داشبورد تحلیلی</a></li>
135 +<li><a href="#" class="nav-link" data-view="view-invoices" onclick="switchView('view-invoices');return false">🧾 صدور فاکتور و اسناد</a></li>
136 +<li><a href="#" class="nav-link" data-view="view-products" onclick="switchView('view-products');return false">📦 کالاها و خدمات</a></li>
137 +<li><a href="#" class="nav-link" data-view="view-contacts" onclick="switchView('view-contacts');return false">👥 طرف‌حساب‌ها و معین</a></li>
138 +<li><a href="#" class="nav-link" data-view="view-cheques" onclick="switchView('view-cheques');return false">💳 چک‌ها و صیاد</a></li>
139 +<li><a href="#" class="nav-link" data-view="view-expenses" onclick="switchView('view-expenses');return false">💰 هزینه‌ها و درآمد</a></li>
140 +<li><a href="#" class="nav-link" data-view="view-settings" onclick="switchView('view-settings');return false">⚙️ تنظیمات و شرکت‌ها</a></li>
141 +<li id="menu-admin-panel" style="display:none"><a href="#" class="nav-link" data-view="view-admin" onclick="switchView('view-admin');return false" style="background:#fef2f2;color:#dc2626;font-weight:bold">👑 مدیریت کاربران و لایسنس</a></li>
142 +</ul>
143 +<div class="sidebar-footer">
144 +<span id="logged-user-label">کاربر</span>
145 +<button class="btn btn-danger btn-inline" style="padding:4px 10px;font-size:11px;min-height:28px;width:100%;margin-top:4px" onclick="handleLogout()">🚪 خروج از حساب کاربری</button>
146 +</div>
147 +</aside>
148 +
149 +<a class="whatsapp-support no-print" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener" title="پشتیبانی واتس‌اپ">
150 +<svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
151 +<span>پشتیبانی واتس‌اپ</span>
152 +</a>
153 +
154 +<main class="main-surface">
155 +
156 +<section id="view-dashboard" class="view-pane active">
157 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
158 +<div><h1 style="font-size:20px;font-weight:bold">سامانه ایزی فاکتور</h1><p style="color:var(--text-muted);font-size:13px" id="dashboard-date-display"></p></div>
159 +<div style="display:flex;align-items:center;gap:10px">
160 +<span id="user-license-status-badge" class="badge badge-warning">در حال بررسی...</span>
161 +<button class="btn btn-inline no-print" onclick="startNewInvoice()">➕ فاکتور جدید</button>
162 +</div>
163 +</div>
164 +<div id="dashboard-license-details"></div>
165 +
166 +<div class="grid-kpi">
167 +<div class="kpi-unit"><div class="kpi-icon" style="background:#eff6ff;color:var(--primary)">💰</div><div><div class="kpi-lbl">مجموع فروش ثبت‌شده (<span class="cur-label">ریال</span>)</div><div class="kpi-val" id="kpi-sales-sum">۰ ریال</div></div></div>
168 +<div class="kpi-unit"><div class="kpi-icon" style="background:#ecfdf5;color:var(--success)">📥</div><div><div class="kpi-lbl">دریافت وصول شده</div><div class="kpi-val" id="kpi-settled-sum">۰ ریال</div></div></div>
169 +<div class="kpi-unit"><div class="kpi-icon" style="background:#fffbeb;color:var(--warning)">⏳</div><div><div class="kpi-lbl">مانده مطالبات نسیه</div><div class="kpi-val" id="kpi-debtors-sum">۰ ریال</div></div></div>
170 +<div class="kpi-unit"><div class="kpi-icon" style="background:#fef2f2;color:var(--danger)">💳</div><div><div class="kpi-lbl">چک‌های باز صیادی</div><div class="kpi-val" id="kpi-cheques-count">۰ فقره</div></div></div>
171 +</div>
172 +
173 +<div class="card">
174 +<h3 style="font-size:15px;margin-bottom:12px">آخرین فاکتورهای صادر شده</h3>
175 +<div class="table-responsive">
176 +<table>
177 +<thead><tr><th>شماره</th><th>فروشنده (شرکت)</th><th>خریدار</th><th>نوع فاکتور</th><th>ارزش افزوده</th><th>مبلغ کل (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr></thead>
178 +<tbody id="dashboard-recent-table"><tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr></tbody>
179 +</table>
180 +</div>
181 +</div>
182 +
183 +<div class="card no-print" style="background:linear-gradient(135deg,#ecfdf5,#f0fdf4);border-color:#bbf7d0">
184 +<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;justify-content:space-between">
185 +<div style="display:flex;align-items:center;gap:12px">
186 +<div style="width:44px;height:44px;border-radius:50%;background:linear-gradient(135deg,#25D366,#128C7E);display:flex;align-items:center;justify-content:center;color:#fff">
187 +<svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
188 +</div>
189 +<div><h3 style="font-size:15px;color:#166534">پشتیبانی سریع</h3><p style="font-size:12.5px;color:#475569;margin-top:2px">سؤالی دارید؟ از طریق واتس‌اپ با ما در تماس باشید.</p></div>
190 +</div>
191 +<a href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener" class="btn btn-inline" style="background:linear-gradient(135deg,#25D366,#128C7E)">💬 گفتگو در واتس‌اپ</a>
192 +</div>
193 +</div>
194 +</section>
195 +
196 +<section id="view-invoices" class="view-pane">
197 +<div class="card no-print">
198 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
199 +<h2 style="font-size:17px" id="invoice-form-title">صدور فاکتور جدید</h2>
200 +<button class="btn btn-secondary btn-inline" style="display:none;padding:4px 10px;font-size:12px" id="btn-cancel-edit" onclick="cancelInvoiceEdit()">انصراف از ویرایش</button>
201 +</div>
202 +<input type="hidden" id="edit-invoice-id" value="" />
203 +
204 +<div class="form-row" style="background:#f1f5f9;padding:12px;border-radius:10px;margin-bottom:14px">
205 +<div class="form-group" style="margin-bottom:0"><label>تاریخ فاکتور</label><input type="text" id="invoice-date-input" class="form-control" /></div>
206 +<div class="form-group" style="margin-bottom:0"><label>شماره فاکتور</label><input type="text" id="invoice-number" class="form-control" placeholder="PINV-31" /></div>
207 +<div class="form-group" style="margin-bottom:0">
208 +<label>قالب و نوع سند</label>
209 +<select id="invoice-kind" class="form-control" onchange="handleInvoiceKindChange()">
210 +<option value="non_formal">فاکتور غیررسمی</option>
211 +<option value="formal">فاکتور رسمی</option>
212 +<option value="pre_invoice">پیش‌فاکتور فروش</option>
213 +</select>
214 +</div>
215 +</div>
216 +
217 +<div class="form-row">
218 +<div class="form-group"><label>فروشنده (سربرگ شرکت)</label><select id="invoice-company-id" class="form-control" onchange="onActiveCompanyFilterChange()"></select></div>
219 +<div class="form-group">
220 +<label style="display:flex;justify-content:space-between"><span>نام خریدار را وارد یا انتخاب کنید</span><a href="#" style="color:var(--primary);text-decoration:none" onclick="openQuickContactModal();return false">➕ شخص جدید</a></label>
221 +<div style="display:flex;gap:8px">
222 +<select id="invoice-contact-id" class="form-control" style="flex:1"></select>
223 +<button class="btn btn-secondary btn-inline" type="button" onclick="openQuickContactModal()" style="padding:0 12px;min-height:42px">➕</button>
224 +</div>
225 +</div>
226 +</div>
227 +
228 +<div style="margin:16px 0">
229 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
230 +<h4 style="font-size:14px">اقلام کالا یا خدمات</h4>
231 +<button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px;padding:4px 10px" onclick="openQuickProductModal()">➕ کالای جدید</button>
232 +</div>
233 +<div class="table-responsive">
234 +<table id="invoice-items-table">
235 +<thead><tr style="background:#e2e8f0"><th style="width:40px;text-align:center">#</th><th>شرح کالا | خدمات</th><th style="width:90px;text-align:center">واحد</th><th style="width:100px;text-align:center">مقدار</th><th style="width:160px;text-align:left">قیمت واحد (<span class="cur-label">ریال</span>)</th><th style="width:170px;text-align:left">قیمت کل (<span class="cur-label">ریال</span>)</th><th style="width:50px;text-align:center">حذف</th></tr></thead>
236 +<tbody id="invoice-items-table-body"></tbody>
237 +</table>
238 +</div>
239 +<button class="btn btn-secondary btn-inline" style="margin-top:10px;width:100%;border:1.5px dashed var(--primary);color:var(--primary);background:#eff6ff" onclick="addInvoiceItemRow()">+ افزودن ردیف</button>
240 +</div>
241 +
242 +<div class="form-row" style="background:#f1f5f9;padding:14px;border-radius:10px;margin-top:12px">
243 +<div class="form-group" style="background:#fff;padding:12px;border-radius:8px;border:1px solid var(--border);margin-bottom:0">
244 +<label style="font-weight:bold;border-bottom:1px solid #eee;padding-bottom:6px;margin-bottom:8px">مالیات و تخفیف</label>
245 +<div id="box-invoice-vat-mode-row" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
246 +<span>مالیات ارزش افزوده</span>
247 +<select id="invoice-vat-mode" class="form-control" style="width:140px;min-height:36px" onchange="handleVatModeChange()"><option value="none">غیرفعال</option><option value="with_vat">فعال</option></select>
248 +</div>
249 +<div id="box-invoice-vat-rate" style="display:none;justify-content:space-between;align-items:center;margin-bottom:8px;gap:8px">
250 +<select id="invoice-vat-type" class="form-control" style="width:110px;min-height:36px" onchange="handleVatTypeChange()"><option value="percent">درصدی</option><option value="fixed">مبلغ ثابت</option></select>
251 +<input type="number" id="invoice-vat-rate-input" class="form-control" style="width:100px;min-height:36px" value="10" oninput="recomputeTotals()" />
252 +</div>
253 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;gap:8px">
254 +<span>تخفیف کلی فاکتور</span>
255 +<select id="invoice-discount-type" class="form-control" style="width:110px;min-height:36px" onchange="handleDiscountTypeChange()"><option value="fixed">مبلغ ثابت</option><option value="percent">درصدی</option></select>
256 +</div>
257 +<div style="display:flex;justify-content:space-between;align-items:center">
258 +<span id="label-invoice-discount-value">مبلغ تخفیف (ریال)</span>
259 +<input type="number" id="invoice-discount-fixed" class="form-control" style="width:140px;min-height:36px" value="0" oninput="recomputeTotals()" />
260 +</div>
261 +</div>
262 +<div class="form-group" style="background:#fff;padding:12px;border-radius:8px;border:1px solid var(--border);margin-bottom:0">
263 +<label style="font-weight:bold;border-bottom:1px solid #eee;padding-bottom:6px;margin-bottom:8px">جمع‌بندی نهایی</label>
264 +<div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:13px"><span>جمع کل:</span><span id="summary-subtotal" style="font-weight:bold">۰ ریال</span></div>
265 +<div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:13px"><span>مالیات:</span><span id="summary-vat" style="font-weight:bold">۰ ریال</span></div>
266 +<div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:14px;border-top:1px solid #eee;padding-top:6px"><span style="font-weight:bold;color:var(--primary)">قابل پرداخت:</span><span id="summary-grandtotal" style="font-weight:bold;color:var(--primary)">۰ ریال</span></div>
267 +<div style="font-size:11px;color:var(--text-muted);margin-top:4px" id="summary-words">به حروف: صفر ریال</div>
268 +</div>
269 +</div>
270 +
271 +<div class="form-row" style="margin-top:14px">
272 +<div class="form-group" style="margin-bottom:0"><label>توضیحات فاکتور</label><textarea id="invoice-desc-input" class="form-control" rows="2" placeholder="توضیحات تکمیلی..."></textarea></div>
273 +</div>
274 +
275 +<div style="display:flex;gap:10px;margin-top:16px;flex-wrap:wrap">
276 +<button class="btn btn-success" id="btn-save-invoice" onclick="commitSaveInvoice()">💾 ثبت فاکتور</button>
277 +</div>
278 +</div>
279 +
280 +<div class="card no-print">
281 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:10px">
282 +<h3 style="font-size:15px">دفتر بایگانی فاکتورها</h3>
283 +<select id="filter-invoice-company" class="form-control" style="width:200px;min-height:36px" onchange="renderInvoices()"></select>
284 +</div>
285 +<div class="table-responsive">
286 +<table>
287 +<thead><tr><th>شماره</th><th>فروشنده</th><th>خریدار</th><th>نوع</th><th>تاریخ</th><th>قابل پرداخت (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr></thead>
288 +<tbody id="invoice-archive-table-body"></tbody>
289 +</table>
290 +</div>
291 +</div>
292 +</section>
293 +
294 +<section id="view-products" class="view-pane">
295 +<div class="card no-print">
296 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
297 +<h2 style="font-size:17px">تعریف کالا / خدمت جدید</h2>
298 +<div style="display:flex;gap:8px">
299 +<label class="btn btn-secondary btn-inline" style="min-height:36px;padding:4px 12px;font-size:13px">📥 ورود از اکسل<input type="file" id="excel-import-products" style="display:none" onchange="importProductsFromExcel(event)" accept=".xlsx, .xls" /></label>
300 +<button class="btn btn-secondary btn-inline" style="min-height:36px;padding:4px 12px;font-size:13px" onclick="downloadProductsExcelTemplate()">📄 نمونه اکسل</button>
301 +</div>
302 +</div>
303 +<div class="form-row">
304 +<div class="form-group"><label>کد کالا</label><input type="text" id="prod-code-input" class="form-control" placeholder="101" /></div>
305 +<div class="form-group"><label>عنوان کالا</label><input type="text" id="prod-name-input" class="form-control" placeholder="هارد سرور..." /></div>
306 +<div class="form-group"><label>مشخصه / مدل</label><input type="text" id="prod-spec-input" class="form-control" placeholder="2.5 اینچ SAS" /></div>
307 +<div class="form-group"><label>واحد</label><input type="text" id="prod-unit-input" class="form-control" value="عدد" /></div>
308 +</div>
309 +<div class="form-row">
310 +<div class="form-group"><label>قیمت خرید (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-buy-input" class="form-control" value="0" /></div>
311 +<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-sale-input" class="form-control" value="0" /></div>
312 +</div>
313 +<button class="btn btn-success" onclick="commitSaveProduct()">➕ ثبت کالا</button>
314 +</div>
315 +<div class="card">
316 +<h3 style="font-size:15px;margin-bottom:12px">کالاهای ثبت‌شده</h3>
317 +<div class="table-responsive">
318 +<table><thead><tr><th>کد</th><th>نام کالا</th><th>مشخصه</th><th>واحد</th><th>قیمت فروش (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr></thead><tbody id="products-catalog-table-body"></tbody></table>
319 +</div>
320 +</div>
321 +</section>
322 +
323 +<section id="view-contacts" class="view-pane">
324 +<div class="card no-print">
325 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
326 +<h2 style="font-size:17px">ثبت طرف حساب جدید</h2>
327 +<div style="display:flex;gap:8px">
328 +<label class="btn btn-secondary btn-inline" style="min-height:36px;padding:4px 12px;font-size:13px">📥 ورود از اکسل<input type="file" id="excel-import-contacts" style="display:none" onchange="importContactsFromExcel(event)" accept=".xlsx, .xls" /></label>
329 +<button class="btn btn-secondary btn-inline" style="min-height:36px;padding:4px 12px;font-size:13px" onclick="downloadContactsExcelTemplate()">📄 نمونه اکسل</button>
330 +</div>
331 +</div>
332 +<div class="form-row">
333 +<div class="form-group"><label>نوع شخص</label><select id="contact-entity-type" class="form-control" onchange="handleContactEntityChange()"><option value="natural">شخص حقیقی</option><option value="legal">شخص حقوقی</option></select></div>
334 +<div class="form-group" id="box-contact-prefix"><label>پیشوند</label><select id="contact-prefix-select" class="form-control"><option value="آقا/خانم">آقا / خانم</option><option value="فروشگاه">فروشگاه</option></select></div>
335 +<div class="form-group" style="grid-column:span 2" id="box-contact-name"><label>نام طرف حساب</label><input type="text" id="contact-name-input" class="form-control" placeholder="دانشگاه صنعتی شریف..." /></div>
336 +</div>
337 +<div class="form-row">
338 +<div class="form-group"><label>نقش</label><select id="contact-role-input" class="form-control"><option value="customer">مشتری</option><option value="supplier">تامین‌کننده</option></select></div>
339 +<div class="form-group"><label>همراه</label><input type="text" id="contact-mobile-input" class="form-control" /></div>
340 +<div class="form-group"><label id="label-contact-national">شناسه ملی</label><input type="text" id="contact-national-input" class="form-control" /></div>
341 +<div class="form-group" id="box-contact-economic"><label>کد اقتصادی</label><input type="text" id="contact-economic-input" class="form-control" /></div>
342 +</div>
343 +<div class="form-row">
344 +<div class="form-group" id="box-contact-reg"><label>شماره ثبت</label><input type="text" id="contact-reg-input" class="form-control" /></div>
345 +<div class="form-group"><label>کد پستی</label><input type="text" id="contact-postal-input" class="form-control" /></div>
346 +<div class="form-group" style="grid-column:span 2"><label>نشانی</label><input type="text" id="contact-address-input" class="form-control" /></div>
347 +</div>
348 +<button class="btn btn-success" onclick="commitSaveContact()">➕ ثبت طرف حساب</button>
349 +</div>
350 +<div class="card">
351 +<h3 style="font-size:15px;margin-bottom:12px">دفتر اشخاص</h3>
352 +<div class="table-responsive">
353 +<table><thead><tr><th>نام</th><th>نوع</th><th>شناسه / کد ملی</th><th>کد اقتصادی</th><th>کد پستی</th><th>همراه</th><th>مانده (<span class="cur-label">ریال</span>)</th><th>عملیات</th></tr></thead><tbody id="contacts-ledger-table-body"></tbody></table>
354 +</div>
355 +</div>
356 +</section>
357 +
358 +<section id="view-cheques" class="view-pane">
359 +<div class="card">
360 +<h2 style="font-size:17px;margin-bottom:14px">ثبت چک صیادی</h2>
361 +<div class="form-row">
362 +<div class="form-group"><label>نوع</label><select id="chq-direction-input" class="form-control"><option value="inbound">دریافتی</option><option value="outbound">پرداختی</option></select></div>
363 +<div class="form-group"><label>طرف حساب</label><select id="chq-contact-select" class="form-control"></select></div>
364 +<div class="form-group"><label>شناسه صیادی</label><input type="text" id="chq-sayad-input" class="form-control" /></div>
365 +<div class="form-group"><label>بانک</label><input type="text" id="chq-bank-input" class="form-control" /></div>
366 +</div>
367 +<div class="form-row">
368 +<div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="chq-amount-input" class="form-control" /></div>
369 +<div class="form-group"><label>سررسید</label><input type="text" id="chq-due-input" class="form-control" placeholder="1405/06/30" /></div>
370 +<div class="form-group"><label>وضعیت</label><select id="chq-status-input" class="form-control"><option value="registered">در جریان</option><option value="cleared">وصول شده</option></select></div>
371 +</div>
372 +<button class="btn btn-success" onclick="commitSaveCheque()">➕ ثبت چک</button>
373 +</div>
374 +<div class="card">
375 +<h3 style="font-size:15px;margin-bottom:12px">لیست چک‌ها</h3>
376 +<div class="table-responsive"><table><thead><tr><th>نوع</th><th>طرف حساب</th><th>بانک / صیاد</th><th>مبلغ (<span class="cur-label">ریال</span>)</th><th>سررسید</th><th>وضعیت</th></tr></thead><tbody id="cheques-ledger-table-body"></tbody></table></div>
377 +</div>
378 +</section>
379 +
380 +<section id="view-expenses" class="view-pane">
381 +<div class="card">
382 +<h2 style="font-size:17px;margin-bottom:14px">ثبت هزینه / درآمد</h2>
383 +<div class="form-row">
384 +<div class="form-group"><label>نوع</label><select id="trx-kind-input" class="form-control"><option value="expense">هزینه</option><option value="income">درآمد</option></select></div>
385 +<div class="form-group"><label>سرفصل</label><select id="trx-category-input" class="form-control"><option value="قبوض">قبوض</option><option value="حقوق">حقوق</option><option value="سایر">سایر</option></select></div>
386 +<div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="trx-amount-input" class="form-control" /></div>
387 +<div class="form-group"><label>شرح</label><input type="text" id="trx-desc-input" class="form-control" /></div>
388 +</div>
389 +<button class="btn btn-success" onclick="commitSaveExpense()">➕ ثبت سند</button>
390 +</div>
391 +<div class="card">
392 +<h3 style="font-size:15px;margin-bottom:12px">گردش هزینه و درآمد</h3>
393 +<div class="table-responsive"><table><thead><tr><th>نوع</th><th>سرفصل</th><th>شرح</th><th>مبلغ (<span class="cur-label">ریال</span>)</th></tr></thead><tbody id="expenses-ledger-table-body"></tbody></table></div>
394 +</div>
395 +</section>
396 +
397 +<section id="view-settings" class="view-pane">
398 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
399 +<h2 style="font-size:17px">⚙️ تنظیمات و شرکت‌ها</h2>
400 +<button class="btn btn-danger btn-inline no-print" style="padding:6px 12px;font-size:12px;min-height:32px" onclick="handleLogout()">🚪 خروج از حساب کاربری</button>
401 +</div>
402 +
403 +<div class="accordion-item open">
404 +<div class="accordion-header" onclick="toggleAccordion(this)"><span>🏢 اطلاعات فروشگاه و چاپ (مدیریت شرکت‌ها)</span><span>▼</span></div>
405 +<div class="accordion-body">
406 +<div class="form-row">
407 +<div class="form-group"><label>نوع شخص</label><select id="company-entity-type" class="form-control"><option value="legal">حقوقی</option><option value="natural">حقیقی</option></select></div>
408 +<div class="form-group"><label>نام شرکت / فروشگاه</label><input type="text" id="company-name-input" class="form-control" placeholder="آرا سپهر راستین" /></div>
409 +<div class="form-group"><label>تلفن</label><input type="text" id="company-phone-input" class="form-control" /></div>
410 +</div>
411 +<div class="form-row">
412 +<div class="form-group"><label>شناسه ملی</label><input type="text" id="company-national-input" class="form-control" /></div>
413 +<div class="form-group"><label>کد اقتصادی</label><input type="text" id="company-economic-input" class="form-control" /></div>
414 +<div class="form-group"><label>شماره ثبت</label><input type="text" id="company-reg-input" class="form-control" /></div>
415 +<div class="form-group"><label>کد پستی</label><input type="text" id="company-postal-input" class="form-control" /></div>
416 +</div>
417 +<div class="form-group"><label>نشانی کامل</label><input type="text" id="company-address-input" class="form-control" /></div>
418 +<div class="form-group"><label>پاورقی فاکتور</label><textarea id="company-footer-input" class="form-control" rows="2"></textarea></div>
419 +<button class="btn btn-success" onclick="commitSaveCompany()">➕ ثبت شرکت جدید</button>
420 +<div style="margin-top:16px">
421 +<h4 style="font-size:14px;margin-bottom:8px">لیست شرکت‌های ثبت‌شده</h4>
422 +<div class="table-responsive"><table><thead><tr><th>نام</th><th>شناسه ملی</th><th>کد اقتصادی</th><th>پیش‌فرض</th><th>عملیات</th></tr></thead><tbody id="companies-table-body"></tbody></table></div>
423 +</div>
424 +</div>
425 +</div>
426 +
427 +<div class="accordion-item">
428 +<div class="accordion-header" onclick="toggleAccordion(this)"><span>⚙️ مالیات، تخفیف و واحد پول (پیش‌فرض فاکتور جدید)</span><span>▼</span></div>
429 +<div class="accordion-body">
430 +<div class="form-row">
431 +<div class="form-group"><label>قالب پیش‌فرض فاکتور</label><select id="def-invoice-kind" class="form-control"><option value="non_formal">فاکتور غیررسمی</option><option value="formal">فاکتور رسمی</option><option value="pre_invoice">پیش‌فاکتور فروش</option></select></div>
432 +<div class="form-group"><label>وضعیت پیش‌فرض ارزش افزوده</label><select id="def-vat-mode" class="form-control"><option value="none">بدون ارزش افزوده</option><option value="with_vat">با ارزش افزوده</option></select></div>
433 +<div class="form-group"><label>نرخ ارزش افزوده (درصد)</label><input type="number" id="def-vat-rate" class="form-control" value="10" /></div>
434 +</div>
435 +<div class="form-row">
436 +<div class="form-group"><label>واحد پول</label><select id="def-currency-mode" class="form-control" onchange="handleCurrencyModeChange()"><option value="rial">ریال</option><option value="toman">تومان</option><option value="custom">سایر (دلخواه)</option></select></div>
437 +<div class="form-group" id="box-currency-custom" style="display:none"><label>نام واحد پول دلخواه</label><input type="text" id="def-currency-custom" class="form-control" placeholder="مثلاً: یورو، دلار، درهم..." /></div>
438 +</div>
439 +<button class="btn btn-primary" onclick="commitSaveDefaultSettings()">ذخیره پیش‌فرض‌ها</button>
440 +</div>
441 +</div>
442 +
443 +<div class="accordion-item">
444 +<div class="accordion-header" onclick="toggleAccordion(this)"><span>💾 دیتابیس و پشتیبان‌گیری</span><span>▼</span></div>
445 +<div class="accordion-body">
446 +<p style="font-size:13px;color:var(--text-muted);margin-bottom:12px">وضعیت دیتابیس: <span class="badge badge-success">تفکیک کاربر فعال</span></p>
447 +<div style="display:flex;gap:10px;flex-wrap:wrap">
448 +<button class="btn btn-secondary" onclick="exportDataBlob()">📥 دانلود فایل پشتیبان (JSON)</button>
449 +<label class="btn btn-secondary" style="margin-bottom:0">📤 بازگردانی فایل<input type="file" id="import-json-file" style="display:none" onchange="importDataBlob(event)" accept=".json" /></label>
450 +</div>
451 +</div>
452 +</div>
453 +
454 +<div class="accordion-item">
455 +<div class="accordion-header" onclick="toggleAccordion(this)"><span>ℹ️ درباره نرم‌افزار</span><span>▼</span></div>
456 +<div class="accordion-body">
457 +<h3 style="font-size:16px;font-weight:bold">ایزی فاکتور - EasyFactor</h3>
458 +<p style="color:var(--text-muted);font-size:13px;margin:6px 0 12px 0">سامانه ابری صدور فاکتور و مدیریت مالی چندکاربره</p>
459 +<p style="font-size:13px;margin-bottom:8px">نگارش فعال: <strong>نسخه ۵.۲</strong></p>
460 +<div class="about-dev-card">
461 +<div class="about-dev-avatar">د.م</div>
462 +<div class="about-dev-info">
463 +<h4>داود مهربان</h4>
464 +<p>طراح و توسعه‌دهنده نرم‌افزار</p>
465 +<p>📱 <span dir="ltr" style="font-family:Tahoma">0912-437-6991</span></p>
466 +</div>
467 +<div class="about-dev-actions">
468 +<a class="btn-wa" href="https://wa.me/989124376991?text=سلام%20داود%20عزیز،%20درباره%20نرم‌افزار%20ایزی%20فاکتور%20سؤال%20داشتم." target="_blank" rel="noopener">
469 +<svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
470 +واتس‌اپ
471 +</a>
472 +<a class="btn-call" href="tel:+989124376991">📞 تماس</a>
473 +</div>
474 +</div>
475 +<div style="display:flex;gap:10px;margin-top:10px">
476 +<button class="btn btn-primary" onclick="alert('آخرین نگارش نصب است.')">بررسی آپدیت</button>
477 +<button class="btn btn-secondary" onclick="alert('پشتیبانی فعال است.')">گزارش باگ</button>
478 +</div>
479 +</div>
480 +</div>
481 +</section>
482 +
483 +<section id="view-admin" class="view-pane">
484 +<div class="card">
485 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:10px">
486 +<div><h2 style="font-size:18px;color:var(--danger)">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2><p style="color:var(--text-muted);font-size:13px;margin-top:4px">تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.</p></div>
487 +<button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
488 +</div>
489 +<div style="background:#f8fafc;border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:20px">
490 +<h4 style="font-size:14px;margin-bottom:12px;color:#1e293b">➕ ایجاد حساب کاربری جدید</h4>
491 +<div class="form-row">
492 +<div class="form-group"><label>نام کاربری</label><input type="text" id="admin-new-username" class="form-control" placeholder="نام کاربری..." /></div>
493 +<div class="form-group"><label>رمز عبور</label><input type="password" id="admin-new-password" class="form-control" placeholder="رمز عبور..." /></div>
494 +<div class="form-group"><label>طرح اولیه لایسنس</label><select id="admin-new-subtype" class="form-control"><option value="trial">آزمایشی (۱۵ روزه)</option><option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option><option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option><option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option><option value="lifetime">اشتراک دائمی (Lifetime)</option></select></div>
495 +<div class="form-group" style="display:flex;align-items:flex-end"><button class="btn btn-success" style="width:100%;min-height:44px" onclick="adminCreateNewUser()">➕ ایجاد کاربر</button></div>
496 +</div>
497 +</div>
498 +<div class="table-responsive">
499 +<table><thead><tr><th>نام کاربری</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead><tbody id="admin-users-table-body"><tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr></tbody></table>
500 +</div>
501 +</div>
502 +</section>
503 +
504 +<div id="printable-invoice" style="display:none"></div>
505 +</main>
506 +</div>
507 +
508 +<div class="modal-backdrop" id="modal-quick-contact">
509 +<div class="modal-card">
510 +<h3 style="font-size:16px;margin-bottom:12px">➕ تعریف سریع خریدار</h3>
511 +<div class="form-row">
512 +<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>
513 +<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>
514 +<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>
515 +</div>
516 +<div class="form-row">
517 +<div class="form-group"><label id="label-quick-c-national">شناسه ملی</label><input type="text" id="quick-c-national" class="form-control" /></div>
518 +<div class="form-group" id="box-quick-c-economic"><label>کد اقتصادی</label><input type="text" id="quick-c-economic" class="form-control" /></div>
519 +<div class="form-group" id="box-quick-c-reg"><label>شماره ثبت</label><input type="text" id="quick-c-reg" class="form-control" /></div>
520 +</div>
521 +<div class="form-row">
522 +<div class="form-group"><label>کد پستی</label><input type="text" id="quick-c-postal" class="form-control" /></div>
523 +<div class="form-group"><label>تلفن</label><input type="text" id="quick-c-mobile" class="form-control" /></div>
524 +</div>
525 +<div class="form-group"><label>نشانی</label><input type="text" id="quick-c-address" class="form-control" /></div>
526 +<div style="display:flex;gap:10px;margin-top:12px">
527 +<button class="btn btn-success" onclick="saveQuickContact()">ذخیره و انتخاب</button>
528 +<button class="btn btn-secondary" onclick="closeQuickContactModal()">انصراف</button>
529 +</div>
530 +</div>
531 +</div>
532 +
533 +<div class="modal-backdrop" id="modal-quick-product">
534 +<div class="modal-card">
535 +<h3 style="font-size:16px;margin-bottom:12px">➕ تعریف سریع کالا</h3>
536 +<div class="form-row">
537 +<div class="form-group"><label>کد</label><input type="text" id="quick-p-code" class="form-control" /></div>
538 +<div class="form-group"><label>عنوان</label><input type="text" id="quick-p-name" class="form-control" /></div>
539 +<div class="form-group"><label>مشخصه</label><input type="text" id="quick-p-spec" class="form-control" /></div>
540 +</div>
541 +<div class="form-row">
542 +<div class="form-group"><label>واحد</label><input type="text" id="quick-p-unit" class="form-control" value="عدد" /></div>
543 +<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="quick-p-price" class="form-control" value="0" /></div>
544 +</div>
545 +<div style="display:flex;gap:10px;margin-top:12px">
546 +<button class="btn btn-success" onclick="saveQuickProduct()">ذخیره و افزودن</button>
547 +<button class="btn btn-secondary" onclick="closeQuickProductModal()">انصراف</button>
548 +</div>
549 +</div>
550 +</div>
551 +
552 +<div class="modal-backdrop" id="modal-admin-license-edit">
553 +<div class="modal-card">
554 +<h3 style="font-size:16px;margin-bottom:12px" id="modal-license-user-title">تغییر مدت و لایسنس کاربر</h3>
555 +<input type="hidden" id="modal-license-target-username" />
556 +<div class="form-group"><label>انتخاب مدت و نوع لایسنس جدید</label><select id="modal-license-duration-select" class="form-control"><option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option><option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option><option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option><option value="lifetime">اشتراک دائمی (Lifetime)</option></select></div>
557 +<div style="display:flex;gap:10px;margin-top:16px">
558 +<button class="btn btn-success" style="flex:1" onclick="applyLicenseDurationChange()">تایید و اعمال لایسنس</button>
559 +<button class="btn btn-secondary" style="flex:1" onclick="closeLicenseEditModal()">انصراف</button>
560 +</div>
561 +</div>
562 +</div>
563 +
564 +<nav class="mobile-dock">
565 +<div class="dock-tab active" onclick="switchView('view-dashboard')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path></svg><span>داشبورد</span></div>
566 +<div class="dock-tab" onclick="switchView('view-invoices')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg><span>فاکتورها</span></div>
567 +<div class="dock-tab" onclick="switchView('view-products')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path></svg><span>کالاها</span></div>
568 +<div class="dock-tab" onclick="switchView('view-contacts')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg><span>اشخاص</span></div>
569 +<div class="dock-tab" onclick="switchView('view-cheques')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path></svg><span>چک‌ها</span></div>
570 +<div class="dock-tab" onclick="switchView('view-settings')"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg><span>تنظیمات</span></div>
571 +</nav>
572
841 - function formatToJalali(dateInput) {
842 - if (!dateInput) return '—';
843 - let dateObj;
844 - if (dateInput instanceof Date) dateObj = dateInput;
845 - else if (typeof dateInput === 'string' && dateInput.includes('/')) return toPersianDigits(dateInput);
846 - else {
847 - const str = String(dateInput).split('T')[0];
848 - const parts = str.split('-');
849 - if (parts.length === 3) dateObj = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
850 - else dateObj = new Date(dateInput);
851 - }
852 - if (isNaN(dateObj.getTime())) return toPersianDigits(String(dateInput));
853 - return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(dateObj);
854 - }
573 +<script>
574 +const STORAGE_KEY = 'easy_factor_commercial_v4_7';
575 +const AUTH_KEY = 'easy_factor_auth_users_v4_7';
576
856 - function getRemainingDays(endDateStr) {
857 - if (!endDateStr) return 0;
858 - if (String(endDateStr).startsWith('2099')) return Infinity;
859 - const str = String(endDateStr).split('T')[0];
860 - const parts = str.split('-');
861 - if (parts.length !== 3) return 0;
862 - const end = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 23, 59, 59);
863 - const now = new Date();
864 - return Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
865 - }
577 +function toPersianDigits(str) {
578 + if (str === null || str === undefined) return '';
579 + return String(str).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
580 +}
581
867 - function addDaysToDate(baseDateStr, days) {
868 - let d;
869 - if (baseDateStr) {
870 - const parts = String(baseDateStr).split('T')[0].split('-');
871 - d = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
872 - } else d = new Date();
873 - if (isNaN(d.getTime())) d = new Date();
874 - d.setDate(d.getDate() + days);
875 - return d.toISOString().split('T')[0];
876 - }
582 +function formatToJalali(dateInput) {
583 + if (!dateInput) return '—';
584 + let dateObj;
585 + if (dateInput instanceof Date) dateObj = dateInput;
586 + else if (typeof dateInput === 'string' && dateInput.includes('/')) return toPersianDigits(dateInput);
587 + else {
588 + const str = String(dateInput).split('T')[0];
589 + const parts = str.split('-');
590 + if (parts.length === 3) dateObj = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
591 + else dateObj = new Date(dateInput);
592 + }
593 + if (isNaN(dateObj.getTime())) return toPersianDigits(String(dateInput));
594 + return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(dateObj);
595 +}
596
878 - let currentUser = null;
879 - let usersDb = [];
880 -
881 - const defaultAdminUser = {
882 - id: 'user_admin', username: 'admin', pass: 'admin123', role: 'admin',
883 - createdAt: '2026-09-16T00:00:00.000Z',
884 - subscriptionType: 'lifetime', subscriptionStart: '2026-09-16', subscriptionEnd: '2099-01-01',
885 - licenseStatus: 'active',
886 - subscription: { type: 'lifetime', startDate: '2026-09-16', endDate: '2099-01-01', status: 'active' }
887 - };
888 -
889 - function loadUsers() {
890 - const saved = localStorage.getItem(AUTH_KEY);
891 - if (saved) { try { usersDb = JSON.parse(saved); } catch (e) { usersDb = []; } }
892 - if (!Array.isArray(usersDb) || usersDb.length === 0) {
893 - usersDb = [defaultAdminUser]; persistUsers();
894 - } else {
895 - let modified = false;
896 - usersDb.forEach((u, idx) => {
897 - if (!u.id) { u.id = u.username === 'admin' ? 'user_admin' : 'usr_' + Date.now() + '_' + idx; modified = true; }
898 - if (!u.createdAt) { u.createdAt = new Date().toISOString(); modified = true; }
899 - if (!u.subscription) {
900 - u.subscription = {
901 - type: u.subscriptionType || 'trial',
902 - startDate: u.subscriptionStart || new Date().toISOString().split('T')[0],
903 - endDate: u.subscriptionEnd || addDaysToDate(null, 15),
904 - status: (u.subscriptionType === 'lifetime' || u.role === 'admin') ? 'active' : 'trial'
905 - };
906 - modified = true;
907 - }
908 - u.subscriptionType = u.subscription.type;
909 - u.subscriptionStart = u.subscription.startDate;
910 - u.subscriptionEnd = u.subscription.endDate;
911 - u.licenseStatus = u.subscription.status;
912 - });
913 - if (modified) persistUsers();
914 - }
915 - return usersDb;
916 - }
597 +function getRemainingDays(endDateStr) {
598 + if (!endDateStr) return 0;
599 + if (String(endDateStr).startsWith('2099')) return Infinity;
600 + const str = String(endDateStr).split('T')[0];
601 + const parts = str.split('-');
602 + if (parts.length !== 3) return 0;
603 + const end = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 23, 59, 59);
604 + const now = new Date();
605 + return Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
606 +}
607
918 - function persistUsers() { localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb)); }
608 +function addDaysToDate(baseDateStr, days) {
609 + let d;
610 + if (baseDateStr) {
611 + const parts = String(baseDateStr).split('T')[0].split('-');
612 + d = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
613 + } else d = new Date();
614 + if (isNaN(d.getTime())) d = new Date();
615 + d.setDate(d.getDate() + days);
616 + return d.toISOString().split('T')[0];
617 +}
618
920 - function initAuthSystem() {
921 - loadUsers();
922 - const activeSession = sessionStorage.getItem('easy_factor_session_v4_7');
923 - if (activeSession) {
924 - const u = usersDb.find(x => x.username === activeSession);
925 - if (u) { loginSuccess(u); return; }
619 +let currentUser = null;
620 +let usersDb = [];
621 +
622 +const defaultAdminUser = {
623 + id: 'user_admin', username: 'admin', pass: 'admin123', role: 'admin',
624 + createdAt: '2026-09-16T00:00:00.000Z',
625 + subscriptionType: 'lifetime', subscriptionStart: '2026-09-16', subscriptionEnd: '2099-01-01',
626 + licenseStatus: 'active',
627 + subscription: { type: 'lifetime', startDate: '2026-09-16', endDate: '2099-01-01', status: 'active' }
628 +};
629 +
630 +function loadUsers() {
631 + const saved = localStorage.getItem(AUTH_KEY);
632 + if (saved) { try { usersDb = JSON.parse(saved); } catch (e) { usersDb = []; } }
633 + if (!Array.isArray(usersDb) || usersDb.length === 0) {
634 + usersDb = [defaultAdminUser]; persistUsers();
635 + } else {
636 + let modified = false;
637 + usersDb.forEach((u, idx) => {
638 + if (!u.id) { u.id = u.username === 'admin' ? 'user_admin' : 'usr_' + Date.now() + '_' + idx; modified = true; }
639 + if (!u.createdAt) { u.createdAt = new Date().toISOString(); modified = true; }
640 + if (!u.subscription) {
641 + u.subscription = {
642 + type: u.subscriptionType || 'trial',
643 + startDate: u.subscriptionStart || new Date().toISOString().split('T')[0],
644 + endDate: u.subscriptionEnd || addDaysToDate(null, 15),
645 + status: (u.subscriptionType === 'lifetime' || u.role === 'admin') ? 'active' : 'trial'
646 + };
647 + modified = true;
648 }
927 - document.getElementById('auth-screen').style.display = 'flex';
928 - }
929 -
930 - function handleLogin() {
931 - const user = document.getElementById('auth-username').value.trim();
932 - const pass = document.getElementById('auth-password').value.trim();
933 - loadUsers();
934 - const found = usersDb.find(x => x.username === user && x.pass === pass);
935 - if (!found) { alert('نام کاربری یا رمز عبور اشتباه است.'); return; }
936 - sessionStorage.setItem('easy_factor_session_v4_7', found.username);
937 - loginSuccess(found);
938 - }
939 -
940 - function switchToRegister() {
941 - const user = document.getElementById('auth-username').value.trim();
942 - const pass = document.getElementById('auth-password').value.trim();
943 - if (!user || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
944 - loadUsers();
945 - if (usersDb.some(x => x.username === user)) { alert('این نام کاربری قبلاً ثبت‌نام کرده است.'); return; }
946 - const today = new Date().toISOString().split('T')[0];
947 - const expireStr = addDaysToDate(today, 15);
948 - const newUser = {
949 - id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
950 - username: user, pass: pass, role: 'user', createdAt: new Date().toISOString(),
951 - subscriptionType: 'trial', subscriptionStart: today, subscriptionEnd: expireStr,
952 - licenseStatus: 'trial',
953 - subscription: { type: 'trial', startDate: today, endDate: expireStr, status: 'trial' }
954 - };
955 - usersDb.push(newUser);
956 - persistUsers();
957 - sessionStorage.setItem('easy_factor_session_v4_7', newUser.username);
958 - alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
959 - loginSuccess(newUser);
960 - }
961 -
962 - function loginSuccess(userObj) {
963 - currentUser = userObj;
964 - document.getElementById('auth-screen').style.display = 'none';
965 - document.getElementById('logged-user-label').innerText = 'کاربر: ' + userObj.username + (userObj.role === 'admin' ? ' (مدیر سیستم)' : '');
966 - const adminMenu = document.getElementById('menu-admin-panel');
967 - adminMenu.style.display = (userObj.role === 'admin') ? 'block' : 'none';
968 - initDatastore();
969 - }
970 -
971 - function handleLogout() {
972 - sessionStorage.removeItem('easy_factor_session_v4_7');
973 - window.location.reload();
974 - }
649 + u.subscriptionType = u.subscription.type;
650 + u.subscriptionStart = u.subscription.startDate;
651 + u.subscriptionEnd = u.subscription.endDate;
652 + u.licenseStatus = u.subscription.status;
653 + });
654 + if (modified) persistUsers();
655 + }
656 + return usersDb;
657 +}
658
976 - function updateLicenseDisplay(user) {
977 - if (!user) return;
978 - const badge = document.getElementById('user-license-status-badge');
979 - const detailsBox = document.getElementById('dashboard-license-details');
980 - if (detailsBox) { detailsBox.style.display = 'none'; detailsBox.innerHTML = ''; }
981 - const sub = user.subscription || { type: user.subscriptionType || 'trial', startDate: user.subscriptionStart || user.createdAt, endDate: user.subscriptionEnd, status: user.licenseStatus || 'trial' };
982 - const remDays = getRemainingDays(sub.endDate);
983 - const isExpired = remDays <= 0 && sub.type !== 'lifetime';
984 - const hasActiveLicense = (sub.status === 'active') && (sub.type === 'lifetime' || !isExpired) && (sub.type !== 'trial');
985 - if (!badge) return;
986 - if (hasActiveLicense) {
987 - badge.className = 'badge badge-success';
988 - badge.innerText = (sub.type === 'lifetime') ? 'وضعیت اشتراک : نامحدود' : `وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
989 - } else if (isExpired || sub.status === 'cancelled') {
990 - badge.className = 'badge badge-danger';
991 - badge.innerText = 'وضعیت اشتراک : منقضی شده';
992 - } else {
993 - badge.className = 'badge badge-warning';
994 - badge.innerText = `وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
995 - }
996 - }
659 +function persistUsers() { localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb)); }
660
998 - function adminCreateNewUser() {
999 - const username = document.getElementById('admin-new-username').value.trim();
1000 - const pass = document.getElementById('admin-new-password').value.trim();
1001 - const plan = document.getElementById('admin-new-subtype').value;
1002 - if (!username || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
1003 - loadUsers();
1004 - if (usersDb.some(u => u.username === username)) { alert('این نام کاربری از قبل وجود دارد.'); return; }
1005 - const today = new Date().toISOString().split('T')[0];
1006 - let endDate = today; let status = 'active';
1007 - if (plan === 'trial') { endDate = addDaysToDate(today, 15); status = 'trial'; }
1008 - else if (plan === 'monthly') endDate = addDaysToDate(today, 30);
1009 - else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
1010 - else if (plan === 'annual') endDate = addDaysToDate(today, 365);
1011 - else if (plan === 'lifetime') endDate = '2099-01-01';
1012 - const newUser = {
1013 - id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
1014 - username, pass, role: 'user', createdAt: new Date().toISOString(),
1015 - subscriptionType: plan, subscriptionStart: today, subscriptionEnd: endDate, licenseStatus: status,
1016 - subscription: { type: plan, startDate: today, endDate: endDate, status: status }
1017 - };
1018 - usersDb.push(newUser); persistUsers();
1019 - alert(`کاربر جدید "${username}" با موفقیت ایجاد شد.`);
1020 - document.getElementById('admin-new-username').value = '';
1021 - document.getElementById('admin-new-password').value = '';
1022 - renderAdminPanel();
1023 - }
661 +function initAuthSystem() {
662 + loadUsers();
663 + const activeSession = sessionStorage.getItem('easy_factor_session_v4_7');
664 + if (activeSession) {
665 + const u = usersDb.find(x => x.username === activeSession);
666 + if (u) { loginSuccess(u); return; }
667 + }
668 + document.getElementById('auth-screen').style.display = 'flex';
669 +}
670
1025 - function refreshAdminPanel() { loadUsers(); renderAdminPanel(); }
1026 -
1027 - function renderAdminPanel() {
1028 - const tbody = document.getElementById('admin-users-table-body');
1029 - if (!tbody) return;
1030 - loadUsers();
1031 - if (usersDb.length === 0) { tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding:20px;">هیچ کاربری یافت نشد.</td></tr>'; return; }
1032 - const planLabels = { monthly: 'طرح ۱ ماهه', three_months: 'طرح ۳ ماهه', annual: 'طرح ۱ ساله', lifetime: 'دائمی (Lifetime)', trial: 'آزمایشی (Trial)' };
1033 - tbody.innerHTML = usersDb.map(u => {
1034 - const sub = u.subscription || { type: u.subscriptionType || 'trial', startDate: u.subscriptionStart, endDate: u.subscriptionEnd, status: u.licenseStatus || 'trial' };
1035 - const remDays = getRemainingDays(sub.endDate);
1036 - const isExp = remDays <= 0 && sub.type !== 'lifetime';
1037 - let statusBadge = '';
1038 - if (sub.status === 'cancelled') statusBadge = '<span class="badge badge-danger">لغو شده</span>';
1039 - else if (sub.status === 'active') statusBadge = isExp ? '<span class="badge badge-danger">منقضی شده</span>' : '<span class="badge badge-success">فعال</span>';
1040 - else statusBadge = isExp ? '<span class="badge badge-danger">آزمایشی منقضی</span>' : '<span class="badge badge-warning">آزمایشی</span>';
1041 - const startJalali = formatToJalali(sub.startDate);
1042 - const endJalali = sub.type === 'lifetime' ? 'نامحدود' : formatToJalali(sub.endDate);
1043 - const remDaysText = sub.type === 'lifetime' ? 'نامحدود' : toPersianDigits(Math.max(0, remDays)) + ' روز';
1044 - return `
1045 - <tr>
1046 - <td><strong>${u.username}</strong> ${u.role === 'admin' ? '<span class="badge badge-info">مدیر</span>' : ''}</td>
1047 - <td>${statusBadge}</td>
1048 - <td>${planLabels[sub.type] || sub.type}</td>
1049 - <td>${startJalali}</td>
1050 - <td>${endJalali}</td>
1051 - <td>${remDaysText}</td>
1052 - <td style="display:flex; gap:6px; flex-wrap:wrap;">
1053 - <button class="btn btn-success btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="adminActivateLicense('${u.username}')">فعال‌سازی</button>
1054 - <button class="btn btn-secondary btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="openLicenseEditModal('${u.username}')">تغییر مدت</button>
1055 - <button class="btn btn-secondary btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="adminExtendSubscription('${u.username}', 30)">+۳۰ روز</button>
1056 - ${sub.status !== 'cancelled' ? `<button class="btn btn-danger btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="adminCancelSubscription('${u.username}')">لغو اشتراک</button>` : ''}
1057 - </td>
1058 - </tr>`;
1059 - }).join('');
1060 - }
671 +function handleLogin() {
672 + const user = document.getElementById('auth-username').value.trim();
673 + const pass = document.getElementById('auth-password').value.trim();
674 + loadUsers();
675 + const found = usersDb.find(x => x.username === user && x.pass === pass);
676 + if (!found) { alert('نام کاربری یا رمز عبور اشتباه است.'); return; }
677 + sessionStorage.setItem('easy_factor_session_v4_7', found.username);
678 + loginSuccess(found);
679 +}
680
1062 - function adminActivateLicense(username) {
1063 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
1064 - const today = new Date().toISOString().split('T')[0];
1065 - const endDate = addDaysToDate(today, 30);
1066 - u.subscription = { type: 'monthly', startDate: today, endDate: endDate, status: 'active' };
1067 - u.subscriptionType = 'monthly'; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
1068 - persistUsers();
1069 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1070 - alert(`لایسنس ۱ ماهه فعال برای کاربر ${username} ثبت شد.`);
1071 - renderAdminPanel();
1072 - }
681 +function switchToRegister() {
682 + const user = document.getElementById('auth-username').value.trim();
683 + const pass = document.getElementById('auth-password').value.trim();
684 + if (!user || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
685 + loadUsers();
686 + if (usersDb.some(x => x.username === user)) { alert('این نام کاربری قبلاً ثبت‌نام کرده است.'); return; }
687 + const today = new Date().toISOString().split('T')[0];
688 + const expireStr = addDaysToDate(today, 15);
689 + const newUser = {
690 + id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
691 + username: user, pass: pass, role: 'user', createdAt: new Date().toISOString(),
692 + subscriptionType: 'trial', subscriptionStart: today, subscriptionEnd: expireStr,
693 + licenseStatus: 'trial',
694 + subscription: { type: 'trial', startDate: today, endDate: expireStr, status: 'trial' }
695 + };
696 + usersDb.push(newUser);
697 + persistUsers();
698 + sessionStorage.setItem('easy_factor_session_v4_7', newUser.username);
699 + alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
700 + loginSuccess(newUser);
701 +}
702
1074 - function openLicenseEditModal(username) {
1075 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
1076 - document.getElementById('modal-license-target-username').value = username;
1077 - document.getElementById('modal-license-user-title').innerText = `تغییر مدت و نوع لایسنس: ${username}`;
1078 - document.getElementById('modal-license-duration-select').value = u.subscription?.type || 'monthly';
1079 - document.getElementById('modal-admin-license-edit').classList.add('active');
1080 - }
1081 - function closeLicenseEditModal() { document.getElementById('modal-admin-license-edit').classList.remove('active'); }
1082 -
1083 - function applyLicenseDurationChange() {
1084 - const username = document.getElementById('modal-license-target-username').value;
1085 - const plan = document.getElementById('modal-license-duration-select').value;
1086 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
1087 - const today = new Date().toISOString().split('T')[0];
1088 - let endDate = today;
1089 - if (plan === 'monthly') endDate = addDaysToDate(today, 30);
1090 - else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
1091 - else if (plan === 'annual') endDate = addDaysToDate(today, 365);
1092 - else if (plan === 'lifetime') endDate = '2099-01-01';
1093 - u.subscription = { type: plan, startDate: today, endDate: endDate, status: 'active' };
1094 - u.subscriptionType = plan; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
1095 - persistUsers();
1096 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1097 - closeLicenseEditModal();
1098 - alert(`طرح لایسنس کاربر ${username} با موفقیت به "${plan}" تغییر یافت.`);
1099 - renderAdminPanel();
1100 - }
703 +function loginSuccess(userObj) {
704 + currentUser = userObj;
705 + document.getElementById('auth-screen').style.display = 'none';
706 + document.getElementById('logged-user-label').innerText = 'کاربر: ' + userObj.username + (userObj.role === 'admin' ? ' (مدیر سیستم)' : '');
707 + const adminMenu = document.getElementById('menu-admin-panel');
708 + adminMenu.style.display = (userObj.role === 'admin') ? 'block' : 'none';
709 + initDatastore();
710 +}
711
1102 - function adminExtendSubscription(username, days) {
1103 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
1104 - let currentEnd = u.subscription?.endDate || new Date().toISOString().split('T')[0];
1105 - if (currentEnd.startsWith('2099')) { alert('این حساب دائمی است و نیازی به تمدید ندارد.'); return; }
1106 - const today = new Date().toISOString().split('T')[0];
1107 - const base = (currentEnd < today) ? today : currentEnd;
1108 - const newEnd = addDaysToDate(base, days);
1109 - if (!u.subscription) u.subscription = {};
1110 - u.subscription.endDate = newEnd;
1111 - u.subscription.status = 'active';
1112 - if (u.subscription.type === 'trial') u.subscription.type = 'monthly';
1113 - u.subscriptionType = u.subscription.type; u.subscriptionEnd = newEnd; u.licenseStatus = 'active';
1114 - persistUsers();
1115 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1116 - alert(`اشتراک کاربر ${username} به مدت ${days} روز تمدید گردید.`);
1117 - renderAdminPanel();
1118 - }
712 +function handleLogout() {
713 + sessionStorage.removeItem('easy_factor_session_v4_7');
714 + window.location.reload();
715 +}
716
1120 - function adminCancelSubscription(username) {
1121 - if (!confirm(`آیا از لغو اشتراک کاربر ${username} اطمینان دارید؟`)) return;
1122 - loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
1123 - if (!u.subscription) u.subscription = {};
1124 - u.subscription.status = 'cancelled'; u.licenseStatus = 'cancelled';
1125 - persistUsers();
1126 - if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
1127 - alert(`اشتراک کاربر ${username} لغو گردید.`);
1128 - renderAdminPanel();
1129 - }
717 +function updateLicenseDisplay(user) {
718 + if (!user) return;
719 + const badge = document.getElementById('user-license-status-badge');
720 + const detailsBox = document.getElementById('dashboard-license-details');
721 + if (detailsBox) { detailsBox.style.display = 'none'; detailsBox.innerHTML = ''; }
722 + const sub = user.subscription || { type: user.subscriptionType || 'trial', startDate: user.subscriptionStart || user.createdAt, endDate: user.subscriptionEnd, status: user.licenseStatus || 'trial' };
723 + const remDays = getRemainingDays(sub.endDate);
724 + const isExpired = remDays <= 0 && sub.type !== 'lifetime';
725 + const hasActiveLicense = (sub.status === 'active') && (sub.type === 'lifetime' || !isExpired) && (sub.type !== 'trial');
726 + if (!badge) return;
727 + if (hasActiveLicense) {
728 + badge.className = 'badge badge-success';
729 + badge.innerText = (sub.type === 'lifetime') ? 'وضعیت اشتراک : نامحدود' : `وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
730 + } else if (isExpired || sub.status === 'cancelled') {
731 + badge.className = 'badge badge-danger';
732 + badge.innerText = 'وضعیت اشتراک : منقضی شده';
733 + } else {
734 + badge.className = 'badge badge-warning';
735 + badge.innerText = `وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
736 + }
737 +}
738
1131 - let datastore = { companies: [], contacts: [], products: [], invoices: [], cheques: [], expenses: [], settings: [] };
1132 -
1133 - function getMyProducts() { return !currentUser ? [] : datastore.products.filter(p => p.ownerUserId === currentUser.id); }
1134 - function getMyContacts() { return !currentUser ? [] : datastore.contacts.filter(c => c.ownerUserId === currentUser.id); }
1135 - function getMyCompanies() { return !currentUser ? [] : datastore.companies.filter(c => c.ownerUserId === currentUser.id); }
1136 - function getMyInvoices() { return !currentUser ? [] : datastore.invoices.filter(i => i.ownerUserId === currentUser.id); }
1137 - function getMyCheques() { return !currentUser ? [] : datastore.cheques.filter(c => c.ownerUserId === currentUser.id); }
1138 - function getMyExpenses() { return !currentUser ? [] : datastore.expenses.filter(e => e.ownerUserId === currentUser.id); }
1139 - function getMySettings() {
1140 - if (!currentUser) return { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
1141 - if (!Array.isArray(datastore.settings)) datastore.settings = [];
1142 - let s = datastore.settings.find(item => item.ownerUserId === currentUser.id);
1143 - if (!s) {
1144 - s = { ownerUserId: currentUser.id, invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
1145 - datastore.settings.push(s);
1146 - }
1147 - if (typeof s.currency_mode === 'undefined') s.currency_mode = 'rial';
1148 - if (typeof s.currency_custom === 'undefined') s.currency_custom = '';
1149 - return s;
1150 - }
739 +function adminCreateNewUser() {
740 + const username = document.getElementById('admin-new-username').value.trim();
741 + const pass = document.getElementById('admin-new-password').value.trim();
742 + const plan = document.getElementById('admin-new-subtype').value;
743 + if (!username || !pass) { alert('لطفاً نام کاربری و رمز عبور را وارد کنید.'); return; }
744 + loadUsers();
745 + if (usersDb.some(u => u.username === username)) { alert('این نام کاربری از قبل وجود دارد.'); return; }
746 + const today = new Date().toISOString().split('T')[0];
747 + let endDate = today; let status = 'active';
748 + if (plan === 'trial') { endDate = addDaysToDate(today, 15); status = 'trial'; }
749 + else if (plan === 'monthly') endDate = addDaysToDate(today, 30);
750 + else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
751 + else if (plan === 'annual') endDate = addDaysToDate(today, 365);
752 + else if (plan === 'lifetime') endDate = '2099-01-01';
753 + const newUser = {
754 + id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
755 + username, pass, role: 'user', createdAt: new Date().toISOString(),
756 + subscriptionType: plan, subscriptionStart: today, subscriptionEnd: endDate, licenseStatus: status,
757 + subscription: { type: plan, startDate: today, endDate: endDate, status: status }
758 + };
759 + usersDb.push(newUser); persistUsers();
760 + alert(`کاربر جدید "${username}" با موفقیت ایجاد شد.`);
761 + document.getElementById('admin-new-username').value = '';
762 + document.getElementById('admin-new-password').value = '';
763 + renderAdminPanel();
764 +}
765
1152 - function saveDatastore() {
1153 - try { localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore)); return true; }
1154 - catch (err) { console.error('Error saving datastore:', err); return false; }
1155 - }
766 +function refreshAdminPanel() { loadUsers(); renderAdminPanel(); }
767 +
768 +function renderAdminPanel() {
769 + const tbody = document.getElementById('admin-users-table-body');
770 + if (!tbody) return;
771 + loadUsers();
772 + if (usersDb.length === 0) { tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>'; return; }
773 + const planLabels = { monthly: 'طرح ۱ ماهه', three_months: 'طرح ۳ ماهه', annual: 'طرح ۱ ساله', lifetime: 'دائمی (Lifetime)', trial: 'آزمایشی (Trial)' };
774 + tbody.innerHTML = usersDb.map(u => {
775 + const sub = u.subscription || { type: u.subscriptionType || 'trial', startDate: u.subscriptionStart, endDate: u.subscriptionEnd, status: u.licenseStatus || 'trial' };
776 + const remDays = getRemainingDays(sub.endDate);
777 + const isExp = remDays <= 0 && sub.type !== 'lifetime';
778 + let statusBadge = '';
779 + if (sub.status === 'cancelled') statusBadge = '<span class="badge badge-danger">لغو شده</span>';
780 + else if (sub.status === 'active') statusBadge = isExp ? '<span class="badge badge-danger">منقضی شده</span>' : '<span class="badge badge-success">فعال</span>';
781 + else statusBadge = isExp ? '<span class="badge badge-danger">آزمایشی منقضی</span>' : '<span class="badge badge-warning">آزمایشی</span>';
782 + const startJalali = formatToJalali(sub.startDate);
783 + const endJalali = sub.type === 'lifetime' ? 'نامحدود' : formatToJalali(sub.endDate);
784 + const remDaysText = sub.type === 'lifetime' ? 'نامحدود' : toPersianDigits(Math.max(0, remDays)) + ' روز';
785 + return `<tr><td><strong>${u.username}</strong> ${u.role === 'admin' ? '<span class="badge badge-info">مدیر</span>' : ''}</td><td>${statusBadge}</td><td>${planLabels[sub.type] || sub.type}</td><td>${startJalali}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${u.username}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${u.username}')">تغییر مدت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${u.username}', 30)">+۳۰ روز</button>${sub.status !== 'cancelled' ? `<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${u.username}')">لغو اشتراک</button>` : ''}</td></tr>`;
786 + }).join('');
787 +}
788
1157 - function loadDatastore() {
1158 - const persisted = localStorage.getItem(STORAGE_KEY);
1159 - if (persisted) { try { datastore = JSON.parse(persisted); } catch (e) { console.error(e); } }
1160 - ['companies','contacts','products','invoices','cheques','expenses','settings'].forEach(k => { if (!Array.isArray(datastore[k])) datastore[k] = []; });
1161 -
1162 - if (datastore.companies.length === 0 && datastore.products.length === 0) {
1163 - datastore.companies.push({
1164 - id: 'COMP-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'آرا سپهر راستین',
1165 - phone: '09124376991', national_id: '14008507476', economic_code: '14008507476',
1166 - reg_number: '544926', postal_code: '1445956311',
1167 - address: 'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',
1168 - footer: 'از خرید شما سپاسگزاریم.'
1169 - });
1170 - datastore.contacts.push({
1171 - id: 'C-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'شرکت دانشگاه صنعتی شریف',
1172 - mobile: '02166165000', national_id: '14002830256', economic_code: '14002830256',
1173 - reg_number: '', postal_code: '1458889694', address: 'طرشت محله تیموری پلاک 435',
1174 - balance: 7978300000, role: 'customer'
1175 - });
1176 - datastore.products.push(
1177 - { id: 'P-1', ownerUserId: 'user_admin', code: '1', name: 'سوئیچ شبکه 24 پورت فیبر نوری', spec: 'با 2 پاور 350', unit: 'عدد', buy_price: 1800000000, sale_price: 2180000000, stock: 10, type: 'good' },
1178 - { id: 'P-2', ownerUserId: 'user_admin', code: '2', name: 'هارد 2.5 اینچ سرور', spec: '', unit: 'عدد', buy_price: 30000000, sale_price: 37000000, stock: 10, type: 'good' }
1179 - );
1180 - datastore.settings.push({
1181 - ownerUserId: 'user_admin', invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10,
1182 - default_company_id: 'COMP-1', currency_mode: 'rial', currency_custom: ''
1183 - });
1184 - saveDatastore();
1185 - } else {
1186 - let migrated = false;
1187 - ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(coll => {
1188 - datastore[coll].forEach(item => { if (!item.ownerUserId) { item.ownerUserId = 'user_admin'; migrated = true; } });
1189 - });
1190 - datastore.settings.forEach(s => {
1191 - if (typeof s.currency_mode === 'undefined') { s.currency_mode = 'rial'; migrated = true; }
1192 - if (typeof s.currency_custom === 'undefined') { s.currency_custom = ''; migrated = true; }
1193 - });
1194 - if (migrated) saveDatastore();
1195 - }
1196 - return datastore;
1197 - }
789 +function adminActivateLicense(username) {
790 + loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
791 + const today = new Date().toISOString().split('T')[0];
792 + const endDate = addDaysToDate(today, 30);
793 + u.subscription = { type: 'monthly', startDate: today, endDate: endDate, status: 'active' };
794 + u.subscriptionType = 'monthly'; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
795 + persistUsers();
796 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
797 + alert(`لایسنس ۱ ماهه فعال برای کاربر ${username} ثبت شد.`);
798 + renderAdminPanel();
799 +}
800
1199 - function initDatastore() { loadDatastore(); refreshAllSurfaces(); }
801 +function openLicenseEditModal(username) {
802 + loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
803 + document.getElementById('modal-license-target-username').value = username;
804 + document.getElementById('modal-license-user-title').innerText = `تغییر مدت و نوع لایسنس: ${username}`;
805 + document.getElementById('modal-license-duration-select').value = u.subscription?.type || 'monthly';
806 + document.getElementById('modal-admin-license-edit').classList.add('active');
807 +}
808 +function closeLicenseEditModal() { document.getElementById('modal-admin-license-edit').classList.remove('active'); }
809 +
810 +function applyLicenseDurationChange() {
811 + const username = document.getElementById('modal-license-target-username').value;
812 + const plan = document.getElementById('modal-license-duration-select').value;
813 + loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
814 + const today = new Date().toISOString().split('T')[0];
815 + let endDate = today;
816 + if (plan === 'monthly') endDate = addDaysToDate(today, 30);
817 + else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
818 + else if (plan === 'annual') endDate = addDaysToDate(today, 365);
819 + else if (plan === 'lifetime') endDate = '2099-01-01';
820 + u.subscription = { type: plan, startDate: today, endDate: endDate, status: 'active' };
821 + u.subscriptionType = plan; u.subscriptionStart = today; u.subscriptionEnd = endDate; u.licenseStatus = 'active';
822 + persistUsers();
823 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
824 + closeLicenseEditModal();
825 + alert(`طرح لایسنس کاربر ${username} با موفقیت به "${plan}" تغییر یافت.`);
826 + renderAdminPanel();
827 +}
828
1201 - function getJalaliDate() { return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { dateStyle: 'full' }).format(new Date()); }
1202 - function getJalaliNumeric() { return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); }
829 +function adminExtendSubscription(username, days) {
830 + loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
831 + let currentEnd = u.subscription?.endDate || new Date().toISOString().split('T')[0];
832 + if (currentEnd.startsWith('2099')) { alert('این حساب دائمی است و نیازی به تمدید ندارد.'); return; }
833 + const today = new Date().toISOString().split('T')[0];
834 + const base = (currentEnd < today) ? today : currentEnd;
835 + const newEnd = addDaysToDate(base, days);
836 + if (!u.subscription) u.subscription = {};
837 + u.subscription.endDate = newEnd;
838 + u.subscription.status = 'active';
839 + if (u.subscription.type === 'trial') u.subscription.type = 'monthly';
840 + u.subscriptionType = u.subscription.type; u.subscriptionEnd = newEnd; u.licenseStatus = 'active';
841 + persistUsers();
842 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
843 + alert(`اشتراک کاربر ${username} به مدت ${days} روز تمدید گردید.`);
844 + renderAdminPanel();
845 +}
846
1204 - function getCurrencyLabel() {
1205 - const s = getMySettings();
1206 - if (s.currency_mode === 'toman') return 'تومان';
1207 - if (s.currency_mode === 'custom') return (s.currency_custom || '').trim() || 'واحد پول';
1208 - return 'ریال';
1209 - }
847 +function adminCancelSubscription(username) {
848 + if (!confirm(`آیا از لغو اشتراک کاربر ${username} اطمینان دارید؟`)) return;
849 + loadUsers(); const u = usersDb.find(x => x.username === username); if (!u) return;
850 + if (!u.subscription) u.subscription = {};
851 + u.subscription.status = 'cancelled'; u.licenseStatus = 'cancelled';
852 + persistUsers();
853 + if (currentUser && currentUser.username === username) { currentUser = u; updateLicenseDisplay(currentUser); }
854 + alert(`اشتراک کاربر ${username} لغو گردید.`);
855 + renderAdminPanel();
856 +}
857
1211 - function refreshCurrencyLabels() {
1212 - const label = getCurrencyLabel();
1213 - document.querySelectorAll('.cur-label').forEach(el => { el.innerText = label; });
1214 - }
858 +let datastore = { companies: [], contacts: [], products: [], invoices: [], cheques: [], expenses: [], settings: [] };
859 +
860 +function getMyProducts() { return !currentUser ? [] : datastore.products.filter(p => p.ownerUserId === currentUser.id); }
861 +function getMyContacts() { return !currentUser ? [] : datastore.contacts.filter(c => c.ownerUserId === currentUser.id); }
862 +function getMyCompanies() { return !currentUser ? [] : datastore.companies.filter(c => c.ownerUserId === currentUser.id); }
863 +function getMyInvoices() { return !currentUser ? [] : datastore.invoices.filter(i => i.ownerUserId === currentUser.id); }
864 +function getMyCheques() { return !currentUser ? [] : datastore.cheques.filter(c => c.ownerUserId === currentUser.id); }
865 +function getMyExpenses() { return !currentUser ? [] : datastore.expenses.filter(e => e.ownerUserId === currentUser.id); }
866 +
867 +function getMySettings() {
868 + if (!currentUser) return { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
869 + if (!Array.isArray(datastore.settings)) datastore.settings = [];
870 + let s = datastore.settings.find(item => item.ownerUserId === currentUser.id);
871 + if (!s) {
872 + s = { ownerUserId: currentUser.id, invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '', currency_mode: 'rial', currency_custom: '' };
873 + datastore.settings.push(s);
874 + }
875 + if (typeof s.currency_mode === 'undefined') s.currency_mode = 'rial';
876 + if (typeof s.currency_custom === 'undefined') s.currency_custom = '';
877 + return s;
878 +}
879
1216 - function handleCurrencyModeChange() {
1217 - const mode = document.getElementById('def-currency-mode').value;
1218 - document.getElementById('box-currency-custom').style.display = (mode === 'custom') ? 'block' : 'none';
1219 - }
880 +function saveDatastore() {
881 + try { localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore)); return true; }
882 + catch (err) { console.error('Error saving datastore:', err); return false; }
883 +}
884
1221 - function switchView(viewId) {
1222 - document.querySelectorAll('.view-pane').forEach(el => el.classList.remove('active'));
1223 - const target = document.getElementById(viewId);
1224 - if (target) target.classList.add('active');
1225 - document.querySelectorAll('.nav-link').forEach(btn => btn.classList.toggle('active', btn.getAttribute('data-view') === viewId));
1226 - const dockViews = ['view-dashboard', 'view-invoices', 'view-products', 'view-contacts', 'view-cheques', 'view-settings'];
1227 - document.querySelectorAll('.dock-tab').forEach((dock, idx) => { dock.classList.toggle('active', dockViews[idx] === viewId); });
1228 - if (viewId === 'view-admin') renderAdminPanel();
1229 - window.scrollTo({ top: 0, behavior: 'smooth' });
1230 - }
885 +function loadDatastore() {
886 + const persisted = localStorage.getItem(STORAGE_KEY);
887 + if (persisted) { try { datastore = JSON.parse(persisted); } catch (e) { console.error(e); } }
888 + ['companies','contacts','products','invoices','cheques','expenses','settings'].forEach(k => { if (!Array.isArray(datastore[k])) datastore[k] = []; });
889 +
890 + if (datastore.companies.length === 0 && datastore.products.length === 0) {
891 + datastore.companies.push({
892 + id: 'COMP-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'آرا سپهر راستین',
893 + phone: '09124376991', national_id: '14008507476', economic_code: '14008507476',
894 + reg_number: '544926', postal_code: '1445956311',
895 + address: 'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',
896 + footer: 'از خرید شما سپاسگزاریم.'
897 + });
898 + datastore.contacts.push({
899 + id: 'C-1', ownerUserId: 'user_admin', entity_type: 'legal', name: 'شرکت دانشگاه صنعتی شریف',
900 + mobile: '02166165000', national_id: '14002830256', economic_code: '14002830256',
901 + reg_number: '', postal_code: '1458889694', address: 'طرشت محله تیموری پلاک 435',
902 + balance: 7978300000, role: 'customer'
903 + });
904 + datastore.products.push(
905 + { id: 'P-1', ownerUserId: 'user_admin', code: '1', name: 'سوئیچ شبکه 24 پورت فیبر نوری', spec: 'با 2 پاور 350', unit: 'عدد', buy_price: 1800000000, sale_price: 2180000000, stock: 10, type: 'good' },
906 + { id: 'P-2', ownerUserId: 'user_admin', code: '2', name: 'هارد 2.5 اینچ سرور', spec: '', unit: 'عدد', buy_price: 30000000, sale_price: 37000000, stock: 10, type: 'good' }
907 + );
908 + datastore.settings.push({
909 + ownerUserId: 'user_admin', invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10,
910 + default_company_id: 'COMP-1', currency_mode: 'rial', currency_custom: ''
911 + });
912 + saveDatastore();
913 + } else {
914 + let migrated = false;
915 + ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(coll => {
916 + datastore[coll].forEach(item => { if (!item.ownerUserId) { item.ownerUserId = 'user_admin'; migrated = true; } });
917 + });
918 + datastore.settings.forEach(s => {
919 + if (typeof s.currency_mode === 'undefined') { s.currency_mode = 'rial'; migrated = true; }
920 + if (typeof s.currency_custom === 'undefined') { s.currency_custom = ''; migrated = true; }
921 + });
922 + if (migrated) saveDatastore();
923 + }
924 + return datastore;
925 +}
926
1232 - function toggleAccordion(headerEl) { headerEl.parentElement.classList.toggle('open'); }
1233 -
1234 - function refreshAllSurfaces() {
1235 - const dashDate = document.getElementById('dashboard-date-display');
1236 - if (dashDate) dashDate.innerText = getJalaliDate();
1237 - const invDate = document.getElementById('invoice-date-input');
1238 - if (invDate && !invDate.value) invDate.value = getJalaliNumeric();
1239 - updateLicenseDisplay(currentUser);
1240 - renderCompanies(); renderContacts(); renderProducts(); renderInvoices();
1241 - renderDashboard(); renderCheques(); renderExpenses();
1242 - applyDefaultSettingsToForm();
1243 - handleContactEntityChange();
1244 - handleCurrencyModeChange();
1245 - refreshCurrencyLabels();
1246 - if (currentUser && currentUser.role === 'admin') renderAdminPanel();
1247 - }
927 +function initDatastore() { loadDatastore(); refreshAllSurfaces(); }
928
1249 - function formatEntityName(rawName, entityType, customPrefix = '') {
1250 - let trimmed = (rawName || '').trim();
1251 - if (entityType === 'legal') {
1252 - if (!trimmed.startsWith('شرکت') && !trimmed.startsWith('موسسه') && !trimmed.startsWith('سازمان') && !trimmed.startsWith('اداره')) trimmed = 'شرکت ' + trimmed;
1253 - } else if (entityType === 'natural' && customPrefix) {
1254 - if (!trimmed.startsWith(customPrefix)) trimmed = customPrefix + ' ' + trimmed;
1255 - }
1256 - return trimmed;
1257 - }
929 +function getJalaliDate() { return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { dateStyle: 'full' }).format(new Date()); }
930 +function getJalaliNumeric() { return new Intl.DateTimeFormat('fa-IR-u-ca-persian', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); }
931
1259 - function applyEntityTypeToForm(entity, opts) {
1260 - const { prefixId, nameId, econId, regId, nationalLabelId } = opts;
1261 - const prefixBox = document.getElementById(prefixId);
1262 - const nameBox = document.getElementById(nameId);
1263 - const econBox = document.getElementById(econId);
1264 - const regBox = document.getElementById(regId);
1265 - const natLabel = document.getElementById(nationalLabelId);
1266 - if (entity === 'legal') {
1267 - if (prefixBox) prefixBox.style.display = 'none';
1268 - if (nameBox) nameBox.style.gridColumn = 'span 3';
1269 - if (econBox) econBox.style.display = 'block';
1270 - if (regBox) regBox.style.display = 'block';
1271 - if (natLabel) natLabel.innerText = 'شناسه ملی';
1272 - } else {
1273 - if (prefixBox) prefixBox.style.display = 'block';
1274 - if (nameBox) nameBox.style.gridColumn = 'span 2';
1275 - if (econBox) econBox.style.display = 'none';
1276 - if (regBox) regBox.style.display = 'none';
1277 - if (natLabel) natLabel.innerText = 'کد ملی';
1278 - }
1279 - }
932 +function getCurrencyLabel() {
933 + const s = getMySettings();
934 + if (s.currency_mode === 'toman') return 'تومان';
935 + if (s.currency_mode === 'custom') return (s.currency_custom || '').trim() || 'واحد پول';
936 + return 'ریال';
937 +}
938
1281 - function handleContactEntityChange() {
1282 - const el = document.getElementById('contact-entity-type'); if (!el) return;
1283 - applyEntityTypeToForm(el.value, { prefixId: 'box-contact-prefix', nameId: 'box-contact-name', econId: 'box-contact-economic', regId: 'box-contact-reg', nationalLabelId: 'label-contact-national' });
1284 - }
1285 - function handleQuickCEntityChange() {
1286 - const el = document.getElementById('quick-c-entity'); if (!el) return;
1287 - applyEntityTypeToForm(el.value, { prefixId: 'box-quick-c-prefix', nameId: 'box-quick-c-name', econId: 'box-quick-c-economic', regId: 'box-quick-c-reg', nationalLabelId: 'label-quick-c-national' });
1288 - }
939 +function refreshCurrencyLabels() {
940 + const label = getCurrencyLabel();
941 + document.querySelectorAll('.cur-label').forEach(el => { el.innerText = label; });
942 +}
943
1290 - function handleInvoiceKindChange() {
1291 - const kind = document.getElementById('invoice-kind').value;
1292 - const vatModeRow = document.getElementById('box-invoice-vat-mode-row');
1293 - const vatModeSelect = document.getElementById('invoice-vat-mode');
1294 - if (kind === 'non_formal') {
1295 - if (vatModeRow) vatModeRow.style.display = 'none';
1296 - if (vatModeSelect) vatModeSelect.value = 'none';
1297 - } else {
1298 - if (vatModeRow) vatModeRow.style.display = 'flex';
1299 - }
1300 - handleVatModeChange();
1301 - recomputeTotals();
1302 - }
944 +function handleCurrencyModeChange() {
945 + const mode = document.getElementById('def-currency-mode').value;
946 + document.getElementById('box-currency-custom').style.display = (mode === 'custom') ? 'block' : 'none';
947 +}
948
1304 - function handleVatModeChange() {
1305 - const mode = document.getElementById('invoice-vat-mode').value;
1306 - const kind = document.getElementById('invoice-kind').value;
1307 - const rateBox = document.getElementById('box-invoice-vat-rate');
1308 - if (kind === 'non_formal') { rateBox.style.display = 'none'; document.getElementById('invoice-vat-mode').value = 'none'; }
1309 - else { rateBox.style.display = (mode === 'with_vat') ? 'flex' : 'none'; }
1310 - recomputeTotals();
1311 - }
949 +function switchView(viewId) {
950 + document.querySelectorAll('.view-pane').forEach(el => el.classList.remove('active'));
951 + const target = document.getElementById(viewId);
952 + if (target) target.classList.add('active');
953 + document.querySelectorAll('.nav-link').forEach(btn => btn.classList.toggle('active', btn.getAttribute('data-view') === viewId));
954 + const dockViews = ['view-dashboard', 'view-invoices', 'view-products', 'view-contacts', 'view-cheques', 'view-settings'];
955 + document.querySelectorAll('.dock-tab').forEach((dock, idx) => { dock.classList.toggle('active', dockViews[idx] === viewId); });
956 + if (viewId === 'view-admin') renderAdminPanel();
957 + window.scrollTo({ top: 0, behavior: 'smooth' });
958 +}
959
1313 - function handleVatTypeChange() {
1314 - const type = document.getElementById('invoice-vat-type').value;
1315 - document.getElementById('invoice-vat-rate-input').value = (type === 'percent') ? 10 : 0;
1316 - recomputeTotals();
1317 - }
960 +function toggleAccordion(headerEl) { headerEl.parentElement.classList.toggle('open'); }
961 +
962 +function refreshAllSurfaces() {
963 + const dashDate = document.getElementById('dashboard-date-display');
964 + if (dashDate) dashDate.innerText = getJalaliDate();
965 + const invDate = document.getElementById('invoice-date-input');
966 + if (invDate && !invDate.value) invDate.value = getJalaliNumeric();
967 + updateLicenseDisplay(currentUser);
968 + renderCompanies(); renderContacts(); renderProducts(); renderInvoices();
969 + renderDashboard(); renderCheques(); renderExpenses();
970 + applyDefaultSettingsToForm();
971 + handleContactEntityChange();
972 + handleCurrencyModeChange();
973 + refreshCurrencyLabels();
974 + if (currentUser && currentUser.role === 'admin') renderAdminPanel();
975 +}
976
1319 - function handleDiscountTypeChange() {
1320 - const type = document.getElementById('invoice-discount-type').value;
1321 - const label = document.getElementById('label-invoice-discount-value');
1322 - const cur = getCurrencyLabel();
1323 - label.innerText = (type === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${cur})`;
1324 - document.getElementById('invoice-discount-fixed').value = 0;
1325 - recomputeTotals();
1326 - }
977 +function formatEntityName(rawName, entityType, customPrefix = '') {
978 + let trimmed = (rawName || '').trim();
979 + if (entityType === 'legal') {
980 + if (!trimmed.startsWith('شرکت') && !trimmed.startsWith('موسسه') && !trimmed.startsWith('سازمان') && !trimmed.startsWith('اداره')) trimmed = 'شرکت ' + trimmed;
981 + } else if (entityType === 'natural' && customPrefix) {
982 + if (!trimmed.startsWith(customPrefix)) trimmed = customPrefix + ' ' + trimmed;
983 + }
984 + return trimmed;
985 +}
986
1328 - function applyDefaultSettingsToForm() {
1329 - const def = getMySettings();
1330 - const defKind = document.getElementById('def-invoice-kind');
1331 - const defVat = document.getElementById('def-vat-mode');
1332 - const defRate = document.getElementById('def-vat-rate');
1333 - const defCurMode = document.getElementById('def-currency-mode');
1334 - const defCurCustom = document.getElementById('def-currency-custom');
1335 - if (defKind) defKind.value = def.invoice_kind || 'non_formal';
1336 - if (defVat) defVat.value = def.vat_mode || 'none';
1337 - if (defRate) defRate.value = def.vat_rate || 10;
1338 - if (defCurMode) defCurMode.value = def.currency_mode || 'rial';
1339 - if (defCurCustom) defCurCustom.value = def.currency_custom || '';
1340 - handleCurrencyModeChange();
1341 -
1342 - const editId = document.getElementById('edit-invoice-id')?.value;
1343 - if (!editId) {
1344 - const kindEl = document.getElementById('invoice-kind');
1345 - if (kindEl) kindEl.value = def.invoice_kind || 'non_formal';
1346 - handleInvoiceKindChange();
1347 - if ((def.invoice_kind || 'non_formal') !== 'non_formal') {
1348 - document.getElementById('invoice-vat-mode').value = def.vat_mode || 'none';
1349 - document.getElementById('invoice-vat-rate-input').value = def.vat_rate || 10;
1350 - handleVatModeChange();
1351 - }
1352 - }
1353 - }
987 +function applyEntityTypeToForm(entity, opts) {
988 + const { prefixId, nameId, econId, regId, nationalLabelId } = opts;
989 + const prefixBox = document.getElementById(prefixId);
990 + const nameBox = document.getElementById(nameId);
991 + const econBox = document.getElementById(econId);
992 + const regBox = document.getElementById(regId);
993 + const natLabel = document.getElementById(nationalLabelId);
994 + if (entity === 'legal') {
995 + if (prefixBox) prefixBox.style.display = 'none';
996 + if (nameBox) nameBox.style.gridColumn = 'span 3';
997 + if (econBox) econBox.style.display = 'block';
998 + if (regBox) regBox.style.display = 'block';
999 + if (natLabel) natLabel.innerText = 'شناسه ملی';
1000 + } else {
1001 + if (prefixBox) prefixBox.style.display = 'block';
1002 + if (nameBox) nameBox.style.gridColumn = 'span 2';
1003 + if (econBox) econBox.style.display = 'none';
1004 + if (regBox) regBox.style.display = 'none';
1005 + if (natLabel) natLabel.innerText = 'کد ملی';
1006 + }
1007 +}
1008
1355 - function commitSaveDefaultSettings() {
1356 - const s = getMySettings();
1357 - s.invoice_kind = document.getElementById('def-invoice-kind').value;
1358 - s.vat_mode = document.getElementById('def-vat-mode').value;
1359 - s.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1360 - s.currency_mode = document.getElementById('def-currency-mode').value;
1361 - s.currency_custom = document.getElementById('def-currency-custom').value || '';
1362 - saveDatastore();
1363 - refreshCurrencyLabels();
1364 - alert('پیش‌فرض‌ها ذخیره شد.');
1365 - }
1009 +function handleContactEntityChange() {
1010 + const el = document.getElementById('contact-entity-type'); if (!el) return;
1011 + applyEntityTypeToForm(el.value, { prefixId: 'box-contact-prefix', nameId: 'box-contact-name', econId: 'box-contact-economic', regId: 'box-contact-reg', nationalLabelId: 'label-contact-national' });
1012 +}
1013 +function handleQuickCEntityChange() {
1014 + const el = document.getElementById('quick-c-entity'); if (!el) return;
1015 + applyEntityTypeToForm(el.value, { prefixId: 'box-quick-c-prefix', nameId: 'box-quick-c-name', econId: 'box-quick-c-economic', regId: 'box-quick-c-reg', nationalLabelId: 'label-quick-c-national' });
1016 +}
1017
1367 - function renderDashboard() {
1368 - let salesSum = 0; let debtorsSum = 0;
1369 - const myInvoices = getMyInvoices();
1370 - const myCheques = getMyCheques();
1371 - const myCompanies = getMyCompanies();
1372 - const mySettings = getMySettings();
1373 - const activeCompId = mySettings.default_company_id || document.getElementById('invoice-company-id')?.value || (myCompanies[0]?.id);
1374 - const filteredInvoices = activeCompId ? myInvoices.filter(inv => inv.companyId === activeCompId) : myInvoices;
1375 - const cur = getCurrencyLabel();
1376 -
1377 - filteredInvoices.forEach(inv => {
1378 - salesSum += inv.grandTotal;
1379 - if (inv.paymentMethod === 'credit') debtorsSum += inv.grandTotal;
1380 - });
1018 +function handleInvoiceKindChange() {
1019 + const kind = document.getElementById('invoice-kind').value;
1020 + const vatModeRow = document.getElementById('box-invoice-vat-mode-row');
1021 + const vatModeSelect = document.getElementById('invoice-vat-mode');
1022 + if (kind === 'non_formal') {
1023 + if (vatModeRow) vatModeRow.style.display = 'none';
1024 + if (vatModeSelect) vatModeSelect.value = 'none';
1025 + } else {
1026 + if (vatModeRow) vatModeRow.style.display = 'flex';
1027 + }
1028 + handleVatModeChange();
1029 + recomputeTotals();
1030 +}
1031
1382 - const salesEl = document.getElementById('kpi-sales-sum');
1383 - const settledEl = document.getElementById('kpi-settled-sum');
1384 - const debtorsEl = document.getElementById('kpi-debtors-sum');
1385 - const chequesEl = document.getElementById('kpi-cheques-count');
1386 - if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ' + cur;
1387 - if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ' + cur;
1388 - if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ' + cur;
1389 - if (chequesEl) chequesEl.innerText = myCheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1390 -
1391 - const recentTbody = document.getElementById('dashboard-recent-table');
1392 - if (recentTbody) {
1393 - if (filteredInvoices.length === 0) {
1394 - recentTbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری صادر نشده است.</td></tr>';
1395 - return;
1396 - }
1397 - recentTbody.innerHTML = filteredInvoices.slice(-5).reverse().map(inv => `
1398 - <tr>
1399 - <td><strong>#${inv.number}</strong></td>
1400 - <td>${inv.companyName || '—'}</td>
1401 - <td>${inv.contactName}</td>
1402 - <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1403 - <td>${inv.vat > 0 ? 'با ارزش افزوده' : 'بدون مالیات'}</td>
1404 - <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1405 - <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px; font-size:12px;" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
1406 - </tr>
1407 - `).join('');
1408 - }
1409 - }
1032 +function handleVatModeChange() {
1033 + const mode = document.getElementById('invoice-vat-mode').value;
1034 + const kind = document.getElementById('invoice-kind').value;
1035 + const rateBox = document.getElementById('box-invoice-vat-rate');
1036 + if (kind === 'non_formal') { rateBox.style.display = 'none'; document.getElementById('invoice-vat-mode').value = 'none'; }
1037 + else { rateBox.style.display = (mode === 'with_vat') ? 'flex' : 'none'; }
1038 + recomputeTotals();
1039 +}
1040
1411 - function onActiveCompanyFilterChange() {
1412 - const activeCompId = document.getElementById('invoice-company-id').value;
1413 - const filterSelect = document.getElementById('filter-invoice-company');
1414 - if (filterSelect) filterSelect.value = activeCompId;
1415 - renderInvoices(); renderDashboard();
1416 - }
1041 +function handleVatTypeChange() {
1042 + const type = document.getElementById('invoice-vat-type').value;
1043 + document.getElementById('invoice-vat-rate-input').value = (type === 'percent') ? 10 : 0;
1044 + recomputeTotals();
1045 +}
1046
1418 - function startNewInvoice() { cancelInvoiceEdit(); switchView('view-invoices'); }
1047 +function handleDiscountTypeChange() {
1048 + const type = document.getElementById('invoice-discount-type').value;
1049 + const label = document.getElementById('label-invoice-discount-value');
1050 + const cur = getCurrencyLabel();
1051 + label.innerText = (type === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${cur})`;
1052 + document.getElementById('invoice-discount-fixed').value = 0;
1053 + recomputeTotals();
1054 +}
1055
1420 - function updateInvoiceItemRowNumbers() {
1421 - const rows = document.querySelectorAll('#invoice-items-table-body tr');
1422 - rows.forEach((tr, index) => {
1423 - const numCell = tr.querySelector('.row-item-number');
1424 - if (numCell) numCell.innerText = (index + 1).toLocaleString('fa-IR');
1425 - });
1056 +function applyDefaultSettingsToForm() {
1057 + const def = getMySettings();
1058 + const defKind = document.getElementById('def-invoice-kind');
1059 + const defVat = document.getElementById('def-vat-mode');
1060 + const defRate = document.getElementById('def-vat-rate');
1061 + const defCurMode = document.getElementById('def-currency-mode');
1062 + const defCurCustom = document.getElementById('def-currency-custom');
1063 + if (defKind) defKind.value = def.invoice_kind || 'non_formal';
1064 + if (defVat) defVat.value = def.vat_mode || 'none';
1065 + if (defRate) defRate.value = def.vat_rate || 10;
1066 + if (defCurMode) defCurMode.value = def.currency_mode || 'rial';
1067 + if (defCurCustom) defCurCustom.value = def.currency_custom || '';
1068 + handleCurrencyModeChange();
1069 +
1070 + const editId = document.getElementById('edit-invoice-id')?.value;
1071 + if (!editId) {
1072 + const kindEl = document.getElementById('invoice-kind');
1073 + if (kindEl) kindEl.value = def.invoice_kind || 'non_formal';
1074 + handleInvoiceKindChange();
1075 + if ((def.invoice_kind || 'non_formal') !== 'non_formal') {
1076 + document.getElementById('invoice-vat-mode').value = def.vat_mode || 'none';
1077 + document.getElementById('invoice-vat-rate-input').value = def.vat_rate || 10;
1078 + handleVatModeChange();
1079 }
1080 + }
1081 +}
1082
1428 - function addInvoiceItemRow(selectedProdId = '', initialQty = 1, initialPrice = null) {
1429 - const tbody = document.getElementById('invoice-items-table-body');
1430 - const rowKey = 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 4);
1431 - const tr = document.createElement('tr');
1432 - tr.id = rowKey;
1433 - const myProducts = getMyProducts();
1434 - const productOptions = myProducts.map(p =>
1435 - `<option value="${p.id}" data-price="${p.sale_price}" data-unit="${p.unit || 'عدد'}" ${p.id === selectedProdId ? 'selected' : ''}>${p.name} ${p.spec ? '(' + p.spec + ')' : ''}</option>`
1436 - ).join('');
1437 - tr.innerHTML = `
1438 - <td class="row-item-number" style="width:40px; text-align:center; font-weight:bold; vertical-align:middle;"></td>
1439 - <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
1440 - <td style="width:90px;"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center;" /></td>
1441 - <td style="width:100px;"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center;" /></td>
1442 - <td style="width:160px;"><input type="number" class="form-control row-price" value="${initialPrice !== null ? initialPrice : 0}" oninput="recomputeTotals()" style="text-align:left;" /></td>
1443 - <td class="row-linetotal" style="width:170px; font-weight:bold; text-align:left; vertical-align:middle; direction:ltr;">۰</td>
1444 - <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>
1445 - `;
1446 - tbody.appendChild(tr);
1447 - updateInvoiceItemRowNumbers();
1448 - if (selectedProdId && initialPrice === null) onRowProductChange(rowKey);
1449 - else recomputeTotals();
1450 - }
1083 +function commitSaveDefaultSettings() {
1084 + const s = getMySettings();
1085 + s.invoice_kind = document.getElementById('def-invoice-kind').value;
1086 + s.vat_mode = document.getElementById('def-vat-mode').value;
1087 + s.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1088 + s.currency_mode = document.getElementById('def-currency-mode').value;
1089 + s.currency_custom = document.getElementById('def-currency-custom').value || '';
1090 + saveDatastore();
1091 + refreshCurrencyLabels();
1092 + alert('پیش‌فرض‌ها ذخیره شد.');
1093 +}
1094
1452 - function onRowProductChange(rowKey) {
1453 - const tr = document.getElementById(rowKey);
1454 - if (!tr) return;
1455 - const sel = tr.querySelector('.row-product-select');
1456 - const opt = sel.options[sel.selectedIndex];
1457 - const prc = opt?.getAttribute('data-price') || 0;
1458 - const unt = opt?.getAttribute('data-unit');
1459 - tr.querySelector('.row-price').value = prc;
1460 - if (unt) {
1461 - const unitInput = tr.querySelector('.row-unit-input');
1462 - if (unitInput) unitInput.value = unt;
1463 - }
1464 - recomputeTotals();
1095 +function renderDashboard() {
1096 + let salesSum = 0; let debtorsSum = 0;
1097 + const myInvoices = getMyInvoices();
1098 + const myCheques = getMyCheques();
1099 + const myCompanies = getMyCompanies();
1100 + const mySettings = getMySettings();
1101 + const activeCompId = mySettings.default_company_id || document.getElementById('invoice-company-id')?.value || (myCompanies[0]?.id);
1102 + const filteredInvoices = activeCompId ? myInvoices.filter(inv => inv.companyId === activeCompId) : myInvoices;
1103 + const cur = getCurrencyLabel();
1104 + filteredInvoices.forEach(inv => {
1105 + salesSum += inv.grandTotal;
1106 + if (inv.paymentMethod === 'credit') debtorsSum += inv.grandTotal;
1107 + });
1108 + const salesEl = document.getElementById('kpi-sales-sum');
1109 + const settledEl = document.getElementById('kpi-settled-sum');
1110 + const debtorsEl = document.getElementById('kpi-debtors-sum');
1111 + const chequesEl = document.getElementById('kpi-cheques-count');
1112 + if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ' + cur;
1113 + if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ' + cur;
1114 + if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ' + cur;
1115 + if (chequesEl) chequesEl.innerText = myCheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1116 + const recentTbody = document.getElementById('dashboard-recent-table');
1117 + if (recentTbody) {
1118 + if (filteredInvoices.length === 0) {
1119 + recentTbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr>';
1120 + return;
1121 }
1122 + recentTbody.innerHTML = filteredInvoices.slice(-5).reverse().map(inv => `
1123 + <tr>
1124 + <td><strong>#${inv.number}</strong></td>
1125 + <td>${inv.companyName || '—'}</td>
1126 + <td>${inv.contactName}</td>
1127 + <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1128 + <td>${inv.vat > 0 ? 'با ارزش افزوده' : 'بدون مالیات'}</td>
1129 + <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1130 + <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px;font-size:12px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
1131 + </tr>
1132 + `).join('');
1133 + }
1134 +}
1135
1467 - function recomputeTotals() {
1468 - let subtotal = 0;
1469 - document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1470 - const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1471 - const prc = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1472 - const line = qty * prc;
1473 - const lineEl = tr.querySelector('.row-linetotal');
1474 - if (lineEl) lineEl.innerText = line.toLocaleString('fa-IR');
1475 - subtotal += line;
1476 - });
1477 -
1478 - const discountType = document.getElementById('invoice-discount-type')?.value || 'fixed';
1479 - const discountInput = parseFloat(document.getElementById('invoice-discount-fixed')?.value) || 0;
1480 - const rawDiscount = (discountType === 'percent') ? Math.round(subtotal * (discountInput / 100)) : discountInput;
1481 - const fixedDiscount = Math.max(0, Math.min(rawDiscount, subtotal));
1136 +function onActiveCompanyFilterChange() {
1137 + const activeCompId = document.getElementById('invoice-company-id').value;
1138 + const filterSelect = document.getElementById('filter-invoice-company');
1139 + if (filterSelect) filterSelect.value = activeCompId;
1140 + renderInvoices(); renderDashboard();
1141 +}
1142
1483 - const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1484 - const vatMode = (kind === 'non_formal') ? 'none' : (document.getElementById('invoice-vat-mode')?.value || 'none');
1485 - const vatType = document.getElementById('invoice-vat-type')?.value || 'percent';
1486 - const vatRate = parseFloat(document.getElementById('invoice-vat-rate-input')?.value) || 0;
1143 +function startNewInvoice() { cancelInvoiceEdit(); switchView('view-invoices'); }
1144
1488 - const afterDiscount = Math.max(0, subtotal - fixedDiscount);
1489 - let vatAmount = 0;
1490 - if (vatMode === 'with_vat') {
1491 - vatAmount = (vatType === 'fixed') ? Math.max(0, Math.round(vatRate)) : Math.round(afterDiscount * (vatRate / 100));
1492 - }
1493 - const grandTotal = afterDiscount + vatAmount;
1494 -
1495 - const cur = getCurrencyLabel();
1496 - const subtotalEl = document.getElementById('summary-subtotal');
1497 - const vatEl = document.getElementById('summary-vat');
1498 - const grandEl = document.getElementById('summary-grandtotal');
1499 - const wordsEl = document.getElementById('summary-words');
1500 - if (subtotalEl) subtotalEl.innerText = subtotal.toLocaleString('fa-IR') + ' ' + cur;
1501 - if (vatEl) vatEl.innerText = vatAmount.toLocaleString('fa-IR') + ' ' + cur;
1502 - if (grandEl) grandEl.innerText = grandTotal.toLocaleString('fa-IR') + ' ' + cur;
1503 - if (wordsEl) wordsEl.innerText = 'به حروف: ' + numberToPersianWords(grandTotal, cur);
1504 -
1505 - return { subtotal, fixedDiscount, discountType, discountInput, vatAmount, vatType, grandTotal, vatRate };
1506 - }
1145 +function updateInvoiceItemRowNumbers() {
1146 + const rows = document.querySelectorAll('#invoice-items-table-body tr');
1147 + rows.forEach((tr, index) => {
1148 + const numCell = tr.querySelector('.row-item-number');
1149 + if (numCell) numCell.innerText = (index + 1).toLocaleString('fa-IR');
1150 + });
1151 +}
1152
1508 - function commitSaveInvoice() {
1509 - if (!currentUser) return;
1510 - const myCompanies = getMyCompanies();
1511 - const mySettings = getMySettings();
1512 - const companySelect = document.getElementById('invoice-company-id');
1513 - const selectedCompanyId = companySelect ? companySelect.value : mySettings.default_company_id;
1514 - const sellerCompany = myCompanies.find(c => c.id === selectedCompanyId) ||
1515 - myCompanies.find(c => c.id === mySettings.default_company_id) ||
1516 - myCompanies[0];
1517 - if (!sellerCompany) { alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.'); return; }
1518 - const companyId = sellerCompany.id;
1519 - const companyName = sellerCompany.name;
1520 -
1521 - const contactSelect = document.getElementById('invoice-contact-id');
1522 - const contactId = contactSelect ? contactSelect.value : '';
1523 - const contactName = contactSelect?.options[contactSelect.selectedIndex]?.text || 'مشتری آزاد';
1524 - const number = document.getElementById('invoice-number')?.value.trim() || ('PINV-' + (getMyInvoices().length + 31));
1525 - const date = document.getElementById('invoice-date-input')?.value.trim() || getJalaliNumeric();
1526 - const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1527 - const description = document.getElementById('invoice-desc-input')?.value.trim() || '';
1528 - const editId = document.getElementById('edit-invoice-id')?.value;
1529 -
1530 - if (kind === 'non_formal') {
1531 - document.getElementById('invoice-vat-mode').value = 'none';
1532 - }
1153 +function addInvoiceItemRow(selectedProdId = '', initialQty = 1, initialPrice = null) {
1154 + const tbody = document.getElementById('invoice-items-table-body');
1155 + const rowKey = 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 4);
1156 + const tr = document.createElement('tr');
1157 + tr.id = rowKey;
1158 + const myProducts = getMyProducts();
1159 + const productOptions = myProducts.map(p => `<option value="${p.id}" data-price="${p.sale_price}" data-unit="${p.unit || 'عدد'}" ${p.id === selectedProdId ? 'selected' : ''}>${p.name} ${p.spec ? '(' + p.spec + ')' : ''}</option>`).join('');
1160 + tr.innerHTML = `
1161 + <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
1162 + <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
1163 + <td style="width:90px"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center" /></td>
1164 + <td style="width:100px"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center" /></td>
1165 + <td style="width:160px"><input type="number" class="form-control row-price" value="${initialPrice !== null ? initialPrice : 0}" oninput="recomputeTotals()" style="text-align:left" /></td>
1166 + <td class="row-linetotal" style="width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr">۰</td>
1167 + <td style="width:50px;text-align:center;vertical-align:middle"><button class="btn btn-danger btn-inline" style="min-height:36px;padding:4px 10px" onclick="document.getElementById('${rowKey}').remove();updateInvoiceItemRowNumbers();recomputeTotals()">✕</button></td>
1168 + `;
1169 + tbody.appendChild(tr);
1170 + updateInvoiceItemRowNumbers();
1171 + if (selectedProdId && initialPrice === null) onRowProductChange(rowKey);
1172 + else recomputeTotals();
1173 +}
1174
1534 - const items = [];
1535 - document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1536 - const sel = tr.querySelector('.row-product-select');
1537 - const prodId = sel ? sel.value : '';
1538 - const prodName = sel ? sel.options[sel.selectedIndex]?.text : '';
1539 - const unit = tr.querySelector('.row-unit-input')?.value || 'عدد';
1540 - const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1541 - const price = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1542 - if (prodId && qty > 0) {
1543 - items.push({ prodId, prodName, unit, qty, price, lineTotal: qty * price });
1544 - }
1545 - });
1175 +function onRowProductChange(rowKey) {
1176 + const tr = document.getElementById(rowKey);
1177 + if (!tr) return;
1178 + const sel = tr.querySelector('.row-product-select');
1179 + const opt = sel.options[sel.selectedIndex];
1180 + const prc = opt?.getAttribute('data-price') || 0;
1181 + const unt = opt?.getAttribute('data-unit');
1182 + tr.querySelector('.row-price').value = prc;
1183 + if (unt) {
1184 + const unitInput = tr.querySelector('.row-unit-input');
1185 + if (unitInput) unitInput.value = unt;
1186 + }
1187 + recomputeTotals();
1188 +}
1189
1547 - if (items.length === 0) { alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.'); return; }
1548 -
1549 - const totals = recomputeTotals();
1550 - const kindLabels = { formal: 'رسمی', non_formal: 'غیررسمی', pre_invoice: 'پیش‌فاکتور' };
1551 - const cur = getCurrencyLabel();
1552 -
1553 - if (editId) {
1554 - const existingIndex = datastore.invoices.findIndex(i => i.id === editId && i.ownerUserId === currentUser.id);
1555 - if (existingIndex !== -1) {
1556 - datastore.invoices[existingIndex] = {
1557 - ...datastore.invoices[existingIndex],
1558 - ownerUserId: currentUser.id, number, date, companyId, companyName, kind,
1559 - kindLabel: kindLabels[kind], contactId, contactName,
1560 - paymentMethod: 'cash', paymentMethodLabel: 'نقدی',
1561 - subtotal: totals.subtotal, discount: totals.fixedDiscount,
1562 - discountType: totals.discountType, discountInput: totals.discountInput,
1563 - vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate,
1564 - grandTotal: totals.grandTotal, description, items,
1565 - currencyLabel: cur
1566 - };
1567 - alert('فاکتور با موفقیت ویرایش شد.');
1568 - }
1569 - cancelInvoiceEdit();
1570 - } else {
1571 - const record = {
1572 - id: 'INV_' + Date.now(), ownerUserId: currentUser.id,
1573 - number, date, companyId, companyName, kind,
1574 - kindLabel: kindLabels[kind], contactId, contactName,
1575 - paymentMethod: 'cash', paymentMethodLabel: 'نقدی',
1576 - subtotal: totals.subtotal, discount: totals.fixedDiscount,
1577 - discountType: totals.discountType, discountInput: totals.discountInput,
1578 - vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate,
1579 - grandTotal: totals.grandTotal, description, items,
1580 - currencyLabel: cur
1581 - };
1582 - datastore.invoices.push(record);
1583 - alert('فاکتور با موفقیت ثبت شد.');
1584 - cancelInvoiceEdit();
1585 - renderAndPrintDirect(record.id);
1586 - }
1587 - saveDatastore();
1588 - refreshAllSurfaces();
1589 - }
1190 +function recomputeTotals() {
1191 + let subtotal = 0;
1192 + document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1193 + const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1194 + const prc = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1195 + const line = qty * prc;
1196 + const lineEl = tr.querySelector('.row-linetotal');
1197 + if (lineEl) lineEl.innerText = line.toLocaleString('fa-IR');
1198 + subtotal += line;
1199 + });
1200 + const discountType = document.getElementById('invoice-discount-type')?.value || 'fixed';
1201 + const discountInput = parseFloat(document.getElementById('invoice-discount-fixed')?.value) || 0;
1202 + const rawDiscount = (discountType === 'percent') ? Math.round(subtotal * (discountInput / 100)) : discountInput;
1203 + const fixedDiscount = Math.max(0, Math.min(rawDiscount, subtotal));
1204 + const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1205 + const vatMode = (kind === 'non_formal') ? 'none' : (document.getElementById('invoice-vat-mode')?.value || 'none');
1206 + const vatType = document.getElementById('invoice-vat-type')?.value || 'percent';
1207 + const vatRate = parseFloat(document.getElementById('invoice-vat-rate-input')?.value) || 0;
1208 + const afterDiscount = Math.max(0, subtotal - fixedDiscount);
1209 + let vatAmount = 0;
1210 + if (vatMode === 'with_vat') {
1211 + vatAmount = (vatType === 'fixed') ? Math.max(0, Math.round(vatRate)) : Math.round(afterDiscount * (vatRate / 100));
1212 + }
1213 + const grandTotal = afterDiscount + vatAmount;
1214 + const cur = getCurrencyLabel();
1215 + const subtotalEl = document.getElementById('summary-subtotal');
1216 + const vatEl = document.getElementById('summary-vat');
1217 + const grandEl = document.getElementById('summary-grandtotal');
1218 + const wordsEl = document.getElementById('summary-words');
1219 + if (subtotalEl) subtotalEl.innerText = subtotal.toLocaleString('fa-IR') + ' ' + cur;
1220 + if (vatEl) vatEl.innerText = vatAmount.toLocaleString('fa-IR') + ' ' + cur;
1221 + if (grandEl) grandEl.innerText = grandTotal.toLocaleString('fa-IR') + ' ' + cur;
1222 + if (wordsEl) wordsEl.innerText = 'به حروف: ' + numberToPersianWords(grandTotal, cur);
1223 + return { subtotal, fixedDiscount, discountType, discountInput, vatAmount, vatType, grandTotal, vatRate };
1224 +}
1225
1591 - function editInvoice(invId) {
1592 - const inv = getMyInvoices().find(i => i.id === invId);
1593 - if (!inv) return;
1594 - switchView('view-invoices');
1595 - document.getElementById('edit-invoice-id').value = inv.id;
1596 - document.getElementById('invoice-form-title').innerText = `✏️ ویرایش فاکتور #${inv.number}`;
1597 - document.getElementById('btn-cancel-edit').style.display = 'inline-flex';
1598 - document.getElementById('btn-save-invoice').innerText = '💾 ذخیره تغییرات';
1599 - document.getElementById('invoice-company-id').value = inv.companyId;
1600 - document.getElementById('invoice-kind').value = inv.kind;
1601 - document.getElementById('invoice-vat-mode').value = inv.vat > 0 ? 'with_vat' : 'none';
1602 - document.getElementById('invoice-vat-type').value = inv.vatType || 'percent';
1603 - document.getElementById('invoice-vat-rate-input').value = inv.vatRate || 10;
1604 - document.getElementById('invoice-number').value = inv.number;
1605 - document.getElementById('invoice-contact-id').value = inv.contactId;
1606 - document.getElementById('invoice-date-input').value = inv.date;
1607 - document.getElementById('invoice-discount-type').value = inv.discountType || 'fixed';
1608 - document.getElementById('label-invoice-discount-value').innerText = (inv.discountType === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${getCurrencyLabel()})`;
1609 - document.getElementById('invoice-discount-fixed').value = (inv.discountType === 'percent') ? (inv.discountInput || 0) : (inv.discount || 0);
1610 - document.getElementById('invoice-desc-input').value = inv.description || '';
1611 - handleInvoiceKindChange();
1612 -
1613 - const tbody = document.getElementById('invoice-items-table-body');
1614 - tbody.innerHTML = '';
1615 - inv.items.forEach(it => {
1616 - addInvoiceItemRow(it.prodId, it.qty, it.price);
1617 - const lastRow = tbody.lastElementChild;
1618 - if (lastRow) lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
1619 - });
1620 - updateInvoiceItemRowNumbers();
1621 - recomputeTotals();
1622 - }
1226 +function commitSaveInvoice() {
1227 + if (!currentUser) return;
1228 + const myCompanies = getMyCompanies();
1229 + const mySettings = getMySettings();
1230 + const companySelect = document.getElementById('invoice-company-id');
1231 + const selectedCompanyId = companySelect ? companySelect.value : mySettings.default_company_id;
1232 + const sellerCompany = myCompanies.find(c => c.id === selectedCompanyId) || myCompanies.find(c => c.id === mySettings.default_company_id) || myCompanies[0];
1233 + if (!sellerCompany) { alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.'); return; }
1234 + const companyId = sellerCompany.id;
1235 + const companyName = sellerCompany.name;
1236 + const contactSelect = document.getElementById('invoice-contact-id');
1237 + const contactId = contactSelect ? contactSelect.value : '';
1238 + const contactName = contactSelect?.options[contactSelect.selectedIndex]?.text || 'مشتری آزاد';
1239 + const number = document.getElementById('invoice-number')?.value.trim() || ('PINV-' + (getMyInvoices().length + 31));
1240 + const date = document.getElementById('invoice-date-input')?.value.trim() || getJalaliNumeric();
1241 + const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1242 + const description = document.getElementById('invoice-desc-input')?.value.trim() || '';
1243 + const editId = document.getElementById('edit-invoice-id')?.value;
1244 + if (kind === 'non_formal') { document.getElementById('invoice-vat-mode').value = 'none'; }
1245 + const items = [];
1246 + document.querySelectorAll('#invoice-items-table-body tr').forEach(tr => {
1247 + const sel = tr.querySelector('.row-product-select');
1248 + const prodId = sel ? sel.value : '';
1249 + const prodName = sel ? sel.options[sel.selectedIndex]?.text : '';
1250 + const unit = tr.querySelector('.row-unit-input')?.value || 'عدد';
1251 + const qty = parseFloat(tr.querySelector('.row-quantity')?.value) || 0;
1252 + const price = parseFloat(tr.querySelector('.row-price')?.value) || 0;
1253 + if (prodId && qty > 0) { items.push({ prodId, prodName, unit, qty, price, lineTotal: qty * price }); }
1254 + });
1255 + if (items.length === 0) { alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.'); return; }
1256 + const totals = recomputeTotals();
1257 + const kindLabels = { formal: 'رسمی', non_formal: 'غیررسمی', pre_invoice: 'پیش‌فاکتور' };
1258 + const cur = getCurrencyLabel();
1259 + if (editId) {
1260 + const existingIndex = datastore.invoices.findIndex(i => i.id === editId && i.ownerUserId === currentUser.id);
1261 + if (existingIndex !== -1) {
1262 + datastore.invoices[existingIndex] = { ...datastore.invoices[existingIndex], ownerUserId: currentUser.id, number, date, companyId, companyName, kind, kindLabel: kindLabels[kind], contactId, contactName, paymentMethod: 'cash', paymentMethodLabel: 'نقدی', subtotal: totals.subtotal, discount: totals.fixedDiscount, discountType: totals.discountType, discountInput: totals.discountInput, vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate, grandTotal: totals.grandTotal, description, items, currencyLabel: cur };
1263 + alert('فاکتور با موفقیت ویرایش شد.');
1264 + }
1265 + cancelInvoiceEdit();
1266 + } else {
1267 + const record = { id: 'INV_' + Date.now(), ownerUserId: currentUser.id, number, date, companyId, companyName, kind, kindLabel: kindLabels[kind], contactId, contactName, paymentMethod: 'cash', paymentMethodLabel: 'نقدی', subtotal: totals.subtotal, discount: totals.fixedDiscount, discountType: totals.discountType, discountInput: totals.discountInput, vat: totals.vatAmount, vatType: totals.vatType, vatRate: totals.vatRate, grandTotal: totals.grandTotal, description, items, currencyLabel: cur };
1268 + datastore.invoices.push(record);
1269 + alert('فاکتور با موفقیت ثبت شد.');
1270 + cancelInvoiceEdit();
1271 + renderAndPrintDirect(record.id);
1272 + }
1273 + saveDatastore();
1274 + refreshAllSurfaces();
1275 +}
1276
1624 - function cancelInvoiceEdit() {
1625 - document.getElementById('edit-invoice-id').value = '';
1626 - document.getElementById('invoice-form-title').innerText = 'صدور فاکتور جدید';
1627 - document.getElementById('btn-cancel-edit').style.display = 'none';
1628 - document.getElementById('btn-save-invoice').innerText = '💾 ثبت فاکتور';
1629 - document.getElementById('invoice-items-table-body').innerHTML = '';
1630 - document.getElementById('invoice-number').value = '';
1631 - document.getElementById('invoice-discount-type').value = 'fixed';
1632 - document.getElementById('label-invoice-discount-value').innerText = `مبلغ تخفیف (${getCurrencyLabel()})`;
1633 - document.getElementById('invoice-discount-fixed').value = 0;
1634 - document.getElementById('invoice-vat-type').value = 'percent';
1635 - document.getElementById('invoice-desc-input').value = '';
1636 - addInvoiceItemRow();
1637 - applyDefaultSettingsToForm();
1638 - }
1277 +function editInvoice(invId) {
1278 + const inv = getMyInvoices().find(i => i.id === invId);
1279 + if (!inv) return;
1280 + switchView('view-invoices');
1281 + document.getElementById('edit-invoice-id').value = inv.id;
1282 + document.getElementById('invoice-form-title').innerText = `✏️ ویرایش فاکتور #${inv.number}`;
1283 + document.getElementById('btn-cancel-edit').style.display = 'inline-flex';
1284 + document.getElementById('btn-save-invoice').innerText = '💾 ذخیره تغییرات';
1285 + document.getElementById('invoice-company-id').value = inv.companyId;
1286 + document.getElementById('invoice-kind').value = inv.kind;
1287 + document.getElementById('invoice-vat-mode').value = inv.vat > 0 ? 'with_vat' : 'none';
1288 + document.getElementById('invoice-vat-type').value = inv.vatType || 'percent';
1289 + document.getElementById('invoice-vat-rate-input').value = inv.vatRate || 10;
1290 + document.getElementById('invoice-number').value = inv.number;
1291 + document.getElementById('invoice-contact-id').value = inv.contactId;
1292 + document.getElementById('invoice-date-input').value = inv.date;
1293 + document.getElementById('invoice-discount-type').value = inv.discountType || 'fixed';
1294 + document.getElementById('label-invoice-discount-value').innerText = (inv.discountType === 'percent') ? 'درصد تخفیف (٪)' : `مبلغ تخفیف (${getCurrencyLabel()})`;
1295 + document.getElementById('invoice-discount-fixed').value = (inv.discountType === 'percent') ? (inv.discountInput || 0) : (inv.discount || 0);
1296 + document.getElementById('invoice-desc-input').value = inv.description || '';
1297 + handleInvoiceKindChange();
1298 + const tbody = document.getElementById('invoice-items-table-body');
1299 + tbody.innerHTML = '';
1300 + inv.items.forEach(it => {
1301 + addInvoiceItemRow(it.prodId, it.qty, it.price);
1302 + const lastRow = tbody.lastElementChild;
1303 + if (lastRow) lastRow.querySelector('.row-unit-input').value = it.unit || 'عدد';
1304 + });
1305 + updateInvoiceItemRowNumbers();
1306 + recomputeTotals();
1307 +}
1308
1640 - function renderInvoices() {
1641 - const tbody = document.getElementById('invoice-archive-table-body');
1642 - const filterSelect = document.getElementById('filter-invoice-company');
1643 - const selectedFilter = filterSelect?.value || document.getElementById('invoice-company-id')?.value || 'ALL';
1644 - let list = getMyInvoices();
1645 - if (selectedFilter !== 'ALL') list = list.filter(i => i.companyId === selectedFilter);
1646 - if (list.length === 0) {
1647 - tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ فاکتوری ثبت نشده است.</td></tr>';
1648 - return;
1649 - }
1650 - tbody.innerHTML = list.map(inv => `
1651 - <tr>
1652 - <td><strong>#${inv.number}</strong></td>
1653 - <td>${inv.companyName || '—'}</td>
1654 - <td>${inv.contactName}</td>
1655 - <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1656 - <td>${inv.date}</td>
1657 - <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1658 - <td>
1659 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
1660 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
1661 - </td>
1662 - </tr>
1663 - `).join('');
1664 - }
1309 +function cancelInvoiceEdit() {
1310 + document.getElementById('edit-invoice-id').value = '';
1311 + document.getElementById('invoice-form-title').innerText = 'صدور فاکتور جدید';
1312 + document.getElementById('btn-cancel-edit').style.display = 'none';
1313 + document.getElementById('btn-save-invoice').innerText = '💾 ثبت فاکتور';
1314 + document.getElementById('invoice-items-table-body').innerHTML = '';
1315 + document.getElementById('invoice-number').value = '';
1316 + document.getElementById('invoice-discount-type').value = 'fixed';
1317 + document.getElementById('label-invoice-discount-value').innerText = `مبلغ تخفیف (${getCurrencyLabel()})`;
1318 + document.getElementById('invoice-discount-fixed').value = 0;
1319 + document.getElementById('invoice-vat-type').value = 'percent';
1320 + document.getElementById('invoice-desc-input').value = '';
1321 + addInvoiceItemRow();
1322 + applyDefaultSettingsToForm();
1323 +}
1324
1666 - /* =========================================================================
1667 - چاپ فاکتور — Landscape، حداکثر ۱۰ ردیف در هر صفحه، باکس کامل روی هر صفحه
1668 - ========================================================================= */
1669 - const MAX_ROWS_PER_PAGE = 10;
1670 -
1671 - function computeInvoiceLines(inv) {
1672 - const n = inv.items.length;
1673 - const afterDiscountTotal = Math.max(0, (inv.subtotal || 0) - (inv.discount || 0));
1674 - let usedDiscount = 0, usedVat = 0;
1675 - return inv.items.map((it, idx) => {
1676 - const lineSubtotal = it.lineTotal;
1677 - const isLastItem = (idx === n - 1);
1678 - let lineDiscount, lineVat;
1679 - if (isLastItem) {
1680 - lineDiscount = Math.max(0, (inv.discount || 0) - usedDiscount);
1681 - lineVat = Math.max(0, (inv.vat || 0) - usedVat);
1682 - } else {
1683 - lineDiscount = (inv.subtotal > 0) ? Math.round((inv.discount || 0) * (lineSubtotal / inv.subtotal)) : 0;
1684 - const lineAfterDiscount = lineSubtotal - lineDiscount;
1685 - lineVat = (afterDiscountTotal > 0 && inv.vat > 0) ? Math.round((inv.vat || 0) * (lineAfterDiscount / afterDiscountTotal)) : 0;
1686 - }
1687 - usedDiscount += lineDiscount;
1688 - usedVat += lineVat;
1689 - const lineNet = lineSubtotal - lineDiscount + lineVat;
1690 - return { rowNo: idx + 1, prodName: it.prodName, qty: it.qty, unit: it.unit || 'عدد', price: it.price, lineSubtotal, lineDiscount, lineVat, lineNet };
1691 - });
1692 - }
1325 +function renderInvoices() {
1326 + const tbody = document.getElementById('invoice-archive-table-body');
1327 + const filterSelect = document.getElementById('filter-invoice-company');
1328 + const selectedFilter = filterSelect?.value || document.getElementById('invoice-company-id')?.value || 'ALL';
1329 + let list = getMyInvoices();
1330 + if (selectedFilter !== 'ALL') list = list.filter(i => i.companyId === selectedFilter);
1331 + if (list.length === 0) {
1332 + tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';
1333 + return;
1334 + }
1335 + tbody.innerHTML = list.map(inv => `
1336 + <tr>
1337 + <td><strong>#${inv.number}</strong></td>
1338 + <td>${inv.companyName || '—'}</td>
1339 + <td>${inv.contactName}</td>
1340 + <td><span class="badge ${inv.kind === 'formal' ? 'badge-danger' : 'badge-success'}">${inv.kindLabel}</span></td>
1341 + <td>${inv.date}</td>
1342 + <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1343 + <td>
1344 + <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
1345 + <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
1346 + </td>
1347 + </tr>
1348 + `).join('');
1349 +}
1350
1694 - function buildFormalPage(items, seller, contact, inv, opt) {
1695 - const cur = inv.currencyLabel || 'ریال';
1696 - const isLast = opt.isLastPage;
1697 -
1698 - const rowsHtml = items.map(li => `
1699 - <tr style="text-align:center;">
1700 - <td style="border:1px solid #1e293b; padding:3px 6px; font-size:10.5px;">${li.rowNo.toLocaleString('fa-IR')}</td>
1701 - <td style="border:1px solid #1e293b; padding:3px 6px; text-align:right; font-size:10.5px; font-weight:600;">${li.prodName}</td>
1702 - <td style="border:1px solid #1e293b; padding:3px 6px; font-size:10.5px;">${li.qty.toLocaleString('fa-IR')}</td>
1703 - <td style="border:1px solid #1e293b; padding:3px 6px; font-size:10.5px;">${li.unit}</td>
1704 - <td style="border:1px solid #1e293b; padding:3px 6px; text-align:left; font-size:10.5px;">${li.price.toLocaleString('fa-IR')}</td>
1705 - <td style="border:1px solid #1e293b; padding:3px 6px; text-align:left; font-size:10.5px;">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1706 - <td style="border:1px solid #1e293b; padding:3px 6px; text-align:left; font-size:10.5px;">${li.lineDiscount.toLocaleString('fa-IR')}</td>
1707 - <td style="border:1px solid #1e293b; padding:3px 6px; text-align:left; font-size:10.5px;">${li.lineVat.toLocaleString('fa-IR')}</td>
1708 - <td style="border:1px solid #1e293b; padding:3px 6px; text-align:left; font-size:10.5px; font-weight:bold;">${li.lineNet.toLocaleString('fa-IR')}</td>
1709 - </tr>
1710 - `).join('');
1351 +const MAX_ROWS_PER_PAGE = 10;
1352 +
1353 +function computeInvoiceLines(inv) {
1354 + const n = inv.items.length;
1355 + const afterDiscountTotal = Math.max(0, (inv.subtotal || 0) - (inv.discount || 0));
1356 + let usedDiscount = 0, usedVat = 0;
1357 + return inv.items.map((it, idx) => {
1358 + const lineSubtotal = it.lineTotal;
1359 + const isLastItem = (idx === n - 1);
1360 + let lineDiscount, lineVat;
1361 + if (isLastItem) {
1362 + lineDiscount = Math.max(0, (inv.discount || 0) - usedDiscount);
1363 + lineVat = Math.max(0, (inv.vat || 0) - usedVat);
1364 + } else {
1365 + lineDiscount = (inv.subtotal > 0) ? Math.round((inv.discount || 0) * (lineSubtotal / inv.subtotal)) : 0;
1366 + const lineAfterDiscount = lineSubtotal - lineDiscount;
1367 + lineVat = (afterDiscountTotal > 0 && inv.vat > 0) ? Math.round((inv.vat || 0) * (lineAfterDiscount / afterDiscountTotal)) : 0;
1368 + }
1369 + usedDiscount += lineDiscount;
1370 + usedVat += lineVat;
1371 + const lineNet = lineSubtotal - lineDiscount + lineVat;
1372 + return { rowNo: idx + 1, prodName: it.prodName, qty: it.qty, unit: it.unit || 'عدد', price: it.price, lineSubtotal, lineDiscount, lineVat, lineNet };
1373 + });
1374 +}
1375
1712 - const sellerIds = `${seller.national_id || '—'} / ${seller.reg_number || '—'}`;
1376 +function buildFormalPage(items, seller, contact, inv, opt) {
1377 + const cur = inv.currencyLabel || 'ریال';
1378 + const isLast = opt.isLastPage;
1379 + const rowsHtml = items.map(li => `
1380 + <tr style="text-align:center">
1381 + <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1382 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:right;font-size:10.5px;font-weight:600">${li.prodName}</td>
1383 + <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
1384 + <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.unit}</td>
1385 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
1386 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1387 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineDiscount.toLocaleString('fa-IR')}</td>
1388 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineVat.toLocaleString('fa-IR')}</td>
1389 + <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px;font-weight:bold">${li.lineNet.toLocaleString('fa-IR')}</td>
1390 + </tr>
1391 + `).join('');
1392 + const sellerIds = `${seller.national_id || '—'} / ${seller.reg_number || '—'}`;
1393 const contactIds = `${contact.national_id || '—'} / ${contact.reg_number || '—'}`;
1394 const cumSub = opt.cumulativeSubtotal || 0;
1395 const cumDisc = opt.cumulativeDiscount || 0;
@@ -1720,119 +1400,105 @@
1400 const vatLabel = isLast ? 'مالیات و عوارض ارزش افزوده:' : 'مالیات تا این صفحه:';
1401 const netLabel = isLast ? 'مبلغ قابل پرداخت:' : 'جمع تا این صفحه:';
1402 const wordsLabel = isLast ? 'مبلغ کل به حروف:' : 'مبلغ تا این صفحه به حروف:';
1723 -
1403 const summaryBox = `
1725 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10.5px; margin-top:3px;">
1404 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10.5px;margin-top:3px">
1405 <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 - `}
1406 + <td style="width:60%;border:1px solid #1e3a8a;padding:6px;vertical-align:top;background:#f8fafc">
1407 + <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet, cur)}</div>
1408 + ${isLast ? `<div style="margin-bottom:4px"><strong>شرایط و نحوه پرداخت:</strong> نقدی ☑ &nbsp;&nbsp;&nbsp; غیرنقدی (نسیه/چک) ☐</div><div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${inv.description || seller.footer || 'تحویل کالا منوط به تسویه نهایی می‌باشد.'}</div>` : `<div style="font-size:9.5px;color:#64748b;margin-top:4px">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>`}
1409 </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>
1410 + <td style="width:40%;border:1px solid #1e3a8a;padding:0">
1411 + <table style="width:100%;border-collapse:collapse;font-size:10.5px">
1412 + <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>
1413 + <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>
1414 + <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>
1415 + <tr style="background:#eff6ff;font-weight:bold;font-size:11.5px;color:#1e3a8a"><td style="padding:5px 8px">${netLabel}</td><td style="padding:5px 8px;text-align:left">${cumNet.toLocaleString('fa-IR')} ${cur}</td></tr>
1416 </table>
1417 </td>
1418 </tr>
1419 </table>
1420 `;
1750 -
1421 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;">
1422 + <table style="width:100%;border-collapse:collapse;border:1px solid #1e3a8a;margin-top:6px;text-align:center;font-size:10.5px">
1423 <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>
1424 + <td style="width:50%;height:50px;vertical-align:top;border:1px solid #1e3a8a;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
1425 + <td style="width:50%;height:50px;vertical-align:top;border:1px solid #1e3a8a;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
1426 </tr>
1427 </table>
1428 ` : '';
1759 -
1429 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;">
1430 + <div class="invoice-a4-page landscape" style="background:#fff;padding:6mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif">
1431 + <table style="width:100%;border-collapse:collapse;border:2px solid #1e3a8a;margin-bottom:3px">
1432 <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>
1433 + <td style="width:28%;border:1px solid #1e3a8a;padding:5px;font-size:11px;vertical-align:middle">
1434 + <div style="font-weight:bold;font-size:13px;color:#1e3a8a">${seller.name || 'فروشگاه'}</div>
1435 + <div style="font-size:9.5px;color:#475569;margin-top:1px">صادرکننده فاکتور رسمی</div>
1436 </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>
1437 + <td style="width:44%;border:1px solid #1e3a8a;padding:6px;text-align:center;vertical-align:middle;background:#eff6ff">
1438 + <h1 style="font-size:15px;margin:0;font-weight:bold;color:#1e3a8a">صورتحساب فروش کالا و خدمات</h1>
1439 + <div style="font-size:10px;margin-top:2px">(ماده ۱۶۹ مکرر قانون مالیات‌های مستقیم)</div>
1440 </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>
1441 + <td style="width:28%;border:1px solid #1e3a8a;padding:5px;font-size:10.5px;vertical-align:middle;text-align:left">
1442 + <div>شماره سریال: <strong style="color:#b91c1c">${inv.number}</strong></div>
1443 + <div style="margin-top:1px">تاریخ صدور: <strong>${inv.date}</strong></div>
1444 + <div style="margin-top:1px;color:#64748b;font-size:9.5px">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1445 </td>
1446 </tr>
1447 </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>
1448 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px;margin-bottom:3px">
1449 + <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">الف) مشخصات فروشنده</td></tr>
1450 <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>
1451 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
1452 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${seller.name || '—'}</strong></td>
1453 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
1454 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${seller.economic_code || '—'}</td>
1455 </tr>
1456 <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>
1457 + <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
1458 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${sellerIds}</td>
1459 + <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
1460 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${seller.postal_code || '—'}</td>
1461 </tr>
1462 <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>
1463 + <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
1464 + <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${seller.address || '—'} ${seller.phone ? ' | تلفن: ' + seller.phone : ''}</td>
1465 </tr>
1466 </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>
1467 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px;margin-bottom:3px">
1468 + <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">ب) مشخصات خریدار</td></tr>
1469 <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>
1470 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
1471 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${contact.name || inv.contactName}</strong></td>
1472 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
1473 + <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${contact.economic_code || '—'}</td>
1474 </tr>
1475 <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>
1476 + <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
1477 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${contactIds}</td>
1478 + <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
1479 + <td style="border:1px solid #cbd5e1;padding:3px 6px">${contact.postal_code || '—'}</td>
1480 </tr>
1481 <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>
1482 + <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
1483 + <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${contact.address || '—'} ${contact.mobile ? ' | همراه: ' + contact.mobile : ''}</td>
1484 </tr>
1485 </table>
1819 -
1820 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #1e3a8a; font-size:10px;">
1486 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px">
1487 <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>
1488 + <tr style="background:#1e3a8a;color:#fff;font-weight:bold;text-align:center">
1489 + <th style="border:1px solid #1e3a8a;padding:4px;width:28px">ردیف</th>
1490 + <th style="border:1px solid #1e3a8a;padding:4px 6px;text-align:right">شرح کالا یا خدمات</th>
1491 + <th style="border:1px solid #1e3a8a;padding:4px;width:42px">تعداد</th>
1492 + <th style="border:1px solid #1e3a8a;padding:4px;width:42px">واحد</th>
1493 + <th style="border:1px solid #1e3a8a;padding:4px;width:105px">مبلغ واحد (${cur})</th>
1494 + <th style="border:1px solid #1e3a8a;padding:4px;width:110px">مبلغ کل (${cur})</th>
1495 + <th style="border:1px solid #1e3a8a;padding:4px;width:80px">تخفیف (${cur})</th>
1496 + <th style="border:1px solid #1e3a8a;padding:4px;width:90px">مالیات (${cur})</th>
1497 + <th style="border:1px solid #1e3a8a;padding:4px;width:120px">مبلغ نهایی (${cur})</th>
1498 </tr>
1499 </thead>
1500 <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>` : ''}
1501 + ${!opt.isFirstPage ? `<tr style="background:#fef3c7;font-weight:bold;font-size:9.5px"><td colspan="5" style="border:1px solid #1e293b;padding:3px;text-align:left">نقل از صفحه قبل:</td><td colspan="4" style="border:1px solid #1e293b;padding:3px;text-align:left">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1502 ${rowsHtml}
1503 </tbody>
1504 </table>
@@ -1847,125 +1513,110 @@ function buildNonFormalPage(items, seller, contact, inv, opt) {
1513 const isLast = opt.isLastPage;
1514 const hasVat = isPre && inv.vat > 0;
1515 const title = isPre ? 'پیش‌فاکتور فروش کالا و خدمات' : 'فاکتور فروش کالا و خدمات';
1850 -
1516 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>
1517 + <tr style="text-align:center">
1518 + <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.rowNo.toLocaleString('fa-IR')}</td>
1519 + <td style="border:1px solid #334155;padding:3px 6px;text-align:right;font-size:10px;font-weight:600">${li.prodName}</td>
1520 + <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.unit}</td>
1521 + <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.qty.toLocaleString('fa-IR')}</td>
1522 + <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.price.toLocaleString('fa-IR')}</td>
1523 + <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1524 + <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineVat.toLocaleString('fa-IR')}</td>
1525 + <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px;font-weight:bold">${li.lineNet.toLocaleString('fa-IR')}</td>
1526 </tr>
1527 ` : `
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>
1528 + <tr style="text-align:center">
1529 + <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1530 + <td style="border:1px solid #334155;padding:4px 8px;text-align:right;font-size:10.5px;font-weight:600">${li.prodName}</td>
1531 + <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.unit}</td>
1532 + <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
1533 + <td style="border:1px solid #334155;padding:4px 5px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
1534 + <td style="border:1px solid #334155;padding:4px 5px;text-align:left;font-size:10.5px;font-weight:bold">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1535 </tr>
1536 `).join('');
1872 -
1537 const cumSub = opt.cumulativeSubtotal || 0;
1538 const cumDisc = opt.cumulativeDiscount || 0;
1539 const cumVat = opt.cumulativeVat || 0;
1540 const cumNet = opt.cumulativeNet || 0;
1877 -
1541 const subtotalLabel = isLast ? 'قیمت کل اقلام:' : 'جمع اقلام تا این صفحه:';
1542 const discountLabel = isLast ? 'تخفیف:' : 'تخفیف تا این صفحه:';
1543 const vatLabel = isLast ? 'مالیات ارزش افزوده:' : 'مالیات تا این صفحه:';
1544 const netLabel = isLast ? `مبلغ کل (${cur}):` : 'جمع تا این صفحه:';
1545 const wordsLabel = isLast ? 'مبلغ به حروف:' : 'مبلغ تا این صفحه به حروف:';
1883 -
1546 const summaryBox = `
1885 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px; margin-top:5px;">
1547 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px;margin-top:5px">
1548 <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 - `}
1549 + <td style="width:60%;border:1px solid #334155;padding:6px;vertical-align:top;background:#f8fafc">
1550 + <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet, cur)}</div>
1551 + ${isLast ? `<div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${inv.description || seller.footer || (isPre ? 'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.' : 'از خرید شما سپاسگزاریم.')}</div>` : `<div style="font-size:9.5px;color:#64748b">(ادامه در صفحه بعد...)</div>`}
1552 </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>
1553 + <td style="width:40%;border:1px solid #334155;padding:0">
1554 + <table style="width:100%;border-collapse:collapse;font-size:10.5px">
1555 + <tr><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px">${subtotalLabel}</td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left">${cumSub.toLocaleString('fa-IR')} ${cur}</td></tr>
1556 + ${cumDisc > 0 || inv.discount > 0 ? `<tr><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px">${discountLabel}</td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left">${cumDisc.toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1557 + ${hasVat ? `<tr style="background:#fffbeb"><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px"><strong>${vatLabel}</strong></td><td style="border-bottom:1px solid #cbd5e1;padding:3px 8px;text-align:left"><strong>${cumVat.toLocaleString('fa-IR')} ${cur}</strong></td></tr>` : ''}
1558 + <tr style="background:#f1f5f9;font-weight:bold;font-size:11.5px"><td style="padding:5px 8px">${netLabel}</td><td style="padding:5px 8px;text-align:left">${cumNet.toLocaleString('fa-IR')} ${cur}</td></tr>
1559 </table>
1560 </td>
1561 </tr>
1562 </table>
1563 `;
1909 -
1564 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;">
1565 + <table style="width:100%;border-collapse:collapse;border:1px solid #334155;margin-top:6px;text-align:center;font-size:10.5px">
1566 <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>
1567 + <td style="width:50%;height:50px;vertical-align:top;border:1px solid #334155;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
1568 + <td style="width:50%;height:50px;vertical-align:top;border:1px solid #334155;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
1569 </tr>
1570 </table>
1571 ` : '';
1918 -
1572 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;">
1573 + <div class="invoice-a4-page landscape" style="background:#fff;padding:7mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif">
1574 + <table style="width:100%;border-collapse:collapse;border:2px solid #334155;margin-bottom:5px">
1575 <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>
1576 + <td style="width:30%;border:1px solid #334155;padding:6px;vertical-align:middle">
1577 + <div style="font-weight:bold;font-size:13px;color:#0f172a">${seller.name || 'فروشگاه'}</div>
1578 + <div style="font-size:10px;color:#475569;margin-top:1px">تلفن: ${seller.phone || '—'}</div>
1579 </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>
1580 + <td style="width:40%;border:1px solid #334155;padding:6px;text-align:center;vertical-align:middle;background:#f8fafc">
1581 + <h1 style="font-size:15px;margin:0;font-weight:bold;color:#0f172a">${title}</h1>
1582 </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>
1583 + <td style="width:30%;border:1px solid #334155;padding:6px;font-size:10.5px;vertical-align:middle;text-align:left">
1584 + <div>شماره: <strong style="font-size:11.5px">#${inv.number}</strong></div>
1585 + <div style="margin-top:1px">تاریخ: <strong>${inv.date}</strong></div>
1586 + <div style="margin-top:1px;color:#64748b;font-size:9.5px">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
1587 </td>
1588 </tr>
1589 </table>
1937 -
1938 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px; margin-bottom:5px;">
1590 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px;margin-bottom:5px">
1591 <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>
1592 + <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
1593 + <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات فروشنده:</div>
1594 <div>نام: <strong>${seller.name || '—'}</strong></div>
1595 <div>نشانی: ${seller.address || '—'}</div>
1596 <div>تلفن تماس: ${seller.phone || '—'}</div>
1597 </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>
1598 + <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
1599 + <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات خریدار:</div>
1600 <div>نام: <strong>${contact.name || inv.contactName}</strong></div>
1601 <div>نشانی: ${contact.address || '—'}</div>
1602 <div>شماره همراه: ${contact.mobile || '—'}</div>
1603 </td>
1604 </tr>
1605 </table>
1954 -
1955 - <table style="width:100%; border-collapse:collapse; border:1.5px solid #334155; font-size:10.5px;">
1606 + <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px">
1607 <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>` : ''}
1608 + <tr style="background:#334155;color:#fff;font-weight:bold;text-align:center">
1609 + <th style="border:1px solid #334155;padding:5px 4px;width:32px">ردیف</th>
1610 + <th style="border:1px solid #334155;padding:5px 8px;text-align:right">شرح کالا | خدمات</th>
1611 + <th style="border:1px solid #334155;padding:5px 4px;width:60px">واحد</th>
1612 + <th style="border:1px solid #334155;padding:5px 4px;width:60px">مقدار</th>
1613 + <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat ? '110' : '150'}px;text-align:left">قیمت واحد (${cur})</th>
1614 + <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat ? '120' : '170'}px;text-align:left">قیمت کل (${cur})</th>
1615 + ${hasVat ? `<th style="border:1px solid #334155;padding:5px 4px;width:110px;text-align:left">مالیات (${cur})</th><th style="border:1px solid #334155;padding:5px 4px;width:130px;text-align:left">مبلغ نهایی (${cur})</th>` : ''}
1616 </tr>
1617 </thead>
1618 <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>` : ''}
1619 + ${!opt.isFirstPage ? `<tr style="background:#fef3c7;font-weight:bold;font-size:9.5px"><td colspan="${hasVat ? 6 : 5}" style="border:1px solid #334155;padding:3px;text-align:left">نقل از صفحه قبل:</td><td colspan="${hasVat ? 2 : 1}" style="border:1px solid #334155;padding:3px;text-align:left">${(opt.cumulativeBefore || 0).toLocaleString('fa-IR')} ${cur}</td></tr>` : ''}
1620 ${rowsHtml}
1621 </tbody>
1622 </table>
@@ -1983,7 +1634,6 @@ function renderAndPrintDirect(invId) {
1634 const contact = myContacts.find(c => c.id === inv.contactId) || {};
1635 const isFormal = (inv.kind === 'formal');
1636 const builder = isFormal ? buildFormalPage : buildNonFormalPage;
1986 -
1637 const allLines = computeInvoiceLines(inv);
1638 const pageGroups = [];
1639 let cumulativeSub = 0, cumulativeDisc = 0, cumulativeVat = 0;
@@ -1998,33 +1648,21 @@ function renderAndPrintDirect(invId) {
1648 const cumDiscAfter = cumulativeDisc + pageDisc;
1649 const cumVatAfter = cumulativeVat + pageVat;
1650 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 - });
1651 + pageGroups.push({ items: pageItems, isFirstPage, isLastPage, cumulativeBefore: cumulativeSub, cumulativeSubtotal: cumSubAfter, cumulativeDiscount: cumDiscAfter, cumulativeVat: cumVatAfter, cumulativeNet: cumNetAfter });
1652 cumulativeSub = cumSubAfter;
1653 cumulativeDisc = cumDiscAfter;
1654 cumulativeVat = cumVatAfter;
1655 }
1656 const totalPages = pageGroups.length;
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 -
1657 + const containerHtml = pageGroups.map((g, idx) => builder(g.items, seller, contact, inv, {
1658 + pageNum: idx + 1, totalPages,
1659 + isFirstPage: g.isFirstPage, isLastPage: g.isLastPage,
1660 + cumulativeBefore: g.cumulativeBefore,
1661 + cumulativeSubtotal: g.cumulativeSubtotal,
1662 + cumulativeDiscount: g.cumulativeDiscount,
1663 + cumulativeVat: g.cumulativeVat,
1664 + cumulativeNet: g.cumulativeNet
1665 + })).join('');
1666 let orientationStyle = document.getElementById('dynamic-print-orientation');
1667 if (!orientationStyle) {
1668 orientationStyle = document.createElement('style');
@@ -2032,7 +1670,6 @@ function renderAndPrintDirect(invId) {
1670 document.head.appendChild(orientationStyle);
1671 }
1672 orientationStyle.innerHTML = `@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
2035 -
1673 const printContainer = document.getElementById('printable-invoice');
1674 printContainer.innerHTML = containerHtml;
1675 printContainer.style.display = 'block';
@@ -2050,10 +1687,7 @@ function commitSaveProduct() {
1687 const buy_price = parseFloat(document.getElementById('prod-buy-input').value) || 0;
1688 const sale_price = parseFloat(document.getElementById('prod-sale-input').value) || 0;
1689 if (!name) { alert('عنوان کالا الزامی است.'); return; }
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 - });
1690 + datastore.products.push({ id: 'P_' + Date.now(), ownerUserId: currentUser.id, code, name, spec, type: 'good', unit, buy_price, sale_price, stock: 0 });
1691 saveDatastore();
1692 alert('کالا ثبت شد.');
1693 document.getElementById('prod-name-input').value = '';
@@ -2064,27 +1698,15 @@ function commitSaveProduct() {
1698 function renderProducts() {
1699 const tbody = document.getElementById('products-catalog-table-body');
1700 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('');
1701 + if (myProducts.length === 0) { tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:var(--text-muted);padding:20px">هیچ کالایی ثبت نشده است.</td></tr>'; return; }
1702 + tbody.innerHTML = myProducts.map(p => `<tr><td>${p.code}</td><td><strong>${p.name}</strong></td><td>${p.spec || '—'}</td><td>${p.unit}</td><td>${p.sale_price.toLocaleString('fa-IR')}</td><td><button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="deleteProduct('${p.id}')">حذف</button></td></tr>`).join('');
1703 }
1704
1705 function deleteProduct(id) {
1706 if (!currentUser) return;
1707 if (confirm('حذف شود؟')) {
1708 datastore.products = datastore.products.filter(p => !(p.id === id && p.ownerUserId === currentUser.id));
2086 - saveDatastore();
2087 - refreshAllSurfaces();
1709 + saveDatastore(); refreshAllSurfaces();
1710 }
1711 }
1712
@@ -2101,10 +1723,7 @@ function saveQuickProduct() {
1723 const price = parseFloat(document.getElementById('quick-p-price').value) || 0;
1724 if (!name) { alert('عنوان کالا الزامی است.'); return; }
1725 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 - });
1726 + datastore.products.push({ id: newId, ownerUserId: currentUser.id, code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good' });
1727 saveDatastore();
1728 closeQuickProductModal();
1729 refreshAllSurfaces();
@@ -2112,11 +1731,7 @@ function saveQuickProduct() {
1731 }
1732
1733 function downloadProductsExcelTemplate() {
2115 - const ws_data = [
2116 - ["کد کالا", "نام کالا", "مشخصه و نوع", "واحد", "قیمت فروش (ریال)"],
2117 - ["1", "سوئیچ شبکه 24 پورت", "با 2 پاور", "عدد", 2180000000],
2118 - ["2", "هارد 2.5 اینچ سرور", "", "عدد", 37000000]
2119 - ];
1734 + const ws_data = [["کد کالا","نام کالا","مشخصه و نوع","واحد","قیمت فروش (ریال)"],["1","سوئیچ شبکه 24 پورت","با 2 پاور","عدد",2180000000],["2","هارد 2.5 اینچ سرور","","عدد",37000000]];
1735 const ws = XLSX.utils.aoa_to_sheet(ws_data);
1736 const wb = XLSX.utils.book_new();
1737 XLSX.utils.book_append_sheet(wb, ws, "کالاها");
@@ -2149,8 +1764,7 @@ function importProductsFromExcel(event) {
1764 });
1765 }
1766 });
2152 - saveDatastore();
2153 - refreshAllSurfaces();
1767 + saveDatastore(); refreshAllSurfaces();
1768 alert('کالاها ایمپورت شدند.');
1769 } catch(err) { alert('خطا در فایل اکسل!'); }
1770 };
@@ -2171,11 +1785,7 @@ function commitSaveContact() {
1785 const address = document.getElementById('contact-address-input').value;
1786 if (!raw_name.trim()) { alert('نام طرف حساب الزامی است.'); return; }
1787 const formatted_name = formatEntityName(raw_name, entity_type, custom_prefix);
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 - });
1788 + datastore.contacts.push({ id: 'C_' + Date.now(), ownerUserId: currentUser.id, entity_type, name: formatted_name, role, mobile, national_id, economic_code, reg_number, postal_code, address, balance: 0 });
1789 saveDatastore();
1790 alert('طرف حساب ثبت شد.');
1791 document.getElementById('contact-name-input').value = '';
@@ -2188,19 +1798,9 @@ function renderContacts() {
1798 const chqSelect = document.getElementById('chq-contact-select');
1799 const myContacts = getMyContacts();
1800 if (myContacts.length === 0) {
2191 - tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ طرف حسابی ثبت نشده است.</td></tr>';
1801 + tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">هیچ طرف حسابی ثبت نشده است.</td></tr>';
1802 } 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('');
1803 + tbody.innerHTML = myContacts.map(c => `<tr><td><strong>${c.name}</strong></td><td><span class="badge ${c.entity_type === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td><td>${c.national_id || '—'}</td><td>${c.economic_code || '—'}</td><td>${c.postal_code || '—'}</td><td>${c.mobile || '—'}</td><td>${Math.abs(c.balance || 0).toLocaleString('fa-IR')}</td><td><button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="deleteContact('${c.id}')">حذف</button></td></tr>`).join('');
1804 }
1805 const options = myContacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
1806 if (invSelect) invSelect.innerHTML = options;
@@ -2211,15 +1811,11 @@ function deleteContact(id) {
1811 if (!currentUser) return;
1812 if (confirm('حذف شود؟')) {
1813 datastore.contacts = datastore.contacts.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
2214 - saveDatastore();
2215 - refreshAllSurfaces();
1814 + saveDatastore(); refreshAllSurfaces();
1815 }
1816 }
1817
2219 -function openQuickContactModal() {
2220 - document.getElementById('modal-quick-contact').classList.add('active');
2221 - handleQuickCEntityChange();
2222 -}
1818 +function openQuickContactModal() { document.getElementById('modal-quick-contact').classList.add('active'); handleQuickCEntityChange(); }
1819 function closeQuickContactModal() { document.getElementById('modal-quick-contact').classList.remove('active'); }
1820
1821 function saveQuickContact() {
@@ -2248,10 +1844,7 @@ function saveQuickContact() {
1844 }
1845
1846 function downloadContactsExcelTemplate() {
2251 - const ws_data = [
2252 - ["نام شخص یا شرکت", "نوع (حقیقی/حقوقی)", "شماره همراه", "شناسه یا کد ملی", "کد اقتصادی", "شماره ثبت", "کد پستی", "نشانی"],
2253 - ["دانشگاه صنعتی شریف", "حقوقی", "02166165000", "14002830256", "14002830256", "", "1458889694", "طرشت محله تیموری پلاک 435"]
2254 - ];
1847 + const ws_data = [["نام شخص یا شرکت","نوع (حقیقی/حقوقی)","شماره همراه","شناسه یا کد ملی","کد اقتصادی","شماره ثبت","کد پستی","نشانی"],["دانشگاه صنعتی شریف","حقوقی","02166165000","14002830256","14002830256","","1458889694","طرشت محله تیموری پلاک 435"]];
1848 const ws = XLSX.utils.aoa_to_sheet(ws_data);
1849 const wb = XLSX.utils.book_new();
1850 XLSX.utils.book_append_sheet(wb, ws, "اشخاص");
@@ -2286,8 +1879,7 @@ function importContactsFromExcel(event) {
1879 });
1880 }
1881 });
2289 - saveDatastore();
2290 - refreshAllSurfaces();
1882 + saveDatastore(); refreshAllSurfaces();
1883 alert('اشخاص ایمپورت شدند.');
1884 } catch(err) { alert('خطا در فایل اکسل!'); }
1885 };
@@ -2303,12 +1895,7 @@ function commitSaveCheque() {
1895 const bank = document.getElementById('chq-bank-input').value;
1896 const amount = parseFloat(document.getElementById('chq-amount-input').value) || 0;
1897 if (!sayad_id || amount <= 0) { alert('اطلاعات چک نامعتبر است.'); return; }
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 - });
1898 + datastore.cheques.push({ id: 'CHQ_' + Date.now(), ownerUserId: currentUser.id, direction, contactName, sayad_id, bank, amount, due_date: document.getElementById('chq-due-input').value, status: document.getElementById('chq-status-input').value });
1899 saveDatastore();
1900 alert('چک ثبت شد.');
1901 refreshAllSurfaces();
@@ -2317,20 +1904,14 @@ function commitSaveCheque() {
1904 function renderCheques() {
1905 const tbody = document.getElementById('cheques-ledger-table-body');
1906 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('');
1907 + tbody.innerHTML = myCheques.length === 0 ? '<tr><td colspan="6" style="text-align:center;padding:20px;color:var(--text-muted)">چکی ثبت نشده است.</td></tr>' : myCheques.map(c => `<tr><td>${c.direction === 'inbound' ? 'دریافتی' : 'پرداختی'}</td><td>${c.contactName}</td><td>${c.bank} - ${c.sayad_id}</td><td>${c.amount.toLocaleString('fa-IR')}</td><td>${c.due_date}</td><td>${c.status}</td></tr>`).join('');
1908 }
1909
1910 function commitSaveExpense() {
1911 if (!currentUser) return;
1912 const amount = parseFloat(document.getElementById('trx-amount-input').value) || 0;
1913 if (amount <= 0) { alert('مبلغ معتبر نیست.'); return; }
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 - });
1914 + datastore.expenses.push({ id: 'TRX_' + Date.now(), ownerUserId: currentUser.id, kind: document.getElementById('trx-kind-input').value, category: document.getElementById('trx-category-input').value, amount, desc: document.getElementById('trx-desc-input').value });
1915 saveDatastore();
1916 alert('سند ثبت شد.');
1917 refreshAllSurfaces();
@@ -2339,8 +1920,7 @@ function commitSaveExpense() {
1920 function renderExpenses() {
1921 const tbody = document.getElementById('expenses-ledger-table-body');
1922 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('');
1923 + tbody.innerHTML = myExpenses.length === 0 ? '<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">موردی ثبت نشده است.</td></tr>' : myExpenses.map(e => `<tr><td>${e.kind}</td><td>${e.category}</td><td>${e.desc}</td><td>${e.amount.toLocaleString('fa-IR')}</td></tr>`).join('');
1924 }
1925
1926 function commitSaveCompany() {
@@ -2364,10 +1944,7 @@ function commitSaveCompany() {
1944 s.default_company_id = newComp.id;
1945 saveDatastore();
1946 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 - });
1947 + ['company-name-input','company-phone-input','company-national-input','company-economic-input','company-reg-input','company-postal-input','company-address-input','company-footer-input'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; });
1948 refreshAllSurfaces();
1949 }
1950
@@ -2380,16 +1957,9 @@ function renderCompanies() {
1957 const defCompId = mySettings.default_company_id || (myCompanies[0]?.id);
1958 if (tbody) {
1959 if (myCompanies.length === 0) {
2383 - tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
1960 + tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:var(--text-muted);padding:20px">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
1961 } 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('');
1962 + tbody.innerHTML = myCompanies.map(c => `<tr><td><strong>${c.name}</strong></td><td>${c.national_id || '—'}</td><td>${c.economic_code || '—'}</td><td>${c.id === defCompId ? '<span class="badge badge-success">پیش‌فرض</span>' : `<button class="btn btn-secondary btn-inline" style="padding:2px 8px;font-size:11px" onclick="setDefaultCompany('${c.id}')">انتخاب</button>`}</td><td>${myCompanies.length > 1 ? `<button class="btn btn-danger btn-inline" style="padding:2px 8px;font-size:11px" onclick="deleteCompany('${c.id}')">حذف</button>` : '—'}</td></tr>`).join('');
1963 }
1964 }
1965 if (invoiceCompSelect) {
@@ -2403,12 +1973,7 @@ function renderCompanies() {
1973 }
1974 }
1975
2406 -function setDefaultCompany(id) {
2407 - const s = getMySettings();
2408 - s.default_company_id = id;
2409 - saveDatastore();
2410 - refreshAllSurfaces();
2411 -}
1976 +function setDefaultCompany(id) { const s = getMySettings(); s.default_company_id = id; saveDatastore(); refreshAllSurfaces(); }
1977
1978 function deleteCompany(id) {
1979 if (!currentUser) return;
@@ -2417,19 +1982,12 @@ function deleteCompany(id) {
1982 const myCompanies = getMyCompanies();
1983 const s = getMySettings();
1984 if (s.default_company_id === id) s.default_company_id = myCompanies[0]?.id || '';
2420 - saveDatastore();
2421 - refreshAllSurfaces();
1985 + saveDatastore(); refreshAllSurfaces();
1986 }
1987 }
1988
1989 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 - };
1990 + const userExport = { user: currentUser?.username, exportedAt: new Date().toISOString(), companies: getMyCompanies(), contacts: getMyContacts(), products: getMyProducts(), invoices: getMyInvoices(), cheques: getMyCheques(), expenses: getMyExpenses(), settings: getMySettings() };
1991 const blobString = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(userExport, null, 2));
1992 const anchor = document.createElement('a');
1993 anchor.setAttribute("href", blobString);
@@ -2453,12 +2011,8 @@ function importDataBlob(event) {
2011 imported[key].forEach(item => { item.ownerUserId = userId; datastore[key].push(item); });
2012 }
2013 });
2456 - if (imported.settings) {
2457 - const s = getMySettings();
2458 - Object.assign(s, imported.settings, { ownerUserId: userId });
2459 - }
2460 - saveDatastore();
2461 - refreshAllSurfaces();
2014 + if (imported.settings) { const s = getMySettings(); Object.assign(s, imported.settings, { ownerUserId: userId }); }
2015 + saveDatastore(); refreshAllSurfaces();
2016 alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
2017 } catch(err) { alert('فایل نامعتبر است.'); }
2018 };
@@ -2514,35 +2068,19 @@ window.addEventListener('DOMContentLoaded', () => { initAuthSystem(); });
2068 const oldSave = window.commitSaveInvoice;
2069 window.commitSaveInvoice = function(){
2070 const rows = document.querySelectorAll('#invoice-items-table-body tr');
2517 - if(!rows.length){
2518 - alert('حداقل یک ردیف کالا یا خدمت لازم است.');
2519 - return;
2520 - }
2071 + if(!rows.length){ alert('حداقل یک ردیف کالا یا خدمت لازم است.'); return; }
2072 for(const row of rows){
2073 const sel = row.querySelector('.row-product-select');
2523 - if(sel && !sel.value){
2524 - alert('لطفاً شرح کالا یا خدمت را از لیست انتخاب کنید.');
2525 - return;
2526 - }
2074 + if(sel && !sel.value){ alert('لطفاً شرح کالا یا خدمت را از لیست انتخاب کنید.'); return; }
2075 const qty = parseFloat(row.querySelector('.row-quantity')?.value) || 0;
2528 - if(qty <= 0){
2529 - alert('مقدار کالا باید بزرگتر از صفر باشد.');
2530 - return;
2531 - }
2076 + if(qty <= 0){ alert('مقدار کالا باید بزرگتر از صفر باشد.'); return; }
2077 }
2078 if(typeof oldSave === 'function') return oldSave();
2079 };
2535 -
2080 window.EasyFactorHealth = {
2081 version: '5.2-dev-info',
2082 storage: 'localStorage',
2539 - checks(){
2540 - return {
2541 - rtl: document.documentElement.dir === 'rtl',
2542 - storage: !!window.localStorage,
2543 - printReady: !!document.getElementById('printable-invoice')
2544 - };
2545 - }
2083 + checks(){ return { rtl: document.documentElement.dir === 'rtl', storage: !!window.localStorage, printReady: !!document.getElementById('printable-invoice') }; }
2084 };
2085 })();
2086 </script>