From 482a171579ef4097f353f02b08f22f5b95fb72d6 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:37:58 +0000 Subject: [PATCH 01/20] fix: point otherFills sources at the caller's lines --- src/extract.ts | 27 +++++++++++++++++---------- test/rows.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/extract.ts b/src/extract.ts index cbc02e5..85c339f 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -969,14 +969,21 @@ function withCallerLines( origin: (lineIndex: number, box: FieldSource["box"]) => number, reading: ReceiptReading, ): ReceiptReading { - const out: Record = { ...reading }; - for (const [key, field] of Object.entries(reading)) { - const source = (field as ScannedField | null)?.source; - if (!source) continue; - out[key] = { - ...field, - source: { ...source, lineIndex: origin(source.lineIndex, source.box) }, - }; - } - return out as unknown as ReceiptReading; + const remap = (record: T): T => { + const out: Record = { ...(record as object) }; + for (const [key, field] of Object.entries(record)) { + const source = (field as ScannedField | null)?.source; + if (!source) continue; + out[key] = { + ...field, + source: { ...source, lineIndex: origin(source.lineIndex, source.box) }, + }; + } + return out as unknown as T; + }; + return { + ...remap(reading), + // Each fill carries boxes of its own, read off the same joined rows. + otherFills: reading.otherFills?.map(remap), + }; } diff --git a/test/rows.test.ts b/test/rows.test.ts index 38b0af7..76328ff 100644 --- a/test/rows.test.ts +++ b/test/rows.test.ts @@ -19,6 +19,30 @@ import { const NOW = new Date(2026, 9, 31); describe("rows split by the recogniser", () => { + it("points every fill's sources at the caller's own lines", () => { + const at = (text: string, y: number, x = 0.05, width = 0.5): OcrLine => ({ + text, + box: { x, y, width, height: 0.02 }, + }); + const lines = [ + at("GASOLEO", 0.1), + at("31,93 L x 1,899 EUR/L", 0.14), + at("60,64", 0.14, 0.7, 0.2), + at("ADBLUE", 0.2), + at("10,00 L x 1,000 EUR/L", 0.24), + at("10,00", 0.24, 0.7, 0.2), + at("TOTAL 70,64 EUR", 0.3), + ]; + const receipt = extractReceipt(lines, { now: NOW }); + const fill = receipt.otherFills?.[0]; + expect(fill?.quantity.value).toBe(10); + expect(lines[fill?.quantity.source?.lineIndex ?? -1].text).toBe( + "10,00 L x 1,000 EUR/L", + ); + expect(lines[fill?.total.source?.lineIndex ?? -1].text).toBe("10,00"); + expect(lines[fill?.fuelLabel?.source?.lineIndex ?? -1].text).toBe("ADBLUE"); + }); + it("reads a table whose headings sit above the values", () => { const receipt = extractReceipt(galpColumns, { now: NOW }); expect(receipt.quantity?.value).toBe(38.52); From 06fdc0e4294056e08577c3bb0d59690b652d3c2c Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:38:21 +0000 Subject: [PATCH 02/20] fix: only read gal as a gallon mark when it is a whole word --- src/format.ts | 5 ++++- test/global.test.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/format.ts b/src/format.ts index 02d28a7..d9e0a79 100644 --- a/src/format.ts +++ b/src/format.ts @@ -18,7 +18,10 @@ export function normalizeReceiptText(text: string): string { .replace(/,/g, ",") .replace(/[\u202f\u2009]/g, "\u00a0") .replace(/(\d[.,]\d{2})\u2079/g, "$19") - .replace(/^.*(?:gal|ppg|@).*$/i, tenthOfACent); + .replace( + /^.*(?:(? { 0, ); }); + it("does not take Portugal or Galp for a gallon line", () => { + expect(normalizeReceiptText("PORTUGAL 12.50 9 ITENS")).toBe( + "PORTUGAL 12.50 9 ITENS", + ); + expect(normalizeReceiptText("GALP 3.45 9")).toBe("GALP 3.45 9"); + expect(normalizeReceiptText("11.482GAL @ 3.45 9")).toBe( + "11.482GAL @ 3.459 ", + ); + }); }); From a29f0d26b9e1626d53432bb50acdad9a9c9e1cfa Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:38:49 +0000 Subject: [PATCH 03/20] fix: price Bulgaria in euros since 2026 --- src/region.ts | 4 ++-- test/global.test.ts | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/region.ts b/src/region.ts index 80423fe..e759b13 100644 --- a/src/region.ts +++ b/src/region.ts @@ -23,7 +23,8 @@ import type { ScanContext } from "./types.js"; const COUNTRY_CURRENCIES: Record = Object.fromEntries( Object.entries({ - EUR: "PT ES FR IT DE AT BE NL IE FI LU MT CY EE LV LT SK SI GR HR AD MC SM VA", + // Bulgaria joined the euro on 1 January 2026; older receipts still name лв. + EUR: "PT ES FR IT DE AT BE NL IE FI LU MT CY EE LV LT SK SI GR HR BG AD MC SM VA", GBP: "GB GG JE IM", USD: "US EC SV PA PR TL", AUD: "AU KI NR TV", @@ -40,7 +41,6 @@ const COUNTRY_CURRENCIES: Record = Object.fromEntries( CZK: "CZ", HUF: "HU", RON: "RO", - BGN: "BG", RSD: "RS", TRY: "TR", UAH: "UA", diff --git a/test/global.test.ts b/test/global.test.ts index 18d2bdd..ea14f4d 100644 --- a/test/global.test.ts +++ b/test/global.test.ts @@ -2,7 +2,11 @@ import { describe, expect, it } from "vitest"; import { CURRENCIES } from "../src/currencies.js"; import { extractReceipt } from "../src/extract.js"; import { normalizeReceiptText } from "../src/format.js"; -import { receiptCurrency, receiptRecognitionLanguage } from "../src/region.js"; +import { + countryCurrency, + receiptCurrency, + receiptRecognitionLanguage, +} from "../src/region.js"; import type { OcrLine, ScanContext } from "../src/types.js"; import { receiptUnitMetadata, storedReceiptUnit } from "../src/units.js"; @@ -247,4 +251,8 @@ describe("reference edge cases", () => { "11.482GAL @ 3.459 ", ); }); + it("prices Bulgaria in euros and still reads a lev receipt", () => { + expect(countryCurrency("BG")).toBe("EUR"); + expect(receiptCurrency("ОБЩО 60,00 лв.", { country: "BG" })).toBe("BGN"); + }); }); From ba94e3d9fa04598a5a16cfc8b5fef48c24f6c657 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:39:43 +0000 Subject: [PATCH 04/20] fix: let the caller's currency outrank the country's for an ambiguous symbol --- src/region.ts | 3 ++- test/global.test.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/region.ts b/src/region.ts index e759b13..c39614e 100644 --- a/src/region.ts +++ b/src/region.ts @@ -187,7 +187,8 @@ export function receiptCurrency( for (const { pattern, candidates } of CURRENCY_SYMBOLS) { if (!pattern.test(text)) continue; if (candidates.length === 1) return candidates[0]; - const expected = countryCurrency(context.country) ?? context.currency; + // The currency the caller names outranks the one its country implies. + const expected = context.currency ?? countryCurrency(context.country); return expected && candidates.includes(expected) ? expected : null; } return null; diff --git a/test/global.test.ts b/test/global.test.ts index ea14f4d..8d56026 100644 --- a/test/global.test.ts +++ b/test/global.test.ts @@ -255,4 +255,9 @@ describe("reference edge cases", () => { expect(countryCurrency("BG")).toBe("EUR"); expect(receiptCurrency("ОБЩО 60,00 лв.", { country: "BG" })).toBe("BGN"); }); + it("lets the caller's currency settle an ambiguous symbol over the country's", () => { + expect( + receiptCurrency("Total $36", { country: "US", currency: "CAD" }), + ).toBe("CAD"); + }); }); From 705185a575d028a53456826be576c92958661563 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:39:43 +0000 Subject: [PATCH 05/20] fix: check other fills against the receipt's currency, not the euro's cent --- src/extract.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/extract.ts b/src/extract.ts index 85c339f..96a45f3 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -724,7 +724,15 @@ export function extractReceipt( ? "other" : "unknown"; const otherFills = arithmeticChecked - ? fillsBeside(solution, quantities, prices, totals, lines, context) + ? fillsBeside( + solution, + quantities, + prices, + totals, + lines, + context, + fallbackCurrency, + ) : []; const date = readDate( lines, @@ -921,6 +929,7 @@ function fillsBeside( totals: readonly Candidate[], lines: readonly OcrLine[], context: ScanContext, + fallbackCurrency: string | null, ): ReceiptFill[] { const used = [solution.quantity, solution.unitPrice, solution.total] .filter((c): c is Candidate => c !== null) @@ -941,7 +950,7 @@ function fillsBeside( c.token.lineIndex === q.token.lineIndex && !samePlace(c.token, q.token) && !samePlace(c.token, p.token) && - balances(q, p, c, null), + balances(q, p, c, fallbackCurrency), ); if (!t || !measuresFuel(q.token, p.token, lines)) continue; const named = productNear(q.token, lines); From 382578893beead58c72bee46b77bcaa1280d5422 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:39:55 +0000 Subject: [PATCH 06/20] chore: move contextFor's doc comment back onto it --- src/extract.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/extract.ts b/src/extract.ts index 96a45f3..590fd8b 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -66,10 +66,6 @@ const SEARCH_WIDTH = 20; */ const LABEL_REACH = 64; -/** - * The label nearest a number: what precedes it, else the column heading above - * it, else the start of its line. - */ /** * The amount for the fuel alone, on a receipt that also sells a car wash or a * snack: `FUEL 77.99`, `UNLEADED 77.99` above `TOTAL 85.99`. @@ -82,6 +78,10 @@ function namesFuelAmount(label: string): boolean { ); } +/** + * The label nearest a number: what precedes it, else the column heading above + * it, else the start of its line. + */ function contextFor(token: NumberToken, lines: readonly OcrLine[]): string { const before = token.before.trim(); if (token.heading && !/\p{L}/u.test(before)) return token.heading; From 39edb1cd4428111aeeca7a6b9cdaab3dfb99eac4 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:40:04 +0000 Subject: [PATCH 07/20] perf: read the currency once and compile the unit patterns once --- src/extract.ts | 12 +++++------- src/numbers.ts | 21 +++++++++++++-------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/extract.ts b/src/extract.ts index 590fd8b..3808aec 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -671,17 +671,15 @@ export function extractReceipt( // A sum that closes proves the arithmetic, not the purchase: a shop line // (`2 x 5,00 10,00`) closes as well as the pump's. It counts as checked // only when the paper also says the triple measures fuel or energy. + const currency = currencyOf(lines, context); + const moneyCurrency = currency?.value ?? fallbackCurrency; const discount = discountOf( tokens, lines, solution.quantity?.value, - currencyOf(lines, context)?.value ?? fallbackCurrency, - ); - const fees = feesOf( - tokens, - lines, - currencyOf(lines, context)?.value ?? fallbackCurrency, + moneyCurrency, ); + const fees = feesOf(tokens, lines, moneyCurrency); // A total printed after a printed discount or fee: what the pump measured, // less what came off and plus what was added, is what was paid. That total // wins over the amount on the fuel line, which is the energy alone. @@ -749,7 +747,7 @@ export function extractReceipt( unitPrice: conflictingRate ? null : fieldFrom(solution.unitPrice, arithmeticChecked), - currency: currencyOf(lines, context), + currency, fuelLabel: product, fuelTypeId: (product ? fuelTypeIdFor(product.value) : null) ?? diff --git a/src/numbers.ts b/src/numbers.ts index 12d8963..e26a3fd 100644 --- a/src/numbers.ts +++ b/src/numbers.ts @@ -330,19 +330,24 @@ function unionBox(a: TextBox, b: TextBox): TextBox { }; } +const IS_MASS = new RegExp(`^(?:${MASS})$`, "i"); +const IS_GAS_VOLUME = new RegExp(`^(?:${GAS_VOLUME})$`, "i"); +const IS_KWH = new RegExp(`^(?:${KWH})$`, "i"); +const IS_GALLON = new RegExp(`^(?:${GALLON})$`, "i"); + function rateKind(word: string): TokenUnit { - if (new RegExp(`^(?:${MASS})$`, "i").test(word)) return "per-kg"; - if (new RegExp(`^(?:${GAS_VOLUME})$`, "i").test(word)) return "per-m3"; - if (new RegExp(`^(?:${KWH})$`, "i").test(word)) return "per-kwh"; - if (new RegExp(`^(?:${GALLON})$`, "i").test(word)) return "per-gallon"; + if (IS_MASS.test(word)) return "per-kg"; + if (IS_GAS_VOLUME.test(word)) return "per-m3"; + if (IS_KWH.test(word)) return "per-kwh"; + if (IS_GALLON.test(word)) return "per-gallon"; return "per-litre"; } function plainKind(word: string): TokenUnit { - if (new RegExp(`^(?:${MASS})$`, "i").test(word)) return "mass"; - if (new RegExp(`^(?:${GAS_VOLUME})$`, "i").test(word)) return "volume-gas"; - if (new RegExp(`^(?:${KWH})$`, "i").test(word)) return "kwh"; - if (new RegExp(`^(?:${GALLON})$`, "i").test(word)) return "gallon"; + if (IS_MASS.test(word)) return "mass"; + if (IS_GAS_VOLUME.test(word)) return "volume-gas"; + if (IS_KWH.test(word)) return "kwh"; + if (IS_GALLON.test(word)) return "gallon"; return "litre"; } From 5ef22d497287206ecdf86aa938365b9531f4b547 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:40:11 +0000 Subject: [PATCH 08/20] chore: remove unit and number helpers the library never uses --- src/format.ts | 31 -------------------------- src/units.ts | 54 --------------------------------------------- test/global.test.ts | 19 ---------------- 3 files changed, 104 deletions(-) delete mode 100644 src/units.ts diff --git a/src/format.ts b/src/format.ts index d9e0a79..4ada652 100644 --- a/src/format.ts +++ b/src/format.ts @@ -33,34 +33,3 @@ export function normalizeReceiptText(text: string): string { function tenthOfACent(line: string): string { return line.replace(/(\d\.\d{2}) 9(?![\d.,])/g, "$19 "); } - -export function decimalInput(raw: string): number | null { - const normalized = normalizeReceiptText(raw).trim().replace(/[\s']/g, ""); - if (!/^(?:\d+(?:[.,]\d*)?|[.,]\d+)$/.test(normalized)) return null; - const value = Number(normalized.replace(",", ".")); - return Number.isFinite(value) ? value : null; -} - -export function localNumber( - value: number, - locale: string, - maximumFractionDigits = 3, - minimumFractionDigits = 0, -): string { - return new Intl.NumberFormat(locale, { - useGrouping: false, - maximumFractionDigits, - minimumFractionDigits, - }).format(value); -} - -/** Localize a validated receipt amount without rounding converted values. */ -export function localReceiptNumber(value: string, locale: string): string { - if (!value.trim()) return ""; - const amount = Number(value); - if (!Number.isFinite(amount)) return ""; - return new Intl.NumberFormat(locale, { - useGrouping: false, - maximumSignificantDigits: 21, - }).format(amount); -} diff --git a/src/units.ts b/src/units.ts deleted file mode 100644 index 4a0987b..0000000 --- a/src/units.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { ReceiptUnit } from "./types.js"; - -/** Keep ambiguous historical gallons ambiguous when a record is edited. */ -export function receiptUnitMetadata(unit: ReceiptUnit) { - return { - quantityUnit: unit === "gallon_us" || unit === "gallon_uk" ? "gal" : unit, - volumeUnit: - unit === "gallon_us" || unit === "gallon_uk" - ? unit - : unit === "L" - ? "liter" - : undefined, - }; -} - -export function receiptUnitLabel(unit: ReceiptUnit | null): string { - return unit === "gallon_us" - ? "gal (US)" - : unit === "gallon_uk" - ? "gal (imp)" - : (unit ?? "?"); -} - -export function storedReceiptUnit( - metadata: Record | undefined, -): ReceiptUnit | null { - const unit = metadata?.quantityUnit; - if (unit === "gal" && metadata?.volumeUnit === "gallon_us") - return "gallon_us"; - if (unit === "gal" && metadata?.volumeUnit === "gallon_uk") - return "gallon_uk"; - return ["L", "gal", "gallon_us", "gallon_uk", "kg", "m3", "kWh"].includes( - String(unit), - ) - ? (unit as ReceiptUnit) - : null; -} - -const GALLONS: readonly ReceiptUnit[] = ["gal", "gallon_us", "gallon_uk"]; - -/** - * Whether two quantities are measured in the same unit, compared as units and - * never as the labels the screen prints for them. - * - * A bare "gal" (what older builds and a CSV import store) names no gallon in - * particular, so it agrees with either: nobody logs one car in both. A US - * gallon and an imperial one are still two units. - */ -export function sameReceiptUnit(a: ReceiptUnit, b: ReceiptUnit): boolean { - if (a === b) return true; - return ( - (a === "gal" || b === "gal") && GALLONS.includes(a) && GALLONS.includes(b) - ); -} diff --git a/test/global.test.ts b/test/global.test.ts index 8d56026..85f7c81 100644 --- a/test/global.test.ts +++ b/test/global.test.ts @@ -8,7 +8,6 @@ import { receiptRecognitionLanguage, } from "../src/region.js"; import type { OcrLine, ScanContext } from "../src/types.js"; -import { receiptUnitMetadata, storedReceiptUnit } from "../src/units.js"; function read(rows: string[], context: ScanContext = {}) { const lines: OcrLine[] = rows.map((text, i) => ({ @@ -208,24 +207,6 @@ describe("unit and date context", () => { }); }); -describe("unit persistence", () => { - it("does not assign the current account preference to an old ambiguous gallon", () => { - const original = { quantityUnit: "gal" }; - const unit = storedReceiptUnit(original); - expect(unit).toBe("gal"); - expect(receiptUnitMetadata(unit ?? "L")).toEqual({ - quantityUnit: "gal", - volumeUnit: undefined, - }); - }); - it.each(["gallon_us", "gallon_uk", "L", "kg", "m3", "kWh"] as const)( - "round trips %s", - (unit) => { - expect(storedReceiptUnit(receiptUnitMetadata(unit))).toBe(unit); - }, - ); -}); - describe("reference edge cases", () => { it("recognizes an ISO currency printed as a standalone heading", () => { expect( From 698a0b291103fbd15bd2cdae79a0b7ace74cb682 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:40:30 +0000 Subject: [PATCH 09/20] docs: note the review fixes in the changelog --- CHANGELOG.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb16b28..91ba2a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes to this package are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Fixed + +- The sources of each fill in `otherFills` point at the caller's own lines. When the recogniser split a row in pieces they pointed at the joined rows instead, so a review screen drew the second fill's highlights on the wrong line. +- A line that mentions `Portugal`, `Galp` or `Legal` is no longer read as a US gallon line, which had turned `12.50 9` into `12.509`. +- `country: "BG"` prices in euros, as Bulgaria has since 1 January 2026. A receipt printed in leva (`лв.`) is still read as BGN. +- `currency` passed by the caller now settles an ambiguous symbol such as `$` ahead of the currency implied by `country`. +- A second fill on the same receipt is checked to the receipt's own currency precision, not always to the euro cent. + +### Removed + +- `src/units.ts` and the `decimalInput`, `localNumber` and `localReceiptNumber` helpers in `src/format.ts`. None was exported from the package or used by it. + ## [1.1.2] - 2026-11-01 ### Fixed From ea867ff6b38f8f5da7a4913ddc277a0e23ff2de2 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:48:30 +0000 Subject: [PATCH 10/20] perf: ask whether a total names the fuel once, not once per pair --- src/extract.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/extract.ts b/src/extract.ts index 3808aec..922e0a0 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -259,6 +259,10 @@ function solve( let best: Solution | null = null; let bestScore = -Infinity; const closing: Solution[] = []; + // Asked once per total here, not once per pair in the loop below. + const fuelAmounts = new Set( + totals.filter((c) => namesFuelAmount(contextFor(c.token, lines))), + ); const closes = (q: Candidate, p: Candidate, t: Candidate | null) => !!t && !samePlace(t.token, q.token) && @@ -279,7 +283,7 @@ function solve( !c.token.alternate && (c.token.lineIndex === q.token.lineIndex || c.token.lineIndex === p.token.lineIndex || - namesFuelAmount(contextFor(c.token, lines))) && + fuelAmounts.has(c)) && closes(q, p, c), ) ?? printedTotal); const balanced = closes(q, p, t); From 994c1ec8891910ea7efa6a2539a2159486d2f84e Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:48:49 +0000 Subject: [PATCH 11/20] fix: bound the recogniser's alternates like the lines themselves --- src/extract.ts | 7 +++++++ test/resilience.test.ts | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/extract.ts b/src/extract.ts index 922e0a0..4ba5edc 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -607,6 +607,13 @@ export function extractReceipt( lines.slice(0, 500).map((line) => ({ ...line, text: normalizeReceiptText(line.text.slice(0, 1500)), + // The same bounds for the recogniser's other readings: a few, each + // no longer than a line, so no input can cost more than the page. + ...(line.alternates && { + alternates: line.alternates + .slice(0, 3) + .map((alternate) => alternate.slice(0, 1500)), + }), })), ); lines = rows.lines; diff --git a/test/resilience.test.ts b/test/resilience.test.ts index 14abfcf..95ea980 100644 --- a/test/resilience.test.ts +++ b/test/resilience.test.ts @@ -119,6 +119,26 @@ describe("the recogniser's second thoughts", () => { expect(receipt.total?.source).not.toBeNull(); }); + it("reads only the recogniser's first three alternates", () => { + // Only the fourth says 60,64. A recogniser that returns dozens of + // readings per line must not make one line cost more than a page. + const receipt = read([ + "GALP", + "SP95", + "31,93 L x 1,899 EUR/L", + [ + "TOTAL 50,64 EUR", + "TOTAL 50,84 EUR", + "TOTAL 58,64 EUR", + "TOTAL 50,61 EUR", + "TOTAL 60,64 EUR", + ], + "01/09/2026", + ]); + expect(receipt.arithmeticChecked).toBe(false); + expect(receipt.total?.value).toBe(50.64); + }); + it("never lets an alternate win a slot on its own", () => { // Nothing balances either way. The preferred reading is what the // recogniser believed, and the review screen shows that, not its doubts. From 1c7f953ea25a32cb8404da9d13ffda7841b57d69 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:49:11 +0000 Subject: [PATCH 12/20] ci: install without scripts in the job that can publish --- .github/workflows/release.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8822abb..ffd36a2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,8 @@ jobs: node-version: 24 registry-url: https://registry.npmjs.org cache: npm - - run: npm ci + # No install scripts: this job can mint the token that publishes. + - run: npm ci --ignore-scripts # Staged publishing needs npm 12. The version waits on npmjs.com until a # maintainer approves it with 2FA, so a workflow alone cannot publish. - run: npm install --global npm@12.2.1 From 664c931f7637edebc7f4d11b99b10078dea9b4de Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:49:11 +0000 Subject: [PATCH 13/20] docs: note the speed-up and the alternates bound in the changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91ba2a8..af893fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ All notable changes to this package are listed here. The format follows [Keep a - `country: "BG"` prices in euros, as Bulgaria has since 1 January 2026. A receipt printed in leva (`лв.`) is still read as BGN. - `currency` passed by the caller now settles an ambiguous symbol such as `$` ahead of the currency implied by `country`. - A second fill on the same receipt is checked to the receipt's own currency precision, not always to the euro cent. +- A recogniser's `alternates` are bounded like the lines themselves: the first three per line, each cut to 1500 characters. A line with dozens of very long alternates could run the parser out of memory. + +### Changed + +- About 20 times faster on a typical receipt: the solver asked whether each total names the fuel once per pair of candidates, not once per total. ### Removed From f1dad1dbafe1fd5362a4e0f2168c115648f2ff91 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:53:08 +0000 Subject: [PATCH 14/20] fix: rank a tax total below the total that includes the tax --- src/extract.ts | 10 ++++++++++ test/extract.test.ts | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/extract.ts b/src/extract.ts index 4ba5edc..81e5f8b 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -56,6 +56,13 @@ function tolerance(total: number, currency = "EUR"): number { ); } +/** A tax named in a total's label. */ +const TAX_WORD = + /(? { expect(receipt.arithmeticChecked).toBe(true); }); + it.each([ + ["Total IVA 11,22 EUR", "TOTAL 60,00 EUR"], + ["Valor IVA 11,22 EUR", "Valor 60,00 EUR"], + ["Total IVA 11,22", "Total s/IVA 48,78", "Total c/IVA 60,00"], + ])( + "does not take a tax total for the total when the sum cannot close: %s", + (...lines) => { + // No litres were read, so nothing checks the total but its label. + const receipt = read(["GALP", "GASOLEO SIMPLES", ...lines, "01/09/2026"]); + expect(receipt.total?.value).toBe(60); + }, + ); + it("does not take the change from a fifty for the total", () => { const receipt = read([ "GALP", From a444345e323d37b17a247843339b32aba8c0e261 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:53:09 +0000 Subject: [PATCH 15/20] fix: do not read a loyalty scheme's miles as the odometer --- src/extract.ts | 6 +++++- test/extract.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/extract.ts b/src/extract.ts index 81e5f8b..40881d3 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -562,6 +562,10 @@ function placeOf( const ODOMETER_WORD = /odomet|odómet|kilomet|quilomet|quilómet|chilomet|conta-quil|mileage|kmstand|tachostand/i; +/** A loyalty scheme whose name says miles or points: `Miles & More 123456`. */ +const LOYALTY = + /miles\s*(?:&|and|\+|e|und|et|y)\s*more|avios|payback|pontos|points|punkte|puntos/i; + /** A line that names a road: the words, or a designation like `A-4` or `N-IV`. */ const ROAD_MARKER = /\b(?:autovia|autovía|autopista|autostrada|autoestrada|autobahn|carretera|ctra|estrada|rodovia|strada|route|highway|hwy|salida|saída|uscita|ausfahrt|sortie|exit|pk)\b|\b(?:A|AP|N|E|M|IC|IP|EN|SS|RN|BR|CR|D|B)-(?:\d{1,3}|[IVX]{1,5})\b/i; @@ -583,7 +587,7 @@ function odometerOf( const header = Math.ceil(lines.length / 3); for (const token of tokens) { const label = contextFor(token, lines); - if (!names("odometer", label)) { + if (!names("odometer", label) || LOYALTY.test(label)) { continue; } // `KM 245` in a station's address is a road marker, not a reading: a diff --git a/test/extract.test.ts b/test/extract.test.ts index 8df1233..d7cf265 100644 --- a/test/extract.test.ts +++ b/test/extract.test.ts @@ -469,6 +469,19 @@ describe("the odometer, which is nearly always handwritten", () => { expect(receipt.odometer?.value).toBe(148230); }); + it("does not take a loyalty scheme's miles for a reading", () => { + const receipt = read([ + "GALP", + "GASOLEO 40,00 L x 1,500 EUR/L 60,00", + "TOTAL 60,00 EUR", + "01/09/2026", + "OBRIGADO", + "Miles & More 123456", + ]); + expect(receipt.arithmeticChecked).toBe(true); + expect(receipt.odometer).toBeNull(); + }); + it("leaves it empty rather than guess", () => { // An odometer that goes backwards corrupts every consumption figure // after it, so an unlabelled number is never one. From a54187ecef96d88c7b64b7f5698c1a0561b31061 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:53:16 +0000 Subject: [PATCH 16/20] docs: document the alternates bound and the currency precedence --- CHANGELOG.md | 2 ++ README.md | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af893fd..7a35230 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ All notable changes to this package are listed here. The format follows [Keep a - `country: "BG"` prices in euros, as Bulgaria has since 1 January 2026. A receipt printed in leva (`лв.`) is still read as BGN. - `currency` passed by the caller now settles an ambiguous symbol such as `$` ahead of the currency implied by `country`. - A second fill on the same receipt is checked to the receipt's own currency precision, not always to the euro cent. +- `Total IVA 11,22` or `Valor IVA 11,22` is no longer taken for the total when the sum cannot close. A total whose label names a tax ranks below one that does not, unless the label says the tax is included (`Total c/IVA`, `inkl. MwSt`, `TTC`). +- `Miles & More 123456` and other loyalty schemes that count miles or points are no longer read as an odometer in miles. - A recogniser's `alternates` are bounded like the lines themselves: the first three per line, each cut to 1500 characters. A line with dozens of very long alternates could run the parser out of memory. ### Changed diff --git a/README.md b/README.md index 4ba9589..ce01f00 100644 --- a/README.md +++ b/README.md @@ -116,14 +116,14 @@ if (wantsSecondPass(reading)) { ### `extractReceipt(lines, context?): ReceiptReading` -`lines` can arrive in any order. At most 500 lines of 1,500 characters are read, and a label is looked for in the 64 characters before a number, so even the largest input that passes these limits is read in under a second on a laptop. A real receipt takes a few milliseconds. +`lines` can arrive in any order. At most 500 lines of 1,500 characters are read, with up to three `alternates` per line cut to the same length, and a label is looked for in the 64 characters before a number, so even the largest input that passes these limits is read in under a second on a laptop. A real receipt takes a few milliseconds. `context` is optional and holds what the paper does not say: | Field | Type | Use | | -------------- | ---------------- | --------------------------------------------------------------------------------------------- | | `country` | `string` | ISO 3166 country of purchase, for example `"PT"`. Decides the currency of a bare `$` or `kr`. | -| `currency` | `string` | ISO 4217 code to assume when the receipt prints none. | +| `currency` | `string` | ISO 4217 code to assume when the receipt prints none. Also settles a bare `$` or `kr` ahead of `country`. | | `quantityUnit` | `ReceiptUnit` | Unit to assume when the receipt prints none. | | `brands` | `string[]` | Station names to look for. Defaults to `KNOWN_BRANDS`. | | `dateOrder` | `"dmy" \| "mdy" \| "ymd"` | How the reader's region writes numeric dates, the last resort for `08/09/2026`. `regionDateOrder(country)` gives it. | From ed859006a67b7448f843a4de44cd937a55bc12a9 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:56:01 +0000 Subject: [PATCH 17/20] fix: name the fuel printed on the same line as its numbers --- src/extract.ts | 2 ++ test/extract.test.ts | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/extract.ts b/src/extract.ts index 40881d3..0d163ba 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -508,6 +508,8 @@ function productAt( const whole = line.text.trim(); // `Bomba 4 GASOLEO`: the pump number refuses the line, not the fuel. const text = [ + // `GASOLEO 40,00 L x 1,600 EUR/L 64,00`: the name before the numbers. + whole.replace(/\s+\d+[.,]\d.*$/u, ""), whole, ...whole.split(/\s{2,}/), whole.replace(/^\p{L}+\.?\s*#?\s*\d+\s+/u, ""), diff --git a/test/extract.test.ts b/test/extract.test.ts index d7cf265..ab55b7e 100644 --- a/test/extract.test.ts +++ b/test/extract.test.ts @@ -456,6 +456,22 @@ describe("what it does with nothing", () => { }); }); +describe("a product printed on the line it measures", () => { + it.each([ + ["GASOLEO 40,00 L x 1,600 EUR/L 64,00", "GASOLEO", "diesel_simple"], + ["SP95 31,93 L x 1,899 EUR/L 60,64", "SP95", "gasoline_95"], + [ + "Gasolina 95 Simples 31,93L 1,899 60,64", + "Gasolina 95 Simples", + "gasoline_95", + ], + ])("names the fuel in %s", (line, label, fuel) => { + const receipt = read(["GALP", line, "TOTAL 64,00", "01/09/2026"]); + expect(receipt.fuelLabel?.value).toBe(label); + expect(receipt.fuelTypeId).toBe(fuel); + }); +}); + describe("the odometer, which is nearly always handwritten", () => { it("takes a printed reading when the receipt labels one", () => { const receipt = read([ From 6135f907675bb726850fc670088437b9c48f20c7 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:56:14 +0000 Subject: [PATCH 18/20] feat: read Evologic and Optima as additised diesel, and name Alves Bandeira --- src/labels.ts | 3 ++- test/extract.test.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/labels.ts b/src/labels.ts index ec2395f..667ca14 100644 --- a/src/labels.ts +++ b/src/labels.ts @@ -639,7 +639,7 @@ export function namesDiscount(text: string): boolean { const FUEL_RULES: readonly (readonly [FuelTypeId, RegExp])[] = [ [ "diesel_aditivado", - /\b(?:diesel|gasoleo|gazole|gasoil|gasolio|dieselkraftstoff)\b[^\n]{0,20}\b(?:aditivado|adit|premium|plus|top|evolution|excellium|ultimate|momentum|v-?power|extra|energy|efficient)\b|\b(?:aditivado|premium|excellium|ultimate|v-?power|momentum|evolution)\b[^\n]{0,20}\b(?:diesel|gasoleo|gazole|gasoil|gasolio)\b/i, + /\b(?:diesel|gasoleo|gazole|gasoil|gasolio|dieselkraftstoff)\b[^\n]{0,20}\b(?:aditivado|adit|premium|plus|top|evolution|excellium|ultimate|momentum|v-?power|extra|energy|efficient|evologic|optima)\b|\b(?:aditivado|premium|excellium|ultimate|v-?power|momentum|evolution|evologic|optima)\b[^\n]{0,20}\b(?:diesel|gasoleo|gazole|gasoil|gasolio)\b/i, ], [ "diesel_simple", @@ -754,6 +754,7 @@ export const KNOWN_BRANDS: readonly string[] = [ "Cepsa", "Shell", "Petrogal", + "Alves Bandeira", "Intermarché", "Continente", "Auchan", diff --git a/test/extract.test.ts b/test/extract.test.ts index ab55b7e..317408b 100644 --- a/test/extract.test.ts +++ b/test/extract.test.ts @@ -20,6 +20,7 @@ import { describe, expect, it } from "vitest"; import { extractReceipt } from "../src/extract.js"; +import { fuelTypeIdFor } from "../src/labels.js"; import { readings, tokenize } from "../src/numbers.js"; import type { OcrLine } from "../src/types.js"; @@ -472,6 +473,24 @@ describe("a product printed on the line it measures", () => { }); }); +describe("Portuguese premium diesels and stations", () => { + it.each(["Gasoleo Evologic", "Óptima Diesel", "Gasóleo Aditivado"])( + "reads %s as an additised diesel", + (name) => { + expect(fuelTypeIdFor(name)).toBe("diesel_aditivado"); + }, + ); + it("keeps a plain diesel plain", () => { + expect(fuelTypeIdFor("Gasoleo Simples")).toBe("diesel_simple"); + expect(fuelTypeIdFor("Diesel Star")).toBe("diesel_simple"); + }); + it.each(["ALVES BANDEIRA"])("names the station %s", (brand) => { + expect( + read([brand, "Lisboa", "TOTAL 64,00", "01/09/2026"]).place, + ).not.toBeNull(); + }); +}); + describe("the odometer, which is nearly always handwritten", () => { it("takes a printed reading when the receipt labels one", () => { const receipt = read([ From 67a825a7868ba6a632d6d0fab058ba910d3b6fd2 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:56:59 +0000 Subject: [PATCH 19/20] feat: add Mobi.E's OPC and EGME charges to the energy --- src/labels.ts | 5 +++++ test/discount-fills.test.ts | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/labels.ts b/src/labels.ts index 667ca14..9e002c0 100644 --- a/src/labels.ts +++ b/src/labels.ts @@ -614,6 +614,11 @@ const FEE: readonly string[] = [ "tarifa de sesión", "costo di sessione", "commissione", + // Mobi.E, the Portuguese network: the operator's and the network's charges. + "taxa opc", + "tarifa opc", + "taxa egme", + "tarifa egme", ]; /** Whether the text names a fee charged on top of the energy. */ diff --git a/test/discount-fills.test.ts b/test/discount-fills.test.ts index 7fa7915..9cd5918 100644 --- a/test/discount-fills.test.ts +++ b/test/discount-fills.test.ts @@ -175,3 +175,21 @@ describe("each fill's own product", () => { expect(fuels).toContainEqual([10, "adblue"]); }); }); + +describe("a Mobi.E charge", () => { + it("adds the operator's and the network's charges to the energy", () => { + const r = read([ + "MOBI.E", + "Carregamento", + "Energia 25,000 kWh", + "Preco 0,30 EUR/kWh", + "Taxa OPC 1,20", + "Taxa EGME 0,30", + "Total 9,00 EUR", + "01/09/2026", + ]); + expect(r.fees?.value).toBe(1.5); + expect(r.total?.value).toBe(9); + expect(r.arithmeticChecked).toBe(true); + }); +}); From 1dadaf9c53b3bb457b6c63360289e6c6af648db2 Mon Sep 17 00:00:00 2001 From: Rafael Soares <107703258+rsoaresdev@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:56:59 +0000 Subject: [PATCH 20/20] docs: note the product, premium diesel and Mobi.E changes in the changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a35230..50bac76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,14 @@ All notable changes to this package are listed here. The format follows [Keep a ## [Unreleased] +### Added + +- `Gasóleo Evologic` and `Óptima Diesel` read as additised diesel, and `Alves Bandeira` as a station. +- Mobi.E's `Taxa OPC` and `Taxa EGME` are fees added to the energy, so a Portuguese charging receipt that prints them can be checked. + ### Fixed +- A fuel named on the same line as its numbers (`GASOLEO 40,00 L x 1,600 EUR/L 64,00`) is named: `fuelLabel` is `GASOLEO` and `fuelTypeId` is `diesel_simple`. Before, both were `null`, or the label was the whole line with its numbers. - The sources of each fill in `otherFills` point at the caller's own lines. When the recogniser split a row in pieces they pointed at the joined rows instead, so a review screen drew the second fill's highlights on the wrong line. - A line that mentions `Portugal`, `Galp` or `Legal` is no longer read as a US gallon line, which had turned `12.50 9` into `12.509`. - `country: "BG"` prices in euros, as Bulgaria has since 1 January 2026. A receipt printed in leva (`лв.`) is still read as BGN.