Skip to content

Scrubs bank statements locally & analyse with Groq.

Python

Step 9: vanilla JS frontend; fix phone rule eating the next line

asadullahdot1d229b424a3b
diff --git a/app/localparse.py b/app/localparse.py
index 8e40ab1..0fe81aa 100644
--- a/app/localparse.py
+++ b/app/localparse.py
@@ -167,6 +167,8 @@ def guess_merchant(description: str) -> str | None:
s = _PREFIX.sub("", s, count=1)
elif (m := _PREFIX_ANY.search(s)): # CSV rows start with the "type" column
s = s[m.end():]
+ if (m := _PREFIX_ANY.match(s)): # "POS" + "Paid to X": strip the second prefix too
+ s = s[m.end():]
s = _STOP.split(s, maxsplit=1)[0]
words = [w for w in s.split() if not re.fullmatch(r"[#\d\-/:.]+", w)][:4]
name = " ".join(words).strip(" -:/")
diff --git a/app/scrubber.py b/app/scrubber.py
index 981e6b5..751524b 100644
--- a/app/scrubber.py
+++ b/app/scrubber.py
@@ -237,7 +237,9 @@ def scrub_text(text: str) -> str:
return "<PHONE>"
# International: +92-300-1234567, +44 7700 900123, +1 (512) 555-0148
- t = _sub(r"(?<![\w.,])\+\d{1,3}(?:[\s.-]?(?:\(\d{1,5}\)|\d{1,5})){2,5}", phone, t)
+ # The separator is a space, tab, dot or dash but NOT a newline: "+44 7700 900123\n01 Apr 2026"
+ # must not swallow the next line's date.
+ t = _sub(r"(?<![\w.,])\+\d{1,3}(?:[ \t .-]?(?:\(\d{1,5}\)|\d{1,5})){2,5}", phone, t)
t = _sub(r"(?<![\w.,])\(0\d{3}\)\s?\d{7}\b", "<PHONE>", t) # PK: (0315) 1234567
t = _sub(r"(?<![\w.,])0\d{3}[ -]?\d{7}\b", "<PHONE>", t) # PK: 0300-1234567
t = _sub(r"(?<![\w.,])0\d{4}[ ]?\d{6}\b", "<PHONE>", t) # UK: 07700 900123
diff --git a/frontend/app.js b/frontend/app.js
new file mode 100644
index 0000000..b8000eb
--- /dev/null
+++ b/frontend/app.js
@@ -0,0 +1,358 @@
+// Vanilla JS front end for the Statement Scrubber API (same origin, no framework).
+// Everything that comes from a statement or from the model is put on the page with
+// textContent, never innerHTML, so text inside a statement cannot inject markup.
+"use strict";
+
+const $ = (id) => document.getElementById(id);
+const state = { runId: null, analysis: null, currency: null, timer: null };
+
+// ---------------------------------------------------------------- helpers
+function el(tag, props = {}, ...kids) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === "class") node.className = v;
+ else if (k === "text") node.textContent = v;
+ else node.setAttribute(k, v);
+ }
+ for (const kid of kids) if (kid != null) node.append(kid);
+ return node;
+}
+
+function fmt(n) {
+ return Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+}
+
+function setStatus(msg, isErr = false) {
+ const s = $("status");
+ s.textContent = msg || "";
+ s.className = "status" + (isErr ? " err" : "");
+}
+
+async function api(path, options = {}) {
+ let res;
+ try {
+ res = await fetch(path, options);
+ } catch (e) {
+ throw new Error("Cannot reach the API. Is `uvicorn app.main:app` running?");
+ }
+ if (res.status === 204) return null;
+ const type = res.headers.get("content-type") || "";
+ const body = type.includes("json") ? await res.json() : await res.text();
+ if (!res.ok) {
+ let msg = body && body.detail !== undefined ? body.detail : body;
+ if (msg && typeof msg === "object") msg = msg.message || JSON.stringify(msg);
+ const err = new Error(String(msg) || res.statusText);
+ err.status = res.status;
+ throw err;
+ }
+ return body;
+}
+
+function busy(btn, on, label) {
+ if (on) { btn.dataset.label = btn.textContent; btn.textContent = label; btn.disabled = true; }
+ else { btn.textContent = btn.dataset.label || btn.textContent; btn.disabled = false; }
+}
+
+// ---------------------------------------------------------------- health + runs list
+async function checkHealth() {
+ try {
+ const h = await api("/health");
+ setStatus(h.database === "up" ? "API and PostgreSQL are up." : "API is up but PostgreSQL is not reachable.", h.database !== "up");
+ } catch (e) { setStatus(e.message, true); }
+}
+
+async function loadRuns(selectId) {
+ try {
+ const runs = await api("/runs");
+ const sel = $("runs");
+ sel.replaceChildren(el("option", { value: "", text: runs.length ? "choose a run..." : "none yet" }));
+ for (const r of runs) {
+ const when = new Date(r.created_at).toLocaleString();
+ sel.append(el("option", { value: r.run_id, text: `#${r.run_id} ${when} (${r.file_count} files)` }));
+ }
+ if (selectId) sel.value = String(selectId);
+ } catch (e) { setStatus(e.message, true); }
+}
+
+// ---------------------------------------------------------------- 1. scrub
+function renderRun(run) {
+ state.runId = run.run_id;
+ state.analysis = null;
+ $("run-info").hidden = false;
+ $("run-title").textContent = `Run #${run.run_id}: ${run.file_count} file(s) scrubbed and stored`;
+ const dl = $("dl");
+ dl.href = `/runs/${run.run_id}/combined`;
+ dl.setAttribute("download", `run_${run.run_id}_scrubbed.txt`);
+
+ const chips = $("chips");
+ chips.replaceChildren();
+ const counts = Object.entries(run.placeholder_counts || {}).sort((a, b) => b[1] - a[1]);
+ if (!counts.length) chips.append(el("span", { class: "chip", text: "nothing removed" }));
+ for (const [tag, n] of counts) chips.append(el("span", { class: "chip", text: `${tag} x ${n}` }));
+
+ const tb = $("files-table").tBodies[0];
+ tb.replaceChildren();
+ for (const f of run.files || []) {
+ const removed = Object.values(f.placeholder_counts || {}).reduce((a, b) => a + b, 0);
+ tb.append(el("tr", {},
+ el("td", { text: f.filename }), el("td", { text: f.file_type }),
+ el("td", { text: f.status }), el("td", { class: "num", text: String(f.chars) }),
+ el("td", { text: String(removed) })));
+ }
+ $("combined").textContent = run.combined_text || "";
+
+ $("btn-delete").disabled = false;
+ $("btn-analyze").disabled = false;
+ $("s2").classList.remove("locked");
+ resetAnalysis();
+ resetChat();
+}
+
+async function openRun(id) {
+ setStatus(`Loading run #${id}...`);
+ try {
+ renderRun(await api(`/runs/${id}`));
+ $("runs").value = String(id);
+ setStatus("");
+ try { renderAnalysis(await api(`/runs/${id}/analysis`)); } catch (e) { if (e.status !== 404) throw e; }
+ if (state.analysis) await loadChat();
+ } catch (e) { setStatus(e.message, true); }
+}
+
+async function scrub(request, button, label) {
+ busy(button, true, label);
+ setStatus("Scrubbing...");
+ try {
+ const run = await api(request.path, request.options);
+ renderRun(run);
+ await loadRuns(run.run_id);
+ setStatus(`Run #${run.run_id} saved. Next: analyse it.`);
+ } catch (e) { setStatus(e.message, true); }
+ finally { busy(button, false); }
+}
+
+$("btn-upload").addEventListener("click", () => {
+ const files = $("files").files;
+ if (!files.length) { setStatus("Choose one or more statement files first.", true); return; }
+ const fd = new FormData();
+ for (const f of files) fd.append("files", f);
+ scrub({ path: "/runs", options: { method: "POST", body: fd } }, $("btn-upload"), "Scrubbing...");
+});
+
+$("btn-folder").addEventListener("click", () => {
+ scrub({ path: "/runs/from-folder", options: {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ folder: "data" }) } },
+ $("btn-folder"), "Scrubbing...");
+});
+
+$("runs").addEventListener("change", (e) => { if (e.target.value) openRun(e.target.value); });
+
+$("btn-delete").addEventListener("click", async () => {
+ if (!state.runId || !confirm(`Delete run #${state.runId} and its analysis and chat? This cannot be undone.`)) return;
+ try {
+ await api(`/runs/${state.runId}`, { method: "DELETE" });
+ state.runId = null;
+ $("run-info").hidden = true;
+ $("btn-delete").disabled = true; $("btn-analyze").disabled = true;
+ $("s2").classList.add("locked"); $("s3").classList.add("locked");
+ resetAnalysis(); resetChat();
+ await loadRuns();
+ setStatus("Run deleted.");
+ } catch (e) { setStatus(e.message, true); }
+});
+
+// ---------------------------------------------------------------- 2. analysis
+function resetAnalysis() {
+ state.analysis = null;
+ $("an").hidden = true;
+ $("an-msg").hidden = true;
+ $("timer").textContent = "";
+}
+
+function showNotice(text, isErr) {
+ const n = $("an-msg");
+ n.textContent = text;
+ n.className = "notice" + (isErr ? " err" : "");
+ n.hidden = false;
+}
+
+$("btn-analyze").addEventListener("click", async () => {
+ if (!state.runId) return;
+ const btn = $("btn-analyze");
+ busy(btn, true, "Analysing...");
+ $("an-msg").hidden = true;
+ const started = Date.now();
+ $("timer").textContent = "0 s";
+ state.timer = setInterval(() => { $("timer").textContent = `${Math.round((Date.now() - started) / 1000)} s`; }, 500);
+ try {
+ const mode = $("mode").value;
+ const a = await api(`/runs/${state.runId}/analysis?mode=${encodeURIComponent(mode)}`, { method: "POST" });
+ renderAnalysis(a);
+ await loadChat();
+ setStatus("Analysis stored. You can now chat about the data.");
+ } catch (e) {
+ showNotice(e.status === 429 ? e.message : `Analysis failed: ${e.message}`, true);
+ } finally {
+ clearInterval(state.timer);
+ busy(btn, false);
+ }
+});
+
+function chip(text, kind = "") { return el("span", { class: "chip " + kind, text }); }
+
+function renderAnalysis(a) {
+ state.analysis = a;
+ const v = a.validation || {};
+ const r = a.result || {};
+ $("an").hidden = false;
+
+ const chips = $("an-chips");
+ chips.replaceChildren(
+ chip(`mode: ${v.mode || "llm"}`), chip(`model: ${v.model || a.model}`),
+ chip(`${v.kept ?? (r.transactions || []).length} transactions verified`, "ok"));
+ if (v.rows_from_local_parser != null) chips.append(chip(`${v.rows_from_local_parser} read locally`));
+ if (v.rows_from_model) chips.append(chip(`${v.rows_from_model} read by the model`));
+ chips.append(chip(`${v.model_calls ?? 0} model call(s)`), chip(`${v.seconds_total ?? "?"} s`));
+ const dropped = Object.entries(v).filter(([k, n]) => k.startsWith("dropped_") && n > 0);
+ for (const [k, n] of dropped) chips.append(chip(`${k.replace("dropped_", "dropped: ").replaceAll("_", " ")} (${n})`, "warn"));
+ if (v.insights_from_template) chips.append(chip("insights from template", "warn"));
+ if ((v.injection_phrases_found || []).length) chips.append(chip("possible injection text in statement (ignored)", "warn"));
+
+ if (v.llm_problem) {
+ const why = { daily_limit: "Groq's daily limit was reached", no_api_key: "no GROQ_API_KEY is set", model_error: "the model returned unusable output" }[v.llm_problem] || "the model was unavailable";
+ showNotice(`${why}, so this analysis was completed locally: rule-based categories and template insights.`, false);
+ }
+
+ const byCur = r.by_currency || {};
+ const currencies = Object.keys(byCur).sort((x, y) => byCur[y].transactions - byCur[x].transactions);
+ if (!currencies.includes(state.currency)) state.currency = currencies[0] || null;
+ const tabs = $("tabs");
+ tabs.replaceChildren();
+ for (const c of currencies) {
+ const b = el("button", { role: "tab", "aria-selected": String(c === state.currency), text: `${c} (${byCur[c].transactions})` });
+ b.addEventListener("click", () => { state.currency = c; renderAnalysis(state.analysis); });
+ tabs.append(b);
+ }
+ renderCurrency(r, state.currency);
+
+ const ul = $("insights");
+ ul.replaceChildren();
+ for (const t of r.insights || []) ul.append(el("li", { text: t }));
+ if (!(r.insights || []).length) ul.append(el("li", { class: "empty", text: "No insights passed the number check." }));
+
+ const flags = $("flags");
+ flags.replaceChildren();
+ const dups = r.possible_duplicates || [];
+ const revs = r.reversals_and_refunds || [];
+ if (dups.length) {
+ flags.append(el("h3", { text: "Possible duplicates (kept, flagged)" }));
+ for (const d of dups) flags.append(el("div", { class: "small", text: `${d.date}: ${d.currency} ${fmt(d.amount)} listed ${d.times_listed}x` }));
+ }
+ if (revs.length) {
+ flags.append(el("h3", { text: "Refunds and reversals (not counted as spending)" }));
+ for (const x of revs) flags.append(el("div", { class: "small", text: `${x.date}: ${x.currency} ${fmt(x.amount)} (${x.direction})` }));
+ }
+}
+
+function renderCurrency(r, cur) {
+ const cards = $("cur-cards"), cats = $("cats"), tb = $("merch").tBodies[0];
+ cards.replaceChildren(); cats.replaceChildren(); tb.replaceChildren();
+ if (!cur) return;
+ const b = r.by_currency[cur];
+ const items = [["Income", b.income], ["Spending", b.spending], ["Money in", b.total_in], ["Money out", b.total_out], ["Net", b.net]];
+ for (const [k, val] of items) cards.append(el("div", { class: "card" }, el("div", { class: "k", text: k }), el("div", { class: "v", text: `${cur} ${fmt(val)}` })));
+
+ const list = (r.spending_by_category || {})[cur] || [];
+ const max = Math.max(...list.map((c) => c.spent), 1);
+ for (const c of list) {
+ const bar = el("div", { class: "bar" }, el("i"));
+ bar.firstChild.style.width = `${(100 * c.spent) / max}%`;
+ cats.append(el("div", { class: "bar-row" },
+ el("span", { text: c.category.replaceAll("_", " ") }), bar, el("span", { class: "num", text: `${fmt(c.spent)} (${c.share_pct}%)` })));
+ }
+ if (!list.length) cats.append(el("div", { class: "empty", text: "No spending in this currency." }));
+
+ for (const m of ((r.top_merchants || {})[cur] || [])) {
+ tb.append(el("tr", {}, el("td", { text: m.merchant }), el("td", { class: "num", text: `${m.times}x` }), el("td", { class: "num", text: fmt(m.spent) })));
+ }
+}
+
+// ---------------------------------------------------------------- 3. chat
+function resetChat() {
+ $("chat-log").replaceChildren();
+ const on = !!state.analysis;
+ $("s3").classList.toggle("locked", !on);
+ for (const id of ["q", "btn-send", "btn-clear"]) $(id).disabled = !on;
+}
+
+function addMsg(kind, text) {
+ const m = el("div", { class: `msg ${kind}` }, el("div", { text }));
+ const log = $("chat-log");
+ log.append(m);
+ log.scrollTop = log.scrollHeight;
+ return m;
+}
+
+async function loadChat() {
+ resetChat();
+ if (!state.analysis) return;
+ try {
+ for (const m of await api(`/runs/${state.runId}/chat`)) addMsg(m.role === "user" ? "user" : "bot", m.content);
+ } catch (e) { setStatus(e.message, true); }
+}
+
+function renderBotMeta(m, d) {
+ const meta = el("div", { class: "meta" });
+ meta.append(d.verified ? chip("numbers verified", "ok") : chip("could not verify the figures", "warn"), " ");
+ if (!d.in_scope) meta.append(chip("not answerable from the data"), " ");
+ meta.append(chip(`${d.history_turns_used} earlier turn(s) in context`));
+ if (d.unverified_numbers_caught) meta.append(" ", chip(`${d.unverified_numbers_caught} wrong figure(s) caught`, "warn"));
+ m.append(meta);
+ const comp = Object.entries(d.computed || {});
+ if (comp.length) {
+ m.append(el("div", { class: "meta", text: "Computed by the app from the rows used: " +
+ comp.map(([c, b]) => `${c}: ${b.count} transaction(s), out ${fmt(b.total_out)}, in ${fmt(b.total_in)}`).join("; ") }));
+ }
+ if ((d.sources || []).length) {
+ const tbl = el("table", { class: "tbl" }, el("thead", {}, el("tr", {}, ...["Date", "Merchant", "Category", "Amount"].map((h) => el("th", { text: h })))));
+ const body = el("tbody");
+ for (const s of d.sources) {
+ body.append(el("tr", {}, el("td", { text: s.date }), el("td", { text: s.merchant || "" }), el("td", { text: s.category }),
+ el("td", { class: "num", text: `${s.direction === "credit" ? "+" : "-"}${s.currency} ${fmt(s.amount)}` })));
+ }
+ tbl.append(body);
+ m.append(el("details", {}, el("summary", { text: `Rows used (${d.sources.length})` }), tbl));
+ }
+}
+
+$("chat-form").addEventListener("submit", async (e) => {
+ e.preventDefault();
+ const q = $("q").value.trim();
+ if (!q || !state.runId) return;
+ $("q").value = "";
+ addMsg("user", q);
+ const pending = addMsg("bot", "Thinking...");
+ $("btn-send").disabled = true; $("q").disabled = true;
+ try {
+ const d = await api(`/runs/${state.runId}/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question: q }) });
+ pending.replaceChildren(el("div", { text: d.answer }));
+ if (d.question_as_sent !== q) pending.append(el("div", { class: "meta", text: `Sent as: ${d.question_as_sent} (identifiers removed)` }));
+ renderBotMeta(pending, d);
+ } catch (err) {
+ pending.replaceChildren(el("div", { text: err.status === 429 ? err.message : `Could not answer: ${err.message}` }));
+ } finally {
+ $("btn-send").disabled = false; $("q").disabled = false; $("q").focus();
+ $("chat-log").scrollTop = $("chat-log").scrollHeight;
+ }
+});
+
+$("btn-clear").addEventListener("click", async () => {
+ if (!state.runId) return;
+ try { await api(`/runs/${state.runId}/chat`, { method: "DELETE" }); $("chat-log").replaceChildren(); }
+ catch (e) { setStatus(e.message, true); }
+});
+
+// ---------------------------------------------------------------- start
+resetChat();
+checkHealth();
+loadRuns();
diff --git a/frontend/index.html b/frontend/index.html
new file mode 100644
index 0000000..4d7e3c3
--- /dev/null
+++ b/frontend/index.html
@@ -0,0 +1,90 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Statement Scrubber</title>
+<link rel="stylesheet" href="style.css">
+</head>
+<body>
+<header>
+ <h1>Statement Scrubber</h1>
+ <p class="sub">Raw statements are scrubbed on this machine. Only the scrubbed text is stored and analysed.</p>
+ <div id="status" class="status" aria-live="polite"></div>
+</header>
+
+<main>
+ <!-- 1. SCRUB -->
+ <section id="s1">
+ <h2><span class="n">1</span> Scrub</h2>
+ <div class="row">
+ <input id="files" type="file" multiple accept=".pdf,.docx,.csv,.txt,.xlsx">
+ <button id="btn-upload" class="primary">Scrub selected files</button>
+ <span class="or">or</span>
+ <button id="btn-folder">Scrub the <code>data/</code> folder</button>
+ </div>
+ <div class="row small">
+ <label for="runs">Earlier runs</label>
+ <select id="runs"><option value="">-</option></select>
+ <button id="btn-delete" class="danger" disabled>Delete run</button>
+ </div>
+ <div id="run-info" hidden>
+ <div class="row">
+ <strong id="run-title"></strong>
+ <a id="dl" class="link" download>Download combined text</a>
+ </div>
+ <div id="chips" class="chips"></div>
+ <table id="files-table" class="tbl">
+ <thead><tr><th>File</th><th>Type</th><th>Status</th><th class="num">Characters</th><th>Removed</th></tr></thead>
+ <tbody></tbody>
+ </table>
+ <details open>
+ <summary>Combined scrubbed output</summary>
+ <pre id="combined"></pre>
+ </details>
+ </div>
+ </section>
+
+ <!-- 2. ANALYSIS -->
+ <section id="s2" class="locked">
+ <h2><span class="n">2</span> Analysis</h2>
+ <div class="row">
+ <button id="btn-analyze" class="primary" disabled>Analyse with Groq</button>
+ <label for="mode" class="small">Mode</label>
+ <select id="mode">
+ <option value="hybrid">hybrid: local parser + model for the rest</option>
+ <option value="llm">llm: model reads every line</option>
+ <option value="local">local: no model call</option>
+ </select>
+ <span id="timer" class="small"></span>
+ </div>
+ <div id="an-msg" class="notice" hidden></div>
+ <div id="an" hidden>
+ <div id="an-chips" class="chips"></div>
+ <div id="tabs" class="tabs" role="tablist"></div>
+ <div id="cur-cards" class="cards"></div>
+ <div class="grid2">
+ <div><h3>Spending by category</h3><div id="cats"></div></div>
+ <div><h3>Top merchants</h3><table id="merch" class="tbl"><tbody></tbody></table></div>
+ </div>
+ <h3>Insights</h3>
+ <ul id="insights"></ul>
+ <div id="flags"></div>
+ </div>
+ </section>
+
+ <!-- 3. CHAT -->
+ <section id="s3" class="locked">
+ <h2><span class="n">3</span> Chat about your data</h2>
+ <div id="chat-log" class="chat-log" aria-live="polite"></div>
+ <form id="chat-form" class="row">
+ <input id="q" type="text" maxlength="500" placeholder="e.g. How much did I spend on food? Which merchant did I pay most often?" autocomplete="off" disabled>
+ <button id="btn-send" class="primary" disabled>Ask</button>
+ <button id="btn-clear" type="button" class="small-btn" disabled>Clear chat</button>
+ </form>
+ <p class="small hint">Answers use only your scrubbed transactions. Every number is checked by the app before it is shown. Identifiers you type are scrubbed first.</p>
+ </section>
+</main>
+<script src="app.js"></script>
+</body>
+</html>
diff --git a/frontend/style.css b/frontend/style.css
new file mode 100644
index 0000000..ba33ea7
--- /dev/null
+++ b/frontend/style.css
@@ -0,0 +1,71 @@
+:root {
+ --bg: #f6f7f9; --card: #ffffff; --ink: #1b1f24; --muted: #5d6673; --line: #dfe3e8;
+ --accent: #1f6feb; --accent-ink: #ffffff; --ok: #1a7f37; --ok-bg: #e6f4ea;
+ --warn: #9a6700; --warn-bg: #fff4d6; --bad: #b42318; --bad-bg: #fde7e4; --bar: #7aa7f7;
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #14171b; --card: #1c2025; --ink: #e8ebef; --muted: #9aa4b1; --line: #2d333b;
+ --accent: #4c8dff; --accent-ink: #0b1220; --ok: #56d364; --ok-bg: #12301c;
+ --warn: #e3b341; --warn-bg: #3a2f10; --bad: #ff7b72; --bad-bg: #3d1a17; --bar: #3b66b8;
+ }
+}
+* { box-sizing: border-box; }
+body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
+header, main { max-width: 980px; margin: 0 auto; padding: 0 16px; }
+header { padding-top: 24px; }
+h1 { margin: 0; font-size: 1.6rem; }
+h2 { margin: 0 0 12px; font-size: 1.15rem; display: flex; align-items: center; gap: 10px; }
+h3 { margin: 18px 0 8px; font-size: .95rem; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
+.sub { margin: 4px 0 8px; color: var(--muted); }
+.n { display: inline-grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; background: var(--accent); color: var(--accent-ink); font-size: .85rem; }
+section { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 18px; margin: 16px 0; }
+section.locked { opacity: .55; }
+.row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 8px 0; }
+.small { font-size: .85rem; color: var(--muted); }
+.or { color: var(--muted); }
+button, select, input[type=text] { font: inherit; color: var(--ink); background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: 7px 12px; }
+input[type=file] { max-width: 100%; }
+button { cursor: pointer; }
+button:disabled { cursor: not-allowed; opacity: .5; }
+button.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 600; }
+button.danger { color: var(--bad); }
+button:focus-visible, select:focus-visible, input:focus-visible, a:focus-visible, summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+#q { flex: 1 1 280px; min-width: 0; }
+.link { color: var(--accent); }
+code { background: var(--bg); padding: 1px 5px; border-radius: 4px; }
+.status { min-height: 1.4em; font-size: .9rem; }
+.status.err { color: var(--bad); }
+.notice { padding: 10px 12px; border-radius: 6px; margin: 8px 0; background: var(--warn-bg); color: var(--warn); }
+.notice.err { background: var(--bad-bg); color: var(--bad); }
+.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0; }
+.chip { font-size: .8rem; padding: 2px 9px; border-radius: 999px; background: var(--bg); border: 1px solid var(--line); }
+.chip.ok { background: var(--ok-bg); color: var(--ok); border-color: transparent; }
+.chip.warn { background: var(--warn-bg); color: var(--warn); border-color: transparent; }
+.tbl { width: 100%; border-collapse: collapse; font-size: .9rem; margin: 8px 0; }
+.tbl th, .tbl td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
+.tbl th { color: var(--muted); font-weight: 600; font-size: .8rem; }
+.num { text-align: right !important; font-variant-numeric: tabular-nums; }
+pre { white-space: pre-wrap; word-break: break-word; background: var(--bg); border: 1px solid var(--line); border-radius: 6px; padding: 12px; max-height: 360px; overflow: auto; font: 12.5px/1.45 ui-monospace, Consolas, monospace; }
+summary { cursor: pointer; margin: 8px 0; font-weight: 600; }
+.tabs { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0; }
+.tabs button[aria-selected=true] { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
+.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
+.card { border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; }
+.card .k { font-size: .75rem; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
+.card .v { font-size: 1.15rem; font-weight: 600; font-variant-numeric: tabular-nums; }
+.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
+@media (max-width: 720px) { .grid2 { grid-template-columns: 1fr; } }
+.bar-row { display: grid; grid-template-columns: 120px 1fr 90px; align-items: center; gap: 8px; font-size: .88rem; margin: 4px 0; }
+.bar { height: 12px; background: var(--bg); border-radius: 6px; overflow: hidden; }
+.bar > i { display: block; height: 100%; background: var(--bar); }
+ul#insights { padding-left: 20px; margin: 6px 0; }
+.chat-log { display: flex; flex-direction: column; gap: 10px; max-height: 460px; overflow: auto; padding: 4px 2px; }
+.msg { max-width: 88%; padding: 9px 12px; border-radius: 10px; border: 1px solid var(--line); white-space: pre-wrap; word-break: break-word; }
+.msg.user { align-self: flex-end; background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
+.msg.bot { align-self: flex-start; background: var(--bg); }
+.msg .meta { margin-top: 6px; font-size: .78rem; color: var(--muted); white-space: normal; }
+.msg details { margin-top: 4px; white-space: normal; }
+.msg .tbl { font-size: .8rem; }
+.hint { margin: 6px 0 0; }
+.empty { color: var(--muted); font-style: italic; }
diff --git a/tests/test_hybrid.py b/tests/test_hybrid.py
index 307066b..7242e3c 100644
--- a/tests/test_hybrid.py
+++ b/tests/test_hybrid.py
@@ -247,3 +247,7 @@ def test_mode_must_be_known():
def test_cheque_lines_get_no_invented_merchant():
assert guess_merchant("CHECK #1102 IMAGE REF <REF_ID>") is None
+
+
+def test_two_stacked_prefixes_are_both_stripped():
+ assert guess_merchant("POS Paid to IMTIAZ SUPER MARKET, GULSHAN BRANCH KARACHI PK|Visa xxxx2070") == "IMTIAZ SUPER MARKET"
diff --git a/tests/test_scrubber.py b/tests/test_scrubber.py
index 968d2f4..39ebbc8 100644
--- a/tests/test_scrubber.py
+++ b/tests/test_scrubber.py
@@ -200,3 +200,13 @@ def test_regression_removed(combined, token):
@pytest.mark.parametrize("token", REGRESSION_KEEP)
def test_regression_kept(combined, token):
assert token in combined
+
+
+def test_international_phone_does_not_swallow_the_next_line():
+ """Found in the browser with a synthetic UK statement: the separator class included a newline,
+ so '+44 7700 900123' + newline + '01 Apr 2026' lost the date's day and the line break."""
+ from app.scrubber import scrub_text
+ assert scrub_text("Phone: +44 7700 900123\n01 Apr 2026 | X") == "Phone: <PHONE>\n01 Apr 2026 | X"
+ assert scrub_text("Cell # +92 300 1234567\n05 Apr 2026 y") == "Cell # <PHONE>\n05 Apr 2026 y"
+ assert scrub_text("Phone +1 (415) 555-2671\n04/01/2026 | w") == "Phone <PHONE>\n04/01/2026 | w"
+ assert scrub_text("Tel: +92-300-1234567 ok") == "Tel: <PHONE> ok"