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

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

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

Synced Dec 4, 11:45 UTC

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