Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e41fcc4a73 | ||
|
|
db404a3029 | ||
|
|
0692914666 |
No files matched your search
@@ -7,10 +7,11 @@
|
||||
> **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.6 (Gerichte 4a) — Arbeitspakete 1 und 2 fertig: Anmeldung mit Passkeys,
|
||||
> Datenmodell (24 Tabellen, E-0007/E-0008), Test mit zwei Haushalten, Sicherung nach
|
||||
> `/app/data`. Als Nächstes Arbeitspaket 3, Seed (`docs/PROJEKTSTART.md`).
|
||||
> **Letzte Aktualisierung:** 6. November 2026
|
||||
> **Status:** 26.11.14 — 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. Offen sind V2 (Preise, Bons, Kosten im Plan) und der Magic Link.
|
||||
> **Letzte Aktualisierung:** 7. November 2026
|
||||
|
||||
Diese Datei ist das Gedächtnis jeder Sitzung. Entscheidungen stehen in
|
||||
`docs/entscheidungen.md` und gelten vor dem Konzept. Bei Unsicherheit: stoppen
|
||||
@@ -181,6 +182,15 @@ Migration ein — Zutaten mit fester Kennung aus dem Schlüssel, nie gelöscht;
|
||||
Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
|
||||
übernimmt Kopien (`lib/starter.ts`, `lib/stores.ts`).
|
||||
|
||||
## Zutatennamen bei Mengen
|
||||
|
||||
- Stück-Zutaten haben im Seed beide Formen je Sprache (`forms: {de: {one, other}}`,
|
||||
Spalte `ingredients.forms`, Migration 0008): „1 Zwiebel“, „½ Zitrone“, „3
|
||||
Knoblauchzehen“. Gewählt wird nur über `lib/ingredient-name.ts` (`labelFor`,
|
||||
`ingredientLabel`; Einzahl bis einschließlich 1). Gewicht und Volumen behalten den
|
||||
Listennamen. Eine neue Stück-Zutat braucht beide Formen in allen vier Sprachen —
|
||||
`tests/ingredient-name.test.ts` wacht.
|
||||
|
||||
## Gerichte (Arbeitspaket 4)
|
||||
|
||||
- Seiten unter `app/(app)/gerichte/`: Pool (Kacheln, „Ausprobieren“), Hinzufügen,
|
||||
@@ -250,6 +260,32 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
|
||||
- Der Rundgang misst Überlauf gegen die Gerätebreite: Ein mobiles Layout-Viewport
|
||||
wächst mit überstehendem Inhalt mit (`innerWidth` sah den Fehler nicht).
|
||||
|
||||
## Kochen und Bewerten (Arbeitspaket 8)
|
||||
|
||||
- Kochmodus `/kochen/[slot]` (`components/cooking/cooking-mode.tsx`): Mise en place
|
||||
als Checkliste in der Portionszahl des Slots, dann Schritte groß, mit Timer (aus
|
||||
`dish_steps.timer_seconds`, sonst aus dem Text: `lib/timer.ts`, „30 Minuten
|
||||
köcheln“). Timer laufen beim Blättern weiter, gerechnet gegen die Uhr. Screen Wake
|
||||
Lock, Wischen, Pfeiltasten; im Querformat zwei Spalten. Kinder lesen mit, „Fertig“
|
||||
drücken nur Erwachsene.
|
||||
- `lib/cooking.ts`: Fertig setzt `cooked_at` (und den Koch, falls offen); ist der
|
||||
letzte Slot gekocht, ist die Runde `done`. Bewerten (Daumen + ein Satz, ersetzt die
|
||||
eigene Bewertung) und Dankeschön (einmal je Person, nie an sich selbst) auf „Heute“
|
||||
für Gekochtes der letzten drei Tage; der Koch sieht Dankeschöns, Daumen und Sätze.
|
||||
- Bewertungen fließen über `dish_popularity` in den nächsten Vorschlag.
|
||||
|
||||
## Web-App (Arbeitspaket 9)
|
||||
|
||||
- Manifest (`app/manifest.ts`) mit `id`, Sprache, Kurzbefehlen (Wünschen, Plan,
|
||||
Einkauf) und maskierbarem Symbol. Service Worker aus `app/sw.ts` (Serwist): Seiten
|
||||
zuerst aus dem Netz, sonst aus dem Cache; was nie offen war, zeigt `/offline`
|
||||
(vorab gespeichert, `additionalPrecacheEntries` in `next.config.ts`).
|
||||
- **Abmelden leert die Caches** (`lib/clear-caches.ts`, auch „Wechseln“ am
|
||||
Kindergerät): Gespeicherte Seiten gehören der Person, die geht.
|
||||
- Installationshinweis (`components/install-hint.tsx`): `beforeinstallprompt` wo es
|
||||
ihn gibt, am iPhone der Weg über „Teilen → Zum Home-Bildschirm“; auf „Heute“
|
||||
wegtippbar, unter „Mehr“ bleibend; installiert erscheint er nicht.
|
||||
|
||||
## Kinderkonten (Arbeitspaket 5b)
|
||||
|
||||
- **Gerät + PIN** (Kai 6.11.2026), nicht Haushaltscode + PIN: Lunch ist öffentlich
|
||||
|
||||
+2
-2
@@ -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.12
|
||||
version: 26.11.15
|
||||
categories:
|
||||
- Applications
|
||||
|
||||
@@ -61,7 +61,7 @@ permission:
|
||||
appData: true
|
||||
|
||||
spec:
|
||||
versionName: '26.11.12'
|
||||
versionName: '26.11.15'
|
||||
|
||||
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
promoteImage:
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
import { CookingMode } from "@/components/cooking/cooking-mode";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { cookingSlot } from "@/lib/cooking";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Kochmodus. Kinder dürfen mitlesen (Konzept, „Kindermodus“), abschließen nur Erwachsene.
|
||||
export default async function CookingPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) notFound();
|
||||
const session = await requireSession();
|
||||
if (session.role === "guest") redirect("/");
|
||||
const t = await getTranslations("cooking");
|
||||
const slot = await withHousehold(session.householdId, async (c) => cookingSlot(c, id, await getLocale()));
|
||||
if (!slot) notFound();
|
||||
return (
|
||||
<main className="mx-auto flex max-w-md flex-col gap-4 px-4 py-6 landscape:max-w-4xl">
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="eyebrow">{slot.cookName ? t("eyebrowCook", { name: slot.cookName }) : t("eyebrow")}</p>
|
||||
<h1 className="text-4xl leading-tight">{slot.dish.title}</h1>
|
||||
</header>
|
||||
{slot.cookedAt ? (
|
||||
<p className="rounded-2xl border border-border p-4">{t("alreadyCooked")}</p>
|
||||
) : (
|
||||
<CookingMode
|
||||
slotId={slot.id}
|
||||
title={slot.dish.title}
|
||||
portions={slot.portions}
|
||||
ingredients={slot.dish.ingredients}
|
||||
steps={slot.dish.steps}
|
||||
canFinish={session.role === "admin" || session.role === "member"}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { LanguageSelect, SignOutButton } from "@/components/more/account-actions
|
||||
import { RemoveButton } from "@/components/more/remove-button";
|
||||
import { requireAdult } from "@/lib/auth/session";
|
||||
import { KidDevices, KidsAdmin } from "@/components/more/kids-admin";
|
||||
import { InstallHint } from "@/components/install-hint";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { isLocale } from "@/lib/locale";
|
||||
|
||||
@@ -124,6 +125,7 @@ export default async function MorePage() {
|
||||
<LanguageSelect current={isLocale(locale) ? locale : "de"} />
|
||||
</Section>
|
||||
|
||||
<InstallHint />
|
||||
<SignOutButton />
|
||||
</main>
|
||||
);
|
||||
|
||||
+25
-1
@@ -1,4 +1,7 @@
|
||||
import { CookingPot, Crown } from "lucide-react";
|
||||
import { ChefHat, CookingPot, Crown, Heart } from "lucide-react";
|
||||
import { RateCard } from "@/components/cooking/rate-card";
|
||||
import { InstallHint } from "@/components/install-hint";
|
||||
import { pendingRatings, thanksForCook } from "@/lib/cooking";
|
||||
import Link from "next/link";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
import { DishPhoto } from "@/components/dishes/dish-tile";
|
||||
@@ -21,6 +24,10 @@ export default async function TodayPage() {
|
||||
const t = await getTranslations("today");
|
||||
const locale = await getLocale();
|
||||
const date = new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long" }).format(new Date());
|
||||
const after = await withHousehold(session.householdId, async (c) => ({
|
||||
toRate: await pendingRatings(c, session.memberId),
|
||||
thanks: await thanksForCook(c, session.memberId),
|
||||
}));
|
||||
const data = await withHousehold(session.householdId, async (c) => {
|
||||
const round = await currentRound(c);
|
||||
if (round && round.status !== "open") return { round, slots: await planSlots(c, round.id) };
|
||||
@@ -42,7 +49,20 @@ export default async function TodayPage() {
|
||||
<p className="eyebrow">{t("eyebrow", { date })}</p>
|
||||
<h1 className="text-4xl leading-tight">{t("greeting", { name: session.displayName })}</h1>
|
||||
</header>
|
||||
<InstallHint dismissible />
|
||||
|
||||
{after.toRate.map((r) => (
|
||||
<RateCard key={r.slotId} item={r} />
|
||||
))}
|
||||
{after.thanks.map((th) => (
|
||||
<p key={th.slotId} role="status" className="flex items-start gap-2 rounded-2xl border border-border p-4">
|
||||
<Heart aria-hidden className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||
<span>
|
||||
{t("thanks", { title: th.title, kudos: th.kudos, up: th.up })}
|
||||
{th.comments.length ? <span className="block text-sm text-muted-foreground">„{th.comments.join("“, „")}“</span> : null}
|
||||
</span>
|
||||
</p>
|
||||
))}
|
||||
{"slots" in data && data.slots ? (
|
||||
<PlanToday slots={data.slots} adult={adult} />
|
||||
) : "budget" in data && data.budget ? (
|
||||
@@ -135,6 +155,10 @@ async function PlanToday({ slots, adult }: { slots: Awaited<ReturnType<typeof pl
|
||||
<p className="text-muted-foreground">
|
||||
{[t("portions", { n: next.portions }), next.cookName ? t("cook", { name: next.cookName }) : null].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
<Link href={`/kochen/${next.id}`} className={cn(buttonVariants({ size: "lg" }), "mt-2")}>
|
||||
<ChefHat aria-hidden />
|
||||
{adult ? t("startCooking") : t("readAlong")}
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
) : (
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json } from "@/lib/auth/http";
|
||||
import { markCooked } from "@/lib/cooking";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { notifyShopping } from "@/lib/shopping";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// „Fertig“ im Kochmodus: Slot gekocht, Bewertung kann beginnen.
|
||||
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
const { id } = await params;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
return withHousehold(session.householdId, async (c) => {
|
||||
if (!(await markCooked(c, id, session.memberId))) return fail("notFound", 404);
|
||||
await notifyShopping(c, session.householdId); // die Liste braucht das Gekochte nicht mehr
|
||||
return json({ ok: true });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json } from "@/lib/auth/http";
|
||||
import { RatingRefused, thank } from "@/lib/cooking";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { WISHERS } from "@/lib/wishes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Dankeschön an den Koch (Konzept, „Gamification“): einmal je Person und Essen.
|
||||
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const session = await guardWrite(request, [...WISHERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const { id } = await params;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
try {
|
||||
await withHousehold(session.householdId, (c) => thank(c, session.householdId, id, session.memberId));
|
||||
return json({ ok: true });
|
||||
} catch (error) {
|
||||
if (error instanceof RatingRefused) return fail(error.message, 409);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { rate, RatingRefused } from "@/lib/cooking";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { WISHERS } from "@/lib/wishes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Daumen hoch oder runter, optional ein Satz — jede Person am Tisch, auch Kinder.
|
||||
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const session = await guardWrite(request, [...WISHERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const { id } = await params;
|
||||
const body = z.object({ thumbsUp: z.boolean(), comment: z.string().max(280).nullable().optional() }).safeParse(await readJson(request));
|
||||
if (!/^[0-9a-f-]{36}$/.test(id) || !body.success) return fail("invalid", 400);
|
||||
try {
|
||||
await withHousehold(session.householdId, (c) => rate(c, session.householdId, id, session.memberId, body.data.thumbsUp, body.data.comment ?? null));
|
||||
return json({ ok: true });
|
||||
} catch (error) {
|
||||
if (error instanceof RatingRefused) return fail(error.message, 409);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -1,9 +1,14 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
|
||||
export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
||||
const t = await getTranslations("app");
|
||||
const nav = await getTranslations("nav");
|
||||
return {
|
||||
id: "/",
|
||||
lang: await getLocale(),
|
||||
orientation: "any",
|
||||
categories: ["food", "lifestyle"],
|
||||
name: t("name"),
|
||||
short_name: t("name"),
|
||||
description: t("tagline"),
|
||||
@@ -11,6 +16,12 @@ export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
||||
display: "standalone",
|
||||
background_color: "#fdfcfe",
|
||||
theme_color: "#fdfcfe",
|
||||
// Lange auf das Symbol drücken: direkt zu Wünschen, Plan und Einkauf.
|
||||
shortcuts: [
|
||||
{ name: nav("wish"), url: "/wuenschen", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("plan"), url: "/plan", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("shopping"), url: "/einkauf", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
],
|
||||
icons: [
|
||||
{ src: "/icon-192.png", sizes: "192x192", type: "image/png" },
|
||||
{ src: "/icon-512.png", sizes: "512x512", type: "image/png" },
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { CloudOff } from "lucide-react";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { AuthShell } from "@/components/auth/auth-shell";
|
||||
|
||||
// Ohne Netz und ohne gespeicherten Stand zeigt der Service Worker diese Seite
|
||||
// (app/sw.ts, fallbacks). Sie braucht keine Sitzung und keine Daten.
|
||||
export default async function OfflinePage() {
|
||||
const t = await getTranslations("offline");
|
||||
return (
|
||||
<AuthShell title={t("title")} intro={t("text")}>
|
||||
<p className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<CloudOff aria-hidden className="size-4" />
|
||||
{t("hint")}
|
||||
</p>
|
||||
</AuthShell>
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,11 @@ import { defaultCache } from "@serwist/next/worker";
|
||||
import type { PrecacheEntry, SerwistGlobalConfig } from "serwist";
|
||||
import { Serwist } from "serwist";
|
||||
|
||||
// App-Shell offline. Rezepte und die Einkaufsliste als Warteschlange kommen
|
||||
// mit Arbeitspaket 7 und 8 dazu.
|
||||
// Offline: Seiten, die schon einmal offen waren (etwa die Einkaufsliste),
|
||||
// kommen aus dem Cache (defaultCache: zuerst Netz, dann Cache). Für alles
|
||||
// andere zeigt /offline, was los ist. Haken auf der Liste wartet die
|
||||
// Warteschlange im Browser ab (components/shopping/shopping-list.tsx).
|
||||
// Beim Abmelden leert die App diese Caches (lib/clear-caches.ts).
|
||||
declare global {
|
||||
interface WorkerGlobalScope extends SerwistGlobalConfig {
|
||||
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
|
||||
@@ -17,6 +20,9 @@ const serwist = new Serwist({
|
||||
clientsClaim: true,
|
||||
navigationPreload: true,
|
||||
runtimeCaching: defaultCache,
|
||||
fallbacks: {
|
||||
entries: [{ url: "/offline", matcher: ({ request }) => request.destination === "document" }],
|
||||
},
|
||||
});
|
||||
|
||||
serwist.addEventListeners();
|
||||
@@ -5,6 +5,7 @@ import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { clearCaches } from "@/lib/clear-caches";
|
||||
|
||||
// Untere Leiste unter dem Daumen (Leitprinzip 8). Plan und Einkauf kommen
|
||||
// mit ihren Arbeitspaketen dazu.
|
||||
@@ -57,6 +58,7 @@ export function AppNav({ child = false }: { child?: boolean }) {
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
await clearCaches();
|
||||
router.replace("/kinder");
|
||||
router.refresh();
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"use client";
|
||||
|
||||
import { Check, ChevronLeft, ChevronRight, Pause, Play, Sun, Timer as TimerIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import { timerFromText } from "@/lib/timer";
|
||||
import { formatQuantity, type BaseUnit } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Ingredient = { ingredientId: string; name: string; forms: { one: string; other: string } | null; qtyPerPortion: number; unit: BaseUnit; note: string | null };
|
||||
type Step = { text: string; timerSeconds: number | null };
|
||||
type Running = { step: number; endsAt: number | null; left: number; done: boolean };
|
||||
|
||||
const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.max(0, Math.round(s % 60))).padStart(2, "0")}`;
|
||||
|
||||
function beep() {
|
||||
try {
|
||||
const ctx = new AudioContext();
|
||||
for (const [i, f] of [880, 660, 880].entries()) {
|
||||
const o = ctx.createOscillator();
|
||||
const g = ctx.createGain();
|
||||
o.frequency.value = f;
|
||||
o.connect(g).connect(ctx.destination);
|
||||
g.gain.setValueAtTime(0.2, ctx.currentTime + i * 0.35);
|
||||
o.start(ctx.currentTime + i * 0.35);
|
||||
o.stop(ctx.currentTime + i * 0.35 + 0.25);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Kochmodus (Konzept, „Kochen“): erst Mise en place als Checkliste in der
|
||||
// Portionszahl des Slots, dann Schritt für Schritt in großer Schrift mit Timer.
|
||||
// Das Display bleibt an (Screen Wake Lock); Wischen, Tippen oder Pfeiltasten
|
||||
// blättern. „Fertig“ schließt den Slot ab und führt zur Bewertung auf „Heute“.
|
||||
export function CookingMode({
|
||||
slotId,
|
||||
title,
|
||||
portions,
|
||||
ingredients,
|
||||
steps,
|
||||
canFinish,
|
||||
}: {
|
||||
slotId: string;
|
||||
title: string;
|
||||
portions: number;
|
||||
ingredients: Ingredient[];
|
||||
steps: Step[];
|
||||
canFinish: boolean;
|
||||
}) {
|
||||
const t = useTranslations("cooking");
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const [index, setIndex] = useState(-1); // -1 = Mise en place
|
||||
const [have, setHave] = useState<Set<string>>(new Set());
|
||||
const [timers, setTimers] = useState<Running[]>([]);
|
||||
const [awake, setAwake] = useState(false);
|
||||
const [alarm, setAlarm] = useState<string | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const touch = useRef<number | null>(null);
|
||||
|
||||
// Display an lassen, solange der Kochmodus offen ist.
|
||||
useEffect(() => {
|
||||
let lock: WakeLockSentinel | null = null;
|
||||
const request = async () => {
|
||||
try {
|
||||
lock = (await navigator.wakeLock?.request("screen")) ?? null;
|
||||
setAwake(!!lock);
|
||||
} catch {
|
||||
setAwake(false);
|
||||
}
|
||||
};
|
||||
void request();
|
||||
const again = () => document.visibilityState === "visible" && void request();
|
||||
document.addEventListener("visibilitychange", again);
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", again);
|
||||
void lock?.release().catch(() => undefined);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Timer laufen weiter, auch beim Blättern; gerechnet wird gegen die Uhr, nicht gegen Intervalle.
|
||||
useEffect(() => {
|
||||
const tick = setInterval(() => {
|
||||
setTimers((list) =>
|
||||
list.map((r) => {
|
||||
if (r.done || r.endsAt === null) return r;
|
||||
const left = (r.endsAt - Date.now()) / 1000;
|
||||
if (left > 0) return { ...r, left };
|
||||
if ("vibrate" in navigator) navigator.vibrate?.([300, 150, 300]);
|
||||
beep();
|
||||
setAlarm(t("alarm", { n: r.step + 1 }));
|
||||
return { ...r, left: 0, done: true, endsAt: null };
|
||||
}),
|
||||
);
|
||||
}, 500);
|
||||
return () => clearInterval(tick);
|
||||
}, [t]);
|
||||
|
||||
const go = (by: number) => setIndex((i) => Math.min(steps.length - 1, Math.max(-1, i + by)));
|
||||
|
||||
useEffect(() => {
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if ((e.target as HTMLElement)?.closest("input, textarea, select")) return;
|
||||
if (e.key === "ArrowRight") go(1);
|
||||
if (e.key === "ArrowLeft") go(-1);
|
||||
};
|
||||
window.addEventListener("keydown", key);
|
||||
return () => window.removeEventListener("keydown", key);
|
||||
});
|
||||
|
||||
function toggleTimer(step: number, seconds: number) {
|
||||
setAlarm(null);
|
||||
setTimers((list) => {
|
||||
const r = list.find((x) => x.step === step);
|
||||
if (!r || r.done) return [...list.filter((x) => x.step !== step), { step, endsAt: Date.now() + seconds * 1000, left: seconds, done: false }];
|
||||
if (r.endsAt === null) return list.map((x) => (x.step === step ? { ...x, endsAt: Date.now() + x.left * 1000 } : x)); // weiter
|
||||
return list.map((x) => (x.step === step ? { ...x, endsAt: null } : x)); // Pause
|
||||
});
|
||||
}
|
||||
|
||||
async function finish() {
|
||||
setBusy(true);
|
||||
const res = await fetch(`/api/slots/${slotId}/cooked`, { method: "POST" }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) {
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else setError(true);
|
||||
}
|
||||
|
||||
const amount = (i: Ingredient) => {
|
||||
const f = formatQuantity(i.qtyPerPortion * portions, i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
};
|
||||
const raw = index >= 0 ? steps[index] : null;
|
||||
// Kein hinterlegter Timer? Dann die Zeit aus dem Text („30 Minuten köcheln“).
|
||||
const step = raw ? { ...raw, timerSeconds: raw.timerSeconds ?? timerFromText(raw.text) } : null;
|
||||
const running = timers.filter((r) => !r.done || r.left === 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col gap-5"
|
||||
onTouchStart={(e) => (touch.current = e.touches[0]?.clientX ?? null)}
|
||||
onTouchEnd={(e) => {
|
||||
const start = touch.current;
|
||||
const end = e.changedTouches[0]?.clientX;
|
||||
touch.current = null;
|
||||
if (start === null || end === undefined || Math.abs(end - start) < 60) return;
|
||||
go(end < start ? 1 : -1);
|
||||
}}
|
||||
>
|
||||
<p className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
{awake ? (
|
||||
<>
|
||||
<Sun aria-hidden className="size-4" />
|
||||
{t("awake")}
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
<p role="alert" aria-live="assertive" className={cn(alarm ? "rounded-xl border border-accent bg-accent/10 px-4 py-3 font-semibold" : "sr-only")}>
|
||||
{alarm}
|
||||
</p>
|
||||
|
||||
{running.length ? (
|
||||
<ul className="flex flex-wrap gap-2" aria-label={t("timers")}>
|
||||
{running.map((r) => (
|
||||
<li key={r.step}>
|
||||
<Button type="button" variant="outline" onClick={() => setIndex(r.step)}>
|
||||
<TimerIcon aria-hidden />
|
||||
{t("timerChip", { n: r.step + 1, time: mmss(r.left) })}
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
<div className="landscape:grid landscape:grid-cols-[2fr_3fr] landscape:gap-8 flex flex-col gap-5">
|
||||
<section aria-labelledby="mise-title" className={cn("flex flex-col gap-2", index >= 0 && "hidden landscape:flex")}>
|
||||
<h2 id="mise-title" className="eyebrow">
|
||||
{t("mise", { n: portions })}
|
||||
</h2>
|
||||
<ul className="flex flex-col">
|
||||
{ingredients.map((i) => {
|
||||
const checked = have.has(i.ingredientId);
|
||||
return (
|
||||
<li key={i.ingredientId} className="border-b border-border">
|
||||
<label className="flex min-h-14 cursor-pointer items-center gap-3 py-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="peer sr-only"
|
||||
checked={checked}
|
||||
onChange={() =>
|
||||
setHave((s) => {
|
||||
const n = new Set(s);
|
||||
if (n.has(i.ingredientId)) n.delete(i.ingredientId);
|
||||
else n.add(i.ingredientId);
|
||||
return n;
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span aria-hidden className={cn("flex size-7 shrink-0 items-center justify-center rounded-lg border-2 peer-focus-visible:ring-2 peer-focus-visible:ring-ring", checked ? "border-accent bg-accent text-background" : "border-border")}>
|
||||
{checked ? <Check className="size-5" /> : null}
|
||||
</span>
|
||||
<span className={cn("text-lg", checked && "text-muted-foreground line-through")}>
|
||||
<span className="font-semibold tabular-nums">{amount(i)}</span> {labelFor(i, i.qtyPerPortion * portions)}
|
||||
{i.note ? <span className="text-muted-foreground">, {i.note}</span> : null}
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{step ? (
|
||||
<section aria-labelledby="step-title" className="flex flex-col gap-5">
|
||||
<h2 id="step-title" className="eyebrow">
|
||||
{t("step", { n: index + 1, of: steps.length })}
|
||||
</h2>
|
||||
<p className="text-3xl leading-snug">{step.text}</p>
|
||||
{step.timerSeconds ? (
|
||||
<TimerButton
|
||||
running={timers.find((r) => r.step === index)}
|
||||
seconds={step.timerSeconds}
|
||||
onToggle={() => toggleTimer(index, step.timerSeconds!)}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
|
||||
|
||||
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" size="lg" disabled={index < 0} onClick={() => go(-1)} aria-label={t("back")}>
|
||||
<ChevronLeft aria-hidden />
|
||||
</Button>
|
||||
{index < steps.length - 1 ? (
|
||||
<Button type="button" size="lg" className="flex-1" onClick={() => go(1)}>
|
||||
{index < 0 ? t("start") : t("next")}
|
||||
<ChevronRight aria-hidden />
|
||||
</Button>
|
||||
) : canFinish ? (
|
||||
<Button type="button" size="lg" className="h-auto min-h-11 min-w-0 flex-1 whitespace-normal py-3 text-center" disabled={busy} onClick={finish}>
|
||||
{t("done", { title })}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TimerButton({ running, seconds, onToggle }: { running: Running | undefined; seconds: number; onToggle: () => void }) {
|
||||
const t = useTranslations("cooking");
|
||||
const active = running && !running.done && running.endsAt !== null;
|
||||
const paused = running && !running.done && running.endsAt === null;
|
||||
const left = running && !running.done ? running.left : seconds;
|
||||
return (
|
||||
<Button type="button" variant={active ? "default" : "outline"} size="lg" className="h-16 self-start px-6 text-2xl tabular-nums" onClick={onToggle}>
|
||||
{active ? <Pause aria-hidden /> : <Play aria-hidden />}
|
||||
<span>{mmss(left)}</span>
|
||||
<span className="sr-only">{active ? t("pause") : paused ? t("resume") : t("startTimer")}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { Heart, ThumbsDown, ThumbsUp } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type ToRate = { slotId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
|
||||
|
||||
// Bewerten (Konzept, „Bewerten“): Daumen hoch oder runter, optional ein Satz,
|
||||
// und ein Dankeschön an den Koch. Fünf Sekunden, am Tisch.
|
||||
export function RateCard({ item }: { item: ToRate }) {
|
||||
const t = useTranslations("rating");
|
||||
const router = useRouter();
|
||||
const [thumb, setThumb] = useState<boolean | null>(null);
|
||||
const [comment, setComment] = useState("");
|
||||
const [thanked, setThanked] = useState(item.thanked);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function post(url: string, body?: object) {
|
||||
setBusy(true);
|
||||
const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null);
|
||||
setBusy(false);
|
||||
return !!res?.ok;
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="flex flex-col gap-3 rounded-2xl bg-muted p-5" aria-labelledby={`rate-${item.slotId}`}>
|
||||
<p className="eyebrow">{t("eyebrow")}</p>
|
||||
<h2 id={`rate-${item.slotId}`} className="text-2xl leading-snug">
|
||||
{t("question", { title: item.title })}
|
||||
</h2>
|
||||
<div className="flex gap-3" role="group" aria-label={t("thumbs")}>
|
||||
{[true, false].map((up) => (
|
||||
<Button
|
||||
key={String(up)}
|
||||
type="button"
|
||||
variant="outline"
|
||||
aria-pressed={thumb === up}
|
||||
className={cn("h-16 flex-1 text-lg", thumb === up && "border-accent bg-accent text-background")}
|
||||
disabled={busy}
|
||||
onClick={() => setThumb(up)}
|
||||
>
|
||||
{up ? <ThumbsUp aria-hidden className="size-6" /> : <ThumbsDown aria-hidden className="size-6" />}
|
||||
{up ? t("up") : t("down")}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{thumb !== null ? (
|
||||
<form
|
||||
className="flex flex-col gap-3"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
if (await post(`/api/slots/${item.slotId}/rating`, { thumbsUp: thumb, comment: comment || null })) router.refresh();
|
||||
}}
|
||||
>
|
||||
<Input aria-label={t("comment")} placeholder={t("commentPlaceholder")} maxLength={280} value={comment} onChange={(e) => setComment(e.target.value)} />
|
||||
<Button type="submit" size="lg" disabled={busy}>
|
||||
{t("send")}
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
{!item.isCook && item.cookName ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
disabled={busy || thanked}
|
||||
aria-pressed={thanked}
|
||||
onClick={async () => {
|
||||
if (await post(`/api/slots/${item.slotId}/kudos`)) setThanked(true);
|
||||
}}
|
||||
>
|
||||
<Heart aria-hidden className={cn(thanked && "fill-current text-accent")} />
|
||||
{thanked ? t("thanked", { name: item.cookName }) : t("thank", { name: item.cookName })}
|
||||
</Button>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,18 @@ import { Minus, Plus, Timer } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import { formatQuantity, scale, type BaseUnit } from "@/lib/units";
|
||||
|
||||
type Ingredient = { ingredientId: string; name: string; qtyPerPortion: number; unit: BaseUnit; note: string | null; isStaple: boolean };
|
||||
type Ingredient = {
|
||||
ingredientId: string;
|
||||
name: string;
|
||||
forms: { one: string; other: string } | null;
|
||||
qtyPerPortion: number;
|
||||
unit: BaseUnit;
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
};
|
||||
type Step = { text: string; timerSeconds: number | null };
|
||||
|
||||
// Zutaten in der gewählten Portionszahl, darunter die Schritte. Die Mengen
|
||||
@@ -43,7 +52,7 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
|
||||
{f.unit ? ` ${f.unit}` : ""}
|
||||
</span>
|
||||
<span className="flex-1">
|
||||
{i.name}
|
||||
{labelFor(i, scale(i.qtyPerPortion, portions))}
|
||||
{i.note ? <span className="text-muted-foreground">, {i.note}</span> : null}
|
||||
</span>
|
||||
{i.isStaple ? <span className="text-xs text-muted-foreground">{t("staple")}</span> : null}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"use client";
|
||||
|
||||
import { Download, Share, X } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type PromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: string }> };
|
||||
|
||||
const DISMISSED = "lunch_install_hint";
|
||||
|
||||
// Lunch auf den Home-Bildschirm holen. Chrome und Android bieten einen eigenen
|
||||
// Dialog an (beforeinstallprompt), Safari am iPhone nicht — dort steht, wo es geht.
|
||||
// Läuft die App schon installiert, erscheint nichts. `dismissible`: auf „Heute“
|
||||
// lässt sich der Hinweis wegtippen, unter „Mehr“ bleibt er.
|
||||
export function InstallHint({ dismissible = false }: { dismissible?: boolean }) {
|
||||
const t = useTranslations("install");
|
||||
const [prompt, setPrompt] = useState<PromptEvent | null>(null);
|
||||
const [mode, setMode] = useState<"none" | "ios" | "prompt">("none");
|
||||
|
||||
useEffect(() => {
|
||||
const standalone = window.matchMedia("(display-mode: standalone)").matches || (navigator as { standalone?: boolean }).standalone;
|
||||
let gone = false;
|
||||
try {
|
||||
gone = dismissible && localStorage.getItem(DISMISSED) === "1";
|
||||
} catch {}
|
||||
if (standalone || gone) return;
|
||||
if (/iPhone|iPad|iPod/.test(navigator.userAgent)) setMode("ios");
|
||||
const onPrompt = (e: Event) => {
|
||||
e.preventDefault();
|
||||
setPrompt(e as PromptEvent);
|
||||
setMode("prompt");
|
||||
};
|
||||
window.addEventListener("beforeinstallprompt", onPrompt);
|
||||
return () => window.removeEventListener("beforeinstallprompt", onPrompt);
|
||||
}, [dismissible]);
|
||||
|
||||
if (mode === "none") return null;
|
||||
const dismiss = () => {
|
||||
try {
|
||||
localStorage.setItem(DISMISSED, "1");
|
||||
} catch {}
|
||||
setMode("none");
|
||||
};
|
||||
return (
|
||||
<aside aria-labelledby="install-title" className="flex items-start gap-3 rounded-2xl border border-border p-4">
|
||||
{mode === "ios" ? <Share aria-hidden className="mt-1 size-5 shrink-0 text-accent" /> : <Download aria-hidden className="mt-1 size-5 shrink-0 text-accent" />}
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<p id="install-title" className="font-semibold">
|
||||
{t("title")}
|
||||
</p>
|
||||
{mode === "ios" ? (
|
||||
<p className="text-sm text-muted-foreground">{t("ios")}</p>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="self-start"
|
||||
onClick={async () => {
|
||||
await prompt?.prompt();
|
||||
setMode("none");
|
||||
}}
|
||||
>
|
||||
{t("install")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{dismissible ? (
|
||||
<Button type="button" variant="ghost" size="icon" aria-label={t("dismiss")} onClick={dismiss}>
|
||||
<X aria-hidden />
|
||||
</Button>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LOCALES, type Locale } from "@/lib/locale";
|
||||
import { clearCaches } from "@/lib/clear-caches";
|
||||
|
||||
const NAMES: Record<Locale, string> = { de: "Deutsch", en: "English", fr: "Français", es: "Español" };
|
||||
|
||||
@@ -42,6 +43,7 @@ export function SignOutButton() {
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
await clearCaches();
|
||||
router.replace("/anmelden");
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Einzahl und Mehrzahl für Zutaten, die man in Stück zählt („1 Zwiebel“,
|
||||
-- „3 Knoblauchzehen“). Je Sprache { "one": …, "other": … }; eingespielt aus
|
||||
-- db/seed/ingredients.json (scripts/seed.mjs), gewählt in lib/ingredient-name.ts.
|
||||
alter table ingredients add column forms jsonb not null default '{}';
|
||||
+1178
-62
File diff suppressed because it is too large.
Load diff
@@ -59,7 +59,9 @@ Das Repo erbt sie, weil es in der Organisation liegt.
|
||||
7. **Einkaufsliste:** `lib/aggregate.ts` mit Tests, Gangsortierung, Echtzeit (SSE), Offline-Warteschlange.
|
||||
**Erledigt** in 26.11.12 (mit Vorrats-Check, Packungen, Hauptladen, Freitext).
|
||||
8. **Kochmodus** mit Wake Lock und Timer, Bewertung, Dankeschön.
|
||||
**Erledigt** in 26.11.13 (Timer auch aus dem Schritttext, Runde endet mit dem letzten gekochten Slot).
|
||||
9. **PWA-Feinschliff:** Manifest, Icons, Installationshinweis, Playwright für Wünschen, Planen, Einkaufen.
|
||||
**Erledigt** in 26.11.14 (Kurzbefehle, Offline-Seite, Caches leeren beim Abmelden; Browser-Tests für jeden Ablauf von Einrichten bis Bewerten).
|
||||
|
||||
Danach: Lunch in `aimighty/plattform` `werkzeug/apps.json` eintragen (nicht
|
||||
ins CI, E-0002).
|
||||
|
||||
@@ -30,10 +30,16 @@ test("a dish scales its ingredients with the portions", async ({ page }) => {
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Spaghetti Bolognese");
|
||||
const spaghetti = page.locator("li", { hasText: "Spaghetti" }).first();
|
||||
await expect(spaghetti).toContainText("250 g");
|
||||
// Stück in Einzahl und Mehrzahl, je nach Menge.
|
||||
const garlic = page.locator("li", { hasText: "Knoblauch" }).first();
|
||||
await expect(page.locator("li", { hasText: "Zwiebel" }).first()).toContainText("½Zwiebel");
|
||||
await expect(garlic).toContainText("1Knoblauchzehe");
|
||||
await page.getByRole("button", { name: "Eine Portion mehr" }).click();
|
||||
await page.getByRole("button", { name: "Eine Portion mehr" }).click();
|
||||
await expect(page.locator("output")).toHaveText("4 Portionen");
|
||||
await expect(spaghetti).toContainText("500 g");
|
||||
await expect(garlic).toContainText("2Knoblauchzehen");
|
||||
await expect(page.locator("li", { hasText: "Zwiebel" }).first()).toContainText("1Zwiebel");
|
||||
});
|
||||
|
||||
test("an own dish is created with searched ingredients, then edited", async ({ page }) => {
|
||||
@@ -52,8 +58,8 @@ test("an own dish is created with searched ingredients, then edited", async ({ p
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Gemüsecurry");
|
||||
await expect(page.locator("main")).toContainText("vegetarisch");
|
||||
// 2 Zwiebeln für 4 Portionen → 1 für 2 Portionen.
|
||||
await expect(page.locator("ul li", { hasText: "Zwiebeln" })).toContainText("1");
|
||||
// 2 Zwiebeln für 4 Portionen → 1 Zwiebel für 2 Portionen (Einzahl).
|
||||
await expect(page.locator("ul li", { hasText: "Zwiebel" })).toContainText(/^1\s*Zwiebel$/);
|
||||
await expect(page.locator("ul li", { hasText: "Kokosmilch" })).toContainText("200 ml");
|
||||
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// Kochmodus und Bewertung am iPhone (Paket 8). Läuft nach „einkauf“ mit Kais
|
||||
// Sitzung; als Nächstes steht Spaghetti Bolognese an (Kai kocht).
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
test("cooking mode: mise en place, steps by key, timer from the step text, done", async ({ page }) => {
|
||||
await page.clock.install();
|
||||
await page.goto("/");
|
||||
await expect(page.getByRole("heading", { level: 2 }).first()).toHaveText("Spaghetti Bolognese");
|
||||
await page.getByRole("link", { name: "Kochen" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Spaghetti Bolognese");
|
||||
await expect(page.getByText(/Alles bereit\? · \d+ Portionen/)).toBeVisible();
|
||||
const first = page.getByRole("checkbox").first();
|
||||
await first.check({ force: true });
|
||||
await expect(first).toBeChecked();
|
||||
|
||||
await page.getByRole("button", { name: "Los geht's" }).click();
|
||||
await expect(page.getByText("Schritt 1 von 6")).toBeVisible();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(page.getByText("Schritt 2 von 6")).toBeVisible();
|
||||
// „… 5 Minuten mitbraten“: Timer aus dem Text.
|
||||
await page.getByRole("button", { name: /5:00/ }).click();
|
||||
await page.clock.fastForward("02:00");
|
||||
await expect(page.getByRole("button", { name: /Timer anhalten/ })).toContainText(/3:0\d|2:5\d/);
|
||||
await page.keyboard.press("ArrowRight"); // der Timer läuft beim Blättern weiter
|
||||
await expect(page.getByRole("list", { name: "Laufende Timer" })).toContainText("Schritt 2");
|
||||
await page.clock.fastForward("03:05");
|
||||
await expect(page.locator("main [role=alert]")).toHaveText("Timer für Schritt 2 ist abgelaufen!");
|
||||
|
||||
for (let i = 0; i < 3; i++) await page.getByRole("button", { name: "Weiter" }).click();
|
||||
await expect(page.getByText("Schritt 6 von 6")).toBeVisible();
|
||||
// Ein langer Titel im Fertig-Knopf darf die Seite nicht verbreitern.
|
||||
const width = page.viewportSize()!.width;
|
||||
expect(await page.evaluate(() => Math.max(document.documentElement.scrollWidth, window.innerWidth))).toBeLessThanOrEqual(width);
|
||||
await page.getByRole("button", { name: "Spaghetti Bolognese ist fertig" }).click();
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
});
|
||||
|
||||
test("after cooking everyone rates; the cook sees the thumbs", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const card = page.getByRole("article", { name: "Wie war Spaghetti Bolognese?" });
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card.getByRole("button", { name: /Danke an/ })).toHaveCount(0); // Kai hat selbst gekocht
|
||||
await card.getByRole("button", { name: "Lecker" }).click();
|
||||
await card.getByRole("textbox", { name: "Ein Satz dazu (optional)" }).fill("mehr Soße");
|
||||
await card.getByRole("button", { name: "Abschicken" }).click();
|
||||
await expect(card).toHaveCount(0);
|
||||
await expect(page.getByRole("status").filter({ hasText: "Spaghetti Bolognese" })).toContainText("1 Daumen hoch");
|
||||
await expect(page.getByText("„mehr Soße“")).toBeVisible();
|
||||
await expect(page.getByText("Als Nächstes")).toBeVisible();
|
||||
await expect(page.getByRole("heading", { level: 2 }).filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// Web-App (Paket 9): Manifest mit Kurzbefehlen, Service Worker, offline die
|
||||
// zuletzt offene Einkaufsliste, sonst die Offline-Seite; Installationshinweis.
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
test("the manifest names the app and offers shortcuts", async ({ request }) => {
|
||||
const res = await request.get("/manifest.webmanifest");
|
||||
expect(res.ok()).toBe(true);
|
||||
const m = await res.json();
|
||||
expect(m).toMatchObject({ name: "Was gibt's?", display: "standalone", start_url: "/", id: "/" });
|
||||
expect(m.shortcuts.map((s: { url: string }) => s.url)).toEqual(["/wuenschen", "/plan", "/einkauf"]);
|
||||
expect(m.icons.some((i: { purpose?: string }) => i.purpose === "maskable")).toBe(true);
|
||||
});
|
||||
|
||||
test("offline: the shopping list opened before still works, other pages explain", async ({ page, context }) => {
|
||||
await page.goto("/");
|
||||
await page.evaluate(() => navigator.serviceWorker.ready);
|
||||
await page.reload(); // jetzt steuert der Service Worker die Seite
|
||||
await expect.poll(() => page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true);
|
||||
await page.goto("/einkauf");
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Einkaufsliste");
|
||||
|
||||
await context.setOffline(true);
|
||||
await page.reload();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Einkaufsliste");
|
||||
const other = await context.newPage(); // die Liste hält ihre Echtzeit-Verbindung offen
|
||||
await other.goto("/gerichte/neu");
|
||||
await expect(other.getByRole("heading", { level: 1 })).toHaveText("Kein Netz");
|
||||
await context.setOffline(false);
|
||||
});
|
||||
|
||||
test("Today offers to put Lunch on the home screen, and the hint can be hidden", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const hint = page.getByRole("complementary", { name: "Lunch auf den Home-Bildschirm" });
|
||||
await expect(hint).toContainText("Zum Home-Bildschirm");
|
||||
await hint.getByRole("button", { name: "Hinweis ausblenden" }).click();
|
||||
await expect(hint).toHaveCount(0);
|
||||
await page.reload();
|
||||
await expect(page.getByRole("complementary", { name: "Lunch auf den Home-Bildschirm" })).toHaveCount(0);
|
||||
await page.goto("/mehr");
|
||||
await expect(page.getByRole("complementary", { name: "Lunch auf den Home-Bildschirm" })).toBeVisible(); // unter „Mehr“ bleibt er
|
||||
});
|
||||
+11
-4
@@ -26,6 +26,7 @@ const SIGNED_OUT = [
|
||||
{ path: "/anmelden", heading: "Anmelden" },
|
||||
{ path: "/wiederherstellen", heading: "Zugang wiederherstellen" },
|
||||
{ path: "/kinder", heading: "Kein Kindergerät" },
|
||||
{ path: "/offline", heading: "Kein Netz" },
|
||||
];
|
||||
|
||||
async function check(page: Page, path: string, heading: string) {
|
||||
@@ -104,8 +105,14 @@ test("signed in: a dish and its edit form", async ({ page }) => {
|
||||
|
||||
test("the bottom bar never covers the last element", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
|
||||
const last = await page.getByRole("button", { name: "Abmelden" }).boundingBox();
|
||||
const nav = await page.getByRole("navigation").boundingBox();
|
||||
expect(last && nav && last.y + last.height <= nav.y).toBe(true);
|
||||
// Bis die Seite fertig ist (der Installationshinweis kommt erst nach dem Laden dazu):
|
||||
// jedes Mal ganz nach unten und nachmessen.
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
|
||||
const last = await page.getByRole("button", { name: "Abmelden" }).boundingBox();
|
||||
const nav = await page.getByRole("navigation").boundingBox();
|
||||
return !!(last && nav && last.y + last.height <= nav.y);
|
||||
})
|
||||
.toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
// Beim Abmelden: Was der Service Worker an Seiten gespeichert hat, gehört der
|
||||
// Person, die gerade geht (Einkaufsliste, Plan). Auf einem geteilten Tablet
|
||||
// soll das nicht stehen bleiben.
|
||||
export async function clearCaches(): Promise<void> {
|
||||
try {
|
||||
if (!("caches" in window)) return;
|
||||
for (const key of await caches.keys()) await caches.delete(key);
|
||||
} catch {
|
||||
// Kein Cache-Zugriff (privates Fenster): nichts zu tun.
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import "server-only";
|
||||
import type { PoolClient } from "pg";
|
||||
import { getDish, type DishDetail } from "./dishes";
|
||||
|
||||
// Kochen und danach (Konzept, „Kochen“ und „Bewerten“): ein Slot wird gekocht,
|
||||
// jede Person gibt Daumen hoch oder runter und optional ein Dankeschön an den
|
||||
// Koch. Bewertungen fließen über dish_popularity in den nächsten Vorschlag.
|
||||
|
||||
export type CookingSlot = {
|
||||
id: string;
|
||||
portions: number;
|
||||
cookMemberId: string | null;
|
||||
cookName: string | null;
|
||||
cookedAt: string | null;
|
||||
dish: DishDetail;
|
||||
};
|
||||
|
||||
export async function cookingSlot(client: PoolClient, slotId: string, locale: string): Promise<CookingSlot | null> {
|
||||
const row = (
|
||||
await client.query(
|
||||
`select s.id, s.portions, s.cook_member_id as "cookMemberId", m.display_name as "cookName", s.cooked_at::text as "cookedAt", s.dish_id
|
||||
from slots s left join members m on m.id = s.cook_member_id where s.id = $1 and s.dish_id is not null`,
|
||||
[slotId],
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) return null;
|
||||
const dish = await getDish(client, row.dish_id, locale);
|
||||
if (!dish) return null;
|
||||
const { dish_id: _, ...slot } = row;
|
||||
return { ...slot, dish };
|
||||
}
|
||||
|
||||
/** „Fertig“: Slot ist gekocht; wer kocht, steht fest; ist alles gekocht, endet die Runde. */
|
||||
export async function markCooked(client: PoolClient, slotId: string, memberId: string): Promise<boolean> {
|
||||
const { rows } = await client.query(
|
||||
`update slots set cooked_at = now(), cook_member_id = coalesce(cook_member_id, $2)
|
||||
where id = $1 and cooked_at is null and dish_id is not null returning round_id`,
|
||||
[slotId, memberId],
|
||||
);
|
||||
if (!rows[0]) return false;
|
||||
await client.query(
|
||||
`update rounds set status = 'done' where id = $1 and status <> 'done'
|
||||
and not exists (select 1 from slots where round_id = $1 and dish_id is not null and cooked_at is null)`,
|
||||
[rows[0].round_id],
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
export class RatingRefused extends Error {}
|
||||
|
||||
async function cookedSlot(client: PoolClient, slotId: string) {
|
||||
return (await client.query("select cook_member_id from slots where id = $1 and cooked_at is not null", [slotId])).rows[0] as
|
||||
| { cook_member_id: string | null }
|
||||
| undefined;
|
||||
}
|
||||
|
||||
export async function rate(client: PoolClient, householdId: string, slotId: string, memberId: string, thumbsUp: boolean, comment: string | null) {
|
||||
if (!(await cookedSlot(client, slotId))) throw new RatingRefused("notCooked");
|
||||
await client.query(
|
||||
`insert into ratings (household_id, slot_id, member_id, thumbs_up, comment) values ($1, $2, $3, $4, $5)
|
||||
on conflict (slot_id, member_id) do update set thumbs_up = excluded.thumbs_up, comment = excluded.comment`,
|
||||
[householdId, slotId, memberId, thumbsUp, comment?.trim() || null],
|
||||
);
|
||||
}
|
||||
|
||||
export async function thank(client: PoolClient, householdId: string, slotId: string, memberId: string) {
|
||||
const slot = await cookedSlot(client, slotId);
|
||||
if (!slot) throw new RatingRefused("notCooked");
|
||||
if (slot.cook_member_id === memberId) throw new RatingRefused("ownDish");
|
||||
await client.query(
|
||||
"insert into kudos (household_id, slot_id, from_member_id) values ($1, $2, $3) on conflict do nothing",
|
||||
[householdId, slotId, memberId],
|
||||
);
|
||||
}
|
||||
|
||||
export type ToRate = { slotId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
|
||||
|
||||
/** Gekochtes der letzten drei Tage, das ich noch nicht bewertet habe. */
|
||||
export async function pendingRatings(client: PoolClient, memberId: string): Promise<ToRate[]> {
|
||||
const { rows } = await client.query(
|
||||
`select s.id as "slotId", d.title, m.display_name as "cookName", s.cook_member_id = $1 as "isCook",
|
||||
exists (select 1 from kudos k where k.slot_id = s.id and k.from_member_id = $1) as thanked
|
||||
from slots s join dishes d on d.id = s.dish_id left join members m on m.id = s.cook_member_id
|
||||
where s.cooked_at > now() - interval '3 days'
|
||||
and not exists (select 1 from ratings r where r.slot_id = s.id and r.member_id = $1)
|
||||
order by s.cooked_at desc`,
|
||||
[memberId],
|
||||
);
|
||||
return rows.map((r) => ({ ...r, isCook: !!r.isCook }));
|
||||
}
|
||||
|
||||
export type Thanks = { slotId: string; title: string; kudos: number; up: number; down: number; comments: string[] };
|
||||
|
||||
/** Für den Koch: Dankeschöns und Daumen der letzten sieben Tage. */
|
||||
export async function thanksForCook(client: PoolClient, memberId: string): Promise<Thanks[]> {
|
||||
const { rows } = await client.query(
|
||||
`select s.id as "slotId", d.title,
|
||||
(select count(*)::int from kudos k where k.slot_id = s.id) as kudos,
|
||||
(select count(*)::int from ratings r where r.slot_id = s.id and r.thumbs_up) as up,
|
||||
(select count(*)::int from ratings r where r.slot_id = s.id and not r.thumbs_up) as down,
|
||||
coalesce((select array_agg(r.comment order by r.created_at) from ratings r where r.slot_id = s.id and r.comment is not null), '{}') as comments
|
||||
from slots s join dishes d on d.id = s.dish_id
|
||||
where s.cook_member_id = $1 and s.cooked_at > now() - interval '7 days'
|
||||
order by s.cooked_at desc`,
|
||||
[memberId],
|
||||
);
|
||||
return rows.filter((r) => r.kudos + r.up + r.down > 0);
|
||||
}
|
||||
+13
-3
@@ -51,7 +51,16 @@ export type DishSummary = {
|
||||
|
||||
export type DishDetail = DishSummary & {
|
||||
sourceUrl: string | null;
|
||||
ingredients: { ingredientId: string; name: string; qtyPerPortion: number; unit: BaseUnit; note: string | null; isStaple: boolean }[];
|
||||
ingredients: {
|
||||
ingredientId: string;
|
||||
name: string;
|
||||
// Einzahl/Mehrzahl bei Stück („1 Zwiebel“, „2 Zwiebeln“), lib/ingredient-name.ts
|
||||
forms: { one: string; other: string } | null;
|
||||
qtyPerPortion: number;
|
||||
unit: BaseUnit;
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
}[];
|
||||
steps: { text: string; timerSeconds: number | null }[];
|
||||
};
|
||||
|
||||
@@ -67,7 +76,7 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
|
||||
const dish = (await client.query(`select ${summaryColumns}, source_url as "sourceUrl" from dishes where id = $1 and archived_at is null`, [id]))
|
||||
.rows[0];
|
||||
if (!dish) return null;
|
||||
const names = new Map((await allIngredients()).map((i) => [i.id, i.names[locale] ?? i.names.en ?? ""]));
|
||||
const entries = new Map((await allIngredients()).map((i) => [i.id, i]));
|
||||
const ingredients = (
|
||||
await client.query(
|
||||
"select ingredient_id, qty_per_portion, unit, note, is_staple from dish_ingredients where dish_id = $1 order by position",
|
||||
@@ -75,7 +84,8 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
|
||||
)
|
||||
).rows.map((r) => ({
|
||||
ingredientId: r.ingredient_id,
|
||||
name: names.get(r.ingredient_id) ?? "",
|
||||
name: entries.get(r.ingredient_id)?.names[locale] ?? entries.get(r.ingredient_id)?.names.en ?? "",
|
||||
forms: entries.get(r.ingredient_id)?.forms?.[locale] ?? entries.get(r.ingredient_id)?.forms?.en ?? null,
|
||||
qtyPerPortion: Number(r.qty_per_portion),
|
||||
unit: r.unit,
|
||||
note: r.note,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// Wie eine Zutat bei einer Menge heißt. Bei Stück zählt die Zahl: „1 Zwiebel“,
|
||||
// „½ Zitrone“, aber „2 Zwiebeln“, „1½ Zitronen“. Gewicht und Volumen behalten den
|
||||
// Listennamen („500 g Kartoffeln“). Die Formen kommen aus dem Seed (ingredients.forms).
|
||||
|
||||
export type Forms = Partial<Record<string, { one: string; other: string }>>;
|
||||
|
||||
export type Nameable = { names: Record<string, string>; forms?: Forms | null; unit: "g" | "ml" | "piece" };
|
||||
|
||||
/** Einzahl bis einschließlich 1 — also auch für ½ und ¼. */
|
||||
export const isOne = (qty: number) => qty > 0 && qty <= 1 + 1e-9;
|
||||
|
||||
/** Für Anzeigen, die Name und Formen schon in der Sprache haben (Gerichtsseite, Kochmodus). */
|
||||
export function labelFor(i: { name: string; forms: { one: string; other: string } | null; unit: string }, qty: number): string {
|
||||
if (i.unit !== "piece" || !i.forms) return i.name;
|
||||
return isOne(qty) ? i.forms.one : i.forms.other;
|
||||
}
|
||||
|
||||
export function ingredientLabel(entry: Nameable, locale: string, qty: number | null): string {
|
||||
const list = entry.names[locale] ?? entry.names.en ?? "";
|
||||
if (entry.unit !== "piece" || qty === null) return list;
|
||||
const f = entry.forms?.[locale] ?? entry.forms?.en;
|
||||
if (!f) return list;
|
||||
return isOne(qty) ? f.one : f.other;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export type IngredientEntry = {
|
||||
category: string;
|
||||
names: Record<string, string>;
|
||||
synonyms: string[];
|
||||
forms?: Partial<Record<string, { one: string; other: string }>> | null;
|
||||
};
|
||||
|
||||
export function normalize(text: string): string {
|
||||
@@ -28,9 +29,12 @@ export function searchIngredients(list: IngredientEntry[], query: string, locale
|
||||
const scored: { entry: IngredientEntry; score: number }[] = [];
|
||||
for (const entry of list) {
|
||||
const name = normalize(entry.names[locale] ?? entry.names.en ?? "");
|
||||
const one = normalize(entry.forms?.[locale]?.one ?? "");
|
||||
let score = 0;
|
||||
if (name === q) score = 100;
|
||||
else if (one === q) score = 95; // „Ei“ findet „Eier“, „Apfel“ findet „Äpfel“
|
||||
else if (name.startsWith(q)) score = 80;
|
||||
else if (one.startsWith(q)) score = 75;
|
||||
else if (name.split(" ").some((w) => w.startsWith(q))) score = 60;
|
||||
else if (name.includes(q)) score = 40;
|
||||
else if (entry.synonyms.some((s) => normalize(s).startsWith(q))) score = 30;
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ let cache: Promise<IngredientEntry[]> | null = null;
|
||||
|
||||
export function allIngredients(): Promise<IngredientEntry[]> {
|
||||
cache ??= pool
|
||||
.query("select id, key, default_unit as unit, category, names, synonyms from ingredients order by key")
|
||||
.query("select id, key, default_unit as unit, category, names, synonyms, forms from ingredients order by key")
|
||||
.then((r) => r.rows as IngredientEntry[])
|
||||
.catch((error) => {
|
||||
cache = null;
|
||||
|
||||
+6
-2
@@ -1,6 +1,7 @@
|
||||
import "server-only";
|
||||
import type { PoolClient } from "pg";
|
||||
import { aggregate, withPacks, type PlanSlotInput } from "./aggregate";
|
||||
import { labelFor } from "./ingredient-name";
|
||||
import type { Round } from "./rounds";
|
||||
|
||||
// Einkaufsliste einer Runde: aus dem Plan abgeglichen, abgehakt von allen,
|
||||
@@ -45,7 +46,8 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
`select s.id as slot, d.title, s.portions, di.ingredient_id, di.qty_per_portion::float as q, di.unit,
|
||||
i.category, i.pack_sizes::float[] as packs,
|
||||
(i.pantry_default or exists (select 1 from pantry_staples p where p.ingredient_id = i.id)) as pantry,
|
||||
coalesce(i.names ->> $2, i.names ->> 'de', i.key) as name
|
||||
coalesce(i.names ->> $2, i.names ->> 'de', i.key) as name,
|
||||
coalesce(i.forms -> $2, i.forms -> 'en') as form
|
||||
from slots s join dishes d on d.id = s.dish_id
|
||||
join dish_ingredients di on di.dish_id = d.id
|
||||
join ingredients i on i.id = di.ingredient_id
|
||||
@@ -56,11 +58,13 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
).rows;
|
||||
const bySlot = new Map<string, PlanSlotInput>();
|
||||
const packs = new Map<string, number[]>();
|
||||
const forms = new Map<string, { one: string; other: string }>();
|
||||
for (const r of rows) {
|
||||
const slot: PlanSlotInput = bySlot.get(r.slot) ?? { dishTitle: r.title, portions: r.portions, ingredients: [] };
|
||||
slot.ingredients.push({ ingredientId: r.ingredient_id, name: r.name, unit: r.unit, qtyPerPortion: r.q, category: r.category, packs: r.packs, pantry: r.pantry });
|
||||
bySlot.set(r.slot, slot);
|
||||
packs.set(r.ingredient_id, r.packs ?? []);
|
||||
if (r.form) forms.set(r.ingredient_id, r.form);
|
||||
}
|
||||
const lines = withPacks(aggregate([...bySlot.values()], await defaultAisles(client)), (id) => packs.get(id) ?? []);
|
||||
for (const l of lines) {
|
||||
@@ -73,7 +77,7 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
pack_count = excluded.pack_count, pack_size = excluded.pack_size, dishes = excluded.dishes,
|
||||
aisle_position = excluded.aisle_position,
|
||||
pantry_state = case when excluded.pantry_state is null then null else coalesce(shopping_items.pantry_state, 'ask') end`,
|
||||
[householdId, round.id, l.ingredientId, l.name, l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
|
||||
[householdId, round.id, l.ingredientId, labelFor({ name: l.name, forms: forms.get(l.ingredientId) ?? null, unit: l.unit }, l.qty), l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
|
||||
l.dishes, l.aislePosition, l.pantry ? "ask" : null],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// Zeit aus einem Schritttext lesen („30 Minuten köcheln“, „bake for 1 hour“),
|
||||
// damit der Kochmodus auch ohne hinterlegten Timer einen anbietet. Bei einer
|
||||
// Spanne („10–15 Minuten“) gilt die kürzere Zeit: lieber einmal früher nachsehen.
|
||||
const UNITS: [RegExp, number][] = [
|
||||
[/^(min|min\.|minute|minuten|minutes|mins)$/i, 60],
|
||||
[/^(std|std\.|stunde|stunden|h|hour|hours|heure|heures|hora|horas)$/i, 3600],
|
||||
[/^(sek|sek\.|sekunden|sec|secs|seconds|secondes|segundos)$/i, 1],
|
||||
];
|
||||
|
||||
export function timerFromText(text: string): number | null {
|
||||
const m = text.match(/(\d+(?:[.,]\d+)?)(?:\s*(?:-|–|bis|to|à|a)\s*\d+(?:[.,]\d+)?)?\s*([A-Za-zäöüÄÖÜ]+\.?)/);
|
||||
if (!m) return null;
|
||||
const word = m[2]!.replace(/\.$/, "");
|
||||
const unit = UNITS.find(([re]) => re.test(word));
|
||||
if (!unit) return null;
|
||||
const seconds = Math.round(Number(m[1]!.replace(",", ".")) * unit[1]);
|
||||
return seconds > 0 && seconds <= 24 * 3600 ? seconds : null;
|
||||
}
|
||||
+46
-1
@@ -26,7 +26,10 @@
|
||||
"cook": "Koch: {name}",
|
||||
"allCooked": "Alles aus dieser Runde ist gekocht.",
|
||||
"thePlan": "Der Plan",
|
||||
"editPlan": "Bearbeiten"
|
||||
"editPlan": "Bearbeiten",
|
||||
"startCooking": "Kochen",
|
||||
"readAlong": "Mitlesen",
|
||||
"thanks": "Für {title}: {up, plural, =0 {noch kein Daumen hoch} one {1 Daumen hoch} other {# Daumen hoch}}{kudos, plural, =0 {} one { und 1 Dankeschön} other { und # Dankeschöns}}."
|
||||
},
|
||||
"auth": {
|
||||
"setup": {
|
||||
@@ -527,5 +530,47 @@
|
||||
"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.}}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Kochen",
|
||||
"eyebrowCook": "Kochen · {name}",
|
||||
"awake": "Das Display bleibt an.",
|
||||
"alarm": "Timer für Schritt {n} ist abgelaufen!",
|
||||
"timers": "Laufende Timer",
|
||||
"timerChip": "Schritt {n} · {time}",
|
||||
"mise": "Alles bereit? · {n, plural, one {1 Portion} other {# Portionen}}",
|
||||
"step": "Schritt {n} von {of}",
|
||||
"start": "Los geht's",
|
||||
"next": "Weiter",
|
||||
"back": "Zurück",
|
||||
"done": "{title} ist fertig",
|
||||
"pause": "Timer anhalten",
|
||||
"resume": "Timer fortsetzen",
|
||||
"startTimer": "Timer starten",
|
||||
"error": "Das hat nicht geklappt. Bitte versuch es noch einmal.",
|
||||
"alreadyCooked": "Das ist schon gekocht. Guten Appetit!"
|
||||
},
|
||||
"rating": {
|
||||
"eyebrow": "Wie war's?",
|
||||
"question": "Wie war {title}?",
|
||||
"thumbs": "Bewertung",
|
||||
"up": "Lecker",
|
||||
"down": "Nicht so",
|
||||
"comment": "Ein Satz dazu (optional)",
|
||||
"commentPlaceholder": "z. B. mehr Soße",
|
||||
"send": "Abschicken",
|
||||
"thank": "Danke an {name}",
|
||||
"thanked": "Danke an {name} ist angekommen"
|
||||
},
|
||||
"install": {
|
||||
"title": "Lunch auf den Home-Bildschirm",
|
||||
"ios": "In Safari auf das Teilen-Symbol tippen, dann „Zum Home-Bildschirm“. Danach öffnet sich Lunch wie eine App.",
|
||||
"install": "App installieren",
|
||||
"dismiss": "Hinweis ausblenden"
|
||||
},
|
||||
"offline": {
|
||||
"title": "Kein Netz",
|
||||
"text": "Diese Seite war noch nicht offen und ist deshalb nicht gespeichert. Sobald wieder Netz da ist, geht es weiter.",
|
||||
"hint": "Die Einkaufsliste funktioniert auch ohne Netz, wenn sie vorher einmal offen war."
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -26,7 +26,10 @@
|
||||
"cook": "Cook: {name}",
|
||||
"allCooked": "Everything from this round has been cooked.",
|
||||
"thePlan": "The plan",
|
||||
"editPlan": "Edit"
|
||||
"editPlan": "Edit",
|
||||
"startCooking": "Cook",
|
||||
"readAlong": "Read along",
|
||||
"thanks": "For {title}: {up, plural, =0 {no thumbs up yet} one {1 thumbs up} other {# thumbs up}}{kudos, plural, =0 {} one { and 1 thank-you} other { and # thank-yous}}."
|
||||
},
|
||||
"auth": {
|
||||
"setup": {
|
||||
@@ -527,5 +530,47 @@
|
||||
"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.}}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Cooking",
|
||||
"eyebrowCook": "Cooking · {name}",
|
||||
"awake": "The screen stays on.",
|
||||
"alarm": "Timer for step {n} is done!",
|
||||
"timers": "Running timers",
|
||||
"timerChip": "Step {n} · {time}",
|
||||
"mise": "All set? · {n, plural, one {1 portion} other {# portions}}",
|
||||
"step": "Step {n} of {of}",
|
||||
"start": "Let's go",
|
||||
"next": "Next",
|
||||
"back": "Back",
|
||||
"done": "{title} is ready",
|
||||
"pause": "Pause timer",
|
||||
"resume": "Resume timer",
|
||||
"startTimer": "Start timer",
|
||||
"error": "That did not work. Please try again.",
|
||||
"alreadyCooked": "This has been cooked already. Enjoy!"
|
||||
},
|
||||
"rating": {
|
||||
"eyebrow": "How was it?",
|
||||
"question": "How was {title}?",
|
||||
"thumbs": "Rating",
|
||||
"up": "Tasty",
|
||||
"down": "Not really",
|
||||
"comment": "A sentence (optional)",
|
||||
"commentPlaceholder": "e.g. more sauce",
|
||||
"send": "Send",
|
||||
"thank": "Thank {name}",
|
||||
"thanked": "Your thanks reached {name}"
|
||||
},
|
||||
"install": {
|
||||
"title": "Put Lunch on your home screen",
|
||||
"ios": "In Safari, tap the share icon, then “Add to Home Screen”. Lunch then opens like an app.",
|
||||
"install": "Install app",
|
||||
"dismiss": "Hide hint"
|
||||
},
|
||||
"offline": {
|
||||
"title": "No connection",
|
||||
"text": "This page has not been opened before, so it is not saved. It works again as soon as you are back online.",
|
||||
"hint": "The shopping list works without a connection if it was opened once before."
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -26,7 +26,10 @@
|
||||
"cook": "Cook: {name}",
|
||||
"allCooked": "Everything from this round has been cooked.",
|
||||
"thePlan": "The plan",
|
||||
"editPlan": "Edit"
|
||||
"editPlan": "Edit",
|
||||
"startCooking": "Cook",
|
||||
"readAlong": "Read along",
|
||||
"thanks": "For {title}: {up, plural, =0 {no thumbs up yet} one {1 thumbs up} other {# thumbs up}}{kudos, plural, =0 {} one { and 1 thank-you} other { and # thank-yous}}."
|
||||
},
|
||||
"auth": {
|
||||
"setup": {
|
||||
@@ -527,5 +530,47 @@
|
||||
"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.}}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Cooking",
|
||||
"eyebrowCook": "Cooking · {name}",
|
||||
"awake": "The screen stays on.",
|
||||
"alarm": "Timer for step {n} is done!",
|
||||
"timers": "Running timers",
|
||||
"timerChip": "Step {n} · {time}",
|
||||
"mise": "All set? · {n, plural, one {1 portion} other {# portions}}",
|
||||
"step": "Step {n} of {of}",
|
||||
"start": "Let's go",
|
||||
"next": "Next",
|
||||
"back": "Back",
|
||||
"done": "{title} is ready",
|
||||
"pause": "Pause timer",
|
||||
"resume": "Resume timer",
|
||||
"startTimer": "Start timer",
|
||||
"error": "That did not work. Please try again.",
|
||||
"alreadyCooked": "This has been cooked already. Enjoy!"
|
||||
},
|
||||
"rating": {
|
||||
"eyebrow": "How was it?",
|
||||
"question": "How was {title}?",
|
||||
"thumbs": "Rating",
|
||||
"up": "Tasty",
|
||||
"down": "Not really",
|
||||
"comment": "A sentence (optional)",
|
||||
"commentPlaceholder": "e.g. more sauce",
|
||||
"send": "Send",
|
||||
"thank": "Thank {name}",
|
||||
"thanked": "Your thanks reached {name}"
|
||||
},
|
||||
"install": {
|
||||
"title": "Put Lunch on your home screen",
|
||||
"ios": "In Safari, tap the share icon, then “Add to Home Screen”. Lunch then opens like an app.",
|
||||
"install": "Install app",
|
||||
"dismiss": "Hide hint"
|
||||
},
|
||||
"offline": {
|
||||
"title": "No connection",
|
||||
"text": "This page has not been opened before, so it is not saved. It works again as soon as you are back online.",
|
||||
"hint": "The shopping list works without a connection if it was opened once before."
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -26,7 +26,10 @@
|
||||
"cook": "Cook: {name}",
|
||||
"allCooked": "Everything from this round has been cooked.",
|
||||
"thePlan": "The plan",
|
||||
"editPlan": "Edit"
|
||||
"editPlan": "Edit",
|
||||
"startCooking": "Cook",
|
||||
"readAlong": "Read along",
|
||||
"thanks": "For {title}: {up, plural, =0 {no thumbs up yet} one {1 thumbs up} other {# thumbs up}}{kudos, plural, =0 {} one { and 1 thank-you} other { and # thank-yous}}."
|
||||
},
|
||||
"auth": {
|
||||
"setup": {
|
||||
@@ -527,5 +530,47 @@
|
||||
"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.}}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Cooking",
|
||||
"eyebrowCook": "Cooking · {name}",
|
||||
"awake": "The screen stays on.",
|
||||
"alarm": "Timer for step {n} is done!",
|
||||
"timers": "Running timers",
|
||||
"timerChip": "Step {n} · {time}",
|
||||
"mise": "All set? · {n, plural, one {1 portion} other {# portions}}",
|
||||
"step": "Step {n} of {of}",
|
||||
"start": "Let's go",
|
||||
"next": "Next",
|
||||
"back": "Back",
|
||||
"done": "{title} is ready",
|
||||
"pause": "Pause timer",
|
||||
"resume": "Resume timer",
|
||||
"startTimer": "Start timer",
|
||||
"error": "That did not work. Please try again.",
|
||||
"alreadyCooked": "This has been cooked already. Enjoy!"
|
||||
},
|
||||
"rating": {
|
||||
"eyebrow": "How was it?",
|
||||
"question": "How was {title}?",
|
||||
"thumbs": "Rating",
|
||||
"up": "Tasty",
|
||||
"down": "Not really",
|
||||
"comment": "A sentence (optional)",
|
||||
"commentPlaceholder": "e.g. more sauce",
|
||||
"send": "Send",
|
||||
"thank": "Thank {name}",
|
||||
"thanked": "Your thanks reached {name}"
|
||||
},
|
||||
"install": {
|
||||
"title": "Put Lunch on your home screen",
|
||||
"ios": "In Safari, tap the share icon, then “Add to Home Screen”. Lunch then opens like an app.",
|
||||
"install": "Install app",
|
||||
"dismiss": "Hide hint"
|
||||
},
|
||||
"offline": {
|
||||
"title": "No connection",
|
||||
"text": "This page has not been opened before, so it is not saved. It works again as soon as you are back online.",
|
||||
"hint": "The shopping list works without a connection if it was opened once before."
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ const withSerwist = withSerwistInit({
|
||||
swSrc: "app/sw.ts",
|
||||
swDest: "public/sw.js",
|
||||
disable: process.env.NODE_ENV !== "production",
|
||||
// Die Offline-Seite liegt vorab im Cache (Fallback in app/sw.ts).
|
||||
additionalPrecacheEntries: [{ url: "/offline", revision: String(Date.now()) }],
|
||||
});
|
||||
|
||||
const withNextIntl = createNextIntlPlugin("./i18n/request.ts");
|
||||
|
||||
+2
-2
@@ -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.12 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
|
||||
appVersion: "26.11.12" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
|
||||
version: 26.11.15 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
|
||||
appVersion: "26.11.15" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
|
||||
@@ -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.12
|
||||
version: 26.11.15
|
||||
categories:
|
||||
- Applications
|
||||
|
||||
@@ -61,7 +61,7 @@ permission:
|
||||
appData: true
|
||||
|
||||
spec:
|
||||
versionName: '26.11.12'
|
||||
versionName: '26.11.15'
|
||||
|
||||
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
promoteImage:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Cooking mode and thank-yous
|
||||
v26.11.13: Today now opens a cooking mode for what is up next: ingredients as a checklist in the planned portions, then one step at a time in large type, with timers that keep running while you move on and ring when done. The screen stays on, and swipes or arrow keys turn the page; on a tablet in landscape the ingredients sit next to the step. After the meal everyone gives a thumbs up or down, with a sentence if they like, and thanks the cook, who sees it on Today. Ratings feed the next round's suggestion.
|
||||
|
||||
## Deutsch
|
||||
v26.11.13: „Heute“ öffnet jetzt einen Kochmodus für das, was als Nächstes dran ist: Zutaten als Checkliste in der geplanten Portionszahl, dann Schritt für Schritt in großer Schrift, mit Timern, die beim Weiterblättern weiterlaufen und am Ende klingeln. Das Display bleibt an, Wischen oder Pfeiltasten blättern; am Tablet im Querformat stehen die Zutaten neben dem Schritt. Nach dem Essen gibt jede Person Daumen hoch oder runter, gern mit einem Satz, und sagt dem Koch Danke, der das auf „Heute“ sieht. Die Bewertungen fließen in den Vorschlag der nächsten Runde.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Ready for the home screen
|
||||
v26.11.14: Lunch is now a proper home-screen app: on the iPhone it shows how to add it via Share, elsewhere it offers to install itself, and a long press on the icon jumps straight to wishes, the plan or the shopping list. Pages opened before work without signal, anything else explains that you are offline, and signing out clears what the phone has stored. With this, all nine work packages of the first version are done.
|
||||
|
||||
## Deutsch
|
||||
v26.11.14: Lunch ist jetzt eine richtige App für den Home-Bildschirm: Am iPhone steht, wie es über „Teilen“ dorthin kommt, anderswo bietet es die Installation selbst an, und ein langer Druck aufs Symbol führt direkt zu Wünschen, Plan oder Einkaufsliste. Seiten, die schon offen waren, gehen auch ohne Netz, alles andere sagt, dass gerade kein Netz da ist, und Abmelden leert, was das Handy gespeichert hat. Damit sind alle neun Arbeitspakete der ersten Version fertig.
|
||||
@@ -0,0 +1,5 @@
|
||||
# One onion, two onions
|
||||
v26.11.15: Ingredients counted in pieces now read naturally in every language: "1 onion", "½ lemon", "3 garlic cloves" — on the dish page as you change the portions, in cooking mode and on the shopping list. Searching for the singular ("egg", "apple") finds the ingredient too.
|
||||
|
||||
## Deutsch
|
||||
v26.11.15: Zutaten, die man in Stück zählt, lesen sich jetzt in jeder Sprache richtig: „1 Zwiebel“, „½ Zitrone“, „3 Knoblauchzehen“ — am Gericht beim Ändern der Portionen, im Kochmodus und auf der Einkaufsliste. Die Suche findet sie auch in der Einzahl („Ei“, „Apfel“).
|
||||
+15
-3
@@ -54,22 +54,34 @@ export default defineConfig({
|
||||
dependencies: ["plan"],
|
||||
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
|
||||
},
|
||||
{
|
||||
name: "kochen",
|
||||
testMatch: /kochen\.spec\.ts/,
|
||||
dependencies: ["einkauf"],
|
||||
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
|
||||
},
|
||||
{
|
||||
name: "pwa",
|
||||
testMatch: /pwa\.spec\.ts/,
|
||||
dependencies: ["kochen"],
|
||||
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
|
||||
},
|
||||
{
|
||||
name: "iphone-hell",
|
||||
testMatch: /rundgang\.spec\.ts/,
|
||||
dependencies: ["einkauf"],
|
||||
dependencies: ["pwa"],
|
||||
use: { ...iphone, colorScheme: "light", storageState: "e2e/.auth/kai.json" },
|
||||
},
|
||||
{
|
||||
name: "iphone-dunkel",
|
||||
testMatch: /rundgang\.spec\.ts/,
|
||||
dependencies: ["einkauf"],
|
||||
dependencies: ["pwa"],
|
||||
use: { ...iphone, colorScheme: "dark", storageState: "e2e/.auth/kai.json" },
|
||||
},
|
||||
{
|
||||
name: "desktop",
|
||||
testMatch: /rundgang\.spec\.ts/,
|
||||
dependencies: ["einkauf"],
|
||||
dependencies: ["pwa"],
|
||||
use: { ...devices["Desktop Chrome"], viewport: { width: 1280, height: 860 }, storageState: "e2e/.auth/kai.json" },
|
||||
},
|
||||
],
|
||||
|
||||
+4
-4
@@ -41,13 +41,13 @@ export async function seed(client) {
|
||||
await client.query("select set_config('app.maintenance', 'on', true)");
|
||||
if (ingredients.length) {
|
||||
await client.query(
|
||||
`insert into ingredients (id, key, category, default_unit, names, synonyms, freshness, pack_sizes, pantry_default)
|
||||
select x.id, x.key, x.category, x.unit, x.names, x.synonyms, x.freshness, x.packs, x.pantry
|
||||
`insert into ingredients (id, key, category, default_unit, names, synonyms, freshness, pack_sizes, pantry_default, forms)
|
||||
select x.id, x.key, x.category, x.unit, x.names, x.synonyms, x.freshness, x.packs, x.pantry, coalesce(x.forms, '{}')
|
||||
from jsonb_to_recordset($1::jsonb) as x(id uuid, key text, category text, unit text, names jsonb,
|
||||
synonyms text[], freshness smallint, packs numeric[], pantry boolean)
|
||||
synonyms text[], freshness smallint, packs numeric[], pantry boolean, forms jsonb)
|
||||
on conflict (key) do update set category = excluded.category, default_unit = excluded.default_unit,
|
||||
names = excluded.names, synonyms = excluded.synonyms, freshness = excluded.freshness,
|
||||
pack_sizes = excluded.pack_sizes, pantry_default = excluded.pantry_default`,
|
||||
pack_sizes = excluded.pack_sizes, pantry_default = excluded.pantry_default, forms = excluded.forms`,
|
||||
[JSON.stringify(ingredients.map((i) => ({ ...i, id: idByKey.get(i.key) })))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import pg from "pg";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { seedHousehold } from "./fixture";
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
|
||||
// lib/cooking.ts gegen die Testdatenbank: Fertig, Ende der Runde, Bewertung,
|
||||
// Dankeschön (nicht an sich selbst), offene Bewertungen, Rückmeldung an den Koch.
|
||||
const url = process.env.TEST_DATABASE_URL;
|
||||
|
||||
describe.skipIf(!url)("cooking", () => {
|
||||
const client = new pg.Client({ connectionString: url });
|
||||
const h = randomUUID();
|
||||
let kai = "";
|
||||
let ben = "";
|
||||
let roundId = "";
|
||||
const slots: string[] = [];
|
||||
let cooking: typeof import("@/lib/cooking");
|
||||
let db: typeof import("@/lib/db");
|
||||
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.DATABASE_URL = url;
|
||||
await client.connect();
|
||||
const ingredient = (await client.query("select id from ingredients limit 1")).rows[0].id;
|
||||
kai = (await seedHousehold(client, h, ingredient)).member;
|
||||
cooking = await import("@/lib/cooking");
|
||||
db = await import("@/lib/db");
|
||||
await as(async (c) => {
|
||||
await c.query("update rounds set status = 'done'");
|
||||
ben = (await c.query("insert into members (household_id, display_name, role) values ($1, 'Ben', 'child') returning id", [h])).rows[0].id;
|
||||
roundId = (await c.query("insert into rounds (household_id, slots_count, default_portions, status) values ($1, 2, 4, 'shopping') returning id", [h])).rows[0].id;
|
||||
for (const [i, t] of ["Curry", "Pizza"].entries()) {
|
||||
const d = (await c.query("insert into dishes (household_id, title) values ($1, $2) returning id", [h, t])).rows[0].id;
|
||||
slots.push((await c.query("insert into slots (household_id, round_id, position, dish_id, portions) values ($1, $2, $3, $4, 4) returning id", [h, roundId, i + 1, d])).rows[0].id);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db.pool.end();
|
||||
await client.end();
|
||||
});
|
||||
|
||||
it("marks a slot cooked once, makes the finisher the cook, and ends the round with the last slot", async () => {
|
||||
expect(await as((c) => cooking.markCooked(c, slots[0]!, kai))).toBe(true);
|
||||
expect(await as((c) => cooking.markCooked(c, slots[0]!, kai))).toBe(false);
|
||||
const status = () => as(async (c) => (await c.query("select status from rounds where id = $1", [roundId])).rows[0].status);
|
||||
expect(await status()).toBe("shopping");
|
||||
expect(await as((c) => cooking.markCooked(c, slots[1]!, kai))).toBe(true);
|
||||
expect(await status()).toBe("done");
|
||||
expect(await as(async (c) => (await c.query("select cook_member_id from slots where id = $1", [slots[0]])).rows[0].cook_member_id)).toBe(kai);
|
||||
});
|
||||
|
||||
it("rates once per person (a second rating replaces it) and lists what is left to rate", async () => {
|
||||
const mine = async () => (await as((c) => cooking.pendingRatings(c, ben))).map((r) => r.slotId).filter((id) => slots.includes(id));
|
||||
expect((await mine()).sort()).toEqual([...slots].sort()); // dazu kommt der gekochte Slot aus der Fixture
|
||||
await as((c) => cooking.rate(c, h, slots[0]!, ben, false, "mehr Soße"));
|
||||
await as((c) => cooking.rate(c, h, slots[0]!, ben, true, " doch lecker "));
|
||||
const r = await as(async (c) => (await c.query("select thumbs_up, comment from ratings where slot_id = $1", [slots[0]])).rows);
|
||||
expect(r).toEqual([{ thumbs_up: true, comment: "doch lecker" }]);
|
||||
expect(await mine()).toEqual([slots[1]]);
|
||||
});
|
||||
|
||||
it("thanks the cook once, never oneself, and the cook sees it", async () => {
|
||||
await as((c) => cooking.thank(c, h, slots[0]!, ben));
|
||||
await as((c) => cooking.thank(c, h, slots[0]!, ben));
|
||||
await expect(as((c) => cooking.thank(c, h, slots[0]!, kai))).rejects.toThrow("ownDish");
|
||||
const thanks = await as((c) => cooking.thanksForCook(c, kai));
|
||||
expect(thanks.find((x) => x.slotId === slots[0])).toMatchObject({ kudos: 1, up: 1, down: 0, comments: ["doch lecker"] });
|
||||
});
|
||||
|
||||
it("refuses ratings for what has not been cooked", async () => {
|
||||
const open = await as(async (c) => {
|
||||
const d = (await c.query("select dish_id from slots where id = $1", [slots[0]])).rows[0].dish_id;
|
||||
return (await c.query("insert into slots (household_id, round_id, position, dish_id, portions) values ($1, $2, 3, $3, 2) returning id", [h, roundId, d])).rows[0].id;
|
||||
});
|
||||
await expect(as((c) => cooking.rate(c, h, open, ben, true, null))).rejects.toThrow("notCooked");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ingredientLabel, type Nameable } from "@/lib/ingredient-name";
|
||||
|
||||
const seed: (Nameable & { key: string })[] = JSON.parse(readFileSync("db/seed/ingredients.json", "utf8"));
|
||||
const byKey = (k: string) => seed.find((i) => i.key === k)!;
|
||||
|
||||
describe("ingredient names with amounts", () => {
|
||||
it("uses the singular up to one piece and the plural above", () => {
|
||||
expect(ingredientLabel(byKey("onion"), "de", 1)).toBe("Zwiebel");
|
||||
expect(ingredientLabel(byKey("onion"), "de", 0.5)).toBe("Zwiebel");
|
||||
expect(ingredientLabel(byKey("onion"), "de", 3)).toBe("Zwiebeln");
|
||||
expect(ingredientLabel(byKey("garlic"), "de", 3)).toBe("Knoblauchzehen");
|
||||
expect(ingredientLabel(byKey("egg"), "en", 1)).toBe("Egg");
|
||||
expect(ingredientLabel(byKey("egg"), "fr", 2)).toBe("Œufs");
|
||||
expect(ingredientLabel(byKey("lemon"), "es", 1.5)).toBe("Limones");
|
||||
});
|
||||
|
||||
it("keeps the list name for weight and volume, and without an amount", () => {
|
||||
expect(ingredientLabel(byKey("potato"), "de", 500)).toBe("Kartoffeln");
|
||||
expect(ingredientLabel(byKey("onion"), "de", null)).toBe("Zwiebeln");
|
||||
});
|
||||
|
||||
it("every ingredient counted in pieces has both forms in all four languages", () => {
|
||||
const missing = seed
|
||||
.filter((i) => i.unit === "piece")
|
||||
.filter((i) => ["de", "en", "fr", "es"].some((l) => !i.forms?.[l]?.one || !i.forms?.[l]?.other))
|
||||
.map((i) => i.key);
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { timerFromText } from "@/lib/timer";
|
||||
|
||||
describe("timer from text", () => {
|
||||
it("reads minutes, hours and ranges in several languages", () => {
|
||||
expect(timerFromText("Bei kleiner Hitze 30 Minuten köcheln lassen.")).toBe(1800);
|
||||
expect(timerFromText("Gemüse dazugeben und 5 Minuten mitbraten.")).toBe(300);
|
||||
expect(timerFromText("10–15 Min. backen")).toBe(600);
|
||||
expect(timerFromText("Bake for 1 hour.")).toBe(3600);
|
||||
expect(timerFromText("Laisser reposer 1,5 heures")).toBe(5400);
|
||||
});
|
||||
|
||||
it("ignores numbers that are not times", () => {
|
||||
expect(timerFromText("Ofen auf 200 °C vorheizen.")).toBeNull();
|
||||
expect(timerFromText("2 Eier verquirlen")).toBeNull();
|
||||
expect(timerFromText("Spaghetti kochen")).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user