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