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:
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { buildPreferenceMap, scoreCandidate, rankForYou } from "../for-you-ranking";
|
||||
|
||||
describe("buildPreferenceMap", () => {
|
||||
it("counts tags and true dietary-tag keys across liked recipes", () => {
|
||||
const map = buildPreferenceMap([
|
||||
{ tags: ["spicy", "quick"], dietaryTags: { vegan: true, glutenFree: false } },
|
||||
{ tags: ["spicy"], dietaryTags: null },
|
||||
]);
|
||||
expect(map.get("spicy")).toBe(2);
|
||||
expect(map.get("quick")).toBe(1);
|
||||
expect(map.get("vegan")).toBe(1);
|
||||
expect(map.get("glutenFree")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns an empty map for no liked recipes", () => {
|
||||
expect(buildPreferenceMap([]).size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scoreCandidate", () => {
|
||||
it("sums preference weights for overlapping tags", () => {
|
||||
const prefs = new Map([["spicy", 3], ["vegan", 1]]);
|
||||
const score = scoreCandidate({ tags: ["spicy"], dietaryTags: { vegan: true } }, prefs);
|
||||
expect(score).toBe(4);
|
||||
});
|
||||
|
||||
it("scores 0 when nothing overlaps", () => {
|
||||
const prefs = new Map([["spicy", 3]]);
|
||||
expect(scoreCandidate({ tags: ["sweet"], dietaryTags: null }, prefs)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rankForYou", () => {
|
||||
const base = { dietaryTags: null };
|
||||
|
||||
it("sorts by score descending", () => {
|
||||
const prefs = new Map([["spicy", 5]]);
|
||||
const candidates = [
|
||||
{ id: "a", tags: ["sweet"], createdAt: new Date("2024-01-01"), ...base },
|
||||
{ id: "b", tags: ["spicy"], createdAt: new Date("2024-01-01"), ...base },
|
||||
];
|
||||
const ranked = rankForYou(candidates, prefs);
|
||||
expect(ranked.map((r) => r.id)).toEqual(["b", "a"]);
|
||||
});
|
||||
|
||||
it("breaks ties by recency", () => {
|
||||
const prefs = new Map<string, number>();
|
||||
const candidates = [
|
||||
{ id: "old", tags: [], createdAt: new Date("2024-01-01"), ...base },
|
||||
{ id: "new", tags: [], createdAt: new Date("2024-06-01"), ...base },
|
||||
];
|
||||
const ranked = rankForYou(candidates, prefs);
|
||||
expect(ranked.map((r) => r.id)).toEqual(["new", "old"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { buildGroceryExportPayload, groceryExportToText } from "../grocery-export";
|
||||
|
||||
describe("buildGroceryExportPayload", () => {
|
||||
it("maps unchecked items and drops checked ones", () => {
|
||||
const payload = buildGroceryExportPayload({
|
||||
name: "Weekly groceries",
|
||||
items: [
|
||||
{ rawName: "Milk", quantity: "1", unit: "L", checked: false },
|
||||
{ rawName: "Eggs", quantity: "12", unit: null, checked: true },
|
||||
],
|
||||
});
|
||||
expect(payload.listName).toBe("Weekly groceries");
|
||||
expect(payload.items).toEqual([{ name: "Milk", quantity: "1", unit: "L" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("groceryExportToText", () => {
|
||||
it("renders a plain-text list with quantities", () => {
|
||||
const text = groceryExportToText({
|
||||
listName: "Weekly groceries",
|
||||
items: [
|
||||
{ name: "Milk", quantity: "1", unit: "L" },
|
||||
{ name: "Bananas", quantity: null, unit: null },
|
||||
],
|
||||
});
|
||||
expect(text).toBe("Weekly groceries\n\n1 L Milk\nBananas");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const { mockPlanFindFirst, mockMemberFindFirst } = vi.hoisted(() => ({
|
||||
mockPlanFindFirst: vi.fn(),
|
||||
mockMemberFindFirst: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@epicure/db", () => ({
|
||||
db: {
|
||||
query: {
|
||||
mealPlans: { findFirst: mockPlanFindFirst },
|
||||
mealPlanMembers: { findFirst: mockMemberFindFirst },
|
||||
},
|
||||
},
|
||||
mealPlans: { id: "id", userId: "user_id" },
|
||||
mealPlanMembers: { mealPlanId: "meal_plan_id", userId: "user_id" },
|
||||
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
|
||||
and: vi.fn((...args) => ({ args, op: "and" })),
|
||||
}));
|
||||
|
||||
const { getMealPlanAccessById, canWriteMealPlan } = await import("../meal-plan-access");
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("getMealPlanAccessById", () => {
|
||||
it("returns null when the plan doesn't exist", async () => {
|
||||
mockPlanFindFirst.mockResolvedValue(undefined);
|
||||
expect(await getMealPlanAccessById("plan-1", "user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("grants owner role to the plan's userId", async () => {
|
||||
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
|
||||
const access = await getMealPlanAccessById("plan-1", "user-1");
|
||||
expect(access?.role).toBe("owner");
|
||||
});
|
||||
|
||||
it("grants the member's assigned role", async () => {
|
||||
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-owner" });
|
||||
mockMemberFindFirst.mockResolvedValue({ role: "viewer" });
|
||||
const access = await getMealPlanAccessById("plan-1", "user-2");
|
||||
expect(access?.role).toBe("viewer");
|
||||
});
|
||||
|
||||
it("returns null when the user is neither owner nor a member", async () => {
|
||||
mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-owner" });
|
||||
mockMemberFindFirst.mockResolvedValue(undefined);
|
||||
expect(await getMealPlanAccessById("plan-1", "user-2")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("canWriteMealPlan", () => {
|
||||
it("allows owner and editor, denies viewer", () => {
|
||||
expect(canWriteMealPlan("owner")).toBe(true);
|
||||
expect(canWriteMealPlan("editor")).toBe(true);
|
||||
expect(canWriteMealPlan("viewer")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const { mockListFindFirst, mockMemberFindFirst } = vi.hoisted(() => ({
|
||||
mockListFindFirst: vi.fn(),
|
||||
mockMemberFindFirst: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@epicure/db", () => ({
|
||||
db: {
|
||||
query: {
|
||||
shoppingLists: { findFirst: mockListFindFirst },
|
||||
shoppingListMembers: { findFirst: mockMemberFindFirst },
|
||||
},
|
||||
},
|
||||
shoppingLists: { id: "id", userId: "user_id" },
|
||||
shoppingListMembers: { listId: "list_id", userId: "user_id" },
|
||||
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
|
||||
and: vi.fn((...args) => ({ args, op: "and" })),
|
||||
}));
|
||||
|
||||
const { getShoppingListAccess, canWriteShoppingList } = await import("../shopping-list-access");
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("getShoppingListAccess", () => {
|
||||
it("returns null when the list doesn't exist", async () => {
|
||||
mockListFindFirst.mockResolvedValue(undefined);
|
||||
expect(await getShoppingListAccess("list-1", "user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("grants owner role to the list's userId", async () => {
|
||||
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-1" });
|
||||
const access = await getShoppingListAccess("list-1", "user-1");
|
||||
expect(access?.role).toBe("owner");
|
||||
});
|
||||
|
||||
it("grants the member's assigned role", async () => {
|
||||
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-owner" });
|
||||
mockMemberFindFirst.mockResolvedValue({ role: "editor" });
|
||||
const access = await getShoppingListAccess("list-1", "user-2");
|
||||
expect(access?.role).toBe("editor");
|
||||
});
|
||||
|
||||
it("returns null when the user is neither owner nor a member", async () => {
|
||||
mockListFindFirst.mockResolvedValue({ id: "list-1", userId: "user-owner" });
|
||||
mockMemberFindFirst.mockResolvedValue(undefined);
|
||||
expect(await getShoppingListAccess("list-1", "user-2")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("canWriteShoppingList", () => {
|
||||
it("allows owner and editor, denies viewer", () => {
|
||||
expect(canWriteShoppingList("owner")).toBe(true);
|
||||
expect(canWriteShoppingList("editor")).toBe(true);
|
||||
expect(canWriteShoppingList("viewer")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
export type TaggedRecipe = {
|
||||
id: string;
|
||||
tags: string[];
|
||||
dietaryTags: Record<string, boolean> | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
/** Collapses a recipe's tags + true dietary-tag keys into one flat tag list. */
|
||||
function tagSet(recipe: Pick<TaggedRecipe, "tags" | "dietaryTags">): string[] {
|
||||
const dietary = Object.entries(recipe.dietaryTags ?? {})
|
||||
.filter(([, v]) => v)
|
||||
.map(([k]) => k);
|
||||
return [...recipe.tags, ...dietary];
|
||||
}
|
||||
|
||||
/** Builds a tag → frequency map from the recipes a user has favorited/highly rated. */
|
||||
export function buildPreferenceMap(likedRecipes: Array<Pick<TaggedRecipe, "tags" | "dietaryTags">>): Map<string, number> {
|
||||
const map = new Map<string, number>();
|
||||
for (const recipe of likedRecipes) {
|
||||
for (const tag of tagSet(recipe)) {
|
||||
map.set(tag, (map.get(tag) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scores a candidate recipe by how many of its tags overlap with the user's
|
||||
* preference map (weighted by how often that tag shows up in their history).
|
||||
* Recency is used only as a tiebreaker (see rankForYou) — an empty preference
|
||||
* map scores everything 0, which the caller should treat as "fall back to
|
||||
* trending" rather than a meaningful ranking.
|
||||
*/
|
||||
export function scoreCandidate(candidate: Pick<TaggedRecipe, "tags" | "dietaryTags">, preferences: Map<string, number>): number {
|
||||
return tagSet(candidate).reduce((sum, tag) => sum + (preferences.get(tag) ?? 0), 0);
|
||||
}
|
||||
|
||||
export function rankForYou<T extends TaggedRecipe>(candidates: T[], preferences: Map<string, number>): T[] {
|
||||
return [...candidates]
|
||||
.map((c) => ({ c, score: scoreCandidate(c, preferences) }))
|
||||
.sort((a, b) => b.score - a.score || b.c.createdAt.getTime() - a.c.createdAt.getTime())
|
||||
.map(({ c }) => c);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
export type GroceryExportItem = {
|
||||
name: string;
|
||||
quantity: string | null;
|
||||
unit: string | null;
|
||||
};
|
||||
|
||||
export type GroceryExportPayload = {
|
||||
listName: string;
|
||||
items: GroceryExportItem[];
|
||||
};
|
||||
|
||||
type ShoppingListForExport = {
|
||||
name: string;
|
||||
items: Array<{ rawName: string; quantity: string | null; unit: string | null; checked: boolean }>;
|
||||
};
|
||||
|
||||
/** Maps a shopping list into a provider-agnostic export shape any grocery-delivery adapter can consume. */
|
||||
export function buildGroceryExportPayload(list: ShoppingListForExport): GroceryExportPayload {
|
||||
return {
|
||||
listName: list.name,
|
||||
items: list.items
|
||||
.filter((i) => !i.checked)
|
||||
.map((i) => ({ name: i.rawName, quantity: i.quantity, unit: i.unit })),
|
||||
};
|
||||
}
|
||||
|
||||
export function groceryExportToText(payload: GroceryExportPayload): string {
|
||||
const lines = payload.items.map((i) => {
|
||||
const qty = [i.quantity, i.unit].filter(Boolean).join(" ");
|
||||
return qty ? `${qty} ${i.name}` : i.name;
|
||||
});
|
||||
return [payload.listName, "", ...lines].join("\n");
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { GroceryExportPayload } from "@/lib/grocery-export";
|
||||
|
||||
/**
|
||||
* Stub adapter for the Instacart "Recipe & Shopping List" partner API.
|
||||
*
|
||||
* Not wired to a live endpoint — Instacart requires a signed partnership
|
||||
* agreement and a per-integration API key before any request can succeed.
|
||||
* This documents the request shape so activation is a config change, not a
|
||||
* rewrite, once `INSTACART_API_KEY` is issued.
|
||||
*
|
||||
* Real endpoint (per Instacart Developer Platform docs, subject to change):
|
||||
* POST https://connect.instacart.com/idp/v1/products/products_link
|
||||
* Authorization: Bearer <INSTACART_API_KEY>
|
||||
* Body: { title: string, link_type: "shopping_list", line_items: [{ name, quantity, unit }] }
|
||||
* Response contains a `products_link_url` the user is redirected to.
|
||||
*/
|
||||
export async function createInstacartShoppingListLink(
|
||||
payload: GroceryExportPayload
|
||||
): Promise<{ url: string } | null> {
|
||||
const apiKey = process.env["INSTACART_API_KEY"];
|
||||
if (!apiKey) return null;
|
||||
|
||||
throw new Error(
|
||||
"Instacart integration is stubbed — INSTACART_API_KEY is set but no live API call is wired up yet. " +
|
||||
`Would send list "${payload.listName}" with ${payload.items.length} item(s).`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { db, mealPlans, mealPlanMembers, eq, and } from "@epicure/db";
|
||||
|
||||
export type MealPlanRole = "owner" | "editor" | "viewer";
|
||||
|
||||
export type MealPlanAccess = {
|
||||
plan: typeof mealPlans.$inferSelect;
|
||||
role: MealPlanRole;
|
||||
};
|
||||
|
||||
/** Resolves a user's access to a meal plan by its id — owner, or member with their assigned role. Null if no access. */
|
||||
export async function getMealPlanAccessById(
|
||||
mealPlanId: string,
|
||||
userId: string
|
||||
): Promise<MealPlanAccess | null> {
|
||||
const plan = await db.query.mealPlans.findFirst({ where: eq(mealPlans.id, mealPlanId) });
|
||||
if (!plan) return null;
|
||||
if (plan.userId === userId) return { plan, role: "owner" };
|
||||
|
||||
const member = await db.query.mealPlanMembers.findFirst({
|
||||
where: and(eq(mealPlanMembers.mealPlanId, mealPlanId), eq(mealPlanMembers.userId, userId)),
|
||||
});
|
||||
if (!member) return null;
|
||||
|
||||
return { plan, role: member.role };
|
||||
}
|
||||
|
||||
export function canWriteMealPlan(role: MealPlanRole): boolean {
|
||||
return role === "owner" || role === "editor";
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { db, shoppingLists, shoppingListMembers, eq, and } from "@epicure/db";
|
||||
|
||||
export type ShoppingListRole = "owner" | "editor" | "viewer";
|
||||
|
||||
export type ShoppingListAccess = {
|
||||
list: typeof shoppingLists.$inferSelect;
|
||||
role: ShoppingListRole;
|
||||
};
|
||||
|
||||
/** Resolves a user's access to a shopping list — owner, or member with their assigned role. Null if no access. */
|
||||
export async function getShoppingListAccess(
|
||||
listId: string,
|
||||
userId: string
|
||||
): Promise<ShoppingListAccess | null> {
|
||||
const list = await db.query.shoppingLists.findFirst({ where: eq(shoppingLists.id, listId) });
|
||||
if (!list) return null;
|
||||
if (list.userId === userId) return { list, role: "owner" };
|
||||
|
||||
const member = await db.query.shoppingListMembers.findFirst({
|
||||
where: and(eq(shoppingListMembers.listId, listId), eq(shoppingListMembers.userId, userId)),
|
||||
});
|
||||
if (!member) return null;
|
||||
|
||||
return { list, role: member.role };
|
||||
}
|
||||
|
||||
export function canWriteShoppingList(role: ShoppingListRole): boolean {
|
||||
return role === "owner" || role === "editor";
|
||||
}
|
||||
Reference in New Issue
Block a user