feat: per-category email prefs, admin ops webhooks, per-user feature toggles (v0.61.0)

- Notification email preferences: every push category (follow, comment,
  reply, reaction, rating, mention, leftoverExpiring, shoppingList) now has
  an independent email toggle, plus a Weekly Digest toggle. Previously email
  sent unconditionally whenever the recipient had one; now gated the same
  way push already was. The weekly-digest cron route excludes opted-out
  users.

- Admin-only site-wide webhooks (Admin → Webhooks): new signups, support
  tickets, and reports filed can now fire an HMAC-signed HTTP webhook
  (Slack/Discord/ops alerting), independent of the existing per-user
  webhooks (which stay scoped to a user's own recipe/meal-plan/shopping-list
  events). Signing/delivery logic factored into lib/webhook-delivery.ts and
  shared by both dispatchers instead of duplicated.

- Settings → Features: users can hide Nutrition, Pantry, Meal Plan,
  Shopping Lists, Collections, or Messages from their own nav. Purely
  cosmetic — hidden pages stay reachable by direct link, nothing is
  access-restricted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-20 23:07:28 +02:00
parent cced962bff
commit c5e1643d39
40 changed files with 18383 additions and 79 deletions
@@ -0,0 +1,313 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { ChevronDown, ChevronUp, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
const ALL_EVENTS = ["user.signed_up", "support_ticket.created", "report.filed"] as const;
type AdminWebhookEventType = (typeof ALL_EVENTS)[number];
type Webhook = {
id: string;
url: string;
events: string[];
active: boolean;
createdAt: string;
};
type Delivery = {
id: string;
event: string;
statusCode: number | null;
success: boolean;
attempts: number;
createdAt: string;
};
type CreateWebhookResponse = {
id: string;
url: string;
events: string[];
secret: string;
active: boolean;
createdAt: string;
};
function formatDate(iso: string) {
return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
}
function formatDateTime(iso: string) {
return new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
}
export function AdminWebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
const [url, setUrl] = useState("");
const [selectedEvents, setSelectedEvents] = useState<AdminWebhookEventType[]>([]);
const [creating, setCreating] = useState(false);
const [newSecret, setNewSecret] = useState<{ id: string; secret: string } | null>(null);
const [copied, setCopied] = useState(false);
const [deliveries, setDeliveries] = useState<Record<string, Delivery[]>>({});
const [loadingDeliveries, setLoadingDeliveries] = useState<string | null>(null);
const [expandedDeliveries, setExpandedDeliveries] = useState<Set<string>>(new Set());
const [redelivering, setRedelivering] = useState<string | null>(null);
function toggleEvent(event: AdminWebhookEventType) {
setSelectedEvents((prev) => (prev.includes(event) ? prev.filter((e) => e !== event) : [...prev, event]));
}
async function handleCreate(e: React.FormEvent) {
e.preventDefault();
if (!url.trim()) return;
setCreating(true);
try {
const res = await fetch("/api/v1/admin/webhooks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: url.trim(), events: selectedEvents }),
});
if (!res.ok) {
const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to add webhook");
}
const data = await res.json() as CreateWebhookResponse;
setNewSecret({ id: data.id, secret: data.secret });
setWebhookList((prev) => [
{ id: data.id, url: data.url, events: data.events, active: data.active, createdAt: data.createdAt },
...prev,
]);
setUrl("");
setSelectedEvents([]);
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to add webhook");
} finally {
setCreating(false);
}
}
async function handleDelete(id: string) {
try {
const res = await fetch(`/api/v1/admin/webhooks/${id}`, { method: "DELETE" });
if (!res.ok && res.status !== 204) {
const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to delete webhook");
}
setWebhookList((prev) => prev.filter((w) => w.id !== id));
if (newSecret?.id === id) setNewSecret(null);
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to delete webhook");
}
}
async function handleToggleActive(id: string, currentActive: boolean) {
try {
const res = await fetch(`/api/v1/admin/webhooks/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ active: !currentActive }),
});
if (!res.ok) {
const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to update webhook");
}
setWebhookList((prev) => prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w)));
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to update webhook");
}
}
async function handleCopySecret() {
if (!newSecret) return;
try {
await navigator.clipboard.writeText(newSecret.secret);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
toast.error("Copy failed");
}
}
async function toggleDeliveries(webhookId: string) {
const isExpanded = expandedDeliveries.has(webhookId);
if (isExpanded) {
setExpandedDeliveries((prev) => { const s = new Set(prev); s.delete(webhookId); return s; });
return;
}
setExpandedDeliveries((prev) => new Set([...prev, webhookId]));
if (deliveries[webhookId]) return;
setLoadingDeliveries(webhookId);
try {
const res = await fetch(`/api/v1/admin/webhooks/${webhookId}/deliveries`);
if (res.ok) {
const data = await res.json() as Delivery[];
setDeliveries((prev) => ({ ...prev, [webhookId]: data }));
}
} finally {
setLoadingDeliveries(null);
}
}
async function handleRedeliver(webhookId: string, deliveryId: string) {
setRedelivering(deliveryId);
try {
const res = await fetch(`/api/v1/admin/webhooks/${webhookId}/redeliver`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ deliveryId }),
});
if (res.ok) toast.success("Redelivered");
else toast.error("Redelivery failed");
} finally {
setRedelivering(null);
}
}
return (
<div className="space-y-8">
<form onSubmit={handleCreate} className="space-y-4 rounded-xl border p-6">
<div className="space-y-2">
<Label htmlFor="admin-webhook-url">Endpoint URL</Label>
<Input
id="admin-webhook-url"
type="url"
placeholder="https://hooks.slack.com/services/..."
value={url}
onChange={(e) => setUrl(e.target.value)}
maxLength={2048}
required
/>
</div>
<div className="space-y-2">
<Label>Events</Label>
<p className="text-xs text-muted-foreground">Leave all unchecked to receive every event.</p>
<div className="flex flex-wrap gap-3">
{ALL_EVENTS.map((event) => {
const checked = selectedEvents.includes(event);
return (
<label key={event} className="flex items-center gap-2 cursor-pointer select-none">
<input type="checkbox" className="rounded" checked={checked} onChange={() => toggleEvent(event)} />
<span className="text-sm font-mono">{event}</span>
</label>
);
})}
</div>
</div>
<Button type="submit" disabled={creating || !url.trim()}>
{creating ? "Adding…" : "Add webhook"}
</Button>
</form>
{newSecret && (
<div className="rounded-md border border-yellow-400 bg-yellow-50 p-4 space-y-3 dark:bg-yellow-950 dark:border-yellow-700">
<p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">
Save this secret now it won&apos;t be shown again.
</p>
<p className="text-xs text-yellow-700 dark:text-yellow-300">
Used to verify the X-Epicure-Signature header on each delivery.
</p>
<div className="flex items-center gap-2">
<code className="flex-1 rounded bg-white dark:bg-black border px-3 py-2 text-sm font-mono break-all">
{newSecret.secret}
</code>
<Button type="button" variant="outline" onClick={() => { void handleCopySecret(); }}>
{copied ? "Copied" : "Copy"}
</Button>
</div>
<Button type="button" variant="ghost" size="sm" onClick={() => setNewSecret(null)} className="text-muted-foreground">
Dismiss
</Button>
</div>
)}
{webhookList.length === 0 ? (
<p className="text-sm text-muted-foreground">No webhooks configured yet.</p>
) : (
<div className="divide-y rounded-md border">
{webhookList.map((w) => {
const isExpanded = expandedDeliveries.has(w.id);
const wDeliveries = deliveries[w.id] ?? [];
return (
<div key={w.id} className="px-4 py-3 space-y-2">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 flex-1 space-y-1">
<p className="text-sm font-mono truncate">{w.url}</p>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>Added {formatDate(w.createdAt)}</span>
<span>·</span>
<Badge variant={w.active ? "default" : "secondary"} className="text-xs">
{w.active ? "Active" : "Inactive"}
</Badge>
</div>
{w.events.length > 0 ? (
<div className="flex flex-wrap gap-1 pt-1">
{w.events.map((ev) => (
<Badge key={ev} variant="outline" className="text-xs font-mono">{ev}</Badge>
))}
</div>
) : (
<p className="text-xs text-muted-foreground pt-1">All events</p>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
<Button type="button" variant="ghost" size="sm" onClick={() => { void toggleDeliveries(w.id); }} className="text-muted-foreground gap-1">
{isExpanded ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
Deliveries
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => { void handleToggleActive(w.id, w.active); }}>
{w.active ? "Disable" : "Enable"}
</Button>
<Button type="button" variant="destructive" size="sm" onClick={() => { void handleDelete(w.id); }}>
Delete
</Button>
</div>
</div>
{isExpanded && (
<div className="mt-2 rounded-md border bg-muted/30">
{loadingDeliveries === w.id ? (
<p className="text-xs text-muted-foreground px-3 py-2">Loading</p>
) : wDeliveries.length === 0 ? (
<p className="text-xs text-muted-foreground px-3 py-2">No deliveries yet.</p>
) : (
<div className="divide-y">
{wDeliveries.map((d) => (
<div key={d.id} className="flex items-center gap-3 px-3 py-2 text-xs">
<Badge variant={d.success ? "default" : "destructive"} className="text-xs shrink-0 w-14 justify-center">
{d.statusCode ?? "err"}
</Badge>
<span className="font-mono text-muted-foreground shrink-0">{d.event}</span>
<span className="text-muted-foreground flex-1 text-right">{formatDateTime(d.createdAt)}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 px-2 shrink-0"
disabled={redelivering === d.id}
onClick={() => { void handleRedeliver(w.id, d.id); }}
>
<RotateCcw className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
</div>
)}
</div>
);
})}
</div>
)}
</div>
);
}
+35 -9
View File
@@ -1,11 +1,13 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { BookOpen, Calendar, Package, ChefHat, User, FolderOpen, ShoppingCart, Shield, Search, Compass, Menu, Sun, Moon, Monitor, Apple, LifeBuoy, Settings, LogOut } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button";
import type { FeaturePrefs } from "@/lib/feature-prefs";
import {
DropdownMenu,
DropdownMenuContent,
@@ -28,13 +30,13 @@ import { authClient } from "@/lib/auth/client";
import { useTranslations } from "next-intl";
const NAV_ITEMS = [
{ href: "/recipes", key: "recipes", icon: BookOpen },
{ href: "/explore", key: "explore", icon: Search },
{ href: "/collections", key: "collections", icon: FolderOpen },
{ href: "/meal-plan", key: "mealPlan", icon: Calendar },
{ href: "/nutrition", key: "nutrition", icon: Apple },
{ href: "/pantry", key: "pantry", icon: Package },
{ href: "/shopping-lists", key: "shopping", icon: ShoppingCart },
{ href: "/recipes", key: "recipes", icon: BookOpen, feature: null },
{ href: "/explore", key: "explore", icon: Search, feature: null },
{ href: "/collections", key: "collections", icon: FolderOpen, feature: "collections" },
{ href: "/meal-plan", key: "mealPlan", icon: Calendar, feature: "mealPlan" },
{ href: "/nutrition", key: "nutrition", icon: Apple, feature: "nutrition" },
{ href: "/pantry", key: "pantry", icon: Package, feature: "pantry" },
{ href: "/shopping-lists", key: "shopping", icon: ShoppingCart, feature: "shoppingLists" },
] as const;
export function Nav() {
@@ -45,6 +47,30 @@ export function Nav() {
const username = (session?.user as { username?: string } | undefined)?.username;
const { theme, setTheme } = useTheme();
const t = useTranslations("nav");
// Defaults to "everything on" until the fetch resolves, matching the
// backend default — avoids a flash of items disappearing on load for the
// (much more common) case where a user hasn't hidden anything.
const [featurePrefs, setFeaturePrefs] = useState<FeaturePrefs>({
nutrition: true, pantry: true, mealPlan: true, shoppingLists: true, collections: true, messages: true,
});
useEffect(() => {
function load() {
fetch("/api/v1/users/me/feature-prefs")
.then((res) => (res.ok ? res.json() : null))
.then((json) => { if (json?.data) setFeaturePrefs(json.data); })
.catch(() => {});
}
load();
// Settings → Features saves on the same origin without a full nav
// remount, so it fires this event to make the change visible immediately
// rather than only on the next page load.
window.addEventListener("epicure:feature-prefs-changed", load);
return () => window.removeEventListener("epicure:feature-prefs-changed", load);
}, []);
const visibleNavItems = NAV_ITEMS.filter((item) => item.feature === null || featurePrefs[item.feature]);
const THEME_OPTIONS = [
{ value: "light", icon: Sun, label: t("lightMode") },
{ value: "dark", icon: Moon, label: t("darkMode") },
@@ -68,7 +94,7 @@ export function Nav() {
</SheetTitle>
</SheetHeader>
<nav className="flex flex-col gap-1 px-2">
{NAV_ITEMS.map(({ href, key, icon: Icon }) => (
{visibleNavItems.map(({ href, key, icon: Icon }) => (
<SheetClose
key={href}
nativeButton={false}
@@ -110,7 +136,7 @@ export function Nav() {
))}
</nav>
<div className="ml-auto flex items-center gap-2">
<MessagesNavLink />
{featurePrefs.messages && <MessagesNavLink />}
<NotificationBell />
<DropdownMenu>
<DropdownMenuTrigger className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring">
@@ -0,0 +1,76 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import type { FeatureKey, FeaturePrefs } from "@/lib/feature-prefs";
const FEATURES: FeatureKey[] = ["nutrition", "pantry", "mealPlan", "shoppingLists", "collections", "messages"];
export function FeatureTogglesForm() {
const t = useTranslations("settingsForm.featureToggles");
const t_common = useTranslations("common");
const [prefs, setPrefs] = useState<FeaturePrefs | null>(null);
const [saving, setSaving] = useState<FeatureKey | null>(null);
useEffect(() => {
fetch("/api/v1/users/me/feature-prefs")
.then((res) => (res.ok ? res.json() : null))
.then((json) => setPrefs(json?.data ?? null))
.catch(() => setPrefs(null));
}, []);
async function toggle(feature: FeatureKey, checked: boolean) {
if (!prefs) return;
const previous = prefs;
setPrefs({ ...prefs, [feature]: checked });
setSaving(feature);
try {
const res = await fetch("/api/v1/users/me/feature-prefs", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ [feature]: checked }),
});
if (!res.ok) {
setPrefs(previous);
toast.error(t_common("saveFailed"));
} else {
// Nav reads this same endpoint on its own mount — no shared client
// cache to invalidate, so a hard reason to re-fetch is a full nav
// refresh. Cheapest correct fix: reload so the nav picks it up now
// instead of on the next navigation.
window.dispatchEvent(new Event("epicure:feature-prefs-changed"));
}
} catch {
setPrefs(previous);
toast.error(t_common("saveFailed"));
} finally {
setSaving(null);
}
}
if (!prefs) return null;
return (
<div className="space-y-3">
{FEATURES.map((feature) => (
<div key={feature} className="flex items-center justify-between gap-3">
<div>
<Label htmlFor={`feature-${feature}`} className="cursor-pointer">
{t(feature)}
</Label>
<p className="text-xs text-muted-foreground">{t(`${feature}Description`)}</p>
</div>
<Switch
id={`feature-${feature}`}
checked={prefs[feature]}
disabled={saving === feature}
onCheckedChange={(checked) => { void toggle(feature, checked); }}
/>
</div>
))}
</div>
);
}
@@ -11,11 +11,13 @@ const CATEGORIES: NotificationCategory[] = [
"follow", "comment", "reply", "reaction", "rating", "mention", "leftoverExpiring", "shoppingList",
];
type Field = keyof NotificationPrefs;
export function NotificationCategoriesForm() {
const t = useTranslations("settingsForm.notificationCategories");
const t_common = useTranslations("common");
const [prefs, setPrefs] = useState<NotificationPrefs | null>(null);
const [saving, setSaving] = useState<NotificationCategory | null>(null);
const [saving, setSaving] = useState<Field | null>(null);
useEffect(() => {
fetch("/api/v1/users/me/notification-prefs")
@@ -24,16 +26,16 @@ export function NotificationCategoriesForm() {
.catch(() => setPrefs(null));
}, []);
async function toggle(category: NotificationCategory, checked: boolean) {
async function toggle(field: Field, checked: boolean) {
if (!prefs) return;
const previous = prefs;
setPrefs({ ...prefs, [category]: checked });
setSaving(category);
setPrefs({ ...prefs, [field]: checked });
setSaving(field);
try {
const res = await fetch("/api/v1/users/me/notification-prefs", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ [category]: checked }),
body: JSON.stringify({ [field]: checked }),
});
if (!res.ok) {
setPrefs(previous);
@@ -50,20 +52,57 @@ export function NotificationCategoriesForm() {
if (!prefs) return null;
return (
<div className="space-y-3">
{CATEGORIES.map((category) => (
<div key={category} className="flex items-center justify-between gap-3">
<Label htmlFor={`notif-${category}`} className="cursor-pointer">
{t(category)}
<div className="space-y-1">
<div className="grid grid-cols-[1fr_auto_auto] items-center gap-3 pb-2">
<span />
<span className="text-xs font-medium text-muted-foreground w-12 text-center">{t("push")}</span>
<span className="text-xs font-medium text-muted-foreground w-12 text-center">{t("email")}</span>
</div>
{CATEGORIES.map((category) => {
const emailField = `${category}Email` as const;
return (
<div key={category} className="grid grid-cols-[1fr_auto_auto] items-center gap-3 py-2 border-t first:border-t-0">
<Label htmlFor={`notif-${category}`} className="cursor-pointer">
{t(category)}
</Label>
<div className="w-12 flex justify-center">
<Switch
id={`notif-${category}`}
checked={prefs[category]}
disabled={saving === category}
onCheckedChange={(checked) => { void toggle(category, checked); }}
/>
</div>
<div className="w-12 flex justify-center">
<Switch
id={`notif-${emailField}`}
checked={prefs[emailField]}
disabled={saving === emailField}
onCheckedChange={(checked) => { void toggle(emailField, checked); }}
/>
</div>
</div>
);
})}
<div className="grid grid-cols-[1fr_auto_auto] items-center gap-3 py-2 border-t">
<div>
<Label htmlFor="notif-weeklyDigestEmail" className="cursor-pointer">
{t("weeklyDigest")}
</Label>
<p className="text-xs text-muted-foreground">{t("weeklyDigestDescription")}</p>
</div>
<span className="w-12" />
<div className="w-12 flex justify-center">
<Switch
id={`notif-${category}`}
checked={prefs[category]}
disabled={saving === category}
onCheckedChange={(checked) => { void toggle(category, checked); }}
id="notif-weeklyDigestEmail"
checked={prefs.weeklyDigestEmail}
disabled={saving === "weeklyDigestEmail"}
onCheckedChange={(checked) => { void toggle("weeklyDigestEmail", checked); }}
/>
</div>
))}
</div>
</div>
);
}
@@ -3,7 +3,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslations } from "next-intl";
import { User, Shield, Bot, Bell, Apple, Key, Webhook } from "lucide-react";
import { User, Shield, Bot, Bell, Apple, Key, Webhook, SlidersHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
const NAV_ITEMS = [
@@ -11,6 +11,7 @@ const NAV_ITEMS = [
{ href: "/settings/security", key: "security", icon: Shield, exact: false },
{ href: "/settings/ai", key: "aiModels", icon: Bot, exact: false },
{ href: "/settings/notifications", key: "notifications", icon: Bell, exact: false },
{ href: "/settings/features", key: "features", icon: SlidersHorizontal, exact: false },
{ href: "/settings/nutrition", key: "nutrition", icon: Apple, exact: false },
{ href: "/settings/api-keys", key: "apiKeys", icon: Key, exact: false },
{ href: "/settings/webhooks", key: "webhooks", icon: Webhook, exact: false },