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

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

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

Synced Dec 3, 17:00 UTC

qa/posted-source-immutable-jwt-20261122
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 941 lines 69.3 KB
Raw
1 const {test,expect}=require('@playwright/test');
2
3 const BASE=process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
4 const USER='FINORA_F0_FIXTURE_ONLY';
5 const copy=value=>JSON.parse(JSON.stringify(value));
6 function fakeServer(){
7 const records=new Map();
8 for(const [collection,id,data] of [
9 ['companies','QA_CO',{name:'شرکت آزمون ایزوله',entityType:'legal'}],
10 ['contacts','QA_CONTACT',{name:'خریدار آزمایشی',role:'both'}],
11 ['products','QA_PROD',{name:'بلوک سیمانی',code:'BLK-001',unit:'عدد',sale_price:1500}],
12 ['settings','main',{invoice_kind:'formal',vat_mode:'none',vat_rate:10,default_company_id:'QA_CO',currency_mode:'rial'}],
13 ['fiscalYears','FY_QA',{name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}],
14 ['accounts','A_CASH',{code:'1101',title:'صندوق',systemRole:'cash_default',postingAllowed:true,active:true}],
15 ['accounts','A_AR',{code:'1102',title:'دریافتنی',systemRole:'receivable_control',postingAllowed:true,active:true}],
16 ['accounts','A_REV',{code:'4101',title:'درآمد فروش',systemRole:'revenue_default',postingAllowed:true,active:true}],
17 ['accounts','A_VAT',{code:'2102',title:'مالیات',systemRole:'vat_payable',postingAllowed:true,active:true}],
18 ['accounts','A_BUY',{code:'5101',title:'خرید',systemRole:'purchase_default',postingAllowed:true,active:true}],
19 ['accounts','A_AP',{code:'2101',title:'پرداختنی',systemRole:'payable_control',postingAllowed:true,active:true}],
20 ])records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
21 return {records,failNext:false,failCount:0,rpcCount:0,reversalStatuses:[],reverseCount:0};
22 }
23 function remoteInvoices(server){return [...server.records.values()].filter(r=>r.collection==='invoices').map(r=>copy(r.data));}
24
25 test.beforeEach(async({page})=>{
26 page.on('console',message=>{
27 if(message.type()==='error'||message.text().includes('sync error'))
28 console.log('FINORA_F0_BROWSER_CONSOLE',message.type(),message.text());
29 });
30 page.on('pageerror',error=>console.log('FINORA_F0_PAGE_ERROR',error.message));
31 });
32 test.afterEach(async({page},testInfo)=>{
33 if(testInfo.status===testInfo.expectedStatus)return;
34 try{
35 const state=await page.evaluate(()=>({
36 syncPending:typeof syncPending==='undefined'?null:syncPending,
37 syncRunning:typeof syncRunning==='undefined'?null:syncRunning,
38 syncFailCount:typeof syncFailCount==='undefined'?null:syncFailCount,
39 currentOrg:typeof currentUser==='undefined'?null:currentUser?.organizationId,
40 pendingDiff:typeof computeDiff==='function'?(()=>{const d=computeDiff();return {up:d.up.map(x=>x.key),del:d.del};})():null,
41 alerts:window.__f0Alerts||[]
42 }));
43 console.log('FINORA_F0_FAILURE_DIAGNOSTICS',JSON.stringify(state));
44 }catch(err){console.log('FINORA_F0_DIAGNOSTICS_UNAVAILABLE',String(err));}
45 });
46 async function installHarness(page,server){
47 await page.exposeFunction('qaF0Read',async()=>[...server.records.values()].map(row=>({...copy(row),version:Number(row.version)||1})));
48 await page.exposeFunction('qaF0Write',async args=>{
49 server.rpcCount++;
50 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)}));
51 if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'Network unavailable — isolated QA failure',code:'QA_NETWORK'}};}
52 if(args.p_organization_id!=='QA_ORG')return {error:{message:'Unexpected organization scope',code:'QA_ORG_SCOPE'}};
53 const upserts=[];
54 for(const row of args.p_upserts||[]){
55 const key=row.collection+'|'+row.id,current=server.records.get(key);
56 const currentVersion=current?(Number(current.version)||1):0;
57 const parentVoucherId=row.collection==='journalLines'?(row.data?.voucherId||current?.data?.voucherId):null;
58 const parentVoucher=parentVoucherId?server.records.get('journalVouchers|'+parentVoucherId):null;
59 if(row.collection==='journalVouchers'&&current&&current.data.status==='posted'&&['sale','purchase'].includes(current.data.sourceType))
60 return {error:{message:'FINORA_POSTED_SOURCE_VOUCHER_IMMUTABLE',code:'23514'}};
61 if(row.collection==='journalLines'&&parentVoucher&&parentVoucher.data.status==='posted'&&['sale','purchase'].includes(parentVoucher.data.sourceType))
62 return {error:{message:'FINORA_POSTED_SOURCE_VOUCHER_IMMUTABLE',code:'23514'}};
63 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'}};}
64 const version=currentVersion+1;
65 server.records.set(key,{collection:row.collection,id:row.id,data:copy(row.data),version});
66 upserts.push({collection:row.collection,id:row.id,version});
67 }
68 const deletes=[];
69 for(const row of args.p_deletes||[]){
70 const key=row.collection+'|'+row.id,current=server.records.get(key);
71 const currentVersion=current?(Number(current.version)||1):0;
72 const parentVoucherId=row.collection==='journalLines'?current?.data?.voucherId:null;
73 const parentVoucher=parentVoucherId?server.records.get('journalVouchers|'+parentVoucherId):null;
74 if((row.collection==='journalVouchers'&&current?.data?.status==='posted'&&['sale','purchase'].includes(current.data.sourceType))||
75 (row.collection==='journalLines'&&parentVoucher?.data?.status==='posted'&&['sale','purchase'].includes(parentVoucher.data.sourceType)))
76 return {error:{message:'FINORA_POSTED_SOURCE_VOUCHER_IMMUTABLE',code:'23514'}};
77 if(!current||Number(row.expected_version)!==currentVersion)return {error:{message:'FINORA_VERSION_CONFLICT',code:'40001'}};
78 server.records.delete(key);deletes.push({collection:row.collection,id:row.id});
79 }
80 return {data:{upserts,deletes},error:null};
81 });
82 await page.exposeFunction('qaF0Reverse',async args=>{
83 server.reverseCount=(server.reverseCount||0)+1;
84 if(args.p_organization_id!=='QA_ORG')return {data:null,error:{message:'FINORA_ORG_FORBIDDEN',code:'42501'}};
85 if(args.p_allocations!==null)return {data:null,error:{message:'FINORA_REVERSAL_ALLOCATION_INVALID',code:'23514'}};
86 if(String(args.p_reason||'').trim().length<4)return {data:null,error:{message:'FINORA_REVERSAL_REASON_REQUIRED',code:'23514'}};
87 const original=server.records.get('journalVouchers|'+args.p_original_id);
88 if(!original||original.data.status!=='posted')return {data:null,error:{message:'FINORA_REVERSAL_SOURCE_NOT_POSTED',code:'23514'}};
89 if(Number(original.version)!==Number(args.p_expected_version))return {data:null,error:{message:'FINORA_VERSION_CONFLICT',code:'40001'}};
90 const fiscalYear=server.records.get('fiscalYears|'+original.data.fiscalYearId);
91 if(!fiscalYear||fiscalYear.data.status==='locked'||args.p_date<fiscalYear.data.startDate||args.p_date>fiscalYear.data.endDate)
92 return {data:null,error:{message:'FINORA_REVERSAL_FISCAL_DATE_INVALID',code:'23514'}};
93 if((server.reversalStatuses||[]).some(x=>x.voucher_id===args.p_original_id))return {data:null,error:{message:'FINORA_VOUCHER_ALREADY_REVERSED',code:'23514'}};
94 const originalLines=[...server.records.values()].filter(row=>row.collection==='journalLines'&&row.data.voucherId===args.p_original_id);
95 if(!originalLines.length)return {data:null,error:{message:'FINORA_REVERSAL_LINES_MISSING',code:'23514'}};
96 const reversalId=args.p_reversal_id,now=new Date().toISOString();
97 const reversal={companyId:original.data.companyId,fiscalYearId:original.data.fiscalYearId,date:args.p_date,
98 description:'برگشت سند '+(original.data.number||args.p_original_id),reference:original.data.reference||'',
99 voucherType:'reversal',sourceType:'reversal',sourceId:args.p_original_id,reversesVoucherId:args.p_original_id,
100 reversalReason:String(args.p_reason).trim(),reversalAllocations:null,
101 number:String([...server.records.values()].filter(row=>row.collection==='journalVouchers').length+1),
102 status:'posted',postedAt:now,postedBy:'FINORA_F0_FIXTURE_ONLY'};
103 server.records.set('journalVouchers|'+reversalId,{collection:'journalVouchers',id:reversalId,data:copy(reversal),version:1});
104 const reversalLines=originalLines.map((row,index)=>{
105 const lineId=reversalId+'_L'+(index+1),data={voucherId:reversalId,companyId:original.data.companyId,
106 fiscalYearId:original.data.fiscalYearId,accountId:row.data.accountId,
107 debit:Number(row.data.credit||0),credit:Number(row.data.debit||0),
108 description:'برگشت: '+String(row.data.description||''),reversesLineId:row.id};
109 server.records.set('journalLines|'+lineId,{collection:'journalLines',id:lineId,data,version:1});
110 return {...copy(data),id:lineId};
111 });
112 server.reversalStatuses=(server.reversalStatuses||[]).filter(x=>x.voucher_id!==args.p_original_id)
113 .concat([{organization_id:'QA_ORG',voucher_id:args.p_original_id,effective_status:'reversed'}]);
114 if(server.failReverseAfterCommit){server.failReverseAfterCommit=false;return {data:null,error:{message:'QA_NETWORK_AFTER_COMMIT',code:'QA_NETWORK'}};}
115 return {data:{voucher:{...copy(reversal),id:reversalId,version:1},originalVoucherId:args.p_original_id,
116 reversalLineIds:reversalLines.map(x=>x.id),replayed:false},error:null};
117 });
118 await page.exposeFunction('qaF0ReversalStatuses',async()=>copy(server.reversalStatuses||[]));
119 await page.exposeFunction('qaF0AutoPost',async args=>{
120 server.autoPostCount=(server.autoPostCount||0)+1;
121 if(args.p_organization_id!=='QA_ORG')return {data:null,error:{message:'FINORA_ORG_FORBIDDEN',code:'42501'}};
122 const sourceKey=args.p_source_collection+'|'+args.p_source_id;
123 const sourceRow=server.records.get(sourceKey);
124 if(!sourceRow)return {data:null,error:{message:'FINORA_SOURCE_NOT_COMMITTED_IN_ORG',code:'23503'}};
125 const kind=args.p_header.sourceType;
126 if(!['cash','credit'].includes(sourceRow.data.paymentMethod))return {data:null,error:{message:'FINORA_SOURCE_METHOD_OR_CURRENCY_UNSUPPORTED',code:'23514'}};
127 const digitMap={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9','٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9'};
128 const normalizeDate=value=>String(value||'').replace(/[۰-۹٠-٩]/g,digit=>digitMap[digit]||digit);
129 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'}};
130 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));
131 if(prior)return {data:{voucher:{...copy(prior.data),id:prior.id,version:Number(prior.version)||1},replayed:true},error:null};
132 const amount=Number(sourceRow.data.grandTotal||0);
133 if(!Number.isSafeInteger(amount)||amount<=0)return {data:null,error:{message:'FINORA_INVALID_RIAL_AMOUNT',code:'23514'}};
134 const debitAccount=kind==='sale'?(sourceRow.data.paymentMethod==='credit'?'A_AR':'A_CASH'):'A_BUY';
135 const creditAccount=kind==='sale'?'A_REV':(sourceRow.data.paymentMethod==='credit'?'A_AP':'A_CASH');
136 for(const accountId of [debitAccount,creditAccount]){
137 const account=server.records.get('accounts|'+accountId);
138 if(!account||account.data.active===false||account.data.postingAllowed!==true)
139 return {data:null,error:{message:'حساب موردنیاز در کدینگ فعال و قابل ثبت نیست: '+accountId,code:'23514'}};
140 }
141 const now=new Date().toISOString(),voucherId=args.p_voucher_id;
142 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);
143 const voucher={companyId:args.p_header.companyId,fiscalYearId:args.p_header.fiscalYearId,date:args.p_header.date,
144 description:args.p_header.description,reference:args.p_header.reference,voucherType:args.p_header.voucherType,
145 sourceType:kind,sourceId:args.p_source_id,sourceVersion:String(args.p_header.sourceVersion),
146 number:voucherNumber,status:'posted',postedAt:now,postedBy:'FINORA_F0_FIXTURE_ONLY'};
147 const updatedSource={...copy(sourceRow.data),journalVoucherId:voucherId,accountingStatus:'posted',
148 accountingPostedAt:now,documentStatus:'posted',documentPostedAt:now,
149 documentPostedBy:'FINORA_F0_FIXTURE_ONLY',documentVersion:Number(sourceRow.data.documentVersion||1),updatedAt:now};
150 server.records.set(sourceKey,{collection:args.p_source_collection,id:args.p_source_id,data:updatedSource,version:(Number(sourceRow.version)||1)+1});
151 server.records.set('journalVouchers|'+voucherId,{collection:'journalVouchers',id:voucherId,data:voucher,version:1});
152 const lines=[
153 {id:voucherId+'_L1',data:{voucherId,companyId:args.p_header.companyId,fiscalYearId:args.p_header.fiscalYearId,accountId:debitAccount,debit:amount,credit:0}},
154 {id:voucherId+'_L2',data:{voucherId,companyId:args.p_header.companyId,fiscalYearId:args.p_header.fiscalYearId,accountId:creditAccount,debit:0,credit:amount}}
155 ];
156 for(const line of lines)server.records.set('journalLines|'+line.id,{collection:'journalLines',id:line.id,data:line.data,version:1});
157 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};
158 });
159 await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
160 }
161 async function authenticatedMockBrowser(page){
162 await page.goto(BASE,{waitUntil:'domcontentloaded'});
163 // Await the two explicit core login barriers; extension registration alone does not settle either promise.
164 // The synthetic account must not race the organization entitlement wrapper.
165 // Function availability precedes completion of asynchronously loaded ERP modules.
166 await page.waitForFunction(()=>typeof enterApp==='function'&&typeof commitSaveInvoice==='function'&&
167 typeof pullAll==='function'&&window.FinoraStartupStatus?.extensionsReady===true&&
168 window.FinoraStartupStatus?.failedExtensionCount===0&&
169 window.FinoraStartupStatus?.authChecked===true,{timeout:20000});
170 await page.evaluate(()=>Promise.all([window.FinoraAppAssetsReady,window.FinoraOrganizationContextReady]));
171 await page.evaluate(async()=>{
172 window.__FINORA_PRINT_TEST_MODE=true;
173 window.__f0Alerts=[];
174 window.alert=m=>window.__f0Alerts.push(String(m));
175 window.confirm=()=>false;
176 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'}});
177 maybeMigrateLegacyData=()=>{};
178 sb.from=collection=>{
179 if(collection==='finora_journal_reversal_status')return {select:()=>({eq:async()=>({data:await window.qaF0ReversalStatuses(),error:null})})};
180 return {select:()=>({
181 eq(){return this;},
182 order(){return this;},
183 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};}
184 })};
185 };
186 window.requireFreshFinoraMembership=async()=>true;
187 sb.rpc=async(name,args)=>{
188 // Both deployed sync RPC entrypoints share the same transactional mock contract.
189 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);}
190 if(name==='finora_journal_autopost')return await window.qaF0AutoPost(args);
191 if(name==='finora_journal_reverse')return await window.qaF0Reverse(args);
192 throw Error('Unexpected RPC '+name);
193 };
194 await enterApp({id:'FINORA_F0_FIXTURE_ONLY'});
195 const authState={display:getComputedStyle(document.getElementById('auth-screen')).display,status:document.getElementById('auth-login-status')?.textContent||'',userId:currentUser?.id||null,startup:window.FinoraStartupStatus};
196 if(authState.display!=='none')throw new Error('QA_ENTER_APP_FAILED '+JSON.stringify(authState));
197 document.querySelectorAll('.modal-backdrop.active').forEach(x=>x.classList.remove('active'));
198 switchView('view-invoices');
199 });
200 await expect(page.locator('#auth-screen')).toBeHidden();
201 await expect(page.locator('#invoice-company-id option[value="QA_CO"]')).toHaveCount(1);
202 await expect(page.locator('#invoice-items-table-body .row-product-select').first().locator('option[value="QA_PROD"]')).toHaveCount(1);
203 }
204 async function fillInvoice(page,number,qty){
205 // The native invoice-kind/contact selectors are hidden by the unified commercial combobox.
206 // Drive their real DOM change handlers, not Playwright visibility on replaced native selects.
207 await page.evaluate(()=>{
208 for(const [id,value] of [['invoice-kind','formal'],['invoice-company-id','QA_CO'],['invoice-contact-id','QA_CONTACT']]){
209 const el=document.getElementById(id);el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
210 }
211 });
212 await page.locator('#invoice-number').fill(number);
213 await page.locator('#invoice-date-input').fill('۱۴۰۵/۰۷/۱۹');
214 await page.evaluate(()=>{
215 const el=document.querySelector('#invoice-items-table-body .row-product-select');
216 el.value='QA_PROD';el.dispatchEvent(new Event('change',{bubbles:true}));
217 });
218 await page.locator('#invoice-items-table-body .row-quantity').first().fill(String(qty));
219 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
220 }
221
222 test('invoice and purchase registers isolate companies selected in Settings; no ALL fallback or cross-company edit',async({page})=>{
223 const server=fakeServer();
224 const sale=(id,companyId,number)=>({companyId,kind:'non_formal',kindLabel:'غیررسمی',number,date:'1405/07/19',
225 contactId:'QA_CONTACT',contactName:'طرف حساب آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:1500}],grandTotal:1500,
226 documentStatus:'draft',accountingStatus:'draft'});
227 const purchase=(id,companyId,number)=>({companyId,number,date:'1405/07/19',supplierId:'QA_CONTACT',
228 supplierName:'تأمین‌کننده آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:100}],grandTotal:100,accountingStatus:'draft'});
229 server.records.set('companies|QA_CO_B',{collection:'companies',id:'QA_CO_B',data:{name:'شرکت دوم آزمون'}});
230 for(const [collection,id,data] of [
231 ['invoices','INV_SCOPE_A',sale('INV_SCOPE_A','QA_CO','INV-COMPANY-A')],
232 ['invoices','INV_SCOPE_B',sale('INV_SCOPE_B','QA_CO_B','INV-COMPANY-B')],
233 ['invoices','INV_LEGACY_UNSCOPED',sale('INV_LEGACY_UNSCOPED','', 'INV-LEGACY')],
234 ['purchases','PUR_SCOPE_A',purchase('PUR_SCOPE_A','QA_CO','PUR-COMPANY-A')],
235 ['purchases','PUR_SCOPE_B',purchase('PUR_SCOPE_B','QA_CO_B','PUR-COMPANY-B')]
236 ])server.records.set(collection+'|'+id,{collection,id,data});
237 await installHarness(page,server);await authenticatedMockBrowser(page);
238 const archive=page.locator('#invoice-archive-table-body');
239 const purchases=page.locator('#pur-list-body');
240 await expect(archive).toContainText('INV-COMPANY-A');
241 await expect(archive).not.toContainText('INV-COMPANY-B');
242 await expect(archive).not.toContainText('INV-LEGACY');
243 await expect(purchases).toContainText('PUR-COMPANY-A');
244 await expect(purchases).not.toContainText('PUR-COMPANY-B');
245 await expect(page.locator('#filter-invoice-company')).toBeDisabled();
246 await expect(page.locator('#filter-invoice-company option')).toHaveCount(1);
247 await expect(page.locator('#filter-invoice-company option[value="ALL"]')).toHaveCount(0);
248 await expect(page.locator('#invoice-company-id')).toBeDisabled();
249 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
250 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
251 await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-A');
252 await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-B');
253 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-A');
254 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-B');
255 // A settings change refreshes all three surfaces without new login.
256 await page.evaluate(()=>setDefaultCompany('QA_CO_B'));
257 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO_B');
258 await expect(archive).toContainText('INV-COMPANY-B');
259 await expect(archive).not.toContainText('INV-COMPANY-A');
260 await expect(purchases).toContainText('PUR-COMPANY-B');
261 await expect(purchases).not.toContainText('PUR-COMPANY-A');
262 await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-B');
263 await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-A');
264 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-B');
265 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-A');
266 // Direct stale entrypoint cannot open an off-company draft.
267 await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_A')});
268 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
269 await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_B')});
270 await expect(page.locator('#edit-invoice-id')).toHaveValue('INV_SCOPE_B');
271 // Changing company while a form is open clears that edit context.
272 await page.evaluate(()=>setDefaultCompany('QA_CO'));
273 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
274 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
275 await expect(archive).toContainText('INV-COMPANY-A');
276 await expect(archive).not.toContainText('INV-COMPANY-B');
277 await expect(purchases).toContainText('PUR-COMPANY-A');
278 await expect(purchases).not.toContainText('PUR-COMPANY-B');
279 // Both originals are preserved in storage.
280 expect(await page.evaluate(()=>getMyInvoices().filter(x=>x.id.startsWith('INV_SCOPE_')).length)).toBe(2);
281 expect(await page.evaluate(()=>getMyPurchases().filter(x=>x.id.startsWith('PUR_SCOPE_')).length)).toBe(2);
282 await page.waitForFunction(()=>!syncPending&&!syncRunning);
283 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
284 await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
285 await expect(page.locator('#invoice-archive-table-body')).toContainText('INV-COMPANY-A');
286 await expect(page.locator('#invoice-archive-table-body')).not.toContainText('INV-COMPANY-B');
287 });
288 test('formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher',async({page})=>{
289 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
290 await fillInvoice(page,'FIN-DRAFT-001',2);
291 await page.evaluate(()=>commitSaveInvoice());
292 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
293 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
294 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
295 const id=remoteInvoices(server)[0].id;
296 // A saved formal draft prints its complete invoice; the print UI must not stamp it
297 // as provisional. The underlying draft state and zero-posting invariant remain.
298 await page.evaluate(x=>renderAndPrintDirect(x),id);
299 await expect(page.locator('#printable-invoice')).toContainText('FIN-DRAFT-۰۰۱');
300 await expect(page.locator('#printable-invoice')).toContainText('۳٬۰۰۰');
301 await expect(page.locator('#printable-invoice')).not.toContainText('پیش‌نویس — غیرقطعی');
302 await expect(page.locator('#printable-invoice [style*="rotate(-12deg)"]')).toHaveCount(0);
303 const isolatedPrint=page.frameLocator('#finora-print-frame').locator('#finora-print-document');
304 await expect(isolatedPrint).toContainText('FIN-DRAFT-۰۰۱');
305 await expect(isolatedPrint).not.toContainText('پیش‌نویس — غیرقطعی');
306 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
307 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
308 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
309 await page.evaluate(x=>editInvoice(x),id);
310 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
311 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
312 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
313 await page.evaluate(()=>commitSaveInvoice());
314 await expect.poll(()=>remoteInvoices(server)[0]?.grandTotal,{timeout:13000}).toBe(4500);
315 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
316 await expect(page.locator('#finora-document-management-body')).toContainText('FIN-DRAFT-001');
317 await expect(page.locator('#finora-document-management-body')).toContainText('پیش‌نویس');
318 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
319 // Show a confirmation requiring explicit intent; no automatic posting on Save.
320 await expect.poll(()=>remoteInvoices(server)[0].accountingStatus,{timeout:3000}).toBe('draft');
321 await page.evaluate(()=>{window.confirm=()=>true});
322 await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
323 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
324 const posted=remoteInvoices(server)[0];
325 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
326 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
327 expect(vouchers).toHaveLength(1);
328 expect(vouchers[0].data.status).toBe('posted');
329 expect(lines.length).toBeGreaterThanOrEqual(2);
330 expect(lines.reduce((t,x)=>t+Number(x.data.debit||0),0)).toBe(4500);
331 expect(lines.reduce((t,x)=>t+Number(x.data.credit||0),0)).toBe(4500);
332 expect(posted.journalVoucherId).toBe(vouchers[0].id);
333 expect(server.autoPostCount).toBe(1);
334 // Repeat post must be idempotent, and posted source cannot be edited or overwritten.
335 await page.evaluate(x=>finalizeInvoiceDocument(x),id);
336 expect(server.autoPostCount).toBe(1);
337 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
338 await page.evaluate(x=>editInvoice(x),id);
339 await expect(page.locator('#edit-invoice-id')).toHaveValue('');
340 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
341 const saved=await page.evaluate(x=>getMyInvoices().find(i=>i.id===x),id);
342 expect(saved.documentStatus).toBe('posted');
343 expect(saved.grandTotal).toBe(4500);
344 expect(saved.documentVersion).toBe(2);
345 });
346 test('posted sale can be returned to an editable corrective draft; original voucher stays immutable and balances',async({page})=>{
347 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
348 await fillInvoice(page,'PILOT-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
349 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
350 const originalId=remoteInvoices(server)[0].id;
351 await page.evaluate(id=>finalizeInvoiceDocument(id),originalId);
352 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
353 const before=remoteInvoices(server)[0],originalVoucherId=before.journalVoucherId;
354 const originalLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy);
355 const result=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تصحیح تعداد پایلوت'),originalId);
356 expect(server.reverseCount).toBe(1);
357 expect(result).toBeTruthy();expect(result).not.toBe(originalId);
358 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
359 const after=remoteInvoices(server),original=after.find(i=>i.id===originalId),draft=after.find(i=>i.id===result);
360 expect(original.grandTotal).toBe(3000);
361 expect(original.journalVoucherId).toBe(originalVoucherId);
362 expect(draft.correctsInvoiceId).toBe(originalId);
363 expect(draft.documentStatus).toBe('draft');
364 expect(draft.journalVoucherId).toBeUndefined();
365 expect(draft.number).not.toBe(original.number);
366 const allVouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
367 expect(allVouchers).toHaveLength(2);
368 expect(allVouchers.find(x=>x.id===originalVoucherId).data.status).toBe('posted');
369 expect(server.reversalStatuses.find(x=>x.voucher_id===originalVoucherId)?.effective_status).toBe('reversed');
370 const reversal=allVouchers.find(x=>x.id!==originalVoucherId);
371 expect(reversal.data.status).toBe('posted');
372 expect(originalLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===originalVoucherId).map(copy));
373 expect(await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),originalId)).toBe('reversed');
374 // The replacement source uses the normal draft editor and preserves provenance.
375 await page.evaluate(id=>editInvoice(id),result);
376 await expect(page.locator('#edit-invoice-id')).toHaveValue(result);
377 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
378 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
379 await page.evaluate(()=>commitSaveInvoice());
380 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.grandTotal,{timeout:13000}).toBe(4500);
381 await page.evaluate(id=>finalizeInvoiceDocument(id),result);
382 await expect.poll(()=>remoteInvoices(server).find(x=>x.id===result)?.accountingStatus,{timeout:13000}).toBe('posted');
383 const later=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
384 expect(later).toHaveLength(3);
385 expect(later.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 lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
388 for(const v of later){
389 const subset=lines.filter(l=>l.data.voucherId===v.id);
390 expect(subset.reduce((t,l)=>t+Number(l.data.debit||0),0)).toBe(subset.reduce((t,l)=>t+Number(l.data.credit||0),0));
391 }
392 // Repeating the same correction is idempotent: return its existing draft without another reversal.
393 const retry=await page.evaluate(id=>reopenPostedInvoiceAsDraft(id,'تکرار'),originalId);
394 expect(retry).toBe(result);
395 expect(server.reverseCount).toBe(1);
396 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
397 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);
398 expect(persisted.old).toBe('reversed');
399 expect(persisted.drafts).toEqual(['posted']);
400 });
401
402 test('pilot manual journal correction permits draft edits, balanced repost and auditable cancellation',async({page})=>{
403 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
404 const first=await page.evaluate(()=>{
405 const v=jeCreateDraft({number:'8801',date:'1405/07/19',description:'ثبت آزمایشی',sourceType:'manual',
406 lines:[{accountId:'A_CASH',debit:1000,credit:0},{accountId:'A_REV',debit:0,credit:1000}]});
407 jePost(v.id);return v.id;
408 });
409 await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='journalVouchers').length,{timeout:13000}).toBe(1);
410 const oldLineData=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy);
411 const ids=await page.evaluate(id=>{
412 const out=jeReturnPostedToDraft(id,'اشتباه مبلغ آزمایشی','1405/07/19');
413 return {draft:out.draft.id,reversal:out.reversal.id,old:out.original.id};
414 },first);
415 await page.evaluate(id=>jeUpdateDraft(id,{date:'1405/07/19',description:'اصلاح مبلغ به ۲۰۰۰',
416 lines:[{accountId:'A_CASH',debit:2000,credit:0},{accountId:'A_REV',debit:0,credit:2000}]}),ids.draft);
417 const details=await page.evaluate(({draft,old})=>{
418 jePost(draft);return {old:getMyJournalVouchers().find(x=>x.id===old).status,new:getMyJournalVouchers().find(x=>x.id===draft).status,trial:jeTrialBalance()};
419 },ids);
420 expect(details.old).toBe('reversed');expect(details.new).toBe('posted');
421 expect(details.trial.find(x=>x.accountId==='A_CASH').balance).toBe(2000);
422 await page.evaluate(id=>jeCancelPostedManual(id,'ابطال بعد از تست','1405/07/19'),ids.draft);
423 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(4);
424 const final=await page.evaluate(()=>jeTrialBalance());
425 expect(final.reduce((sum,row)=>sum+row.debit-row.credit,0)).toBe(0);
426 expect(final.find(x=>x.accountId==='A_CASH').balance).toBe(0);
427 expect(oldLineData).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first).map(copy));
428 const rows=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
429 expect(rows.find(x=>x.id===first).data.status).toBe('reversed');
430 expect(rows.find(x=>x.id===ids.draft).data.status).toBe('reversed');
431 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
432 expect(await page.evaluate(()=>jeTrialBalance().find(x=>x.accountId==='A_CASH').balance)).toBe(0);
433 });
434
435 test('pilot cancellation preserves posted invoice record while only unposted drafts can be deleted',async({page})=>{
436 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
437 await fillInvoice(page,'PILOT-CANCEL-001',2);await page.evaluate(()=>commitSaveInvoice());
438 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
439 const invoiceId=remoteInvoices(server)[0].id;
440 await page.evaluate(id=>finalizeInvoiceDocument(id),invoiceId);
441 const original=remoteInvoices(server)[0];
442 expect(original.accountingStatus).toBe('posted');
443 const blocked=await page.evaluate(id=>{try{deleteInvoicePilotDraft(id);return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
444 expect(blocked).not.toBe('unexpected');
445 await page.evaluate(id=>cancelPostedInvoicePilot(id,'ابطال سند پایلوت'),invoiceId);
446 expect(server.reverseCount).toBe(1);
447 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:13000}).toBe(2);
448 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
449 expect(remoteInvoices(server)[0].grandTotal).toBe(original.grandTotal);
450 const status=await page.evaluate(id=>invoiceDocumentStatus(getMyInvoices().find(x=>x.id===id)),invoiceId);
451 expect(status).toBe('reversed');
452 const bad=await page.evaluate(async id=>{try{await reopenPostedInvoiceAsDraft(id,'تکرار');return 'unexpected'}catch(e){return String(e.message)}},invoiceId);
453 expect(bad).not.toBe('unexpected');
454 expect(bad).toMatch(/ابطال|اصلاحیه/);
455 expect(server.reverseCount).toBe(1);
456 // A separate never-posted invoice may be deleted; posted history stays intact.
457 await fillInvoice(page,'PILOT-DELETE-DRAFT-001',1);await page.evaluate(()=>commitSaveInvoice());
458 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(2);
459 const draft=remoteInvoices(server).find(x=>x.number==='PILOT-DELETE-DRAFT-001');
460 expect(draft).toBeTruthy();
461 await page.evaluate(id=>deleteInvoicePilotDraft(id),draft.id);
462 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
463 expect(remoteInvoices(server)[0].id).toBe(invoiceId);
464 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(2);
465 });
466
467 function remotePurchases(server){return [...server.records.values()].filter(x=>x.collection==='purchases').map(x=>copy(x.data));}
468 async function createPostedPurchase(page,server,number='PILOT-PUR-001',qty=2){
469 const id=await page.evaluate(async({number,qty})=>{
470 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'};
471 datastore.purchases.push(p);await finalizePurchasePilotDraft(p.id);return p.id;
472 },{number,qty});
473 await expect.poll(()=>remotePurchases(server).find(x=>x.id===id)?.journalVoucherId,{timeout:13000}).toBeTruthy();
474 return id;
475 }
476 test('pilot purchase: posted to corrective draft to edited balanced repost via document manager',async({page})=>{
477 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
478 const originalId=await createPostedPurchase(page,server);
479 expect(server.autoPostCount).toBe(1);
480 const first=remotePurchases(server).find(x=>x.id===originalId);
481 expect(first.accountingStatus).toBe('posted');
482 const voucher=first.journalVoucherId;
483 const untouched=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy);
484 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(2);
485 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(2);
486 await page.evaluate(()=>{
487 window.confirm=()=>true;window.prompt=()=> 'اصلاح مقدار خرید';
488 navigateShell('accounting','view-journal','documents');
489 });
490 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PILOT-PUR-001');
491 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]')).toHaveCount(1);
492 // Technical correction primitive remains available for pre-existing in-progress
493 // drafts; the new employee UI correctly DOES NOT write on open.
494 await page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]').click();
495 expect(remotePurchases(server)).toHaveLength(1);
496 await page.evaluate(()=>purCancelEdit());
497 await page.evaluate(()=>runSync());
498 server.failReverseAfterCommit=true;
499 const uncertain=await page.evaluate(async id=>{try{await returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی');return 'unexpected'}catch(e){return String(e.message)}},originalId);
500 expect(uncertain).not.toBe('unexpected');
501 await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تطبیق پیش‌نویس قدیمی'),originalId);
502 expect(server.reverseCount).toBe(1);
503 await expect.poll(()=>remotePurchases(server).length,{timeout:14000}).toBe(2);
504 const corrected=remotePurchases(server).find(x=>x.correctsPurchaseId===originalId);
505 expect(corrected.documentStatus).toBe('draft');
506 expect(corrected.journalVoucherId).toBeUndefined();
507 expect(corrected.number).not.toBe(first.number);
508 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
509 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(0);
510 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),originalId)).toBe('reversed');
511 // Internal API fixture made a technical draft without clicking the employee form.
512 await page.evaluate(id=>purEdit(id),corrected.id);
513 await expect(page.locator('#pur-edit-id')).toHaveValue(corrected.id);
514 await page.locator('#pur-items-body .pur-qty').first().fill('3');
515 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
516 await page.locator('#pur-save-btn').click();
517 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.grandTotal,{timeout:14000}).toBe(300);
518 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
519 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
520 await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]')).toHaveCount(1);
521 await page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]').click();
522 await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.accountingStatus,{timeout:14000}).toBe('posted');
523 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
524 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(3);
525 const journal=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
526 expect(journal).toHaveLength(3);
527 expect(journal.find(x=>x.id===voucher).data.status).toBe('posted');
528 expect(server.reversalStatuses.find(x=>x.voucher_id===voucher)?.effective_status).toBe('reversed');
529 expect(untouched).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy));
530 for(const v of journal){
531 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
532 expect(lines.reduce((s,l)=>s+Number(l.data.debit||0),0)).toBe(lines.reduce((s,l)=>s+Number(l.data.credit||0),0));
533 }
534 const retry=await page.evaluate(id=>returnPostedPurchaseAsDraft(id,'تکرار'),originalId);
535 expect(retry).toBe(corrected.id);
536 expect(server.reverseCount).toBe(1);
537 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
538 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
539 expect(await page.evaluate(()=>productKardexRows('QA_PROD').reduce((n,x)=>n+x.qty,0))).toBe(3);
540 });
541
542 test('pilot purchase denies paid/consumed source; cancels unallocated posting without erasing old voucher',async({page})=>{
543 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
544 const purchaseId=await createPostedPurchase(page,server,'PILOT-PUR-GUARDS');
545 // A payment allocation blocks both corrective reopen and cancellation.
546 const blockedPayment=await page.evaluate(async id=>{
547 datastore.payments.push({id:'QA-SETTLE',ownerUserId:currentUser.id,companyId:'QA_CO',direction:'outbound',invoiceType:'purchase',invoiceId:id,amount:10});
548 try{await cancelPostedPurchasePilot(id,'ابطال');return 'unsafe'}catch(e){return String(e.message)}
549 },purchaseId);
550 expect(blockedPayment).toMatch(/پرداخت/);
551 await page.evaluate(()=>{datastore.payments=datastore.payments.filter(x=>x.id!=='QA-SETTLE');});
552 // Consumption means stock would become negative after purchase reversal.
553 const blockedStock=await page.evaluate(async id=>{
554 const sale={id:'QA-USE',ownerUserId:currentUser.id,companyId:'QA_CO',kind:'formal',documentStatus:'posted',items:[{prodId:'QA_PROD',qty:2}],grandTotal:200};
555 datastore.invoices.push(sale);
556 try{await returnPostedPurchaseAsDraft(id,'اصلاح');return 'unsafe'}catch(e){return String(e.message)}
557 },purchaseId);
558 expect(blockedStock).toMatch(/موجودی/);
559 await page.evaluate(()=>{datastore.invoices=datastore.invoices.filter(x=>x.id!=='QA-USE');});
560 await page.evaluate(id=>cancelPostedPurchasePilot(id,'ابطال خرید آزمایشی'),purchaseId);
561 expect(server.reverseCount).toBe(1);
562 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:14000}).toBe(2);
563 expect(remotePurchases(server)).toHaveLength(1);
564 const original=remotePurchases(server)[0];
565 expect(original.id).toBe(purchaseId);
566 expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),purchaseId)).toBe('reversed');
567 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
568 expect(await page.evaluate(id=>{try{deletePurchasePilotDraft(id);return 'unsafe'}catch(e){return String(e.message)}},purchaseId)).not.toBe('unsafe');
569 });
570 test('seamless sale correction: opening and cancelling leaves ledger unchanged; saving retains visible identity, printing and audit',async({page})=>{
571 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
572 await fillInvoice(page,'SAME-SALE-001',2);await page.evaluate(()=>commitSaveInvoice());
573 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
574 const id=remoteInvoices(server)[0].id;await page.evaluate(x=>finalizeInvoiceDocument(x),id);
575 await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
576 const original=copy(remoteInvoices(server)[0]),initialLines=[...server.records.values()].filter(x=>x.collection==='journalLines').map(copy);
577 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
578 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
579 await page.locator('#finora-document-management-body [data-doc-action="reopen"]').click();
580 await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
581 await expect(page.locator('#invoice-number')).toHaveValue('SAME-SALE-001');
582 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
583 await page.evaluate(()=>cancelInvoiceEdit());
584 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
585 expect(remoteInvoices(server)).toHaveLength(1);
586 await page.evaluate(x=>beginInvoiceAmendment(x),id);
587 await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
588 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
589 await page.evaluate(()=>commitSaveInvoice());
590 await expect.poll(()=>remoteInvoices(server).filter(x=>x.correctsInvoiceId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
591 expect(remoteInvoices(server)).toHaveLength(2);expect(remoteInvoices(server).find(x=>x.id===id)).toEqual(original);
592 const current=remoteInvoices(server).find(x=>x.correctsInvoiceId===id);
593 expect(current.grandTotal).toBe(4500);
594 expect(current.number).not.toBe(original.number);
595 const visible=await page.evaluate(()=>invoiceVisibleRecords().map(x=>({id:x.id,number:invoiceVisibleNumber(x)})));
596 expect(visible).toEqual([{id:current.id,number:'SAME-SALE-001'}]);
597 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
598 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
599 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
600 await expect(page.locator('#finora-document-management-body')).not.toContainText('-اصلاح');
601 await page.evaluate(x=>renderAndPrintDirect(x),id);
602 await expect(page.locator('#printable-invoice')).toContainText('SAME-SALE-۰۰۱');
603 await expect(page.locator('#printable-invoice')).toContainText('۴٬۵۰۰');
604 await expect(page.locator('#printable-invoice')).not.toContainText('-اصلاح');
605 expect(initialLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===original.journalVoucherId).map(copy));
606 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
607 expect(vouchers).toHaveLength(3);expect(vouchers.find(v=>v.id===original.journalVoucherId).data.status).toBe('posted');
608 expect(server.reversalStatuses.find(x=>x.voucher_id===original.journalVoucherId)?.effective_status).toBe('reversed');
609 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
610 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
611 await expect(page.locator('#finora-document-management-body tr')).toHaveCount(1);
612 await expect(page.locator('#finora-document-management-body')).toContainText('SAME-SALE-001');
613 });
614
615 test('seamless purchase correction: same visible number, no write on opening, save and print corrected purchase',async({page})=>{
616 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
617 const id=await createPostedPurchase(page,server,'SAME-PURCHASE-001',2);
618 const initial=copy(remotePurchases(server).find(x=>x.id===id));const before=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
619 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
620 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
621 await page.locator('#finora-purchase-document-management-body [data-doc-action="reopen"]').click();
622 await expect(page.locator('#pur-edit-id')).toHaveValue(id);
623 await expect(page.locator('#pur-number')).toHaveValue('SAME-PURCHASE-001');
624 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(before.length);
625 await page.evaluate(()=>purCancelEdit());
626 expect(remotePurchases(server)).toHaveLength(1);
627 await page.evaluate(x=>beginPurchaseAmendment(x),id);
628 await page.locator('#pur-items-body .pur-qty').first().fill('3');
629 await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
630 await page.locator('#pur-save-btn').click();
631 await expect.poll(()=>remotePurchases(server).filter(x=>x.correctsPurchaseId===id&&x.accountingStatus==='posted').length,{timeout:20000}).toBe(1);
632 expect(remotePurchases(server).find(x=>x.id===id)).toEqual(initial);
633 const current=remotePurchases(server).find(x=>x.correctsPurchaseId===id);
634 expect(current.grandTotal).toBe(300);expect(current.number).not.toBe(initial.number);
635 const visible=await page.evaluate(()=>purchaseVisibleRecords().map(x=>({id:x.id,number:purchaseVisibleNumber(x)})));
636 expect(visible).toEqual([{id:current.id,number:'SAME-PURCHASE-001'}]);
637 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
638 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
639 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
640 await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('-اصلاح');
641 await page.evaluate(x=>purPrint(x),id);
642 await expect(page.locator('#finora-purchase-document-management-body')).toContainText('SAME-PURCHASE-001');
643 expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
644 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
645 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
646 await expect(page.locator('#finora-purchase-document-management-body tr')).toHaveCount(1);
647 });
648 function remotePayments(server){return [...server.records.values()].filter(x=>x.collection==='payments').map(x=>copy(x.data));}
649 async function createUiPayment(page,server,amount=1000,direction='inbound'){
650 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
651 await page.locator('#pay-direction').selectOption(direction);
652 await page.locator('#pay-contact').selectOption('QA_CONTACT');
653 await page.locator('#pay-method').selectOption('bank');
654 await page.locator('#pay-amount').fill(String(amount));
655 await page.locator('#pay-reference').fill('REF-ORIGINAL-001');
656 await page.evaluate(()=>commitSavePayment());
657 await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
658 await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
659 return remotePayments(server)[0].id;
660 }
661
662 test('treasury amendment in the same form preserves one record and same reference without on-open ledger writes',async({page})=>{
663 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
664 const firstId=await createUiPayment(page,server);
665 await page.waitForFunction(()=>!syncPending&&!syncRunning);
666 const first=copy(remotePayments(server)[0]);
667 const oldLines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy);
668 const beforeRpc=server.rpcCount;
669 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
670 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
671 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
672 await page.locator('#finora-treasury-document-management-body [data-doc-action="edit"]').click();
673 await expect(page.locator('#pay-amount')).toHaveValue('1,000');
674 await expect(page.locator('#pay-reference')).toHaveValue('REF-ORIGINAL-001');
675 await page.evaluate(()=>resetPaymentForm());
676 expect(server.rpcCount).toBe(beforeRpc);
677 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
678 expect(remotePayments(server)).toHaveLength(1);
679 await page.locator('#payments-ledger button').first().click();
680 await page.locator('#pay-amount').fill('1250');
681 await page.locator('#pay-note').fill('اصلاح مبلغ');
682 const beforeCorrectionRpc=server.rpcCount;
683 await page.locator('#pay-save').click();
684 await expect.poll(()=>remotePayments(server).filter(x=>x.correctsPaymentId===firstId&&x.accountingStatus==='posted').length,{timeout:18000}).toBe(1);
685 await page.waitForFunction(()=>!syncPending&&!syncRunning);
686 // Reversal + new source + repost must be a single server-side sync_records batch.
687 expect(server.rpcCount-beforeCorrectionRpc).toBe(1);
688 const original=remotePayments(server).find(p=>p.id===firstId);
689 expect(original).toEqual(first);
690 const amended=remotePayments(server).find(p=>p.correctsPaymentId===firstId);
691 expect(amended.amount).toBe(1250);
692 expect(amended.reference).toBe(first.reference);
693 expect(amended.journalVoucherId).toBeTruthy();
694 const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
695 expect(vouchers).toHaveLength(3);
696 expect(vouchers.find(x=>x.id===first.journalVoucherId).data.status).toBe('reversed');
697 expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy));
698 for(const v of vouchers){
699 const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
700 expect(lines.reduce((n,x)=>n+Number(x.data.debit||0),0)).toBe(lines.reduce((n,x)=>n+Number(x.data.credit||0),0));
701 }
702 expect(await page.evaluate(()=>paymentVisibleRecords().map(x=>x.id))).toEqual([amended.id]);
703 expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
704 await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
705 await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
706 await expect(page.locator('#finora-treasury-document-management-body')).toContainText('REF-ORIGINAL-001');
707 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
708 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
709 await expect(page.locator('#payments-ledger')).toContainText('۱٬۲۵۰');
710 await expect(page.locator('#payments-ledger')).toContainText('REF-ORIGINAL-001');
711 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
712 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
713 await expect(page.locator('#payments-ledger tr')).toHaveCount(1);
714 expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]);
715 });
716
717 test('treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history',async({page})=>{
718 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
719 const id=await createUiPayment(page,server,450,'outbound');
720 const noCheck=await page.evaluate(async id=>{
721 const p=getMyPayments().find(x=>x.id===id);
722 const saved=p.method;p.method='cheque';
723 try{await paymentAmendPosted(id,{direction:p.direction,contactId:p.contactId,companyId:p.companyId,
724 amount:400,method:'cash',invoiceId:'',invoiceType:'',reference:'x',note:'x'});return 'unsafe';}
725 catch(e){return String(e.message)}
726 finally{p.method=saved}
727 },id);
728 expect(noCheck).toMatch(/چک|تطبیق/);
729 const linked=await page.evaluate(async id=>{
730 const p=getMyPayments().find(x=>x.id===id);
731 p.invoiceType='purchase';p.invoiceId='QA_LINKED';
732 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
733 catch(e){return String(e.message)}
734 finally{p.invoiceType='';p.invoiceId=''}
735 },id);
736 expect(linked).toMatch(/تسویه|فاکتور|تطبیق/);
737 const locked=await page.evaluate(async id=>{
738 const fy=getMyFiscalYears()[0],old=fy.status;
739 fy.status='locked';
740 try{await paymentCancelPosted(id,'ابطال');return 'unsafe';}
741 catch(e){return String(e.message)}
742 finally{fy.status=old}
743 },id);
744 expect(locked).toMatch(/قفل|سال مالی/);
745 await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال اشتباه آزمایشی';});
746 await page.evaluate(id=>deletePayment(id),id);
747 await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(2);
748 expect(remotePayments(server)).toHaveLength(1);
749 expect(remotePayments(server)[0].id).toBe(id);
750 expect(await page.evaluate(id=>paymentPostingStatus(getMyPayments().find(x=>x.id===id)),id)).toBe('reversed');
751 expect(await page.evaluate(()=>paymentEffectiveRecords().length)).toBe(0);
752 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
753 await expect(page.locator('#payments-ledger')).toContainText('ابطال‌شده');
754 });
755
756 test('treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload',async({page})=>{
757 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
758 const id=await createUiPayment(page,server);
759 await page.waitForFunction(()=>!syncPending&&!syncRunning);
760 const before=copy(remotePayments(server)[0]);
761 const vouchersBefore=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id);
762 server.failNext=true;
763 await page.evaluate(id=>editPayment(id),id);
764 await page.locator('#pay-amount').fill('1800');
765 await page.locator('#pay-save').click();
766 await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('اصلاح کامل نشد'))),{timeout:8000}).toBe(true);
767 expect(server.failCount).toBe(1);
768 // The RPC did not persist any subset of the combined financial diff.
769 expect(remotePayments(server)).toEqual([before]);
770 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(vouchersBefore);
771 // After uncertain acknowledgment, do not call the amend API again blindly.
772 });
773 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
774 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
775 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());
776 await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
777 const id=remoteInvoices(server)[0].id;
778 const result=await page.evaluate(async x=>{try{await finalizeInvoiceDocument(x);return 'unexpected success'}catch(e){return String(e.message)}},id);
779 expect(result).toMatch(/حساب|کدینگ/);
780 expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
781 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
782 });
783
784
785 test('F2 validates formal invoice then saves a draft without posting any financial journal',async({page})=>{
786 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
787 await page.keyboard.press('F2');
788 expect(remoteInvoices(server)).toHaveLength(0);
789 expect(await page.evaluate(()=>window.__f0Alerts.at(-1))).toMatch(/حداقل یک کالا|خدمت معتبر/);
790 await fillInvoice(page,'F2-SAFE-DRAFT-001',2);
791 await page.keyboard.press('F2');
792 await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1);
793 const saved=remoteInvoices(server)[0];
794 expect(saved.number).toBe('F2-SAFE-DRAFT-001');
795 expect(saved.accountingStatus).toBe('draft');
796 expect(saved.documentStatus).toBe('draft');
797 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
798 await page.keyboard.press('F2');
799 expect(remoteInvoices(server)).toHaveLength(1);
800 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
801 });
802
803 async function pastePaymentAmount(page,text){
804 await page.context().grantPermissions(['clipboard-read','clipboard-write']);
805 await page.evaluate(value=>navigator.clipboard.writeText(value),text);
806 await page.locator('#pay-amount').focus();
807 await page.keyboard.press('ControlOrMeta+A');
808 await page.keyboard.press('ControlOrMeta+V');
809 }
810
811 for(const [script,typed,pasted] of [
812 ['Latin','1234567','1,234,567'],
813 ['Persian','۱۲۳۴۵۶۷','۱٬۲۳۴٬۵۶۷'],
814 ['Arabic','١٢٣٤٥٦٧','١٬٢٣٤٬٥٦٧'],
815 ]){
816 test(`treasury amount groups ${script} typing and clipboard paste without changing numeric saved value`,async({page})=>{
817 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
818 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
819 const amount=page.locator('#pay-amount');
820 await amount.pressSequentially(typed);
821 await expect(amount).toHaveValue('1,234,567');
822 await pastePaymentAmount(page,pasted);
823 await expect(amount).toHaveValue('1,234,567');
824 await page.locator('#pay-contact').selectOption('QA_CONTACT');
825 await page.locator('#pay-save').click();
826 await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
827 expect(remotePayments(server)[0].amount).toBe(1234567);
828 expect(remotePayments(server)[0].accountingStatus).toBe('posted');
829 });
830 }
831
832 test('treasury amount editing groups an existing value and preserves numeric correction payload and original history',async({page})=>{
833 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
834 const id=await createUiPayment(page,server,1234567.5);
835 const original=copy(remotePayments(server)[0]);
836 await page.locator('#payments-ledger button').first().click();
837 await expect(page.locator('#pay-amount')).toHaveValue('1,234,567.5');
838 await page.locator('#pay-save').click();
839 await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===id)?.amount,{timeout:18000}).toBe(1234567.5);
840 const unchanged=remotePayments(server).find(x=>x.correctsPaymentId===id);
841 expect(remotePayments(server).find(x=>x.id===id)).toEqual(original);
842 await page.locator('#payments-ledger button').first().click();
843 await pastePaymentAmount(page,'۲٬۳۴۵٬۶۷۸٫۵');
844 await expect(page.locator('#pay-amount')).toHaveValue('2,345,678.5');
845 await page.locator('#pay-save').click();
846 await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===unchanged.id)?.amount,{timeout:18000}).toBe(2345678.5);
847 expect(remotePayments(server).find(x=>x.id===id)).toEqual(original);
848 });
849
850 test('treasury amount keeps negative and invalid pasted input rejectable with no payment or journal write',async({page})=>{
851 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
852 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
853 await page.locator('#pay-contact').selectOption('QA_CONTACT');
854 for(const value of ['-1,234','−۱٬۲۳۴','1,234oops','1.2.3','Infinity','1e6','']){
855 await pastePaymentAmount(page,value);
856 await page.evaluate(()=>{window.__f0Alerts=[]});
857 await page.locator('#pay-save').click();
858 expect(await page.evaluate(()=>window.__f0Alerts.length),value).toBe(1);
859 expect(await page.evaluate(()=>datastore.payments.length)).toBe(0);
860 expect(await page.evaluate(()=>datastore.journalVouchers.length)).toBe(0);
861 }
862 expect(remotePayments(server)).toEqual([]);
863 });
864
865 test('treasury amount grouping keeps the insertion caret while editing digits in the middle',async({page})=>{
866 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
867 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
868 const amount=page.locator('#pay-amount');
869 await amount.pressSequentially('1234567');
870 await expect(amount).toHaveValue('1,234,567');
871 await amount.press('Home');await amount.press('ArrowRight');
872 await amount.pressSequentially('9');
873 await expect(amount).toHaveValue('19,234,567');
874 expect(await amount.evaluate(el=>el.selectionStart)).toBe(2);
875 });
876
877 for(const direction of ['outbound','inbound'])test('contact operational balance includes effective '+direction+' settlements once and isolates company',async({page})=>{
878 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
879 await page.evaluate(({direction,USER})=>{
880 const base={ownerUserId:USER,companyId:'QA_CO',contactId:'QA_CONTACT'};
881 datastore.companies.push({id:'QA_OTHER',ownerUserId:USER,name:'Other company'});
882 const voucher=(id,status='posted')=>({id,ownerUserId:USER,companyId:'QA_CO',status});
883 datastore.journalVouchers.push(voucher('J_TRADE'),voucher('J_OLD','reversed'),voucher('J_NEW'),voucher('J_CANCEL','reversed'),{...voucher('J_FOREIGN'),companyId:'QA_OTHER'});
884 const trade={...base,id:'TRADE',supplierId:'QA_CONTACT',kind:'formal',grandTotal:1000,paymentMethod:'credit',journalVoucherId:'J_TRADE',number:'TRADE-VALID'};
885 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}];
886 if(direction==='inbound')datastore.invoices.push({...trade,id:'PROFORMA',number:'PROFORMA-EXCLUDED',kind:'pre_invoice'});
887 datastore.payments=[
888 {...base,id:'ALLOC',direction,method:'bank',amount:200,invoiceType:direction==='outbound'?'purchase':'sale',invoiceId:'TRADE'},
889 {...base,id:'OLD',direction,method:'bank',amount:600,journalVoucherId:'J_OLD'},
890 {...base,id:'NEW',direction,method:'bank',amount:300,journalVoucherId:'J_NEW',correctsPaymentId:'OLD'},
891 {...base,id:'CANCEL',direction,method:'bank',amount:700,journalVoucherId:'J_CANCEL'},
892 {...base,id:'RAW-CHEQUE',direction,method:'cheque',amount:900},
893 {...base,id:'OTHER',direction,method:'bank',amount:9000,companyId:'QA_OTHER'},
894 {...base,id:'UNSCOPED',direction,method:'bank',amount:5555,companyId:''},
895 {...base,id:'BADALLOC',direction,method:'bank',amount:6666,invoiceType:direction==='outbound'?'purchase':'sale',invoiceId:'FOREIGN'}
896 ];
897 datastore.cheques=[{...base,id:'CHQ',direction,amount:9999,status:'registered',contactName:'خریدار آزمایشی'}];
898 window.__contactBefore=JSON.stringify([datastore.invoices,datastore.purchases,datastore.payments,datastore.journalVouchers,datastore.cheques]);
899 switchView('view-contacts');renderContacts();
900 },{direction,USER});
901 const row=page.locator('#contacts-ledger-table-body tr').first();
902 await expect(row.locator('td').nth(6)).toContainText('۵۰۰');
903 await row.locator('td').nth(6).locator('button').click();
904 const body=page.locator('#finora-drill-body');
905 await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'-500':'500');
906 await expect(body).not.toContainText('DRAFT-EXCLUDED');await expect(body).not.toContainText('FOREIGN-EXCLUDED');await expect(body).not.toContainText('PROFORMA-EXCLUDED');
907 expect(await page.evaluate(()=>JSON.stringify([datastore.invoices,datastore.purchases,datastore.payments,datastore.journalVouchers,datastore.cheques])===window.__contactBefore)).toBe(true);
908 await page.evaluate(({direction,USER})=>{
909 datastore.journalVouchers.push({id:'J_CHEQUE',ownerUserId:USER,companyId:'QA_CO',status:'posted'});
910 const scope={ownerUserId:USER,companyId:'QA_CO',contactId:'QA_CONTACT',direction,amount:100,journalVoucherId:'J_CHEQUE'};
911 datastore.payments.push({...scope,id:'PAY_CHEQUE',method:'cheque'});
912 datastore.cheques.push({...scope,id:'REGISTER_CHEQUE',status:'registered'});
913 renderContacts();openContactLedger('QA_CONTACT');
914 },{direction,USER});
915 await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'-400':'400');
916 await page.evaluate(()=>{closeFinoraDrill();getMySettings().default_company_id='QA_OTHER';renderContacts();openContactLedger('QA_CONTACT')});
917 await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'1000':'-1000');
918 await expect(body).toContainText(direction==='outbound'?'پیش‌پرداخت':'پیش‌دریافت');
919 });
920
921
922 test('contact operational balance reflects a saved unallocated supplier payment after reload',async({page})=>{
923 const server=fakeServer();
924 server.records.set('journalVouchers|J_PUR',{collection:'journalVouchers',id:'J_PUR',data:{companyId:'QA_CO',status:'posted'}});
925 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'}});
926 await installHarness(page,server);await authenticatedMockBrowser(page);
927 await page.evaluate(()=>{switchView('view-payments');renderPayments()});
928 await page.locator('#pay-direction').selectOption('outbound');
929 await page.locator('#pay-contact').selectOption('QA_CONTACT');
930 await page.locator('#pay-method').selectOption('bank');
931 await page.locator('#pay-amount').fill('450');
932 await page.locator('#pay-save').click();
933 await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
934 await page.evaluate(()=>{switchView('view-contacts');renderContacts();openContactLedger('QA_CONTACT')});
935 await expect(page.locator('[data-contact-net]')).toHaveAttribute('data-contact-net','-550');
936 await expect(page.locator('#finora-drill-body')).toContainText('پرداخت — بدون تخصیص');
937 await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
938 await page.evaluate(()=>openContactLedger('QA_CONTACT'));
939 await expect(page.locator('[data-contact-net]')).toHaveAttribute('data-contact-net','-550');
940 expect(remotePayments(server)).toHaveLength(1);
941 });