Files
Epicure/apps/web/app/api/v1/users/me/nutrition-diary/route.ts
T
Arnaud b0849c3989 feat: cooking history/gallery, unit conversion, nutrition diary, pantry scan, digest cron, nutrition-targeted meal plans
Six M-sized items from HANDOFF.md's new-features backlog:

- Profile tabs: cooking-history stats (total cooked, last-cooked, streak)
  and a "cooked it" photo gallery, both owner-only
- Display-time unit conversion (metric<->imperial) for recipe ingredients,
  respecting each user's unitPref; original value always shown alongside
  the conversion
- Nutrition daily diary: per-day macro totals computed from cooking history
  x recipe nutritionData, compared against user goals
- Pantry scan: real barcode lookup (zxing + Open Food Facts, no API key)
  with an AI-vision fallback for unbarcoded items, always confirm-before-
  insert, both paths tier/rate-limited like other AI features
- Weekly digest email: new followers/comments/ratings + trending recipes,
  sent via a new `cron` Docker stage (alpine+crond+curl) and `digest-cron`
  compose service hitting a bearer-token-protected internal route
- Meal-plan generation can now target a user's nutrition goals as a
  prompt-level nudge (recipes are AI-invented, not DB-sourced, so this
  can't be a hard macro constraint)

Caught a real deploy-breaking issue while adding the cron stage: appending
it after `runner` silently changed the Dockerfile's default build target,
and `web`'s compose config didn't pin one — fixed by pinning `target:
runner` explicitly. Verified with typecheck, lint, and three separate
`docker build --target` runs (runner/cron/migrator) plus `docker compose
config` validation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-10 08:06:28 +02:00

104 lines
3.3 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { db, cookingHistory, recipes, userNutritionGoals, eq, and, gte, lt } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
function isValidDate(value: string): boolean {
return /^\d{4}-\d{2}-\d{2}$/.test(value) && !isNaN(new Date(`${value}T00:00:00.000Z`).getTime());
}
export async function GET(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const userId = session!.user.id;
const dateParam = req.nextUrl.searchParams.get("date");
const date = dateParam && isValidDate(dateParam) ? dateParam : new Date().toISOString().slice(0, 10);
const dayStart = new Date(`${date}T00:00:00.000Z`);
const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);
const rows = await db
.select({
id: cookingHistory.id,
recipeId: cookingHistory.recipeId,
servings: cookingHistory.servings,
cookedAt: cookingHistory.cookedAt,
recipeTitle: recipes.title,
baseServings: recipes.baseServings,
nutritionData: recipes.nutritionData,
})
.from(cookingHistory)
.leftJoin(recipes, eq(cookingHistory.recipeId, recipes.id))
.where(
and(
eq(cookingHistory.userId, userId),
gte(cookingHistory.cookedAt, dayStart),
lt(cookingHistory.cookedAt, dayEnd)
)
)
.orderBy(cookingHistory.cookedAt);
const totals = { calories: 0, proteinG: 0, carbsG: 0, fatG: 0, fiberG: 0, sodiumMg: 0 };
const entries: {
id: string;
recipeId: string;
title: string;
servings: number;
cookedAt: string;
nutritionKnown: boolean;
}[] = [];
let unknownCount = 0;
for (const row of rows) {
const servings = row.servings ?? row.baseServings ?? 1;
const perServing = row.nutritionData?.perServing;
const nutritionKnown = !!perServing;
if (perServing) {
totals.calories += perServing.calories * servings;
totals.proteinG += perServing.proteinG * servings;
totals.carbsG += perServing.carbsG * servings;
totals.fatG += perServing.fatG * servings;
totals.fiberG += perServing.fiberG * servings;
totals.sodiumMg += perServing.sodiumMg * servings;
} else {
unknownCount += 1;
}
entries.push({
id: row.id,
recipeId: row.recipeId,
title: row.recipeTitle ?? "Unknown recipe",
servings,
cookedAt: row.cookedAt.toISOString(),
nutritionKnown,
});
}
for (const key of Object.keys(totals) as (keyof typeof totals)[]) {
totals[key] = Math.round(totals[key]);
}
const goalsRow = await db.query.userNutritionGoals.findFirst({
where: eq(userNutritionGoals.userId, userId),
});
const goals = goalsRow
? {
caloriesKcal: goalsRow.caloriesKcal,
proteinG: goalsRow.proteinG,
carbsG: goalsRow.carbsG,
fatG: goalsRow.fatG,
}
: null;
const coverage = {
calories: goals?.caloriesKcal ? Math.round((totals.calories / goals.caloriesKcal) * 100) : 0,
protein: goals?.proteinG ? Math.round((totals.proteinG / goals.proteinG) * 100) : 0,
carbs: goals?.carbsG ? Math.round((totals.carbsG / goals.carbsG) * 100) : 0,
fat: goals?.fatG ? Math.round((totals.fatG / goals.fatG) * 100) : 0,
};
return NextResponse.json({ date, totals, goals, coverage, entries, unknownCount });
}