feat: catalogo+30, varianti, sostituti, reintroduzione Fase 2, free meal Fase 3 (PRD §5.1)

Quattro completamenti del PRD §5.1: catalogo, varianti/sostituti, fase 2,
free meal.

Catalogo ricette 16 → 46
- seed-recipes.ts: +30 ricette italiane keto bilanciate
  (8 colazione · 8 pranzo · 6 spuntino · 8 cena)
- seed-ingredients.ts: 33 → 55 ingredienti
  (verdura/carne/pesce/latticini/condimenti + categorie nuove `legumi` e
  `cereali` per Fase 2)
- seed.ts: ora fa upsert anche degli ingredienti pre-esistenti per
  propagare campi nuovi (es. phase2Week)

Varianti + sostituti
- Recipe.variants Json (array { name, description, kcalDelta? })
- RecipeIngredient.substitutes String[]
- /recipes/[id]: nuova sezione "Varianti suggerite" + riga "Sostituzioni:"
  sotto ogni ingrediente quando presenti

Reintroduzione progressiva Fase 2
- Ingredient.phase2Week (settimana minima di reintroduzione, NULL=sempre)
- User.phase2StartedAt: settato automaticamente quando si passa a TRANSITION
- @ketopath/shared/planner/phase-progression: currentPhase2Week,
  isRecipeAllowedForPhaseWeek, weeksSince
- plan.routes filtra fuori le ricette con ingredienti non ancora reintrodotti
- POST /me/profile/phase per avanzare di fase (idempotente sul timestamp)
- 12 unit test su phase-progression
- Esempi seed: lenticchie phase2Week=3, ceci=4, mela=5, pera=6, quinoa=7

Free Meal pianificato Fase 3
- MealSlot.isFreeMeal Boolean (default false)
- POST /me/meal-plans/slots/:id/free-meal toggle, valido solo in MAINTENANCE
- @ketopath/shared/planner/phase-progression: freeMealKcalAdjustment
  (compensazione clamp -200/+50 kcal per pasto sui rimanenti)
- /plan: bottone ☆ in ogni SlotCard quando phase=MAINTENANCE; lo slot
  marcato come pasto libero rende "Pasto libero pianificato" + ~750 kcal
  stimate; macro tracker ne tiene conto

Indicatori di fase nel piano
- /plan ora include currentPhase + phase2Week dalla API
- Header del piano: "Settimana N di Fase 2" o "Mantenimento — Fase 3"

i18n: namespaces Plan + Recipe arricchiti

Schema migration 20260429XXXXXX_add_meal_plan_extras.

66/66 unit test verdi (12 nuovi). Smoke verificato live: API ritorna
correctly i campi nuovi, UI rende badge fase, bottoni ☆/↻, free-meal slot.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
lucianoandClaude Opus 4.7 committed 2026-04-29 23:18:47 +02:00
1 parent 2c11b73703
commit bda96a3550
15 files changed
+1288 -44

No files matched your search

