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

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

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

Synced Dec 3, 17:00 UTC

Update print statement from 'Hello' to 'Goodbye'

davoodmehraban89 committed Sep 17, 2026 at 06:31 UTC 9a98ede770edd3af641087d47b4952e0165f68db
1 file changed +895 -343
index.html
+895 -343
@@ -68,6 +68,7 @@
68 .btn-secondary:hover { background: #cbd5e1; }
69 .btn-success { background: var(--success); }
70 .btn-danger { background: var(--danger); }
71 + .btn-warning { background: var(--warning); color: #fff; }
72
73 .form-group { margin-bottom: 14px; width: 100%; }
74 .form-group label { display: block; margin-bottom: 6px; font-size: 13px; font-weight: 600; color: #334155; }
@@ -81,7 +82,6 @@
82 th, td { padding: 10px 10px; border-bottom: 1px solid var(--border); }
83 th { background: #f1f5f9; color: #334155; font-weight: 700; }
84
84 - /* ترتیب و نمایش صحیح جدول اقلام فاکتور در RTL */
85 #invoice-items-table { direction: rtl; width: 100%; table-layout: auto; }
86 #invoice-items-table th, #invoice-items-table td { text-align: right; }
87 #invoice-items-table th:first-child, #invoice-items-table td:first-child { text-align: center; }
@@ -91,6 +91,7 @@
91 .badge-success { background: #d1fae5; color: #065f46; }
92 .badge-warning { background: #fef3c7; color: #92400e; }
93 .badge-danger { background: #fee2e2; color: #991b1b; }
94 + .badge-info { background: #e0f2fe; color: #0369a1; }
95
96 .view-pane { display: none; }
97 .view-pane.active { display: block; }
@@ -104,9 +105,6 @@
105 .accordion-body { padding: 16px; border-top: 1px solid var(--border); display: none; background: #fff; }
106 .accordion-item.open .accordion-body { display: block; }
107
107 - /* =========================================================================
108 - تنظیمات اختصاصی و کنترل دقیق چاپ فاکتور در اندازه A4 (رسمی و غیررسمی)
109 - ========================================================================= */
108 @media print {
109 @page {
110 size: A4 portrait;
@@ -164,7 +162,7 @@
162 </head>
163 <body>
164
167 - <!-- صفحه ورود و ثبت‌نام تجاری -->
165 + <!-- صفحه ورود و ثبت‌نام -->
166 <div id="auth-screen">
167 <div class="auth-card">
168 <div style="text-align:center; margin-bottom:20px;">
@@ -197,7 +195,7 @@
195 <div class="brand-icon">ایزی</div>
196 <div>
197 <h2 style="font-size: 15px; font-weight: bold;">ایزی فاکتور</h2>
200 - <small style="color: var(--text-muted); font-size: 11px;">نگارش ۴.۶ (ضد کش کامل)</small>
198 + <small style="color: var(--text-muted); font-size: 11px;">نسخه چندکاربره ۴.۷</small>
199 </div>
200 </div>
201 <ul class="sidebar-menu">
@@ -208,7 +206,7 @@
206 <li><a href="#" class="nav-link" data-view="view-cheques" onclick="switchView('view-cheques'); return false;">💳 چک‌ها و صیاد</a></li>
207 <li><a href="#" class="nav-link" data-view="view-expenses" onclick="switchView('view-expenses'); return false;">💰 هزینه‌ها و درآمد</a></li>
208 <li><a href="#" class="nav-link" data-view="view-settings" onclick="switchView('view-settings'); return false;">⚙️ تنظیمات و شرکت‌ها</a></li>
211 - <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>
209 + <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>
210 </ul>
211 <div class="sidebar-footer">
212 <span id="logged-user-label">کاربر</span>
@@ -221,17 +219,20 @@
219
220 <!-- ۱. داشبورد -->
221 <section id="view-dashboard" class="view-pane active">
224 - <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; flex-wrap: wrap; gap: 10px;">
222 + <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; gap: 10px;">
223 <div>
224 <h1 style="font-size: 20px; font-weight: bold;">سامانه ایزی فاکتور</h1>
225 <p style="color: var(--text-muted); font-size: 13px;" id="dashboard-date-display"></p>
226 </div>
227 <div style="display:flex; align-items:center; gap:10px;">
230 - <span id="user-license-status-badge" class="badge badge-warning">آزمایشی</span>
228 + <span id="user-license-status-badge" class="badge badge-warning">در حال بررسی...</span>
229 <button class="btn btn-inline no-print" onclick="startNewInvoice()">➕ فاکتور جدید</button>
230 </div>
231 </div>
232
233 + <!-- جزئیات لایسنس و اشتراک کاربر بر اساس اولویت سیستم لایسنس -->
234 + <div id="dashboard-license-details"></div>
235 +
236 <div class="grid-kpi">
237 <div class="kpi-unit">
238 <div class="kpi-icon" style="background:#eff6ff; color:var(--primary);">💰</div>
@@ -332,7 +333,7 @@
333 </div>
334 </div>
335
335 - <!-- بخش اقلام فاکتور با ترتیب ستون‌های کاملاً استاندارد و منطبق در RTL -->
336 + <!-- اقلام کالا -->
337 <div style="margin: 16px 0;">
338 <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
339 <h4 style="font-size: 14px;">اقلام کالا یا خدمات</h4>
@@ -642,19 +643,19 @@
643 <div class="form-row">
644 <div class="form-group">
645 <label>قالب پیش‌فرض فاکتور</label>
645 - <select id="def-invoice-kind" class="form-control" onchange="handleDefaultKindChange()">
646 + <select id="def-invoice-kind" class="form-control">
647 <option value="non_formal">فاکتور غیررسمی</option>
648 <option value="formal">فاکتور رسمی</option>
649 </select>
650 </div>
650 - <div class="form-group" id="def-vat-mode-box">
651 + <div class="form-group">
652 <label>وضعیت پیش‌فرض ارزش افزوده</label>
652 - <select id="def-vat-mode" class="form-control" onchange="handleDefaultVatModeChange()">
653 + <select id="def-vat-mode" class="form-control">
654 <option value="none">بدون ارزش افزوده</option>
655 <option value="with_vat">با ارزش افزوده</option>
656 </select>
657 </div>
657 - <div class="form-group" id="def-vat-rate-box">
658 + <div class="form-group">
659 <label>نرخ ارزش افزوده (درصد)</label>
660 <input type="number" id="def-vat-rate" class="form-control" value="10" />
661 </div>
@@ -670,7 +671,7 @@
671 </div>
672 <div class="accordion-body">
673 <p style="font-size:13px; color:var(--text-muted); margin-bottom:12px;">
673 - وضعیت دیتابیس: <span class="badge badge-success">سالم و فعال</span>
674 + وضعیت دیتابیس: <span class="badge badge-success">تفکیک کاربر فعال</span>
675 </p>
676 <div style="display:flex; gap:10px; flex-wrap:wrap;">
677 <button class="btn btn-secondary" onclick="exportDataBlob()">📥 دانلود فایل پشتیبان (JSON)</button>
@@ -686,8 +687,8 @@
687 </div>
688 <div class="accordion-body">
689 <h3 style="font-size:16px; font-weight:bold;">ایزی فاکتور - EasyFactor</h3>
689 - <p style="color:var(--text-muted); font-size:13px; margin:6px 0 12px 0;">سیستم هوشمند صدور فاکتور رسمی و غیررسمی (ریال)</p>
690 - <p style="font-size:13px; margin-bottom:14px;">نگارش فعال: <strong>نسخه ۴.۶ (پایدار کامل)</strong></p>
690 + <p style="color:var(--text-muted); font-size:13px; margin:6px 0 12px 0;">سامانه ابری صدور فاکتور و مدیریت مالی چندکاربره</p>
691 + <p style="font-size:13px; margin-bottom:14px;">نگارش فعال: <strong>نسخه ۴.۷ (ایزولاسیون کامل داده و مدیریت مرکزی لایسنس)</strong></p>
692 <div style="display:flex; gap:10px;">
693 <button class="btn btn-primary" onclick="alert('آخرین نگارش نصب است.')">بررسی آپدیت</button>
694 <button class="btn btn-secondary" onclick="alert('پشتیبانی فعال است.')">گزارش باگ</button>
@@ -697,24 +698,64 @@
698
699 </section>
700
700 - <!-- بخش ادمین کل -->
701 + <!-- بخش ادمین کل و مدیریت کاربران و لایسنس‌ها -->
702 <section id="view-admin" class="view-pane">
703 <div class="card">
703 - <h2 style="font-size: 18px; margin-bottom: 12px; color:var(--danger);">👑 پنل مدیریت مرکزی لایسنس کاربران</h2>
704 - <p style="color:var(--text-muted); font-size:13px; margin-bottom:16px;">
705 - مدیریت دسترسی کاربران و تمدید حساب‌های آزمایشی (Trial) به نسخه تجاری.
706 - </p>
704 + <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; flex-wrap:wrap; gap:10px;">
705 + <div>
706 + <h2 style="font-size: 18px; color:var(--danger);">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2>
707 + <p style="color:var(--text-muted); font-size:13px; margin-top:4px;">
708 + تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.
709 + </p>
710 + </div>
711 + <button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
712 + </div>
713 +
714 + <!-- فرم تعریف کاربر جدید توسط ادمین -->
715 + <div style="background:#f8fafc; border:1px solid var(--border); border-radius:10px; padding:16px; margin-bottom:20px;">
716 + <h4 style="font-size:14px; margin-bottom:12px; color:#1e293b;">➕ ایجاد حساب کاربری جدید</h4>
717 + <div class="form-row">
718 + <div class="form-group">
719 + <label>نام کاربری</label>
720 + <input type="text" id="admin-new-username" class="form-control" placeholder="نام کاربری..." />
721 + </div>
722 + <div class="form-group">
723 + <label>رمز عبور</label>
724 + <input type="password" id="admin-new-password" class="form-control" placeholder="رمز عبور..." />
725 + </div>
726 + <div class="form-group">
727 + <label>طرح اولیه لایسنس</label>
728 + <select id="admin-new-subtype" class="form-control">
729 + <option value="trial">آزمایشی (۱۵ روزه)</option>
730 + <option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option>
731 + <option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option>
732 + <option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option>
733 + <option value="lifetime">اشتراک دائمی (Lifetime)</option>
734 + </select>
735 + </div>
736 + <div class="form-group" style="display:flex; align-items:flex-end;">
737 + <button class="btn btn-success" style="width:100%; min-height:44px;" onclick="adminCreateNewUser()">➕ ایجاد کاربر</button>
738 + </div>
739 + </div>
740 + </div>
741 +
742 + <!-- جدول کاربران و لایسنس‌ها با ستون‌های الزامی -->
743 <div class="table-responsive">
744 <table>
745 <thead>
746 <tr>
747 <th>نام کاربری</th>
712 - <th>وضعیت اشتراک</th>
713 - <th>تاریخ انقضا / اعتبار</th>
714 - <th>عملیات ادمین (ارتقای لایسنس)</th>
748 + <th>وضعیت حساب</th>
749 + <th>نوع اشتراک</th>
750 + <th>تاریخ شروع</th>
751 + <th>تاریخ پایان</th>
752 + <th>روزهای باقیمانده</th>
753 + <th>عملیات مدیریت لایسنس</th>
754 </tr>
755 </thead>
717 - <tbody id="admin-users-table-body"></tbody>
756 + <tbody id="admin-users-table-body">
757 + <tr><td colspan="7" style="text-align:center; padding:20px;">در حال بارگذاری کاربران...</td></tr>
758 + </tbody>
759 </table>
760 </div>
761 </div>
@@ -772,7 +813,28 @@
813 </div>
814 </div>
815
775 - <!-- ناو بار موبایل با ۶ تب کامل شامل تنظیمات -->
816 + <!-- مودال تغییر مدت و لایسنس توسط ادمین -->
817 + <div class="modal-backdrop" id="modal-admin-license-edit">
818 + <div class="modal-card">
819 + <h3 style="font-size:16px; margin-bottom:12px;" id="modal-license-user-title">تغییر مدت و لایسنس کاربر</h3>
820 + <input type="hidden" id="modal-license-target-username" />
821 + <div class="form-group">
822 + <label>انتخاب مدت و نوع لایسنس جدید</label>
823 + <select id="modal-license-duration-select" class="form-control">
824 + <option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option>
825 + <option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option>
826 + <option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option>
827 + <option value="lifetime">اشتراک دائمی (Lifetime)</option>
828 + </select>
829 + </div>
830 + <div style="display:flex; gap:10px; margin-top:16px;">
831 + <button class="btn btn-success" style="flex:1;" onclick="applyLicenseDurationChange()">تایید و اعمال لایسنس</button>
832 + <button class="btn btn-secondary" style="flex:1;" onclick="closeLicenseEditModal()">انصراف</button>
833 + </div>
834 + </div>
835 + </div>
836 +
837 + <!-- ناو بار موبایل -->
838 <nav class="mobile-dock">
839 <div class="dock-tab active" onclick="switchView('view-dashboard')">
840 <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>
@@ -805,188 +867,135 @@
867 const AUTH_KEY = 'easy_factor_auth_users_v4_6';
868
869 /* =========================================================================
808 - معماری ذخیره‌سازی داده‌ها و آمادگی برای همگام‌سازی ابری (Cloud Sync Layer)
809 - -------------------------------------------------------------------------
810 - این لایه عملیات ذخیره و بازیابی محلی را مدیریت کرده و نقاط اتصال استاندارد
811 - برای هماهنگ‌سازی میان دستگاه‌های مختلف (آیفون، کامپیوتر و...) را فراهم می‌کند.
870 + توابع کمکی تبدیل و قالب‌بندی تاریخ خورشیدی و اعداد فارسی
871 ========================================================================= */
813 - const CLOUD_SYNC_CONFIG = {
814 - enabled: false, // پس از راه‌اندازی سرور به true تغییر دهید
815 - apiEndpoint: '', // به عنوان مثال: 'https://api.yourdomain.com/v1/sync'
816 - authToken: '',
817 - deviceId: localStorage.getItem('easy_factor_device_id') || (() => {
818 - const id = 'dev_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
819 - localStorage.setItem('easy_factor_device_id', id);
820 - return id;
821 - })()
822 - };
872 + function toPersianDigits(str) {
873 + if (str === null || str === undefined) return '';
874 + return String(str).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
875 + }
876
824 - /**
825 - * ذخیره پایگاه داده در حافظه محلی و فراخوانی همگام‌سازی ابری در صورت فعال بودن
826 - */
827 - async function saveDatastore() {
828 - try {
829 - localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
830 - if (CLOUD_SYNC_CONFIG.enabled && CLOUD_SYNC_CONFIG.apiEndpoint) {
831 - await syncDatastore('push');
877 + function formatToJalali(dateInput) {
878 + if (!dateInput) return '—';
879 + let dateObj;
880 + if (dateInput instanceof Date) {
881 + dateObj = dateInput;
882 + } else if (typeof dateInput === 'string' && dateInput.includes('/')) {
883 + return toPersianDigits(dateInput);
884 + } else {
885 + const str = String(dateInput).split('T')[0];
886 + const parts = str.split('-');
887 + if (parts.length === 3) {
888 + dateObj = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
889 + } else {
890 + dateObj = new Date(dateInput);
891 }
833 - return true;
834 - } catch (err) {
835 - console.error('Error saving datastore:', err);
836 - return false;
892 }
893 + if (isNaN(dateObj.getTime())) return toPersianDigits(String(dateInput));
894 + return new Intl.DateTimeFormat('fa-IR-u-ca-persian', {
895 + year: 'numeric',
896 + month: '2-digit',
897 + day: '2-digit'
898 + }).format(dateObj);
899 }
900
840 - // حفظ سازگاری توابع قبلی
841 - function persistDatastore() {
842 - return saveDatastore();
901 + function getRemainingDays(endDateStr) {
902 + if (!endDateStr) return 0;
903 + if (String(endDateStr).startsWith('2099')) return Infinity;
904 + const str = String(endDateStr).split('T')[0];
905 + const parts = str.split('-');
906 + if (parts.length !== 3) return 0;
907 + const end = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 23, 59, 59);
908 + const now = new Date();
909 + const diff = end.getTime() - now.getTime();
910 + return Math.ceil(diff / (1000 * 60 * 60 * 24));
911 }
912
845 - /**
846 - * بارگذاری پایگاه داده از حافظه محلی به همراه اصلاحات امنیتی و بررسی ابری
847 - */
848 - async function loadDatastore() {
849 - const persisted = localStorage.getItem(STORAGE_KEY);
850 - if (persisted) {
851 - try {
852 - datastore = JSON.parse(persisted);
853 - } catch (e) {
854 - console.error('Error parsing datastore:', e);
855 - }
856 - }
857 -
858 - // ساختارهای پیش‌فرض ایمن
859 - if (!datastore.default_settings) {
860 - datastore.default_settings = {};
861 - }
862 - if (!Array.isArray(datastore.companies)) {
863 - datastore.companies = [];
864 - }
865 - if (!Array.isArray(datastore.contacts)) {
866 - datastore.contacts = [];
867 - }
868 - if (!Array.isArray(datastore.products)) {
869 - datastore.products = [];
870 - }
871 - if (!Array.isArray(datastore.invoices)) {
872 - datastore.invoices = [];
873 - }
874 - if (!Array.isArray(datastore.cheques)) {
875 - datastore.cheques = [];
876 - }
877 - if (!Array.isArray(datastore.expenses)) {
878 - datastore.expenses = [];
879 - }
880 -
881 - // بررسی و تثبیت شرکت فعال پیش‌فرض
882 - if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
883 - datastore.default_settings.default_company_id = datastore.companies[0].id;
884 - }
885 -
886 - localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
887 -
888 - if (CLOUD_SYNC_CONFIG.enabled && CLOUD_SYNC_CONFIG.apiEndpoint) {
889 - await syncDatastore('pull');
913 + function addDaysToDate(baseDateStr, days) {
914 + let d;
915 + if (baseDateStr) {
916 + const parts = String(baseDateStr).split('T')[0].split('-');
917 + d = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 12, 0, 0);
918 + } else {
919 + d = new Date();
920 }
891 -
892 - return datastore;
921 + if (isNaN(d.getTime())) d = new Date();
922 + d.setDate(d.getDate() + days);
923 + return d.toISOString().split('T')[0];
924 }
925
895 - /**
896 - * هوک همگام‌سازی ابری بین دستگاه‌ها (آیفون، کامپیوتر و...)
897 - * جهت اتصال به بک‌اند (REST API / Supabase / Firebase / Node.js)
898 - */
899 - async function syncDatastore(direction = 'merge') {
900 - /* =========================================================================
901 - [محل اتصال API همگام‌سازی ابری]
902 - جهت هماهنگ‌سازی آنی فاکتورها و شرکت‌ها بین گوشی و رایانه:
903 - ۱. CLOUD_SYNC_CONFIG.enabled را برابر true قرار دهید.
904 - ۲. آدرس وب‌سرویس خود را در CLOUD_SYNC_CONFIG.apiEndpoint تنظیم فرمایید.
905 - ۳. در این بخش درخواست HTTP به سرور ارسال و پاسخ در datastore جایگزین می‌شود.
906 - ========================================================================= */
907 - if (!CLOUD_SYNC_CONFIG.enabled || !CLOUD_SYNC_CONFIG.apiEndpoint) {
908 - return { status: 'offline_mode', message: 'حافظه محلی مرورگر فعال است.' };
926 + /* =========================================================================
927 + سیستم مرکزی کاربران و احراز هویت (Central User Management)
928 + ========================================================================= */
929 + let currentUser = null;
930 + let usersDb = [];
931 +
932 + const defaultAdminUser = {
933 + id: 'user_admin',
934 + username: 'admin',
935 + pass: 'admin123',
936 + role: 'admin',
937 + createdAt: '2026-09-16T00:00:00.000Z',
938 + subscriptionType: 'lifetime',
939 + subscriptionStart: '2026-09-16',
940 + subscriptionEnd: '2099-01-01',
941 + licenseStatus: 'active',
942 + subscription: {
943 + type: 'lifetime',
944 + startDate: '2026-09-16',
945 + endDate: '2099-01-01',
946 + status: 'active'
947 }
948 + };
949
911 - try {
912 - /* نمونه کد جهت اتصال به سرور ابری در آینده:
913 - const response = await fetch(CLOUD_SYNC_CONFIG.apiEndpoint, {
914 - method: 'POST',
915 - headers: {
916 - 'Content-Type': 'application/json',
917 - 'Authorization': `Bearer ${CLOUD_SYNC_CONFIG.authToken}`,
918 - 'X-Device-ID': CLOUD_SYNC_CONFIG.deviceId
919 - },
920 - body: JSON.stringify({ direction, datastore, timestamp: Date.now() })
921 - });
922 - if (response.ok) {
923 - const resData = await response.json();
924 - if (resData && resData.datastore) {
925 - datastore = resData.datastore;
926 - localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
927 - refreshAllSurfaces();
928 - }
950 + function loadUsers() {
951 + const saved = localStorage.getItem(AUTH_KEY);
952 + if (saved) {
953 + try {
954 + usersDb = JSON.parse(saved);
955 + } catch (e) {
956 + console.error('Error parsing users:', e);
957 + usersDb = [];
958 }
930 - */
931 - return { status: 'synced' };
932 - } catch (err) {
933 - console.warn('Sync connection notice:', err);
934 - return { status: 'error', error: err };
959 }
960 + if (!Array.isArray(usersDb) || usersDb.length === 0) {
961 + usersDb = [defaultAdminUser];
962 + persistUsers();
963 + } else {
964 + let modified = false;
965 + usersDb.forEach((u, idx) => {
966 + if (!u.id) {
967 + u.id = u.username === 'admin' ? 'user_admin' : 'usr_' + Date.now() + '_' + idx;
968 + modified = true;
969 + }
970 + if (!u.createdAt) {
971 + u.createdAt = new Date().toISOString();
972 + modified = true;
973 + }
974 + if (!u.subscription) {
975 + u.subscription = {
976 + type: u.subscriptionType || u.license_type || 'trial',
977 + startDate: u.subscriptionStart || new Date().toISOString().split('T')[0],
978 + endDate: u.subscriptionEnd || u.expire_date || addDaysToDate(null, 15),
979 + status: (u.license_type === 'lifetime' || u.subscriptionType === 'lifetime' || u.role === 'admin') ? 'active' : 'trial'
980 + };
981 + modified = true;
982 + }
983 + u.subscriptionType = u.subscription.type;
984 + u.subscriptionStart = u.subscription.startDate;
985 + u.subscriptionEnd = u.subscription.endDate;
986 + u.licenseStatus = u.subscription.status;
987 + });
988 + if (modified) persistUsers();
989 + }
990 + return usersDb;
991 }
992
938 - let currentUser = null;
939 - let usersDb = [
940 - { username: 'admin', pass: 'admin123', role: 'admin', license_type: 'lifetime', expire_date: '2099-01-01' }
941 - ];
942 -
943 - let datastore = {
944 - default_settings: { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: 'COMP-1' },
945 - companies: [
946 - {
947 - id: 'COMP-1',
948 - entity_type: 'legal',
949 - name: 'آرا سپهر راستین',
950 - phone: '09124376991',
951 - national_id: '14008507476',
952 - economic_code: '14008507476',
953 - reg_number: '544926',
954 - postal_code: '1445956311',
955 - address: 'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',
956 - footer: 'از خرید شما سپاسگزاریم.'
957 - }
958 - ],
959 - contacts: [
960 - {
961 - id: 'C-1',
962 - entity_type: 'legal',
963 - name: 'شرکت دانشگاه صنعتی شریف',
964 - mobile: '02166165000',
965 - national_id: '14002830256',
966 - economic_code: '14002830256',
967 - reg_number: '',
968 - postal_code: '1458889694',
969 - address: 'طرشت محله تیموری پلاک 435',
970 - balance: 7978300000,
971 - role: 'customer'
972 - }
973 - ],
974 - products: [
975 - { id: 'P-1', code: '1', name: 'سوئیچ شبکه 24 پورت فیبر نوری', spec: 'با 2 پاور 350', unit: 'عدد', buy_price: 1800000000, sale_price: 2180000000, stock: 10, type: 'good' },
976 - { id: 'P-2', code: '2', name: 'هارد 2.5 اینچ سرور', spec: '', unit: 'عدد', buy_price: 30000000, sale_price: 37000000, stock: 10, type: 'good' }
977 - ],
978 - invoices: [],
979 - cheques: [],
980 - expenses: []
981 - };
993 + function persistUsers() {
994 + localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb));
995 + }
996
997 function initAuthSystem() {
984 - const savedUsers = localStorage.getItem(AUTH_KEY);
985 - if (savedUsers) {
986 - try { usersDb = JSON.parse(savedUsers); } catch(e) {}
987 - } else {
988 - localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb));
989 - }
998 + loadUsers();
999
1000 const activeSession = sessionStorage.getItem('easy_factor_session_v4_6');
1001 if (activeSession) {
@@ -1002,6 +1011,7 @@
1011 function handleLogin() {
1012 const user = document.getElementById('auth-username').value.trim();
1013 const pass = document.getElementById('auth-password').value.trim();
1014 + loadUsers();
1015 const found = usersDb.find(x => x.username === user && x.pass === pass);
1016
1017 if (!found) {
@@ -1022,34 +1032,44 @@
1032 return;
1033 }
1034
1035 + loadUsers();
1036 if (usersDb.some(x => x.username === user)) {
1037 alert('این نام کاربری قبلاً ثبت‌نام کرده است.');
1038 return;
1039 }
1040
1030 - const now = new Date();
1031 - now.setDate(now.getDate() + 15);
1032 - const expireStr = now.toISOString().split('T')[0];
1041 + const today = new Date().toISOString().split('T')[0];
1042 + const expireStr = addDaysToDate(today, 15);
1043
1044 const newUser = {
1045 + id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
1046 username: user,
1047 pass: pass,
1048 role: 'user',
1038 - license_type: 'trial',
1039 - expire_date: expireStr
1049 + createdAt: new Date().toISOString(),
1050 + subscriptionType: 'trial',
1051 + subscriptionStart: today,
1052 + subscriptionEnd: expireStr,
1053 + licenseStatus: 'trial',
1054 + subscription: {
1055 + type: 'trial',
1056 + startDate: today,
1057 + endDate: expireStr,
1058 + status: 'trial'
1059 + }
1060 };
1061
1062 usersDb.push(newUser);
1043 - localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb));
1063 + persistUsers();
1064 sessionStorage.setItem('easy_factor_session_v4_6', newUser.username);
1045 - alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال شد.');
1065 + alert('ثبت‌نام با موفقیت انجام شد. حساب شما به مدت ۱۵ روز آزمایشی فعال گردید.');
1066 loginSuccess(newUser);
1067 }
1068
1069 function loginSuccess(userObj) {
1070 currentUser = userObj;
1071 document.getElementById('auth-screen').style.display = 'none';
1052 - document.getElementById('logged-user-label').innerText = 'کاربر: ' + userObj.username + (userObj.role === 'admin' ? ' (مدیر)' : '');
1072 + document.getElementById('logged-user-label').innerText = 'کاربر: ' + userObj.username + (userObj.role === 'admin' ? ' (مدیر سیستم)' : '');
1073
1074 const adminMenu = document.getElementById('menu-admin-panel');
1075 if (userObj.role === 'admin') {
@@ -1058,74 +1078,504 @@
1078 adminMenu.style.display = 'none';
1079 }
1080
1061 - checkLicenseValidity(userObj);
1081 initDatastore();
1082 }
1083
1065 - function checkLicenseValidity(user) {
1084 + function handleLogout() {
1085 + sessionStorage.removeItem('easy_factor_session_v4_6');
1086 + window.location.reload();
1087 + }
1088 +
1089 + /* =========================================================================
1090 + منطق لایسنس و اولویت‌بندی نمایش (License System Logic)
1091 + اولویت ۱: اشتراک فعال (Active Subscription) -> هرگز Trial نمایش داده نمی‌شود.
1092 + اولویت ۲: نسخه آزمایشی (Trial Version) یا منقضی شده.
1093 + ========================================================================= */
1094 + function updateLicenseDisplay(user) {
1095 + if (!user) return;
1096 const badge = document.getElementById('user-license-status-badge');
1067 - if (user.role === 'admin') {
1068 - badge.innerText = 'نسخه دائمی (Lifetime)';
1069 - badge.className = 'badge badge-success';
1097 + const detailsBox = document.getElementById('dashboard-license-details');
1098 +
1099 + const sub = user.subscription || {
1100 + type: user.subscriptionType || 'trial',
1101 + startDate: user.subscriptionStart || user.createdAt,
1102 + endDate: user.subscriptionEnd,
1103 + status: user.licenseStatus || 'trial'
1104 + };
1105 +
1106 + const planLabels = {
1107 + monthly: 'طرح ۱ ماهه',
1108 + three_months: 'طرح ۳ ماهه',
1109 + annual: 'طرح ۱ ساله',
1110 + lifetime: 'دائمی (Lifetime)',
1111 + trial: 'آزمایشی (Trial)'
1112 + };
1113 +
1114 + const remDays = getRemainingDays(sub.endDate);
1115 + const isExpired = remDays <= 0 && sub.type !== 'lifetime';
1116 +
1117 + const hasActiveLicense = (sub.status === 'active') && (sub.type === 'lifetime' || !isExpired) && (sub.type !== 'trial');
1118 +
1119 + if (hasActiveLicense) {
1120 + const planName = planLabels[sub.type] || sub.type;
1121 + const startJalali = formatToJalali(sub.startDate);
1122 + const endJalali = sub.type === 'lifetime' ? 'نامحدود' : formatToJalali(sub.endDate);
1123 + const remText = sub.type === 'lifetime' ? 'نامحدود' : toPersianDigits(remDays) + ' روز';
1124 +
1125 + if (badge) {
1126 + badge.className = 'badge badge-success';
1127 + badge.innerText = `اشتراک فعال (${planName})`;
1128 + }
1129 + if (detailsBox) {
1130 + detailsBox.style.display = 'block';
1131 + detailsBox.innerHTML = `
1132 + <div style="font-size:12px; display:flex; flex-wrap:wrap; gap:16px; align-items:center; background:#ecfdf5; border:1px solid #6ee7b7; color:#065f46; padding:8px 14px; border-radius:8px; margin-bottom:14px;">
1133 + <div><strong>وضعیت:</strong> اشتراک فعال</div>
1134 + <div><strong>نوع طرح:</strong> ${planName}</div>
1135 + <div><strong>تاریخ شروع:</strong> ${startJalali}</div>
1136 + <div><strong>تاریخ پایان:</strong> ${endJalali}</div>
1137 + <div><strong>روزهای باقیمانده:</strong> ${remText}</div>
1138 + </div>
1139 + `;
1140 + }
1141 + } else {
1142 + if (isExpired || sub.status === 'cancelled') {
1143 + if (badge) {
1144 + badge.className = 'badge badge-danger';
1145 + badge.innerText = 'منقضی شده / لغو شده';
1146 + }
1147 + if (detailsBox) {
1148 + detailsBox.style.display = 'block';
1149 + detailsBox.innerHTML = `
1150 + <div style="font-size:12px; display:flex; flex-wrap:wrap; gap:16px; align-items:center; background:#fef2f2; border:1px solid #fca5a5; color:#991b1b; padding:8px 14px; border-radius:8px; margin-bottom:14px;">
1151 + <div><strong>وضعیت:</strong> اشتراک غیرفعال / منقضی شده</div>
1152 + <div><strong>تاریخ انقضا:</strong> ${formatToJalali(sub.endDate)}</div>
1153 + <div>لطفاً با مدیر سامانه جهت تمدید یا فعال‌سازی لایسنس تماس بگیرید.</div>
1154 + </div>
1155 + `;
1156 + }
1157 + } else {
1158 + const endJalali = formatToJalali(sub.endDate);
1159 + const remText = toPersianDigits(Math.max(0, remDays)) + ' روز';
1160 + if (badge) {
1161 + badge.className = 'badge badge-warning';
1162 + badge.innerText = `نسخه آزمایشی (${remText} باقیمانده)`;
1163 + }
1164 + if (detailsBox) {
1165 + detailsBox.style.display = 'block';
1166 + detailsBox.innerHTML = `
1167 + <div style="font-size:12px; display:flex; flex-wrap:wrap; gap:16px; align-items:center; background:#fffbeb; border:1px solid #fcd34d; color:#92400e; padding:8px 14px; border-radius:8px; margin-bottom:14px;">
1168 + <div><strong>وضعیت:</strong> نسخه آزمایشی (Trial)</div>
1169 + <div><strong>تاریخ پایان مهلت آزمایشی:</strong> ${endJalali}</div>
1170 + <div><strong>روزهای باقیمانده:</strong> ${remText}</div>
1171 + </div>
1172 + `;
1173 + }
1174 + }
1175 + }
1176 + }
1177 +
1178 + /* =========================================================================
1179 + مدیریت مرکزی کاربران توسط ادمین (Admin Central User & License Management)
1180 + ========================================================================= */
1181 + function adminCreateNewUser() {
1182 + const username = document.getElementById('admin-new-username').value.trim();
1183 + const pass = document.getElementById('admin-new-password').value.trim();
1184 + const plan = document.getElementById('admin-new-subtype').value;
1185 +
1186 + if (!username || !pass) {
1187 + alert('لطفاً نام کاربری و رمز عبور را وارد کنید.');
1188 + return;
1189 + }
1190 +
1191 + loadUsers();
1192 + if (usersDb.some(u => u.username === username)) {
1193 + alert('این نام کاربری از قبل وجود دارد.');
1194 return;
1195 }
1196
1197 const today = new Date().toISOString().split('T')[0];
1074 - if (user.expire_date && user.expire_date < today) {
1075 - badge.innerText = 'منقضی شده';
1076 - badge.className = 'badge badge-danger';
1077 - alert('مهلت استفاده آزمایشی ۱۵ روزه شما به پایان رسیده است.');
1078 - } else {
1079 - badge.innerText = `آزمایشی (تا ${user.expire_date})`;
1080 - badge.className = 'badge badge-warning';
1198 + let endDate = today;
1199 + let status = 'active';
1200 +
1201 + if (plan === 'trial') {
1202 + endDate = addDaysToDate(today, 15);
1203 + status = 'trial';
1204 + } else if (plan === 'monthly') {
1205 + endDate = addDaysToDate(today, 30);
1206 + } else if (plan === 'three_months') {
1207 + endDate = addDaysToDate(today, 90);
1208 + } else if (plan === 'annual') {
1209 + endDate = addDaysToDate(today, 365);
1210 + } else if (plan === 'lifetime') {
1211 + endDate = '2099-01-01';
1212 }
1213 +
1214 + const newUser = {
1215 + id: 'usr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
1216 + username,
1217 + pass,
1218 + role: 'user',
1219 + createdAt: new Date().toISOString(),
1220 + subscriptionType: plan,
1221 + subscriptionStart: today,
1222 + subscriptionEnd: endDate,
1223 + licenseStatus: status,
1224 + subscription: {
1225 + type: plan,
1226 + startDate: today,
1227 + endDate: endDate,
1228 + status: status
1229 + }
1230 + };
1231 +
1232 + usersDb.push(newUser);
1233 + persistUsers();
1234 + alert(`کاربر جدید "${username}" با موفقیت ایجاد شد و اطلاعات وی خالی می‌باشد.`);
1235 + document.getElementById('admin-new-username').value = '';
1236 + document.getElementById('admin-new-password').value = '';
1237 + renderAdminPanel();
1238 }
1239
1084 - function handleLogout() {
1085 - sessionStorage.removeItem('easy_factor_session_v4_6');
1086 - window.location.reload();
1240 + function refreshAdminPanel() {
1241 + loadUsers();
1242 + renderAdminPanel();
1243 }
1244
1245 function renderAdminPanel() {
1246 const tbody = document.getElementById('admin-users-table-body');
1091 - tbody.innerHTML = usersDb.map(u => `
1092 - <tr>
1093 - <td><strong>${u.username}</strong> ${u.role === 'admin' ? '👑' : ''}</td>
1094 - <td><span class="badge ${u.license_type === 'trial' ? 'badge-warning' : 'badge-success'}">${u.license_type}</span></td>
1095 - <td>${u.expire_date || 'نامحدود'}</td>
1096 - <td>
1097 - <button class="btn btn-secondary btn-inline" style="padding:2px 8px; font-size:11px;" onclick="upgradeUserLicense('${u.username}', 30)">+ ۱ ماه</button>
1098 - <button class="btn btn-secondary btn-inline" style="padding:2px 8px; font-size:11px;" onclick="upgradeUserLicense('${u.username}', 90)">+ ۳ ماه</button>
1099 - <button class="btn btn-secondary btn-inline" style="padding:2px 8px; font-size:11px;" onclick="upgradeUserLicense('${u.username}', 365)">+ ۱ سال</button>
1100 - <button class="btn btn-success btn-inline" style="padding:2px 8px; font-size:11px;" onclick="upgradeUserLicense('${u.username}', 'lifetime')">دائمی (Lifetime)</button>
1101 - </td>
1102 - </tr>
1103 - `).join('');
1247 + if (!tbody) return;
1248 +
1249 + loadUsers();
1250 + if (usersDb.length === 0) {
1251 + tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding:20px;">هیچ کاربری یافت نشد.</td></tr>';
1252 + return;
1253 + }
1254 +
1255 + const planLabels = {
1256 + monthly: 'طرح ۱ ماهه',
1257 + three_months: 'طرح ۳ ماهه',
1258 + annual: 'طرح ۱ ساله',
1259 + lifetime: 'دائمی (Lifetime)',
1260 + trial: 'آزمایشی (Trial)'
1261 + };
1262 +
1263 + tbody.innerHTML = usersDb.map(u => {
1264 + const sub = u.subscription || {
1265 + type: u.subscriptionType || 'trial',
1266 + startDate: u.subscriptionStart,
1267 + endDate: u.subscriptionEnd,
1268 + status: u.licenseStatus || 'trial'
1269 + };
1270 +
1271 + const remDays = getRemainingDays(sub.endDate);
1272 + const isExp = remDays <= 0 && sub.type !== 'lifetime';
1273 +
1274 + let statusBadge = '';
1275 + if (sub.status === 'cancelled') {
1276 + statusBadge = '<span class="badge badge-danger">لغو شده</span>';
1277 + } else if (sub.status === 'active') {
1278 + statusBadge = isExp ? '<span class="badge badge-danger">منقضی شده</span>' : '<span class="badge badge-success">فعال</span>';
1279 + } else {
1280 + statusBadge = isExp ? '<span class="badge badge-danger">آزمایشی منقضی</span>' : '<span class="badge badge-warning">آزمایشی</span>';
1281 + }
1282 +
1283 + const startJalali = formatToJalali(sub.startDate);
1284 + const endJalali = sub.type === 'lifetime' ? 'نامحدود' : formatToJalali(sub.endDate);
1285 + const remDaysText = sub.type === 'lifetime' ? 'نامحدود' : toPersianDigits(Math.max(0, remDays)) + ' روز';
1286 +
1287 + return `
1288 + <tr>
1289 + <td><strong>${u.username}</strong> ${u.role === 'admin' ? '<span class="badge badge-info">مدیر</span>' : ''}</td>
1290 + <td>${statusBadge}</td>
1291 + <td>${planLabels[sub.type] || sub.type}</td>
1292 + <td>${startJalali}</td>
1293 + <td>${endJalali}</td>
1294 + <td>${remDaysText}</td>
1295 + <td style="display:flex; gap:6px; flex-wrap:wrap;">
1296 + <button class="btn btn-success btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="adminActivateLicense('${u.username}')">فعال‌سازی</button>
1297 + <button class="btn btn-secondary btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="openLicenseEditModal('${u.username}')">تغییر مدت</button>
1298 + <button class="btn btn-secondary btn-inline" style="padding:3px 8px; font-size:11px; min-height:30px;" onclick="adminExtendSubscription('${u.username}', 30)">+۳۰ روز</button>
1299 + ${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>` : ''}
1300 + </td>
1301 + </tr>
1302 + `;
1303 + }).join('');
1304 }
1305
1106 - function upgradeUserLicense(username, durationDays) {
1306 + function adminActivateLicense(username) {
1307 + loadUsers();
1308 const u = usersDb.find(x => x.username === username);
1309 if (!u) return;
1310
1110 - if (durationDays === 'lifetime') {
1111 - u.license_type = 'lifetime';
1112 - u.expire_date = '2099-01-01';
1113 - } else {
1114 - u.license_type = 'pro';
1115 - const d = new Date();
1116 - d.setDate(d.getDate() + durationDays);
1117 - u.expire_date = d.toISOString().split('T')[0];
1311 + const today = new Date().toISOString().split('T')[0];
1312 + const endDate = addDaysToDate(today, 30);
1313 +
1314 + u.subscription = {
1315 + type: 'monthly',
1316 + startDate: today,
1317 + endDate: endDate,
1318 + status: 'active'
1319 + };
1320 + u.subscriptionType = 'monthly';
1321 + u.subscriptionStart = today;
1322 + u.subscriptionEnd = endDate;
1323 + u.licenseStatus = 'active';
1324 +
1325 + persistUsers();
1326 + if (currentUser && currentUser.username === username) {
1327 + currentUser = u;
1328 + updateLicenseDisplay(currentUser);
1329 }
1330 + alert(`لایسنس ۱ ماهه فعال برای کاربر ${username} ثبت شد.`);
1331 + renderAdminPanel();
1332 + }
1333
1120 - localStorage.setItem(AUTH_KEY, JSON.stringify(usersDb));
1121 - alert(`لایسنس کاربر ${username} با موفقیت ارتقا یافت.`);
1334 + function openLicenseEditModal(username) {
1335 + loadUsers();
1336 + const u = usersDb.find(x => x.username === username);
1337 + if (!u) return;
1338 + document.getElementById('modal-license-target-username').value = username;
1339 + document.getElementById('modal-license-user-title').innerText = `تغییر مدت و نوع لایسنس: ${username}`;
1340 + document.getElementById('modal-license-duration-select').value = u.subscription?.type || 'monthly';
1341 + document.getElementById('modal-admin-license-edit').classList.add('active');
1342 + }
1343 +
1344 + function closeLicenseEditModal() {
1345 + document.getElementById('modal-admin-license-edit').classList.remove('active');
1346 + }
1347 +
1348 + function applyLicenseDurationChange() {
1349 + const username = document.getElementById('modal-license-target-username').value;
1350 + const plan = document.getElementById('modal-license-duration-select').value;
1351 + loadUsers();
1352 + const u = usersDb.find(x => x.username === username);
1353 + if (!u) return;
1354 +
1355 + const today = new Date().toISOString().split('T')[0];
1356 + let endDate = today;
1357 +
1358 + if (plan === 'monthly') endDate = addDaysToDate(today, 30);
1359 + else if (plan === 'three_months') endDate = addDaysToDate(today, 90);
1360 + else if (plan === 'annual') endDate = addDaysToDate(today, 365);
1361 + else if (plan === 'lifetime') endDate = '2099-01-01';
1362 +
1363 + u.subscription = {
1364 + type: plan,
1365 + startDate: today,
1366 + endDate: endDate,
1367 + status: 'active'
1368 + };
1369 + u.subscriptionType = plan;
1370 + u.subscriptionStart = today;
1371 + u.subscriptionEnd = endDate;
1372 + u.licenseStatus = 'active';
1373 +
1374 + persistUsers();
1375 + if (currentUser && currentUser.username === username) {
1376 + currentUser = u;
1377 + updateLicenseDisplay(currentUser);
1378 + }
1379 + closeLicenseEditModal();
1380 + alert(`طرح لایسنس کاربر ${username} با موفقیت به "${plan}" تغییر یافت.`);
1381 + renderAdminPanel();
1382 + }
1383 +
1384 + function adminExtendSubscription(username, days) {
1385 + loadUsers();
1386 + const u = usersDb.find(x => x.username === username);
1387 + if (!u) return;
1388 +
1389 + let currentEnd = u.subscription?.endDate || new Date().toISOString().split('T')[0];
1390 + if (currentEnd.startsWith('2099')) {
1391 + alert('این حساب دائمی است و نیازی به تمدید ندارد.');
1392 + return;
1393 + }
1394 + const today = new Date().toISOString().split('T')[0];
1395 + const base = (currentEnd < today) ? today : currentEnd;
1396 + const newEnd = addDaysToDate(base, days);
1397 +
1398 + if (!u.subscription) u.subscription = {};
1399 + u.subscription.endDate = newEnd;
1400 + u.subscription.status = 'active';
1401 + if (u.subscription.type === 'trial') {
1402 + u.subscription.type = 'monthly';
1403 + }
1404 +
1405 + u.subscriptionType = u.subscription.type;
1406 + u.subscriptionEnd = newEnd;
1407 + u.licenseStatus = 'active';
1408 +
1409 + persistUsers();
1410 + if (currentUser && currentUser.username === username) {
1411 + currentUser = u;
1412 + updateLicenseDisplay(currentUser);
1413 + }
1414 + alert(`اشتراک کاربر ${username} به مدت ${days} روز تمدید گردید.`);
1415 renderAdminPanel();
1416 }
1417
1418 + function adminCancelSubscription(username) {
1419 + if (!confirm(`آیا از لغو اشتراک کاربر ${username} اطمینان دارید؟`)) return;
1420 + loadUsers();
1421 + const u = usersDb.find(x => x.username === username);
1422 + if (!u) return;
1423 +
1424 + if (!u.subscription) u.subscription = {};
1425 + u.subscription.status = 'cancelled';
1426 + u.licenseStatus = 'cancelled';
1427 +
1428 + persistUsers();
1429 + if (currentUser && currentUser.username === username) {
1430 + currentUser = u;
1431 + updateLicenseDisplay(currentUser);
1432 + }
1433 + alert(`اشتراک کاربر ${username} لغو گردید.`);
1434 + renderAdminPanel();
1435 + }
1436 +
1437 + /* =========================================================================
1438 + تفکیک کامل داده‌ها بر اساس مالکیت کاربر (Multi-User Data Isolation)
1439 + قانون: هر رکورد شامل ownerUserId بوده و کاربر فقط به داده‌های خود دسترسی دارد.
1440 + ========================================================================= */
1441 + let datastore = {
1442 + companies: [],
1443 + contacts: [],
1444 + products: [],
1445 + invoices: [],
1446 + cheques: [],
1447 + expenses: [],
1448 + settings: []
1449 + };
1450 +
1451 + function getMyProducts() {
1452 + if (!currentUser) return [];
1453 + return datastore.products.filter(p => p.ownerUserId === currentUser.id);
1454 + }
1455 + function getMyContacts() {
1456 + if (!currentUser) return [];
1457 + return datastore.contacts.filter(c => c.ownerUserId === currentUser.id);
1458 + }
1459 + function getMyCompanies() {
1460 + if (!currentUser) return [];
1461 + return datastore.companies.filter(c => c.ownerUserId === currentUser.id);
1462 + }
1463 + function getMyInvoices() {
1464 + if (!currentUser) return [];
1465 + return datastore.invoices.filter(i => i.ownerUserId === currentUser.id);
1466 + }
1467 + function getMyCheques() {
1468 + if (!currentUser) return [];
1469 + return datastore.cheques.filter(c => c.ownerUserId === currentUser.id);
1470 + }
1471 + function getMyExpenses() {
1472 + if (!currentUser) return [];
1473 + return datastore.expenses.filter(e => e.ownerUserId === currentUser.id);
1474 + }
1475 + function getMySettings() {
1476 + if (!currentUser) return { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '' };
1477 + if (!Array.isArray(datastore.settings)) datastore.settings = [];
1478 + let s = datastore.settings.find(item => item.ownerUserId === currentUser.id);
1479 + if (!s) {
1480 + s = { ownerUserId: currentUser.id, invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10, default_company_id: '' };
1481 + datastore.settings.push(s);
1482 + }
1483 + return s;
1484 + }
1485 +
1486 + function saveDatastore() {
1487 + try {
1488 + localStorage.setItem(STORAGE_KEY, JSON.stringify(datastore));
1489 + return true;
1490 + } catch (err) {
1491 + console.error('Error saving datastore:', err);
1492 + return false;
1493 + }
1494 + }
1495 +
1496 + function persistDatastore() {
1497 + return saveDatastore();
1498 + }
1499 +
1500 + function loadDatastore() {
1501 + const persisted = localStorage.getItem(STORAGE_KEY);
1502 + if (persisted) {
1503 + try {
1504 + datastore = JSON.parse(persisted);
1505 + } catch (e) {
1506 + console.error('Error parsing datastore:', e);
1507 + }
1508 + }
1509 +
1510 + if (!Array.isArray(datastore.companies)) datastore.companies = [];
1511 + if (!Array.isArray(datastore.contacts)) datastore.contacts = [];
1512 + if (!Array.isArray(datastore.products)) datastore.products = [];
1513 + if (!Array.isArray(datastore.invoices)) datastore.invoices = [];
1514 + if (!Array.isArray(datastore.cheques)) datastore.cheques = [];
1515 + if (!Array.isArray(datastore.expenses)) datastore.expenses = [];
1516 + if (!Array.isArray(datastore.settings)) datastore.settings = [];
1517 +
1518 + // اگر برای اولین بار برنامه باز شده است، داده‌های اولیه صرفاً متعلق به کاربر admin است
1519 + if (datastore.companies.length === 0 && datastore.products.length === 0) {
1520 + datastore.companies.push({
1521 + id: 'COMP-1',
1522 + ownerUserId: 'user_admin',
1523 + entity_type: 'legal',
1524 + name: 'آرا سپهر راستین',
1525 + phone: '09124376991',
1526 + national_id: '14008507476',
1527 + economic_code: '14008507476',
1528 + reg_number: '544926',
1529 + postal_code: '1445956311',
1530 + address: 'استان تهران - شهرستان تهران - شهر آرا کوچه مجاهد پلاک 61',
1531 + footer: 'از خرید شما سپاسگزاریم.'
1532 + });
1533 + datastore.contacts.push({
1534 + id: 'C-1',
1535 + ownerUserId: 'user_admin',
1536 + entity_type: 'legal',
1537 + name: 'شرکت دانشگاه صنعتی شریف',
1538 + mobile: '02166165000',
1539 + national_id: '14002830256',
1540 + economic_code: '14002830256',
1541 + reg_number: '',
1542 + postal_code: '1458889694',
1543 + address: 'طرشت محله تیموری پلاک 435',
1544 + balance: 7978300000,
1545 + role: 'customer'
1546 + });
1547 + datastore.products.push(
1548 + { id: 'P-1', ownerUserId: 'user_admin', code: '1', name: 'سوئیچ شبکه 24 پورت فیبر نوری', spec: 'با 2 پاور 350', unit: 'عدد', buy_price: 1800000000, sale_price: 2180000000, stock: 10, type: 'good' },
1549 + { id: 'P-2', ownerUserId: 'user_admin', code: '2', name: 'هارد 2.5 اینچ سرور', spec: '', unit: 'عدد', buy_price: 30000000, sale_price: 37000000, stock: 10, type: 'good' }
1550 + );
1551 + datastore.settings.push({
1552 + ownerUserId: 'user_admin',
1553 + invoice_kind: 'non_formal',
1554 + vat_mode: 'none',
1555 + vat_rate: 10,
1556 + default_company_id: 'COMP-1'
1557 + });
1558 + saveDatastore();
1559 + } else {
1560 + // مهاجرت امن: رکوردهای قدیمی بدون شناسه مالک به ادمین نسبت داده می‌شوند
1561 + let migrated = false;
1562 + ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(coll => {
1563 + datastore[coll].forEach(item => {
1564 + if (!item.ownerUserId) {
1565 + item.ownerUserId = 'user_admin';
1566 + migrated = true;
1567 + }
1568 + });
1569 + });
1570 + if (migrated) saveDatastore();
1571 + }
1572 +
1573 + return datastore;
1574 + }
1575 +
1576 function initDatastore() {
1126 - loadDatastore().then(() => {
1127 - refreshAllSurfaces();
1128 - });
1577 + loadDatastore();
1578 + refreshAllSurfaces();
1579 }
1580
1581 function getJalaliDate() {
@@ -1150,6 +1600,10 @@
1600 dock.classList.toggle('active', dockViews[idx] === viewId);
1601 });
1602
1603 + if (viewId === 'view-admin') {
1604 + renderAdminPanel();
1605 + }
1606 +
1607 window.scrollTo({ top: 0, behavior: 'smooth' });
1608 }
1609
@@ -1164,6 +1618,7 @@
1618 const invDate = document.getElementById('invoice-date-input');
1619 if (invDate && !invDate.value) invDate.value = getJalaliNumeric();
1620
1621 + updateLicenseDisplay(currentUser);
1622 renderCompanies();
1623 renderContacts();
1624 renderProducts();
@@ -1173,10 +1628,13 @@
1628 renderExpenses();
1629 applyDefaultSettingsToForm();
1630 handleContactEntityChange();
1631 + if (currentUser && currentUser.role === 'admin') {
1632 + renderAdminPanel();
1633 + }
1634 }
1635
1636 /* =========================================================================
1179 - قواعد پیشوند و قالب‌بندی نام طرف حساب (شخص حقیقی / حقوقی)
1637 + قواعد پیشوند و نام طرف‌حساب
1638 ========================================================================= */
1639 function formatEntityName(rawName, entityType, customPrefix = '') {
1640 let trimmed = (rawName || '').trim();
@@ -1254,7 +1712,7 @@
1712 }
1713
1714 function applyDefaultSettingsToForm() {
1257 - const def = datastore.default_settings || { invoice_kind: 'non_formal', vat_mode: 'none', vat_rate: 10 };
1715 + const def = getMySettings();
1716 const defKind = document.getElementById('def-invoice-kind');
1717 const defVat = document.getElementById('def-vat-mode');
1718 const defRate = document.getElementById('def-vat-rate');
@@ -1265,22 +1723,28 @@
1723 }
1724
1725 function commitSaveDefaultSettings() {
1268 - if (!datastore.default_settings) datastore.default_settings = {};
1269 - datastore.default_settings.invoice_kind = document.getElementById('def-invoice-kind').value;
1270 - datastore.default_settings.vat_mode = document.getElementById('def-vat-mode').value;
1271 - datastore.default_settings.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1272 - if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
1273 - datastore.default_settings.default_company_id = datastore.companies[0].id;
1274 - }
1726 + const s = getMySettings();
1727 + s.invoice_kind = document.getElementById('def-invoice-kind').value;
1728 + s.vat_mode = document.getElementById('def-vat-mode').value;
1729 + s.vat_rate = parseFloat(document.getElementById('def-vat-rate').value) || 0;
1730 saveDatastore();
1731 alert('پیش‌فرض‌ها ذخیره شد.');
1732 }
1733
1734 + /* =========================================================================
1735 + داشبورد تحلیلی با فیلتر دقیق کاربر فعلی (currentUser.id)
1736 + ========================================================================= */
1737 function renderDashboard() {
1738 let salesSum = 0;
1739 let debtorsSum = 0;
1282 - const activeCompId = datastore.default_settings?.default_company_id || document.getElementById('invoice-company-id')?.value || (datastore.companies[0]?.id);
1283 - const filteredInvoices = datastore.invoices.filter(inv => inv.companyId === activeCompId);
1740 + const myInvoices = getMyInvoices();
1741 + const myCheques = getMyCheques();
1742 +
1743 + const myCompanies = getMyCompanies();
1744 + const mySettings = getMySettings();
1745 + const activeCompId = mySettings.default_company_id || document.getElementById('invoice-company-id')?.value || (myCompanies[0]?.id);
1746 +
1747 + const filteredInvoices = activeCompId ? myInvoices.filter(inv => inv.companyId === activeCompId) : myInvoices;
1748
1749 filteredInvoices.forEach(inv => {
1750 salesSum += inv.grandTotal;
@@ -1295,7 +1759,7 @@
1759 if (salesEl) salesEl.innerText = salesSum.toLocaleString('fa-IR') + ' ریال';
1760 if (settledEl) settledEl.innerText = (salesSum - debtorsSum).toLocaleString('fa-IR') + ' ریال';
1761 if (debtorsEl) debtorsEl.innerText = debtorsSum.toLocaleString('fa-IR') + ' ریال';
1298 - if (chequesEl) chequesEl.innerText = datastore.cheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1762 + if (chequesEl) chequesEl.innerText = myCheques.filter(c => c.status === 'registered').length.toLocaleString('fa-IR') + ' فقره';
1763
1764 const recentTbody = document.getElementById('dashboard-recent-table');
1765 if (recentTbody) {
@@ -1332,8 +1796,7 @@
1796 }
1797
1798 /* =========================================================================
1335 - مدیریت اقلام فاکتور با چینش دقیق و تطابق کامل سرستون‌ها و خانه‌ها در RTL
1336 - ترتیب: # | شرح کالا | خدمات | واحد | مقدار | قیمت واحد | قیمت کل | حذف
1799 + جدول اقلام فاکتور با چینش استاندارد و شماره‌گذاری خودکار در RTL
1800 ========================================================================= */
1801 function updateInvoiceItemRowNumbers() {
1802 const rows = document.querySelectorAll('#invoice-items-table-body tr');
@@ -1351,7 +1814,8 @@
1814 const tr = document.createElement('tr');
1815 tr.id = rowKey;
1816
1354 - const productOptions = datastore.products.map(p =>
1817 + const myProducts = getMyProducts();
1818 + const productOptions = myProducts.map(p =>
1819 `<option value="${p.id}" data-price="${p.sale_price}" data-unit="${p.unit || 'عدد'}" ${p.id === selectedProdId ? 'selected' : ''}>${p.name} ${p.spec ? '(' + p.spec + ')' : ''}</option>`
1820 ).join('');
1821
@@ -1432,15 +1896,16 @@
1896 }
1897
1898 function commitSaveInvoice() {
1899 + if (!currentUser) return;
1900 + const myCompanies = getMyCompanies();
1901 + const mySettings = getMySettings();
1902 +
1903 const companySelect = document.getElementById('invoice-company-id');
1436 - const selectedCompanyId = companySelect ? companySelect.value : (datastore.default_settings?.default_company_id);
1904 + const selectedCompanyId = companySelect ? companySelect.value : mySettings.default_company_id;
1905
1438 - // استخراج فروشنده فعال دقیقاً بر اساس شناسه انتخاب‌شده و عدم اتکا به ایندکس 0
1439 - const sellerCompany = datastore.companies.find(
1440 - company => company.id === selectedCompanyId
1441 - ) || datastore.companies.find(
1442 - company => company.id === datastore.default_settings?.default_company_id
1443 - ) || datastore.companies[0];
1906 + const sellerCompany = myCompanies.find(c => c.id === selectedCompanyId) ||
1907 + myCompanies.find(c => c.id === mySettings.default_company_id) ||
1908 + myCompanies[0];
1909
1910 if (!sellerCompany) {
1911 alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');
@@ -1453,7 +1918,7 @@
1918 const contactSelect = document.getElementById('invoice-contact-id');
1919 const contactId = contactSelect ? contactSelect.value : '';
1920 const contactName = contactSelect?.options[contactSelect.selectedIndex]?.text || 'مشتری آزاد';
1456 - const number = document.getElementById('invoice-number')?.value.trim() || ('PINV-' + (datastore.invoices.length + 31));
1921 + const number = document.getElementById('invoice-number')?.value.trim() || ('PINV-' + (getMyInvoices().length + 31));
1922 const date = document.getElementById('invoice-date-input')?.value.trim() || getJalaliNumeric();
1923 const kind = document.getElementById('invoice-kind')?.value || 'non_formal';
1924 const description = document.getElementById('invoice-desc-input')?.value.trim() || '';
@@ -1482,10 +1947,11 @@
1947 const kindLabels = { formal: 'رسمی', non_formal: 'غیررسمی', pre_invoice: 'پیش‌فاکتور' };
1948
1949 if (editId) {
1485 - const existingIndex = datastore.invoices.findIndex(i => i.id === editId);
1950 + const existingIndex = datastore.invoices.findIndex(i => i.id === editId && i.ownerUserId === currentUser.id);
1951 if (existingIndex !== -1) {
1952 datastore.invoices[existingIndex] = {
1953 ...datastore.invoices[existingIndex],
1954 + ownerUserId: currentUser.id,
1955 number, date, companyId, companyName, kind,
1956 kindLabel: kindLabels[kind],
1957 contactId, contactName,
@@ -1505,6 +1971,7 @@
1971 } else {
1972 const record = {
1973 id: 'INV_' + Date.now(),
1974 + ownerUserId: currentUser.id,
1975 number, date, companyId, companyName, kind,
1976 kindLabel: kindLabels[kind],
1977 contactId, contactName,
@@ -1529,7 +1996,7 @@
1996 }
1997
1998 function editInvoice(invId) {
1532 - const inv = datastore.invoices.find(i => i.id === invId);
1999 + const inv = getMyInvoices().find(i => i.id === invId);
2000 if (!inv) return;
2001
2002 switchView('view-invoices');
@@ -1581,7 +2048,7 @@
2048 const filterSelect = document.getElementById('filter-invoice-company');
2049 const selectedFilter = filterSelect?.value || document.getElementById('invoice-company-id')?.value || 'ALL';
2050
1584 - let list = datastore.invoices;
2051 + let list = getMyInvoices();
2052 if (selectedFilter !== 'ALL') {
2053 list = list.filter(i => i.companyId === selectedFilter);
2054 }
@@ -1608,20 +2075,20 @@
2075 }
2076
2077 /* =========================================================================
1611 - سیستم چاپ حرفه‌ای A4 مطابق فایل‌های مرجع (رسمی.pdf و غیر رسمی.pdf)
1612 - با کنترل دقیق حداکثر ۱۰ ردیف کالا در هر صفحه و جلوگیری از سرریز امضا
2078 + سیستم چاپ پیشرفته فاکتورهای رسمی و غیررسمی با کنترل حداکثر ۱۰ ردیف در صفحه
2079 ========================================================================= */
2080 function renderAndPrintDirect(invId) {
1615 - const inv = datastore.invoices.find(i => i.id === invId);
2081 + const inv = getMyInvoices().find(i => i.id === invId);
2082 if (!inv) return;
2083
1618 - const seller = datastore.companies.find(c => c.id === inv.companyId) ||
1619 - datastore.companies.find(c => c.id === datastore.default_settings?.default_company_id) ||
1620 - datastore.companies[0] || {};
1621 - const contact = datastore.contacts.find(c => c.id === inv.contactId) || {};
2084 + const myCompanies = getMyCompanies();
2085 + const myContacts = getMyContacts();
2086 +
2087 + const seller = myCompanies.find(c => c.id === inv.companyId) || myCompanies[0] || {};
2088 + const contact = myContacts.find(c => c.id === inv.contactId) || {};
2089
2090 const isFormal = (inv.kind === 'formal');
1624 - const itemsPerPage = 10; // کنترل دقیق حداکثر ۱۰ ردیف در هر صفحه A4
2091 + const itemsPerPage = 10;
2092 const totalPages = Math.ceil(inv.items.length / itemsPerPage) || 1;
2093 let containerHtml = '';
2094
@@ -1640,7 +2107,6 @@
2107 let rowsHtml = '';
2108
2109 if (isFormal) {
1643 - // تولید سطرهای جدول قالب رسمی (۹ ستون مطابق استاندارد دارایی و رسمی.pdf)
2110 rowsHtml = pageItems.map((it, idx) => {
2111 const absoluteIndex = (p * itemsPerPage) + idx + 1;
2112 const lineSubtotal = it.lineTotal;
@@ -1669,7 +2135,6 @@
2135 `;
2136 }).join('');
2137 } else {
1672 - // تولید سطرهای جدول قالب غیررسمی / پیش‌فاکتور (۶ ستون استاندارد و شکیل مطابق غیر رسمی.pdf)
2138 rowsHtml = pageItems.map((it, idx) => {
2139 const absoluteIndex = (p * itemsPerPage) + idx + 1;
2140 pageSubtotal += it.lineTotal;
@@ -1692,9 +2157,7 @@
2157 runningDiscount += pageDiscount;
2158 runningVat += pageVat;
2159
1695 - // ساخت ساختار صفحه کامل A4
2160 if (isFormal) {
1697 - // ======================== قالب رسمی استاندارد A4 ========================
2161 containerHtml += `
2162 <div class="invoice-a4-page" style="background:#fff; padding:8mm 6mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
2163 <!-- سربرگ رسمی -->
@@ -1834,7 +2297,6 @@
2297 </div>
2298 `;
2299 } else {
1837 - // ======================== قالب غیررسمی / پیش‌فاکتور A4 ========================
2300 containerHtml += `
2301 <div class="invoice-a4-page" style="background:#fff; padding:8mm 6mm; color:#000; font-family:'Vazirmatn FD', sans-serif;">
2302 <!-- سربرگ شکیل پیش‌فاکتور / غیررسمی -->
@@ -1949,19 +2411,26 @@
2411 printContainer.style.display = 'none';
2412 }
2413
1952 - // ۳. کالاها
2414 + /* =========================================================================
2415 + مدیریت کالاها با تفکیک دقیق کاربر (ownerUserId)
2416 + ========================================================================= */
2417 function commitSaveProduct() {
1954 - const code = document.getElementById('prod-code-input').value || (datastore.products.length + 1).toString();
2418 + if (!currentUser) return;
2419 + const myProducts = getMyProducts();
2420 + const code = document.getElementById('prod-code-input').value || (myProducts.length + 1).toString();
2421 const name = document.getElementById('prod-name-input').value;
2422 const spec = document.getElementById('prod-spec-input').value || '';
1957 - const type = document.getElementById('prod-type-input')?.value || 'good';
2423 const unit = document.getElementById('prod-unit-input').value || 'عدد';
2424 const buy_price = parseFloat(document.getElementById('prod-buy-input').value) || 0;
2425 const sale_price = parseFloat(document.getElementById('prod-sale-input').value) || 0;
2426
2427 if (!name) { alert('عنوان کالا الزامی است.'); return; }
2428
1964 - datastore.products.push({ id: 'P_' + Date.now(), code, name, spec, type, unit, buy_price, sale_price, stock: 0 });
2429 + datastore.products.push({
2430 + id: 'P_' + Date.now(),
2431 + ownerUserId: currentUser.id,
2432 + code, name, spec, type: 'good', unit, buy_price, sale_price, stock: 0
2433 + });
2434 saveDatastore();
2435 alert('کالا ثبت شد.');
2436 document.getElementById('prod-name-input').value = '';
@@ -1971,7 +2440,12 @@
2440
2441 function renderProducts() {
2442 const tbody = document.getElementById('products-catalog-table-body');
1974 - tbody.innerHTML = datastore.products.map(p => `
2443 + const myProducts = getMyProducts();
2444 + if (myProducts.length === 0) {
2445 + tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ کالایی ثبت نشده است.</td></tr>';
2446 + return;
2447 + }
2448 + tbody.innerHTML = myProducts.map(p => `
2449 <tr>
2450 <td>${p.code}</td>
2451 <td><strong>${p.name}</strong></td>
@@ -1984,8 +2458,9 @@
2458 }
2459
2460 function deleteProduct(id) {
2461 + if (!currentUser) return;
2462 if (confirm('حذف شود؟')) {
1988 - datastore.products = datastore.products.filter(p => p.id !== id);
2463 + datastore.products = datastore.products.filter(p => !(p.id === id && p.ownerUserId === currentUser.id));
2464 saveDatastore();
2465 refreshAllSurfaces();
2466 }
@@ -1994,7 +2469,9 @@
2469 function openQuickProductModal() { document.getElementById('modal-quick-product').classList.add('active'); }
2470 function closeQuickProductModal() { document.getElementById('modal-quick-product').classList.remove('active'); }
2471 function saveQuickProduct() {
1997 - const code = document.getElementById('quick-p-code').value || (datastore.products.length + 1).toString();
2472 + if (!currentUser) return;
2473 + const myProducts = getMyProducts();
2474 + const code = document.getElementById('quick-p-code').value || (myProducts.length + 1).toString();
2475 const name = document.getElementById('quick-p-name').value;
2476 const spec = document.getElementById('quick-p-spec').value || '';
2477 const unit = document.getElementById('quick-p-unit').value || 'عدد';
@@ -2003,7 +2480,11 @@
2480 if (!name) { alert('عنوان کالا الزامی است.'); return; }
2481
2482 const newId = 'P_' + Date.now();
2006 - datastore.products.push({ id: newId, code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good' });
2483 + datastore.products.push({
2484 + id: newId,
2485 + ownerUserId: currentUser.id,
2486 + code, name, spec, unit, buy_price: 0, sale_price: price, stock: 0, type: 'good'
2487 + });
2488 saveDatastore();
2489 closeQuickProductModal();
2490 refreshAllSurfaces();
@@ -2023,6 +2504,7 @@
2504 }
2505
2506 function importProductsFromExcel(event) {
2507 + if (!currentUser) return;
2508 const file = event.target.files[0];
2509 if (!file) return;
2510 const reader = new FileReader();
@@ -2031,12 +2513,14 @@
2513 const data = new Uint8Array(e.target.result);
2514 const workbook = XLSX.read(data, { type: 'array' });
2515 const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
2516 + const myProducts = getMyProducts();
2517 rows.forEach((r, idx) => {
2518 const name = r["نام کالا"] || r["عنوان"];
2519 if (name) {
2520 datastore.products.push({
2521 id: 'P_' + Date.now() + '_' + idx,
2039 - code: (r["کد کالا"] || (datastore.products.length + 1)).toString(),
2522 + ownerUserId: currentUser.id,
2523 + code: (r["کد کالا"] || (myProducts.length + idx + 1)).toString(),
2524 name: name.toString(),
2525 spec: (r["مشخصه و نوع"] || '').toString(),
2526 unit: (r["واحد"] || 'عدد').toString(),
@@ -2054,8 +2538,11 @@
2538 reader.readAsArrayBuffer(file);
2539 }
2540
2057 - // ۴. اشخاص
2541 + /* =========================================================================
2542 + مدیریت اشخاص و طرف‌حساب‌ها با تفکیک دقیق کاربر (ownerUserId)
2543 + ========================================================================= */
2544 function commitSaveContact() {
2545 + if (!currentUser) return;
2546 const entity_type = document.getElementById('contact-entity-type').value;
2547 const custom_prefix = entity_type === 'natural' ? document.getElementById('contact-prefix-select')?.value : '';
2548 const raw_name = document.getElementById('contact-name-input').value;
@@ -2070,7 +2557,11 @@
2557 if (!raw_name.trim()) { alert('نام طرف حساب الزامی است.'); return; }
2558
2559 const formatted_name = formatEntityName(raw_name, entity_type, custom_prefix);
2073 - datastore.contacts.push({ id: 'C_' + Date.now(), entity_type, name: formatted_name, role, mobile, national_id, economic_code, reg_number, postal_code, address, balance: 0 });
2560 + datastore.contacts.push({
2561 + id: 'C_' + Date.now(),
2562 + ownerUserId: currentUser.id,
2563 + entity_type, name: formatted_name, role, mobile, national_id, economic_code, reg_number, postal_code, address, balance: 0
2564 + });
2565 saveDatastore();
2566 alert('طرف حساب ثبت شد.');
2567 document.getElementById('contact-name-input').value = '';
@@ -2081,28 +2572,34 @@
2572 const tbody = document.getElementById('contacts-ledger-table-body');
2573 const invSelect = document.getElementById('invoice-contact-id');
2574 const chqSelect = document.getElementById('chq-contact-select');
2575 + const myContacts = getMyContacts();
2576
2085 - tbody.innerHTML = datastore.contacts.map(c => `
2086 - <tr>
2087 - <td><strong>${c.name}</strong></td>
2088 - <td><span class="badge ${c.entity_type === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td>
2089 - <td>${c.national_id || '—'}</td>
2090 - <td>${c.economic_code || '—'}</td>
2091 - <td>${c.postal_code || '—'}</td>
2092 - <td>${c.mobile || '—'}</td>
2093 - <td>${Math.abs(c.balance || 0).toLocaleString('fa-IR')}</td>
2094 - <td><button class="btn btn-danger btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="deleteContact('${c.id}')">حذف</button></td>
2095 - </tr>
2096 - `).join('');
2577 + if (myContacts.length === 0) {
2578 + tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ طرف حسابی ثبت نشده است.</td></tr>';
2579 + } else {
2580 + tbody.innerHTML = myContacts.map(c => `
2581 + <tr>
2582 + <td><strong>${c.name}</strong></td>
2583 + <td><span class="badge ${c.entity_type === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td>
2584 + <td>${c.national_id || '—'}</td>
2585 + <td>${c.economic_code || '—'}</td>
2586 + <td>${c.postal_code || '—'}</td>
2587 + <td>${c.mobile || '—'}</td>
2588 + <td>${Math.abs(c.balance || 0).toLocaleString('fa-IR')}</td>
2589 + <td><button class="btn btn-danger btn-inline" style="padding:4px 8px; font-size:12px; min-height:30px;" onclick="deleteContact('${c.id}')">حذف</button></td>
2590 + </tr>
2591 + `).join('');
2592 + }
2593
2098 - const options = datastore.contacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
2594 + const options = myContacts.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
2595 if (invSelect) invSelect.innerHTML = options;
2596 if (chqSelect) chqSelect.innerHTML = options;
2597 }
2598
2599 function deleteContact(id) {
2600 + if (!currentUser) return;
2601 if (confirm('حذف شود؟')) {
2105 - datastore.contacts = datastore.contacts.filter(c => c.id !== id);
2602 + datastore.contacts = datastore.contacts.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
2603 saveDatastore();
2604 refreshAllSurfaces();
2605 }
@@ -2112,6 +2609,7 @@
2609 function closeQuickContactModal() { document.getElementById('modal-quick-contact').classList.remove('active'); }
2610
2611 function saveQuickContact() {
2612 + if (!currentUser) return;
2613 const entity_type = document.getElementById('quick-c-entity').value;
2614 const prefix = entity_type === 'natural' ? document.getElementById('quick-c-prefix')?.value : '';
2615 const raw_name = document.getElementById('quick-c-name').value;
@@ -2119,7 +2617,9 @@
2617
2618 const newId = 'C_' + Date.now();
2619 datastore.contacts.push({
2122 - id: newId, entity_type,
2620 + id: newId,
2621 + ownerUserId: currentUser.id,
2622 + entity_type,
2623 name: formatEntityName(raw_name, entity_type, prefix),
2624 role: 'customer',
2625 mobile: document.getElementById('quick-c-mobile').value,
@@ -2148,6 +2648,7 @@
2648 }
2649
2650 function importContactsFromExcel(event) {
2651 + if (!currentUser) return;
2652 const file = event.target.files[0];
2653 if (!file) return;
2654 const reader = new FileReader();
@@ -2162,6 +2663,7 @@
2663 const entity_type = (r["نوع (حقیقی/حقوقی)"] || '').includes('حقوقی') ? 'legal' : 'natural';
2664 datastore.contacts.push({
2665 id: 'C_' + Date.now() + '_' + idx,
2666 + ownerUserId: currentUser.id,
2667 entity_type,
2668 name: formatEntityName(raw_name.toString(), entity_type, 'آقا/خانم'),
2669 role: 'customer',
@@ -2183,8 +2685,11 @@
2685 reader.readAsArrayBuffer(file);
2686 }
2687
2186 - // ۵. چک و ۶. هزینه
2688 + /* =========================================================================
2689 + مدیریت چک‌ها و هزینه‌ها با تفکیک دقیق کاربر (ownerUserId)
2690 + ========================================================================= */
2691 function commitSaveCheque() {
2692 + if (!currentUser) return;
2693 const direction = document.getElementById('chq-direction-input').value;
2694 const contactSelect = document.getElementById('chq-contact-select');
2695 const contactName = contactSelect.options[contactSelect.selectedIndex]?.text || '';
@@ -2192,38 +2697,58 @@
2697 const bank = document.getElementById('chq-bank-input').value;
2698 const amount = parseFloat(document.getElementById('chq-amount-input').value) || 0;
2699 if (!sayad_id || amount <= 0) { alert('اطلاعات چک نامعتبر است.'); return; }
2195 - datastore.cheques.push({ id: 'CHQ_' + Date.now(), direction, contactName, sayad_id, bank, amount, due_date: document.getElementById('chq-due-input').value, status: document.getElementById('chq-status-input').value });
2700 + datastore.cheques.push({
2701 + id: 'CHQ_' + Date.now(),
2702 + ownerUserId: currentUser.id,
2703 + direction, contactName, sayad_id, bank, amount,
2704 + due_date: document.getElementById('chq-due-input').value,
2705 + status: document.getElementById('chq-status-input').value
2706 + });
2707 saveDatastore();
2708 alert('چک ثبت شد.');
2709 refreshAllSurfaces();
2710 }
2711 function renderCheques() {
2712 const tbody = document.getElementById('cheques-ledger-table-body');
2202 - tbody.innerHTML = datastore.cheques.length === 0 ? '<tr><td colspan="6" style="text-align:center;">چکی ثبت نشده است.</td></tr>' :
2203 - datastore.cheques.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('');
2713 + const myCheques = getMyCheques();
2714 + tbody.innerHTML = myCheques.length === 0 ? '<tr><td colspan="6" style="text-align:center; padding:20px; color:var(--text-muted);">چکی ثبت نشده است.</td></tr>' :
2715 + 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('');
2716 }
2717 function commitSaveExpense() {
2718 + if (!currentUser) return;
2719 const amount = parseFloat(document.getElementById('trx-amount-input').value) || 0;
2720 if (amount <= 0) { alert('مبلغ معتبر نیست.'); return; }
2208 - datastore.expenses.push({ id: 'TRX_' + Date.now(), kind: document.getElementById('trx-kind-input').value, category: document.getElementById('trx-category-input').value, amount, desc: document.getElementById('trx-desc-input').value });
2721 + datastore.expenses.push({
2722 + id: 'TRX_' + Date.now(),
2723 + ownerUserId: currentUser.id,
2724 + kind: document.getElementById('trx-kind-input').value,
2725 + category: document.getElementById('trx-category-input').value,
2726 + amount,
2727 + desc: document.getElementById('trx-desc-input').value
2728 + });
2729 saveDatastore();
2730 alert('سند ثبت شد.');
2731 refreshAllSurfaces();
2732 }
2733 function renderExpenses() {
2734 const tbody = document.getElementById('expenses-ledger-table-body');
2215 - tbody.innerHTML = datastore.expenses.length === 0 ? '<tr><td colspan="4" style="text-align:center;">موردی ثبت نشده است.</td></tr>' :
2216 - datastore.expenses.map(e => `<tr><td>${e.kind}</td><td>${e.category}</td><td>${e.desc}</td><td>${e.amount.toLocaleString('fa-IR')}</td></tr>`).join('');
2735 + const myExpenses = getMyExpenses();
2736 + tbody.innerHTML = myExpenses.length === 0 ? '<tr><td colspan="4" style="text-align:center; padding:20px; color:var(--text-muted);">موردی ثبت نشده است.</td></tr>' :
2737 + 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('');
2738 }
2739
2219 - // ۷. شرکت‌ها (اصلاح کامل ثبت شرکت و فعال‌سازی فوری)
2740 + /* =========================================================================
2741 + مدیریت شرکت‌ها و فروشگاه‌ها با تفکیک دقیق کاربر (ownerUserId)
2742 + ========================================================================= */
2743 function commitSaveCompany() {
2744 + if (!currentUser) return;
2745 const entity_type = document.getElementById('company-entity-type').value;
2746 const raw_name = document.getElementById('company-name-input').value;
2747 if (!raw_name.trim()) { alert('نام شرکت الزامی است.'); return; }
2748
2749 const newComp = {
2750 id: 'COMP_' + Date.now(),
2751 + ownerUserId: currentUser.id,
2752 entity_type,
2753 name: formatEntityName(raw_name, entity_type),
2754 phone: document.getElementById('company-phone-input').value || '',
@@ -2237,10 +2762,8 @@
2762
2763 datastore.companies.push(newComp);
2764
2240 - if (!datastore.default_settings) {
2241 - datastore.default_settings = {};
2242 - }
2243 - datastore.default_settings.default_company_id = newComp.id;
2765 + const s = getMySettings();
2766 + s.default_company_id = newComp.id;
2767
2768 saveDatastore();
2769 alert('شرکت با موفقیت ثبت و ذخیره شد و به عنوان فروشنده پیش‌فرض تنظیم گردید.');
@@ -2261,22 +2784,28 @@
2784 const tbody = document.getElementById('companies-table-body');
2785 const invoiceCompSelect = document.getElementById('invoice-company-id');
2786 const filterCompSelect = document.getElementById('filter-invoice-company');
2264 - const defCompId = datastore.default_settings?.default_company_id || (datastore.companies[0]?.id);
2787 + const myCompanies = getMyCompanies();
2788 + const mySettings = getMySettings();
2789 + const defCompId = mySettings.default_company_id || (myCompanies[0]?.id);
2790
2791 if (tbody) {
2267 - tbody.innerHTML = datastore.companies.map(c => `
2268 - <tr>
2269 - <td><strong>${c.name}</strong></td>
2270 - <td>${c.national_id || '—'}</td>
2271 - <td>${c.economic_code || '—'}</td>
2272 - <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>
2273 - <td>${datastore.companies.length > 1 ? `<button class="btn btn-danger btn-inline" style="padding:2px 8px; font-size:11px;" onclick="deleteCompany('${c.id}')">حذف</button>` : '—'}</td>
2274 - </tr>
2275 - `).join('');
2792 + if (myCompanies.length === 0) {
2793 + tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:20px;">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
2794 + } else {
2795 + tbody.innerHTML = myCompanies.map(c => `
2796 + <tr>
2797 + <td><strong>${c.name}</strong></td>
2798 + <td>${c.national_id || '—'}</td>
2799 + <td>${c.economic_code || '—'}</td>
2800 + <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>
2801 + <td>${myCompanies.length > 1 ? `<button class="btn btn-danger btn-inline" style="padding:2px 8px; font-size:11px;" onclick="deleteCompany('${c.id}')">حذف</button>` : '—'}</td>
2802 + </tr>
2803 + `).join('');
2804 + }
2805 }
2806
2807 if (invoiceCompSelect) {
2279 - invoiceCompSelect.innerHTML = datastore.companies.map(c => `<option value="${c.id}" ${c.id === defCompId ? 'selected' : ''}>${c.name}</option>`).join('');
2808 + invoiceCompSelect.innerHTML = myCompanies.map(c => `<option value="${c.id}" ${c.id === defCompId ? 'selected' : ''}>${c.name}</option>`).join('');
2809 if (defCompId) {
2810 invoiceCompSelect.value = defCompId;
2811 }
@@ -2284,23 +2813,26 @@
2813
2814 if (filterCompSelect) {
2815 const currentVal = filterCompSelect.value || 'ALL';
2287 - filterCompSelect.innerHTML = `<option value="ALL">نمایش همه شرکت‌ها</option>` + datastore.companies.map(c => `<option value="${c.id}">فقط ${c.name}</option>`).join('');
2816 + filterCompSelect.innerHTML = `<option value="ALL">نمایش همه شرکت‌ها</option>` + myCompanies.map(c => `<option value="${c.id}">فقط ${c.name}</option>`).join('');
2817 filterCompSelect.value = currentVal;
2818 }
2819 }
2820
2821 function setDefaultCompany(id) {
2293 - if (!datastore.default_settings) datastore.default_settings = {};
2294 - datastore.default_settings.default_company_id = id;
2822 + const s = getMySettings();
2823 + s.default_company_id = id;
2824 saveDatastore();
2825 refreshAllSurfaces();
2826 }
2827
2828 function deleteCompany(id) {
2829 + if (!currentUser) return;
2830 if (confirm('حذف شود؟')) {
2301 - datastore.companies = datastore.companies.filter(c => c.id !== id);
2302 - if (datastore.default_settings?.default_company_id === id) {
2303 - datastore.default_settings.default_company_id = datastore.companies[0]?.id || null;
2831 + datastore.companies = datastore.companies.filter(c => !(c.id === id && c.ownerUserId === currentUser.id));
2832 + const myCompanies = getMyCompanies();
2833 + const s = getMySettings();
2834 + if (s.default_company_id === id) {
2835 + s.default_company_id = myCompanies[0]?.id || '';
2836 }
2837 saveDatastore();
2838 refreshAllSurfaces();
@@ -2308,36 +2840,56 @@
2840 }
2841
2842 function exportDataBlob() {
2311 - const blobString = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(datastore, null, 2));
2843 + const userExport = {
2844 + user: currentUser?.username,
2845 + exportedAt: new Date().toISOString(),
2846 + companies: getMyCompanies(),
2847 + contacts: getMyContacts(),
2848 + products: getMyProducts(),
2849 + invoices: getMyInvoices(),
2850 + cheques: getMyCheques(),
2851 + expenses: getMyExpenses(),
2852 + settings: getMySettings()
2853 + };
2854 + const blobString = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(userExport, null, 2));
2855 const anchor = document.createElement('a');
2856 anchor.setAttribute("href", blobString);
2314 - anchor.setAttribute("download", `easy-factor-backup-${Date.now()}.json`);
2857 + anchor.setAttribute("download", `easy-factor-${currentUser?.username || 'data'}-${Date.now()}.json`);
2858 document.body.appendChild(anchor);
2859 anchor.click();
2860 anchor.remove();
2861 }
2862
2863 function importDataBlob(event) {
2864 + if (!currentUser) return;
2865 const file = event.target.files[0];
2866 if (!file) return;
2867 const reader = new FileReader();
2868 reader.onload = function(e) {
2869 try {
2326 - datastore = JSON.parse(e.target.result);
2327 - if (!datastore.default_settings) datastore.default_settings = {};
2328 - if (!Array.isArray(datastore.companies)) datastore.companies = [];
2329 - if (!datastore.default_settings.default_company_id && datastore.companies.length > 0) {
2330 - datastore.default_settings.default_company_id = datastore.companies[0].id;
2870 + const imported = JSON.parse(e.target.result);
2871 + const userId = currentUser.id;
2872 +
2873 + ['companies', 'contacts', 'products', 'invoices', 'cheques', 'expenses'].forEach(key => {
2874 + if (Array.isArray(imported[key])) {
2875 + imported[key].forEach(item => {
2876 + item.ownerUserId = userId;
2877 + datastore[key].push(item);
2878 + });
2879 + }
2880 + });
2881 + if (imported.settings) {
2882 + const s = getMySettings();
2883 + Object.assign(s, imported.settings, { ownerUserId: userId });
2884 }
2885 saveDatastore();
2886 refreshAllSurfaces();
2334 - alert('اطلاعات بازگردانی شد.');
2887 + alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
2888 } catch(err) { alert('فایل نامعتبر است.'); }
2889 };
2890 reader.readAsText(file);
2891 }
2892
2340 - // تبدیل ارقام به حروف فارسی استاندارد
2893 function numberToPersianWords(num) {
2894 if (!num || isNaN(num) || num == 0) return 'صفر ریال';
2895 const yegan = ["", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"];