سامانه صدور فاکتور و حسابداری
feat(stage3 audit): classify historical source contract readiness without mutation or inferred VAT/currency
davoodmehraban89 committed
Oct 23, 2026 at 11:10 UTC
fd5ccf5bc0f6e557d0fd38aadee2528180f4912b
1 file changed
+85
scripts/stage3-legacy-source-audit.mjs
new
+85
@@ -0,0 +1,85 @@
1
+#!/usr/bin/env node
2
+// FINORA Stage3: source-contract readiness classification only. READ ONLY.
3
+// Accepts local explicitly provided JSON; NEVER fetches DB or mutates rows.
4
+// Does NOT guess historical VAT mode, currency unit, version, or account mapping.
5
+import {readFileSync} from 'node:fs';
6
+import {pathToFileURL} from 'node:url';
7
+
8
+const required=['vatMode','currencyCode','accountingVersion','discountType',
9
+ 'discountInput','vatType','vatRate','paymentMethod','items','subtotal',
10
+ 'discount','vat','grandTotal'];
11
+const own=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
12
+const integer=(v,min=0)=>typeof v==='number'&&Number.isSafeInteger(v)&&v>=min;
13
+const summarize=(rows)=>{
14
+ if(!Array.isArray(rows))throw Error('FINORA_AUDIT_SOURCE_ARRAY_REQUIRED');
15
+ const result={
16
+ total:rows.length,eligible:0,reconciliationRequired:0,unsupported:0,
17
+ contractMismatch:0,outOfScope:0,postedWithGaps:0,reasonCounts:{}
18
+ };
19
+ for(const row of rows){
20
+ if(!row||!['invoices','purchases'].includes(row.collection)
21
+ ||!row.data||typeof row.data!=='object'||Array.isArray(row.data))
22
+ throw Error('FINORA_AUDIT_INVALID_SOURCE_SHAPE');
23
+ const d=row.data;
24
+ const eligibleKind=row.collection==='purchases'||
25
+ ['formal','non_formal'].includes(d.kind);
26
+ const posted=d.accountingStatus==='posted'||d.documentStatus==='posted';
27
+ let status='eligible',reason='';
28
+ if(!eligibleKind){
29
+ status='outOfScope';reason='NON_POSTING_INVOICE_KIND';
30
+ }else{
31
+ const missing=required.filter(k=>!own(d,k));
32
+ if(missing.length){
33
+ status='reconciliationRequired';reason='MISSING_'+missing.join('_');
34
+ }else if(d.currencyCode!=='IRR'){
35
+ status='unsupported';reason='CURRENCY_NOT_APPROVED';
36
+ }else if(!['cash','credit'].includes(d.paymentMethod)){
37
+ status='unsupported';reason='PAYMENT_METHOD_UNSUPPORTED';
38
+ }else if(!['none','with_vat'].includes(d.vatMode)||
39
+ !['fixed','percent'].includes(d.discountType)||
40
+ !['fixed','percent'].includes(d.vatType)||
41
+ ![1,'1'].includes(d.accountingVersion)){
42
+ status='unsupported';reason='SOURCE_CONTRACT_UNSUPPORTED';
43
+ }else if(!Array.isArray(d.items)||d.items.length===0||
44
+ !d.items.every(x=>x&&integer(x.qty,1)&&x.qty<=999999999&&
45
+ integer(x.price)&&integer(x.lineTotal))){
46
+ status='unsupported';reason='ITEM_QUANTITY_OR_AMOUNT_UNSUPPORTED';
47
+ }else if(!['subtotal','discount','discountInput','vat','vatRate','grandTotal']
48
+ .every(k=>integer(d[k]))){
49
+ status='unsupported';reason='MONEY_PRECISION_UNSUPPORTED';
50
+ }else{
51
+ const subtotal=d.items.reduce((s,x)=>s+x.qty*x.price,0);
52
+ const validLines=d.items.every(x=>x.qty*x.price===x.lineTotal);
53
+ const expectedDiscount=Math.min(subtotal,d.discountType==='percent'?
54
+ Math.round(subtotal*d.discountInput/100):d.discountInput);
55
+ const net=subtotal-expectedDiscount;
56
+ const expectedVat=d.vatMode==='none'?0:
57
+ d.vatType==='percent'?Math.round(net*d.vatRate/100):d.vatRate;
58
+ if(!Number.isSafeInteger(subtotal)||!validLines||
59
+ subtotal<=0||d.subtotal!==subtotal||
60
+ d.discount!==expectedDiscount||expectedDiscount>subtotal||
61
+ (d.discountType==='percent'&&d.discountInput>100)||
62
+ (d.vatType==='percent'&&d.vatRate>100)||
63
+ (row.collection==='invoices'&&d.kind==='non_formal'&&d.vat!==0)||
64
+ d.vat!==expectedVat||d.grandTotal!==net+expectedVat||d.grandTotal<=0){
65
+ status='contractMismatch';reason='SERVER_V1_AMOUNT_MISMATCH';
66
+ }
67
+ }
68
+ }
69
+ result[status]++;
70
+ if(posted&&status!=='eligible')result.postedWithGaps++;
71
+ if(reason)result.reasonCounts[reason]=(result.reasonCounts[reason]||0)+1;
72
+ }
73
+ // Deliberately never include record IDs, amounts, names, organizations or raw data.
74
+ result.reasonCounts=Object.fromEntries(Object.entries(result.reasonCounts)
75
+ .sort(([a],[b])=>a.localeCompare(b)));
76
+ return result;
77
+};
78
+export {summarize as auditSourceRecords};
79
+if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
80
+ const pathname=process.argv[2];
81
+ if(!pathname||pathname.startsWith('http:')||pathname.startsWith('https:'))
82
+ throw Error('FINORA_AUDIT_LOCAL_EXPLICIT_FILE_ONLY');
83
+ const report=summarize(JSON.parse(readFileSync(pathname,'utf8')));
84
+ console.log('FINORA_STAGE3_LEGACY_READONLY_REPORT '+JSON.stringify(report));
85
+}