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

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

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

Synced Dec 3, 17:00 UTC

feat(treasury): in-place unallocated receipt/payment amendment with balanced audit history

* docs(treasury): record owner continuation and bounded payment amendment scope * feat(treasury): preserve posted payment history with in-form unallocated amendments and cancellation * fix(treasury): maintain valid guarded payment UI handlers * fix(treasury): exclude reversed historical payment source revisions from project cash totals * fix(treasury): stage reversal and corrected payment as one debounced sync batch with local exception rollback * test(treasury): same-form payment amendment, single-batch posting, cancellation and negative guards * feat(treasury): add receipt/payment register to central document management * fix(treasury): show amendment only for supported noncheque instruments and refresh manager after server acknowledgment * feat(treasury): central document management shows one active receipt/payment and routes amendment to existing form * test(treasury): verify central manager opens same receipt form with one visible row before and after correction * docs(treasury): record source scope, one-batch amendment design and pending QA

davoodmehraban89 committed Oct 14, 2026 at 11:06 UTC e32a540b863d7931afefc140ed3417065b9a3d01
6 files changed +333 -13
PROJECT_STATE.md
+15
@@ -231,6 +231,21 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
231 - **Financial/operational limits:** Existing live customer financial records, permissions, RLS, roles, schema, Stripe, SMS and production DB rows were not modified by this source release. Sale/purchase historical accounting remains immutable. This is an application-level linked revision workflow using multiple sync stages, not independently verified as one server-side atomic amendment transaction; if a stage loses server confirmation, recovery must inspect state before retry. Closed periods, settled allocations, submitted tax invoices and historical unlinked vouchers still fail closed. Manual journal, payment/receipt, expense/income, taxpayer and multi-tenant concurrent correction acceptance remain separate tasks. F0-01 slow real owner sign-in still open.
232 - **User-visible acceptance next:** In browser, refresh site, open posted purchase/sale, select اصلاح فاکتور, verify original number and edit form; cancel = zero posting, then authorized disposable test edit/save/print yields one visible record and same number after reload, while auditing all linked vouchers. Never use actual production business financial records solely as test fixtures.
233
234 +### 2026-10-14 Owner: continue Finora development — P0 treasury receipt/payment amendment slice OPEN
235 +- **Owner latest instruction:** «ادامه کار توسعه پیش ببر». Same-document sale/purchase UX PR #128 has been released; prior auth startup F0-01 still OPEN/deferred, no owner-authenticated acceptance claimed. Work on next independent Phase 3 treasury source corrections, preserving original document in employee view, without adding technical revision rows or changing posted accounting.
236 +- **Read-only baseline:** protected `main=b4d5da725a68af6c2a534422d3de85c13bf17b4d`; exact-main Quality `38524072782`, Security `38524072853`, Release `38524404953` and Pages `38524466785` all SUCCESS. Supabase `hcsixhqbyuhpshfwqpjx` ACTIVE_HEALTHY. This status is CI/provider metadata, not a customer login or genuine bank transfer test.
237 +- **Confirmed source problem:** `js/payments.js` posts new receipt/payment entries via `jePostSourceRecord`, but `editPayment` on a linked posted source reaches `jeGuardSourceMutation` and blocks saving. `deletePayment` likewise guards immutable journal; project cash totals and invoice outstanding currently aggregate raw payment rows, which would double count additive revisions unless filtered. `js/journal-engine.js` only allows posted historical correction through balanced compensating reversal; old source and voucher must remain immutable.
238 +- **First narrow authorized slice:** One **current visible** payment/receipt with same reference/date/form, backend correction version chain; only `cash`, `bank`, `card` postings **without** invoice allocation, cheque instrument or external reconciliation link. Preserve original direction, counterparty/company/project; allow changing amount/method/reference/note, creating no financial event on Open/Cancel. On Save, validate open fiscal year, current posted source, operator company/permission, source linkage and correction lineage; only then create linked balanced reversal and new posted source/ledger. Fold past revisions in `renderPayments`, derived cash/project totals and any allocated payment aggregates; visible delete of posted record must mean auditable reversal, not physical deletion. Deny or hold linked invoice/cheque and legacy unlinked records until separate reconciliation tests. No third-party banking action or external SMS.
239 +- **Required tests:** isolated browser mock with synthetic user/company and payment: open+cancel zero ledger writes; revise→reversal→new balanced posted voucher→same visible row after reload; original posted lines/metadata untouched; treasury totals count current revision once; reject allocated or cheque; fiscal-year lock; double-click/idempotency; aborted sync fail-closed and no duplicate blind retry. Existing Chromium Golden accounting and 3 disposable PostgreSQL, Security/CodeQL, exact main Release+Pages gates. No production financial data writes, schema/RLS/role/Auth changes, new paid costs. If tests reveal unsatisfied integrity, do not merge.
240 +- **Owner acceptance:** native browser authenticated test still OPEN. Rollback targeted code PR; legitimate future financial reversals remain historical and cannot be destroyed by reverting code.
241 +
242 +### 2026-10-14 Treasury correction implementation — 5/5 syntax PASS, Chromium+Golden+DB+Security PENDING
243 +- **Delivered on isolated branch:** `js/payments.js` adds `paymentPostingStatus`, `paymentCurrentVisible`, `paymentVisibleRecords`, `paymentEffectiveRecords` and `paymentAmendPosted` / `paymentCancelPosted`. A posted unallocated non-cheque cash/card/bank receipt/payment opens in **its original form** with unchanged reference/date/contact/direction and no journal write on open/cancel. On Save, it validates permissions, active company, open fiscal year, source-voucher posting and immutable contact/direction/invoice allocation, then **synchronously stages** balanced original-voucher reversal and corrected posted source with a new internal revision before the first async boundary. Debounced `finora_sync_records` sends the resulting diff as one batch and a server ack is required before employee success. A synchronous exception restores local journal/source/profile staging before sync. Cancel only reverses the internal accounting, clearly warning it **does not** undo actual bank/card movement.
244 +- **Employee UX:** central `حسابداری ← مدیریت اسناد` treasury table in `js/journal-ui.js` and `js/document-management.js` lists one current visible receipt/payment and routes «اصلاح» directly to `view-payments` existing form; earlier source versions remain in accounting audit. `js/payments.js` treasury list also folds technical rows; `invoiceOutstanding` / `purchaseOutstanding` count effective current settled records only; `js/accounting.js` project cash totals exclude reversed/historical versions and retain legacy unlinked treatment.
245 +- **Safety boundary:** only **unallocated cash/card/bank** receipt/payment documents with currently posted canonical vouchers. Cheques, invoice-linked settlement, historical unlinked, locked fiscal years, cross-company and different-party/direction edits fail closed. Do not allow actual banking cancellation from local accounting UI; real bank/cheque movements require external reconciliation. No production financial rows altered, and no schema/RLS/Auth/role or paid service change.
246 +- **Tests authored:** four new `scripts/accounting-document-workflow.spec.js` isolated real-DOM scenarios: employee central-manager → same form → cancel=no writes; amendment → original journal reversed + balancing compensator + new posting in **one server diff** with one visible row, same reference, old lines unchanged, reload; denial for cheque, invoice-linked and fiscal lock; cancellation keeps original history; simulated one-RPC network failure produces no partial server commit and no false UI success. Syntax 5/5 PASS on actual branch files; **real browser/Golden/three disposable PostgreSQL/Security PR-head and exact-main release NOT VERIFIED at this checkpoint**. Fail CI → fix/retest, never release red.
247 +- **Remaining risk:** client-side multi-record staging uses existing shared sync RPC and auto-retry; single-call SQL atomicity, lost-ack retry behavior and concurrency cannot be considered owner-accepted solely from synthetic browser tests. Full integrated receipt→invoice settlement/cheque/bank reconciliation and independent authorized two-user tests remain Phase 3/Phase 5 dependencies. Owner live acceptance open; original Phase 0 startup F0-01 open.
248 +
249 ## Current change ledger
250 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
251
js/accounting.js
+2 -2
@@ -19,8 +19,8 @@ function getProjectFinancials(projectId){
19 const purchases=getMyPurchases().filter(i=>companyOk(i)&&purchaseAffectsBalance(i)&&(i.projectId===projectId||i.costCenterId===projectId)).reduce((s,i)=>s+n(i.grandTotal),0);
20 const expenses=getMyExpenses().filter(e=>companyOk(e)&&e.projectId===projectId&&e.kind==='expense').reduce((s,e)=>s+n(e.amount),0);
21 const income=getMyExpenses().filter(e=>companyOk(e)&&e.projectId===projectId&&e.kind==='income').reduce((s,e)=>s+n(e.amount),0);
22 - const receipts=getMyPayments().filter(p=>companyOk(p)&&p.projectId===projectId&&p.direction==='inbound').reduce((s,p)=>s+n(p.amount),0);
23 - const payments=getMyPayments().filter(p=>companyOk(p)&&p.projectId===projectId&&p.direction==='outbound').reduce((s,p)=>s+n(p.amount),0);
22 + const receipts=(typeof paymentEffectiveRecords==='function'?paymentEffectiveRecords():getMyPayments()).filter(p=>companyOk(p)&&p.projectId===projectId&&p.direction==='inbound').reduce((s,p)=>s+n(p.amount),0);
23 + const payments=(typeof paymentEffectiveRecords==='function'?paymentEffectiveRecords():getMyPayments()).filter(p=>companyOk(p)&&p.projectId===projectId&&p.direction==='outbound').reduce((s,p)=>s+n(p.amount),0);
24 return {sales,purchases,expenses,income,receipts,payments,accrualProfit:sales+income-purchases-expenses,cashNet:receipts+income-payments-expenses};
25 }
26 window.productMovement=productMovement;window.getInventorySnapshot=getInventorySnapshot;window.getProjectFinancials=getProjectFinancials;
js/document-management.js
+23
@@ -33,10 +33,33 @@ function renderDocumentManagement(){
33 return '<tr><td>'+esc(purchaseVisibleNumber(p)||'—')+'</td><td>'+esc(p.date||'—')+'</td><td>'+esc(p.supplierName||'—')+'</td><td>'+Number(p.grandTotal||0).toLocaleString('fa-IR')+'</td><td>'+esc(label)+'</td><td style="display:flex;flex-wrap:wrap;gap:5px">'+actions+voucher+'<button class="btn btn-secondary btn-inline" data-doc-action="print"'+attr+'>چاپ</button></td></tr>';
34 }).join(''):'<tr><td colspan="6" class="af-empty">سند خریدی در این وضعیت وجود ندارد.</td></tr>';
35 }
36 + const cashBody=document.getElementById('finora-treasury-document-management-body');
37 + if(cashBody&&typeof paymentVisibleRecords==='function'){
38 + const payments=paymentVisibleRecords().filter(p=>(!active||p.companyId===active)&&
39 + (status==='all'||paymentPostingStatus(p)===status)).slice()
40 + .sort((a,b)=>String(b.createdAt||b.date||'').localeCompare(String(a.createdAt||a.date||'')));
41 + cashBody.innerHTML=payments.length?payments.map(p=>{
42 + const state=paymentPostingStatus(p),id=esc(p.id),attr=' data-doc-kind="treasury" data-doc-id="'+id+'"';
43 + const label=({posted:'قطعی',reversed:'ابطال‌شده',legacy_review:'قدیمی، نیازمند تطبیق'})[state]||'نیازمند بررسی';
44 + const actions=state==='posted'&&paymentCanAmend(p)?
45 + '<button class="btn btn-secondary btn-inline" data-doc-action="edit"'+attr+'>اصلاح</button> <button class="btn btn-danger btn-inline" data-doc-action="cancel"'+attr+'>ابطال ثبت</button>':
46 + state==='reversed'?'ثبت حسابداری خنثی شده است':'نیازمند تطبیق';
47 + return '<tr><td>'+esc(p.date||'—')+'</td><td>'+esc(p.direction==='outbound'?'پرداخت':'دریافت')+'</td><td>'+esc(p.contactName||'—')+'</td><td>'+Number(p.amount||0).toLocaleString('fa-IR')+'</td><td>'+esc(p.reference||'—')+'</td><td>'+esc(label)+'</td><td>'+actions+'</td></tr>';
48 + }).join(''):'<tr><td colspan="7" class="af-empty">دریافت/پرداختی در این وضعیت وجود ندارد.</td></tr>';
49 + }
50 }
51 document.addEventListener('click',async event=>{
52 const button=event.target instanceof Element?event.target.closest('#view-journal button[data-doc-action]'):null;
53 if(!button)return;
54 + if(button.dataset.docKind==='treasury'){
55 + const p=getMyPayments().find(x=>x.id===button.dataset.docId&&x.ownerUserId===currentUser?.id&&x.companyId===afCompanyId());
56 + if(!p)return;
57 + if(button.dataset.docAction==='edit'){
58 + switchView('view-payments');renderPayments();return editPayment(p.id);
59 + }
60 + if(button.dataset.docAction==='cancel')return cancelPostedPaymentUi(p.id);
61 + return;
62 + }
63 if(button.dataset.docKind==='purchase'){
64 const purchase=getMyPurchases().find(p=>p.id===button.dataset.docId&&p.ownerUserId===currentUser?.id&&p.companyId===afCompanyId());
65 if(!purchase)return;
js/journal-ui.js
+5 -3
@@ -5,10 +5,12 @@ function ensureJournalView(){
5 <div class="form-row"><div class="form-group" style="flex:1"><label>شرح سند</label><input id="je-desc" class="form-control"></div></div><div id="je-lines"></div>
6 <div id="je-totals" class="af-hint" style="margin:10px 0;font-weight:700"></div><input type="hidden" id="je-edit-voucher-id" value=""><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="jeAddRow()">+ آرتیکل</button><button id="je-save-draft-button" class="btn btn-success" onclick="jeSaveManual()">ثبت پیش‌نویس</button><button id="je-cancel-edit-button" class="btn btn-secondary" onclick="jeClearManualForm()" style="display:none">انصراف از ویرایش</button></div></div>
7 <div class="card" data-finora-task="register"><h3>فهرست اسناد حسابداری</h3><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>نوع</th><th>مرجع</th><th>شرح</th><th>وضعیت</th><th>بدهکار</th><th>بستانکار</th><th>منبع</th><th>عملیات</th></tr></thead><tbody id="je-vouchers"></tbody></table></div></div>
8 - <div class="card" data-finora-task="documents"><h3>مدیریت اسناد — اصلاح، قطعی‌سازی و ابطال فاکتورهای فروش و خرید</h3>
9 - <p class="af-hint">برای اسناد فروش، «برگشت قطعی به موقت» یک سند برگشتی ثبت می‌کند و نسخه اصلاحی قابل ویرایش می‌سازد؛ سند قطعی و شماره اصلی در تاریخچه باقی می‌ماند. حذفِ قطعی به‌صورت ابطال قابل‌ردیابی است و حذف مستقیم فقط برای پیش‌نویس بدون سند حسابداری مجاز است. برای اسناد مرتبط با تسویه یا مؤدیان، ابتدا تطبیق جداگانه لازم است.</p>
8 + <div class="card" data-finora-task="documents"><h3>مدیریت اسناد — فروش، خرید، دریافت و پرداخت</h3>
9 + <p class="af-hint">«اصلاح» همان سند را در فرم اصلی باز می‌کند. هنگام ذخیره، سابقه حسابداری به‌صورت قابل‌ردیابی حفظ می‌شود؛ بازکردن یا انصراف هیچ ثبت جدیدی ایجاد نمی‌کند. دریافت/پرداختِ دارای تخصیص به فاکتور یا چک، ابتدا نیازمند تطبیق مستقل است. ابطال فقط ثبت نرم‌افزاری را خنثی می‌کند و تراکنش واقعی بانکی را برگشت نمی‌دهد.</p>
10 <label for="document-status-filter">نمایش وضعیت</label> <select id="document-status-filter" class="form-control" style="max-width:200px" onchange="renderDocumentManagement()"><option value="all">همه</option><option value="draft">پیش‌نویس</option><option value="posted">قطعی</option><option value="reversed">ابطال/برگشت‌شده</option><option value="legacy_review">قدیمی و نیازمند تطبیق</option></select>
11 - <div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>شرکت</th><th>طرف حساب</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-document-management-body"></tbody></table></div><h4 style="margin:16px 0 8px">فاکتورهای خرید — مدیریت وضعیت حسابداری</h4><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>تأمین‌کننده</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-purchase-document-management-body"></tbody></table></div></div>
11 + <div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>شرکت</th><th>طرف حساب</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-document-management-body"></tbody></table></div><h4 style="margin:16px 0 8px">فاکتورهای خرید — مدیریت وضعیت حسابداری</h4><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>تأمین‌کننده</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-purchase-document-management-body"></tbody></table></div>
12 + <h4 style="margin:16px 0 8px">دریافت و پرداخت — مدیریت ثبت‌های حسابداری</h4>
13 + <div class="table-responsive"><table><thead><tr><th>تاریخ</th><th>نوع</th><th>طرف حساب</th><th>مبلغ</th><th>مرجع</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-treasury-document-management-body"></tbody></table></div></div>
14 <div class="card" data-finora-task="trial"><h3>تراز آزمایشی</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody id="je-trial"></tbody></table></div></div>`;const main=document.querySelector('.main-surface'),p=document.getElementById('printable-invoice');p?main.insertBefore(s,p):main.appendChild(s);
15 }
16 function jeAccountOptions(){return getMyAccounts().filter(x=>x.postingAllowed&&x.active!==false).map(x=>'<option value="'+x.id+'">'+esc(x.code)+' — '+esc(x.title)+'</option>').join('')}
js/payments.js
+163 -8
@@ -5,17 +5,148 @@ 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&&['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(){
@@ -59,7 +190,21 @@ function commitSavePayment(){
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);
@@ -71,8 +216,12 @@ function commitSavePayment(){
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';
@@ -86,7 +235,9 @@ function editPayment(id){
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();
@@ -94,8 +245,12 @@ function deletePayment(id){
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(&#39;'+escP(p.id)+'&#39;)">اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deletePayment(&#39;'+escP(p.id)+'&#39;)">ابطال ثبت</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;
scripts/accounting-document-workflow.spec.js
+125
@@ -416,6 +416,131 @@ test('seamless purchase correction: same visible number, no write on opening, sa
416 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
417 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
418 });
419 +function remotePayments(server){return [...server.records.values()].filter(x=>x.collection==='payments').map(x=>copy(x.data));}
420 +async function createUiPayment(page,server,amount=1000,direction='inbound'){
421 + await page.evaluate(()=>{switchView('view-payments');renderPayments()});
422 + await page.locator('#pay-direction').selectOption(direction);
423 + await page.locator('#pay-contact').selectOption('QA_CONTACT');
424 + await page.locator('#pay-method').selectOption('bank');
425 + await page.locator('#pay-amount').fill(String(amount));
426 + await page.locator('#pay-reference').fill('REF-ORIGINAL-001');
427 + await page.evaluate(()=>commitSavePayment());
428 + await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
429 + await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
430 + return remotePayments(server)[0].id;
431 +}
432 +
433 +test('treasury amendment in the same form preserves one record and same reference without on-open ledger writes',async({page})=>{
434 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
435 + const firstId=await createUiPayment(page,server);
436 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
437 + const first=copy(remotePayments(server)[0]);
438 + const oldLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy);
439 + const beforeRpc=server.rpcCount;
440 + await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
441 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
442 + await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
443 + await page.locator('#finora-treasury-document-management-body [data-doc-action="edit"]').click();
444 + await expect(page.locator('#pay-amount')).toHaveValue('1000');
445 + await expect(page.locator('#pay-reference')).toHaveValue('REF-ORIGINAL-001');
446 + await page.evaluate(()=>resetPaymentForm());
447 + expect(server.rpcCount).toBe(beforeRpc);
448 + expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
449 + expect(remotePayments(server)).toHaveLength(1);
450 + await page.locator('#payments-ledger button').first().click();
451 + await page.locator('#pay-amount').fill('1250');
452 + await page.locator('#pay-note').fill('اصلاح مبلغ');
453 + const beforeCorrectionRpc=server.rpcCount;
454 + await page.locator('#pay-save').click();
455 + await expect.poll(()=>remotePayments(server).filter(x=>x.correctsPaymentId===firstId&&x.accountingStatus==='posted').length,{timeout:18000}).toBe(1);
456 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
457 + // Reversal + new source + repost must be a single server-side sync_records batch.
458 + expect(server.rpcCount-beforeCorrectionRpc).toBe(1);
459 + const original=remotePayments(server).find(p=>p.id===firstId);
460 + expect(original).toEqual(first);
461 + const amended=remotePayments(server).find(p=>p.correctsPaymentId===firstId);
462 + expect(amended.amount).toBe(1250);
463 + expect(amended.reference).toBe(first.reference);
464 + expect(amended.journalVoucherId).toBeTruthy();
465 + const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
466 + expect(vouchers).toHaveLength(3);
467 + expect(vouchers.find(x=>x.id===first.journalVoucherId).data.status).toBe('reversed');
468 + expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy));
469 + for(const v of vouchers){
470 + const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
471 + expect(lines.reduce((n,x)=>n+Number(x.data.debit||0),0)).toBe(lines.reduce((n,x)=>n+Number(x.data.credit||0),0));
472 + }
473 + expect(await page.evaluate(()=>paymentVisibleRecords().map(x=>x.id))).toEqual([amended.id]);
474 + expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
475 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
476 + await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
477 + await expect(page.locator('#finora-treasury-document-management-body')).toContainText('REF-ORIGINAL-001');
478 + await page.evaluate(()=>{switchView('view-payments');renderPayments()});
479 + await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
480 + await expect(page.locator('#payments-ledger')).toContainText('۱٬۲۵۰');
481 + await expect(page.locator('#payments-ledger')).toContainText('REF-ORIGINAL-001');
482 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
483 + await page.evaluate(()=>{switchView('view-payments');renderPayments()});
484 + await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
485 + expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
486 +});
487 +
488 +test('treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history',async({page})=>{
489 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
490 + const id=await createUiPayment(page,server,450,'outbound');
491 + const noCheck=await page.evaluate(async id=>{
492 + const p=getMyPayments().find(x=>x.id===id);
493 + const saved=p.method;p.method='cheque';
494 + try{await paymentAmendPosted(id,{direction:p.direction,contactId:p.contactId,companyId:p.companyId,
495 + amount:400,method:'cash',invoiceId:'',invoiceType:'',reference:'x',note:'x'});return 'unsafe';}
496 + catch(e){return String(e.message)}
497 + finally{p.method=saved}
498 + },id);
499 + expect(noCheck).toMatch(/چک|تطبیق/);
500 + const linked=await page.evaluate(async id=>{
501 + const p=getMyPayments().find(x=>x.id===id);
502 + p.invoiceType='purchase';p.invoiceId='QA_LINKED';
503 + try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
504 + catch(e){return String(e.message)}
505 + finally{p.invoiceType='';p.invoiceId=''}
506 + },id);
507 + expect(linked).toMatch(/تسویه|فاکتور|تطبیق/);
508 + const locked=await page.evaluate(async id=>{
509 + const fy=getMyFiscalYears()[0],old=fy.status;
510 + fy.status='locked';
511 + try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
512 + catch(e){return String(e.message)}
513 + finally{fy.status=old}
514 + },id);
515 + expect(locked).toMatch(/قفل|سال مالی/);
516 + await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال اشتباه آزمایشی';});
517 + await page.evaluate(id=>deletePayment(id),id);
518 + await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(2);
519 + expect(remotePayments(server)).toHaveLength(1);
520 + expect(remotePayments(server)[0].id).toBe(id);
521 + expect(await page.evaluate(id=>paymentPostingStatus(getMyPayments().find(x=>x.id===id)),id)).toBe('reversed');
522 + expect(await page.evaluate(()=>paymentEffectiveRecords().length)).toBe(0);
523 + await page.evaluate(()=>{switchView('view-payments');renderPayments()});
524 + await expect(page.locator('#payments-ledger')).toContainText('ابطال‌شده');
525 +});
526 +
527 +test('treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload',async({page})=>{
528 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
529 + const id=await createUiPayment(page,server);
530 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
531 + const before=copy(remotePayments(server)[0]);
532 + const vouchersBefore=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id);
533 + server.failNext=true;
534 + await page.evaluate(id=>editPayment(id),id);
535 + await page.locator('#pay-amount').fill('1800');
536 + await page.locator('#pay-save').click();
537 + await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('اصلاح کامل نشد'))),{timeout:8000}).toBe(true);
538 + expect(server.failCount).toBe(1);
539 + // The RPC did not persist any subset of the combined financial diff.
540 + expect(remotePayments(server)).toEqual([before]);
541 + expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(vouchersBefore);
542 + // After uncertain acknowledgment, do not call the amend API again blindly.
543 +});
544 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
545 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
546 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());