+60 -3
View File
@@ -5,8 +5,10 @@ import {
calculateBmrKatchMcArdle,
calculateTdee,
computeDailyKcalTarget,
currentPhase2Week,
extraKcalForSession,
hasExcludingCondition,
isRecipeAllowedForPhaseWeek,
isTrainingDay,
macrosForPhase,
matchMeals,
@@ -71,7 +73,9 @@ export const planRoutes: FastifyPluginAsync = async (fastify) => {
phases: true,
prepMinutes: true,
ingredients: {
select: { ingredient: { select: { exclusionGroups: true } } },
select: {
ingredient: { select: { exclusionGroups: true, phase2Week: true } },
},
},
},
});
@@ -79,7 +83,20 @@ export const planRoutes: FastifyPluginAsync = async (fastify) => {
return reply.code(409).send({ error: 'recipe_catalog_empty' });
}
const candidates: RecipeCandidate[] = recipes.map((r) => {
// PRD §5.1 — Reintroduzione progressiva: in fase 2 filtriamo le ricette
// che contengono ingredienti non ancora reintrodotti per la settimana
// corrente di fase 2.
const phaseIntForFilter = phaseToInt(profile.currentPhase);
const phase2WeekForFilter = currentPhase2Week(profile.user.phase2StartedAt);
const allowedRecipes = recipes.filter((r) =>
isRecipeAllowedForPhaseWeek(
r.ingredients.map((ri) => ({ phase2Week: ri.ingredient.phase2Week })),
phaseIntForFilter,
phase2WeekForFilter,
),
);
const candidates: RecipeCandidate[] = allowedRecipes.map((r) => {
const tags = new Set<string>();
for (const ri of r.ingredients) {
for (const g of ri.ingredient.exclusionGroups) tags.add(g);
@@ -266,6 +283,31 @@ export const planRoutes: FastifyPluginAsync = async (fastify) => {
},
);
// PRD §5.1 — toggle "pasto libero". Disponibile solo in Fase 3.
fastify.post(
'/me/meal-plans/slots/:slotId/free-meal',
{ preHandler: requireAuth() },
async (request, reply) => {
const slotId = (request.params as { slotId: string }).slotId;
const userId = request.user!.id;
const slot = await fastify.prisma.mealSlot.findFirst({
where: { id: slotId, plan: { userId } },
include: { plan: true },
});
if (!slot) return reply.code(404).send({ error: 'slot_not_found' });
const profile = await fastify.prisma.profile.findUnique({ where: { userId } });
if (!profile) return reply.code(409).send({ error: 'profile_required' });
if (profile.currentPhase !== 'MAINTENANCE') {
return reply.code(409).send({ error: 'free_meal_phase3_only' });
}
const updated = await fastify.prisma.mealSlot.update({
where: { id: slotId },
data: { isFreeMeal: !slot.isFreeMeal },
});
return { slot: { id: updated.id, isFreeMeal: updated.isFreeMeal } };
},
);
// PRD §5.1 — rigenera UN solo slot: ricalcola le top5 ricette tenendo
// conto dei pasti del giorno già scelti (coerenza dei macros).
fastify.post(
@@ -456,7 +498,7 @@ export const planRoutes: FastifyPluginAsync = async (fastify) => {
fastify.get('/me/meal-plans/current', { preHandler: requireAuth() }, async (request, reply) => {
const userId = request.user!.id;
const [plan, prefs] = await Promise.all([
const [plan, prefs, profileForPhase, userForPhase2] = await Promise.all([
fastify.prisma.mealPlan.findFirst({
where: { userId, status: 'ACTIVE' },
orderBy: { weekStart: 'desc' },
@@ -494,14 +536,29 @@ export const planRoutes: FastifyPluginAsync = async (fastify) => {
where: { userId },
select: { fastingProtocol: true },
}),
fastify.prisma.profile.findUnique({
where: { userId },
select: { currentPhase: true },
}),
fastify.prisma.user.findUnique({
where: { id: userId },
select: { phase2StartedAt: true },
}),
]);
if (!plan) return reply.code(404).send({ error: 'plan_not_found' });
const currentPhase = profileForPhase?.currentPhase ?? null;
const phase2Week =
currentPhase === 'TRANSITION'
? currentPhase2Week(userForPhase2?.phase2StartedAt ?? null)
: null;
return {
plan: {
id: plan.id,
weekStart: plan.weekStart.toISOString().slice(0, 10),
slots: plan.slots,
fastingProtocol: prefs?.fastingProtocol ?? null,
currentPhase,
phase2Week,
},
};
});
@@ -153,6 +153,42 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
return { profile: serialize(profile) };
});
// PRD §5.1 — avanzamento di fase. Quando l'utente passa da INTENSIVE a
// TRANSITION (Fase 2), salviamo automaticamente phase2StartedAt sull'utente
// così la reintroduzione progressiva degli alimenti funziona dalla settimana
// corretta.
fastify.post('/me/profile/phase', { preHandler: requireAuth() }, async (request, reply) => {
const body = request.body as { phase?: unknown };
const phase = body.phase;
if (phase !== 'INTENSIVE' && phase !== 'TRANSITION' && phase !== 'MAINTENANCE') {
return reply.code(400).send({ error: 'invalid_phase' });
}
const userId = request.user!.id;
const profile = await fastify.prisma.profile.findUnique({ where: { userId } });
if (!profile) return reply.code(404).send({ error: 'profile_not_found' });
const transitioning = profile.currentPhase !== 'TRANSITION' && phase === 'TRANSITION';
await fastify.prisma.profile.update({
where: { userId },
data: { currentPhase: phase },
});
if (transitioning) {
// Setta phase2StartedAt solo se non già impostato (idempotente).
const user = await fastify.prisma.user.findUnique({
where: { id: userId },
select: { phase2StartedAt: true },
});
if (!user?.phase2StartedAt) {
await fastify.prisma.user.update({
where: { id: userId },
data: { phase2StartedAt: new Date() },
});
}
}
return { phase };
});
// PATCH dedicato per le condizioni mediche: l'onboarding lo usa per salvare
// solo questo delta senza richiedere tutti i campi obbligatori del PUT.
fastify.patch('/me/profile/conditions', { preHandler: requireAuth() }, async (request, reply) => {
+8
View File
@@ -409,6 +409,8 @@
"phasesAll": "Tutte le fasi",
"phasesSome": "Fase {phases}",
"notesChef": "Nota dello chef",
"variantsTitle": "Varianti suggerite",
"substitutesPrefix": "Sostituzioni:",
"difficultyLabel": {
"FACILE": "Facile",
"MEDIA": "Media",
@@ -433,6 +435,12 @@
"hideAlternatives": "Nascondi",
"swap": "Scegli",
"regenerateSlot": "Rigenera questo pasto",
"freeMealMark": "Segna come pasto libero",
"freeMealUndo": "Torna a una ricetta keto",
"freeMealLabel": "Pasto libero pianificato",
"phase2Eyebrow": "Reintroduzione",
"phase2Week": "Settimana {n} di Fase 2",
"phase3Eyebrow": "Mantenimento — Fase 3",
"dayTotal": "{kcal} kcal totali",
"window": "Finestra alimentare",
"avgKcal": "Media kcal/giorno",
+17
View File
@@ -21,6 +21,7 @@ export interface PlanSlot {
meal: 'COLAZIONE' | 'PRANZO' | 'SPUNTINO' | 'CENA';
recipeId: string | null;
status: string;
isFreeMeal: boolean;
selected: SlotRecipe | null;
alternatives: SlotRecipe[];
}
@@ -37,6 +38,8 @@ export interface CurrentPlan {
| 'ESE_24'
| 'FIVE_TWO'
| null;
currentPhase: 'INTENSIVE' | 'TRANSITION' | 'MAINTENANCE' | null;
phase2Week: number | null;
}
function cookieHeader(): string {
@@ -85,6 +88,20 @@ export async function regenerateSlot(slotId: string): Promise<SwapResult> {
return { ok: true };
}
export async function toggleFreeMeal(slotId: string): Promise<SwapResult> {
const res = await fetch(`${API_URL}/me/meal-plans/slots/${slotId}/free-meal`, {
method: 'POST',
headers: { cookie: cookieHeader() },
cache: 'no-store',
});
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
return { ok: false, error: body.error ?? `api_error_${res.status}` };
}
revalidatePath('/plan');
return { ok: true };
}
export async function swapSlotRecipe(slotId: string, recipeId: string): Promise<SwapResult> {
const res = await fetch(`${API_URL}/me/meal-plans/slots/${slotId}`, {
method: 'PATCH',
+12
View File
@@ -70,6 +70,18 @@ function PlanPageContent({ plan }: { plan: Awaited<ReturnType<typeof fetchCurren
</span>
</p>
) : null}
{plan?.currentPhase === 'TRANSITION' && plan.phase2Week ? (
<p className="animate-fade-up mt-3 [animation-delay:330ms]">
<span className="editorial-eyebrow">{t('phase2Eyebrow')}</span>{' '}
<span className="font-display text-oliva ml-2 text-base italic">
{t('phase2Week', { n: plan.phase2Week })}
</span>
</p>
) : plan?.currentPhase === 'MAINTENANCE' ? (
<p className="animate-fade-up mt-3 [animation-delay:330ms]">
<span className="editorial-eyebrow">{t('phase3Eyebrow')}</span>
</p>
) : null}
</div>
<div className="animate-fade-up flex flex-col items-stretch gap-3 [animation-delay:360ms] md:col-span-4 md:items-end">
<form action={regeneratePlan}>
+78 -15
View File
@@ -6,7 +6,13 @@ import { useState, useTransition } from 'react';
import { Button } from '@/components/ui/button';
import { regenerateSlot, swapSlotRecipe, type CurrentPlan, type PlanSlot } from './actions';
import {
regenerateSlot,
swapSlotRecipe,
toggleFreeMeal,
type CurrentPlan,
type PlanSlot,
} from './actions';
const MEAL_ORDER: PlanSlot['meal'][] = ['COLAZIONE', 'PRANZO', 'SPUNTINO', 'CENA'];
const DAY_KEYS = [
@@ -28,6 +34,17 @@ function aggregateMacros(slots: PlanSlot[]): {
} {
return slots.reduce(
(acc, s) => {
// Per i free meal usiamo una stima fissa kcal e azzeriamo i macros
// (non li conosciamo davvero) — il PRD parla di "compensazione" non di
// tracking puntuale del pasto libero.
if (s.isFreeMeal) {
return {
kcal: acc.kcal + FREE_MEAL_DEFAULT_KCAL,
proteinG: acc.proteinG,
fatG: acc.fatG,
netCarbG: acc.netCarbG,
};
}
if (!s.selected) return acc;
return {
kcal: acc.kcal + s.selected.kcal,
@@ -40,6 +57,8 @@ function aggregateMacros(slots: PlanSlot[]): {
);
}
const FREE_MEAL_DEFAULT_KCAL = 750;
export function PlanWeek({ plan }: { plan: CurrentPlan }) {
const t = useTranslations('Plan');
@@ -49,6 +68,7 @@ export function PlanWeek({ plan }: { plan: CurrentPlan }) {
byDay.get(slot.dayOfWeek)!.push(slot);
}
const isPhase3 = plan.currentPhase === 'MAINTENANCE';
const weekTotals = aggregateMacros(plan.slots);
const activeDays = Array.from(byDay.values()).filter((s) => s.length > 0).length;
const weekAvg =
@@ -114,7 +134,7 @@ export function PlanWeek({ plan }: { plan: CurrentPlan }) {
) : (
<div className="divide-ink/10 grid grid-cols-1 divide-y sm:grid-cols-2 sm:gap-x-8 sm:divide-y-0 lg:grid-cols-4 lg:gap-x-6">
{slots.map((slot, slotIdx) => (
<SlotCard key={slot.id} slot={slot} index={slotIdx} />
<SlotCard key={slot.id} slot={slot} index={slotIdx} canFreeMeal={isPhase3} />
))}
</div>
)}
@@ -127,7 +147,15 @@ export function PlanWeek({ plan }: { plan: CurrentPlan }) {
const MEAL_ROMAN = ['I', 'II', 'III', 'IV'];
function SlotCard({ slot, index }: { slot: PlanSlot; index: number }) {
function SlotCard({
slot,
index,
canFreeMeal,
}: {
slot: PlanSlot;
index: number;
canFreeMeal: boolean;
}) {
const t = useTranslations('Plan');
const [open, setOpen] = useState(false);
const [pending, startTransition] = useTransition();
@@ -146,6 +174,13 @@ function SlotCard({ slot, index }: { slot: PlanSlot; index: number }) {
});
}
function freeMeal() {
startTransition(async () => {
await toggleFreeMeal(slot.id);
setOpen(false);
});
}
return (
<article className="group relative flex flex-col gap-3 py-5 sm:py-2">
<header className="flex items-baseline justify-between gap-3">
@@ -155,18 +190,46 @@ function SlotCard({ slot, index }: { slot: PlanSlot; index: number }) {
</span>
<span>{t(`meals.${slot.meal}`)}</span>
</p>
<button
type="button"
onClick={regenerate}
disabled={pending}
aria-label={t('regenerateSlot')}
title={t('regenerateSlot')}
className="text-ink-dim hover:text-pomodoro font-mono text-xs leading-none transition-colors disabled:opacity-40"
>
↻
</button>
<div className="flex items-center gap-2">
{canFreeMeal ? (
<button
type="button"
onClick={freeMeal}
disabled={pending}
aria-label={slot.isFreeMeal ? t('freeMealUndo') : t('freeMealMark')}
title={slot.isFreeMeal ? t('freeMealUndo') : t('freeMealMark')}
className={`font-mono text-xs leading-none transition-colors disabled:opacity-40 ${
slot.isFreeMeal ? 'text-pomodoro' : 'text-ink-dim hover:text-pomodoro'
}`}
>
☆
</button>
) : null}
{!slot.isFreeMeal ? (
<button
type="button"
onClick={regenerate}
disabled={pending}
aria-label={t('regenerateSlot')}
title={t('regenerateSlot')}
className="text-ink-dim hover:text-pomodoro font-mono text-xs leading-none transition-colors disabled:opacity-40"
>
↻
</button>
) : null}
</div>
</header>
{slot.selected ? (
{slot.isFreeMeal ? (
<>
<p className="font-display text-pomodoro text-lg font-medium italic leading-tight">
{t('freeMealLabel')}
</p>
<p className="text-ink-soft font-mono text-xs tracking-tight">
~{FREE_MEAL_DEFAULT_KCAL}{' '}
<span className="font-display text-[10px] italic">kcal stimate</span>
</p>
</>
) : slot.selected ? (
<Link
href={`/recipes/${slot.selected.id}`}
className="font-display text-ink decoration-pomodoro hover:decoration-ink text-lg font-medium leading-tight underline decoration-[1.5px] underline-offset-[5px] transition-colors"
@@ -176,7 +239,7 @@ function SlotCard({ slot, index }: { slot: PlanSlot; index: number }) {
) : (
<p className="font-display text-ink-soft text-lg italic leading-tight">{t('noRecipe')}</p>
)}
{slot.selected ? (
{!slot.isFreeMeal && slot.selected ? (
<p className="text-ink-soft font-mono text-xs tracking-tight">
{Math.round(slot.selected.kcal)}{' '}
<span className="font-display text-[10px] italic">kcal</span>
@@ -13,6 +13,13 @@ interface RecipeIngredientView {
category: string;
quantity: number;
unit: string;
substitutes: string[];
}
interface RecipeVariant {
name: string;
description: string;
kcalDelta?: number;
}
interface RecipeView {
@@ -29,6 +36,7 @@ interface RecipeView {
phases: number[];
notesChef: string | null;
ingredients: RecipeIngredientView[];
variants: RecipeVariant[];
}
export default async function RecipePage({
@@ -72,7 +80,9 @@ export default async function RecipePage({
category: ri.ingredient.category,
quantity: ri.quantity,
unit: ri.unit,
substitutes: ri.substitutes ?? [],
})),
variants: parseVariants(recipe.variants),
};
return <RecipeContent recipe={view} />;
@@ -80,6 +90,21 @@ export default async function RecipePage({
const ROMAN = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII'];
function parseVariants(value: unknown): RecipeVariant[] {
if (!Array.isArray(value)) return [];
return value
.filter((v): v is { name: string; description: string; kcalDelta?: number } => {
if (!v || typeof v !== 'object') return false;
const o = v as Record<string, unknown>;
return typeof o.name === 'string' && typeof o.description === 'string';
})
.map((v) => ({
name: v.name,
description: v.description,
...(typeof v.kcalDelta === 'number' ? { kcalDelta: v.kcalDelta } : {}),
}));
}
function RecipeContent({ recipe }: { recipe: RecipeView }) {
const t = useTranslations('Recipe');
const phasesAll = recipe.phases.length === 3;
@@ -149,6 +174,11 @@ function RecipeContent({ recipe }: { recipe: RecipeView }) {
<p className="text-ink-soft mt-1 font-mono text-[10px] uppercase tracking-widest">
{ing.category}
</p>
{ing.substitutes.length > 0 ? (
<p className="font-display text-ink-dim mt-1 text-xs italic leading-snug">
{t('substitutesPrefix')} {ing.substitutes.join(', ')}
</p>
) : null}
</div>
<span className="text-ink font-mono text-sm tabular-nums">
{formatQuantity(ing.quantity)} {ing.unit}
@@ -190,6 +220,33 @@ function RecipeContent({ recipe }: { recipe: RecipeView }) {
</aside>
) : null}
</section>
{recipe.variants.length > 0 ? (
<>
<div className="rule animate-rule-in my-12" />
<section className="space-y-6">
<p className="editorial-eyebrow">{t('variantsTitle')}</p>
<ul className="grid gap-6 sm:grid-cols-2">
{recipe.variants.map((v, i) => (
<li key={i} className="border-ink/15 border p-5">
<p className="font-display text-ink text-lg font-medium leading-tight">
{v.name}
</p>
<p className="font-display text-ink-soft mt-2 text-base italic leading-snug">
{v.description}
</p>
{v.kcalDelta != null ? (
<p className="text-ink-dim mt-2 font-mono text-[10px] uppercase tracking-widest">
{v.kcalDelta > 0 ? '+' : ''}
{v.kcalDelta} kcal
</p>
) : null}
</li>
))}
</ul>
</section>
</>
) : null}
</main>
<div className="rule-thick mt-16" />