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:
@@ -95,6 +95,15 @@ export function resetPasswordHtml(url: string) {
|
||||
);
|
||||
}
|
||||
|
||||
export function notificationEmailHtml(title: string, body: string, url: string) {
|
||||
return layout(
|
||||
`${title} — Epicure`,
|
||||
`<h1 style="margin:0 0 8px;font-size:24px;">${title}</h1>
|
||||
<p style="margin:0 0 4px;color:#57534e;line-height:1.6;">${body}</p>
|
||||
${btn(url, "View on Epicure")}`
|
||||
);
|
||||
}
|
||||
|
||||
export function welcomeHtml(name: string) {
|
||||
return layout(
|
||||
"Welcome to Epicure",
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { db, notifications } from "@epicure/db";
|
||||
import { db, notifications, users, recipes, eq } from "@epicure/db";
|
||||
import { randomUUID } from "crypto";
|
||||
import { sendPushNotification } from "./push";
|
||||
import { sendEmail, notificationEmailHtml } from "./email";
|
||||
import { getMessages, formatMessage } from "./i18n/server";
|
||||
|
||||
type NotificationType = "follow" | "comment" | "reply" | "reaction" | "rating" | "mention";
|
||||
|
||||
export async function createNotification(opts: {
|
||||
type CreateNotificationOpts = {
|
||||
userId: string;
|
||||
type: NotificationType;
|
||||
actorId: string;
|
||||
recipeId?: string;
|
||||
commentId?: string;
|
||||
}): Promise<void> {
|
||||
/** Rating score (1-5), only relevant for type "rating" — included in the push/email copy. */
|
||||
score?: number;
|
||||
};
|
||||
|
||||
export async function createNotification(opts: CreateNotificationOpts): Promise<void> {
|
||||
if (opts.userId === opts.actorId) return; // never notify yourself
|
||||
|
||||
await db.insert(notifications).values({
|
||||
id: randomUUID(),
|
||||
userId: opts.userId,
|
||||
@@ -19,4 +27,66 @@ export async function createNotification(opts: {
|
||||
recipeId: opts.recipeId,
|
||||
commentId: opts.commentId,
|
||||
});
|
||||
|
||||
// Push + email are best-effort side effects — never let a slow/failing SMTP
|
||||
// or push provider delay or break the caller (which already does `void
|
||||
// createNotification(...)`). Fire-and-forget from here too.
|
||||
void dispatchAlerts(opts).catch((err) => {
|
||||
console.error("[notifications] failed to dispatch push/email", err);
|
||||
});
|
||||
}
|
||||
|
||||
async function dispatchAlerts(opts: CreateNotificationOpts): Promise<void> {
|
||||
const [actor, recipient, recipe] = await Promise.all([
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, opts.actorId),
|
||||
columns: { name: true, username: true },
|
||||
}),
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, opts.userId),
|
||||
columns: { email: true, locale: true },
|
||||
}),
|
||||
opts.recipeId
|
||||
? db.query.recipes.findFirst({
|
||||
where: eq(recipes.id, opts.recipeId),
|
||||
columns: { title: true },
|
||||
})
|
||||
: Promise.resolve(undefined),
|
||||
]);
|
||||
|
||||
if (!actor || !recipient) return;
|
||||
|
||||
const messages = getMessages(recipient.locale);
|
||||
const n = messages.notifications as Record<string, unknown>;
|
||||
const detail = (n["detail"] ?? {}) as Record<string, string>;
|
||||
const pushTitle = (n["pushTitle"] ?? {}) as Record<string, string>;
|
||||
|
||||
const template = detail[opts.type] ?? (n[opts.type] as string | undefined);
|
||||
if (!template) return;
|
||||
|
||||
const body = formatMessage(template, {
|
||||
name: actor.name,
|
||||
title: recipe?.title ?? "",
|
||||
stars: opts.score != null ? String(opts.score) : "",
|
||||
});
|
||||
const title = pushTitle[opts.type] ?? "Epicure";
|
||||
|
||||
const url = opts.type === "follow"
|
||||
? (actor.username ? `/u/${actor.username}` : "/")
|
||||
: opts.recipeId ? `/recipes/${opts.recipeId}` : "/";
|
||||
|
||||
void sendPushNotification(opts.userId, { title, body, url }).catch((err) => {
|
||||
console.error("[notifications] push failed", err);
|
||||
});
|
||||
|
||||
if (recipient.email) {
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
void sendEmail({
|
||||
to: recipient.email,
|
||||
subject: title,
|
||||
html: notificationEmailHtml(title, body, `${baseUrl}${url}`),
|
||||
}).catch((err) => {
|
||||
console.error("[notifications] email failed", err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Conservative pantry-awareness for shopping list generation.
|
||||
*
|
||||
* Matching strategy:
|
||||
* 1. Reliable path: if both the shopping item and a pantry item reference the same
|
||||
* normalized `ingredientId`, they're the same ingredient.
|
||||
* 2. Fallback: normalize free-text `rawName` (case/whitespace/simple plural) and match exactly.
|
||||
* No fuzzy/AI matching — when normalization doesn't produce an exact match, treat as unmatched.
|
||||
*
|
||||
* Quantity handling: only subtract pantry quantity from the needed quantity when both
|
||||
* are parseable numbers in the same (normalized) unit. Otherwise leave the needed quantity
|
||||
* untouched and just flag `inPantry` so the user can decide for themselves.
|
||||
*/
|
||||
|
||||
export type PantrySourceItem = {
|
||||
ingredientId: string | null;
|
||||
rawName: string;
|
||||
quantity: string | null;
|
||||
unit: string | null;
|
||||
};
|
||||
|
||||
export type ShoppingSourceItem = {
|
||||
rawName: string;
|
||||
quantity?: string;
|
||||
unit?: string;
|
||||
ingredientId?: string | null;
|
||||
};
|
||||
|
||||
export type PantryAdjustedItem = {
|
||||
rawName: string;
|
||||
quantity?: string;
|
||||
unit?: string;
|
||||
inPantry: boolean;
|
||||
};
|
||||
|
||||
function normalizeName(name: string): string {
|
||||
const trimmed = name.toLowerCase().trim().replace(/\s+/g, " ");
|
||||
// Simple plural trim — strip a single trailing "s" for words longer than 3 chars.
|
||||
return trimmed.length > 3 && trimmed.endsWith("s") ? trimmed.slice(0, -1) : trimmed;
|
||||
}
|
||||
|
||||
function normalizeUnit(unit: string | null | undefined): string {
|
||||
return (unit ?? "").toLowerCase().trim();
|
||||
}
|
||||
|
||||
function formatQuantity(n: number): string {
|
||||
return Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/\.?0+$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces (or flags) each shopping item's needed quantity based on what's already in the pantry.
|
||||
* Never removes an item outright when the match is uncertain — always returns one entry per input item.
|
||||
*/
|
||||
export function applyPantryToItems(
|
||||
items: ShoppingSourceItem[],
|
||||
pantry: PantrySourceItem[]
|
||||
): PantryAdjustedItem[] {
|
||||
const pantryByIngredientId = new Map<string, PantrySourceItem[]>();
|
||||
const pantryByName = new Map<string, PantrySourceItem[]>();
|
||||
|
||||
for (const p of pantry) {
|
||||
if (p.ingredientId) {
|
||||
const list = pantryByIngredientId.get(p.ingredientId) ?? [];
|
||||
list.push(p);
|
||||
pantryByIngredientId.set(p.ingredientId, list);
|
||||
}
|
||||
const nameKey = normalizeName(p.rawName);
|
||||
const list = pantryByName.get(nameKey) ?? [];
|
||||
list.push(p);
|
||||
pantryByName.set(nameKey, list);
|
||||
}
|
||||
|
||||
return items.map((item) => {
|
||||
let matches: PantrySourceItem[] | undefined;
|
||||
|
||||
if (item.ingredientId && pantryByIngredientId.has(item.ingredientId)) {
|
||||
matches = pantryByIngredientId.get(item.ingredientId);
|
||||
} else {
|
||||
matches = pantryByName.get(normalizeName(item.rawName));
|
||||
}
|
||||
|
||||
if (!matches || matches.length === 0) {
|
||||
return { rawName: item.rawName, quantity: item.quantity, unit: item.unit, inPantry: false };
|
||||
}
|
||||
|
||||
const neededQty = item.quantity ? parseFloat(item.quantity) : NaN;
|
||||
const neededUnit = normalizeUnit(item.unit);
|
||||
|
||||
if (!isNaN(neededQty) && neededQty > 0) {
|
||||
// Only sum pantry entries whose unit matches the needed unit (including both-empty).
|
||||
const compatible = matches.filter((m) => normalizeUnit(m.unit) === neededUnit);
|
||||
const parseableQuantities = compatible
|
||||
.map((m) => (m.quantity ? parseFloat(m.quantity) : NaN))
|
||||
.filter((n) => !isNaN(n));
|
||||
|
||||
if (compatible.length > 0 && parseableQuantities.length === compatible.length) {
|
||||
const havingQty = parseableQuantities.reduce((sum, n) => sum + n, 0);
|
||||
const remaining = neededQty - havingQty;
|
||||
if (remaining <= 0) {
|
||||
// Fully covered — still surfaced in the list (flagged), not silently dropped.
|
||||
return { rawName: item.rawName, quantity: undefined, unit: item.unit, inPantry: true };
|
||||
}
|
||||
return { rawName: item.rawName, quantity: formatQuantity(remaining), unit: item.unit, inPantry: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Matched the ingredient, but quantities/units aren't reliably comparable — flag only.
|
||||
return { rawName: item.rawName, quantity: item.quantity, unit: item.unit, inPantry: true };
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user