Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
482a171
fix: point otherFills sources at the caller's lines
rsoaresdev Nov 26, 2026
06fdc0e
fix: only read gal as a gallon mark when it is a whole word
rsoaresdev Nov 26, 2026
a29f0d2
fix: price Bulgaria in euros since 2026
rsoaresdev Nov 26, 2026
ba94e3d
fix: let the caller's currency outrank the country's for an ambiguous…
rsoaresdev Nov 26, 2026
705185a
fix: check other fills against the receipt's currency, not the euro's…
rsoaresdev Nov 26, 2026
3825788
chore: move contextFor's doc comment back onto it
rsoaresdev Nov 26, 2026
39edb1c
perf: read the currency once and compile the unit patterns once
rsoaresdev Nov 26, 2026
5ef22d4
chore: remove unit and number helpers the library never uses
rsoaresdev Nov 26, 2026
698a0b2
docs: note the review fixes in the changelog
rsoaresdev Nov 26, 2026
ea867ff
perf: ask whether a total names the fuel once, not once per pair
rsoaresdev Nov 26, 2026
994c1ec
fix: bound the recogniser's alternates like the lines themselves
rsoaresdev Nov 26, 2026
1c7f953
ci: install without scripts in the job that can publish
rsoaresdev Nov 26, 2026
664c931
docs: note the speed-up and the alternates bound in the changelog
rsoaresdev Nov 26, 2026
f1dad1d
fix: rank a tax total below the total that includes the tax
rsoaresdev Nov 26, 2026
a444345
fix: do not read a loyalty scheme's miles as the odometer
rsoaresdev Nov 26, 2026
a54187e
docs: document the alternates bound and the currency precedence
rsoaresdev Nov 26, 2026
ed85900
fix: name the fuel printed on the same line as its numbers
rsoaresdev Nov 26, 2026
6135f90
feat: read Evologic and Optima as additised diesel, and name Alves Ba…
rsoaresdev Nov 26, 2026
67a825a
feat: add Mobi.E's OPC and EGME charges to the energy
rsoaresdev Nov 26, 2026
1dadaf9
docs: note the product, premium diesel and Mobi.E changes in the chan…
rsoaresdev Nov 26, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
91 changes: 66 additions & 25 deletions src/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ function tolerance(total: number, currency = "EUR"): number {
);
}

/** A tax named in a total's label. */
const TAX_WORD =
/(?<![a-z])(?:iva|vat|tva|mwst|ust|btw|imposto|impuesto|tax|gst|kdv)(?![a-z])/i;
/** A label that says the tax is in the amount, not that it is the amount. */
const TAX_INCLUDED =
/c\/|(?<![a-z])(?:com|con|incl|inkl|ttc|with|avec|mit)(?![a-z])/i;

/** How many candidates per slot the search considers. */
const SEARCH_WIDTH = 20;

Expand All @@ -66,10 +73,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`.
Expand All @@ -82,6 +85,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;
Expand Down Expand Up @@ -165,6 +172,9 @@ function priorFor(
score += 0.4;
if (namesFuelAmount(label)) score += 0.4;
if (/subtotal|sub total|netto|neto|liquido|base/i.test(label)) score -= 0.6;
// `Total IVA 11,22` is the tax and `Total s/IVA 48,78` the figure
// before it; `Total c/IVA 60,00` is what was paid.
if (TAX_WORD.test(label) && !TAX_INCLUDED.test(label)) score -= 0.6;
}
if (score < 0.35) return -Infinity;
if (token.glued && token.unit === null) score -= 0.1;
Expand Down Expand Up @@ -259,6 +269,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) &&
Expand All @@ -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);
Expand Down Expand Up @@ -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, ""),
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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) ??
Expand Down Expand Up @@ -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)
Expand All @@ -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);
Expand Down Expand Up @@ -969,14 +1003,21 @@ function withCallerLines(
origin: (lineIndex: number, box: FieldSource["box"]) => number,
reading: ReceiptReading,
): ReceiptReading {
const out: Record<string, unknown> = { ...reading };
for (const [key, field] of Object.entries(reading)) {
const source = (field as ScannedField<unknown> | null)?.source;
if (!source) continue;
out[key] = {
...field,
source: { ...source, lineIndex: origin(source.lineIndex, source.box) },
};
}
return out as unknown as ReceiptReading;
const remap = <T extends object>(record: T): T => {
const out: Record<string, unknown> = { ...(record as object) };
for (const [key, field] of Object.entries(record)) {
const source = (field as ScannedField<unknown> | 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),
};
}
36 changes: 4 additions & 32 deletions src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
/^.*(?:(?<![a-z])(?:gal(?:s|lons?)?|ppg)(?![a-z])|@).*$/i,
tenthOfACent,
);
}

/**
Expand All @@ -30,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);
}
8 changes: 7 additions & 1 deletion src/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -639,7 +644,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",
Expand Down Expand Up @@ -754,6 +759,7 @@ export const KNOWN_BRANDS: readonly string[] = [
"Cepsa",
"Shell",
"Petrogal",
"Alves Bandeira",
"Intermarché",
"Continente",
"Auchan",
Expand Down
21 changes: 13 additions & 8 deletions src/numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}

Expand Down
Loading