feat: nutrition trend/history view (v0.69.0)
Extends GET /api/v1/users/me/nutrition-diary with a `range` query param (7/30/90) that switches it into trend mode -- daily calorie/macro totals bucketed from the same cooking-history rows the single-day diary already reads, with zero-filled days so the chart has a continuous x-axis. New NutritionTrend component reuses the existing hand-rolled TimeSeriesChart (previously admin-only, now imported from user-facing code too) for the calorie line, plus simple average-macro stat tiles below it. Nutrition page now has Diary/Trend tabs instead of just the diary. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,11 +6,19 @@ function isValidDate(value: string): boolean {
|
||||
return /^\d{4}-\d{2}-\d{2}$/.test(value) && !isNaN(new Date(`${value}T00:00:00.000Z`).getTime());
|
||||
}
|
||||
|
||||
const VALID_RANGES = [7, 30, 90];
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
const userId = session!.user.id;
|
||||
|
||||
const rangeParam = req.nextUrl.searchParams.get("range");
|
||||
const range = rangeParam ? parseInt(rangeParam, 10) : null;
|
||||
if (range && VALID_RANGES.includes(range)) {
|
||||
return getTrend(userId, range);
|
||||
}
|
||||
|
||||
const dateParam = req.nextUrl.searchParams.get("date");
|
||||
const date = dateParam && isValidDate(dateParam) ? dateParam : new Date().toISOString().slice(0, 10);
|
||||
|
||||
@@ -101,3 +109,56 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
return NextResponse.json({ date, totals, goals, coverage, entries, unknownCount });
|
||||
}
|
||||
|
||||
/** Multi-day trend: daily calorie/macro totals over the last N days, one
|
||||
* bucket per calendar day (UTC, matching the single-day endpoint's own
|
||||
* dayStart/dayEnd math above) — days with nothing cooked still appear with
|
||||
* zero totals so the chart has a continuous x-axis. */
|
||||
async function getTrend(userId: string, days: number): Promise<NextResponse> {
|
||||
const todayStr = new Date().toISOString().slice(0, 10);
|
||||
const since = new Date(`${todayStr}T00:00:00.000Z`);
|
||||
since.setUTCDate(since.getUTCDate() - (days - 1));
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
servings: cookingHistory.servings,
|
||||
cookedAt: cookingHistory.cookedAt,
|
||||
baseServings: recipes.baseServings,
|
||||
nutritionData: recipes.nutritionData,
|
||||
})
|
||||
.from(cookingHistory)
|
||||
.leftJoin(recipes, eq(cookingHistory.recipeId, recipes.id))
|
||||
.where(and(eq(cookingHistory.userId, userId), gte(cookingHistory.cookedAt, since)));
|
||||
|
||||
const buckets = new Map<string, { calories: number; proteinG: number; carbsG: number; fatG: number }>();
|
||||
for (let i = 0; i < days; i++) {
|
||||
const d = new Date(since);
|
||||
d.setUTCDate(d.getUTCDate() + i);
|
||||
buckets.set(d.toISOString().slice(0, 10), { calories: 0, proteinG: 0, carbsG: 0, fatG: 0 });
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
const perServing = row.nutritionData?.perServing;
|
||||
if (!perServing) continue;
|
||||
const servings = row.servings ?? row.baseServings ?? 1;
|
||||
const key = row.cookedAt.toISOString().slice(0, 10);
|
||||
const bucket = buckets.get(key);
|
||||
if (!bucket) continue;
|
||||
bucket.calories += perServing.calories * servings;
|
||||
bucket.proteinG += perServing.proteinG * servings;
|
||||
bucket.carbsG += perServing.carbsG * servings;
|
||||
bucket.fatG += perServing.fatG * servings;
|
||||
}
|
||||
|
||||
const goalsRow = await db.query.userNutritionGoals.findFirst({ where: eq(userNutritionGoals.userId, userId) });
|
||||
|
||||
const daysOut = [...buckets.entries()].map(([date, totals]) => ({
|
||||
date,
|
||||
calories: Math.round(totals.calories),
|
||||
proteinG: Math.round(totals.proteinG),
|
||||
carbsG: Math.round(totals.carbsG),
|
||||
fatG: Math.round(totals.fatG),
|
||||
}));
|
||||
|
||||
return NextResponse.json({ range: days, days: daysOut, goalCalories: goalsRow?.caloriesKcal ?? null });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user