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

feat(treasury): preserve posted payment history with in-form unallocated amendments and cancellation

davoodmehraban89 committed Oct 14, 2026 at 10:51 UTC e1787cb70b03e9cc88cc94c3344aadb007d74f24
1 file changed +142 -8
js/payments.js
+142 -8
@@ -5,17 +5,127 @@ const escP=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'
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 +// One employee-facing treasury document; corrections are private linked source
9 +// versions and balanced journal events, never mutations of posted history.
10 +function paymentPostingStatus(p){
11 + if(!p)return 'unknown';
12 + const v=typeof jeSourceVoucher==='function'?jeSourceVoucher(p):null;
13 + if(v?.status==='posted')return 'posted';
14 + if(v?.status==='reversed')return 'reversed';
15 + return 'legacy_review'; // Unlinked historical records need manual reconciliation.
16 +}
17 +function paymentCurrentVisible(id){
18 + const rows=getMyPayments();let p=rows.find(x=>x.id===id),seen=new Set();
19 + while(p&&!seen.has(p.id)){
20 + seen.add(p.id);
21 + const next=rows.filter(x=>x.correctsPaymentId===p.id)
22 + .sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')))[0];
23 + if(!next)break;p=next;
24 + }
25 + return p;
26 +}
27 +function paymentVisibleRecords(){
28 + const rows=getMyPayments(),parents=new Set(rows.map(p=>p.correctsPaymentId).filter(Boolean));
29 + return rows.filter(p=>!parents.has(p.id));
30 +}
31 +function paymentEffectiveRecords(){
32 + return paymentVisibleRecords().filter(p=>['posted','legacy_review'].includes(paymentPostingStatus(p)));
33 +}
34 +function paymentCanAmend(p){
35 + return !!p&&!p.invoiceId&&!p.invoiceType&&p.method!=='cheque';
36 +}
37 +function paymentEligibility(id){
38 + if(!requireWrite()||!currentUser)throw new Error('مجوز اصلاح دریافت/پرداخت ندارید.');
39 + const p=paymentCurrentVisible(id);
40 + if(!p||p.id!==id||p.ownerUserId!==currentUser.id||p.companyId!==afCompanyId())
41 + throw new Error('سند جاری مربوط به این کاربر و شرکت نیست.');
42 + if(paymentPostingStatus(p)!=='posted')throw new Error('فقط ثبت قطعیِ دارای سند حسابداری قابل اصلاح است.');
43 + if(!paymentCanAmend(p))throw new Error('سند دارای تسویه فاکتور یا چک است و ابتدا باید جداگانه تطبیق شود.');
44 + const v=jeSourceVoucher(p);
45 + if(!v||v.status!=='posted'||v.sourceId!==p.id||
46 + v.sourceType!==(p.direction==='outbound'?'payment':'receipt'))throw new Error('سند حسابداری متصل تطبیق ندارد.');
47 + const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);
48 + const next=jeFiscalForDate(getJalaliNumeric());
49 + if(!fy||fy.status==='locked'||!next||next.status==='locked')
50 + throw new Error('سال مالی قفل‌شده یا بدون دوره باز است.');
51 + if(getMyPayments().some(x=>x.correctsPaymentId===p.id))
52 + throw new Error('نسخه اصلاحی جدیدتری ثبت شده؛ فهرست را تازه کنید.');
53 + return {record:p,voucher:v};
54 +}
55 +function paymentPreflight(patch,p){
56 + const amount=num(patch.amount);
57 + if(!Number.isFinite(amount)||amount<=0)throw new Error('مبلغ معتبر نیست.');
58 + if(patch.direction!==p.direction||patch.contactId!==p.contactId||
59 + patch.companyId!==p.companyId||patch.invoiceId||patch.invoiceType)
60 + throw new Error('طرف حساب، شرکت، نوع و تخصیص سند قطعی در این مرحله قابل تغییر نیست.');
61 + if(!['cash','card','bank'].includes(patch.method))throw new Error('اصلاح چک نیازمند بررسی مستقل است.');
62 + if(!getMyContacts().some(c=>c.id===p.contactId))throw new Error('طرف حساب یافت نشد.');
63 + const kind=p.direction==='outbound'?'payment':'receipt';
64 + if(typeof jeProfile!=='function'||!jeProfile(kind))throw new Error('پروفایل ثبت حسابداری دریافت/پرداخت یافت نشد.');
65 + return amount;
66 +}
67 +async function paymentAmendPosted(id,patch){
68 + const {record:p,voucher:v}=paymentEligibility(id);
69 + paymentPreflight(patch,p);
70 + // The original voucher is not reversed on form OPEN/CANCEL, only on SAVE.
71 + const reversal=jeReverse(v.id,getJalaliNumeric(),'اصلاح دریافت/پرداخت دوره پایلوت');
72 + await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id]);
73 + const now=new Date().toISOString();
74 + const newer={...p,id:afId('PAY'),amount:num(patch.amount),method:patch.method,
75 + reference:String(patch.reference||''),note:String(patch.note||''),
76 + createdAt:now,updatedAt:now,accountingStatus:'draft',
77 + correctsPaymentId:p.id,correctionReversalId:reversal.id,
78 + accountingVersion:1};
79 + delete newer.journalVoucherId;delete newer.accountingPostedAt;
80 + datastore.payments.push(newer);saveDatastore();
81 + await invoicePilotAwaitSync(['payments|'+newer.id]);
82 + const posted=jePostSourceRecord(p.direction==='outbound'?'payment':'receipt',newer);
83 + await invoicePilotAwaitSync(['payments|'+newer.id,'journalVouchers|'+posted.id]);
84 + return newer.id;
85 +}
86 +async function paymentCancelPosted(id,reason){
87 + const {voucher:v}=paymentEligibility(id);
88 + if(!String(reason||'').trim())throw new Error('دلیل ابطال لازم است.');
89 + const reversed=jeReverse(v.id,getJalaliNumeric(),'ابطال ثبت نرم‌افزاری: '+String(reason).trim());
90 + await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversed.id]);
91 + return reversed.id;
92 +}
93 +function paymentCorrectionPayload(){
94 + return {direction:document.getElementById('pay-direction')?.value||'',
95 + contactId:document.getElementById('pay-contact')?.value||'',
96 + companyId:afCompanyId(),
97 + amount:num(document.getElementById('pay-amount')?.value),
98 + method:document.getElementById('pay-method')?.value||'bank',
99 + reference:(document.getElementById('pay-reference')?.value||'').trim(),
100 + note:(document.getElementById('pay-note')?.value||'').trim(),
101 + invoiceType:(document.getElementById('pay-invoice')?.value||'').split('|')[0]||'',
102 + invoiceId:(document.getElementById('pay-invoice')?.value||'').split('|')[1]||''};
103 +}
104 +function cancelPostedPaymentUi(id){
105 + if(!confirm('فقط ثبت داخل فینورا با سند حسابداری معکوس ابطال می‌شود. تراکنش واقعی بانک/کارت برگشت نمی‌خورد. ادامه می‌دهید؟'))return;
106 + const reason=prompt('دلیل ابطال ثبت نرم‌افزاری:','اشتباه ثبت در دوره پایلوت');
107 + if(reason===null)return;
108 + void paymentCancelPosted(id,reason).then(()=>{refreshAllSurfaces();renderPayments();alert('ابطال ثبت شد. سابقه اصلی محفوظ است.');})
109 + .catch(e=>{refreshAllSurfaces();renderPayments();alert('ابطال تأیید نشد؛ وضعیت سرور را قبل از تکرار بررسی کنید: '+e.message);});
110 +}
111 +window.paymentVisibleRecords=paymentVisibleRecords;
112 +window.paymentEffectiveRecords=paymentEffectiveRecords;
113 +window.paymentPostingStatus=paymentPostingStatus;
114 +window.paymentAmendPosted=paymentAmendPosted;
115 +window.paymentCancelPosted=paymentCancelPosted;
116 +window.cancelPostedPaymentUi=cancelPostedPaymentUi;
117 +
118 function invoiceOutstanding(inv){
119 const gross=num(inv?.grandTotal);
120 if(inv?.paymentMethod!=='credit')return 0;
11 - const paid=getMyPayments().filter(p=>p.direction==='inbound'&&p.invoiceType==='sale'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
121 + const paid=paymentEffectiveRecords().filter(p=>p.direction==='inbound'&&p.invoiceType==='sale'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
122 return Math.max(0,gross-paid);
123 }
124 function purchaseOutstanding(inv){
125 if(typeof purchaseDocumentStatus==='function'&&purchaseDocumentStatus(inv)!=='posted')return 0;
126 const gross=num(inv?.grandTotal);
127 if(inv?.paymentMethod!=='credit')return 0;
18 - const paid=getMyPayments().filter(p=>p.direction==='outbound'&&p.invoiceType==='purchase'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
128 + const paid=paymentEffectiveRecords().filter(p=>p.direction==='outbound'&&p.invoiceType==='purchase'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
129 return Math.max(0,gross-paid);
130 }
131 function resetPaymentForm(){
@@ -59,7 +169,21 @@ function commitSavePayment(){
169 let outstanding=Infinity;
170 if(invoiceId&&invoiceType==='sale'){const inv=getMyInvoices().find(i=>i.id===invoiceId);if(!inv||typeof invoiceDocumentStatus!=='function'||invoiceDocumentStatus(inv)!=='posted'||direction!=='inbound'||inv.contactId!==contactId){alert('فاکتور فروش با طرف حساب یا نوع دریافت مطابقت ندارد.');return;}if(inv.paymentMethod!=='credit'){alert('فاکتور نقدی مانده قابل تخصیص ندارد.');return;}outstanding=invoiceOutstanding(inv);}
171 if(invoiceId&&invoiceType==='purchase'){const inv=getMyPurchases().find(i=>i.id===invoiceId);if(!inv||direction!=='outbound'||inv.supplierId!==contactId){alert('فاکتور خرید با طرف حساب یا نوع پرداخت مطابقت ندارد.');return;}if(inv.paymentMethod!=='credit'){alert('فاکتور خرید نقدی مانده قابل تخصیص ندارد.');return;}outstanding=purchaseOutstanding(inv);}
62 - const old=editingPaymentId?getMyPayments().find(p=>p.id===editingPaymentId):null;if(old&&typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(old,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}
172 + const old=editingPaymentId?getMyPayments().find(p=>p.id===editingPaymentId):null;
173 + if(old&&paymentPostingStatus(old)==='posted'){
174 + const payload=paymentCorrectionPayload(),id=old.id;
175 + try{paymentEligibility(id);paymentPreflight(payload,old);}catch(e){alert(e.message);return;}
176 + const btn=document.getElementById('pay-save');if(btn)btn.disabled=true;
177 + void paymentAmendPosted(id,payload).then(()=>{
178 + resetPaymentForm();refreshAllSurfaces();renderPayments();
179 + alert('اصلاح دریافت/پرداخت ذخیره شد.');
180 + }).catch(e=>{
181 + resetPaymentForm();refreshAllSurfaces();renderPayments();
182 + alert('اصلاح کامل نشد؛ وضعیت ثبت‌های حسابداری و سرور را بررسی کنید، سپس اقدام کنید: '+e.message);
183 + }).finally(()=>{if(btn)btn.disabled=false;});
184 + return;
185 + }
186 + if(old&&typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(old,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}
187 if(old&&old.invoiceId===invoiceId&&old.invoiceType===invoiceType&&old.direction===direction)outstanding+=num(old.amount);
188 if(invoiceId&&amount>outstanding){alert('مبلغ از مانده فاکتور بیشتر است.');return;}
189 const contact=getMyContacts().find(c=>c.id===contactId);
@@ -71,8 +195,12 @@ function commitSavePayment(){
195 saveDatastore();resetPaymentForm();refreshAllSurfaces();renderPayments();
196 }
197 function editPayment(id){
74 - const p=getMyPayments().find(x=>x.id===id);if(!p)return;
75 - editingPaymentId=id;refreshPaymentContacts();
198 + const p=paymentCurrentVisible(id);if(!p)return;
199 + if(paymentPostingStatus(p)!=='posted'||!paymentCanAmend(p)){
200 + alert('این ثبت ابتدا به تطبیق تاریخچه، تسویه فاکتور یا چک نیاز دارد.');return;
201 + }
202 + try{paymentEligibility(p.id);}catch(e){alert(e.message);return;}
203 + editingPaymentId=p.id;refreshPaymentContacts();
204 document.getElementById('pay-direction').value=p.direction;
205 document.getElementById('pay-contact').value=p.contactId||'';
206 document.getElementById('pay-method').value=p.method||'bank';
@@ -86,7 +214,9 @@ function editPayment(id){
214 }
215 function deletePayment(id){
216 if(typeof requireWrite==='function'&&!requireWrite())return;
89 - const source=getMyPayments().find(p=>p.id===id);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}if(!confirm('این دریافت/پرداخت حذف شود؟ مانده فاکتور دوباره محاسبه می‌شود.'))return;
217 + const source=paymentCurrentVisible(id);if(source&&paymentPostingStatus(source)==='posted')
218 + return cancelPostedPaymentUi(source.id);
219 + if(typeof jeGuardSourceMutation==='function'{try{jeGuardSourceMutation(source,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}if(!confirm('این دریافت/پرداخت حذف شود؟ مانده فاکتور دوباره محاسبه می‌شود.'))return;
220 datastore.payments=datastore.payments.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
221 if(editingPaymentId===id)resetPaymentForm();
222 saveDatastore();refreshAllSurfaces();renderPayments();
@@ -94,8 +224,12 @@ function deletePayment(id){
224 function renderPayments(){
225 refreshPaymentContacts();refreshPaymentInvoices();
226 const body=document.getElementById('payments-ledger');if(!body)return;
97 - const companies=getMyCompanies(),active=getMySettings().default_company_id||companies[0]?.id||'',legacyOk=companies.length===1;const rows=getMyPayments().filter(p=>!active||p.companyId===active||(!p.companyId&&legacyOk)).slice().sort((a,b)=>String(b.date).localeCompare(String(a.date)));
98 - body.innerHTML=rows.length?rows.map(p=>{const displayDate=/^\d{4}\/\d{2}\/\d{2}$/.test(String(p.date||''))?p.date:new Date(p.date).toLocaleDateString('fa-IR');return `<tr><td>${escP(displayDate)}</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>';
227 + const companies=getMyCompanies(),active=getMySettings().default_company_id||companies[0]?.id||'',legacyOk=companies.length===1;const rows=paymentVisibleRecords().filter(p=>!active||p.companyId===active||(!p.companyId&&legacyOk))
228 + .slice().sort((a,b)=>String(b.date).localeCompare(String(a.date)));
229 + body.innerHTML=rows.length?rows.map(p=>{const displayDate=/^\d{4}\/\d{2}\/\d{2}$/.test(String(p.date||''))?p.date:new Date(p.date).toLocaleDateString('fa-IR');return `<tr><td>${escP(displayDate)}</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>${paymentPostingStatus(p)==='posted'&&paymentCanAmend(p)?
230 + '<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>':
231 + paymentPostingStatus(p)==='reversed'?'ابطال‌شده':
232 + '<button class="btn btn-secondary btn-inline" disabled title="نیازمند تطبیق ثبت‌های مرتبط">نیازمند تطبیق</button>'}</td></tr>`}).join(''):'<tr><td colspan="7" style="text-align:center">هنوز دریافت یا پرداختی ثبت نشده است.</td></tr>';
233 }
234 function installPaymentUI(){
235 if(document.getElementById('view-payments'))return;