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

Add first-class receipt and payment settlement ledger

davoodmehraban89 committed Sep 28, 2026 at 15:06 UTC 2ec069385e24667fc81b6dd8d5a23f3b05ec05c0
1 file changed +115
js/payments.js new
+115
@@ -0,0 +1,115 @@
1 +// First-class receipt/payment settlements with invoice allocation.
2 +(function(){
3 +let editingPaymentId=null;
4 +const escP=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
5 +const num=v=>Math.max(0,Number(v)||0);
6 +function paymentDirectionLabel(v){return v==='outbound'?'پرداخت':'دریافت';}
7 +function paymentMethodLabel(v){return ({cash:'نقد',card:'کارت',bank:'انتقال بانکی',cheque:'چک'}[v]||'سایر');}
8 +function invoiceOutstanding(inv){
9 + const gross=num(inv?.grandTotal);
10 + const paid=getMyPayments().filter(p=>p.direction==='inbound'&&p.invoiceType==='sale'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
11 + return Math.max(0,gross-paid);
12 +}
13 +function purchaseOutstanding(inv){
14 + const gross=num(inv?.grandTotal);
15 + const paid=getMyPayments().filter(p=>p.direction==='outbound'&&p.invoiceType==='purchase'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
16 + return Math.max(0,gross-paid);
17 +}
18 +function resetPaymentForm(){
19 + editingPaymentId=null;
20 + ['pay-amount','pay-reference','pay-note'].forEach(id=>{const e=document.getElementById(id);if(e)e.value='';});
21 + const d=document.getElementById('pay-direction');if(d)d.value='inbound';
22 + const m=document.getElementById('pay-method');if(m)m.value='bank';
23 + const c=document.getElementById('pay-contact');if(c)c.value='';
24 + refreshPaymentInvoices();
25 + const b=document.getElementById('pay-save');if(b)b.textContent='ثبت دریافت / پرداخت';
26 + const x=document.getElementById('pay-cancel');if(x)x.style.display='none';
27 +}
28 +function refreshPaymentContacts(){
29 + const el=document.getElementById('pay-contact');if(!el)return;
30 + const prev=el.value;
31 + el.innerHTML='<option value="">انتخاب طرف حساب</option>'+getMyContacts().map(c=>`<option value="${escP(c.id)}">${escP(c.name)}</option>`).join('');
32 + if([...el.options].some(o=>o.value===prev))el.value=prev;
33 +}
34 +function refreshPaymentInvoices(){
35 + const el=document.getElementById('pay-invoice');if(!el)return;
36 + const dir=document.getElementById('pay-direction')?.value||'inbound';
37 + const cid=document.getElementById('pay-contact')?.value||'';
38 + let rows=[];
39 + if(dir==='inbound')rows=getMyInvoices().filter(i=>(!cid||i.contactId===cid)&&invoiceOutstanding(i)>0).map(i=>({id:i.id,type:'sale',label:`فروش ${i.invoiceNumber||i.id} — مانده ${invoiceOutstanding(i).toLocaleString('fa-IR')}`}));
40 + else rows=getMyPurchases().filter(i=>(!cid||i.supplierId===cid)&&purchaseOutstanding(i)>0).map(i=>({id:i.id,type:'purchase',label:`خرید ${i.invoiceNo||i.id} — مانده ${purchaseOutstanding(i).toLocaleString('fa-IR')}`}));
41 + const prev=el.value;
42 + el.innerHTML='<option value="">بدون تخصیص به فاکتور</option>'+rows.map(r=>`<option value="${r.type}|${escP(r.id)}">${escP(r.label)}</option>`).join('');
43 + if([...el.options].some(o=>o.value===prev))el.value=prev;
44 +}
45 +function commitSavePayment(){
46 + if(typeof requireWrite==='function'&&!requireWrite())return;
47 + const direction=document.getElementById('pay-direction')?.value||'inbound';
48 + const contactId=document.getElementById('pay-contact')?.value||'';
49 + const amount=num(document.getElementById('pay-amount')?.value);
50 + if(!contactId){alert('طرف حساب را انتخاب کنید.');return;}
51 + if(amount<=0){alert('مبلغ باید بیشتر از صفر باشد.');return;}
52 + const alloc=(document.getElementById('pay-invoice')?.value||'').split('|');
53 + const invoiceType=alloc.length===2?alloc[0]:'';
54 + const invoiceId=alloc.length===2?alloc[1]:'';
55 + let outstanding=Infinity;
56 + if(invoiceId&&invoiceType==='sale'){const inv=getMyInvoices().find(i=>i.id===invoiceId);outstanding=inv?invoiceOutstanding(inv):0;}
57 + if(invoiceId&&invoiceType==='purchase'){const inv=getMyPurchases().find(i=>i.id===invoiceId);outstanding=inv?purchaseOutstanding(inv):0;}
58 + const old=editingPaymentId?getMyPayments().find(p=>p.id===editingPaymentId):null;
59 + if(old&&old.invoiceId===invoiceId)outstanding+=num(old.amount);
60 + if(invoiceId&&amount>outstanding){alert('مبلغ از مانده فاکتور بیشتر است.');return;}
61 + const contact=getMyContacts().find(c=>c.id===contactId);
62 + const companies=getMyCompanies(),active=getMySettings().default_company_id||companies[0]?.id||'';
63 + const payload={id:old?.id||('PAY-'+Date.now()),ownerUserId:currentUser.id,companyId:active,contactId,contactName:contact?.name||'',direction,amount,method:document.getElementById('pay-method')?.value||'bank',reference:(document.getElementById('pay-reference')?.value||'').trim(),note:(document.getElementById('pay-note')?.value||'').trim(),invoiceType,invoiceId,date:old?.date||new Date().toISOString()};
64 + if(old)Object.assign(old,payload);else datastore.payments.push(payload);
65 + saveDatastore();resetPaymentForm();refreshAllSurfaces();renderPayments();
66 +}
67 +function editPayment(id){
68 + const p=getMyPayments().find(x=>x.id===id);if(!p)return;
69 + editingPaymentId=id;refreshPaymentContacts();
70 + document.getElementById('pay-direction').value=p.direction;
71 + document.getElementById('pay-contact').value=p.contactId||'';
72 + document.getElementById('pay-method').value=p.method||'bank';
73 + document.getElementById('pay-amount').value=p.amount||'';
74 + document.getElementById('pay-reference').value=p.reference||'';
75 + document.getElementById('pay-note').value=p.note||'';
76 + refreshPaymentInvoices();
77 + if(p.invoiceId)document.getElementById('pay-invoice').value=(p.invoiceType||'sale')+'|'+p.invoiceId;
78 + document.getElementById('pay-save').textContent='ذخیره اصلاح';
79 + document.getElementById('pay-cancel').style.display='';
80 +}
81 +function deletePayment(id){
82 + if(typeof requireWrite==='function'&&!requireWrite())return;
83 + if(!confirm('این دریافت/پرداخت حذف شود؟ مانده فاکتور دوباره محاسبه می‌شود.'))return;
84 + datastore.payments=datastore.payments.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
85 + if(editingPaymentId===id)resetPaymentForm();
86 + saveDatastore();refreshAllSurfaces();renderPayments();
87 +}
88 +function renderPayments(){
89 + refreshPaymentContacts();refreshPaymentInvoices();
90 + const body=document.getElementById('payments-ledger');if(!body)return;
91 + const rows=getMyPayments().slice().sort((a,b)=>String(b.date).localeCompare(String(a.date)));
92 + body.innerHTML=rows.length?rows.map(p=>`<tr><td>${escP(new Date(p.date).toLocaleDateString('fa-IR'))}</td><td>${escP(paymentDirectionLabel(p.direction))}</td><td>${escP(p.contactName)}</td><td>${escP(paymentMethodLabel(p.method))}</td><td>${num(p.amount).toLocaleString('fa-IR')}</td><td>${escP(p.reference||'-')}</td><td><button class="btn btn-secondary btn-inline" onclick="editPayment('${escP(p.id)}')">اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deletePayment('${escP(p.id)}')">حذف</button></td></tr>`).join(''):'<tr><td colspan="7" style="text-align:center">هنوز دریافت یا پرداختی ثبت نشده است.</td></tr>';
93 +}
94 +function installPaymentUI(){
95 + if(document.getElementById('view-payments'))return;
96 + const expLink=document.querySelector('[data-view="view-expenses"]')?.closest('li');
97 + if(expLink){const li=document.createElement('li');li.innerHTML='<a href="#" class="nav-link" data-view="view-payments" onclick="switchView(\'view-payments\');renderPayments();return false">💵 دریافت و پرداخت</a>';expLink.after(li);}
98 + const expenses=document.getElementById('view-expenses');if(!expenses)return;
99 + const s=document.createElement('section');s.id='view-payments';s.className='view-pane';
100 + s.innerHTML=`<div class="card"><h2 style="font-size:17px;margin-bottom:14px">دریافت و پرداخت</h2><div class="form-grid">
101 + <div class="form-group"><label>نوع</label><select id="pay-direction" class="form-control" onchange="refreshPaymentInvoices()"><option value="inbound">دریافت از مشتری</option><option value="outbound">پرداخت به تأمین‌کننده</option></select></div>
102 + <div class="form-group"><label>طرف حساب</label><select id="pay-contact" class="form-control" onchange="refreshPaymentInvoices()"></select></div>
103 + <div class="form-group"><label>فاکتور مرتبط</label><select id="pay-invoice" class="form-control"></select></div>
104 + <div class="form-group"><label>روش</label><select id="pay-method" class="form-control"><option value="bank">انتقال بانکی</option><option value="card">کارت</option><option value="cash">نقد</option><option value="cheque">چک</option></select></div>
105 + <div class="form-group"><label>مبلغ</label><input id="pay-amount" type="number" min="0" class="form-control"></div>
106 + <div class="form-group"><label>شماره پیگیری / مرجع</label><input id="pay-reference" class="form-control"></div>
107 + <div class="form-group" style="grid-column:1/-1"><label>توضیحات</label><input id="pay-note" class="form-control"></div></div>
108 + <div style="display:flex;gap:8px"><button id="pay-save" class="btn btn-success" onclick="commitSavePayment()">ثبت دریافت / پرداخت</button><button id="pay-cancel" class="btn btn-secondary" style="display:none" onclick="resetPaymentForm()">انصراف</button></div></div>
109 + <div class="card"><h3 style="font-size:15px;margin-bottom:12px">گردش دریافت و پرداخت</h3><div class="table-wrap"><table><thead><tr><th>تاریخ</th><th>نوع</th><th>طرف حساب</th><th>روش</th><th>مبلغ</th><th>مرجع</th><th>عملیات</th></tr></thead><tbody id="payments-ledger"></tbody></table></div></div>`;
110 + expenses.after(s);renderPayments();
111 +}
112 +window.invoiceOutstanding=invoiceOutstanding;window.purchaseOutstanding=purchaseOutstanding;window.renderPayments=renderPayments;window.commitSavePayment=commitSavePayment;window.editPayment=editPayment;window.deletePayment=deletePayment;window.resetPaymentForm=resetPaymentForm;window.refreshPaymentInvoices=refreshPaymentInvoices;
113 +document.addEventListener('DOMContentLoaded',installPaymentUI);
114 +const oldRefresh=window.refreshAllSurfaces;if(typeof oldRefresh==='function')window.refreshAllSurfaces=function(){oldRefresh();renderPayments();};
115 +})();
\ No newline at end of file