mirror of
https://github.com/Komediruzecki/token-circles.git
synced 2026-10-20 09:46:43 +02:00
A Google Sheet sync rejected 479 of 5,194 rows. Replaying the sheet through the real import path reproduced the reported rows exactly and pinned down three defects; two more were found reviewing the fix. 1. A blank description dropped the row, and only locally. The IndexedDB path required a description; the Worker never has, so the same sheet imported clean in the cloud and silently lost 291 rows in local mode. Those rows carry a date, an amount, a category and both accounts — a missing description is not a reason to discard one. The message was wrong twice over: description is not a number, and it named a field the numeric parser never validates. A Worker test now pins that side of the contract. 2. The rejection label was cut mid-token. importRowLabel sliced the date to ten characters to drop a trailing time, but the frontend reads sheets through the Google Visualization API, which delivers `Date(2026,1,7)` — sliced to `Date(2026,`. It now trims only when the value leads with a calendar date, and the local path labels from the normalized date. 3. One CSV parser instead of two. Both runtimes split the text into lines before tracking quotes, so a quoted cell containing a newline — how Sheets exports every multi-line cell — was torn into fragments: the real row vanished and short, column-shifted junk rows took its place, silently. The parser now carries quote state across newlines, handles the RFC 4180 `""` escape the old copies dropped, and lives in shared/ so the two cannot drift. 4. A byte-order mark ahead of a quoted header left the header as `"description"` with the quotes attached, which silently unmaps a saved header→column mapping. Unquoted headers survived by accident, since trim() drops U+FEFF. 5. Padding before an opening quote (`a, "b"`) is accepted again, as the parsers this replaced did — the Worker ingests uploaded and emailed CSVs from arbitrary producers. A missing date still rejects the row, now saying "No date — every transaction needs one" rather than blaming the number format.
100 lines
3.6 KiB
TypeScript
100 lines
3.6 KiB
TypeScript
/**
|
|
* CSV parsing for imports.
|
|
*
|
|
* Both runtimes had their own hand-rolled copy (worker/src/routes/imports.ts and the IndexedDB
|
|
* handler), and both carried the same defect: they split the text into lines FIRST and only then
|
|
* tracked quotes. A quoted cell is allowed to contain a newline — Google Sheets exports any
|
|
* multi-line cell that way — so such a record was torn into fragments, each parsed as its own
|
|
* short row. The result was silent corruption: a row that never appeared, plus one or two junk
|
|
* rows with the columns shifted.
|
|
*
|
|
* This is a single scanner over the whole text that tracks quote state across newlines, so a
|
|
* record ends only at a newline that is genuinely outside quotes. It also handles the RFC 4180
|
|
* escape for a literal quote (`""` inside a quoted field), which the old copies dropped.
|
|
*
|
|
* Lives in shared/ so the Worker and the frontend cannot drift apart again.
|
|
*/
|
|
|
|
export interface ParsedCsv {
|
|
headers: string[];
|
|
rows: string[][];
|
|
}
|
|
|
|
/**
|
|
* Parse RFC 4180-ish CSV: comma-delimited, `"`-quoted fields, `""` for a literal quote inside a
|
|
* quoted field, and CR/LF or LF record separators. Unquoted cells are trimmed (sheet exports pad
|
|
* them); quoted cells are preserved verbatim, since the quotes are how a sheet says "this
|
|
* whitespace is mine".
|
|
*/
|
|
export function parseImportCsv(input: string): ParsedCsv {
|
|
// Strip a leading byte-order mark. Spreadsheet exports (Excel especially) routinely prefix one,
|
|
// and it would otherwise ride along inside the first header — silently breaking a saved
|
|
// header→column mapping, which matches header names exactly. The line-splitting parsers this
|
|
// replaced got this for free from `text.trim()`, since U+FEFF counts as whitespace to trim().
|
|
const text = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
|
|
const records: string[][] = [];
|
|
let row: string[] = [];
|
|
let cell = '';
|
|
let quoted = false; // this cell is a quoted field
|
|
let inQuotes = false; // currently inside the quotes
|
|
|
|
const endCell = () => {
|
|
row.push(quoted ? cell : cell.trim());
|
|
cell = '';
|
|
quoted = false;
|
|
};
|
|
const endRow = () => {
|
|
endCell();
|
|
records.push(row);
|
|
row = [];
|
|
};
|
|
|
|
for (let i = 0; i < text.length; i++) {
|
|
const ch = text[i]!;
|
|
if (inQuotes) {
|
|
if (ch === '"') {
|
|
if (text[i + 1] === '"') {
|
|
cell += '"'; // escaped quote
|
|
i++;
|
|
} else {
|
|
inQuotes = false;
|
|
}
|
|
} else {
|
|
cell += ch;
|
|
}
|
|
continue;
|
|
}
|
|
if (ch === '"' && !quoted && cell.trim() === '') {
|
|
// A quote opens a quoted field only at the start of a cell — anywhere else it is content,
|
|
// so `12" pipe` keeps its inch mark. Padding ahead of the quote is tolerated and dropped
|
|
// (`a, "b"` → `b`): strict RFC 4180 says such a field is unquoted, but producers emit it
|
|
// and the parsers this replaced accepted it by stripping the outer quotes after trimming.
|
|
inQuotes = true;
|
|
quoted = true;
|
|
cell = '';
|
|
continue;
|
|
}
|
|
if (ch === ',') {
|
|
endCell();
|
|
continue;
|
|
}
|
|
if (ch === '\r') {
|
|
if (text[i + 1] === '\n') i++;
|
|
endRow();
|
|
continue;
|
|
}
|
|
if (ch === '\n') {
|
|
endRow();
|
|
continue;
|
|
}
|
|
cell += ch;
|
|
}
|
|
// Trailing cell/record — unless the text ended exactly on a record separator.
|
|
if (cell !== '' || row.length > 0 || quoted) endRow();
|
|
|
|
// Drop wholly empty records (trailing blank lines, and the blank rows sheets like to export).
|
|
const all = records.filter((r) => r.some((c) => c !== ''));
|
|
const headers = all[0] || [];
|
|
return { headers, rows: all.slice(1) };
|
|
}
|