Files
Epicure/apps/web/app/api/v1/recipes/[id]/cooked/route.ts
T
Arnaud 002f14ced0 feat: batch-cook shopping list (already worked) + leftover expiry reminders
Shopping list add already worked generically for batch-cook recipes —
no code needed there.

New: mark a specific batch-cook dish as "cooked today", track its
fridge expiry (cookingHistory.batchDishId), surface a "Leftovers
expiring soon" widget on the pantry page, and send a daily push+email
reminder via a new /api/internal/cron/leftover-reminders endpoint
(mirrors the weekly-digest cron pattern; doesn't use the social
notifications table, which requires a non-null actor and isn't built
for self-reminders).

Also fixes, from user-reported bugs:
- Recipe cards showed no batch-cook badge/dish-count/prep-time in some
  views — added dishCount + prepMins/cookMins (now generated by the AI
  and persisted) to the card component and /recipes query.
- Batch-cook descriptions occasionally contained raw markdown
  (**bold**) — added explicit "plain prose only" prompt instructions
  and a stripMarkdown() defensive fallback at render time.
- Truncated/cut-off descriptions — the generateObject call had no
  maxOutputTokens set, so long structured responses could get cut off
  mid-field; now capped explicitly at 8000.
- Generate dialogs (batch-cook + the main AI dialog) could show
  buttons unreachable once the progress bar appeared mid-generation —
  restructured so the action row is pinned outside the scrollable
  content area, not affected by content height changes.
- /api/internal/* routes were being redirected to /login by middleware
  before their own CRON_SECRET check ever ran (pre-existing bug,
  affected the weekly-digest cron too) — added to PUBLIC_PATHS.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 10:03:52 +02:00

84 lines
3.1 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, cookingHistory, pantryItems, recipeIngredients, recipeBatchDishes, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
const Schema = z.object({
servings: z.number().int().min(1).max(1000).optional(),
notes: z.string().max(2000).optional(),
deductFromPantry: z.boolean().default(true),
batchDishId: z.string().optional(),
});
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const userId = session!.user.id;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== userId)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json().catch(() => ({})) as unknown;
const parsed = Schema.safeParse(body);
const data = parsed.success ? parsed.data : { deductFromPantry: true };
if (data.batchDishId) {
const dish = await db.query.recipeBatchDishes.findFirst({
where: and(eq(recipeBatchDishes.id, data.batchDishId), eq(recipeBatchDishes.recipeId, id)),
});
if (!dish) return NextResponse.json({ error: "Dish not found" }, { status: 404 });
}
await db.insert(cookingHistory).values({
id: crypto.randomUUID(),
userId,
recipeId: id,
batchDishId: data.batchDishId,
servings: data.servings,
notes: data.notes,
cookedAt: new Date(),
});
if (data.deductFromPantry && !data.batchDishId) {
const ings = await db.query.recipeIngredients.findMany({
where: eq(recipeIngredients.recipeId, id),
});
const scale = data.servings ? data.servings / recipe.baseServings : 1;
const userPantry = await db.query.pantryItems.findMany({
where: eq(pantryItems.userId, userId),
});
for (const ing of ings) {
const key = ing.rawName.toLowerCase();
const pantryItem = userPantry.find(
(p) => p.rawName.toLowerCase() === key && (p.unit ?? "") === (ing.unit ?? "")
);
if (!pantryItem) continue;
const pantryQty = pantryItem.quantity ? parseFloat(pantryItem.quantity) : null;
const ingQty = ing.quantity ? parseFloat(ing.quantity) * scale : null;
if (pantryQty !== null && ingQty !== null && !isNaN(pantryQty) && !isNaN(ingQty)) {
const remaining = pantryQty - ingQty;
if (remaining <= 0) {
await db.delete(pantryItems).where(eq(pantryItems.id, pantryItem.id));
} else {
await db.update(pantryItems)
.set({ quantity: String(Math.round(remaining * 10000) / 10000) })
.where(eq(pantryItems.id, pantryItem.id));
}
} else {
// no numeric quantity to deduct — remove the item entirely
await db.delete(pantryItems).where(eq(pantryItems.id, pantryItem.id));
}
}
}
return NextResponse.json({ logged: true }, { status: 201 });
}