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>
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, pantryItems, recipes, eq, or, inArray } from "@epicure/db";
|
||||
import { db, pantryItems, recipes, cookingHistory, eq, and, or, inArray, isNotNull } from "@epicure/db";
|
||||
import { asc } from "@epicure/db";
|
||||
import { PantryManager } from "@/components/meal-plan/pantry-manager";
|
||||
import { PantryPageHeader } from "@/components/pantry/pantry-page-header";
|
||||
import { ExpiringSoonSuggestions } from "@/components/pantry/expiring-soon-suggestions";
|
||||
import { ExpiringLeftovers } from "@/components/pantry/expiring-leftovers";
|
||||
import { scoreRecipesAgainstPantry } from "@/lib/pantry-match";
|
||||
import { dishExpiresAt, daysUntil, isLeftoverExpiringSoon } from "@/lib/leftover-match";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
@@ -15,7 +17,7 @@ export default async function PantryPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const [items, candidateRecipes] = await Promise.all([
|
||||
const [items, candidateRecipes, cookedDishes] = await Promise.all([
|
||||
db.query.pantryItems.findMany({
|
||||
where: eq(pantryItems.userId, session.user.id),
|
||||
orderBy: asc(pantryItems.rawName),
|
||||
@@ -24,6 +26,13 @@ export default async function PantryPage() {
|
||||
where: or(eq(recipes.authorId, session.user.id), inArray(recipes.visibility, ["public", "unlisted"])),
|
||||
with: { ingredients: true, photos: true },
|
||||
}),
|
||||
db.query.cookingHistory.findMany({
|
||||
where: and(eq(cookingHistory.userId, session.user.id), isNotNull(cookingHistory.batchDishId)),
|
||||
with: {
|
||||
batchDish: { columns: { id: true, name: true, fridgeDays: true } },
|
||||
recipe: { columns: { id: true, title: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const mappedItems = items.map((i) => ({
|
||||
@@ -47,9 +56,27 @@ export default async function PantryPage() {
|
||||
};
|
||||
});
|
||||
|
||||
const latestByDish = new Map<string, (typeof cookedDishes)[number]>();
|
||||
for (const log of cookedDishes) {
|
||||
if (!log.batchDish) continue;
|
||||
const existing = latestByDish.get(log.batchDish.id);
|
||||
if (!existing || log.cookedAt > existing.cookedAt) latestByDish.set(log.batchDish.id, log);
|
||||
}
|
||||
const leftovers = [...latestByDish.values()]
|
||||
.filter((log) => log.batchDish && isLeftoverExpiringSoon(log.cookedAt, log.batchDish.fridgeDays))
|
||||
.map((log) => ({
|
||||
recipeId: log.recipe.id,
|
||||
dishName: log.batchDish!.name,
|
||||
recipeTitle: log.recipe.title,
|
||||
expiresAt: dishExpiresAt(log.cookedAt, log.batchDish!.fridgeDays).toISOString(),
|
||||
daysLeft: daysUntil(dishExpiresAt(log.cookedAt, log.batchDish!.fridgeDays)),
|
||||
}))
|
||||
.sort((a, b) => a.daysLeft - b.daysLeft);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PantryPageHeader items={mappedItems} />
|
||||
<ExpiringLeftovers leftovers={leftovers} />
|
||||
<ExpiringSoonSuggestions suggestions={suggestions} />
|
||||
<PantryManager key={mappedItems.map((i) => i.id).join(",")} initialItems={mappedItems} />
|
||||
</div>
|
||||
|
||||
@@ -18,8 +18,8 @@ import { ForkRecipeButton } from "@/components/recipe/fork-recipe-button";
|
||||
import { NutritionPanel } from "@/components/recipe/nutrition-panel";
|
||||
import { GenerateContentButton } from "@/components/recipe/generate-content-button";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, recipes, ratings, favorites, recipeVariations, recipeNotes, avg } from "@epicure/db";
|
||||
import { and, eq, or, count, inArray } from "@epicure/db";
|
||||
import { db, recipes, ratings, favorites, recipeVariations, recipeNotes, cookingHistory, avg } from "@epicure/db";
|
||||
import { and, eq, or, count, inArray, desc } from "@epicure/db";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
@@ -32,7 +32,7 @@ import { CookedItReview } from "@/components/social/cooked-it-review";
|
||||
import { RecipeNotes } from "@/components/recipe/recipe-notes";
|
||||
import { CommentsSection } from "@/components/social/comments-section";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn, stripMarkdown } from "@/lib/utils";
|
||||
import { RecipeChatPanel } from "@/components/recipe/recipe-chat-panel";
|
||||
import { BatchCookSteps } from "@/components/recipe/batch-cook-steps";
|
||||
import { BatchCookDishes } from "@/components/recipe/batch-cook-dishes";
|
||||
@@ -62,7 +62,7 @@ export default async function RecipePage({ params }: Params) {
|
||||
const DIETARY_LABELS = m.recipe.dietary;
|
||||
const unitPref = (session.user as { unitPref?: string }).unitPref === "imperial" ? "imperial" : "metric";
|
||||
|
||||
const [recipe, ratingData, favoriteData, myRating, forkedFrom, myNote] = await Promise.all([
|
||||
const [recipe, ratingData, favoriteData, myRating, forkedFrom, myNote, dishCookLog] = await Promise.all([
|
||||
db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, id),
|
||||
@@ -87,12 +87,24 @@ export default async function RecipePage({ params }: Params) {
|
||||
where: and(eq(recipeNotes.recipeId, id), eq(recipeNotes.userId, session.user.id)),
|
||||
columns: { content: true },
|
||||
}),
|
||||
db.query.cookingHistory.findMany({
|
||||
where: and(eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, session.user.id)),
|
||||
orderBy: desc(cookingHistory.cookedAt),
|
||||
columns: { batchDishId: true, cookedAt: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!recipe) notFound();
|
||||
|
||||
const isOwner = recipe.authorId === session.user.id;
|
||||
|
||||
const dishCookedAtMap = new Map<string, string>();
|
||||
for (const log of dishCookLog) {
|
||||
if (log.batchDishId && !dishCookedAtMap.has(log.batchDishId)) {
|
||||
dishCookedAtMap.set(log.batchDishId, log.cookedAt.toISOString());
|
||||
}
|
||||
}
|
||||
|
||||
const avgScore = ratingData[0]?.avgScore ? parseFloat(ratingData[0].avgScore) : null;
|
||||
const ratingCount = ratingData[0]?.total ?? 0;
|
||||
const isFavorited = !!favoriteData;
|
||||
@@ -267,7 +279,9 @@ export default async function RecipePage({ params }: Params) {
|
||||
)}
|
||||
|
||||
{recipe.description && (
|
||||
<p className="text-muted-foreground leading-relaxed">{recipe.description}</p>
|
||||
<p className="text-muted-foreground leading-relaxed">
|
||||
{recipe.isBatchCook ? stripMarkdown(recipe.description) : recipe.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{recipe.sourceUrl && (
|
||||
@@ -411,7 +425,10 @@ export default async function RecipePage({ params }: Params) {
|
||||
{recipe.isBatchCook && recipe.batchDishes.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<BatchCookDishes dishes={recipe.batchDishes} />
|
||||
<BatchCookDishes
|
||||
recipeId={id}
|
||||
dishes={recipe.batchDishes.map((d) => ({ ...d, cookedAt: dishCookedAtMap.get(d.id) ?? null }))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ export default async function RecipesPage({ searchParams }: { searchParams: Sear
|
||||
db.query.recipes.findMany({
|
||||
where,
|
||||
orderBy: SORT_MAP[sortKey],
|
||||
with: { photos: true },
|
||||
with: { photos: true, batchDishes: { columns: { id: true } } },
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
}),
|
||||
@@ -87,7 +87,7 @@ export default async function RecipesPage({ searchParams }: { searchParams: Sear
|
||||
.where(and(eq(favorites.userId, session.user.id), inArray(favorites.recipeId, recipeIds)))
|
||||
: [];
|
||||
const favoritedIds = new Set(favoritedRows.map((r) => r.recipeId));
|
||||
const recipesWithFavorites = userRecipes.map((r) => ({ ...r, isFavorited: favoritedIds.has(r.id) }));
|
||||
const recipesWithFavorites = userRecipes.map((r) => ({ ...r, isFavorited: favoritedIds.has(r.id), dishCount: r.batchDishes.length }));
|
||||
|
||||
const pageHref = (p: number) => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { db, cookingHistory, eq, and, isNotNull, isNull } from "@epicure/db";
|
||||
import { sendEmail, notificationEmailHtml } from "@/lib/email";
|
||||
import { sendPushNotification } from "@/lib/push";
|
||||
import { isLeftoverExpiringSoon } from "@/lib/leftover-match";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
// Internal cron endpoint — triggered daily by a cron container (see
|
||||
// compose.prod.yml / cron/crontab). Not part of the public API surface;
|
||||
// protected by a shared secret rather than user auth.
|
||||
//
|
||||
// For every cooking_history row tied to a batch-cook dish, checks whether it
|
||||
// expires soon (see lib/leftover-match.ts) and hasn't already been reminded
|
||||
// about, then sends one push + email and marks it reminded so it never fires
|
||||
// twice for the same cooked dish.
|
||||
|
||||
function isAuthorized(req: NextRequest): boolean {
|
||||
const secret = process.env["CRON_SECRET"];
|
||||
if (!secret) return false;
|
||||
|
||||
const header = req.headers.get("authorization");
|
||||
if (!header?.startsWith("Bearer ")) return false;
|
||||
const provided = header.slice("Bearer ".length);
|
||||
|
||||
const a = Buffer.from(provided);
|
||||
const b = Buffer.from(secret);
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isAuthorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const candidates = await db.query.cookingHistory.findMany({
|
||||
where: and(isNotNull(cookingHistory.batchDishId), isNull(cookingHistory.expiryReminderSentAt)),
|
||||
with: {
|
||||
batchDish: { columns: { id: true, name: true, fridgeDays: true } },
|
||||
recipe: { columns: { id: true, title: true } },
|
||||
user: { columns: { id: true, email: true, locale: true } },
|
||||
},
|
||||
});
|
||||
|
||||
let sent = 0;
|
||||
for (const log of candidates) {
|
||||
if (!log.batchDish || !log.user) continue;
|
||||
if (!isLeftoverExpiringSoon(log.cookedAt, log.batchDish.fridgeDays)) continue;
|
||||
|
||||
const messages = getMessages(log.user.locale);
|
||||
const template = messages.notifications.detail.leftoverExpiring;
|
||||
const title = messages.notifications.pushTitle.leftoverExpiring;
|
||||
const body = formatMessage(template, { dish: log.batchDish.name, title: log.recipe.title });
|
||||
const url = `/recipes/${log.recipe.id}`;
|
||||
|
||||
await Promise.all([
|
||||
sendPushNotification(log.user.id, { title, body, url }).catch((err) => {
|
||||
console.error("[leftover-reminders] push failed", err);
|
||||
}),
|
||||
log.user.email
|
||||
? sendEmail({
|
||||
to: log.user.email,
|
||||
subject: title,
|
||||
html: notificationEmailHtml(title, body, `${process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"}${url}`),
|
||||
}).catch((err) => {
|
||||
console.error("[leftover-reminders] email failed", err);
|
||||
})
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
|
||||
await db.update(cookingHistory)
|
||||
.set({ expiryReminderSentAt: new Date() })
|
||||
.where(eq(cookingHistory.id, log.id));
|
||||
sent++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, checked: candidates.length, sent });
|
||||
}
|
||||
@@ -71,6 +71,8 @@ export async function POST(req: NextRequest) {
|
||||
aiGenerated: true,
|
||||
isBatchCook: true,
|
||||
language: locale,
|
||||
prepMins: plan.prepMins,
|
||||
cookMins: plan.cookMins,
|
||||
});
|
||||
|
||||
if (plan.ingredients.length > 0) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, recipes, cookingHistory, pantryItems, recipeIngredients, eq, and } from "@epicure/db";
|
||||
import { db, recipes, cookingHistory, pantryItems, recipeIngredients, recipeBatchDishes, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
@@ -9,6 +9,7 @@ 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) {
|
||||
@@ -26,16 +27,24 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
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) {
|
||||
if (data.deductFromPantry && !data.batchDishId) {
|
||||
const ings = await db.query.recipeIngredients.findMany({
|
||||
where: eq(recipeIngredients.recipeId, id),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user