323 lines
16 KiB
TypeScript
323 lines
16 KiB
TypeScript
import "server-only";
|
||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||
import path from "node:path";
|
||
import type { PoolClient } from "pg";
|
||
import sharp from "sharp";
|
||
import { AiNotConfigured, AiUnavailable, askJson, askText } from "./ai";
|
||
import { aiFor } from "./ai-settings";
|
||
import { withHousehold } from "./db";
|
||
import { searchIngredients, type IngredientEntry } from "./ingredient-search";
|
||
import { allIngredients } from "./ingredients";
|
||
import { PhotoRejected } from "./photos";
|
||
import { matchesProduct, normalizeLine, packFromText, RECEIPT_PROMPT, receiptFromText, tokens, unitPrice } from "./receipt-read";
|
||
|
||
// Kassenbons (Konzept, „Bon-Pipeline, lokal“): Foto → Bildmodell liest Laden,
|
||
// Datum, Zeilen → Zuordnung (gelernt, Produkt eines Gerichts, Suche, AI-Vorschlag)
|
||
// → ein Mensch bestätigt → Preisgedächtnis und Gelerntes. Das Foto liegt nur bis
|
||
// zur Bestätigung unter /app/data/bons/ und wird dann gelöscht. Ohne AI wartet
|
||
// der Bon; kein Ausweichen in die Cloud.
|
||
|
||
const MAX_BYTES = 15 * 1024 * 1024;
|
||
const root = () => path.join(process.env.APP_DATA_DIR ?? path.join(process.cwd(), ".data"), "bons");
|
||
|
||
export async function storeReceiptPhoto(householdId: string, receiptId: string, file: File): Promise<string> {
|
||
if (!file.type.startsWith("image/") || file.size === 0 || file.size > MAX_BYTES) throw new PhotoRejected(file.type);
|
||
let jpg: Buffer;
|
||
try {
|
||
jpg = await sharp(Buffer.from(await file.arrayBuffer())).rotate().resize({ width: 2000, height: 2000, fit: "inside", withoutEnlargement: true }).jpeg({ quality: 85 }).toBuffer();
|
||
} catch {
|
||
throw new PhotoRejected("decode");
|
||
}
|
||
const relative = path.join(householdId, `${receiptId}.jpg`);
|
||
await mkdir(path.join(root(), householdId), { recursive: true, mode: 0o700 });
|
||
await writeFile(path.join(root(), relative), jpg, { mode: 0o600 });
|
||
return relative;
|
||
}
|
||
|
||
async function dropPhoto(relative: string | null) {
|
||
if (!relative) return;
|
||
const full = path.join(root(), relative);
|
||
if (full.startsWith(root() + path.sep)) await rm(full, { force: true });
|
||
}
|
||
|
||
export async function createReceipt(client: PoolClient, householdId: string, memberId: string, file: File): Promise<string> {
|
||
const id = (await client.query("select gen_random_uuid() as id")).rows[0].id as string;
|
||
const photo = await storeReceiptPhoto(householdId, id, file);
|
||
await client.query("insert into receipts (id, household_id, photo_path, status, created_by) values ($1, $2, $3, 'queued', $4)", [
|
||
id,
|
||
householdId,
|
||
photo,
|
||
memberId,
|
||
]);
|
||
return id;
|
||
}
|
||
|
||
type Suggestion = { ingredientId: string | null; source: "alias" | "product" | "search" | "ai" | "skip" | null; product: string | null; pack: { qty: number; unit: string } | null };
|
||
|
||
const MATCH_PROMPT = `You match supermarket receipt lines to ingredients. Answer with one JSON object only:
|
||
{"matches": [{"line": number, "key": string|null}]}
|
||
For each line pick the one candidate key that is the same food, or null if none fits (household goods, drinks you are unsure of).
|
||
Never use a key that is not listed for that line.`;
|
||
|
||
/** Vorschläge je Zeile: gelernt → Produkt eines Gerichts → Suche → (gesammelt) AI. */
|
||
export async function suggestLines(client: PoolClient, lines: string[], locale: string, ai: Awaited<ReturnType<typeof aiFor>>): Promise<Suggestion[]> {
|
||
const list = await allIngredients(client);
|
||
const byId = new Map(list.map((e) => [e.id, e]));
|
||
const aliases = new Map(
|
||
(await client.query("select raw_text_normalized as k, ingredient_id as i, pack_qty::float as q, pack_unit as u from ingredient_aliases")).rows.map((r) => [r.k as string, r]),
|
||
);
|
||
const products = (await client.query("select distinct ingredient_id as i, product as p from dish_ingredients where product is not null")).rows as { i: string; p: string }[];
|
||
const out: Suggestion[] = [];
|
||
const open: { index: number; candidates: IngredientEntry[] }[] = [];
|
||
for (const [index, text] of lines.entries()) {
|
||
const pack = packFromText(text);
|
||
const alias = aliases.get(normalizeLine(text));
|
||
if (alias) {
|
||
// Ohne Zutat gelernt: „nicht zum Kochen“ (Toastbrot) — kein Vorschlag, kein Modell.
|
||
if (!alias.i) out.push({ ingredientId: null, source: "skip", product: null, pack: null });
|
||
else out.push({ ingredientId: alias.i, source: "alias", product: null, pack: alias.q ? { qty: alias.q, unit: alias.u } : pack });
|
||
continue;
|
||
}
|
||
const prod = products.find((p) => matchesProduct(text, p.p));
|
||
if (prod) {
|
||
out.push({ ingredientId: prod.i, source: "product", product: prod.p, pack });
|
||
continue;
|
||
}
|
||
// Suche über die Wörter der Zeile (Abkürzungen: Wortanfang), längste Wörter zuerst.
|
||
const words = tokens(text).filter((w) => w.length >= 4 && !/\d/.test(w)).sort((a, b) => b.length - a.length);
|
||
const candidates = new Map<string, IngredientEntry>();
|
||
let hit: IngredientEntry | null = null;
|
||
for (const w of words) {
|
||
const found = searchIngredients(list, w, locale, 4);
|
||
if (!hit && found[0] && words.length === 1) hit = found[0];
|
||
for (const f of found) candidates.set(f.id, f);
|
||
}
|
||
if (hit) out.push({ ingredientId: hit.id, source: "search", product: null, pack });
|
||
else {
|
||
out.push({ ingredientId: null, source: null, product: null, pack });
|
||
if (candidates.size) open.push({ index, candidates: [...candidates.values()].slice(0, 6) });
|
||
}
|
||
}
|
||
// Was offen ist, schlägt das Textmodell vor — nur aus den Kandidaten der Suche.
|
||
if (open.length && ai?.textModel) {
|
||
try {
|
||
const input = open.map((o, n) => ({ line: n + 1, text: lines[o.index], candidates: o.candidates.map((c) => ({ key: c.key, name: c.names[locale] ?? c.names.en })) }));
|
||
const reply = (await askJson(ai, "text", MATCH_PROMPT, JSON.stringify(input))) as { matches?: { line?: number; key?: string | null }[] } | null;
|
||
for (const m of reply?.matches ?? []) {
|
||
const o = typeof m.line === "number" ? open[m.line - 1] : undefined;
|
||
const c = o?.candidates.find((x) => x.key === m.key);
|
||
if (o && c) out[o.index] = { ...out[o.index]!, ingredientId: c.id, source: "ai" };
|
||
}
|
||
} catch (error) {
|
||
if (!(error instanceof AiUnavailable)) throw error;
|
||
}
|
||
}
|
||
// Packung, wo die Zeile keine nennt: aus dem Gelernten oder leer (die Person ergänzt).
|
||
return out.map((s) => (s.ingredientId && !s.pack && byId.get(s.ingredientId)?.unit === "piece" ? { ...s, pack: { qty: 1, unit: "piece" } } : s));
|
||
}
|
||
|
||
const running = new Set<string>();
|
||
|
||
/** Wartende Bons eines Haushalts lesen (nacheinander, je Bon höchstens drei Versuche). */
|
||
export async function processQueued(householdId: string, locale: string): Promise<void> {
|
||
if (running.has(householdId)) return;
|
||
running.add(householdId);
|
||
try {
|
||
const ai = await aiFor(householdId);
|
||
if (!ai?.visionModel) return;
|
||
for (;;) {
|
||
const next = await withHousehold(householdId, async (c) =>
|
||
(
|
||
await c.query(
|
||
`update receipts set status = 'processing', attempts = attempts + 1
|
||
where id = (select id from receipts where status = 'queued' and attempts < ${ATTEMPTS} order by created_at limit 1)
|
||
returning id, photo_path, attempts`,
|
||
)
|
||
).rows[0] as { id: string; photo_path: string; attempts: number } | undefined,
|
||
);
|
||
if (!next) return;
|
||
await readOne(householdId, next.id, next.photo_path, ai, locale, next.attempts);
|
||
}
|
||
} finally {
|
||
running.delete(householdId);
|
||
}
|
||
}
|
||
|
||
// Ein langer Bon braucht Platz und Zeit: 50 Zeilen sind gut 2.000 Token Antwort,
|
||
// dazu das Nachdenken; ein großes Bild liest das Modell auf der Box nicht in zwei Minuten.
|
||
const READ = { maxTokens: 16_000, timeoutMs: 300_000 };
|
||
const ATTEMPTS = 3;
|
||
|
||
async function readOne(householdId: string, id: string, photo: string, ai: NonNullable<Awaited<ReturnType<typeof aiFor>>>, locale: string, attempt: number) {
|
||
const fail = (status: "queued" | "failed", error: string) =>
|
||
withHousehold(householdId, (c) => c.query("update receipts set status = $2, error = $3 where id = $1", [id, status, error]));
|
||
let read;
|
||
try {
|
||
const jpg = await readFile(path.join(root(), photo));
|
||
read = receiptFromText(
|
||
await askText(
|
||
ai,
|
||
"vision",
|
||
RECEIPT_PROMPT,
|
||
[
|
||
{ type: "text", text: "Read this receipt." },
|
||
{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${jpg.toString("base64")}` } },
|
||
],
|
||
READ,
|
||
),
|
||
);
|
||
} catch (error) {
|
||
// Nach dem letzten Versuch nicht ewig „wartet“: als fehlgeschlagen zeigen, mit „Nochmal“.
|
||
if (error instanceof AiUnavailable || error instanceof AiNotConfigured) return fail(attempt >= ATTEMPTS ? "failed" : "queued", "unavailable");
|
||
return fail("failed", "photo");
|
||
}
|
||
if (!read) return fail("failed", "unreadable");
|
||
await withHousehold(householdId, async (c) => {
|
||
const suggestions = await suggestLines(c, read.lines.map((l) => l.text), locale, ai);
|
||
const stores = (await c.query("select id, name, chain, is_default from stores")).rows as { id: string; name: string; chain: string | null; is_default: boolean }[];
|
||
const said = (read.store ?? "").toLocaleLowerCase("de");
|
||
const store = stores.find((s) => said && (said.includes(s.name.toLocaleLowerCase("de")) || (s.chain && said.includes(s.chain)))) ?? stores.find((s) => s.is_default);
|
||
await c.query("delete from receipt_lines where receipt_id = $1", [id]);
|
||
for (const [i, l] of read.lines.entries()) {
|
||
const s = suggestions[i]!;
|
||
await c.query(
|
||
`insert into receipt_lines (household_id, receipt_id, position, raw_text, qty, unit_price, total_price, ingredient_id, pack_qty, pack_unit, match_source, product, weighed, skipped)
|
||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,
|
||
[
|
||
householdId, id, i + 1, l.text, l.qty, l.unitPrice, l.totalPrice, s.ingredientId, s.pack?.qty ?? null, s.pack?.unit ?? null, s.source, s.product,
|
||
// Gewogen: aus der Gewichtszeile, oder eine Menge mit Nachkommastellen (0,416 kg).
|
||
!!l.weighed || (l.qty !== null && !Number.isInteger(l.qty)),
|
||
s.source === "skip",
|
||
],
|
||
);
|
||
}
|
||
await c.query(
|
||
`update receipts set status = 'review', error = $6, store_name = $2, store_id = $3, total = $4,
|
||
purchased_at = coalesce($5::date::timestamptz, created_at) where id = $1`,
|
||
[id, read.store, store?.id ?? null, read.total, read.date, read.partial ? "partial" : null],
|
||
);
|
||
});
|
||
}
|
||
|
||
export type ReceiptSummary = { id: string; status: string; storeName: string | null; purchasedAt: string | null; total: number | null; lines: number; error: string | null; createdAt: string };
|
||
|
||
export async function listReceipts(client: PoolClient): Promise<ReceiptSummary[]> {
|
||
const { rows } = await client.query(
|
||
`select r.id, r.status, coalesce(s.name, r.store_name) as "storeName", r.purchased_at::date::text as "purchasedAt", r.total::float,
|
||
(select count(*)::int from receipt_lines l where l.receipt_id = r.id) as lines, r.error, r.created_at::text as "createdAt"
|
||
from receipts r left join stores s on s.id = r.store_id
|
||
order by r.created_at desc limit 50`,
|
||
);
|
||
return rows;
|
||
}
|
||
|
||
export type ReviewLine = {
|
||
id: string;
|
||
text: string;
|
||
qty: number | null;
|
||
totalPrice: number | null;
|
||
ingredientId: string | null;
|
||
ingredientName: string | null;
|
||
ingredientUnit: string | null;
|
||
packQty: number | null;
|
||
packUnit: string | null;
|
||
source: string | null;
|
||
product: string | null;
|
||
weighed: boolean;
|
||
skipped: boolean;
|
||
};
|
||
|
||
export async function getReceipt(client: PoolClient, id: string, locale: string) {
|
||
const receipt = (
|
||
await client.query(
|
||
`select id, status, store_id as "storeId", store_name as "storeName", purchased_at::date::text as "purchasedAt", total::float, error
|
||
from receipts where id = $1`,
|
||
[id],
|
||
)
|
||
).rows[0];
|
||
if (!receipt) return null;
|
||
const names = new Map((await allIngredients(client)).map((e) => [e.id, e]));
|
||
const lines: ReviewLine[] = (
|
||
await client.query(
|
||
`select id, raw_text as text, qty::float, total_price::float as "totalPrice", ingredient_id as "ingredientId",
|
||
pack_qty::float as "packQty", pack_unit as "packUnit", match_source as source, product, weighed, skipped
|
||
from receipt_lines where receipt_id = $1 order by position`,
|
||
[id],
|
||
)
|
||
).rows.map((l) => {
|
||
const e = l.ingredientId ? names.get(l.ingredientId) : undefined;
|
||
return { ...l, ingredientName: e ? (e.names[locale] ?? e.names.en ?? null) : null, ingredientUnit: e?.unit ?? null };
|
||
});
|
||
const stores = (await client.query("select id, name from stores order by is_default desc, name")).rows;
|
||
return { ...receipt, lines, stores };
|
||
}
|
||
|
||
/** skip: „nicht zum Kochen“ — Lunch merkt sich den Bontext ohne Zutat. */
|
||
export type Decision = { lineId: string; ingredientId: string | null; packQty: number | null; packUnit: "g" | "ml" | "piece" | null; skip?: boolean };
|
||
|
||
export class ReceiptRefused extends Error {}
|
||
|
||
/**
|
||
* Bestätigen: je Zeile Zutat (oder Sonstiges) und Packung. Gelernt wird die Zuordnung,
|
||
* ins Preisgedächtnis geht Preis ÷ (Anzahl × Packung). Danach ist das Foto weg.
|
||
*/
|
||
export async function confirmReceipt(
|
||
client: PoolClient,
|
||
householdId: string,
|
||
id: string,
|
||
input: { storeId: string | null; purchasedAt: string | null; decisions: Decision[] },
|
||
): Promise<void> {
|
||
const receipt = (await client.query("select status, photo_path, created_at from receipts where id = $1 for update", [id])).rows[0];
|
||
if (!receipt || receipt.status !== "review") throw new ReceiptRefused("status");
|
||
const units = new Map((await allIngredients(client)).map((e) => [e.id, e.unit]));
|
||
const when = input.purchasedAt ?? receipt.created_at.toISOString().slice(0, 10);
|
||
await client.query("update receipts set store_id = $2, purchased_at = $3::date::timestamptz where id = $1", [id, input.storeId, when]);
|
||
for (const d of input.decisions) {
|
||
const line = (await client.query("select raw_text, qty::float, total_price::float as total from receipt_lines where id = $1 and receipt_id = $2", [d.lineId, id])).rows[0];
|
||
if (!line) throw new ReceiptRefused("line");
|
||
if (d.skip || !d.ingredientId) {
|
||
await client.query("update receipt_lines set ingredient_id = null, pack_qty = null, pack_unit = null, skipped = $2, confirmed = true where id = $1", [d.lineId, !!d.skip]);
|
||
// Nur, wer es selbst weggewischt hat, lehrt Lunch „nicht zum Kochen“; Unerkanntes bleibt offen.
|
||
if (d.skip)
|
||
await client.query(
|
||
`insert into ingredient_aliases (household_id, raw_text_normalized, ingredient_id, pack_qty, pack_unit) values ($1, $2, null, null, null)
|
||
on conflict (household_id, raw_text_normalized) do update set ingredient_id = null, pack_qty = null, pack_unit = null`,
|
||
[householdId, normalizeLine(line.raw_text)],
|
||
);
|
||
continue;
|
||
}
|
||
const unit = units.get(d.ingredientId);
|
||
if (d.ingredientId && !unit) throw new ReceiptRefused("ingredient");
|
||
// Packung nur in der Einheit der Zutat (Gewicht zu Gewicht usw.).
|
||
const pack = d.ingredientId && d.packQty && d.packQty > 0 && d.packUnit === unit ? d.packQty : null;
|
||
await client.query("update receipt_lines set ingredient_id = $2, pack_qty = $3, pack_unit = $4, skipped = false, confirmed = true where id = $1", [
|
||
d.lineId,
|
||
d.ingredientId,
|
||
pack,
|
||
pack ? unit : null,
|
||
]);
|
||
await client.query(
|
||
`insert into ingredient_aliases (household_id, raw_text_normalized, ingredient_id, pack_qty, pack_unit) values ($1, $2, $3, $4, $5)
|
||
on conflict (household_id, raw_text_normalized) do update set ingredient_id = excluded.ingredient_id, pack_qty = excluded.pack_qty, pack_unit = excluded.pack_unit`,
|
||
[householdId, normalizeLine(line.raw_text), d.ingredientId, pack, pack ? unit : null],
|
||
);
|
||
const perUnit = unitPrice(line.total, line.qty, pack);
|
||
if (perUnit !== null) {
|
||
await client.query(
|
||
`insert into price_points (household_id, ingredient_id, store_id, price_per_unit, unit, observed_at, source, receipt_id)
|
||
values ($1, $2, $3, $4, $5, $6::date::timestamptz, 'receipt', $7)`,
|
||
[householdId, d.ingredientId, input.storeId, perUnit, unit, when, id],
|
||
);
|
||
}
|
||
}
|
||
await client.query("update receipts set status = 'done', photo_path = null where id = $1", [id]);
|
||
await dropPhoto(receipt.photo_path);
|
||
}
|
||
|
||
export async function deleteReceipt(client: PoolClient, id: string): Promise<boolean> {
|
||
const gone = (await client.query("delete from receipts where id = $1 returning photo_path", [id])).rows[0];
|
||
if (!gone) return false;
|
||
await dropPhoto(gone.photo_path);
|
||
return true;
|
||
}
|