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

+1
View File
@@ -8,6 +8,7 @@ export * from './nutrition/tdee.js';
export * from './nutrition/types.js';
export * from './planner/macros.js';
export * from './planner/matchmaking.js';
export * from './planner/phase-progression.js';
export * from './planner/types.js';
export * from './preferences/training.js';
export * from './profile/diet-history.js';
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest';
import {
currentPhase2Week,
freeMealKcalAdjustment,
isRecipeAllowedForPhaseWeek,
weeksSince,
} from './phase-progression.js';
describe('weeksSince / currentPhase2Week', () => {
it('oggi → 0 settimane intere; current = 1', () => {
const today = new Date();
expect(weeksSince(today)).toBe(0);
expect(currentPhase2Week(today)).toBe(1);
});
it('14 giorni fa → 2 settimane; current = 3', () => {
const start = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000);
expect(weeksSince(start)).toBe(2);
expect(currentPhase2Week(start)).toBe(3);
});
it('null → settimana 1', () => {
expect(currentPhase2Week(null)).toBe(1);
expect(currentPhase2Week(undefined)).toBe(1);
});
});
describe('isRecipeAllowedForPhaseWeek', () => {
const lentils = { phase2Week: 3 };
const oliveOil = { phase2Week: null };
const apple = { phase2Week: 5 };
it('Fase 1 → tutto permesso', () => {
expect(isRecipeAllowedForPhaseWeek([lentils, apple], 1, 1)).toBe(true);
});
it('Fase 3 → tutto permesso', () => {
expect(isRecipeAllowedForPhaseWeek([lentils, apple], 3, 1)).toBe(true);
});
it('Fase 2 settimana 2 → ricetta con lenticchie (week 3) bloccata', () => {
expect(isRecipeAllowedForPhaseWeek([lentils, oliveOil], 2, 2)).toBe(false);
});
it('Fase 2 settimana 3 → ricetta con lenticchie sblocca', () => {
expect(isRecipeAllowedForPhaseWeek([lentils, oliveOil], 2, 3)).toBe(true);
});
it('Fase 2 settimana 4 → mela ancora bloccata (week 5)', () => {
expect(isRecipeAllowedForPhaseWeek([apple], 2, 4)).toBe(false);
});
});
describe('freeMealKcalAdjustment', () => {
it('free meal a 750 invece di 500 → spalma -250 sui rimanenti', () => {
const adj = freeMealKcalAdjustment({
freeMealKcal: 750,
originalSlotKcal: 500,
remainingSlots: 5,
});
// delta = 250, perSlot = 50, adjustment = -50
expect(adj).toBe(-50);
});
it('cap di sicurezza a -200 kcal/pasto', () => {
const adj = freeMealKcalAdjustment({
freeMealKcal: 2000,
originalSlotKcal: 500,
remainingSlots: 3,
});
// perSlot = 500, ma cap -200
expect(adj).toBe(-200);
});
it('free meal più piccolo del normale → leggero +', () => {
const adj = freeMealKcalAdjustment({
freeMealKcal: 300,
originalSlotKcal: 500,
remainingSlots: 4,
});
// delta = -200, perSlot = -50, adjustment = +50 (cap)
expect(adj).toBe(50);
});
it('remainingSlots 0 → 0', () => {
expect(
freeMealKcalAdjustment({ freeMealKcal: 750, originalSlotKcal: 500, remainingSlots: 0 }),
).toBe(0);
});
});
@@ -0,0 +1,77 @@
// PRD §5.1 — Reintroduzione progressiva degli alimenti in Fase 2.
//
// In Fase 2 (TRANSITION) alcuni ingredienti vengono reintrodotti gradualmente
// (legumi → cereali integrali → frutta più zuccherina). Ciascun `Ingredient`
// ha un `phase2Week` che indica la settimana minima di Fase 2 dalla quale
// è disponibile. NULL = sempre.
export interface IngredientPhase2 {
phase2Week: number | null | undefined;
}
export function weeksSince(start: Date | string, now: Date = new Date()): number {
const startMs = typeof start === 'string' ? new Date(start).getTime() : start.getTime();
const elapsed = Math.max(0, now.getTime() - startMs);
return Math.floor(elapsed / (7 * 24 * 60 * 60 * 1000));
}
/**
* Settimana corrente della Fase 2. 1 = prima settimana.
* Se `phase2StartedAt` è null o nel futuro, ritorna 1.
*/
export function currentPhase2Week(phase2StartedAt: Date | string | null | undefined): number {
if (!phase2StartedAt) return 1;
return Math.max(1, weeksSince(phase2StartedAt) + 1);
}
/**
* Vero se tutti gli ingredienti della ricetta sono disponibili nella
* settimana di fase 2 corrente (o se non siamo in fase 2).
*
* Il filtro è hard: ricetta con almeno un ingrediente non ancora reintrodotto
* viene esclusa. Per la Fase 1 (INTENSIVE) il filtro non si applica perché
* `Recipe.phases` esclude già le ricette non keto-compatibili.
*/
export function isRecipeAllowedForPhaseWeek(
ingredients: ReadonlyArray<IngredientPhase2>,
phase: 1 | 2 | 3,
weekInPhase: number,
): boolean {
if (phase !== 2) return true;
for (const i of ingredients) {
if (i.phase2Week != null && i.phase2Week > weekInPhase) return false;
}
return true;
}
// PRD §5.1 — Compensazione per Free Meal in Fase 3.
//
// L'utente segna uno slot della settimana come "pasto libero" (es. cena al
// ristorante). Il free meal "pesa" un valore stimato (default 750 kcal) e
// gli altri pasti della settimana vengono ricalibrati per restare nel budget
// settimanale.
export const FREE_MEAL_DEFAULT_KCAL = 750;
/**
* Spalma la differenza fra freeMealKcal e il target normale del pasto sui
* pasti rimanenti della stessa settimana, fino a un limite di sicurezza.
*
* delta = freeMealKcal − originalSlotKcal
* adjustment per pasto = clamp(delta / remainingSlots, -200, +50)
*
* Il negativo (riduzione) è limitato a 200 kcal/pasto per non rendere i
* pasti troppo magri. La compensazione è morbida: il free meal *non* viene
* mai compensato al 100% del suo extra.
*/
export function freeMealKcalAdjustment(args: {
freeMealKcal: number;
originalSlotKcal: number;
remainingSlots: number;
}): number {
const { freeMealKcal, originalSlotKcal, remainingSlots } = args;
if (remainingSlots <= 0) return 0;
const delta = freeMealKcal - originalSlotKcal;
const perSlot = delta / remainingSlots;
return Math.max(-200, Math.min(50, -perSlot));
}