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

hardening/wp1-ledger-integrity-20261102
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
mjs 180 lines 14.9 KB
Raw
1 import fs from 'node:fs';
2 import vm from 'node:vm';
3 import assert from 'node:assert/strict';
4 import test from 'node:test';
5
6 // Real synchronization code; only the network, clock and page boundary are simulated.
7 // Removing targeted publication or the context/dirty guards must break these tests.
8 function fixture(){
9 const rows=[
10 {collection:'companies',id:'C',version:4,data:{id:'C',name:'company'}},
11 {collection:'journalVouchers',id:'V',version:2,data:{id:'V',companyId:'C',status:'draft',description:'old'}},
12 {collection:'journalLines',id:'L',version:2,data:{id:'L',companyId:'C',voucherId:'V',debit:100,credit:0}},
13 {collection:'journalLineDimensions',id:'D',version:2,data:{id:'D',companyId:'C',voucherId:'V',journalLineId:'L',dimensionValueId:'X'}},
14 {collection:'journalVouchers',id:'OTHER',version:1,data:{id:'OTHER',companyId:'C',status:'draft'}}
15 ];
16 const graph={organization_id:'O',voucher_id:'V',effective_status:'posted',records:[
17 {collection:'journalVouchers',id:'V',version:3,data:{id:'V',companyId:'C',status:'posted',description:'server'}},
18 {collection:'journalLines',id:'L2',version:1,data:{id:'L2',companyId:'C',voucherId:'V',debit:200,credit:0}}
19 ]};
20 let view={companyId:'C',formId:'F',editRevision:0},nextTimer=0;
21 const timers=new Map(),calls=[];
22 const state={rows,graph,hook:null,error:null};
23 const c={console:{error(){},warn(){}},Map,Set,JSON,Promise,Number,String,Array,Date,Math,
24 setTimeout(fn,ms){const id=++nextTimer;timers.set(id,{fn,ms});return id;},clearTimeout(id){timers.delete(id);},
25 currentUser:{id:'U',organizationId:'O'},COLLS:['companies','journalVouchers','journalLines','journalLineDimensions'],ID_RE:/^[A-Za-z0-9_-]+$/,
26 document:{getElementById:()=>null,addEventListener(){}},canWrite:()=>true,requireWrite:()=>true,refreshAllSurfaces(){},alert(){},finoraAbortableRead:async p=>p};
27 c.window=c;c.addEventListener=()=>{};
28 c.sb={from(){const q={select(){return q;},order(){return q;},range:async()=>({error:null,data:structuredClone(state.rows)})};return q;},
29 async rpc(name,args){calls.push({name,args});if(state.hook)await state.hook(name,args);
30 if(name==='finora_journal_read_graph')return {error:state.error,data:structuredClone(state.graph)};
31 if(name==='finora_journal_get_guard_mode')return {error:null,data:'audit'};
32 return {error:null,data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:args.p_deletes}};
33 }};
34 vm.createContext(c);vm.runInContext(fs.readFileSync(process.env.FINORA_SYNC_SOURCE||'js/sync.js','utf8'),c);
35 const run=s=>vm.runInContext(s,c),capture=(id='V')=>c.finoraCaptureJournalRefresh(id,()=>view);
36 return {c,state,calls,timers,run,capture,setView:v=>{view={...view,...v};},snapshot:()=>run('JSON.stringify({datastore,snap:[...syncSnap],versions:[...versionSnap]})')};
37 }
38 const tick=()=>new Promise(r=>setImmediate(r));
39 function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}
40 async function prepared(){const f=fixture();await f.c.pullAll();return f;}
41 async function refresh(f){return f.c.finoraRefreshJournalGraph(f.capture());}
42
43 test('targeted refresh replaces only its graph and acknowledges versions without syncing display status',async()=>{
44 const f=await prepared();f.state.graph.effective_status='partially_reversed';
45 const result=await refresh(f);
46 assert.equal(result.effectiveStatus,'partially_reversed');
47 assert.equal(f.run("datastore.journalVouchers.find(r=>r.id==='V').status"),'posted');
48 assert.equal(f.run('datastore.journalLines[0].id'),'L2');
49 assert.equal(f.run('datastore.journalLineDimensions.length'),0);
50 assert.equal(f.run("versionSnap.get('journalVouchers|V')"),3);
51 assert.equal(f.run("syncSnap.has('journalLines|L')"),false);
52 assert.equal(f.run("versionSnap.has('journalLineDimensions|D')"),false);
53 assert.equal(f.run('computeDiff().up.length+computeDiff().del.length'),0);
54 assert.deepEqual(f.calls.map(x=>x.name),['finora_journal_read_graph']);
55 });
56 test('unrelated dirty objects, deletion, pending state and save timer survive graph publication',async()=>{
57 const f=await prepared();f.run("datastore.companies[0].name='unsaved';datastore.journalVouchers=datastore.journalVouchers.filter(r=>r.id!=='OTHER');saveDatastore();globalThis.keepCompany=datastore.companies;globalThis.keepObject=datastore.companies[0];globalThis.keepTimer=syncTimer");
58 await refresh(f);
59 assert.equal(f.run('datastore.companies===keepCompany&&datastore.companies[0]===keepObject&&syncTimer===keepTimer&&syncPending'),true);
60 assert.equal(f.run('computeDiff().up[0].payload.name'),'unsaved');
61 assert.equal(f.run('computeDiff().del[0]'),'journalVouchers|OTHER');
62 assert.equal(f.timers.get(f.run('syncTimer')).ms,300);
63 });
64 for(const edit of ["datastore.journalVouchers[0].description='local'","datastore.journalLines=[]","datastore.journalLines[0].voucherId='OTHER'","datastore.journalLineDimensions[0].journalLineId='bad'"]){
65 test('initial dirty graph rejects without network: '+edit,async()=>{
66 const f=await prepared();f.run(edit);const before=f.snapshot();
67 await assert.rejects(async()=>refresh(f),{code:'FINORA_GRAPH_LOCAL_CHANGED'});
68 assert.equal(f.snapshot(),before);assert.equal(f.calls.length,0);
69 });
70 }
71 for(const [code,change] of [
72 ['FINORA_GRAPH_LOCAL_CHANGED',f=>f.run("datastore.journalLines[0].debit=101")],
73 ['FINORA_GRAPH_LOCAL_CHANGED',f=>f.run("datastore.journalLines.push({id:'NEW',ownerUserId:'U',companyId:'C',voucherId:'V',debit:20})")],
74 ['FINORA_GRAPH_VIEW_CHANGED',f=>f.setView({companyId:'C2'})],['FINORA_GRAPH_VIEW_CHANGED',f=>f.setView({formId:'F2'})],['FINORA_GRAPH_VIEW_CHANGED',f=>f.setView({editRevision:1})],
75 ['FINORA_SYNC_CONTEXT_CHANGED',f=>{f.c.currentUser.organizationId='OTHER';}],['FINORA_SYNC_CONTEXT_CHANGED',f=>{f.c.currentUser={id:'U',organizationId:'O'};}],
76 ['FINORA_SYNC_CONTEXT_CHANGED',f=>f.c.pullAll()]
77 ])test('in-flight local/view/account/snapshot change rejects atomic publication #'+change.toString(),async()=>{
78 const f=await prepared();f.state.hook=async name=>{if(name==='finora_journal_read_graph')await change(f);};
79 const p=refresh(f);await assert.rejects(p,{code});assert.notEqual(f.run("datastore.journalVouchers.find(r=>r.id==='V').description"),'server');
80 assert.equal(f.run('syncRunning'),false);
81 });
82 for(const [name,mutate] of [
83 ['null',f=>f.state.graph=null],['wrong tenant',f=>f.state.graph.organization_id='OTHER'],
84 ['wrong voucher',f=>f.state.graph.voucher_id='OTHER'],['no header',f=>f.state.graph.records.shift()],
85 ['duplicate',f=>f.state.graph.records.push(f.state.graph.records[0])],
86 ['foreign collection',f=>f.state.graph.records[1].collection='companies'],
87 ['unsafe version',f=>f.state.graph.records[0].version=Number.MAX_SAFE_INTEGER],
88 ['regressed version',f=>f.state.graph.records[0].version=1],
89 ['same revision altered payload',f=>f.state.graph.records[0].version=2],
90 ['wrong company',f=>f.state.graph.records[1].data.companyId='C2'],
91 ['wrong parent',f=>f.state.graph.records[1].data.voucherId='OTHER'],
92 ['bad ID',f=>f.state.graph.records[1].id='bad|id'],
93 ['mismatched data ID',f=>f.state.graph.records[1].data.id='bad'],
94 ['invalid status',f=>f.state.graph.effective_status='success'],
95 ['draft reversed status',f=>{f.state.graph.records[0].data.status='draft';f.state.graph.effective_status='reversed';}],
96 ['orphan dimension',f=>f.state.graph.records.push({collection:'journalLineDimensions',id:'D2',version:1,data:{id:'D2',companyId:'C',voucherId:'V',journalLineId:'missing'}})],
97 ['collision',f=>{f.state.graph.records[1].id='COLLIDE';f.state.graph.records[1].data.id='COLLIDE';f.run("datastore.journalLines.push({id:'COLLIDE',ownerUserId:'U',companyId:'C',voucherId:'OTHER'})");}],
98 ['error',f=>f.state.error={code:'42501',message:'private server details'}]
99 ])test('malformed or unauthorized graph preserves all arrays and snapshots: '+name,async()=>{
100 const f=await prepared();mutate(f);const before=f.snapshot();
101 await assert.rejects(refresh(f),{code:name==='error'?'FINORA_GRAPH_READ_UNAVAILABLE':'FINORA_GRAPH_INVALID'});assert.equal(f.snapshot(),before);assert.equal(f.run('syncRunning'),false);
102 });
103 test('normal sync waits for refresh and sends only unrelated dirty records',async()=>{
104 const f=await prepared(),gate=deferred();f.state.hook=name=>name==='finora_journal_read_graph'?gate.promise:undefined;
105 const p=refresh(f);await tick();f.run("datastore.companies[0].name='pending'");await f.c.runSync();
106 assert.deepEqual(f.calls.map(x=>x.name),['finora_journal_read_graph']);
107 gate.resolve();await p;const timer=f.timers.get(f.run('syncTimer'));assert.equal(timer.ms,0);await timer.fn();
108 const write=f.calls.find(x=>x.name==='finora_sync_records_v2');assert.equal(write.args.p_upserts.length,1);assert.equal(write.args.p_upserts[0].collection,'companies');
109 });
110 test('refresh queues behind an existing normal save',async()=>{
111 const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");
112 f.state.hook=name=>name==='finora_sync_records_v2'?gate.promise:undefined;
113 const sync=f.c.runSync();await tick();const graph=refresh(f);await tick();
114 assert.equal(f.calls.some(x=>x.name==='finora_journal_read_graph'),false);
115 gate.resolve();await sync;await graph;assert.equal(f.run("datastore.journalVouchers.find(r=>r.id==='V').description"),'server');
116 });
117 test('second captured refresh rejects after first graph changes, without a second request',async()=>{
118 const f=await prepared(),gate=deferred();f.state.hook=()=>gate.promise;
119 const a=refresh(f);await tick();const b=refresh(f);const reject=assert.rejects(b,{code:'FINORA_SYNC_CONTEXT_CHANGED'});
120 gate.resolve();await a;await reject;assert.equal(f.calls.length,1);
121 });
122 test('request timeout releases lock and a late graph cannot publish',async()=>{
123 const f=await prepared(),gate=deferred();f.state.hook=()=>gate.promise;const before=f.snapshot();
124 const p=refresh(f);const rejection=assert.rejects(p,{code:'FINORA_GRAPH_READ_UNAVAILABLE'});await tick();
125 for(const t of [...f.timers.values()])if(t.ms===20000)t.fn();await rejection;
126 gate.resolve();await tick();assert.equal(f.snapshot(),before);assert.equal(f.run('syncRunning'),false);
127 });
128 test('queued refresh timeout does not steal active writer lock',async()=>{
129 const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");f.state.hook=name=>name==='finora_sync_records_v2'?gate.promise:undefined;
130 const sync=f.c.runSync();await tick();const p=refresh(f);const rejection=assert.rejects(p,{code:'FINORA_GRAPH_BUSY'});await tick();
131 const last=[...f.timers.values()].at(-1);last.fn();await rejection;
132 assert.equal(f.run('syncRunning'),true);gate.resolve();await sync;assert.equal(f.calls.some(x=>x.name==='finora_journal_read_graph'),false);
133 });
134 test('read-only user can refresh a new visible graph without a write',async()=>{
135 const f=await prepared();f.c.canWrite=()=>false;f.state.graph.voucher_id='NEW';f.state.graph.records=f.state.graph.records.slice(0,1);f.state.graph.records[0].id='NEW';f.state.graph.records[0].data.id='NEW';
136 await f.c.finoraRefreshJournalGraph(f.capture('NEW'));assert.equal(f.run('datastore.journalVouchers.length'),3);assert.equal(f.calls.length,1);
137 });
138 test('valid same-revision JSON with different key order remains clean',async()=>{
139 const f=await prepared();f.state.graph.effective_status='draft';f.state.graph.records=structuredClone(f.state.rows.filter(r=>r.id!=='C'&&r.id!=='OTHER'));
140 f.state.graph.records[0].data={description:'old',status:'draft',companyId:'C',id:'V'};
141 await refresh(f);assert.equal(f.run('computeDiff().up.length+computeDiff().del.length'),0);
142 });
143 test('complete graph above normal page size retains all lines and linked dimensions',async()=>{
144 const f=await prepared();f.state.graph.records=f.state.graph.records.slice(0,1);
145 for(let n=0;n<1001;n++)f.state.graph.records.push({collection:'journalLines',id:'N'+n,version:1,data:{companyId:'C',voucherId:'V',debit:n+1,credit:0}});
146 f.state.graph.records.push({collection:'journalLineDimensions',id:'D2',version:1,data:{companyId:'C',voucherId:'V',journalLineId:'N1000'}});
147 await refresh(f);assert.equal(f.run('datastore.journalLines.length'),1001);assert.equal(f.run("versionSnap.get('journalLines|N1000')"),1);assert.equal(f.run('datastore.journalLineDimensions[0].journalLineId'),'N1000');assert.equal(f.run('computeDiff().up.length+computeDiff().del.length'),0);
148 });
149 test('context changed while queued rejects before sending graph request',async()=>{
150 const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");f.state.hook=name=>name==='finora_sync_records_v2'?gate.promise:undefined;
151 const sync=f.c.runSync();await tick();const graph=refresh(f);const rejected=assert.rejects(graph,{code:'FINORA_GRAPH_VIEW_CHANGED'});f.setView({editRevision:1});gate.resolve();await sync;await rejected;
152 assert.equal(f.calls.some(x=>x.name==='finora_journal_read_graph'),false);assert.equal(f.run('syncRunning'),false);
153 });
154 test('unhydrated same-user tenant cannot capture old graph',async()=>{
155 const f=await prepared();f.c.currentUser.organizationId='OTHER';const before=f.snapshot();await assert.rejects(async()=>refresh(f),{code:'FINORA_SYNC_SNAPSHOT_REQUIRED'});assert.equal(f.snapshot(),before);assert.equal(f.calls.length,0);
156 });
157
158 test('failed writer drops pre-failure queued retry even when a graph refresh follows',async()=>{
159 const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");
160 let writes=0;f.state.hook=async name=>{if(name==='finora_sync_records_v2'){writes++;await gate.promise;throw new Error('transport lost');}};
161 const sync=f.c.runSync();await tick();await f.c.runSync();const graph=refresh(f);await tick();
162 gate.resolve();await sync;await graph;
163 assert.equal(f.timers.size,0,'An uncertain write cannot gain a retry timer from the read-only graph operation');
164 assert.equal(writes,1);assert.equal(f.run('syncPending'),true);assert.equal(f.run('computeDiff().up[0].payload.name'),'pending');
165 });
166 test('a new explicit save queued during graph read still resumes after earlier writer failure',async()=>{
167 const f=await prepared(),writeGate=deferred(),readGate=deferred();f.run("datastore.companies[0].name='pending'");
168 f.state.hook=async name=>{if(name==='finora_sync_records_v2'){await writeGate.promise;throw new Error('transport lost');}if(name==='finora_journal_read_graph')await readGate.promise;};
169 const sync=f.c.runSync();await tick();const graph=refresh(f);writeGate.resolve();await sync;await tick();
170 await f.c.runSync();readGate.resolve();await graph;
171 assert.equal(f.timers.get(f.run('syncTimer')).ms,0);
172 });
173 test('older same-tenant full read cannot overwrite a newer targeted graph publication',async()=>{
174 const f=await prepared(),gate=deferred();const original=f.c.sb.from;
175 f.c.sb.from=()=>{const q=original();q.range=async()=>{const old=structuredClone(f.state.rows);await gate.promise;return {error:null,data:old};};return q;};
176 const pull=f.c.pullAll();const rejected=assert.rejects(pull,{code:'FINORA_SYNC_CONTEXT_CHANGED'});
177 await refresh(f);gate.resolve();await rejected;
178 assert.equal(f.run("versionSnap.get('journalVouchers|V')"),3);
179 assert.equal(f.run("datastore.journalVouchers.find(r=>r.id==='V').description"),'server');
180 });