Compare commits

...
1 Commits
Author SHA1 Message Date
kai e41fcc4a73 Singular and plural for ingredients counted in pieces (26.11.15) (#16)
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 1m4s
release / tag and release (push) Successful in 2s
2026-11-07 06:01:49 +00:00
17 changed files with 1307 additions and 84 deletions

No files matched your search

+9
View File
@@ -182,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,
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: What's cooking?
description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.14
version: 26.11.15
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.14'
versionName: '26.11.15'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+3 -2
View File
@@ -6,11 +6,12 @@ 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; qtyPerPortion: number; unit: BaseUnit; note: string | null };
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 };
@@ -206,7 +207,7 @@ export function CookingMode({
{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> {i.name}
<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>
+11 -2
View File
@@ -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}
+4
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+8 -2
View File
@@ -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();
+13 -3
View File
@@ -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,
+24
View File
@@ -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;
}
+4
View File
@@ -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
View File
@@ -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
View File
@@ -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],
);
}
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: lunch
description: Was gibt's? — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste
type: application
version: 26.11.14 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.14" # 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
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: What's cooking?
description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.14
version: 26.11.15
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.14'
versionName: '26.11.15'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -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“).
+4 -4
View File
@@ -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) })))],
);
}
+31
View File
@@ -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([]);
});
});