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

feat(A02): parse explicit mapped safe Holoo CSV extracts read-only

davoodmehraban89 committed Oct 17, 2026 at 02:02 UTC 59ac63b96f7ce1d7fa7786277cf8acc73839fb22
1 file changed +143
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 +}