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:
@@ -2,6 +2,8 @@ import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { NutritionDiary } from "@/components/nutrition/nutrition-diary";
|
||||
import { NutritionTrend } from "@/components/nutrition/nutrition-trend";
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
@@ -17,7 +19,18 @@ export default async function NutritionDiaryPage() {
|
||||
<h1 className="text-2xl font-bold tracking-tight">{m.nutritionDiary.title}</h1>
|
||||
<p className="text-muted-foreground mt-1">{m.nutritionDiary.subtitle}</p>
|
||||
</div>
|
||||
<NutritionDiary />
|
||||
<Tabs defaultValue="diary" className="gap-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="diary">{m.nutritionDiary.tabDiary}</TabsTrigger>
|
||||
<TabsTrigger value="trend">{m.nutritionDiary.tabTrend}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="diary">
|
||||
<NutritionDiary />
|
||||
</TabsContent>
|
||||
<TabsContent value="trend">
|
||||
<NutritionTrend />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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