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

Add js/patches.js and js/idle-and-reports.js (final js modules)

davoodmehraban89 committed Sep 26, 2026 at 13:02 UTC f0e86a14a423ca92a9e58f021a8e86d1ab564e78
2 files changed +300
js/idle-and-reports.js new
+281
@@ -0,0 +1,281 @@
1 +(function(){
2 + const IDLE_TIMEOUT_MS = 30*60*1000; // ۳۰ دقیقه
3 + const WARN_LEAD_MS = 60*1000; // ۱ دقیقه قبل هشدار
4 + const DRAFT_KEY = 'factoreasy_invoice_draft_v1';
5 + let idleTimer=null, warnTimer=null, countdownInterval=null, warningVisible=false, lastActivityReset=0;
6 +
7 + function ensureIdleModal(){
8 + if(document.getElementById('modal-idle-warning'))return;
9 + const div=document.createElement('div');
10 + div.className='modal-backdrop';
11 + div.id='modal-idle-warning';
12 + div.innerHTML=`<div class="modal-card" style="max-width:420px;text-align:center">
13 + <h3 style="font-size:16px;margin-bottom:10px">⏰ عدم فعالیت</h3>
14 + <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>
15 + <div style="display:flex;gap:10px;justify-content:center">
16 + <button class="btn btn-success" onclick="window.__idleContinueWorking()">✅ ادامه کار</button>
17 + <button class="btn btn-secondary" onclick="window.__idleLogoutNow()">🚪 خروج فوری</button>
18 + </div>
19 + </div>`;
20 + document.body.appendChild(div);
21 + }
22 + function hideWarning(){
23 + warningVisible=false;
24 + clearInterval(countdownInterval);
25 + const el=document.getElementById('modal-idle-warning');
26 + if(el)el.classList.remove('active');
27 + }
28 + function showWarning(){
29 + ensureIdleModal();
30 + warningVisible=true;
31 + let remain=Math.round(WARN_LEAD_MS/1000);
32 + const cd=document.getElementById('idle-countdown');
33 + if(cd)cd.innerText=remain;
34 + document.getElementById('modal-idle-warning').classList.add('active');
35 + countdownInterval=setInterval(()=>{
36 + remain--;
37 + const el=document.getElementById('idle-countdown');
38 + if(el)el.innerText=Math.max(remain,0);
39 + if(remain<=0)clearInterval(countdownInterval);
40 + },1000);
41 + }
42 +
43 + function getInvoiceFormSnapshot(){
44 + const rows=[...document.querySelectorAll('#invoice-items-table-body tr')].map(tr=>({
45 + prodId: tr.querySelector('.row-product-select')?.value||'',
46 + unit: tr.querySelector('.row-unit-input')?.value||'',
47 + qty: tr.querySelector('.row-quantity')?.value||'',
48 + price: tr.querySelector('.row-price')?.value||''
49 + })).filter(r=>r.prodId);
50 + return {
51 + editId: document.getElementById('edit-invoice-id')?.value||'',
52 + companyId: document.getElementById('invoice-company-id')?.value||'',
53 + kind: document.getElementById('invoice-kind')?.value||'',
54 + vatMode: document.getElementById('invoice-vat-mode')?.value||'',
55 + vatType: document.getElementById('invoice-vat-type')?.value||'',
56 + vatRate: document.getElementById('invoice-vat-rate-input')?.value||'',
57 + number: document.getElementById('invoice-number')?.value||'',
58 + contactId: document.getElementById('invoice-contact-id')?.value||'',
59 + date: document.getElementById('invoice-date-input')?.value||'',
60 + discountType: document.getElementById('invoice-discount-type')?.value||'',
61 + discountFixed: document.getElementById('invoice-discount-fixed')?.value||'',
62 + desc: document.getElementById('invoice-desc-input')?.value||'',
63 + items: rows,
64 + savedAt: Date.now(),
65 + userId: (typeof currentUser!=='undefined'&&currentUser)?currentUser.id:null
66 + };
67 + }
68 + function isSnapshotWorthSaving(snap){
69 + return !!(snap.contactId || (snap.desc&&snap.desc.trim()) || (snap.items&&snap.items.length>0));
70 + }
71 + function saveInvoiceDraftIfNeeded(){
72 + try{
73 + const snap=getInvoiceFormSnapshot();
74 + if(!isSnapshotWorthSaving(snap))return;
75 + localStorage.setItem(DRAFT_KEY, JSON.stringify(snap));
76 + }catch(e){console.error('draft save failed',e);}
77 + }
78 +
79 + async function performIdleLogout(){
80 + hideWarning();
81 + saveInvoiceDraftIfNeeded();
82 + try{await sb.auth.signOut();}catch(e){}
83 + }
84 + window.__idleContinueWorking=function(){ hideWarning(); resetIdleTimer(); };
85 + window.__idleLogoutNow=async function(){
86 + hideWarning();
87 + saveInvoiceDraftIfNeeded();
88 + try{await sb.auth.signOut();}catch(e){}
89 + };
90 +
91 + function resetIdleTimer(){
92 + if(!window.__idleWatcherActive)return;
93 + clearTimeout(idleTimer);
94 + clearTimeout(warnTimer);
95 + warnTimer=setTimeout(showWarning, IDLE_TIMEOUT_MS-WARN_LEAD_MS);
96 + idleTimer=setTimeout(performIdleLogout, IDLE_TIMEOUT_MS);
97 + }
98 + function onActivity(){
99 + if(!window.__idleWatcherActive)return;
100 + const now=Date.now();
101 + if(warningVisible)hideWarning();
102 + if(now-lastActivityReset<3000)return;
103 + lastActivityReset=now;
104 + resetIdleTimer();
105 + }
106 + ['mousemove','mousedown','keydown','scroll','touchstart','click'].forEach(evt=>{
107 + window.addEventListener(evt, onActivity, {passive:true});
108 + });
109 +
110 + window.startIdleWatcher=function(){ window.__idleWatcherActive=true; resetIdleTimer(); };
111 + window.stopIdleWatcher=function(){
112 + window.__idleWatcherActive=false;
113 + clearTimeout(idleTimer); clearTimeout(warnTimer); hideWarning();
114 + };
115 +
116 + window.offerInvoiceDraftRestoreIfAny=function(){
117 + try{
118 + const raw=localStorage.getItem(DRAFT_KEY);
119 + if(!raw)return;
120 + const snap=JSON.parse(raw);
121 + const uid=(typeof currentUser!=='undefined'&&currentUser)?currentUser.id:null;
122 + if(!uid||snap.userId!==uid){localStorage.removeItem(DRAFT_KEY);return;}
123 + const ageMin=Math.max(1,Math.round((Date.now()-(snap.savedAt||0))/60000));
124 + if(!confirm(`یک فاکتور پیش‌نویس ذخیره‌نشده (حدود ${ageMin} دقیقه پیش، به‌دلیل خروج خودکار به‌خاطر عدم فعالیت) پیدا شد. بازیابی شود؟`)){
125 + localStorage.removeItem(DRAFT_KEY); return;
126 + }
127 + switchView('view-invoices');
128 + document.getElementById('edit-invoice-id').value=snap.editId||'';
129 + if(snap.editId){
130 + document.getElementById('invoice-form-title').innerText='✏️ ویرایش فاکتور (پیش‌نویس بازیابی‌شده)';
131 + document.getElementById('btn-cancel-edit').style.display='inline-flex';
132 + document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
133 + }else{
134 + document.getElementById('invoice-form-title').innerText='📝 فاکتور پیش‌نویس بازیابی‌شده';
135 + }
136 + document.getElementById('invoice-company-id').value=snap.companyId||'';
137 + document.getElementById('invoice-kind').value=snap.kind||'non_formal';
138 + document.getElementById('invoice-vat-mode').value=snap.vatMode||'none';
139 + document.getElementById('invoice-vat-type').value=snap.vatType||'percent';
140 + document.getElementById('invoice-vat-rate-input').value=snap.vatRate||10;
141 + document.getElementById('invoice-number').value=snap.number||'';
142 + document.getElementById('invoice-contact-id').value=snap.contactId||'';
143 + document.getElementById('invoice-date-input').value=snap.date||'';
144 + document.getElementById('invoice-discount-type').value=snap.discountType||'fixed';
145 + document.getElementById('invoice-discount-fixed').value=snap.discountFixed||0;
146 + document.getElementById('invoice-desc-input').value=snap.desc||'';
147 + if(typeof handleInvoiceKindChange==='function')handleInvoiceKindChange();
148 + const tbody=document.getElementById('invoice-items-table-body');
149 + tbody.innerHTML='';
150 + (snap.items||[]).forEach(it=>{
151 + addInvoiceItemRow(it.prodId, parseFloat(it.qty)||1, it.price!==''?parseFloat(it.price):null);
152 + const lastRow=tbody.lastElementChild;
153 + if(lastRow&&it.unit)lastRow.querySelector('.row-unit-input').value=it.unit;
154 + });
155 + if(typeof updateInvoiceItemRowNumbers==='function')updateInvoiceItemRowNumbers();
156 + if(typeof recomputeTotals==='function')recomputeTotals();
157 + localStorage.removeItem(DRAFT_KEY);
158 + }catch(e){console.error('draft restore failed',e);}
159 + };
160 +
161 + // اتصال بدون دست‌زدن به کد اصلی enterApp/handleLogout
162 + const oldEnterApp=window.enterApp;
163 + window.enterApp=async function(authUser){
164 + await oldEnterApp(authUser);
165 + if(typeof currentUser!=='undefined'&&currentUser){
166 + window.startIdleWatcher();
167 + window.offerInvoiceDraftRestoreIfAny();
168 + }
169 + };
170 + const oldHandleLogout=window.handleLogout;
171 + window.handleLogout=async function(){
172 + window.stopIdleWatcher();
173 + return oldHandleLogout();
174 + };
175 +})();
176 +
177 +// ============== گزارشات مالی ==============
178 +function toEnglishDigits(str){
179 + if(str===null||str===undefined)return '';
180 + const map={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9'};
181 + return String(str).replace(/[۰-۹]/g,d=>map[d]);
182 +}
183 +const persianMonthNames=['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
184 +function populateReportYearSelect(years){
185 + const sel=document.getElementById('report-year-select');
186 + if(!sel)return;
187 + const current=sel.value;
188 + sel.innerHTML=years.map(y=>`<option value="${y}">سال ${toPersianDigits(y)}</option>`).join('');
189 + if(current&&years.includes(parseInt(current)))sel.value=current;
190 +}
191 +function renderFinancialReports(){
192 + const cur=(typeof getCurrencyLabel==='function')?getCurrencyLabel():'ریال';
193 + const invoices=(typeof getMyInvoices==='function')?getMyInvoices():[];
194 + const parsed=invoices.map(inv=>{
195 + const d=toEnglishDigits(inv.date||'');
196 + const parts=d.split('/');
197 + if(parts.length<2)return null;
198 + const y=parseInt(parts[0]),m=parseInt(parts[1]);
199 + if(!y||!m)return null;
200 + return {year:y,month:m,inv};
201 + }).filter(Boolean);
202 +
203 + let years=[...new Set(parsed.map(p=>p.year))].sort((a,b)=>b-a);
204 + if(years.length===0){
205 + const fallback=parseInt(toEnglishDigits((typeof getJalaliNumeric==='function'?getJalaliNumeric():'').split('/')[0]))||1404;
206 + years=[fallback];
207 + }
208 + populateReportYearSelect(years);
209 + const sel=document.getElementById('report-year-select');
210 + const selectedYear=(sel&&sel.value)?parseInt(sel.value):years[0];
211 +
212 + const yearInvoices=parsed.filter(p=>p.year===selectedYear);
213 + const monthTotals=Array(12).fill(0);
214 + yearInvoices.forEach(p=>{ if(p.month>=1&&p.month<=12) monthTotals[p.month-1]+=(p.inv.grandTotal||0); });
215 + const yearTotal=monthTotals.reduce((a,b)=>a+b,0);
216 + const avg=yearTotal/12;
217 + const maxVal=Math.max(...monthTotals,1);
218 + const maxIdx=monthTotals.indexOf(maxVal);
219 +
220 + const setTxt=(id,txt)=>{const el=document.getElementById(id);if(el)el.innerText=txt;};
221 + setTxt('rep-year-total',yearTotal.toLocaleString('fa-IR')+' '+cur);
222 + setTxt('rep-year-avg',Math.round(avg).toLocaleString('fa-IR')+' '+cur);
223 + setTxt('rep-best-month',monthTotals[maxIdx]>0?persianMonthNames[maxIdx]:'—');
224 + setTxt('rep-invoice-count',yearInvoices.length.toLocaleString('fa-IR'));
225 +
226 + const chartEl=document.getElementById('report-monthly-chart');
227 + if(chartEl){
228 + chartEl.innerHTML=monthTotals.map((v,i)=>{
229 + const h=Math.max(4,Math.round((v/maxVal)*130));
230 + return `<div class="report-bar-col">
231 + <div class="report-bar-value">${v>0?(v/1000000).toLocaleString('fa-IR',{maximumFractionDigits:1})+'M':''}</div>
232 + <div class="report-bar" style="height:${h}px"></div>
233 + <div class="report-bar-label">${persianMonthNames[i].slice(0,3)}</div>
234 + </div>`;
235 + }).join('');
236 + }
237 +
238 + const byCustomer={};
239 + yearInvoices.forEach(p=>{
240 + const key=p.inv.contactId||p.inv.contactName||'—';
241 + if(!byCustomer[key])byCustomer[key]={name:p.inv.contactName||'—',count:0,sum:0};
242 + byCustomer[key].count++;
243 + byCustomer[key].sum+=(p.inv.grandTotal||0);
244 + });
245 + const topList=Object.values(byCustomer).sort((a,b)=>b.sum-a.sum).slice(0,10);
246 + const tbody=document.getElementById('report-top-customers');
247 + if(tbody){
248 + if(topList.length===0){
249 + tbody.innerHTML='<tr><td colspan="3" style="text-align:center;color:var(--text-muted);padding:20px">داده‌ای برای نمایش وجود ندارد.</td></tr>';
250 + }else{
251 + 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('');
252 + }
253 + }
254 +
255 + let formalCount=0,formalSum=0,informalCount=0,informalSum=0;
256 + yearInvoices.forEach(p=>{
257 + if(p.inv.kind==='formal'){formalCount++;formalSum+=(p.inv.grandTotal||0);}
258 + else{informalCount++;informalSum+=(p.inv.grandTotal||0);}
259 + });
260 + setTxt('rep-formal-count',formalCount.toLocaleString('fa-IR'));
261 + setTxt('rep-formal-sum',formalSum.toLocaleString('fa-IR')+' '+cur);
262 + setTxt('rep-informal-count',informalCount.toLocaleString('fa-IR'));
263 + setTxt('rep-informal-sum',informalSum.toLocaleString('fa-IR')+' '+cur);
264 +}
265 +
266 +// ============== تغییر/تعیین رمز عبور از داخل تنظیمات (برای کاربران گوگل هم کار می‌کند) ==============
267 +async function changeAccountPassword(){
268 + const p1=document.getElementById('acct-newpass').value;
269 + const p2=document.getElementById('acct-newpass2').value;
270 + if(p1.length<8){alert('رمز عبور باید حداقل ۸ کاراکتر باشد.');return;}
271 + if(p1!==p2){alert('تکرار رمز عبور با رمز اصلی یکی نیست.');return;}
272 + try{
273 + const {error}=await sb.auth.updateUser({password:p1,data:{has_password:true}});
274 + if(error)throw error;
275 + document.getElementById('acct-newpass').value='';
276 + document.getElementById('acct-newpass2').value='';
277 + alert('رمز عبور با موفقیت ذخیره شد. دفعات بعد می‌توانید با ایمیل و همین رمز هم وارد شوید.');
278 + }catch(err){
279 + alert(typeof authMsg==='function'?authMsg(err):(err.message||'خطا در ذخیره رمز عبور.'));
280 + }
281 +}
js/patches.js new
+19
@@ -0,0 +1,19 @@
1 +(function(){
2 + const oldSave = window.commitSaveInvoice;
3 + window.commitSaveInvoice = function(){
4 + const rows = document.querySelectorAll('#invoice-items-table-body tr');
5 + if(!rows.length){ alert('حداقل یک ردیف کالا یا خدمت لازم است.'); return; }
6 + for(const row of rows){
7 + const sel = row.querySelector('.row-product-select');
8 + if(sel && !sel.value){ alert('لطفاً شرح کالا یا خدمت را از لیست انتخاب کنید.'); return; }
9 + const qty = parseFloat(row.querySelector('.row-quantity')?.value) || 0;
10 + if(qty <= 0){ alert('مقدار کالا باید بزرگتر از صفر باشد.'); return; }
11 + }
12 + if(typeof oldSave === 'function') return oldSave();
13 + };
14 + window.FinoraHealth = {
15 + version: '7.0-finora',
16 + storage: 'supabase',
17 + checks(){ return { rtl: document.documentElement.dir === 'rtl', storage: !!window.localStorage, printReady: !!document.getElementById('printable-invoice') }; }
18 + };
19 +})();