Compare commits
28 Commits
09333ccc0a
...
feat/issue
| Author | SHA1 | Date | |
|---|---|---|---|
| df95462094 | |||
| 2d6ddf0e48 | |||
| 73b33ee956 | |||
| 8daaa0e21d | |||
| 45b7e7b003 | |||
| 3581af2bf9 | |||
| 21b873b85b | |||
| 65f18cfb43 | |||
| 7b497be1c1 | |||
| 7979076f5e | |||
| d68a9d9312 | |||
| 97175e7d9d | |||
| 3550d681dc | |||
| 54df70a442 | |||
| d577e0231c | |||
| 376dc03646 | |||
| 7bdc049461 | |||
| 7c66dcad3a | |||
| 01a321caa9 | |||
| 2d1604492d | |||
| 3742364956 | |||
| 36dfea34cc | |||
| 66525484a6 | |||
| e5614ccf30 | |||
| 6de7f5a9b5 | |||
| e85a7ca313 | |||
| 175bfbe7dd | |||
| b9ef06fd73 |
71
frontend/src/lib/components/ProgressSidebar.svelte
Normal file
71
frontend/src/lib/components/ProgressSidebar.svelte
Normal file
@@ -0,0 +1,71 @@
|
||||
<script lang="ts">
|
||||
const { currentStep }: { currentStep: number } = $props();
|
||||
|
||||
const steps = [
|
||||
{
|
||||
number: 1,
|
||||
label: 'Haushalt benennen',
|
||||
subtitle: 'Deiner Familie einen Namen geben'
|
||||
},
|
||||
{
|
||||
number: 2,
|
||||
label: 'Vorräte einrichten',
|
||||
subtitle: 'Was ihr immer zu Hause habt'
|
||||
},
|
||||
{
|
||||
number: 3,
|
||||
label: 'Mitglieder einladen',
|
||||
subtitle: 'Haushalt teilen'
|
||||
}
|
||||
];
|
||||
|
||||
function circleClass(n: number): string {
|
||||
if (n === currentStep) return 'bg-[var(--green)] text-white';
|
||||
if (n < currentStep) return 'bg-[var(--green-tint)] text-[var(--green-dark)]';
|
||||
return 'bg-[var(--color-subtle)] text-[var(--color-text-muted)]';
|
||||
}
|
||||
|
||||
function labelClass(n: number): string {
|
||||
if (n === currentStep) return 'text-[13px] font-medium text-[var(--color-text)]';
|
||||
return 'text-[13px] text-[var(--color-text-muted)]';
|
||||
}
|
||||
</script>
|
||||
|
||||
<nav>
|
||||
<!-- Logo row -->
|
||||
<div class="flex items-center gap-[8px] mb-[40px]">
|
||||
<div
|
||||
class="w-[28px] h-[28px] rounded-[6px] bg-[var(--green)] flex items-center justify-center text-[14px]"
|
||||
>
|
||||
🥗
|
||||
</div>
|
||||
<span class="font-[var(--font-display)] text-[16px] font-medium">Mealplan</span>
|
||||
</div>
|
||||
|
||||
<!-- Steps -->
|
||||
<div class="flex flex-col gap-[24px]">
|
||||
{#each steps as step (step.number)}
|
||||
<div
|
||||
class="flex gap-[12px] items-start"
|
||||
data-testid="step-{step.number}"
|
||||
data-state={step.number < currentStep
|
||||
? 'completed'
|
||||
: step.number === currentStep
|
||||
? 'current'
|
||||
: 'future'}
|
||||
aria-current={step.number === currentStep ? 'step' : undefined}
|
||||
>
|
||||
<div
|
||||
class="w-[28px] h-[28px] rounded-full flex items-center justify-center text-[12px] font-medium flex-shrink-0 {circleClass(step.number)}"
|
||||
aria-label="Schritt {step.number}"
|
||||
>
|
||||
{step.number < currentStep ? '✓' : step.number}
|
||||
</div>
|
||||
<div>
|
||||
<div class={labelClass(step.number)}>{step.label}</div>
|
||||
<div class="text-[11px] text-[var(--color-text-muted)] mt-[2px]">{step.subtitle}</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</nav>
|
||||
63
frontend/src/lib/components/ProgressSidebar.test.ts
Normal file
63
frontend/src/lib/components/ProgressSidebar.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import ProgressSidebar from './ProgressSidebar.svelte';
|
||||
|
||||
describe('ProgressSidebar', () => {
|
||||
it('renders the app logo and name', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 1 } });
|
||||
expect(screen.getByText('Mealplan')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders all 3 step labels', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 1 } });
|
||||
expect(screen.getByText('Haushalt benennen')).toBeInTheDocument();
|
||||
expect(screen.getByText('Vorräte einrichten')).toBeInTheDocument();
|
||||
expect(screen.getByText('Mitglieder einladen')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('step 1 active: renders green circle for step 1', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 1 } });
|
||||
const step1 = screen.getByTestId('step-1');
|
||||
expect(step1).toHaveAttribute('aria-current', 'step');
|
||||
});
|
||||
|
||||
it('step 1 active: steps 2 and 3 are not current', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 1 } });
|
||||
expect(screen.getByTestId('step-2')).not.toHaveAttribute('aria-current');
|
||||
expect(screen.getByTestId('step-3')).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
it('step 2 active: step 1 is completed (checkmark), step 2 is current, step 3 is future', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 2 } });
|
||||
expect(screen.getByTestId('step-1')).toHaveAttribute('data-state', 'completed');
|
||||
expect(screen.getByTestId('step-2')).toHaveAttribute('aria-current', 'step');
|
||||
expect(screen.getByTestId('step-3')).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
it('step 1 completed has accessible label', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 2 } });
|
||||
const step1 = screen.getByTestId('step-1');
|
||||
expect(step1).toHaveAttribute('data-state', 'completed');
|
||||
expect(screen.getByLabelText(/schritt 1/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('each step has an accessible aria-label', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 1 } });
|
||||
expect(screen.getByLabelText(/schritt 1/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/schritt 2/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/schritt 3/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('future steps do not have aria-current', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 1 } });
|
||||
expect(screen.getByTestId('step-2')).not.toHaveAttribute('aria-current');
|
||||
expect(screen.getByTestId('step-3')).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
it('step 3 active: steps 1 and 2 are both completed', () => {
|
||||
render(ProgressSidebar, { props: { currentStep: 3 } });
|
||||
expect(screen.getByTestId('step-1')).toHaveAttribute('data-state', 'completed');
|
||||
expect(screen.getByTestId('step-2')).toHaveAttribute('data-state', 'completed');
|
||||
expect(screen.getByTestId('step-3')).toHaveAttribute('aria-current', 'step');
|
||||
});
|
||||
});
|
||||
26
frontend/src/lib/onboarding/CategorySection.svelte
Normal file
26
frontend/src/lib/onboarding/CategorySection.svelte
Normal file
@@ -0,0 +1,26 @@
|
||||
<script lang="ts">
|
||||
import StapleChip from './StapleChip.svelte';
|
||||
|
||||
type Ingredient = { id: string; name: string; isStaple: boolean };
|
||||
|
||||
let { name, ingredients, onToggle }: {
|
||||
name: string;
|
||||
ingredients: Ingredient[];
|
||||
onToggle: (id: string, value: boolean) => void;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<p class="text-[10px] font-medium tracking-[.08em] uppercase text-[var(--color-text-muted)] mb-[8px]">
|
||||
{name}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-[6px]">
|
||||
{#each ingredients as ingredient (ingredient.id)}
|
||||
<StapleChip
|
||||
name={ingredient.name}
|
||||
selected={ingredient.isStaple}
|
||||
onToggle={(value) => onToggle(ingredient.id, value)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
55
frontend/src/lib/onboarding/CategorySection.test.ts
Normal file
55
frontend/src/lib/onboarding/CategorySection.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { userEvent } from '@testing-library/user-event';
|
||||
import CategorySection from './CategorySection.svelte';
|
||||
|
||||
const mockIngredients = [
|
||||
{ id: '1', name: 'Olivenöl', isStaple: true },
|
||||
{ id: '2', name: 'Butter', isStaple: false },
|
||||
{ id: '3', name: 'Kokosöl', isStaple: false }
|
||||
];
|
||||
|
||||
describe('CategorySection', () => {
|
||||
it('renders the category name as a heading', () => {
|
||||
render(CategorySection, {
|
||||
props: { name: 'Öle & Fette', ingredients: mockIngredients, onToggle: vi.fn() }
|
||||
});
|
||||
expect(screen.getByText('Öle & Fette')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a chip for each ingredient', () => {
|
||||
render(CategorySection, {
|
||||
props: { name: 'Öle & Fette', ingredients: mockIngredients, onToggle: vi.fn() }
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'Olivenöl' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Butter' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Kokosöl' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reflects isStaple state on each chip', () => {
|
||||
render(CategorySection, {
|
||||
props: { name: 'Öle & Fette', ingredients: mockIngredients, onToggle: vi.fn() }
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'Olivenöl' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByRole('button', { name: 'Butter' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('calls onToggle with ingredient id and new value when chip is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggle = vi.fn();
|
||||
render(CategorySection, {
|
||||
props: { name: 'Öle & Fette', ingredients: mockIngredients, onToggle }
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Butter' }));
|
||||
expect(onToggle).toHaveBeenCalledWith('2', true);
|
||||
});
|
||||
|
||||
it('renders an empty category without crashing', () => {
|
||||
render(CategorySection, {
|
||||
props: { name: 'Leer', ingredients: [], onToggle: vi.fn() }
|
||||
});
|
||||
expect(screen.getByText('Leer')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
80
frontend/src/lib/onboarding/HouseholdSetupForm.svelte
Normal file
80
frontend/src/lib/onboarding/HouseholdSetupForm.svelte
Normal file
@@ -0,0 +1,80 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
|
||||
type FormResult = {
|
||||
errors?: Record<string, string>;
|
||||
name?: string;
|
||||
} | null;
|
||||
|
||||
let { form = null }: { form?: FormResult } = $props();
|
||||
|
||||
let name = $state('');
|
||||
let touched = $state(false);
|
||||
let submitAttempted = $state(false);
|
||||
let formError = $state('');
|
||||
|
||||
const isDisabled = $derived(name.trim().length === 0);
|
||||
const error = $derived(
|
||||
(touched || submitAttempted) && name.trim() === '' ? 'Haushaltsname ist erforderlich' : ''
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (form?.errors) {
|
||||
formError = form.errors.form ?? '';
|
||||
name = form?.name ?? '';
|
||||
}
|
||||
});
|
||||
|
||||
function handleSubmit(event: SubmitEvent) {
|
||||
submitAttempted = true;
|
||||
if (name.trim() === '') {
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
function handleInput() {
|
||||
touched = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form method="POST" novalidate use:enhance onsubmit={handleSubmit}>
|
||||
<h1 class="mb-[8px] font-[var(--font-display)] text-[18px] font-medium md:text-[28px]">Haushalt benennen</h1>
|
||||
<p class="mb-[24px] text-[12px] text-[var(--color-text-muted)] md:text-[14px]">
|
||||
Gib deinem Haushalt einen Namen, damit du ihn leicht wiederfindest.
|
||||
</p>
|
||||
|
||||
<div class="mb-[16px]">
|
||||
<label for="name" class="mb-[6px] block text-[14px] font-medium">Haushaltsname</label>
|
||||
<input
|
||||
type="text"
|
||||
id="name"
|
||||
name="name"
|
||||
placeholder="z.B. Familie Müller"
|
||||
autocomplete="organization"
|
||||
bind:value={name}
|
||||
oninput={handleInput}
|
||||
class="w-full rounded-[var(--radius-md)] border bg-[var(--color-page)] px-[12px] py-[10px] text-[14px] outline-none focus:ring-2 focus:ring-[var(--green-dark)] {error
|
||||
? 'border-[var(--color-error)]'
|
||||
: 'border-[var(--color-border)]'}"
|
||||
/>
|
||||
{#if error}
|
||||
<p class="mt-1 text-[12px] text-[var(--color-error)]">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if formError}
|
||||
<p
|
||||
class="mb-[16px] rounded-[var(--radius-md)] bg-[color-mix(in_srgb,var(--color-error),transparent_90%)] px-[12px] py-[10px] text-[12px] text-[var(--color-error)]"
|
||||
>
|
||||
{formError}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isDisabled}
|
||||
class="w-full cursor-pointer rounded-[var(--radius-md)] bg-[var(--green-dark)] px-[24px] py-[12px] text-[14px] font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Weiter → Vorräte einrichten
|
||||
</button>
|
||||
</form>
|
||||
83
frontend/src/lib/onboarding/HouseholdSetupForm.test.ts
Normal file
83
frontend/src/lib/onboarding/HouseholdSetupForm.test.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { userEvent } from '@testing-library/user-event';
|
||||
import HouseholdSetupForm from './HouseholdSetupForm.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({
|
||||
enhance: () => ({ destroy: () => {} })
|
||||
}));
|
||||
|
||||
describe('HouseholdSetupForm', () => {
|
||||
it('renders household name input with label', () => {
|
||||
render(HouseholdSetupForm);
|
||||
expect(screen.getByLabelText('Haushaltsname')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders heading', () => {
|
||||
render(HouseholdSetupForm);
|
||||
expect(screen.getByText('Haushalt benennen')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders Continue button', () => {
|
||||
render(HouseholdSetupForm);
|
||||
expect(screen.getByRole('button', { name: /weiter/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Continue button is disabled when name is empty', () => {
|
||||
render(HouseholdSetupForm);
|
||||
const btn = screen.getByRole('button', { name: /weiter/i });
|
||||
expect(btn).toBeDisabled();
|
||||
});
|
||||
|
||||
it('Continue button is enabled when name has text', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(HouseholdSetupForm);
|
||||
|
||||
await user.type(screen.getByLabelText('Haushaltsname'), 'Familie Müller');
|
||||
expect(screen.getByRole('button', { name: /weiter/i })).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows validation error when submitting with empty name', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(HouseholdSetupForm);
|
||||
|
||||
// Type then clear: sets touched=true, which makes the $derived error visible
|
||||
// as soon as the field is empty. The button is disabled so the click is a no-op,
|
||||
// but the error is already shown from the touched+empty state.
|
||||
const input = screen.getByLabelText('Haushaltsname');
|
||||
await user.type(input, 'a');
|
||||
await user.clear(input);
|
||||
await user.click(screen.getByRole('button', { name: /weiter/i }));
|
||||
|
||||
expect(screen.getByText('Haushaltsname ist erforderlich')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows server-side error from form prop', () => {
|
||||
render(HouseholdSetupForm, {
|
||||
props: {
|
||||
form: {
|
||||
errors: { form: 'Haushalt konnte nicht erstellt werden.' },
|
||||
name: 'Smith family'
|
||||
}
|
||||
}
|
||||
});
|
||||
expect(screen.getByText('Haushalt konnte nicht erstellt werden.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('repopulates name from form prop on server error', () => {
|
||||
render(HouseholdSetupForm, {
|
||||
props: {
|
||||
form: {
|
||||
errors: { form: 'Fehler' },
|
||||
name: 'Familie Müller'
|
||||
}
|
||||
}
|
||||
});
|
||||
expect(screen.getByLabelText('Haushaltsname')).toHaveValue('Familie Müller');
|
||||
});
|
||||
|
||||
it('input has correct placeholder', () => {
|
||||
render(HouseholdSetupForm);
|
||||
expect(screen.getByPlaceholderText('z.B. Familie Müller')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
20
frontend/src/lib/onboarding/StapleChip.svelte
Normal file
20
frontend/src/lib/onboarding/StapleChip.svelte
Normal file
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
let { name, selected, onToggle }: {
|
||||
name: string;
|
||||
selected: boolean;
|
||||
onToggle: (value: boolean) => void;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
onclick={() => onToggle(!selected)}
|
||||
class="inline-flex font-sans text-[13px] font-medium tracking-[0.04em] px-[12px] py-[6px] rounded-full border cursor-pointer
|
||||
focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--green-light)]
|
||||
{selected
|
||||
? 'bg-[var(--green-tint)] border-[var(--green-light)] text-[var(--green-dark)]'
|
||||
: 'bg-[var(--color-surface)] border-[var(--color-border)] text-[var(--color-text-muted)]'}"
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
53
frontend/src/lib/onboarding/StapleChip.test.ts
Normal file
53
frontend/src/lib/onboarding/StapleChip.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { userEvent } from '@testing-library/user-event';
|
||||
import StapleChip from './StapleChip.svelte';
|
||||
|
||||
describe('StapleChip', () => {
|
||||
it('renders a button with the ingredient name', () => {
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: false, onToggle: vi.fn() } });
|
||||
expect(screen.getByRole('button', { name: 'Olivenöl' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is aria-pressed="false" when unselected', () => {
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: false, onToggle: vi.fn() } });
|
||||
expect(screen.getByRole('button', { name: 'Olivenöl' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('is aria-pressed="true" when selected', () => {
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: true, onToggle: vi.fn() } });
|
||||
expect(screen.getByRole('button', { name: 'Olivenöl' })).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('calls onToggle with true when unselected chip is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggle = vi.fn();
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: false, onToggle } });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Olivenöl' }));
|
||||
expect(onToggle).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('calls onToggle with false when selected chip is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggle = vi.fn();
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: true, onToggle } });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Olivenöl' }));
|
||||
expect(onToggle).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('has a visible focus ring class for keyboard accessibility', () => {
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: false, onToggle: vi.fn() } });
|
||||
const btn = screen.getByRole('button', { name: 'Olivenöl' });
|
||||
expect(btn.className).toContain('focus-visible:outline');
|
||||
});
|
||||
|
||||
it('uses design-system button text spec: 13px, tracking, font-sans', () => {
|
||||
render(StapleChip, { props: { name: 'Olivenöl', selected: false, onToggle: vi.fn() } });
|
||||
const btn = screen.getByRole('button', { name: 'Olivenöl' });
|
||||
expect(btn.className).toContain('text-[13px]');
|
||||
expect(btn.className).toContain('tracking-[0.04em]');
|
||||
expect(btn.className).toContain('font-sans');
|
||||
});
|
||||
});
|
||||
80
frontend/src/lib/onboarding/StaplesManager.svelte
Normal file
80
frontend/src/lib/onboarding/StaplesManager.svelte
Normal file
@@ -0,0 +1,80 @@
|
||||
<script lang="ts">
|
||||
import CategorySection from './CategorySection.svelte';
|
||||
|
||||
type Ingredient = { id: string; name: string; isStaple: boolean };
|
||||
type Category = { id: string; name: string; ingredients: Ingredient[] };
|
||||
|
||||
let { categories, context }: {
|
||||
categories: Category[];
|
||||
context: 'onboarding' | 'settings';
|
||||
} = $props();
|
||||
|
||||
let stapleState = $state<Record<string, boolean>>({});
|
||||
let errorMessage = $state('');
|
||||
|
||||
$effect(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
for (const cat of categories) {
|
||||
for (const ing of cat.ingredients) {
|
||||
initial[ing.id] = ing.isStaple;
|
||||
}
|
||||
}
|
||||
stapleState = initial;
|
||||
});
|
||||
|
||||
function debounce<T extends (...args: any[]) => void>(fn: T, ms: number): T {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
return ((...args: any[]) => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), ms);
|
||||
}) as T;
|
||||
}
|
||||
|
||||
const debouncedPatchers: Record<string, (id: string, value: boolean) => void> = {};
|
||||
|
||||
function getPatcher(id: string) {
|
||||
if (!debouncedPatchers[id]) {
|
||||
debouncedPatchers[id] = debounce(async (ingredientId: string, value: boolean) => {
|
||||
const previous = !value;
|
||||
const res = await fetch(`/household/staples`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: ingredientId, isStaple: value })
|
||||
});
|
||||
if (!res.ok) {
|
||||
stapleState[ingredientId] = previous;
|
||||
errorMessage = 'Vorrat konnte nicht gespeichert werden.';
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
return debouncedPatchers[id];
|
||||
}
|
||||
|
||||
function handleToggle(ingredientId: string, newValue: boolean) {
|
||||
errorMessage = '';
|
||||
stapleState[ingredientId] = newValue;
|
||||
getPatcher(ingredientId)(ingredientId, newValue);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div>
|
||||
{#if errorMessage}
|
||||
<p class="mb-[12px] text-[12px] text-[var(--color-error)]">{errorMessage}</p>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
data-testid="category-grid"
|
||||
class="grid grid-cols-1 gap-[24px_32px] {context === 'settings' ? 'md:grid-cols-3' : 'md:grid-cols-2'}"
|
||||
>
|
||||
{#each categories as category (category.id)}
|
||||
<CategorySection
|
||||
name={category.name}
|
||||
ingredients={category.ingredients.map(ing => ({
|
||||
...ing,
|
||||
isStaple: stapleState[ing.id] ?? ing.isStaple
|
||||
}))}
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
107
frontend/src/lib/onboarding/StaplesManager.test.ts
Normal file
107
frontend/src/lib/onboarding/StaplesManager.test.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { userEvent } from '@testing-library/user-event';
|
||||
import StaplesManager from './StaplesManager.svelte';
|
||||
|
||||
const mockCategories = [
|
||||
{
|
||||
id: 'cat-1',
|
||||
name: 'Öle & Fette',
|
||||
ingredients: [
|
||||
{ id: 'ing-1', name: 'Olivenöl', isStaple: true },
|
||||
{ id: 'ing-2', name: 'Butter', isStaple: false }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'cat-2',
|
||||
name: 'Gewürze',
|
||||
ingredients: [
|
||||
{ id: 'ing-3', name: 'Salz', isStaple: true },
|
||||
{ id: 'ing-4', name: 'Pfeffer', isStaple: true }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
describe('StaplesManager', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('renders all categories', () => {
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'onboarding' } });
|
||||
expect(screen.getByText('Öle & Fette')).toBeInTheDocument();
|
||||
expect(screen.getByText('Gewürze')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders all chips with correct initial aria-pressed state', () => {
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'onboarding' } });
|
||||
expect(screen.getByRole('button', { name: 'Olivenöl' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByRole('button', { name: 'Butter' })).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(screen.getByRole('button', { name: 'Salz' })).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('clicking a chip immediately updates aria-pressed (optimistic)', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'onboarding' } });
|
||||
|
||||
const butter = screen.getByRole('button', { name: 'Butter' });
|
||||
expect(butter).toHaveAttribute('aria-pressed', 'false');
|
||||
await user.click(butter);
|
||||
expect(butter).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('rapid clicks on same chip result in exactly one fetch call after debounce', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'onboarding' } });
|
||||
|
||||
const butter = screen.getByRole('button', { name: 'Butter' });
|
||||
await user.click(butter);
|
||||
await user.click(butter);
|
||||
await user.click(butter);
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(300);
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reverts chip and shows error when PATCH fails', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'onboarding' } });
|
||||
|
||||
const butter = screen.getByRole('button', { name: 'Butter' });
|
||||
await user.click(butter);
|
||||
expect(butter).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
expect(butter).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(screen.getByText(/konnte nicht gespeichert werden/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses 2-column grid class in onboarding context', () => {
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'onboarding' } });
|
||||
const grid = screen.getByTestId('category-grid');
|
||||
expect(grid.className).toContain('md:grid-cols-2');
|
||||
});
|
||||
|
||||
it('uses 3-column grid class in settings context', () => {
|
||||
render(StaplesManager, { props: { categories: mockCategories, context: 'settings' } });
|
||||
const grid = screen.getByTestId('category-grid');
|
||||
expect(grid.className).toContain('md:grid-cols-3');
|
||||
});
|
||||
|
||||
it('renders without crashing when categories is empty', () => {
|
||||
render(StaplesManager, { props: { categories: [], context: 'onboarding' } });
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
7
frontend/src/routes/household/invite/+page.svelte
Normal file
7
frontend/src/routes/household/invite/+page.svelte
Normal file
@@ -0,0 +1,7 @@
|
||||
<svelte:head>
|
||||
<title>Mitglieder einladen — Mealplan</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="flex min-h-screen items-center justify-center bg-[var(--color-page)]">
|
||||
<p class="text-[var(--color-text-muted)]">A4 — Mitglieder einladen (coming soon)</p>
|
||||
</div>
|
||||
39
frontend/src/routes/household/setup/+page.server.ts
Normal file
39
frontend/src/routes/household/setup/+page.server.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { redirect, fail } from '@sveltejs/kit';
|
||||
import { apiClient } from '$lib/server/api';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
if (locals.haushalt?.id) {
|
||||
throw redirect(303, '/planner');
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
export const actions = {
|
||||
default: async ({ request, fetch }) => {
|
||||
const formData = await request.formData();
|
||||
const name = (formData.get('name') ?? '').toString().trim();
|
||||
|
||||
if (!name) {
|
||||
return fail(400, { errors: { name: 'Haushaltsname ist erforderlich' }, name: '' });
|
||||
}
|
||||
|
||||
if (name.length > 100) {
|
||||
return fail(400, { errors: { name: 'Haushaltsname darf maximal 100 Zeichen lang sein' }, name });
|
||||
}
|
||||
|
||||
const api = apiClient(fetch);
|
||||
const { data, error } = await api.POST('/v1/households', {
|
||||
body: { name }
|
||||
});
|
||||
|
||||
if (error || !data?.data) {
|
||||
return fail(500, {
|
||||
errors: { form: 'Haushalt konnte nicht erstellt werden. Bitte versuche es erneut.' },
|
||||
name
|
||||
});
|
||||
}
|
||||
|
||||
throw redirect(303, '/household/staples?ctx=onboarding');
|
||||
}
|
||||
} satisfies Actions;
|
||||
41
frontend/src/routes/household/setup/+page.svelte
Normal file
41
frontend/src/routes/household/setup/+page.svelte
Normal file
@@ -0,0 +1,41 @@
|
||||
<script lang="ts">
|
||||
import ProgressSidebar from '$lib/components/ProgressSidebar.svelte';
|
||||
import HouseholdSetupForm from '$lib/onboarding/HouseholdSetupForm.svelte';
|
||||
|
||||
type FormResult = {
|
||||
errors?: Record<string, string>;
|
||||
name?: string;
|
||||
} | null;
|
||||
|
||||
let { form = null }: { form?: FormResult } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Haushalt einrichten — Mealplan</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="flex min-h-screen bg-[var(--color-page)]">
|
||||
<!-- Desktop progress sidebar — hidden on mobile -->
|
||||
<aside
|
||||
class="hidden md:flex w-[300px] flex-shrink-0 flex-col bg-[var(--color-surface)] border-r border-[var(--color-border)] p-[40px_28px]"
|
||||
>
|
||||
<ProgressSidebar currentStep={1} />
|
||||
</aside>
|
||||
|
||||
<!-- Form area -->
|
||||
<main class="flex flex-1 flex-col justify-center">
|
||||
<!-- Mobile: step indicator (visible only on mobile) -->
|
||||
<div class="md:hidden px-[20px] pt-[24px] pb-[0]">
|
||||
<p class="text-[10px] font-medium tracking-[.08em] uppercase text-[var(--color-text-muted)]">
|
||||
Schritt 1 von 3
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Form -->
|
||||
<div class="px-[20px] py-[24px] md:px-[56px] md:py-[48px]">
|
||||
<div class="max-w-[420px]">
|
||||
<HouseholdSetupForm {form} />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
158
frontend/src/routes/household/setup/page.server.test.ts
Normal file
158
frontend/src/routes/household/setup/page.server.test.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('$env/dynamic/private', () => ({
|
||||
env: { BACKEND_URL: 'http://localhost:8080' }
|
||||
}));
|
||||
|
||||
const mockPost = vi.fn();
|
||||
vi.mock('$lib/server/api', () => ({
|
||||
apiClient: () => ({ POST: mockPost })
|
||||
}));
|
||||
|
||||
describe('household setup — load', () => {
|
||||
let load: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
const mod = await import('./+page.server');
|
||||
load = mod.load;
|
||||
});
|
||||
|
||||
it('redirects to /planner when user already has a household', async () => {
|
||||
const event = {
|
||||
locals: {
|
||||
benutzer: { id: '1', name: 'Sarah', rolle: 'planer' },
|
||||
haushalt: { id: 'household-123', name: 'Smith family' }
|
||||
}
|
||||
} as any;
|
||||
|
||||
try {
|
||||
await load(event);
|
||||
expect.unreachable();
|
||||
} catch (e: any) {
|
||||
expect(e.status).toBe(303);
|
||||
expect(e.location).toBe('/planner');
|
||||
}
|
||||
});
|
||||
|
||||
it('allows access when user has no household', async () => {
|
||||
const event = {
|
||||
locals: {
|
||||
benutzer: { id: '1', name: 'Sarah', rolle: 'planer' },
|
||||
haushalt: { id: undefined, name: 'Kein Haushalt' }
|
||||
}
|
||||
} as any;
|
||||
|
||||
const result = await load(event);
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('household setup — form action', () => {
|
||||
let actions: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockPost.mockReset();
|
||||
const mod = await import('./+page.server');
|
||||
actions = mod.actions;
|
||||
});
|
||||
|
||||
function createRequest(formData: Record<string, string>) {
|
||||
const fd = new FormData();
|
||||
for (const [key, value] of Object.entries(formData)) {
|
||||
fd.append(key, value);
|
||||
}
|
||||
return {
|
||||
request: { formData: () => Promise.resolve(fd) },
|
||||
fetch: vi.fn(),
|
||||
cookies: { get: vi.fn(), set: vi.fn() }
|
||||
} as any;
|
||||
}
|
||||
|
||||
function mockSuccess() {
|
||||
return {
|
||||
data: { data: { id: 'hh-123', name: 'Smith family', members: [] } },
|
||||
error: undefined
|
||||
};
|
||||
}
|
||||
|
||||
it('calls POST /v1/households with the household name', async () => {
|
||||
mockPost.mockResolvedValue(mockSuccess());
|
||||
|
||||
try {
|
||||
await actions.default(createRequest({ name: 'Smith family' }));
|
||||
} catch {
|
||||
// redirect throws
|
||||
}
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith('/v1/households', {
|
||||
body: { name: 'Smith family' }
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects to /household/staples on success', async () => {
|
||||
mockPost.mockResolvedValue(mockSuccess());
|
||||
|
||||
try {
|
||||
await actions.default(createRequest({ name: 'Smith family' }));
|
||||
expect.unreachable();
|
||||
} catch (e: any) {
|
||||
expect(e.status).toBe(303);
|
||||
expect(e.location).toBe('/household/staples?ctx=onboarding');
|
||||
}
|
||||
});
|
||||
|
||||
it('returns fail(400) when name is empty', async () => {
|
||||
const result = await actions.default(createRequest({ name: '' }));
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.data.errors.name).toBeTruthy();
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns fail(400) when name is whitespace only', async () => {
|
||||
const result = await actions.default(createRequest({ name: ' ' }));
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.data.errors.name).toBeTruthy();
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('echoes name back on validation error', async () => {
|
||||
const result = await actions.default(createRequest({ name: '' }));
|
||||
expect(result.data.name).toBe('');
|
||||
});
|
||||
|
||||
it('returns fail(400) when name exceeds 100 characters', async () => {
|
||||
const longName = 'a'.repeat(101);
|
||||
const result = await actions.default(createRequest({ name: longName }));
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.data.errors.name).toBeTruthy();
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('accepts name at exactly 100 characters', async () => {
|
||||
mockPost.mockResolvedValue(mockSuccess());
|
||||
const maxName = 'a'.repeat(100);
|
||||
|
||||
try {
|
||||
await actions.default(createRequest({ name: maxName }));
|
||||
} catch {
|
||||
// redirect throws
|
||||
}
|
||||
|
||||
expect(mockPost).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns fail with form error on API failure', async () => {
|
||||
mockPost.mockResolvedValue({
|
||||
data: undefined,
|
||||
error: { status: 500, message: 'Internal server error' }
|
||||
});
|
||||
|
||||
const result = await actions.default(createRequest({ name: 'Smith family' }));
|
||||
|
||||
expect(result.status).toBe(500);
|
||||
expect(result.data.errors.form).toBeTruthy();
|
||||
});
|
||||
});
|
||||
53
frontend/src/routes/household/setup/page.test.ts
Normal file
53
frontend/src/routes/household/setup/page.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({
|
||||
enhance: () => ({ destroy: () => {} })
|
||||
}));
|
||||
|
||||
describe('household setup page', () => {
|
||||
it('renders the form heading', () => {
|
||||
render(Page);
|
||||
expect(screen.getByRole('heading', { name: 'Haushalt benennen' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the household name input', () => {
|
||||
render(Page);
|
||||
expect(screen.getByLabelText('Haushaltsname')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the continue button', () => {
|
||||
render(Page);
|
||||
expect(screen.getByRole('button', { name: /weiter/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the ProgressSidebar with step 1 active', () => {
|
||||
render(Page);
|
||||
const step1 = screen.getByTestId('step-1');
|
||||
expect(step1).toHaveAttribute('aria-current', 'step');
|
||||
});
|
||||
|
||||
it('renders steps 2 and 3 as future steps', () => {
|
||||
render(Page);
|
||||
expect(screen.getByTestId('step-2')).not.toHaveAttribute('aria-current');
|
||||
expect(screen.getByTestId('step-3')).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
it('does not render app navigation chrome', () => {
|
||||
render(Page);
|
||||
// No nav links like Planer or Rezepte (those are app shell nav items)
|
||||
expect(screen.queryByText('Planer')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Rezepte')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sets the page title', () => {
|
||||
render(Page);
|
||||
expect(document.title).toBe('Haushalt einrichten — Mealplan');
|
||||
});
|
||||
|
||||
it('renders the mobile step indicator text', () => {
|
||||
render(Page);
|
||||
expect(screen.getByText(/schritt 1 von 3/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
28
frontend/src/routes/household/staples/+page.server.ts
Normal file
28
frontend/src/routes/household/staples/+page.server.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { apiClient } from '$lib/server/api';
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch, url }) => {
|
||||
const api = apiClient(fetch);
|
||||
|
||||
const [categoriesResult, ingredientsResult] = await Promise.all([
|
||||
api.GET('/v1/ingredient-categories'),
|
||||
api.GET('/v1/ingredients')
|
||||
]);
|
||||
|
||||
const rawCategories = categoriesResult.data ?? [];
|
||||
const rawIngredients = ingredientsResult.data ?? [];
|
||||
|
||||
const categories = rawCategories.map((cat) => ({
|
||||
id: cat.id!,
|
||||
name: cat.name!,
|
||||
ingredients: rawIngredients
|
||||
.filter((ing) => ing.category?.id === cat.id)
|
||||
.map((ing) => ({
|
||||
id: ing.id!,
|
||||
name: ing.name!,
|
||||
isStaple: ing.isStaple ?? false
|
||||
}))
|
||||
}));
|
||||
|
||||
return { categories, ctx: url.searchParams.get('ctx') };
|
||||
};
|
||||
51
frontend/src/routes/household/staples/+page.svelte
Normal file
51
frontend/src/routes/household/staples/+page.svelte
Normal file
@@ -0,0 +1,51 @@
|
||||
<script lang="ts">
|
||||
import ProgressSidebar from '$lib/components/ProgressSidebar.svelte';
|
||||
import StaplesManager from '$lib/onboarding/StaplesManager.svelte';
|
||||
|
||||
type Category = { id: string; name: string; ingredients: { id: string; name: string; isStaple: boolean }[] };
|
||||
|
||||
let { data }: { data: { categories: Category[]; ctx: string | null } } = $props();
|
||||
|
||||
const isOnboarding = $derived(data.ctx === 'onboarding');
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Vorräte einrichten — Mealplan</title>
|
||||
</svelte:head>
|
||||
|
||||
{#if isOnboarding}
|
||||
<div class="flex min-h-screen bg-[var(--color-page)]">
|
||||
<!-- Desktop sidebar -->
|
||||
<aside class="hidden md:flex w-[300px] flex-shrink-0 flex-col bg-[var(--color-surface)] border-r border-[var(--color-border)] p-[40px_28px]">
|
||||
<ProgressSidebar currentStep={2} />
|
||||
</aside>
|
||||
|
||||
<!-- Main area -->
|
||||
<main class="flex flex-1 flex-col">
|
||||
<!-- Mobile step indicator -->
|
||||
<p class="md:hidden px-6 pt-6 text-sm text-[var(--color-text-muted)]">Schritt 2 von 3</p>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="flex-1 p-6">
|
||||
<StaplesManager categories={data.categories} context="onboarding" />
|
||||
</div>
|
||||
|
||||
<!-- Footer navigation -->
|
||||
<div class="flex justify-between p-6">
|
||||
<a
|
||||
href="/planner"
|
||||
class="font-sans text-[13px] font-medium tracking-[0.04em] text-[var(--color-text-muted)] hover:text-[var(--color-text)]"
|
||||
>Überspringen</a>
|
||||
<a
|
||||
href="/household/invite"
|
||||
class="font-sans text-[13px] font-medium tracking-[0.04em] rounded-[var(--radius-md)] bg-[var(--green-dark)] px-[24px] py-[12px] text-white"
|
||||
>Weiter</a>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex min-h-screen flex-col bg-[var(--color-page)]">
|
||||
<h1 class="mb-[8px] font-[var(--font-display)] text-[18px] font-medium md:text-[28px] text-[var(--color-text)]">Vorräte</h1>
|
||||
<StaplesManager categories={data.categories} context="settings" />
|
||||
</div>
|
||||
{/if}
|
||||
33
frontend/src/routes/household/staples/+server.ts
Normal file
33
frontend/src/routes/household/staples/+server.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { apiClient } from '$lib/server/api';
|
||||
|
||||
export const PATCH: RequestHandler = async ({ request, fetch, locals }) => {
|
||||
if (locals.benutzer?.rolle !== 'planer') {
|
||||
return json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { id, isStaple } = body;
|
||||
|
||||
if (!id) {
|
||||
return json({ error: 'id is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (typeof isStaple !== 'boolean') {
|
||||
return json({ error: 'isStaple must be a boolean' }, { status: 400 });
|
||||
}
|
||||
|
||||
const api = apiClient(fetch);
|
||||
const { error } = await api.PATCH('/v1/ingredients/{id}', {
|
||||
params: { path: { id } },
|
||||
body: { isStaple }
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const status = (error as { status?: number }).status ?? 500;
|
||||
return json({ error: 'Failed to update ingredient' }, { status });
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
};
|
||||
107
frontend/src/routes/household/staples/page.server.test.ts
Normal file
107
frontend/src/routes/household/staples/page.server.test.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('$env/dynamic/private', () => ({
|
||||
env: { BACKEND_URL: 'http://localhost:8080' }
|
||||
}));
|
||||
|
||||
const mockGet = vi.fn();
|
||||
vi.mock('$lib/server/api', () => ({
|
||||
apiClient: () => ({ GET: mockGet })
|
||||
}));
|
||||
|
||||
const mockCategories = [
|
||||
{ id: 'cat-1', name: 'Öle & Fette' },
|
||||
{ id: 'cat-2', name: 'Gewürze' }
|
||||
];
|
||||
|
||||
const mockIngredients = [
|
||||
{ id: 'ing-1', name: 'Olivenöl', isStaple: true, category: { id: 'cat-1', name: 'Öle & Fette' } },
|
||||
{ id: 'ing-2', name: 'Butter', isStaple: false, category: { id: 'cat-1', name: 'Öle & Fette' } },
|
||||
{ id: 'ing-3', name: 'Salz', isStaple: true, category: { id: 'cat-2', name: 'Gewürze' } }
|
||||
];
|
||||
|
||||
describe('household staples page — load', () => {
|
||||
let load: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockGet.mockReset();
|
||||
vi.resetModules();
|
||||
const mod = await import('./+page.server');
|
||||
load = mod.load;
|
||||
});
|
||||
|
||||
function mockApiResponses() {
|
||||
mockGet.mockImplementation((path: string) => {
|
||||
if (path === '/v1/ingredient-categories') {
|
||||
return Promise.resolve({ data: mockCategories, error: undefined });
|
||||
}
|
||||
if (path === '/v1/ingredients') {
|
||||
return Promise.resolve({ data: mockIngredients, error: undefined });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('passes ctx from url searchParams into returned data', async () => {
|
||||
mockApiResponses();
|
||||
const url = new URL('http://localhost/household/staples?ctx=onboarding');
|
||||
const result = await load({ fetch: vi.fn(), url } as any);
|
||||
expect(result.ctx).toBe('onboarding');
|
||||
});
|
||||
|
||||
it('returns ctx as null when no ctx param is present', async () => {
|
||||
mockApiResponses();
|
||||
const url = new URL('http://localhost/household/staples');
|
||||
const result = await load({ fetch: vi.fn(), url } as any);
|
||||
expect(result.ctx).toBeNull();
|
||||
});
|
||||
|
||||
it('fetches both categories and ingredients in parallel', async () => {
|
||||
mockApiResponses();
|
||||
await load({ fetch: vi.fn(), url: new URL('http://localhost/household/staples') } as any);
|
||||
|
||||
const calls = mockGet.mock.calls.map((c) => c[0]);
|
||||
expect(calls).toContain('/v1/ingredient-categories');
|
||||
expect(calls).toContain('/v1/ingredients');
|
||||
});
|
||||
|
||||
it('groups ingredients by category id', async () => {
|
||||
mockApiResponses();
|
||||
const result = await load({ fetch: vi.fn(), url: new URL('http://localhost/household/staples') } as any);
|
||||
|
||||
expect(result.categories).toHaveLength(2);
|
||||
const oele = result.categories.find((c: any) => c.id === 'cat-1');
|
||||
expect(oele.ingredients).toHaveLength(2);
|
||||
expect(oele.ingredients[0].name).toBe('Olivenöl');
|
||||
});
|
||||
|
||||
it('preserves isStaple flag on each ingredient', async () => {
|
||||
mockApiResponses();
|
||||
const result = await load({ fetch: vi.fn(), url: new URL('http://localhost/household/staples') } as any);
|
||||
|
||||
const oele = result.categories.find((c: any) => c.id === 'cat-1');
|
||||
expect(oele.ingredients.find((i: any) => i.name === 'Olivenöl').isStaple).toBe(true);
|
||||
expect(oele.ingredients.find((i: any) => i.name === 'Butter').isStaple).toBe(false);
|
||||
});
|
||||
|
||||
it('categories without ingredients are included with empty array', async () => {
|
||||
mockGet.mockImplementation((path: string) => {
|
||||
if (path === '/v1/ingredient-categories') {
|
||||
return Promise.resolve({ data: [...mockCategories, { id: 'cat-3', name: 'Leer' }], error: undefined });
|
||||
}
|
||||
if (path === '/v1/ingredients') {
|
||||
return Promise.resolve({ data: mockIngredients, error: undefined });
|
||||
}
|
||||
});
|
||||
|
||||
const result = await load({ fetch: vi.fn(), url: new URL('http://localhost/household/staples') } as any);
|
||||
const leer = result.categories.find((c: any) => c.id === 'cat-3');
|
||||
expect(leer).toBeDefined();
|
||||
expect(leer.ingredients).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns empty categories when API fails', async () => {
|
||||
mockGet.mockResolvedValue({ data: undefined, error: { status: 500 } });
|
||||
const result = await load({ fetch: vi.fn(), url: new URL('http://localhost/household/staples') } as any);
|
||||
expect(result.categories).toEqual([]);
|
||||
});
|
||||
});
|
||||
82
frontend/src/routes/household/staples/page.test.ts
Normal file
82
frontend/src/routes/household/staples/page.test.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
const mockCategories = [
|
||||
{
|
||||
id: 'cat-1',
|
||||
name: 'Öle & Fette',
|
||||
ingredients: [
|
||||
{ id: 'ing-1', name: 'Olivenöl', isStaple: true },
|
||||
{ id: 'ing-2', name: 'Butter', isStaple: false }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
describe('staples page — onboarding context (?ctx=onboarding)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('renders ProgressSidebar with step 2 active', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: 'onboarding' } } });
|
||||
expect(screen.getByTestId('step-2')).toHaveAttribute('aria-current', 'step');
|
||||
});
|
||||
|
||||
it('renders Continue button linking to /household/invite', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: 'onboarding' } } });
|
||||
const continueLink = screen.getByRole('link', { name: /weiter/i });
|
||||
expect(continueLink).toHaveAttribute('href', '/household/invite');
|
||||
});
|
||||
|
||||
it('renders Skip button linking to /planner', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: 'onboarding' } } });
|
||||
const skipLink = screen.getByRole('link', { name: /überspringen/i });
|
||||
expect(skipLink).toHaveAttribute('href', '/planner');
|
||||
});
|
||||
|
||||
it('renders the StaplesManager with categories', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: 'onboarding' } } });
|
||||
expect(screen.getByText('Öle & Fette')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sets the page title', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: 'onboarding' } } });
|
||||
expect(document.title).toBe('Vorräte einrichten — Mealplan');
|
||||
});
|
||||
|
||||
it('renders mobile step indicator Schritt 2 von 3', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: 'onboarding' } } });
|
||||
expect(screen.getByText(/schritt 2 von 3/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('staples page — settings context (no ctx)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('does not render ProgressSidebar', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: null } } });
|
||||
expect(screen.queryByTestId('step-1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render Continue or Skip buttons', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: null } } });
|
||||
expect(screen.queryByRole('link', { name: /weiter/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: /überspringen/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a settings heading', () => {
|
||||
render(Page, { props: { data: { categories: mockCategories, ctx: null } } });
|
||||
expect(screen.getByRole('heading', { name: /vorräte/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
93
frontend/src/routes/household/staples/server.test.ts
Normal file
93
frontend/src/routes/household/staples/server.test.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('$env/dynamic/private', () => ({
|
||||
env: { BACKEND_URL: 'http://localhost:8080' }
|
||||
}));
|
||||
|
||||
const mockPatch = vi.fn();
|
||||
vi.mock('$lib/server/api', () => ({
|
||||
apiClient: () => ({ PATCH: mockPatch })
|
||||
}));
|
||||
|
||||
describe('household staples PATCH handler', () => {
|
||||
let PATCH: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockPatch.mockReset();
|
||||
const mod = await import('./+server');
|
||||
PATCH = mod.PATCH;
|
||||
});
|
||||
|
||||
function createRequest(body: object, rolle: 'planer' | 'mitglied' = 'planer') {
|
||||
return {
|
||||
request: {
|
||||
json: () => Promise.resolve(body)
|
||||
},
|
||||
fetch: vi.fn(),
|
||||
locals: { benutzer: { rolle } }
|
||||
} as any;
|
||||
}
|
||||
|
||||
it('calls backend PATCH /v1/ingredients/{id} with isStaple', async () => {
|
||||
mockPatch.mockResolvedValue({ data: {}, error: undefined });
|
||||
|
||||
await PATCH(createRequest({ id: 'ing-1', isStaple: true }));
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith('/v1/ingredients/{id}', {
|
||||
params: { path: { id: 'ing-1' } },
|
||||
body: { isStaple: true }
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 204 on success', async () => {
|
||||
mockPatch.mockResolvedValue({ data: {}, error: undefined });
|
||||
|
||||
const response = await PATCH(createRequest({ id: 'ing-1', isStaple: true }));
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
});
|
||||
|
||||
it('returns 500 when backend returns a 500 error', async () => {
|
||||
mockPatch.mockResolvedValue({ data: undefined, error: { status: 500, message: 'error' } });
|
||||
|
||||
const response = await PATCH(createRequest({ id: 'ing-1', isStaple: false }));
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
});
|
||||
|
||||
it('forwards backend 404 status when ingredient not found', async () => {
|
||||
mockPatch.mockResolvedValue({ data: undefined, error: { status: 404 } });
|
||||
|
||||
const response = await PATCH(createRequest({ id: 'ing-1', isStaple: false }));
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
});
|
||||
|
||||
it('returns 400 when id is missing', async () => {
|
||||
const response = await PATCH(createRequest({ isStaple: true }));
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(mockPatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 when isStaple is missing', async () => {
|
||||
const response = await PATCH(createRequest({ id: 'ing-1' }));
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(mockPatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 403 when caller has mitglied role', async () => {
|
||||
const response = await PATCH(createRequest({ id: 'ing-1', isStaple: true }, 'mitglied'));
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(mockPatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 when isStaple is not a boolean', async () => {
|
||||
const response = await PATCH(createRequest({ id: 'ing-1', isStaple: 'yes' }));
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(mockPatch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
1
frontend/src/test-setup.ts
Normal file
1
frontend/src/test-setup.ts
Normal file
@@ -0,0 +1 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
Reference in New Issue
Block a user