feat: §6 Gruppo B residuo — pannello macros, esclusioni granulari, achievement

- Plan: pannello macros laterale "oggi" con consumati/pianificati vs target (kcal/P/F/C). Sticky su lg, in-flow su mobile. Profile/derived ora include kcalTarget e i macro target (BMR aggiustato per condizioni e diet history).
- Preferenze: nuova sezione "Ingredienti specifici da evitare" con ricerca debounced sul catalogo (cap 50). Schema Preferences.bannedIngredientIds + matchmaking che scarta ricette contenenti ingredient bandito (test unit).
- Achievement: tabella Achievement (userId+key unique), 4 traguardi iniziali (first_weigh_in, first_plan, first_fast_complete, ten_meals_consumed). Service idempotente eval+persist agganciato a 4 trigger (weight POST, plan POST, fast PATCH→COMPLETED, slot consumed). Push notification best-effort all'unlock. Pannello badge nel profilo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
lucianoandClaude Opus 4.7 committed 2026-05-06 15:45:30 +02:00
1 parent 3b895191f5
commit d17c5ef869
29 files changed
+1048 -86

No files matched your search

@@ -0,0 +1,53 @@
// PRD §6 — sistema achievement: tassonomia ufficiale.
// Le `key` sono stabili: una volta esposte agli utenti non si rinominano. Per
// dismettere un achievement, lasciare la chiave qui (così il record storico
// continua a risolversi) e rimuoverla dal set "attivi".
export type AchievementKey =
| 'first_weigh_in'
| 'first_plan'
| 'first_fast_complete'
| 'ten_meals_consumed';
export interface AchievementDefinition {
key: AchievementKey;
/** Etichetta corta da mostrare nel badge. */
title: string;
/** Una riga di descrizione di cosa serve per sbloccarlo. */
hint: string;
/** Categoria visiva — utile per raggruppare in UI. */
category: 'tracking' | 'plan' | 'fasting';
}
// Set ordinato per la visualizzazione in UI: i più "tutorial" prima.
export const ACHIEVEMENTS: ReadonlyArray<AchievementDefinition> = [
{
key: 'first_weigh_in',
title: 'Prima pesata',
hint: 'Hai registrato il tuo peso per la prima volta.',
category: 'tracking',
},
{
key: 'first_plan',
title: 'Primo piano',
hint: 'Hai generato il tuo primo piano settimanale.',
category: 'plan',
},
{
key: 'first_fast_complete',
title: 'Primo digiuno completato',
hint: 'Hai portato a termine la tua prima sessione di digiuno.',
category: 'fasting',
},
{
key: 'ten_meals_consumed',
title: 'Dieci pasti spuntati',
hint: 'Hai marcato come consumati 10 pasti dal tuo piano.',
category: 'plan',
},
];
export const ACHIEVEMENT_KEYS: ReadonlyArray<AchievementKey> = ACHIEVEMENTS.map((a) => a.key);
// Soglia singola per ten_meals_consumed — esposta come costante per l'eval.
export const TEN_MEALS_THRESHOLD = 10;
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest';
import { evaluateAchievements } from './evaluator.js';
describe('evaluateAchievements', () => {
it('returns nothing when all metrics are zero', () => {
expect(
evaluateAchievements({
weightEntryCount: 0,
planCount: 0,
completedFastCount: 0,
consumedMealCount: 0,
}),
).toEqual([]);
});
it('unlocks first-time achievements at threshold 1', () => {
expect(
evaluateAchievements({
weightEntryCount: 1,
planCount: 1,
completedFastCount: 1,
consumedMealCount: 0,
}),
).toEqual(['first_weigh_in', 'first_plan', 'first_fast_complete']);
});
it('unlocks ten_meals_consumed at exactly 10 consumed meals', () => {
const at9 = evaluateAchievements({
weightEntryCount: 0,
planCount: 0,
completedFastCount: 0,
consumedMealCount: 9,
});
expect(at9).not.toContain('ten_meals_consumed');
const at10 = evaluateAchievements({
weightEntryCount: 0,
planCount: 0,
completedFastCount: 0,
consumedMealCount: 10,
});
expect(at10).toContain('ten_meals_consumed');
});
});
@@ -0,0 +1,22 @@
// PRD §6 — eval puro degli achievement.
// Non tocca persistenza: prende metriche già misurate e ritorna le `key`
// che dovrebbero risultare sbloccate. Idempotente — l'API decide cosa
// scrivere a DB confrontando con gli already-unlocked.
import { TEN_MEALS_THRESHOLD, type AchievementKey } from './definitions.js';
export interface AchievementMetrics {
weightEntryCount: number;
planCount: number;
completedFastCount: number;
consumedMealCount: number;
}
export function evaluateAchievements(metrics: AchievementMetrics): AchievementKey[] {
const unlocked: AchievementKey[] = [];
if (metrics.weightEntryCount >= 1) unlocked.push('first_weigh_in');
if (metrics.planCount >= 1) unlocked.push('first_plan');
if (metrics.completedFastCount >= 1) unlocked.push('first_fast_complete');
if (metrics.consumedMealCount >= TEN_MEALS_THRESHOLD) unlocked.push('ten_meals_consumed');
return unlocked;
}
+2
View File
@@ -1,3 +1,5 @@
export * from './achievements/definitions.js';
export * from './achievements/evaluator.js';
export * from './medical/conditions.js';
export * from './planner/adherence.js';
export * from './notifications/schema.js';
@@ -110,4 +110,22 @@ describe('matchMeals', () => {
});
expect(out).toHaveLength(0);
});
it('filters by banned ingredient ids', () => {
const withIds: RecipeCandidate[] = recipes.map((r) => ({
...r,
ingredientIds: r.id === 'r1' ? ['ing-egg', 'ing-spinach'] : ['ing-avocado'],
}));
const out = matchMeals({
candidates: withIds,
meal: 'COLAZIONE',
phase: 1,
excludedTags: [],
bannedIngredientIds: ['ing-egg'],
dailyTarget: { kcal: 1900, proteinG: 130, fatG: 130, netCarbG: 25 },
mealShare: DEFAULT_MEAL_SHARE,
});
expect(out.find((r) => r.id === 'r1')).toBeUndefined();
expect(out.find((r) => r.id === 'r2')).toBeDefined();
});
});
@@ -15,6 +15,9 @@ export interface RecipeCandidate {
fatG: number;
netCarbG: number;
exclusionTags: ReadonlyArray<string>;
// PRD §6 — ingredient ids della ricetta. Usati per applicare le esclusioni
// granulari per singolo ingrediente (`bannedIngredientIds`).
ingredientIds?: ReadonlyArray<string>;
phases: ReadonlyArray<1 | 2 | 3>;
prepMinutes?: number;
}
@@ -31,6 +34,9 @@ export interface MatchOptions {
meal: RecipeCandidate['category'];
phase: 1 | 2 | 3;
excludedTags: ReadonlyArray<string>;
// PRD §6 — ids di Ingredient che l'utente ha bandito espressamente.
// Una ricetta è scartata se contiene almeno uno di questi ingredients.
bannedIngredientIds?: ReadonlyArray<string>;
recentlyConsumedIds?: ReadonlyArray<string>;
// Macros già consumati nello stesso giorno; usati per bilanciare le scelte
// successive (la cena tiene conto di colazione/pranzo/spuntino).
@@ -74,6 +80,7 @@ export function matchMeals(opts: MatchOptions): MatchResult[] {
const recentSet = new Set(opts.recentlyConsumedIds ?? []);
const exclusionSet = new Set(opts.excludedTags);
const bannedSet = new Set(opts.bannedIngredientIds ?? []);
const results: MatchResult[] = [];
@@ -81,6 +88,8 @@ export function matchMeals(opts: MatchOptions): MatchResult[] {
if (r.category !== opts.meal) continue;
if (!r.phases.includes(opts.phase)) continue;
if (r.exclusionTags.some((tag) => exclusionSet.has(tag))) continue;
if (bannedSet.size > 0 && r.ingredientIds && r.ingredientIds.some((id) => bannedSet.has(id)))
continue;
const dKcal = (r.kcal - mealTarget.kcal) / Math.max(1, mealTarget.kcal);
const dPro = (r.proteinG - mealTarget.proteinG) / Math.max(1, mealTarget.proteinG);
@@ -53,6 +53,9 @@ export const preferencesPatchSchema = z
sessionMinutes: z.coerce.number().int().min(10).max(240).nullable().optional(),
// Pasti/giorno preferiti. Il fastingProtocol ha precedenza.
mealsPerDay: z.coerce.number().int().min(1).max(4).nullable().optional(),
// PRD §6 — esclusioni granulari su singoli ingredient. Cap a 50 per evitare
// di soffocare il matchmaking (in pratica più di così è una dieta diversa).
bannedIngredientIds: z.array(z.string().min(1).max(120)).max(50).optional(),
})
.strict();