Compare commits

..
2 Commits
Author SHA1 Message Date
kai 9a5a049273 Keep bottom-pinned buttons on the keyboard while typing (26.11.26) (#27)
release / which version (push) Successful in 4s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m5s
release / tag and release (push) Successful in 2s
2026-11-07 08:33:12 +00:00
kai 248ef3de31 Receipts: read on the box, match, confirm into the price memory (26.11.25) (#26)
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m5s
release / tag and release (push) Successful in 2s
2026-11-07 08:18:25 +00:00
33 changed files with 1360 additions and 15 deletions

No files matched your search

+17 -3
View File
@@ -7,15 +7,15 @@
> **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase,
> kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002).
> Verteilung über den Markt, Repo öffentlich (E-0005).
> **Status:** 26.11.24 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> **Status:** 26.11.26 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> Anmeldung (Passkeys, Kinder mit Gerät + PIN), Gerichte (Link, Kochbuchfoto, AI über den
> Olares Router), Wünschen, Plan, Einkaufsliste (Echtzeit, offline), Kochmodus mit
> Bewertung, Web-App; Einzahl bei Stück-Mengen (26.11.15), Preise und Kosten mit Ampel
> (V2a, 26.11.16), Olares Router als Standard (26.11.17), untere Leiste am iPhone (26.11.18),
> Rolle „Jugendlich“ (26.11.19), Rezepte in einer Form (26.11.20),
> Produkte je Gericht (26.11.21), Veto mit Gegenvorschlag (26.11.22),
> bis zu 5 Fotos je Gericht (26.11.23), Gerichte einsprechen (26.11.24). Offen sind V2b (Kassenbons)
> und der Magic Link.
> bis zu 5 Fotos je Gericht (26.11.23), Gerichte einsprechen (26.11.24), Kassenbons (V2b, 26.11.25). Offen ist der
> Magic Link (braucht SMTP).
> **Letzte Aktualisierung:** 7. November 2026
Diese Datei ist das Gedächtnis jeder Sitzung. Entscheidungen stehen in
@@ -374,6 +374,17 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
- `Permissions-Policy` erlaubt das Mikrofon nur für die eigene Seite (`next.config.ts`).
Playwright nimmt mit künstlichem Mikrofon auf (`playwright.config.ts`, `launchOptions`).
## Kassenbons (V2b, seit 26.11.25)
- `/bons` (SHOPPERS): Foto → `/api/receipts` (Datei unter `/app/data/bons/`, Status
`queued`) → `processQueued` im Hintergrund (je Bon höchstens 3 Versuche; ohne Bildmodell
wartet er) → Bildmodell mit `RECEIPT_PROMPT`, geprüft in `lib/receipt-read.ts` → Zeilen
mit Vorschlag (`suggestLines`: gelernt `ingredient_aliases` → Produkt eines Gerichts
`matchesProduct` → Suche → AI nur aus Suchkandidaten) → `review`.
- Bestätigen (`confirmReceipt`): Alias lernen, `price_points` (source `receipt`, Preis ÷
(Anzahl × Packung), nur wenn die Packung zur Einheit der Zutat passt), Status `done`,
**Foto gelöscht**. Migration 0016 (`store_name`, `error`, `attempts`, `match_source`).
## Rollen
- `admin`, `member`, `teen` (seit 26.11.19), `child`, `guest`. Wer was darf, steht nur
@@ -392,6 +403,9 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
`useKeyboardSafeNav` (`lib/use-keyboard-nav.ts`): beim Tippen `hidden`, danach am
`visualViewport` ausgerichtet (`translateY` um die Lücke) und ein Scroll auf der
Stelle. Eine neue feste Leiste unten nutzt denselben Haken. `e2e/pwa.spec.ts` wacht.
- Feste Knopfleisten unten nehmen `sticky bottom-[var(--nav-space)]` (seit 26.11.26), nie
einen festen Abstand: Beim Tippen setzt der Haken `data-typing` an `<html>`, dann ist
`--nav-space` 0 und die Knöpfe sitzen über der Tastatur.
## AI
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: What's cooking?
description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.24
version: 26.11.26
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.24'
versionName: '26.11.26'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+28
View File
@@ -0,0 +1,28 @@
import { notFound } from "next/navigation";
import { getLocale, getTranslations } from "next-intl/server";
import { ReceiptReview } from "@/components/receipts/receipt-review";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { getReceipt } from "@/lib/receipts";
export const dynamic = "force-dynamic";
export default async function ReceiptPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
if (!/^[0-9a-f-]{36}$/.test(id)) notFound();
const session = await requireSession();
const t = await getTranslations("receipts");
const locale = await getLocale();
const receipt = await withHousehold(session.householdId, (c) => getReceipt(c, id, locale));
if (!receipt) notFound();
return (
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
<header className="flex flex-col gap-1">
<p className="eyebrow">{t("eyebrow")}</p>
<h1 className="text-4xl leading-tight">{receipt.status === "done" ? t("doneTitle") : t("reviewTitle")}</h1>
{receipt.storeName ? <p className="text-muted-foreground">{t("read", { store: receipt.storeName })}</p> : null}
</header>
<ReceiptReview receipt={receipt} />
</main>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { redirect } from "next/navigation";
import { requireSession } from "@/lib/auth/session";
import { can, SHOPPERS } from "@/lib/auth/roles";
// Bons scannen und bestätigen: wer einkauft (Erwachsene, Jugendliche).
export default async function ShoppersOnly({ children }: { children: React.ReactNode }) {
const session = await requireSession();
if (!can(SHOPPERS, session.role)) redirect("/");
return children;
}
+71
View File
@@ -0,0 +1,71 @@
import Link from "next/link";
import { getLocale, getTranslations } from "next-intl/server";
import { ReceiptUpload, ReceiptWatcher } from "@/components/receipts/receipt-upload";
import { aiFor } from "@/lib/ai-settings";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { listReceipts, processQueued } from "@/lib/receipts";
import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export default async function ReceiptsPage() {
const session = await requireSession();
const t = await getTranslations("receipts");
const locale = await getLocale();
const ai = await aiFor(session.householdId);
// Wartende Bons anstoßen (etwa wenn die AI vorhin nicht erreichbar war).
void processQueued(session.householdId, locale).catch(() => undefined);
const receipts = await withHousehold(session.householdId, listReceipts);
const date = new Intl.DateTimeFormat(locale, { dateStyle: "medium" });
const money = new Intl.NumberFormat(locale, { style: "currency", currency: "EUR" });
const busy = receipts.some((r) => r.status === "queued" || r.status === "processing");
return (
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
<header className="flex flex-col gap-1">
<p className="eyebrow">{t("eyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("title")}</h1>
<p className="text-muted-foreground">{t("intro")}</p>
</header>
{ai?.visionModel ? null : (
<p role="note" className="rounded-2xl bg-muted p-4 text-sm">
{t("noAi")}
</p>
)}
<ReceiptUpload />
{busy ? <ReceiptWatcher /> : null}
{receipts.length ? (
<ul className="flex flex-col divide-y divide-border">
{receipts.map((r) => {
const label = [r.storeName, r.purchasedAt ? date.format(new Date(`${r.purchasedAt}T12:00:00`)) : null].filter(Boolean).join(" · ") || t("unnamed");
const status = t(`status.${r.status}`, { n: r.lines });
return (
<li key={r.id}>
{r.status === "review" || r.status === "done" ? (
<Link href={`/bons/${r.id}`} className="flex min-h-14 items-center justify-between gap-3 py-2">
<span className="flex min-w-0 flex-col">
<span className="font-semibold">{label}</span>
<span className={cn("text-sm", r.status === "review" ? "text-accent" : "text-muted-foreground")}>{status}</span>
</span>
{r.total !== null ? <span className="tabular-nums">{money.format(r.total)}</span> : null}
</Link>
) : (
<div className="flex min-h-14 flex-col justify-center py-2">
<span className="font-semibold">{label}</span>
<span className="text-sm text-muted-foreground">
{status}
{r.error ? ` · ${t(`errors.${r.error}`)}` : ""}
</span>
{r.status === "failed" || (r.status === "queued" && r.error) ? <ReceiptUpload retry={r.id} /> : null}
</div>
)}
</li>
);
})}
</ul>
) : (
<p className="rounded-2xl border border-border p-4 text-sm text-muted-foreground">{t("empty")}</p>
)}
</main>
);
}
+6
View File
@@ -1,3 +1,4 @@
import { Receipt } from "lucide-react";
import Link from "next/link";
import { getLocale, getTranslations } from "next-intl/server";
import { ShoppingList } from "@/components/shopping/shopping-list";
@@ -14,6 +15,7 @@ export const dynamic = "force-dynamic";
export default async function ShoppingPage() {
const session = await requireAdult();
const t = await getTranslations("shopping");
const tr = await getTranslations("receipts");
const locale = await getLocale();
const data = await withHousehold(session.householdId, async (c) => {
const round = await currentRound(c);
@@ -29,6 +31,10 @@ export default async function ShoppingPage() {
<p className="eyebrow">{data.store ? t("eyebrowStore", { store: data.store }) : t("eyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("title")}</h1>
</header>
<Link href="/bons" className={cn(buttonVariants({ variant: "outline" }), "self-start")}>
<Receipt aria-hidden />
{tr("link")}
</Link>
{data.chains.length ? <StorePicker chains={data.chains} /> : null}
{"items" in data && data.items ? (
<ShoppingList initial={data.items} aisles={data.aisles} me={session.displayName} />
+22
View File
@@ -0,0 +1,22 @@
import { getLocale } from "next-intl/server";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json } from "@/lib/auth/http";
import { SHOPPERS } from "@/lib/auth/roles";
import { withHousehold } from "@/lib/db";
import { processQueued } from "@/lib/receipts";
export const dynamic = "force-dynamic";
// Noch einmal lesen (nach einem Fehler oder wenn die AI wieder da ist).
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await guardWrite(request, [...SHOPPERS]);
if (isResponse(session)) return session;
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
const n = await withHousehold(session.householdId, async (c) =>
(await c.query("update receipts set status = 'queued', attempts = 0, error = null where id = $1 and status in ('queued', 'failed')", [id])).rowCount,
);
if (!n) return fail("status", 409);
void processQueued(session.householdId, await getLocale()).catch(() => undefined);
return json({ ok: true });
}
+50
View File
@@ -0,0 +1,50 @@
import { z } from "zod";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json, readJson } from "@/lib/auth/http";
import { SHOPPERS } from "@/lib/auth/roles";
import { withHousehold } from "@/lib/db";
import { confirmReceipt, deleteReceipt, ReceiptRefused } from "@/lib/receipts";
export const dynamic = "force-dynamic";
const uuid = z.string().uuid();
const body = z.object({
storeId: uuid.nullable(),
purchasedAt: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(),
decisions: z
.array(
z.object({
lineId: uuid,
ingredientId: uuid.nullable(),
packQty: z.number().positive().max(100000).nullable(),
packUnit: z.enum(["g", "ml", "piece"]).nullable(),
}),
)
.max(200),
});
// Bestätigen: Zuordnung lernen, Preise ins Preisgedächtnis, Foto löschen.
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await guardWrite(request, [...SHOPPERS]);
if (isResponse(session)) return session;
if (!uuid.safeParse(id).success) return fail("invalid", 400);
const parsed = body.safeParse(await readJson(request));
if (!parsed.success) return fail("invalid", 400);
try {
await withHousehold(session.householdId, (c) => confirmReceipt(c, session.householdId, id, parsed.data));
return json({ ok: true });
} catch (error) {
if (error instanceof ReceiptRefused) return fail(error.message, 409);
throw error;
}
}
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await guardWrite(request, [...SHOPPERS]);
if (isResponse(session)) return session;
if (!uuid.safeParse(id).success) return fail("invalid", 400);
const ok = await withHousehold(session.householdId, (c) => deleteReceipt(c, id));
return ok ? json({ ok: true }) : fail("notFound", 404);
}
+28
View File
@@ -0,0 +1,28 @@
import { getLocale } from "next-intl/server";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json } from "@/lib/auth/http";
import { SHOPPERS } from "@/lib/auth/roles";
import { withHousehold } from "@/lib/db";
import { PhotoRejected } from "@/lib/photos";
import { createReceipt, processQueued } from "@/lib/receipts";
export const dynamic = "force-dynamic";
// Bons fotografieren, auch mehrere hintereinander. Gelesen wird danach im
// Hintergrund; niemand wartet auf das Modell (Konzept, „Bons laufen asynchron“).
export async function POST(request: Request) {
const session = await guardWrite(request, [...SHOPPERS]);
if (isResponse(session)) return session;
const form = await request.formData().catch(() => null);
const files = (form?.getAll("photo") ?? []).filter((f): f is File => f instanceof File).slice(0, 10);
if (!files.length) return fail("invalid", 400);
const ids: string[] = [];
try {
for (const f of files) ids.push(await withHousehold(session.householdId, (c) => createReceipt(c, session.householdId, session.memberId, f)));
} catch (error) {
if (error instanceof PhotoRejected) return fail("photo", 400);
throw error;
}
void processQueued(session.householdId, await getLocale()).catch(() => undefined);
return json({ ids }, 201);
}
+10
View File
@@ -65,6 +65,16 @@
--font-serif: var(--font-newsreader), ui-serif, Georgia, serif;
}
/* Abstand fester Knopfleisten (Speichern, Übernehmen, Weiter) zur unteren Navigation.
Beim Tippen ist die Navigation weg (lib/use-keyboard-nav.ts) — dann sitzen die Knöpfe
direkt über der Tastatur statt mitten im Bild (Kai, 7.11.2026). */
:root {
--nav-space: calc(4rem + env(safe-area-inset-bottom));
}
:root[data-typing] {
--nav-space: 0px;
}
html {
color-scheme: light dark;
-webkit-text-size-adjust: 100%;
+1 -1
View File
@@ -251,7 +251,7 @@ export function CookingMode({
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-10 flex gap-2 bg-background py-2">
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
<Button type="button" variant="outline" size="lg" disabled={index < 0} onClick={() => go(-1)} aria-label={t("back")}>
<ChevronLeft aria-hidden />
</Button>
+3 -3
View File
@@ -13,7 +13,7 @@ import { parseNumber, type BaseUnit } from "@/lib/units";
import { cn } from "@/lib/utils";
import { SECTIONS, type Section } from "@/lib/recipe-style";
type Picked = { id: string; name: string; unit: BaseUnit };
export type Picked = { id: string; name: string; unit: BaseUnit };
// Produkt (optional): Name, Packung in der Einheit der Zeile, Kochzeit laut Packung.
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string; product: string; pack: string; cook: string; open: boolean };
type StepRow = { key: number; text: string; timer: string; section: Section | "" };
@@ -447,7 +447,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
</section>
{error ? <ErrorNotice>{t(`form.errors.${error}`)}</ErrorNotice> : null}
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-10 flex gap-2 bg-background py-2">
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
<Button type="button" variant="outline" onClick={() => router.back()}>
{t("form.cancel")}
</Button>
@@ -461,7 +461,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
// Zutat suchen und wählen. Tippen sucht in der Sprache der Person, auch über
// Synonyme (lib/ingredient-search.ts); ein Tipp auf einen Treffer wählt ihn.
function IngredientPicker({ value, onPick }: { value: Picked | null; onPick: (p: Picked) => void }) {
export function IngredientPicker({ value, onPick }: { value: Picked | null; onPick: (p: Picked) => void }) {
const t = useTranslations("dishes.form");
const id = useId();
const [query, setQuery] = useState(value?.name ?? "");
+1 -1
View File
@@ -61,7 +61,7 @@ export function StarterPicker({ starters }: { starters: Starter[] }) {
})}
</ul>
{error ? <ErrorNotice>{t("form.errors.unknown")}</ErrorNotice> : null}
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-10 bg-background/0 pb-2">
<div className="sticky bottom-[var(--nav-space)] z-10 bg-background/0 pb-2">
<Button
size="lg"
className="w-full shadow-lg"
+1 -1
View File
@@ -186,7 +186,7 @@ export function PlanBoard({
) : null}
{status === "open" && slots.length ? (
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-10 bg-background py-2">
<div className="sticky bottom-[var(--nav-space)] z-10 bg-background py-2">
<Button type="button" size="lg" className="w-full" disabled={busy} onClick={() => act("POST", "/api/plan/approve")}>
{t("approve")}
</Button>
+183
View File
@@ -0,0 +1,183 @@
"use client";
import { Check, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { IngredientPicker, type Picked } from "@/components/dishes/dish-form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ErrorNotice } from "@/components/ui/notice";
import { parseNumber } from "@/lib/units";
import { cn } from "@/lib/utils";
type Line = {
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;
};
type Receipt = { id: string; status: string; storeId: string | null; purchasedAt: string | null; lines: Line[]; stores: { id: string; name: string }[] };
type Row = { line: Line; ingredient: Picked | null; pack: string; other: boolean };
const fmt = (n: number | null) => (n === null ? "" : String(Math.round(n * 1000) / 1000).replace(".", ","));
// Bon bestätigen (Konzept: „erst gelernte Zuordnungen, dann KI-Vorschlag, dann
// Bestätigung“). Je Zeile: Zutat und Packung prüfen, eine andere wählen oder
// „Sonstiges“. Erst „Übernehmen“ schreibt ins Preisgedächtnis und lernt.
export function ReceiptReview({ receipt }: { receipt: Receipt }) {
const t = useTranslations("receipts");
const locale = useLocale();
const router = useRouter();
const money = new Intl.NumberFormat(locale, { style: "currency", currency: "EUR" });
const done = receipt.status === "done";
const [rows, setRows] = useState<Row[]>(
receipt.lines.map((l) => ({
line: l,
ingredient: l.ingredientId ? { id: l.ingredientId, name: l.ingredientName ?? "", unit: (l.ingredientUnit ?? "g") as Picked["unit"] } : null,
pack: fmt(l.packQty),
other: !l.ingredientId,
})),
);
const [storeId, setStoreId] = useState(receipt.storeId ?? "");
const [date, setDate] = useState(receipt.purchasedAt ?? "");
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
const update = (i: number, patch: Partial<Row>) => setRows((rs) => rs.map((r, n) => (n === i ? { ...r, ...patch } : r)));
async function save() {
setBusy(true);
setError(false);
const res = await fetch(`/api/receipts/${receipt.id}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
storeId: storeId || null,
purchasedAt: date || null,
decisions: rows.map((r) => ({
lineId: r.line.id,
ingredientId: r.other ? null : (r.ingredient?.id ?? null),
packQty: r.other || !r.pack.trim() ? null : parseNumber(r.pack),
packUnit: r.other || !r.ingredient ? null : r.ingredient.unit,
})),
}),
}).catch(() => null);
setBusy(false);
if (!res?.ok) return setError(true);
router.push("/bons");
router.refresh();
}
async function remove() {
setBusy(true);
await fetch(`/api/receipts/${receipt.id}`, { method: "DELETE" }).catch(() => null);
router.push("/bons");
router.refresh();
}
return (
<div className="flex flex-col gap-5">
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-2">
<Label htmlFor="receipt-store">{t("store")}</Label>
<select
id="receipt-store"
disabled={done}
value={storeId}
onChange={(e) => setStoreId(e.target.value)}
className="min-h-11 rounded-xl border border-border bg-background px-3 text-base"
>
<option value="">{t("noStore")}</option>
{receipt.stores.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="receipt-date">{t("date")}</Label>
<Input id="receipt-date" type="date" disabled={done} value={date} onChange={(e) => setDate(e.target.value)} />
</div>
</div>
<ul className="flex flex-col gap-3">
{rows.map((r, i) => (
<li key={r.line.id} className={cn("flex flex-col gap-2 rounded-2xl p-3", r.other ? "border border-border" : "bg-muted")}>
<div className="flex items-baseline justify-between gap-3">
<span className="font-mono text-sm">
{r.line.qty && r.line.qty !== 1 ? `${fmt(r.line.qty)} × ` : ""}
{r.line.text}
</span>
<span className="shrink-0 tabular-nums">{r.line.totalPrice !== null ? money.format(r.line.totalPrice) : "–"}</span>
</div>
{r.other ? (
<div className="flex items-center justify-between gap-2">
<span className="text-sm text-muted-foreground">{t("otherLine")}</span>
{!done ? (
<Button type="button" variant="ghost" onClick={() => update(i, { other: false })}>
{t("assign")}
</Button>
) : null}
</div>
) : (
<>
{r.line.source && r.ingredient?.id === r.line.ingredientId ? (
<p className="text-xs text-muted-foreground">{t(`source.${r.line.source}`, { product: r.line.product ?? "" })}</p>
) : null}
{done ? (
<p>{r.ingredient?.name}</p>
) : (
<IngredientPicker value={r.ingredient} onPick={(p) => update(i, { ingredient: p, pack: p.unit === "piece" ? "1" : "" })} />
)}
<div className="flex items-end gap-2">
<div className="flex flex-col gap-1">
<Label htmlFor={`pack-${r.line.id}`} className="text-sm">
{t("pack", { unit: t(`units.${r.ingredient?.unit ?? "g"}`) })}
</Label>
<Input
id={`pack-${r.line.id}`}
inputMode="decimal"
className="w-32"
disabled={done}
value={r.pack}
onChange={(e) => update(i, { pack: e.target.value })}
/>
</div>
{!done ? (
<Button type="button" variant="ghost" className="ml-auto" onClick={() => update(i, { other: true })}>
{t("other")}
</Button>
) : null}
</div>
</>
)}
</li>
))}
</ul>
{error ? <ErrorNotice>{t("saveError")}</ErrorNotice> : null}
{done ? (
<p className="text-sm text-muted-foreground">{t("doneText")}</p>
) : (
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
<Button type="button" variant="outline" disabled={busy} onClick={remove} aria-label={t("delete")}>
<Trash2 aria-hidden />
</Button>
<Button type="button" size="lg" className="flex-1" disabled={busy} onClick={save}>
<Check aria-hidden />
{t("confirm")}
</Button>
</div>
)}
</div>
);
}
+79
View File
@@ -0,0 +1,79 @@
"use client";
import { Camera, RotateCcw } from "lucide-react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { ErrorNotice } from "@/components/ui/notice";
// Bon fotografieren (auch mehrere) oder einen gescheiterten noch einmal lesen lassen.
export function ReceiptUpload({ retry }: { retry?: string }) {
const t = useTranslations("receipts");
const router = useRouter();
const input = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
if (retry) {
return (
<Button
type="button"
variant="ghost"
className="self-start"
disabled={busy}
onClick={async () => {
setBusy(true);
await fetch(`/api/receipts/${retry}/retry`, { method: "POST" }).catch(() => null);
setBusy(false);
router.refresh();
}}
>
<RotateCcw aria-hidden />
{t("retry")}
</Button>
);
}
async function upload(files: FileList) {
setBusy(true);
setError(false);
const form = new FormData();
for (const f of Array.from(files)) form.append("photo", f);
const res = await fetch("/api/receipts", { method: "POST", body: form }).catch(() => null);
setBusy(false);
if (input.current) input.current.value = "";
if (res?.ok) router.refresh();
else setError(true);
}
return (
<div className="flex flex-col gap-2">
<input
ref={input}
type="file"
accept="image/*"
multiple
className="sr-only"
tabIndex={-1}
aria-hidden
onChange={(e) => e.target.files?.length && upload(e.target.files)}
/>
<Button type="button" size="lg" disabled={busy} onClick={() => input.current?.click()}>
<Camera aria-hidden />
{busy ? t("uploading") : t("scan")}
</Button>
{error ? <ErrorNotice>{t("uploadError")}</ErrorNotice> : null}
</div>
);
}
/** Solange ein Bon gelesen wird: die Liste alle paar Sekunden neu laden. */
export function ReceiptWatcher() {
const router = useRouter();
useEffect(() => {
const tick = setInterval(() => router.refresh(), 3000);
return () => clearInterval(tick);
}, [router]);
return null;
}
+10
View File
@@ -0,0 +1,10 @@
-- Kassenbons (V2b): was das Bildmodell als Laden gelesen hat, warum ein Lauf
-- scheiterte, und woher der Zuordnungsvorschlag einer Zeile stammt (gelernt,
-- Produkt eines Gerichts, Suche, AI) — damit die Bestätigung es zeigen kann.
alter table receipts
add column store_name text check (length(store_name) <= 80),
add column error text check (length(error) <= 200),
add column attempts integer not null default 0;
alter table receipt_lines
add column match_source text check (match_source in ('alias', 'product', 'search', 'ai')),
add column product text check (length(product) <= 80);
+60
View File
@@ -1,4 +1,5 @@
import { expect, test, type Browser, type Page } from "@playwright/test";
import sharp from "sharp";
// Einkaufsliste am iPhone (Paket 7): Hauptladen, Vorrats-Check, Abhaken,
// Echtzeit zwischen zwei Geräten, ohne Netz weiter bedienbar, Freitext.
@@ -92,3 +93,62 @@ test("a product on a dish goes on the list and sets the cooking timer", async ({
await page.goto("/einkauf");
await expect(page.locator("main")).toContainText("Barilla Spaghetti Nr. 5");
});
// Kassenbon (V2b): eine nachgebildete AI auf der Testadresse liest einen Bon mit
// dem Produkt aus dem Test davor und Klopapier. Der Schlüssel ist der aus „gerichte“.
test.describe("receipts", () => {
let server: import("node:http").Server;
const origin = process.env.IMPORT_TEST_ORIGIN ?? "http://127.0.0.1:3021";
const reply = (r: object) => JSON.stringify({ choices: [{ message: { content: JSON.stringify(r) } }] });
test.beforeAll(async () => {
const { createServer } = await import("node:http");
server = createServer((req, res) => {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
if (req.headers.authorization !== "Bearer sk-test") return res.writeHead(401).end();
if (raw.includes("supermarket receipt photo")) {
return res.writeHead(200, { "content-type": "application/json" }).end(
reply({
store: "REWE Markt GmbH",
date: "07.11.26",
total: 5.28,
lines: [
{ text: "BARILLA SPAGH N5 500G", qty: null, unit_price: null, total_price: 1.79 },
{ text: "KLOPAPIER 8ST", qty: null, unit_price: null, total_price: 3.49 },
],
}),
);
}
return res.writeHead(500).end();
});
});
await new Promise<void>((done) => server.listen(Number(new URL(origin).port), "127.0.0.1", done));
});
test.afterAll(() => new Promise<void>((done) => server.close(() => done())));
test("a receipt is read, the product recognised, and its price lands on the dish", async ({ page }) => {
await page.goto("/einkauf");
await page.getByRole("link", { name: "Bon fotografieren" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Kassenbons");
const jpg = await sharp({ create: { width: 600, height: 1200, channels: 3, background: { r: 250, g: 250, b: 245 } } }).jpeg().toBuffer();
await page.locator("input[type=file]").setInputFiles({ name: "bon.jpg", mimeType: "image/jpeg", buffer: jpg });
await page.getByRole("link", { name: /2 Zeilen zu bestätigen/ }).click({ timeout: 20_000 });
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Bon prüfen");
await expect(page.getByText("Gelesen: REWE Markt GmbH")).toBeVisible();
await expect(page.getByLabel("Datum")).toHaveValue("2026-11-07");
const pasta = page.locator("li", { hasText: "BARILLA SPAGH N5 500G" });
await expect(pasta).toContainText("euer Produkt: Barilla Spaghetti Nr. 5");
await expect(pasta.getByLabel("Packung in g")).toHaveValue("500");
await expect(page.locator("li", { hasText: "KLOPAPIER 8ST" })).toContainText("Sonstiges");
await page.getByRole("button", { name: "Übernehmen" }).click();
await expect(page.getByText("bestätigt")).toBeVisible();
// Der Bonpreis gilt jetzt am Gericht: 1,79 € für 500 g = 3,58 € je kg.
await page.goto("/gerichte");
await page.getByRole("link", { name: /Spaghetti Bolognese/ }).click();
await expect(page.locator("section", { hasText: "Kosten" }).last().locator("li", { hasText: "Spaghetti" }).first()).toContainText("3,58 € je kg · vom Bon");
});
});
+19
View File
@@ -57,3 +57,22 @@ test("the bottom bar steps aside while typing and comes back at the bottom", asy
expect(Math.round(box!.y + box!.height)).toBe(height);
await expect(nav).not.toHaveAttribute("style", /translateY/);
});
test("buttons pinned to the bottom sit on the keyboard while typing, above the bar afterwards", async ({ page }) => {
// iOS: „Speichern“ schwebte beim Tippen eine Leistenhöhe über der Tastatur (Kai, 7.11.2026).
await page.goto("/gerichte/neu");
const save = page.getByRole("button", { name: "Speichern" });
const height = page.viewportSize()!.height;
const nav = page.getByRole("navigation", { name: "Navigation" });
const bottomOf = async () => {
const box = (await save.locator("xpath=..").boundingBox())!;
return Math.round(box.y + box.height);
};
await page.locator("#title").focus();
await expect(nav).toBeHidden();
await expect.poll(bottomOf).toBe(height);
await page.locator("#title").blur();
await expect(nav).toBeVisible();
const navTop = Math.round((await nav.boundingBox())!.y);
await expect.poll(bottomOf).toBeLessThanOrEqual(navTop);
});
+1
View File
@@ -22,6 +22,7 @@ const SIGNED_IN = [
{ path: "/wuenschen", heading: "Wünschen" },
{ path: "/plan", heading: "Plan" },
{ path: "/einkauf", heading: "Einkaufsliste" },
{ path: "/bons", heading: "Kassenbons" },
];
const SIGNED_OUT = [
{ path: "/anmelden", heading: "Anmelden" },
+97
View File
@@ -0,0 +1,97 @@
// Kassenbons lesen (Konzept, „Bon-Pipeline, lokal“) — rein, ohne Datenbank.
// Das Bildmodell schreibt ab, was auf dem Bon steht; es rechnet nichts. Preise
// und Mengen sind abgeschrieben und werden vor dem Speichern von einem Menschen
// bestätigt. Datum: das Modell nennt es wie gedruckt, gerechnet wird hier.
export const RECEIPT_PROMPT = `You read a supermarket receipt photo. Answer with one JSON object only, no prose:
{"store": string|null, "date": string|null, "total": number|null,
"lines": [{"text": string, "qty": number|null, "unit_price": number|null, "total_price": number|null}]}
Rules: copy each article line's text exactly as printed (abbreviations included). "qty" only if a quantity is printed
(e.g. "2 x 1,29"), else null. Prices in the receipt's currency as numbers (1,29 → 1.29). Skip deposit returns, payment,
change, tax and sum lines. "date" exactly as printed (e.g. "07.11.26"). Never invent a line, a price or a date.`;
export type ReadLine = { text: string; qty: number | null; unitPrice: number | null; totalPrice: number | null };
export type ReadReceipt = { store: string | null; date: string | null; total: number | null; lines: ReadLine[] };
const money = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 && v < 10000 ? Math.round(v * 100) / 100 : null);
/** Antwort des Bildmodells prüfen; ohne lesbare Zeile null. */
export function fromReceiptReply(reply: unknown): ReadReceipt | null {
const r = (reply ?? {}) as Record<string, unknown>;
if (!Array.isArray(r.lines)) return null;
const lines: ReadLine[] = [];
for (const raw of r.lines.slice(0, 200)) {
const l = (raw ?? {}) as Record<string, unknown>;
const text = typeof l.text === "string" ? l.text.replace(/\s+/g, " ").trim().slice(0, 120) : "";
if (!text) continue;
const qty = typeof l.qty === "number" && l.qty > 0 && l.qty < 1000 ? l.qty : null;
lines.push({ text, qty, unitPrice: money(l.unit_price), totalPrice: money(l.total_price) });
}
if (!lines.length) return null;
return {
store: typeof r.store === "string" && r.store.trim() ? r.store.trim().slice(0, 80) : null,
date: parseReceiptDate(typeof r.date === "string" ? r.date : null),
total: money(r.total),
lines,
};
}
/** „07.11.26“, „07.11.2026“, „2026-11-07“ → ISO-Datum; Unplausibles → null. */
export function parseReceiptDate(text: string | null, today = new Date()): string | null {
if (!text) return null;
let y: number, m: number, d: number;
const de = text.match(/(\d{1,2})[./](\d{1,2})[./](\d{2,4})/);
const iso = text.match(/(\d{4})-(\d{2})-(\d{2})/);
if (iso) [y, m, d] = [Number(iso[1]), Number(iso[2]), Number(iso[3])];
else if (de) [d, m, y] = [Number(de[1]), Number(de[2]), Number(de[3])];
else return null;
if (y < 100) y += 2000;
const date = new Date(Date.UTC(y, m - 1, d));
if (date.getUTCMonth() !== m - 1 || date.getUTCDate() !== d) return null;
const age = (today.getTime() - date.getTime()) / 86400000;
if (age < -2 || age > 400) return null; // Zukunft oder älter als ein gutes Jahr: lieber fragen
return date.toISOString().slice(0, 10);
}
/** Schlüssel für gelernte Zuordnungen: klein, ohne Preise und doppelte Leerzeichen. */
export function normalizeLine(text: string): string {
return text
.toLocaleLowerCase("de")
.replace(/-?\d+[.,]\d{2}\s*[a-z]?$/i, "")
.replace(/[^\p{L}\p{N}%.,/ ]+/gu, " ")
.replace(/\s+/g, " ")
.trim();
}
/** Packungsgröße aus dem Bontext („RINDERHACK 500G“ → 500 g, „MILCH 1L“ → 1000 ml, „EIER 10ST“ → 10 Stück). */
export function packFromText(text: string): { qty: number; unit: "g" | "ml" | "piece" } | null {
const m = text.match(/(\d+(?:[.,]\d+)?)\s*(kg|gr?|ml|cl|l|ltr|st|stk|stück|er)\b/i);
if (!m) return null;
const n = Number(m[1]!.replace(",", "."));
const u = m[2]!.toLowerCase();
if (!(n > 0)) return null;
if (u === "kg") return { qty: n * 1000, unit: "g" };
if (u === "g" || u === "gr") return { qty: n, unit: "g" };
if (u === "l" || u === "ltr") return { qty: n * 1000, unit: "ml" };
if (u === "cl") return { qty: n * 10, unit: "ml" };
if (u === "ml") return { qty: n, unit: "ml" };
return { qty: n, unit: "piece" };
}
/** Wörter eines Bontexts oder Produktnamens zum Vergleichen („BARILLA SPAGH N5“ ~ „Barilla Spaghetti Nr. 5“). */
export function tokens(text: string): string[] {
return text
.toLocaleLowerCase("de")
.replace(/nr\.?\s*(\d)/g, "n$1")
.split(/[^\p{L}\p{N}]+/u)
.filter((t) => t.length >= 2);
}
/** Passt eine Bonzeile zu einem Produkt? Jedes Wort der Zeile muss den Anfang eines Produktworts treffen (Abkürzungen). */
export function matchesProduct(line: string, product: string): boolean {
const ls = tokens(line).filter((t) => !/^\d+(g|kg|ml|l|st)?$/.test(t));
const ps = tokens(product);
if (ls.length < 2) return false;
const hits = ls.filter((l) => ps.some((p) => p.startsWith(l) || l.startsWith(p)));
return hits.length >= 2 && hits.length / ls.length >= 0.6;
}
+290
View File
@@ -0,0 +1,290 @@
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 } 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 { fromReceiptReply, matchesProduct, normalizeLine, packFromText, RECEIPT_PROMPT, tokens } 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" | 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();
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) {
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 < 3 order by created_at limit 1)
returning id, photo_path`,
)
).rows[0] as { id: string; photo_path: string } | undefined,
);
if (!next) return;
await readOne(householdId, next.id, next.photo_path, ai, locale);
}
} finally {
running.delete(householdId);
}
}
async function readOne(householdId: string, id: string, photo: string, ai: NonNullable<Awaited<ReturnType<typeof aiFor>>>, locale: string) {
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 = fromReceiptReply(
await askJson(ai, "vision", RECEIPT_PROMPT, [
{ type: "text", text: "Read this receipt." },
{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${jpg.toString("base64")}` } },
]),
);
} catch (error) {
if (error instanceof AiUnavailable || error instanceof AiNotConfigured) return fail("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)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
[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],
);
}
await c.query(
`update receipts set status = 'review', error = null, 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],
);
});
}
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;
};
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()).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
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 };
}
export type Decision = { lineId: string; ingredientId: string | null; packQty: number | null; packUnit: "g" | "ml" | "piece" | null };
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()).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");
const unit = d.ingredientId ? units.get(d.ingredientId) : null;
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, confirmed = true where id = $1", [
d.lineId,
d.ingredientId,
pack,
pack ? unit : null,
]);
if (!d.ingredientId) continue;
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],
);
if (pack && line.total) {
const amount = (line.qty ?? 1) * pack;
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, line.total / amount, 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;
}
+5
View File
@@ -18,6 +18,11 @@ export function useKeyboardSafeNav<T extends HTMLElement>() {
const ref = useRef<T>(null);
const [typing, setTyping] = useState(false);
// Für feste Knopfleisten (globals.css, --nav-space): beim Tippen ohne Abstand zur Navigation.
useEffect(() => {
document.documentElement.toggleAttribute("data-typing", typing);
}, [typing]);
useEffect(() => {
const vv = window.visualViewport;
// Abstand zwischen Unterkante des sichtbaren Bereichs und der des Layouts.
+50
View File
@@ -737,5 +737,55 @@
"saved": "Gespeichert.",
"save": "Speichern"
}
},
"receipts": {
"eyebrow": "Einkauf",
"title": "Kassenbons",
"intro": "Bon fotografieren, weiter einkaufen. Lunch liest ihn auf der Box und merkt sich die Preise, sobald du bestätigst. Das Foto wird danach gelöscht.",
"noAi": "Zum Lesen braucht Lunch ein Bildmodell (beim Olares Router dabei). Bons warten so lange.",
"scan": "Bon fotografieren",
"uploading": "Lädt hoch …",
"uploadError": "Das Foto ließ sich nicht lesen. Nimm ein JPEG, PNG oder HEIC bis 15 MB.",
"retry": "Noch einmal lesen",
"empty": "Noch keine Bons.",
"unnamed": "Bon",
"status": {
"queued": "wartet auf die AI",
"processing": "wird gelesen …",
"review": "{n, plural, one {# Zeile} other {# Zeilen}} zu bestätigen",
"done": "bestätigt",
"failed": "nicht lesbar"
},
"errors": {
"unavailable": "AI gerade nicht erreichbar",
"unreadable": "keine Zeilen erkannt",
"photo": "Foto nicht lesbar"
},
"reviewTitle": "Bon prüfen",
"doneTitle": "Bon",
"read": "Gelesen: {store}",
"store": "Laden",
"noStore": "unbekannt",
"date": "Datum",
"otherLine": "Sonstiges – zählt zu keinem Gericht",
"assign": "Zutat zuordnen",
"other": "Sonstiges",
"pack": "Packung in {unit}",
"source": {
"alias": "so schon einmal bestätigt",
"product": "euer Produkt: {product}",
"search": "Vorschlag aus der Suche",
"ai": "Vorschlag der AI – bitte prüfen"
},
"units": {
"g": "g",
"ml": "ml",
"piece": "Stück"
},
"confirm": "Übernehmen",
"delete": "Bon löschen",
"saveError": "Das hat nicht geklappt.",
"doneText": "Die Preise sind im Preisgedächtnis, die Zuordnungen gelernt. Das Foto ist gelöscht.",
"link": "Bon fotografieren"
}
}
+50
View File
@@ -737,5 +737,55 @@
"saved": "Saved.",
"save": "Save"
}
},
"receipts": {
"eyebrow": "Shopping",
"title": "Receipts",
"intro": "Snap the receipt and carry on. Lunch reads it on your box and remembers the prices once you confirm. The photo is deleted afterwards.",
"noAi": "Reading needs an image model (included with the Olares Router). Receipts wait until then.",
"scan": "Photograph receipt",
"uploading": "Uploading …",
"uploadError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"retry": "Read again",
"empty": "No receipts yet.",
"unnamed": "Receipt",
"status": {
"queued": "waiting for the AI",
"processing": "being read …",
"review": "{n, plural, one {# line} other {# lines}} to confirm",
"done": "confirmed",
"failed": "unreadable"
},
"errors": {
"unavailable": "AI not reachable right now",
"unreadable": "no lines found",
"photo": "photo unreadable"
},
"reviewTitle": "Check receipt",
"doneTitle": "Receipt",
"read": "Read: {store}",
"store": "Store",
"noStore": "unknown",
"date": "Date",
"otherLine": "Other – not part of any dish",
"assign": "Assign ingredient",
"other": "Other",
"pack": "Pack in {unit}",
"source": {
"alias": "confirmed like this before",
"product": "your product: {product}",
"search": "suggested by search",
"ai": "suggested by the AI – please check"
},
"units": {
"g": "g",
"ml": "ml",
"piece": "pieces"
},
"confirm": "Confirm",
"delete": "Delete receipt",
"saveError": "That didn't work.",
"doneText": "Prices are in the price memory and the matches are learned. The photo is deleted.",
"link": "Photograph receipt"
}
}
+50
View File
@@ -737,5 +737,55 @@
"saved": "Guardado.",
"save": "Guardar"
}
},
"receipts": {
"eyebrow": "Compra",
"title": "Tickets",
"intro": "Fotografía el ticket y sigue. Lunch lo lee en tu box y recuerda los precios cuando confirmas. Después se borra la foto.",
"noAi": "Para leer hace falta un modelo de imagen (incluido en el Router de Olares). Los tickets esperan hasta entonces.",
"scan": "Fotografiar ticket",
"uploading": "Subiendo …",
"uploadError": "No se pudo leer la foto. Usa JPEG, PNG o HEIC hasta 15 MB.",
"retry": "Leer de nuevo",
"empty": "Aún no hay tickets.",
"unnamed": "Ticket",
"status": {
"queued": "esperando a la AI",
"processing": "leyendo …",
"review": "{n, plural, one {# línea} other {# líneas}} por confirmar",
"done": "confirmado",
"failed": "ilegible"
},
"errors": {
"unavailable": "AI no disponible ahora",
"unreadable": "no se encontraron líneas",
"photo": "foto ilegible"
},
"reviewTitle": "Revisar ticket",
"doneTitle": "Ticket",
"read": "Leído: {store}",
"store": "Tienda",
"noStore": "desconocida",
"date": "Fecha",
"otherLine": "Otros – no cuenta para ningún plato",
"assign": "Asignar ingrediente",
"other": "Otros",
"pack": "Paquete en {unit}",
"source": {
"alias": "confirmado así antes",
"product": "tu producto: {product}",
"search": "sugerido por la búsqueda",
"ai": "sugerido por la AI – revísalo"
},
"units": {
"g": "g",
"ml": "ml",
"piece": "unidades"
},
"confirm": "Confirmar",
"delete": "Borrar ticket",
"saveError": "No ha funcionado.",
"doneText": "Los precios están guardados y las asignaciones aprendidas. La foto se ha borrado.",
"link": "Fotografiar ticket"
}
}
+50
View File
@@ -737,5 +737,55 @@
"saved": "Enregistré.",
"save": "Enregistrer"
}
},
"receipts": {
"eyebrow": "Courses",
"title": "Tickets de caisse",
"intro": "Photographie le ticket et continue. Lunch le lit sur ta box et retient les prix dès que tu confirmes. La photo est ensuite supprimée.",
"noAi": "La lecture nécessite un modèle d'image (inclus dans le Router d'Olares). Les tickets attendent jusque-là.",
"scan": "Photographier le ticket",
"uploading": "Envoi …",
"uploadError": "Photo illisible. Utilise un JPEG, PNG ou HEIC jusqu'à 15 Mo.",
"retry": "Relire",
"empty": "Pas encore de tickets.",
"unnamed": "Ticket",
"status": {
"queued": "en attente de l'AI",
"processing": "lecture en cours …",
"review": "{n, plural, one {# ligne} other {# lignes}} à confirmer",
"done": "confirmé",
"failed": "illisible"
},
"errors": {
"unavailable": "AI injoignable pour l'instant",
"unreadable": "aucune ligne trouvée",
"photo": "photo illisible"
},
"reviewTitle": "Vérifier le ticket",
"doneTitle": "Ticket",
"read": "Lu : {store}",
"store": "Magasin",
"noStore": "inconnu",
"date": "Date",
"otherLine": "Divers – ne compte pour aucun plat",
"assign": "Associer un ingrédient",
"other": "Divers",
"pack": "Paquet en {unit}",
"source": {
"alias": "déjà confirmé ainsi",
"product": "ton produit : {product}",
"search": "proposé par la recherche",
"ai": "proposé par l'AI – à vérifier"
},
"units": {
"g": "g",
"ml": "ml",
"piece": "pièces"
},
"confirm": "Valider",
"delete": "Supprimer le ticket",
"saveError": "Ça n'a pas marché.",
"doneText": "Les prix sont mémorisés et les associations apprises. La photo est supprimée.",
"link": "Photographier le ticket"
}
}
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: lunch
description: Was gibt's? — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste
type: application
version: 26.11.24 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.24" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
version: 26.11.26 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.26" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: What's cooking?
description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.24
version: 26.11.26
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.24'
versionName: '26.11.26'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -0,0 +1,5 @@
# Receipts fill the price memory
v26.11.25: Photograph your receipts (several at once) under Shopping › Photograph receipt and carry on — Lunch reads store, date and every line on your box. Lines are matched to ingredients: first what you confirmed before, then the products you set on your dishes ("BARILLA SPAGH N5" → Barilla Spaghetti No. 5), then search, then an AI suggestion. You check, adjust pack sizes or mark lines as Other, and confirm. Prices then flow into dish costs (the confidence dots fill up), each line is learned so it is never asked again, and the photo is deleted. Without an image model, receipts wait instead of going anywhere else.
## Deutsch
v26.11.25: Kassenbons unter Einkauf › Bon fotografieren aufnehmen (auch mehrere) und weitermachen — Lunch liest Laden, Datum und jede Zeile auf der Box. Die Zeilen werden Zutaten zugeordnet: erst was ihr schon bestätigt habt, dann die Produkte an euren Gerichten („BARILLA SPAGH N5“ → Barilla Spaghetti Nr. 5), dann die Suche, dann ein Vorschlag der AI. Ihr prüft, passt Packungen an oder legt Zeilen unter Sonstiges ab und übernehmt. Danach gehen die Preise in die Kosten der Gerichte (die Punkte füllen sich), jede Zeile ist gelernt und wird nie wieder gefragt, und das Foto ist gelöscht. Ohne Bildmodell warten Bons, statt anderswo hinzugehen.
+5
View File
@@ -0,0 +1,5 @@
# Buttons stay at the bottom
v26.11.26: On the iPhone, buttons pinned to the bottom (Save, Confirm, Approve plan, Next in cooking mode) floated in the middle of the screen while typing, a bar's height above the keyboard. They now sit right on the keyboard while you type and above the bottom bar afterwards.
## Deutsch
v26.11.26: Am iPhone schwebten die unten festen Knöpfe (Speichern, Übernehmen, Plan freigeben, Weiter im Kochmodus) beim Tippen mitten im Bild, eine Leistenhöhe über der Tastatur. Jetzt sitzen sie beim Tippen direkt über der Tastatur und danach wieder über der unteren Leiste.
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { fromReceiptReply, matchesProduct, normalizeLine, packFromText, parseReceiptDate } from "@/lib/receipt-read";
describe("reading receipts", () => {
const today = new Date("2026-11-08T12:00:00Z");
it("parses the printed date and refuses implausible ones", () => {
expect(parseReceiptDate("07.11.26", today)).toBe("2026-11-07");
expect(parseReceiptDate("Datum 07.11.2026 18:32", today)).toBe("2026-11-07");
expect(parseReceiptDate("31.02.26", today)).toBeNull();
expect(parseReceiptDate("07.11.24", today)).toBeNull(); // zu alt
expect(parseReceiptDate(null, today)).toBeNull();
});
it("takes only sane lines and prices from the model", () => {
const r = fromReceiptReply({
store: "REWE Markt",
date: "07.11.26",
total: 12.47,
lines: [
{ text: " RINDERHACK 500G ", qty: null, unit_price: null, total_price: 4.99 },
{ text: "", total_price: 1 },
{ text: "BANANEN", qty: 2, unit_price: 0.35, total_price: -3 },
],
});
expect(r?.lines).toEqual([
{ text: "RINDERHACK 500G", qty: null, unitPrice: null, totalPrice: 4.99 },
{ text: "BANANEN", qty: 2, unitPrice: 0.35, totalPrice: null },
]);
expect(r?.store).toBe("REWE Markt");
expect(fromReceiptReply({ lines: [] })).toBeNull();
expect(fromReceiptReply("kaputt")).toBeNull();
});
it("reads pack sizes and normalizes lines for learning", () => {
expect(packFromText("RINDERHACK 500G")).toEqual({ qty: 500, unit: "g" });
expect(packFromText("H-MILCH 1,5% 1L")).toEqual({ qty: 1000, unit: "ml" });
expect(packFromText("EIER BODENH. 10ST")).toEqual({ qty: 10, unit: "piece" });
expect(packFromText("BANANEN")).toBeNull();
expect(normalizeLine("RINDERHACK 500G 4,99 A")).toBe("rinderhack 500g");
});
it("recognises a product from its abbreviation on the receipt", () => {
expect(matchesProduct("BARILLA SPAGH N5 500G", "Barilla Spaghetti Nr. 5")).toBe(true);
expect(matchesProduct("BARILLA PENNE 500G", "Barilla Spaghetti Nr. 5")).toBe(false);
expect(matchesProduct("SPAGHETTI", "Barilla Spaghetti Nr. 5")).toBe(false);
});
});
+105
View File
@@ -0,0 +1,105 @@
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { seedHousehold } from "./fixture";
vi.mock("server-only", () => ({}));
// Kassenbons gegen die Testdatenbank (lib/receipts.ts): Vorschläge aus Produkt,
// Suche und Gelerntem; Bestätigen schreibt Preise, lernt die Zeile, löscht das Foto.
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)("receipts", () => {
const client = new pg.Client({ connectionString: url });
const h = randomUUID();
let kai = "";
let store = "";
let spaghetti = "";
let receipts: typeof import("@/lib/receipts");
let db: typeof import("@/lib/db");
let dir = "";
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
async function receiptWith(lines: [string, number | null][]): Promise<string> {
const id = randomUUID();
const photo = `${h}/${id}.jpg`;
await mkdir(path.join(dir, "bons", h), { recursive: true });
await writeFile(path.join(dir, "bons", photo), "x");
await as(async (c) => {
await c.query("insert into receipts (id, household_id, photo_path, status, store_id, created_by) values ($1, $2, $3, 'review', $4, $5)", [id, h, photo, store, kai]);
const s = await receipts.suggestLines(c, lines.map((l) => l[0]), "de", null);
for (const [i, [text, price]] of lines.entries()) {
await c.query(
`insert into receipt_lines (household_id, receipt_id, position, raw_text, total_price, ingredient_id, pack_qty, pack_unit, match_source)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[h, id, i + 1, text, price, s[i]!.ingredientId, s[i]!.pack?.qty ?? null, s[i]!.pack?.unit ?? null, s[i]!.source],
);
}
});
return id;
}
beforeAll(async () => {
process.env.DATABASE_URL = url;
dir = await mkdtemp(path.join(os.tmpdir(), "lunch-bons-"));
process.env.APP_DATA_DIR = dir;
await client.connect();
spaghetti = (await client.query("select id from ingredients where key = 'spaghetti'")).rows[0].id;
const potato = (await client.query("select id from ingredients where key = 'potato'")).rows[0].id;
kai = (await seedHousehold(client, h, potato)).member;
receipts = await import("@/lib/receipts");
db = await import("@/lib/db");
await as(async (c) => {
store = (await c.query("select id from stores where is_default")).rows[0].id;
const dish = (await c.query("insert into dishes (household_id, title) values ($1, 'Pasta') returning id", [h])).rows[0].id;
await c.query(
"insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, product) values ($1, $2, $3, 100, 'g', 'Barilla Spaghetti Nr. 5')",
[h, dish, spaghetti],
);
});
});
afterAll(async () => {
await db.pool.end();
await client.end();
});
it("suggests from the dish's product, from search, and leaves household goods open", async () => {
const s = await as((c) => receipts.suggestLines(c, ["BARILLA SPAGH N5 500G", "ZWIEBELN", "KLOPAPIER 8ST"], "de", null));
expect(s[0]).toMatchObject({ ingredientId: spaghetti, source: "product", product: "Barilla Spaghetti Nr. 5", pack: { qty: 500, unit: "g" } });
expect(s[1]).toMatchObject({ source: "search" });
expect(s[2]).toMatchObject({ ingredientId: null, source: null });
});
it("confirming writes the price per gram, learns the line and deletes the photo", async () => {
const id = await receiptWith([["BARILLA SPAGH N5 500G", 1.79], ["KLOPAPIER 8ST", 3.49]]);
const r = await as((c) => receipts.getReceipt(c, id, "de"));
const photo = path.join(dir, "bons", h, `${id}.jpg`);
expect(existsSync(photo)).toBe(true);
await as((c) =>
receipts.confirmReceipt(c, h, id, {
storeId: store,
purchasedAt: "2026-11-07",
decisions: r!.lines.map((l: import("@/lib/receipts").ReviewLine) => ({ lineId: l.id, ingredientId: l.ingredientId, packQty: l.packQty, packUnit: l.packUnit as "g" | null })),
}),
);
const price = await as(async (c) => (await c.query("select price_per_unit::float as p, source, observed_at::date::text as d from price_points where receipt_id = $1", [id])).rows);
expect(price).toEqual([{ p: expect.closeTo(1.79 / 500, 6), source: "receipt", d: "2026-11-07" }]);
expect(existsSync(photo)).toBe(false);
expect(await as(async (c) => (await c.query("select status from receipts where id = $1", [id])).rows[0].status)).toBe("done");
// Dieselbe Zeile fragt die App nie wieder: gelernt.
const again = await as((c) => receipts.suggestLines(c, ["BARILLA SPAGH N5 500G"], "de", null));
expect(again[0]).toMatchObject({ ingredientId: spaghetti, source: "alias", pack: { qty: 500, unit: "g" } });
});
it("refuses to confirm twice", async () => {
const id = await receiptWith([["ZWIEBELN", 0.99]]);
const confirm = () => as((c) => receipts.confirmReceipt(c, h, id, { storeId: null, purchasedAt: null, decisions: [] }));
await confirm();
await expect(confirm()).rejects.toBeInstanceOf(receipts.ReceiptRefused);
});
});