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 diff --git a/CHANGELOG.md b/CHANGELOG.md index fb16b28..50bac76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,33 @@ 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] + +### 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. +- `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 + +- 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 + +- `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 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. | diff --git a/src/extract.ts b/src/extract.ts index cbc02e5..0d163ba 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 = + /(? namesFuelAmount(contextFor(c.token, lines))), + ); const closes = (q: Candidate, p: Candidate, t: Candidate | null) => !!t && !samePlace(t.token, q.token) && @@ -279,7 +293,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); @@ -494,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, ""), @@ -548,6 +564,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; @@ -569,7 +589,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 @@ -603,6 +623,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; @@ -671,17 +698,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. @@ -724,7 +749,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, @@ -741,7 +774,7 @@ export function extractReceipt( unitPrice: conflictingRate ? null : fieldFrom(solution.unitPrice, arithmeticChecked), - currency: currencyOf(lines, context), + currency, fuelLabel: product, fuelTypeId: (product ? fuelTypeIdFor(product.value) : null) ?? @@ -921,6 +954,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 +975,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); @@ -969,14 +1003,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/src/format.ts b/src/format.ts index 02d28a7..4ada652 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( + /^.*(?:(? = 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", @@ -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/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/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); + }); +}); diff --git a/test/extract.test.ts b/test/extract.test.ts index 28d11b8..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"; @@ -172,6 +173,19 @@ describe("numbers that are not the ones we want", () => { 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", @@ -443,6 +457,40 @@ 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("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([ @@ -456,6 +504,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. diff --git a/test/global.test.ts b/test/global.test.ts index 89898f4..85f7c81 100644 --- a/test/global.test.ts +++ b/test/global.test.ts @@ -1,9 +1,13 @@ import { describe, expect, it } from "vitest"; import { CURRENCIES } from "../src/currencies.js"; import { extractReceipt } from "../src/extract.js"; -import { receiptCurrency, receiptRecognitionLanguage } from "../src/region.js"; +import { normalizeReceiptText } from "../src/format.js"; +import { + countryCurrency, + receiptCurrency, + 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) => ({ @@ -203,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( @@ -237,4 +223,22 @@ describe("reference edge cases", () => { 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 ", + ); + }); + it("prices Bulgaria in euros and still reads a lev receipt", () => { + 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"); + }); }); 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. 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);