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

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

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

Synced Dec 3, 17:00 UTC

feat(ux): same-document sales and purchase amendments with hidden linked journal revisions

* docs: record owner's same-document amendment UX and deferred financial mutation contract * feat(ux): edit posted sale in same form and keep technical correction versions out of invoice archive * feat(ux): amend existing purchase form on save, fold technical revisions and preserve visible number * feat(ux): one logical sale/purchase row, direct existing-document edit without journal prompts * fix(print): always print current visible sale revision under unchanged business number * test(ux): verify same sale/purchase number, deferred reversal, cancel, save, print and reload * docs(ux): record deferred in-place document correction implementation and validation gates * fix(ux): preserve internal revision ID when saving an old corrective draft * fix(ux): preserve internal revision ID when saving an old corrective draft * test(ux): retain technical draft compatibility while no longer mutating on edit open * test(ux): load manually created legacy correction draft explicitly before edit

davoodmehraban89 committed Oct 14, 2026 at 10:05 UTC 635db7de4e71143fd167539780731f9277e20da0
6 files changed +270 -39
PROJECT_STATE.md
+12
@@ -211,6 +211,18 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
211 - **Still OPEN:** receipts/payments and expense/income source corrections, taxpayer-submitted documents, linked bank/warehouse allocations beyond bounded guards, legacy chartless records and closed fiscal years; two-user adversarial permission tests, production correction atomicity/reload and owner confirmation. Global 'all documents' request is partially implemented only; no bulk unposting or physical deletion of posted evidence. F0-01 slow startup remains separately OPEN.
212 - **Security/cost:** no production SQL DDL/DML, Auth/RLS/grant/role changes, external messaging, paid resource, existing posted ledger rewrite or live financial test transaction. Version rollback by reverting the targeted PR; real user reversal history, once created in future, is immutable and cannot be erased by reverting UI.
213
214 +### 2026-10-14 Owner UX correction — SAME visible document during pilot amendment — STARTED
215 +- **Exact latest owner instruction:** an employee clicks «اصلاح» on an existing finalized sales or purchase document and immediately edits **that same visible document, number, form and print view**. Employee must NOT see a "new invoice", correction suffix/ID or special bookkeeping messages; internal journal history remains with compensating reversal and properly posted amended transaction, never physical rewrite of historical accounting lines. Browser cancellation/no-op must NOT create a compensating entry. Save should complete amendment and maintain a single current visible document. Scope follows owner-approved sale/purchase and manual journal workflows where safe; no automatically unposting all existing documents.
216 +- **Starting verified live main** `d4d9e6df34f67c5f80b51daa4bb6e5512be31a8a`, protected main Quality `38518349856`, Security `38518349912`, Release Gate `38518625874`, Pages `38518677412` all SUCCESS. Current visible sale/purchase correction engines create separate physical source rows with `correctsInvoiceId` / `correctsPurchaseId` and internal numbered suffix; existing UI currently exposes these technical source versions. New user-directed correction supersedes that UX.
217 +- **Intended implementation:** change posted edit entry to in-place form prefill with deferred mutation until SAVE, use existing reversal/source-version safeguards behind the interface and invisible public history folding (one current visible version with original displayed number). Old source row and financial posting stay queryable in accounting audit. Receipt/payment allocations, external tax documents, locked periods and legacy unlinked sources remain hold cases. When full server transaction atomicity cannot be proven, fail closed and never present success before server acknowledgment; tests include open-and-cancel zero write, save+reopen, print same number, old history retained, balanced ledger, no duplicate visible rows after reload.
218 +- **No production user financial rows or Auth/RLS/SQL/schema touched; no new paid resources.** Build on isolated branch, PR-head Chromium/Golden/3 disposable PG/CodeQL, exact-main gated Pages; user acceptance remains distinct from CI.
219 +
220 +### 2026-10-14 Same-document correction UX implementation checkpoint — PR QA PENDING
221 +- **Implemented on isolated branch:** `js/invoices.js` uses `invoiceVisibleRecords` / `invoiceVisibleNumber` to fold internal version chain and show one active business invoice under the original number; `beginInvoiceAmendment` opens the existing posted invoice's **same edit form** with zero accounting mutations until Save. Save privately creates linked compensating posting and corrected source, persists edited data, re-posts and confirms server sync. `js/purchases.js` implements same in-form deferred purchase correction, one logical purchase record and original supplier number, while preserving payment/stock/period restrictions. `js/document-management.js` renders one sale and purchase row per logical invoice, and `js/print.js` prints corrected sale content with original number; purchase print follows current active revision and original supplier number. Existing journal audit displays original/reversal/new source-linked postings.
222 +- **No user-visible correction suffix, new invoice message or internal journal prompt** on normal posted→edit form workflow; editing can be cancelled without reversal. Original source data and posted voucher/lines remain physically unchanged. This design still stores internal technical source revisions, distinct from a user-visible business document ID; genuine single-row storage requires a separately approved schema redesign.
223 +- **Automated test coverage added:** 2 browser journeys for posted sale and purchase: click same document→cancel=no write→reopen→edit→single Save→internal reversal/repost→single visible item, same printed number, original transaction unchanged, reload consistency. **5/5 V8 syntax PASS**. Full Chromium/Golden/3 DB/CodeQL and exact-main Pages: PENDING; do not merge if any gate fails.
224 +- **Caveats:** source amendment is currently a multi-step application sync (not a server transaction) and waits for acknowledged stages; fail closed on sync trouble and do not retry blindly. Do not edit production historical customer records for testing; owner sign-in & UI acceptance remain OPEN. Payment/expense/tax source families remain unimplemented.
225 +
226 ## Current change ledger
227 | 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. |
228
js/document-management.js
+8 -19
@@ -3,34 +3,34 @@ function renderDocumentManagement(){
3 const tbody=document.getElementById('finora-document-management-body');if(!tbody||!currentUser)return;
4 const status=document.getElementById('document-status-filter')?.value||'all';
5 const active=typeof afCompanyId==='function'?afCompanyId():'';
6 - const records=getMyInvoices().filter(x=>(!active||x.companyId===active)&&(status==='all'||invoiceDocumentStatus(x)===status))
6 + const records=invoiceVisibleRecords().filter(x=>(!active||x.companyId===active)&&(status==='all'||invoiceDocumentStatus(x)===status))
7 .slice().sort((a,b)=>String(b.createdAt||b.date||'').localeCompare(String(a.createdAt||a.date||'')));
8 tbody.innerHTML=records.length?records.map(inv=>{
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>':'';
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>';
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>';
19 + return '<tr><td>'+esc(invoiceVisibleNumber(inv)||'—')+'</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 const buyBody=document.getElementById('finora-purchase-document-management-body');
22 if(buyBody&&typeof purchaseDocumentStatus==='function'){
23 - const rows=getMyPurchases().filter(x=>(!active||x.companyId===active)&&(status==='all'||purchaseDocumentStatus(x)===status)).slice()
23 + const rows=purchaseVisibleRecords().filter(x=>(!active||x.companyId===active)&&(status==='all'||purchaseDocumentStatus(x)===status)).slice()
24 .sort((a,b)=>String(b.createdAt||b.date||'').localeCompare(String(a.createdAt||a.date||'')));
25 buyBody.innerHTML=rows.length?rows.map(p=>{
26 const state=purchaseDocumentStatus(p),id=esc(p.id),attr=' data-doc-kind="purchase" data-doc-id="'+id+'"';
27 const label=({posted:'قطعی',draft:'موقت قابل‌ویرایش',reversed:'برگشت/ابطال‌شده',legacy_review:'قدیمی، نیازمند تطبیق'})[state]||'نامشخص';
28 const actions=state==='posted'?
29 - '<button class="btn btn-secondary btn-inline" data-doc-action="reopen"'+attr+'>برگشت به موقت</button> <button class="btn btn-danger btn-inline" data-doc-action="cancel"'+attr+'>ابطال قطعی</button>':
29 + '<button class="btn btn-secondary btn-inline" data-doc-action="reopen"'+attr+'>اصلاح فاکتور</button> <button class="btn btn-danger btn-inline" data-doc-action="cancel"'+attr+'>ابطال قطعی</button>':
30 state==='draft'?
31 '<button class="btn btn-secondary btn-inline" data-doc-action="edit"'+attr+'>ویرایش موقت</button> <button class="btn btn-success btn-inline" data-doc-action="post"'+attr+'>قطعی‌سازی</button> <button class="btn btn-danger btn-inline" data-doc-action="delete"'+attr+'>حذف موقت</button>':'';
32 const voucher=p.journalVoucherId?'<button class="btn btn-secondary btn-inline" data-doc-action="voucher"'+attr+'>مشاهده سند</button>':'';
33 - return '<tr><td>'+esc(p.number||'—')+'</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>';
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 }
@@ -41,7 +41,7 @@ document.addEventListener('click',async event=>{
41 const purchase=getMyPurchases().find(p=>p.id===button.dataset.docId&&p.ownerUserId===currentUser?.id&&p.companyId===afCompanyId());
42 if(!purchase)return;
43 const action=button.dataset.docAction;
44 - if(action==='reopen')return purReturnToDraftUi(purchase.id);
44 + if(action==='reopen')return beginPurchaseAmendment(purchase.id);
45 if(action==='cancel')return purCancelPostedUi(purchase.id);
46 if(action==='post')return purFinalizeUi(purchase.id);
47 if(action==='edit')return purEdit(purchase.id);
@@ -56,18 +56,7 @@ document.addEventListener('click',async event=>{
56 const inv=getMyInvoices().find(x=>x.id===button.dataset.docId);
57 if(!inv)return;
58 const action=button.dataset.docAction;
59 - if(action==='reopen'){
60 - const reason=prompt('دلیل برگشت از قطعی به موقت (نسخه اصلاحی):','اصلاح اطلاعات دوره پایلوت');
61 - if(reason===null)return;
62 - if(!String(reason).trim())return alert('دلیل اصلاح الزامی است.');
63 - if(!confirm('سند قطعی قدیمی و سطرهای آن حفظ می‌شوند؛ یک سند برگشتی و نسخه موقت جدید برای اصلاح ساخته می‌شود. ادامه می‌دهید؟'))return;
64 - try{
65 - const draftId=await reopenPostedInvoiceAsDraft(inv.id,reason);
66 - alert('نسخه موقت اصلاحی ساخته و در سرور ثبت شد. شماره فاکتور اصلی محفوظ است.');
67 - renderDocumentManagement();editInvoice(draftId);
68 - }catch(e){alert('برگشت به موقت تأیید نشد: '+e.message);}
69 - return;
70 - }
59 + if(action==='reopen')return beginInvoiceAmendment(inv.id);
60 if(action==='cancel'){
61 const reason=prompt('دلیل ابطال سند قطعی:','اشتباه ثبت در دوره پایلوت');
62 if(reason===null)return;
js/invoices.js
+98 -9
@@ -294,6 +294,71 @@ function saveElectronicDocToPending(){
294 }
295
296 function invoiceCreatesAccountingEntry(kind){return kind==='formal'||kind==='non_formal';}
297 +
298 +function invoiceLogicalRoot(inv){
299 + if(!inv)return null;
300 + const rows=getMyInvoices(),seen=new Set();let current=inv;
301 + while(current?.correctsInvoiceId&&!seen.has(current.id)){
302 + seen.add(current.id);const parent=rows.find(x=>x.id===current.correctsInvoiceId);
303 + if(!parent)break;current=parent;
304 + }
305 + return current;
306 +}
307 +function invoiceVisibleNumber(inv){return invoiceLogicalRoot(inv)?.number||inv?.number||'';}
308 +function invoiceVisibleRecords(){
309 + const all=getMyInvoices(),children=new Set(all.map(x=>x.correctsInvoiceId).filter(Boolean));
310 + return all.filter(x=>!children.has(x.id));
311 +}
312 +function invoiceCurrentVisible(invId){
313 + const all=getMyInvoices();let current=all.find(x=>x.id===invId);
314 + if(!current)return null;
315 + const seen=new Set();
316 + while(current&&!seen.has(current.id)){
317 + seen.add(current.id);const next=all.filter(x=>x.correctsInvoiceId===current.id)
318 + .sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')))[0];
319 + if(!next)break;current=next;
320 + }
321 + return current;
322 +}
323 +function invoicePrintView(record){
324 + if(!record)return null;
325 + const current=invoiceCurrentVisible(record.id)||record;
326 + return {...current,number:invoiceVisibleNumber(current)};
327 +}
328 +let finoraSaleAmendmentId='';
329 +function beginInvoiceAmendment(id){
330 + const source=invoiceCurrentVisible(id);
331 + if(!source)return alert('فاکتور پیدا نشد.');
332 + try{
333 + invoicePilotCorrectionEligible(source);
334 + finoraSaleAmendmentId=source.id;
335 + editInvoice(source.id,true);
336 + }catch(e){finoraSaleAmendmentId='';alert(e.message)}
337 +}
338 +async function commitInvoiceSeamlessAmendment(id,changes){
339 + if(!requireWrite())throw new Error('مجوز اصلاح ندارید.');
340 + const current=invoiceCurrentVisible(id),root=invoiceLogicalRoot(current);
341 + if(!current||current.id!==id||!root)throw new Error('نسخه جاری سند با درخواست ویرایش مطابقت ندارد.');
342 + invoicePilotCorrectionEligible(current);
343 + if(changes.companyId!==current.companyId||changes.kind!==current.kind||changes.number!==root.number)
344 + throw new Error('شماره اصلی، نوع سند و شرکت را در اصلاح سند قطعی تغییر ندهید.');
345 + if(!Number.isFinite(changes.grandTotal)||changes.grandTotal<=0||!changes.items?.length)
346 + throw new Error('مبلغ و اقلام فاکتور معتبر نیست.');
347 + // Zero accounting writes occurred when the employee merely opened the form.
348 + const idNew=await reopenPostedInvoiceAsDraft(id,'اصلاح اطلاعات فاکتور در دوره پایلوت');
349 + const copy=getMyInvoices().find(x=>x.id===idNew);
350 + if(!copy)throw new Error('فاکتور اصلاح‌شده بارگذاری نشد.');
351 + Object.assign(copy,changes,{number:copy.number,documentStatus:'draft',accountingStatus:'draft',
352 + electronicDoc:current.electronicDoc||null,documentVersion:Number(current.documentVersion||1)+1,
353 + correctsInvoiceId:current.id,correctionOriginalNumber:root.number,updatedAt:new Date().toISOString()});
354 + saveDatastore();
355 + await invoicePilotAwaitSync(['invoices|'+idNew]);
356 + await finalizeInvoiceDocument(idNew);
357 + finoraSaleAmendmentId='';
358 + cancelInvoiceEdit();refreshAllSurfaces();
359 + return idNew;
360 +}
361 +
362 function invoiceDocumentStatus(inv){
363 if(!inv)return 'unknown';
364 const linked=inv.journalVoucherId&&typeof jeSourceVoucher==='function'?jeSourceVoucher(inv):null;
@@ -446,7 +511,7 @@ function commitSaveInvoice(){
511 const contactSelect=document.getElementById('invoice-contact-id');
512 const contactId=contactSelect?contactSelect.value:'';
513 const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
449 - const number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
514 + let number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
515 const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
516 const kind=document.getElementById('invoice-kind')?.value||'non_formal';
517 const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
@@ -454,7 +519,12 @@ function commitSaveInvoice(){
519 const paymentMethodLabel=paymentMethod==='credit'?'نسیه':'نقدی';
520 const warehouseId=document.getElementById('invoice-warehouse-id')?.value||'';
521 const editId=document.getElementById('edit-invoice-id')?.value;
457 - if(getMyInvoices().some(i=>i.id!==editId&&i.companyId===companyId&&String(i.number||'').trim()===number)){alert('شماره فاکتور برای این شرکت قبلاً ثبت شده است.');return;}
522 + const previousDraft=getMyInvoices().find(i=>i.id===editId);
523 + // Old in-progress correction drafts show the original business number;
524 + // preserve their private unique storage number while updating them.
525 + if(previousDraft?.correctsInvoiceId&&invoiceDocumentStatus(previousDraft)==='draft'
526 + &&number===invoiceVisibleNumber(previousDraft))number=previousDraft.number;
527 + if(getMyInvoices().some(i=>i.id!==editId&&i.companyId===companyId&&String(i.number||'').trim()===number)&&!(finoraSaleAmendmentId===editId&&invoiceVisibleNumber(getMyInvoices().find(i=>i.id===editId))===number)){alert('شماره فاکتور برای این شرکت قبلاً ثبت شده است.');return;}
528 if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
529
530 const contractNumber=document.getElementById('invoice-contract-number')?.value.trim()||'';
@@ -499,6 +569,24 @@ function commitSaveInvoice(){
569 const totals=recomputeTotals();
570 const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور',contract_statement:'صورت وضعیت پیمان'};
571 const cur=getCurrencyLabel();
572 + if(editId&&finoraSaleAmendmentId===editId){
573 + const changes={number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,
574 + projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,
575 + subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,
576 + discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,
577 + vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,
578 + electronicDoc:edoc};
579 + const btn=document.getElementById('btn-save-invoice');if(btn)btn.disabled=true;
580 + void commitInvoiceSeamlessAmendment(editId,changes).then(()=>{
581 + alert('اصلاحات فاکتور '+number+' ذخیره و تأیید شد. چاپ از همین فاکتور امکان‌پذیر است.');
582 + }).catch(e=>{
583 + finoraSaleAmendmentId='';
584 + // If sync failed mid-correction, do not silently retry a reversal.
585 + cancelInvoiceEdit();refreshAllSurfaces();
586 + alert('اصلاح فاکتور تکمیل نشد؛ وضعیت سند را تازه‌سازی و بررسی کنید: '+e.message);
587 + }).finally(()=>{if(btn)btn.disabled=false;});
588 + return;
589 + }
590 if(editId){
591 const lockedExisting=getMyInvoices().find(i=>i.id===editId);
592 if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
@@ -523,13 +611,13 @@ function commitSaveInvoice(){
611 saveDatastore();
612 refreshAllSurfaces();
613 }
526 -function editInvoice(invId){
614 +function editInvoice(invId,allowPostedCorrection=false){
615 const inv=getMyInvoices().find(i=>i.id===invId);
616 if(!inv)return;
529 - if(!invoiceMayEdit(inv)){alert('این فاکتور قطعی یا قدیمی است؛ برای مشاهده جزئیات از مدیریت اسناد استفاده کنید.');return;}
617 + if(!invoiceMayEdit(inv)&&!(allowPostedCorrection&&invoiceDocumentStatus(inv)==='posted')){alert('فاکتور برای اصلاح در این وضعیت قابل دسترس نیست.');return;}
618 switchView('view-invoices');
619 document.getElementById('edit-invoice-id').value=inv.id;
532 - document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
620 + document.getElementById('invoice-form-title').innerText=`✏️ اصلاح فاکتور #${invoiceVisibleNumber(inv)}`;
621 document.getElementById('btn-cancel-edit').style.display='inline-flex';
622 document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
623 document.getElementById('invoice-company-id').value=inv.companyId;
@@ -537,7 +625,7 @@ function editInvoice(invId){
625 document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
626 document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
627 document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
540 - document.getElementById('invoice-number').value=inv.number;
628 + document.getElementById('invoice-number').value=invoiceVisibleNumber(inv);
629 document.getElementById('invoice-contact-id').value=inv.contactId;
630 document.getElementById('invoice-date-input').value=inv.date;
631 if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value=inv.paymentMethod||'cash';if(document.getElementById('invoice-warehouse-id'))document.getElementById('invoice-warehouse-id').value=inv.warehouseId||p5DefaultWarehouse()?.id||'';
@@ -576,6 +664,7 @@ function editInvoice(invId){
664 recomputeTotals();
665 }
666 function cancelInvoiceEdit(){
667 + finoraSaleAmendmentId='';
668 document.getElementById('edit-invoice-id').value='';
669 document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
670 document.getElementById('btn-cancel-edit').style.display='none';
@@ -606,19 +695,19 @@ function renderInvoices(){
695 const tbody=document.getElementById('invoice-archive-table-body');
696 const filterSelect=document.getElementById('filter-invoice-company');
697 const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
609 - let list=getMyInvoices();
698 + let list=invoiceVisibleRecords();
699 if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
700 if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
701 tbody.innerHTML=list.map(inv=>`
702 <tr>
614 - <td><strong>#${esc(inv.number)}</strong></td>
703 + <td><strong>#${esc(invoiceVisibleNumber(inv))}</strong></td>
704 <td>${esc(inv.companyName||'—')}</td>
705 <td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
706 <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
707 <td>${esc(inv.date)}</td>
708 <td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
709 <td>
621 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="navigateShell('accounting','view-journal','documents')">▤ مدیریت سند</button>${invoiceMayEdit(inv)?` <button class="btn btn-secondary btn-inline" onclick="editInvoice('${inv.id}')">✏️ ویرایش پیش‌نویس</button>` : ''}
710 + <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="navigateShell('accounting','view-journal','documents')">▤ مدیریت سند</button>${invoiceMayEdit(inv)?` <button class="btn btn-secondary btn-inline" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>` : (invoiceDocumentStatus(inv)==='posted'?` <button class="btn btn-secondary btn-inline" onclick="beginInvoiceAmendment('${inv.id}')">✏️ اصلاح</button>`:'')}
711 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
712 ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
713 </td>
js/print.js
+2 -1
@@ -534,7 +534,8 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
534 </div>`;
535 }
536 function renderAndPrintDirect(invId){
537 - const inv=getMyInvoices().find(i=>i.id===invId);
537 + const record=getMyInvoices().find(i=>i.id===invId);
538 + const inv=typeof invoicePrintView==='function'?invoicePrintView(record):record;
539 if(!inv)return;
540 const myCompanies=getMyCompanies();
541 const myContacts=getMyContacts();
js/purchases.js
+66 -10
@@ -70,6 +70,47 @@
70 return 'legacy_review';
71 }
72 window.purchaseDocumentStatus=purchaseDocumentStatus;
73 + function purchaseLogicalRoot(p){
74 + if(!p)return null;const rows=myPurchases(),seen=new Set();let v=p;
75 + while(v.correctsPurchaseId&&!seen.has(v.id)){seen.add(v.id);const parent=rows.find(x=>x.id===v.correctsPurchaseId);if(!parent)break;v=parent;}
76 + return v;
77 + }
78 + function purchaseVisibleNumber(p){return purchaseLogicalRoot(p)?.number||p?.number||'';}
79 + function purchaseCurrentVisible(id){
80 + const rows=myPurchases();let v=rows.find(x=>x.id===id),seen=new Set();
81 + while(v&&!seen.has(v.id)){seen.add(v.id);const next=rows.filter(x=>x.correctsPurchaseId===v.id)
82 + .sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')))[0];if(!next)break;v=next;}
83 + return v;
84 + }
85 + function purchaseVisibleRecords(){
86 + const rows=myPurchases(),parents=new Set(rows.map(p=>p.correctsPurchaseId).filter(Boolean));
87 + return rows.filter(p=>!parents.has(p.id));
88 + }
89 + window.purchaseVisibleRecords=purchaseVisibleRecords;
90 + window.purchaseVisibleNumber=purchaseVisibleNumber;
91 + let editingPostedPurchaseId='';
92 + window.beginPurchaseAmendment=function(id){
93 + const p=purchaseCurrentVisible(id);
94 + try{if(!p)throw new Error('فاکتور خرید پیدا نشد.');purchasePilotEligibility(p.id);editingPostedPurchaseId=p.id;purEdit(p.id,true);}
95 + catch(e){editingPostedPurchaseId='';alert(e.message);}
96 + };
97 + async function purchaseSaveSeamless(id,payload){
98 + const p=purchaseCurrentVisible(id),root=purchaseLogicalRoot(p);
99 + if(!p||p.id!==id||!root)throw new Error('نسخه سند خرید تغییر کرده است.');
100 + purchasePilotEligibility(id);
101 + if(payload.companyId!==p.companyId||payload.number!==root.number)
102 + throw new Error('شرکت و شماره سند اصلی نباید در ویرایش خرید قطعی تغییر کند.');
103 + if(!Number.isFinite(payload.grandTotal)||payload.grandTotal<=0||!payload.items?.length)
104 + throw new Error('مبلغ و اقلام خرید نامعتبر است.');
105 + const newId=await returnPostedPurchaseAsDraft(id,'اصلاح فاکتور خرید در دوره پایلوت');
106 + const record=myPurchases().find(x=>x.id===newId);if(!record)throw new Error('نسخه سند اصلاحی پیدا نشد.');
107 + Object.assign(record,payload,{number:record.number,accountingStatus:'draft',documentStatus:'draft',
108 + correctsPurchaseId:id,correctionOriginalNumber:root.number,updatedAt:new Date().toISOString()});
109 + saveDatastore();await invoicePilotAwaitSync(['purchases|'+newId]);
110 + await finalizePurchasePilotDraft(newId);
111 + editingPostedPurchaseId='';purCancelEdit();refreshAllSurfaces();return newId;
112 + }
113 +
114 function purchasePilotEligibility(id){
115 if(!requireWrite()||!currentUser)throw new Error('مجوز اصلاح خرید ندارید.');
116 const p=myPurchases().find(x=>x.id===id&&x.companyId===afCompanyId());
@@ -224,9 +265,22 @@
265 if(!Array.isArray(datastore.purchases))datastore.purchases=[];
266 const paymentMethod=$('pur-payment-method')?.value||'cash';
267 const editId=$('pur-edit-id')?.value||'';
227 - const purNumber=$('pur-number').value.trim();
228 - if(purNumber&&myPurchases().some(p=>p.id!==editId&&p.supplierId===supSel.value&&String(p.number||'').trim()===purNumber)){alert('این شماره فاکتور برای تأمین‌کننده انتخاب‌شده قبلاً ثبت شده است.');return;}
268 + let purNumber=$('pur-number').value.trim();
269 + const previousDraft=myPurchases().find(p=>p.id===editId);
270 + if(previousDraft?.correctsPurchaseId&&purchaseDocumentStatus(previousDraft)==='draft'
271 + &&purNumber===purchaseVisibleNumber(previousDraft))purNumber=previousDraft.number;
272 + if(purNumber&&myPurchases().some(p=>p.id!==editId&&p.supplierId===supSel.value&&String(p.number||'').trim()===purNumber)&&!(editingPostedPurchaseId===editId&&purchaseVisibleNumber(myPurchases().find(p=>p.id===editId))===purNumber)){alert('این شماره فاکتور برای تأمین‌کننده انتخاب‌شده قبلاً ثبت شده است.');return;}
273 const activeCompanyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';const warehouseId=$('pur-warehouse')?.value||'',projectId=ccSel.value,projectName=projectId?ccSel.options[ccSel.selectedIndex].text:'';const payload={warehouseId,number:purNumber,date:$('pur-date').value.trim()||getJalaliNumeric(),companyId:activeCompanyId,supplierId:supSel.value,supplierName:supSel.options[supSel.selectedIndex].text,projectId,projectName,costCenterId:'',costCenterLabel:'',contractNumber:$('pur-contract').value.trim(),paymentMethod,paymentMethodLabel:paymentMethod==='credit'?'نسیه':'نقدی',items,subtotal:t.sub,discount:t.disc,vat:t.vat,grandTotal:t.grand,description:$('pur-desc').value.trim()};
274 + if(editId&&editingPostedPurchaseId===editId){
275 + const btn=$('pur-save-btn');if(btn)btn.disabled=true;
276 + void purchaseSaveSeamless(editId,payload).then(()=>{
277 + alert('اصلاحات فاکتور خرید '+purNumber+' ذخیره و تأیید شد.');
278 + }).catch(e=>{
279 + editingPostedPurchaseId='';purCancelEdit();refreshAllSurfaces();
280 + alert('اصلاح سند خرید تکمیل نشد؛ وضعیت را تازه‌سازی و بررسی کنید: '+e.message);
281 + }).finally(()=>{if(btn)btn.disabled=false;});
282 + return;
283 + }
284 if(editId){
285 const old=datastore.purchases.find(p=>p.id===editId&&p.ownerUserId===currentUser.id);
286 if(!old){alert('فاکتور خرید پیدا نشد.');return;}
@@ -245,6 +299,7 @@
299 refreshAllSurfaces();
300 };
301 window.purCancelEdit=function(){
302 + editingPostedPurchaseId='';
303 if($('pur-edit-id'))$('pur-edit-id').value='';
304 if($('pur-form-title'))$('pur-form-title').innerText='🛒 ثبت فاکتور خرید';
305 if($('pur-save-btn'))$('pur-save-btn').innerText='💾 ثبت فاکتور خرید';
@@ -258,17 +313,18 @@
313 if($('pur-date'))$('pur-date').value=getJalaliNumeric();
314 purAddRow();
315 };
261 - window.purEdit=function(id){
316 + window.purEdit=function(id,allowPostedCorrection=false){
317 const p=myPurchases().find(x=>x.id===id);if(!p)return;
263 - if(purchaseDocumentStatus(p)!=='draft'){alert('سند قطعی ابتدا از مدیریت اسناد به نسخه موقت اصلاحی تبدیل شود؛ اسناد قدیمی نیازمند تطبیق هستند.');return;}
264 - $('pur-edit-id').value=p.id;$('pur-form-title').innerText='✏️ اصلاح فاکتور خرید '+(p.number||'');
318 + if(purchaseDocumentStatus(p)!=='draft'&&!(allowPostedCorrection&&purchaseDocumentStatus(p)==='posted')){alert('سند قطعی ابتدا از مدیریت اسناد به نسخه موقت اصلاحی تبدیل شود؛ اسناد قدیمی نیازمند تطبیق هستند.');return;}
319 + $('pur-edit-id').value=p.id;$('pur-form-title').innerText='✏️ اصلاح فاکتور خرید '+purchaseVisibleNumber(p);
320 $('pur-save-btn').innerText='💾 ذخیره اصلاحات';$('pur-cancel-edit').style.display='inline-flex';
266 - $('pur-date').value=p.date||'';$('pur-number').value=p.number||'';$('pur-supplier').value=p.supplierId||'';purRefreshProjects();$('pur-costcenter').value=p.projectId||p.costCenterId||'';if($('pur-payment-method'))$('pur-payment-method').value=p.paymentMethod||'cash';if($('pur-warehouse'))$('pur-warehouse').value=p.warehouseId||p5DefaultWarehouse()?.id||'';$('pur-contract').value=p.contractNumber||'';$('pur-desc').value=p.description||'';$('pur-discount').value=(p.discount||0).toLocaleString('en-US');$('pur-vat-mode').value=(p.vat||0)>0?'with_vat':'none';
321 + $('pur-date').value=p.date||'';$('pur-number').value=purchaseVisibleNumber(p);$('pur-supplier').value=p.supplierId||'';purRefreshProjects();$('pur-costcenter').value=p.projectId||p.costCenterId||'';if($('pur-payment-method'))$('pur-payment-method').value=p.paymentMethod||'cash';if($('pur-warehouse'))$('pur-warehouse').value=p.warehouseId||p5DefaultWarehouse()?.id||'';$('pur-contract').value=p.contractNumber||'';$('pur-desc').value=p.description||'';$('pur-discount').value=(p.discount||0).toLocaleString('en-US');$('pur-vat-mode').value=(p.vat||0)>0?'with_vat':'none';
322 $('pur-items-body').innerHTML='';(p.items||[]).forEach(it=>purAddRow(it.prodId,it.qty,it.price,it.unit));purRecalc();
323 switchView('view-purchases');$('pur-form-title').scrollIntoView({behavior:'smooth',block:'center'});
324 };
325 window.purPrint=function(id){
271 - const p=myPurchases().find(x=>x.id===id);if(!p)return;
326 + const source=myPurchases().find(x=>x.id===id);if(!source)return;
327 + const current=purchaseCurrentVisible(id)||source,p={...current,number:purchaseVisibleNumber(current)};
328 const cur=(typeof getCurrencyLabel==='function'?getCurrencyLabel():'ریال');
329 const itemRows=(p.items||[]).map((it,i)=>`<tr><td>${(i+1).toLocaleString('fa-IR')}</td><td>${esc(it.prodName||'')}</td><td>${esc(it.unit||'')}</td><td>${Number(it.qty||0).toLocaleString('fa-IR')}</td><td>${fmt(it.price)}</td><td>${fmt(it.lineTotal)}</td></tr>`).join('');
330 const w=window.open('','_blank','width=900,height=700');if(!w){alert('مرورگر پنجره چاپ را مسدود کرده است.');return;}
@@ -328,16 +384,16 @@
384 purRefreshProjects();
385 if(!$('pur-date').value)$('pur-date').value=getJalaliNumeric();
386 if(!document.querySelector('#pur-items-body tr'))purAddRow();
331 - const list=myPurchases();let total=0;
387 + const list=purchaseVisibleRecords();let total=0;
388 $('pur-list-body').innerHTML=list.length?list.map(p=>{
389 const state=purchaseDocumentStatus(p),published=state==='posted',draft=state==='draft';
390 if(published)total+=Number(p.grandTotal)||0;
391 const label=({posted:'قطعی',draft:'موقت قابل اصلاح',reversed:'برگشت/ابطال‌شده',legacy_review:'قدیمی / نیازمند تطبیق'})[state]||'نامشخص';
392 const id=esc(p.id);
393 const actions=published?
338 - '<button class="btn btn-secondary btn-inline" onclick="purReturnToDraftUi(\''+id+'\')">برگشت به موقت</button> <button class="btn btn-danger btn-inline" onclick="purCancelPostedUi(\''+id+'\')">ابطال</button>':
394 + '<button class="btn btn-secondary btn-inline" onclick="beginPurchaseAmendment(\''+id+'\')">اصلاح</button> <button class="btn btn-danger btn-inline" onclick="purCancelPostedUi(\''+id+'\')">ابطال</button>':
395 draft?'<button class="btn btn-secondary btn-inline" onclick="purEdit(\''+id+'\')">ویرایش موقت</button> <button class="btn btn-success btn-inline" onclick="purFinalizeUi(\''+id+'\')">قطعی‌سازی</button> <button class="btn btn-danger btn-inline" onclick="purDeleteDraftUi(\''+id+'\')">حذف موقت</button>':'';
340 - return '<tr><td>'+esc(p.number||'—')+'</td><td>'+esc(p.date)+'</td><td>'+esc(p.supplierName)+'</td><td>'+esc(p.projectName||p.costCenterLabel||'—')+'</td><td>'+esc(p.contractNumber||'—')+'</td><td>'+fmt(p.grandTotal)+'</td><td>'+esc(label)+'</td><td>'+actions+' <button class="btn btn-secondary btn-inline" onclick="purPrint(\''+id+'\')">چاپ</button></td></tr>';
396 + return '<tr><td>'+esc(purchaseVisibleNumber(p)||'—')+'</td><td>'+esc(p.date)+'</td><td>'+esc(p.supplierName)+'</td><td>'+esc(p.projectName||p.costCenterLabel||'—')+'</td><td>'+esc(p.contractNumber||'—')+'</td><td>'+fmt(p.grandTotal)+'</td><td>'+esc(label)+'</td><td>'+actions+' <button class="btn btn-secondary btn-inline" onclick="purPrint(\''+id+'\')">چاپ</button></td></tr>';
397 }).join(''):'<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">فاکتور خریدی ثبت نشده است.</td></tr>';
398 $('pur-total-all').innerText=list.length?('جمع کل خریدها: '+fmt(total)):'';
399 }
scripts/accounting-document-workflow.spec.js
+84
@@ -272,7 +272,12 @@ test('pilot purchase: posted to corrective draft to edited balanced repost via d
272 });
273 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PILOT-PUR-001');
274 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]')).toHaveCount(1);
275 + // Technical correction primitive remains available for pre-existing in-progress
276 + // drafts; the new employee UI correctly DOES NOT write on open.
277 await page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]').click();
278 + expect(remotePurchases(server)).toHaveLength(1);
279 + await page.evaluate(()=>purCancelEdit());
280 + await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی'),originalId);
281 await expect.poll(()=>remotePurchases(server).length,{timeout:14000}).toBe(2);
282 const corrected=remotePurchases(server).find(x=>x.correctsPurchaseId===originalId);
283 expect(corrected.documentStatus).toBe('draft');
@@ -280,6 +285,8 @@ test('pilot purchase: posted to corrective draft to edited balanced repost via d
285 expect(corrected.number).not.toBe(first.number);
286 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
287 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),originalId)).toBe('reversed');
288 + // Internal API fixture made a technical draft without clicking the employee form.
289 + await page.evaluate(id=>purEdit(id),corrected.id);
290 await expect(page.locator('#pur-edit-id')).toHaveValue(corrected.id);
291 await page.locator('#pur-items-body .pur-qty').first().fill('3');
292 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
@@ -332,6 +339,83 @@ test('pilot purchase denies paid/consumed source; cancels unallocated posting wi
339 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
340 expect(await page.evaluate(id=>{try{deletePurchasePilotDraft(id);return 'unsafe'}catch(e){return String(e.message)}},purchaseId)).not.toBe('unsafe');
341 });
342 +test('seamless sale correction: opening and cancelling leaves ledger unchanged; saving retains visible identity, printing and audit',async({page})=>{
343 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
344 + await fillInvoice(page,'SAME-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
345 + await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
346 + const id=remoteInvoices(server)[0].id;await page.evaluate(x=>finalizeInvoiceDocument(x),id);
347 + await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
348 + const original=copy(remoteInvoices(server)[0]),initialLines=[...server.records.values()].filter(x=>x.collection==='journalLines').map(copy);
349 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
350 + await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
351 + await page.locator('#finora-document-management-body [data-doc-action="reopen"]').click();
352 + await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
353 + await expect(page.locator('#invoice-number')).toHaveValue('SAME-SALE-001');
354 + expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
355 + await page.evaluate(()=>cancelInvoiceEdit());
356 + expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
357 + expect(remoteInvoices(server)).toHaveLength(1);
358 + await page.evaluate(x=>beginInvoiceAmendment(x),id);
359 + await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
360 + await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
361 + await page.evaluate(()=>commitSaveInvoice());
362 + await expect.poll(()=>remoteInvoices(server).filter(x=>x.correctsInvoiceId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
363 + expect(remoteInvoices(server)).toHaveLength(2);expect(remoteInvoices(server).find(x=>x.id===id)).toEqual(original);
364 + const current=remoteInvoices(server).find(x=>x.correctsInvoiceId===id);
365 + expect(current.grandTotal).toBe(4500);
366 + expect(current.number).not.toBe(original.number);
367 + const visible=await page.evaluate(()=>invoiceVisibleRecords().map(x=>({id:x.id,number:invoiceVisibleNumber(x)})));
368 + expect(visible).toEqual([{id:current.id,number:'SAME-SALE-001'}]);
369 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
370 + await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
371 + await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
372 + await expect(page.locator('#finora-document-management-body')).not.toContainText('-اصلاح');
373 + await page.evaluate(x=>renderAndPrintDirect(x),id);
374 + await expect(page.locator('#printable-invoice')).toContainText('SAME-SALE-۰۰۱');
375 + await expect(page.locator('#printable-invoice')).toContainText('۴٬۵۰۰');
376 + await expect(page.locator('#printable-invoice')).not.toContainText('-اصلاح');
377 + expect(initialLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy));
378 + const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
379 + expect(vouchers).toHaveLength(3);expect(vouchers.find(v=>v.id===original.journalVoucherId).data.status).toBe('reversed');
380 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
381 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
382 + await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
383 + await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
384 +});
385 +
386 +test('seamless purchase correction: same visible number, no write on opening, save and print corrected purchase',async({page})=>{
387 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
388 + const id=await createPostedPurchase(page,server,'SAME-PURCHASE-001',2);
389 + const initial=copy(remotePurchases(server).find(x=>x.id===id));const before=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
390 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
391 + await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
392 + await page.locator('#finora-purchase-document-management-body [data-doc-action="reopen"]').click();
393 + await expect(page.locator('#pur-edit-id')).toHaveValue(id);
394 + await expect(page.locator('#pur-number')).toHaveValue('SAME-PURCHASE-001');
395 + expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(before.length);
396 + await page.evaluate(()=>purCancelEdit());
397 + expect(remotePurchases(server)).toHaveLength(1);
398 + await page.evaluate(x=>beginPurchaseAmendment(x),id);
399 + await page.locator('#pur-items-body .pur-qty').first().fill('3');
400 + await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
401 + await page.locator('#pur-save-btn').click();
402 + await expect.poll(()=>remotePurchases(server).filter(x=>x.correctsPurchaseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
403 + expect(remotePurchases(server).find(x=>x.id===id)).toEqual(initial);
404 + const current=remotePurchases(server).find(x=>x.correctsPurchaseId===id);
405 + expect(current.grandTotal).toBe(300);expect(current.number).not.toBe(initial.number);
406 + const visible=await page.evaluate(()=>purchaseVisibleRecords().map(x=>({id:x.id,number:purchaseVisibleNumber(x)})));
407 + expect(visible).toEqual([{id:current.id,number:'SAME-PURCHASE-001'}]);
408 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
409 + await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
410 + await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
411 + await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('-اصلاح');
412 + await page.evaluate(x=>purPrint(x),id);
413 + await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
414 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
415 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
416 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
417 + await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
418 +});
419 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
420 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
421 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());