سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 23:15 UTC
test(adr216): audit source-only, orphan and duplicate draft identities in existing read-only inventory
davoodmehraban89 committed
Nov 22, 2026 at 09:40 UTC
717b0ebbf71fd76813e3bfb1724c567f3dcc950c
2 files changed
+130
-7
scripts/draft-conversion-inventory.test.mjs
+40
-3
@@ -15,9 +15,9 @@ test('source-derived inventory on isolated PostgreSQL preserves scope, exact amo
15
const sql=q=>docker(['exec','-i',name,'psql','-h','127.0.0.1','-X','-A','-t','-v','ON_ERROR_STOP=1','-U','postgres'],q).trim();
16
const query=readFileSync(new URL('./sql/draft-conversion-inventory.sql',import.meta.url),'utf8');
17
const inventory=()=>JSON.parse(sql(query));
18
- const owner='00000000-0000-4000-8000-000000000001',org='00000000-0000-4000-8000-000000000002';
18
+ const owner='00000000-0000-4000-8000-000000000001',org='00000000-0000-4000-8000-000000000002',org2='00000000-0000-4000-8000-000000000003';
19
const quote=value=>"'"+String(value).replaceAll("'","''")+"'";
20
- const insert=(collection,id,data)=>sql(`insert into public.records values (${quote(owner)},${quote(collection)},${quote(id)},${quote(JSON.stringify(data))}::jsonb,now(),${quote(org)});`);
20
+ const insert=(collection,id,data,organization=org,recordOwner=owner)=>sql(`insert into public.records values (${quote(recordOwner)},${quote(collection)},${quote(id)},${quote(JSON.stringify(data))}::jsonb,now(),${quote(organization)});`);
21
try{
22
docker(['run','--detach','--name',name,'--network','none','--tmpfs','/var/lib/postgresql/data','-e','POSTGRES_HOST_AUTH_METHOD=trust','postgres:17-alpine']);
23
// The image's temporary initialization server accepts Unix sockets before
@@ -28,7 +28,7 @@ test('source-derived inventory on isolated PostgreSQL preserves scope, exact amo
28
if(r.status===0){ready=true;break;}await new Promise(resolve=>setTimeout(resolve,250));
29
}
30
assert.ok(ready,'isolated PostgreSQL ready');
31
- sql('create table public.records(owner_id uuid not null,collection text not null,id text not null,data jsonb not null,updated_at timestamptz,organization_id uuid,primary key(owner_id,collection,id));');
31
+ sql('create table public.records(owner_id uuid not null,collection text not null,id text not null,data jsonb not null,updated_at timestamptz,organization_id uuid not null,primary key(organization_id,collection,id));');
32
insert('fiscalYears','FY',{companyId:'C',status:'open',startDate:'1405/01/01',endDate:'1405/12/29'});
33
insert('invoices','I',{companyId:'C',journalVoucherId:'J',kind:'formal'});
34
insert('journalVouchers','J',{companyId:'C',fiscalYearId:'FY',status:'posted',sourceType:'sale',sourceId:'I',date:'۱۴۰۵/۰۸/۲۲',totalDebit:'9007199254740993',totalCredit:'9007199254740993'});
@@ -39,6 +39,12 @@ test('source-derived inventory on isolated PostgreSQL preserves scope, exact amo
39
let inv=inventory();assert.equal(inv.journals.length,1);assert.equal(planDraftConversion(inv.journals).integrityReady,true);
40
assert.equal(inv.journals[0].lines.find(l=>l.debit!=='0').debit,'9007199254740993');
41
assert.equal(sql('select md5(string_agg(row(r.*)::text,\'\' order by collection,id)) from public.records r;'),before);
42
+ assert.equal(inv.sourceIdentityAudit.sourcesConsidered,1);
43
+ assert.equal(inv.sourceIdentityAudit.withoutGeneratedVoucher,0);
44
+ assert.equal(inv.sourceIdentityAudit.orphanGeneratedVouchers,0);
45
+ assert.equal(inv.sourceIdentityAudit.duplicateDraftSourceIdentities,0);
46
+ assert.equal(inv.sourceIdentityAudit.postedProjectionMismatches,1,
47
+ 'synthetic posted voucher with no source projection must be visible');
48
const fingerprint=inv.financialFingerprint;
49
sql("update public.records set data=jsonb_set(data,'{companyId}','\"OTHER\"') where collection='invoices';");
50
inv=inventory();assert.notEqual(inv.financialFingerprint,fingerprint);
@@ -53,5 +59,36 @@ test('source-derived inventory on isolated PostgreSQL preserves scope, exact amo
59
assert.ok(planDraftConversion(inventory().journals).blockers.some(b=>b.code==='FISCAL_SCOPE_NOT_OPEN'));
60
sql("delete from public.records where collection='invoices';");
61
assert.equal(inventory().journals[0].source,null);
62
+ // ADR216: one owner may belong to two organizations with the same record IDs.
63
+ // A source in org2 must never attach to a voucher in org1 during inventory.
64
+ insert('invoices','I',{companyId:'OTHER',kind:'formal'},org2);
65
+ assert.equal(inventory().journals.find(x=>x.sourceType==='sale'&&x.status==='posted').source,null);
66
+ insert('purchases','P_ONLY',{companyId:'C',documentStatus:'draft'});
67
+ insert('invoices','I_OPERATIONAL',{companyId:'C',kind:'pre_invoice'});
68
+ insert('invoices','I_DRAFT',{companyId:'C',kind:'formal',journalVoucherId:'J_DRAFT_A',documentStatus:'draft',accountingStatus:'draft'});
69
+ insert('journalVouchers','J_DRAFT_A',{companyId:'C',sourceType:'sale',sourceId:'I_DRAFT',status:'draft'});
70
+ insert('journalVouchers','J_DRAFT_B',{companyId:'C',sourceType:'sale',sourceId:'I_DRAFT',status:'draft'});
71
+ insert('invoices','I_DANGLING',{companyId:'C',kind:'formal',journalVoucherId:'J_MISSING'});
72
+ insert('invoices','I_WRONG',{companyId:'C',kind:'formal',journalVoucherId:'J_DRAFT_A'});
73
+ insert('journalVouchers','J_ORPHAN',{companyId:'C',sourceType:'purchase',sourceId:'NONEXISTENT',status:'draft'});
74
+ insert('invoices','I_POSTED',{companyId:'C',kind:'formal',journalVoucherId:'J_POSTED',documentStatus:'draft',accountingStatus:'draft'});
75
+ insert('journalVouchers','J_POSTED',{companyId:'C',sourceType:'sale',sourceId:'I_POSTED',status:'posted'});
76
+ insert('purchases','P_DRAFT_BAD',{companyId:'C',journalVoucherId:'P_JV',documentStatus:'posted',accountingStatus:'draft'});
77
+ insert('journalVouchers','P_JV',{companyId:'C',sourceType:'purchase',sourceId:'P_DRAFT_BAD',status:'draft'});
78
+ insert('invoices','I_UNLINKED',{companyId:'C',kind:'formal',documentStatus:'draft',accountingStatus:'draft'});
79
+ insert('journalVouchers','J_UNLINKED',{companyId:'C',sourceType:'sale',sourceId:'I_UNLINKED',status:'draft'});
80
+ const signal=inventory().sourceIdentityAudit;
81
+ assert.deepEqual(signal,{
82
+ sourcesConsidered:8, withoutGeneratedVoucher:4,
83
+ unlinkedWithGeneratedVoucher:1, danglingSourceLinks:1,
84
+ wrongIdentitySourceLinks:1, linkedDraftSources:2,
85
+ linkedDraftProjectionMismatches:1, postedProjectionMismatches:1,
86
+ duplicateDraftSourceIdentities:1, orphanGeneratedVouchers:2,
87
+ crossScopeGeneratedVouchers:0
88
+ },'aggregate-only source identity diagnostics for legacy / draft-first rollout');
89
+ // A generated voucher pointing to a real but different-company source is
90
+ // a separate risk from a missing source, not a reason to join across orgs.
91
+ insert('journalVouchers','J_BAD_SCOPE',{companyId:'WRONG',sourceType:'purchase',sourceId:'P_ONLY',status:'draft'});
92
+ assert.equal(inventory().sourceIdentityAudit.crossScopeGeneratedVouchers,1);
93
}finally{spawnSync('docker',['rm','--force',name],{encoding:'utf8',timeout:30000});}
94
});
scripts/sql/draft-conversion-inventory.sql
+90
-4
@@ -1,6 +1,8 @@
1
-- READ ONLY. Run as the authorized operator for the owner's global conversion.
2
-- Opaque keys are correlation tokens, not anonymous/public datasets. Keep the
3
-- result outside Git. This query does not export descriptions or source items.
4
+-- Source identity aggregates are PRE-MIGRATION signals, not conversion approval.
5
+-- Operational/pre-invoice sale kinds are not counted as financial sources.
6
with vouchers as (
7
select v.*, case v.data->>'sourceType'
8
when 'sale' then 'invoices' when 'purchase' then 'purchases'
@@ -36,14 +38,15 @@ with vouchers as (
38
'company',md5(nullif(s.data->>'companyId','')),
39
'voucher',case when nullif(s.data->>'journalVoucherId','') is not null then md5(s.owner_id::text||'|'||(s.data->>'journalVoucherId')) end,
40
'electronicMetadata',coalesce(s.data->>'electronicDoc','') not in ('','null','{}'),
39
- 'dependencyCount',(select count(*) from public.records dep where dep.owner_id=s.owner_id
41
+ 'dependencyCount',(select count(*) from public.records dep where dep.owner_id=s.owner_id and dep.organization_id=s.organization_id
42
and dep.collection in ('payments','stockMovements','contractStatements','integrationOutbox')
43
and s.id in (dep.data->>'invoiceId',dep.data->>'sourceInvoiceId',dep.data->>'relatedInvoiceId',
44
dep.data->>'purchaseId',dep.data->>'sourceId',dep.data->>'chequeId'))
45
) end
46
) as item
47
from vouchers v
46
- left join public.records s on s.owner_id=v.owner_id and s.collection=v.source_collection and s.id=v.data->>'sourceId'
48
+ left join public.records s on s.owner_id=v.owner_id and s.organization_id=v.organization_id
49
+ and s.collection=v.source_collection and s.id=v.data->>'sourceId'
50
left join lateral (
51
select jsonb_agg(jsonb_build_object(
52
'account',md5(nullif(l.data->>'accountId','')),
@@ -52,19 +55,102 @@ with vouchers as (
55
'debit',l.data->>'debit','credit',l.data->>'credit',
56
'dimensions',coalesce((select jsonb_agg(md5((d.data->>'dimensionTypeId')||'|'||(d.data->>'dimensionValueId')) order by d.id)
57
from public.records d where d.collection='journalLineDimensions' and d.owner_id=l.owner_id
58
+ and d.organization_id=l.organization_id
59
and d.data->>'journalLineId'=l.id),'[]'::jsonb)
60
) order by l.id) as lines,
61
bool_and(l.organization_id is not distinct from v.organization_id
62
and l.data->>'companyId' is not distinct from v.data->>'companyId'
63
and not exists(select 1 from public.records d where d.collection='journalLineDimensions'
60
- and d.owner_id=l.owner_id and d.data->>'journalLineId'=l.id and (
64
+ and d.owner_id=l.owner_id and d.organization_id=l.organization_id
65
+ and d.data->>'journalLineId'=l.id and (
66
d.organization_id is distinct from v.organization_id or d.data->>'companyId' is distinct from v.data->>'companyId'
67
or d.data->>'voucherId' is distinct from v.id))) as scope_valid
63
- from public.records l where l.collection='journalLines' and l.owner_id=v.owner_id and l.data->>'voucherId'=v.id
68
+ from public.records l where l.collection='journalLines' and l.owner_id=v.owner_id
69
+ and l.organization_id=v.organization_id and l.data->>'voucherId'=v.id
70
) graph on true
71
+), source_rows as (
72
+ -- Include only invoice kinds which create accounting entries, plus purchases.
73
+ select s.organization_id,s.owner_id,s.collection,s.id,s.data,
74
+ case s.collection when 'invoices' then 'sale' else 'purchase' end kind,
75
+ nullif(btrim(s.data->>'journalVoucherId'),'') linked_id
76
+ from public.records s
77
+ where s.collection='purchases' or
78
+ (s.collection='invoices' and s.data->>'kind' in ('formal','non_formal'))
79
+), generated as (
80
+ select v.organization_id,v.owner_id,v.id,v.data,
81
+ v.data->>'sourceType' kind,nullif(btrim(v.data->>'sourceId'),'') source_id
82
+ from public.records v
83
+ where v.collection='journalVouchers' and v.data->>'sourceType' in ('sale','purchase')
84
+ and nullif(btrim(v.data->>'sourceId'),'') is not null
85
+), generated_by_identity as (
86
+ select organization_id,kind,source_id,
87
+ count(*) as voucher_count,
88
+ count(*) filter (where data->>'status'='draft') as draft_count
89
+ from generated group by organization_id,kind,source_id
90
+), source_observations as (
91
+ select s.*,v.id matched_link_id,v.owner_id linked_owner,v.data linked_data,
92
+ coalesce(g.voucher_count,0) generated_count
93
+ from source_rows s
94
+ left join public.records v on v.organization_id=s.organization_id
95
+ and v.collection='journalVouchers' and v.id=s.linked_id
96
+ left join generated_by_identity g on g.organization_id=s.organization_id
97
+ and g.kind=s.kind and g.source_id=s.id
98
+), source_health as (
99
+ select count(*) sources_considered,
100
+ count(*) filter (where generated_count=0) without_generated_voucher,
101
+ count(*) filter (where linked_id is null and generated_count>0) unlinked_with_generated_voucher,
102
+ count(*) filter (where linked_id is not null and matched_link_id is null) dangling_links,
103
+ count(*) filter (where matched_link_id is not null and (
104
+ linked_owner is distinct from owner_id or
105
+ linked_data->>'sourceType' is distinct from kind or
106
+ linked_data->>'sourceId' is distinct from id or
107
+ linked_data->>'companyId' is distinct from data->>'companyId'
108
+ )) wrong_identity_links,
109
+ count(*) filter (where matched_link_id is not null and
110
+ linked_data->>'sourceType'=kind and linked_data->>'sourceId'=id
111
+ and linked_owner=owner_id and linked_data->>'companyId'=data->>'companyId'
112
+ and linked_data->>'status'='draft') linked_draft_sources,
113
+ count(*) filter (where matched_link_id is not null and
114
+ linked_data->>'sourceType'=kind and linked_data->>'sourceId'=id
115
+ and linked_owner=owner_id and linked_data->>'companyId'=data->>'companyId'
116
+ and linked_data->>'status'='draft' and
117
+ (data->>'documentStatus' is distinct from 'draft' or
118
+ data->>'accountingStatus' is distinct from 'draft')) linked_draft_projection_mismatches,
119
+ count(*) filter (where matched_link_id is not null and
120
+ linked_data->>'sourceType'=kind and linked_data->>'sourceId'=id
121
+ and linked_owner=owner_id and linked_data->>'companyId'=data->>'companyId'
122
+ and linked_data->>'status'='posted' and
123
+ (data->>'documentStatus' is distinct from 'posted' or
124
+ data->>'accountingStatus' is distinct from 'posted')) posted_projection_mismatches
125
+ from source_observations
126
+), generated_health as (
127
+ select
128
+ count(*) filter (where s.id is null) as orphan_generated_vouchers,
129
+ count(*) filter (where s.id is not null and
130
+ (s.owner_id is distinct from g.owner_id or
131
+ s.data->>'companyId' is distinct from g.data->>'companyId'))
132
+ as cross_scope_generated_vouchers
133
+ from generated g
134
+ left join public.records s on s.organization_id=g.organization_id
135
+ and s.collection=case g.kind when 'sale' then 'invoices' else 'purchases' end
136
+ and s.id=g.source_id
137
)
138
select jsonb_build_object(
139
'journals',coalesce((select jsonb_agg(item order by item->>'key') from inventory),'[]'::jsonb),
140
+ 'sourceIdentityAudit',(select jsonb_build_object(
141
+ 'sourcesConsidered',h.sources_considered,
142
+ 'withoutGeneratedVoucher',h.without_generated_voucher,
143
+ 'unlinkedWithGeneratedVoucher',h.unlinked_with_generated_voucher,
144
+ 'danglingSourceLinks',h.dangling_links,
145
+ 'wrongIdentitySourceLinks',h.wrong_identity_links,
146
+ 'linkedDraftSources',h.linked_draft_sources,
147
+ 'linkedDraftProjectionMismatches',h.linked_draft_projection_mismatches,
148
+ 'postedProjectionMismatches',h.posted_projection_mismatches,
149
+ 'duplicateDraftSourceIdentities',
150
+ (select count(*) from generated_by_identity where draft_count>1),
151
+ 'orphanGeneratedVouchers',g.orphan_generated_vouchers,
152
+ 'crossScopeGeneratedVouchers',g.cross_scope_generated_vouchers
153
+ ) from source_health h cross join generated_health g),
154
'snapshotAt',statement_timestamp(),
155
'financialFingerprint',(select md5(string_agg(md5(row(r.owner_id,r.organization_id,r.collection,r.id,r.data,r.updated_at)::text),'' order by r.owner_id,r.collection,r.id))
156
from public.records r where r.collection in ('journalVouchers','journalLines','journalLineDimensions','invoices','purchases','payments','cheques','fiscalYears','stockMovements'))