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

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

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

Synced Dec 4, 06:45 UTC

qa/finora-issue223-manual-kardex-browser-red-20261123
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 1,875 lines 124 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 const {isDeepStrictEqual}=require('node:util');
7 // Do not allow an unexpected third product state to masquerade as expected P0 RED.
8 function assertKnownRedOrFixed(observed,knownBroken,required,label){
9 if(isDeepStrictEqual(observed,knownBroken)||isDeepStrictEqual(observed,required))return;
10 throw new Error('FINORA_ISSUE229_UNEXPECTED_PRODUCT_STATE '+label+' (not the known P0 RED): '+
11 JSON.stringify({observed,knownBroken,required}));
12 }
13 test('P0 #229 sentinel rejects unexpected financial states before expected-RED markers',()=>{
14 const broken={status:'posted',count:1,voucherStates:['posted']};
15 const fixed={status:'draft',count:0,voucherStates:['draft']};
16 expect(()=>assertKnownRedOrFixed(broken,broken,fixed,'fixture')).not.toThrow();
17 expect(()=>assertKnownRedOrFixed(fixed,broken,fixed,'fixture')).not.toThrow();
18 expect(()=>assertKnownRedOrFixed({status:'partial',count:2,voucherStates:['posted']},
19 broken,fixed,'fixture')).toThrow(/FINORA_ISSUE229_UNEXPECTED_PRODUCT_STATE/);
20 expect(()=>assertKnownRedOrFixed({status:'posted',count:1,voucherStates:['posted','orphan']},
21 broken,fixed,'fixture')).toThrow(/FINORA_ISSUE229_UNEXPECTED_PRODUCT_STATE/);
22 });
23 function fakeServer(){
24 const records=new Map();
25 for(const [collection,id,data] of [
26 ['companies','QA_CO',{name:'شرکت آزمون ایزوله',entityType:'legal'}],
27 ['contacts','QA_CONTACT',{name:'خریدار آزمایشی',role:'both'}],
28 ['products','QA_PROD',{name:'بلوک سیمانی',code:'BLK-001',unit:'عدد',sale_price:1500}],
29 ['settings','main',{invoice_kind:'formal',vat_mode:'none',vat_rate:10,default_company_id:'QA_CO',currency_mode:'rial'}],
30 ['fiscalYears','FY_QA',{name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}],
31 ['accounts','A_CASH',{code:'1101',title:'صندوق',systemRole:'cash_default',postingAllowed:true,active:true}],
32 ['accounts','A_AR',{code:'1102',title:'دریافتنی',systemRole:'receivable_control',postingAllowed:true,active:true}],
33 ['accounts','A_REV',{code:'4101',title:'درآمد فروش',systemRole:'revenue_default',postingAllowed:true,active:true}],
34 ['accounts','A_VAT',{code:'2102',title:'مالیات',systemRole:'vat_payable',postingAllowed:true,active:true}],
35 ['accounts','A_BUY',{code:'5101',title:'خرید',systemRole:'purchase_default',postingAllowed:true,active:true}],
36 ['accounts','A_AP',{code:'2101',title:'پرداختنی',systemRole:'payable_control',postingAllowed:true,active:true}],
37 ])records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
38 return {records,failNext:false,failCount:0,rpcCount:0,reversalStatuses:[],reverseCount:0};
39 }
40 function remoteInvoices(server){return [...server.records.values()].filter(r=>r.collection==='invoices').map(r=>copy(r.data));}
41
42 test.beforeEach(async({page})=>{
43 page.on('console',message=>{
44 if(message.type()==='error'||message.text().includes('sync error'))
45 console.log('FINORA_F0_BROWSER_CONSOLE',message.type(),message.text());
46 });
47 page.on('pageerror',error=>console.log('FINORA_F0_PAGE_ERROR',error.message));
48 });
49 test.afterEach(async({page},testInfo)=>{
50 if(testInfo.status===testInfo.expectedStatus)return;
51 try{
52 const state=await page.evaluate(()=>({
53 syncPending:typeof syncPending==='undefined'?null:syncPending,
54 syncRunning:typeof syncRunning==='undefined'?null:syncRunning,
55 syncFailCount:typeof syncFailCount==='undefined'?null:syncFailCount,
56 currentOrg:typeof currentUser==='undefined'?null:currentUser?.organizationId,
57 pendingDiff:typeof computeDiff==='function'?(()=>{const d=computeDiff();return {up:d.up.map(x=>x.key),del:d.del};})():null,
58 alerts:window.__f0Alerts||[]
59 }));
60 console.log('FINORA_F0_FAILURE_DIAGNOSTICS',JSON.stringify(state));
61 }catch(err){console.log('FINORA_F0_DIAGNOSTICS_UNAVAILABLE',String(err));}
62 });
63 async function installHarness(page,server){
64 await page.exposeFunction('qaF0Read',async()=>[...server.records.values()].map(row=>({...copy(row),version:Number(row.version)||1})));
65 await page.exposeFunction('qaF0Write',async args=>{
66 server.rpcCount++;
67 if(server.rpcCount<=3)console.log('FINORA_F0_RPC_TRACE',JSON.stringify({org:args.p_organization_id,upserts:(args.p_upserts||[]).map(x=>x.collection+'|'+x.id),deletes:(args.p_deletes||[]).map(x=>x.collection+'|'+x.id)}));
68 if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'Network unavailable — isolated QA failure',code:'QA_NETWORK'}};}
69 if(args.p_organization_id!=='QA_ORG')return {error:{message:'Unexpected organization scope',code:'QA_ORG_SCOPE'}};
70 const upserts=[];
71 for(const row of args.p_upserts||[]){
72 const key=row.collection+'|'+row.id,current=server.records.get(key);
73 const currentVersion=current?(Number(current.version)||1):0;
74 const parentVoucherId=row.collection==='journalLines'?(row.data?.voucherId||current?.data?.voucherId):null;
75 const parentVoucher=parentVoucherId?server.records.get('journalVouchers|'+parentVoucherId):null;
76 if(row.collection==='journalVouchers'&&current&&current.data.status==='posted'&&['sale','purchase'].includes(current.data.sourceType))
77 return {error:{message:'FINORA_POSTED_SOURCE_VOUCHER_IMMUTABLE',code:'23514'}};
78 if(row.collection==='journalLines'&&parentVoucher&&parentVoucher.data.status==='posted'&&['sale','purchase'].includes(parentVoucher.data.sourceType))
79 return {error:{message:'FINORA_POSTED_SOURCE_VOUCHER_IMMUTABLE',code:'23514'}};
80 if(Number(row.expected_version||0)!==currentVersion){console.log('FINORA_F0_VERSION_CONFLICT',JSON.stringify({key,expected:row.expected_version,actual:currentVersion,rpcCount:server.rpcCount,upsertKeys:Object.keys(row),rpcKeys:Object.keys(args),rawExpectedVersion:row.expectedVersion}));return {error:{message:'FINORA_VERSION_CONFLICT',code:'40001'}};}
81 const version=currentVersion+1;
82 server.records.set(key,{collection:row.collection,id:row.id,data:copy(row.data),version});
83 upserts.push({collection:row.collection,id:row.id,version});
84 }
85 const deletes=[];
86 for(const row of args.p_deletes||[]){
87 const key=row.collection+'|'+row.id,current=server.records.get(key);
88 const currentVersion=current?(Number(current.version)||1):0;
89 const parentVoucherId=row.collection==='journalLines'?current?.data?.voucherId:null;
90 const parentVoucher=parentVoucherId?server.records.get('journalVouchers|'+parentVoucherId):null;
91 if((row.collection==='journalVouchers'&&current?.data?.status==='posted'&&['sale','purchase'].includes(current.data.sourceType))||
92 (row.collection==='journalLines'&&parentVoucher?.data?.status==='posted'&&['sale','purchase'].includes(parentVoucher.data.sourceType)))
93 return {error:{message:'FINORA_POSTED_SOURCE_VOUCHER_IMMUTABLE',code:'23514'}};
94 if(!current||Number(row.expected_version)!==currentVersion)return {error:{message:'FINORA_VERSION_CONFLICT',code:'40001'}};
95 server.records.delete(key);deletes.push({collection:row.collection,id:row.id});
96 }
97 return {data:{upserts,deletes},error:null};
98 });
99 await page.exposeFunction('qaF0Reverse',async args=>{
100 server.reverseCount=(server.reverseCount||0)+1;
101 if(args.p_organization_id!=='QA_ORG')return {data:null,error:{message:'FINORA_ORG_FORBIDDEN',code:'42501'}};
102 if(args.p_allocations!==null)return {data:null,error:{message:'FINORA_REVERSAL_ALLOCATION_INVALID',code:'23514'}};
103 if(String(args.p_reason||'').trim().length<4)return {data:null,error:{message:'FINORA_REVERSAL_REASON_REQUIRED',code:'23514'}};
104 const original=server.records.get('journalVouchers|'+args.p_original_id);
105 if(!original||original.data.status!=='posted')return {data:null,error:{message:'FINORA_REVERSAL_SOURCE_NOT_POSTED',code:'23514'}};
106 if(Number(original.version)!==Number(args.p_expected_version))return {data:null,error:{message:'FINORA_VERSION_CONFLICT',code:'40001'}};
107 const fiscalYear=server.records.get('fiscalYears|'+original.data.fiscalYearId);
108 if(!fiscalYear||fiscalYear.data.status==='locked'||args.p_date<fiscalYear.data.startDate||args.p_date>fiscalYear.data.endDate)
109 return {data:null,error:{message:'FINORA_REVERSAL_FISCAL_DATE_INVALID',code:'23514'}};
110 if((server.reversalStatuses||[]).some(x=>x.voucher_id===args.p_original_id))return {data:null,error:{message:'FINORA_VOUCHER_ALREADY_REVERSED',code:'23514'}};
111 const originalLines=[...server.records.values()].filter(row=>row.collection==='journalLines'&&row.data.voucherId===args.p_original_id);
112 if(!originalLines.length)return {data:null,error:{message:'FINORA_REVERSAL_LINES_MISSING',code:'23514'}};
113 const reversalId=args.p_reversal_id,now=new Date().toISOString();
114 const reversal={companyId:original.data.companyId,fiscalYearId:original.data.fiscalYearId,date:args.p_date,
115 description:'برگشت سند '+(original.data.number||args.p_original_id),reference:original.data.reference||'',
116 voucherType:'reversal',sourceType:'reversal',sourceId:args.p_original_id,reversesVoucherId:args.p_original_id,
117 reversalReason:String(args.p_reason).trim(),reversalAllocations:null,
118 number:String([...server.records.values()].filter(row=>row.collection==='journalVouchers').length+1),
119 status:'posted',postedAt:now,postedBy:'FINORA_F0_FIXTURE_ONLY'};
120 server.records.set('journalVouchers|'+reversalId,{collection:'journalVouchers',id:reversalId,data:copy(reversal),version:1});
121 const reversalLines=originalLines.map((row,index)=>{
122 const lineId=reversalId+'_L'+(index+1),data={voucherId:reversalId,companyId:original.data.companyId,
123 fiscalYearId:original.data.fiscalYearId,accountId:row.data.accountId,
124 debit:Number(row.data.credit||0),credit:Number(row.data.debit||0),
125 description:'برگشت: '+String(row.data.description||''),reversesLineId:row.id};
126 server.records.set('journalLines|'+lineId,{collection:'journalLines',id:lineId,data,version:1});
127 return {...copy(data),id:lineId};
128 });
129 server.reversalStatuses=(server.reversalStatuses||[]).filter(x=>x.voucher_id!==args.p_original_id)
130 .concat([{organization_id:'QA_ORG',voucher_id:args.p_original_id,effective_status:'reversed'}]);
131 if(server.failReverseAfterCommit){server.failReverseAfterCommit=false;return {data:null,error:{message:'QA_NETWORK_AFTER_COMMIT',code:'QA_NETWORK'}};}
132 return {data:{voucher:{...copy(reversal),id:reversalId,version:1},originalVoucherId:args.p_original_id,
133 reversalLineIds:reversalLines.map(x=>x.id),replayed:false},error:null};
134 });
135 await page.exposeFunction('qaF0ReversalStatuses',async()=>copy(server.reversalStatuses||[]));
136 await page.exposeFunction('qaF0AutoPost',async args=>{
137 server.autoPostCount=(server.autoPostCount||0)+1;
138 if(args.p_organization_id!=='QA_ORG')return {data:null,error:{message:'FINORA_ORG_FORBIDDEN',code:'42501'}};
139 const sourceKey=args.p_source_collection+'|'+args.p_source_id;
140 const sourceRow=server.records.get(sourceKey);
141 if(!sourceRow)return {data:null,error:{message:'FINORA_SOURCE_NOT_COMMITTED_IN_ORG',code:'23503'}};
142 const kind=args.p_header.sourceType;
143 if(!['cash','credit'].includes(sourceRow.data.paymentMethod))return {data:null,error:{message:'FINORA_SOURCE_METHOD_OR_CURRENCY_UNSUPPORTED',code:'23514'}};
144 const digitMap={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9','٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9'};
145 const normalizeDate=value=>String(value||'').replace(/[۰-۹٠-٩]/g,digit=>digitMap[digit]||digit);
146 if(args.p_header.voucherType!==kind||normalizeDate(args.p_header.date)!==normalizeDate(sourceRow.data.date))return {data:null,error:{message:'FINORA_SOURCE_HEADER_MISMATCH',code:'23514'}};
147 const prior=[...server.records.values()].find(row=>row.collection==='journalVouchers'&&row.data.sourceType===kind&&row.data.sourceId===args.p_source_id&&['posted','reversed'].includes(row.data.status));
148 if(prior)return {data:{voucher:{...copy(prior.data),id:prior.id,version:Number(prior.version)||1},replayed:true},error:null};
149 const amount=Number(sourceRow.data.grandTotal||0);
150 if(!Number.isSafeInteger(amount)||amount<=0)return {data:null,error:{message:'FINORA_INVALID_RIAL_AMOUNT',code:'23514'}};
151 const debitAccount=kind==='sale'?(sourceRow.data.paymentMethod==='credit'?'A_AR':'A_CASH'):'A_BUY';
152 const creditAccount=kind==='sale'?'A_REV':(sourceRow.data.paymentMethod==='credit'?'A_AP':'A_CASH');
153 for(const accountId of [debitAccount,creditAccount]){
154 const account=server.records.get('accounts|'+accountId);
155 if(!account||account.data.active===false||account.data.postingAllowed!==true)
156 return {data:null,error:{message:'حساب موردنیاز در کدینگ فعال و قابل ثبت نیست: '+accountId,code:'23514'}};
157 }
158 const now=new Date().toISOString(),voucherId=args.p_voucher_id;
159 const voucherNumber=String([...server.records.values()].filter(row=>row.collection==='journalVouchers'&&row.data.companyId===args.p_header.companyId&&row.data.fiscalYearId===args.p_header.fiscalYearId).length+1);
160 const voucher={companyId:args.p_header.companyId,fiscalYearId:args.p_header.fiscalYearId,date:args.p_header.date,
161 description:args.p_header.description,reference:args.p_header.reference,voucherType:args.p_header.voucherType,
162 sourceType:kind,sourceId:args.p_source_id,sourceVersion:String(args.p_header.sourceVersion),
163 number:voucherNumber,status:'posted',postedAt:now,postedBy:'FINORA_F0_FIXTURE_ONLY'};
164 const updatedSource={...copy(sourceRow.data),journalVoucherId:voucherId,accountingStatus:'posted',
165 accountingPostedAt:now,documentStatus:'posted',documentPostedAt:now,
166 documentPostedBy:'FINORA_F0_FIXTURE_ONLY',documentVersion:Number(sourceRow.data.documentVersion||1),updatedAt:now};
167 server.records.set(sourceKey,{collection:args.p_source_collection,id:args.p_source_id,data:updatedSource,version:(Number(sourceRow.version)||1)+1});
168 server.records.set('journalVouchers|'+voucherId,{collection:'journalVouchers',id:voucherId,data:voucher,version:1});
169 const lines=[
170 {id:voucherId+'_L1',data:{voucherId,companyId:args.p_header.companyId,fiscalYearId:args.p_header.fiscalYearId,accountId:debitAccount,debit:amount,credit:0}},
171 {id:voucherId+'_L2',data:{voucherId,companyId:args.p_header.companyId,fiscalYearId:args.p_header.fiscalYearId,accountId:creditAccount,debit:0,credit:amount}}
172 ];
173 for(const line of lines)server.records.set('journalLines|'+line.id,{collection:'journalLines',id:line.id,data:line.data,version:1});
174 return {data:{voucher:{...copy(voucher),id:voucherId,version:1},computedLines:lines.map(line=>({...copy(line.data),id:line.id})),contractVersion:1,draftReplayed:false},error:null};
175 });
176 await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
177 }
178 async function authenticatedMockBrowser(page){
179 await page.goto(BASE,{waitUntil:'domcontentloaded'});
180 // Await the two explicit core login barriers; extension registration alone does not settle either promise.
181 // The synthetic account must not race the organization entitlement wrapper.
182 // Function availability precedes completion of asynchronously loaded ERP modules.
183 await page.waitForFunction(()=>typeof enterApp==='function'&&typeof commitSaveInvoice==='function'&&
184 typeof pullAll==='function'&&window.FinoraStartupStatus?.extensionsReady===true&&
185 window.FinoraStartupStatus?.failedExtensionCount===0&&
186 window.FinoraStartupStatus?.authChecked===true,{timeout:20000});
187 await page.evaluate(()=>Promise.all([window.FinoraAppAssetsReady,window.FinoraOrganizationContextReady]));
188 await page.evaluate(async()=>{
189 window.__FINORA_PRINT_TEST_MODE=true;
190 window.__f0Alerts=[];
191 window.alert=m=>window.__f0Alerts.push(String(m));
192 window.confirm=()=>false;
193 fetchCurrentUser=async()=>({id:'FINORA_F0_FIXTURE_ONLY',organizationId:'QA_ORG',username:'qa-only',email:'qa@example.invalid',fullName:'QA F0',role:'admin',maxCompanies:2,subscription:{type:'lifetime',status:'active',endDate:'2099-12-31'}});
194 maybeMigrateLegacyData=()=>{};
195 sb.from=collection=>{
196 if(collection==='finora_journal_reversal_status')return {select:()=>({eq:async()=>({data:await window.qaF0ReversalStatuses(),error:null})})};
197 return {select:()=>({
198 eq(){return this;},
199 order(){return this;},
200 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};}
201 })};
202 };
203 window.requireFreshFinoraMembership=async()=>true;
204 sb.rpc=async(name,args)=>{
205 // Both deployed sync RPC entrypoints share the same transactional mock contract.
206 if(name==='finora_sync_records_v2'||name==='finora_sync_records'){if((args?.p_upserts||[]).some(row=>!Object.prototype.hasOwnProperty.call(row,'expected_version')))console.error('FINORA_F0_MISSING_VERSION_RPC_CALLSITE',JSON.stringify({name,firstUpsert:(args?.p_upserts||[])[0],stack:new Error('sync RPC callsite').stack}));return await window.qaF0Write(args);}
207 if(name==='finora_journal_autopost')return await window.qaF0AutoPost(args);
208 if(name==='finora_journal_reverse')return await window.qaF0Reverse(args);
209 throw Error('Unexpected RPC '+name);
210 };
211 await enterApp({id:'FINORA_F0_FIXTURE_ONLY'});
212 const authState={display:getComputedStyle(document.getElementById('auth-screen')).display,status:document.getElementById('auth-login-status')?.textContent||'',userId:currentUser?.id||null,startup:window.FinoraStartupStatus};
213 if(authState.display!=='none')throw new Error('QA_ENTER_APP_FAILED '+JSON.stringify(authState));
214 document.querySelectorAll('.modal-backdrop.active').forEach(x=>x.classList.remove('active'));
215 switchView('view-invoices');
216 });
217 await expect(page.locator('#auth-screen')).toBeHidden();
218 await expect(page.locator('#invoice-company-id option[value="QA_CO"]')).toHaveCount(1);
219 await expect(page.locator('#invoice-items-table-body .row-product-select').first().locator('option[value="QA_PROD"]')).toHaveCount(1);
220 }
221 async function fillInvoice(page,number,qty){
222 // The native invoice-kind/contact selectors are hidden by the unified commercial combobox.
223 // Drive their real DOM change handlers, not Playwright visibility on replaced native selects.
224 await page.evaluate(()=>{
225 for(const [id,value] of [['invoice-kind','formal'],['invoice-company-id','QA_CO'],['invoice-contact-id','QA_CONTACT']]){
226 const el=document.getElementById(id);el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
227 }
228 });
229 await page.locator('#invoice-number').fill(number);
230 await page.locator('#invoice-date-input').fill('۱۴۰۵/۰۷/۱۹');
231 await page.evaluate(()=>{
232 const el=document.querySelector('#invoice-items-table-body .row-product-select');
233 el.value='QA_PROD';el.dispatchEvent(new Event('change',{bubbles:true}));
234 });
235 await page.locator('#invoice-items-table-body .row-quantity').first().fill(String(qty));
236 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
237 }
238
239 test('invoice and purchase registers isolate companies selected in Settings; no ALL fallback or cross-company edit',async({page})=>{
240 const server=fakeServer();
241 const sale=(id,companyId,number)=>({companyId,kind:'non_formal',kindLabel:'غیررسمی',number,date:'1405/07/19',
242 contactId:'QA_CONTACT',contactName:'طرف حساب آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:1500}],grandTotal:1500,
243 documentStatus:'draft',accountingStatus:'draft'});
244 const purchase=(id,companyId,number)=>({companyId,number,date:'1405/07/19',supplierId:'QA_CONTACT',
245 supplierName:'تأمین‌کننده آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:100}],grandTotal:100,accountingStatus:'draft'});
246 server.records.set('companies|QA_CO_B',{collection:'companies',id:'QA_CO_B',data:{name:'شرکت دوم آزمون'}});
247 for(const [collection,id,data] of [
248 ['invoices','INV_SCOPE_A',sale('INV_SCOPE_A','QA_CO','INV-COMPANY-A')],
249 ['invoices','INV_SCOPE_B',sale('INV_SCOPE_B','QA_CO_B','INV-COMPANY-B')],
250 ['invoices','INV_LEGACY_UNSCOPED',sale('INV_LEGACY_UNSCOPED','', 'INV-LEGACY')],
251 ['purchases','PUR_SCOPE_A',purchase('PUR_SCOPE_A','QA_CO','PUR-COMPANY-A')],
252 ['purchases','PUR_SCOPE_B',purchase('PUR_SCOPE_B','QA_CO_B','PUR-COMPANY-B')]
253 ])server.records.set(collection+'|'+id,{collection,id,data});
254 await installHarness(page,server);await authenticatedMockBrowser(page);
255 const archive=page.locator('#invoice-archive-table-body');
256 const purchases=page.locator('#pur-list-body');
257 await expect(archive).toContainText('INV-COMPANY-A');
258 await expect(archive).not.toContainText('INV-COMPANY-B');
259 await expect(archive).not.toContainText('INV-LEGACY');
260 await expect(purchases).toContainText('PUR-COMPANY-A');
261 await expect(purchases).not.toContainText('PUR-COMPANY-B');
262 await expect(page.locator('#filter-invoice-company')).toBeDisabled();
263 await expect(page.locator('#filter-invoice-company option')).toHaveCount(1);
264 await expect(page.locator('#filter-invoice-company option[value="ALL"]')).toHaveCount(0);
265 await expect(page.locator('#invoice-company-id')).toBeDisabled();
266 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
267 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
268 await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-A');
269 await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-B');
270 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-A');
271 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-B');
272 // A settings change refreshes all three surfaces without new login.
273 await page.evaluate(()=>setDefaultCompany('QA_CO_B'));
274 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO_B');
275 await expect(archive).toContainText('INV-COMPANY-B');
276 await expect(archive).not.toContainText('INV-COMPANY-A');
277 await expect(purchases).toContainText('PUR-COMPANY-B');
278 await expect(purchases).not.toContainText('PUR-COMPANY-A');
279 await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-B');
280 await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-A');
281 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-B');
282 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-A');
283 // Direct stale entrypoint cannot open an off-company draft.
284 await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_A')});
285 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
286 await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_B')});
287 await expect(page.locator('#edit-invoice-id')).toHaveValue('INV_SCOPE_B');
288 // Changing company while a form is open clears that edit context.
289 await page.evaluate(()=>setDefaultCompany('QA_CO'));
290 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
291 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
292 await expect(archive).toContainText('INV-COMPANY-A');
293 await expect(archive).not.toContainText('INV-COMPANY-B');
294 await expect(purchases).toContainText('PUR-COMPANY-A');
295 await expect(purchases).not.toContainText('PUR-COMPANY-B');
296 // Both originals are preserved in storage.
297 expect(await page.evaluate(()=>getMyInvoices().filter(x=>x.id.startsWith('INV_SCOPE_')).length)).toBe(2);
298 expect(await page.evaluate(()=>getMyPurchases().filter(x=>x.id.startsWith('PUR_SCOPE_')).length)).toBe(2);
299 await page.waitForFunction(()=>!syncPending&&!syncRunning);
300 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
301 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
302 await expect(page.locator('#invoice-archive-table-body')).toContainText('INV-COMPANY-A');
303 await expect(page.locator('#invoice-archive-table-body')).not.toContainText('INV-COMPANY-B');
304 });
305 test('formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher',async({page})=>{
306 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
307 await fillInvoice(page,'FIN-DRAFT-001',2);
308 await page.evaluate(()=>commitSaveInvoice());
309 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
310 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
311 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
312 const id=remoteInvoices(server)[0].id;
313 // A saved formal draft prints its complete invoice; the print UI must not stamp it
314 // as provisional. The underlying draft state and zero-posting invariant remain.
315 await page.evaluate(x=>renderAndPrintDirect(x),id);
316 await expect(page.locator('#printable-invoice')).toContainText('FIN-DRAFT-۰۰۱');
317 await expect(page.locator('#printable-invoice')).toContainText('۳٬۰۰۰');
318 await expect(page.locator('#printable-invoice')).not.toContainText('پیش‌نویس — غیرقطعی');
319 await expect(page.locator('#printable-invoice [style*="rotate(-12deg)"]')).toHaveCount(0);
320 const isolatedPrint=page.frameLocator('#finora-print-frame').locator('#finora-print-document');
321 await expect(isolatedPrint).toContainText('FIN-DRAFT-۰۰۱');
322 await expect(isolatedPrint).not.toContainText('پیش‌نویس — غیرقطعی');
323 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
324 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
325 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
326 await page.evaluate(x=>editInvoice(x),id);
327 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
328 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
329 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
330 await page.evaluate(()=>commitSaveInvoice());
331 await expect.poll(()=>remoteInvoices(server)[0]?.grandTotal,{timeout:13000}).toBe(4500);
332 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
333 await expect(page.locator('#finora-document-management-body')).toContainText('FIN-DRAFT-001');
334 await expect(page.locator('#finora-document-management-body')).toContainText('پیش‌نویس');
335 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
336 // Show a confirmation requiring explicit intent; no automatic posting on Save.
337 await expect.poll(()=>remoteInvoices(server)[0].accountingStatus,{timeout:3000}).toBe('draft');
338 await page.evaluate(()=>{window.confirm=()=>true});
339 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
340 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
341 const posted=remoteInvoices(server)[0];
342 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
343 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
344 expect(vouchers).toHaveLength(1);
345 expect(vouchers[0].data.status).toBe('posted');
346 expect(lines.length).toBeGreaterThanOrEqual(2);
347 expect(lines.reduce((t,x)=>t+Number(x.data.debit||0),0)).toBe(4500);
348 expect(lines.reduce((t,x)=>t+Number(x.data.credit||0),0)).toBe(4500);
349 expect(posted.journalVoucherId).toBe(vouchers[0].id);
350 expect(server.autoPostCount).toBe(1);
351 // Repeat post must be idempotent, and posted source cannot be edited or overwritten.
352 await page.evaluate(x=>finalizeInvoiceDocument(x),id);
353 expect(server.autoPostCount).toBe(1);
354 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
355 await page.evaluate(x=>editInvoice(x),id);
356 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
357 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
358 const saved=await page.evaluate(x=>getMyInvoices().find(i=>i.id===x),id);
359 expect(saved.documentStatus).toBe('posted');
360 expect(saved.grandTotal).toBe(4500);
361 expect(saved.documentVersion).toBe(2);
362 });
363 test('posted sale can be returned to an editable corrective draft; original voucher stays immutable and balances',async({page})=>{
364 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
365 await fillInvoice(page,'PILOT-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
366 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
367 const originalId=remoteInvoices(server)[0].id;
368 await page.evaluate(id=>finalizeInvoiceDocument(id),originalId);
369 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
370 const before=remoteInvoices(server)[0],originalVoucherId=before.journalVoucherId;
371 const originalLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy);
372 const result=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تصحیح تعداد پایلوت'),originalId);
373 expect(server.reverseCount).toBe(1);
374 expect(result).toBeTruthy();expect(result).not.toBe(originalId);
375 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
376 const after=remoteInvoices(server),original=after.find(i=>i.id===originalId),draft=after.find(i=>i.id===result);
377 expect(original.grandTotal).toBe(3000);
378 expect(original.journalVoucherId).toBe(originalVoucherId);
379 expect(draft.correctsInvoiceId).toBe(originalId);
380 expect(draft.documentStatus).toBe('draft');
381 expect(draft.journalVoucherId).toBeUndefined();
382 expect(draft.number).not.toBe(original.number);
383 const allVouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
384 expect(allVouchers).toHaveLength(2);
385 expect(allVouchers.find(x=>x.id===originalVoucherId).data.status).toBe('posted');
386 expect(server.reversalStatuses.find(x=>x.voucher_id===originalVoucherId)?.effective_status).toBe('reversed');
387 const reversal=allVouchers.find(x=>x.id!==originalVoucherId);
388 expect(reversal.data.status).toBe('posted');
389 expect(originalLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy));
390 expect(await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),originalId)).toBe('reversed');
391 // The replacement source uses the normal draft editor and preserves provenance.
392 await page.evaluate(id=>editInvoice(id),result);
393 await expect(page.locator('#edit-invoice-id')).toHaveValue(result);
394 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
395 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
396 await page.evaluate(()=>commitSaveInvoice());
397 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.grandTotal,{timeout:13000}).toBe(4500);
398 await page.evaluate(id=>finalizeInvoiceDocument(id),result);
399 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.accountingStatus,{timeout:13000}).toBe('posted');
400 const later=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
401 expect(later).toHaveLength(3);
402 expect(later.find(x=>x.id===originalVoucherId).data.status).toBe('posted');
403 expect(server.reversalStatuses.find(x=>x.voucher_id===originalVoucherId)?.effective_status).toBe('reversed');
404 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
405 for(const v of later){
406 const subset=lines.filter(l=>l.data.voucherId===v.id);
407 expect(subset.reduce((t,l)=>t+Number(l.data.debit||0),0)).toBe(subset.reduce((t,l)=>t+Number(l.data.credit||0),0));
408 }
409 // Repeating the same correction is idempotent: return its existing draft without another reversal.
410 const retry=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تکرار'),originalId);
411 expect(retry).toBe(result);
412 expect(server.reverseCount).toBe(1);
413 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
414 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);
415 expect(persisted.old).toBe('reversed');
416 expect(persisted.drafts).toEqual(['posted']);
417 });
418
419 test('pilot manual journal correction permits draft edits, balanced repost and auditable cancellation',async({page})=>{
420 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
421 const first=await page.evaluate(()=>{
422 const v=jeCreateDraft({number:'8801',date:'1405/07/19',description:'ثبت آزمایشی',sourceType:'manual',
423 lines:[{accountId:'A_CASH',debit:1000,credit:0},{accountId:'A_REV',debit:0,credit:1000}]});
424 jePost(v.id);return v.id;
425 });
426 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='journalVouchers').length,{timeout:13000}).toBe(1);
427 const oldLineData=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy);
428 const ids=await page.evaluate(id=>{
429 const out=jeReturnPostedToDraft(id,'اشتباه مبلغ آزمایشی','1405/07/19');
430 return {draft:out.draft.id,reversal:out.reversal.id,old:out.original.id};
431 },first);
432 await page.evaluate(id=>jeUpdateDraft(id,{date:'1405/07/19',description:'اصلاح مبلغ به ۲۰۰۰',
433 lines:[{accountId:'A_CASH',debit:2000,credit:0},{accountId:'A_REV',debit:0,credit:2000}]}),ids.draft);
434 const details=await page.evaluate(({draft,old})=>{
435 jePost(draft);return {old:getMyJournalVouchers().find(x=>x.id===old).status,new:getMyJournalVouchers().find(x=>x.id===draft).status,trial:jeTrialBalance()};
436 },ids);
437 expect(details.old).toBe('reversed');expect(details.new).toBe('posted');
438 expect(details.trial.find(x=>x.accountId==='A_CASH').balance).toBe(2000);
439 await page.evaluate(id=>jeCancelPostedManual(id,'ابطال بعد از تست','1405/07/19'),ids.draft);
440 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(4);
441 const final=await page.evaluate(()=>jeTrialBalance());
442 expect(final.reduce((sum,row)=>sum+row.debit-row.credit,0)).toBe(0);
443 expect(final.find(x=>x.accountId==='A_CASH').balance).toBe(0);
444 expect(oldLineData).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy));
445 const rows=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
446 expect(rows.find(x=>x.id===first).data.status).toBe('reversed');
447 expect(rows.find(x=>x.id===ids.draft).data.status).toBe('reversed');
448 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
449 expect(await page.evaluate(()=>jeTrialBalance().find(x=>x.accountId==='A_CASH').balance)).toBe(0);
450 });
451
452 test('pilot cancellation preserves posted invoice record while only unposted drafts can be deleted',async({page})=>{
453 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
454 await fillInvoice(page,'PILOT-CANCEL-001',2);await page.evaluate(()=>commitSaveInvoice());
455 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
456 const invoiceId=remoteInvoices(server)[0].id;
457 await page.evaluate(id=>finalizeInvoiceDocument(id),invoiceId);
458 const original=remoteInvoices(server)[0];
459 expect(original.accountingStatus).toBe('posted');
460 const blocked=await page.evaluate(id=>{try{deleteInvoicePilotDraft(id);return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
461 expect(blocked).not.toBe('unexpected');
462 await page.evaluate(id=>cancelPostedInvoicePilot(id,'ابطال سند پایلوت'),invoiceId);
463 expect(server.reverseCount).toBe(1);
464 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(2);
465 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
466 expect(remoteInvoices(server)[0].grandTotal).toBe(original.grandTotal);
467 const status=await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),invoiceId);
468 expect(status).toBe('reversed');
469 const bad=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
470 expect(bad).not.toBe('unexpected');
471 expect(bad).toMatch(/ابطال|اصلاحیه/);
472 expect(server.reverseCount).toBe(1);
473 // A separate never-posted invoice may be deleted; posted history stays intact.
474 await fillInvoice(page,'PILOT-DELETE-DRAFT-001',1);await page.evaluate(()=>commitSaveInvoice());
475 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
476 const draft=remoteInvoices(server).find(x=>x.number==='PILOT-DELETE-DRAFT-001');
477 expect(draft).toBeTruthy();
478 await page.evaluate(id=>deleteInvoicePilotDraft(id),draft.id);
479 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
480 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
481 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(2);
482 });
483
484 function remotePurchases(server){return [...server.records.values()].filter(x=>x.collection==='purchases').map(x=>copy(x.data));}
485 async function createPostedPurchase(page,server,number='PILOT-PUR-001',qty=2){
486 const id=await page.evaluate(async({number,qty})=>{
487 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}],subtotal:qty*100,discount:0,discountType:'fixed',discountInput:0,vat:0,vatMode:'none',vatType:'percent',vatRate:0,grandTotal:qty*100,accountingVersion:1,documentVersion:1,accountingStatus:'draft',documentStatus:'draft'};
488 datastore.purchases.push(p);await finalizePurchasePilotDraft(p.id);return p.id;
489 },{number,qty});
490 await expect.poll(()=>remotePurchases(server).find(x=>x.id===id)?.journalVoucherId,{timeout:13000}).toBeTruthy();
491 return id;
492 }
493 test('pilot purchase: posted to corrective draft to edited balanced repost via document manager',async({page})=>{
494 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
495 const originalId=await createPostedPurchase(page,server);
496 expect(server.autoPostCount).toBe(1);
497 const first=remotePurchases(server).find(x=>x.id===originalId);
498 expect(first.accountingStatus).toBe('posted');
499 const voucher=first.journalVoucherId;
500 const untouched=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy);
501 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(2);
502 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(2);
503 await page.evaluate(()=>{
504 window.confirm=()=>true;window.prompt=()=> 'اصلاح مقدار خرید';
505 navigateShell('accounting','view-journal','documents');
506 });
507 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PILOT-PUR-001');
508 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]')).toHaveCount(1);
509 // Technical correction primitive remains available for pre-existing in-progress
510 // drafts; the new employee UI correctly DOES NOT write on open.
511 await page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]').click();
512 expect(remotePurchases(server)).toHaveLength(1);
513 await page.evaluate(()=>purCancelEdit());
514 await page.evaluate(()=>runSync());
515 server.failReverseAfterCommit=true;
516 const uncertain=await page.evaluate(async id=>{try{await returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی');return 'unexpected'}catch(e){return String(e.message)}},originalId);
517 expect(uncertain).not.toBe('unexpected');
518 await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی'),originalId);
519 expect(server.reverseCount).toBe(1);
520 await expect.poll(()=>remotePurchases(server).length,{timeout:14000}).toBe(2);
521 const corrected=remotePurchases(server).find(x=>x.correctsPurchaseId===originalId);
522 expect(corrected.documentStatus).toBe('draft');
523 expect(corrected.journalVoucherId).toBeUndefined();
524 expect(corrected.number).not.toBe(first.number);
525 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
526 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(0);
527 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),originalId)).toBe('reversed');
528 // Internal API fixture made a technical draft without clicking the employee form.
529 await page.evaluate(id=>purEdit(id),corrected.id);
530 await expect(page.locator('#pur-edit-id')).toHaveValue(corrected.id);
531 await page.locator('#pur-items-body .pur-qty').first().fill('3');
532 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
533 await page.locator('#pur-save-btn').click();
534 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.grandTotal,{timeout:14000}).toBe(300);
535 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
536 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
537 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]')).toHaveCount(1);
538 await page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]').click();
539 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.accountingStatus,{timeout:14000}).toBe('posted');
540 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
541 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(3);
542 const journal=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
543 expect(journal).toHaveLength(3);
544 expect(journal.find(x=>x.id===voucher).data.status).toBe('posted');
545 expect(server.reversalStatuses.find(x=>x.voucher_id===voucher)?.effective_status).toBe('reversed');
546 expect(untouched).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy));
547 for(const v of journal){
548 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
549 expect(lines.reduce((s,l)=>s+Number(l.data.debit||0),0)).toBe(lines.reduce((s,l)=>s+Number(l.data.credit||0),0));
550 }
551 const retry=await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تکرار'),originalId);
552 expect(retry).toBe(corrected.id);
553 expect(server.reverseCount).toBe(1);
554 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
555 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
556 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(3);
557 });
558
559 test('pilot purchase denies paid/consumed source; cancels unallocated posting without erasing old voucher',async({page})=>{
560 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
561 const purchaseId=await createPostedPurchase(page,server,'PILOT-PUR-GUARDS');
562 // A payment allocation blocks both corrective reopen and cancellation.
563 const blockedPayment=await page.evaluate(async id=>{
564 datastore.payments.push({id:'QA-SETTLE',ownerUserId:currentUser.id,companyId:'QA_CO',direction:'outbound',invoiceType:'purchase',invoiceId:id,amount:10});
565 try{await cancelPostedPurchasePilot(id,'ابطال');return 'unsafe'}catch(e){return String(e.message)}
566 },purchaseId);
567 expect(blockedPayment).toMatch(/پرداخت/);
568 await page.evaluate(()=>{datastore.payments=datastore.payments.filter(x=>x.id!=='QA-SETTLE');});
569 // Consumption means stock would become negative after purchase reversal.
570 const blockedStock=await page.evaluate(async id=>{
571 const sale={id:'QA-USE',ownerUserId:currentUser.id,companyId:'QA_CO',kind:'formal',documentStatus:'posted',items:[{prodId:'QA_PROD',qty:2}],grandTotal:200};
572 datastore.invoices.push(sale);
573 try{await returnPostedPurchaseAsDraft(id,'اصلاح');return 'unsafe'}catch(e){return String(e.message)}
574 },purchaseId);
575 expect(blockedStock).toMatch(/موجودی/);
576 await page.evaluate(()=>{datastore.invoices=datastore.invoices.filter(x=>x.id!=='QA-USE');});
577 await page.evaluate(id=>cancelPostedPurchasePilot(id,'ابطال خرید آزمایشی'),purchaseId);
578 expect(server.reverseCount).toBe(1);
579 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:14000}).toBe(2);
580 expect(remotePurchases(server)).toHaveLength(1);
581 const original=remotePurchases(server)[0];
582 expect(original.id).toBe(purchaseId);
583 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),purchaseId)).toBe('reversed');
584 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
585 expect(await page.evaluate(id=>{try{deletePurchasePilotDraft(id);return 'unsafe'}catch(e){return String(e.message)}},purchaseId)).not.toBe('unsafe');
586 });
587 test('seamless sale correction: opening and cancelling leaves ledger unchanged; saving retains visible identity, printing and audit',async({page})=>{
588 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
589 await fillInvoice(page,'SAME-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
590 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
591 const id=remoteInvoices(server)[0].id;await page.evaluate(x=>finalizeInvoiceDocument(x),id);
592 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
593 const original=copy(remoteInvoices(server)[0]),initialLines=[...server.records.values()].filter(x=>x.collection==='journalLines').map(copy);
594 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
595 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
596 await page.locator('#finora-document-management-body [data-doc-action="reopen"]').click();
597 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
598 await expect(page.locator('#invoice-number')).toHaveValue('SAME-SALE-001');
599 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
600 await page.evaluate(()=>cancelInvoiceEdit());
601 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
602 expect(remoteInvoices(server)).toHaveLength(1);
603 await page.evaluate(x=>beginInvoiceAmendment(x),id);
604 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
605 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
606 await page.evaluate(()=>commitSaveInvoice());
607 await expect.poll(()=>remoteInvoices(server).filter(x=>x.correctsInvoiceId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
608 expect(remoteInvoices(server)).toHaveLength(2);expect(remoteInvoices(server).find(x=>x.id===id)).toEqual(original);
609 const current=remoteInvoices(server).find(x=>x.correctsInvoiceId===id);
610 expect(current.grandTotal).toBe(4500);
611 expect(current.number).not.toBe(original.number);
612 const visible=await page.evaluate(()=>invoiceVisibleRecords().map(x=>({id:x.id,number:invoiceVisibleNumber(x)})));
613 expect(visible).toEqual([{id:current.id,number:'SAME-SALE-001'}]);
614 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
615 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
616 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
617 await expect(page.locator('#finora-document-management-body')).not.toContainText('-اصلاح');
618 await page.evaluate(x=>renderAndPrintDirect(x),id);
619 await expect(page.locator('#printable-invoice')).toContainText('SAME-SALE-۰۰۱');
620 await expect(page.locator('#printable-invoice')).toContainText('۴٬۵۰۰');
621 await expect(page.locator('#printable-invoice')).not.toContainText('-اصلاح');
622 expect(initialLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy));
623 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
624 expect(vouchers).toHaveLength(3);expect(vouchers.find(v=>v.id===original.journalVoucherId).data.status).toBe('posted');
625 expect(server.reversalStatuses.find(x=>x.voucher_id===original.journalVoucherId)?.effective_status).toBe('reversed');
626 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
627 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
628 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
629 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
630 });
631
632 test('seamless purchase correction: same visible number, no write on opening, save and print corrected purchase',async({page})=>{
633 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
634 const id=await createPostedPurchase(page,server,'SAME-PURCHASE-001',2);
635 const initial=copy(remotePurchases(server).find(x=>x.id===id));const before=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
636 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
637 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
638 await page.locator('#finora-purchase-document-management-body [data-doc-action="reopen"]').click();
639 await expect(page.locator('#pur-edit-id')).toHaveValue(id);
640 await expect(page.locator('#pur-number')).toHaveValue('SAME-PURCHASE-001');
641 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(before.length);
642 await page.evaluate(()=>purCancelEdit());
643 expect(remotePurchases(server)).toHaveLength(1);
644 await page.evaluate(x=>beginPurchaseAmendment(x),id);
645 await page.locator('#pur-items-body .pur-qty').first().fill('3');
646 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
647 await page.locator('#pur-save-btn').click();
648 await expect.poll(()=>remotePurchases(server).filter(x=>x.correctsPurchaseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
649 expect(remotePurchases(server).find(x=>x.id===id)).toEqual(initial);
650 const current=remotePurchases(server).find(x=>x.correctsPurchaseId===id);
651 expect(current.grandTotal).toBe(300);expect(current.number).not.toBe(initial.number);
652 const visible=await page.evaluate(()=>purchaseVisibleRecords().map(x=>({id:x.id,number:purchaseVisibleNumber(x)})));
653 expect(visible).toEqual([{id:current.id,number:'SAME-PURCHASE-001'}]);
654 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
655 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
656 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
657 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('-اصلاح');
658 await page.evaluate(x=>purPrint(x),id);
659 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
660 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
661 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
662 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
663 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
664 });
665 function remotePayments(server){return [...server.records.values()].filter(x=>x.collection==='payments').map(x=>copy(x.data));}
666 async function createUiPayment(page,server,amount=1000,direction='inbound'){
667 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
668 await page.locator('#pay-direction').selectOption(direction);
669 await page.locator('#pay-contact').selectOption('QA_CONTACT');
670 await page.locator('#pay-method').selectOption('bank');
671 await page.locator('#pay-amount').fill(String(amount));
672 await page.locator('#pay-reference').fill('REF-ORIGINAL-001');
673 await page.evaluate(()=>commitSavePayment());
674 await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
675 await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
676 return remotePayments(server)[0].id;
677 }
678
679 test('treasury amendment edit form opens without on-open ledger writes or changing the original',async({page})=>{
680 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
681 const firstId=await createUiPayment(page,server);
682 await page.waitForFunction(()=>!syncPending&&!syncRunning);
683 const first=copy(remotePayments(server).find(p=>p.id===firstId));
684 const oldLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy);
685 const beforeRpc=server.rpcCount;
686 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
687 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
688 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
689 await page.locator('#finora-treasury-document-management-body [data-doc-action="edit"]').click();
690 await expect(page.locator('#pay-amount')).toHaveValue('1,000');
691 await expect(page.locator('#pay-reference')).toHaveValue('REF-ORIGINAL-001');
692 await page.evaluate(()=>resetPaymentForm());
693 expect(server.rpcCount).toBe(beforeRpc);
694 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
695 expect(remotePayments(server)).toEqual([first]);
696 expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy));
697 });
698
699 for(const direction of ['inbound','outbound'])test('P0 #238 expected RED: '+direction+' treasury correction Save must leave the new linked journal DRAFT',async({page})=>{
700 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
701 const firstId=await createUiPayment(page,server,1000,direction);
702 await page.waitForFunction(()=>!syncPending&&!syncRunning);
703 const first=copy(remotePayments(server).find(p=>p.id===firstId));
704 const originalVoucher=copy(server.records.get('journalVouchers|'+first.journalVoucherId));
705 const originalLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy);
706 if(first?.accountingStatus!=='posted'||originalVoucher?.data.status!=='posted'||originalLines.length<2)
707 throw Error('Original posted treasury fixture invalid; NOT the expected correction Save RED');
708 const sourceType=direction==='outbound'?'payment':'receipt';
709 await page.locator('#payments-ledger button').first().click();
710 await expect(page.locator('#pay-amount')).toHaveValue('1,000');
711 await page.locator('#pay-amount').fill('1250');
712 await page.locator('#pay-note').fill('اصلاح مبلغ');
713 await page.locator('#pay-save').click();
714 await expect.poll(()=>remotePayments(server).filter(p=>p.correctsPaymentId===firstId).length,{timeout:18000}).toBe(1);
715 await page.waitForFunction(()=>!syncPending&&!syncRunning);
716 const original=remotePayments(server).find(p=>p.id===firstId);
717 const amended=remotePayments(server).find(p=>p.correctsPaymentId===firstId);
718 if(!amended||amended.amount!==1250||amended.companyId!=='QA_CO'||amended.direction!==direction||
719 amended.reference!==first.reference||!amended.journalVoucherId)
720 throw Error('Treasury correction fixture invalid; NOT the expected product RED: '+JSON.stringify(amended));
721 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
722 const linked=vouchers.find(x=>x.id===amended.journalVoucherId);
723 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===amended.journalVoucherId);
724 const debit=lines.reduce((n,x)=>n+Number(x.data.debit||0),0);
725 const credit=lines.reduce((n,x)=>n+Number(x.data.credit||0),0);
726 const observed={
727 originalSourceUnchanged:isDeepStrictEqual(original,first),
728 originalVoucherStatus:vouchers.find(x=>x.id===first.journalVoucherId)?.data.status||'missing',
729 originalLinesUnchanged:isDeepStrictEqual(originalLines,
730 [...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy)),
731 correctionSourceStatus:amended.accountingStatus||'',
732 correctionVoucherStatus:linked?.data.status||'missing',
733 correctionLinkedToSource:!!linked&&linked.data.sourceType===sourceType&&linked.data.sourceId===amended.id,
734 correctionHasReversalLink:!!amended.correctionReversalId,
735 balancedCorrectionLines:lines.length>=2&&debit===credit&&debit===1250,
736 correctionAlreadyPosted:vouchers.some(x=>x.data.status==='posted'&&x.data.sourceType===sourceType&&x.data.sourceId===amended.id),
737 originalReversalVoucherCount:vouchers.filter(x=>x.data.voucherType==='reversal'&&x.data.sourceType==='reversal'&&x.data.sourceId===first.journalVoucherId).length,
738 reversalVoucherPosted:vouchers.filter(x=>x.data.voucherType==='reversal'&&x.data.sourceType==='reversal'&&x.data.sourceId===first.journalVoucherId).every(x=>x.data.status==='posted'),
739 voucherCount:vouchers.length,
740 effectiveAmounts:await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))
741 };
742 const knownBroken={
743 originalSourceUnchanged:true,originalVoucherStatus:'reversed',originalLinesUnchanged:true,
744 correctionSourceStatus:'posted',correctionVoucherStatus:'posted',correctionLinkedToSource:true,
745 correctionHasReversalLink:true,balancedCorrectionLines:true,correctionAlreadyPosted:true,
746 originalReversalVoucherCount:1,reversalVoucherPosted:true,voucherCount:3,effectiveAmounts:[1250]
747 };
748 const required={
749 originalSourceUnchanged:true,originalVoucherStatus:'reversed',originalLinesUnchanged:true,
750 correctionSourceStatus:'draft',correctionVoucherStatus:'draft',correctionLinkedToSource:true,
751 correctionHasReversalLink:true,balancedCorrectionLines:true,correctionAlreadyPosted:false,
752 originalReversalVoucherCount:1,reversalVoucherPosted:true,voucherCount:3,effectiveAmounts:[]
753 };
754 assertKnownRedOrFixed(observed,knownBroken,required,'treasury-correction-'+direction);
755 if(isDeepStrictEqual(observed,knownBroken))
756 console.log('FINORA_ISSUE238_PAYMENT_CORRECTION_EXPECTED_RED '+direction+': correction Save immediately posts its new source-linked journal');
757 test.fail(true,'#238 / ADR216: treasury correction Save must leave the new source-linked journal draft until independent accounting approval');
758 expect(observed).toEqual(required);
759 });
760
761 test('treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history',async({page})=>{
762 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
763 const id=await createUiPayment(page,server,450,'outbound');
764 const noCheck=await page.evaluate(async id=>{
765 const p=getMyPayments().find(x=>x.id===id);
766 const saved=p.method;p.method='cheque';
767 try{await paymentAmendPosted(id,{direction:p.direction,contactId:p.contactId,companyId:p.companyId,
768 amount:400,method:'cash',invoiceId:'',invoiceType:'',reference:'x',note:'x'});return 'unsafe';}
769 catch(e){return String(e.message)}
770 finally{p.method=saved}
771 },id);
772 expect(noCheck).toMatch(/چک|تطبیق/);
773 const linked=await page.evaluate(async id=>{
774 const p=getMyPayments().find(x=>x.id===id);
775 p.invoiceType='purchase';p.invoiceId='QA_LINKED';
776 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
777 catch(e){return String(e.message)}
778 finally{p.invoiceType='';p.invoiceId=''}
779 },id);
780 expect(linked).toMatch(/تسویه|فاکتور|تطبیق/);
781 const locked=await page.evaluate(async id=>{
782 const fy=getMyFiscalYears()[0],old=fy.status;
783 fy.status='locked';
784 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
785 catch(e){return String(e.message)}
786 finally{fy.status=old}
787 },id);
788 expect(locked).toMatch(/قفل|سال مالی/);
789 await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال اشتباه آزمایشی';});
790 await page.evaluate(id=>deletePayment(id),id);
791 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(2);
792 expect(remotePayments(server)).toHaveLength(1);
793 expect(remotePayments(server)[0].id).toBe(id);
794 expect(await page.evaluate(id=>paymentPostingStatus(getMyPayments().find(x=>x.id===id)),id)).toBe('reversed');
795 expect(await page.evaluate(()=>paymentEffectiveRecords().length)).toBe(0);
796 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
797 await expect(page.locator('#payments-ledger')).toContainText('ابطال‌شده');
798 });
799
800 test('treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload',async({page})=>{
801 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
802 const id=await createUiPayment(page,server);
803 await page.waitForFunction(()=>!syncPending&&!syncRunning);
804 const before=copy(remotePayments(server)[0]);
805 const vouchersBefore=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id);
806 server.failNext=true;
807 await page.evaluate(id=>editPayment(id),id);
808 await page.locator('#pay-amount').fill('1800');
809 await page.locator('#pay-save').click();
810 await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('اصلاح کامل نشد'))),{timeout:8000}).toBe(true);
811 expect(server.failCount).toBe(1);
812 // The RPC did not persist any subset of the combined financial diff.
813 expect(remotePayments(server)).toEqual([before]);
814 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(vouchersBefore);
815 // After uncertain acknowledgment, do not call the amend API again blindly.
816 });
817 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
818 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
819 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());
820 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
821 const id=remoteInvoices(server)[0].id;
822 const result=await page.evaluate(async x=>{try{await finalizeInvoiceDocument(x);return 'unexpected success'}catch(e){return String(e.message)}},id);
823 expect(result).toMatch(/حساب|کدینگ/);
824 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
825 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
826 });
827
828
829 test('F2 validates formal invoice then saves a draft without posting any financial journal',async({page})=>{
830 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
831 await page.keyboard.press('F2');
832 expect(remoteInvoices(server)).toHaveLength(0);
833 expect(await page.evaluate(()=>window.__f0Alerts.at(-1))).toMatch(/حداقل یک کالا|خدمت معتبر/);
834 await fillInvoice(page,'F2-SAFE-DRAFT-001',2);
835 await page.keyboard.press('F2');
836 await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1);
837 const saved=remoteInvoices(server)[0];
838 expect(saved.number).toBe('F2-SAFE-DRAFT-001');
839 expect(saved.accountingStatus).toBe('draft');
840 expect(saved.documentStatus).toBe('draft');
841 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
842 await page.keyboard.press('F2');
843 expect(remoteInvoices(server)).toHaveLength(1);
844 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
845 });
846
847 async function pastePaymentAmount(page,text){
848 await page.context().grantPermissions(['clipboard-read','clipboard-write']);
849 await page.evaluate(value=>navigator.clipboard.writeText(value),text);
850 await page.locator('#pay-amount').focus();
851 await page.keyboard.press('ControlOrMeta+A');
852 await page.keyboard.press('ControlOrMeta+V');
853 }
854
855 for(const [script,typed,pasted] of [
856 ['Latin','1234567','1,234,567'],
857 ['Persian','۱۲۳۴۵۶۷','۱٬۲۳۴٬۵۶۷'],
858 ['Arabic','١٢٣٤٥٦٧','١٬٢٣٤٬٥٦٧'],
859 ]){
860 test(`treasury amount groups ${script} typing and clipboard paste without changing numeric saved value`,async({page})=>{
861 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
862 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
863 const amount=page.locator('#pay-amount');
864 await amount.pressSequentially(typed);
865 await expect(amount).toHaveValue('1,234,567');
866 await pastePaymentAmount(page,pasted);
867 await expect(amount).toHaveValue('1,234,567');
868 await page.locator('#pay-contact').selectOption('QA_CONTACT');
869 await page.locator('#pay-save').click();
870 await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
871 expect(remotePayments(server)[0].amount).toBe(1234567);
872 expect(remotePayments(server)[0].accountingStatus).toBe('posted');
873 });
874 }
875
876 test('treasury amount editing groups an existing value and preserves numeric correction payload and original history',async({page})=>{
877 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
878 const id=await createUiPayment(page,server,1234567.5);
879 const original=copy(remotePayments(server)[0]);
880 await page.locator('#payments-ledger button').first().click();
881 await expect(page.locator('#pay-amount')).toHaveValue('1,234,567.5');
882 await page.locator('#pay-save').click();
883 await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===id)?.amount,{timeout:18000}).toBe(1234567.5);
884 const unchanged=remotePayments(server).find(x=>x.correctsPaymentId===id);
885 expect(remotePayments(server).find(x=>x.id===id)).toEqual(original);
886 await page.locator('#payments-ledger button').first().click();
887 await pastePaymentAmount(page,'۲٬۳۴۵٬۶۷۸٫۵');
888 await expect(page.locator('#pay-amount')).toHaveValue('2,345,678.5');
889 await page.locator('#pay-save').click();
890 await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===unchanged.id)?.amount,{timeout:18000}).toBe(2345678.5);
891 expect(remotePayments(server).find(x=>x.id===id)).toEqual(original);
892 });
893
894 test('treasury amount keeps negative and invalid pasted input rejectable with no payment or journal write',async({page})=>{
895 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
896 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
897 await page.locator('#pay-contact').selectOption('QA_CONTACT');
898 for(const value of ['-1,234','−۱٬۲۳۴','1,234oops','1.2.3','Infinity','1e6','']){
899 await pastePaymentAmount(page,value);
900 await page.evaluate(()=>{window.__f0Alerts=[]});
901 await page.locator('#pay-save').click();
902 expect(await page.evaluate(()=>window.__f0Alerts.length),value).toBe(1);
903 expect(await page.evaluate(()=>datastore.payments.length)).toBe(0);
904 expect(await page.evaluate(()=>datastore.journalVouchers.length)).toBe(0);
905 }
906 expect(remotePayments(server)).toEqual([]);
907 });
908
909 test('treasury amount grouping keeps the insertion caret while editing digits in the middle',async({page})=>{
910 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
911 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
912 const amount=page.locator('#pay-amount');
913 await amount.pressSequentially('1234567');
914 await expect(amount).toHaveValue('1,234,567');
915 await amount.press('Home');await amount.press('ArrowRight');
916 await amount.pressSequentially('9');
917 await expect(amount).toHaveValue('19,234,567');
918 expect(await amount.evaluate(el=>el.selectionStart)).toBe(2);
919 });
920
921 for(const direction of ['outbound','inbound'])test('contact operational balance includes effective '+direction+' settlements once and isolates company',async({page})=>{
922 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
923 await page.evaluate(({direction,USER})=>{
924 const base={ownerUserId:USER,companyId:'QA_CO',contactId:'QA_CONTACT'};
925 datastore.companies.push({id:'QA_OTHER',ownerUserId:USER,name:'Other company'});
926 const voucher=(id,status='posted')=>({id,ownerUserId:USER,companyId:'QA_CO',status});
927 datastore.journalVouchers.push(voucher('J_TRADE'),voucher('J_OLD','reversed'),voucher('J_NEW'),voucher('J_CANCEL','reversed'),{...voucher('J_FOREIGN'),companyId:'QA_OTHER'});
928 const trade={...base,id:'TRADE',supplierId:'QA_CONTACT',kind:'formal',grandTotal:1000,paymentMethod:'credit',journalVoucherId:'J_TRADE',number:'TRADE-VALID'};
929 datastore[direction==='outbound'?'purchases':'invoices']=[trade,{...trade,id:'DRAFT',number:'DRAFT-EXCLUDED',journalVoucherId:'',accountingStatus:'draft',documentStatus:'draft',grandTotal:99999},{...trade,id:'FOREIGN',number:'FOREIGN-EXCLUDED',companyId:'QA_OTHER',journalVoucherId:'J_FOREIGN',grandTotal:8000}];
930 if(direction==='inbound')datastore.invoices.push({...trade,id:'PROFORMA',number:'PROFORMA-EXCLUDED',kind:'pre_invoice'});
931 datastore.payments=[
932 {...base,id:'ALLOC',direction,method:'bank',amount:200,invoiceType:direction==='outbound'?'purchase':'sale',invoiceId:'TRADE'},
933 {...base,id:'OLD',direction,method:'bank',amount:600,journalVoucherId:'J_OLD'},
934 {...base,id:'NEW',direction,method:'bank',amount:300,journalVoucherId:'J_NEW',correctsPaymentId:'OLD'},
935 {...base,id:'CANCEL',direction,method:'bank',amount:700,journalVoucherId:'J_CANCEL'},
936 {...base,id:'RAW-CHEQUE',direction,method:'cheque',amount:900},
937 {...base,id:'OTHER',direction,method:'bank',amount:9000,companyId:'QA_OTHER'},
938 {...base,id:'UNSCOPED',direction,method:'bank',amount:5555,companyId:''},
939 {...base,id:'BADALLOC',direction,method:'bank',amount:6666,invoiceType:direction==='outbound'?'purchase':'sale',invoiceId:'FOREIGN'}
940 ];
941 datastore.cheques=[{...base,id:'CHQ',direction,amount:9999,status:'registered',contactName:'خریدار آزمایشی'}];
942 window.__contactBefore=JSON.stringify([datastore.invoices,datastore.purchases,datastore.payments,datastore.journalVouchers,datastore.cheques]);
943 switchView('view-contacts');renderContacts();
944 },{direction,USER});
945 const row=page.locator('#contacts-ledger-table-body tr').first();
946 await expect(row.locator('td').nth(6)).toContainText('۵۰۰');
947 await row.locator('td').nth(6).locator('button').click();
948 const body=page.locator('#finora-drill-body');
949 await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'-500':'500');
950 await expect(body).not.toContainText('DRAFT-EXCLUDED');await expect(body).not.toContainText('FOREIGN-EXCLUDED');await expect(body).not.toContainText('PROFORMA-EXCLUDED');
951 expect(await page.evaluate(()=>JSON.stringify([datastore.invoices,datastore.purchases,datastore.payments,datastore.journalVouchers,datastore.cheques])===window.__contactBefore)).toBe(true);
952 await page.evaluate(({direction,USER})=>{
953 datastore.journalVouchers.push({id:'J_CHEQUE',ownerUserId:USER,companyId:'QA_CO',status:'posted'});
954 const scope={ownerUserId:USER,companyId:'QA_CO',contactId:'QA_CONTACT',direction,amount:100,journalVoucherId:'J_CHEQUE'};
955 datastore.payments.push({...scope,id:'PAY_CHEQUE',method:'cheque'});
956 datastore.cheques.push({...scope,id:'REGISTER_CHEQUE',status:'registered'});
957 renderContacts();openContactLedger('QA_CONTACT');
958 },{direction,USER});
959 await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'-400':'400');
960 await page.evaluate(()=>{closeFinoraDrill();getMySettings().default_company_id='QA_OTHER';renderContacts();openContactLedger('QA_CONTACT')});
961 await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'1000':'-1000');
962 await expect(body).toContainText(direction==='outbound'?'پیش‌پرداخت':'پیش‌دریافت');
963 });
964
965
966 test('contact operational balance reflects a saved unallocated supplier payment after reload',async({page})=>{
967 const server=fakeServer();
968 server.records.set('journalVouchers|J_PUR',{collection:'journalVouchers',id:'J_PUR',data:{companyId:'QA_CO',status:'posted'}});
969 server.records.set('purchases|P_BAL',{collection:'purchases',id:'P_BAL',data:{companyId:'QA_CO',supplierId:'QA_CONTACT',number:'PUR-BAL',grandTotal:1000,paymentMethod:'credit',journalVoucherId:'J_PUR'}});
970 await installHarness(page,server);await authenticatedMockBrowser(page);
971 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
972 await page.locator('#pay-direction').selectOption('outbound');
973 await page.locator('#pay-contact').selectOption('QA_CONTACT');
974 await page.locator('#pay-method').selectOption('bank');
975 await page.locator('#pay-amount').fill('450');
976 await page.locator('#pay-save').click();
977 await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
978 await page.evaluate(()=>{switchView('view-contacts');renderContacts();openContactLedger('QA_CONTACT')});
979 await expect(page.locator('[data-contact-net]')).toHaveAttribute('data-contact-net','-550');
980 await expect(page.locator('#finora-drill-body')).toContainText('پرداخت — بدون تخصیص');
981 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
982 await page.evaluate(()=>openContactLedger('QA_CONTACT'));
983 await expect(page.locator('[data-contact-net]')).toHaveAttribute('data-contact-net','-550');
984 expect(remotePayments(server)).toHaveLength(1);
985 });
986
987
988 // Issue #229 / ADR0216: executable expected-RED acceptance contracts.
989 // test.fail is a transparent temporary xfail, NOT a product PASS. Remove
990 // annotations only after the linked-draft lifecycle works end-to-end.
991 test('P0 #229 expected RED: purchase Save must not auto-post',async({page})=>{
992 const server=fakeServer();
993 await installHarness(page,server);
994 await authenticatedMockBrowser(page);
995 await page.evaluate(()=>{
996 switchView('view-purchases');
997 refreshAllSurfaces();
998 const supplier=document.getElementById('pur-supplier');
999 if(!supplier?.querySelector('option[value="QA_CONTACT"]'))
1000 throw Error('QA supplier option missing: fixture setup failure, NOT accounting RED');
1001 supplier.value='QA_CONTACT';
1002 document.getElementById('pur-number').value='QA-ADR216-PUR-NO-AUTOPOST';
1003 document.getElementById('pur-date').value='1405/07/19';
1004 document.getElementById('pur-payment-method').value='credit';
1005 const row=document.querySelector('#pur-items-body tr');
1006 if(!row?.querySelector('.pur-prod option[value="QA_PROD"]'))
1007 throw Error('QA product option missing: fixture setup failure, NOT accounting RED');
1008 row.querySelector('.pur-prod').value='QA_PROD';
1009 row.querySelector('.pur-qty').value='2';
1010 row.querySelector('.pur-price').value='100';
1011 purRecalc();
1012 });
1013 await page.locator('#pur-save-btn').click();
1014 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='purchases').length,
1015 {timeout:15000}).toBe(1);
1016 await expect.poll(()=>page.evaluate(()=>!document.getElementById('pur-save-btn').disabled),
1017 {timeout:15000}).toBe(true);
1018 const purchase=[...server.records.values()].find(x=>x.collection==='purchases');
1019 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
1020 const observed={
1021 documentStatus:purchase?.data.documentStatus,
1022 accountingStatus:purchase?.data.accountingStatus,
1023 hasLinkedDraft:!!purchase?.data.journalVoucherId&&vouchers.some(v=>
1024 v.id===purchase.data.journalVoucherId&&v.data.status==='draft'),
1025 postedVouchers:vouchers.filter(v=>v.data.status==='posted').length,
1026 automaticPostCalls:server.autoPostCount||0
1027 };
1028 // CURRENT: posted, posted, no linked draft, one posted voucher, one autopost.
1029 // REQUIRED: business source + linked draft; no final number/posted voucher.
1030 assertKnownRedOrFixed(observed,{
1031 documentStatus:'posted',accountingStatus:'posted',hasLinkedDraft:false,
1032 postedVouchers:1,automaticPostCalls:1
1033 },{
1034 documentStatus:'draft',accountingStatus:'draft',hasLinkedDraft:true,
1035 postedVouchers:0,automaticPostCalls:0
1036 },'purchase-initial-save');
1037 test.fail(true,'#229: Save invokes automatic posting instead of persisted linked draft');
1038 expect(observed).toEqual({
1039 documentStatus:'draft',accountingStatus:'draft',hasLinkedDraft:true,
1040 postedVouchers:0,automaticPostCalls:0
1041 });
1042 });
1043
1044
1045 test('P0 #229 linked journal draft stays draft for both sales and purchases',async({page})=>{
1046 const server=fakeServer();
1047 await installHarness(page,server);
1048 await authenticatedMockBrowser(page);
1049 const observed=await page.evaluate(()=>{
1050 const ownerUserId=currentUser.id,companyId='QA_CO';
1051 const sale={id:'QA_SALE_LINK_DRAFT',ownerUserId,companyId,kind:'formal',
1052 journalVoucherId:'QA_SALE_JV_DRAFT',accountingStatus:'draft',documentStatus:'draft'};
1053 const purchase={id:'QA_PUR_LINK_DRAFT',ownerUserId,companyId,
1054 journalVoucherId:'QA_PUR_JV_DRAFT',accountingStatus:'draft',documentStatus:'draft'};
1055 const conflictingSale={...sale,id:'QA_SALE_LINK_CONFLICT',
1056 journalVoucherId:'QA_SALE_JV_CONFLICT',accountingStatus:'posted'};
1057 const conflictingPurchase={...purchase,id:'QA_PUR_LINK_CONFLICT',
1058 journalVoucherId:'QA_PUR_JV_CONFLICT',documentStatus:'posted'};
1059 const danglingSale={...sale,id:'QA_SALE_LINK_DANGLING',journalVoucherId:'QA_NOT_FOUND_SALE'};
1060 const danglingPurchase={...purchase,id:'QA_PUR_LINK_DANGLING',journalVoucherId:'QA_NOT_FOUND_PUR'};
1061 const partiallyReversedSale={...sale,id:'QA_SALE_PARTIAL',journalVoucherId:'QA_SALE_JV_PARTIAL',
1062 accountingStatus:'posted',documentStatus:'posted'};
1063 const partiallyReversedPurchase={...purchase,id:'QA_PUR_PARTIAL',journalVoucherId:'QA_PUR_JV_PARTIAL',
1064 accountingStatus:'posted',documentStatus:'posted'};
1065 datastore.invoices.push(sale,conflictingSale,danglingSale,partiallyReversedSale);
1066 datastore.purchases.push(purchase,conflictingPurchase,danglingPurchase,partiallyReversedPurchase);
1067 datastore.journalVouchers.push(
1068 {id:'QA_SALE_JV_DRAFT',ownerUserId,companyId,status:'draft',
1069 sourceType:'sale',sourceId:sale.id},
1070 {id:'QA_PUR_JV_DRAFT',ownerUserId,companyId,status:'draft',
1071 sourceType:'purchase',sourceId:purchase.id},
1072 {id:'QA_SALE_JV_CONFLICT',ownerUserId,companyId,status:'draft',
1073 sourceType:'sale',sourceId:conflictingSale.id},
1074 {id:'QA_PUR_JV_CONFLICT',ownerUserId,companyId,status:'draft',
1075 sourceType:'purchase',sourceId:conflictingPurchase.id},
1076 {id:'QA_SALE_JV_PARTIAL',ownerUserId,companyId,status:'posted',
1077 sourceType:'sale',sourceId:partiallyReversedSale.id},
1078 {id:'QA_PUR_JV_PARTIAL',ownerUserId,companyId,status:'posted',
1079 sourceType:'purchase',sourceId:partiallyReversedPurchase.id}
1080 );
1081 // Effective status can be partial while the immutable original remains posted.
1082 jeRpcEffectiveStatuses.set('QA_SALE_JV_PARTIAL','partially_reversed');
1083 jeRpcEffectiveStatuses.set('QA_PUR_JV_PARTIAL','partially_reversed');
1084 return {
1085 sale:invoiceDocumentStatus(sale),
1086 purchase:purchaseDocumentStatus(purchase),
1087 conflictingSale:invoiceDocumentStatus(conflictingSale),
1088 conflictingPurchase:purchaseDocumentStatus(conflictingPurchase),
1089 danglingSale:invoiceDocumentStatus(danglingSale),
1090 danglingPurchase:purchaseDocumentStatus(danglingPurchase),
1091 partiallyReversedSale:invoiceDocumentStatus(partiallyReversedSale),
1092 partiallyReversedPurchase:purchaseDocumentStatus(partiallyReversedPurchase),
1093 saleDirectEditPermitted:invoiceMayEdit(sale),
1094 purchaseDirectEditPermitted:(()=>{
1095 const before=document.getElementById('pur-edit-id')?.value||'';
1096 const prevAlert=window.alert;
1097 let warning='';
1098 window.alert=message=>{warning=String(message)};
1099 try{purEdit(purchase.id)}finally{window.alert=prevAlert}
1100 return (document.getElementById('pur-edit-id')?.value||'')!==before||
1101 !warning.includes('سند موقت متصل');
1102 })(),
1103 voucherStates:getMyJournalVouchers().filter(v=>v.id.endsWith('_JV_DRAFT')).map(v=>v.status)
1104 };
1105 });
1106 expect(observed).toEqual({
1107 sale:'draft',purchase:'draft',
1108 conflictingSale:'legacy_review',conflictingPurchase:'legacy_review',
1109 danglingSale:'legacy_review',danglingPurchase:'legacy_review',
1110 partiallyReversedSale:'posted',partiallyReversedPurchase:'posted',
1111 saleDirectEditPermitted:false,purchaseDirectEditPermitted:false,
1112 voucherStates:['draft','draft']
1113 });
1114 });
1115
1116
1117 test('P0 #229 linked journal drafts do not advertise unsupported source-only edit or finalize buttons',async({page})=>{
1118 const server=fakeServer();
1119 await installHarness(page,server);
1120 await authenticatedMockBrowser(page);
1121 const observed=await page.evaluate(()=>{
1122 const ownerUserId=currentUser.id,companyId='QA_CO';
1123 const sale={id:'QA_SALE_LINKED_UI',ownerUserId,companyId,number:'QA-SALE-LINKED-UI',
1124 companyName:'QA Company',contactId:'QA_CONTACT',contactName:'QA Customer',
1125 date:'1405/07/19',kind:'formal',kindLabel:'رسمی',items:[],grandTotal:170,
1126 journalVoucherId:'QA_SALE_JV_LINKED_UI',accountingStatus:'draft',documentStatus:'draft'};
1127 const purchase={id:'QA_PUR_LINKED_UI',ownerUserId,companyId,number:'QA-PUR-LINKED-UI',
1128 supplierId:'QA_CONTACT',supplierName:'QA Supplier',date:'1405/07/19',
1129 items:[],grandTotal:170,journalVoucherId:'QA_PUR_JV_LINKED_UI',
1130 accountingStatus:'draft',documentStatus:'draft'};
1131 datastore.invoices.push(sale);
1132 datastore.purchases.push(purchase);
1133 datastore.journalVouchers.push(
1134 {id:sale.journalVoucherId,ownerUserId,companyId,status:'draft',sourceType:'sale',sourceId:sale.id},
1135 {id:purchase.journalVoucherId,ownerUserId,companyId,status:'draft',sourceType:'purchase',sourceId:purchase.id}
1136 );
1137 switchView('view-purchases');
1138 refreshAllSurfaces();
1139 renderInvoices();
1140 const purRow=[...document.querySelectorAll('#pur-list-body tr')].find(tr=>tr.textContent.includes(purchase.number));
1141 const saleRow=[...document.querySelectorAll('#invoice-archive-table-body tr')].find(tr=>tr.textContent.includes(sale.number));
1142 if(!purRow||!saleRow)throw Error('Linked draft source rows missing from browser DOM; fixture failure');
1143 return {
1144 purchaseStatus:purchaseDocumentStatus(purchase),
1145 saleStatus:invoiceDocumentStatus(sale),
1146 purchaseMessage:purRow.textContent.includes('سند موقت متصل'),
1147 purchaseActions:[...purRow.querySelectorAll('button')].map(b=>b.getAttribute('onclick')||''),
1148 saleActions:[...saleRow.querySelectorAll('button')].map(b=>b.getAttribute('onclick')||'')
1149 };
1150 });
1151 expect(observed.purchaseStatus).toBe('draft');
1152 expect(observed.saleStatus).toBe('draft');
1153 expect(observed.purchaseMessage).toBe(true);
1154 expect(observed.purchaseActions).toEqual([expect.stringContaining('purPrint(')]);
1155 expect(observed.saleActions).toContainEqual(expect.stringContaining('renderAndPrintDirect('));
1156 expect(observed.saleActions).not.toContainEqual(expect.stringContaining('editInvoice('));
1157 expect(observed.saleActions).not.toContainEqual(expect.stringContaining('beginInvoiceAmendment('));
1158 });
1159
1160
1161 test('P0 #229 linked draft direct actions deny before confirm, sync or autopost',async({page})=>{
1162 const server=fakeServer();
1163 await installHarness(page,server);
1164 await authenticatedMockBrowser(page);
1165 const observed=await page.evaluate(async()=>{
1166 const ownerUserId=currentUser.id,companyId='QA_CO';
1167 const sale={id:'QA_SALE_LINK_ACTION',ownerUserId,companyId,kind:'formal',
1168 kindLabel:'رسمی',companyName:'QA Company',number:'QA-SALE-LINK-ACTION',
1169 contactId:'QA_CONTACT',contactName:'QA Customer',date:'1405/07/19',
1170 items:[],grandTotal:170,journalVoucherId:'QA_SALE_JV_LINK_ACTION',
1171 documentStatus:'draft',accountingStatus:'draft'};
1172 const purchase={id:'QA_PUR_LINK_ACTION',ownerUserId,companyId,
1173 number:'QA-PUR-LINK-ACTION',supplierId:'QA_CONTACT',supplierName:'QA Supplier',
1174 date:'1405/07/19',items:[],grandTotal:170,
1175 journalVoucherId:'QA_PUR_JV_LINK_ACTION',documentStatus:'draft',accountingStatus:'draft'};
1176 datastore.invoices.push(sale);datastore.purchases.push(purchase);
1177 datastore.journalVouchers.push(
1178 {id:sale.journalVoucherId,ownerUserId,companyId,status:'draft',
1179 sourceType:'sale',sourceId:sale.id},
1180 {id:purchase.journalVoucherId,ownerUserId,companyId,status:'draft',
1181 sourceType:'purchase',sourceId:purchase.id}
1182 );
1183 const snapshot=()=>JSON.stringify({
1184 sale:datastore.invoices.find(x=>x.id===sale.id),
1185 purchase:datastore.purchases.find(x=>x.id===purchase.id),
1186 journals:datastore.journalVouchers.filter(x=>x.id.endsWith('_JV_LINK_ACTION'))});
1187 const before=snapshot(),alerts=[];
1188 let confirmCalls=0,directDenial='';
1189 const previousConfirm=window.confirm,previousAlert=window.alert;
1190 window.confirm=()=>{confirmCalls++;return true;};
1191 window.alert=value=>alerts.push(String(value));
1192 try{
1193 try{await finalizeInvoiceDocument(sale.id)}catch(e){directDenial=String(e.message);}
1194 await finalizeInvoiceDocumentUi(sale.id);
1195 await purFinalizeUi(purchase.id);
1196 purDeleteDraftUi(purchase.id);
1197 }finally{window.confirm=previousConfirm;window.alert=previousAlert;}
1198 switchView('view-purchases');refreshAllSurfaces();renderInvoices();
1199 const saleRow=[...document.querySelectorAll('#invoice-archive-table-body tr')]
1200 .find(tr=>tr.textContent.includes(sale.number));
1201 const purchaseRow=[...document.querySelectorAll('#pur-list-body tr')]
1202 .find(tr=>tr.textContent.includes(purchase.number));
1203 if(!saleRow||!purchaseRow)throw Error('Linked draft action register row missing');
1204 return {confirmCalls,directDenial,alerts,unchanged:before===snapshot(),
1205 saleLabel:saleRow.textContent,purchaseLabel:purchaseRow.textContent};
1206 });
1207 expect(observed.confirmCalls).toBe(0);
1208 expect(observed.directDenial).toContain('سند موقت متصل');
1209 expect(observed.alerts.filter(x=>x.includes('قطعی‌سازی مستقل'))).toHaveLength(2);
1210 expect(observed.alerts.some(x=>x.includes('حذف سند موقت متصل'))).toBe(true);
1211 expect(observed.unchanged).toBe(true);
1212 expect(observed.saleLabel).toContain('پیش‌نویس متصل');
1213 expect(observed.saleLabel).not.toContain('پیش‌نویس قابل ویرایش');
1214 expect(observed.purchaseLabel).toContain('موقت متصل');
1215 expect(observed.purchaseLabel).not.toContain('موقت قابل اصلاح');
1216 expect(server.autoPostCount||0).toBe(0);
1217 });
1218
1219
1220 test('P0 #229 expected RED: formal sale Save must persist linked journal draft without posting',async({page})=>{
1221 const server=fakeServer();
1222 await installHarness(page,server);
1223 await authenticatedMockBrowser(page);
1224 await fillInvoice(page,'QA-ADR216-SALE-LINK-DRAFT',2);
1225 await page.evaluate(()=>commitSaveInvoice());
1226 await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1);
1227 // A fixture failure is not allowed to masquerade as the expected accounting RED.
1228 await page.waitForFunction(()=>!syncPending&&!syncRunning);
1229 const source=remoteInvoices(server)[0];
1230 if(source.number!=='QA-ADR216-SALE-LINK-DRAFT'||source.kind!=='formal'||
1231 source.companyId!=='QA_CO'||source.grandTotal!==3000)
1232 throw Error('QA formal sale Save fixture invalid; NOT expected-red: '+JSON.stringify(source));
1233 const vouchers=[...server.records.values()].filter(row=>row.collection==='journalVouchers');
1234 const linked=vouchers.find(row=>row.id===source.journalVoucherId);
1235 const lines=[...server.records.values()].filter(row=>
1236 row.collection==='journalLines'&&row.data.voucherId===source.journalVoucherId);
1237 const debit=lines.reduce((sum,row)=>sum+Number(row.data.debit||0),0);
1238 const credit=lines.reduce((sum,row)=>sum+Number(row.data.credit||0),0);
1239 const observed={
1240 documentStatus:source.documentStatus,
1241 accountingStatus:source.accountingStatus,
1242 hasLinkedDraft:!!linked&&linked.data.status==='draft',
1243 linkedSourceMatches:!!linked&&linked.data.sourceType==='sale'&&linked.data.sourceId===source.id,
1244 draftHasNoFinalNumber:!!linked&&!linked.data.number,
1245 draftHasBalancedLines:lines.length>=2&&debit===credit&&debit===source.grandTotal,
1246 postedVouchers:vouchers.filter(row=>row.data.status==='posted').length,
1247 automaticPostCalls:server.autoPostCount||0
1248 };
1249 // CURRENT: source-only sale draft, no linked journal, no autopost.
1250 // REQUIRED ADR216: atomic source + linked journal draft, balanced lines, no final number.
1251 assertKnownRedOrFixed(observed,{
1252 documentStatus:'draft',accountingStatus:'draft',
1253 hasLinkedDraft:false,linkedSourceMatches:false,
1254 draftHasNoFinalNumber:false,draftHasBalancedLines:false,
1255 postedVouchers:0,automaticPostCalls:0
1256 },{
1257 documentStatus:'draft',accountingStatus:'draft',
1258 hasLinkedDraft:true,linkedSourceMatches:true,
1259 draftHasNoFinalNumber:true,draftHasBalancedLines:true,
1260 postedVouchers:0,automaticPostCalls:0
1261 },'sale-initial-save');
1262 test.fail(true,'#229 / ADR216: formal sale Save still lacks server-persisted linked journal draft');
1263 expect(observed).toEqual({
1264 documentStatus:'draft',accountingStatus:'draft',
1265 hasLinkedDraft:true,linkedSourceMatches:true,
1266 draftHasNoFinalNumber:true,draftHasBalancedLines:true,
1267 postedVouchers:0,automaticPostCalls:0
1268 });
1269 });
1270
1271
1272 test('P0 #229 expected RED: posted purchase correction Save must remain linked accounting draft',async({page})=>{
1273 const server=fakeServer();
1274 await installHarness(page,server);
1275 await authenticatedMockBrowser(page);
1276 const id=await createPostedPurchase(page,server,'QA-ADR216-CORRECTION-SAVE',2);
1277 const original=remotePurchases(server).find(p=>p.id===id);
1278 const originalVoucher=[...server.records.values()].find(r=>r.collection==='journalVouchers'&&r.id===original.journalVoucherId);
1279 if(original?.accountingStatus!=='posted'||originalVoucher?.data.status!=='posted')
1280 throw Error('Original posted purchase fixture invalid; NOT the expected correction Save RED');
1281 const originalSourceFingerprint=copy(original);
1282 const originalVoucherFingerprint=copy(originalVoucher);
1283 const originalLines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&
1284 r.data.voucherId===original.journalVoucherId).map(copy);
1285 await page.evaluate(x=>beginPurchaseAmendment(x),id);
1286 await expect(page.locator('#pur-edit-id')).toHaveValue(id);
1287 await page.locator('#pur-items-body .pur-qty').first().fill('3');
1288 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
1289 await page.locator('#pur-save-btn').click();
1290 // Await the actual completed Save path, not its intermediate locally inserted draft.
1291 await expect(page.locator('#pur-edit-id')).toHaveValue('',{timeout:22000});
1292 await expect.poll(()=>remotePurchases(server).filter(p=>p.correctsPurchaseId===id).length,
1293 {timeout:15000}).toBe(1);
1294 await page.waitForFunction(()=>!syncPending&&!syncRunning);
1295 const corrected=remotePurchases(server).find(p=>p.correctsPurchaseId===id);
1296 if(corrected?.grandTotal!==300||corrected?.companyId!=='QA_CO'||
1297 corrected?.correctionOriginalNumber!==original.number)
1298 throw Error('Correction Save fixture invalid; NOT the expected product RED: '+JSON.stringify(corrected));
1299 // A correction must never rewrite or destroy the original posted source/journal.
1300 expect(remotePurchases(server).find(p=>p.id===id)).toEqual(originalSourceFingerprint);
1301 expect([...server.records.values()].find(r=>r.collection==='journalVouchers'&&
1302 r.id===original.journalVoucherId)).toEqual(originalVoucherFingerprint);
1303 expect([...server.records.values()].filter(r=>r.collection==='journalLines'&&
1304 r.data.voucherId===original.journalVoucherId)).toEqual(originalLines);
1305 const vouchers=[...server.records.values()].filter(r=>r.collection==='journalVouchers');
1306 const linked=vouchers.find(r=>r.id===corrected.journalVoucherId);
1307 const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&
1308 r.data.voucherId===corrected.journalVoucherId);
1309 const debit=lines.reduce((sum,r)=>sum+Number(r.data.debit||0),0);
1310 const credit=lines.reduce((sum,r)=>sum+Number(r.data.credit||0),0);
1311 const observed={
1312 documentStatus:corrected.documentStatus,
1313 accountingStatus:corrected.accountingStatus,
1314 hasSourceLinkedJournalDraft:!!linked&&linked.data.status==='draft',
1315 journalPointsToCorrection:!!linked&&linked.data.sourceType==='purchase'&&
1316 linked.data.sourceId===corrected.id,
1317 balancedDraftLines:lines.length>=2&&debit===credit&&debit===300,
1318 correctionAlreadyPosted:vouchers.some(r=>r.data.status==='posted'&&
1319 r.data.sourceType==='purchase'&&r.data.sourceId===corrected.id),
1320 originalReversalCount:server.reverseCount
1321 };
1322 // CURRENT: purchaseSaveSeamless directly calls finalizePurchasePilotDraft(newId)
1323 // on Save, bypassing independent accounting approval for the correction.
1324 assertKnownRedOrFixed(observed,{
1325 documentStatus:'posted',accountingStatus:'posted',
1326 hasSourceLinkedJournalDraft:false,journalPointsToCorrection:true,
1327 balancedDraftLines:true,correctionAlreadyPosted:true,originalReversalCount:1
1328 },{
1329 documentStatus:'draft',accountingStatus:'draft',
1330 hasSourceLinkedJournalDraft:true,journalPointsToCorrection:true,
1331 balancedDraftLines:true,correctionAlreadyPosted:false,originalReversalCount:1
1332 },'purchase-correction-save');
1333 test.fail(true,'#229 / ADR216: correcting posted purchase Save auto-finalizes the new source');
1334 expect(observed).toEqual({
1335 documentStatus:'draft',accountingStatus:'draft',
1336 hasSourceLinkedJournalDraft:true,journalPointsToCorrection:true,
1337 balancedDraftLines:true,correctionAlreadyPosted:false,originalReversalCount:1
1338 });
1339 });
1340
1341
1342 // Issue238 / ADR216 — real loaded-browser negative acceptance for non-sale
1343 // financial producers. The Supabase fixture is synthetic: these tests prove
1344 // the UI's client Save call chain, NOT real-JWT server authorization.
1345 // A known broken state is an expected PRODUCT RED; an unknown third state is
1346 // a genuine test failure; a fixed linked DRAFT is a regular passing test.
1347 function issue238AssertKnownRedOrDraft(observed,broken,required,label){
1348 if(isDeepStrictEqual(observed,required))return;
1349 if(!isDeepStrictEqual(observed,broken))
1350 throw Error('FINORA_ISSUE238_UNEXPECTED_PRODUCT_STATE '+label+' '+JSON.stringify({observed,broken,required}));
1351 console.log('FINORA_ISSUE238_SAVE_EXPECTED_RED '+label+': Save already finalizes a source-linked journal');
1352 test.fail(true,'#238 / ADR216: '+label+' Save auto-posts instead of saving a linked accounting draft');
1353 expect(observed).toEqual(required);
1354 }
1355 function issue238JournalSnapshot(server,collection,kind){
1356 const sourceRows=[...server.records.values()].filter(r=>r.collection===collection&&r.data?.kind===kind||
1357 r.collection===collection&&r.data?.direction===kind);
1358 if(sourceRows.length!==1)throw Error('FINORA_ISSUE238_INVALID_FIXTURE '+collection+'/'+kind+' sourceRows='+sourceRows.length);
1359 const source=sourceRows[0],vouchers=[...server.records.values()].filter(r=>r.collection==='journalVouchers');
1360 const linked=vouchers.find(v=>v.id===source.data.journalVoucherId);
1361 const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&r.data.voucherId===source.data.journalVoucherId);
1362 const debit=lines.reduce((sum,r)=>sum+Number(r.data.debit||0),0);
1363 const credit=lines.reduce((sum,r)=>sum+Number(r.data.credit||0),0);
1364 return {
1365 sourceStatus:source.data.accountingStatus||'',
1366 linkedDraft:!!linked&&linked.data.status==='draft',
1367 linkedPosted:!!linked&&linked.data.status==='posted',
1368 linkedToSource:!!linked&&linked.data.sourceId===source.id&&
1369 linked.data.sourceType===(collection==='payments'?(kind==='inbound'?'receipt':'payment'):kind),
1370 balanced:lines.length>=2&&debit===credit&&debit===Number(source.data.amount),
1371 postedCount:vouchers.filter(v=>v.data.status==='posted').length,
1372 voucherCount:vouchers.length
1373 };
1374 }
1375 const issue238KnownPosted={
1376 sourceStatus:'posted',linkedDraft:false,linkedPosted:true,linkedToSource:true,
1377 balanced:true,postedCount:1,voucherCount:1
1378 };
1379 const issue238RequiredDraft={
1380 sourceStatus:'draft',linkedDraft:true,linkedPosted:false,linkedToSource:true,
1381 balanced:true,postedCount:0,voucherCount:1
1382 };
1383
1384 for(const direction of ['inbound','outbound'])test('P0 #238 expected RED: '+direction+' payment Save must leave balanced linked journal DRAFT',async({page})=>{
1385 const server=fakeServer();
1386 await installHarness(page,server);
1387 await authenticatedMockBrowser(page);
1388 await page.evaluate(dir=>{
1389 switchView('view-payments');renderPayments();
1390 for(const [id,value] of [['pay-direction',dir],['pay-contact','QA_CONTACT'],
1391 ['pay-method','bank'],['pay-amount','1200'],['pay-reference','ISSUE238-'+dir]]){
1392 const el=document.getElementById(id);
1393 if(!el)throw Error('FINORA_ISSUE238_PAYMENT_FORM_MISSING '+id);
1394 el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
1395 }
1396 commitSavePayment();
1397 },direction);
1398 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='payments').length,
1399 {timeout:14000}).toBe(1);
1400 await page.waitForFunction(()=>!syncPending&&!syncRunning);
1401 const rows=[...server.records.values()].filter(r=>r.collection==='payments');
1402 if(rows[0]?.data.amount!==1200||rows[0]?.data.companyId!=='QA_CO'||rows[0]?.data.direction!==direction)
1403 throw Error('FINORA_ISSUE238_PAYMENT_FIXTURE_INVALID '+JSON.stringify(rows[0]?.data));
1404 const observed=issue238JournalSnapshot(server,'payments',direction);
1405 issue238AssertKnownRedOrDraft(observed,issue238KnownPosted,issue238RequiredDraft,'payment-'+direction);
1406 });
1407
1408 for(const kind of ['expense','income'])test('P0 #238 expected RED: '+kind+' Save must leave balanced linked journal DRAFT',async({page})=>{
1409 const server=fakeServer();
1410 // The original sale/purchase fixture does not seed expense/income posting roles.
1411 for(const [id,code,title,role] of [
1412 ['A_EXP','6103','هزینه عمومی','expense_default'],
1413 ['A_OTHER','4201','سایر درآمد','other_income_default']
1414 ])server.records.set('accounts|'+id,{
1415 collection:'accounts',id,data:{code,title,systemRole:role,active:true,postingAllowed:true},version:1
1416 });
1417 await installHarness(page,server);
1418 await authenticatedMockBrowser(page);
1419 await page.evaluate(k=>{
1420 switchView('view-expenses');
1421 if(typeof window.commitSaveExpense!=='function')
1422 throw Error('FINORA_ISSUE238_EXPENSE_OVERRIDE_MISSING');
1423 for(const [id,value] of [['trx-kind-input',k],['trx-amount-input','1200'],
1424 ['trx-desc-input','ISSUE238 '+k]]){
1425 const el=document.getElementById(id);
1426 if(!el)throw Error('FINORA_ISSUE238_EXPENSE_FORM_MISSING '+id);
1427 el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
1428 }
1429 window.commitSaveExpense();
1430 },kind);
1431 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='expenses').length,
1432 {timeout:14000}).toBe(1);
1433 await page.waitForFunction(()=>!syncPending&&!syncRunning);
1434 const rows=[...server.records.values()].filter(r=>r.collection==='expenses');
1435 if(rows[0]?.data.amount!==1200||rows[0]?.data.companyId!=='QA_CO'||rows[0]?.data.kind!==kind)
1436 throw Error('FINORA_ISSUE238_EXPENSE_FIXTURE_INVALID '+JSON.stringify(rows[0]?.data));
1437 const observed=issue238JournalSnapshot(server,'expenses',kind);
1438 issue238AssertKnownRedOrDraft(observed,issue238KnownPosted,issue238RequiredDraft,'expense-'+kind);
1439 });
1440
1441 // #238 / ADR216: count-Save must not finalize valuation or operational stock.
1442 // The browser uses the real loaded phase5 module and a synthetic sync server.
1443 // Real database/JWT approval, inventory locking and duplicate-count safety need
1444 // separate Codex-main E2E. Keep this expected RED strict and source-grounded.
1445 test('P0 #238 expected RED: inventory count Save must persist pending stock and a balanced DRAFT valuation journal',async({page})=>{
1446 const server=fakeServer();
1447 // Genuine positive weighted-average valuation requires existing priced stock:
1448 // without an opening movement, weightedAverage(0, buy_price, []) returns 0.
1449 server.records.get('products|QA_PROD').data.buy_price=25;
1450 for(const [collection,id,data] of [
1451 ['warehouses','QA_WH',{companyId:'QA_CO',code:'MAIN',name:'انبار آزمون',active:true}],
1452 ['stockMovements','QA_OPEN',{companyId:'QA_CO',kind:'opening',productId:'QA_PROD',
1453 warehouseId:'QA_WH',qty:2,unitCost:25,date:'1405/07/19',status:'posted'}],
1454 ['accounts','QA_INVENTORY',{companyId:'QA_CO',code:'1103',title:'موجودی کالا',active:true,postingAllowed:true}],
1455 ['accounts','QA_INVENTORY_GAIN',{companyId:'QA_CO',code:'4201',title:'تعدیل افزایشی موجودی',active:true,postingAllowed:true}]
1456 ])server.records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
1457 await installHarness(page,server);
1458 await authenticatedMockBrowser(page);
1459 const before=await page.evaluate(()=>{
1460 if(typeof p5SaveCount!=='function'||typeof p5RenderInventory!=='function')
1461 throw Error('FINORA_ISSUE238_INVENTORY_RUNTIME_MISSING');
1462 switchView('view-inventory');
1463 p5RenderInventory();
1464 return {stock:p5Stock('QA_PROD','QA_WH'),averageCost:p5AverageCost('QA_PROD')};
1465 });
1466 expect(before).toEqual({stock:2,averageCost:25});
1467 await expect(page.locator('#p5-count-product option[value="QA_PROD"]')).toHaveCount(1);
1468 await expect(page.locator('#p5-count-wh option[value="QA_WH"]')).toHaveCount(1);
1469 await page.locator('#p5-count-product').selectOption('QA_PROD');
1470 await page.locator('#p5-count-wh').selectOption('QA_WH');
1471 await page.locator('#p5-count-qty').fill('5');
1472 await page.locator('#p5-inventory-root button[onclick="p5SaveCount()"]').click();
1473 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='inventoryCounts').length,
1474 {timeout:15000}).toBe(1);
1475 await page.waitForFunction(()=>!syncPending&&!syncRunning);
1476 const counts=[...server.records.values()].filter(r=>r.collection==='inventoryCounts');
1477 const count=counts[0];
1478 const adjustments=[...server.records.values()].filter(r=>r.collection==='stockMovements'&&
1479 r.data.sourceType==='inventory_count'&&r.data.sourceId===count?.id);
1480 const move=adjustments[0];
1481 const vouchers=[...server.records.values()].filter(r=>r.collection==='journalVouchers');
1482 const linked=vouchers.find(r=>r.id===move?.data.journalVoucherId);
1483 const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&
1484 r.data.voucherId===linked?.id);
1485 const debit=lines.reduce((n,r)=>n+Number(r.data.debit||0),0);
1486 const credit=lines.reduce((n,r)=>n+Number(r.data.credit||0),0);
1487 if(count?.data.companyId!=='QA_CO'||count.data.productId!=='QA_PROD'||
1488 count.data.warehouseId!=='QA_WH'||count.data.systemQty!==2||
1489 count.data.physicalQty!==5||count.data.difference!==3||
1490 move?.data.qty!==3||move.data.unitCost!==25||move.data.kind!=='adjustment_in')
1491 throw Error('FINORA_ISSUE238_INVENTORY_COUNT_FIXTURE_INVALID '+JSON.stringify({count:count?.data,move:move?.data}));
1492 const observed={
1493 countStatus:count.data.status||'missing',
1494 adjustmentStatus:move.data.status||'missing',
1495 valuationStatus:linked?.data.status||'missing',
1496 movementAccountingStatus:move.data.accountingStatus||'',
1497 countLinkedToJournal:!!linked&&count.data.journalVoucherId===linked.id,
1498 movementLinkedToJournal:!!linked&&move.data.journalVoucherId===linked.id,
1499 journalSourceMatches:!!linked&&linked.data.sourceType==='inventory_adjustment'&&
1500 linked.data.sourceId===move.id&&linked.data.companyId==='QA_CO',
1501 balancedValuation:lines.length===2&&debit===75&&credit===75,
1502 countCount:counts.length,adjustmentCount:adjustments.length,voucherCount:vouchers.length,
1503 postedJournalCount:vouchers.filter(v=>v.data.status==='posted').length,
1504 countPostedAt:!!count.data.postedAt,adjustmentPostedAt:!!move.data.postedAt,
1505 valuationPostedAt:!!linked?.data.postedAt,
1506 effectiveStock:await page.evaluate(()=>p5Stock('QA_PROD','QA_WH')),
1507 effectiveValuationLines:await page.evaluate(()=>
1508 jeLedgerRows().filter(x=>x.voucher?.sourceType==='inventory_adjustment').length)
1509 };
1510 const broken={
1511 countStatus:'posted',adjustmentStatus:'posted',valuationStatus:'posted',
1512 movementAccountingStatus:'posted',
1513 countLinkedToJournal:true,movementLinkedToJournal:true,journalSourceMatches:true,balancedValuation:true,
1514 countCount:1,adjustmentCount:1,voucherCount:1,postedJournalCount:1,
1515 countPostedAt:true,adjustmentPostedAt:true,valuationPostedAt:true,
1516 effectiveStock:5,effectiveValuationLines:2
1517 };
1518 const required={
1519 countStatus:'draft',adjustmentStatus:'draft',valuationStatus:'draft',
1520 movementAccountingStatus:'draft',
1521 countLinkedToJournal:true,movementLinkedToJournal:true,journalSourceMatches:true,balancedValuation:true,
1522 countCount:1,adjustmentCount:1,voucherCount:1,postedJournalCount:0,
1523 countPostedAt:false,adjustmentPostedAt:false,valuationPostedAt:false,
1524 effectiveStock:2,effectiveValuationLines:0
1525 };
1526 if(isDeepStrictEqual(observed,required))return;
1527 if(!isDeepStrictEqual(observed,broken))
1528 throw Error('FINORA_ISSUE238_INVENTORY_COUNT_THIRD_STATE '+JSON.stringify({observed,broken,required}));
1529 console.log('FINORA_ISSUE238_INVENTORY_COUNT_EXPECTED_RED: count Save immediately posts stock movement and balanced valuation journal');
1530 test.fail(true,'#238 / ADR216: inventory count Save must not finalize stock or journal without independent accounting approval');
1531 expect(observed).toEqual(required);
1532 });
1533
1534
1535 // #238: a linked DRAFT purchase with NO committed physical receiving document
1536 // must not change effective Phase5 stock/weighted-average valuation. Compare the
1537 // same authenticated loaded browser's Kardex and accounting read models. This is
1538 // synthetic Supabase-backed UI evidence, NOT a real JWT warehouse transaction.
1539 test('P0 #238 expected RED: draft purchase must not inflate Phase5 stock or weighted-average cost',async({page})=>{
1540 const server=fakeServer();
1541 server.records.get('products|QA_PROD').data.stock=0;
1542 server.records.get('products|QA_PROD').data.buy_price=25;
1543 const fixture=[
1544 ['warehouses','QA_WH',{companyId:'QA_CO',code:'MAIN',name:'انبار آزمایشی',active:true}],
1545 ['purchases','QA_PUR_POSTED',{companyId:'QA_CO',warehouseId:'QA_WH',date:'1405/07/21',
1546 number:'P-POSTED',documentStatus:'posted',accountingStatus:'posted',
1547 journalVoucherId:'QA_JV_POSTED',items:[{prodId:'QA_PROD',qty:2,price:50}],grandTotal:100}],
1548 ['purchases','QA_PUR_DRAFT',{companyId:'QA_CO',warehouseId:'QA_WH',date:'1405/07/22',
1549 number:'P-DRAFT',documentStatus:'draft',accountingStatus:'draft',
1550 journalVoucherId:'QA_JV_DRAFT',items:[{prodId:'QA_PROD',qty:3,price:100}],grandTotal:300}],
1551 ['journalVouchers','QA_JV_POSTED',{companyId:'QA_CO',fiscalYearId:'FY_QA',sourceType:'purchase',
1552 sourceId:'QA_PUR_POSTED',status:'posted',date:'1405/07/21',voucherType:'purchase',number:'1',
1553 postedAt:'2026-10-13T08:00:00.000Z'}],
1554 ['journalVouchers','QA_JV_DRAFT',{companyId:'QA_CO',fiscalYearId:'FY_QA',sourceType:'purchase',
1555 sourceId:'QA_PUR_DRAFT',status:'draft',date:'1405/07/22',voucherType:'purchase'}],
1556 ['journalLines','QA_POSTED_DR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_POSTED',
1557 accountId:'A_BUY',debit:100,credit:0}],
1558 ['journalLines','QA_POSTED_CR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_POSTED',
1559 accountId:'A_AP',debit:0,credit:100}],
1560 ['journalLines','QA_DRAFT_DR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_DRAFT',
1561 accountId:'A_BUY',debit:300,credit:0}],
1562 ['journalLines','QA_DRAFT_CR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_DRAFT',
1563 accountId:'A_AP',debit:0,credit:300}]
1564 ];
1565 for(const [collection,id,data] of fixture)
1566 server.records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
1567 // Validate the fixture financial graph before classifying the read-model RED.
1568 for(const [purchaseId,voucherId,amount,status] of [
1569 ['QA_PUR_POSTED','QA_JV_POSTED',100,'posted'],
1570 ['QA_PUR_DRAFT','QA_JV_DRAFT',300,'draft']
1571 ]){
1572 const p=server.records.get('purchases|'+purchaseId)?.data;
1573 const v=server.records.get('journalVouchers|'+voucherId)?.data;
1574 const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&r.data.voucherId===voucherId);
1575 if(!p||!v||p.companyId!=='QA_CO'||p.warehouseId!=='QA_WH'||
1576 p.journalVoucherId!==voucherId||p.documentStatus!==status||
1577 v.sourceType!=='purchase'||v.sourceId!==purchaseId||v.status!==status||
1578 lines.length!==2||lines.reduce((s,r)=>s+Number(r.data.debit||0),0)!==amount||
1579 lines.reduce((s,r)=>s+Number(r.data.credit||0),0)!==amount)
1580 throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_INVALID_GRAPH '+purchaseId);
1581 }
1582 if([...server.records.values()].some(r=>r.collection==='stockMovements'))
1583 throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_UNEXPECTED_RECEIPT');
1584 await installHarness(page,server);
1585 await authenticatedMockBrowser(page);
1586 const observed=await page.evaluate(()=>{
1587 if(typeof p5Stock!=='function'||typeof p5AverageCost!=='function'||
1588 typeof productMovement!=='function'||typeof productKardexRows!=='function'||
1589 typeof purchaseDocumentStatus!=='function')
1590 throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_MODULE_MISSING');
1591 switchView('view-inventory');
1592 p5RenderInventory();
1593 const purchases=getMyPurchases();
1594 const statuses=purchases.map(p=>[p.id,purchaseDocumentStatus(p)]).sort((a,b)=>a[0].localeCompare(b[0]));
1595 const rows=[...document.querySelectorAll('#p5-inventory-root table tbody tr')];
1596 const row=rows.find(r=>r.cells[0]?.textContent.includes('بلوک سیمانی')&&
1597 r.cells[1]?.textContent.includes('انبار آزمایشی'));
1598 if(!row)throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_INVENTORY_ROW_MISSING');
1599 const parseCell=cell=>{
1600 const value=toEnDigits(cell.textContent).replace(/[٬,\s]/g,'');
1601 const number=Number(value);if(!Number.isFinite(number))
1602 throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_BAD_UI_NUMBER '+value);
1603 return number;
1604 };
1605 const kardex=productKardexRows('QA_PROD').filter(x=>x.kind==='خرید');
1606 const balance=productMovement('QA_PROD');
1607 return {
1608 purchaseStatuses:statuses,
1609 postedPurchasedQty:balance.purchased,
1610 kardexPurchaseCount:kardex.length,
1611 kardexPurchaseQty:kardex.reduce((sum,x)=>sum+x.qty,0),
1612 inventoryEventSourceIds:p5OperationalEvents('QA_PROD','QA_WH')
1613 .filter(x=>x.source==='purchase').map(x=>x.sourceId).sort(),
1614 phase5EffectiveQty:p5Stock('QA_PROD','QA_WH'),
1615 phase5AverageCost:p5AverageCost('QA_PROD'),
1616 renderedQty:parseCell(row.cells[2]),
1617 renderedAverageCost:parseCell(row.cells[3])
1618 };
1619 });
1620 const shared={
1621 purchaseStatuses:[['QA_PUR_DRAFT','draft'],['QA_PUR_POSTED','posted']],
1622 postedPurchasedQty:2,kardexPurchaseCount:1,kardexPurchaseQty:2
1623 };
1624 const broken={...shared,
1625 inventoryEventSourceIds:['QA_PUR_DRAFT','QA_PUR_POSTED'],
1626 phase5EffectiveQty:5,phase5AverageCost:80,renderedQty:5,renderedAverageCost:80
1627 };
1628 const required={...shared,
1629 inventoryEventSourceIds:['QA_PUR_POSTED'],
1630 phase5EffectiveQty:2,phase5AverageCost:50,renderedQty:2,renderedAverageCost:50
1631 };
1632 if(isDeepStrictEqual(observed,required))return;
1633 if(!isDeepStrictEqual(observed,broken))
1634 throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_THIRD_STATE '+JSON.stringify({observed,broken,required}));
1635 console.log('FINORA_ISSUE238_DRAFT_PURCHASE_STOCK_EXPECTED_RED: linked DRAFT purchase inflates Phase5 stock and cost, while posted-only Kardex excludes it');
1636 test.fail(true,'#238: DRAFT purchase without committed physical receipt must not alter Phase5 stock/valuation');
1637 expect(observed).toEqual(required);
1638 });
1639
1640 // ADR216 / Issue238 cross-warehouse, cross-company stock projection sentinels.
1641 // These are loaded-browser read-model tests, not live database RLS or inventory
1642 // receiving/approval proofs. Costing *between* warehouses requires owner policy;
1643 // cross-company purchase contamination is always forbidden.
1644 function issue238SeedPostedPurchase(server,{id,companyId,warehouseId,qty,price}){
1645 const voucherId='QA_JV_'+id,amount=qty*price;
1646 const purchase={companyId,date:'1405/07/22',number:'PO-'+id,
1647 documentStatus:'posted',accountingStatus:'posted',journalVoucherId:voucherId,
1648 items:[{prodId:'QA_PROD',qty,price}],grandTotal:amount,
1649 ...(warehouseId?{warehouseId}:{})};
1650 const voucher={companyId,fiscalYearId:'FY_QA',sourceType:'purchase',
1651 sourceId:id,status:'posted',date:'1405/07/22',voucherType:'purchase',
1652 number:'PO-'+id,postedAt:'2026-10-13T08:00:00.000Z'};
1653 for(const [collection,key,data] of [
1654 ['purchases',id,purchase],['journalVouchers',voucherId,voucher],
1655 ['journalLines',voucherId+'_DR',{companyId,fiscalYearId:'FY_QA',voucherId,accountId:'A_BUY',debit:amount,credit:0}],
1656 ['journalLines',voucherId+'_CR',{companyId,fiscalYearId:'FY_QA',voucherId,accountId:'A_AP',debit:0,credit:amount}]
1657 ])server.records.set(collection+'|'+key,{collection,id:key,data:copy(data),version:1});
1658 const original=server.records.get('purchases|'+id)?.data;
1659 const posted=server.records.get('journalVouchers|'+voucherId)?.data;
1660 const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&r.data.voucherId===voucherId);
1661 const debit=lines.reduce((s,r)=>s+Number(r.data.debit||0),0);
1662 const credit=lines.reduce((s,r)=>s+Number(r.data.credit||0),0);
1663 if(!original||!posted||posted.sourceId!==id||posted.companyId!==companyId||
1664 original.companyId!==companyId||original.journalVoucherId!==voucherId||
1665 posted.status!=='posted'||lines.length!==2||debit!==amount||credit!==amount)
1666 throw Error('FINORA_ISSUE238_WAREHOUSE_FIXTURE_GRAPH_INVALID '+id);
1667 }
1668 function issue238AssertProjection(observed,knownBroken,required,marker){
1669 if(isDeepStrictEqual(observed,required))return;
1670 if(!isDeepStrictEqual(observed,knownBroken))
1671 throw Error('FINORA_ISSUE238_WAREHOUSE_THIRD_STATE '+marker+' '+JSON.stringify({observed,knownBroken,required}));
1672 console.log(marker+': posted purchase inventory is projected to the wrong company or warehouse');
1673 test.fail(true,'#238 / inventory posting must respect company and warehouse scope');
1674 expect(observed).toEqual(required);
1675 }
1676
1677 test('P0 #238 expected RED: posted purchase at a non-default warehouse must appear in that warehouse',async({page})=>{
1678 const server=fakeServer();
1679 server.records.get('products|QA_PROD').data.stock=0;
1680 server.records.get('products|QA_PROD').data.buy_price=25;
1681 for(const [id,name] of [['QA_WH','انبار اول آزمایشی'],['QA_WH2','انبار دوم آزمایشی']])
1682 server.records.set('warehouses|'+id,{collection:'warehouses',id,
1683 data:{companyId:'QA_CO',code:id,name,active:true},version:1});
1684 issue238SeedPostedPurchase(server,{id:'QA_PUR_W1',companyId:'QA_CO',warehouseId:'QA_WH',qty:2,price:50});
1685 issue238SeedPostedPurchase(server,{id:'QA_PUR_W2',companyId:'QA_CO',warehouseId:'QA_WH2',qty:3,price:100});
1686 await installHarness(page,server);await authenticatedMockBrowser(page);
1687 const observed=await page.evaluate(()=>{
1688 if(typeof p5Stock!=='function'||typeof p5OperationalEvents!=='function'||
1689 typeof productKardexRows!=='function'||typeof productMovement!=='function')
1690 throw Error('FINORA_ISSUE238_WAREHOUSE_MODULE_MISSING');
1691 switchView('view-inventory');p5RenderInventory();
1692 const purchaseStatuses=getMyPurchases().map(p=>[p.id,purchaseDocumentStatus(p)])
1693 .sort((a,b)=>a[0].localeCompare(b[0]));
1694 const rows=[...document.querySelectorAll('#p5-inventory-root table tbody tr')];
1695 const readWh=id=>{
1696 const name=getMyWarehouses().find(w=>w.id===id)?.name;
1697 const row=rows.find(r=>r.cells[0]?.textContent.includes('بلوک سیمانی')&&
1698 r.cells[1]?.textContent.includes(name));
1699 if(!row)throw Error('FINORA_ISSUE238_WAREHOUSE_UI_ROW_MISSING '+id);
1700 const text=toEnDigits(row.cells[2].textContent).replace(/[٬,\s]/g,'');
1701 if(!Number.isFinite(Number(text)))throw Error('FINORA_ISSUE238_WAREHOUSE_BAD_UI_QTY '+text);
1702 return Number(text);
1703 };
1704 return {
1705 activeCompany:afCompanyId(),defaultWarehouse:p5DefaultWarehouse()?.id,
1706 purchaseStatuses,
1707 companyPostedPurchased:productMovement('QA_PROD').purchased,
1708 kardexPostedPurchased:productKardexRows('QA_PROD')
1709 .filter(x=>x.kind==='خرید').reduce((s,x)=>s+x.qty,0),
1710 warehouseOneEventIds:p5OperationalEvents('QA_PROD','QA_WH')
1711 .filter(e=>e.source==='purchase').map(e=>e.sourceId).sort(),
1712 warehouseTwoEventIds:p5OperationalEvents('QA_PROD','QA_WH2')
1713 .filter(e=>e.source==='purchase').map(e=>e.sourceId).sort(),
1714 warehouseOneStock:p5Stock('QA_PROD','QA_WH'),
1715 warehouseTwoStock:p5Stock('QA_PROD','QA_WH2'),
1716 renderedWarehouseOneStock:readWh('QA_WH'),
1717 renderedWarehouseTwoStock:readWh('QA_WH2')
1718 };
1719 });
1720 const shared={activeCompany:'QA_CO',defaultWarehouse:'QA_WH',
1721 purchaseStatuses:[['QA_PUR_W1','posted'],['QA_PUR_W2','posted']],
1722 companyPostedPurchased:5,kardexPostedPurchased:5,
1723 warehouseOneEventIds:['QA_PUR_W1'],
1724 warehouseOneStock:2,renderedWarehouseOneStock:2
1725 };
1726 const broken={...shared,
1727 warehouseTwoEventIds:[],warehouseTwoStock:0,renderedWarehouseTwoStock:0};
1728 const required={...shared,
1729 warehouseTwoEventIds:['QA_PUR_W2'],warehouseTwoStock:3,renderedWarehouseTwoStock:3};
1730 issue238AssertProjection(observed,broken,required,'FINORA_ISSUE238_OTHER_WAREHOUSE_EXPECTED_RED');
1731 });
1732
1733 test('P0 #238 expected RED: a different-company posted purchase without warehouse cannot contaminate active-company stock and cost',async({page})=>{
1734 const server=fakeServer();
1735 server.records.get('products|QA_PROD').data.stock=0;
1736 server.records.get('products|QA_PROD').data.buy_price=25;
1737 server.records.set('companies|QA_CO_B',{collection:'companies',id:'QA_CO_B',
1738 data:{name:'شرکت آزمایشی دیگر',entityType:'legal'},version:1});
1739 server.records.set('warehouses|QA_WH',{collection:'warehouses',id:'QA_WH',
1740 data:{companyId:'QA_CO',code:'MAIN',name:'انبار شرکت فعال',active:true},version:1});
1741 issue238SeedPostedPurchase(server,{id:'QA_PUR_OWN',companyId:'QA_CO',warehouseId:'QA_WH',qty:2,price:50});
1742 // Legacy purchase has no warehouseId; previous code substitutes ACTIVE default warehouse,
1743 // even when the purchase's companyId is different. Same owner, different company.
1744 issue238SeedPostedPurchase(server,{id:'QA_PUR_FOREIGN',companyId:'QA_CO_B',qty:4,price:200});
1745 if('warehouseId' in server.records.get('purchases|QA_PUR_FOREIGN').data)
1746 throw Error('FINORA_ISSUE238_CROSS_COMPANY_LEGACY_WAREHOUSE_SETUP_INVALID');
1747 await installHarness(page,server);await authenticatedMockBrowser(page);
1748 const observed=await page.evaluate(()=>{
1749 if(typeof p5Stock!=='function'||typeof p5AverageCost!=='function'||
1750 typeof productMovement!=='function'||typeof productKardexRows!=='function')
1751 throw Error('FINORA_ISSUE238_CROSS_COMPANY_MODULE_MISSING');
1752 switchView('view-inventory');p5RenderInventory();
1753 const status=getMyPurchases().map(p=>[p.id,p.companyId,purchaseDocumentStatus(p)])
1754 .sort((a,b)=>a[0].localeCompare(b[0]));
1755 const row=[...document.querySelectorAll('#p5-inventory-root table tbody tr')]
1756 .find(r=>r.cells[0]?.textContent.includes('بلوک سیمانی')&&
1757 r.cells[1]?.textContent.includes('انبار شرکت فعال'));
1758 if(!row)throw Error('FINORA_ISSUE238_CROSS_COMPANY_UI_ROW_MISSING');
1759 const parseCell=index=>{
1760 const input=toEnDigits(row.cells[index].textContent).replace(/[٬,\s]/g,'');
1761 const val=Number(input);
1762 if(!Number.isFinite(val))throw Error('FINORA_ISSUE238_CROSS_COMPANY_UI_NUM_INVALID '+index+' '+input);
1763 return val;
1764 };
1765 return {
1766 activeCompany:afCompanyId(),defaultWarehouse:p5DefaultWarehouse()?.id,
1767 sourceStatuses:status,
1768 postedPurchasedQty:productMovement('QA_PROD').purchased,
1769 kardexPurchaseQty:productKardexRows('QA_PROD')
1770 .filter(x=>x.kind==='خرید').reduce((s,x)=>s+x.qty,0),
1771 phase5EventIds:p5OperationalEvents('QA_PROD','QA_WH')
1772 .filter(e=>e.source==='purchase').map(e=>e.sourceId).sort(),
1773 phase5Stock:p5Stock('QA_PROD','QA_WH'),
1774 phase5AverageCost:p5AverageCost('QA_PROD'),
1775 renderedStock:parseCell(2),renderedAverageCost:parseCell(3)
1776 };
1777 });
1778 const shared={activeCompany:'QA_CO',defaultWarehouse:'QA_WH',
1779 sourceStatuses:[['QA_PUR_FOREIGN','QA_CO_B','legacy_review'],['QA_PUR_OWN','QA_CO','posted']],
1780 postedPurchasedQty:2,kardexPurchaseQty:2};
1781 const broken={...shared,
1782 phase5EventIds:['QA_PUR_FOREIGN','QA_PUR_OWN'],
1783 phase5Stock:6,phase5AverageCost:150,renderedStock:6,renderedAverageCost:150};
1784 const required={...shared,
1785 phase5EventIds:['QA_PUR_OWN'],
1786 phase5Stock:2,phase5AverageCost:50,renderedStock:2,renderedAverageCost:50};
1787 issue238AssertProjection(observed,broken,required,'FINORA_ISSUE238_CROSS_COMPANY_STOCK_EXPECTED_RED');
1788 });
1789
1790
1791 // Issue223: loaded-browser regression for manual stock movement company/status/sign.
1792 // These cases reuse the existing authenticated synthetic Supabase fixture. They
1793 // DO NOT establish PostgreSQL RLS or real inventory posting authorization.
1794 // The current Kardex is company-aggregate, not a warehouse-specific stock card;
1795 // therefore an internal transfer must contribute zero to its net movement.
1796 // No presentation contract is imposed on whether a transfer displays 0 or two
1797 // offsetting rows. Product stock recognition policy belongs to Codex-main.
1798 const issue223Cases=[
1799 {key:'CROSS_COMPANY',name:'posted manual movement from another company must be excluded',
1800 movements:[['QA_223_FOREIGN','QA_CO_B','adjustment_in','posted','QA_WH_B',null,5]],
1801 broken:{stockW1:0,stockW2:0,scopedIds:[],kardexNet:5,foreignNet:5,draftNet:0,outNet:0,transferNet:0},
1802 required:{stockW1:0,stockW2:0,scopedIds:[],kardexNet:0,foreignNet:0,draftNet:0,outNet:0,transferNet:0}},
1803 {key:'DRAFT',name:'draft manual adjustment must not enter committed Kardex',
1804 movements:[['QA_223_DRAFT','QA_CO','adjustment_in','draft','QA_WH',null,3]],
1805 broken:{stockW1:0,stockW2:0,scopedIds:['QA_223_DRAFT'],kardexNet:3,foreignNet:0,draftNet:3,outNet:0,transferNet:0},
1806 required:{stockW1:0,stockW2:0,scopedIds:['QA_223_DRAFT'],kardexNet:0,foreignNet:0,draftNet:0,outNet:0,transferNet:0}},
1807 {key:'OUTBOUND_SIGN',name:'posted adjustment_out must subtract from aggregate Kardex',
1808 movements:[['QA_223_OPEN','QA_CO','opening','posted','QA_WH',null,5],
1809 ['QA_223_OUT','QA_CO','adjustment_out','posted','QA_WH',null,2]],
1810 broken:{stockW1:3,stockW2:0,scopedIds:['QA_223_OPEN','QA_223_OUT'],kardexNet:7,foreignNet:0,draftNet:0,outNet:2,transferNet:0},
1811 required:{stockW1:3,stockW2:0,scopedIds:['QA_223_OPEN','QA_223_OUT'],kardexNet:3,foreignNet:0,draftNet:0,outNet:-2,transferNet:0}},
1812 {key:'TRANSFER_NET',name:'posted internal transfer must net zero in company Kardex',
1813 movements:[['QA_223_OPEN','QA_CO','opening','posted','QA_WH',null,8],
1814 ['QA_223_TRANSFER','QA_CO','transfer','posted','QA_WH','QA_WH2',3]],
1815 broken:{stockW1:5,stockW2:3,scopedIds:['QA_223_OPEN','QA_223_TRANSFER'],kardexNet:11,foreignNet:0,draftNet:0,outNet:0,transferNet:3},
1816 required:{stockW1:5,stockW2:3,scopedIds:['QA_223_OPEN','QA_223_TRANSFER'],kardexNet:8,foreignNet:0,draftNet:0,outNet:0,transferNet:0}}
1817 ];
1818 for(const spec of issue223Cases){
1819 test('P0 #223 expected RED: '+spec.name,async({page})=>{
1820 const server=fakeServer();
1821 server.records.get('products|QA_PROD').data.stock=0;
1822 for(const [collection,id,data] of [
1823 ['companies','QA_CO_B',{name:'شرکت مستقل QA B',entityType:'legal'}],
1824 ['warehouses','QA_WH',{companyId:'QA_CO',code:'A1',name:'انبار اول شرکت فعال',active:true}],
1825 ['warehouses','QA_WH2',{companyId:'QA_CO',code:'A2',name:'انبار دوم شرکت فعال',active:true}],
1826 ['warehouses','QA_WH_B',{companyId:'QA_CO_B',code:'B1',name:'انبار شرکت دیگر',active:true}]
1827 ])server.records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
1828 for(const [id,companyId,kind,status,warehouseId,toWarehouseId,qty] of spec.movements){
1829 if(!server.records.has('companies|'+companyId)||
1830 !server.records.has('warehouses|'+warehouseId)||
1831 server.records.get('warehouses|'+warehouseId).data.companyId!==companyId||
1832 (toWarehouseId&&server.records.get('warehouses|'+toWarehouseId)?.data.companyId!==companyId))
1833 throw Error('FINORA_ISSUE223_INVALID_COMPANY_WAREHOUSE_GRAPH '+id);
1834 if(!Number.isFinite(qty)||qty<=0||!['draft','posted'].includes(status))
1835 throw Error('FINORA_ISSUE223_INVALID_MOVEMENT '+id);
1836 const data={companyId,fiscalYearId:'FY_QA',productId:'QA_PROD',kind,status,
1837 warehouseId,toWarehouseId:toWarehouseId||'',qty,unitCost:50,
1838 date:'1405/07/21',reference:'ISSUE223 '+id,
1839 ...(status==='posted'?{postedAt:'2026-11-20T08:00:00.000Z'}:{})};
1840 server.records.set('stockMovements|'+id,{
1841 collection:'stockMovements',id,data:copy(data),version:1});
1842 }
1843 if([...server.records.values()].some(r=>['purchases','invoices'].includes(r.collection))||
1844 [...server.records.values()].filter(r=>r.collection==='stockMovements').length!==spec.movements.length)
1845 throw Error('FINORA_ISSUE223_FIXTURE_ISOLATION_INVALID');
1846 await installHarness(page,server);
1847 await authenticatedMockBrowser(page);
1848 const observed=await page.evaluate(()=>{
1849 if(typeof productKardexRows!=='function'||typeof p5Stock!=='function'||
1850 typeof getMyStockMovements!=='function'||typeof p5ManualEvents!=='function')
1851 throw Error('FINORA_ISSUE223_RUNTIME_MISSING');
1852 switchView('view-inventory');p5RenderInventory();
1853 if(afCompanyId()!=='QA_CO'||getMyCompanies().length!==2||
1854 getMyWarehouses().some(w=>w.companyId!=='QA_CO'))
1855 throw Error('FINORA_ISSUE223_COMPANY_SCOPE_INVALID');
1856 const movementRows=productKardexRows('QA_PROD');
1857 const seedRows=movementRows.filter(r=>String(r.doc).startsWith('QA_223_'));
1858 if(movementRows.length!==seedRows.length)
1859 throw Error('FINORA_ISSUE223_UNEXPECTED_KARDEX_SOURCE');
1860 const delta=id=>seedRows.filter(r=>r.doc===id).reduce((s,r)=>s+r.qty,0);
1861 return {stockW1:p5Stock('QA_PROD','QA_WH'),stockW2:p5Stock('QA_PROD','QA_WH2'),
1862 scopedIds:getMyStockMovements().map(m=>m.id).filter(id=>id.startsWith('QA_223_')).sort(),
1863 kardexNet:seedRows.reduce((s,r)=>s+r.qty,0),
1864 foreignNet:delta('QA_223_FOREIGN'),draftNet:delta('QA_223_DRAFT'),
1865 outNet:delta('QA_223_OUT'),transferNet:delta('QA_223_TRANSFER')};
1866 });
1867 if(isDeepStrictEqual(observed,spec.required))return;
1868 if(!isDeepStrictEqual(observed,spec.broken))
1869 throw Error('FINORA_ISSUE223_MANUAL_KARDEX_THIRD_STATE '+spec.key+' '+
1870 JSON.stringify({observed,broken:spec.broken,required:spec.required}));
1871 console.log('FINORA_ISSUE223_'+spec.key+'_EXPECTED_RED: known incorrect manual Kardex projection '+JSON.stringify(observed));
1872 test.fail(true,'#223 manual Kardex must scope company and posted status, preserve outbound sign and net internal transfers to zero');
1873 expect(observed).toEqual(spec.required);
1874 });
1875 }