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

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

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

Synced Dec 4, 08:00 UTC

feat/pilot-expense-income-inplace-amendment-20261014
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
js 688 lines 49.5 KB
Raw
1 const {test,expect}=require('@playwright/test');
2
3 const BASE=process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
4 const USER='FINORA_F0_FIXTURE_ONLY';
5 const copy=value=>JSON.parse(JSON.stringify(value));
6 function fakeServer(){
7 const records=new Map();
8 for(const [collection,id,data] of [
9 ['companies','QA_CO',{name:'شرکت آزمون ایزوله',entityType:'legal'}],
10 ['contacts','QA_CONTACT',{name:'خریدار آزمایشی',role:'both'}],
11 ['products','QA_PROD',{name:'بلوک سیمانی',code:'BLK-001',unit:'عدد',sale_price:1500}],
12 ['settings','main',{invoice_kind:'formal',vat_mode:'none',vat_rate:10,default_company_id:'QA_CO',currency_mode:'rial'}],
13 ['fiscalYears','FY_QA',{name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}],
14 ['accounts','A_CASH',{code:'1101',title:'صندوق',systemRole:'cash_default',postingAllowed:true,active:true}],
15 ['accounts','A_AR',{code:'1102',title:'دریافتنی',systemRole:'receivable_control',postingAllowed:true,active:true}],
16 ['accounts','A_REV',{code:'4101',title:'درآمد فروش',systemRole:'revenue_default',postingAllowed:true,active:true}],
17 ['accounts','A_VAT',{code:'2102',title:'مالیات',systemRole:'vat_payable',postingAllowed:true,active:true}],
18 ['accounts','A_BUY',{code:'5101',title:'خرید',systemRole:'purchase_default',postingAllowed:true,active:true}],
19 ['accounts','A_AP',{code:'2101',title:'پرداختنی',systemRole:'payable_control',postingAllowed:true,active:true}],
20 ['accounts','A_EXP',{code:'6103',title:'هزینه عمومی',systemRole:'expense_default',postingAllowed:true,active:true}],
21 ['accounts','A_OTHER',{code:'4201',title:'سایر درآمد',systemRole:'other_income_default',postingAllowed:true,active:true}],
22 ])records.set(collection+'|'+id,{collection,id,data:copy(data)});
23 return {records,failNext:false,failCount:0,rpcCount:0};
24 }
25 function remoteInvoices(server){return [...server.records.values()].filter(r=>r.collection==='invoices').map(r=>copy(r.data));}
26
27 async function installHarness(page,server){
28 await page.exposeFunction('qaF0Read',async()=>[...server.records.values()].map(copy));
29 await page.exposeFunction('qaF0Write',async args=>{
30 server.rpcCount++;
31 if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'Network unavailable — isolated QA failure',code:'QA_NETWORK'}};}
32 for(const row of args.p_upserts||[])server.records.set(row.collection+'|'+row.id,{collection:row.collection,id:row.id,data:copy(row.data)});
33 for(const row of args.p_deletes||[])server.records.delete(row.collection+'|'+row.id);
34 return {error:null};
35 });
36 await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
37 }
38 async function authenticatedMockBrowser(page){
39 await page.goto(BASE,{waitUntil:'domcontentloaded'});
40 await page.waitForFunction(()=>typeof enterApp==='function'&&typeof commitSaveInvoice==='function'&&typeof pullAll==='function');
41 await page.evaluate(async()=>{
42 window.__FINORA_PRINT_TEST_MODE=true;
43 window.__f0Alerts=[];
44 window.alert=m=>window.__f0Alerts.push(String(m));
45 window.confirm=()=>false;
46 fetchCurrentUser=async()=>({id:'FINORA_F0_FIXTURE_ONLY',username:'qa-only',email:'qa@example.invalid',fullName:'QA F0',role:'admin',maxCompanies:2,subscription:{type:'lifetime',status:'active',endDate:'2099-12-31'}});
47 maybeMigrateLegacyData=()=>{};
48 sb.from=collection=>({
49 select:()=>({
50 order(){return this;},
51 async range(from,to){const rows=(await window.qaF0Read()).filter(r=>r.collection).sort((a,b)=>a.collection.localeCompare(b.collection)||a.id.localeCompare(b.id));return {data:rows.slice(from,to+1),error:null};}
52 })
53 });
54 sb.rpc=async(name,args)=>{
55 if(name!=='finora_sync_records')throw Error('Unexpected RPC '+name);
56 return await window.qaF0Write(args);
57 };
58 await enterApp({id:'FINORA_F0_FIXTURE_ONLY'});
59 document.querySelectorAll('.modal-backdrop.active').forEach(x=>x.classList.remove('active'));
60 switchView('view-invoices');
61 });
62 await expect(page.locator('#auth-screen')).toBeHidden();
63 await expect(page.locator('#invoice-company-id option[value="QA_CO"]')).toHaveCount(1);
64 await expect(page.locator('#invoice-items-table-body .row-product-select').first().locator('option[value="QA_PROD"]')).toHaveCount(1);
65 }
66 async function fillInvoice(page,number,qty){
67 // The native invoice-kind/contact selectors are hidden by the unified commercial combobox.
68 // Drive their real DOM change handlers, not Playwright visibility on replaced native selects.
69 await page.evaluate(()=>{
70 for(const [id,value] of [['invoice-kind','formal'],['invoice-company-id','QA_CO'],['invoice-contact-id','QA_CONTACT']]){
71 const el=document.getElementById(id);el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
72 }
73 });
74 await page.locator('#invoice-number').fill(number);
75 await page.locator('#invoice-date-input').fill('۱۴۰۵/۰۷/۱۹');
76 await page.evaluate(()=>{
77 const el=document.querySelector('#invoice-items-table-body .row-product-select');
78 el.value='QA_PROD';el.dispatchEvent(new Event('change',{bubbles:true}));
79 });
80 await page.locator('#invoice-items-table-body .row-quantity').first().fill(String(qty));
81 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
82 }
83
84 test('formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher',async({page})=>{
85 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
86 await fillInvoice(page,'FIN-DRAFT-001',2);
87 await page.evaluate(()=>commitSaveInvoice());
88 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
89 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
90 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
91 const id=remoteInvoices(server)[0].id;
92 // A saved formal draft prints its complete invoice; the print UI must not stamp it
93 // as provisional. The underlying draft state and zero-posting invariant remain.
94 await page.evaluate(x=>renderAndPrintDirect(x),id);
95 await expect(page.locator('#printable-invoice')).toContainText('FIN-DRAFT-۰۰۱');
96 await expect(page.locator('#printable-invoice')).toContainText('۳٬۰۰۰');
97 await expect(page.locator('#printable-invoice')).not.toContainText('پیش‌نویس — غیرقطعی');
98 await expect(page.locator('#printable-invoice [style*="rotate(-12deg)"]')).toHaveCount(0);
99 const isolatedPrint=page.frameLocator('#finora-print-frame').locator('#finora-print-document');
100 await expect(isolatedPrint).toContainText('FIN-DRAFT-۰۰۱');
101 await expect(isolatedPrint).not.toContainText('پیش‌نویس — غیرقطعی');
102 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
103 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
104 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
105 await page.evaluate(x=>editInvoice(x),id);
106 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
107 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
108 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
109 await page.evaluate(()=>commitSaveInvoice());
110 await expect.poll(()=>remoteInvoices(server)[0]?.grandTotal,{timeout:13000}).toBe(4500);
111 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
112 await expect(page.locator('#finora-document-management-body')).toContainText('FIN-DRAFT-001');
113 await expect(page.locator('#finora-document-management-body')).toContainText('پیش‌نویس');
114 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
115 // Show a confirmation requiring explicit intent; no automatic posting on Save.
116 await expect.poll(()=>remoteInvoices(server)[0].accountingStatus,{timeout:3000}).toBe('draft');
117 await page.evaluate(()=>{window.confirm=()=>true});
118 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
119 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
120 const posted=remoteInvoices(server)[0];
121 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
122 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
123 expect(vouchers).toHaveLength(1);
124 expect(vouchers[0].data.status).toBe('posted');
125 expect(lines.length).toBeGreaterThanOrEqual(2);
126 expect(lines.reduce((t,x)=>t+Number(x.data.debit||0),0)).toBe(4500);
127 expect(lines.reduce((t,x)=>t+Number(x.data.credit||0),0)).toBe(4500);
128 expect(posted.journalVoucherId).toBe(vouchers[0].id);
129 // Repeat post must be idempotent, and posted source cannot be edited or overwritten.
130 await page.evaluate(x=>finalizeInvoiceDocument(x),id);
131 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
132 await page.evaluate(x=>editInvoice(x),id);
133 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
134 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
135 const saved=await page.evaluate(x=>getMyInvoices().find(i=>i.id===x),id);
136 expect(saved.documentStatus).toBe('posted');
137 expect(saved.grandTotal).toBe(4500);
138 expect(saved.documentVersion).toBe(2);
139 });
140 test('posted sale can be returned to an editable corrective draft; original voucher stays immutable and balances',async({page})=>{
141 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
142 await fillInvoice(page,'PILOT-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
143 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
144 const originalId=remoteInvoices(server)[0].id;
145 await page.evaluate(id=>finalizeInvoiceDocument(id),originalId);
146 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
147 const before=remoteInvoices(server)[0],originalVoucherId=before.journalVoucherId;
148 const originalLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy);
149 const result=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تصحیح تعداد پایلوت'),originalId);
150 expect(result).toBeTruthy();expect(result).not.toBe(originalId);
151 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
152 const after=remoteInvoices(server),original=after.find(i=>i.id===originalId),draft=after.find(i=>i.id===result);
153 expect(original.grandTotal).toBe(3000);
154 expect(original.journalVoucherId).toBe(originalVoucherId);
155 expect(draft.correctsInvoiceId).toBe(originalId);
156 expect(draft.documentStatus).toBe('draft');
157 expect(draft.journalVoucherId).toBeUndefined();
158 expect(draft.number).not.toBe(original.number);
159 const allVouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
160 expect(allVouchers).toHaveLength(2);
161 expect(allVouchers.find(x=>x.id===originalVoucherId).data.status).toBe('reversed');
162 const reversal=allVouchers.find(x=>x.id!==originalVoucherId);
163 expect(reversal.data.status).toBe('posted');
164 expect(originalLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy));
165 expect(await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),originalId)).toBe('reversed');
166 // The replacement source uses the normal draft editor and preserves provenance.
167 await page.evaluate(id=>editInvoice(id),result);
168 await expect(page.locator('#edit-invoice-id')).toHaveValue(result);
169 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
170 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
171 await page.evaluate(()=>commitSaveInvoice());
172 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.grandTotal,{timeout:13000}).toBe(4500);
173 await page.evaluate(id=>finalizeInvoiceDocument(id),result);
174 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.accountingStatus,{timeout:13000}).toBe('posted');
175 const later=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
176 expect(later).toHaveLength(3);
177 expect(later.find(x=>x.id===originalVoucherId).data.status).toBe('reversed');
178 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
179 for(const v of later){
180 const subset=lines.filter(l=>l.data.voucherId===v.id);
181 expect(subset.reduce((t,l)=>t+Number(l.data.debit||0),0)).toBe(subset.reduce((t,l)=>t+Number(l.data.credit||0),0));
182 }
183 // Reopening the same historical voucher again is blocked.
184 const retry=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},originalId);
185 expect(retry).not.toBe('unexpected');
186 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
187 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);
188 expect(persisted.old).toBe('reversed');
189 expect(persisted.drafts).toEqual(['posted']);
190 });
191
192 test('pilot manual journal correction permits draft edits, balanced repost and auditable cancellation',async({page})=>{
193 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
194 const first=await page.evaluate(()=>{
195 const v=jeCreateDraft({number:'8801',date:'1405/07/19',description:'ثبت آزمایشی',sourceType:'manual',
196 lines:[{accountId:'A_CASH',debit:1000,credit:0},{accountId:'A_REV',debit:0,credit:1000}]});
197 jePost(v.id);return v.id;
198 });
199 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='journalVouchers').length,{timeout:13000}).toBe(1);
200 const oldLineData=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy);
201 const ids=await page.evaluate(id=>{
202 const out=jeReturnPostedToDraft(id,'اشتباه مبلغ آزمایشی','1405/07/19');
203 return {draft:out.draft.id,reversal:out.reversal.id,old:out.original.id};
204 },first);
205 await page.evaluate(id=>jeUpdateDraft(id,{date:'1405/07/19',description:'اصلاح مبلغ به ۲۰۰۰',
206 lines:[{accountId:'A_CASH',debit:2000,credit:0},{accountId:'A_REV',debit:0,credit:2000}]}),ids.draft);
207 const details=await page.evaluate(({draft,old})=>{
208 jePost(draft);return {old:getMyJournalVouchers().find(x=>x.id===old).status,new:getMyJournalVouchers().find(x=>x.id===draft).status,trial:jeTrialBalance()};
209 },ids);
210 expect(details.old).toBe('reversed');expect(details.new).toBe('posted');
211 expect(details.trial.find(x=>x.accountId==='A_CASH').balance).toBe(2000);
212 await page.evaluate(id=>jeCancelPostedManual(id,'ابطال بعد از تست','1405/07/19'),ids.draft);
213 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(4);
214 const final=await page.evaluate(()=>jeTrialBalance());
215 expect(final.reduce((sum,row)=>sum+row.debit-row.credit,0)).toBe(0);
216 expect(final.find(x=>x.accountId==='A_CASH').balance).toBe(0);
217 expect(oldLineData).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy));
218 const rows=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
219 expect(rows.find(x=>x.id===first).data.status).toBe('reversed');
220 expect(rows.find(x=>x.id===ids.draft).data.status).toBe('reversed');
221 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
222 expect(await page.evaluate(()=>jeTrialBalance().find(x=>x.accountId==='A_CASH').balance)).toBe(0);
223 });
224
225 test('pilot cancellation preserves posted invoice record while only unposted drafts can be deleted',async({page})=>{
226 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
227 await fillInvoice(page,'PILOT-CANCEL-001',2);await page.evaluate(()=>commitSaveInvoice());
228 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
229 const invoiceId=remoteInvoices(server)[0].id;
230 await page.evaluate(id=>finalizeInvoiceDocument(id),invoiceId);
231 const original=remoteInvoices(server)[0];
232 expect(original.accountingStatus).toBe('posted');
233 const blocked=await page.evaluate(id=>{try{deleteInvoicePilotDraft(id);return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
234 expect(blocked).not.toBe('unexpected');
235 await page.evaluate(id=>cancelPostedInvoicePilot(id,'ابطال سند پایلوت'),invoiceId);
236 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(2);
237 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
238 expect(remoteInvoices(server)[0].grandTotal).toBe(original.grandTotal);
239 const status=await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),invoiceId);
240 expect(status).toBe('reversed');
241 const bad=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
242 expect(bad).not.toBe('unexpected');
243 // A separate never-posted invoice may be deleted; posted history stays intact.
244 await fillInvoice(page,'PILOT-DELETE-DRAFT-001',1);await page.evaluate(()=>commitSaveInvoice());
245 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
246 const draft=remoteInvoices(server).find(x=>x.number==='PILOT-DELETE-DRAFT-001');
247 expect(draft).toBeTruthy();
248 await page.evaluate(id=>deleteInvoicePilotDraft(id),draft.id);
249 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
250 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
251 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(2);
252 });
253
254 function remotePurchases(server){return [...server.records.values()].filter(x=>x.collection==='purchases').map(x=>copy(x.data));}
255 async function createPostedPurchase(page,server,number='PILOT-PUR-001',qty=2){
256 const id=await page.evaluate(({number,qty})=>{
257 const p={id:'PUR-QA-'+number,ownerUserId:'FINORA_F0_FIXTURE_ONLY',companyId:'QA_CO',number,date:'1405/07/19',supplierId:'QA_CONTACT',supplierName:'خریدار آزمایشی',paymentMethod:'cash',warehouseId:'',projectId:'',items:[{prodId:'QA_PROD',prodName:'بلوک سیمانی',qty,unit:'عدد',price:100,lineTotal:qty*100}],grandTotal:qty*100,vat:0,accountingVersion:1};
258 datastore.purchases.push(p);jePostSourceRecord('purchase',p);return p.id;
259 },{number,qty});
260 await expect.poll(()=>remotePurchases(server).find(x=>x.id===id)?.journalVoucherId,{timeout:13000}).toBeTruthy();
261 return id;
262 }
263 test('pilot purchase: posted to corrective draft to edited balanced repost via document manager',async({page})=>{
264 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
265 const originalId=await createPostedPurchase(page,server);
266 const first=remotePurchases(server).find(x=>x.id===originalId);
267 expect(first.accountingStatus).toBe('posted');
268 const voucher=first.journalVoucherId;
269 const untouched=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy);
270 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(2);
271 await page.evaluate(()=>{
272 window.confirm=()=>true;window.prompt=()=> 'اصلاح مقدار خرید';
273 navigateShell('accounting','view-journal','documents');
274 });
275 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PILOT-PUR-001');
276 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]')).toHaveCount(1);
277 // Technical correction primitive remains available for pre-existing in-progress
278 // drafts; the new employee UI correctly DOES NOT write on open.
279 await page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]').click();
280 expect(remotePurchases(server)).toHaveLength(1);
281 await page.evaluate(()=>purCancelEdit());
282 await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی'),originalId);
283 await expect.poll(()=>remotePurchases(server).length,{timeout:14000}).toBe(2);
284 const corrected=remotePurchases(server).find(x=>x.correctsPurchaseId===originalId);
285 expect(corrected.documentStatus).toBe('draft');
286 expect(corrected.journalVoucherId).toBeUndefined();
287 expect(corrected.number).not.toBe(first.number);
288 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
289 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),originalId)).toBe('reversed');
290 // Internal API fixture made a technical draft without clicking the employee form.
291 await page.evaluate(id=>purEdit(id),corrected.id);
292 await expect(page.locator('#pur-edit-id')).toHaveValue(corrected.id);
293 await page.locator('#pur-items-body .pur-qty').first().fill('3');
294 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
295 await page.locator('#pur-save-btn').click();
296 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.grandTotal,{timeout:14000}).toBe(300);
297 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
298 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
299 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]')).toHaveCount(1);
300 await page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]').click();
301 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.accountingStatus,{timeout:14000}).toBe('posted');
302 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
303 const journal=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
304 expect(journal).toHaveLength(3);
305 expect(journal.find(x=>x.id===voucher).data.status).toBe('reversed');
306 expect(untouched).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy));
307 for(const v of journal){
308 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
309 expect(lines.reduce((s,l)=>s+Number(l.data.debit||0),0)).toBe(lines.reduce((s,l)=>s+Number(l.data.credit||0),0));
310 }
311 const retry=await page.evaluate(async id=>{try{await returnPostedPurchaseAsDraft(id,'تکرار');return 'unsafe'}catch(e){return String(e.message)}},originalId);
312 expect(retry).not.toBe('unsafe');
313 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
314 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
315 });
316
317 test('pilot purchase denies paid/consumed source; cancels unallocated posting without erasing old voucher',async({page})=>{
318 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
319 const purchaseId=await createPostedPurchase(page,server,'PILOT-PUR-GUARDS');
320 // A payment allocation blocks both corrective reopen and cancellation.
321 const blockedPayment=await page.evaluate(async id=>{
322 datastore.payments.push({id:'QA-SETTLE',ownerUserId:currentUser.id,companyId:'QA_CO',direction:'outbound',invoiceType:'purchase',invoiceId:id,amount:10});
323 try{await cancelPostedPurchasePilot(id,'ابطال');return 'unsafe'}catch(e){return String(e.message)}
324 },purchaseId);
325 expect(blockedPayment).toMatch(/پرداخت/);
326 await page.evaluate(()=>{datastore.payments=datastore.payments.filter(x=>x.id!=='QA-SETTLE');});
327 // Consumption means stock would become negative after purchase reversal.
328 const blockedStock=await page.evaluate(async id=>{
329 const sale={id:'QA-USE',ownerUserId:currentUser.id,companyId:'QA_CO',kind:'formal',documentStatus:'posted',items:[{prodId:'QA_PROD',qty:2}],grandTotal:200};
330 datastore.invoices.push(sale);
331 try{await returnPostedPurchaseAsDraft(id,'اصلاح');return 'unsafe'}catch(e){return String(e.message)}
332 },purchaseId);
333 expect(blockedStock).toMatch(/موجودی/);
334 await page.evaluate(()=>{datastore.invoices=datastore.invoices.filter(x=>x.id!=='QA-USE');});
335 await page.evaluate(id=>cancelPostedPurchasePilot(id,'ابطال خرید آزمایشی'),purchaseId);
336 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:14000}).toBe(2);
337 expect(remotePurchases(server)).toHaveLength(1);
338 const original=remotePurchases(server)[0];
339 expect(original.id).toBe(purchaseId);
340 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),purchaseId)).toBe('reversed');
341 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
342 expect(await page.evaluate(id=>{try{deletePurchasePilotDraft(id);return 'unsafe'}catch(e){return String(e.message)}},purchaseId)).not.toBe('unsafe');
343 });
344 test('seamless sale correction: opening and cancelling leaves ledger unchanged; saving retains visible identity, printing and audit',async({page})=>{
345 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
346 await fillInvoice(page,'SAME-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
347 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
348 const id=remoteInvoices(server)[0].id;await page.evaluate(x=>finalizeInvoiceDocument(x),id);
349 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
350 const original=copy(remoteInvoices(server)[0]),initialLines=[...server.records.values()].filter(x=>x.collection==='journalLines').map(copy);
351 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
352 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
353 await page.locator('#finora-document-management-body [data-doc-action="reopen"]').click();
354 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
355 await expect(page.locator('#invoice-number')).toHaveValue('SAME-SALE-001');
356 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
357 await page.evaluate(()=>cancelInvoiceEdit());
358 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
359 expect(remoteInvoices(server)).toHaveLength(1);
360 await page.evaluate(x=>beginInvoiceAmendment(x),id);
361 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
362 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
363 await page.evaluate(()=>commitSaveInvoice());
364 await expect.poll(()=>remoteInvoices(server).filter(x=>x.correctsInvoiceId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
365 expect(remoteInvoices(server)).toHaveLength(2);expect(remoteInvoices(server).find(x=>x.id===id)).toEqual(original);
366 const current=remoteInvoices(server).find(x=>x.correctsInvoiceId===id);
367 expect(current.grandTotal).toBe(4500);
368 expect(current.number).not.toBe(original.number);
369 const visible=await page.evaluate(()=>invoiceVisibleRecords().map(x=>({id:x.id,number:invoiceVisibleNumber(x)})));
370 expect(visible).toEqual([{id:current.id,number:'SAME-SALE-001'}]);
371 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
372 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
373 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
374 await expect(page.locator('#finora-document-management-body')).not.toContainText('-اصلاح');
375 await page.evaluate(x=>renderAndPrintDirect(x),id);
376 await expect(page.locator('#printable-invoice')).toContainText('SAME-SALE-۰۰۱');
377 await expect(page.locator('#printable-invoice')).toContainText('۴٬۵۰۰');
378 await expect(page.locator('#printable-invoice')).not.toContainText('-اصلاح');
379 expect(initialLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy));
380 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
381 expect(vouchers).toHaveLength(3);expect(vouchers.find(v=>v.id===original.journalVoucherId).data.status).toBe('reversed');
382 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
383 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
384 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
385 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
386 });
387
388 test('seamless purchase correction: same visible number, no write on opening, save and print corrected purchase',async({page})=>{
389 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
390 const id=await createPostedPurchase(page,server,'SAME-PURCHASE-001',2);
391 const initial=copy(remotePurchases(server).find(x=>x.id===id));const before=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
392 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
393 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
394 await page.locator('#finora-purchase-document-management-body [data-doc-action="reopen"]').click();
395 await expect(page.locator('#pur-edit-id')).toHaveValue(id);
396 await expect(page.locator('#pur-number')).toHaveValue('SAME-PURCHASE-001');
397 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(before.length);
398 await page.evaluate(()=>purCancelEdit());
399 expect(remotePurchases(server)).toHaveLength(1);
400 await page.evaluate(x=>beginPurchaseAmendment(x),id);
401 await page.locator('#pur-items-body .pur-qty').first().fill('3');
402 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
403 await page.locator('#pur-save-btn').click();
404 await expect.poll(()=>remotePurchases(server).filter(x=>x.correctsPurchaseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
405 expect(remotePurchases(server).find(x=>x.id===id)).toEqual(initial);
406 const current=remotePurchases(server).find(x=>x.correctsPurchaseId===id);
407 expect(current.grandTotal).toBe(300);expect(current.number).not.toBe(initial.number);
408 const visible=await page.evaluate(()=>purchaseVisibleRecords().map(x=>({id:x.id,number:purchaseVisibleNumber(x)})));
409 expect(visible).toEqual([{id:current.id,number:'SAME-PURCHASE-001'}]);
410 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
411 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
412 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
413 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('-اصلاح');
414 await page.evaluate(x=>purPrint(x),id);
415 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
416 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
417 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
418 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
419 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
420 });
421 function remotePayments(server){return [...server.records.values()].filter(x=>x.collection==='payments').map(x=>copy(x.data));}
422 async function createUiPayment(page,server,amount=1000,direction='inbound'){
423 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
424 await page.locator('#pay-direction').selectOption(direction);
425 await page.locator('#pay-contact').selectOption('QA_CONTACT');
426 await page.locator('#pay-method').selectOption('bank');
427 await page.locator('#pay-amount').fill(String(amount));
428 await page.locator('#pay-reference').fill('REF-ORIGINAL-001');
429 await page.evaluate(()=>commitSavePayment());
430 await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
431 await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
432 return remotePayments(server)[0].id;
433 }
434
435 test('treasury amendment in the same form preserves one record and same reference without on-open ledger writes',async({page})=>{
436 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
437 const firstId=await createUiPayment(page,server);
438 await page.waitForFunction(()=>!syncPending&&!syncRunning);
439 const first=copy(remotePayments(server)[0]);
440 const oldLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy);
441 const beforeRpc=server.rpcCount;
442 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
443 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
444 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
445 await page.locator('#finora-treasury-document-management-body [data-doc-action="edit"]').click();
446 await expect(page.locator('#pay-amount')).toHaveValue('1000');
447 await expect(page.locator('#pay-reference')).toHaveValue('REF-ORIGINAL-001');
448 await page.evaluate(()=>resetPaymentForm());
449 expect(server.rpcCount).toBe(beforeRpc);
450 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
451 expect(remotePayments(server)).toHaveLength(1);
452 await page.locator('#payments-ledger button').first().click();
453 await page.locator('#pay-amount').fill('1250');
454 await page.locator('#pay-note').fill('اصلاح مبلغ');
455 const beforeCorrectionRpc=server.rpcCount;
456 await page.locator('#pay-save').click();
457 await expect.poll(()=>remotePayments(server).filter(x=>x.correctsPaymentId===firstId&&x.accountingStatus==='posted').length,{timeout:18000}).toBe(1);
458 await page.waitForFunction(()=>!syncPending&&!syncRunning);
459 // Reversal + new source + repost must be a single server-side sync_records batch.
460 expect(server.rpcCount-beforeCorrectionRpc).toBe(1);
461 const original=remotePayments(server).find(p=>p.id===firstId);
462 expect(original).toEqual(first);
463 const amended=remotePayments(server).find(p=>p.correctsPaymentId===firstId);
464 expect(amended.amount).toBe(1250);
465 expect(amended.reference).toBe(first.reference);
466 expect(amended.journalVoucherId).toBeTruthy();
467 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
468 expect(vouchers).toHaveLength(3);
469 expect(vouchers.find(x=>x.id===first.journalVoucherId).data.status).toBe('reversed');
470 expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy));
471 for(const v of vouchers){
472 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
473 expect(lines.reduce((n,x)=>n+Number(x.data.debit||0),0)).toBe(lines.reduce((n,x)=>n+Number(x.data.credit||0),0));
474 }
475 expect(await page.evaluate(()=>paymentVisibleRecords().map(x=>x.id))).toEqual([amended.id]);
476 expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
477 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
478 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
479 await expect(page.locator('#finora-treasury-document-management-body')).toContainText('REF-ORIGINAL-001');
480 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
481 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
482 await expect(page.locator('#payments-ledger')).toContainText('۱٬۲۵۰');
483 await expect(page.locator('#payments-ledger')).toContainText('REF-ORIGINAL-001');
484 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
485 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
486 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
487 expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
488 });
489
490 test('treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history',async({page})=>{
491 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
492 const id=await createUiPayment(page,server,450,'outbound');
493 const noCheck=await page.evaluate(async id=>{
494 const p=getMyPayments().find(x=>x.id===id);
495 const saved=p.method;p.method='cheque';
496 try{await paymentAmendPosted(id,{direction:p.direction,contactId:p.contactId,companyId:p.companyId,
497 amount:400,method:'cash',invoiceId:'',invoiceType:'',reference:'x',note:'x'});return 'unsafe';}
498 catch(e){return String(e.message)}
499 finally{p.method=saved}
500 },id);
501 expect(noCheck).toMatch(/چک|تطبیق/);
502 const linked=await page.evaluate(async id=>{
503 const p=getMyPayments().find(x=>x.id===id);
504 p.invoiceType='purchase';p.invoiceId='QA_LINKED';
505 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
506 catch(e){return String(e.message)}
507 finally{p.invoiceType='';p.invoiceId=''}
508 },id);
509 expect(linked).toMatch(/تسویه|فاکتور|تطبیق/);
510 const locked=await page.evaluate(async id=>{
511 const fy=getMyFiscalYears()[0],old=fy.status;
512 fy.status='locked';
513 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
514 catch(e){return String(e.message)}
515 finally{fy.status=old}
516 },id);
517 expect(locked).toMatch(/قفل|سال مالی/);
518 await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال اشتباه آزمایشی';});
519 await page.evaluate(id=>deletePayment(id),id);
520 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(2);
521 expect(remotePayments(server)).toHaveLength(1);
522 expect(remotePayments(server)[0].id).toBe(id);
523 expect(await page.evaluate(id=>paymentPostingStatus(getMyPayments().find(x=>x.id===id)),id)).toBe('reversed');
524 expect(await page.evaluate(()=>paymentEffectiveRecords().length)).toBe(0);
525 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
526 await expect(page.locator('#payments-ledger')).toContainText('ابطال‌شده');
527 });
528
529 test('treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload',async({page})=>{
530 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
531 const id=await createUiPayment(page,server);
532 await page.waitForFunction(()=>!syncPending&&!syncRunning);
533 const before=copy(remotePayments(server)[0]);
534 const vouchersBefore=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id);
535 server.failNext=true;
536 await page.evaluate(id=>editPayment(id),id);
537 await page.locator('#pay-amount').fill('1800');
538 await page.locator('#pay-save').click();
539 await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('اصلاح کامل نشد'))),{timeout:8000}).toBe(true);
540 expect(server.failCount).toBe(1);
541 // The RPC did not persist any subset of the combined financial diff.
542 expect(remotePayments(server)).toEqual([before]);
543 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(vouchersBefore);
544 // After uncertain acknowledgment, do not call the amend API again blindly.
545 });
546 function remoteExpenses(server){return [...server.records.values()].filter(x=>x.collection==='expenses').map(x=>copy(x.data));}
547 async function createUiExpense(page,server,kind='expense',amount=1000){
548 expect(await page.evaluate(()=>String(commitSaveExpense).includes('expenseAmendPosted'))).toBe(true);
549 expect(await page.evaluate(()=>String(renderExpenses).includes('expenseVisibleRecords'))).toBe(true);
550 await page.evaluate(()=>{switchView('view-expenses');renderExpenses()});
551 await page.locator('#trx-kind-input').selectOption(kind);
552 await page.locator('#trx-category-input').selectOption('سایر');
553 await page.locator('#trx-amount-input').fill(String(amount));
554 await page.locator('#trx-desc-input').fill('ثبت اولیه آزمایشی');
555 await page.evaluate(()=>commitSaveExpense());
556 await expect.poll(()=>remoteExpenses(server).length,{timeout:14000}).toBe(1);
557 await expect.poll(()=>remoteExpenses(server)[0]?.accountingStatus,{timeout:14000}).toBe('posted');
558 return remoteExpenses(server)[0].id;
559 }
560 test('expense same-form correction preserves one row, posted history and project cost across reload',async({page})=>{
561 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
562 const id=await createUiExpense(page,server);
563 await page.waitForFunction(()=>!syncPending&&!syncRunning);
564 const original=remoteExpenses(server)[0],oldLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy),rpcBefore=server.rpcCount;
565 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
566 await expect(page.locator('#finora-expense-document-management-body tr')).toHaveCount(1);
567 await page.locator('#finora-expense-document-management-body [data-doc-action="edit"]').click();
568 await expect.poll(async()=>page.evaluate(()=>parseFormattedNumber(document.getElementById('trx-amount-input').value))).toBe(1000);
569 await expect(page.locator('#trx-kind-input')).toHaveValue('expense');
570 await expect(page.locator('#trx-desc-input')).toHaveValue('ثبت اولیه آزمایشی');
571 await page.evaluate(()=>cancelExpenseEdit());
572 expect(server.rpcCount).toBe(rpcBefore);
573 expect(remoteExpenses(server)).toHaveLength(1);
574 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
575 await page.evaluate(x=>editExpense(x),id);
576 await page.locator('#trx-amount-input').fill('1450');
577 await page.locator('#trx-desc-input').fill('اصلاح در همان فرم');
578 const rpcAtSave=server.rpcCount;
579 await page.locator('#expense-save-btn').click();
580 await page.waitForTimeout(900);
581 console.log('EXPENSE_TEST_DIAGNOSTIC',JSON.stringify(await page.evaluate(()=>({alerts:window.__f0Alerts,editing:expenseEditingId,rows:getMyExpenses().map(x=>({id:x.id,original:x.correctsExpenseId,accountingStatus:x.accountingStatus,amount:x.amount})),sync:{pending:syncPending,running:syncRunning,fail:syncFailCount}}))));
582 await expect.poll(()=>remoteExpenses(server).filter(x=>x.correctsExpenseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
583 await page.waitForFunction(()=>!syncRunning&&!syncPending);
584 expect(server.rpcCount-rpcAtSave).toBe(1);
585 expect(remoteExpenses(server).find(x=>x.id===id)).toEqual(original);
586 const newer=remoteExpenses(server).find(x=>x.correctsExpenseId===id);
587 expect(newer.amount).toBe(1450);expect(newer.desc).toBe('اصلاح در همان فرم');
588 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
589 expect(vouchers).toHaveLength(3);
590 expect(vouchers.find(x=>x.id===original.journalVoucherId).data.status).toBe('reversed');
591 expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy));
592 for(const v of vouchers){
593 const ls=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
594 expect(ls.reduce((sum,l)=>sum+Number(l.data.debit||0),0)).toBe(ls.reduce((sum,l)=>sum+Number(l.data.credit||0),0));
595 }
596 expect(await page.evaluate(()=>expenseVisibleRecords().map(x=>x.id))).toEqual([newer.id]);
597 expect(await page.evaluate(()=>expenseEffectiveRecords().map(x=>x.amount))).toEqual([1450]);
598 expect(await page.evaluate(()=>getProjectFinancials('').expenses)).toBe(1450);
599 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
600 await expect(page.locator('#finora-expense-document-management-body tr')).toHaveCount(1);
601 await expect(page.locator('#finora-expense-document-management-body')).toContainText('۱٬۴۵۰');
602 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
603 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
604 await expect(page.locator('#finora-expense-document-management-body tr')).toHaveCount(1);
605 expect(await page.evaluate(()=>getProjectFinancials('').expenses)).toBe(1450);
606 });
607
608 test('income correction and cancellation preserve initial audit and eliminate active project income',async({page})=>{
609 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
610 const id=await createUiExpense(page,server,'income',700);
611 await page.waitForFunction(()=>!syncPending&&!syncRunning);
612 const locked=await page.evaluate(id=>{
613 const fy=getMyFiscalYears()[0],old=fy.status;fy.status='locked';
614 try{expenseCorrectionEligibility(id);return 'unsafe'}catch(e){return String(e.message)}
615 finally{fy.status=old}
616 },id);
617 expect(locked).toMatch(/مالی|قفل/);
618 expect(await page.evaluate(()=>getProjectFinancials('').income)).toBe(700);
619 await page.evaluate(id=>editExpense(id),id);
620 await expect(page.locator('#trx-kind-input')).toHaveValue('income');
621 await page.locator('#trx-amount-input').fill('950');
622 await page.locator('#expense-save-btn').click();
623 await page.waitForTimeout(900);
624 console.log('EXPENSE_TEST_DIAGNOSTIC',JSON.stringify(await page.evaluate(()=>({alerts:window.__f0Alerts,editing:expenseEditingId,rows:getMyExpenses().map(x=>({id:x.id,original:x.correctsExpenseId,accountingStatus:x.accountingStatus,amount:x.amount})),sync:{pending:syncPending,running:syncRunning,fail:syncFailCount}}))));
625 await expect.poll(()=>remoteExpenses(server).filter(x=>x.correctsExpenseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
626 const replacement=remoteExpenses(server).find(x=>x.correctsExpenseId===id);
627 expect(await page.evaluate(()=>getProjectFinancials('').income)).toBe(950);
628 await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال درآمد آزمایشی';});
629 await page.evaluate(id=>cancelPostedExpenseUi(id),replacement.id);
630 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(4);
631 expect(remoteExpenses(server)).toHaveLength(2);
632 expect(await page.evaluate(()=>expenseEffectiveRecords().length)).toBe(0);
633 expect(await page.evaluate(()=>getProjectFinancials('').income)).toBe(0);
634 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
635 await expect(page.locator('#finora-expense-document-management-body')).toContainText('ابطال‌شده');
636 });
637
638 test('expense amendment refuses mismatched kind and failed single RPC does not partially commit posted records',async({page})=>{
639 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
640 const id=await createUiExpense(page,server,'expense',500);
641 await page.waitForFunction(()=>!syncRunning&&!syncPending);
642 const original=copy(remoteExpenses(server)[0]),originalJournalIds=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id);
643 const mismatch=await page.evaluate(async id=>{
644 const e=getMyExpenses().find(x=>x.id===id);
645 try{await expenseAmendPosted(id,{kind:'income',contactId:e.contactId||'',projectId:e.projectId||'',amount:600,category:'سایر',desc:'x'});return 'unsafe';}
646 catch(err){return String(err.message)}
647 },id);
648 expect(mismatch).toMatch(/نوع سند|نوع|طرف حساب/);
649 server.failNext=true;
650 await page.evaluate(id=>editExpense(id),id);
651 await page.locator('#trx-amount-input').fill('800');
652 await page.locator('#expense-save-btn').click();
653 await page.waitForTimeout(900);
654 console.log('EXPENSE_FAIL_DIAGNOSTIC',JSON.stringify(await page.evaluate(()=>({alerts:window.__f0Alerts,editing:expenseEditingId,rows:getMyExpenses().map(x=>({id:x.id,source:x.correctsExpenseId,status:x.accountingStatus})),sync:{pending:syncPending,running:syncRunning,fail:syncFailCount}}))));
655 await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('ثبت اصلاح تأیید نشد'))),{timeout:9000}).toBe(true);
656 expect(server.failCount).toBe(1);
657 expect(remoteExpenses(server)).toEqual([original]);
658 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(originalJournalIds);
659 });
660 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
661 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
662 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());
663 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
664 const id=remoteInvoices(server)[0].id;
665 const result=await page.evaluate(async x=>{try{await finalizeInvoiceDocument(x);return 'unexpected success'}catch(e){return String(e.message)}},id);
666 expect(result).toMatch(/حساب|کدینگ/);
667 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
668 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
669 });
670
671
672 test('F2 validates formal invoice then saves a draft without posting any financial journal',async({page})=>{
673 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
674 await page.keyboard.press('F2');
675 expect(remoteInvoices(server)).toHaveLength(0);
676 expect(await page.evaluate(()=>window.__f0Alerts.at(-1))).toMatch(/حداقل یک کالا|خدمت معتبر/);
677 await fillInvoice(page,'F2-SAFE-DRAFT-001',2);
678 await page.keyboard.press('F2');
679 await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1);
680 const saved=remoteInvoices(server)[0];
681 expect(saved.number).toBe('F2-SAFE-DRAFT-001');
682 expect(saved.accountingStatus).toBe('draft');
683 expect(saved.documentStatus).toBe('draft');
684 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
685 await page.keyboard.press('F2');
686 expect(remoteInvoices(server)).toHaveLength(1);
687 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
688 });