Compare commits

...

6 Commits

7 changed files with 54 additions and 281 deletions

View File

@@ -216,10 +216,6 @@ public class PlanningService {
private double scoreFromSimulatedSlots(List<SimulatedSlot> slots, VarietyScoreConfig config,
Set<UUID> recentlyCookedIds) {
List<String> checkedTagTypes = config.getRepeatTagTypes();
double wTagRepeat = config.getWTagRepeat().doubleValue();
double wIngredientOverlap = config.getWIngredientOverlap().doubleValue();
double wRecentRepeat = config.getWRecentRepeat().doubleValue();
double wPlanDuplicate = config.getWPlanDuplicate().doubleValue();
// 1. Tag-type repeats on consecutive days
Map<String, List<LocalDate>> tagDays = new LinkedHashMap<>();
@@ -259,11 +255,16 @@ public class PlanningService {
.mapToLong(c -> c - 1)
.sum();
return applyPenalties(tagRepeatCount, ingredientOverlapCount, recentRepeatCount, duplicatePenaltyCount, config);
}
private double applyPenalties(long tagRepeats, long ingredientOverlaps, long recentRepeats,
long duplicates, VarietyScoreConfig config) {
double score = MAX_VARIETY_SCORE;
score -= tagRepeatCount * wTagRepeat;
score -= ingredientOverlapCount * wIngredientOverlap;
score -= recentRepeatCount * wRecentRepeat;
score -= duplicatePenaltyCount * wPlanDuplicate;
score -= tagRepeats * config.getWTagRepeat().doubleValue();
score -= ingredientOverlaps * config.getWIngredientOverlap().doubleValue();
score -= recentRepeats * config.getWRecentRepeat().doubleValue();
score -= duplicates * config.getWPlanDuplicate().doubleValue();
return Math.max(0, Math.min(MAX_VARIETY_SCORE, score));
}
@@ -281,10 +282,6 @@ public class PlanningService {
.orElse(VarietyScoreConfig.defaults(plan.getHousehold()));
List<String> checkedTagTypes = config.getRepeatTagTypes();
double wTagRepeat = config.getWTagRepeat().doubleValue();
double wIngredientOverlap = config.getWIngredientOverlap().doubleValue();
double wRecentRepeat = config.getWRecentRepeat().doubleValue();
double wPlanDuplicate = config.getWPlanDuplicate().doubleValue();
int historyDays = config.getHistoryDays();
// 1. Tag-type repeats on consecutive days
@@ -352,13 +349,7 @@ public class PlanningService {
}
}
// Calculate score
double score = MAX_VARIETY_SCORE;
score -= tagRepeats.size() * wTagRepeat;
score -= overlaps.size() * wIngredientOverlap;
score -= recentRepeats.size() * wRecentRepeat;
score -= duplicatePenaltyCount * wPlanDuplicate;
score = Math.max(0, Math.min(MAX_VARIETY_SCORE, score));
double score = applyPenalties(tagRepeats.size(), overlaps.size(), recentRepeats.size(), duplicatePenaltyCount, config);
return new VarietyScoreResponse(score, tagRepeats, overlaps, recentRepeats, duplicatesInPlan);
}

View File

@@ -82,21 +82,23 @@
data-type="neutral"
style="display: inline-block; margin-top: 3px; font-size: 9px; font-weight: 500; padding: 1px 5px; border-radius: 3px; background: var(--yellow-tint); color: var(--yellow-text);"
>
= {delta.toFixed(1)} Punkte
Kein Einfluss
</span>
{/if}
{/snippet}
<div style="background: var(--color-page); font-family: var(--font-sans);">
<!-- Header -->
<div style="padding: 10px 12px 6px; border-bottom: 1px solid var(--color-border);">
<p style="font-family: var(--font-display); font-size: 14px; font-weight: 500; color: var(--color-text); margin: 0;">
Rezept wählen
</p>
<p style="font-size: 11px; color: var(--color-text-muted); margin: 2px 0 0;">
{dateLabel}
</p>
</div>
<!-- Header (hidden in swap context — the panel/sheet title already provides context) -->
{#if !replacingRecipe}
<div style="padding: 10px 12px 6px; border-bottom: 1px solid var(--color-border);">
<p style="font-family: var(--font-display); font-size: 14px; font-weight: 500; color: var(--color-text); margin: 0;">
Rezept wählen
</p>
<p style="font-size: 11px; color: var(--color-text-muted); margin: 2px 0 0;">
{dateLabel}
</p>
</div>
{/if}
<!-- Wird ersetzt banner (swap context) -->
{#if replacingRecipe}

View File

@@ -115,7 +115,7 @@ describe('RecipePicker', () => {
const alleRezepte = screen.getByTestId('alle-rezepte-section');
const badge = within(alleRezepte).getByTestId('badge-r1');
expect(badge.getAttribute('data-type')).toBe('neutral');
expect(badge.textContent).toContain('0.0');
expect(badge.textContent).toContain('Kein Einfluss');
});
it('Empfohlen shows only positive-delta suggestions, capped at 5', () => {
@@ -186,6 +186,16 @@ describe('RecipePicker', () => {
expect(screen.queryByText(/Wird ersetzt/i)).toBeNull();
});
it('hides Rezept wählen header when replacingRecipe is set', () => {
render(RecipePicker, { props: { ...baseProps, replacingRecipe: { name: 'Pasta' } } });
expect(screen.queryByText(/Rezept wählen/i)).toBeNull();
});
it('shows Rezept wählen header when replacingRecipe is not set', () => {
render(RecipePicker, { props: baseProps });
expect(screen.getByText(/Rezept wählen/i)).toBeTruthy();
});
it('excludes recipe from Alle Rezepte when excludeRecipeId is set', () => {
render(RecipePicker, { props: { ...baseProps, excludeRecipeId: 'r2' } });
expect(screen.queryByText('Spaghetti Carbonara')).toBeNull();

View File

@@ -1,126 +0,0 @@
<script lang="ts">
interface Recipe {
id: string;
name: string;
effort?: string | null;
cookTimeMin?: number | null;
}
let {
replacingName,
replacingMeta,
recipes,
currentWeekRecipeIds,
excludeRecipeId,
isLoading = false,
onpick,
oncancel
}: {
replacingName: string;
replacingMeta?: string;
recipes: Recipe[];
currentWeekRecipeIds: Set<string>;
excludeRecipeId?: string;
isLoading?: boolean;
onpick: (recipeId: string, recipeName: string) => void;
oncancel?: () => void;
} = $props();
let visibleRecipes = $derived(
excludeRecipeId ? recipes.filter((r) => r.id !== excludeRecipeId) : recipes
);
function recipeMeta(recipe: Recipe): string {
return [
recipe.cookTimeMin != null ? `${recipe.cookTimeMin} min` : null,
recipe.effort ?? null
]
.filter(Boolean)
.join(' · ');
}
</script>
<!-- Replacing banner -->
<div
style="background: var(--orange-tint); border: 1px solid #FBCDA4; border-radius: var(--radius-lg); padding: 10px 12px; margin-bottom: 14px;"
>
<p
style="font-size: 10px; font-weight: 500; letter-spacing: .08em; text-transform: uppercase; color: var(--orange-dark); margin: 0 0 4px 0; font-family: var(--font-sans);"
>
Wird ersetzt
</p>
<span
data-testid="replacing-name"
title={replacingName}
style="display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--font-display); font-size: 14px; text-decoration: line-through; opacity: 0.6; color: var(--color-text);"
>
{replacingName}{#if replacingMeta} · {replacingMeta}{/if}
</span>
</div>
<!-- Eyebrow label -->
<p
style="font-size: 10px; font-weight: 500; letter-spacing: .08em; text-transform: uppercase; color: var(--color-text-muted); margin: 0 0 6px 0; font-family: var(--font-sans);"
>
Ersetzen durch (einfachste zuerst)
</p>
<!-- Recipe list -->
{#if visibleRecipes.length === 0}
<p
data-testid="swap-empty-state"
style="text-align: center; color: var(--color-text-muted); font-family: var(--font-sans); margin: 0;"
>
Keine Rezepte verfügbar.
</p>
{:else}
{#each visibleRecipes as recipe (recipe.id)}
{@const meta = recipeMeta(recipe)}
{@const alreadyPlanned = currentWeekRecipeIds.has(recipe.id)}
<div
style="background: var(--color-surface); border: 1px solid var(--color-border); border-radius: var(--radius-lg); padding: 10px 12px; margin-bottom: 6px; display: flex; align-items: center; gap: 8px;"
>
<div style="flex: 1; min-width: 0;">
<p
style="font-family: var(--font-display); font-size: 13px; color: var(--color-text); margin: 0;"
>
{recipe.name}
</p>
{#if meta}
<p
style="font-size: 9px; color: var(--color-text-muted); font-family: var(--font-sans); margin: 1px 0 0;"
>
{meta}
</p>
{/if}
{#if alreadyPlanned}
<p
data-testid="already-planned-{recipe.id}"
style="font-size: 9px; color: var(--yellow-text); font-family: var(--font-sans); margin: 1px 0 0;"
>
⚠ Bereits diese Woche
</p>
{/if}
</div>
<button
type="button"
onclick={() => onpick(recipe.id, recipe.name)}
disabled={isLoading}
style="background: none; border: none; cursor: {isLoading ? 'default' : 'pointer'}; font-size: 11px; font-weight: 500; color: var(--green); font-family: var(--font-sans); flex-shrink: 0; opacity: {isLoading ? '0.4' : '1'};"
>
Wählen
</button>
</div>
{/each}
{/if}
<!-- Cancel button (optional) -->
{#if oncancel}
<button
type="button"
onclick={oncancel}
style="width: 100%; background: none; border: none; cursor: pointer; color: var(--color-text-muted); font-size: 13px; text-align: center; padding: 8px 0; font-family: var(--font-sans);"
>
Abbrechen
</button>
{/if}

View File

@@ -1,120 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/svelte';
import { userEvent } from '@testing-library/user-event';
import SwapSuggestionList from './SwapSuggestionList.svelte';
const recipes = [
{ id: 'r1', name: 'Quick carbonara', effort: 'easy', cookTimeMin: 20 },
{ id: 'r2', name: 'Chicken stir-fry', effort: 'easy', cookTimeMin: 25 },
{ id: 'r3', name: 'Mushroom risotto', effort: 'medium', cookTimeMin: 50 }
];
const baseProps = {
replacingName: 'Tomato pasta',
replacingMeta: '45 min · Easy',
recipes,
currentWeekRecipeIds: new Set<string>(),
onpick: vi.fn()
};
describe('SwapSuggestionList', () => {
it('renders the Replacing banner', () => {
render(SwapSuggestionList, { props: baseProps });
expect(screen.getByText(/Wird ersetzt/i)).toBeTruthy();
});
it('renders old meal name with strikethrough', () => {
render(SwapSuggestionList, { props: baseProps });
const struck = screen.getByTestId('replacing-name');
expect(struck.textContent).toContain('Tomato pasta');
expect(getComputedStyle(struck).textDecoration || struck.style.textDecoration).toContain('line-through');
});
it('replacing-name span has title attribute for full name', () => {
render(SwapSuggestionList, { props: baseProps });
const struck = screen.getByTestId('replacing-name');
expect(struck.getAttribute('title')).toBe('Tomato pasta');
});
it('renders the easiest-first eyebrow label', () => {
render(SwapSuggestionList, { props: baseProps });
expect(screen.getByText(/einfachste zuerst/i)).toBeTruthy();
});
it('renders all recipe names', () => {
render(SwapSuggestionList, { props: baseProps });
expect(screen.getByText('Quick carbonara')).toBeTruthy();
expect(screen.getByText('Chicken stir-fry')).toBeTruthy();
expect(screen.getByText('Mushroom risotto')).toBeTruthy();
});
it('clicking Wählen calls onpick with recipeId and name', async () => {
const onpick = vi.fn();
const user = userEvent.setup();
render(SwapSuggestionList, { props: { ...baseProps, onpick } });
const buttons = screen.getAllByRole('button', { name: /Wählen/i });
await user.click(buttons[0]);
expect(onpick).toHaveBeenCalledWith('r1', 'Quick carbonara');
});
it('shows already-planned warning for recipes in currentWeekRecipeIds', () => {
render(SwapSuggestionList, {
props: { ...baseProps, currentWeekRecipeIds: new Set(['r2']) }
});
expect(screen.getByTestId('already-planned-r2')).toBeTruthy();
});
it('does not show already-planned warning for recipes not in currentWeekRecipeIds', () => {
render(SwapSuggestionList, { props: baseProps });
expect(screen.queryByTestId('already-planned-r1')).toBeNull();
});
it('shows empty state when no recipes', () => {
render(SwapSuggestionList, { props: { ...baseProps, recipes: [] } });
expect(screen.getByTestId('swap-empty-state')).toBeTruthy();
});
it('excludes the recipe being replaced when excludeRecipeId is provided', () => {
render(SwapSuggestionList, { props: { ...baseProps, excludeRecipeId: 'r2' } });
expect(screen.queryByText('Chicken stir-fry')).toBeNull();
expect(screen.getByText('Quick carbonara')).toBeTruthy();
expect(screen.getByText('Mushroom risotto')).toBeTruthy();
});
it('shows all recipes when excludeRecipeId is not provided', () => {
render(SwapSuggestionList, { props: baseProps });
expect(screen.getByText('Quick carbonara')).toBeTruthy();
expect(screen.getByText('Chicken stir-fry')).toBeTruthy();
expect(screen.getByText('Mushroom risotto')).toBeTruthy();
});
it('disables all Wählen buttons when isLoading is true', () => {
render(SwapSuggestionList, { props: { ...baseProps, isLoading: true } });
const buttons = screen.getAllByRole('button', { name: /Wählen/i });
buttons.forEach((btn) => expect((btn as HTMLButtonElement).disabled).toBe(true));
});
it('Wählen buttons are enabled when isLoading is false', () => {
render(SwapSuggestionList, { props: { ...baseProps, isLoading: false } });
const buttons = screen.getAllByRole('button', { name: /Wählen/i });
buttons.forEach((btn) => expect((btn as HTMLButtonElement).disabled).toBe(false));
});
it('renders optional Abbrechen button when oncancel provided', () => {
render(SwapSuggestionList, { props: { ...baseProps, oncancel: vi.fn() } });
expect(screen.getByRole('button', { name: /Abbrechen/i })).toBeTruthy();
});
it('does not render Abbrechen button when oncancel not provided', () => {
render(SwapSuggestionList, { props: baseProps });
expect(screen.queryByRole('button', { name: /Abbrechen/i })).toBeNull();
});
it('clicking Abbrechen calls oncancel', async () => {
const oncancel = vi.fn();
const user = userEvent.setup();
render(SwapSuggestionList, { props: { ...baseProps, oncancel } });
await user.click(screen.getByRole('button', { name: /Abbrechen/i }));
expect(oncancel).toHaveBeenCalledOnce();
});
});

View File

@@ -7,10 +7,9 @@
import DayMealCard from '$lib/planner/DayMealCard.svelte';
import RecipePicker from '$lib/planner/RecipePicker.svelte';
import MealActionSheet from '$lib/planner/MealActionSheet.svelte';
import SwapSuggestionList from '$lib/planner/SwapSuggestionList.svelte';
import BottomSheet from '$lib/components/BottomSheet.svelte';
import UndoBar from '$lib/planner/UndoBar.svelte';
import { prevWeek, nextWeek, getWeekStart, weekDays, formatDayLabel, formatDayAbbr, formatWeekRange, sortEasiestFirst } from '$lib/planner/week';
import { prevWeek, nextWeek, getWeekStart, weekDays, formatDayLabel, formatDayAbbr, formatWeekRange } from '$lib/planner/week';
import type { Suggestion } from '$lib/planner/types';
let { data, form = null }: { data: { weekPlan: any; varietyScore: any; weekStart: string; recipes: any[] }; form?: any } = $props();
@@ -79,9 +78,6 @@
new Set<string>(slots.filter((s: any) => s.recipe?.id).map((s: any) => s.recipe.id))
);
// Recipes sorted easiest-first for the swap suggestion list
let sortedRecipes = $derived(sortEasiestFirst(data.recipes));
// Hidden form field bindings
let addPlanId = $state('');
let addSlotDate = $state('');

View File

@@ -93,6 +93,26 @@ describe('+page.svelte — $effect suggestion fetch', () => {
});
});
describe('+page.svelte — swap sheet suggestion fetch', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('opening mobile swap sheet triggers fetch with planId and date', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: () => Promise.resolve({ suggestions: [] }) }));
render(Page, { props: { data: mockDataWithSlot } });
// Open action sheet, then swap sheet
await userEvent.click(screen.getByTestId('day-meal-card'));
await userEvent.click(await screen.findByRole('button', { name: /Gericht tauschen/i }));
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
expect((fetch as any).mock.calls[0][0]).toContain(`planId=${PLAN_ID}`);
expect((fetch as any).mock.calls[0][0]).toContain(`date=${DATE}`);
});
});
describe('+page.svelte — remove meal', () => {
afterEach(() => {
vi.restoreAllMocks();