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

fix/login-startup-readiness-20261024
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 643 lines 45.7 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 ])records.set(collection+'|'+id,{collection,id,data:copy(data)});
21 return {records,failNext:false,failCount:0,rpcCount:0};
22 }
23 function remoteInvoices(server){return [...server.records.values()].filter(r=>r.collection==='invoices').map(r=>copy(r.data));}
24
25 async function installHarness(page,server){
26 await page.exposeFunction('qaF0Read',async()=>[...server.records.values()].map(copy));
27 await page.exposeFunction('qaF0Write',async args=>{
28 server.rpcCount++;
29 if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'Network unavailable — isolated QA failure',code:'QA_NETWORK'}};}
30 for(const row of args.p_upserts||[])server.records.set(row.collection+'|'+row.id,{collection:row.collection,id:row.id,data:copy(row.data)});
31 for(const row of args.p_deletes||[])server.records.delete(row.collection+'|'+row.id);
32 return {error:null};
33 });
34 await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
35 }
36 async function authenticatedMockBrowser(page){
37 await page.goto(BASE,{waitUntil:'domcontentloaded'});
38 // The synthetic account must not race the organization entitlement wrapper.
39 // Function availability precedes completion of asynchronously loaded ERP modules.
40 await page.waitForFunction(()=>typeof enterApp==='function'&&typeof commitSaveInvoice==='function'&&
41 typeof pullAll==='function'&&window.FinoraStartupStatus?.extensionsReady===true&&
42 window.FinoraStartupStatus?.failedExtensionCount===0&&
43 window.FinoraStartupStatus?.authChecked===true,{timeout:20000});
44 await page.evaluate(async()=>{
45 window.__FINORA_PRINT_TEST_MODE=true;
46 window.__f0Alerts=[];
47 window.alert=m=>window.__f0Alerts.push(String(m));
48 window.confirm=()=>false;
49 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'}});
50 maybeMigrateLegacyData=()=>{};
51 sb.from=collection=>({
52 select:()=>({
53 order(){return this;},
54 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};}
55 })
56 });
57 sb.rpc=async(name,args)=>{
58 if(name!=='finora_sync_records')throw Error('Unexpected RPC '+name);
59 return await window.qaF0Write(args);
60 };
61 await enterApp({id:'FINORA_F0_FIXTURE_ONLY'});
62 document.querySelectorAll('.modal-backdrop.active').forEach(x=>x.classList.remove('active'));
63 switchView('view-invoices');
64 });
65 await expect(page.locator('#auth-screen')).toBeHidden();
66 await expect(page.locator('#invoice-company-id option[value="QA_CO"]')).toHaveCount(1);
67 await expect(page.locator('#invoice-items-table-body .row-product-select').first().locator('option[value="QA_PROD"]')).toHaveCount(1);
68 }
69 async function fillInvoice(page,number,qty){
70 // The native invoice-kind/contact selectors are hidden by the unified commercial combobox.
71 // Drive their real DOM change handlers, not Playwright visibility on replaced native selects.
72 await page.evaluate(()=>{
73 for(const [id,value] of [['invoice-kind','formal'],['invoice-company-id','QA_CO'],['invoice-contact-id','QA_CONTACT']]){
74 const el=document.getElementById(id);el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
75 }
76 });
77 await page.locator('#invoice-number').fill(number);
78 await page.locator('#invoice-date-input').fill('۱۴۰۵/۰۷/۱۹');
79 await page.evaluate(()=>{
80 const el=document.querySelector('#invoice-items-table-body .row-product-select');
81 el.value='QA_PROD';el.dispatchEvent(new Event('change',{bubbles:true}));
82 });
83 await page.locator('#invoice-items-table-body .row-quantity').first().fill(String(qty));
84 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
85 }
86
87 test('invoice and purchase registers isolate companies selected in Settings; no ALL fallback or cross-company edit',async({page})=>{
88 const server=fakeServer();
89 const sale=(id,companyId,number)=>({companyId,kind:'non_formal',kindLabel:'غیررسمی',number,date:'1405/07/19',
90 contactId:'QA_CONTACT',contactName:'طرف حساب آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:1500}],grandTotal:1500,
91 documentStatus:'draft',accountingStatus:'draft'});
92 const purchase=(id,companyId,number)=>({companyId,number,date:'1405/07/19',supplierId:'QA_CONTACT',
93 supplierName:'تأمین‌کننده آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:100}],grandTotal:100,accountingStatus:'draft'});
94 server.records.set('companies|QA_CO_B',{collection:'companies',id:'QA_CO_B',data:{name:'شرکت دوم آزمون'}});
95 for(const [collection,id,data] of [
96 ['invoices','INV_SCOPE_A',sale('INV_SCOPE_A','QA_CO','INV-COMPANY-A')],
97 ['invoices','INV_SCOPE_B',sale('INV_SCOPE_B','QA_CO_B','INV-COMPANY-B')],
98 ['invoices','INV_LEGACY_UNSCOPED',sale('INV_LEGACY_UNSCOPED','', 'INV-LEGACY')],
99 ['purchases','PUR_SCOPE_A',purchase('PUR_SCOPE_A','QA_CO','PUR-COMPANY-A')],
100 ['purchases','PUR_SCOPE_B',purchase('PUR_SCOPE_B','QA_CO_B','PUR-COMPANY-B')]
101 ])server.records.set(collection+'|'+id,{collection,id,data});
102 await installHarness(page,server);await authenticatedMockBrowser(page);
103 const archive=page.locator('#invoice-archive-table-body');
104 const purchases=page.locator('#pur-list-body');
105 await expect(archive).toContainText('INV-COMPANY-A');
106 await expect(archive).not.toContainText('INV-COMPANY-B');
107 await expect(archive).not.toContainText('INV-LEGACY');
108 await expect(purchases).toContainText('PUR-COMPANY-A');
109 await expect(purchases).not.toContainText('PUR-COMPANY-B');
110 await expect(page.locator('#filter-invoice-company')).toBeDisabled();
111 await expect(page.locator('#filter-invoice-company option')).toHaveCount(1);
112 await expect(page.locator('#filter-invoice-company option[value="ALL"]')).toHaveCount(0);
113 await expect(page.locator('#invoice-company-id')).toBeDisabled();
114 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
115 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
116 await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-A');
117 await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-B');
118 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-A');
119 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-B');
120 // A settings change refreshes all three surfaces without new login.
121 await page.evaluate(()=>setDefaultCompany('QA_CO_B'));
122 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO_B');
123 await expect(archive).toContainText('INV-COMPANY-B');
124 await expect(archive).not.toContainText('INV-COMPANY-A');
125 await expect(purchases).toContainText('PUR-COMPANY-B');
126 await expect(purchases).not.toContainText('PUR-COMPANY-A');
127 await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-B');
128 await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-A');
129 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-B');
130 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-A');
131 // Direct stale entrypoint cannot open an off-company draft.
132 await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_A')});
133 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
134 await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_B')});
135 await expect(page.locator('#edit-invoice-id')).toHaveValue('INV_SCOPE_B');
136 // Changing company while a form is open clears that edit context.
137 await page.evaluate(()=>setDefaultCompany('QA_CO'));
138 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
139 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
140 await expect(archive).toContainText('INV-COMPANY-A');
141 await expect(archive).not.toContainText('INV-COMPANY-B');
142 await expect(purchases).toContainText('PUR-COMPANY-A');
143 await expect(purchases).not.toContainText('PUR-COMPANY-B');
144 // Both originals are preserved in storage.
145 expect(await page.evaluate(()=>getMyInvoices().filter(x=>x.id.startsWith('INV_SCOPE_')).length)).toBe(2);
146 expect(await page.evaluate(()=>getMyPurchases().filter(x=>x.id.startsWith('PUR_SCOPE_')).length)).toBe(2);
147 await page.waitForFunction(()=>!syncPending&&!syncRunning);
148 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
149 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
150 await expect(page.locator('#invoice-archive-table-body')).toContainText('INV-COMPANY-A');
151 await expect(page.locator('#invoice-archive-table-body')).not.toContainText('INV-COMPANY-B');
152 });
153 test('formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher',async({page})=>{
154 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
155 await fillInvoice(page,'FIN-DRAFT-001',2);
156 await page.evaluate(()=>commitSaveInvoice());
157 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
158 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
159 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
160 const id=remoteInvoices(server)[0].id;
161 // A saved formal draft prints its complete invoice; the print UI must not stamp it
162 // as provisional. The underlying draft state and zero-posting invariant remain.
163 await page.evaluate(x=>renderAndPrintDirect(x),id);
164 await expect(page.locator('#printable-invoice')).toContainText('FIN-DRAFT-۰۰۱');
165 await expect(page.locator('#printable-invoice')).toContainText('۳٬۰۰۰');
166 await expect(page.locator('#printable-invoice')).not.toContainText('پیش‌نویس — غیرقطعی');
167 await expect(page.locator('#printable-invoice [style*="rotate(-12deg)"]')).toHaveCount(0);
168 const isolatedPrint=page.frameLocator('#finora-print-frame').locator('#finora-print-document');
169 await expect(isolatedPrint).toContainText('FIN-DRAFT-۰۰۱');
170 await expect(isolatedPrint).not.toContainText('پیش‌نویس — غیرقطعی');
171 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
172 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
173 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
174 await page.evaluate(x=>editInvoice(x),id);
175 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
176 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
177 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
178 await page.evaluate(()=>commitSaveInvoice());
179 await expect.poll(()=>remoteInvoices(server)[0]?.grandTotal,{timeout:13000}).toBe(4500);
180 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
181 await expect(page.locator('#finora-document-management-body')).toContainText('FIN-DRAFT-001');
182 await expect(page.locator('#finora-document-management-body')).toContainText('پیش‌نویس');
183 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
184 // Show a confirmation requiring explicit intent; no automatic posting on Save.
185 await expect.poll(()=>remoteInvoices(server)[0].accountingStatus,{timeout:3000}).toBe('draft');
186 await page.evaluate(()=>{window.confirm=()=>true});
187 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
188 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
189 const posted=remoteInvoices(server)[0];
190 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
191 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
192 expect(vouchers).toHaveLength(1);
193 expect(vouchers[0].data.status).toBe('posted');
194 expect(lines.length).toBeGreaterThanOrEqual(2);
195 expect(lines.reduce((t,x)=>t+Number(x.data.debit||0),0)).toBe(4500);
196 expect(lines.reduce((t,x)=>t+Number(x.data.credit||0),0)).toBe(4500);
197 expect(posted.journalVoucherId).toBe(vouchers[0].id);
198 // Repeat post must be idempotent, and posted source cannot be edited or overwritten.
199 await page.evaluate(x=>finalizeInvoiceDocument(x),id);
200 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
201 await page.evaluate(x=>editInvoice(x),id);
202 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
203 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
204 const saved=await page.evaluate(x=>getMyInvoices().find(i=>i.id===x),id);
205 expect(saved.documentStatus).toBe('posted');
206 expect(saved.grandTotal).toBe(4500);
207 expect(saved.documentVersion).toBe(2);
208 });
209 test('posted sale can be returned to an editable corrective draft; original voucher stays immutable and balances',async({page})=>{
210 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
211 await fillInvoice(page,'PILOT-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
212 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
213 const originalId=remoteInvoices(server)[0].id;
214 await page.evaluate(id=>finalizeInvoiceDocument(id),originalId);
215 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
216 const before=remoteInvoices(server)[0],originalVoucherId=before.journalVoucherId;
217 const originalLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy);
218 const result=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تصحیح تعداد پایلوت'),originalId);
219 expect(result).toBeTruthy();expect(result).not.toBe(originalId);
220 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
221 const after=remoteInvoices(server),original=after.find(i=>i.id===originalId),draft=after.find(i=>i.id===result);
222 expect(original.grandTotal).toBe(3000);
223 expect(original.journalVoucherId).toBe(originalVoucherId);
224 expect(draft.correctsInvoiceId).toBe(originalId);
225 expect(draft.documentStatus).toBe('draft');
226 expect(draft.journalVoucherId).toBeUndefined();
227 expect(draft.number).not.toBe(original.number);
228 const allVouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
229 expect(allVouchers).toHaveLength(2);
230 expect(allVouchers.find(x=>x.id===originalVoucherId).data.status).toBe('reversed');
231 const reversal=allVouchers.find(x=>x.id!==originalVoucherId);
232 expect(reversal.data.status).toBe('posted');
233 expect(originalLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy));
234 expect(await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),originalId)).toBe('reversed');
235 // The replacement source uses the normal draft editor and preserves provenance.
236 await page.evaluate(id=>editInvoice(id),result);
237 await expect(page.locator('#edit-invoice-id')).toHaveValue(result);
238 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
239 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
240 await page.evaluate(()=>commitSaveInvoice());
241 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.grandTotal,{timeout:13000}).toBe(4500);
242 await page.evaluate(id=>finalizeInvoiceDocument(id),result);
243 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.accountingStatus,{timeout:13000}).toBe('posted');
244 const later=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
245 expect(later).toHaveLength(3);
246 expect(later.find(x=>x.id===originalVoucherId).data.status).toBe('reversed');
247 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
248 for(const v of later){
249 const subset=lines.filter(l=>l.data.voucherId===v.id);
250 expect(subset.reduce((t,l)=>t+Number(l.data.debit||0),0)).toBe(subset.reduce((t,l)=>t+Number(l.data.credit||0),0));
251 }
252 // Reopening the same historical voucher again is blocked.
253 const retry=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},originalId);
254 expect(retry).not.toBe('unexpected');
255 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
256 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);
257 expect(persisted.old).toBe('reversed');
258 expect(persisted.drafts).toEqual(['posted']);
259 });
260
261 test('pilot manual journal correction permits draft edits, balanced repost and auditable cancellation',async({page})=>{
262 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
263 const first=await page.evaluate(()=>{
264 const v=jeCreateDraft({number:'8801',date:'1405/07/19',description:'ثبت آزمایشی',sourceType:'manual',
265 lines:[{accountId:'A_CASH',debit:1000,credit:0},{accountId:'A_REV',debit:0,credit:1000}]});
266 jePost(v.id);return v.id;
267 });
268 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='journalVouchers').length,{timeout:13000}).toBe(1);
269 const oldLineData=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy);
270 const ids=await page.evaluate(id=>{
271 const out=jeReturnPostedToDraft(id,'اشتباه مبلغ آزمایشی','1405/07/19');
272 return {draft:out.draft.id,reversal:out.reversal.id,old:out.original.id};
273 },first);
274 await page.evaluate(id=>jeUpdateDraft(id,{date:'1405/07/19',description:'اصلاح مبلغ به ۲۰۰۰',
275 lines:[{accountId:'A_CASH',debit:2000,credit:0},{accountId:'A_REV',debit:0,credit:2000}]}),ids.draft);
276 const details=await page.evaluate(({draft,old})=>{
277 jePost(draft);return {old:getMyJournalVouchers().find(x=>x.id===old).status,new:getMyJournalVouchers().find(x=>x.id===draft).status,trial:jeTrialBalance()};
278 },ids);
279 expect(details.old).toBe('reversed');expect(details.new).toBe('posted');
280 expect(details.trial.find(x=>x.accountId==='A_CASH').balance).toBe(2000);
281 await page.evaluate(id=>jeCancelPostedManual(id,'ابطال بعد از تست','1405/07/19'),ids.draft);
282 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(4);
283 const final=await page.evaluate(()=>jeTrialBalance());
284 expect(final.reduce((sum,row)=>sum+row.debit-row.credit,0)).toBe(0);
285 expect(final.find(x=>x.accountId==='A_CASH').balance).toBe(0);
286 expect(oldLineData).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy));
287 const rows=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
288 expect(rows.find(x=>x.id===first).data.status).toBe('reversed');
289 expect(rows.find(x=>x.id===ids.draft).data.status).toBe('reversed');
290 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
291 expect(await page.evaluate(()=>jeTrialBalance().find(x=>x.accountId==='A_CASH').balance)).toBe(0);
292 });
293
294 test('pilot cancellation preserves posted invoice record while only unposted drafts can be deleted',async({page})=>{
295 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
296 await fillInvoice(page,'PILOT-CANCEL-001',2);await page.evaluate(()=>commitSaveInvoice());
297 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
298 const invoiceId=remoteInvoices(server)[0].id;
299 await page.evaluate(id=>finalizeInvoiceDocument(id),invoiceId);
300 const original=remoteInvoices(server)[0];
301 expect(original.accountingStatus).toBe('posted');
302 const blocked=await page.evaluate(id=>{try{deleteInvoicePilotDraft(id);return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
303 expect(blocked).not.toBe('unexpected');
304 await page.evaluate(id=>cancelPostedInvoicePilot(id,'ابطال سند پایلوت'),invoiceId);
305 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(2);
306 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
307 expect(remoteInvoices(server)[0].grandTotal).toBe(original.grandTotal);
308 const status=await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),invoiceId);
309 expect(status).toBe('reversed');
310 const bad=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
311 expect(bad).not.toBe('unexpected');
312 // A separate never-posted invoice may be deleted; posted history stays intact.
313 await fillInvoice(page,'PILOT-DELETE-DRAFT-001',1);await page.evaluate(()=>commitSaveInvoice());
314 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
315 const draft=remoteInvoices(server).find(x=>x.number==='PILOT-DELETE-DRAFT-001');
316 expect(draft).toBeTruthy();
317 await page.evaluate(id=>deleteInvoicePilotDraft(id),draft.id);
318 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
319 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
320 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(2);
321 });
322
323 function remotePurchases(server){return [...server.records.values()].filter(x=>x.collection==='purchases').map(x=>copy(x.data));}
324 async function createPostedPurchase(page,server,number='PILOT-PUR-001',qty=2){
325 const id=await page.evaluate(({number,qty})=>{
326 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};
327 datastore.purchases.push(p);jePostSourceRecord('purchase',p);return p.id;
328 },{number,qty});
329 await expect.poll(()=>remotePurchases(server).find(x=>x.id===id)?.journalVoucherId,{timeout:13000}).toBeTruthy();
330 return id;
331 }
332 test('pilot purchase: posted to corrective draft to edited balanced repost via document manager',async({page})=>{
333 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
334 const originalId=await createPostedPurchase(page,server);
335 const first=remotePurchases(server).find(x=>x.id===originalId);
336 expect(first.accountingStatus).toBe('posted');
337 const voucher=first.journalVoucherId;
338 const untouched=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy);
339 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(2);
340 await page.evaluate(()=>{
341 window.confirm=()=>true;window.prompt=()=> 'اصلاح مقدار خرید';
342 navigateShell('accounting','view-journal','documents');
343 });
344 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PILOT-PUR-001');
345 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]')).toHaveCount(1);
346 // Technical correction primitive remains available for pre-existing in-progress
347 // drafts; the new employee UI correctly DOES NOT write on open.
348 await page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]').click();
349 expect(remotePurchases(server)).toHaveLength(1);
350 await page.evaluate(()=>purCancelEdit());
351 await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی'),originalId);
352 await expect.poll(()=>remotePurchases(server).length,{timeout:14000}).toBe(2);
353 const corrected=remotePurchases(server).find(x=>x.correctsPurchaseId===originalId);
354 expect(corrected.documentStatus).toBe('draft');
355 expect(corrected.journalVoucherId).toBeUndefined();
356 expect(corrected.number).not.toBe(first.number);
357 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
358 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),originalId)).toBe('reversed');
359 // Internal API fixture made a technical draft without clicking the employee form.
360 await page.evaluate(id=>purEdit(id),corrected.id);
361 await expect(page.locator('#pur-edit-id')).toHaveValue(corrected.id);
362 await page.locator('#pur-items-body .pur-qty').first().fill('3');
363 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
364 await page.locator('#pur-save-btn').click();
365 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.grandTotal,{timeout:14000}).toBe(300);
366 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
367 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
368 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]')).toHaveCount(1);
369 await page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]').click();
370 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.accountingStatus,{timeout:14000}).toBe('posted');
371 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
372 const journal=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
373 expect(journal).toHaveLength(3);
374 expect(journal.find(x=>x.id===voucher).data.status).toBe('reversed');
375 expect(untouched).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy));
376 for(const v of journal){
377 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
378 expect(lines.reduce((s,l)=>s+Number(l.data.debit||0),0)).toBe(lines.reduce((s,l)=>s+Number(l.data.credit||0),0));
379 }
380 const retry=await page.evaluate(async id=>{try{await returnPostedPurchaseAsDraft(id,'تکرار');return 'unsafe'}catch(e){return String(e.message)}},originalId);
381 expect(retry).not.toBe('unsafe');
382 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
383 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
384 });
385
386 test('pilot purchase denies paid/consumed source; cancels unallocated posting without erasing old voucher',async({page})=>{
387 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
388 const purchaseId=await createPostedPurchase(page,server,'PILOT-PUR-GUARDS');
389 // A payment allocation blocks both corrective reopen and cancellation.
390 const blockedPayment=await page.evaluate(async id=>{
391 datastore.payments.push({id:'QA-SETTLE',ownerUserId:currentUser.id,companyId:'QA_CO',direction:'outbound',invoiceType:'purchase',invoiceId:id,amount:10});
392 try{await cancelPostedPurchasePilot(id,'ابطال');return 'unsafe'}catch(e){return String(e.message)}
393 },purchaseId);
394 expect(blockedPayment).toMatch(/پرداخت/);
395 await page.evaluate(()=>{datastore.payments=datastore.payments.filter(x=>x.id!=='QA-SETTLE');});
396 // Consumption means stock would become negative after purchase reversal.
397 const blockedStock=await page.evaluate(async id=>{
398 const sale={id:'QA-USE',ownerUserId:currentUser.id,companyId:'QA_CO',kind:'formal',documentStatus:'posted',items:[{prodId:'QA_PROD',qty:2}],grandTotal:200};
399 datastore.invoices.push(sale);
400 try{await returnPostedPurchaseAsDraft(id,'اصلاح');return 'unsafe'}catch(e){return String(e.message)}
401 },purchaseId);
402 expect(blockedStock).toMatch(/موجودی/);
403 await page.evaluate(()=>{datastore.invoices=datastore.invoices.filter(x=>x.id!=='QA-USE');});
404 await page.evaluate(id=>cancelPostedPurchasePilot(id,'ابطال خرید آزمایشی'),purchaseId);
405 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:14000}).toBe(2);
406 expect(remotePurchases(server)).toHaveLength(1);
407 const original=remotePurchases(server)[0];
408 expect(original.id).toBe(purchaseId);
409 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),purchaseId)).toBe('reversed');
410 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
411 expect(await page.evaluate(id=>{try{deletePurchasePilotDraft(id);return 'unsafe'}catch(e){return String(e.message)}},purchaseId)).not.toBe('unsafe');
412 });
413 test('seamless sale correction: opening and cancelling leaves ledger unchanged; saving retains visible identity, printing and audit',async({page})=>{
414 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
415 await fillInvoice(page,'SAME-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
416 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
417 const id=remoteInvoices(server)[0].id;await page.evaluate(x=>finalizeInvoiceDocument(x),id);
418 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
419 const original=copy(remoteInvoices(server)[0]),initialLines=[...server.records.values()].filter(x=>x.collection==='journalLines').map(copy);
420 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
421 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
422 await page.locator('#finora-document-management-body [data-doc-action="reopen"]').click();
423 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
424 await expect(page.locator('#invoice-number')).toHaveValue('SAME-SALE-001');
425 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
426 await page.evaluate(()=>cancelInvoiceEdit());
427 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
428 expect(remoteInvoices(server)).toHaveLength(1);
429 await page.evaluate(x=>beginInvoiceAmendment(x),id);
430 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
431 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
432 await page.evaluate(()=>commitSaveInvoice());
433 await expect.poll(()=>remoteInvoices(server).filter(x=>x.correctsInvoiceId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
434 expect(remoteInvoices(server)).toHaveLength(2);expect(remoteInvoices(server).find(x=>x.id===id)).toEqual(original);
435 const current=remoteInvoices(server).find(x=>x.correctsInvoiceId===id);
436 expect(current.grandTotal).toBe(4500);
437 expect(current.number).not.toBe(original.number);
438 const visible=await page.evaluate(()=>invoiceVisibleRecords().map(x=>({id:x.id,number:invoiceVisibleNumber(x)})));
439 expect(visible).toEqual([{id:current.id,number:'SAME-SALE-001'}]);
440 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
441 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
442 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
443 await expect(page.locator('#finora-document-management-body')).not.toContainText('-اصلاح');
444 await page.evaluate(x=>renderAndPrintDirect(x),id);
445 await expect(page.locator('#printable-invoice')).toContainText('SAME-SALE-۰۰۱');
446 await expect(page.locator('#printable-invoice')).toContainText('۴٬۵۰۰');
447 await expect(page.locator('#printable-invoice')).not.toContainText('-اصلاح');
448 expect(initialLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy));
449 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
450 expect(vouchers).toHaveLength(3);expect(vouchers.find(v=>v.id===original.journalVoucherId).data.status).toBe('reversed');
451 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
452 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
453 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
454 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
455 });
456
457 test('seamless purchase correction: same visible number, no write on opening, save and print corrected purchase',async({page})=>{
458 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
459 const id=await createPostedPurchase(page,server,'SAME-PURCHASE-001',2);
460 const initial=copy(remotePurchases(server).find(x=>x.id===id));const before=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
461 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
462 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
463 await page.locator('#finora-purchase-document-management-body [data-doc-action="reopen"]').click();
464 await expect(page.locator('#pur-edit-id')).toHaveValue(id);
465 await expect(page.locator('#pur-number')).toHaveValue('SAME-PURCHASE-001');
466 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(before.length);
467 await page.evaluate(()=>purCancelEdit());
468 expect(remotePurchases(server)).toHaveLength(1);
469 await page.evaluate(x=>beginPurchaseAmendment(x),id);
470 await page.locator('#pur-items-body .pur-qty').first().fill('3');
471 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
472 await page.locator('#pur-save-btn').click();
473 await expect.poll(()=>remotePurchases(server).filter(x=>x.correctsPurchaseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
474 expect(remotePurchases(server).find(x=>x.id===id)).toEqual(initial);
475 const current=remotePurchases(server).find(x=>x.correctsPurchaseId===id);
476 expect(current.grandTotal).toBe(300);expect(current.number).not.toBe(initial.number);
477 const visible=await page.evaluate(()=>purchaseVisibleRecords().map(x=>({id:x.id,number:purchaseVisibleNumber(x)})));
478 expect(visible).toEqual([{id:current.id,number:'SAME-PURCHASE-001'}]);
479 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
480 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
481 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
482 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('-اصلاح');
483 await page.evaluate(x=>purPrint(x),id);
484 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
485 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
486 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
487 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
488 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
489 });
490 function remotePayments(server){return [...server.records.values()].filter(x=>x.collection==='payments').map(x=>copy(x.data));}
491 async function createUiPayment(page,server,amount=1000,direction='inbound'){
492 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
493 await page.locator('#pay-direction').selectOption(direction);
494 await page.locator('#pay-contact').selectOption('QA_CONTACT');
495 await page.locator('#pay-method').selectOption('bank');
496 await page.locator('#pay-amount').fill(String(amount));
497 await page.locator('#pay-reference').fill('REF-ORIGINAL-001');
498 await page.evaluate(()=>commitSavePayment());
499 await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
500 await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
501 return remotePayments(server)[0].id;
502 }
503
504 test('treasury amendment in the same form preserves one record and same reference without on-open ledger writes',async({page})=>{
505 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
506 const firstId=await createUiPayment(page,server);
507 await page.waitForFunction(()=>!syncPending&&!syncRunning);
508 const first=copy(remotePayments(server)[0]);
509 const oldLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy);
510 const beforeRpc=server.rpcCount;
511 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
512 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
513 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
514 await page.locator('#finora-treasury-document-management-body [data-doc-action="edit"]').click();
515 await expect(page.locator('#pay-amount')).toHaveValue('1000');
516 await expect(page.locator('#pay-reference')).toHaveValue('REF-ORIGINAL-001');
517 await page.evaluate(()=>resetPaymentForm());
518 expect(server.rpcCount).toBe(beforeRpc);
519 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
520 expect(remotePayments(server)).toHaveLength(1);
521 await page.locator('#payments-ledger button').first().click();
522 await page.locator('#pay-amount').fill('1250');
523 await page.locator('#pay-note').fill('اصلاح مبلغ');
524 const beforeCorrectionRpc=server.rpcCount;
525 await page.locator('#pay-save').click();
526 await expect.poll(()=>remotePayments(server).filter(x=>x.correctsPaymentId===firstId&&x.accountingStatus==='posted').length,{timeout:18000}).toBe(1);
527 await page.waitForFunction(()=>!syncPending&&!syncRunning);
528 // Reversal + new source + repost must be a single server-side sync_records batch.
529 expect(server.rpcCount-beforeCorrectionRpc).toBe(1);
530 const original=remotePayments(server).find(p=>p.id===firstId);
531 expect(original).toEqual(first);
532 const amended=remotePayments(server).find(p=>p.correctsPaymentId===firstId);
533 expect(amended.amount).toBe(1250);
534 expect(amended.reference).toBe(first.reference);
535 expect(amended.journalVoucherId).toBeTruthy();
536 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
537 expect(vouchers).toHaveLength(3);
538 expect(vouchers.find(x=>x.id===first.journalVoucherId).data.status).toBe('reversed');
539 expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy));
540 for(const v of vouchers){
541 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
542 expect(lines.reduce((n,x)=>n+Number(x.data.debit||0),0)).toBe(lines.reduce((n,x)=>n+Number(x.data.credit||0),0));
543 }
544 expect(await page.evaluate(()=>paymentVisibleRecords().map(x=>x.id))).toEqual([amended.id]);
545 expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
546 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
547 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
548 await expect(page.locator('#finora-treasury-document-management-body')).toContainText('REF-ORIGINAL-001');
549 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
550 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
551 await expect(page.locator('#payments-ledger')).toContainText('۱٬۲۵۰');
552 await expect(page.locator('#payments-ledger')).toContainText('REF-ORIGINAL-001');
553 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
554 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
555 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
556 expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
557 });
558
559 test('treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history',async({page})=>{
560 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
561 const id=await createUiPayment(page,server,450,'outbound');
562 const noCheck=await page.evaluate(async id=>{
563 const p=getMyPayments().find(x=>x.id===id);
564 const saved=p.method;p.method='cheque';
565 try{await paymentAmendPosted(id,{direction:p.direction,contactId:p.contactId,companyId:p.companyId,
566 amount:400,method:'cash',invoiceId:'',invoiceType:'',reference:'x',note:'x'});return 'unsafe';}
567 catch(e){return String(e.message)}
568 finally{p.method=saved}
569 },id);
570 expect(noCheck).toMatch(/چک|تطبیق/);
571 const linked=await page.evaluate(async id=>{
572 const p=getMyPayments().find(x=>x.id===id);
573 p.invoiceType='purchase';p.invoiceId='QA_LINKED';
574 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
575 catch(e){return String(e.message)}
576 finally{p.invoiceType='';p.invoiceId=''}
577 },id);
578 expect(linked).toMatch(/تسویه|فاکتور|تطبیق/);
579 const locked=await page.evaluate(async id=>{
580 const fy=getMyFiscalYears()[0],old=fy.status;
581 fy.status='locked';
582 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
583 catch(e){return String(e.message)}
584 finally{fy.status=old}
585 },id);
586 expect(locked).toMatch(/قفل|سال مالی/);
587 await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال اشتباه آزمایشی';});
588 await page.evaluate(id=>deletePayment(id),id);
589 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(2);
590 expect(remotePayments(server)).toHaveLength(1);
591 expect(remotePayments(server)[0].id).toBe(id);
592 expect(await page.evaluate(id=>paymentPostingStatus(getMyPayments().find(x=>x.id===id)),id)).toBe('reversed');
593 expect(await page.evaluate(()=>paymentEffectiveRecords().length)).toBe(0);
594 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
595 await expect(page.locator('#payments-ledger')).toContainText('ابطال‌شده');
596 });
597
598 test('treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload',async({page})=>{
599 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
600 const id=await createUiPayment(page,server);
601 await page.waitForFunction(()=>!syncPending&&!syncRunning);
602 const before=copy(remotePayments(server)[0]);
603 const vouchersBefore=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id);
604 server.failNext=true;
605 await page.evaluate(id=>editPayment(id),id);
606 await page.locator('#pay-amount').fill('1800');
607 await page.locator('#pay-save').click();
608 await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('اصلاح کامل نشد'))),{timeout:8000}).toBe(true);
609 expect(server.failCount).toBe(1);
610 // The RPC did not persist any subset of the combined financial diff.
611 expect(remotePayments(server)).toEqual([before]);
612 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(vouchersBefore);
613 // After uncertain acknowledgment, do not call the amend API again blindly.
614 });
615 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
616 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
617 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());
618 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
619 const id=remoteInvoices(server)[0].id;
620 const result=await page.evaluate(async x=>{try{await finalizeInvoiceDocument(x);return 'unexpected success'}catch(e){return String(e.message)}},id);
621 expect(result).toMatch(/حساب|کدینگ/);
622 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
623 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
624 });
625
626
627 test('F2 validates formal invoice then saves a draft without posting any financial journal',async({page})=>{
628 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
629 await page.keyboard.press('F2');
630 expect(remoteInvoices(server)).toHaveLength(0);
631 expect(await page.evaluate(()=>window.__f0Alerts.at(-1))).toMatch(/حداقل یک کالا|خدمت معتبر/);
632 await fillInvoice(page,'F2-SAFE-DRAFT-001',2);
633 await page.keyboard.press('F2');
634 await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1);
635 const saved=remoteInvoices(server)[0];
636 expect(saved.number).toBe('F2-SAFE-DRAFT-001');
637 expect(saved.accountingStatus).toBe('draft');
638 expect(saved.documentStatus).toBe('draft');
639 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
640 await page.keyboard.press('F2');
641 expect(remoteInvoices(server)).toHaveLength(1);
642 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
643 });