Compare commits

...
2 Commits
Author SHA1 Message Date
kai ffee757b81 26.11.33: Bons – nicht zum Kochen, Preis je 100 g (#34)
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m5s
release / tag and release (push) Successful in 3s
2026-11-07 12:08:36 +00:00
kai 241a836028 26.11.32: Leiste unten rutscht beim Scrollen nicht mehr mit (#33)
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m2s
release / tag and release (push) Successful in 3s
2026-11-07 10:48:54 +00:00
22 changed files with 639 additions and 121 deletions

No files matched your search

+16 -4
View File
@@ -7,7 +7,7 @@
> **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.31 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> **Status:** 26.11.33 — 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
@@ -394,6 +394,12 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
`tidyLines`: Mengen-/Gewichtszeile über dem Artikel gehört zu ihm, Pfand und Leergut
fallen weg. Nach drei Fehlversuchen `failed`, nicht ewig `queued`. Das Foto des Bons
bleibt außerhalb des Repos; Tests bauen die Zeilen nach.
- Seit 26.11.33: „Nicht zum Kochen“ = Alias **ohne** Zutat (`ingredient_aliases.ingredient_id`
null, Migration 0020) → `suggestLines` liefert `source: "skip"`, die Zeile steht
zugeklappt am Ende (`receipt_lines.skipped`). Gelernt wird nur, was jemand selbst
weggewischt hat (`Decision.skip`); Unerkanntes bleibt offen. Preis immer über
`unitPrice` (`lib/receipt-read.ts`): Zeilenpreis ÷ (Anzahl × Packung); ohne Packung kein
Preis — die Prüfung warnt. Gewogene Zeilen (`weighed`) bekommen 1000 vorgefüllt.
## Führung (seit 26.11.27)
@@ -445,9 +451,15 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
- iOS lässt eine feste Leiste nach dem Schließen der Tastatur oft dort stehen, wo die
Tastatur endete (Kai, 7.11.2026). `components/app-nav.tsx` nutzt deshalb
`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.
`useKeyboardSafeNav` (`lib/use-keyboard-nav.ts`): beim Tippen `hidden`, danach ein
Scroll auf der Stelle und **nur eine Sekunde lang** `translateY` um die Lücke
(`keyboardGap`, ab 40 px), nur in der Web-App vom Home-Bildschirm; die erste Berührung
beendet es. Eine neue feste Leiste unten nutzt denselben Haken.
- **Nie beim Scrollen verschieben** (26.11.32): Bis 26.11.31 hing die Korrektur an jedem
`visualViewport`-Ereignis, und die Leiste rutschte beim Scrollen mit, wenn Safaris
Adressleiste ein- und ausfuhr. Kein Listener auf `scroll` des sichtbaren Bereichs.
`e2e/leiste.spec.ts` täuscht den iOS-Sichtbereich vor und wacht darüber (fällt mit dem
alten Haken durch).
- 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.
+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.31
version: 26.11.33
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.31'
versionName: '26.11.33'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+1
View File
@@ -18,6 +18,7 @@ const body = z.object({
ingredientId: uuid.nullable(),
packQty: z.number().positive().max(100000).nullable(),
packUnit: z.enum(["g", "ml", "piece"]).nullable(),
skip: z.boolean().optional(),
}),
)
.max(200),
+177 -64
View File
@@ -1,14 +1,15 @@
"use client";
import { Check, Trash2 } from "lucide-react";
import { AlertTriangle, Check, ChevronRight, Trash2, Undo2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { useRef, 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 { pricePer, unitPrice } from "@/lib/receipt-read";
import { parseNumber } from "@/lib/units";
import { cn } from "@/lib/utils";
@@ -24,15 +25,23 @@ type Line = {
packUnit: string | null;
source: string | null;
product: string | null;
weighed: boolean;
skipped: boolean;
};
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 };
// open: Zutatenwahl offen, obwohl noch keine Zutat gewählt ist.
type Row = { line: Line; ingredient: Picked | null; pack: string; skip: boolean; open: boolean };
const fmt = (n: number | null) => (n === null ? "" : String(Math.round(n * 1000) / 1000).replace(".", ","));
/** Vorgabe für die Packung: Stück 1, gewogene Ware 1000 (Preis je kg vom Bon). */
const packFor = (line: Line, unit: Picked["unit"] | undefined) => (unit === "piece" ? "1" : line.weighed && unit ? "1000" : "");
// 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.
// Bestätigung“). Oben, was zum Kochen zählt: Zutat und Packung prüfen, darunter der
// Preis je 100 g, den Lunch sich merkt. Was nicht zum Kochen zählt (Toastbrot,
// Klopapier), wischt man nach links oder tippt „Nicht zum Kochen“ — es wandert
// zugeklappt ans Ende, Lunch merkt es sich für den nächsten Bon (26.11.33).
export function ReceiptReview({ receipt }: { receipt: Receipt }) {
const t = useTranslations("receipts");
const locale = useLocale();
@@ -40,18 +49,32 @@ export function ReceiptReview({ receipt }: { receipt: Receipt }) {
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,
})),
receipt.lines.map((l) => {
const unit = (l.ingredientUnit ?? undefined) as Picked["unit"] | undefined;
return {
line: l,
ingredient: l.ingredientId ? { id: l.ingredientId, name: l.ingredientName ?? "", unit: unit ?? "g" } : null,
pack: l.packQty !== null ? fmt(l.packQty) : packFor(l, unit),
skip: l.skipped,
open: false,
};
}),
);
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)));
const [lastSkipped, setLastSkipped] = useState<string | null>(null);
const touch = useRef<{ id: string; x: number; y: number } | null>(null);
const update = (id: string, patch: Partial<Row>) => setRows((rs) => rs.map((r) => (r.line.id === id ? { ...r, ...patch } : r)));
const skip = (id: string) => {
update(id, { skip: true });
setLastSkipped(id);
};
const unskip = (id: string) => {
update(id, { skip: false });
setLastSkipped(null);
};
async function save() {
setBusy(true);
@@ -64,9 +87,10 @@ export function ReceiptReview({ receipt }: { receipt: Receipt }) {
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,
skip: r.skip,
ingredientId: r.skip ? null : (r.ingredient?.id ?? null),
packQty: r.skip || !r.ingredient || !r.pack.trim() ? null : parseNumber(r.pack),
packUnit: r.skip || !r.ingredient ? null : r.ingredient.unit,
})),
}),
}).catch(() => null);
@@ -83,6 +107,34 @@ export function ReceiptReview({ receipt }: { receipt: Receipt }) {
router.refresh();
}
const cooking = rows.filter((r) => !r.skip);
const skipped = rows.filter((r) => r.skip);
const undoRow = lastSkipped ? rows.find((r) => r.line.id === lastSkipped && r.skip) : undefined;
/** „= 2,20 € je 100 g · 800 g für 17,58 €“ oder die Warnung ohne Packung. */
function priceNote(r: Row) {
if (!r.ingredient || r.line.totalPrice === null) return null;
const pack = r.pack.trim() ? parseNumber(r.pack) : null;
const per = unitPrice(r.line.totalPrice, r.line.qty, pack);
if (per === null) {
return (
<p className="flex items-start gap-2 text-sm">
<AlertTriangle aria-hidden className="mt-0.5 size-4 shrink-0 text-accent" />
{t("noPackWarning")}
</p>
);
}
const shown = pricePer(per, r.ingredient.unit);
const amount = (r.line.qty && r.line.qty > 0 ? r.line.qty : 1) * (pack ?? 0);
const many = (r.line.qty ?? 1) !== 1;
return (
<p className="text-sm text-muted-foreground" data-testid="unit-price">
{t("perPrice", { price: money.format(shown.price), per: t(`per.${shown.per}`) })}
{many ? ` · ${t("perDetail", { amount: fmt(amount), unit: t(`units.${r.ingredient.unit}`), total: money.format(r.line.totalPrice) })}` : ""}
</p>
);
}
return (
<div className="flex flex-col gap-5">
<div className="grid grid-cols-2 gap-3">
@@ -109,61 +161,122 @@ export function ReceiptReview({ receipt }: { receipt: Receipt }) {
</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}
{!done && cooking.length ? <p className="text-sm text-muted-foreground">{t("swipeHint")}</p> : null}
<ul className="flex flex-col gap-3" aria-label={t("forCooking")}>
{cooking.map((r) => {
const id = r.line.id;
const many = r.line.qty !== null && Number.isInteger(r.line.qty) && r.line.qty > 1;
return (
<li
key={id}
className={cn("flex flex-col gap-2 rounded-2xl p-3", r.ingredient ? "bg-muted" : "border border-border")}
onTouchStart={(e) => {
const p = e.touches[0];
touch.current = p && !done ? { id, x: p.clientX, y: p.clientY } : null;
}}
onTouchEnd={(e) => {
const start = touch.current;
const end = e.changedTouches[0];
touch.current = null;
if (!start || !end || start.id !== id) return;
const dx = end.clientX - start.x;
if (dx < -80 && Math.abs(dx) > Math.abs(end.clientY - start.y)) skip(id); // nach links: nicht zum Kochen
}}
>
<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.weighed ? " kg" : ""} × ` : ""}
{r.line.text}
</span>
<span className="shrink-0 tabular-nums">{r.line.totalPrice !== null ? money.format(r.line.totalPrice) : "–"}</span>
</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>
{!r.ingredient && !r.open ? (
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-sm text-muted-foreground">{t("noIngredient")}</span>
{!done ? (
<Button type="button" variant="ghost" className="ml-auto" onClick={() => update(i, { other: true })}>
{t("other")}
</Button>
<span className="flex gap-1">
<Button type="button" variant="ghost" className="px-3" onClick={() => update(id, { open: true })}>
{t("assign")}
</Button>
<Button type="button" variant="ghost" className="px-3" onClick={() => skip(id)}>
{t("notCooking")}
</Button>
</span>
) : null}
</div>
</>
)}
</li>
))}
) : (
<>
{r.line.source && r.line.source !== "skip" && 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(id, { ingredient: p, pack: packFor(r.line, p.unit) })} />
)}
{r.ingredient ? (
<div className="flex items-end gap-2">
<div className="flex flex-col gap-1">
<Label htmlFor={`pack-${id}`} className="text-sm">
{t(many ? "packEach" : "pack", { unit: t(`units.${r.ingredient.unit}`) })}
</Label>
<Input id={`pack-${id}`} inputMode="decimal" className="w-32" disabled={done} value={r.pack} onChange={(e) => update(id, { pack: e.target.value })} />
</div>
{!done ? (
<Button type="button" variant="ghost" className="ml-auto px-3" onClick={() => skip(id)}>
{t("notCooking")}
</Button>
) : null}
</div>
) : !done ? (
<Button type="button" variant="ghost" className="self-start px-3" onClick={() => skip(id)}>
{t("notCooking")}
</Button>
) : null}
{r.ingredient && r.line.weighed ? <p className="text-xs text-muted-foreground">{t("weighedHint")}</p> : null}
{priceNote(r)}
</>
)}
</li>
);
})}
</ul>
{undoRow ? (
<p role="status" className="flex items-center justify-between gap-2 rounded-xl border border-border py-1 pl-4 pr-1 text-sm">
<span className="min-w-0 truncate">{t("skippedOne", { text: undoRow.line.text })}</span>
<Button type="button" variant="ghost" className="shrink-0 px-3" onClick={() => unskip(undoRow.line.id)}>
<Undo2 aria-hidden />
{t("undo")}
</Button>
</p>
) : null}
{skipped.length ? (
<details className="group rounded-2xl border border-border">
<summary className="flex min-h-12 cursor-pointer list-none items-center justify-between gap-2 px-4 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<span>{t("notCookingGroup", { n: skipped.length })}</span>
<ChevronRight aria-hidden className="size-5 transition-transform group-open:rotate-90" />
</summary>
<ul className="flex flex-col divide-y divide-border border-t border-border">
{skipped.map((r) => (
<li key={r.line.id} className="flex min-h-12 items-center justify-between gap-3 py-1 pl-4 pr-1">
<span className="min-w-0 font-mono text-sm">{r.line.text}</span>
<span className="flex shrink-0 items-center gap-1">
<span className="text-sm tabular-nums">{r.line.totalPrice !== null ? money.format(r.line.totalPrice) : "–"}</span>
{!done ? (
<Button type="button" variant="ghost" className="px-3" aria-label={t("assignLine", { text: r.line.text })} onClick={() => unskip(r.line.id)}>
{t("assignShort")}
</Button>
) : null}
</span>
</li>
))}
</ul>
</details>
) : null}
{error ? <ErrorNotice>{t("saveError")}</ErrorNotice> : null}
{done ? (
<p className="text-sm text-muted-foreground">{t("doneText")}</p>
+14
View File
@@ -0,0 +1,14 @@
-- Bons: „Nicht zum Kochen“ und Gewichtsware (Kai, 7.11.2026, 26.11.33).
-- Ein gelernter Bontext ohne Zutat heißt: Das kaufen wir, aber nicht zum Kochen
-- (Toastbrot, Klopapier). Beim nächsten Bon landet er gleich unten. Gewogene Ware
-- („0,416 kg x 2,79 €/kg“) trägt die Menge in kg; ihr Preis gilt je 1000 g.
alter table ingredient_aliases alter column ingredient_id drop not null;
alter table ingredient_aliases add constraint ingredient_aliases_skip_no_pack
check (ingredient_id is not null or (pack_qty is null and pack_unit is null));
alter table receipt_lines drop constraint if exists receipt_lines_match_source_check;
alter table receipt_lines add constraint receipt_lines_match_source_check
check (match_source in ('alias', 'product', 'search', 'ai', 'skip'));
alter table receipt_lines add column weighed boolean not null default false;
alter table receipt_lines add column skipped boolean not null default false;
+36 -2
View File
@@ -1,4 +1,4 @@
import { expect, test, type Browser, type Page } from "@playwright/test";
import { expect, test, type Locator, type Browser, type Page } from "@playwright/test";
import sharp from "sharp";
// Einkaufsliste am iPhone (Paket 7): Hauptladen, Vorrats-Check, Abhaken,
@@ -142,13 +142,47 @@ test.describe("receipts", () => {
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");
// Preis je 100 g, so wie Lunch ihn sich merkt; ohne Packung eine Warnung.
await expect(pasta.getByTestId("unit-price")).toHaveText("= 0,36 € je 100 g");
await pasta.getByLabel("Packung in g").fill("");
await expect(pasta).toContainText("Ohne Packungsgröße merkt sich Lunch keinen Preis.");
await pasta.getByLabel("Packung in g").fill("500");
// Klopapier gehört zu keinem Gericht: nach links wischen (26.11.33).
const paper = page.getByRole("list", { name: "Zum Kochen" }).locator("li", { hasText: "KLOPAPIER 8ST" });
await expect(paper).toContainText("Keine Zutat erkannt");
await swipeLeft(paper);
await expect(page.getByRole("status")).toContainText("KLOPAPIER 8ST: nicht zum Kochen");
await expect(page.getByRole("list", { name: "Zum Kochen" }).locator("li", { hasText: "KLOPAPIER" })).toHaveCount(0);
await expect(page.getByText("1 weiterer Artikel — nicht zum Kochen")).toBeVisible();
await page.getByRole("button", { name: "Übernehmen" }).click();
await expect(page.getByText("bestätigt")).toBeVisible();
// Der nächste Bon: Klopapier landet gleich unten, die Spaghetti sind gelernt.
await page.locator("input[type=file]").setInputFiles({ name: "bon2.jpg", mimeType: "image/jpeg", buffer: jpg });
await page.getByRole("link", { name: /2 Zeilen zu bestätigen/ }).click({ timeout: 20_000 });
await expect(page.getByRole("list", { name: "Zum Kochen" }).locator("li")).toHaveCount(1);
await expect(page.locator("li", { hasText: "BARILLA SPAGH N5 500G" })).toContainText("so schon einmal bestätigt");
await page.getByText("1 weiterer Artikel — nicht zum Kochen").click();
await page.getByRole("button", { name: "KLOPAPIER 8ST doch einer Zutat zuordnen" }).click();
await expect(page.getByRole("list", { name: "Zum Kochen" }).locator("li")).toHaveCount(2);
await page.getByRole("button", { name: "Bon löschen" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Kassenbons");
// 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");
});
});
/** Nach links wischen wie am Handy (Chromium hat keine Wischgeste). */
async function swipeLeft(target: Locator) {
await target.evaluate((el) => {
const r = el.getBoundingClientRect();
const y = r.top + 20;
const at = (x: number) => new Touch({ identifier: 1, target: el, clientX: x, clientY: y });
el.dispatchEvent(new TouchEvent("touchstart", { bubbles: true, touches: [at(r.right - 20)], changedTouches: [at(r.right - 20)] }));
el.dispatchEvent(new TouchEvent("touchend", { bubbles: true, touches: [], changedTouches: [at(r.left + 20)] }));
});
}
+101
View File
@@ -0,0 +1,101 @@
import { expect, test, type Page } from "@playwright/test";
// Die untere Leiste bleibt unten (26.11.32, Kai: „rutscht beim Scrollen mit nach
// oben“). Chromium fährt keine Adressleiste ein und hat keine Tastatur; deshalb
// täuscht der Test einen iPhone-Sichtbereich vor (visualViewport, Web-App vom
// Home-Bildschirm) und bewegt ihn wie iOS beim Scrollen und nach dem Tippen.
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
const vv = new EventTarget() as EventTarget & Record<string, unknown>;
const w = window as unknown as { __vv: typeof vv; __extra: number; __top: number };
w.__extra = 0;
w.__top = 0;
const props: Record<string, () => number> = {
height: () => window.innerHeight + w.__extra,
width: () => window.innerWidth,
offsetTop: () => w.__top,
offsetLeft: () => 0,
pageTop: () => window.scrollY + w.__top,
pageLeft: () => 0,
scale: () => 1,
};
for (const [k, get] of Object.entries(props))
Object.defineProperty(vv, k, { get });
Object.defineProperty(window, "visualViewport", { get: () => vv, configurable: true });
w.__vv = vv;
const media = window.matchMedia.bind(window);
window.matchMedia = (q: string) =>
q.includes("standalone") ? ({ matches: true, media: q, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent: () => false } as MediaQueryList) : media(q);
});
});
/** iOS bewegt den sichtbaren Bereich: um extra Pixel größer, um top verschoben. */
async function moveViewport(page: Page, extra: number, top = 0) {
await page.evaluate(
({ extra, top }) => {
const w = window as unknown as { __vv: EventTarget; __extra: number; __top: number };
w.__extra = extra;
w.__top = top;
w.__vv.dispatchEvent(new Event("resize"));
w.__vv.dispatchEvent(new Event("scroll"));
},
{ extra, top },
);
}
async function navAtBottom(page: Page) {
const nav = page.getByRole("navigation", { name: "Navigation" });
await expect(nav).toBeVisible();
const { bottom, inner, transform } = await nav.evaluate((el) => ({
bottom: Math.round(el.getBoundingClientRect().bottom),
inner: window.innerHeight,
transform: (el as HTMLElement).style.transform,
}));
expect(transform).toBe("");
expect(bottom).toBe(inner);
}
test("scrolling never moves the bar, even while the address bar comes and goes", async ({ page }) => {
await page.goto("/mehr");
await navAtBottom(page);
const height = await page.evaluate(() => document.documentElement.scrollHeight);
for (const [y, extra, top] of [
[300, 80, 0], // Adressleiste fährt ein
[900, 80, 0],
[height, 120, 40], // Gummiband am Ende
[400, 0, 0], // Adressleiste wieder da
[0, 0, -30], // Gummiband oben
]) {
await page.mouse.wheel(0, y! - (await page.evaluate(() => window.scrollY)));
await moveViewport(page, extra!, top!);
await page.waitForTimeout(50);
await navAtBottom(page);
}
});
test("after typing, a stale gap is bridged briefly and dropped at the first touch", async ({ page }) => {
await page.goto("/mehr");
const field = page.locator("#kid-name");
await field.focus();
await expect(page.getByRole("navigation", { name: "Navigation" })).toBeHidden(); // beim Tippen weg
// iOS lässt das Layout nach dem Schließen der Tastatur 300 px zu kurz stehen.
await moveViewport(page, 300);
await field.blur();
const nav = page.getByRole("navigation", { name: "Navigation" });
await expect(nav).toBeVisible();
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("translateY(300px)");
await page.evaluate(() => window.dispatchEvent(new Event("touchstart")));
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("");
});
test("the bridge ends by itself after a second, and never starts without typing", async ({ page }) => {
await page.goto("/mehr");
const nav = page.getByRole("navigation", { name: "Navigation" });
await moveViewport(page, 300); // ohne Tastatur: nichts tun
await page.waitForTimeout(100);
expect(await nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("");
await page.locator("#kid-name").focus();
await page.locator("#kid-name").blur();
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("translateY(300px)");
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform), { timeout: 3000 }).toBe("");
});
+25 -4
View File
@@ -13,7 +13,8 @@ the next article line — put it into that article's qty and unit_price, never a
Skip deposit lines (Pfand, Pfandwert, Leergut), payment, change, tax and sum lines. "total": the amount to pay.
"date" exactly as printed (e.g. "07.11.26"), null if none is visible. Never invent a line, a price or a date.`;
export type ReadLine = { text: string; qty: number | null; unitPrice: number | null; totalPrice: number | null };
/** weighed: Menge stammt aus einer Gewichtszeile („0,416 kg x 2,79 €/kg“), qty ist dann in kg. */
export type ReadLine = { text: string; qty: number | null; unitPrice: number | null; totalPrice: number | null; weighed?: boolean };
export type ReadReceipt = { store: string | null; date: string | null; total: number | null; lines: ReadLine[]; partial?: boolean };
const money = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 && v < 10000 ? Math.round(v * 100) / 100 : null);
@@ -45,19 +46,23 @@ function rawLine(raw: unknown): ReadLine | null {
/** Zeilen aufräumen: Mengenzeilen zum Artikel darunter, Pfand und Leergut weg. */
export function tidyLines(lines: ReadLine[]): ReadLine[] {
const out: ReadLine[] = [];
let pending: { qty: number; unitPrice: number } | null = null;
let pending: { qty: number; unitPrice: number; weighed: boolean } | null = null;
for (const line of lines) {
const q = line.text.match(QTY_LINE);
if (q) {
const qty = num(q[1]!);
pending = qty > 0 ? { qty, unitPrice: num(q[2]!) } : null; // „-41 x 0,25“ gehört zum Leergut
pending = qty > 0 ? { qty, unitPrice: num(q[2]!), weighed: /kg\s*[x×*]/i.test(line.text) } : null; // „-41 x 0,25“ gehört zum Leergut
continue;
}
if (DEPOSIT.test(line.text)) {
pending = null;
continue;
}
out.push(pending && line.qty === null ? { ...line, qty: pending.qty, unitPrice: line.unitPrice ?? pending.unitPrice } : line);
out.push(
pending && line.qty === null
? { ...line, qty: pending.qty, unitPrice: line.unitPrice ?? pending.unitPrice, ...(pending.weighed ? { weighed: true } : {}) }
: line,
);
pending = null;
}
return out;
@@ -175,3 +180,19 @@ export function matchesProduct(line: string, product: string): boolean {
const hits = ls.filter((l) => ps.some((p) => p.startsWith(l) || l.startsWith(p)));
return hits.length >= 2 && hits.length / ls.length >= 0.6;
}
/**
* Preis je Grundeinheit (g, ml, Stück) einer Bonzeile: Zeilenpreis ÷ (Anzahl × Packung).
* 2 × 400 g Hack für 17,58 € → 0,021975 € je g. Ohne Packung oder Preis: null — dann
* merkt sich Lunch keinen Preis.
*/
export function unitPrice(total: number | null, qty: number | null, pack: number | null): number | null {
if (total === null || !(total > 0) || pack === null || !(pack > 0)) return null;
const amount = (qty && qty > 0 ? qty : 1) * pack;
return amount > 0 ? total / amount : null;
}
/** Zum Anzeigen: je 100 g / 100 ml, bei Stück je Stück. */
export function pricePer(perUnit: number, unit: "g" | "ml" | "piece"): { price: number; per: "100g" | "100ml" | "piece" } {
return unit === "piece" ? { price: perUnit, per: "piece" } : { price: perUnit * 100, per: unit === "g" ? "100g" : "100ml" };
}
+34 -14
View File
@@ -9,7 +9,7 @@ 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 } from "./receipt-read";
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)
@@ -52,7 +52,7 @@ export async function createReceipt(client: PoolClient, householdId: string, mem
return id;
}
type Suggestion = { ingredientId: string | null; source: "alias" | "product" | "search" | "ai" | null; product: string | null; pack: { qty: number; unit: string } | null };
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}]}
@@ -73,7 +73,9 @@ export async function suggestLines(client: PoolClient, lines: string[], locale:
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 });
// 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));
@@ -179,9 +181,14 @@ async function readOne(householdId: string, id: string, photo: string, ai: NonNu
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],
`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(
@@ -216,6 +223,8 @@ export type ReviewLine = {
packUnit: string | null;
source: string | null;
product: string | null;
weighed: boolean;
skipped: boolean;
};
export async function getReceipt(client: PoolClient, id: string, locale: string) {
@@ -231,7 +240,7 @@ export async function getReceipt(client: PoolClient, id: string, locale: string)
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
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],
)
@@ -243,7 +252,8 @@ export async function getReceipt(client: PoolClient, id: string, locale: string)
return { ...receipt, lines, stores };
}
export type Decision = { lineId: string; ingredientId: string | null; packQty: number | null; packUnit: "g" | "ml" | "piece" | null };
/** 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 {}
@@ -265,28 +275,38 @@ export async function confirmReceipt(
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.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, confirmed = true where id = $1", [
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,
]);
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;
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, line.total / amount, unit, when, id],
[householdId, d.ingredientId, input.storeId, perUnit, unit, when, id],
);
}
}
+55 -12
View File
@@ -5,8 +5,28 @@ import { useEffect, useRef, useState } from "react";
// iOS (Web-App vom Home-Bildschirm): Nach dem Schließen der Tastatur bleibt eine
// feste Leiste oft dort stehen, wo die Tastatur endete — mitten im Bild (Kai,
// 7.11.2026). Deshalb: Während getippt wird, ist die Leiste weg; danach richtet sie
// sich am sichtbaren Bereich (visualViewport) aus statt am Layout, das iOS zu kurz
// stehen lässt, und ein Scroll auf der Stelle stößt das Neuvermessen an.
// sich kurz am sichtbaren Bereich (visualViewport) aus.
//
// Nur kurz (26.11.32): Bis 26.11.31 hing die Korrektur an jedem Scroll- und
// Größenereignis des sichtbaren Bereichs. In Safari fährt beim Scrollen die
// Adressleiste ein und aus, iOS meldet das verzögert — die Leiste rutschte mit
// (Kai, 7.11.2026). Jetzt gilt: Beim Scrollen fasst Lunch die Leiste nie an.
// Korrigiert wird nur im Fenster nach dem Schließen der Tastatur, und die erste
// Berührung oder der erste Scroll danach nimmt die Korrektur zurück.
/** Wie lange nach dem Schließen der Tastatur nachgemessen wird. */
export const SETTLE_MS = 1000;
/** Web-App vom Home-Bildschirm? Nur dort trat der Fehler auf; in Safari ist eine Lücke die Adressleiste. */
export const isStandalone = () =>
window.matchMedia?.("(display-mode: standalone)").matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
/** Abstand zwischen Unterkante des sichtbaren Bereichs und der des Layouts; 0, wenn nichts zu tun ist. */
export function keyboardGap(vv: { offsetTop: number; height: number; scale: number }, layoutHeight: number): number {
if (vv.scale > 1.01) return 0; // gezoomt: nicht eingreifen
const gap = Math.round(vv.offsetTop + vv.height - layoutHeight);
return gap > 40 && gap < 800 ? gap : 0; // kleine Lücken sind Adressleiste oder Gummiband, keine Tastatur
}
const EDITABLE =
'input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="range"]):not([type="file"]), textarea, select, [contenteditable=""], [contenteditable="true"]';
@@ -25,38 +45,61 @@ export function useKeyboardSafeNav<T extends HTMLElement>() {
useEffect(() => {
const vv = window.visualViewport;
// Abstand zwischen Unterkante des sichtbaren Bereichs und der des Layouts.
let until = 0; // Ende des Fensters nach dem Schließen der Tastatur
const clear = () => {
until = 0;
if (ref.current) ref.current.style.transform = "";
};
const pin = () => {
const el = ref.current;
if (!el || !vv) return;
const gap = vv.scale > 1.01 ? 0 : Math.round(vv.offsetTop + vv.height - document.documentElement.clientHeight);
el.style.transform = gap > 0 && gap < 800 ? `translateY(${gap}px)` : "";
if (Date.now() > until || !isStandalone()) return clear();
const gap = keyboardGap(vv, document.documentElement.clientHeight);
el.style.transform = gap ? `translateY(${gap}px)` : "";
};
const onFocusIn = (e: FocusEvent) => {
if (isEditable(e.target as Element)) setTyping(true);
if (isEditable(e.target as Element)) {
clear();
setTyping(true);
}
};
const onFocusOut = () => {
// Erst prüfen, wenn der Fokus angekommen ist (Feld → Feld bleibt „tippen“).
setTimeout(() => {
if (isEditable(document.activeElement)) return;
setTyping(false);
window.scrollTo(window.scrollX, window.scrollY);
window.scrollTo(window.scrollX, window.scrollY); // stößt das Neuvermessen an
until = Date.now() + SETTLE_MS;
requestAnimationFrame(pin);
setTimeout(pin, 300); // nach der Animation der Tastatur noch einmal
setTimeout(() => {
if (!until) return;
clear();
// Steht die Leiste ohne Korrektur noch falsch, iOS noch einmal neu messen lassen.
if (vv && isStandalone() && keyboardGap(vv, document.documentElement.clientHeight)) {
window.scrollTo(window.scrollX, window.scrollY + 1);
window.scrollTo(window.scrollX, window.scrollY - 1);
}
}, SETTLE_MS + 50);
}, 50);
};
// Sobald die Person wieder berührt (jeder Scroll am Handy beginnt so) oder am Rad
// dreht, gilt die Lage, die iOS selbst rechnet. Kein „scroll“: Den lösen auch das
// scrollTo oben und iOS beim Schließen der Tastatur aus.
const onUser = () => until && clear();
document.addEventListener("focusin", onFocusIn);
document.addEventListener("focusout", onFocusOut);
vv?.addEventListener("resize", pin);
vv?.addEventListener("scroll", pin);
window.addEventListener("orientationchange", pin);
pin();
window.addEventListener("touchstart", onUser, { passive: true });
window.addEventListener("wheel", onUser, { passive: true });
window.addEventListener("orientationchange", clear);
return () => {
document.removeEventListener("focusin", onFocusIn);
document.removeEventListener("focusout", onFocusOut);
vv?.removeEventListener("resize", pin);
vv?.removeEventListener("scroll", pin);
window.removeEventListener("orientationchange", pin);
window.removeEventListener("touchstart", onUser);
window.removeEventListener("wheel", onUser);
window.removeEventListener("orientationchange", clear);
};
}, []);
+20 -3
View File
@@ -794,9 +794,7 @@
"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",
@@ -814,7 +812,26 @@
"saveError": "Das hat nicht geklappt.",
"doneText": "Die Preise sind im Preisgedächtnis, die Zuordnungen gelernt. Das Foto ist gelöscht.",
"link": "Bon fotografieren",
"partialHint": "Der Bon war lang; die AI hat ihn nur bis zu einer Stelle gelesen. Prüf die Zeilen hier — den Rest fotografierst du als eigenen Bon (nur die untere Hälfte)."
"partialHint": "Der Bon war lang; die AI hat ihn nur bis zu einer Stelle gelesen. Prüf die Zeilen hier — den Rest fotografierst du als eigenen Bon (nur die untere Hälfte).",
"notCooking": "Nicht zum Kochen",
"notCookingGroup": "{n, plural, one {1 weiterer Artikel} other {# weitere Artikel}} — nicht zum Kochen",
"skippedOne": "{text}: nicht zum Kochen",
"undo": "Rückgängig",
"assignShort": "Zuordnen",
"assignLine": "{text} doch einer Zutat zuordnen",
"noIngredient": "Keine Zutat erkannt",
"forCooking": "Zum Kochen",
"swipeHint": "Was nicht zum Kochen gehört, nach links wischen — Lunch merkt es sich für den nächsten Bon.",
"packEach": "Packung je Stück in {unit}",
"perPrice": "= {price} {per}",
"perDetail": "{amount} {unit} für {total}",
"per": {
"100g": "je 100 g",
"100ml": "je 100 ml",
"piece": "je Stück"
},
"noPackWarning": "Ohne Packungsgröße merkt sich Lunch keinen Preis.",
"weighedHint": "Gewogen: 1000 heißt, der Preis gilt je kg wie auf dem Bon."
},
"setup": {
"title": "Los geht's",
+20 -3
View File
@@ -794,9 +794,7 @@
"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",
@@ -814,7 +812,26 @@
"saveError": "That didn't work.",
"doneText": "Prices are in the price memory and the matches are learned. The photo is deleted.",
"link": "Photograph receipt",
"partialHint": "The receipt was long; the AI read it only up to a point. Check the lines here — photograph the rest as a receipt of its own (just the lower half)."
"partialHint": "The receipt was long; the AI read it only up to a point. Check the lines here — photograph the rest as a receipt of its own (just the lower half).",
"notCooking": "Not for cooking",
"notCookingGroup": "{n, plural, one {1 more item} other {# more items}} — not for cooking",
"skippedOne": "{text}: not for cooking",
"undo": "Undo",
"assignShort": "Assign",
"assignLine": "Assign {text} to an ingredient after all",
"noIngredient": "No ingredient recognised",
"forCooking": "For cooking",
"swipeHint": "Swipe left what is not for cooking — Lunch remembers it for the next receipt.",
"packEach": "Pack per item in {unit}",
"perPrice": "= {price} {per}",
"perDetail": "{amount} {unit} for {total}",
"per": {
"100g": "per 100 g",
"100ml": "per 100 ml",
"piece": "per item"
},
"noPackWarning": "Without a pack size Lunch keeps no price.",
"weighedHint": "Weighed: 1000 means the price is per kg as on the receipt."
},
"setup": {
"title": "Getting started",
+20 -3
View File
@@ -794,9 +794,7 @@
"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",
@@ -814,7 +812,26 @@
"saveError": "No ha funcionado.",
"doneText": "Los precios están guardados y las asignaciones aprendidas. La foto se ha borrado.",
"link": "Fotografiar ticket",
"partialHint": "The receipt was long; the AI read it only up to a point. Check the lines here — photograph the rest as a receipt of its own (just the lower half)."
"partialHint": "The receipt was long; the AI read it only up to a point. Check the lines here — photograph the rest as a receipt of its own (just the lower half).",
"notCooking": "Not for cooking",
"notCookingGroup": "{n, plural, one {1 more item} other {# more items}} — not for cooking",
"skippedOne": "{text}: not for cooking",
"undo": "Undo",
"assignShort": "Assign",
"assignLine": "Assign {text} to an ingredient after all",
"noIngredient": "No ingredient recognised",
"forCooking": "For cooking",
"swipeHint": "Swipe left what is not for cooking — Lunch remembers it for the next receipt.",
"packEach": "Pack per item in {unit}",
"perPrice": "= {price} {per}",
"perDetail": "{amount} {unit} for {total}",
"per": {
"100g": "per 100 g",
"100ml": "per 100 ml",
"piece": "per item"
},
"noPackWarning": "Without a pack size Lunch keeps no price.",
"weighedHint": "Weighed: 1000 means the price is per kg as on the receipt."
},
"setup": {
"title": "Primeros pasos",
+20 -3
View File
@@ -794,9 +794,7 @@
"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",
@@ -814,7 +812,26 @@
"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",
"partialHint": "The receipt was long; the AI read it only up to a point. Check the lines here — photograph the rest as a receipt of its own (just the lower half)."
"partialHint": "The receipt was long; the AI read it only up to a point. Check the lines here — photograph the rest as a receipt of its own (just the lower half).",
"notCooking": "Not for cooking",
"notCookingGroup": "{n, plural, one {1 more item} other {# more items}} — not for cooking",
"skippedOne": "{text}: not for cooking",
"undo": "Undo",
"assignShort": "Assign",
"assignLine": "Assign {text} to an ingredient after all",
"noIngredient": "No ingredient recognised",
"forCooking": "For cooking",
"swipeHint": "Swipe left what is not for cooking — Lunch remembers it for the next receipt.",
"packEach": "Pack per item in {unit}",
"perPrice": "= {price} {per}",
"perDetail": "{amount} {unit} for {total}",
"per": {
"100g": "per 100 g",
"100ml": "per 100 ml",
"piece": "per item"
},
"noPackWarning": "Without a pack size Lunch keeps no price.",
"weighedHint": "Weighed: 1000 means the price is per kg as on the receipt."
},
"setup": {
"title": "C'est parti",
+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.31 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.31" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
version: 26.11.33 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.33" # 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.31
version: 26.11.33
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.31'
versionName: '26.11.33'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -0,0 +1,5 @@
# The bottom bar stays down
v26.11.32: The bottom bar no longer slides up while scrolling. The fix for the keyboard (26.11.18) moved the bar on every scroll as the address bar came and went; now Lunch leaves the bar alone while scrolling. Only in the home-screen app, and only for a second after the keyboard closes, it closes a gap the keyboard left behind — the first touch ends that.
## Deutsch
v26.11.32: Die Leiste unten rutscht beim Scrollen nicht mehr mit nach oben. Die Korrektur für die Tastatur (26.11.18) schob die Leiste bei jedem Scrollen nach, während die Adressleiste ein- und ausfuhr; jetzt lässt Lunch die Leiste beim Scrollen in Ruhe. Nur in der Web-App vom Home-Bildschirm und nur eine Sekunde nach dem Schließen der Tastatur schließt sie eine Lücke, die die Tastatur hinterlassen hat — die erste Berührung beendet das.
+5
View File
@@ -0,0 +1,5 @@
# Receipts: not for cooking, price per 100 g
v26.11.33: When checking a receipt, swipe left what is not for cooking (toast, toilet paper) or tap "Not for cooking": the line moves to a folded list at the end, stays part of the receipt, and Lunch remembers it — next time it lands there by itself, and it can be assigned again at any time. Each line now shows the price Lunch keeps, per 100 g, 100 ml or item; for 2 × 400 g it says "800 g for 17.58 €". Without a pack size there is a warning, because then no price is kept. Weighed goods (0.416 kg × 2.79 €/kg) are filled in with 1000 g, so the price per kilo is right.
## Deutsch
v26.11.33: Beim Prüfen eines Bons wischt man nach links, was nicht zum Kochen gehört (Toastbrot, Klopapier), oder tippt „Nicht zum Kochen“: Die Zeile wandert zugeklappt ans Ende, bleibt Teil des Bons, und Lunch merkt sie sich — beim nächsten Bon landet sie gleich dort und lässt sich jederzeit wieder zuordnen. Jede Zeile zeigt jetzt den Preis, den Lunch sich merkt, je 100 g, 100 ml oder Stück; bei 2 × 400 g steht „800 g für 17,58 €“ dabei. Ohne Packungsgröße warnt Lunch, weil dann kein Preis gemerkt wird. Gewogene Ware (0,416 kg × 2,79 €/kg) bekommt 1000 g vorgefüllt, damit der Kilopreis stimmt.
+7 -1
View File
@@ -75,10 +75,16 @@ export default defineConfig({
dependencies: ["kueche"],
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
},
{
name: "leiste",
testMatch: /leiste\.spec\.ts/,
dependencies: ["pwa"],
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
},
{
name: "iphone-hell",
testMatch: /rundgang\.spec\.ts/,
dependencies: ["pwa"],
dependencies: ["leiste"],
use: { ...iphone, colorScheme: "light", storageState: "e2e/.auth/kai.json" },
},
{
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { keyboardGap } from "@/lib/use-keyboard-nav";
// Wann die untere Leiste nach dem Tippen nachgeschoben wird (26.11.32): nur bei einer
// Lücke, wie sie eine eben geschlossene Tastatur hinterlässt — nie für Adressleiste,
// Gummiband oder Zoom.
describe("keyboard gap", () => {
const vv = (height: number, offsetTop = 0, scale = 1) => ({ height, offsetTop, scale });
it("is the stale space a closed keyboard leaves behind", () => {
expect(keyboardGap(vv(852), 520)).toBe(332);
});
it("ignores small gaps from the address bar or a bounce, and negative ones", () => {
expect(keyboardGap(vv(852), 812)).toBe(0);
expect(keyboardGap(vv(780, -30), 812)).toBe(0);
});
it("leaves a zoomed page alone and refuses absurd values", () => {
expect(keyboardGap(vv(852, 0, 2), 520)).toBe(0);
expect(keyboardGap(vv(5000), 520)).toBe(0);
});
});
+18 -2
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { fromReceiptReply, matchesProduct, normalizeLine, packFromText, parseReceiptDate, receiptFromText } from "@/lib/receipt-read";
import { fromReceiptReply, matchesProduct, normalizeLine, packFromText, parseReceiptDate, pricePer, receiptFromText, unitPrice } from "@/lib/receipt-read";
describe("reading receipts", () => {
const today = new Date("2026-11-08T12:00:00Z");
@@ -76,7 +76,7 @@ describe("an Aldi receipt", () => {
{ text: "H-KOCHSAHNE 12%", qty: 3, unitPrice: 0.59, totalPrice: 1.77 },
{ text: "RINDERHACKFLEI. XXL -", qty: 2, unitPrice: 8.79, totalPrice: 17.58 },
{ text: "BIO MÖHREN NL", qty: null, unitPrice: null, totalPrice: 1.69 },
{ text: "MANDARINEN KG-WARE", qty: 0.416, unitPrice: 2.79, totalPrice: 1.16 },
{ text: "MANDARINEN KG-WARE", qty: 0.416, unitPrice: 2.79, totalPrice: 1.16, weighed: true },
]);
expect(r?.total).toBe(96.67);
expect(r?.date).toBeNull(); // auf dem Foto abgeschnitten — dann gilt der Tag des Hochladens
@@ -103,3 +103,19 @@ describe("an Aldi receipt", () => {
expect(receiptFromText("Ich kann den Bon nicht lesen.")).toBeNull();
});
});
describe("price per unit (26.11.33)", () => {
it("divides the line by count times pack", () => {
const hack = unitPrice(17.58, 2, 400)!; // 2 × 400 g
expect(pricePer(hack, "g").price).toBeCloseTo(2.1975, 4);
expect(pricePer(hack, "g").per).toBe("100g");
const mandarins = unitPrice(1.16, 0.416, 1000)!; // gewogen: 0,416 kg, Packung 1000 g
expect(mandarins * 1000).toBeCloseTo(2.79, 2);
expect(pricePer(unitPrice(2.49, null, 1)!, "piece")).toEqual({ price: 2.49, per: "piece" });
});
it("gives no price without a pack size or a price", () => {
expect(unitPrice(17.58, 2, null)).toBeNull();
expect(unitPrice(null, 1, 500)).toBeNull();
expect(unitPrice(1.19, 1, 0)).toBeNull();
});
});
+39
View File
@@ -96,6 +96,45 @@ describe.skipIf(!url)("receipts", () => {
expect(again[0]).toMatchObject({ ingredientId: spaghetti, source: "alias", pack: { qty: 500, unit: "g" } });
});
it("a line swiped away as not for cooking is remembered, and assigning it later overrides that (26.11.33)", async () => {
const id = await receiptWith([["TOASTBROT 500G", 1.19], ["KLOPAPIER 8ST", 3.49]]);
const r = await as((c) => receipts.getReceipt(c, id, "de"));
const [toast, paper] = r!.lines;
await as((c) =>
receipts.confirmReceipt(c, h, id, {
storeId: null,
purchasedAt: null,
decisions: [
{ lineId: toast!.id, ingredientId: null, packQty: null, packUnit: null, skip: true },
{ lineId: paper!.id, ingredientId: null, packQty: null, packUnit: null }, // nur nicht zugeordnet: wird nicht gelernt
],
}),
);
expect(await as(async (c) => (await c.query("select skipped from receipt_lines where id = $1", [toast!.id])).rows[0].skipped)).toBe(true);
const next = await as((c) => receipts.suggestLines(c, ["TOASTBROT 500G", "KLOPAPIER 8ST"], "de", null));
expect(next[0]).toEqual({ ingredientId: null, source: "skip", product: null, pack: null });
expect(next[1]).toMatchObject({ ingredientId: null, source: null });
// Toast Hawaii: doch zugeordnet — die gelernte Zuordnung gilt ab jetzt.
const id2 = await receiptWith([["TOASTBROT 500G", 1.19]]);
const r2 = await as((c) => receipts.getReceipt(c, id2, "de"));
await as((c) =>
receipts.confirmReceipt(c, h, id2, { storeId: null, purchasedAt: null, decisions: [{ lineId: r2!.lines[0]!.id, ingredientId: spaghetti, packQty: 500, packUnit: "g" }] }),
);
const after = await as((c) => receipts.suggestLines(c, ["TOASTBROT 500G"], "de", null));
expect(after[0]).toMatchObject({ ingredientId: spaghetti, source: "alias" });
});
it("two packs of 400 g give the price per gram of all 800 g", async () => {
const id = await receiptWith([["RINDERHACKFLEI. XXL -", 17.58]]);
await as((c) => c.query("update receipt_lines set qty = 2 where receipt_id = $1", [id]));
const r = await as((c) => receipts.getReceipt(c, id, "de"));
await as((c) =>
receipts.confirmReceipt(c, h, id, { storeId: null, purchasedAt: null, decisions: [{ lineId: r!.lines[0]!.id, ingredientId: spaghetti, packQty: 400, packUnit: "g" }] }),
);
const p = await as(async (c) => (await c.query("select price_per_unit::float as p from price_points where receipt_id = $1", [id])).rows[0].p);
expect(p * 100).toBeCloseTo(2.1975, 4); // 2,20 € je 100 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: [] }));