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&&['cash','bank','card'].includes(p.method);
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
+ // Compose compensator + new finalized source synchronously. The debounced
71
+ // finora_sync_records call receives one diff, not an intermediate reversal.
72
+ // PostgreSQL RPC errors never leave a partly acknowledged accounting chain.
73
+ const knownVoucherIds=new Set(datastore.journalVouchers.map(x=>x.id));
74
+ const knownLineIds=new Set(datastore.journalLines.map(x=>x.id));
75
+ const knownDimensionIds=new Set(datastore.journalLineDimensions.map(x=>x.id));
76
+ const knownProfileIds=new Set(datastore.postingProfiles.map(x=>x.id));
77
+ const oldVoucher={...v};
78
+ let newer,posted,reversal;
79
+ try{
80
+ reversal=jeReverse(v.id,getJalaliNumeric(),'اصلاح دریافت/پرداخت دوره پایلوت');
81
+ const now=new Date().toISOString();
82
+ newer={...p,id:afId('PAY'),amount:num(patch.amount),method:patch.method,
83
+ reference:String(patch.reference||''),note:String(patch.note||''),
84
+ createdAt:now,updatedAt:now,accountingStatus:'draft',
85
+ correctsPaymentId:p.id,correctionReversalId:reversal.id,accountingVersion:1};
86
+ delete newer.journalVoucherId;delete newer.accountingPostedAt;
87
+ datastore.payments.push(newer);
88
+ posted=jePostSourceRecord(p.direction==='outbound'?'payment':'receipt',newer);
89
+ saveDatastore();
90
+ }catch(e){
91
+ // Before the first async boundary, the batch has not been dispatched.
92
+ // Undo local staging if a validation/posting exception occurs.
93
+ Object.assign(v,oldVoucher);
94
+ datastore.journalVouchers=datastore.journalVouchers.filter(x=>knownVoucherIds.has(x.id));
95
+ datastore.journalLines=datastore.journalLines.filter(x=>knownLineIds.has(x.id));
96
+ datastore.journalLineDimensions=datastore.journalLineDimensions.filter(x=>knownDimensionIds.has(x.id));
97
+ datastore.postingProfiles=datastore.postingProfiles.filter(x=>knownProfileIds.has(x.id));
98
+ if(newer)datastore.payments=datastore.payments.filter(x=>x.id!==newer.id);
99
+ saveDatastore();
100
+ throw e;
101
+ }
102
+ await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id,
103
+ 'journalVouchers|'+posted.id,'payments|'+newer.id]);
104
+ return newer.id;
105
+}
106
+async function paymentCancelPosted(id,reason){
107
+ const {voucher:v}=paymentEligibility(id);
108
+ if(!String(reason||'').trim())throw new Error('دلیل ابطال لازم است.');
109
+ const reversed=jeReverse(v.id,getJalaliNumeric(),'ابطال ثبت نرمافزاری: '+String(reason).trim());
110
+ await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversed.id]);
111
+ return reversed.id;
112
+}
113
+function paymentCorrectionPayload(){
114
+ return {direction:document.getElementById('pay-direction')?.value||'',
115
+ contactId:document.getElementById('pay-contact')?.value||'',
116
+ companyId:afCompanyId(),
117
+ amount:num(document.getElementById('pay-amount')?.value),
118
+ method:document.getElementById('pay-method')?.value||'bank',
119
+ reference:(document.getElementById('pay-reference')?.value||'').trim(),
120
+ note:(document.getElementById('pay-note')?.value||'').trim(),
121
+ invoiceType:(document.getElementById('pay-invoice')?.value||'').split('|')[0]||'',
122
+ invoiceId:(document.getElementById('pay-invoice')?.value||'').split('|')[1]||''};
123
+}
124
+function cancelPostedPaymentUi(id){
125
+ if(!confirm('فقط ثبت داخل فینورا با سند حسابداری معکوس ابطال میشود. تراکنش واقعی بانک/کارت برگشت نمیخورد. ادامه میدهید؟'))return;
126
+ const reason=prompt('دلیل ابطال ثبت نرمافزاری:','اشتباه ثبت در دوره پایلوت');
127
+ if(reason===null)return;
128
+ void paymentCancelPosted(id,reason).then(()=>{refreshAllSurfaces();renderPayments();if(typeof renderDocumentManagement==='function')renderDocumentManagement();alert('ابطال ثبت شد. سابقه اصلی محفوظ است.');})
129
+ .catch(e=>{refreshAllSurfaces();renderPayments();alert('ابطال تأیید نشد؛ وضعیت سرور را قبل از تکرار بررسی کنید: '+e.message);});
130
+}
131
+window.paymentCanAmend=paymentCanAmend;
132
+window.paymentVisibleRecords=paymentVisibleRecords;
133
+window.paymentEffectiveRecords=paymentEffectiveRecords;
134
+window.paymentPostingStatus=paymentPostingStatus;
135
+window.paymentAmendPosted=paymentAmendPosted;
136
+window.paymentCancelPosted=paymentCancelPosted;
137
+window.cancelPostedPaymentUi=cancelPostedPaymentUi;
138
+
139
function invoiceOutstanding(inv){
140
const gross=num(inv?.grandTotal);
141
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);
142
+ const paid=paymentEffectiveRecords().filter(p=>p.direction==='inbound'&&p.invoiceType==='sale'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
143
return Math.max(0,gross-paid);
144
}
145
function purchaseOutstanding(inv){
146
if(typeof purchaseDocumentStatus==='function'&&purchaseDocumentStatus(inv)!=='posted')return 0;
147
const gross=num(inv?.grandTotal);
148
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);
149
+ const paid=paymentEffectiveRecords().filter(p=>p.direction==='outbound'&&p.invoiceType==='purchase'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
150
return Math.max(0,gross-paid);
151
}
152
function resetPaymentForm(){
190
let outstanding=Infinity;
191
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);}
192
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;}}
193
+ const old=editingPaymentId?getMyPayments().find(p=>p.id===editingPaymentId):null;
194
+ if(old&&paymentPostingStatus(old)==='posted'){
195
+ const payload=paymentCorrectionPayload(),id=old.id;
196
+ try{paymentEligibility(id);paymentPreflight(payload,old);}catch(e){alert(e.message);return;}
197
+ const btn=document.getElementById('pay-save');if(btn)btn.disabled=true;
198
+ void paymentAmendPosted(id,payload).then(()=>{
199
+ resetPaymentForm();refreshAllSurfaces();renderPayments();if(typeof renderDocumentManagement==='function')renderDocumentManagement();
200
+ alert('اصلاح دریافت/پرداخت ذخیره شد.');
201
+ }).catch(e=>{
202
+ resetPaymentForm();refreshAllSurfaces();renderPayments();
203
+ alert('اصلاح کامل نشد؛ وضعیت ثبتهای حسابداری و سرور را بررسی کنید، سپس اقدام کنید: '+e.message);
204
+ }).finally(()=>{if(btn)btn.disabled=false;});
205
+ return;
206
+ }
207
+ if(old&&typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(old,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}
208
if(old&&old.invoiceId===invoiceId&&old.invoiceType===invoiceType&&old.direction===direction)outstanding+=num(old.amount);
209
if(invoiceId&&amount>outstanding){alert('مبلغ از مانده فاکتور بیشتر است.');return;}
210
const contact=getMyContacts().find(c=>c.id===contactId);
216
saveDatastore();resetPaymentForm();refreshAllSurfaces();renderPayments();
217
}
218
function editPayment(id){
74
- const p=getMyPayments().find(x=>x.id===id);if(!p)return;
75
- editingPaymentId=id;refreshPaymentContacts();
219
+ const p=paymentCurrentVisible(id);if(!p)return;
220
+ if(paymentPostingStatus(p)!=='posted'||!paymentCanAmend(p)){
221
+ alert('این ثبت ابتدا به تطبیق تاریخچه، تسویه فاکتور یا چک نیاز دارد.');return;
222
+ }
223
+ try{paymentEligibility(p.id);}catch(e){alert(e.message);return;}
224
+ editingPaymentId=p.id;refreshPaymentContacts();
225
document.getElementById('pay-direction').value=p.direction;
226
document.getElementById('pay-contact').value=p.contactId||'';
227
document.getElementById('pay-method').value=p.method||'bank';
235
}
236
function deletePayment(id){
237
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;
238
+ const source=paymentCurrentVisible(id);if(source&&paymentPostingStatus(source)==='posted')
239
+ return cancelPostedPaymentUi(source.id);
240
+ if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}if(!confirm('این دریافت/پرداخت حذف شود؟ مانده فاکتور دوباره محاسبه میشود.'))return;
241
datastore.payments=datastore.payments.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
242
if(editingPaymentId===id)resetPaymentForm();
243
saveDatastore();refreshAllSurfaces();renderPayments();
245
function renderPayments(){
246
refreshPaymentContacts();refreshPaymentInvoices();
247
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>';
248
+ 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))
249
+ .slice().sort((a,b)=>String(b.date).localeCompare(String(a.date)));
250
+ 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)?
251
+ '<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>':
252
+ paymentPostingStatus(p)==='reversed'?'ابطالشده':
253
+ '<button class="btn btn-secondary btn-inline" disabled title="نیازمند تطبیق ثبتهای مرتبط">نیازمند تطبیق</button>'}</td></tr>`}).join(''):'<tr><td colspan="7" style="text-align:center">هنوز دریافت یا پرداختی ثبت نشده است.</td></tr>';
254
}
255
function installPaymentUI(){
256
if(document.getElementById('view-payments'))return;