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:
@@ -0,0 +1,131 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import {
|
||||
db,
|
||||
users,
|
||||
recipes,
|
||||
comments,
|
||||
ratings,
|
||||
userFollows,
|
||||
favorites,
|
||||
eq,
|
||||
and,
|
||||
gte,
|
||||
desc,
|
||||
count,
|
||||
sql,
|
||||
} from "@epicure/db";
|
||||
import { sendEmail, weeklyDigestHtml } from "@/lib/email";
|
||||
|
||||
// Internal cron endpoint — triggered by the `digest-cron` container on a weekly
|
||||
// schedule (see docker/compose.prod.yml). Not part of the public API surface;
|
||||
// protected by a shared secret rather than user auth.
|
||||
//
|
||||
// Computes, for every user: new followers / new comments / new ratings on
|
||||
// their recipes in the last 7 days, plus a site-wide top-3 trending list, and
|
||||
// emails a summary. Sends to all users (all users have a non-null email) —
|
||||
// there's no per-user opt-out preference yet; out of scope for this pass.
|
||||
|
||||
const CHUNK_SIZE = 20;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function chunk<T>(arr: T[], size: number): T[][] {
|
||||
const out: T[][] = [];
|
||||
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isAuthorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
|
||||
const [allUsers, followerRows, commentRows, ratingRows, trending] = await Promise.all([
|
||||
db.select({ id: users.id, email: users.email }).from(users),
|
||||
db
|
||||
.select({ userId: userFollows.followingId, n: count() })
|
||||
.from(userFollows)
|
||||
.where(gte(userFollows.createdAt, weekAgo))
|
||||
.groupBy(userFollows.followingId),
|
||||
db
|
||||
.select({ userId: recipes.authorId, n: count() })
|
||||
.from(comments)
|
||||
.innerJoin(recipes, eq(comments.recipeId, recipes.id))
|
||||
.where(gte(comments.createdAt, weekAgo))
|
||||
.groupBy(recipes.authorId),
|
||||
db
|
||||
.select({ userId: recipes.authorId, n: count() })
|
||||
.from(ratings)
|
||||
.innerJoin(recipes, eq(ratings.recipeId, recipes.id))
|
||||
.where(gte(ratings.createdAt, weekAgo))
|
||||
.groupBy(recipes.authorId),
|
||||
db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
|
||||
})
|
||||
.from(recipes)
|
||||
.leftJoin(
|
||||
favorites,
|
||||
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, weekAgo))
|
||||
)
|
||||
.where(eq(recipes.visibility, "public"))
|
||||
.groupBy(recipes.id)
|
||||
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
|
||||
.limit(3),
|
||||
]);
|
||||
|
||||
const followerMap = new Map(followerRows.map((r) => [r.userId, r.n]));
|
||||
const commentMap = new Map(commentRows.map((r) => [r.userId, r.n]));
|
||||
const ratingMap = new Map(ratingRows.map((r) => [r.userId, r.n]));
|
||||
const trendingList = trending.map((r) => ({ id: r.id, title: r.title }));
|
||||
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (const batch of chunk(allUsers, CHUNK_SIZE)) {
|
||||
const results = await Promise.allSettled(
|
||||
batch.map((user) => {
|
||||
const newFollowers = followerMap.get(user.id) ?? 0;
|
||||
const newComments = commentMap.get(user.id) ?? 0;
|
||||
const newRatings = ratingMap.get(user.id) ?? 0;
|
||||
|
||||
return sendEmail({
|
||||
to: user.email,
|
||||
subject: "Your weekly digest — Epicure",
|
||||
html: weeklyDigestHtml({
|
||||
newFollowers,
|
||||
newComments,
|
||||
newRatings,
|
||||
trending: trendingList,
|
||||
baseUrl,
|
||||
}),
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled") sent++;
|
||||
else failed++;
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, totalUsers: allUsers.length, sent, failed });
|
||||
}
|
||||
Reference in New Issue
Block a user