فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

feat(A02): strict read-only Holoo CSV/TSV source preview and currency guardrails

Add purely in-memory explicit-mapping CSV/TSV adapter for user-authorized and already-extracted Holoo exports. Supports BOM, quoted multiline fields, mapped rial/toman conversion with integer overflow checks, bounded non-identifying diagnostics and fail-closed CSV structure validation. Block missing reference parent datasets in existing preflight. Nine synthetic tests. PR Quality #38976459981 passed (213 Node tests + Vite + audit + Windows preview installer); native Windows VM #38976459938 passed on identical PR commit. Still no real Holoo file inspected, no proprietary backup decoder, no actual import, no customer data or public release, A02 accepted:false.

davoodmehraban89 committed Oct 17, 2026 at 02:10 UTC 18f434b9d78e8575a1432bcd51afa5acc520532d
4 files changed +280 -1
docs/adr/ADR-002-holoo-migration-compatibility-fa.md
+17
@@ -32,6 +32,23 @@
32 ## آنچه هم‌اکنون پیاده‌سازی شد
33 ماژول `src/core/HolooMigrationPreflight.mjs` یک پیش‌بررسی **صرفاً حافظه‌ای و غیرمخرب** برای داده‌های جدولی از پیش استخراج‌شده و ستون‌های **صریحاً نگاشت‌شده** فراهم می‌کند. این ماژول شناسه‌های تکراری، ارجاع یتیم، مبلغ غیرصحیح ریالی و بیش‌پرداخت را پیدا می‌کند؛ گزارش فقط کد و شماره ردیف دارد و ورودی یا دیتابیس را تغییر نمی‌دهد. نتیجه موفق هم فقط `requires-source-and-accountant-review` است و **مجوز commit نیست**. آزمون‌ها کاملاً ساختگی‌اند و ادعای خواندن مستقیم `.bak` یا بکاپ اختصاصی هلو ندارند.
34
35 +## پشتیبانی اولیه از خروجی CSV/TSV، با واحد پول صریح
36 +
37 +ماژول `src/core/HolooDelimitedExportPreflight.mjs` اکنون می‌تواند **فقط متن خروجی جدولی استخراج‌شده** را با `delimiter` صریح (کاما، سمی‌کالن یا Tab) و `mappings` صریح ستون‌ها بررسی کند. BOM، نقل‌قول‌های دوتایی، متن چندخطی، ستون تکراری، سطر ناقص، حجم ورودی و ارجاع جدول والد کنترل می‌شود. واحد پول باید `rial` یا `toman` باشد؛ تبدیل تومان به ریال تنها با همین ورودی صریح و کنترل سرریز انجام می‌شود. هیچ فرمت یا واحد پولی از روی نام فایل یا محتوای خصوصی حدس زده نمی‌شود.
38 +
39 +نمونه قرارداد **ساختگی** و نه ادعای نام ستون واقعی هلو:
40 +
41 +```js
42 +previewHolooDelimitedExport({
43 + sourceSystem: 'holoo', moneyUnit: 'rial',
44 + tables: { products: { text: 'id,name\nP1,Sample\n', delimiter: ',' } },
45 + mappings: { products: { sourceId: 'id', name: 'name' } }
46 +})
47 +// { canCommit: false, status: 'requires-source-and-accountant-review', ... }
48 +```
49 +
50 +تمام نتایج فقط شمارش رکورد، کد ایراد و شماره ردیف‌اند؛ **متن خام فایل، نام شخص، شماره حساب و شماره چک در خروجی قرار نمی‌گیرد**. هنوز تشخیص اصالت فایل هلو، خواندن `.bak`، تبدیل کامل فاکتورها و ثبت داده در دیتابیس مقصد پشتیبانی نمی‌شود. برای مانده افتتاحیه واقعی باید همه جدول‌های مربوط و تأیید حسابدار فراهم باشد.
51 +
52 ## مانع مرحله بعد
53 **نیاز به یک فایل واقعی متعلق به مالک** است (فایل اصلی بدون تغییر می‌ماند). ابتدا پسوند، امضای فایل، نسخه هلو و امکان خواندن امن/مجاز در محیط ایزوله بررسی می‌شود. سپس آداپتور همان فرمت بر اساس شواهد واقعی توسعه داده می‌شود. پیش از اتصال به CI عمومی، اطلاعات اشخاص، مالی، بانکی و رمزها حذف/ناشناس می‌شوند.
54
src/core/HolooDelimitedExportPreflight.mjs new
+143
@@ -0,0 +1,143 @@
1 +// A02: read-only, explicit CSV/TSV source adapter for *already exported*
2 +// Holoo tables. This DOES NOT decode Holoo proprietary binary backups.
3 +// No file-system, IndexedDB, ledger or network access.
4 +import { previewHolooExtract } from './HolooMigrationPreflight.mjs';
5 +
6 +const COLUMNS = Object.freeze({
7 + contacts: ['receivable', 'payable'],
8 + products: [],
9 + invoices: ['grandTotal', 'paidAmount'],
10 + invoiceLines: [],
11 + cheques: ['amount']
12 +});
13 +const MAX_TEXT_LENGTH = 12 * 1024 * 1024;
14 +const MAX_DATA_ROWS = 100000;
15 +const MAX_FIELDS = 200;
16 +const MAX_CELL_LENGTH = 256 * 1024;
17 +const SEPARATORS = new Set([',', ';', '\t']);
18 +
19 +const reject = code => { throw new Error(code); };
20 +const validMap = value => value && typeof value === 'object' &&
21 + !Array.isArray(value);
22 +const parseMoney = (value, unit) => {
23 + // Never infer rial vs toman or decimal separators; source version must
24 + // explicitly provide a mapping and integer currency-unit policy.
25 + const valueText = typeof value === 'string' ? value.trim() : '';
26 + if (!/^[0-9]+$/.test(valueText)) return NaN;
27 + const integer = Number(valueText);
28 + const multiplier = unit === 'toman' ? 10 : 1;
29 + return Number.isSafeInteger(integer) &&
30 + Number.isSafeInteger(integer * multiplier)
31 + ? integer * multiplier : NaN;
32 +};
33 +
34 +export function parseStrictDelimitedRows(text, { delimiter = ',' } = {}) {
35 + if (typeof text !== 'string' || text.length > MAX_TEXT_LENGTH)
36 + throw new RangeError('CSV_INVALID_SIZE');
37 + if (!SEPARATORS.has(delimiter)) reject('CSV_UNSUPPORTED_DELIMITER');
38 + if (!text.length) reject('CSV_EMPTY_SOURCE');
39 + const rows = [];
40 + let record = [], cell = '', quoted = false, afterQuote = false, begun = false;
41 + // Include the final sentinel newline to flush a possibly unterminated row.
42 + // Quoted multiline fields are preserved verbatim; raw data is never logged.
43 + const submitCell = () => {
44 + if (cell.length > MAX_CELL_LENGTH) reject('CSV_CELL_TOO_LARGE');
45 + record.push(cell); cell = ''; afterQuote = false; begun = false;
46 + if (record.length > MAX_FIELDS) reject('CSV_TOO_MANY_COLUMNS');
47 + };
48 + const submitRecord = () => {
49 + submitCell();
50 + if (!(record.length === 1 && record[0] === '')) {
51 + rows.push(record);
52 + if (rows.length > MAX_DATA_ROWS + 1) reject('CSV_TOO_MANY_ROWS');
53 + }
54 + record = [];
55 + };
56 + const input = text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
57 + for (let i = 0; i < input.length; i++) {
58 + const c = input[i];
59 + if (quoted) {
60 + if (c === '"') {
61 + if (input[i + 1] === '"') { cell += '"'; i++; }
62 + else { quoted = false; afterQuote = true; }
63 + } else cell += c;
64 + } else if (afterQuote) {
65 + if (c === delimiter) submitCell();
66 + else if (c === '\r' || c === '\n') {
67 + submitRecord();
68 + if (c === '\r' && input[i + 1] === '\n') i++;
69 + } else reject('CSV_CHARACTERS_AFTER_QUOTE');
70 + } else if (c === delimiter) {
71 + submitCell();
72 + } else if (c === '\r' || c === '\n') {
73 + submitRecord();
74 + if (c === '\r' && input[i + 1] === '\n') i++;
75 + } else if (c === '"') {
76 + if (begun || cell.length) reject('CSV_UNEXPECTED_QUOTE');
77 + quoted = true; begun = true;
78 + } else {
79 + cell += c; begun = true;
80 + }
81 + if (cell.length > MAX_CELL_LENGTH) reject('CSV_CELL_TOO_LARGE');
82 + }
83 + if (quoted) reject('CSV_UNTERMINATED_QUOTE');
84 + if (record.length || cell || afterQuote || begun) submitRecord();
85 + if (!rows.length) reject('CSV_NO_HEADER');
86 + const headers = rows.shift().map(x => x.trim());
87 + if (!headers.length || headers.some(x => !x) ||
88 + new Set(headers).size !== headers.length) reject('CSV_INVALID_HEADER');
89 + if (rows.some(row => row.length !== headers.length))
90 + reject('CSV_ROW_WIDTH_MISMATCH');
91 + // Null prototype prevents special header names (__proto__, constructor)
92 + // from modifying object prototypes in any downstream processing.
93 + const data = rows.map(row => Object.fromEntries(
94 + headers.map((header, j) => [header, row[j]])));
95 + return { headers, rows: data };
96 +}
97 +
98 +export function previewHolooDelimitedExport({
99 + sourceSystem, moneyUnit, tables, mappings
100 +} = {}, { maxIssues = 100 } = {}) {
101 + if (sourceSystem !== 'holoo') reject('SOURCE_SYSTEM_NOT_HOLOO');
102 + if (!['rial', 'toman'].includes(moneyUnit)) reject('MONEY_UNIT_REQUIRED');
103 + if (!validMap(tables) || !validMap(mappings)) reject('SOURCE_MAPPING_REQUIRED');
104 + if (Object.keys(tables).some(name => !(name in COLUMNS)) ||
105 + Object.keys(mappings).some(name => !(name in COLUMNS))) {
106 + reject('SOURCE_UNSUPPORTED_TABLE');
107 + }
108 + const datasets = {};
109 + for (const [table, item] of Object.entries(tables)) {
110 + if (!validMap(item) || typeof item.text !== 'string' ||
111 + !validMap(mappings[table])) reject('CSV_TABLE_CONFIGURATION_REQUIRED');
112 + const parsed = parseStrictDelimitedRows(item.text, { delimiter: item.delimiter });
113 + const mapped = mappings[table];
114 + for (const column of Object.values(mapped)) {
115 + if (typeof column !== 'string' || !parsed.headers.includes(column))
116 + reject('CSV_MAPPED_COLUMN_ABSENT');
117 + }
118 + for (const row of parsed.rows) {
119 + for (const field of COLUMNS[table]) {
120 + const name = mapped[field];
121 + if (name && Object.hasOwn(row, name)) {
122 + row[name] = parseMoney(row[name], moneyUnit);
123 + }
124 + }
125 + }
126 + datasets[table] = parsed.rows;
127 + }
128 + // The original strings are not mutated and never returned. Any result
129 + // contains only bounded diagnostic codes, row positions and counts.
130 + const report = previewHolooExtract({
131 + sourceSystem: 'holoo', datasets, columns: mappings
132 + }, { maxIssues });
133 + return Object.freeze({
134 + ...report,
135 + inputType: 'explicit-mapped-delimited-export',
136 + sourceCurrencyUnit: moneyUnit,
137 + // This parser is not an authenticity check for Holoo CSV exports.
138 + sourceVersionVerified: false,
139 + writePerformed: false,
140 + importPerformed: false,
141 + canCommit: false
142 + });
143 +}
src/core/HolooMigrationPreflight.mjs
+10 -1
@@ -105,7 +105,16 @@ export function previewHolooExtract(input = {}, { maxIssues = 100 } = {}) {
105 for (const { table, key, parent } of references) {
106 const rows = datasets[table] || [];
107 const mapped = mappings[table]?.[key];
108 - if (!rows.length || !mapped || !counts[parent] || !mappings[parent]?.sourceId) continue;
108 + if (!rows.length || !mapped) continue;
109 + // A missing parent table cannot silently be treated as a clean migration.
110 + // Real migrations require all referenced master-data exports to be present.
111 + if (!counts[parent] || !mappings[parent]?.sourceId) {
112 + if (rows.some(record => record && typeof record === 'object' &&
113 + identity(field(table, record, key)))) {
114 + add('REFERENCE_PARENT_DATASET_REQUIRED', table);
115 + }
116 + continue;
117 + }
118 rows.forEach((record, i) => {
119 if (!record || typeof record !== 'object' || Array.isArray(record)) return;
120 const id = identity(field(table, record, key));
tests/a02-holoo-delimited-export.test.mjs new
+110
@@ -0,0 +1,110 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {
4 + parseStrictDelimitedRows, previewHolooDelimitedExport
5 +} from '../src/core/HolooDelimitedExportPreflight.mjs';
6 +
7 +const fixture = () => ({
8 + sourceSystem: 'holoo',
9 + moneyUnit: 'rial',
10 + tables: {
11 + contacts: { text: '\uFEFFcode;name;ar;ap\r\nC1;"مشتری ""نمونه""";0;0\r\n', delimiter: ';' },
12 + products: { text: 'code,name\r\nP1,نمونه\r\n' },
13 + invoices: { text: 'id,contact,gross,paid\nI1,C1,300,100\n' },
14 + invoiceLines: { text: 'invoice,product\nI1,P1\n' },
15 + cheques: { text: 'id,amount\nQ1,50\n' }
16 + },
17 + mappings: {
18 + contacts: { sourceId: 'code', name: 'name', receivable: 'ar', payable: 'ap' },
19 + products: { sourceId: 'code', name: 'name' },
20 + invoices: { sourceId: 'id', contactId: 'contact', grandTotal: 'gross', paidAmount: 'paid' },
21 + invoiceLines: { invoiceId: 'invoice', productId: 'product' },
22 + cheques: { sourceId: 'id', amount: 'amount' }
23 + }
24 +});
25 +
26 +test('A02: mapped synthetic Holoo CSV/TSV extracts report only bounded non-identifying results', () => {
27 + const sample=fixture(), snapshot=structuredClone(sample);
28 + const report=previewHolooDelimitedExport(sample);
29 + assert.equal(report.issueCount, 0, JSON.stringify(report.issues));
30 + assert.equal(report.inspectedRows, 5);
31 + assert.equal(report.inputType, 'explicit-mapped-delimited-export');
32 + assert.equal(report.status, 'requires-source-and-accountant-review');
33 + assert.equal(report.canCommit, false);
34 + assert.equal(report.sourceVersionVerified, false);
35 + assert.deepEqual(sample,snapshot);
36 + assert.ok(!JSON.stringify(report).includes('مشتری'));
37 +});
38 +
39 +test('A02: quoted multiline text, escaped quotes and BOM parse without changing identity', () => {
40 + const parsed=parseStrictDelimitedRows('\uFEFFid,comment\r\n1,"line\n""quoted"""\r\n');
41 + assert.equal(parsed.rows.length,1);
42 + assert.deepEqual(parsed.headers,['id','comment']);
43 + assert.equal(parsed.rows[0].comment,'line\n"quoted"');
44 +});
45 +
46 +test('A02: currency unit conversion is explicit; no unannounced toman/rial guessing', () => {
47 + const sample=fixture();
48 + sample.moneyUnit='toman';
49 + sample.tables.invoices.text='id,contact,gross,paid\nI1,C1,1.5,1\n';
50 + const invalid=previewHolooDelimitedExport(sample);
51 + assert.ok(invalid.issues.some(x=>x.code==='AMOUNT_NOT_INTEGER_RIAL'));
52 + sample.tables.invoices.text='id,contact,gross,paid\nI1,C1,100,110\n';
53 + const bad=previewHolooDelimitedExport(sample);
54 + assert.ok(bad.issues.some(x=>x.code==='PAID_EXCEEDS_GROSS'));
55 + sample.moneyUnit='auto';
56 + assert.throws(()=>previewHolooDelimitedExport(sample),/MONEY_UNIT_REQUIRED/);
57 +});
58 +
59 +test('A02: partial source graph cannot silently pretend linked contacts exist', () => {
60 + const sample=fixture();
61 + delete sample.tables.contacts;
62 + delete sample.mappings.contacts;
63 + const result=previewHolooDelimitedExport(sample);
64 + assert.ok(result.issues.some(x=>x.code==='REFERENCE_PARENT_DATASET_REQUIRED'));
65 + assert.equal(result.status,'blocked');
66 +});
67 +
68 +test('A02: reference mismatch, malformed quote and row width abort before import', () => {
69 + const sample=fixture();
70 + sample.tables.invoiceLines.text='invoice,product\nI1,OTHER\n';
71 + const invalid=previewHolooDelimitedExport(sample);
72 + assert.ok(invalid.issues.some(x=>x.code==='REFERENCE_NOT_FOUND'));
73 + sample.tables.invoiceLines.text='invoice,product\n"I1,P1\n';
74 + assert.throws(()=>previewHolooDelimitedExport(sample),/CSV_UNTERMINATED_QUOTE/);
75 + sample.tables.invoiceLines.text='invoice,product\nI1\n';
76 + assert.throws(()=>previewHolooDelimitedExport(sample),/CSV_ROW_WIDTH_MISMATCH/);
77 +});
78 +
79 +test('A02: fail closed on ambiguous headers, missing mapped columns and unsupported table', () => {
80 + const sample=fixture();
81 + sample.tables.invoices.text='id,id,gross,paid\nI1,C1,300,100\n';
82 + assert.throws(()=>previewHolooDelimitedExport(sample),/CSV_INVALID_HEADER/);
83 + sample.tables.invoices.text='id,contact,gross,paid\nI1,C1,300,100\n';
84 + sample.mappings.invoices.paidAmount='missing';
85 + assert.throws(()=>previewHolooDelimitedExport(sample),/CSV_MAPPED_COLUMN_ABSENT/);
86 + sample.tables.hiddenSecrets={text:'anything\nraw\n'};
87 + assert.throws(()=>previewHolooDelimitedExport(sample),/SOURCE_UNSUPPORTED_TABLE/);
88 +});
89 +
90 +test('A02: text containing prototype-like column header cannot poison object prototype', () => {
91 + const result=parseStrictDelimitedRows('__proto__,constructor,id\nhijack,x,C1\n');
92 + assert.equal(result.rows[0]['__proto__'],'hijack');
93 + assert.equal(({}).hijack,undefined);
94 +});
95 +
96 +test('A02: diagnostics never expose raw bank IDs, contacts or formulas', () => {
97 + const sample=fixture();
98 + sample.tables.cheques.text='id,amount,name\nPRIVATE1234,-25,"=HYPERLINK(""https://example.invalid"")"\n';
99 + const outcome=previewHolooDelimitedExport(sample,{maxIssues:1});
100 + assert.equal(outcome.status,'blocked');
101 + for(const term of ['PRIVATE1234','HYPERLINK','example.invalid'])
102 + assert.ok(!JSON.stringify(outcome).includes(term));
103 + assert.equal(outcome.writePerformed,false);
104 + assert.equal(outcome.importPerformed,false);
105 +});
106 +
107 +test('A02: reject large cells and unsupported separator without emitting source text', () => {
108 + assert.throws(()=>parseStrictDelimitedRows('id,name\n1,'+'z'.repeat(270000)),/CSV_CELL_TOO_LARGE/);
109 + assert.throws(()=>parseStrictDelimitedRows('id|name\n1|x',{delimiter:'|'}),/CSV_UNSUPPORTED_DELIMITER/);
110 +});