Compare commits

...
2 Commits
Author SHA1 Message Date
kai afdbf34b89 26.11.47: Mein Gericht per Herz (#48)
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m15s
release / tag and release (push) Successful in 3s
2026-11-08 07:32:29 +00:00
kai 5952eda953 26.11.46: Einkaufsliste einsprechen (#47)
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 2s
2026-11-08 05:35:00 +00:00
28 changed files with 501 additions and 66 deletions

No files matched your search

+2 -2
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.45 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> **Status:** 26.11.47 — 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
@@ -22,7 +22,7 @@
> (26.11.39, E-0016), Anmelden per Mail-Link über Resend (26.11.40, E-0017; nur
> anmelden, keine Geräte oder Passkeys aus einer Mail-Sitzung), Leiste bleibt nach der
> Tastatur unten (26.11.41), Icon Kochmütze mit Herz (26.11.42), Fotos aus der Mediathek (26.11.43), gleich große Karten (26.11.44), Runde beenden/löschen/ändern,
> Tage je Gericht von Hand und Kalender-Abo je Haushalt (26.11.45, E-0018). Offen: Kai trägt
> Tage je Gericht von Hand und Kalender-Abo je Haushalt (26.11.45, E-0018), Einkaufsliste einsprechen (26.11.46), Herz für „Mein Gericht“ auf jeder Wunschkarte (26.11.47). Offen: Kai trägt
> den Resend-Schlüssel unter Mehr › Mails verschicken ein und abonniert den Kalender-Link einmal auf dem iPhone.
> **Letzte Aktualisierung:** 8. November 2026
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: foodplanhero
description: Plan. Cook. Smile. 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.45
version: 26.11.47
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.45'
versionName: '26.11.47'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+2 -1
View File
@@ -4,6 +4,7 @@ import { getLocale, getTranslations } from "next-intl/server";
import { ShoppingList } from "@/components/shopping/shopping-list";
import { StorePicker } from "@/components/shopping/store-picker";
import { buttonVariants } from "@/components/ui/button";
import { aiFor } from "@/lib/ai-settings";
import { requireAdult } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { currentRound } from "@/lib/rounds";
@@ -37,7 +38,7 @@ export default async function ShoppingPage() {
</Link>
{data.chains.length ? <StorePicker chains={data.chains} /> : null}
{"items" in data && data.items ? (
<ShoppingList initial={data.items} aisles={data.aisles} me={session.displayName} />
<ShoppingList initial={data.items} aisles={data.aisles} me={session.displayName} canRecord={!!(await aiFor(session.householdId))?.speechModel} />
) : (
<div className="flex flex-col gap-3 rounded-2xl border border-border p-4">
<p>{data.round ? t("notYet") : t("noRound")}</p>
+5 -22
View File
@@ -1,30 +1,13 @@
import { getLocale } from "next-intl/server";
import { AiNotConfigured, AiUnavailable, transcribe } from "@/lib/ai";
import { aiFor } from "@/lib/ai-settings";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json } from "@/lib/auth/http";
import { json } from "@/lib/auth/http";
import { transcribeUpload } from "@/lib/voice";
export const dynamic = "force-dynamic";
const MAX_BYTES = 25 * 1024 * 1024; // rund zehn Minuten Sprache
// Gericht einsprechen, Schritt 1: Aufnahme → Abschrift (Router „default-stt“ oder
// eigenes Sprachmodell). Die Aufnahme wird nicht gespeichert.
// Gericht einsprechen, Schritt 1: Aufnahme → Abschrift.
export async function POST(request: Request) {
const session = await guardWrite(request);
if (isResponse(session)) return session;
const form = await request.formData().catch(() => null);
const audio = form?.get("audio");
if (!(audio instanceof File) || audio.size === 0 || audio.size > MAX_BYTES || !/^(audio|video)\//.test(audio.type)) return fail("audio", 400);
const ai = await aiFor(session.householdId);
if (!ai?.speechModel) return fail("noSpeech", 409);
try {
const ext = audio.type.includes("mp4") || audio.type.includes("m4a") ? "m4a" : audio.type.includes("ogg") ? "ogg" : audio.type.includes("wav") ? "wav" : "webm";
const text = await transcribe(ai, audio, `aufnahme.${ext}`, await getLocale());
if (!text) return fail("empty", 422);
return json({ text });
} catch (error) {
if (error instanceof AiUnavailable || error instanceof AiNotConfigured) return fail("aiUnavailable", 503);
throw error;
}
const result = await transcribeUpload(request, session.householdId);
return result instanceof Response ? result : json(result);
}
+5 -2
View File
@@ -14,10 +14,13 @@ export async function PATCH(request: Request) {
}
export async function POST(request: Request) {
const body = z.object({ label: z.string().trim().min(1).max(80) }).safeParse(await readJson(request));
// Ein Posten getippt, oder mehrere auf einmal nach dem Einsprechen (26.11.46).
const label = z.string().trim().min(1).max(80);
const body = z.union([z.object({ label }), z.object({ labels: z.array(label).min(1).max(20) })]).safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
const labels = "labels" in body.data ? body.data.labels : [body.data.label];
return withShopping(request, async (c, round, session) => {
await addManual(c, session.householdId, round.id, body.data.label);
for (const l of labels) await addManual(c, session.householdId, round.id, l);
return json({ ok: true }, 201);
});
}
+18
View File
@@ -0,0 +1,18 @@
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { json } from "@/lib/auth/http";
import { SHOPPERS } from "@/lib/auth/roles";
import { splitSpoken } from "@/lib/spoken-list";
import { transcribeUpload } from "@/lib/voice";
export const dynamic = "force-dynamic";
// Einkaufsliste einsprechen (Kai, 8.11.2026): Abschrift → einzelne Posten. Kein
// Sprachmodell zerlegt — die Regeln in lib/spoken-list.ts tun es, und auf die
// Liste kommt erst, was die Person geprüft hat.
export async function POST(request: Request) {
const session = await guardWrite(request, [...SHOPPERS]);
if (isResponse(session)) return session;
const result = await transcribeUpload(request, session.householdId);
if (result instanceof Response) return result;
return json({ text: result.text, items: splitSpoken(result.text) });
}
+2 -2
View File
@@ -10,10 +10,10 @@ export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const session = await guardWrite(request, [...WISHERS]);
if (isResponse(session)) return session;
const body = z.object({ dishId: z.string().uuid(), mine: z.boolean() }).safeParse(await readJson(request));
const body = z.object({ dishId: z.string().uuid(), mine: z.boolean(), wish: z.boolean().optional() }).safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
try {
await withHousehold(session.householdId, (c) => setMine(c, session.memberId, body.data.dishId, body.data.mine));
await withHousehold(session.householdId, (c) => setMine(c, session.memberId, body.data.dishId, body.data.mine, body.data.wish ? { wishIn: session.householdId } : {}));
return json({ ok: true });
} catch (error) {
if (error instanceof WishRefused) return fail(error.reason, 409);
+4 -1
View File
@@ -5,6 +5,7 @@ import { useLocale, useTranslations } from "next-intl";
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { VoiceAdd } from "@/components/shopping/voice-add";
import { formatQuantity, type PackKind } from "@/lib/units";
import { cn } from "@/lib/utils";
@@ -46,7 +47,7 @@ function writeQueue(ops: Op[]) {
// Einkaufsliste (Konzept, „Einkaufen“): große Haken, nach Gängen des Hauptladens,
// in Echtzeit bei allen (SSE), und ohne Netz bedienbar — Haken landen in einer
// Warteschlange im Browser und gehen raus, sobald wieder Netz da ist.
export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles: Aisle[]; me: string }) {
export function ShoppingList({ initial, aisles, me, canRecord = false }: { initial: Item[]; aisles: Aisle[]; me: string; canRecord?: boolean }) {
const t = useTranslations("shopping");
const tm = useTranslations("measure");
const locale = useLocale();
@@ -131,6 +132,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
async function send(method: string, url: string, body: object) {
const res = await fetch(url, { method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
if (res?.ok) await reload();
return !!res?.ok;
}
const amount = (i: Item) => {
@@ -212,6 +214,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
<Plus aria-hidden />
</Button>
</form>
{canRecord ? <VoiceAdd onAdd={(labels) => send("POST", "/api/shopping/items", { labels })} /> : null}
{done.length ? (
<section className="flex flex-col gap-1" aria-labelledby="cart-title">
+99
View File
@@ -0,0 +1,99 @@
"use client";
import { Mic, Square, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ErrorNotice } from "@/components/ui/notice";
import { useRecorder } from "@/lib/use-recorder";
const mmss = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
// Einkaufsliste einsprechen (Kai, 8.11.2026, 26.11.46): aufnehmen, Abschrift in
// Posten zerlegen (lib/spoken-list.ts), prüfen und ändern, dann hinzufügen.
export function VoiceAdd({ onAdd }: { onAdd: (labels: string[]) => Promise<boolean> }) {
const t = useTranslations("shopping.voice");
const [busy, setBusy] = useState<"transcribe" | "add" | null>(null);
const [error, setError] = useState<string | null>(null);
const [items, setItems] = useState<string[] | null>(null);
const rec = useRecorder(upload);
async function upload(audio: Blob) {
setBusy("transcribe");
const form = new FormData();
form.append("audio", new File([audio], "aufnahme", { type: audio.type }));
const res = await fetch("/api/shopping/voice", { method: "POST", body: form }).catch(() => null);
const data = await res?.json().catch(() => ({}));
setBusy(null);
if (!res?.ok) return setError(["noSpeech", "aiUnavailable", "empty", "audio"].includes(data?.error) ? data.error : "unknown");
if (!data.items?.length) return setError("empty");
setItems(data.items);
}
async function add() {
const labels = (items ?? []).map((i) => i.trim()).filter(Boolean);
if (!labels.length) return;
setBusy("add");
const ok = await onAdd(labels);
setBusy(null);
if (ok) setItems(null);
else setError("unknown");
}
const filled = (items ?? []).filter((i) => i.trim()).length;
return (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-3">
<Button
type="button"
variant={rec.recording ? "default" : "outline"}
size="icon"
disabled={busy !== null || items !== null}
aria-label={rec.recording ? t("stop") : t("record")}
onClick={async () => {
setError(null);
if (rec.recording) rec.stop();
else if (!(await rec.start())) setError("mic");
}}
>
{rec.recording ? <Square aria-hidden /> : <Mic aria-hidden />}
</Button>
<p aria-live="polite" className="text-sm text-muted-foreground">
{rec.recording ? t("recording", { time: mmss(rec.seconds) }) : busy === "transcribe" ? t("transcribing") : items ? null : t("hint")}
</p>
</div>
{items ? (
<section aria-labelledby="voice-items" className="flex flex-col gap-2 rounded-2xl bg-muted p-4">
<h2 id="voice-items" className="eyebrow">
{t("check")}
</h2>
<ul className="flex flex-col gap-2">
{items.map((item, i) => (
<li key={i} className="flex items-center gap-2">
<Input
aria-label={t("item", { n: i + 1 })}
value={item}
maxLength={80}
onChange={(e) => setItems((all) => all!.map((x, j) => (j === i ? e.target.value : x)))}
/>
<Button type="button" variant="ghost" size="icon" aria-label={t("drop", { name: item })} onClick={() => setItems((all) => all!.filter((_, j) => j !== i))}>
<X aria-hidden />
</Button>
</li>
))}
</ul>
<Button type="button" disabled={busy !== null || !filled} onClick={add}>
{t("add", { n: filled })}
</Button>
<Button type="button" variant="ghost" disabled={busy !== null} onClick={() => setItems(null)}>
{t("discard")}
</Button>
</section>
) : null}
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
</div>
);
}
+24 -10
View File
@@ -97,7 +97,6 @@ export function WishBoard({
const mineOf = (id: string) => (byDish.get(id) ?? []).filter((e) => e.isMine);
const myDish = entries.find((e) => e.memberId === me && e.isMine);
const myDishTitle = myDish ? tiles.find((x) => x.id === myDish.dishId)?.title : null;
const wishedSomething = entries.some((e) => e.memberId === me && !e.isVeto);
const shown = applyFilter(tiles, filter);
async function call(method: string, url: string, body?: object, key = "x") {
@@ -174,12 +173,12 @@ export function WishBoard({
<Heart aria-hidden className="size-4 shrink-0 fill-accent text-accent" />
{t("mineChosen", { title: myDishTitle })}
</p>
) : wishedSomething ? (
) : (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Heart aria-hidden className="size-4 shrink-0" />
{t("mineHint")}
</p>
) : null}
)}
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
{message ? (
@@ -218,12 +217,6 @@ export function WishBoard({
<Check aria-hidden className="size-5" />
</span>
) : null}
{mineNames.length ? (
<span aria-hidden className="absolute right-2 top-2 inline-flex items-center gap-1 rounded-full bg-background/90 px-2 py-1 text-xs font-semibold">
<Heart aria-hidden className={cn("size-4 text-accent", isMyDish && "fill-accent")} />
{isMyDish ? t("mine") : t("mineOf", { names: mineNames.filter((n) => n !== t("you")).join(", ") })}
</span>
) : null}
{favorite ? (
<span aria-hidden className="absolute bottom-2 left-2 inline-flex items-center gap-1 rounded-full bg-background/90 px-2 py-1 text-xs font-semibold">
<Crown aria-hidden className="size-4 text-accent" />
@@ -234,7 +227,12 @@ export function WishBoard({
<span className="flex min-h-11 flex-col gap-0.5 p-3 pr-12">
<span className="font-semibold text-lg leading-snug">{tile.title}</span>
{favorite ? <span className="sr-only">{t("favorite")}</span> : null}
{mineNames.length ? <span className="sr-only">{isMyDish ? t("mine") : t("mineOf", { names: mineNames.join(", ") })}</span> : null}
{mineNames.length ? (
<span className="inline-flex items-center gap-1 text-xs font-semibold">
<Heart aria-hidden className={cn("size-3.5 shrink-0 text-accent", isMyDish && "fill-accent")} />
{isMyDish ? t("mine") : t("mineOf", { names: mineNames.filter((n) => n !== t("you")).join(", ") })}
</span>
) : null}
{names.length ? <span className="text-xs text-muted-foreground">{t("wishedBy", { names: names.join(", ") })}</span> : null}
{vetoList.length && !mineNames.length ? (
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
@@ -244,6 +242,22 @@ export function WishBoard({
) : null}
</span>
</button>
{/* Herz (Kai, 8.11.2026, 26.11.47): ein Tipp macht das Gericht zu meinem —
noch nicht gewünscht, wird es dabei gewünscht (ein Jeton). */}
{own?.isVeto || own?.viaVeto ? null : (
<button
type="button"
aria-pressed={isMyDish}
aria-label={isMyDish ? t("mineUntoggle", { title: tile.title }) : t("mineToggle", { title: tile.title })}
disabled={!!busy}
onClick={() => call("POST", "/api/wishes/mine", isMyDish ? { dishId: tile.id, mine: false } : { dishId: tile.id, mine: true, wish: true }, tile.id)}
className="absolute right-1 top-1 flex size-11 items-center justify-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span className="flex size-9 items-center justify-center rounded-full bg-background/90 shadow-sm">
<Heart aria-hidden className={cn("size-5", isMyDish ? "fill-accent text-accent" : "text-foreground")} />
</span>
</button>
)}
<Button
type="button"
variant="ghost"
+17
View File
@@ -369,3 +369,20 @@ Haushalts, Vorgabe 18:30, eine Stunde.
keine Wünsche.
- Fehlversuche bremsen je Adresse und gemeinsam; gültige Abrufe zählen nicht,
weil Kalender stündlich nachfragen.
**Nachtrag 26.11.46 · Einkaufsliste einsprechen** (Kai, 8.11.2026): Neben dem
Freitextfeld der Einkaufsliste steht ein Mikrofon, sobald ein Sprachmodell
eingerichtet ist (dasselbe wie bei „Gericht einsprechen“). Die Abschrift zerlegt
`lib/spoken-list.ts` ohne Sprachmodell in Posten (Komma, „und“, Satzende;
Füllwörter wie „wir brauchen noch“, „bitte“ fallen weg). Die Person prüft und
ändert die Posten, erst dann kommen sie unter „Sonstiges“ auf die Liste. Die
Aufnahme wird nicht gespeichert.
**Nachtrag 26.11.47 · „Mein Gericht“ per Herz** (Kai, 8.11.2026, „Jede Karte“):
Jede Wunschkarte trägt oben rechts ein Herz — Herz, nicht Stern, weil das Herz
schon „Mein Gericht“ heißt und ein Stern nach Bewertung aussähe. Ein Tipp aufs
leere Herz wünscht das Gericht (ein Jeton) und macht es zu meinem, in einer
Transaktion (`setMine` mit `wishIn`): ohne Jeton entsteht nichts. Gefüllt
nimmt ein Tipp es zurück, der Wunsch bleibt. Eins pro Runde, ein neues ersetzt
das alte. Kein Herz an eigenen Vetos und an Wünschen aus einem Veto. Der Weg
über „…“ bleibt.
+24
View File
@@ -108,6 +108,10 @@ test.describe("receipts", () => {
req.on("data", (c) => (raw += c));
req.on("end", () => {
if (req.headers.authorization !== "Bearer sk-test") return res.writeHead(401).end();
// Einkaufsliste einsprechen (26.11.46): feste Abschrift.
if (req.url === "/v1/audio/transcriptions") {
return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ text: "Wir brauchen noch Hafermilch, zwei Gurken und Spülmittel, bitte." }));
}
if (raw.includes("supermarket receipt photo")) {
return res.writeHead(200, { "content-type": "application/json" }).end(
reply({
@@ -174,6 +178,26 @@ test.describe("receipts", () => {
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");
});
test("the list can be dictated: items are split, checked, then added", async ({ page }) => {
await page.goto("/einkauf");
await page.getByRole("button", { name: "Einkaufsliste einsprechen" }).click();
await expect(page.getByText(/Aufnahme läuft/)).toBeVisible();
await page.waitForTimeout(1200);
await page.getByRole("button", { name: "Aufnahme beenden" }).click();
const check = page.getByRole("region", { name: "Erkannt — bitte prüfen" });
await expect(check.getByRole("textbox")).toHaveCount(3);
await expect(check.getByLabel("Posten 1")).toHaveValue("Hafermilch");
await expect(check.getByLabel("Posten 2")).toHaveValue("Zwei Gurken");
await check.getByRole("button", { name: "Spülmittel weglassen" }).click();
await check.getByLabel("Posten 2").fill("2 Gurken");
await check.getByRole("button", { name: "2 Posten hinzufügen" }).click();
await expect(check).toHaveCount(0);
const other = page.getByRole("region", { name: "Sonstiges" });
await expect(other).toContainText("Hafermilch");
await expect(other).toContainText("2 Gurken");
await expect(page.getByText("Spülmittel")).toHaveCount(0);
});
});
/** Nach links wischen wie am Handy (Chromium hat keine Wischgeste). */
+3 -4
View File
@@ -72,10 +72,9 @@ test("a child wishes, makes a favourite, and has no veto", async () => {
test("a child makes a wish their own dish, sure to be in the plan", async () => {
await tablet.goto("/wuenschen");
await expect(tablet.getByText("Mach einen Wunsch zu deinem Gericht")).toBeVisible();
await tablet.getByRole("button", { name: "Optionen für Spaghetti Bolognese" }).click();
await tablet.getByRole("dialog").getByRole("button", { name: "Als mein Gericht" }).click();
await expect(tablet.getByRole("dialog")).toBeHidden();
await expect(tablet.getByText("Tipp aufs Herz")).toBeVisible();
await tablet.getByRole("button", { name: "Spaghetti Bolognese als mein Gericht" }).click();
await expect(tablet.getByRole("button", { name: "Spaghetti Bolognese nicht mehr mein Gericht" })).toHaveAttribute("aria-pressed", "true");
await expect(tablet.getByText("Dein Gericht: Spaghetti Bolognese — kommt sicher in den Plan.")).toBeVisible();
await expect(tablet.getByRole("button", { name: /^Wunsch zurücknehmen: Spaghetti Bolognese/ })).toContainText("Mein Gericht");
});
+24
View File
@@ -28,6 +28,30 @@ test("tokens, veto and the joker share one line, even on the iPhone", async ({ p
await expect(page.getByText("1 Veto frei")).toBeVisible();
});
test("the heart makes a dish my dish in one tap, and takes it back (26.11.47)", async ({ page }) => {
await page.goto("/wuenschen");
await expect(page.getByText("Tipp aufs Herz")).toBeVisible();
await page.getByRole("button", { name: "Linseneintopf als mein Gericht" }).click();
const heart = page.getByRole("button", { name: "Linseneintopf nicht mehr mein Gericht" });
await expect(heart).toHaveAttribute("aria-pressed", "true");
await expect(page.getByRole("button", { name: /^Wunsch zurücknehmen: Linseneintopf/ })).toHaveAttribute("aria-pressed", "true");
await expect(page.getByText("1 Jeton frei")).toBeVisible();
await expect(page.getByText("Dein Gericht: Linseneintopf — kommt sicher in den Plan.")).toBeVisible();
// Zurück: das Herz ist leer, der Wunsch bleibt.
await heart.click();
await expect(page.getByRole("button", { name: "Linseneintopf als mein Gericht" })).toHaveAttribute("aria-pressed", "false");
await expect(page.getByText("1 Jeton frei")).toBeVisible();
// Der Weg über das Blatt geht weiter.
await page.getByRole("button", { name: "Optionen für Linseneintopf" }).click();
await page.getByRole("dialog").getByRole("button", { name: "Als mein Gericht" }).click();
await expect(page.getByRole("dialog")).toBeHidden();
await expect(page.getByRole("button", { name: "Linseneintopf nicht mehr mein Gericht" })).toHaveAttribute("aria-pressed", "true");
await page.getByRole("button", { name: "Linseneintopf nicht mehr mein Gericht" }).click();
await expect(page.getByRole("button", { name: "Linseneintopf als mein Gericht" })).toBeVisible();
await page.getByRole("button", { name: /^Wunsch zurücknehmen: Linseneintopf/ }).click();
await expect(page.getByText("2 Jetons frei")).toBeVisible();
});
test("each tap spends a token, and the server says when they are gone", async ({ page }) => {
await page.goto("/");
await page.getByRole("link", { name: "Wünschen" }).click();
+28
View File
@@ -0,0 +1,28 @@
// Einkaufsliste einsprechen (26.11.46): Abschrift → Posten, ohne Sprachmodell.
// „Milch, zwei Packungen Eier und Brot, bitte“ → Milch · zwei Packungen Eier · Brot.
// Was falsch getrennt ist („Salz und Pfeffer“), korrigiert die Person vor dem Hinzufügen.
const SEPARATORS = /[,;\n]+|\.\s+|\s+(?:und dann|und|sowie|außerdem|dann|and then|and|then|et|y)\s+/giu;
// Füllwörter am Anfang oder Ende eines Postens.
const LEADING =
/^(?:(?:ich|wir)\s+(?:brauche|brauchen|hätte gern|hätten gern|möchte|möchten)|brauchen wir|bitte|noch|auch|außerdem|schreib(?:e)?(?:\s+auf)?|setz(?:e)?|kauf(?:e|en)?|wir haben kein(?:e|en)?|es fehlt|es fehlen|(?:we|i)\s+need|please|also|add|buy|get)\s+/iu;
const TRAILING = /\s+(?:bitte|noch|kaufen|einkaufen|auf die liste|mitbringen|please|too|as well)$/iu;
export function splitSpoken(text: string): string[] {
const out: string[] = [];
for (const raw of text.split(SEPARATORS)) {
let item = raw.trim().replace(/[.!?…]+$/u, "").trim();
for (let i = 0; i < 3; i++) {
const before = item;
item = item.replace(LEADING, "").replace(TRAILING, "").trim();
if (item === before) break;
}
if (!item || /^(?:bitte|danke|das wär'?s|das ist alles|fertig|(?:ich|wir) brauche[n]?|please|thanks|that's it)$/iu.test(item)) continue;
item = item.charAt(0).toLocaleUpperCase("de") + item.slice(1);
if (item.length > 80) item = item.slice(0, 80).trim();
if (!out.some((o) => o.toLocaleLowerCase("de") === item.toLocaleLowerCase("de"))) out.push(item);
if (out.length >= 20) break;
}
return out;
}
+48
View File
@@ -0,0 +1,48 @@
"use client";
import { useEffect, useRef, useState } from "react";
// Aufnahme im Browser (MediaRecorder): iPhone liefert audio/mp4, andere webm.
// Nach „stop“ geht die Aufnahme an `onDone`; Mikrofon wird sofort freigegeben.
export function useRecorder(onDone: (audio: Blob) => void) {
const [recording, setRecording] = useState(false);
const [seconds, setSeconds] = useState(0);
const recorder = useRef<MediaRecorder | null>(null);
const chunks = useRef<Blob[]>([]);
const done = useRef(onDone);
done.current = onDone;
useEffect(() => {
if (!recording) return;
const tick = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(tick);
}, [recording]);
async function start(): Promise<boolean> {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const type = ["audio/mp4", "audio/webm;codecs=opus", "audio/webm"].find((x) => MediaRecorder.isTypeSupported?.(x));
const rec = new MediaRecorder(stream, type ? { mimeType: type } : undefined);
chunks.current = [];
rec.ondataavailable = (e) => e.data.size && chunks.current.push(e.data);
rec.onstop = () => {
stream.getTracks().forEach((track) => track.stop());
done.current(new Blob(chunks.current, { type: rec.mimeType || "audio/webm" }));
};
rec.start(1000);
recorder.current = rec;
setSeconds(0);
setRecording(true);
return true;
} catch {
return false;
}
}
function stop() {
setRecording(false);
recorder.current?.stop();
}
return { recording, seconds, start, stop };
}
+29
View File
@@ -0,0 +1,29 @@
import "server-only";
import { getLocale } from "next-intl/server";
import { AiNotConfigured, AiUnavailable, transcribe } from "@/lib/ai";
import { aiFor } from "@/lib/ai-settings";
import { fail } from "@/lib/auth/http";
const MAX_BYTES = 25 * 1024 * 1024; // rund zehn Minuten Sprache
/**
* Aufnahme aus dem Formular (Feld „audio“) → Abschrift über den Router
* („default-stt“) oder das eigene Sprachmodell. Die Aufnahme wird nicht gespeichert.
* Gemeinsam für „Gericht einsprechen“ (26.11.24) und die Einkaufsliste (26.11.46).
*/
export async function transcribeUpload(request: Request, householdId: string): Promise<{ text: string } | Response> {
const form = await request.formData().catch(() => null);
const audio = form?.get("audio");
if (!(audio instanceof File) || audio.size === 0 || audio.size > MAX_BYTES || !/^(audio|video)\//.test(audio.type)) return fail("audio", 400);
const ai = await aiFor(householdId);
if (!ai?.speechModel) return fail("noSpeech", 409);
try {
const ext = audio.type.includes("mp4") || audio.type.includes("m4a") ? "m4a" : audio.type.includes("ogg") ? "ogg" : audio.type.includes("wav") ? "wav" : "webm";
const text = await transcribe(ai, audio, `aufnahme.${ext}`, await getLocale());
if (!text) return fail("empty", 422);
return { text };
} catch (error) {
if (error instanceof AiUnavailable || error instanceof AiNotConfigured) return fail("aiUnavailable", 503);
throw error;
}
}
+14 -4
View File
@@ -139,7 +139,9 @@ export async function lastMine(client: PoolClient, roundId: string): Promise<{ m
}
/** Einen eigenen Wunsch zu „Mein Gericht“ machen (ein anderes verliert es) oder es zurücknehmen. */
export async function setMine(client: PoolClient, memberId: string, dishId: string, on: boolean): Promise<void> {
// Mit `wishIn` (26.11.47, Herz auf der Karte) wünscht ein Tipp das Gericht zuerst
// (ein Jeton) — in derselben Transaktion, also ganz oder gar nicht.
export async function setMine(client: PoolClient, memberId: string, dishId: string, on: boolean, opts: { wishIn?: string } = {}): Promise<void> {
await client.query("select pg_advisory_xact_lock(hashtext('wish:' || $1))", [memberId]);
const round = (await client.query("select id from rounds where status = 'open' order by created_at desc limit 1")).rows[0];
if (!round) throw new WishRefused("noRound");
@@ -147,9 +149,17 @@ export async function setMine(client: PoolClient, memberId: string, dishId: stri
await client.query("update wishes set is_mine = false where round_id = $1 and member_id = $2 and dish_id = $3", [round.id, memberId, dishId]);
return;
}
const own = (
await client.query("select id from wishes where round_id = $1 and member_id = $2 and dish_id = $3 and not is_veto and veto_id is null", [round.id, memberId, dishId])
).rows[0];
const ownWish = () =>
client.query("select id from wishes where round_id = $1 and member_id = $2 and dish_id = $3 and not is_veto and veto_id is null", [round.id, memberId, dishId]);
let own = (await ownWish()).rows[0];
if (!own && opts.wishIn) {
// Ein eigenes Veto oder ein Wunsch aus einem Veto wird nicht still umgedeutet.
const other = await client.query("select 1 from wishes where round_id = $1 and member_id = $2 and dish_id = $3", [round.id, memberId, dishId]);
if (other.rowCount) throw new WishRefused("notWished");
if ((await lastMine(client, round.id)).some((m) => m.memberId === memberId && m.dishId === dishId && m.served)) throw new WishRefused("repeat");
await addWish(client, opts.wishIn, memberId, dishId);
own = (await ownWish()).rows[0];
}
if (!own) throw new WishRefused("notWished");
if ((await lastMine(client, round.id)).some((m) => m.memberId === memberId && m.dishId === dishId && m.served)) throw new WishRefused("repeat");
await client.query("update wishes set is_mine = false where round_id = $1 and member_id = $2 and is_mine", [round.id, memberId]);
+25 -3
View File
@@ -651,12 +651,14 @@
"mineOf": "Gericht von {names}",
"mineSet": "Als mein Gericht",
"mineUnset": "Nicht mehr mein Gericht",
"mineHint": "Mach einen Wunsch zu deinem Gericht: Das kommt sicher in den Plan, kein Veto streicht es.",
"mineHint": "Tipp aufs Herz: Dein Gericht kommt sicher in den Plan, kein Veto streicht es.",
"mineChosen": "Dein Gericht: {title} — kommt sicher in den Plan.",
"mineExplain": "Eins pro Runde. Kein Veto streicht es, und der Plan setzt es zuerst.",
"protected": "Geschützt: Das ist das Gericht von jemandem. Dagegen gibt es kein Veto.",
"vetoCount": "{n, plural, one {1 Veto} other {# Vetos}}",
"jokerShort": "Neues"
"jokerShort": "Neues",
"mineToggle": "{title} als mein Gericht",
"mineUntoggle": "{title} nicht mehr mein Gericht"
},
"kids": {
"title": "Wer bist du?",
@@ -781,7 +783,27 @@
"add": "Hinzufügen",
"remove": "{name} entfernen",
"offline": "{n, plural, =0 {Kein Netz. Die Liste bleibt bedienbar.} one {Kein Netz: 1 Haken wird nachgeholt.} other {Kein Netz: # Haken werden nachgeholt.}}",
"packOf": "{count} {word} à {size}"
"packOf": "{count} {word} à {size}",
"voice": {
"record": "Einkaufsliste einsprechen",
"stop": "Aufnahme beenden",
"recording": "Aufnahme läuft · {time}",
"transcribing": "Wird abgeschrieben …",
"hint": "Einsprechen, z. B. „Milch, Eier und Brot“",
"check": "Erkannt — bitte prüfen",
"item": "Posten {n}",
"drop": "{name} weglassen",
"add": "{n, plural, one {# Posten hinzufügen} other {# Posten hinzufügen}}",
"discard": "Verwerfen",
"errors": {
"mic": "Das Mikrofon ist nicht freigegeben. Erlaube es in den Einstellungen des Browsers.",
"noSpeech": "Für Sprache ist noch kein Modell eingerichtet (Mehr › AI).",
"aiUnavailable": "Die Abschrift ist gerade nicht erreichbar. Bitte versuch es gleich noch einmal.",
"empty": "Da war nichts zu verstehen. Bitte noch einmal.",
"audio": "Die Aufnahme ging nicht durch. Bitte noch einmal.",
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal."
}
}
},
"cooking": {
"eyebrow": "Kochen",
+25 -3
View File
@@ -651,12 +651,14 @@
"mineOf": "{names}'s dish",
"mineSet": "Make it my dish",
"mineUnset": "No longer my dish",
"mineHint": "Make one wish your dish: it is sure to be in the plan, and no veto removes it.",
"mineHint": "Tap the heart: your dish is sure to make the plan, no veto can strike it.",
"mineChosen": "Your dish: {title} — sure to be in the plan.",
"mineExplain": "One per round. No veto removes it, and the plan puts it first.",
"protected": "Protected: this is someone's dish. There is no veto against it.",
"vetoCount": "{n, plural, one {1 veto} other {# vetoes}}",
"jokerShort": "Something new"
"jokerShort": "Something new",
"mineToggle": "{title} as my dish",
"mineUntoggle": "{title} no longer my dish"
},
"kids": {
"title": "Who are you?",
@@ -781,7 +783,27 @@
"add": "Add",
"remove": "Remove {name}",
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}",
"packOf": "{count} {word} of {size}"
"packOf": "{count} {word} of {size}",
"voice": {
"record": "Dictate to the shopping list",
"stop": "Stop recording",
"recording": "Recording · {time}",
"transcribing": "Transcribing …",
"hint": "Say it, e.g. “milk, eggs and toilet paper”",
"check": "Recognised — please check",
"item": "Item {n}",
"drop": "Leave out {name}",
"add": "{n, plural, one {Add # item} other {Add # items}}",
"discard": "Discard",
"errors": {
"mic": "The microphone isn’t allowed. Allow it in your browser settings.",
"noSpeech": "No speech model is set up yet (More › AI).",
"aiUnavailable": "Transcription isn’t reachable right now. Please try again shortly.",
"empty": "Nothing could be understood. Please try again.",
"audio": "The recording didn’t come through. Please try again.",
"unknown": "That didn’t work. Please try again."
}
}
},
"cooking": {
"eyebrow": "Cooking",
+25 -3
View File
@@ -651,12 +651,14 @@
"mineOf": "{names}'s dish",
"mineSet": "Make it my dish",
"mineUnset": "No longer my dish",
"mineHint": "Make one wish your dish: it is sure to be in the plan, and no veto removes it.",
"mineHint": "Toca el corazón: tu plato entra seguro en el plan, ningún veto lo quita.",
"mineChosen": "Your dish: {title} — sure to be in the plan.",
"mineExplain": "One per round. No veto removes it, and the plan puts it first.",
"protected": "Protected: this is someone's dish. There is no veto against it.",
"vetoCount": "{n, plural, one {1 veto} other {# vetoes}}",
"jokerShort": "Something new"
"jokerShort": "Something new",
"mineToggle": "{title} como mi plato",
"mineUntoggle": "{title} ya no es mi plato"
},
"kids": {
"title": "Who are you?",
@@ -781,7 +783,27 @@
"add": "Add",
"remove": "Remove {name}",
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}",
"packOf": "{count} {word} de {size}"
"packOf": "{count} {word} de {size}",
"voice": {
"record": "Dictar la lista de la compra",
"stop": "Detener grabación",
"recording": "Grabando · {time}",
"transcribing": "Transcribiendo …",
"hint": "Dilo, p. ej. «leche, huevos y papel higiénico»",
"check": "Reconocido — revísalo",
"item": "Artículo {n}",
"drop": "Quitar {name}",
"add": "{n, plural, one {Añadir # artículo} other {Añadir # artículos}}",
"discard": "Descartar",
"errors": {
"mic": "El micrófono no está permitido. Permítelo en los ajustes del navegador.",
"noSpeech": "Aún no hay modelo de voz (Más › AI).",
"aiUnavailable": "La transcripción no está disponible ahora. Inténtalo en un momento.",
"empty": "No se entendió nada. Inténtalo de nuevo.",
"audio": "La grabación no llegó. Inténtalo de nuevo.",
"unknown": "No ha funcionado. Inténtalo de nuevo."
}
}
},
"cooking": {
"eyebrow": "Cooking",
+25 -3
View File
@@ -651,12 +651,14 @@
"mineOf": "{names}'s dish",
"mineSet": "Make it my dish",
"mineUnset": "No longer my dish",
"mineHint": "Make one wish your dish: it is sure to be in the plan, and no veto removes it.",
"mineHint": "Touche le cœur : ton plat entre à coup sûr dans le plan, aucun veto ne le retire.",
"mineChosen": "Your dish: {title} — sure to be in the plan.",
"mineExplain": "One per round. No veto removes it, and the plan puts it first.",
"protected": "Protected: this is someone's dish. There is no veto against it.",
"vetoCount": "{n, plural, one {1 veto} other {# vetoes}}",
"jokerShort": "Something new"
"jokerShort": "Something new",
"mineToggle": "{title} comme mon plat",
"mineUntoggle": "{title} n’est plus mon plat"
},
"kids": {
"title": "Who are you?",
@@ -781,7 +783,27 @@
"add": "Add",
"remove": "Remove {name}",
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}",
"packOf": "{count} {word} de {size}"
"packOf": "{count} {word} de {size}",
"voice": {
"record": "Dicter la liste de courses",
"stop": "Arrêter l’enregistrement",
"recording": "Enregistrement · {time}",
"transcribing": "Transcription …",
"hint": "Dis-le, p. ex. « lait, œufs et papier toilette »",
"check": "Reconnu — vérifie",
"item": "Article {n}",
"drop": "Retirer {name}",
"add": "{n, plural, one {Ajouter # article} other {Ajouter # articles}}",
"discard": "Abandonner",
"errors": {
"mic": "Le micro n’est pas autorisé. Autorise-le dans les réglages du navigateur.",
"noSpeech": "Aucun modèle vocal n’est configuré (Plus › AI).",
"aiUnavailable": "La transcription n’est pas joignable. Réessaie dans un instant.",
"empty": "Rien n’a été compris. Réessaie.",
"audio": "L’enregistrement n’est pas passé. Réessaie.",
"unknown": "Cela n’a pas marché. Réessaie."
}
}
},
"cooking": {
"eyebrow": "Cooking",
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: lunch
description: foodplanhero (Plan. Cook. Smile.) — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste
type: application
version: 26.11.45 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.45" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
version: 26.11.47 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.47" # 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: foodplanhero
description: Plan. Cook. Smile. 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.45
version: 26.11.47
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.45'
versionName: '26.11.47'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -0,0 +1,5 @@
# Dictate the shopping list
v26.11.46: The shopping list has a microphone next to the free-text field. Say what is missing, for example "milk, two cucumbers and washing-up liquid": the app splits it into items, you check and change them, then they go on the list. It uses the same speech model as dictating a dish; the recording is not stored.
## Deutsch
v26.11.46: Die Einkaufsliste hat neben dem Freitextfeld ein Mikrofon. Sag, was fehlt, etwa „Milch, zwei Gurken und Spülmittel“: Die App teilt es in Posten auf, du prüfst und änderst sie, dann kommen sie auf die Liste. Es nutzt dasselbe Sprachmodell wie „Gericht einsprechen“; die Aufnahme wird nicht gespeichert.
+5
View File
@@ -0,0 +1,5 @@
# My dish with one tap on the heart
v26.11.47: Every dish card under Wishes now has a heart in the top corner. One tap makes the dish your dish — it is wished at the same time if it was not yet (one token) and is then sure to make the plan, no veto can strike it. A filled heart shows your dish; tap again to take it back, the wish stays. One per round; a new one replaces the old.
## Deutsch
v26.11.47: Jede Gerichtskarte unter „Wünschen“ hat jetzt oben ein Herz. Ein Tipp macht das Gericht zu deinem Gericht — war es noch nicht gewünscht, wird es dabei gewünscht (ein Jeton), und es kommt sicher in den Plan, kein Veto streicht es. Ein gefülltes Herz zeigt dein Gericht; nochmal tippen nimmt es zurück, der Wunsch bleibt. Eins pro Runde; ein neues ersetzt das alte.
+17
View File
@@ -62,6 +62,23 @@ describe.skipIf(!url)("my dish", () => {
expect((await entries()).filter((e) => e.isMine).map((e) => e.dishId)).toEqual([d.Pommes]);
});
it("the heart wishes and makes it my dish in one step, all or nothing (26.11.47)", async () => {
const before = (await as((c) => wishes.budget(c, roundId, lea))).tokensLeft;
await as((c) => wishes.setMine(c, lea, d.Nudeln!, true, { wishIn: h }));
expect((await entries()).find((e) => e.memberId === lea && e.dishId === d.Nudeln)).toMatchObject({ isMine: true, isVeto: false });
expect((await as((c) => wishes.budget(c, roundId, lea))).tokensLeft).toBe(before - 1);
// Zurück: nicht mehr mein Gericht, der Wunsch bleibt.
await as((c) => wishes.setMine(c, lea, d.Nudeln!, false));
expect((await entries()).find((e) => e.memberId === lea && e.dishId === d.Nudeln)).toMatchObject({ isMine: false });
await as((c) => wishes.removeWish(c, lea, d.Nudeln!));
// Ohne Jeton: nichts entsteht.
for (const x of [d.Suppe!, d.Pommes!, d.Nudeln!]) await as((c) => wishes.addWish(c, h, lea, x));
expect((await as((c) => wishes.budget(c, roundId, lea))).tokensLeft).toBe(0);
await expect(as((c) => wishes.setMine(c, lea, d.Pizza!, true, { wishIn: h }))).rejects.toMatchObject({ reason: "noTokens" });
expect((await entries()).some((e) => e.memberId === lea && e.dishId === d.Pizza)).toBe(false);
for (const x of [d.Suppe!, d.Pommes!, d.Nudeln!]) await as((c) => wishes.removeWish(c, lea, x));
});
it("last round's own dish that made it into the plan cannot be chosen again", async () => {
await as((c) => wishes.addWish(c, h, ben, d.Pizza!));
await expect(as((c) => wishes.setMine(c, ben, d.Pizza!, true))).rejects.toMatchObject({ reason: "repeat" });
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { splitSpoken } from "@/lib/spoken-list";
describe("spoken shopping list", () => {
it("splits on commas and 'und' and drops fillers", () => {
expect(splitSpoken("Wir brauchen noch Milch, zwei Packungen Eier und Brot, bitte.")).toEqual(["Milch", "Zwei Packungen Eier", "Brot"]);
});
it("handles sentences and 'außerdem'", () => {
expect(splitSpoken("Klopapier. Außerdem Spülmittel und dann Bananen kaufen. Das wär's.")).toEqual(["Klopapier", "Spülmittel", "Bananen"]);
});
it("keeps what was said, once", () => {
expect(splitSpoken("Butter, butter und 500 Gramm Hack")).toEqual(["Butter", "500 Gramm Hack"]);
});
it("works in English", () => {
expect(splitSpoken("We need apples, oat milk and then coffee please")).toEqual(["Apples", "Oat milk", "Coffee"]);
});
it("gives nothing for nothing", () => {
expect(splitSpoken("Danke.")).toEqual([]);
});
});