@davoodmehraban89 / Factor-easy / commits / e66cbfe
Fork 0

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

feat(pilot): auditable reversal to editable draft for posted manual and sale documents

* docs(pilot): record owner correction/cancellation request and immutable-ledger scope * feat(pilot): preserve posted vouchers via linked reversal and editable manual correction draft * feat(pilot): correct or cancel posted sales via immutable reversal and linked new draft * feat(pilot): expose corrective draft, auditable cancellation and draft deletion in document manager * feat(pilot): add editable journal drafts and auditable return/cancel actions * test(pilot): cover posted sale correction and manual journal return/edit/repost/cancel * docs(pilot): record correction MVP implementation, pending tests, and per-document limitations * test(pilot): assert posted-invoice cancellation retention and draft-only deletion

davoodmehraban89 committed Oct 14, 2026 at 08:34 UTC e66cbfe4e2a59519af0095f0187a4d1e7aab16d7
6 files changed +328 -8
PROJECT_STATE.md
+13
@@ -170,6 +170,19 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
170 - **Source review of all 21 public authenticated-callable SECURITY DEFINER routines** completed using `pg_get_functiondef`, grouped into six admin license mutators (explicit `is_admin`), two read predicates, seven office, five organizational/invitation, one own-profile RPC. Static guard presence does **not** prove correct tenant isolation or absence of privilege escalation. Authenticated two-user revocation/adversarial parameter checks, private RPC exposure, leaked-password protection, backup/restore and migration parity remain OPEN and require appropriate approval/test identities.
171 - **Boundaries:** Owner-directed deferral of F0-01 slowness persists; F0-01/Phase 0 OPEN. Phase 1 audit slice metadata verification PASS only; **Phase 1 owner acceptance NOT CLAIMED**. No JS runtime, production SQL DDL/DML, Auth/RLS/grant change, new identities, financial records, subscription payments or secrets touched. PR Quality/Security and any post-merge exact-SHA gates **PENDING at this checkpoint**; do not claim release until verified. Rollback revert documentation+read-only SQL check.
172
173 +### 2026-10-14 Owner pilot request — allow correction and cancellation of finalized accounting documents — IMPLEMENTATION GATED
174 +- **New explicit owner request:** while Finora is an incomplete pilot, expose in document management an action described as «برگشت سند قطعی به حالت موقت» so previously finalized records can be amended and re-finalized, and provide deletion/cancellation of documents. Owner requests this even for older finalized documents. This is separate from earlier OTP and slow startup scope.
175 +- **Accounting contract verified before implementation:** `js/journal-engine.js` has distinct draft/posted/reversed states and `jeReverse`, `jeCopyVoucherToDraft`, `jeDeleteDraft`; `js/invoices.js` finalizes new sale invoices explicitly with idempotent source-linked journal posting, and blocks edits to posted sources. Existing `public.finora_guard_posted_journal` and child triggers reject direct changes/deletes of posted or reversed vouchers and lines; only posted→reversed with linked reversal ID is allowed. Current docs require immutable posted history and balanced reversals. **Never** grant direct editing/physical deletion of historical posted rows.
176 +- **Safe product interpretation and first slice:** Provide understandable UX for **post→linked reversal→new editable draft→edit→post** preserving original source/voucher and explicit previous-ID provenance; for 'delete' of posted records expose **audited cancellation/reversal**, not physical erase. For never-posted drafts, permit deletion with confirmation and block any linked references. Use explicit confirmation, authorization `requireWrite`, owner/company/fiscal-period checks, and no retroactive mutation of old finance entries. Start with manual journal and sales invoices under «مدیریت اسناد» in an isolated PR; other document types (purchases, receipts, payments, expenses, tax submissions, linked documents, legacy chartless records) require separate type-specific QA/approval; do not present them as implemented. If atomic data persistence cannot be guaranteed, do not enable live controls prematurely.
177 +- **Authority boundary:** user authorizes the **feature design/development** and ordinary reversible PR, but production posted-data bulk conversion, schema/RLS/Auth/role changes, real ledger correction/deletion, closed-period reversal, offboarding, or migration are **not** authorized by a feature request alone. Test isolated synthetic ledger only, preserve tenant isolation and accounting Golden. No existing production 'final' record is automatically modified. Verify exact SHA Quality/Security/Chromium/three disposable PostgreSQL and independent posting invariants before release; keep owner live acceptance OPEN.
178 +- **Baseline before changes:** protected `main=9d40b70be90172772d12eb9fa33915fe9c055c67`, prior Phase 1 security audit PR #123 merged with Quality, Security, Release Gate, Pages successful. Live Supabase state to be checked read-only before merge. Rollback targeted PR revert; correction/cancellation must retain audit history.
179 +
180 +### 2026-10-14 Pilot correction MVP — CODE + SYNTHETIC E2E TESTS IMPLEMENTED ON BRANCH / CI NOT YET RUN
181 +- **Implemented (isolated GitHub branch only):** `js/journal-engine.js` now has `jeReturnPostedToDraft`, `jeUpdateDraft`, `jeCancelPostedManual`. `js/journal-ui.js` exposes editable saved manual drafts and buttons «برگشت به موقت» and «ابطال» for posted **manual** vouchers, preserving old voucher/lines and creating a balanced posted reversal plus a new linked draft. `js/invoices.js` adds `reopenPostedInvoiceAsDraft`, `cancelPostedInvoicePilot`, `deleteInvoicePilotDraft` for **sale invoices** only. `js/document-management.js` shows confirmed corrective return, auditable cancellation and draft-only delete; old original invoice/number/posted voucher remain linked and unchanged, correction gets a new unique number/ID, `correctsInvoiceId` and `correctionReversalId`, and can be edited and re-finalized through the existing path. It checks owner, active company, open fiscal year, current source posting, an electronic-document exclusion and visible payment references. The server's immutable posted journal triggers are not disabled or changed.
182 +- **Tests:** added two isolated authenticated-mock Chromium journeys in `scripts/accounting-document-workflow.spec.js`: sale save→post→return-to-draft→edit→repost and manual journal post→return→edit→repost→cancel with old ledger history/amount immutability, no duplicate replay, reconciliation and reload. Authoring-side JS syntax parsed **5/5 PASS** via V8 on actual GitHub branch blobs; Chromium E2E, Golden, 3 disposable PostgreSQL, CodeQL, CI and owner real authenticated acceptance **PENDING/NOT VERIFIED** until exact PR-head workflows complete. Do not merge/release on syntax alone.
183 +- **Explicit coverage caveat:** this **is not an 'all financial documents' implementation yet**: purchase source, receipts, payment settlements, expenses, tax-submitted/legal documents, closed fiscal periods, and historical records without valid source-voucher linkage are intentionally not converted automatically. Individual record deletion of a posted voucher is never performed; the visible 'delete/cancel' action records reversal, which is legally and technically distinct. Draft sale deletion is allowed only if not linked to journal/tax doc/payments. No automatic bulk unposting of previously posted records.
184 +- **Risk and follow-up:** `jeReverse` stages multiple saves on the existing debounced sync path; invoice correction requires a server acknowledgment before showing success, whereas manual journal correction relies on existing sync badge. Validate server-side immutable triggers and race/partial write scenarios in independent controlled tests before accepting production correction. If these safeguards fail CI, do not merge. No schema, RLS, Auth, user roles, SMS or live financial documents touched in this branch. Rollback by reverting exact scoped code PR; actual user reversals after future rollout remain immutable historical business events and cannot be erased by code rollback.
185 +
186 ## Current change ledger
187 | 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. |
188
js/document-management.js
+33 -2
@@ -9,18 +9,49 @@ function renderDocumentManagement(){
9 const state=invoiceDocumentStatus(inv);
10 const mayPost=invoiceCreatesAccountingEntry(inv.kind)&&state==='draft';
11 const btn=mayPost?'<button class="btn btn-success btn-inline" data-doc-action="post" data-doc-id="'+esc(inv.id)+'">قطعی‌سازی</button>':'';
12 + const correction=state==='posted'&&invoiceCreatesAccountingEntry(inv.kind)?
13 + '<button class="btn btn-secondary btn-inline" data-doc-action="reopen" data-doc-id="'+esc(inv.id)+'">برگشت قطعی به موقت (اصلاحی)</button> <button class="btn btn-danger btn-inline" data-doc-action="cancel" data-doc-id="'+esc(inv.id)+'">ابطال قطعی</button>':'';
14 + const deleteDraft=state==='draft'&&!inv.journalVoucherId?
15 + '<button class="btn btn-danger btn-inline" data-doc-action="delete" data-doc-id="'+esc(inv.id)+'">حذف پیش‌نویس</button>':'';
16 const edit=invoiceMayEdit(inv)?'<button class="btn btn-secondary btn-inline" data-doc-action="edit" data-doc-id="'+esc(inv.id)+'">ویرایش</button>':'';
17 const posted=inv.journalVoucherId?'<button class="btn btn-secondary btn-inline" data-doc-action="voucher" data-doc-id="'+esc(inv.id)+'">مشاهده سند قطعی</button>':'';
18 const print='<button class="btn btn-secondary btn-inline" data-doc-action="print" data-doc-id="'+esc(inv.id)+'">پیش‌نمایش چاپ</button>';
15 - return '<tr><td>'+esc(inv.number||'—')+'</td><td>'+esc(inv.date||'—')+'</td><td>'+esc(inv.companyName||'—')+'</td><td>'+esc(inv.contactName||'—')+'</td><td>'+Number(inv.grandTotal||0).toLocaleString('fa-IR')+'</td><td>'+esc(invoiceDocumentStatusLabel(inv))+'</td><td style="display:flex;flex-wrap:wrap;gap:5px">'+edit+btn+posted+print+'</td></tr>';
19 + return '<tr><td>'+esc(inv.number||'—')+'</td><td>'+esc(inv.date||'—')+'</td><td>'+esc(inv.companyName||'—')+'</td><td>'+esc(inv.contactName||'—')+'</td><td>'+Number(inv.grandTotal||0).toLocaleString('fa-IR')+'</td><td>'+esc(invoiceDocumentStatusLabel(inv))+'</td><td style="display:flex;flex-wrap:wrap;gap:5px">'+edit+btn+correction+deleteDraft+posted+print+'</td></tr>';
20 }).join(''):'<tr><td colspan="7" class="af-empty">سندی در این وضعیت ثبت نشده است.</td></tr>';
21 }
18 -document.addEventListener('click',event=>{
22 +document.addEventListener('click',async event=>{
23 const button=event.target instanceof Element?event.target.closest('#view-journal button[data-doc-action]'):null;
24 if(!button)return;
25 const inv=getMyInvoices().find(x=>x.id===button.dataset.docId);
26 if(!inv)return;
27 const action=button.dataset.docAction;
28 + if(action==='reopen'){
29 + const reason=prompt('دلیل برگشت از قطعی به موقت (نسخه اصلاحی):','اصلاح اطلاعات دوره پایلوت');
30 + if(reason===null)return;
31 + if(!String(reason).trim())return alert('دلیل اصلاح الزامی است.');
32 + if(!confirm('سند قطعی قدیمی و سطرهای آن حفظ می‌شوند؛ یک سند برگشتی و نسخه موقت جدید برای اصلاح ساخته می‌شود. ادامه می‌دهید؟'))return;
33 + try{
34 + const draftId=await reopenPostedInvoiceAsDraft(inv.id,reason);
35 + alert('نسخه موقت اصلاحی ساخته و در سرور ثبت شد. شماره فاکتور اصلی محفوظ است.');
36 + renderDocumentManagement();editInvoice(draftId);
37 + }catch(e){alert('برگشت به موقت تأیید نشد: '+e.message);}
38 + return;
39 + }
40 + if(action==='cancel'){
41 + const reason=prompt('دلیل ابطال سند قطعی:','اشتباه ثبت در دوره پایلوت');
42 + if(reason===null)return;
43 + if(!String(reason).trim())return alert('دلیل ابطال الزامی است.');
44 + if(!confirm('این عملیات سند قطعی را پاک نمی‌کند؛ یک سند معکوسِ قابل‌ردیابی ثبت می‌شود. تأیید می‌کنید؟'))return;
45 + try{await cancelPostedInvoicePilot(inv.id,reason);alert('ابطال از طریق سند برگشتی در سرور ثبت شد.');renderDocumentManagement();}
46 + catch(e){alert('ابطال تأیید نشد: '+e.message);}
47 + return;
48 + }
49 + if(action==='delete'){
50 + if(!confirm('پیش‌نویس انتخابی حذف شود؟ سند قطعی/تاریخچه حذف نخواهد شد.'))return;
51 + try{deleteInvoicePilotDraft(inv.id);renderDocumentManagement();}
52 + catch(e){alert('حذف پیش‌نویس مجاز نیست: '+e.message);}
53 + return;
54 + }
55 if(action==='edit')return editInvoice(inv.id);
56 if(action==='post')return finalizeInvoiceDocumentUi(inv.id);
57 if(action==='print')return renderAndPrintDirect(inv.id);
js/invoices.js
+76
@@ -356,6 +356,82 @@ async function finalizeInvoiceDocumentUi(id){
356 catch(e){alert('قطعی‌سازی تأیید نشد: '+e.message)}
357 }
358
359 +// Pilot only: a posted sale is NEVER turned back into a mutable posted record.
360 +// Compensate the original posting and create a new, traceable, editable invoice.
361 +function invoicePilotCorrectionEligible(inv){
362 + if(!inv||inv.ownerUserId!==currentUser?.id||!invoiceCreatesAccountingEntry(inv.kind))throw new Error('فاکتور فروش معتبر برای حساب جاری انتخاب نشده است.');
363 + if(inv.companyId!==afCompanyId())throw new Error('شرکت فعلی با سند مطابقت ندارد.');
364 + if(invoiceDocumentStatus(inv)!=='posted')throw new Error('فقط فاکتور قطعی قابل برگشت به موقت است.');
365 + const v=typeof jeActiveSourceVoucher==='function'?jeActiveSourceVoucher(inv):null;
366 + if(!v||v.sourceType!=='sale'||v.sourceId!==inv.id)throw new Error('سند حسابداری قطعی و متصل به این فاکتور یافت نشد؛ ابتدا سند را تطبیق دهید.');
367 + const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);
368 + const newFY=jeFiscalForDate(getJalaliNumeric());
369 + if(!fy||fy.status==='locked'||!newFY||newFY.status==='locked')throw new Error('اصلاح در سال مالی قفل‌شده یا بدون سال مالی باز مجاز نیست.');
370 + // Electronic tax references and settled receipts require their own controlled workflow.
371 + if(inv.electronicDoc)throw new Error('این فاکتور سند الکترونیکی مرتبط دارد؛ ابتدا وضعیت مالیاتی آن بررسی شود.');
372 + if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceId===inv.id||p.sourceInvoiceId===inv.id||p.relatedInvoiceId===inv.id))
373 + throw new Error('این فاکتور به دریافت/پرداخت متصل است؛ اصلاح ابتدا نیازمند تطبیق تسویه است.');
374 + return v;
375 +}
376 +function invoicePilotCorrectionNumber(inv){
377 + const initial=String(inv.number||inv.id).trim()+'-اصلاح';
378 + let n=1,number=initial+'-'+n;
379 + while(getMyInvoices().some(x=>x.companyId===inv.companyId&&String(x.number||'').trim()===number)){
380 + n++;number=initial+'-'+n;
381 + if(n>10000)throw new Error('ایجاد شماره نسخه اصلاحی یکتا ممکن نیست.');
382 + }
383 + return number;
384 +}
385 +async function invoicePilotAwaitSync(entries){
386 + if(typeof runSync!=='function'||typeof syncSnap==='undefined')return;
387 + await runSync();
388 + const deadline=Date.now()+20000;
389 + while(Date.now()<deadline){
390 + if(!syncRunning&&!syncPending&&entries.every(key=>syncSnap.has(key)))return;
391 + if(syncFailCount>0)break;
392 + await new Promise(resolve=>setTimeout(resolve,200));
393 + }
394 + throw new Error('سرور هنوز تغییرات را تأیید نکرده است. بدون بررسی همگام‌سازی، عملیات را تکرار نکنید.');
395 +}
396 +async function reopenPostedInvoiceAsDraft(invoiceId,reason){
397 + if(!requireWrite())throw new Error('مجوز اصلاح ندارید.');
398 + const inv=getMyInvoices().find(x=>x.id===invoiceId);
399 + const v=invoicePilotCorrectionEligible(inv);
400 + const why=String(reason||'').trim();if(!why)throw new Error('دلیل برگشت سند الزامی است.');
401 + // Resolve number/clone before reversing, so validation failures do not touch posting.
402 + const number=invoicePilotCorrectionNumber(inv);
403 + const id=afId('INV'),now=new Date().toISOString();
404 + const draft={...inv,id,number,createdAt:now,updatedAt:now,documentStatus:'draft',accountingStatus:'draft',documentVersion:1,accountingVersion:1,
405 + correctsInvoiceId:inv.id,correctsVoucherId:v.id,correctionReason:why,
406 + correctionOriginalNumber:inv.number};
407 + for(const key of ['journalVoucherId','accountingPostedAt','documentPostedAt','documentPostedBy','postedAt','postedBy','reversalVoucherId'])delete draft[key];
408 + // jeReverse records a balanced linked reversal; historical source and lines stay immutable.
409 + const reversal=jeReverse(v.id,getJalaliNumeric(),why);
410 + draft.correctionReversalId=reversal.id;
411 + datastore.invoices.push(draft);saveDatastore();
412 + await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id,'invoices|'+draft.id]);
413 + refreshAllSurfaces();return draft.id;
414 +}
415 +async function cancelPostedInvoicePilot(invoiceId,reason){
416 + if(!requireWrite())throw new Error('مجوز ابطال ندارید.');
417 + const inv=getMyInvoices().find(x=>x.id===invoiceId);
418 + const v=invoicePilotCorrectionEligible(inv);
419 + const why=String(reason||'').trim();if(!why)throw new Error('دلیل ابطال الزامی است.');
420 + const reversal=jeReverse(v.id,getJalaliNumeric(),'ابطال پایلوت: '+why);
421 + await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id]);
422 + refreshAllSurfaces();return reversal.id;
423 +}
424 +function deleteInvoicePilotDraft(invoiceId){
425 + if(!requireWrite())throw new Error('مجوز حذف ندارید.');
426 + const inv=getMyInvoices().find(x=>x.id===invoiceId);
427 + if(!inv||inv.ownerUserId!==currentUser?.id||inv.companyId!==afCompanyId()||invoiceDocumentStatus(inv)!=='draft'||inv.journalVoucherId)
428 + throw new Error('فقط پیش‌نویس ثبت‌نشده همین شرکت قابل حذف است.');
429 + if(inv.electronicDoc)throw new Error('سند الکترونیکی مرتبط ابتدا باید بررسی شود.');
430 + if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceId===inv.id||p.sourceInvoiceId===inv.id||p.relatedInvoiceId===inv.id))
431 + throw new Error('این فاکتور ارجاع دریافت/پرداخت دارد و قابل حذف نیست.');
432 + datastore.invoices=datastore.invoices.filter(x=>x.id!==inv.id);
433 + saveDatastore();refreshAllSurfaces();return true;
434 +}
435 function commitSaveInvoice(){
436 if(!requireWrite())return;
437 if(!currentUser)return;
js/journal-engine.js
+59
@@ -64,6 +64,65 @@ function jeReverse(voucherId,date,reason){
64 function jeCopyVoucherToDraft(voucherId,date){
65 if(!requireWrite())throw new Error('write denied');const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v)throw new Error('سند پیدا نشد.');const lines=getMyJournalLines().filter(x=>x.voucherId===v.id).sort((a,b)=>(a.lineNo||0)-(b.lineNo||0)).map(l=>({accountId:l.accountId,debit:l.debit,credit:l.credit,description:l.description||'',dimensions:getMyJournalLineDimensions().filter(d=>d.journalLineId===l.id).map(d=>({dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))}));return jeCreateDraft({date:date||getJalaliNumeric(),description:'کپی سند '+v.number+(v.description?' — '+v.description:''),reference:v.reference||('سند '+v.number),voucherType:'copy',sourceType:'manual',sourceId:'',lines});
66 }
67 +// Pilot correction: keep the posted voucher and its original lines immutable.
68 +// "Return to draft" means a paired posted reversal plus a NEW linked draft.
69 +function jeVoucherDraftInput(voucherId){
70 + const v=getMyJournalVouchers().find(x=>x.id===voucherId);
71 + if(!v)throw new Error('سند برای شرکت جاری پیدا نشد.');
72 + const lines=getMyJournalLines().filter(x=>x.voucherId===v.id).sort((a,b)=>(a.lineNo||0)-(b.lineNo||0)).map(l=>({
73 + accountId:l.accountId,debit:l.debit,credit:l.credit,description:l.description||'',
74 + dimensions:getMyJournalLineDimensions().filter(d=>d.journalLineId===l.id).map(d=>({dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))
75 + }));
76 + return {voucher:v,lines};
77 +}
78 +function jeUpdateDraft(voucherId,input){
79 + if(!requireWrite())throw new Error('مجوز ویرایش ندارید.');
80 + const v=getMyJournalVouchers().find(x=>x.id===voucherId);
81 + if(!v||v.status!=='draft'||v.sourceType!=='manual'||v.sourceId||v.voucherType==='reversal')throw new Error('فقط پیش‌نویس دستی و بدون ثبت منبع قابل ویرایش است.');
82 + const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);
83 + const date=input.date||v.date;
84 + if(!fy||fy.status==='locked'||!jeFiscalForDate(date)||jeFiscalForDate(date).id!==fy.id)throw new Error('تاریخ ویرایش باید در سال مالی باز همین سند باشد.');
85 + const number=String(input.number||v.number).trim();
86 + if(!number||jeVoucherNumberTaken(v.fiscalYearId,number,v.id))throw new Error('شماره سند معتبر یا یکتا نیست.');
87 + const totals=jeValidateLines(input.lines);
88 + const replacementLines=[],replacementDims=[];
89 + input.lines.forEach((l,n)=>{
90 + const lineId=afId('JL'),dims=l.dimensions||[];
91 + replacementLines.push({id:lineId,ownerUserId:currentUser.id,companyId:v.companyId,voucherId:v.id,lineNo:n+1,accountId:l.accountId,debit:jeNum(l.debit),credit:jeNum(l.credit),description:String(l.description||''),counterpartyId:l.counterpartyId||jeDimensionValueBySource(dims,'contact'),projectId:l.projectId||jeDimensionValueBySource(dims,'project')});
92 + dims.forEach(d=>replacementDims.push({id:afId('JLD'),ownerUserId:currentUser.id,companyId:v.companyId,voucherId:v.id,journalLineId:lineId,dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}));
93 + });
94 + // All checks completed before the first mutation. Posted/reversed rows are untouched.
95 + const oldIds=new Set(getMyJournalLines().filter(l=>l.voucherId===v.id).map(l=>l.id));
96 + datastore.journalLineDimensions=datastore.journalLineDimensions.filter(d=>!oldIds.has(d.journalLineId)).concat(replacementDims);
97 + datastore.journalLines=datastore.journalLines.filter(l=>l.voucherId!==v.id).concat(replacementLines);
98 + Object.assign(v,{number,date,description:String(input.description||''),reference:String(input.reference||''),voucherType:String(input.voucherType||v.voucherType),totalDebit:totals.debit,totalCredit:totals.credit,editedAt:new Date().toISOString(),editedBy:currentUser.id});
99 + saveDatastore();return v;
100 +}
101 +function jeReturnPostedToDraft(voucherId,reason,date){
102 + if(!requireWrite())throw new Error('مجوز اصلاح سند ندارید.');
103 + const {voucher:v,lines}=jeVoucherDraftInput(voucherId);
104 + if(v.status!=='posted'||v.sourceType!=='manual'||v.sourceId||v.voucherType==='reversal')throw new Error('بازگشت به موقت برای این نوع سند پشتیبانی نمی‌شود؛ از مدیریت سند منبع استفاده کنید.');
105 + const oldYear=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);
106 + const correctionDate=date||getJalaliNumeric(),newYear=jeFiscalForDate(correctionDate);
107 + if(!oldYear||oldYear.status==='locked'||!newYear||newYear.status==='locked')throw new Error('سند در سال مالی قفل‌شده قابل برگشت نیست.');
108 + if(!String(reason||'').trim())throw new Error('دلیل اصلاح سند الزامی است.');
109 + jeValidateLines(lines);
110 + // reversal is a posted compensating voucher; old voucher stays reversed in history.
111 + const reversal=jeReverse(v.id,correctionDate,String(reason).trim());
112 + const draft=jeCreateDraft({date:correctionDate,description:v.description,reference:v.reference,voucherType:['manual','adjustment','opening','closing'].includes(v.voucherType)?v.voucherType:'manual',sourceType:'manual',lines});
113 + draft.correctionOfVoucherId=v.id;draft.correctionReversalId=reversal.id;
114 + draft.correctionReason=String(reason).trim();saveDatastore();
115 + return {draft,reversal,original:v};
116 +}
117 +function jeCancelPostedManual(voucherId,reason,date){
118 + if(!requireWrite())throw new Error('مجوز ابطال سند ندارید.');
119 + const v=getMyJournalVouchers().find(x=>x.id===voucherId);
120 + if(!v||v.status!=='posted'||v.sourceType!=='manual'||v.sourceId||v.voucherType==='reversal')throw new Error('ابطال مستقیم فقط برای اسناد دستی قطعی مجاز است.');
121 + if(!String(reason||'').trim())throw new Error('دلیل ابطال الزامی است.');
122 + const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);
123 + if(!fy||fy.status==='locked')throw new Error('سال مالی سند قفل است.');
124 + return jeReverse(v.id,date||getJalaliNumeric(),'ابطال پایلوت: '+String(reason).trim());
125 +}
126 function jeDeleteDraft(voucherId){if(!requireWrite())return false;const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='draft')throw new Error('سند قطعی/برگشتی حذف‌پذیر نیست.');const ids=getMyJournalLines().filter(x=>x.voucherId===voucherId).map(x=>x.id);datastore.journalLineDimensions=datastore.journalLineDimensions.filter(x=>!ids.includes(x.journalLineId));datastore.journalLines=datastore.journalLines.filter(x=>x.voucherId!==voucherId);datastore.journalVouchers=datastore.journalVouchers.filter(x=>x.id!==voucherId);saveDatastore();return true}
127 function jeLedgerRows(){return getMyJournalLines().flatMap(l=>{const v=getMyJournalVouchers().find(x=>x.id===l.voucherId);return v&&['posted','reversed'].includes(v.status)?[{...l,voucher:v,account:jePostingAccount(l.accountId)}]:[]})}
128 function jeTrialBalance(){const m={};jeLedgerRows().forEach(l=>{if(!m[l.accountId])m[l.accountId]={accountId:l.accountId,code:l.account?.code||'',title:l.account?.title||'',debit:0,credit:0};m[l.accountId].debit+=jeNum(l.debit);m[l.accountId].credit+=jeNum(l.credit)});return Object.values(m).map(x=>({...x,balance:x.debit-x.credit})).sort((a,b)=>String(a.code).localeCompare(String(b.code),undefined,{numeric:true}))}
js/journal-ui.js
+33 -6
@@ -3,11 +3,11 @@ function ensureJournalView(){
3 if(document.getElementById('view-journal'))return;const s=document.createElement('section');s.id='view-journal';s.className='view-pane';s.innerHTML=`<div class="af-head"><div><h1>اسناد حسابداری</h1><p>ثبت دوبل، ابعاد تحلیلی، قطعی‌سازی و برگشت اسناد</p></div></div>
4 <div class="card" data-finora-task="new"><h3>ثبت سند حسابداری</h3><div class="form-row"><div class="form-group"><label>شماره سند</label><input id="je-number" class="form-control" placeholder="خودکار"></div><div class="form-group"><label>تاریخ</label><input id="je-date" class="form-control"></div><div class="form-group"><label>نوع سند</label><select id="je-voucher-type" class="form-control"><option value="manual">عادی</option><option value="adjustment">اصلاحی</option><option value="opening">افتتاحیه</option><option value="closing">اختتامیه</option></select></div><div class="form-group"><label>مرجع</label><input id="je-reference" class="form-control" placeholder="شماره فاکتور/قرارداد/نامه"></div></div>
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><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="jeAddRow()">+ آرتیکل</button><button class="btn btn-success" onclick="jeSaveManual()">ثبت پیش‌نویس</button></div></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>
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="legacy_review">قدیمی و نیازمند تطبیق</option></select>
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></div>
12 <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);
13 }
@@ -24,8 +24,35 @@ function jeCollectRows(){return[...document.querySelectorAll('#je-lines .je-line
24 function jeUpdateTotals(){const rows=jeCollectRows(),d=rows.reduce((s,x)=>s+(Number(x.debit)||0),0),c=rows.reduce((s,x)=>s+(Number(x.credit)||0),0),diff=d-c,box=document.getElementById('je-totals');if(box)box.textContent='جمع بدهکار: '+d.toLocaleString('fa-IR')+' | جمع بستانکار: '+c.toLocaleString('fa-IR')+' | اختلاف: '+Math.abs(diff).toLocaleString('fa-IR')+(d>0&&Math.abs(diff)<0.0001?' ✓ تراز':'')}
25 function jeRemoveRow(btn){const rows=document.querySelectorAll('#je-lines .je-line');if(rows.length<=2)return alert('سند باید حداقل دو آرتیکل داشته باشد.');btn.closest('.je-line').remove();jeUpdateTotals()}
26 function jeCopyRow(btn){const row=btn.closest('.je-line'),seed={accountId:row.querySelector('.je-account').value,debit:row.querySelector('.je-debit').value,credit:row.querySelector('.je-credit').value,description:row.querySelector('.je-line-desc').value,dimensions:[...row.querySelectorAll('.je-dim')].filter(x=>x.value).map(x=>({dimensionTypeId:x.dataset.type,dimensionValueId:x.value}))};jeAddRow(seed)}
27 -function jeClearManualForm(){['je-number','je-reference','je-desc'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});const box=document.getElementById('je-lines');if(box)box.innerHTML='';jeAddRow();jeAddRow();jeUpdateTotals()}
28 -function jeSaveManual(){try{const v=jeCreateDraft({number:document.getElementById('je-number').value,date:document.getElementById('je-date').value||getJalaliNumeric(),voucherType:document.getElementById('je-voucher-type').value,reference:document.getElementById('je-reference').value,description:document.getElementById('je-desc').value,lines:jeCollectRows()});alert('پیش‌نویس سند '+v.number+' ثبت شد.');jeClearManualForm();renderJournal()}catch(e){alert(e.message)}}
27 +function jeClearManualForm(){['je-number','je-reference','je-desc','je-edit-voucher-id'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});const box=document.getElementById('je-lines');if(box)box.innerHTML='';const btn=document.getElementById('je-save-draft-button');if(btn)btn.textContent='ثبت پیش‌نویس';const cancel=document.getElementById('je-cancel-edit-button');if(cancel)cancel.style.display='none';jeAddRow();jeAddRow();jeUpdateTotals()}
28 +function jeLoadDraftUi(id){
29 + try{
30 + const {voucher:v,lines}=jeVoucherDraftInput(id);
31 + if(v.status!=='draft'||v.sourceType!=='manual'||v.sourceId)throw new Error('این سند موقت از نوع قابل‌ویرایش دستی نیست.');
32 + const values=[['je-edit-voucher-id',v.id],['je-number',v.number],['je-date',v.date],['je-voucher-type',v.voucherType],['je-reference',v.reference||''],['je-desc',v.description||'']];
33 + values.forEach(([name,value])=>{const el=document.getElementById(name);if(el)el.value=value});
34 + const box=document.getElementById('je-lines');if(box)box.innerHTML='';
35 + lines.forEach(l=>jeAddRow(l));
36 + const btn=document.getElementById('je-save-draft-button');if(btn)btn.textContent='ذخیره اصلاحات سند موقت';
37 + const cancel=document.getElementById('je-cancel-edit-button');if(cancel)cancel.style.display='inline-flex';
38 + jeUpdateTotals();document.getElementById('je-lines')?.scrollIntoView({block:'nearest'});
39 + }catch(e){alert(e.message)}
40 +}
41 +function jeReturnToDraftUi(id){
42 + const why=prompt('دلیل بازگردانی سند قطعی به موقت:','اصلاح سند در دوره پایلوت');
43 + if(why===null)return;
44 + if(!String(why).trim())return alert('دلیل اصلاح الزامی است.');
45 + if(!confirm('سند قدیمی و آرتیکل‌های آن حذف نمی‌شوند. سند برگشتی ثبت و نسخه موقتِ قابل‌ویرایش ساخته می‌شود. ادامه؟'))return;
46 + try{const out=jeReturnPostedToDraft(id,why,getJalaliNumeric());renderJournal();jeLoadDraftUi(out.draft.id);alert('سند اصلاحی موقت '+out.draft.number+' ایجاد شد؛ پس از اصلاح، مجدداً قطعی کنید.');}catch(e){alert(e.message)}
47 +}
48 +function jeCancelPostedUi(id){
49 + const why=prompt('دلیل ابطال سند قطعی:','ابطال سند در دوره پایلوت');
50 + if(why===null)return;
51 + if(!String(why).trim())return alert('دلیل ابطال الزامی است.');
52 + if(!confirm('سند قطعی بدون حذف سابقه، با سند برگشتی خنثی شود؟'))return;
53 + try{jeCancelPostedManual(id,why,getJalaliNumeric());renderJournal()}catch(e){alert(e.message)}
54 +}
55 +function jeSaveManual(){try{const input={number:document.getElementById('je-number').value,date:document.getElementById('je-date').value||getJalaliNumeric(),voucherType:document.getElementById('je-voucher-type').value,reference:document.getElementById('je-reference').value,description:document.getElementById('je-desc').value,lines:jeCollectRows()};const editId=document.getElementById('je-edit-voucher-id')?.value;const v=editId?jeUpdateDraft(editId,input):jeCreateDraft(input);alert('پیش‌نویس سند '+v.number+' ذخیره شد.');jeClearManualForm();renderJournal()}catch(e){alert(e.message)}}
56 function jePostUi(id){try{jePost(id);renderJournal()}catch(e){alert(e.message)}}
57 function jeReverseUi(id){const why=prompt('علت برگشت سند:','اصلاح ثبت');if(why===null)return;try{jeReverse(id,getJalaliNumeric(),why);renderJournal()}catch(e){alert(e.message)}}
58 function jeCopyVoucherUi(id){try{const v=jeCopyVoucherToDraft(id,getJalaliNumeric());alert('کپی سند به پیش‌نویس '+v.number+' ایجاد شد.');renderJournal()}catch(e){alert(e.message)}}
@@ -33,7 +60,7 @@ function jeDeleteUi(id){if(!confirm('پیش‌نویس حذف شود؟'))return;
60 function jeStatusLabel(v){return v==='draft'?'پیش‌نویس':v==='posted'?'قطعی':v==='reversed'?'برگشت‌شده':v}
61 function jeTypeLabel(v){return({manual:'عادی',adjustment:'اصلاحی',opening:'افتتاحیه',closing:'اختتامیه',copy:'کپی',reversal:'برگشت'})[v]||v||'عادی'}
62 function renderJournal(){
36 - ensureJournalView();if(!currentUser)return;if(typeof afEnsureAccountingP0Compatibility==='function')afEnsureAccountingP0Compatibility();jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(jeTypeLabel(v.voucherType))+'</td><td>'+esc(v.reference||'—')+'</td><td>'+esc(v.description)+'</td><td>'+esc(jeStatusLabel(v.status))+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+esc(v.sourceType||'manual')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> <button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف</button> ':v.status==='posted'?'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">برگشت</button> ':'')+'<button class="btn btn-secondary btn-inline" onclick="jeCopyVoucherUi(\''+v.id+'\')">کپی</button></td></tr>').join(''):'<tr><td colspan="10" class="af-empty">سندی ثبت نشده است.</td></tr>';
63 + ensureJournalView();if(!currentUser)return;if(typeof afEnsureAccountingP0Compatibility==='function')afEnsureAccountingP0Compatibility();jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(jeTypeLabel(v.voucherType))+'</td><td>'+esc(v.reference||'—')+'</td><td>'+esc(v.description)+'</td><td>'+esc(jeStatusLabel(v.status))+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+esc(v.sourceType||'manual')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> '+(v.sourceType==='manual'&&!v.sourceId?'<button class="btn btn-secondary btn-inline" onclick="jeLoadDraftUi(\''+v.id+'\')">ویرایش موقت</button> ':'')+'<button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف موقت</button> ':v.status==='posted'?(v.sourceType==='manual'&&!v.sourceId&&v.voucherType!=='reversal'?'<button class="btn btn-secondary btn-inline" onclick="jeReturnToDraftUi(\''+v.id+'\')">برگشت به موقت</button> <button class="btn btn-danger btn-inline" onclick="jeCancelPostedUi(\''+v.id+'\')">ابطال</button> ':'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">سند معکوس</button> '):'')+'<button class="btn btn-secondary btn-inline" onclick="jeCopyVoucherUi(\''+v.id+'\')">کپی</button></td></tr>').join(''):'<tr><td colspan="10" class="af-empty">سندی ثبت نشده است.</td></tr>';
64 const tb=document.getElementById('je-trial'),rows=jeTrialBalance();if(tb)tb.innerHTML=rows.length?rows.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.title)+'</td><td>'+x.debit.toLocaleString('fa-IR')+'</td><td>'+x.credit.toLocaleString('fa-IR')+'</td><td>'+x.balance.toLocaleString('fa-IR')+'</td></tr>').join(''):'<tr><td colspan="5" class="af-empty">گردشی وجود ندارد.</td></tr>';
65 const d=document.getElementById('je-date');if(d&&!d.value)d.value=getJalaliNumeric();if(!document.querySelector('#je-lines .je-line')){jeAddRow();jeAddRow()}jeUpdateTotals();if(typeof renderDocumentManagement==='function')renderDocumentManagement();
66 }
scripts/accounting-document-workflow.spec.js
+114
@@ -133,6 +133,120 @@ test('formal invoice remains editable draft across server reload; explicit posti
133 expect(saved.grandTotal).toBe(4500);
134 expect(saved.documentVersion).toBe(2);
135 });
136 +test('posted sale can be returned to an editable corrective draft; original voucher stays immutable and balances',async({page})=>{
137 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
138 + await fillInvoice(page,'PILOT-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
139 + await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
140 + const originalId=remoteInvoices(server)[0].id;
141 + await page.evaluate(id=>finalizeInvoiceDocument(id),originalId);
142 + await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
143 + const before=remoteInvoices(server)[0],originalVoucherId=before.journalVoucherId;
144 + const originalLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy);
145 + const result=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تصحیح تعداد پایلوت'),originalId);
146 + expect(result).toBeTruthy();expect(result).not.toBe(originalId);
147 + await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
148 + const after=remoteInvoices(server),original=after.find(i=>i.id===originalId),draft=after.find(i=>i.id===result);
149 + expect(original.grandTotal).toBe(3000);
150 + expect(original.journalVoucherId).toBe(originalVoucherId);
151 + expect(draft.correctsInvoiceId).toBe(originalId);
152 + expect(draft.documentStatus).toBe('draft');
153 + expect(draft.journalVoucherId).toBeUndefined();
154 + expect(draft.number).not.toBe(original.number);
155 + const allVouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
156 + expect(allVouchers).toHaveLength(2);
157 + expect(allVouchers.find(x=>x.id===originalVoucherId).data.status).toBe('reversed');
158 + const reversal=allVouchers.find(x=>x.id!==originalVoucherId);
159 + expect(reversal.data.status).toBe('posted');
160 + expect(originalLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy));
161 + expect(await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),originalId)).toBe('reversed');
162 + // The replacement source uses the normal draft editor and preserves provenance.
163 + await page.evaluate(id=>editInvoice(id),result);
164 + await expect(page.locator('#edit-invoice-id')).toHaveValue(result);
165 + await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
166 + await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
167 + await page.evaluate(()=>commitSaveInvoice());
168 + await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.grandTotal,{timeout:13000}).toBe(4500);
169 + await page.evaluate(id=>finalizeInvoiceDocument(id),result);
170 + await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.accountingStatus,{timeout:13000}).toBe('posted');
171 + const later=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
172 + expect(later).toHaveLength(3);
173 + expect(later.find(x=>x.id===originalVoucherId).data.status).toBe('reversed');
174 + const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
175 + for(const v of later){
176 + const subset=lines.filter(l=>l.data.voucherId===v.id);
177 + expect(subset.reduce((t,l)=>t+Number(l.data.debit||0),0)).toBe(subset.reduce((t,l)=>t+Number(l.data.credit||0),0));
178 + }
179 + // Reopening the same historical voucher again is blocked.
180 + const retry=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},originalId);
181 + expect(retry).not.toBe('unexpected');
182 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
183 + const persisted=await page.evaluate(id=>({old:invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),drafts:getMyInvoices().filter(i=>i.correctsInvoiceId===id).map(i=>i.accountingStatus)}),originalId);
184 + expect(persisted.old).toBe('reversed');
185 + expect(persisted.drafts).toEqual(['posted']);
186 +});
187 +
188 +test('pilot manual journal correction permits draft edits, balanced repost and auditable cancellation',async({page})=>{
189 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
190 + const first=await page.evaluate(()=>{
191 + const v=jeCreateDraft({number:'8801',date:'1405/07/19',description:'ثبت آزمایشی',sourceType:'manual',
192 + lines:[{accountId:'A_CASH',debit:1000,credit:0},{accountId:'A_REV',debit:0,credit:1000}]});
193 + jePost(v.id);return v.id;
194 + });
195 + await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='journalVouchers').length,{timeout:13000}).toBe(1);
196 + const oldLineData=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy);
197 + const ids=await page.evaluate(id=>{
198 + const out=jeReturnPostedToDraft(id,'اشتباه مبلغ آزمایشی','1405/07/19');
199 + return {draft:out.draft.id,reversal:out.reversal.id,old:out.original.id};
200 + },first);
201 + await page.evaluate(id=>jeUpdateDraft(id,{date:'1405/07/19',description:'اصلاح مبلغ به ۲۰۰۰',
202 + lines:[{accountId:'A_CASH',debit:2000,credit:0},{accountId:'A_REV',debit:0,credit:2000}]}),ids.draft);
203 + const details=await page.evaluate(({draft,old})=>{
204 + jePost(draft);return {old:getMyJournalVouchers().find(x=>x.id===old).status,new:getMyJournalVouchers().find(x=>x.id===draft).status,trial:jeTrialBalance()};
205 + },ids);
206 + expect(details.old).toBe('reversed');expect(details.new).toBe('posted');
207 + expect(details.trial.find(x=>x.accountId==='A_CASH').balance).toBe(2000);
208 + await page.evaluate(id=>jeCancelPostedManual(id,'ابطال بعد از تست','1405/07/19'),ids.draft);
209 + await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(4);
210 + const final=await page.evaluate(()=>jeTrialBalance());
211 + expect(final.reduce((sum,row)=>sum+row.debit-row.credit,0)).toBe(0);
212 + expect(final.find(x=>x.accountId==='A_CASH').balance).toBe(0);
213 + expect(oldLineData).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy));
214 + const rows=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
215 + expect(rows.find(x=>x.id===first).data.status).toBe('reversed');
216 + expect(rows.find(x=>x.id===ids.draft).data.status).toBe('reversed');
217 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
218 + expect(await page.evaluate(()=>jeTrialBalance().find(x=>x.accountId==='A_CASH').balance)).toBe(0);
219 +});
220 +
221 +test('pilot cancellation preserves posted invoice record while only unposted drafts can be deleted',async({page})=>{
222 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
223 + await fillInvoice(page,'PILOT-CANCEL-001',2);await page.evaluate(()=>commitSaveInvoice());
224 + await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
225 + const invoiceId=remoteInvoices(server)[0].id;
226 + await page.evaluate(id=>finalizeInvoiceDocument(id),invoiceId);
227 + const original=remoteInvoices(server)[0];
228 + expect(original.accountingStatus).toBe('posted');
229 + const blocked=await page.evaluate(id=>{try{deleteInvoicePilotDraft(id);return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
230 + expect(blocked).not.toBe('unexpected');
231 + await page.evaluate(id=>cancelPostedInvoicePilot(id,'ابطال سند پایلوت'),invoiceId);
232 + await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(2);
233 + expect(remoteInvoices(server)[0].id).toBe(invoiceId);
234 + expect(remoteInvoices(server)[0].grandTotal).toBe(original.grandTotal);
235 + const status=await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),invoiceId);
236 + expect(status).toBe('reversed');
237 + const bad=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
238 + expect(bad).not.toBe('unexpected');
239 + // A separate never-posted invoice may be deleted; posted history stays intact.
240 + await fillInvoice(page,'PILOT-DELETE-DRAFT-001',1);await page.evaluate(()=>commitSaveInvoice());
241 + await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
242 + const draft=remoteInvoices(server).find(x=>x.number==='PILOT-DELETE-DRAFT-001');
243 + expect(draft).toBeTruthy();
244 + await page.evaluate(id=>deleteInvoicePilotDraft(id),draft.id);
245 + await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
246 + expect(remoteInvoices(server)[0].id).toBe(invoiceId);
247 + expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(2);
248 +});
249 +
250 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
251 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
252 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());