feat: implement remaining TODO.md feature ideas + fix mobile headers

Implements the six previously-unscoped feature ideas plus a mobile
layout fix reported via screenshot:

- Mobile: Recipes/Collections/Pantry/Meal Plan/Shopping Lists headers
  now stack and wrap instead of clipping buttons on narrow viewports.
- Recipe diff/compare view: word/list diff against any past version,
  next to Restore in version history.
- Shared meal plans & shopping lists: new shoppingListMembers/
  mealPlanMembers tables (viewer/editor roles, mirrors
  collectionMembers), share dialogs, membership-checked routes.
- PDF cookbook export: /print/collection/[id] renders a whole
  collection with page breaks, using the existing print-CSS pattern
  instead of adding a PDF rendering dependency.
- Grocery delivery handoff: shopping lists can copy-as-text (works
  today) or send to Instacart once INSTACART_API_KEY is configured
  (stub adapter — real API needs a partner agreement).
- Personalized "For You" feed tab: ranks public recipes by tag/
  dietary overlap with the user's favorited/highly-rated history.
- PWA: added manifest.json + icons on top of the existing service
  worker so the app is installable; cook-mode pages were already
  cached for offline use.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-02 12:13:00 +02:00
parent d2faf98ac1
commit e5d1080fb9
56 changed files with 6096 additions and 74 deletions
+69
View File
@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, users, favorites, ratings, eq, and, ne, gte, notInArray, inArray, desc } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { buildPreferenceMap, rankForYou } from "@/lib/for-you-ranking";
export async function GET(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const userId = session!.user.id;
const { searchParams } = new URL(req.url);
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
// Recipes the user has favorited, or rated 4+, define their taste profile.
const [favoritedRows, highRatedRows] = await Promise.all([
db.select({ recipeId: favorites.recipeId }).from(favorites).where(eq(favorites.userId, userId)),
db.select({ recipeId: ratings.recipeId }).from(ratings).where(and(eq(ratings.userId, userId), gte(ratings.score, 4))),
]);
const likedIds = [...new Set([...favoritedRows.map((r) => r.recipeId), ...highRatedRows.map((r) => r.recipeId)])];
const likedRecipes = likedIds.length > 0
? await db.select({ tags: recipes.tags, dietaryTags: recipes.dietaryTags }).from(recipes).where(inArray(recipes.id, likedIds))
: [];
const preferences = buildPreferenceMap(likedRecipes);
const excludeIds = likedIds.length > 0 ? likedIds : ["__none__"];
const candidates = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
aiGenerated: recipes.aiGenerated,
createdAt: recipes.createdAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
tags: recipes.tags,
dietaryTags: recipes.dietaryTags,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(and(
eq(recipes.visibility, "public"),
ne(recipes.authorId, userId),
notInArray(recipes.id, excludeIds)
))
.orderBy(desc(recipes.createdAt))
.limit(200); // score a bounded recent window rather than the whole table
const ranked = preferences.size > 0
? rankForYou(candidates, preferences)
: [...candidates].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
const data = ranked.slice(0, limit).map(({ tags: _tags, dietaryTags: _dietaryTags, ...r }) => ({
...r,
createdAt: r.createdAt.toISOString(),
}));
return NextResponse.json({ data });
}
@@ -0,0 +1,137 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-1" } };
vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(),
}));
const { mockPlanFindFirst, mockMemberFindFirst, mockMemberFindMany, mockUserFindFirst, mockInsertValues, mockInsertPlanValues, mockDeleteWhere } = vi.hoisted(() => ({
mockPlanFindFirst: vi.fn(),
mockMemberFindFirst: vi.fn(),
mockMemberFindMany: vi.fn(),
mockUserFindFirst: vi.fn(),
mockInsertValues: vi.fn().mockResolvedValue(undefined),
mockInsertPlanValues: vi.fn().mockResolvedValue(undefined),
mockDeleteWhere: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@epicure/db", () => ({
db: {
query: {
mealPlans: { findFirst: mockPlanFindFirst },
mealPlanMembers: { findFirst: mockMemberFindFirst, findMany: mockMemberFindMany },
users: { findFirst: mockUserFindFirst },
},
insert: vi.fn(() => ({ values: mockInsertValues })),
delete: vi.fn(() => ({ where: mockDeleteWhere })),
},
mealPlans: { id: "id", userId: "user_id", weekStart: "week_start" },
mealPlanMembers: { id: "id", mealPlanId: "meal_plan_id", userId: "user_id" },
users: { id: "id", email: "email" },
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
and: vi.fn((...args) => ({ args, op: "and" })),
}));
const { requireSession } = await import("@/lib/api-auth");
import { GET, POST, DELETE } from "../route";
const ctx = { params: Promise.resolve({ weekStart: "2026-06-01" }) };
function makeRequest(method: string, body?: unknown, search = "") {
return new NextRequest(`http://localhost/api/v1/meal-plans/2026-06-01/members${search}`, {
method,
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
});
describe("GET /api/v1/meal-plans/[weekStart]/members", () => {
it("returns an empty list when the owner has no plan for this week yet", async () => {
mockPlanFindFirst.mockResolvedValue(undefined);
const res = await GET(makeRequest("GET"), ctx);
expect(res.status).toBe(200);
expect(await res.json()).toEqual([]);
});
it("returns members for an existing plan", async () => {
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
mockMemberFindMany.mockResolvedValue([
{ id: "m1", userId: "user-2", role: "editor", createdAt: new Date(), user: { name: "Bob", username: null, avatarUrl: null } },
]);
const res = await GET(makeRequest("GET"), ctx);
const body = await res.json() as unknown[];
expect(body).toHaveLength(1);
});
});
describe("POST /api/v1/meal-plans/[weekStart]/members", () => {
it("returns 400 on invalid body", async () => {
const res = await POST(makeRequest("POST", { role: "viewer" }), ctx);
expect(res.status).toBe(400);
});
it("returns 404 when the target user doesn't exist", async () => {
mockUserFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(404);
});
it("returns 400 when inviting yourself", async () => {
mockUserFindFirst.mockResolvedValue({ id: "user-1" });
const res = await POST(makeRequest("POST", { email: "a@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(400);
});
it("auto-creates the plan for the week and invites the member", async () => {
mockUserFindFirst.mockResolvedValue({ id: "user-2" });
mockPlanFindFirst.mockResolvedValue(undefined); // no plan yet for this week
mockMemberFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "editor" }), ctx);
expect(res.status).toBe(201);
expect(mockInsertValues).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-1", weekStart: "2026-06-01" }));
expect(mockInsertValues).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-2", role: "editor" }));
});
it("returns 409 when already a member", async () => {
mockUserFindFirst.mockResolvedValue({ id: "user-2" });
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1", weekStart: "2026-06-01" });
mockMemberFindFirst.mockResolvedValue({ id: "existing" });
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(409);
});
});
describe("DELETE /api/v1/meal-plans/[weekStart]/members", () => {
it("returns 400 when memberId is missing", async () => {
const res = await DELETE(makeRequest("DELETE"), ctx);
expect(res.status).toBe(400);
});
it("returns 404 when the owner has no plan for this week", async () => {
mockPlanFindFirst.mockResolvedValue(undefined);
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(404);
});
it("returns 403 when caller is neither owner nor the member themselves", async () => {
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-2" });
vi.mocked(requireSession).mockResolvedValue({ session: { user: { id: "user-3" } } as never, response: null });
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(403);
});
it("allows the owner to remove a member", async () => {
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-2" });
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(204);
});
});
@@ -0,0 +1,122 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, mealPlans, mealPlanMembers, users, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ weekStart: string }> };
async function getOrCreatePlan(userId: string, weekStart: string) {
const existing = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, userId), eq(mealPlans.weekStart, weekStart)),
});
if (existing) return existing;
const id = crypto.randomUUID();
await db.insert(mealPlans).values({ id, userId, weekStart });
return { id, userId, weekStart, createdAt: new Date() };
}
// ─── GET /api/v1/meal-plans/[weekStart]/members ──────────────────────────────
// Owner only — returns members joined with basic user info.
export async function GET(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { weekStart } = await params;
const plan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, session!.user.id), eq(mealPlans.weekStart, weekStart)),
});
if (!plan) return NextResponse.json([]);
const members = await db.query.mealPlanMembers.findMany({
where: eq(mealPlanMembers.mealPlanId, plan.id),
with: { user: true },
});
return NextResponse.json(
members.map((m) => ({
id: m.id,
userId: m.userId,
role: m.role,
createdAt: m.createdAt,
user: { name: m.user.name, username: m.user.username, avatarUrl: m.user.avatarUrl },
}))
);
}
// ─── POST /api/v1/meal-plans/[weekStart]/members ─────────────────────────────
// Owner only — invite by email or userId. Auto-creates the plan for this week if missing.
const InviteSchema = z
.object({
email: z.string().email().optional(),
userId: z.string().optional(),
role: z.enum(["viewer", "editor"]),
})
.refine((d) => d.email !== undefined || d.userId !== undefined, {
message: "Provide either email or userId",
});
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { weekStart } = await params;
const body = await req.json() as unknown;
const parsed = InviteSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const { email, userId, role } = parsed.data;
const targetUser = await db.query.users.findFirst({
where: email ? eq(users.email, email) : eq(users.id, userId!),
});
if (!targetUser) return NextResponse.json({ error: "User not found" }, { status: 404 });
if (targetUser.id === session!.user.id) {
return NextResponse.json({ error: "Cannot invite yourself" }, { status: 400 });
}
const plan = await getOrCreatePlan(session!.user.id, weekStart);
const existing = await db.query.mealPlanMembers.findFirst({
where: and(eq(mealPlanMembers.mealPlanId, plan.id), eq(mealPlanMembers.userId, targetUser.id)),
});
if (existing) return NextResponse.json({ error: "Already a member" }, { status: 409 });
const memberId = crypto.randomUUID();
await db.insert(mealPlanMembers).values({
id: memberId,
mealPlanId: plan.id,
userId: targetUser.id,
role,
});
return NextResponse.json({ id: memberId, mealPlanId: plan.id }, { status: 201 });
}
// ─── DELETE /api/v1/meal-plans/[weekStart]/members?memberId=… ────────────────
// Owner OR the member themselves can remove.
export async function DELETE(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { weekStart } = await params;
const memberId = req.nextUrl.searchParams.get("memberId");
if (!memberId) return NextResponse.json({ error: "memberId required" }, { status: 400 });
const plan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, session!.user.id), eq(mealPlans.weekStart, weekStart)),
});
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
const member = await db.query.mealPlanMembers.findFirst({
where: and(eq(mealPlanMembers.id, memberId), eq(mealPlanMembers.mealPlanId, plan.id)),
});
if (!member) return NextResponse.json({ error: "Not found" }, { status: 404 });
const isOwner = plan.userId === session!.user.id;
const isSelf = member.userId === session!.user.id;
if (!isOwner && !isSelf) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
await db.delete(mealPlanMembers).where(eq(mealPlanMembers.id, memberId));
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-2" } };
vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(),
}));
vi.mock("@/lib/webhooks", () => ({
dispatchWebhook: vi.fn(),
}));
const { mockPlanFindFirst, mockMemberFindFirst, mockRecipeFindFirst, mockInsertValues, mockDeleteWhere } = vi.hoisted(() => ({
mockPlanFindFirst: vi.fn(),
mockMemberFindFirst: vi.fn(),
mockRecipeFindFirst: vi.fn(),
mockInsertValues: vi.fn().mockResolvedValue(undefined),
mockDeleteWhere: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@epicure/db", () => ({
db: {
query: {
mealPlans: { findFirst: mockPlanFindFirst },
mealPlanMembers: { findFirst: mockMemberFindFirst },
recipes: { findFirst: mockRecipeFindFirst },
},
insert: vi.fn(() => ({ values: mockInsertValues })),
delete: vi.fn(() => ({ where: mockDeleteWhere })),
},
mealPlans: { id: "id", userId: "user_id" },
mealPlanMembers: { mealPlanId: "meal_plan_id", userId: "user_id" },
mealPlanEntries: { id: "id", mealPlanId: "meal_plan_id", day: "day", mealType: "meal_type" },
recipes: { id: "id", authorId: "author_id", visibility: "visibility" },
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
and: vi.fn((...args) => ({ args, op: "and" })),
or: vi.fn((...args) => ({ args, op: "or" })),
ne: vi.fn((a, b) => ({ a, b, op: "ne" })),
}));
const { requireSession } = await import("@/lib/api-auth");
import { POST, DELETE } from "../route";
const ctx = { params: Promise.resolve({ mealPlanId: "plan-1" }) };
function makeRequest(method: string, body?: unknown, search = "") {
return new NextRequest(`http://localhost/api/v1/meal-plans/shared/plan-1/entries${search}`, {
method,
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
});
const validBody = { day: "mon", mealType: "dinner", recipeId: "r-1", servings: 2 };
describe("POST /api/v1/meal-plans/shared/[mealPlanId]/entries", () => {
it("returns 404 when the caller has no access to the plan", async () => {
mockMemberFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", validBody), ctx);
expect(res.status).toBe(404);
});
it("returns 403 for a viewer trying to add an entry", async () => {
mockMemberFindFirst.mockResolvedValue({ role: "viewer" });
const res = await POST(makeRequest("POST", validBody), ctx);
expect(res.status).toBe(403);
});
it("allows an editor to add an entry", async () => {
mockMemberFindFirst.mockResolvedValue({ role: "editor" });
mockRecipeFindFirst.mockResolvedValue({ id: "r-1" });
const res = await POST(makeRequest("POST", validBody), ctx);
expect(res.status).toBe(201);
expect(mockInsertValues).toHaveBeenCalledWith(expect.objectContaining({ mealPlanId: "plan-1", day: "mon" }));
});
it("returns 404 when the recipe isn't accessible to the editor", async () => {
mockMemberFindFirst.mockResolvedValue({ role: "editor" });
mockRecipeFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", validBody), ctx);
expect(res.status).toBe(404);
});
});
describe("DELETE /api/v1/meal-plans/shared/[mealPlanId]/entries", () => {
it("returns 403 for a viewer trying to remove an entry", async () => {
mockMemberFindFirst.mockResolvedValue({ role: "viewer" });
const res = await DELETE(makeRequest("DELETE", undefined, "?entryId=e1"), ctx);
expect(res.status).toBe(403);
});
it("allows an editor to remove an entry", async () => {
mockMemberFindFirst.mockResolvedValue({ role: "editor" });
const res = await DELETE(makeRequest("DELETE", undefined, "?entryId=e1"), ctx);
expect(res.status).toBe(204);
});
});
@@ -0,0 +1,81 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, mealPlanEntries, recipes, eq, and, or, ne } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getMealPlanAccessById, canWriteMealPlan } from "@/lib/meal-plan-access";
import { dispatchWebhook } from "@/lib/webhooks";
type Params = { params: Promise<{ mealPlanId: string }> };
const Schema = z.object({
day: z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"]),
mealType: z.enum(["breakfast", "lunch", "dinner", "snack"]),
recipeId: z.string().optional(),
servings: z.number().int().min(1).max(100).default(2),
note: z.string().max(500).optional(),
});
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { mealPlanId } = await params;
const access = await getMealPlanAccessById(mealPlanId, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!canWriteMealPlan(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
if (parsed.data.recipeId) {
const recipe = await db.query.recipes.findFirst({
where: and(
eq(recipes.id, parsed.data.recipeId),
or(eq(recipes.authorId, session!.user.id), ne(recipes.visibility, "private"))
),
});
if (!recipe) return NextResponse.json({ error: "Recipe not found" }, { status: 404 });
}
await db.delete(mealPlanEntries).where(
and(
eq(mealPlanEntries.mealPlanId, mealPlanId),
eq(mealPlanEntries.day, parsed.data.day),
eq(mealPlanEntries.mealType, parsed.data.mealType)
)
);
const entryId = crypto.randomUUID();
await db.insert(mealPlanEntries).values({
id: entryId,
mealPlanId,
day: parsed.data.day,
mealType: parsed.data.mealType,
recipeId: parsed.data.recipeId,
servings: parsed.data.servings,
note: parsed.data.note,
});
void dispatchWebhook(access.plan.userId, "meal_plan.updated", { mealPlanId, day: parsed.data.day, mealType: parsed.data.mealType });
return NextResponse.json({ id: entryId }, { status: 201 });
}
export async function DELETE(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { mealPlanId } = await params;
const access = await getMealPlanAccessById(mealPlanId, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!canWriteMealPlan(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const entryId = req.nextUrl.searchParams.get("entryId");
if (!entryId) return NextResponse.json({ error: "entryId required" }, { status: 400 });
await db.delete(mealPlanEntries).where(
and(eq(mealPlanEntries.id, entryId), eq(mealPlanEntries.mealPlanId, mealPlanId))
);
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from "next/server";
import { db, mealPlans, users, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getMealPlanAccessById } from "@/lib/meal-plan-access";
type Params = { params: Promise<{ mealPlanId: string }> };
export async function GET(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { mealPlanId } = await params;
const access = await getMealPlanAccessById(mealPlanId, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
const plan = await db.query.mealPlans.findFirst({
where: eq(mealPlans.id, mealPlanId),
with: {
entries: { with: { recipe: { with: { photos: true } } } },
},
});
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
const owner = await db.query.users.findFirst({ where: eq(users.id, plan.userId) });
return NextResponse.json({ ...plan, role: access.role, owner: owner ? { name: owner.name } : null });
}
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import { db, shoppingLists, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getShoppingListAccess } from "@/lib/shopping-list-access";
import { buildGroceryExportPayload } from "@/lib/grocery-export";
import { createInstacartShoppingListLink } from "@/lib/grocery-providers/instacart";
type Params = { params: Promise<{ id: string }> };
export async function POST(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
const list = await db.query.shoppingLists.findFirst({
where: eq(shoppingLists.id, id),
with: { items: true },
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const payload = buildGroceryExportPayload(list);
try {
const result = await createInstacartShoppingListLink(payload);
if (!result) return NextResponse.json({ error: "Instacart is not configured" }, { status: 501 });
return NextResponse.json(result);
} catch (err) {
return NextResponse.json({ error: String(err instanceof Error ? err.message : err) }, { status: 501 });
}
}
@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from "next/server";
import { db, shoppingLists, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getShoppingListAccess } from "@/lib/shopping-list-access";
import { buildGroceryExportPayload } from "@/lib/grocery-export";
type Params = { params: Promise<{ id: string }> };
export async function GET(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
const list = await db.query.shoppingLists.findFirst({
where: eq(shoppingLists.id, id),
with: { items: true },
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const payload = buildGroceryExportPayload(list);
return NextResponse.json(payload);
}
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { db, shoppingLists, shoppingListItems, eq, and } from "@epicure/db";
import { db, shoppingListItems, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
type Params = { params: Promise<{ id: string; itemId: string }> };
@@ -9,10 +10,9 @@ export async function PUT(req: NextRequest, { params }: Params) {
if (response) return response;
const { id, itemId } = await params;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)),
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await req.json() as { checked?: boolean };
await db.update(shoppingListItems)
@@ -1,7 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, shoppingLists, shoppingListItems, eq, and } from "@epicure/db";
import { db, shoppingListItems } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
const AddItemsSchema = z.object({
items: z.array(z.object({
@@ -19,10 +20,9 @@ export async function POST(req: NextRequest, { params }: Params) {
if (response) return response;
const { id } = await params;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)),
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await req.json() as unknown;
const parsed = AddItemsSchema.safeParse(body);
@@ -0,0 +1,149 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-1" } };
vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(),
}));
const { mockListFindFirst, mockMemberFindFirst, mockMemberFindMany, mockUserFindFirst, mockInsertValues, mockDeleteWhere } = vi.hoisted(() => ({
mockListFindFirst: vi.fn(),
mockMemberFindFirst: vi.fn(),
mockMemberFindMany: vi.fn(),
mockUserFindFirst: vi.fn(),
mockInsertValues: vi.fn().mockResolvedValue(undefined),
mockDeleteWhere: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@epicure/db", () => ({
db: {
query: {
shoppingLists: { findFirst: mockListFindFirst },
shoppingListMembers: { findFirst: mockMemberFindFirst, findMany: mockMemberFindMany },
users: { findFirst: mockUserFindFirst },
},
insert: vi.fn(() => ({ values: mockInsertValues })),
delete: vi.fn(() => ({ where: mockDeleteWhere })),
},
shoppingLists: { id: "id", userId: "user_id" },
shoppingListMembers: { id: "id", listId: "list_id", userId: "user_id" },
users: { id: "id", email: "email" },
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
and: vi.fn((...args) => ({ args, op: "and" })),
}));
const { requireSession } = await import("@/lib/api-auth");
import { GET, POST, DELETE } from "../route";
const ctx = { params: Promise.resolve({ id: "list-1" }) };
function makeRequest(method: string, body?: unknown, search = "") {
return new NextRequest(`http://localhost/api/v1/shopping-lists/list-1/members${search}`, {
method,
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
});
describe("GET /api/v1/shopping-lists/[id]/members", () => {
it("returns 404 when the caller is not the owner", async () => {
mockListFindFirst.mockResolvedValue(undefined);
const res = await GET(makeRequest("GET"), ctx);
expect(res.status).toBe(404);
});
it("returns the member list for the owner", async () => {
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-1" });
mockMemberFindMany.mockResolvedValue([
{ id: "m1", userId: "user-2", role: "viewer", createdAt: new Date(), user: { name: "Bob", username: "bob", avatarUrl: null } },
]);
const res = await GET(makeRequest("GET"), ctx);
expect(res.status).toBe(200);
const body = await res.json() as unknown[];
expect(body).toHaveLength(1);
});
});
describe("POST /api/v1/shopping-lists/[id]/members", () => {
beforeEach(() => {
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-1" });
});
it("returns 404 when the caller is not the owner", async () => {
mockListFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(404);
});
it("returns 400 on invalid body", async () => {
const res = await POST(makeRequest("POST", { role: "viewer" }), ctx);
expect(res.status).toBe(400);
});
it("returns 404 when the target user doesn't exist", async () => {
mockUserFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(404);
});
it("returns 400 when inviting yourself", async () => {
mockUserFindFirst.mockResolvedValue({ id: "user-1", email: "a@test.com" });
const res = await POST(makeRequest("POST", { email: "a@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(400);
});
it("returns 409 when already a member", async () => {
mockUserFindFirst.mockResolvedValue({ id: "user-2", email: "b@test.com" });
mockMemberFindFirst.mockResolvedValue({ id: "existing" });
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
expect(res.status).toBe(409);
});
it("creates the membership on success", async () => {
mockUserFindFirst.mockResolvedValue({ id: "user-2", email: "b@test.com" });
mockMemberFindFirst.mockResolvedValue(undefined);
const res = await POST(makeRequest("POST", { email: "b@test.com", role: "editor" }), ctx);
expect(res.status).toBe(201);
expect(mockInsertValues).toHaveBeenCalledWith(expect.objectContaining({ listId: "list-1", userId: "user-2", role: "editor" }));
});
});
describe("DELETE /api/v1/shopping-lists/[id]/members", () => {
it("returns 400 when memberId is missing", async () => {
const res = await DELETE(makeRequest("DELETE"), ctx);
expect(res.status).toBe(400);
});
it("returns 404 when the member doesn't exist", async () => {
mockMemberFindFirst.mockResolvedValue(undefined);
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(404);
});
it("returns 403 when caller is neither owner nor the member themselves", async () => {
mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-2" });
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-3" });
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(403);
});
it("allows the owner to remove a member", async () => {
mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-2" });
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-1" });
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(204);
});
it("allows a member to remove themselves", async () => {
mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-1" });
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-3" });
const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
expect(res.status).toBe(204);
});
});
@@ -0,0 +1,127 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, shoppingLists, shoppingListMembers, users, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
// ─── GET /api/v1/shopping-lists/[id]/members ─────────────────────────────────
// Owner only — returns members joined with basic user info.
export async function GET(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)),
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const members = await db.query.shoppingListMembers.findMany({
where: eq(shoppingListMembers.listId, id),
with: { user: true },
});
const result = members.map((m) => ({
id: m.id,
userId: m.userId,
role: m.role,
createdAt: m.createdAt,
user: {
name: m.user.name,
username: m.user.username,
avatarUrl: m.user.avatarUrl,
},
}));
return NextResponse.json(result);
}
// ─── POST /api/v1/shopping-lists/[id]/members ────────────────────────────────
// Owner only — invite by email or userId.
const InviteSchema = z
.object({
email: z.string().email().optional(),
userId: z.string().optional(),
role: z.enum(["viewer", "editor"]),
})
.refine((d) => d.email !== undefined || d.userId !== undefined, {
message: "Provide either email or userId",
});
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)),
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const body = await req.json() as unknown;
const parsed = InviteSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const { email, userId, role } = parsed.data;
const targetUser = await db.query.users.findFirst({
where: email ? eq(users.email, email) : eq(users.id, userId!),
});
if (!targetUser) return NextResponse.json({ error: "User not found" }, { status: 404 });
if (targetUser.id === session!.user.id) {
return NextResponse.json({ error: "Cannot invite yourself" }, { status: 400 });
}
const existing = await db.query.shoppingListMembers.findFirst({
where: and(
eq(shoppingListMembers.listId, id),
eq(shoppingListMembers.userId, targetUser.id),
),
});
if (existing) return NextResponse.json({ error: "Already a member" }, { status: 409 });
const memberId = crypto.randomUUID();
await db.insert(shoppingListMembers).values({
id: memberId,
listId: id,
userId: targetUser.id,
role,
});
return NextResponse.json({ id: memberId }, { status: 201 });
}
// ─── DELETE /api/v1/shopping-lists/[id]/members?memberId=… ───────────────────
// Owner OR the member themselves can remove.
export async function DELETE(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const memberId = req.nextUrl.searchParams.get("memberId");
if (!memberId) return NextResponse.json({ error: "memberId required" }, { status: 400 });
const member = await db.query.shoppingListMembers.findFirst({
where: and(eq(shoppingListMembers.id, memberId), eq(shoppingListMembers.listId, id)),
});
if (!member) return NextResponse.json({ error: "Not found" }, { status: 404 });
const list = await db.query.shoppingLists.findFirst({
where: eq(shoppingLists.id, id),
});
const isOwner = list?.userId === session!.user.id;
const isSelf = member.userId === session!.user.id;
if (!isOwner && !isSelf) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
await db.delete(shoppingListMembers).where(eq(shoppingListMembers.id, memberId));
return new NextResponse(null, { status: 204 });
}
@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, shoppingLists, shoppingListItems, eq, and } from "@epicure/db";
import { db, shoppingLists, shoppingListItems, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { dispatchWebhook } from "@/lib/webhooks";
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
type Params = { params: Promise<{ id: string }> };
@@ -11,12 +12,14 @@ export async function GET(_req: NextRequest, { params }: Params) {
if (response) return response;
const { id } = await params;
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)),
where: eq(shoppingLists.id, id),
with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.rawName)] } },
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(list);
}
@@ -27,10 +30,9 @@ export async function PATCH(req: NextRequest, { params }: Params) {
if (response) return response;
const { id } = await params;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)),
});
if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = PatchSchema.safeParse(await req.json());
if (!body.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
@@ -38,7 +40,7 @@ export async function PATCH(req: NextRequest, { params }: Params) {
if (body.data.completed) {
// Mark all items as checked
await db.update(shoppingListItems).set({ checked: true }).where(eq(shoppingListItems.listId, id));
void dispatchWebhook(session!.user.id, "shopping_list.completed", { id, name: list.name });
void dispatchWebhook(session!.user.id, "shopping_list.completed", { id, name: access.list.name });
}
return NextResponse.json({ updated: true });
@@ -49,6 +51,10 @@ export async function DELETE(_req: NextRequest, { params }: Params) {
if (response) return response;
const { id } = await params;
await db.delete(shoppingLists).where(and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session!.user.id)));
const access = await getShoppingListAccess(id, session!.user.id);
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (access.role !== "owner") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
await db.delete(shoppingLists).where(eq(shoppingLists.id, id));
return new NextResponse(null, { status: 204 });
}