Files
Epicure/apps/web/lib/notifications.ts
T
Arnaud 45b886e398 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>
2026-07-10 07:50:58 +02:00

93 lines
3.1 KiB
TypeScript

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";
type CreateNotificationOpts = {
userId: string;
type: NotificationType;
actorId: string;
recipeId?: string;
commentId?: string;
/** 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,
type: opts.type,
actorId: opts.actorId,
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);
});
}
}