feat: push+email notifications, recipe notes, fork/clone, pantry-aware lists, GDPR export
Five S-sized items from HANDOFF.md's new-features backlog, all wiring up previously-orphaned infra: - createNotification now sends web push + email for every notification type (follow/comment/reply/reaction/rating/mention), not just comments - Personal recipe notes: private per-user notes on any viewable recipe (recipeNotes table had zero API/UI before this) - Recipe fork/clone: deep-copies a viewable recipe into your own library as a private draft, linked via recipeVariations, respects tier quota - Pantry-aware shopping lists: meal-plan-generated lists now subtract on-hand pantry quantities (ingredientId match, falling back to normalized name match) and flag partial/ambiguous matches instead of guessing - GDPR data export: downloadable JSON of a user's own content and activity across every relevant table, secrets/internal tables excluded New migrations 0025 (unique index for recipe-notes upsert) and 0026 (shopping_list_items.in_pantry) generated, left unapplied like 0023/0024. Verified with typecheck, lint, and a full local `docker build`. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,6 @@ import { db, recipes, comments, users, userBlocks, eq, and, inArray, isNull, sql
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { dispatchWebhook } from "@/lib/webhooks";
|
||||
import { sendPushNotification } from "@/lib/push";
|
||||
import { createNotification } from "@/lib/notifications";
|
||||
import { isBlockedEitherWay } from "@/lib/blocks";
|
||||
import { extractMentionedUsernames } from "@/lib/mentions";
|
||||
@@ -126,14 +125,10 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
content: parsed.data.content,
|
||||
});
|
||||
|
||||
// Dispatch to recipe author's webhooks (not to the commenter themselves)
|
||||
// Dispatch to recipe author's webhooks (not to the commenter themselves).
|
||||
// Push/email to the author are handled by createNotification's "comment" call below.
|
||||
if (recipe.authorId !== session!.user.id) {
|
||||
void dispatchWebhook(recipe.authorId, "comment.added", { commentId, recipeId: id, recipeTitle: recipe.title });
|
||||
void sendPushNotification(recipe.authorId, {
|
||||
title: "New comment on your recipe",
|
||||
body: `${session!.user.name} commented on "${recipe.title}"`,
|
||||
url: `/recipes/${id}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (parent && parent.userId !== session!.user.id) {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, recipes, recipeIngredients, recipeSteps, recipeVariations } from "@epicure/db";
|
||||
import { eq, and, or, inArray } from "@epicure/db";
|
||||
import { requireSessionOrApiKey } from "@/lib/api-auth";
|
||||
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 20, windowSeconds: 60 } });
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const source = await db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, id),
|
||||
or(eq(recipes.authorId, session!.user.id), inArray(recipes.visibility, ["public", "unlisted"]))
|
||||
),
|
||||
with: {
|
||||
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
steps: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
},
|
||||
});
|
||||
if (!source) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
try {
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "recipe");
|
||||
} catch (err) {
|
||||
if (err instanceof TierLimitError) {
|
||||
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const newId = crypto.randomUUID();
|
||||
const now = new Date();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(recipes).values({
|
||||
id: newId,
|
||||
authorId: session!.user.id,
|
||||
title: source.title,
|
||||
description: source.description,
|
||||
baseServings: source.baseServings,
|
||||
visibility: "private",
|
||||
difficulty: source.difficulty,
|
||||
prepMins: source.prepMins,
|
||||
cookMins: source.cookMins,
|
||||
tags: source.tags,
|
||||
dietaryTags: source.dietaryTags ?? {},
|
||||
aiGenerated: false,
|
||||
language: source.language,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
if (source.ingredients.length > 0) {
|
||||
await tx.insert(recipeIngredients).values(
|
||||
source.ingredients.map((ing) => ({
|
||||
id: crypto.randomUUID(),
|
||||
recipeId: newId,
|
||||
rawName: ing.rawName,
|
||||
quantity: ing.quantity,
|
||||
unit: ing.unit,
|
||||
note: ing.note,
|
||||
order: ing.order,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
if (source.steps.length > 0) {
|
||||
await tx.insert(recipeSteps).values(
|
||||
source.steps.map((step) => ({
|
||||
id: crypto.randomUUID(),
|
||||
recipeId: newId,
|
||||
instruction: step.instruction,
|
||||
timerSeconds: step.timerSeconds,
|
||||
order: step.order,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
await tx.insert(recipeVariations).values({
|
||||
id: crypto.randomUUID(),
|
||||
parentRecipeId: source.id,
|
||||
childRecipeId: newId,
|
||||
description: null,
|
||||
aiGenerated: false,
|
||||
createdAt: now,
|
||||
});
|
||||
});
|
||||
|
||||
return NextResponse.json({ id: newId }, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, recipes, recipeNotes, eq, and, or, inArray } from "@epicure/db";
|
||||
import { z } from "zod";
|
||||
import { requireSessionOrApiKey } from "@/lib/api-auth";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
const PutSchema = z.object({
|
||||
content: z.string().max(5000),
|
||||
});
|
||||
|
||||
async function assertRecipeAccessible(recipeId: string, userId: string) {
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, recipeId),
|
||||
or(eq(recipes.authorId, userId), inArray(recipes.visibility, ["public", "unlisted"]))
|
||||
),
|
||||
columns: { id: true },
|
||||
});
|
||||
return recipe;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const recipe = await assertRecipeAccessible(id, session!.user.id);
|
||||
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const note = await db.query.recipeNotes.findFirst({
|
||||
where: and(eq(recipeNotes.recipeId, id), eq(recipeNotes.userId, session!.user.id)),
|
||||
columns: { content: true, updatedAt: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({ note: note ?? null });
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSessionOrApiKey(req, { rateLimit: { limit: 60, windowSeconds: 60 } });
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const recipe = await assertRecipeAccessible(id, session!.user.id);
|
||||
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const parsed = PutSchema.safeParse(await req.json());
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const content = parsed.data.content.trim();
|
||||
const userId = session!.user.id;
|
||||
|
||||
if (content.length === 0) {
|
||||
await db
|
||||
.delete(recipeNotes)
|
||||
.where(and(eq(recipeNotes.recipeId, id), eq(recipeNotes.userId, userId)));
|
||||
return NextResponse.json({ note: null });
|
||||
}
|
||||
|
||||
await db
|
||||
.insert(recipeNotes)
|
||||
.values({ id: crypto.randomUUID(), recipeId: id, userId, content, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: [recipeNotes.recipeId, recipeNotes.userId],
|
||||
set: { content, updatedAt: new Date() },
|
||||
});
|
||||
|
||||
const note = await db.query.recipeNotes.findFirst({
|
||||
where: and(eq(recipeNotes.recipeId, id), eq(recipeNotes.userId, userId)),
|
||||
columns: { content: true, updatedAt: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({ note });
|
||||
}
|
||||
@@ -53,6 +53,6 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
reviewText: parsed.data.reviewText,
|
||||
photoKey: parsed.data.photoKey,
|
||||
});
|
||||
void createNotification({ userId: recipe.authorId, type: "rating", actorId: session!.user.id, recipeId: id });
|
||||
void createNotification({ userId: recipe.authorId, type: "rating", actorId: session!.user.id, recipeId: id, score: parsed.data.score });
|
||||
return NextResponse.json({ created: true }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, shoppingLists, shoppingListItems, mealPlans, mealPlanEntries, recipeIngredients, eq, and, desc, inArray } from "@epicure/db";
|
||||
import { db, shoppingLists, shoppingListItems, mealPlans, mealPlanEntries, recipeIngredients, pantryItems, eq, and, desc, inArray } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyPantryToItems } from "@/lib/pantry-shopping-match";
|
||||
|
||||
const CreateSchema = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
@@ -38,7 +39,7 @@ export async function POST(req: NextRequest) {
|
||||
const data = parsed.data;
|
||||
const listId = crypto.randomUUID();
|
||||
|
||||
let items: Array<{ rawName: string; quantity?: string; unit?: string; aisle?: string }> = data.items ?? [];
|
||||
let items: Array<{ rawName: string; quantity?: string; unit?: string; aisle?: string; inPantry?: boolean }> = data.items ?? [];
|
||||
|
||||
if (data.fromMealPlanWeek) {
|
||||
const plan = await db.query.mealPlans.findFirst({
|
||||
@@ -54,14 +55,25 @@ export async function POST(req: NextRequest) {
|
||||
});
|
||||
|
||||
// Simple merge by rawName (case-insensitive)
|
||||
const merged = new Map<string, { rawName: string; quantity?: string; unit?: string }>();
|
||||
const merged = new Map<string, { rawName: string; quantity?: string; unit?: string; ingredientId: string | null }>();
|
||||
for (const ing of ings) {
|
||||
const key = ing.rawName.toLowerCase();
|
||||
if (!merged.has(key)) {
|
||||
merged.set(key, { rawName: ing.rawName, quantity: ing.quantity ?? undefined, unit: ing.unit ?? undefined });
|
||||
merged.set(key, {
|
||||
rawName: ing.rawName,
|
||||
quantity: ing.quantity ?? undefined,
|
||||
unit: ing.unit ?? undefined,
|
||||
ingredientId: ing.ingredientId,
|
||||
});
|
||||
}
|
||||
}
|
||||
items = Array.from(merged.values());
|
||||
const mergedItems = Array.from(merged.values());
|
||||
|
||||
// Reduce/flag quantities already covered by the user's pantry. Conservative: never silently
|
||||
// drops an item — fully-covered items are still inserted, flagged `inPantry`, so nothing
|
||||
// disappears from view without the user seeing it.
|
||||
const pantry = await db.query.pantryItems.findMany({ where: eq(pantryItems.userId, session!.user.id) });
|
||||
items = applyPantryToItems(mergedItems, pantry);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,7 +94,8 @@ export async function POST(req: NextRequest) {
|
||||
quantity: item.quantity,
|
||||
unit: item.unit,
|
||||
aisle: item.aisle,
|
||||
checked: false,
|
||||
checked: item.inPantry === true && !item.quantity,
|
||||
inPantry: item.inPantry ?? false,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import {
|
||||
db,
|
||||
eq,
|
||||
or,
|
||||
users,
|
||||
recipes,
|
||||
recipeIngredients,
|
||||
recipeSteps,
|
||||
recipePhotos,
|
||||
recipeNotes,
|
||||
ratings,
|
||||
favorites,
|
||||
comments,
|
||||
collections,
|
||||
collectionRecipes,
|
||||
collectionFavorites,
|
||||
cookingHistory,
|
||||
notifications,
|
||||
userFollows,
|
||||
mealPlans,
|
||||
mealPlanEntries,
|
||||
pantryItems,
|
||||
shoppingLists,
|
||||
shoppingListItems,
|
||||
webhooks,
|
||||
apiKeys,
|
||||
pushSubscriptions,
|
||||
userNutritionGoals,
|
||||
userAllergens,
|
||||
userModelPrefs,
|
||||
userUsage,
|
||||
messages,
|
||||
conversations,
|
||||
} from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const userId = session!.user.id;
|
||||
|
||||
const limited = await applyRateLimit(`rl:export:${userId}`, 3, 3600);
|
||||
if (limited) return limited;
|
||||
|
||||
const [
|
||||
profileRows,
|
||||
userRecipes,
|
||||
userRatings,
|
||||
userComments,
|
||||
userNotes,
|
||||
userFavorites,
|
||||
following,
|
||||
followers,
|
||||
userCollections,
|
||||
userCookingHistory,
|
||||
userNotifications,
|
||||
userMealPlans,
|
||||
userPantryItems,
|
||||
userShoppingLists,
|
||||
userWebhooks,
|
||||
userApiKeys,
|
||||
userPushSubscriptions,
|
||||
userNutritionGoalsRows,
|
||||
userAllergenRows,
|
||||
userMessages,
|
||||
userModelPrefsRows,
|
||||
userUsageRows,
|
||||
] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
name: users.name,
|
||||
username: users.username,
|
||||
bio: users.bio,
|
||||
privateBio: users.privateBio,
|
||||
avatarUrl: users.avatarUrl,
|
||||
role: users.role,
|
||||
tier: users.tier,
|
||||
unitPref: users.unitPref,
|
||||
locale: users.locale,
|
||||
createdAt: users.createdAt,
|
||||
updatedAt: users.updatedAt,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, userId))
|
||||
.limit(1),
|
||||
db.select().from(recipes).where(eq(recipes.authorId, userId)),
|
||||
db.select().from(ratings).where(eq(ratings.userId, userId)),
|
||||
db.select().from(comments).where(eq(comments.userId, userId)),
|
||||
db.select().from(recipeNotes).where(eq(recipeNotes.userId, userId)),
|
||||
db.select().from(favorites).where(eq(favorites.userId, userId)),
|
||||
db
|
||||
.select({ followingId: userFollows.followingId, createdAt: userFollows.createdAt })
|
||||
.from(userFollows)
|
||||
.where(eq(userFollows.followerId, userId)),
|
||||
db
|
||||
.select({ followerId: userFollows.followerId, createdAt: userFollows.createdAt })
|
||||
.from(userFollows)
|
||||
.where(eq(userFollows.followingId, userId)),
|
||||
db.select().from(collections).where(eq(collections.userId, userId)),
|
||||
db.select().from(cookingHistory).where(eq(cookingHistory.userId, userId)),
|
||||
db.select().from(notifications).where(eq(notifications.userId, userId)),
|
||||
db.select().from(mealPlans).where(eq(mealPlans.userId, userId)),
|
||||
db.select().from(pantryItems).where(eq(pantryItems.userId, userId)),
|
||||
db.select().from(shoppingLists).where(eq(shoppingLists.userId, userId)),
|
||||
db
|
||||
.select({
|
||||
id: webhooks.id,
|
||||
url: webhooks.url,
|
||||
events: webhooks.events,
|
||||
active: webhooks.active,
|
||||
createdAt: webhooks.createdAt,
|
||||
})
|
||||
.from(webhooks)
|
||||
.where(eq(webhooks.userId, userId)),
|
||||
db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
})
|
||||
.from(apiKeys)
|
||||
.where(eq(apiKeys.userId, userId)),
|
||||
db
|
||||
.select({ id: pushSubscriptions.id, endpoint: pushSubscriptions.endpoint, createdAt: pushSubscriptions.createdAt })
|
||||
.from(pushSubscriptions)
|
||||
.where(eq(pushSubscriptions.userId, userId)),
|
||||
db.select().from(userNutritionGoals).where(eq(userNutritionGoals.userId, userId)),
|
||||
db.select().from(userAllergens).where(eq(userAllergens.userId, userId)),
|
||||
db
|
||||
.select({
|
||||
id: messages.id,
|
||||
conversationId: messages.conversationId,
|
||||
content: messages.content,
|
||||
createdAt: messages.createdAt,
|
||||
})
|
||||
.from(messages)
|
||||
.where(eq(messages.senderId, userId)),
|
||||
db.select().from(userModelPrefs).where(eq(userModelPrefs.userId, userId)),
|
||||
db.select().from(userUsage).where(eq(userUsage.userId, userId)),
|
||||
]);
|
||||
|
||||
const profile = profileRows[0] ?? null;
|
||||
|
||||
// Recipe sub-data (ingredients/steps/photos) scoped to this user's own recipes.
|
||||
const recipeIds = userRecipes.map((r) => r.id);
|
||||
const [ingredientsRows, stepsRows, photosRows] = recipeIds.length
|
||||
? await Promise.all([
|
||||
db.select().from(recipeIngredients).where(or(...recipeIds.map((id) => eq(recipeIngredients.recipeId, id)))),
|
||||
db.select().from(recipeSteps).where(or(...recipeIds.map((id) => eq(recipeSteps.recipeId, id)))),
|
||||
db.select().from(recipePhotos).where(or(...recipeIds.map((id) => eq(recipePhotos.recipeId, id)))),
|
||||
])
|
||||
: [[], [], []];
|
||||
|
||||
const mealPlanIds = userMealPlans.map((p) => p.id);
|
||||
const mealPlanEntriesRows = mealPlanIds.length
|
||||
? await db.select().from(mealPlanEntries).where(or(...mealPlanIds.map((id) => eq(mealPlanEntries.mealPlanId, id))))
|
||||
: [];
|
||||
|
||||
const shoppingListIds = userShoppingLists.map((l) => l.id);
|
||||
const shoppingListItemsRows = shoppingListIds.length
|
||||
? await db.select().from(shoppingListItems).where(or(...shoppingListIds.map((id) => eq(shoppingListItems.listId, id))))
|
||||
: [];
|
||||
|
||||
const collectionIds = userCollections.map((c) => c.id);
|
||||
const [collectionRecipesRows, collectionFavoritesRows] = collectionIds.length
|
||||
? await Promise.all([
|
||||
db.select().from(collectionRecipes).where(or(...collectionIds.map((id) => eq(collectionRecipes.collectionId, id)))),
|
||||
db.select().from(collectionFavorites).where(eq(collectionFavorites.userId, userId)),
|
||||
])
|
||||
: [[], await db.select().from(collectionFavorites).where(eq(collectionFavorites.userId, userId))];
|
||||
|
||||
const conversationIds = [...new Set(userMessages.map((m) => m.conversationId))];
|
||||
const conversationRows = conversationIds.length
|
||||
? await db.select().from(conversations).where(or(...conversationIds.map((id) => eq(conversations.id, id))))
|
||||
: [];
|
||||
|
||||
const exportData = {
|
||||
exportedAt: new Date().toISOString(),
|
||||
profile,
|
||||
recipes: userRecipes.map((r) => ({
|
||||
...r,
|
||||
ingredients: ingredientsRows.filter((i) => i.recipeId === r.id),
|
||||
steps: stepsRows.filter((s) => s.recipeId === r.id),
|
||||
photos: photosRows.filter((p) => p.recipeId === r.id),
|
||||
})),
|
||||
ratings: userRatings,
|
||||
comments: userComments,
|
||||
recipeNotes: userNotes,
|
||||
favorites: userFavorites,
|
||||
social: {
|
||||
following,
|
||||
followers,
|
||||
},
|
||||
collections: userCollections.map((c) => ({
|
||||
...c,
|
||||
recipeIds: collectionRecipesRows.filter((cr) => cr.collectionId === c.id).map((cr) => cr.recipeId),
|
||||
})),
|
||||
favoriteCollections: collectionFavoritesRows,
|
||||
cookingHistory: userCookingHistory,
|
||||
notifications: userNotifications,
|
||||
mealPlans: userMealPlans.map((p) => ({
|
||||
...p,
|
||||
entries: mealPlanEntriesRows.filter((e) => e.mealPlanId === p.id),
|
||||
})),
|
||||
pantryItems: userPantryItems,
|
||||
shoppingLists: userShoppingLists.map((l) => ({
|
||||
...l,
|
||||
items: shoppingListItemsRows.filter((i) => i.listId === l.id),
|
||||
})),
|
||||
webhooks: userWebhooks,
|
||||
apiKeys: userApiKeys,
|
||||
pushSubscriptions: userPushSubscriptions,
|
||||
nutritionGoals: userNutritionGoalsRows,
|
||||
allergens: userAllergenRows,
|
||||
modelPreferences: userModelPrefsRows,
|
||||
usage: userUsageRows,
|
||||
messages: userMessages.map((m) => {
|
||||
const conversation = conversationRows.find((c) => c.id === m.conversationId);
|
||||
const otherUserId = conversation ? (conversation.userAId === userId ? conversation.userBId : conversation.userAId) : null;
|
||||
return { ...m, otherUserId };
|
||||
}),
|
||||
};
|
||||
|
||||
const dateStr = new Date().toISOString().slice(0, 10);
|
||||
|
||||
return new NextResponse(JSON.stringify(exportData, null, 2), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Disposition": `attachment; filename="epicure-data-export-${dateStr}.json"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user