/** * Duplicate detection for incoming exports. Three separate events, one message each: * * 1. repeated column name in the header - the parser keeps only the last one, * so values of the earlier columns are already lost by the time rows exist; * 2. a full copy of a data row (raw cells byte-equal) - always cut; * 3. a repeated natural key with different cells (renumbered "№ п/п", another * comment, or a genuine disagreement of values). * * Comparison for (2) uses the RAW cell grid, not the parsed record: the customer * format has ten unnamed columns, and the parser collapses them into one key, so * two different rows would look identical as records. * * Mode 'cut' drops the later rows into quarantine and keeps the first one, per the * owner's decision of 07.08.2026. Mode 'warn' only reports: it is used where a * repeated key can be legitimate (see comments at the call sites in load.js). */ const MAX_EXAMPLES = 3; /** Repeated NON-EMPTY header names. Empty ones are normal in the customer format. */ export function findDuplicateColumns(headers) { const seen = new Map(); const repeated = []; for (const header of headers ?? []) { const name = String(header ?? '').trim(); if (name === '') continue; const count = (seen.get(name) ?? 0) + 1; seen.set(name, count); if (count === 2) repeated.push(name); } return repeated.map((name) => ({ name, count: seen.get(name) })); } function plural(count, one, few, many) { const tens = count % 100; const ones = count % 10; if (tens >= 11 && tens <= 14) return `${count} ${many}`; if (ones === 1) return `${count} ${one}`; if (ones >= 2 && ones <= 4) return `${count} ${few}`; return `${count} ${many}`; } /** * Guard over rows of one file. Call check() for every row in file order; it * answers whether the row should be kept. Call finish() once at the end - it * emits ONE aggregated warning per kind, so a file made entirely of duplicates * cannot push other warnings out of the list. */ export function createRowGuard({ ctx, mode = 'cut' }) { const seen = new Map(); const copies = []; const conflicts = []; return { /** * @param key natural key of the row (array of strings) * @param record parsed row as it will be shown - decides "same values or not" * @param cells raw cells of this row, for the byte-equal copy test * @param number 1-based number of the data row, for human-readable messages */ check(key, record, cells, number) { const id = JSON.stringify(key); const previous = seen.get(id); if (!previous) { seen.set(id, { record, cells, number }); return true; } const isCopy = JSON.stringify(cells ?? []) === JSON.stringify(previous.cells ?? []); if (isCopy) { copies.push({ number, first: previous.number }); ctx?.reject(`строка данных №${number} полностью повторяет строку №${previous.number}`, record); return false; } const sameValues = JSON.stringify(record) === JSON.stringify(previous.record); conflicts.push({ number, first: previous.number, sameValues, record, previous: previous.record }); if (mode === 'warn') return true; ctx?.reject(sameValues ? `строка данных №${number} повторяет строку №${previous.number} (значения совпадают)` : `строка данных №${number} спорит со строкой №${previous.number} по тем же данным`, record); return false; }, finish() { if (copies.length > 0) { const examples = copies.slice(0, MAX_EXAMPLES) .map((item) => `№${item.number} = №${item.first}`).join(', '); ctx?.warn('duplicate-rows', `${plural(copies.length, 'строка', 'строки', 'строк')} ` + `полностью повторяет другие и не принята: ${examples}` + (copies.length > MAX_EXAMPLES ? ' и другие' : '')); } if (conflicts.length === 0) return; const cut = mode !== 'warn'; const first = conflicts[0]; const detail = first.sameValues ? 'значения совпадают - похоже на скопированную строку' : `значения разные: ${describe(first.previous)} против ${describe(first.record)}`; ctx?.warn('conflicting-rows', `${plural(conflicts.length, 'строка повторяет', 'строки повторяют', 'строк повторяют')} ` + `данные других строк того же файла (например, №${first.number} и №${first.first}); ${detail}. ` + (cut ? 'Принята первая строка, остальные отложены - проверьте, какая права' : 'Приняты все строки: в этом файле повтор может быть законным - проверьте выгрузку')); }, }; } /** * Runs the guard over parsed rows and returns those that survive. * @param entries array of { record, index } where index is the row index in source.rows * @param matrix raw cell grid from parseCsv (matrix[0] is the header row) */ export function guardRows(entries, { ctx, mode = 'cut', keyOf, matrix = [] }) { const guard = createRowGuard({ ctx, mode }); const kept = entries.filter(({ record, index }) => guard.check( keyOf(record), record, matrix[index + 1], index + 1, )); guard.finish(); return kept.map((item) => item.record); } /** Short human-readable value of a row for the warning text. */ function describe(record) { if (record === null || typeof record !== 'object') return String(record); for (const field of ['fact', 'value', 'balance', 'amount', 'vat', 'closeBalance']) { if (record[field] !== undefined && record[field] !== null) return String(record[field]); } return 'другое значение'; } /** * Rows that became equal only AFTER company names were canonicalized: the * reference book may legitimately merge two spellings of one company, but it may * also merge two different companies. Never cuts - only reports. */ export function findMergedCompanyRows(rows, keyOf) { const seen = new Map(); const merged = []; for (const row of rows ?? []) { const id = JSON.stringify(keyOf(row)); if (seen.has(id)) merged.push(row); else seen.set(id, row); } return merged; }