Simpl-Resultat/src/utils/headerDictionary.ts
le king fu 6f64fc5c1a
All checks were successful
PR Check — Frontend / frontend (pull_request) Successful in 1m56s
feat(import): detect transaction columns by header label
Detection reasoned on the shape of the data alone, so it could not tell a debit
column from a credit one: a file laid out `Date;Description;Credit;Debit` was
mapped by position and every sign of the import came out inverted — silently,
since the total is merely negated and no aggregate check notices.

A new `headerDictionary.ts` carries the FR/EN transaction dictionary (date,
description, amount, debit, credit, balance) plus the two matching helpers,
moved out of `csvAutoDetect.ts` whose holdings tables stay untouched: `montant`
is an exclusion token there and the primary amount keyword here, so the two
tables cannot be merged. Moving the generic helpers rather than exporting them
keeps the dependency one-way.

`csvAutoDetect` puts that layer in front of the shape heuristics. Labels resolve
the debit/credit order, the date, description and single-amount columns, and
give `detectHeader` a second signal for a header row carrying a bare number.
Every hint is a preference the data can veto — a labelled date column must still
parse, a labelled balance column is never excluded if it would leave nothing to
map — and a mute file (no header row, unknown labels) falls back to the shape
heuristics unchanged.

Files pairing unsigned amounts with an adjacent D/C indicator column are now
detected and REFUSED with a dedicated message, instead of being configured as
`positive_expense` and importing every deposit as an expense. Detection reports
that reason through `detectImportFormat`; `autoDetectConfig` keeps its previous
shape for the callers that only need the configuration.

Resolves #327
2026-08-13 13:58:02 -04:00

176 lines
6.3 KiB
TypeScript

