سامانه صدور فاکتور و حسابداری
integration/finora-execution-20261124
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 | import assert from 'node:assert/strict'; |
| 2 | import {spawnSync} from 'node:child_process'; |
| 3 | |
| 4 | // Issue #229 — EXPECTED CONTRACT RED, never a product pass. |
| 5 | // Real Auth JWT / PostgREST against the *disposable local* WP2 stack only. |
| 6 | // psql/service-role are strictly fixture and read-back tools, never the posting caller. |
| 7 | const api=String(process.env.API_URL||'').replace(/\/$/,''); |
| 8 | const anon=process.env.ANON_KEY,service=process.env.SERVICE_ROLE_KEY,db=process.env.DB_URL; |
| 9 | for(const [key,val] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db})){ |
| 10 | assert.ok(val,'missing disposable WP2 setting '+key); |
| 11 | } |
| 12 | for(const [label,url] of [['API_URL',api],['DB_URL',db]]){ |
| 13 | const host=new URL(url).hostname.toLowerCase(); |
| 14 | assert.ok(['localhost','127.0.0.1','::1','[::1]'].includes(host), |
| 15 | label+' MUST refer to localhost: refusing any nonlocal financial operation'); |
| 16 | } |
| 17 | const suffix=Date.now()+'_'+crypto.randomUUID().slice(0,8); |
| 18 | const q=value=>"'"+String(value).replaceAll("'","''")+"'"; |
| 19 | function sql(statement,scalar=false){ |
| 20 | const args=[db,'-X','-v','ON_ERROR_STOP=1']; |
| 21 | if(scalar)args.push('-At'); |
| 22 | args.push('-c',statement); |
| 23 | const result=spawnSync('psql',args,{encoding:'utf8'}); |
| 24 | assert.equal(result.status,0,'disposable fixture SQL failed; check local-stack logs'); |
| 25 | return (result.stdout||'').trim(); |
| 26 | } |
| 27 | function rec(org,owner,collection,id,data){ |
| 28 | return '('+[q(org),q(owner),q(collection),q(id),q(JSON.stringify(data))+'::jsonb'].join(',')+')'; |
| 29 | } |
| 30 | async function addUser(label){ |
| 31 | const email='finora-issue229-'+label+'-'+suffix+'@example.test'; |
| 32 | const password='QA-'+crypto.randomUUID()+'-Aa9!'; |
| 33 | const response=await fetch(api+'/auth/v1/admin/users',{ |
| 34 | method:'POST', |
| 35 | headers:{apikey:service,Authorization:'Bearer '+service,'Content-Type':'application/json'}, |
| 36 | body:JSON.stringify({email,password,email_confirm:true,user_metadata:{username:'qa229'+label+Date.now()}}) |
| 37 | }); |
| 38 | const user=await response.json(); |
| 39 | assert.equal(response.status,200,'disposable Auth setup failed for '+label); |
| 40 | assert.ok(user.id,'new Auth user missing ID'); |
| 41 | return {id:user.id,email,password}; |
| 42 | } |
| 43 | async function login(user){ |
| 44 | const response=await fetch(api+'/auth/v1/token?grant_type=password',{ |
| 45 | method:'POST',headers:{apikey:anon,'Content-Type':'application/json'}, |
| 46 | body:JSON.stringify({email:user.email,password:user.password}) |
| 47 | }); |
| 48 | const body=await response.json(); |
| 49 | assert.equal(response.status,200,'Auth user login failed'); |
| 50 | assert.equal(body.user?.id,user.id,'JWT identity mismatch'); |
| 51 | assert.ok(body.access_token,'Auth access token missing'); |
| 52 | return body.access_token; |
| 53 | } |
| 54 | async function rpc(name,args,jwt){ |
| 55 | const response=await fetch(api+'/rest/v1/rpc/'+name,{ |
| 56 | method:'POST',headers:{apikey:anon,Authorization:'Bearer '+jwt,'Content-Type':'application/json'}, |
| 57 | body:JSON.stringify(args) |
| 58 | }); |
| 59 | const raw=await response.text(); |
| 60 | let body; |
| 61 | try{body=JSON.parse(raw)}catch{body=raw} |
| 62 | return {status:response.status,body}; |
| 63 | } |
| 64 | const owner=await addUser('owner'),seller=await addUser('seller'); |
| 65 | const org=crypto.randomUUID(),co='QA229_CO_'+suffix,fy='QA229_FY_'+suffix; |
| 66 | const cash='QA229_CASH_'+suffix,revenue='QA229_REV_'+suffix; |
| 67 | const sourceId='QA229_SALE_'+suffix,voucherId='QA229_JV_'+suffix; |
| 68 | sql('INSERT INTO public.organizations(id,owner_user_id,name) VALUES ('+ |
| 69 | q(org)+','+q(owner.id)+','+q('QA229 disposable organization')+');'); |
| 70 | sql('UPDATE public.licenses SET organization_id='+q(org)+ |
| 71 | ",plan='lifetime',status='active',max_users=2,ends_at=date '2099-01-01',modules=array['full_suite']::text[] WHERE user_id="+q(owner.id)+';'); |
| 72 | sql('INSERT INTO public.organization_members(organization_id,user_id,status,is_owner) VALUES ('+ |
| 73 | q(org)+','+q(owner.id)+",'active',true),("+q(org)+','+q(seller.id)+",'active',false);"); |
| 74 | sql('INSERT INTO public.member_module_permissions(organization_id,member_id,module_key,capabilities,scope_type) '+ |
| 75 | 'SELECT '+q(org)+",id,'commerce',array['read','create']::text[],'organization' "+ |
| 76 | 'FROM public.organization_members WHERE organization_id='+q(org)+' AND user_id='+q(seller.id)+';'); |
| 77 | const records=[ |
| 78 | rec(org,owner.id,'companies',co,{name:'QA229 disposable company'}), |
| 79 | rec(org,owner.id,'fiscalYears',fy,{companyId:co,startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}), |
| 80 | rec(org,owner.id,'accounts',cash,{companyId:co,systemRole:'cash_default',accountType:'asset', |
| 81 | normalBalance:'debit',level:'detail',postingAllowed:true,active:true,code:'1101',name:'QA229 cash'}), |
| 82 | rec(org,owner.id,'accounts',revenue,{companyId:co,systemRole:'revenue_default',accountType:'revenue', |
| 83 | normalBalance:'credit',level:'detail',postingAllowed:true,active:true,code:'4101',name:'QA229 revenue'}) |
| 84 | ]; |
| 85 | sql('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+records.join(',')+';'); |
| 86 | sql('INSERT INTO private.finora_phase1a_account_role_snapshots ('+ |
| 87 | 'organization_id,company_id,version,assignments,account_fields,approved,approved_by,reason) '+ |
| 88 | 'SELECT '+q(org)+','+q(co)+",1,jsonb_build_object('cash_default',"+q(cash)+ |
| 89 | ",'revenue_default',"+q(revenue)+"),jsonb_build_object('cash_default',"+ |
| 90 | 'private.finora_phase1a_account_fields(c.data),'+ |
| 91 | "'revenue_default',private.finora_phase1a_account_fields(r.data)),true,"+q(owner.id)+ |
| 92 | ",'Issue229 disposable snapshot' FROM public.records c JOIN public.records r ON "+ |
| 93 | 'r.organization_id=c.organization_id AND r.collection='+q('accounts')+ |
| 94 | ' AND r.id='+q(revenue)+' WHERE c.organization_id='+q(org)+ |
| 95 | ' AND c.collection='+q('accounts')+' AND c.id='+q(cash)+';'); |
| 96 | const data={companyId:co,date:'1405/01/01',kind:'formal',description:'QA229 restricted seller sale', |
| 97 | reference:sourceId,accountingVersion:1,accountingStatus:'draft',documentStatus:'draft', |
| 98 | paymentMethod:'cash',currencyCode:'IRR',items:[{prodId:'QA_PRODUCT',qty:1,price:125,lineTotal:125}], |
| 99 | subtotal:125,discountType:'fixed',discountInput:0,discount:0, |
| 100 | vatMode:'none',vatType:'percent',vatRate:0,vat:0,grandTotal:125}; |
| 101 | sql('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+ |
| 102 | rec(org,seller.id,'invoices',sourceId,data)+';'); |
| 103 | const noExtraRoles=sql('SELECT count(*) FROM public.organization_member_roles mr '+ |
| 104 | 'JOIN public.organization_members m ON m.id=mr.member_id WHERE m.organization_id='+ |
| 105 | q(org)+' AND m.user_id='+q(seller.id)+' AND mr.active;',true); |
| 106 | assert.equal(noExtraRoles,'0','seller unexpectedly inherits an assigned reusable role'); |
| 107 | // Verify the REAL capability predicate with seller JWT subject as evaluated by auth.uid(). |
| 108 | // No application privilege is inferred merely from the synthetic grant row. |
| 109 | const privilegeLog=sql('BEGIN; SELECT set_config('+q('request.jwt.claim.sub')+','+ |
| 110 | q(seller.id)+',true); SELECT '+ |
| 111 | "CASE WHEN private.has_org_capability("+q(org)+",'commerce','create') THEN 't' ELSE 'f' END || '|' || "+ |
| 112 | "CASE WHEN private.has_org_capability("+q(org)+",'accounting','approve') THEN 't' ELSE 'f' END; ROLLBACK;",true); |
| 113 | assert.ok(privilegeLog.split(/\r?\n/).includes('t|f'), |
| 114 | 'fixture does not have commerce:create without accounting:approve; NOT a product RED'); |
| 115 | const jwt=await login(seller); |
| 116 | const args={p_organization_id:org,p_voucher_id:voucherId, |
| 117 | p_source_collection:'invoices',p_source_id:sourceId, |
| 118 | p_header:{companyId:co,fiscalYearId:fy,date:'1405/01/01',voucherType:'sale', |
| 119 | sourceType:'sale',sourceId,sourceVersion:'1',description:'QA229 approval boundary'}, |
| 120 | p_lines:[]}; |
| 121 | const result=await rpc('finora_journal_autopost',args,jwt); |
| 122 | // The existing code is known to bypass separate accounting approval. |
| 123 | // A 403/42501 here is an UNEXPECTED PASS of the new authorization boundary; |
| 124 | // review/update this expected-RED test to assert the complete fixed draft-first flow. |
| 125 | if(result.status!==200){ |
| 126 | throw Error('Approval bypass NOT reproduced: JWT RPC status '+result.status+ |
| 127 | '; inspect whether product has been repaired or fixture/setup failed. Do NOT count as expected RED.'); |
| 128 | } |
| 129 | assert.equal(result.body?.voucher?.status,'posted', |
| 130 | 'existing code must have actually POSTED, otherwise no authorization-bypass evidence'); |
| 131 | assert.equal(result.body?.voucher?.id,voucherId, |
| 132 | 'posted voucher identity mismatch; do not count a fake/partial response'); |
| 133 | const journal=sql("SELECT data->>'status' FROM public.records WHERE organization_id="+q(org)+ |
| 134 | " AND collection='journalVouchers' AND id="+q(voucherId)+';',true); |
| 135 | const source=sql("SELECT (data->>'documentStatus') || '|' || (data->>'journalVoucherId') "+ |
| 136 | 'FROM public.records WHERE organization_id='+q(org)+" AND collection='invoices' AND id="+q(sourceId)+';',true); |
| 137 | const lines=sql("SELECT count(*) || '|' || coalesce(sum((data->>'debit')::numeric),0) || '|' || "+ |
| 138 | "coalesce(sum((data->>'credit')::numeric),0) FROM public.records WHERE organization_id="+q(org)+ |
| 139 | " AND collection='journalLines' AND data->>'voucherId'="+q(voucherId)+';',true); |
| 140 | const audit=sql('SELECT count(*) FROM private.finora_phase1a_journal_audit WHERE organization_id='+ |
| 141 | q(org)+' AND voucher_id='+q(voucherId)+' AND actor_id='+q(seller.id)+'::uuid;',true); |
| 142 | const counter=sql('SELECT last_no FROM private.finora_phase1a_journal_counters WHERE organization_id='+ |
| 143 | q(org)+' AND fiscal_year_id='+q(fy)+';',true); |
| 144 | assert.equal(journal,'posted','JWT returned posted but journal status is not persisted'); |
| 145 | assert.equal(source,'posted|'+voucherId,'source-to-posted linkage not persisted'); |
| 146 | assert.equal(lines,'2|125|125','unexpected ledger line count or imbalance'); |
| 147 | assert.ok(Number(audit)>=2,'Auth-user actor audit missing from persisted posting'); |
| 148 | assert.equal(counter,'1','unexpected posting counter state'); |
| 149 | console.log('FINORA_ISSUE229_APPROVAL_EXPECTED_RED: real non-owner commerce:create JWT without accounting:approve POSTED sale via legacy autopost; persisted source, voucher, balanced lines, actor audit and counter verified in disposable local Supabase. This is a CONFIRMED PRODUCT DEFECT, NOT a fix or authorization PASS.'); |
| 150 | |
| 151 | |
| 152 | |
| 153 | // Issue #229 purchase-specific parity: same *non-owner* user and original |
| 154 | // commerce:create-only grant. This is another EXPECTED PRODUCT RED on the |
| 155 | // existing code, NOT a proposed purchase posting implementation. |
| 156 | const purchaseCost='QA229_PURCHASE_COST_'+suffix,payable='QA229_PAYABLE_'+suffix; |
| 157 | const purchaseSource='QA229_PURCHASE_'+suffix,purchaseVoucher='QA229_PURCHASE_JV_'+suffix; |
| 158 | const expenseAccount={companyId:co,systemRole:'purchase_default',accountType:'expense', |
| 159 | normalBalance:'debit',level:'detail',postingAllowed:true,active:true,code:'5101', |
| 160 | name:'QA229 synthetic purchase expense'}; |
| 161 | const payableAccount={companyId:co,systemRole:'payable_control',accountType:'liability', |
| 162 | normalBalance:'credit',level:'detail',postingAllowed:true,active:true,code:'2101', |
| 163 | name:'QA229 synthetic accounts payable'}; |
| 164 | sql('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+ |
| 165 | [rec(org,owner.id,'accounts',purchaseCost,expenseAccount), |
| 166 | rec(org,owner.id,'accounts',payable,payableAccount)].join(',')+';'); |
| 167 | // Preserve approved role-snapshot v1, extending it via immutable v2 for |
| 168 | // legitimate expense/payable source mapping (same proven local QA pattern). |
| 169 | sql('INSERT INTO private.finora_phase1a_account_role_snapshots ('+ |
| 170 | 'organization_id,company_id,version,assignments,account_fields,approved,approved_by,reason) '+ |
| 171 | 'SELECT '+q(org)+','+q(co)+',2,'+ |
| 172 | 'old.assignments || jsonb_build_object('+ |
| 173 | "'purchase_default',"+q(purchaseCost)+",'payable_control',"+q(payable)+'),'+ |
| 174 | 'old.account_fields || jsonb_build_object('+ |
| 175 | "'purchase_default',private.finora_phase1a_account_fields(p.data),"+ |
| 176 | "'payable_control',private.finora_phase1a_account_fields(a.data)),true,"+ |
| 177 | q(owner.id)+",'Issue229 disposable purchase v2' "+ |
| 178 | 'FROM private.finora_phase1a_account_role_snapshots old '+ |
| 179 | 'JOIN public.records p ON p.organization_id=old.organization_id AND p.collection='+ |
| 180 | q('accounts')+' AND p.id='+q(purchaseCost)+' '+ |
| 181 | 'JOIN public.records a ON a.organization_id=old.organization_id AND a.collection='+ |
| 182 | q('accounts')+' AND a.id='+q(payable)+' '+ |
| 183 | 'WHERE old.organization_id='+q(org)+' AND old.company_id='+q(co)+ |
| 184 | ' AND old.version=1 AND old.approved=true;'); |
| 185 | assert.equal(sql('SELECT count(*) FROM private.finora_phase1a_account_role_snapshots '+ |
| 186 | 'WHERE organization_id='+q(org)+' AND company_id='+q(co)+' AND approved;',true),'2', |
| 187 | 'purchase fixture must append role snapshot, not overwrite history'); |
| 188 | const purchaseAmount=170; |
| 189 | const purchaseData={...data,reference:purchaseSource,grandTotal:purchaseAmount, |
| 190 | subtotal:purchaseAmount,description:'QA229 restricted JWT credit purchase', |
| 191 | paymentMethod:'credit',items:[{prodId:'QA_PRODUCT',qty:1, |
| 192 | price:purchaseAmount,lineTotal:purchaseAmount}]}; |
| 193 | sql('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+ |
| 194 | rec(org,seller.id,'purchases',purchaseSource,purchaseData)+';'); |
| 195 | // Assert the account never acquired accounting approve while expanding |
| 196 | // *account-mapping metadata* (which must not affect member permissions). |
| 197 | assert.equal(sql('SELECT count(*) FROM public.member_module_permissions p '+ |
| 198 | 'JOIN public.organization_members m ON m.id=p.member_id '+ |
| 199 | 'WHERE m.organization_id='+q(org)+' AND m.user_id='+q(seller.id)+ |
| 200 | " AND (p.module_key IN ('accounting','full_suite')) AND 'approve'=ANY(p.capabilities);",true),'0', |
| 201 | 'synthetic restricted seller gained accounting approval unexpectedly'); |
| 202 | const purchaseRequest={p_organization_id:org,p_voucher_id:purchaseVoucher, |
| 203 | p_source_collection:'purchases',p_source_id:purchaseSource, |
| 204 | p_header:{companyId:co,fiscalYearId:fy,date:'1405/01/01', |
| 205 | voucherType:'purchase',sourceType:'purchase',sourceId:purchaseSource, |
| 206 | sourceVersion:'1',description:'QA229 restricted purchase approval boundary'}, |
| 207 | p_lines:[]}; |
| 208 | const purchaseResponse=await rpc('finora_journal_autopost',purchaseRequest,jwt); |
| 209 | if(purchaseResponse.status!==200){ |
| 210 | throw Error('Purchase approval bypass NOT reproduced: JWT RPC status '+ |
| 211 | purchaseResponse.status+'; distinguish an owner product fix from QA setup failure.'); |
| 212 | } |
| 213 | assert.equal(purchaseResponse.body?.voucher?.status,'posted', |
| 214 | 'purchase JWT returned without an actually posted voucher'); |
| 215 | assert.equal(purchaseResponse.body?.voucher?.id,purchaseVoucher, |
| 216 | 'purchase JWT generated wrong voucher identity'); |
| 217 | assert.equal(String(purchaseResponse.body?.voucher?.number),'2', |
| 218 | 'purchase did not consume exactly the next final number'); |
| 219 | const purchaseJournal=sql("SELECT data->>'status' FROM public.records WHERE organization_id="+q(org)+ |
| 220 | " AND collection='journalVouchers' AND id="+q(purchaseVoucher)+';',true); |
| 221 | const purchaseSourceProjection=sql("SELECT (data->>'accountingStatus') || '|' || "+ |
| 222 | "(data->>'documentStatus') || '|' || (data->>'journalVoucherId') "+ |
| 223 | 'FROM public.records WHERE organization_id='+q(org)+ |
| 224 | " AND collection='purchases' AND id="+q(purchaseSource)+';',true); |
| 225 | const sourceVoucherCount=sql('SELECT count(*) FROM public.records WHERE organization_id='+q(org)+ |
| 226 | " AND collection='journalVouchers' AND data->>'sourceType'='purchase' AND data->>'sourceId'="+ |
| 227 | q(purchaseSource)+';',true); |
| 228 | const voucherFilter='organization_id='+q(org)+ |
| 229 | " AND collection='journalLines' AND data->>'voucherId'="+q(purchaseVoucher); |
| 230 | const purchaseBalances=sql("SELECT count(*) || '|' || coalesce(sum((data->>'debit')::numeric),0) "+ |
| 231 | "|| '|' || coalesce(sum((data->>'credit')::numeric),0) FROM public.records WHERE "+ |
| 232 | voucherFilter+';',true); |
| 233 | const expenseEntries=sql("SELECT count(*) || '|' || coalesce(sum((data->>'debit')::numeric),0) "+ |
| 234 | "|| '|' || coalesce(sum((data->>'credit')::numeric),0) FROM public.records WHERE "+ |
| 235 | voucherFilter+" AND data->>'accountId'="+q(purchaseCost)+';',true); |
| 236 | const payableEntries=sql("SELECT count(*) || '|' || coalesce(sum((data->>'debit')::numeric),0) "+ |
| 237 | "|| '|' || coalesce(sum((data->>'credit')::numeric),0) FROM public.records WHERE "+ |
| 238 | voucherFilter+" AND data->>'accountId'="+q(payable)+';',true); |
| 239 | const purchaseAudit=sql('SELECT count(*) FROM private.finora_phase1a_journal_audit '+ |
| 240 | 'WHERE organization_id='+q(org)+' AND voucher_id='+q(purchaseVoucher)+ |
| 241 | ' AND actor_id='+q(seller.id)+'::uuid;',true); |
| 242 | const purchaseCounter=sql('SELECT last_no FROM private.finora_phase1a_journal_counters '+ |
| 243 | 'WHERE organization_id='+q(org)+' AND fiscal_year_id='+q(fy)+';',true); |
| 244 | assert.equal(purchaseJournal,'posted','purchase journal was not durably posted'); |
| 245 | assert.equal(purchaseSourceProjection,'posted|posted|'+purchaseVoucher, |
| 246 | 'purchase source document/accounting status and voucher link inconsistent'); |
| 247 | assert.equal(sourceVoucherCount,'1','source linked to duplicate purchased vouchers'); |
| 248 | assert.equal(purchaseBalances,'2|170|170','purchase journal not exactly two balanced lines'); |
| 249 | assert.equal(expenseEntries,'1|170|0','purchase expense debit mapping incorrect'); |
| 250 | assert.equal(payableEntries,'1|0|170','purchase payable credit mapping incorrect'); |
| 251 | assert.ok(Number(purchaseAudit)>=2,'purchase posting audit not attributed to restricted JWT'); |
| 252 | assert.equal(purchaseCounter,'2','unexpected second final-number counter'); |
| 253 | console.log('FINORA_ISSUE229_PURCHASE_APPROVAL_EXPECTED_RED: real non-owner commerce:create JWT without accounting:approve POSTED credit purchase via legacy autopost; persisted purchase source and unique posted voucher, debit expense 170, credit payable 170, actor audit and server numbering verified. CONFIRMED PRODUCT DEFECT, NOT FIX.'); |