سامانه صدور فاکتور و حسابداری
hardening/c01-source-draft-20261129
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
| 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'&¤t&¤t.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'&¤t?.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 in the same form preserves one record and same reference without on-open ledger writes',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)[0]); |
| 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)).toHaveLength(1); |
| 696 | await page.locator('#payments-ledger button').first().click(); |
| 697 | await page.locator('#pay-amount').fill('1250'); |
| 698 | await page.locator('#pay-note').fill('اصلاح مبلغ'); |
| 699 | const beforeCorrectionRpc=server.rpcCount; |
| 700 | await page.locator('#pay-save').click(); |
| 701 | await expect.poll(()=>remotePayments(server).filter(x=>x.correctsPaymentId===firstId&&x.accountingStatus==='posted').length,{timeout:18000}).toBe(1); |
| 702 | await page.waitForFunction(()=>!syncPending&&!syncRunning); |
| 703 | // Reversal + new source + repost must be a single server-side sync_records batch. |
| 704 | expect(server.rpcCount-beforeCorrectionRpc).toBe(1); |
| 705 | const original=remotePayments(server).find(p=>p.id===firstId); |
| 706 | expect(original).toEqual(first); |
| 707 | const amended=remotePayments(server).find(p=>p.correctsPaymentId===firstId); |
| 708 | expect(amended.amount).toBe(1250); |
| 709 | expect(amended.reference).toBe(first.reference); |
| 710 | expect(amended.journalVoucherId).toBeTruthy(); |
| 711 | const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers'); |
| 712 | expect(vouchers).toHaveLength(3); |
| 713 | expect(vouchers.find(x=>x.id===first.journalVoucherId).data.status).toBe('reversed'); |
| 714 | expect(oldLines).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===first.journalVoucherId).map(copy)); |
| 715 | for(const v of vouchers){ |
| 716 | const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id); |
| 717 | expect(lines.reduce((n,x)=>n+Number(x.data.debit||0),0)).toBe(lines.reduce((n,x)=>n+Number(x.data.credit||0),0)); |
| 718 | } |
| 719 | expect(await page.evaluate(()=>paymentVisibleRecords().map(x=>x.id))).toEqual([amended.id]); |
| 720 | expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]); |
| 721 | await page.evaluate(()=>navigateShell('accounting','view-journal','documents')); |
| 722 | await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1); |
| 723 | await expect(page.locator('#finora-treasury-document-management-body')).toContainText('REF-ORIGINAL-001'); |
| 724 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 725 | await expect(page.locator('#payments-ledger tr')).toHaveCount(1); |
| 726 | await expect(page.locator('#payments-ledger')).toContainText('۱٬۲۵۰'); |
| 727 | await expect(page.locator('#payments-ledger')).toContainText('REF-ORIGINAL-001'); |
| 728 | await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page); |
| 729 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 730 | await expect(page.locator('#payments-ledger tr')).toHaveCount(1); |
| 731 | expect(await page.evaluate(()=>paymentEffectiveRecords().map(x=>x.amount))).toEqual([1250]); |
| 732 | }); |
| 733 | |
| 734 | test('treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history',async({page})=>{ |
| 735 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 736 | const id=await createUiPayment(page,server,450,'outbound'); |
| 737 | const noCheck=await page.evaluate(async id=>{ |
| 738 | const p=getMyPayments().find(x=>x.id===id); |
| 739 | const saved=p.method;p.method='cheque'; |
| 740 | try{await paymentAmendPosted(id,{direction:p.direction,contactId:p.contactId,companyId:p.companyId, |
| 741 | amount:400,method:'cash',invoiceId:'',invoiceType:'',reference:'x',note:'x'});return 'unsafe';} |
| 742 | catch(e){return String(e.message)} |
| 743 | finally{p.method=saved} |
| 744 | },id); |
| 745 | expect(noCheck).toMatch(/چک|تطبیق/); |
| 746 | const linked=await page.evaluate(async id=>{ |
| 747 | const p=getMyPayments().find(x=>x.id===id); |
| 748 | p.invoiceType='purchase';p.invoiceId='QA_LINKED'; |
| 749 | try{await paymentCancelPosted(id,'ابطال');return 'unsafe';} |
| 750 | catch(e){return String(e.message)} |
| 751 | finally{p.invoiceType='';p.invoiceId=''} |
| 752 | },id); |
| 753 | expect(linked).toMatch(/تسویه|فاکتور|تطبیق/); |
| 754 | const locked=await page.evaluate(async id=>{ |
| 755 | const fy=getMyFiscalYears()[0],old=fy.status; |
| 756 | fy.status='locked'; |
| 757 | try{await paymentCancelPosted(id,'ابطال');return 'unsafe';} |
| 758 | catch(e){return String(e.message)} |
| 759 | finally{fy.status=old} |
| 760 | },id); |
| 761 | expect(locked).toMatch(/قفل|سال مالی/); |
| 762 | await page.evaluate(()=>{window.confirm=()=>true;window.prompt=()=> 'ابطال اشتباه آزمایشی';}); |
| 763 | await page.evaluate(id=>deletePayment(id),id); |
| 764 | await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:15000}).toBe(2); |
| 765 | expect(remotePayments(server)).toHaveLength(1); |
| 766 | expect(remotePayments(server)[0].id).toBe(id); |
| 767 | expect(await page.evaluate(id=>paymentPostingStatus(getMyPayments().find(x=>x.id===id)),id)).toBe('reversed'); |
| 768 | expect(await page.evaluate(()=>paymentEffectiveRecords().length)).toBe(0); |
| 769 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 770 | await expect(page.locator('#payments-ledger')).toContainText('ابطالشده'); |
| 771 | }); |
| 772 | |
| 773 | test('treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload',async({page})=>{ |
| 774 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 775 | const id=await createUiPayment(page,server); |
| 776 | await page.waitForFunction(()=>!syncPending&&!syncRunning); |
| 777 | const before=copy(remotePayments(server)[0]); |
| 778 | const vouchersBefore=[...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id); |
| 779 | server.failNext=true; |
| 780 | await page.evaluate(id=>editPayment(id),id); |
| 781 | await page.locator('#pay-amount').fill('1800'); |
| 782 | await page.locator('#pay-save').click(); |
| 783 | await expect.poll(async()=>await page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('اصلاح کامل نشد'))),{timeout:8000}).toBe(true); |
| 784 | expect(server.failCount).toBe(1); |
| 785 | // The RPC did not persist any subset of the combined financial diff. |
| 786 | expect(remotePayments(server)).toEqual([before]); |
| 787 | expect([...server.records.values()].filter(x=>x.collection==='journalVouchers').map(x=>x.id)).toEqual(vouchersBefore); |
| 788 | // After uncertain acknowledgment, do not call the amend API again blindly. |
| 789 | }); |
| 790 | test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{ |
| 791 | const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page); |
| 792 | await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice()); |
| 793 | await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1); |
| 794 | const id=remoteInvoices(server)[0].id; |
| 795 | const result=await page.evaluate(async x=>{try{await finalizeInvoiceDocument(x);return 'unexpected success'}catch(e){return String(e.message)}},id); |
| 796 | expect(result).toMatch(/حساب|کدینگ/); |
| 797 | expect(remoteInvoices(server)[0].accountingStatus).toBe('draft'); |
| 798 | expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0); |
| 799 | }); |
| 800 | |
| 801 | |
| 802 | test('F2 validates formal invoice then saves a draft without posting any financial journal',async({page})=>{ |
| 803 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 804 | await page.keyboard.press('F2'); |
| 805 | expect(remoteInvoices(server)).toHaveLength(0); |
| 806 | expect(await page.evaluate(()=>window.__f0Alerts.at(-1))).toMatch(/حداقل یک کالا|خدمت معتبر/); |
| 807 | await fillInvoice(page,'F2-SAFE-DRAFT-001',2); |
| 808 | await page.keyboard.press('F2'); |
| 809 | await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1); |
| 810 | const saved=remoteInvoices(server)[0]; |
| 811 | expect(saved.number).toBe('F2-SAFE-DRAFT-001'); |
| 812 | expect(saved.accountingStatus).toBe('draft'); |
| 813 | expect(saved.documentStatus).toBe('draft'); |
| 814 | expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0); |
| 815 | await page.keyboard.press('F2'); |
| 816 | expect(remoteInvoices(server)).toHaveLength(1); |
| 817 | expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0); |
| 818 | }); |
| 819 | |
| 820 | async function pastePaymentAmount(page,text){ |
| 821 | await page.context().grantPermissions(['clipboard-read','clipboard-write']); |
| 822 | await page.evaluate(value=>navigator.clipboard.writeText(value),text); |
| 823 | await page.locator('#pay-amount').focus(); |
| 824 | await page.keyboard.press('ControlOrMeta+A'); |
| 825 | await page.keyboard.press('ControlOrMeta+V'); |
| 826 | } |
| 827 | |
| 828 | for(const [script,typed,pasted] of [ |
| 829 | ['Latin','1234567','1,234,567'], |
| 830 | ['Persian','۱۲۳۴۵۶۷','۱٬۲۳۴٬۵۶۷'], |
| 831 | ['Arabic','١٢٣٤٥٦٧','١٬٢٣٤٬٥٦٧'], |
| 832 | ]){ |
| 833 | test(`treasury amount groups ${script} typing and clipboard paste without changing numeric saved value`,async({page})=>{ |
| 834 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 835 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 836 | const amount=page.locator('#pay-amount'); |
| 837 | await amount.pressSequentially(typed); |
| 838 | await expect(amount).toHaveValue('1,234,567'); |
| 839 | await pastePaymentAmount(page,pasted); |
| 840 | await expect(amount).toHaveValue('1,234,567'); |
| 841 | await page.locator('#pay-contact').selectOption('QA_CONTACT'); |
| 842 | await page.locator('#pay-save').click(); |
| 843 | await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1); |
| 844 | expect(remotePayments(server)[0].amount).toBe(1234567); |
| 845 | expect(remotePayments(server)[0].accountingStatus).toBe('posted'); |
| 846 | }); |
| 847 | } |
| 848 | |
| 849 | test('treasury amount editing groups an existing value and preserves numeric correction payload and original history',async({page})=>{ |
| 850 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 851 | const id=await createUiPayment(page,server,1234567.5); |
| 852 | const original=copy(remotePayments(server)[0]); |
| 853 | await page.locator('#payments-ledger button').first().click(); |
| 854 | await expect(page.locator('#pay-amount')).toHaveValue('1,234,567.5'); |
| 855 | await page.locator('#pay-save').click(); |
| 856 | await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===id)?.amount,{timeout:18000}).toBe(1234567.5); |
| 857 | const unchanged=remotePayments(server).find(x=>x.correctsPaymentId===id); |
| 858 | expect(remotePayments(server).find(x=>x.id===id)).toEqual(original); |
| 859 | await page.locator('#payments-ledger button').first().click(); |
| 860 | await pastePaymentAmount(page,'۲٬۳۴۵٬۶۷۸٫۵'); |
| 861 | await expect(page.locator('#pay-amount')).toHaveValue('2,345,678.5'); |
| 862 | await page.locator('#pay-save').click(); |
| 863 | await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===unchanged.id)?.amount,{timeout:18000}).toBe(2345678.5); |
| 864 | expect(remotePayments(server).find(x=>x.id===id)).toEqual(original); |
| 865 | }); |
| 866 | |
| 867 | test('treasury amount keeps negative and invalid pasted input rejectable with no payment or journal write',async({page})=>{ |
| 868 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 869 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 870 | await page.locator('#pay-contact').selectOption('QA_CONTACT'); |
| 871 | for(const value of ['-1,234','−۱٬۲۳۴','1,234oops','1.2.3','Infinity','1e6','']){ |
| 872 | await pastePaymentAmount(page,value); |
| 873 | await page.evaluate(()=>{window.__f0Alerts=[]}); |
| 874 | await page.locator('#pay-save').click(); |
| 875 | expect(await page.evaluate(()=>window.__f0Alerts.length),value).toBe(1); |
| 876 | expect(await page.evaluate(()=>datastore.payments.length)).toBe(0); |
| 877 | expect(await page.evaluate(()=>datastore.journalVouchers.length)).toBe(0); |
| 878 | } |
| 879 | expect(remotePayments(server)).toEqual([]); |
| 880 | }); |
| 881 | |
| 882 | test('treasury amount grouping keeps the insertion caret while editing digits in the middle',async({page})=>{ |
| 883 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 884 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 885 | const amount=page.locator('#pay-amount'); |
| 886 | await amount.pressSequentially('1234567'); |
| 887 | await expect(amount).toHaveValue('1,234,567'); |
| 888 | await amount.press('Home');await amount.press('ArrowRight'); |
| 889 | await amount.pressSequentially('9'); |
| 890 | await expect(amount).toHaveValue('19,234,567'); |
| 891 | expect(await amount.evaluate(el=>el.selectionStart)).toBe(2); |
| 892 | }); |
| 893 | |
| 894 | for(const direction of ['outbound','inbound'])test('contact operational balance includes effective '+direction+' settlements once and isolates company',async({page})=>{ |
| 895 | const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page); |
| 896 | await page.evaluate(({direction,USER})=>{ |
| 897 | const base={ownerUserId:USER,companyId:'QA_CO',contactId:'QA_CONTACT'}; |
| 898 | datastore.companies.push({id:'QA_OTHER',ownerUserId:USER,name:'Other company'}); |
| 899 | const voucher=(id,status='posted')=>({id,ownerUserId:USER,companyId:'QA_CO',status}); |
| 900 | datastore.journalVouchers.push(voucher('J_TRADE'),voucher('J_OLD','reversed'),voucher('J_NEW'),voucher('J_CANCEL','reversed'),{...voucher('J_FOREIGN'),companyId:'QA_OTHER'}); |
| 901 | const trade={...base,id:'TRADE',supplierId:'QA_CONTACT',kind:'formal',grandTotal:1000,paymentMethod:'credit',journalVoucherId:'J_TRADE',number:'TRADE-VALID'}; |
| 902 | 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}]; |
| 903 | if(direction==='inbound')datastore.invoices.push({...trade,id:'PROFORMA',number:'PROFORMA-EXCLUDED',kind:'pre_invoice'}); |
| 904 | datastore.payments=[ |
| 905 | {...base,id:'ALLOC',direction,method:'bank',amount:200,invoiceType:direction==='outbound'?'purchase':'sale',invoiceId:'TRADE'}, |
| 906 | {...base,id:'OLD',direction,method:'bank',amount:600,journalVoucherId:'J_OLD'}, |
| 907 | {...base,id:'NEW',direction,method:'bank',amount:300,journalVoucherId:'J_NEW',correctsPaymentId:'OLD'}, |
| 908 | {...base,id:'CANCEL',direction,method:'bank',amount:700,journalVoucherId:'J_CANCEL'}, |
| 909 | {...base,id:'RAW-CHEQUE',direction,method:'cheque',amount:900}, |
| 910 | {...base,id:'OTHER',direction,method:'bank',amount:9000,companyId:'QA_OTHER'}, |
| 911 | {...base,id:'UNSCOPED',direction,method:'bank',amount:5555,companyId:''}, |
| 912 | {...base,id:'BADALLOC',direction,method:'bank',amount:6666,invoiceType:direction==='outbound'?'purchase':'sale',invoiceId:'FOREIGN'} |
| 913 | ]; |
| 914 | datastore.cheques=[{...base,id:'CHQ',direction,amount:9999,status:'registered',contactName:'خریدار آزمایشی'}]; |
| 915 | window.__contactBefore=JSON.stringify([datastore.invoices,datastore.purchases,datastore.payments,datastore.journalVouchers,datastore.cheques]); |
| 916 | switchView('view-contacts');renderContacts(); |
| 917 | },{direction,USER}); |
| 918 | const row=page.locator('#contacts-ledger-table-body tr').first(); |
| 919 | await expect(row.locator('td').nth(6)).toContainText('۵۰۰'); |
| 920 | await row.locator('td').nth(6).locator('button').click(); |
| 921 | const body=page.locator('#finora-drill-body'); |
| 922 | await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'-500':'500'); |
| 923 | await expect(body).not.toContainText('DRAFT-EXCLUDED');await expect(body).not.toContainText('FOREIGN-EXCLUDED');await expect(body).not.toContainText('PROFORMA-EXCLUDED'); |
| 924 | expect(await page.evaluate(()=>JSON.stringify([datastore.invoices,datastore.purchases,datastore.payments,datastore.journalVouchers,datastore.cheques])===window.__contactBefore)).toBe(true); |
| 925 | await page.evaluate(({direction,USER})=>{ |
| 926 | datastore.journalVouchers.push({id:'J_CHEQUE',ownerUserId:USER,companyId:'QA_CO',status:'posted'}); |
| 927 | const scope={ownerUserId:USER,companyId:'QA_CO',contactId:'QA_CONTACT',direction,amount:100,journalVoucherId:'J_CHEQUE'}; |
| 928 | datastore.payments.push({...scope,id:'PAY_CHEQUE',method:'cheque'}); |
| 929 | datastore.cheques.push({...scope,id:'REGISTER_CHEQUE',status:'registered'}); |
| 930 | renderContacts();openContactLedger('QA_CONTACT'); |
| 931 | },{direction,USER}); |
| 932 | await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'-400':'400'); |
| 933 | await page.evaluate(()=>{closeFinoraDrill();getMySettings().default_company_id='QA_OTHER';renderContacts();openContactLedger('QA_CONTACT')}); |
| 934 | await expect(body.locator('[data-contact-net]')).toHaveAttribute('data-contact-net',direction==='outbound'?'1000':'-1000'); |
| 935 | await expect(body).toContainText(direction==='outbound'?'پیشپرداخت':'پیشدریافت'); |
| 936 | }); |
| 937 | |
| 938 | |
| 939 | test('contact operational balance reflects a saved unallocated supplier payment after reload',async({page})=>{ |
| 940 | const server=fakeServer(); |
| 941 | server.records.set('journalVouchers|J_PUR',{collection:'journalVouchers',id:'J_PUR',data:{companyId:'QA_CO',status:'posted'}}); |
| 942 | 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'}}); |
| 943 | await installHarness(page,server);await authenticatedMockBrowser(page); |
| 944 | await page.evaluate(()=>{switchView('view-payments');renderPayments()}); |
| 945 | await page.locator('#pay-direction').selectOption('outbound'); |
| 946 | await page.locator('#pay-contact').selectOption('QA_CONTACT'); |
| 947 | await page.locator('#pay-method').selectOption('bank'); |
| 948 | await page.locator('#pay-amount').fill('450'); |
| 949 | await page.locator('#pay-save').click(); |
| 950 | await expect.poll(()=>remotePayments(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted'); |
| 951 | await page.evaluate(()=>{switchView('view-contacts');renderContacts();openContactLedger('QA_CONTACT')}); |
| 952 | await expect(page.locator('[data-contact-net]')).toHaveAttribute('data-contact-net','-550'); |
| 953 | await expect(page.locator('#finora-drill-body')).toContainText('پرداخت — بدون تخصیص'); |
| 954 | await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page); |
| 955 | await page.evaluate(()=>openContactLedger('QA_CONTACT')); |
| 956 | await expect(page.locator('[data-contact-net]')).toHaveAttribute('data-contact-net','-550'); |
| 957 | expect(remotePayments(server)).toHaveLength(1); |
| 958 | }); |
| 959 | |
| 960 | |
| 961 | // Issue #229 / ADR0216: executable expected-RED acceptance contracts. |
| 962 | // test.fail is a transparent temporary xfail, NOT a product PASS. Remove |
| 963 | // annotations only after the linked-draft lifecycle works end-to-end. |
| 964 | test('P0 #229 expected RED: purchase Save must not auto-post',async({page})=>{ |
| 965 | const server=fakeServer(); |
| 966 | await installHarness(page,server); |
| 967 | await authenticatedMockBrowser(page); |
| 968 | await page.evaluate(()=>{ |
| 969 | switchView('view-purchases'); |
| 970 | refreshAllSurfaces(); |
| 971 | const supplier=document.getElementById('pur-supplier'); |
| 972 | if(!supplier?.querySelector('option[value="QA_CONTACT"]')) |
| 973 | throw Error('QA supplier option missing: fixture setup failure, NOT accounting RED'); |
| 974 | supplier.value='QA_CONTACT'; |
| 975 | document.getElementById('pur-number').value='QA-ADR216-PUR-NO-AUTOPOST'; |
| 976 | document.getElementById('pur-date').value='1405/07/19'; |
| 977 | document.getElementById('pur-payment-method').value='credit'; |
| 978 | const row=document.querySelector('#pur-items-body tr'); |
| 979 | if(!row?.querySelector('.pur-prod option[value="QA_PROD"]')) |
| 980 | throw Error('QA product option missing: fixture setup failure, NOT accounting RED'); |
| 981 | row.querySelector('.pur-prod').value='QA_PROD'; |
| 982 | row.querySelector('.pur-qty').value='2'; |
| 983 | row.querySelector('.pur-price').value='100'; |
| 984 | purRecalc(); |
| 985 | }); |
| 986 | await page.locator('#pur-save-btn').click(); |
| 987 | await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='purchases').length, |
| 988 | {timeout:15000}).toBe(1); |
| 989 | await expect.poll(()=>page.evaluate(()=>!document.getElementById('pur-save-btn').disabled), |
| 990 | {timeout:15000}).toBe(true); |
| 991 | const purchase=[...server.records.values()].find(x=>x.collection==='purchases'); |
| 992 | const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers'); |
| 993 | const observed={ |
| 994 | documentStatus:purchase?.data.documentStatus, |
| 995 | accountingStatus:purchase?.data.accountingStatus, |
| 996 | hasLinkedDraft:!!purchase?.data.journalVoucherId&&vouchers.some(v=> |
| 997 | v.id===purchase.data.journalVoucherId&&v.data.status==='draft'), |
| 998 | postedVouchers:vouchers.filter(v=>v.data.status==='posted').length, |
| 999 | automaticPostCalls:server.autoPostCount||0 |
| 1000 | }; |
| 1001 | // CURRENT: posted, posted, no linked draft, one posted voucher, one autopost. |
| 1002 | // REQUIRED: business source + linked draft; no final number/posted voucher. |
| 1003 | assertKnownRedOrFixed(observed,{ |
| 1004 | documentStatus:'posted',accountingStatus:'posted',hasLinkedDraft:false, |
| 1005 | postedVouchers:1,automaticPostCalls:1 |
| 1006 | },{ |
| 1007 | documentStatus:'draft',accountingStatus:'draft',hasLinkedDraft:true, |
| 1008 | postedVouchers:0,automaticPostCalls:0 |
| 1009 | },'purchase-initial-save'); |
| 1010 | test.fail(true,'#229: Save invokes automatic posting instead of persisted linked draft'); |
| 1011 | expect(observed).toEqual({ |
| 1012 | documentStatus:'draft',accountingStatus:'draft',hasLinkedDraft:true, |
| 1013 | postedVouchers:0,automaticPostCalls:0 |
| 1014 | }); |
| 1015 | }); |
| 1016 | |
| 1017 | |
| 1018 | test('P0 #229 linked journal draft stays draft for both sales and purchases',async({page})=>{ |
| 1019 | const server=fakeServer(); |
| 1020 | await installHarness(page,server); |
| 1021 | await authenticatedMockBrowser(page); |
| 1022 | const observed=await page.evaluate(()=>{ |
| 1023 | const ownerUserId=currentUser.id,companyId='QA_CO'; |
| 1024 | const sale={id:'QA_SALE_LINK_DRAFT',ownerUserId,companyId,kind:'formal', |
| 1025 | journalVoucherId:'QA_SALE_JV_DRAFT',accountingStatus:'draft',documentStatus:'draft'}; |
| 1026 | const purchase={id:'QA_PUR_LINK_DRAFT',ownerUserId,companyId, |
| 1027 | journalVoucherId:'QA_PUR_JV_DRAFT',accountingStatus:'draft',documentStatus:'draft'}; |
| 1028 | const conflictingSale={...sale,id:'QA_SALE_LINK_CONFLICT', |
| 1029 | journalVoucherId:'QA_SALE_JV_CONFLICT',accountingStatus:'posted'}; |
| 1030 | const conflictingPurchase={...purchase,id:'QA_PUR_LINK_CONFLICT', |
| 1031 | journalVoucherId:'QA_PUR_JV_CONFLICT',documentStatus:'posted'}; |
| 1032 | const danglingSale={...sale,id:'QA_SALE_LINK_DANGLING',journalVoucherId:'QA_NOT_FOUND_SALE'}; |
| 1033 | const danglingPurchase={...purchase,id:'QA_PUR_LINK_DANGLING',journalVoucherId:'QA_NOT_FOUND_PUR'}; |
| 1034 | const partiallyReversedSale={...sale,id:'QA_SALE_PARTIAL',journalVoucherId:'QA_SALE_JV_PARTIAL', |
| 1035 | accountingStatus:'posted',documentStatus:'posted'}; |
| 1036 | const partiallyReversedPurchase={...purchase,id:'QA_PUR_PARTIAL',journalVoucherId:'QA_PUR_JV_PARTIAL', |
| 1037 | accountingStatus:'posted',documentStatus:'posted'}; |
| 1038 | datastore.invoices.push(sale,conflictingSale,danglingSale,partiallyReversedSale); |
| 1039 | datastore.purchases.push(purchase,conflictingPurchase,danglingPurchase,partiallyReversedPurchase); |
| 1040 | datastore.journalVouchers.push( |
| 1041 | {id:'QA_SALE_JV_DRAFT',ownerUserId,companyId,status:'draft', |
| 1042 | sourceType:'sale',sourceId:sale.id}, |
| 1043 | {id:'QA_PUR_JV_DRAFT',ownerUserId,companyId,status:'draft', |
| 1044 | sourceType:'purchase',sourceId:purchase.id}, |
| 1045 | {id:'QA_SALE_JV_CONFLICT',ownerUserId,companyId,status:'draft', |
| 1046 | sourceType:'sale',sourceId:conflictingSale.id}, |
| 1047 | {id:'QA_PUR_JV_CONFLICT',ownerUserId,companyId,status:'draft', |
| 1048 | sourceType:'purchase',sourceId:conflictingPurchase.id}, |
| 1049 | {id:'QA_SALE_JV_PARTIAL',ownerUserId,companyId,status:'posted', |
| 1050 | sourceType:'sale',sourceId:partiallyReversedSale.id}, |
| 1051 | {id:'QA_PUR_JV_PARTIAL',ownerUserId,companyId,status:'posted', |
| 1052 | sourceType:'purchase',sourceId:partiallyReversedPurchase.id} |
| 1053 | ); |
| 1054 | // Effective status can be partial while the immutable original remains posted. |
| 1055 | jeRpcEffectiveStatuses.set('QA_SALE_JV_PARTIAL','partially_reversed'); |
| 1056 | jeRpcEffectiveStatuses.set('QA_PUR_JV_PARTIAL','partially_reversed'); |
| 1057 | return { |
| 1058 | sale:invoiceDocumentStatus(sale), |
| 1059 | purchase:purchaseDocumentStatus(purchase), |
| 1060 | conflictingSale:invoiceDocumentStatus(conflictingSale), |
| 1061 | conflictingPurchase:purchaseDocumentStatus(conflictingPurchase), |
| 1062 | danglingSale:invoiceDocumentStatus(danglingSale), |
| 1063 | danglingPurchase:purchaseDocumentStatus(danglingPurchase), |
| 1064 | partiallyReversedSale:invoiceDocumentStatus(partiallyReversedSale), |
| 1065 | partiallyReversedPurchase:purchaseDocumentStatus(partiallyReversedPurchase), |
| 1066 | saleDirectEditPermitted:invoiceMayEdit(sale), |
| 1067 | purchaseDirectEditPermitted:(()=>{ |
| 1068 | const before=document.getElementById('pur-edit-id')?.value||''; |
| 1069 | const prevAlert=window.alert; |
| 1070 | let warning=''; |
| 1071 | window.alert=message=>{warning=String(message)}; |
| 1072 | try{purEdit(purchase.id)}finally{window.alert=prevAlert} |
| 1073 | return (document.getElementById('pur-edit-id')?.value||'')!==before|| |
| 1074 | !warning.includes('سند موقت متصل'); |
| 1075 | })(), |
| 1076 | voucherStates:getMyJournalVouchers().filter(v=>v.id.endsWith('_JV_DRAFT')).map(v=>v.status) |
| 1077 | }; |
| 1078 | }); |
| 1079 | expect(observed).toEqual({ |
| 1080 | sale:'draft',purchase:'draft', |
| 1081 | conflictingSale:'legacy_review',conflictingPurchase:'legacy_review', |
| 1082 | danglingSale:'legacy_review',danglingPurchase:'legacy_review', |
| 1083 | partiallyReversedSale:'posted',partiallyReversedPurchase:'posted', |
| 1084 | saleDirectEditPermitted:false,purchaseDirectEditPermitted:false, |
| 1085 | voucherStates:['draft','draft'] |
| 1086 | }); |
| 1087 | }); |
| 1088 | |
| 1089 | |
| 1090 | test('P0 #229 linked journal drafts do not advertise unsupported source-only edit or finalize buttons',async({page})=>{ |
| 1091 | const server=fakeServer(); |
| 1092 | await installHarness(page,server); |
| 1093 | await authenticatedMockBrowser(page); |
| 1094 | const observed=await page.evaluate(()=>{ |
| 1095 | const ownerUserId=currentUser.id,companyId='QA_CO'; |
| 1096 | const sale={id:'QA_SALE_LINKED_UI',ownerUserId,companyId,number:'QA-SALE-LINKED-UI', |
| 1097 | companyName:'QA Company',contactId:'QA_CONTACT',contactName:'QA Customer', |
| 1098 | date:'1405/07/19',kind:'formal',kindLabel:'رسمی',items:[],grandTotal:170, |
| 1099 | journalVoucherId:'QA_SALE_JV_LINKED_UI',accountingStatus:'draft',documentStatus:'draft'}; |
| 1100 | const purchase={id:'QA_PUR_LINKED_UI',ownerUserId,companyId,number:'QA-PUR-LINKED-UI', |
| 1101 | supplierId:'QA_CONTACT',supplierName:'QA Supplier',date:'1405/07/19', |
| 1102 | items:[],grandTotal:170,journalVoucherId:'QA_PUR_JV_LINKED_UI', |
| 1103 | accountingStatus:'draft',documentStatus:'draft'}; |
| 1104 | datastore.invoices.push(sale); |
| 1105 | datastore.purchases.push(purchase); |
| 1106 | datastore.journalVouchers.push( |
| 1107 | {id:sale.journalVoucherId,ownerUserId,companyId,status:'draft',sourceType:'sale',sourceId:sale.id}, |
| 1108 | {id:purchase.journalVoucherId,ownerUserId,companyId,status:'draft',sourceType:'purchase',sourceId:purchase.id} |
| 1109 | ); |
| 1110 | switchView('view-purchases'); |
| 1111 | refreshAllSurfaces(); |
| 1112 | renderInvoices(); |
| 1113 | const purRow=[...document.querySelectorAll('#pur-list-body tr')].find(tr=>tr.textContent.includes(purchase.number)); |
| 1114 | const saleRow=[...document.querySelectorAll('#invoice-archive-table-body tr')].find(tr=>tr.textContent.includes(sale.number)); |
| 1115 | if(!purRow||!saleRow)throw Error('Linked draft source rows missing from browser DOM; fixture failure'); |
| 1116 | return { |
| 1117 | purchaseStatus:purchaseDocumentStatus(purchase), |
| 1118 | saleStatus:invoiceDocumentStatus(sale), |
| 1119 | purchaseMessage:purRow.textContent.includes('سند موقت متصل'), |
| 1120 | purchaseActions:[...purRow.querySelectorAll('button')].map(b=>b.getAttribute('onclick')||''), |
| 1121 | saleActions:[...saleRow.querySelectorAll('button')].map(b=>b.getAttribute('onclick')||'') |
| 1122 | }; |
| 1123 | }); |
| 1124 | expect(observed.purchaseStatus).toBe('draft'); |
| 1125 | expect(observed.saleStatus).toBe('draft'); |
| 1126 | expect(observed.purchaseMessage).toBe(true); |
| 1127 | expect(observed.purchaseActions).toEqual([expect.stringContaining('purPrint(')]); |
| 1128 | expect(observed.saleActions).toContainEqual(expect.stringContaining('renderAndPrintDirect(')); |
| 1129 | expect(observed.saleActions).not.toContainEqual(expect.stringContaining('editInvoice(')); |
| 1130 | expect(observed.saleActions).not.toContainEqual(expect.stringContaining('beginInvoiceAmendment(')); |
| 1131 | }); |
| 1132 | |
| 1133 | |
| 1134 | test('P0 #229 linked draft direct actions deny before confirm, sync or autopost',async({page})=>{ |
| 1135 | const server=fakeServer(); |
| 1136 | await installHarness(page,server); |
| 1137 | await authenticatedMockBrowser(page); |
| 1138 | const observed=await page.evaluate(async()=>{ |
| 1139 | const ownerUserId=currentUser.id,companyId='QA_CO'; |
| 1140 | const sale={id:'QA_SALE_LINK_ACTION',ownerUserId,companyId,kind:'formal', |
| 1141 | kindLabel:'رسمی',companyName:'QA Company',number:'QA-SALE-LINK-ACTION', |
| 1142 | contactId:'QA_CONTACT',contactName:'QA Customer',date:'1405/07/19', |
| 1143 | items:[],grandTotal:170,journalVoucherId:'QA_SALE_JV_LINK_ACTION', |
| 1144 | documentStatus:'draft',accountingStatus:'draft'}; |
| 1145 | const purchase={id:'QA_PUR_LINK_ACTION',ownerUserId,companyId, |
| 1146 | number:'QA-PUR-LINK-ACTION',supplierId:'QA_CONTACT',supplierName:'QA Supplier', |
| 1147 | date:'1405/07/19',items:[],grandTotal:170, |
| 1148 | journalVoucherId:'QA_PUR_JV_LINK_ACTION',documentStatus:'draft',accountingStatus:'draft'}; |
| 1149 | datastore.invoices.push(sale);datastore.purchases.push(purchase); |
| 1150 | datastore.journalVouchers.push( |
| 1151 | {id:sale.journalVoucherId,ownerUserId,companyId,status:'draft', |
| 1152 | sourceType:'sale',sourceId:sale.id}, |
| 1153 | {id:purchase.journalVoucherId,ownerUserId,companyId,status:'draft', |
| 1154 | sourceType:'purchase',sourceId:purchase.id} |
| 1155 | ); |
| 1156 | const snapshot=()=>JSON.stringify({ |
| 1157 | sale:datastore.invoices.find(x=>x.id===sale.id), |
| 1158 | purchase:datastore.purchases.find(x=>x.id===purchase.id), |
| 1159 | journals:datastore.journalVouchers.filter(x=>x.id.endsWith('_JV_LINK_ACTION'))}); |
| 1160 | const before=snapshot(),alerts=[]; |
| 1161 | let confirmCalls=0,directDenial=''; |
| 1162 | const previousConfirm=window.confirm,previousAlert=window.alert; |
| 1163 | window.confirm=()=>{confirmCalls++;return true;}; |
| 1164 | window.alert=value=>alerts.push(String(value)); |
| 1165 | try{ |
| 1166 | try{await finalizeInvoiceDocument(sale.id)}catch(e){directDenial=String(e.message);} |
| 1167 | await finalizeInvoiceDocumentUi(sale.id); |
| 1168 | await purFinalizeUi(purchase.id); |
| 1169 | purDeleteDraftUi(purchase.id); |
| 1170 | }finally{window.confirm=previousConfirm;window.alert=previousAlert;} |
| 1171 | switchView('view-purchases');refreshAllSurfaces();renderInvoices(); |
| 1172 | const saleRow=[...document.querySelectorAll('#invoice-archive-table-body tr')] |
| 1173 | .find(tr=>tr.textContent.includes(sale.number)); |
| 1174 | const purchaseRow=[...document.querySelectorAll('#pur-list-body tr')] |
| 1175 | .find(tr=>tr.textContent.includes(purchase.number)); |
| 1176 | if(!saleRow||!purchaseRow)throw Error('Linked draft action register row missing'); |
| 1177 | return {confirmCalls,directDenial,alerts,unchanged:before===snapshot(), |
| 1178 | saleLabel:saleRow.textContent,purchaseLabel:purchaseRow.textContent}; |
| 1179 | }); |
| 1180 | expect(observed.confirmCalls).toBe(0); |
| 1181 | expect(observed.directDenial).toContain('سند موقت متصل'); |
| 1182 | expect(observed.alerts.filter(x=>x.includes('قطعیسازی مستقل'))).toHaveLength(2); |
| 1183 | expect(observed.alerts.some(x=>x.includes('حذف سند موقت متصل'))).toBe(true); |
| 1184 | expect(observed.unchanged).toBe(true); |
| 1185 | expect(observed.saleLabel).toContain('پیشنویس متصل'); |
| 1186 | expect(observed.saleLabel).not.toContain('پیشنویس قابل ویرایش'); |
| 1187 | expect(observed.purchaseLabel).toContain('موقت متصل'); |
| 1188 | expect(observed.purchaseLabel).not.toContain('موقت قابل اصلاح'); |
| 1189 | expect(server.autoPostCount||0).toBe(0); |
| 1190 | }); |
| 1191 | |
| 1192 | |
| 1193 | test('P0 #229 expected RED: formal sale Save must persist linked journal draft without posting',async({page})=>{ |
| 1194 | const server=fakeServer(); |
| 1195 | await installHarness(page,server); |
| 1196 | await authenticatedMockBrowser(page); |
| 1197 | await fillInvoice(page,'QA-ADR216-SALE-LINK-DRAFT',2); |
| 1198 | await page.evaluate(()=>commitSaveInvoice()); |
| 1199 | await expect.poll(()=>remoteInvoices(server).length,{timeout:14000}).toBe(1); |
| 1200 | // A fixture failure is not allowed to masquerade as the expected accounting RED. |
| 1201 | await page.waitForFunction(()=>!syncPending&&!syncRunning); |
| 1202 | const source=remoteInvoices(server)[0]; |
| 1203 | if(source.number!=='QA-ADR216-SALE-LINK-DRAFT'||source.kind!=='formal'|| |
| 1204 | source.companyId!=='QA_CO'||source.grandTotal!==3000) |
| 1205 | throw Error('QA formal sale Save fixture invalid; NOT expected-red: '+JSON.stringify(source)); |
| 1206 | const vouchers=[...server.records.values()].filter(row=>row.collection==='journalVouchers'); |
| 1207 | const linked=vouchers.find(row=>row.id===source.journalVoucherId); |
| 1208 | const lines=[...server.records.values()].filter(row=> |
| 1209 | row.collection==='journalLines'&&row.data.voucherId===source.journalVoucherId); |
| 1210 | const debit=lines.reduce((sum,row)=>sum+Number(row.data.debit||0),0); |
| 1211 | const credit=lines.reduce((sum,row)=>sum+Number(row.data.credit||0),0); |
| 1212 | const observed={ |
| 1213 | documentStatus:source.documentStatus, |
| 1214 | accountingStatus:source.accountingStatus, |
| 1215 | hasLinkedDraft:!!linked&&linked.data.status==='draft', |
| 1216 | linkedSourceMatches:!!linked&&linked.data.sourceType==='sale'&&linked.data.sourceId===source.id, |
| 1217 | draftHasNoFinalNumber:!!linked&&!linked.data.number, |
| 1218 | draftHasBalancedLines:lines.length>=2&&debit===credit&&debit===source.grandTotal, |
| 1219 | postedVouchers:vouchers.filter(row=>row.data.status==='posted').length, |
| 1220 | automaticPostCalls:server.autoPostCount||0 |
| 1221 | }; |
| 1222 | // CURRENT: source-only sale draft, no linked journal, no autopost. |
| 1223 | // REQUIRED ADR216: atomic source + linked journal draft, balanced lines, no final number. |
| 1224 | assertKnownRedOrFixed(observed,{ |
| 1225 | documentStatus:'draft',accountingStatus:'draft', |
| 1226 | hasLinkedDraft:false,linkedSourceMatches:false, |
| 1227 | draftHasNoFinalNumber:false,draftHasBalancedLines:false, |
| 1228 | postedVouchers:0,automaticPostCalls:0 |
| 1229 | },{ |
| 1230 | documentStatus:'draft',accountingStatus:'draft', |
| 1231 | hasLinkedDraft:true,linkedSourceMatches:true, |
| 1232 | draftHasNoFinalNumber:true,draftHasBalancedLines:true, |
| 1233 | postedVouchers:0,automaticPostCalls:0 |
| 1234 | },'sale-initial-save'); |
| 1235 | test.fail(true,'#229 / ADR216: formal sale Save still lacks server-persisted linked journal draft'); |
| 1236 | expect(observed).toEqual({ |
| 1237 | documentStatus:'draft',accountingStatus:'draft', |
| 1238 | hasLinkedDraft:true,linkedSourceMatches:true, |
| 1239 | draftHasNoFinalNumber:true,draftHasBalancedLines:true, |
| 1240 | postedVouchers:0,automaticPostCalls:0 |
| 1241 | }); |
| 1242 | }); |
| 1243 | |
| 1244 | |
| 1245 | test('P0 #229 expected RED: posted purchase correction Save must remain linked accounting draft',async({page})=>{ |
| 1246 | const server=fakeServer(); |
| 1247 | await installHarness(page,server); |
| 1248 | await authenticatedMockBrowser(page); |
| 1249 | const id=await createPostedPurchase(page,server,'QA-ADR216-CORRECTION-SAVE',2); |
| 1250 | const original=remotePurchases(server).find(p=>p.id===id); |
| 1251 | const originalVoucher=[...server.records.values()].find(r=>r.collection==='journalVouchers'&&r.id===original.journalVoucherId); |
| 1252 | if(original?.accountingStatus!=='posted'||originalVoucher?.data.status!=='posted') |
| 1253 | throw Error('Original posted purchase fixture invalid; NOT the expected correction Save RED'); |
| 1254 | const originalSourceFingerprint=copy(original); |
| 1255 | const originalVoucherFingerprint=copy(originalVoucher); |
| 1256 | const originalLines=[...server.records.values()].filter(r=>r.collection==='journalLines'&& |
| 1257 | r.data.voucherId===original.journalVoucherId).map(copy); |
| 1258 | await page.evaluate(x=>beginPurchaseAmendment(x),id); |
| 1259 | await expect(page.locator('#pur-edit-id')).toHaveValue(id); |
| 1260 | await page.locator('#pur-items-body .pur-qty').first().fill('3'); |
| 1261 | await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input'); |
| 1262 | await page.locator('#pur-save-btn').click(); |
| 1263 | // Await the actual completed Save path, not its intermediate locally inserted draft. |
| 1264 | await expect(page.locator('#pur-edit-id')).toHaveValue('',{timeout:22000}); |
| 1265 | await expect.poll(()=>remotePurchases(server).filter(p=>p.correctsPurchaseId===id).length, |
| 1266 | {timeout:15000}).toBe(1); |
| 1267 | await page.waitForFunction(()=>!syncPending&&!syncRunning); |
| 1268 | const corrected=remotePurchases(server).find(p=>p.correctsPurchaseId===id); |
| 1269 | if(corrected?.grandTotal!==300||corrected?.companyId!=='QA_CO'|| |
| 1270 | corrected?.correctionOriginalNumber!==original.number) |
| 1271 | throw Error('Correction Save fixture invalid; NOT the expected product RED: '+JSON.stringify(corrected)); |
| 1272 | // A correction must never rewrite or destroy the original posted source/journal. |
| 1273 | expect(remotePurchases(server).find(p=>p.id===id)).toEqual(originalSourceFingerprint); |
| 1274 | expect([...server.records.values()].find(r=>r.collection==='journalVouchers'&& |
| 1275 | r.id===original.journalVoucherId)).toEqual(originalVoucherFingerprint); |
| 1276 | expect([...server.records.values()].filter(r=>r.collection==='journalLines'&& |
| 1277 | r.data.voucherId===original.journalVoucherId)).toEqual(originalLines); |
| 1278 | const vouchers=[...server.records.values()].filter(r=>r.collection==='journalVouchers'); |
| 1279 | const linked=vouchers.find(r=>r.id===corrected.journalVoucherId); |
| 1280 | const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&& |
| 1281 | r.data.voucherId===corrected.journalVoucherId); |
| 1282 | const debit=lines.reduce((sum,r)=>sum+Number(r.data.debit||0),0); |
| 1283 | const credit=lines.reduce((sum,r)=>sum+Number(r.data.credit||0),0); |
| 1284 | const observed={ |
| 1285 | documentStatus:corrected.documentStatus, |
| 1286 | accountingStatus:corrected.accountingStatus, |
| 1287 | hasSourceLinkedJournalDraft:!!linked&&linked.data.status==='draft', |
| 1288 | journalPointsToCorrection:!!linked&&linked.data.sourceType==='purchase'&& |
| 1289 | linked.data.sourceId===corrected.id, |
| 1290 | balancedDraftLines:lines.length>=2&&debit===credit&&debit===300, |
| 1291 | correctionAlreadyPosted:vouchers.some(r=>r.data.status==='posted'&& |
| 1292 | r.data.sourceType==='purchase'&&r.data.sourceId===corrected.id), |
| 1293 | originalReversalCount:server.reverseCount |
| 1294 | }; |
| 1295 | // CURRENT: purchaseSaveSeamless directly calls finalizePurchasePilotDraft(newId) |
| 1296 | // on Save, bypassing independent accounting approval for the correction. |
| 1297 | assertKnownRedOrFixed(observed,{ |
| 1298 | documentStatus:'posted',accountingStatus:'posted', |
| 1299 | hasSourceLinkedJournalDraft:false,journalPointsToCorrection:true, |
| 1300 | balancedDraftLines:true,correctionAlreadyPosted:true,originalReversalCount:1 |
| 1301 | },{ |
| 1302 | documentStatus:'draft',accountingStatus:'draft', |
| 1303 | hasSourceLinkedJournalDraft:true,journalPointsToCorrection:true, |
| 1304 | balancedDraftLines:true,correctionAlreadyPosted:false,originalReversalCount:1 |
| 1305 | },'purchase-correction-save'); |
| 1306 | test.fail(true,'#229 / ADR216: correcting posted purchase Save auto-finalizes the new source'); |
| 1307 | expect(observed).toEqual({ |
| 1308 | documentStatus:'draft',accountingStatus:'draft', |
| 1309 | hasSourceLinkedJournalDraft:true,journalPointsToCorrection:true, |
| 1310 | balancedDraftLines:true,correctionAlreadyPosted:false,originalReversalCount:1 |
| 1311 | }); |
| 1312 | }); |