/**
* Header dictionary for the TRANSACTION import flow (#327).
*
* Detection used to reason on the SHAPE of the data alone — which column parses
* as a date, which one carries the most characters, which pair is sparse and
* complementary. Shape cannot tell a debit column from a credit column, so a
* file laid out `Date;Description;Crédit;Débit` was mapped backwards and every
* sign of the import was inverted. This module is the lexical layer that reads
* the header labels; `csvAutoDetect.ts` puts it in FRONT of the shape
* heuristics and falls back to them whenever the labels are mute (no header
* row, unknown labels).
*
* WHY ITS OWN MODULE. The holdings flow (#245) already matches header labels,
* with its own keyword tables living in `csvAutoDetect.ts`. Merging the two
* tables is not possible: `montant` is an EXCLUSION token there
* (`VALUE_HEADER_KEYWORDS` — a market-value column must never be read as a unit
* price) and it is the PRIMARY amount keyword here. Two flows, two tables. Only
* the two matching helpers are generic, so they live here and the holdings flow
* imports them, unchanged — one direction of dependency, no cycle.
*/
// Keyword tables, matched as SUBSTRINGS against accent-stripped,
// alphanumeric-only header cells, so `Date de l'opération` matches `date` and
// `Débit ($)` matches `debit`. Bilingual FR + EN, order inside each list is
// priority order. Kept deliberately tight: a keyword that fires on the wrong
// column is worse than a keyword that never fires, because the shape heuristic
// behind it is the behaviour the corpus already froze.
export const DATE_HEADER_KEYWORDS = ["date"];
export const DESCRIPTION_HEADER_KEYWORDS = [
"description",
"libelle",
"detail",
"transaction",
];
export const AMOUNT_HEADER_KEYWORDS = ["montant", "amount"];
export const DEBIT_HEADER_KEYWORDS = [
"debit",
"retrait",
"debourse",
"withdrawal",
];
export const CREDIT_HEADER_KEYWORDS = [
"credit",
"depot",
"encaissement",
"deposit",
];
export const BALANCE_HEADER_KEYWORDS = ["solde", "balance"];
/**
* A running-balance column is never an amount column, and `Date de
* transaction` is never the description column. Both are exclusion lists rather
* than ordering tricks, because substring matching has no notion of "the best
* match" — the first column containing the keyword wins.
*/
const AMOUNT_EXCLUDE = BALANCE_HEADER_KEYWORDS;
const DESCRIPTION_EXCLUDE = DATE_HEADER_KEYWORDS;
/** Accent-strip + lowercase + keep alphanumerics only (for header matching). */
export function normalizeHeaderCell(s: string): string {
return (s ?? "")
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
}
/**
* Find the first unused column whose normalized header contains one of the
* keywords (keywords tried in priority order). `exclude` skips columns whose
* header contains any excluded token (e.g. a "value" column for price).
*/
export function matchHeaderColumn(
normalizedHeaders: string[],
keywords: string[],
used: Set<number>,
exclude: string[] = []
): number | null {
for (const kw of keywords) {
for (let i = 0; i < normalizedHeaders.length; i++) {
if (used.has(i)) continue;
const h = normalizedHeaders[i];
if (!h) continue;
if (exclude.some((ex) => h.includes(ex))) continue;
if (h.includes(kw)) return i;
}
}
return null;
}
/** What the labels of one header row say, role by role. */
export interface LexicalHeaderMap {
date: number | null;
description: number | null;
amount: number | null;
debit: number | null;
credit: number | null;
balance: number | null;
/** Number of roles the row actually named — 0 when the labels are mute. */
roleCount: number;
}
/**
* Read one header row through the dictionary.
*
* Roles are resolved in the order balance -> date -> debit -> credit -> amount
* -> description, each claiming its column so a later role cannot steal it.
* That order is what makes `Montant débit` / `Montant crédit` resolve as a
* debit/credit pair instead of the first one being read as THE amount column.
*
* Every field is `null` when no column names that role: a mute row yields a map
* of nulls and `roleCount: 0`, which is the caller's signal to fall back to the
* shape heuristics.
*/
export function matchTransactionHeaders(
headerRow: readonly string[]
): LexicalHeaderMap {
const normalized = headerRow.map(normalizeHeaderCell);
const used = new Set<number>();
const claim = (col: number | null): number | null => {
if (col !== null) used.add(col);
return col;
};
const balance = claim(
matchHeaderColumn(normalized, BALANCE_HEADER_KEYWORDS, used)
);
const date = claim(matchHeaderColumn(normalized, DATE_HEADER_KEYWORDS, used));
const debit = claim(
matchHeaderColumn(normalized, DEBIT_HEADER_KEYWORDS, used, AMOUNT_EXCLUDE)
);
const credit = claim(
matchHeaderColumn(normalized, CREDIT_HEADER_KEYWORDS, used, AMOUNT_EXCLUDE)
);
const amount = claim(
matchHeaderColumn(normalized, AMOUNT_HEADER_KEYWORDS, used, AMOUNT_EXCLUDE)
);
const description = claim(
matchHeaderColumn(
normalized,
DESCRIPTION_HEADER_KEYWORDS,
used,
DESCRIPTION_EXCLUDE
)
);
const roleCount = [date, description, amount, debit, credit, balance].filter(
(c) => c !== null
).length;
return { date, description, amount, debit, credit, balance, roleCount };
}
/**
* How many named roles a row must carry before the lexical layer is allowed to
* call it a header row on its own.
*
* Two, not one: a description cell like `DEPOT PAIE EMPLOYEUR` contains
* `depot`, so a single match proves nothing. Two distinct roles in one row is a
* shape a data row does not produce, and the caller keeps the date test in
* front of this check anyway.
*/
export const MIN_HEADER_ROLE_MATCHES = 2;
/**
* Tokens of a direction-indicator column: the third amount format, where the
* amount column holds unsigned magnitudes and a neighbouring column says which
* way each row goes. `D`/`C` in French exports, `DB`/`CR` in some English ones.
*
* The format is refused rather than imported (spec decision) — see
* `csvAutoDetect.ts`. Reading it correctly is a separate feature; reading it
* wrong imports every debit as income.
*/
export const DEBIT_INDICATOR_TOKENS = ["d", "db"];
export const CREDIT_INDICATOR_TOKENS = ["c", "cr"];