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

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

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

Synced Dec 4, 01:45 UTC

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