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

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

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

Synced Dec 3, 22:00 UTC

Switch index.html to modular js/ files; add contract-statement invoice kind, project selector, and Excel invoice-item import UI

davoodmehraban89 committed Sep 26, 2026 at 23:24 UTC f90143862d021e576896ab8db8c909fdab799089
1 file changed +45 -2180
index.html
+45 -2180
@@ -272,10 +272,13 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
272
273 <section id="view-invoices" class="view-pane">
274 <div class="card no-print">
275 -<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
275 +<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
276 <h2 style="font-size:17px" id="invoice-form-title">صدور فاکتور جدید</h2>
277 +<div style="display:flex;gap:8px">
278 +<label class="btn btn-secondary btn-inline" style="min-height:34px;padding:4px 10px;font-size:12px">📥 ورود اقلام از اکسل<input type="file" id="excel-import-invoice-items" style="display:none" onchange="importInvoiceItemsFromExcel(event)" accept=".xlsx, .xls" /></label>
279 <button class="btn btn-secondary btn-inline" style="display:none;padding:4px 10px;font-size:12px" id="btn-cancel-edit" onclick="cancelInvoiceEdit()">انصراف از ویرایش</button>
280 </div>
281 +</div>
282 <input type="hidden" id="edit-invoice-id" value="" />
283 <div class="form-row" style="background:#f1f5f9;padding:12px;border-radius:10px;margin-bottom:14px">
284 <div class="form-group" style="margin-bottom:0"><label>تاریخ فاکتور</label><input type="text" id="invoice-date-input" class="form-control" /></div>
@@ -286,6 +289,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
289 <option value="non_formal">فاکتور غیررسمی</option>
290 <option value="formal">فاکتور رسمی</option>
291 <option value="pre_invoice">پیش‌فاکتور فروش</option>
292 +<option value="contract_statement">صورت وضعیت پیمان</option>
293 </select>
294 </div>
295 </div>
@@ -294,11 +298,17 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
298 <div class="form-group">
299 <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>
300 <div style="display:flex;gap:8px">
297 -<select id="invoice-contact-id" class="form-control" style="flex:1"></select>
301 +<select id="invoice-contact-id" class="form-control" style="flex:1" onchange="handleInvoiceContactChange()"></select>
302 <button class="btn btn-secondary btn-inline" type="button" onclick="openQuickContactModal()" style="padding:0 12px;min-height:42px">➕</button>
303 </div>
304 </div>
305 </div>
306 +<div class="form-row" id="box-invoice-project-row" style="display:none">
307 +<div class="form-group"><label>پروژه طرف‌حساب</label><select id="invoice-project-id" class="form-control"></select></div>
308 +</div>
309 +<div class="form-row" id="box-invoice-contract-number" style="display:none;background:#fef3c7;padding:12px;border-radius:10px;margin-bottom:14px">
310 +<div class="form-group" style="margin-bottom:0"><label>شماره پیمان <span style="color:var(--danger)">*</span></label><input type="text" id="invoice-contract-number" class="form-control" placeholder="شماره پیمان الزامی است" /></div>
311 +</div>
312 <div style="margin:16px 0">
313 <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
314 <h4 style="font-size:14px">اقلام کالا یا خدمات</h4>
@@ -321,7 +331,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
331 </div>
332 <div id="box-invoice-vat-rate" style="display:none;justify-content:space-between;align-items:center;margin-bottom:8px;gap:8px">
333 <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>
324 -<input type="number" id="invoice-vat-rate-input" class="form-control" style="width:100px;min-height:36px" value="10" oninput="recomputeTotals()" />
334 +<input type="text" inputmode="decimal" id="invoice-vat-rate-input" class="form-control" style="width:100px;min-height:36px" value="10" oninput="handleMoneyInput(this);recomputeTotals()" />
335 </div>
336 <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;gap:8px">
337 <span>تخفیف کلی فاکتور</span>
@@ -329,7 +339,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
339 </div>
340 <div style="display:flex;justify-content:space-between;align-items:center">
341 <span id="label-invoice-discount-value">مبلغ تخفیف (ریال)</span>
332 -<input type="number" id="invoice-discount-fixed" class="form-control" style="width:140px;min-height:36px" value="0" oninput="recomputeTotals()" />
342 +<input type="text" inputmode="decimal" id="invoice-discount-fixed" class="form-control" style="width:140px;min-height:36px" value="0" oninput="handleMoneyInput(this);recomputeTotals()" />
343 </div>
344 </div>
345 <div class="form-group" style="background:#fff;padding:12px;border-radius:8px;border:1px solid var(--border);margin-bottom:0">
@@ -385,8 +395,8 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
395 <div class="form-group"><label>واحد</label><input type="text" id="prod-unit-input" class="form-control" value="عدد" /></div>
396 </div>
397 <div class="form-row">
388 -<div class="form-group"><label>قیمت خرید (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-buy-input" class="form-control" value="0" /></div>
389 -<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="prod-sale-input" class="form-control" value="0" /></div>
398 +<div class="form-group"><label>قیمت خرید (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="prod-buy-input" class="form-control" value="0" oninput="handleMoneyInput(this)" /></div>
399 +<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="prod-sale-input" class="form-control" value="0" oninput="handleMoneyInput(this)" /></div>
400 <div class="form-group"><label>شناسه کالا/خدمت داخلی</label><input type="text" id="prod-internal-id-input" class="form-control" placeholder="2330004169617" /></div>
401 </div>
402 <button class="btn btn-success" onclick="commitSaveProduct()">➕ ثبت کالا</button>
@@ -424,12 +434,15 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
434 <div class="form-group"><label>کد پستی</label><input type="text" id="contact-postal-input" class="form-control" /></div>
435 <div class="form-group" style="grid-column:span 2"><label>نشانی</label><input type="text" id="contact-address-input" class="form-control" /></div>
436 </div>
437 +<div class="form-row">
438 +<div class="form-group"><label>حالت پروژه</label><select id="contact-project-mode" class="form-control"><option value="single">تک‌پروژه (بدون تفکیک پروژه)</option><option value="multi">پروژه‌محور (چند پروژه)</option></select></div>
439 +</div>
440 <button class="btn btn-success" onclick="commitSaveContact()">➕ ثبت طرف حساب</button>
441 </div>
442 <div class="card">
443 <h3 style="font-size:15px;margin-bottom:12px">دفتر اشخاص</h3>
444 <div class="table-responsive">
432 -<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>
445 +<table><thead><tr><th>نام</th><th>نوع</th><th>شناسه / کد ملی</th><th>کد اقتصادی</th><th>کد پستی</th><th>همراه</th><th>مانده (<span class="cur-label">ریال</span>)</th><th>پروژه‌ها</th><th>عملیات</th></tr></thead><tbody id="contacts-ledger-table-body"></tbody></table>
446 </div>
447 </div>
448 </section>
@@ -444,7 +457,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
457 <div class="form-group"><label>بانک</label><input type="text" id="chq-bank-input" class="form-control" /></div>
458 </div>
459 <div class="form-row">
447 -<div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="chq-amount-input" class="form-control" /></div>
460 +<div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="chq-amount-input" class="form-control" oninput="handleMoneyInput(this)" /></div>
461 <div class="form-group"><label>سررسید</label><input type="text" id="chq-due-input" class="form-control" placeholder="1405/06/30" /></div>
462 <div class="form-group"><label>وضعیت</label><select id="chq-status-input" class="form-control"><option value="registered">در جریان</option><option value="cleared">وصول شده</option></select></div>
463 </div>
@@ -462,7 +475,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
475 <div class="form-row">
476 <div class="form-group"><label>نوع</label><select id="trx-kind-input" class="form-control"><option value="expense">هزینه</option><option value="income">درآمد</option></select></div>
477 <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>
465 -<div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="number" id="trx-amount-input" class="form-control" /></div>
478 +<div class="form-group"><label>مبلغ (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="trx-amount-input" class="form-control" oninput="handleMoneyInput(this)" /></div>
479 <div class="form-group"><label>شرح</label><input type="text" id="trx-desc-input" class="form-control" /></div>
480 </div>
481 <button class="btn btn-success" onclick="commitSaveExpense()">➕ ثبت سند</button>
@@ -519,9 +532,9 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
532 <div class="accordion-header" onclick="toggleAccordion(this)"><span>⚙️ مالیات، تخفیف و واحد پول (پیش‌فرض فاکتور جدید)</span><span>▼</span></div>
533 <div class="accordion-body">
534 <div class="form-row">
522 -<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>
535 +<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><option value="contract_statement">صورت وضعیت پیمان</option></select></div>
536 <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>
524 -<div class="form-group"><label>نرخ ارزش افزوده (درصد)</label><input type="number" id="def-vat-rate" class="form-control" value="10" /></div>
537 +<div class="form-group"><label>نرخ ارزش افزوده (درصد)</label><input type="text" inputmode="decimal" id="def-vat-rate" class="form-control" value="10" oninput="handleMoneyInput(this)" /></div>
538 </div>
539 <div class="form-row">
540 <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>
@@ -577,7 +590,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
590 <div><h2 style="font-size:18px;color:var(--danger)">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2><p style="color:var(--text-muted);font-size:13px;margin-top:4px">تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.</p></div>
591 <button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
592 </div>
580 -<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">کاربران خودشان از صفحه‌ی ورود ثبت‌نام می‌کنند و ۱۵ روز آزمایشی می‌گیرند. در این پنل فقط لایسنس‌ها (فعال‌سازی، تمدید، تغییر طرح، لغو) مدیریت می‌شود و کنترل نهایی روی سرور انجام می‌شود.</div>
593 +<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">کاربران خودشان از صفحه ورود ثبت‌نام می‌کنند و ۱۵ روز آزمایشی می‌گیرند. در این پنل فقط لایسنس‌ها (فعال‌سازی، تمدید، تغییر طرح، لغو) مدیریت می‌شود و کنترل نهایی روی سرور انجام می‌شود.</div>
594 <div class="table-responsive">
595 <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>
596 </div>
@@ -623,7 +636,7 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
636 </div>
637 <div class="form-row">
638 <div class="form-group"><label>واحد</label><input type="text" id="quick-p-unit" class="form-control" value="عدد" /></div>
626 -<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="number" id="quick-p-price" class="form-control" value="0" /></div>
639 +<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="quick-p-price" class="form-control" value="0" oninput="handleMoneyInput(this)" /></div>
640 <div class="form-group"><label>شناسه کالا/خدمت داخلی</label><input type="text" id="quick-p-internal-id" class="form-control" /></div>
641 </div>
642 <div style="display:flex;gap:10px;margin-top:12px">
@@ -692,2178 +705,30 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
705 <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>
706 </nav>
707
695 -<script>
696 -const STORAGE_KEY = 'easy_factor_commercial_v4_7';
697 -const AUTH_KEY = 'easy_factor_auth_users_v4_7';
698 -
699 -window.pendingElectronicDoc = null;
700 -
701 -function toPersianDigits(str){if(str===null||str===undefined)return '';return String(str).replace(/[0-9]/g,d=>'۰۱۲۳۴۵۶۷۸۹'[d]);}
702 -function formatToJalali(dateInput){
703 - if(!dateInput)return '—';
704 - let dateObj;
705 - if(dateInput instanceof Date)dateObj=dateInput;
706 - else if(typeof dateInput==='string'&&dateInput.includes('/'))return toPersianDigits(dateInput);
707 - else{const str=String(dateInput).split('T')[0];const parts=str.split('-');if(parts.length===3)dateObj=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),12,0,0);else dateObj=new Date(dateInput);}
708 - if(isNaN(dateObj.getTime()))return toPersianDigits(String(dateInput));
709 - return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(dateObj);
710 -}
711 -function getRemainingDays(endDateStr){
712 - if(!endDateStr)return 0;
713 - if(String(endDateStr).startsWith('2099'))return Infinity;
714 - const str=String(endDateStr).split('T')[0];const parts=str.split('-');
715 - if(parts.length!==3)return 0;
716 - const end=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),23,59,59);
717 - return Math.ceil((end.getTime()-new Date().getTime())/(1000*60*60*24));
718 -}
719 -function addDaysToDate(baseDateStr,days){
720 - let d;
721 - if(baseDateStr){const parts=String(baseDateStr).split('T')[0].split('-');d=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),12,0,0);}
722 - else{const tp=todayISO().split('-');d=new Date(parseInt(tp[0]),parseInt(tp[1])-1,parseInt(tp[2]),12,0,0);}
723 - if(isNaN(d.getTime()))d=new Date();
724 - d.setDate(d.getDate()+days);
725 - return d.toISOString().split('T')[0];
726 -}
727 -
728 -const SUPABASE_URL='https://hcsixhqbyuhpshfwqpjx.supabase.co';
729 -const SUPABASE_KEY='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D'; // publishable (public by design); access is enforced by RLS on the server
730 -const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
731 -const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
732 -const COLLS=['companies','contacts','products','invoices','cheques','expenses','settings'];
733 -
734 -function esc(v){return String(v==null?'':v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}
735 -function todayISO(){return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
736 -
737 -let currentUser=null;
738 -let authBusy=false;
739 -
740 -const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
741 -const OTP_RE=/^[0-9]{6,10}$/;
742 -let otpEmail='',otpCooldownUntil=0,pendingAuthUser=null;
743 -
744 -function normalizeEmail(raw){return String(raw||'').trim().toLowerCase();}
745 -function toEnDigits(s){
746 - return String(s||'').replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[٠-٩]/g,d=>'٠١٢٣٤٥٦٧٨٩'.indexOf(d));
747 -}
748 -function buildUserFromRows(profile,lic){
749 - const sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
750 - return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
751 -}
752 -async function fetchCurrentUser(authUser){
753 - const [p,l]=await Promise.all([
754 - sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single(),
755 - sb.from('licenses').select('plan,status,starts_at,ends_at').eq('user_id',authUser.id).single()
756 - ]);
757 - if(p.error)throw p.error;
758 - if(l.error)throw l.error;
759 - return buildUserFromRows(p.data,l.data);
760 -}
761 -function canWrite(){
762 - if(!currentUser)return false;
763 - const s=currentUser.subscription||{};
764 - if(s.status!=='active'&&s.status!=='trial')return false;
765 - if(s.type==='lifetime')return true;
766 - return String(s.endDate||'')>=todayISO();
767 -}
768 -function requireWrite(){
769 - if(canWrite())return true;
770 - alert('اشتراک شما منقضی یا لغو شده است؛ امکان ثبت یا ویرایش اطلاعات وجود ندارد. اطلاعات قبلی شما همچنان قابل مشاهده و پشتیبان‌گیری است. برای تمدید با پشتیبانی تماس بگیرید.');
771 - return false;
772 -}
773 -function authMsg(err){
774 - const m=(err&&err.message)||'';
775 - const c=(err&&(err.code||err.error_code))||'';
776 - if(c==='invalid_credentials'||/Invalid login credentials/i.test(m))return 'ایمیل یا رمز عبور اشتباه است. اگر رمز ندارید یا فراموش کرده‌اید، «ادامه با کد ایمیل» را بزنید.';
777 - if(c==='otp_expired'||/expired|invalid.*token|token.*invalid/i.test(m))return 'کد اشتباه است یا منقضی شده. دوباره کد بگیرید.';
778 - if(c==='over_email_send_rate_limit'||c==='over_request_rate_limit'||/rate limit|too many|security purposes/i.test(m))return 'تعداد درخواست‌ها زیاد است؛ چند دقیقه بعد دوباره تلاش کنید.';
779 - if(c==='email_address_invalid'||/email address.*invalid|unable to validate email/i.test(m))return 'آدرس ایمیل معتبر نیست.';
780 - if(c==='email_not_confirmed'||/Email not confirmed/i.test(m))return 'ایمیل هنوز تأیید نشده است. از «ادامه با کد ایمیل» استفاده کنید.';
781 - if(c==='validation_failed'&&/provider/i.test(m)||/provider is not enabled|unsupported provider/i.test(m))return 'ورود با Google هنوز در سرور فعال نشده است.';
782 - if(c==='weak_password'||/password.*(weak|short|at least)/i.test(m))return 'رمز عبور ضعیف است؛ حداقل ۸ کاراکتر و ترکیب حروف و عدد استفاده کنید.';
783 - if(c==='same_password'||/different from the old password/i.test(m))return 'رمز جدید باید با رمز قبلی فرق داشته باشد.';
784 - if(/fetch|network|load failed|timeout|abort/i.test(m))return 'ارتباط با سرور برقرار نشد. اتصال اینترنت/VPN را بررسی کنید و دوباره تلاش کنید.';
785 - return 'خطا: '+m;
786 -}
787 -function showAuthPanel(name){
788 - const ids={main:'auth-form-container',otp:'auth-otp-container',setpass:'auth-setpass-container'};
789 - Object.keys(ids).forEach(k=>{const el=document.getElementById(ids[k]);if(el)el.style.display=(k===name)?'block':'none';});
790 -}
791 -function backToAuthMain(){pendingAuthUser=null;showAuthPanel('main');}
792 -function reportOAuthReturnError(){
793 - try{
794 - const q=new URLSearchParams(window.location.search);
795 - const h=new URLSearchParams((window.location.hash||'').replace(/^#/,''));
796 - const desc=q.get('error_description')||h.get('error_description');
797 - if(desc){
798 - alert('ورود با Google انجام نشد: '+desc.replace(/\+/g,' '));
799 - window.history.replaceState({},document.title,window.location.pathname);
800 - }
801 - }catch(e){}
802 -}
803 -async function initAuthSystem(){
804 - // Remove the legacy plaintext user database that older versions kept in this browser.
805 - try{localStorage.removeItem(AUTH_KEY);}catch(e){}
806 - try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
807 - reportOAuthReturnError();
808 - sb.auth.onAuthStateChange(ev=>{if(ev==='SIGNED_OUT'&&currentUser){window.location.reload();}});
809 - try{
810 - const {data}=await sb.auth.getSession();
811 - if(data&&data.session){await enterApp(data.session.user);return;}
812 - }catch(e){console.error(e);}
813 - document.getElementById('auth-screen').style.display='flex';
814 - showAuthPanel('main');
815 -}
816 -async function handleLogin(){
817 - if(authBusy)return;
818 - const email=normalizeEmail(document.getElementById('auth-email').value);
819 - const pass=document.getElementById('auth-password').value;
820 - if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
821 - if(!pass){alert('رمز عبور را وارد کنید؛ یا «ادامه با کد ایمیل» را بزنید.');return;}
822 - authBusy=true;
823 - try{
824 - const {data,error}=await sb.auth.signInWithPassword({email,password:pass});
825 - if(error)throw error;
826 - await enterApp(data.user);
827 - }catch(err){alert(authMsg(err));}
828 - finally{authBusy=false;}
829 -}
830 -async function signInWithGoogle(){
831 - if(authBusy)return;
832 - authBusy=true;
833 - try{
834 - const {error}=await sb.auth.signInWithOAuth({provider:'google',options:{redirectTo:window.location.origin+window.location.pathname,queryParams:{prompt:'select_account'}}});
835 - if(error)throw error;
836 - }catch(err){authBusy=false;alert(authMsg(err));}
837 -}
838 -async function startEmailOtp(isResend){
839 - if(authBusy)return;
840 - const email=normalizeEmail(isResend===true?otpEmail:document.getElementById('auth-email').value);
841 - if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
842 - if(Date.now()<otpCooldownUntil){alert('لطفاً حدود یک دقیقه بین درخواست‌ها صبر کنید.');return;}
843 - authBusy=true;
844 - try{
845 - const {error}=await sb.auth.signInWithOtp({email,options:{shouldCreateUser:true}});
846 - if(error)throw error;
847 - otpEmail=email;otpCooldownUntil=Date.now()+60000;
848 - document.getElementById('auth-otp-email-label').innerText=email;
849 - document.getElementById('auth-otp').value='';
850 - showAuthPanel('otp');
851 - }catch(err){alert(authMsg(err));}
852 - finally{authBusy=false;}
853 -}
854 -async function verifyEmailOtp(){
855 - if(authBusy)return;
856 - const token=toEnDigits(document.getElementById('auth-otp').value).replace(/\s/g,'');
857 - if(!OTP_RE.test(token)){alert('کد را فقط با عدد و کامل وارد کنید.');return;}
858 - authBusy=true;
859 - try{
860 - const {data,error}=await sb.auth.verifyOtp({email:otpEmail,token,type:'email'});
861 - if(error)throw error;
862 - const u=data.user;
863 - const hasPassword=!!(u&&u.user_metadata&&u.user_metadata.has_password===true);
864 - if(!hasPassword){
865 - pendingAuthUser=u;
866 - document.getElementById('auth-newpass').value='';
867 - document.getElementById('auth-newpass2').value='';
868 - showAuthPanel('setpass');
869 - return;
870 - }
871 - await enterApp(u);
872 - }catch(err){alert(authMsg(err));}
873 - finally{authBusy=false;}
874 -}
875 -async function saveNewPassword(){
876 - if(authBusy)return;
877 - const p1=document.getElementById('auth-newpass').value;
878 - const p2=document.getElementById('auth-newpass2').value;
879 - if(p1.length<8){alert('رمز عبور باید حداقل ۸ کاراکتر باشد.');return;}
880 - if(p1!==p2){alert('تکرار رمز عبور با رمز اصلی یکی نیست.');return;}
881 - authBusy=true;
882 - try{
883 - const {data,error}=await sb.auth.updateUser({password:p1,data:{has_password:true}});
884 - if(error)throw error;
885 - const u=(data&&data.user)||pendingAuthUser;
886 - pendingAuthUser=null;
887 - alert('رمز عبور ذخیره شد. دفعات بعد می‌توانید با ایمیل و رمز وارد شوید.');
888 - await enterApp(u);
889 - }catch(err){alert(authMsg(err));}
890 - finally{authBusy=false;}
891 -}
892 -async function skipSetPassword(){
893 - if(authBusy||!pendingAuthUser)return;
894 - const u=pendingAuthUser;pendingAuthUser=null;
895 - authBusy=true;
896 - try{await enterApp(u);}finally{authBusy=false;}
897 -}
898 -async function enterApp(authUser){
899 - try{
900 - currentUser=await fetchCurrentUser(authUser);
901 - await pullAll();
902 - }catch(err){
903 - console.error(err);
904 - currentUser=null;
905 - alert('خطا در بارگذاری اطلاعات حساب. اتصال اینترنت را بررسی کنید و دوباره وارد شوید.');
906 - document.getElementById('auth-screen').style.display='flex';
907 - showAuthPanel('main');
908 - return;
909 - }
910 - document.getElementById('auth-screen').style.display='none';
911 - document.getElementById('logged-user-label').innerText='کاربر: '+(currentUser.fullName||currentUser.email||currentUser.username)+(currentUser.role==='admin'?' (مدیر سیستم)':'');
912 - document.getElementById('menu-admin-panel').style.display=(currentUser.role==='admin')?'block':'none';
913 - refreshAllSurfaces();
914 - maybeMigrateLegacyData();
915 -}
916 -async function handleLogout(){
917 - if(syncPending&&!confirm('تغییرات ذخیره‌نشده وجود دارد. با خروج ممکن است از بین برود. خارج شوم؟'))return;
918 - try{await sb.auth.signOut();}catch(e){}
919 - window.location.reload();
920 -}
921 -
922 -function updateLicenseDisplay(user){
923 - if(!user)return;
924 - const badge=document.getElementById('user-license-status-badge');
925 - const detailsBox=document.getElementById('dashboard-license-details');
926 - if(detailsBox){detailsBox.style.display='none';detailsBox.innerHTML='';}
927 - const sub=user.subscription||{type:user.subscriptionType||'trial',startDate:user.subscriptionStart||user.createdAt,endDate:user.subscriptionEnd,status:user.licenseStatus||'trial'};
928 - const remDays=getRemainingDays(sub.endDate);
929 - const isExpired=remDays<=0&&sub.type!=='lifetime';
930 - const hasActiveLicense=(sub.status==='active')&&(sub.type==='lifetime'||!isExpired)&&(sub.type!=='trial');
931 - if(!badge)return;
932 - if(hasActiveLicense){
933 - badge.className='badge badge-success';
934 - badge.innerText=(sub.type==='lifetime')?'وضعیت اشتراک : نامحدود':`وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
935 - }else if(isExpired||sub.status==='cancelled'){
936 - badge.className='badge badge-danger';badge.innerText='وضعیت اشتراک : منقضی شده';
937 - }else{
938 - badge.className='badge badge-warning';badge.innerText=`وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
939 - }
940 -}
941 -
942 -let adminUsersCache=[];
943 -async function renderAdminPanel(){
944 - const tbody=document.getElementById('admin-users-table-body');
945 - if(!tbody||!currentUser||currentUser.role!=='admin')return;
946 - tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr>';
947 - const [p,l]=await Promise.all([
948 - sb.from('profiles').select('id,email,username,role,created_at').order('created_at',{ascending:false}),
949 - sb.from('licenses').select('user_id,plan,status,starts_at,ends_at')
950 - ]);
951 - if(p.error||l.error){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--danger)">خطا در دریافت لیست کاربران.</td></tr>';return;}
952 - const lic=new Map((l.data||[]).map(x=>[x.user_id,x]));
953 - adminUsersCache=(p.data||[]).map(u=>Object.assign({},u,{lic:lic.get(u.id)||null}));
954 - if(adminUsersCache.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
955 - const planLabels={monthly:'طرح ۱ ماهه',three_months:'طرح ۳ ماهه',annual:'طرح ۱ ساله',lifetime:'دائمی (Lifetime)',trial:'آزمایشی (Trial)'};
956 - tbody.innerHTML=adminUsersCache.map(u=>{
957 - const sub=u.lic?{type:u.lic.plan,startDate:u.lic.starts_at,endDate:u.lic.ends_at,status:u.lic.status}:{type:'trial',startDate:'',endDate:'',status:'cancelled'};
958 - const remDays=getRemainingDays(sub.endDate);
959 - const isExp=remDays<=0&&sub.type!=='lifetime';
960 - let statusBadge='';
961 - if(sub.status==='cancelled')statusBadge='<span class="badge badge-danger">لغو شده</span>';
962 - else if(sub.status==='active')statusBadge=isExp?'<span class="badge badge-danger">منقضی شده</span>':'<span class="badge badge-success">فعال</span>';
963 - else statusBadge=isExp?'<span class="badge badge-danger">آزمایشی منقضی</span>':'<span class="badge badge-warning">آزمایشی</span>';
964 - const endJalali=sub.type==='lifetime'?'نامحدود':formatToJalali(sub.endDate);
965 - const remDaysText=sub.type==='lifetime'?'نامحدود':toPersianDigits(Math.max(0,remDays))+' روز';
966 - const uid=esc(u.id);
967 - return `<tr><td><strong>${esc(u.email||u.username||'—')}</strong> ${u.role==='admin'?'<span class="badge badge-info">مدیر</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td>${formatToJalali(sub.startDate)}</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('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">تغییر مدت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
968 - }).join('');
969 -}
970 -function refreshAdminPanel(){renderAdminPanel();}
971 -async function adminRpc(name,args,okMsg){
972 - const {error}=await sb.rpc(name,args);
973 - if(error){alert('خطا: '+(error.message||'عملیات ناموفق بود.'));return false;}
974 - if(okMsg)alert(okMsg);
975 - if(currentUser&&args.target===currentUser.id){try{currentUser=await fetchCurrentUser({id:currentUser.id});updateLicenseDisplay(currentUser);}catch(e){}}
976 - renderAdminPanel();
977 - return true;
978 -}
979 -function adminActivateLicense(uid){
980 - return adminRpc('admin_set_license',{target:uid,new_plan:'monthly',days:30,new_status:'active'},'لایسنس ۱ ماهه فعال شد.');
981 -}
982 -function openLicenseEditModal(uid){
983 - const u=adminUsersCache.find(x=>x.id===uid);if(!u)return;
984 - document.getElementById('modal-license-target-username').value=uid;
985 - document.getElementById('modal-license-user-title').innerText='تغییر مدت و نوع لایسنس: '+(u.email||u.username);
986 - const cur=u.lic&&u.lic.plan!=='trial'?u.lic.plan:'monthly';
987 - document.getElementById('modal-license-duration-select').value=cur;
988 - document.getElementById('modal-admin-license-edit').classList.add('active');
989 -}
990 -function closeLicenseEditModal(){document.getElementById('modal-admin-license-edit').classList.remove('active');}
991 -function applyLicenseDurationChange(){
992 - const uid=document.getElementById('modal-license-target-username').value;
993 - const plan=document.getElementById('modal-license-duration-select').value;
994 - closeLicenseEditModal();
995 - return adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'طرح لایسنس کاربر تغییر یافت.');
996 -}
997 -function adminExtendSubscription(uid,days){
998 - const u=adminUsersCache.find(x=>x.id===uid);
999 - if(u&&u.lic&&u.lic.plan==='lifetime'){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
1000 - return adminRpc('admin_extend_license',{target:uid,days},'اشتراک کاربر '+days+' روز تمدید شد.');
1001 -}
1002 -function adminCancelSubscription(uid){
1003 - const u=adminUsersCache.find(x=>x.id===uid);
1004 - if(!confirm('آیا از لغو اشتراک کاربر '+(u?(u.email||u.username):'')+' اطمینان دارید؟'))return;
1005 - return adminRpc('admin_cancel_license',{target:uid},'اشتراک کاربر لغو شد.');
1006 -}
1007 -
1008 -let datastore={companies:[],contacts:[],products:[],invoices:[],cheques:[],expenses:[],settings:[]};
1009 -function getMyProducts(){return !currentUser?[]:datastore.products.filter(p=>p.ownerUserId===currentUser.id);}
1010 -function getMyContacts(){return !currentUser?[]:datastore.contacts.filter(c=>c.ownerUserId===currentUser.id);}
1011 -function getMyCompanies(){return !currentUser?[]:datastore.companies.filter(c=>c.ownerUserId===currentUser.id);}
1012 -function getMyInvoices(){return !currentUser?[]:datastore.invoices.filter(i=>i.ownerUserId===currentUser.id);}
1013 -function getMyCheques(){return !currentUser?[]:datastore.cheques.filter(c=>c.ownerUserId===currentUser.id);}
1014 -function getMyExpenses(){return !currentUser?[]:datastore.expenses.filter(e=>e.ownerUserId===currentUser.id);}
1015 -function getMySettings(){
1016 - if(!currentUser)return{invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'',currency_mode:'rial',currency_custom:''};
1017 - if(!Array.isArray(datastore.settings))datastore.settings=[];
1018 - let s=datastore.settings.find(item=>item.ownerUserId===currentUser.id);
1019 - if(!s){s={ownerUserId:currentUser.id,invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'',currency_mode:'rial',currency_custom:''};datastore.settings.push(s);}
1020 - if(typeof s.currency_mode==='undefined')s.currency_mode='rial';
1021 - if(typeof s.currency_custom==='undefined')s.currency_custom='';
1022 - return s;
1023 -}
1024 -// ---------- Cloud data layer (Supabase). UI code keeps using `datastore`; this layer syncs it. ----------
1025 -const syncSnap=new Map();
1026 -let syncTimer=null,syncRunning=false,syncAgain=false,syncPending=false,syncFailCount=0;
1027 -
1028 -function keyOfRecord(coll,item){return coll==='settings'?'main':String(item&&item.id!=null?item.id:'');}
1029 -function stripOwner(item){const c=Object.assign({},item);delete c.ownerUserId;return c;}
1030 -function setSyncBadge(state){
1031 - const el=document.getElementById('sync-badge');if(!el)return;
1032 - const map={saved:['✔ ذخیره شد','#059669'],saving:['⏳ در حال ذخیره…','#d97706'],error:['⚠️ ذخیره نشد؛ تلاش مجدد…','#dc2626']};
1033 - const m=map[state];if(!m)return;
1034 - el.textContent=m[0];el.style.background=m[1];el.style.display='block';
1035 - clearTimeout(setSyncBadge._t);
1036 - if(state==='saved')setSyncBadge._t=setTimeout(()=>{el.style.display='none';},2000);
1037 -}
1038 -async function pullAll(){
1039 - const uid=currentUser.id;
1040 - const fresh={};COLLS.forEach(k=>{fresh[k]=[];});
1041 - const snap=new Map();
1042 - const page=1000;let from=0;
1043 - for(;;){
1044 - const {data,error}=await sb.from('records').select('collection,id,data').order('collection').order('id').range(from,from+page-1);
1045 - if(error)throw error;
1046 - (data||[]).forEach(r=>{
1047 - if(!fresh[r.collection])return;
1048 - const obj=(r.data&&typeof r.data==='object'&&!Array.isArray(r.data))?r.data:{};
1049 - obj.id=r.id;
1050 - snap.set(r.collection+'|'+r.id,JSON.stringify(stripOwner(obj)));
1051 - obj.ownerUserId=uid;
1052 - fresh[r.collection].push(obj);
1053 - });
1054 - if(!data||data.length<page)break;
1055 - from+=page;
1056 - }
1057 - datastore=fresh;
1058 - syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));
1059 -}
1060 -function computeDiff(){
1061 - const uid=currentUser.id;const up=[];const seen=new Set();
1062 - COLLS.forEach(coll=>{(datastore[coll]||[]).forEach(item=>{
1063 - if(!item||item.ownerUserId!==uid)return;
1064 - const id=keyOfRecord(coll,item);
1065 - if(!ID_RE.test(id)){console.warn('skipped record with invalid id',coll,id);return;}
1066 - const key=coll+'|'+id;seen.add(key);
1067 - const payload=stripOwner(item);const s=JSON.stringify(payload);
1068 - if(syncSnap.get(key)!==s)up.push({key,coll,id,payload,s});
1069 - });});
1070 - const del=[];syncSnap.forEach((v,k)=>{if(!seen.has(k))del.push(k);});
1071 - return {up,del};
1072 -}
1073 -function scheduleSync(ms){clearTimeout(syncTimer);syncTimer=setTimeout(runSync,ms);}
1074 -async function runSync(){
1075 - if(!currentUser)return;
1076 - if(syncRunning){syncAgain=true;return;}
1077 - syncRunning=true;
1078 - try{
1079 - let guardLoops=0;
1080 - do{
1081 - syncAgain=false;
1082 - const {up,del}=computeDiff();
1083 - if(up.length===0&&del.length===0)break;
1084 - setSyncBadge('saving');
1085 - for(let i=0;i<up.length;i+=200){
1086 - const chunk=up.slice(i,i+200);
1087 - const {error}=await sb.from('records').upsert(chunk.map(r=>({owner_id:currentUser.id,collection:r.coll,id:r.id,data:r.payload})),{onConflict:'owner_id,collection,id'});
1088 - if(error)throw error;
1089 - chunk.forEach(r=>syncSnap.set(r.key,r.s));
1090 - }
1091 - const byColl={};
1092 - del.forEach(k=>{const j=k.indexOf('|');const c=k.slice(0,j),id=k.slice(j+1);(byColl[c]=byColl[c]||[]).push(id);});
1093 - for(const c of Object.keys(byColl)){
1094 - const ids=byColl[c];
1095 - for(let i=0;i<ids.length;i+=100){
1096 - const part=ids.slice(i,i+100);
1097 - const {error}=await sb.from('records').delete().eq('collection',c).in('id',part);
1098 - if(error)throw error;
1099 - part.forEach(id=>syncSnap.delete(c+'|'+id));
1100 - }
1101 - }
1102 - syncFailCount=0;
1103 - guardLoops++;
1104 - }while(guardLoops<5);
1105 - const d=computeDiff();
1106 - syncPending=(d.up.length>0||d.del.length>0);
1107 - if(syncPending){scheduleSync(500);}else{setSyncBadge('saved');}
1108 - }catch(err){
1109 - console.error('sync error',err);
1110 - await handleSyncError(err);
1111 - }finally{syncRunning=false;}
1112 -}
1113 -async function handleSyncError(err){
1114 - const msg=String((err&&err.message)||'');
1115 - if((err&&err.code==='42501')||/row-level security/i.test(msg)){
1116 - setSyncBadge('error');
1117 - syncPending=false;
1118 - alert('اشتراک شما منقضی یا لغو شده است؛ تغییرات ثبت نشد. برای تمدید با پشتیبانی تماس بگیرید.');
1119 - try{currentUser=await fetchCurrentUser({id:currentUser.id});await pullAll();}catch(e){console.error(e);}
1120 - refreshAllSurfaces();
1121 - return;
1122 - }
1123 - syncFailCount++;syncPending=true;setSyncBadge('error');
1124 - scheduleSync(Math.min(30000,2000*syncFailCount));
1125 -}
1126 -function saveDatastore(){
1127 - if(!currentUser)return false;
1128 - if(!canWrite()){
1129 - requireWrite();
1130 - pullAll().then(()=>refreshAllSurfaces()).catch(()=>{});
1131 - return false;
1132 - }
1133 - syncPending=true;setSyncBadge('saving');scheduleSync(300);
1134 - return true;
1135 -}
1136 -window.addEventListener('beforeunload',e=>{if(syncPending){e.preventDefault();e.returnValue='';}});
1137 -document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden'&&syncPending){clearTimeout(syncTimer);runSync();}});
1138 -
1139 -// ---------- Untrusted input handling (backup files, legacy local data) ----------
1140 -function neutralize(v){
1141 - if(typeof v==='string')return v.replace(/</g,'<').replace(/>/g,'>');
1142 - if(Array.isArray(v))return v.map(neutralize);
1143 - if(v&&typeof v==='object'){const o={};Object.keys(v).forEach(k=>{if(k==='__proto__'||k==='constructor'||k==='prototype')return;o[k]=neutralize(v[k]);});return o;}
1144 - return v;
1145 -}
1146 -function safeId(raw,prefix){
1147 - let s=String(raw==null?'':raw).replace(/[^A-Za-z0-9_-]/g,'_').slice(0,64);
1148 - if(!s)s=prefix+'_'+Date.now().toString(36)+Math.random().toString(36).slice(2,6);
1149 - return s;
1150 -}
1151 -function absorbRecords(imported){
1152 - const uid=currentUser.id;let count=0;
1153 - ['companies','contacts','products','invoices','cheques','expenses'].forEach(key=>{
1154 - if(!Array.isArray(imported[key]))return;
1155 - imported[key].forEach(raw=>{
1156 - if(!raw||typeof raw!=='object')return;
1157 - const item=neutralize(raw);
1158 - item.id=safeId(item.id,key.slice(0,3));
1159 - item.ownerUserId=uid;
1160 - const idx=datastore[key].findIndex(x=>x.id===item.id&&x.ownerUserId===uid);
1161 - if(idx>=0)datastore[key][idx]=item;else datastore[key].push(item);
1162 - count++;
1163 - });
1164 - });
1165 - if(imported.settings&&typeof imported.settings==='object'&&!Array.isArray(imported.settings)){
1166 - const s=getMySettings();Object.assign(s,neutralize(imported.settings),{ownerUserId:uid,id:'main'});
1167 - }
1168 - return count;
1169 -}
1170 -function maybeMigrateLegacyData(){
1171 - try{
1172 - const flag='finora_legacy_done_'+currentUser.id;
1173 - if(localStorage.getItem(flag))return;
1174 - const rawOld=localStorage.getItem(STORAGE_KEY);
1175 - if(!rawOld)return;
1176 - let old;try{old=JSON.parse(rawOld);}catch(e){return;}
1177 - const isSeed=it=>it&&it.ownerUserId==='user_admin'&&['COMP-1','C-1','P-1','P-2'].includes(it.id);
1178 - const clean={};let n=0;
1179 - ['companies','contacts','products','invoices','cheques','expenses'].forEach(k=>{
1180 - clean[k]=(old&&Array.isArray(old[k])?old[k]:[]).filter(it=>!isSeed(it));
1181 - n+=clean[k].length;
1182 - });
1183 - if(n===0){localStorage.setItem(flag,'1');return;}
1184 - if(!confirm('اطلاعات ذخیره‌شده‌ی نسخه‌ی قبلی در این مرورگر پیدا شد ('+n+' مورد). به حساب ابری شما منتقل شود؟')){return;}
1185 - if(!requireWrite())return;
1186 - absorbRecords(clean);
1187 - saveDatastore();refreshAllSurfaces();
1188 - localStorage.setItem(flag,'1');
1189 - alert('اطلاعات قبلی به حساب ابری منتقل شد. نسخه‌ی محلی روی این مرورگر دست‌نخورده باقی می‌ماند.');
1190 - }catch(e){console.error(e);}
1191 -}
1192 -function initDatastore(){refreshAllSurfaces();}
1193 -
1194 -function getJalaliDate(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{dateStyle:'full'}).format(new Date());}
1195 -function getJalaliNumeric(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
1196 -function getCurrencyLabel(){const s=getMySettings();if(s.currency_mode==='toman')return 'تومان';if(s.currency_mode==='custom')return (s.currency_custom||'').trim()||'واحد پول';return 'ریال';}
1197 -function refreshCurrencyLabels(){const label=getCurrencyLabel();document.querySelectorAll('.cur-label').forEach(el=>{el.innerText=label;});}
1198 -function handleCurrencyModeChange(){const mode=document.getElementById('def-currency-mode').value;document.getElementById('box-currency-custom').style.display=(mode==='custom')?'block':'none';}
1199 -
1200 -function switchView(viewId){
1201 - document.querySelectorAll('.view-pane').forEach(el=>el.classList.remove('active'));
1202 - const target=document.getElementById(viewId);
1203 - if(target)target.classList.add('active');
1204 - document.querySelectorAll('.nav-link').forEach(btn=>btn.classList.toggle('active',btn.getAttribute('data-view')===viewId));
1205 - const dockViews=['view-dashboard','view-invoices','view-products','view-contacts','view-cheques','view-settings'];
1206 - document.querySelectorAll('.dock-tab').forEach((dock,idx)=>{dock.classList.toggle('active',dockViews[idx]===viewId);});
1207 - if(viewId==='view-admin')renderAdminPanel();
1208 - if(viewId==='view-reports')renderFinancialReports();
1209 - window.scrollTo({top:0,behavior:'smooth'});
1210 -}
1211 -function toggleAccordion(headerEl){headerEl.parentElement.classList.toggle('open');}
1212 -function refreshAllSurfaces(){
1213 - const dashDate=document.getElementById('dashboard-date-display');
1214 - if(dashDate)dashDate.innerText=getJalaliDate();
1215 - const invDate=document.getElementById('invoice-date-input');
1216 - if(invDate&&!invDate.value)invDate.value=getJalaliNumeric();
1217 - updateLicenseDisplay(currentUser);
1218 - renderCompanies();renderContacts();renderProducts();renderInvoices();
1219 - renderDashboard();renderCheques();renderExpenses();
1220 - applyDefaultSettingsToForm();
1221 - handleContactEntityChange();
1222 - handleCurrencyModeChange();
1223 - refreshCurrencyLabels();
1224 -}
1225 -function formatEntityName(rawName,entityType,customPrefix=''){
1226 - let trimmed=(rawName||'').trim();
1227 - if(entityType==='legal'){
1228 - if(!trimmed.startsWith('شرکت')&&!trimmed.startsWith('موسسه')&&!trimmed.startsWith('سازمان')&&!trimmed.startsWith('اداره'))trimmed='شرکت '+trimmed;
1229 - }else if(entityType==='natural'&&customPrefix){
1230 - if(!trimmed.startsWith(customPrefix))trimmed=customPrefix+' '+trimmed;
1231 - }
1232 - return trimmed;
1233 -}
1234 -function applyEntityTypeToForm(entity,opts){
1235 - const {prefixId,nameId,econId,regId,nationalLabelId}=opts;
1236 - const prefixBox=document.getElementById(prefixId);
1237 - const nameBox=document.getElementById(nameId);
1238 - const econBox=document.getElementById(econId);
1239 - const regBox=document.getElementById(regId);
1240 - const natLabel=document.getElementById(nationalLabelId);
1241 - if(entity==='legal'){
1242 - if(prefixBox)prefixBox.style.display='none';
1243 - if(nameBox)nameBox.style.gridColumn='span 3';
1244 - if(econBox)econBox.style.display='block';
1245 - if(regBox)regBox.style.display='block';
1246 - if(natLabel)natLabel.innerText='شناسه ملی';
1247 - }else{
1248 - if(prefixBox)prefixBox.style.display='block';
1249 - if(nameBox)nameBox.style.gridColumn='span 2';
1250 - if(econBox)econBox.style.display='none';
1251 - if(regBox)regBox.style.display='none';
1252 - if(natLabel)natLabel.innerText='کد ملی';
1253 - }
1254 -}
1255 -function handleContactEntityChange(){const el=document.getElementById('contact-entity-type');if(!el)return;applyEntityTypeToForm(el.value,{prefixId:'box-contact-prefix',nameId:'box-contact-name',econId:'box-contact-economic',regId:'box-contact-reg',nationalLabelId:'label-contact-national'});}
1256 -function handleQuickCEntityChange(){const el=document.getElementById('quick-c-entity');if(!el)return;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'});}
1257 -function handleInvoiceKindChange(){
1258 - const kind=document.getElementById('invoice-kind').value;
1259 - const vatModeRow=document.getElementById('box-invoice-vat-mode-row');
1260 - const vatModeSelect=document.getElementById('invoice-vat-mode');
1261 - if(kind==='non_formal'){
1262 - if(vatModeRow)vatModeRow.style.display='none';
1263 - if(vatModeSelect)vatModeSelect.value='none';
1264 - }else{
1265 - if(vatModeRow)vatModeRow.style.display='flex';
1266 - }
1267 - const boxEdoc=document.getElementById('box-enable-electronic-doc');
1268 - if(boxEdoc){
1269 - if(kind==='formal'){
1270 - boxEdoc.style.display='block';
1271 - }else{
1272 - boxEdoc.style.display='none';
1273 - const cb=document.getElementById('enable-electronic-doc');
1274 - if(cb)cb.checked=false;
1275 - window.pendingElectronicDoc=null;
1276 - const st=document.getElementById('edoc-status');
1277 - if(st)st.innerText='';
1278 - }
1279 - }
1280 - handleVatModeChange();
1281 - recomputeTotals();
1282 -}
1283 -function handleVatModeChange(){
1284 - const mode=document.getElementById('invoice-vat-mode').value;
1285 - const kind=document.getElementById('invoice-kind').value;
1286 - const rateBox=document.getElementById('box-invoice-vat-rate');
1287 - if(kind==='non_formal'){rateBox.style.display='none';document.getElementById('invoice-vat-mode').value='none';}
1288 - else{rateBox.style.display=(mode==='with_vat')?'flex':'none';}
1289 - recomputeTotals();
1290 -}
1291 -function handleVatTypeChange(){const type=document.getElementById('invoice-vat-type').value;document.getElementById('invoice-vat-rate-input').value=(type==='percent')?10:0;recomputeTotals();}
1292 -function handleDiscountTypeChange(){
1293 - const type=document.getElementById('invoice-discount-type').value;
1294 - const label=document.getElementById('label-invoice-discount-value');
1295 - const cur=getCurrencyLabel();
1296 - label.innerText=(type==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${cur})`;
1297 - document.getElementById('invoice-discount-fixed').value=0;
1298 - recomputeTotals();
1299 -}
1300 -function applyDefaultSettingsToForm(){
1301 - const def=getMySettings();
1302 - const defKind=document.getElementById('def-invoice-kind');
1303 - const defVat=document.getElementById('def-vat-mode');
1304 - const defRate=document.getElementById('def-vat-rate');
1305 - const defCurMode=document.getElementById('def-currency-mode');
1306 - const defCurCustom=document.getElementById('def-currency-custom');
1307 - if(defKind)defKind.value=def.invoice_kind||'non_formal';
1308 - if(defVat)defVat.value=def.vat_mode||'none';
1309 - if(defRate)defRate.value=def.vat_rate||10;
1310 - if(defCurMode)defCurMode.value=def.currency_mode||'rial';
1311 - if(defCurCustom)defCurCustom.value=def.currency_custom||'';
1312 - handleCurrencyModeChange();
1313 - const editId=document.getElementById('edit-invoice-id')?.value;
1314 - if(!editId){
1315 - const kindEl=document.getElementById('invoice-kind');
1316 - if(kindEl)kindEl.value=def.invoice_kind||'non_formal';
1317 - handleInvoiceKindChange();
1318 - if((def.invoice_kind||'non_formal')!=='non_formal'){
1319 - document.getElementById('invoice-vat-mode').value=def.vat_mode||'none';
1320 - document.getElementById('invoice-vat-rate-input').value=def.vat_rate||10;
1321 - handleVatModeChange();
1322 - }
1323 - }
1324 -}
1325 -function commitSaveDefaultSettings(){
1326 - if(!requireWrite())return;
1327 - const s=getMySettings();
1328 - s.invoice_kind=document.getElementById('def-invoice-kind').value;
1329 - s.vat_mode=document.getElementById('def-vat-mode').value;
1330 - s.vat_rate=parseFloat(document.getElementById('def-vat-rate').value)||0;
1331 - s.currency_mode=document.getElementById('def-currency-mode').value;
1332 - s.currency_custom=document.getElementById('def-currency-custom').value||'';
1333 - saveDatastore();
1334 - refreshCurrencyLabels();
1335 - alert('پیش‌فرض‌ها ذخیره شد.');
1336 -}
1337 -function renderDashboard(){
1338 - let salesSum=0;let debtorsSum=0;
1339 - const myInvoices=getMyInvoices();
1340 - const myCheques=getMyCheques();
1341 - const myCompanies=getMyCompanies();
1342 - const mySettings=getMySettings();
1343 - const activeCompId=mySettings.default_company_id||document.getElementById('invoice-company-id')?.value||(myCompanies[0]?.id);
1344 - const filteredInvoices=activeCompId?myInvoices.filter(inv=>inv.companyId===activeCompId):myInvoices;
1345 - const cur=getCurrencyLabel();
1346 - filteredInvoices.forEach(inv=>{salesSum+=inv.grandTotal;if(inv.paymentMethod==='credit')debtorsSum+=inv.grandTotal;});
1347 - const salesEl=document.getElementById('kpi-sales-sum');
1348 - const settledEl=document.getElementById('kpi-settled-sum');
1349 - const debtorsEl=document.getElementById('kpi-debtors-sum');
1350 - const chequesEl=document.getElementById('kpi-cheques-count');
1351 - if(salesEl)salesEl.innerText=salesSum.toLocaleString('fa-IR')+' '+cur;
1352 - if(settledEl)settledEl.innerText=(salesSum-debtorsSum).toLocaleString('fa-IR')+' '+cur;
1353 - if(debtorsEl)debtorsEl.innerText=debtorsSum.toLocaleString('fa-IR')+' '+cur;
1354 - if(chequesEl)chequesEl.innerText=myCheques.filter(c=>c.status==='registered').length.toLocaleString('fa-IR')+' فقره';
1355 - const recentTbody=document.getElementById('dashboard-recent-table');
1356 - if(recentTbody){
1357 - if(filteredInvoices.length===0){recentTbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr>';return;}
1358 - recentTbody.innerHTML=filteredInvoices.slice(-5).reverse().map(inv=>`
1359 - <tr>
1360 - <td><strong>#${esc(inv.number)}</strong></td>
1361 - <td>${esc(inv.companyName||'—')}</td>
1362 - <td>${esc(inv.contactName)}</td>
1363 - <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${esc(inv.kindLabel)}</span></td>
1364 - <td>${inv.vat>0?'با ارزش افزوده':'بدون مالیات'}</td>
1365 - <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1366 - <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px;font-size:12px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
1367 - </tr>`).join('');
1368 - }
1369 -}
1370 -function onActiveCompanyFilterChange(){
1371 - const activeCompId=document.getElementById('invoice-company-id').value;
1372 - const filterSelect=document.getElementById('filter-invoice-company');
1373 - if(filterSelect)filterSelect.value=activeCompId;
1374 - renderInvoices();renderDashboard();
1375 -}
1376 -function startNewInvoice(){cancelInvoiceEdit();switchView('view-invoices');}
1377 -function updateInvoiceItemRowNumbers(){
1378 - const rows=document.querySelectorAll('#invoice-items-table-body tr');
1379 - rows.forEach((tr,index)=>{const numCell=tr.querySelector('.row-item-number');if(numCell)numCell.innerText=(index+1).toLocaleString('fa-IR');});
1380 -}
1381 -function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
1382 - const tbody=document.getElementById('invoice-items-table-body');
1383 - const rowKey='item_'+Date.now()+'_'+Math.random().toString(36).substr(2,4);
1384 - const tr=document.createElement('tr');
1385 - tr.id=rowKey;
1386 - const myProducts=getMyProducts();
1387 - const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${esc(p.sale_price)}" data-unit="${esc(p.unit||'عدد')}" ${p.id===selectedProdId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
1388 - tr.innerHTML=`
1389 - <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
1390 - <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
1391 - <td style="width:90px"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center" /></td>
1392 - <td style="width:100px"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center" /></td>
1393 - <td style="width:160px"><input type="number" class="form-control row-price" value="${initialPrice!==null?initialPrice:0}" oninput="recomputeTotals()" style="text-align:left" /></td>
1394 - <td class="row-linetotal" style="width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr">۰</td>
1395 - <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>`;
1396 - tbody.appendChild(tr);
1397 - updateInvoiceItemRowNumbers();
1398 - if(selectedProdId&&initialPrice===null)onRowProductChange(rowKey);
1399 - else recomputeTotals();
1400 -}
1401 -function onRowProductChange(rowKey){
1402 - const tr=document.getElementById(rowKey);if(!tr)return;
1403 - const sel=tr.querySelector('.row-product-select');
1404 - const opt=sel.options[sel.selectedIndex];
1405 - const prc=opt?.getAttribute('data-price')||0;
1406 - const unt=opt?.getAttribute('data-unit');
1407 - tr.querySelector('.row-price').value=prc;
1408 - if(unt){const unitInput=tr.querySelector('.row-unit-input');if(unitInput)unitInput.value=unt;}
1409 - recomputeTotals();
1410 -}
1411 -function recomputeTotals(){
1412 - let subtotal=0;
1413 - document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
1414 - const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
1415 - const prc=parseFloat(tr.querySelector('.row-price')?.value)||0;
1416 - const line=qty*prc;
1417 - const lineEl=tr.querySelector('.row-linetotal');
1418 - if(lineEl)lineEl.innerText=line.toLocaleString('fa-IR');
1419 - subtotal+=line;
1420 - });
1421 - const discountType=document.getElementById('invoice-discount-type')?.value||'fixed';
1422 - const discountInput=parseFloat(document.getElementById('invoice-discount-fixed')?.value)||0;
1423 - const rawDiscount=(discountType==='percent')?Math.round(subtotal*(discountInput/100)):discountInput;
1424 - const fixedDiscount=Math.max(0,Math.min(rawDiscount,subtotal));
1425 - const kind=document.getElementById('invoice-kind')?.value||'non_formal';
1426 - const vatMode=(kind==='non_formal')?'none':(document.getElementById('invoice-vat-mode')?.value||'none');
1427 - const vatType=document.getElementById('invoice-vat-type')?.value||'percent';
1428 - const vatRate=parseFloat(document.getElementById('invoice-vat-rate-input')?.value)||0;
1429 - const afterDiscount=Math.max(0,subtotal-fixedDiscount);
1430 - let vatAmount=0;
1431 - if(vatMode==='with_vat'){vatAmount=(vatType==='fixed')?Math.max(0,Math.round(vatRate)):Math.round(afterDiscount*(vatRate/100));}
1432 - const grandTotal=afterDiscount+vatAmount;
1433 - const cur=getCurrencyLabel();
1434 - const subtotalEl=document.getElementById('summary-subtotal');
1435 - const vatEl=document.getElementById('summary-vat');
1436 - const grandEl=document.getElementById('summary-grandtotal');
1437 - const wordsEl=document.getElementById('summary-words');
1438 - if(subtotalEl)subtotalEl.innerText=subtotal.toLocaleString('fa-IR')+' '+cur;
1439 - if(vatEl)vatEl.innerText=vatAmount.toLocaleString('fa-IR')+' '+cur;
1440 - if(grandEl)grandEl.innerText=grandTotal.toLocaleString('fa-IR')+' '+cur;
1441 - if(wordsEl)wordsEl.innerText='به حروف: '+numberToPersianWords(grandTotal,cur);
1442 - return {subtotal,fixedDiscount,discountType,discountInput,vatAmount,vatType,grandTotal,vatRate};
1443 -}
1444 -
1445 -// ================== سند الکترونیکی سامانه مودیان ==================
1446 -function toggleElectronicDoc(){
1447 - const checked=document.getElementById('enable-electronic-doc').checked;
1448 - if(checked){
1449 - openElectronicDocModal();
1450 - }else{
1451 - window.pendingElectronicDoc=null;
1452 - document.getElementById('edoc-status').innerText='';
1453 - }
1454 -}
1455 -function openElectronicDocModal(){
1456 - const itemsContainer=document.getElementById('edoc-items-container');
1457 - const rows=document.querySelectorAll('#invoice-items-table-body tr');
1458 - let html='';
1459 - if(rows.length===0){
1460 - html='<p style="color:var(--text-muted);font-size:12.5px;padding:8px">ابتدا اقلام فاکتور را اضافه کنید.</p>';
1461 - }else{
1462 - rows.forEach((tr,idx)=>{
1463 - const sel=tr.querySelector('.row-product-select');
1464 - const prodId=sel?sel.value:'';
1465 - const prod=getMyProducts().find(p=>p.id===prodId)||{};
1466 - const prodName=sel&&sel.options[sel.selectedIndex]?sel.options[sel.selectedIndex].text:'';
1467 - html+=`<div style="border:1px solid var(--border);border-radius:8px;padding:10px;margin-bottom:8px;background:#f8fafc">
1468 - <div style="font-weight:bold;font-size:13px;margin-bottom:8px">ردیف ${toPersianDigits(idx+1)}: ${prodName||'—'}</div>
1469 - <div class="form-row">
1470 - <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت داخلی</label><input type="text" class="form-control edoc-row-internal" data-row="${idx}" value="${esc(prod.internal_id||'')}" /></div>
1471 - <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت <span style="color:var(--danger)">*</span></label><input type="text" class="form-control edoc-row-official" data-row="${idx}" value="" /></div>
1472 - </div>
1473 - </div>`;
1474 - });
1475 - }
1476 - itemsContainer.innerHTML=html;
1477 -
1478 - const p=window.pendingElectronicDoc;
1479 - if(p){
1480 - document.getElementById('edoc-unique-number').value=p.uniqueNumber||'';
1481 - document.getElementById('edoc-tax-number').value=p.taxNumber||'';
1482 - document.getElementById('edoc-issue-datetime').value=p.issueDateTime||'';
1483 - document.getElementById('edoc-original-date').value=p.originalDate||'';
1484 - document.getElementById('edoc-original-number').value=p.originalNumber||'';
1485 - document.getElementById('edoc-kind').value=p.kind||'اصل';
1486 - document.getElementById('edoc-pattern').value=p.pattern||'کالا';
1487 - document.getElementById('edoc-contract-id').value=p.contractId||'';
1488 - if(p.items){
1489 - p.items.forEach((it,idx)=>{
1490 - const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
1491 - const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
1492 - if(intEl)intEl.value=it.internalId||'';
1493 - if(offEl)offEl.value=it.officialId||'';
1494 - });
1495 - }
1496 - }else{
1497 - const now=new Date();
1498 - const timeStr=now.getHours().toString().padStart(2,'0')+':'+now.getMinutes().toString().padStart(2,'0')+':00';
1499 - document.getElementById('edoc-issue-datetime').value=getJalaliNumeric()+' '+timeStr;
1500 - document.getElementById('edoc-original-date').value='';
1501 - document.getElementById('edoc-original-number').value='';
1502 - document.getElementById('edoc-unique-number').value='';
1503 - document.getElementById('edoc-tax-number').value='';
1504 - document.getElementById('edoc-kind').value='اصل';
1505 - document.getElementById('edoc-pattern').value='کالا';
1506 - document.getElementById('edoc-contract-id').value='';
1507 - }
1508 - handleEdocPatternChange();
1509 - document.getElementById('modal-electronic-doc').classList.add('active');
1510 -}
1511 -function closeElectronicDocModal(){
1512 - document.getElementById('modal-electronic-doc').classList.remove('active');
1513 -}
1514 -function cancelElectronicDoc(){
1515 - document.getElementById('enable-electronic-doc').checked=false;
1516 - window.pendingElectronicDoc=null;
1517 - document.getElementById('edoc-status').innerText='';
1518 - closeElectronicDocModal();
1519 -}
1520 -function handleEdocPatternChange(){
1521 - const pattern=document.getElementById('edoc-pattern').value;
1522 - const box=document.getElementById('box-edoc-contract');
1523 - const hint=document.getElementById('edoc-contract-hint');
1524 - if(pattern==='پیمانکاری'){
1525 - box.style.display='block';
1526 - hint.style.display='none';
1527 - }else{
1528 - box.style.display='none';
1529 - hint.style.display='block';
1530 - }
1531 -}
1532 -function saveElectronicDocToPending(){
1533 - const pattern=document.getElementById('edoc-pattern').value;
1534 - const contractId=document.getElementById('edoc-contract-id').value.trim();
1535 - if(pattern==='پیمانکاری'&&!contractId){
1536 - alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
1537 - return;
1538 - }
1539 - const items=[];
1540 - const rows=document.querySelectorAll('#invoice-items-table-body tr');
1541 - for(let idx=0;idx<rows.length;idx++){
1542 - const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
1543 - const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
1544 - const offVal=offEl?offEl.value.trim():'';
1545 - if(!offVal){
1546 - alert(`«شناسه کالا/خدمت» برای ردیف ${toPersianDigits(idx+1)} اجباری است.`);
1547 - return;
1548 - }
1549 - items.push({internalId:intEl?intEl.value.trim():'',officialId:offVal});
1550 - }
1551 - const p={
1552 - uniqueNumber:document.getElementById('edoc-unique-number').value.trim(),
1553 - taxNumber:document.getElementById('edoc-tax-number').value.trim(),
1554 - issueDateTime:document.getElementById('edoc-issue-datetime').value.trim(),
1555 - originalDate:document.getElementById('edoc-original-date').value.trim(),
1556 - originalNumber:document.getElementById('edoc-original-number').value.trim(),
1557 - kind:document.getElementById('edoc-kind').value,
1558 - pattern:pattern,
1559 - contractId:contractId,
1560 - items:items
1561 - };
1562 - window.pendingElectronicDoc=p;
1563 - document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی ذخیره شد. با ثبت فاکتور، سند نیز ذخیره می‌شود.';
1564 - closeElectronicDocModal();
1565 -}
1566 -
1567 -function commitSaveInvoice(){
1568 - if(!requireWrite())return;
1569 - if(!currentUser)return;
1570 - const myCompanies=getMyCompanies();
1571 - const mySettings=getMySettings();
1572 - const companySelect=document.getElementById('invoice-company-id');
1573 - const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;
1574 - const sellerCompany=myCompanies.find(c=>c.id===selectedCompanyId)||myCompanies.find(c=>c.id===mySettings.default_company_id)||myCompanies[0];
1575 - if(!sellerCompany){alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');return;}
1576 - const companyId=sellerCompany.id;
1577 - const companyName=sellerCompany.name;
1578 - const contactSelect=document.getElementById('invoice-contact-id');
1579 - const contactId=contactSelect?contactSelect.value:'';
1580 - const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
1581 - const number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
1582 - const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
1583 - const kind=document.getElementById('invoice-kind')?.value||'non_formal';
1584 - const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
1585 - const editId=document.getElementById('edit-invoice-id')?.value;
1586 - if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
1587 - const items=[];
1588 - document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
1589 - const sel=tr.querySelector('.row-product-select');
1590 - const prodId=sel?sel.value:'';
1591 - const prodName=sel?sel.options[sel.selectedIndex]?.text:'';
1592 - const unit=tr.querySelector('.row-unit-input')?.value||'عدد';
1593 - const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
1594 - const price=parseFloat(tr.querySelector('.row-price')?.value)||0;
1595 - if(prodId&&qty>0){items.push({prodId,prodName,unit,qty,price,lineTotal:qty*price});}
1596 - });
1597 - if(items.length===0){alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');return;}
1598 -
1599 - // بررسی سند الکترونیکی
1600 - let edoc=null;
1601 - if(kind==='formal'){
1602 - const cb=document.getElementById('enable-electronic-doc');
1603 - if(cb&&cb.checked){
1604 - if(!window.pendingElectronicDoc){
1605 - alert('برای صدور سند الکترونیکی، ابتدا باید اطلاعات سند را تکمیل و ذخیره کنید.');
1606 - return;
1607 - }
1608 - edoc=window.pendingElectronicDoc;
1609 - if(edoc.pattern==='پیمانکاری'&&!edoc.contractId){
1610 - alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
1611 - return;
1612 - }
1613 - }
1614 - }
1615 -
1616 - const totals=recomputeTotals();
1617 - const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور'};
1618 - const cur=getCurrencyLabel();
1619 - if(editId){
1620 - const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
1621 - if(existingIndex!==-1){
1622 - const prev=datastore.invoices[existingIndex];
1623 - const finalEdoc=edoc?edoc:(prev.electronicDoc||null);
1624 - datastore.invoices[existingIndex]={...prev,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,electronicDoc:finalEdoc};
1625 - alert('فاکتور با موفقیت ویرایش شد.');
1626 - }
1627 - cancelInvoiceEdit();
1628 - }else{
1629 - 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,electronicDoc:edoc};
1630 - datastore.invoices.push(record);
1631 - alert('فاکتور با موفقیت ثبت شد.');
1632 - cancelInvoiceEdit();
1633 - renderAndPrintDirect(record.id);
1634 - }
1635 - window.pendingElectronicDoc=null;
1636 - saveDatastore();
1637 - refreshAllSurfaces();
1638 -}
1639 -function editInvoice(invId){
1640 - const inv=getMyInvoices().find(i=>i.id===invId);
1641 - if(!inv)return;
1642 - switchView('view-invoices');
1643 - document.getElementById('edit-invoice-id').value=inv.id;
1644 - document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
1645 - document.getElementById('btn-cancel-edit').style.display='inline-flex';
1646 - document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
1647 - document.getElementById('invoice-company-id').value=inv.companyId;
1648 - document.getElementById('invoice-kind').value=inv.kind;
1649 - document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
1650 - document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
1651 - document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
1652 - document.getElementById('invoice-number').value=inv.number;
1653 - document.getElementById('invoice-contact-id').value=inv.contactId;
1654 - document.getElementById('invoice-date-input').value=inv.date;
1655 - document.getElementById('invoice-discount-type').value=inv.discountType||'fixed';
1656 - document.getElementById('label-invoice-discount-value').innerText=(inv.discountType==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${getCurrencyLabel()})`;
1657 - document.getElementById('invoice-discount-fixed').value=(inv.discountType==='percent')?(inv.discountInput||0):(inv.discount||0);
1658 - document.getElementById('invoice-desc-input').value=inv.description||'';
1659 - handleInvoiceKindChange();
1660 - // بارگذاری سند الکترونیکی در صورت وجود
1661 - window.pendingElectronicDoc=inv.electronicDoc||null;
1662 - const cb=document.getElementById('enable-electronic-doc');
1663 - if(cb){
1664 - if(inv.kind==='formal'&&inv.electronicDoc){
1665 - cb.checked=true;
1666 - document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی قبلاً ذخیره شده است.';
1667 - }else{
1668 - cb.checked=false;
1669 - document.getElementById('edoc-status').innerText='';
1670 - }
1671 - }
1672 - const tbody=document.getElementById('invoice-items-table-body');
1673 - tbody.innerHTML='';
1674 - inv.items.forEach(it=>{
1675 - addInvoiceItemRow(it.prodId,it.qty,it.price);
1676 - const lastRow=tbody.lastElementChild;
1677 - if(lastRow)lastRow.querySelector('.row-unit-input').value=it.unit||'عدد';
1678 - });
1679 - updateInvoiceItemRowNumbers();
1680 - recomputeTotals();
1681 -}
1682 -function cancelInvoiceEdit(){
1683 - document.getElementById('edit-invoice-id').value='';
1684 - document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
1685 - document.getElementById('btn-cancel-edit').style.display='none';
1686 - document.getElementById('btn-save-invoice').innerText='💾 ثبت فاکتور';
1687 - document.getElementById('invoice-items-table-body').innerHTML='';
1688 - document.getElementById('invoice-number').value='';
1689 - document.getElementById('invoice-discount-type').value='fixed';
1690 - document.getElementById('label-invoice-discount-value').innerText=`مبلغ تخفیف (${getCurrencyLabel()})`;
1691 - document.getElementById('invoice-discount-fixed').value=0;
1692 - document.getElementById('invoice-vat-type').value='percent';
1693 - document.getElementById('invoice-desc-input').value='';
1694 - window.pendingElectronicDoc=null;
1695 - const cb=document.getElementById('enable-electronic-doc');
1696 - if(cb)cb.checked=false;
1697 - const st=document.getElementById('edoc-status');
1698 - if(st)st.innerText='';
1699 - addInvoiceItemRow();
1700 - applyDefaultSettingsToForm();
1701 -}
1702 -function renderInvoices(){
1703 - const tbody=document.getElementById('invoice-archive-table-body');
1704 - const filterSelect=document.getElementById('filter-invoice-company');
1705 - const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
1706 - let list=getMyInvoices();
1707 - if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
1708 - if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
1709 - tbody.innerHTML=list.map(inv=>`
1710 - <tr>
1711 - <td><strong>#${esc(inv.number)}</strong></td>
1712 - <td>${esc(inv.companyName||'—')}</td>
1713 - <td>${esc(inv.contactName)}</td>
1714 - <td><span class="badge ${inv.kind==='formal'?'badge-danger':'badge-success'}">${esc(inv.kindLabel)}</span></td>
1715 - <td>${esc(inv.date)}</td>
1716 - <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
1717 - <td>
1718 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
1719 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
1720 - ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
1721 - </td>
1722 - </tr>`).join('');
1723 -}
1724 -
1725 -// ============== ساخت سند الکترونیکی ==============
1726 -function buildTaxLogo(){
1727 - return `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:80px;height:80px">
1728 - <circle cx="50" cy="50" r="46" fill="none" stroke="#1e3a8a" stroke-width="1.5"/>
1729 - <circle cx="50" cy="50" r="38" fill="none" stroke="#1e3a8a" stroke-width="1"/>
1730 - <rect x="30" y="32" width="4" height="36" fill="#1e3a8a"/>
1731 - <rect x="40" y="26" width="4" height="42" fill="#1e3a8a"/>
1732 - <rect x="50" y="22" width="4" height="46" fill="#1e3a8a"/>
1733 - <rect x="60" y="26" width="4" height="42" fill="#1e3a8a"/>
1734 - <rect x="70" y="32" width="4" height="36" fill="#1e3a8a"/>
1735 - <rect x="26" y="20" width="52" height="5" fill="#1e3a8a" rx="1"/>
1736 - <rect x="28" y="66" width="48" height="4" fill="#1e3a8a" rx="1"/>
1737 - <rect x="24" y="72" width="56" height="4" fill="#1e3a8a" rx="1"/>
1738 - </svg>`;
1739 -}
1740 -function buildElectronicDocPage(inv,edoc,seller,contact){
1741 - const cur='ریال';
1742 - const items=inv.items;
1743 - const vatRate=(inv.vatRate!==undefined&&inv.vatType!=='fixed')?inv.vatRate:10;
1744 -
1745 - const itemsRows=items.map((it,idx)=>{
1746 - const line=it.lineTotal;
1747 - const rowVatRate=(inv.vat>0)?vatRate:0;
1748 - const vat=Math.round(line*rowVatRate/100);
1749 - const total=line+vat;
1750 - const edItem=(edoc.items&&edoc.items[idx])?edoc.items[idx]:{};
1751 - return `<tr>
1752 - <td style="border:1px solid #000;padding:4px;text-align:center">${toPersianDigits(idx+1)}</td>
1753 - <td style="border:1px solid #000;padding:4px">${esc(it.prodName||'')}</td>
1754 - <td style="border:1px solid #000;padding:4px;text-align:center">${toPersianDigits(it.qty)}</td>
1755 - <td style="border:1px solid #000;padding:4px;text-align:center">${esc(it.unit||'')}</td>
1756 - <td style="border:1px solid #000;padding:4px;text-align:left">${it.price.toLocaleString('fa-IR')}</td>
1757 - <td style="border:1px solid #000;padding:4px;text-align:left">${line.toLocaleString('fa-IR')}</td>
1758 - <td style="border:1px solid #000;padding:4px;text-align:center">${toPersianDigits(rowVatRate)}٪</td>
1759 - <td style="border:1px solid #000;padding:4px;text-align:left">${vat.toLocaleString('fa-IR')}</td>
1760 - <td style="border:1px solid #000;padding:4px;text-align:left">${total.toLocaleString('fa-IR')}</td>
1761 - <td style="border:1px solid #000;padding:4px;text-align:center">${esc(edItem.internalId||'')}</td>
1762 - <td style="border:1px solid #000;padding:4px;text-align:center">${esc(edItem.officialId||'')}</td>
1763 - </tr>`;
1764 - }).join('');
1765 -
1766 - let contractText='';
1767 - if(edoc.pattern==='پیمانکاری'&&edoc.contractId){
1768 - contractText=items.map((it,idx)=>
1769 - `+ شناسه یکتای ثبت قرارداد حق‌العمل‌کاری برای ردیف ${toPersianDigits(idx+1)}: ${esc(edoc.contractId)} است`
1770 - ).join('<br>');
1771 - }
1772 -
1773 - const grandTotal=inv.grandTotal||0;
1774 - const vatTotal=inv.vat||0;
1775 - const baseTotal=grandTotal-vatTotal;
1776 -
1777 - return `<div class="invoice-a4-page landscape" style="background:#fff;padding:6mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif;position:relative">
1778 - <table style="width:100%;border-collapse:collapse;margin-bottom:4px">
1779 - <tr>
1780 - <td style="width:20%;vertical-align:top;text-align:center;padding:4px">${buildTaxLogo()}<div style="font-size:9px;color:#1e3a8a;margin-top:2px">سازمان امور مالیاتی</div></td>
1781 - <td style="width:60%;text-align:center;vertical-align:middle;padding:6px">
1782 - <div style="font-size:14px;font-weight:bold;color:#1e3a8a">صورتحساب الکترونیکی فروش کالا / خدمات</div>
1783 - <div style="font-size:9.5px;color:#475569;margin-top:2px">(مطابق استاندارد سامانه مودیان)</div>
1784 - </td>
1785 - <td style="width:20%;vertical-align:top;padding:4px;font-size:9.5px;text-align:left">
1786 - <div>${esc(seller.name||'')}</div>
1787 - <div style="color:#475569">${esc(seller.phone||'')}</div>
1788 - </td>
1789 - </tr>
1790 - </table>
1791 -
1792 - <table style="width:100%;border-collapse:collapse;border:1px solid #000;font-size:10px;margin-bottom:4px">
1793 - <tr>
1794 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9;width:30%"><strong>شماره منحصر به فرد صورتحساب الکترونیکی مالیاتی</strong></td>
1795 - <td style="border:1px solid #000;padding:4px;width:70%">${esc(edoc.uniqueNumber||'—')}</td>
1796 - </tr>
1797 - <tr>
1798 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>شماره مالیاتی مندرج در برگه تشخیص</strong></td>
1799 - <td style="border:1px solid #000;padding:4px">${esc(edoc.taxNumber||'—')}</td>
1800 - </tr>
1801 - <tr>
1802 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>تاریخ و زمان صدور صورتحساب الکترونیکی</strong></td>
1803 - <td style="border:1px solid #000;padding:4px">${esc(edoc.issueDateTime||'—')}</td>
1804 - </tr>
1805 - <tr>
1806 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>تاریخ صورتحساب الکترونیکی اصلی</strong></td>
1807 - <td style="border:1px solid #000;padding:4px">${esc(edoc.originalDate||'—')}</td>
1808 - </tr>
1809 - <tr>
1810 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>شماره صورتحساب الکترونیکی اصلی</strong></td>
1811 - <td style="border:1px solid #000;padding:4px">${esc(edoc.originalNumber||'—')}</td>
1812 - </tr>
1813 - <tr>
1814 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>نوع صورتحساب</strong></td>
1815 - <td style="border:1px solid #000;padding:4px">${esc(edoc.kind||'—')}</td>
1816 - </tr>
1817 - <tr>
1818 - <td style="border:1px solid #000;padding:4px;background:#f1f5f9"><strong>موضوع صورتحساب</strong></td>
1819 - <td style="border:1px solid #000;padding:4px">${esc(edoc.pattern||'—')}</td>
1820 - </tr>
1821 - </table>
1822 -
1823 - <table style="width:100%;border-collapse:collapse;border:1px solid #000;font-size:10px;margin-bottom:4px">
1824 - <tr><td colspan="4" style="border:1px solid #000;padding:4px;background:#f1f5f9;font-weight:bold">مشخصات فروشنده</td></tr>
1825 - <tr>
1826 - <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">نام شخص</td>
1827 - <td style="border:1px solid #000;padding:4px;width:35%">${esc(seller.name||'—')}</td>
1828 - <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">شماره اقتصادی فروشنده</td>
1829 - <td style="border:1px solid #000;padding:4px;width:35%">${esc(seller.economic_code||'0000')}</td>
1830 - </tr>
1831 - <tr>
1832 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">شماره ثبت / شناسه ملی</td>
1833 - <td style="border:1px solid #000;padding:4px">${esc(seller.national_id||'—')}</td>
1834 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">کد پستی</td>
1835 - <td style="border:1px solid #000;padding:4px">${esc(seller.postal_code||'—')}</td>
1836 - </tr>
1837 - </table>
1838 -
1839 - <table style="width:100%;border-collapse:collapse;border:1px solid #000;font-size:10px;margin-bottom:4px">
1840 - <tr><td colspan="4" style="border:1px solid #000;padding:4px;background:#f1f5f9;font-weight:bold">مشخصات خریدار</td></tr>
1841 - <tr>
1842 - <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">نام شخص</td>
1843 - <td style="border:1px solid #000;padding:4px;width:35%">${esc(contact.name||inv.contactName)}</td>
1844 - <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:15%">شماره اقتصادی خریدار</td>
1845 - <td style="border:1px solid #000;padding:4px;width:35%">${esc(contact.economic_code||'0000')}</td>
1846 - </tr>
1847 - <tr>
1848 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">شماره ثبت / شناسه ملی</td>
1849 - <td style="border:1px solid #000;padding:4px">${esc(contact.national_id||'—')}</td>
1850 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">کد پستی</td>
1851 - <td style="border:1px solid #000;padding:4px">${esc(contact.postal_code||'—')}</td>
1852 - </tr>
1853 - </table>
1854 -
1855 - <table style="width:100%;border-collapse:collapse;border:1px solid #000;font-size:9.5px">
1856 - <thead>
1857 - <tr style="background:#f1f5f9;font-weight:bold;text-align:center">
1858 - <th style="border:1px solid #000;padding:4px" rowspan="2">ردیف</th>
1859 - <th style="border:1px solid #000;padding:4px" rowspan="2">شرح کالا/خدمت</th>
1860 - <th style="border:1px solid #000;padding:4px" rowspan="2">تعداد/مقدار</th>
1861 - <th style="border:1px solid #000;padding:4px" rowspan="2">واحد اندازه‌گیری</th>
1862 - <th style="border:1px solid #000;padding:4px" rowspan="2">مبلغ واحد (ریال)</th>
1863 - <th style="border:1px solid #000;padding:4px" rowspan="2">مبلغ کل (ریال)</th>
1864 - <th style="border:1px solid #000;padding:4px" colspan="3">مالیات بر ارزش افزوده</th>
1865 - <th style="border:1px solid #000;padding:4px" rowspan="2">شناسه کالا/خدمت داخلی</th>
1866 - <th style="border:1px solid #000;padding:4px" rowspan="2">شناسه کالا/خدمت</th>
1867 - </tr>
1868 - <tr style="background:#f1f5f9;font-weight:bold;text-align:center">
1869 - <th style="border:1px solid #000;padding:4px">نرخ</th>
1870 - <th style="border:1px solid #000;padding:4px">مبلغ</th>
1871 - <th style="border:1px solid #000;padding:4px">مبلغ کل کالا/خدمت</th>
1872 - </tr>
1873 - </thead>
1874 - <tbody>${itemsRows}</tbody>
1875 - </table>
1876 -
1877 - <table style="width:100%;border-collapse:collapse;border:1px solid #000;font-size:10px;margin-top:6px">
1878 - <tr>
1879 - <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:25%">جمع کل مبلغ کالا/خدمت</td>
1880 - <td style="border:1px solid #000;padding:4px;width:25%;text-align:left">${baseTotal.toLocaleString('fa-IR')} ${cur}</td>
1881 - <td style="border:1px solid #000;padding:4px;background:#f8fafc;width:25%">جمع کل مالیات بر ارزش افزوده</td>
1882 - <td style="border:1px solid #000;padding:4px;width:25%;text-align:left">${vatTotal.toLocaleString('fa-IR')} ${cur}</td>
1883 - </tr>
1884 - <tr>
1885 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">مبلغ کل صورتحساب</td>
1886 - <td style="border:1px solid #000;padding:4px;text-align:left;font-weight:bold" colspan="3">${grandTotal.toLocaleString('fa-IR')} ${cur}</td>
1887 - </tr>
1888 - <tr>
1889 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">مصرف‌کننده نهایی</td>
1890 - <td style="border:1px solid #000;padding:4px">خیر</td>
1891 - <td style="border:1px solid #000;padding:4px;background:#f8fafc">مالیات موضوع ماده ۱۷</td>
1892 - <td style="border:1px solid #000;padding:4px;text-align:left">۰ ${cur}</td>
1893 - </tr>
1894 - </table>
1895 -
1896 - ${contractText?`<div style="border:1px solid #000;padding:6px;margin-top:6px;font-size:10.5px;line-height:1.7;background:#fffbeb">${contractText}</div>`:''}
1897 -
1898 - <table style="width:100%;border-collapse:collapse;margin-top:8px;font-size:10.5px">
1899 - <tr>
1900 - <td style="width:50%;border:1px solid #000;padding:8px;height:70px;vertical-align:top">
1901 - <div style="font-weight:bold;margin-bottom:4px">مهر و امضای فروشنده</div>
1902 - <div style="font-size:9.5px;color:#475569">${esc(seller.name||'')}</div>
1903 - </td>
1904 - <td style="width:50%;border:1px solid #000;padding:8px;height:70px;vertical-align:top">
1905 - <div style="font-weight:bold;margin-bottom:4px">مهر و امضای خریدار</div>
1906 - <div style="font-size:9.5px;color:#475569">${esc(contact.name||inv.contactName)}</div>
1907 - </td>
1908 - </tr>
1909 - </table>
1910 - </div>`;
1911 -}
1912 -
1913 -function printElectronicDoc(invId){
1914 - const inv=getMyInvoices().find(i=>i.id===invId);
1915 - if(!inv||!inv.electronicDoc){
1916 - alert('سند الکترونیکی برای این فاکتور ثبت نشده است.');
1917 - return;
1918 - }
1919 - const myCompanies=getMyCompanies();
1920 - const myContacts=getMyContacts();
1921 - const seller=myCompanies.find(c=>c.id===inv.companyId)||myCompanies[0]||{};
1922 - const contact=myContacts.find(c=>c.id===inv.contactId)||{};
1923 - const html=buildElectronicDocPage(inv,inv.electronicDoc,seller,contact);
1924 - let orientationStyle=document.getElementById('dynamic-print-orientation');
1925 - if(!orientationStyle){orientationStyle=document.createElement('style');orientationStyle.id='dynamic-print-orientation';document.head.appendChild(orientationStyle);}
1926 - orientationStyle.innerHTML=`@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
1927 - const printContainer=document.getElementById('printable-invoice');
1928 - printContainer.innerHTML=html;
1929 - printContainer.style.display='block';
1930 - window.print();
1931 - printContainer.style.display='none';
1932 -}
1933 -
1934 -// ============ فاکتورهای معمول ============
1935 -const MAX_ROWS_PER_PAGE=10;
1936 -function computeInvoiceLines(inv){
1937 - const n=inv.items.length;
1938 - const afterDiscountTotal=Math.max(0,(inv.subtotal||0)-(inv.discount||0));
1939 - let usedDiscount=0,usedVat=0;
1940 - return inv.items.map((it,idx)=>{
1941 - const lineSubtotal=it.lineTotal;
1942 - const isLastItem=(idx===n-1);
1943 - let lineDiscount,lineVat;
1944 - if(isLastItem){
1945 - lineDiscount=Math.max(0,(inv.discount||0)-usedDiscount);
1946 - lineVat=Math.max(0,(inv.vat||0)-usedVat);
1947 - }else{
1948 - lineDiscount=(inv.subtotal>0)?Math.round((inv.discount||0)*(lineSubtotal/inv.subtotal)):0;
1949 - const lineAfterDiscount=lineSubtotal-lineDiscount;
1950 - lineVat=(afterDiscountTotal>0&&inv.vat>0)?Math.round((inv.vat||0)*(lineAfterDiscount/afterDiscountTotal)):0;
1951 - }
1952 - usedDiscount+=lineDiscount;usedVat+=lineVat;
1953 - const lineNet=lineSubtotal-lineDiscount+lineVat;
1954 - return {rowNo:idx+1,prodName:it.prodName,qty:it.qty,unit:it.unit||'عدد',price:it.price,lineSubtotal,lineDiscount,lineVat,lineNet};
1955 - });
1956 -}
1957 -function buildFormalPage(items,seller,contact,inv,opt){
1958 - const cur=inv.currencyLabel||'ریال';
1959 - const isLast=opt.isLastPage;
1960 - const rowsHtml=items.map(li=>`
1961 - <tr style="text-align:center">
1962 - <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
1963 - <td style="border:1px solid #1e293b;padding:3px 6px;text-align:right;font-size:10.5px;font-weight:600">${esc(li.prodName)}</td>
1964 - <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
1965 - <td style="border:1px solid #1e293b;padding:3px 6px;font-size:10.5px">${esc(li.unit)}</td>
1966 - <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
1967 - <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
1968 - <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineDiscount.toLocaleString('fa-IR')}</td>
1969 - <td style="border:1px solid #1e293b;padding:3px 6px;text-align:left;font-size:10.5px">${li.lineVat.toLocaleString('fa-IR')}</td>
1970 - <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>
1971 - </tr>`).join('');
1972 - const sellerIds=`${esc(seller.national_id||'—')} / ${esc(seller.reg_number||'—')}`;
1973 - const contactIds=`${esc(contact.national_id||'—')} / ${esc(contact.reg_number||'—')}`;
1974 - const cumSub=opt.cumulativeSubtotal||0;
1975 - const cumDisc=opt.cumulativeDiscount||0;
1976 - const cumVat=opt.cumulativeVat||0;
1977 - const cumNet=opt.cumulativeNet||0;
1978 - const subtotalLabel=isLast?'جمع کل اقلام:':'جمع اقلام تا این صفحه:';
1979 - const discountLabel=isLast?'مجموع تخفیف:':'مجموع تخفیف تا این صفحه:';
1980 - const vatLabel=isLast?'مالیات و عوارض ارزش افزوده:':'مالیات تا این صفحه:';
1981 - const netLabel=isLast?'مبلغ قابل پرداخت:':'جمع تا این صفحه:';
1982 - const wordsLabel=isLast?'مبلغ کل به حروف:':'مبلغ تا این صفحه به حروف:';
1983 - const summaryBox=`
1984 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10.5px;margin-top:3px">
1985 - <tr>
1986 - <td style="width:60%;border:1px solid #1e3a8a;padding:6px;vertical-align:top;background:#f8fafc">
1987 - <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet,cur)}</div>
1988 - ${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> ${esc(inv.description||seller.footer||'تحویل کالا منوط به تسویه نهایی می‌باشد.')}</div>`:`<div style="font-size:9.5px;color:#64748b;margin-top:4px">(ادامه اقلام در صفحه بعد درج گردیده است...)</div>`}
1989 - </td>
1990 - <td style="width:40%;border:1px solid #1e3a8a;padding:0">
1991 - <table style="width:100%;border-collapse:collapse;font-size:10.5px">
1992 - <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>
1993 - <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>
1994 - <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>
1995 - <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>
1996 - </table>
1997 - </td>
1998 - </tr>
1999 - </table>`;
2000 - const signatures=isLast?`
2001 - <table style="width:100%;border-collapse:collapse;border:1px solid #1e3a8a;margin-top:6px;text-align:center;font-size:10.5px">
2002 - <tr>
2003 - <td style="width:50%;height:50px;vertical-align:top;border:1px solid #1e3a8a;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
2004 - <td style="width:50%;height:50px;vertical-align:top;border:1px solid #1e3a8a;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
2005 - </tr>
2006 - </table>`:'';
2007 - return `
2008 - <div class="invoice-a4-page landscape" style="background:#fff;padding:6mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif">
2009 - <table style="width:100%;border-collapse:collapse;margin-bottom:3px">
2010 - <tr>
2011 - <td style="width:28%;padding:5px;vertical-align:middle"></td>
2012 - <td style="width:44%;padding:6px;text-align:center;vertical-align:middle;background:#eff6ff">
2013 - <h1 style="font-size:15px;margin:0;font-weight:bold;color:#1e3a8a">صورتحساب فروش کالا و خدمات</h1>
2014 - </td>
2015 - <td style="width:28%;padding:5px;font-size:10.5px;vertical-align:middle;text-align:left">
2016 - <div>شماره سریال: <strong style="color:#b91c1c">${esc(inv.number)}</strong></div>
2017 - <div style="margin-top:1px">تاریخ صدور: <strong>${esc(inv.date)}</strong></div>
2018 - <div style="margin-top:1px;color:#64748b;font-size:9.5px">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
2019 - </td>
2020 - </tr>
2021 - </table>
2022 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px;margin-bottom:3px">
2023 - <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">مشخصات فروشنده</td></tr>
2024 - <tr>
2025 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
2026 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${esc(seller.name||'—')}</strong></td>
2027 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
2028 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${esc(seller.economic_code||'—')}</td>
2029 - </tr>
2030 - <tr>
2031 - <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
2032 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${sellerIds}</td>
2033 - <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
2034 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${esc(seller.postal_code||'—')}</td>
2035 - </tr>
2036 - <tr>
2037 - <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
2038 - <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${esc(seller.address||'—')} ${esc(seller.phone?' | تلفن: '+seller.phone:'')}</td>
2039 - </tr>
2040 - </table>
2041 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px;margin-bottom:3px">
2042 - <tr style="background:#f8fafc;font-weight:bold"><td colspan="4" style="border:1px solid #1e3a8a;padding:2px 6px;color:#1e3a8a">مشخصات خریدار</td></tr>
2043 - <tr>
2044 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
2045 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%"><strong>${esc(contact.name||inv.contactName)}</strong></td>
2046 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
2047 - <td style="border:1px solid #cbd5e1;padding:3px 6px;width:35%">${esc(contact.economic_code||'—')}</td>
2048 - </tr>
2049 - <tr>
2050 - <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
2051 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${contactIds}</td>
2052 - <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
2053 - <td style="border:1px solid #cbd5e1;padding:3px 6px">${esc(contact.postal_code||'—')}</td>
2054 - </tr>
2055 - <tr>
2056 - <td style="border:1px solid #cbd5e1;padding:3px 6px;background:#f1f5f9">نشانی و تلفن:</td>
2057 - <td colspan="3" style="border:1px solid #cbd5e1;padding:3px 6px">${esc(contact.address||'—')} ${esc(contact.mobile?' | تلفن: '+contact.mobile:'')}</td>
2058 - </tr>
2059 - </table>
2060 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #1e3a8a;font-size:10px">
2061 - <thead>
2062 - <tr style="background:#1e3a8a;color:#fff;font-weight:bold;text-align:center">
2063 - <th style="border:1px solid #1e3a8a;padding:4px;width:28px">ردیف</th>
2064 - <th style="border:1px solid #1e3a8a;padding:4px 6px;text-align:right">شرح کالا یا خدمات</th>
2065 - <th style="border:1px solid #1e3a8a;padding:4px;width:42px">تعداد</th>
2066 - <th style="border:1px solid #1e3a8a;padding:4px;width:42px">واحد</th>
2067 - <th style="border:1px solid #1e3a8a;padding:4px;width:105px">مبلغ واحد (${cur})</th>
2068 - <th style="border:1px solid #1e3a8a;padding:4px;width:110px">مبلغ کل (${cur})</th>
2069 - <th style="border:1px solid #1e3a8a;padding:4px;width:80px">تخفیف (${cur})</th>
2070 - <th style="border:1px solid #1e3a8a;padding:4px;width:90px">مالیات (${cur})</th>
2071 - <th style="border:1px solid #1e3a8a;padding:4px;width:120px">مبلغ نهایی (${cur})</th>
2072 - </tr>
2073 - </thead>
2074 - <tbody>
2075 - ${!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>`:''}
2076 - ${rowsHtml}
2077 - </tbody>
2078 - </table>
2079 - ${summaryBox}
2080 - ${signatures}
2081 - </div>`;
2082 -}
2083 -function buildNonFormalPage(items,seller,contact,inv,opt){
2084 - const cur=inv.currencyLabel||'ریال';
2085 - const isPre=inv.kind==='pre_invoice';
2086 - const isLast=opt.isLastPage;
2087 - const hasVat=isPre&&inv.vat>0;
2088 - const title=isPre?'پیش‌فاکتور فروش کالا و خدمات':'فاکتور فروش کالا و خدمات';
2089 - const rowsHtml=items.map(li=>hasVat?`
2090 - <tr style="text-align:center">
2091 - <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.rowNo.toLocaleString('fa-IR')}</td>
2092 - <td style="border:1px solid #334155;padding:3px 6px;text-align:right;font-size:10px;font-weight:600">${esc(li.prodName)}</td>
2093 - <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${esc(li.unit)}</td>
2094 - <td style="border:1px solid #334155;padding:3px 5px;font-size:10px">${li.qty.toLocaleString('fa-IR')}</td>
2095 - <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.price.toLocaleString('fa-IR')}</td>
2096 - <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineSubtotal.toLocaleString('fa-IR')}</td>
2097 - <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px">${li.lineVat.toLocaleString('fa-IR')}</td>
2098 - <td style="border:1px solid #334155;padding:3px 5px;text-align:left;font-size:10px;font-weight:bold">${li.lineNet.toLocaleString('fa-IR')}</td>
2099 - </tr>`:`
2100 - <tr style="text-align:center">
2101 - <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.rowNo.toLocaleString('fa-IR')}</td>
2102 - <td style="border:1px solid #334155;padding:4px 8px;text-align:right;font-size:10.5px;font-weight:600">${esc(li.prodName)}</td>
2103 - <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${esc(li.unit)}</td>
2104 - <td style="border:1px solid #334155;padding:4px 5px;font-size:10.5px">${li.qty.toLocaleString('fa-IR')}</td>
2105 - <td style="border:1px solid #334155;padding:4px 5px;text-align:left;font-size:10.5px">${li.price.toLocaleString('fa-IR')}</td>
2106 - <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>
2107 - </tr>`).join('');
2108 - const cumSub=opt.cumulativeSubtotal||0;
2109 - const cumDisc=opt.cumulativeDiscount||0;
2110 - const cumVat=opt.cumulativeVat||0;
2111 - const cumNet=opt.cumulativeNet||0;
2112 - const subtotalLabel=isLast?'قیمت کل اقلام:':'جمع اقلام تا این صفحه:';
2113 - const discountLabel=isLast?'تخفیف:':'تخفیف تا این صفحه:';
2114 - const vatLabel=isLast?'مالیات ارزش افزوده:':'مالیات تا این صفحه:';
2115 - const netLabel=isLast?`مبلغ کل (${cur}):`:'جمع تا این صفحه:';
2116 - const wordsLabel=isLast?'مبلغ به حروف:':'مبلغ تا این صفحه به حروف:';
2117 - const summaryBox=`
2118 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px;margin-top:5px">
2119 - <tr>
2120 - <td style="width:60%;border:1px solid #334155;padding:6px;vertical-align:top;background:#f8fafc">
2121 - <div style="margin-bottom:4px"><strong>${wordsLabel}</strong> ${numberToPersianWords(cumNet,cur)}</div>
2122 - ${isLast?`<div style="font-size:9.5px;color:#475569;line-height:1.5"><strong>توضیحات:</strong> ${esc(inv.description||seller.footer||(isPre?'اعتبار پیش‌فاکتور به مدت ۴۸ ساعت می‌باشد.':'از خرید شما سپاسگزاریم.'))}</div>`:`<div style="font-size:9.5px;color:#64748b">(ادامه در صفحه بعد...)</div>`}
2123 - </td>
2124 - <td style="width:40%;border:1px solid #334155;padding:0">
2125 - <table style="width:100%;border-collapse:collapse;font-size:10.5px">
2126 - <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>
2127 - ${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>`:''}
2128 - ${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>`:''}
2129 - <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>
2130 - </table>
2131 - </td>
2132 - </tr>
2133 - </table>`;
2134 - const signatures=isLast?`
2135 - <table style="width:100%;border-collapse:collapse;border:1px solid #334155;margin-top:6px;text-align:center;font-size:10.5px">
2136 - <tr>
2137 - <td style="width:50%;height:50px;vertical-align:top;border:1px solid #334155;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
2138 - <td style="width:50%;height:50px;vertical-align:top;border:1px solid #334155;padding:5px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
2139 - </tr>
2140 - </table>`:'';
2141 - return `
2142 - <div class="invoice-a4-page landscape" style="background:#fff;padding:7mm 8mm;color:#000;font-family:'Vazirmatn FD',sans-serif">
2143 - <table style="width:100%;border-collapse:collapse;margin-bottom:5px">
2144 - <tr>
2145 - <td style="width:30%;padding:6px;vertical-align:middle"></td>
2146 - <td style="width:40%;padding:6px;text-align:center;vertical-align:middle;background:#f8fafc">
2147 - <h1 style="font-size:15px;margin:0;font-weight:bold;color:#0f172a">${title}</h1>
2148 - </td>
2149 - <td style="width:30%;padding:6px;font-size:10.5px;vertical-align:middle;text-align:left">
2150 - <div>شماره: <strong style="font-size:11.5px">#${esc(inv.number)}</strong></div>
2151 - <div style="margin-top:1px">تاریخ: <strong>${esc(inv.date)}</strong></div>
2152 - <div style="margin-top:1px;color:#64748b;font-size:9.5px">صفحه: ${opt.pageNum} از ${opt.totalPages}</div>
2153 - </td>
2154 - </tr>
2155 - </table>
2156 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px;margin-bottom:5px">
2157 - <tr>
2158 - <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
2159 - <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات فروشنده:</div>
2160 - <div>نام: <strong>${esc(seller.name||'—')}</strong></div>
2161 - <div>نشانی: ${esc(seller.address||'—')}</div>
2162 - <div>تلفن تماس: ${esc(seller.phone||'—')}</div>
2163 - </td>
2164 - <td style="width:50%;border:1px solid #334155;padding:5px;vertical-align:top;background:#f8fafc">
2165 - <div style="font-weight:bold;color:#334155;margin-bottom:2px">مشخصات خریدار:</div>
2166 - <div>نام: <strong>${esc(contact.name||inv.contactName)}</strong></div>
2167 - <div>نشانی: ${esc(contact.address||'—')}</div>
2168 - <div>تلفن: ${esc(contact.mobile||'—')}</div>
2169 - </td>
2170 - </tr>
2171 - </table>
2172 - <table style="width:100%;border-collapse:collapse;border:1.5px solid #334155;font-size:10.5px">
2173 - <thead>
2174 - <tr style="background:#334155;color:#fff;font-weight:bold;text-align:center">
2175 - <th style="border:1px solid #334155;padding:5px 4px;width:32px">ردیف</th>
2176 - <th style="border:1px solid #334155;padding:5px 8px;text-align:right">شرح کالا | خدمات</th>
2177 - <th style="border:1px solid #334155;padding:5px 4px;width:60px">واحد</th>
2178 - <th style="border:1px solid #334155;padding:5px 4px;width:60px">مقدار</th>
2179 - <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat?'110':'150'}px;text-align:left">قیمت واحد (${cur})</th>
2180 - <th style="border:1px solid #334155;padding:5px 4px;width:${hasVat?'120':'170'}px;text-align:left">قیمت کل (${cur})</th>
2181 - ${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>`:''}
2182 - </tr>
2183 - </thead>
2184 - <tbody>
2185 - ${!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>`:''}
2186 - ${rowsHtml}
2187 - </tbody>
2188 - </table>
2189 - ${summaryBox}
2190 - ${signatures}
2191 - </div>`;
2192 -}
2193 -function renderAndPrintDirect(invId){
2194 - const inv=getMyInvoices().find(i=>i.id===invId);
2195 - if(!inv)return;
2196 - const myCompanies=getMyCompanies();
2197 - const myContacts=getMyContacts();
2198 - const seller=myCompanies.find(c=>c.id===inv.companyId)||myCompanies[0]||{};
2199 - const contact=myContacts.find(c=>c.id===inv.contactId)||{};
2200 - const isFormal=(inv.kind==='formal');
2201 - const builder=isFormal?buildFormalPage:buildNonFormalPage;
2202 - const allLines=computeInvoiceLines(inv);
2203 - const pageGroups=[];
2204 - let cumulativeSub=0,cumulativeDisc=0,cumulativeVat=0;
2205 - for(let start=0;start<allLines.length;start+=MAX_ROWS_PER_PAGE){
2206 - const pageItems=allLines.slice(start,start+MAX_ROWS_PER_PAGE);
2207 - const isFirstPage=(start===0);
2208 - const isLastPage=(start+MAX_ROWS_PER_PAGE>=allLines.length);
2209 - const pageSub=pageItems.reduce((s,li)=>s+li.lineSubtotal,0);
2210 - const pageDisc=pageItems.reduce((s,li)=>s+li.lineDiscount,0);
2211 - const pageVat=pageItems.reduce((s,li)=>s+li.lineVat,0);
2212 - const cumSubAfter=cumulativeSub+pageSub;
2213 - const cumDiscAfter=cumulativeDisc+pageDisc;
2214 - const cumVatAfter=cumulativeVat+pageVat;
2215 - const cumNetAfter=cumSubAfter-cumDiscAfter+cumVatAfter;
2216 - pageGroups.push({items:pageItems,isFirstPage,isLastPage,cumulativeBefore:cumulativeSub,cumulativeSubtotal:cumSubAfter,cumulativeDiscount:cumDiscAfter,cumulativeVat:cumVatAfter,cumulativeNet:cumNetAfter});
2217 - cumulativeSub=cumSubAfter;cumulativeDisc=cumDiscAfter;cumulativeVat=cumVatAfter;
2218 - }
2219 - const totalPages=pageGroups.length;
2220 - const containerHtml=pageGroups.map((g,idx)=>builder(g.items,seller,contact,inv,{pageNum:idx+1,totalPages,isFirstPage:g.isFirstPage,isLastPage:g.isLastPage,cumulativeBefore:g.cumulativeBefore,cumulativeSubtotal:g.cumulativeSubtotal,cumulativeDiscount:g.cumulativeDiscount,cumulativeVat:g.cumulativeVat,cumulativeNet:g.cumulativeNet})).join('');
2221 - let orientationStyle=document.getElementById('dynamic-print-orientation');
2222 - if(!orientationStyle){orientationStyle=document.createElement('style');orientationStyle.id='dynamic-print-orientation';document.head.appendChild(orientationStyle);}
2223 - orientationStyle.innerHTML=`@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
2224 - const printContainer=document.getElementById('printable-invoice');
2225 - printContainer.innerHTML=containerHtml;
2226 - printContainer.style.display='block';
2227 - window.print();
2228 - printContainer.style.display='none';
2229 -}
2230 -function commitSaveProduct(){
2231 - if(!requireWrite())return;
2232 - if(!currentUser)return;
2233 - const myProducts=getMyProducts();
2234 - const code=document.getElementById('prod-code-input').value||(myProducts.length+1).toString();
2235 - const name=document.getElementById('prod-name-input').value;
2236 - const spec=document.getElementById('prod-spec-input').value||'';
2237 - const unit=document.getElementById('prod-unit-input').value||'عدد';
2238 - const buy_price=parseFloat(document.getElementById('prod-buy-input').value)||0;
2239 - const sale_price=parseFloat(document.getElementById('prod-sale-input').value)||0;
2240 - const internal_id=document.getElementById('prod-internal-id-input').value||'';
2241 - if(!name){alert('عنوان کالا الزامی است.');return;}
2242 - datastore.products.push({id:'P_'+Date.now(),ownerUserId:currentUser.id,code,name,spec,type:'good',unit,buy_price,sale_price,stock:0,internal_id});
2243 - saveDatastore();
2244 - alert('کالا ثبت شد.');
2245 - document.getElementById('prod-name-input').value='';
2246 - document.getElementById('prod-spec-input').value='';
2247 - document.getElementById('prod-internal-id-input').value='';
2248 - refreshAllSurfaces();
2249 -}
2250 -function renderProducts(){
2251 - const tbody=document.getElementById('products-catalog-table-body');
2252 - const myProducts=getMyProducts();
2253 - if(myProducts.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ کالایی ثبت نشده است.</td></tr>';return;}
2254 - tbody.innerHTML=myProducts.map(p=>`<tr><td>${esc(p.code)}</td><td><strong>${esc(p.name)}</strong></td><td>${esc(p.spec||'—')}</td><td>${esc(p.unit)}</td><td>${p.sale_price.toLocaleString('fa-IR')}</td><td>${esc(p.internal_id||'—')}</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('');
2255 -}
2256 -function deleteProduct(id){
2257 - if(!requireWrite())return;
2258 - if(!currentUser)return;
2259 - if(confirm('حذف شود؟')){
2260 - datastore.products=datastore.products.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
2261 - saveDatastore();refreshAllSurfaces();
2262 - }
2263 -}
2264 -function openQuickProductModal(){document.getElementById('modal-quick-product').classList.add('active');}
2265 -function closeQuickProductModal(){document.getElementById('modal-quick-product').classList.remove('active');}
2266 -function saveQuickProduct(){
2267 - if(!requireWrite())return;
2268 - if(!currentUser)return;
2269 - const myProducts=getMyProducts();
2270 - const code=document.getElementById('quick-p-code').value||(myProducts.length+1).toString();
2271 - const name=document.getElementById('quick-p-name').value;
2272 - const spec=document.getElementById('quick-p-spec').value||'';
2273 - const unit=document.getElementById('quick-p-unit').value||'عدد';
2274 - const price=parseFloat(document.getElementById('quick-p-price').value)||0;
2275 - const internal_id=document.getElementById('quick-p-internal-id').value||'';
2276 - if(!name){alert('عنوان کالا الزامی است.');return;}
2277 - const newId='P_'+Date.now();
2278 - datastore.products.push({id:newId,ownerUserId:currentUser.id,code,name,spec,unit,buy_price:0,sale_price:price,stock:0,type:'good',internal_id});
2279 - saveDatastore();
2280 - closeQuickProductModal();
2281 - refreshAllSurfaces();
2282 - addInvoiceItemRow(newId,1,price);
2283 -}
2284 -function downloadProductsExcelTemplate(){
2285 - const ws_data=[["کد کالا","نام کالا","مشخصه و نوع","واحد","قیمت فروش (ریال)","شناسه کالا/خدمت داخلی"],["1","سوئیچ شبکه 24 پورت","با 2 پاور","عدد",2180000000,""],["2","هارد 2.5 اینچ سرور","","عدد",37000000,""]];
2286 - const ws=XLSX.utils.aoa_to_sheet(ws_data);
2287 - const wb=XLSX.utils.book_new();
2288 - XLSX.utils.book_append_sheet(wb,ws,"کالاها");
2289 - XLSX.writeFile(wb,"نمونه_کالاها_فینورا.xlsx");
2290 -}
2291 -function importProductsFromExcel(event){
2292 - if(!requireWrite())return;
2293 - if(!currentUser)return;
2294 - const file=event.target.files[0];
2295 - if(!file)return;
2296 - const reader=new FileReader();
2297 - reader.onload=function(e){
2298 - try{
2299 - const data=new Uint8Array(e.target.result);
2300 - const workbook=XLSX.read(data,{type:'array'});
2301 - const rows=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
2302 - const myProducts=getMyProducts();
2303 - rows.forEach((r,idx)=>{
2304 - const name=r["نام کالا"]||r["عنوان"];
2305 - if(name){
2306 - datastore.products.push({id:'P_'+Date.now()+'_'+idx,ownerUserId:currentUser.id,code:(r["کد کالا"]||(myProducts.length+idx+1)).toString(),name:name.toString(),spec:(r["مشخصه و نوع"]||'').toString(),unit:(r["واحد"]||'عدد').toString(),buy_price:0,sale_price:parseFloat(r["قیمت فروش (ریال)"]||r["قیمت فروش"]||0)||0,stock:0,type:'good',internal_id:(r["شناسه کالا/خدمت داخلی"]||'').toString()});
2307 - }
2308 - });
2309 - saveDatastore();refreshAllSurfaces();
2310 - alert('کالاها ایمپورت شدند.');
2311 - }catch(err){alert('خطا در فایل اکسل!');}
2312 - };
2313 - reader.readAsArrayBuffer(file);
2314 -}
2315 -function commitSaveContact(){
2316 - if(!requireWrite())return;
2317 - if(!currentUser)return;
2318 - const entity_type=document.getElementById('contact-entity-type').value;
2319 - const custom_prefix=entity_type==='natural'?document.getElementById('contact-prefix-select')?.value:'';
2320 - const raw_name=document.getElementById('contact-name-input').value;
2321 - const role=document.getElementById('contact-role-input').value;
2322 - const mobile=document.getElementById('contact-mobile-input').value;
2323 - const national_id=document.getElementById('contact-national-input').value;
2324 - const economic_code=(entity_type==='natural')?'':document.getElementById('contact-economic-input').value;
2325 - const reg_number=(entity_type==='natural')?'':document.getElementById('contact-reg-input').value;
2326 - const postal_code=document.getElementById('contact-postal-input').value;
2327 - const address=document.getElementById('contact-address-input').value;
2328 - if(!raw_name.trim()){alert('نام طرف حساب الزامی است.');return;}
2329 - const formatted_name=formatEntityName(raw_name,entity_type,custom_prefix);
2330 - 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});
2331 - saveDatastore();
2332 - alert('طرف حساب ثبت شد.');
2333 - document.getElementById('contact-name-input').value='';
2334 - refreshAllSurfaces();
2335 -}
2336 -function renderContacts(){
2337 - const tbody=document.getElementById('contacts-ledger-table-body');
2338 - const invSelect=document.getElementById('invoice-contact-id');
2339 - const chqSelect=document.getElementById('chq-contact-select');
2340 - const myContacts=getMyContacts();
2341 - if(myContacts.length===0){
2342 - tbody.innerHTML='<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">هیچ طرف حسابی ثبت نشده است.</td></tr>';
2343 - }else{
2344 - tbody.innerHTML=myContacts.map(c=>`<tr><td><strong>${esc(c.name)}</strong></td><td><span class="badge ${c.entity_type==='legal'?'badge-warning':'badge-success'}">${c.entity_type==='legal'?'حقوقی':'حقیقی'}</span></td><td>${esc(c.national_id||'—')}</td><td>${esc(c.economic_code||'—')}</td><td>${esc(c.postal_code||'—')}</td><td>${esc(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('');
2345 - }
2346 - const options=myContacts.map(c=>`<option value="${c.id}">${esc(c.name)}</option>`).join('');
2347 - if(invSelect)invSelect.innerHTML=options;
2348 - if(chqSelect)chqSelect.innerHTML=options;
2349 -}
2350 -function deleteContact(id){
2351 - if(!requireWrite())return;
2352 - if(!currentUser)return;
2353 - if(confirm('حذف شود؟')){
2354 - datastore.contacts=datastore.contacts.filter(c=>!(c.id===id&&c.ownerUserId===currentUser.id));
2355 - saveDatastore();refreshAllSurfaces();
2356 - }
2357 -}
2358 -function openQuickContactModal(){document.getElementById('modal-quick-contact').classList.add('active');handleQuickCEntityChange();}
2359 -function closeQuickContactModal(){document.getElementById('modal-quick-contact').classList.remove('active');}
2360 -function saveQuickContact(){
2361 - if(!requireWrite())return;
2362 - if(!currentUser)return;
2363 - const entity_type=document.getElementById('quick-c-entity').value;
2364 - const prefix=entity_type==='natural'?document.getElementById('quick-c-prefix')?.value:'';
2365 - const raw_name=document.getElementById('quick-c-name').value;
2366 - if(!raw_name.trim()){alert('نام الزامی است.');return;}
2367 - const newId='C_'+Date.now();
2368 - datastore.contacts.push({id:newId,ownerUserId:currentUser.id,entity_type,name:formatEntityName(raw_name,entity_type,prefix),role:'customer',mobile:document.getElementById('quick-c-mobile').value,national_id:document.getElementById('quick-c-national').value,economic_code:(entity_type==='natural')?'':document.getElementById('quick-c-economic').value,reg_number:(entity_type==='natural')?'':document.getElementById('quick-c-reg').value,postal_code:document.getElementById('quick-c-postal').value,address:document.getElementById('quick-c-address').value,balance:0});
2369 - saveDatastore();
2370 - closeQuickContactModal();
2371 - refreshAllSurfaces();
2372 - document.getElementById('invoice-contact-id').value=newId;
2373 -}
2374 -function downloadContactsExcelTemplate(){
2375 - const ws_data=[["نام شخص یا شرکت","نوع (حقیقی/حقوقی)","شماره همراه","شناسه یا کد ملی","کد اقتصادی","شماره ثبت","کد پستی","نشانی"],["دانشگاه صنعتی شریف","حقوقی","02166165000","14002830256","14002830256","","1458889694","طرشت محله تیموری پلاک 435"]];
2376 - const ws=XLSX.utils.aoa_to_sheet(ws_data);
2377 - const wb=XLSX.utils.book_new();
2378 - XLSX.utils.book_append_sheet(wb,ws,"اشخاص");
2379 - XLSX.writeFile(wb,"نمونه_اشخاص_فینورا.xlsx");
2380 -}
2381 -function importContactsFromExcel(event){
2382 - if(!requireWrite())return;
2383 - if(!currentUser)return;
2384 - const file=event.target.files[0];
2385 - if(!file)return;
2386 - const reader=new FileReader();
2387 - reader.onload=function(e){
2388 - try{
2389 - const data=new Uint8Array(e.target.result);
2390 - const workbook=XLSX.read(data,{type:'array'});
2391 - const rows=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
2392 - rows.forEach((r,idx)=>{
2393 - const raw_name=r["نام شخص یا شرکت"]||r["نام"];
2394 - if(raw_name){
2395 - const entity_type=(r["نوع (حقیقی/حقوقی)"]||'').includes('حقوقی')?'legal':'natural';
2396 - datastore.contacts.push({id:'C_'+Date.now()+'_'+idx,ownerUserId:currentUser.id,entity_type,name:formatEntityName(raw_name.toString(),entity_type,'آقا/خانم'),role:'customer',mobile:(r["شماره همراه"]||'').toString(),national_id:(r["شناسه یا کد ملی"]||'').toString(),economic_code:(entity_type==='legal'?(r["کد اقتصادی"]||''):'').toString(),reg_number:(entity_type==='legal'?(r["شماره ثبت"]||''):'').toString(),postal_code:(r["کد پستی"]||'').toString(),address:(r["نشانی"]||'').toString(),balance:0});
2397 - }
2398 - });
2399 - saveDatastore();refreshAllSurfaces();
2400 - alert('اشخاص ایمپورت شدند.');
2401 - }catch(err){alert('خطا در فایل اکسل!');}
2402 - };
2403 - reader.readAsArrayBuffer(file);
2404 -}
2405 -function commitSaveCheque(){
2406 - if(!requireWrite())return;
2407 - if(!currentUser)return;
2408 - const direction=document.getElementById('chq-direction-input').value;
2409 - const contactSelect=document.getElementById('chq-contact-select');
2410 - const contactName=contactSelect.options[contactSelect.selectedIndex]?.text||'';
2411 - const sayad_id=document.getElementById('chq-sayad-input').value;
2412 - const bank=document.getElementById('chq-bank-input').value;
2413 - const amount=parseFloat(document.getElementById('chq-amount-input').value)||0;
2414 - if(!sayad_id||amount<=0){alert('اطلاعات چک نامعتبر است.');return;}
2415 - 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});
2416 - saveDatastore();
2417 - alert('چک ثبت شد.');
2418 - refreshAllSurfaces();
2419 -}
2420 -function renderCheques(){
2421 - const tbody=document.getElementById('cheques-ledger-table-body');
2422 - const myCheques=getMyCheques();
2423 - 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>${esc(c.contactName)}</td><td>${esc(c.bank)} - ${esc(c.sayad_id)}</td><td>${c.amount.toLocaleString('fa-IR')}</td><td>${esc(c.due_date)}</td><td>${esc(c.status)}</td></tr>`).join('');
2424 -}
2425 -function commitSaveExpense(){
2426 - if(!requireWrite())return;
2427 - if(!currentUser)return;
2428 - const amount=parseFloat(document.getElementById('trx-amount-input').value)||0;
2429 - if(amount<=0){alert('مبلغ معتبر نیست.');return;}
2430 - 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});
2431 - saveDatastore();
2432 - alert('سند ثبت شد.');
2433 - refreshAllSurfaces();
2434 -}
2435 -function renderExpenses(){
2436 - const tbody=document.getElementById('expenses-ledger-table-body');
2437 - const myExpenses=getMyExpenses();
2438 - 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>${esc(e.kind)}</td><td>${esc(e.category)}</td><td>${esc(e.desc)}</td><td>${e.amount.toLocaleString('fa-IR')}</td></tr>`).join('');
2439 -}
2440 -function commitSaveCompany(){
2441 - if(!requireWrite())return;
2442 - if(!currentUser)return;
2443 - const entity_type=document.getElementById('company-entity-type').value;
2444 - const raw_name=document.getElementById('company-name-input').value;
2445 - if(!raw_name.trim()){alert('نام شرکت الزامی است.');return;}
2446 - const newComp={id:'COMP_'+Date.now(),ownerUserId:currentUser.id,entity_type,name:formatEntityName(raw_name,entity_type),phone:document.getElementById('company-phone-input').value||'',national_id:document.getElementById('company-national-input').value||'',economic_code:document.getElementById('company-economic-input').value||'',reg_number:document.getElementById('company-reg-input').value||'',postal_code:document.getElementById('company-postal-input').value||'',address:document.getElementById('company-address-input').value||'',footer:document.getElementById('company-footer-input')?.value||'از خرید شما سپاسگزاریم.'};
2447 - datastore.companies.push(newComp);
2448 - const s=getMySettings();
2449 - s.default_company_id=newComp.id;
2450 - saveDatastore();
2451 - alert('شرکت با موفقیت ثبت و ذخیره شد و به عنوان فروشنده پیش‌فرض تنظیم گردید.');
2452 - ['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='';});
2453 - refreshAllSurfaces();
2454 -}
2455 -function renderCompanies(){
2456 - const tbody=document.getElementById('companies-table-body');
2457 - const invoiceCompSelect=document.getElementById('invoice-company-id');
2458 - const filterCompSelect=document.getElementById('filter-invoice-company');
2459 - const myCompanies=getMyCompanies();
2460 - const mySettings=getMySettings();
2461 - const defCompId=mySettings.default_company_id||(myCompanies[0]?.id);
2462 - if(tbody){
2463 - if(myCompanies.length===0){
2464 - tbody.innerHTML='<tr><td colspan="5" style="text-align:center;color:var(--text-muted);padding:20px">هیچ شرکتی ثبت نشده است. لطفاً ابتدا شرکت خود را ثبت کنید.</td></tr>';
2465 - }else{
2466 - tbody.innerHTML=myCompanies.map(c=>`<tr><td><strong>${esc(c.name)}</strong></td><td>${esc(c.national_id||'—')}</td><td>${esc(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('');
2467 - }
2468 - }
2469 - if(invoiceCompSelect){
2470 - invoiceCompSelect.innerHTML=myCompanies.map(c=>`<option value="${c.id}" ${c.id===defCompId?'selected':''}>${esc(c.name)}</option>`).join('');
2471 - if(defCompId)invoiceCompSelect.value=defCompId;
2472 - }
2473 - if(filterCompSelect){
2474 - const currentVal=filterCompSelect.value||'ALL';
2475 - filterCompSelect.innerHTML=`<option value="ALL">نمایش همه شرکت‌ها</option>`+myCompanies.map(c=>`<option value="${c.id}">فقط ${esc(c.name)}</option>`).join('');
2476 - filterCompSelect.value=currentVal;
2477 - }
2478 -}
2479 -function setDefaultCompany(id){if(!requireWrite())return;const s=getMySettings();s.default_company_id=id;saveDatastore();refreshAllSurfaces();}
2480 -function deleteCompany(id){
2481 - if(!requireWrite())return;
2482 - if(!currentUser)return;
2483 - if(confirm('حذف شود؟')){
2484 - datastore.companies=datastore.companies.filter(c=>!(c.id===id&&c.ownerUserId===currentUser.id));
2485 - const myCompanies=getMyCompanies();
2486 - const s=getMySettings();
2487 - if(s.default_company_id===id)s.default_company_id=myCompanies[0]?.id||'';
2488 - saveDatastore();refreshAllSurfaces();
2489 - }
2490 -}
2491 -function exportDataBlob(){
2492 - const userExport={user:currentUser?.username,exportedAt:new Date().toISOString(),companies:getMyCompanies(),contacts:getMyContacts(),products:getMyProducts(),invoices:getMyInvoices(),cheques:getMyCheques(),expenses:getMyExpenses(),settings:getMySettings()};
2493 - const blobString="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(userExport,null,2));
2494 - const anchor=document.createElement('a');
2495 - anchor.setAttribute("href",blobString);
2496 - anchor.setAttribute("download",`finora-${currentUser?.username||'data'}-${Date.now()}.json`);
2497 - document.body.appendChild(anchor);
2498 - anchor.click();
2499 - anchor.remove();
2500 -}
2501 -function importDataBlob(event){
2502 - if(!requireWrite())return;
2503 - if(!currentUser)return;
2504 - const file=event.target.files[0];
2505 - if(!file)return;
2506 - const reader=new FileReader();
2507 - reader.onload=function(e){
2508 - try{
2509 - const imported=JSON.parse(e.target.result);
2510 - if(!imported||typeof imported!=='object')throw new Error('bad');
2511 - absorbRecords(imported);
2512 - saveDatastore();refreshAllSurfaces();
2513 - alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
2514 - }catch(err){alert('فایل نامعتبر است.');}
2515 - };
2516 - reader.readAsText(file);
2517 -}
2518 -function numberToPersianWords(num,currencyLabel){
2519 - const cur=currencyLabel||'ریال';
2520 - if(!num||isNaN(num)||num==0)return 'صفر '+cur;
2521 - const yegan=["","یک","دو","سه","چهار","پنج","شش","هفت","هشت","نه"];
2522 - const dahgan=["","","بیست","سی","چهل","پنجاه","شصت","هفتاد","هشتاد","نود"];
2523 - const dah_ta_bist=["ده","یازده","دوازده","سیزده","چهارده","پانزده","شانزده","هفده","هجده","نوزده"];
2524 - const sadgan=["","صد","دویست","سیصد","چهارصد","پانصد","ششصد","هفتصد","هشتصد","نهصد"];
2525 - const part_names=["","هزار","میلیون","میلیارد","تریلیون"];
2526 - function threeDigitToWords(n){
2527 - let c=Math.floor(n/100);
2528 - let d=Math.floor((n%100)/10);
2529 - let y=n%10;
2530 - let parts=[];
2531 - if(c>0)parts.push(sadgan[c]);
2532 - if(d===1)parts.push(dah_ta_bist[y]);
2533 - else{
2534 - if(d>1)parts.push(dahgan[d]);
2535 - if(y>0)parts.push(yegan[y]);
2536 - }
2537 - return parts.join(" و ");
2538 - }
2539 - let parts=[];
2540 - let chunkIdx=0;
2541 - let temp=Math.abs(Math.round(num));
2542 - while(temp>0){
2543 - let chunk=temp%1000;
2544 - if(chunk>0){
2545 - let w=threeDigitToWords(chunk);
2546 - if(part_names[chunkIdx])w+=" "+part_names[chunkIdx];
2547 - parts.unshift(w);
2548 - }
2549 - temp=Math.floor(temp/1000);
2550 - chunkIdx++;
2551 - }
2552 - return parts.join(" و ")+" "+cur;
2553 -}
2554 -window.addEventListener('DOMContentLoaded',()=>{initAuthSystem();});
2555 -</script>
708 +<script src="js/core.js"></script>
709 +<script src="js/admin.js"></script>
710 +<script src="js/sync.js"></script>
711 +<script src="js/ui.js"></script>
712 +<script src="js/invoices.js"></script>
713 +<script src="js/print.js"></script>
714 +<script src="js/products.js"></script>
715 +<script src="js/contacts.js"></script>
716 +<script src="js/cheques.js"></script>
717 +<script src="js/expenses.js"></script>
718 +<script src="js/companies.js"></script>
719 +<script src="js/backup.js"></script>
720 +<script src="js/words.js"></script>
721 +<script src="js/bootstrap.js"></script>
722
723 <style>
724 .form-control, textarea, select { direction: rtl; }
725 </style>
726
2561 -<script>
2562 -(function(){
2563 - const oldSave = window.commitSaveInvoice;
2564 - window.commitSaveInvoice = function(){
2565 - const rows = document.querySelectorAll('#invoice-items-table-body tr');
2566 - if(!rows.length){ alert('حداقل یک ردیف کالا یا خدمت لازم است.'); return; }
2567 - for(const row of rows){
2568 - const sel = row.querySelector('.row-product-select');
2569 - if(sel && !sel.value){ alert('لطفاً شرح کالا یا خدمت را از لیست انتخاب کنید.'); return; }
2570 - const qty = parseFloat(row.querySelector('.row-quantity')?.value) || 0;
2571 - if(qty <= 0){ alert('مقدار کالا باید بزرگتر از صفر باشد.'); return; }
2572 - }
2573 - if(typeof oldSave === 'function') return oldSave();
2574 - };
2575 - window.FinoraHealth = {
2576 - version: '7.0-finora',
2577 - storage: 'supabase',
2578 - checks(){ return { rtl: document.documentElement.dir === 'rtl', storage: !!window.localStorage, printReady: !!document.getElementById('printable-invoice') }; }
2579 - };
2580 -})();
2581 -</script>
2582 -
2583 -<script>
2584 -// ============== خروج خودکار بعد از عدم فعالیت + حفظ پیش‌نویس فاکتور باز ==============
2585 -(function(){
2586 - const IDLE_TIMEOUT_MS = 30*60*1000; // ۳۰ دقیقه
2587 - const WARN_LEAD_MS = 60*1000; // ۱ دقیقه قبل هشدار
2588 - const DRAFT_KEY = 'factoreasy_invoice_draft_v1';
2589 - let idleTimer=null, warnTimer=null, countdownInterval=null, warningVisible=false, lastActivityReset=0;
2590 -
2591 - function ensureIdleModal(){
2592 - if(document.getElementById('modal-idle-warning'))return;
2593 - const div=document.createElement('div');
2594 - div.className='modal-backdrop';
2595 - div.id='modal-idle-warning';
2596 - div.innerHTML=`<div class="modal-card" style="max-width:420px;text-align:center">
2597 - <h3 style="font-size:16px;margin-bottom:10px">⏰ عدم فعالیت</h3>
2598 - <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px">به دلیل عدم فعالیت، تا <span id="idle-countdown" style="font-weight:bold;color:#dc2626">60</span> ثانیه دیگر از حساب خارج می‌شوید.</p>
2599 - <div style="display:flex;gap:10px;justify-content:center">
2600 - <button class="btn btn-success" onclick="window.__idleContinueWorking()">✅ ادامه کار</button>
2601 - <button class="btn btn-secondary" onclick="window.__idleLogoutNow()">🚪 خروج فوری</button>
2602 - </div>
2603 - </div>`;
2604 - document.body.appendChild(div);
2605 - }
2606 - function hideWarning(){
2607 - warningVisible=false;
2608 - clearInterval(countdownInterval);
2609 - const el=document.getElementById('modal-idle-warning');
2610 - if(el)el.classList.remove('active');
2611 - }
2612 - function showWarning(){
2613 - ensureIdleModal();
2614 - warningVisible=true;
2615 - let remain=Math.round(WARN_LEAD_MS/1000);
2616 - const cd=document.getElementById('idle-countdown');
2617 - if(cd)cd.innerText=remain;
2618 - document.getElementById('modal-idle-warning').classList.add('active');
2619 - countdownInterval=setInterval(()=>{
2620 - remain--;
2621 - const el=document.getElementById('idle-countdown');
2622 - if(el)el.innerText=Math.max(remain,0);
2623 - if(remain<=0)clearInterval(countdownInterval);
2624 - },1000);
2625 - }
2626 -
2627 - function getInvoiceFormSnapshot(){
2628 - const rows=[...document.querySelectorAll('#invoice-items-table-body tr')].map(tr=>({
2629 - prodId: tr.querySelector('.row-product-select')?.value||'',
2630 - unit: tr.querySelector('.row-unit-input')?.value||'',
2631 - qty: tr.querySelector('.row-quantity')?.value||'',
2632 - price: tr.querySelector('.row-price')?.value||''
2633 - })).filter(r=>r.prodId);
2634 - return {
2635 - editId: document.getElementById('edit-invoice-id')?.value||'',
2636 - companyId: document.getElementById('invoice-company-id')?.value||'',
2637 - kind: document.getElementById('invoice-kind')?.value||'',
2638 - vatMode: document.getElementById('invoice-vat-mode')?.value||'',
2639 - vatType: document.getElementById('invoice-vat-type')?.value||'',
2640 - vatRate: document.getElementById('invoice-vat-rate-input')?.value||'',
2641 - number: document.getElementById('invoice-number')?.value||'',
2642 - contactId: document.getElementById('invoice-contact-id')?.value||'',
2643 - date: document.getElementById('invoice-date-input')?.value||'',
2644 - discountType: document.getElementById('invoice-discount-type')?.value||'',
2645 - discountFixed: document.getElementById('invoice-discount-fixed')?.value||'',
2646 - desc: document.getElementById('invoice-desc-input')?.value||'',
2647 - items: rows,
2648 - savedAt: Date.now(),
2649 - userId: (typeof currentUser!=='undefined'&&currentUser)?currentUser.id:null
2650 - };
2651 - }
2652 - function isSnapshotWorthSaving(snap){
2653 - return !!(snap.contactId || (snap.desc&&snap.desc.trim()) || (snap.items&&snap.items.length>0));
2654 - }
2655 - function saveInvoiceDraftIfNeeded(){
2656 - try{
2657 - const snap=getInvoiceFormSnapshot();
2658 - if(!isSnapshotWorthSaving(snap))return;
2659 - localStorage.setItem(DRAFT_KEY, JSON.stringify(snap));
2660 - }catch(e){console.error('draft save failed',e);}
2661 - }
2662 -
2663 - async function performIdleLogout(){
2664 - hideWarning();
2665 - saveInvoiceDraftIfNeeded();
2666 - try{await sb.auth.signOut();}catch(e){}
2667 - }
2668 - window.__idleContinueWorking=function(){ hideWarning(); resetIdleTimer(); };
2669 - window.__idleLogoutNow=async function(){
2670 - hideWarning();
2671 - saveInvoiceDraftIfNeeded();
2672 - try{await sb.auth.signOut();}catch(e){}
2673 - };
2674 -
2675 - function resetIdleTimer(){
2676 - if(!window.__idleWatcherActive)return;
2677 - clearTimeout(idleTimer);
2678 - clearTimeout(warnTimer);
2679 - warnTimer=setTimeout(showWarning, IDLE_TIMEOUT_MS-WARN_LEAD_MS);
2680 - idleTimer=setTimeout(performIdleLogout, IDLE_TIMEOUT_MS);
2681 - }
2682 - function onActivity(){
2683 - if(!window.__idleWatcherActive)return;
2684 - const now=Date.now();
2685 - if(warningVisible)hideWarning();
2686 - if(now-lastActivityReset<3000)return;
2687 - lastActivityReset=now;
2688 - resetIdleTimer();
2689 - }
2690 - ['mousemove','mousedown','keydown','scroll','touchstart','click'].forEach(evt=>{
2691 - window.addEventListener(evt, onActivity, {passive:true});
2692 - });
2693 -
2694 - window.startIdleWatcher=function(){ window.__idleWatcherActive=true; resetIdleTimer(); };
2695 - window.stopIdleWatcher=function(){
2696 - window.__idleWatcherActive=false;
2697 - clearTimeout(idleTimer); clearTimeout(warnTimer); hideWarning();
2698 - };
2699 -
2700 - window.offerInvoiceDraftRestoreIfAny=function(){
2701 - try{
2702 - const raw=localStorage.getItem(DRAFT_KEY);
2703 - if(!raw)return;
2704 - const snap=JSON.parse(raw);
2705 - const uid=(typeof currentUser!=='undefined'&&currentUser)?currentUser.id:null;
2706 - if(!uid||snap.userId!==uid){localStorage.removeItem(DRAFT_KEY);return;}
2707 - const ageMin=Math.max(1,Math.round((Date.now()-(snap.savedAt||0))/60000));
2708 - if(!confirm(`یک فاکتور پیش‌نویس ذخیره‌نشده (حدود ${ageMin} دقیقه پیش، به‌دلیل خروج خودکار به‌خاطر عدم فعالیت) پیدا شد. بازیابی شود؟`)){
2709 - localStorage.removeItem(DRAFT_KEY); return;
2710 - }
2711 - switchView('view-invoices');
2712 - document.getElementById('edit-invoice-id').value=snap.editId||'';
2713 - if(snap.editId){
2714 - document.getElementById('invoice-form-title').innerText='✏️ ویرایش فاکتور (پیش‌نویس بازیابی‌شده)';
2715 - document.getElementById('btn-cancel-edit').style.display='inline-flex';
2716 - document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
2717 - }else{
2718 - document.getElementById('invoice-form-title').innerText='📝 فاکتور پیش‌نویس بازیابی‌شده';
2719 - }
2720 - document.getElementById('invoice-company-id').value=snap.companyId||'';
2721 - document.getElementById('invoice-kind').value=snap.kind||'non_formal';
2722 - document.getElementById('invoice-vat-mode').value=snap.vatMode||'none';
2723 - document.getElementById('invoice-vat-type').value=snap.vatType||'percent';
2724 - document.getElementById('invoice-vat-rate-input').value=snap.vatRate||10;
2725 - document.getElementById('invoice-number').value=snap.number||'';
2726 - document.getElementById('invoice-contact-id').value=snap.contactId||'';
2727 - document.getElementById('invoice-date-input').value=snap.date||'';
2728 - document.getElementById('invoice-discount-type').value=snap.discountType||'fixed';
2729 - document.getElementById('invoice-discount-fixed').value=snap.discountFixed||0;
2730 - document.getElementById('invoice-desc-input').value=snap.desc||'';
2731 - if(typeof handleInvoiceKindChange==='function')handleInvoiceKindChange();
2732 - const tbody=document.getElementById('invoice-items-table-body');
2733 - tbody.innerHTML='';
2734 - (snap.items||[]).forEach(it=>{
2735 - addInvoiceItemRow(it.prodId, parseFloat(it.qty)||1, it.price!==''?parseFloat(it.price):null);
2736 - const lastRow=tbody.lastElementChild;
2737 - if(lastRow&&it.unit)lastRow.querySelector('.row-unit-input').value=it.unit;
2738 - });
2739 - if(typeof updateInvoiceItemRowNumbers==='function')updateInvoiceItemRowNumbers();
2740 - if(typeof recomputeTotals==='function')recomputeTotals();
2741 - localStorage.removeItem(DRAFT_KEY);
2742 - }catch(e){console.error('draft restore failed',e);}
2743 - };
2744 -
2745 - // اتصال بدون دست‌زدن به کد اصلی enterApp/handleLogout
2746 - const oldEnterApp=window.enterApp;
2747 - window.enterApp=async function(authUser){
2748 - await oldEnterApp(authUser);
2749 - if(typeof currentUser!=='undefined'&&currentUser){
2750 - window.startIdleWatcher();
2751 - window.offerInvoiceDraftRestoreIfAny();
2752 - }
2753 - };
2754 - const oldHandleLogout=window.handleLogout;
2755 - window.handleLogout=async function(){
2756 - window.stopIdleWatcher();
2757 - return oldHandleLogout();
2758 - };
2759 -})();
2760 -
2761 -// ============== گزارشات مالی ==============
2762 -function toEnglishDigits(str){
2763 - if(str===null||str===undefined)return '';
2764 - const map={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9'};
2765 - return String(str).replace(/[۰-۹]/g,d=>map[d]);
2766 -}
2767 -const persianMonthNames=['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
2768 -function populateReportYearSelect(years){
2769 - const sel=document.getElementById('report-year-select');
2770 - if(!sel)return;
2771 - const current=sel.value;
2772 - sel.innerHTML=years.map(y=>`<option value="${y}">سال ${toPersianDigits(y)}</option>`).join('');
2773 - if(current&&years.includes(parseInt(current)))sel.value=current;
2774 -}
2775 -function renderFinancialReports(){
2776 - const cur=(typeof getCurrencyLabel==='function')?getCurrencyLabel():'ریال';
2777 - const invoices=(typeof getMyInvoices==='function')?getMyInvoices():[];
2778 - const parsed=invoices.map(inv=>{
2779 - const d=toEnglishDigits(inv.date||'');
2780 - const parts=d.split('/');
2781 - if(parts.length<2)return null;
2782 - const y=parseInt(parts[0]),m=parseInt(parts[1]);
2783 - if(!y||!m)return null;
2784 - return {year:y,month:m,inv};
2785 - }).filter(Boolean);
2786 -
2787 - let years=[...new Set(parsed.map(p=>p.year))].sort((a,b)=>b-a);
2788 - if(years.length===0){
2789 - const fallback=parseInt(toEnglishDigits((typeof getJalaliNumeric==='function'?getJalaliNumeric():'').split('/')[0]))||1404;
2790 - years=[fallback];
2791 - }
2792 - populateReportYearSelect(years);
2793 - const sel=document.getElementById('report-year-select');
2794 - const selectedYear=(sel&&sel.value)?parseInt(sel.value):years[0];
2795 -
2796 - const yearInvoices=parsed.filter(p=>p.year===selectedYear);
2797 - const monthTotals=Array(12).fill(0);
2798 - yearInvoices.forEach(p=>{ if(p.month>=1&&p.month<=12) monthTotals[p.month-1]+=(p.inv.grandTotal||0); });
2799 - const yearTotal=monthTotals.reduce((a,b)=>a+b,0);
2800 - const avg=yearTotal/12;
2801 - const maxVal=Math.max(...monthTotals,1);
2802 - const maxIdx=monthTotals.indexOf(maxVal);
2803 -
2804 - const setTxt=(id,txt)=>{const el=document.getElementById(id);if(el)el.innerText=txt;};
2805 - setTxt('rep-year-total',yearTotal.toLocaleString('fa-IR')+' '+cur);
2806 - setTxt('rep-year-avg',Math.round(avg).toLocaleString('fa-IR')+' '+cur);
2807 - setTxt('rep-best-month',monthTotals[maxIdx]>0?persianMonthNames[maxIdx]:'—');
2808 - setTxt('rep-invoice-count',yearInvoices.length.toLocaleString('fa-IR'));
2809 -
2810 - const chartEl=document.getElementById('report-monthly-chart');
2811 - if(chartEl){
2812 - chartEl.innerHTML=monthTotals.map((v,i)=>{
2813 - const h=Math.max(4,Math.round((v/maxVal)*130));
2814 - return `<div class="report-bar-col">
2815 - <div class="report-bar-value">${v>0?(v/1000000).toLocaleString('fa-IR',{maximumFractionDigits:1})+'M':''}</div>
2816 - <div class="report-bar" style="height:${h}px"></div>
2817 - <div class="report-bar-label">${persianMonthNames[i].slice(0,3)}</div>
2818 - </div>`;
2819 - }).join('');
2820 - }
2821 -
2822 - const byCustomer={};
2823 - yearInvoices.forEach(p=>{
2824 - const key=p.inv.contactId||p.inv.contactName||'—';
2825 - if(!byCustomer[key])byCustomer[key]={name:p.inv.contactName||'—',count:0,sum:0};
2826 - byCustomer[key].count++;
2827 - byCustomer[key].sum+=(p.inv.grandTotal||0);
2828 - });
2829 - const topList=Object.values(byCustomer).sort((a,b)=>b.sum-a.sum).slice(0,10);
2830 - const tbody=document.getElementById('report-top-customers');
2831 - if(tbody){
2832 - if(topList.length===0){
2833 - tbody.innerHTML='<tr><td colspan="3" style="text-align:center;color:var(--text-muted);padding:20px">داده‌ای برای نمایش وجود ندارد.</td></tr>';
2834 - }else{
2835 - tbody.innerHTML=topList.map(c=>`<tr><td>${(typeof esc==='function'?esc(c.name):c.name)}</td><td>${c.count.toLocaleString('fa-IR')}</td><td>${c.sum.toLocaleString('fa-IR')}</td></tr>`).join('');
2836 - }
2837 - }
2838 -
2839 - let formalCount=0,formalSum=0,informalCount=0,informalSum=0;
2840 - yearInvoices.forEach(p=>{
2841 - if(p.inv.kind==='formal'){formalCount++;formalSum+=(p.inv.grandTotal||0);}
2842 - else{informalCount++;informalSum+=(p.inv.grandTotal||0);}
2843 - });
2844 - setTxt('rep-formal-count',formalCount.toLocaleString('fa-IR'));
2845 - setTxt('rep-formal-sum',formalSum.toLocaleString('fa-IR')+' '+cur);
2846 - setTxt('rep-informal-count',informalCount.toLocaleString('fa-IR'));
2847 - setTxt('rep-informal-sum',informalSum.toLocaleString('fa-IR')+' '+cur);
2848 -}
2849 -
2850 -// ============== تغییر/تعیین رمز عبور از داخل تنظیمات (برای کاربران گوگل هم کار می‌کند) ==============
2851 -async function changeAccountPassword(){
2852 - const p1=document.getElementById('acct-newpass').value;
2853 - const p2=document.getElementById('acct-newpass2').value;
2854 - if(p1.length<8){alert('رمز عبور باید حداقل ۸ کاراکتر باشد.');return;}
2855 - if(p1!==p2){alert('تکرار رمز عبور با رمز اصلی یکی نیست.');return;}
2856 - try{
2857 - const {error}=await sb.auth.updateUser({password:p1,data:{has_password:true}});
2858 - if(error)throw error;
2859 - document.getElementById('acct-newpass').value='';
2860 - document.getElementById('acct-newpass2').value='';
2861 - alert('رمز عبور با موفقیت ذخیره شد. دفعات بعد می‌توانید با ایمیل و همین رمز هم وارد شوید.');
2862 - }catch(err){
2863 - alert(typeof authMsg==='function'?authMsg(err):(err.message||'خطا در ذخیره رمز عبور.'));
2864 - }
2865 -}
2866 -</script>
727 +<script src="js/patches.js"></script>
728 +<script src="js/idle-and-reports.js"></script>
729 +<script src="js/money-format.js"></script>
730 +<script src="js/projects.js"></script>
731 +<script src="js/invoice-excel-import.js"></script>
732
733 </body>
734 </html>