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>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries, pantryItems, eq, and } from "@epicure/db";
|
||||
import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries, pantryItems, userNutritionGoals, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
@@ -19,6 +19,7 @@ const Schema = z.object({
|
||||
usePantry: z.boolean().default(false),
|
||||
pantryMode: z.boolean().default(false),
|
||||
difficulty: z.enum(["easy", "medium", "hard"]).optional(),
|
||||
targetNutritionGoals: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -56,6 +57,24 @@ export async function POST(req: NextRequest) {
|
||||
pantryItemNames = pantry.map((p) => p.rawName);
|
||||
}
|
||||
|
||||
// Optionally fetch the user's nutrition goals to nudge the AI toward them.
|
||||
// Silently ignored (no-op) if the user hasn't set any goals — no need to
|
||||
// fail the whole generation over a missing preference.
|
||||
let nutritionGoals: { caloriesKcal?: number | null; proteinG?: number | null; carbsG?: number | null; fatG?: number | null } | undefined;
|
||||
if (parsed.data.targetNutritionGoals) {
|
||||
const goals = await db.query.userNutritionGoals.findFirst({
|
||||
where: eq(userNutritionGoals.userId, userId),
|
||||
});
|
||||
if (goals && (goals.caloriesKcal || goals.proteinG || goals.carbsG || goals.fatG)) {
|
||||
nutritionGoals = {
|
||||
caloriesKcal: goals.caloriesKcal,
|
||||
proteinG: goals.proteinG,
|
||||
carbsG: goals.carbsG,
|
||||
fatG: goals.fatG,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
|
||||
generateMealPlan(
|
||||
{
|
||||
@@ -65,6 +84,7 @@ export async function POST(req: NextRequest) {
|
||||
days: parsed.data.days,
|
||||
pantryMode: parsed.data.pantryMode,
|
||||
difficulty: parsed.data.difficulty,
|
||||
nutritionGoals,
|
||||
},
|
||||
{ ...config, userContext: privateBio ?? undefined },
|
||||
locale
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const Schema = z.object({
|
||||
barcode: z.string().trim().min(4).max(32).regex(/^[0-9]+$/, "Barcode must be numeric"),
|
||||
});
|
||||
|
||||
type OffProduct = {
|
||||
product_name?: string;
|
||||
product_name_en?: string;
|
||||
generic_name?: string;
|
||||
quantity?: string;
|
||||
product_quantity?: string;
|
||||
product_quantity_unit?: string;
|
||||
brands?: string;
|
||||
};
|
||||
|
||||
type OffResponse = {
|
||||
status: number;
|
||||
product?: OffProduct;
|
||||
};
|
||||
|
||||
/** Very rough unit guess from Open Food Facts' free-text `quantity` field (e.g. "500 g", "1 L"). */
|
||||
function extractUnit(quantity: string | undefined): string | undefined {
|
||||
if (!quantity) return undefined;
|
||||
const match = /([a-zA-Z]+)\s*$/.exec(quantity.trim());
|
||||
return match?.[1]?.toLowerCase();
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
const parsed = Schema.safeParse(body);
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
const limited = await applyRateLimit(`rl:pantry-scan-barcode:${session!.user.id}`, 20, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const { barcode } = parsed.data;
|
||||
|
||||
let offResponse: Response;
|
||||
try {
|
||||
offResponse = await fetch(
|
||||
`https://world.openfoodfacts.org/api/v2/product/${encodeURIComponent(barcode)}.json`,
|
||||
{
|
||||
headers: { "User-Agent": "Epicure/1.0 (pantry-scan)" },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Barcode lookup service unavailable" }, { status: 502 });
|
||||
}
|
||||
|
||||
if (!offResponse.ok) {
|
||||
return NextResponse.json({ error: "Barcode lookup service unavailable" }, { status: 502 });
|
||||
}
|
||||
|
||||
const data = await offResponse.json() as OffResponse;
|
||||
|
||||
if (data.status !== 1 || !data.product) {
|
||||
return NextResponse.json({ found: false });
|
||||
}
|
||||
|
||||
const product = data.product;
|
||||
const rawName = product.product_name_en?.trim() || product.product_name?.trim() || product.generic_name?.trim();
|
||||
|
||||
if (!rawName) {
|
||||
return NextResponse.json({ found: false });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
found: true,
|
||||
rawName: product.brands ? `${rawName} (${product.brands.split(",")[0]?.trim()})` : rawName,
|
||||
quantity: product.product_quantity,
|
||||
unit: extractUnit(product.product_quantity_unit) ?? extractUnit(product.quantity),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
||||
import { scanPantryPhoto } from "@/lib/ai/features/scan-pantry-photo";
|
||||
|
||||
const Schema = z.object({
|
||||
imageBase64: z.string().max(14_000_000),
|
||||
mimeType: z.enum(["image/jpeg", "image/png", "image/webp"]),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
const parsed = Schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const userId = session!.user.id;
|
||||
|
||||
const limited = await applyRateLimit(`rl:ai:${userId}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const configResult = await resolveAiConfigOrError(() => getModelConfigForUseCase(userId, "vision"));
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
// Fall back to vision-capable defaults if no explicit model configured
|
||||
if (!aiConfig.model) {
|
||||
if (aiConfig.provider === "openai") aiConfig.model = "gpt-4o";
|
||||
else if (aiConfig.provider === "anthropic") aiConfig.model = "claude-sonnet-4-6";
|
||||
}
|
||||
|
||||
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
|
||||
scanPantryPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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 });
|
||||
}
|
||||
Reference in New Issue
Block a user