feat(settings): sidebar layout with profile, security, AI, notifications, nutrition
Sticky sidebar nav. Sections: Profile (name/language), Security (email/password change), AI & Models (BYOK keys + per-use-case model prefs), Notifications (push subscribe), Nutrition goals. Sub-pages: API keys, Webhooks.
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
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 = [
|
||||
"recipe.created",
|
||||
"recipe.updated",
|
||||
"recipe.published",
|
||||
"recipe.deleted",
|
||||
"meal_plan.updated",
|
||||
"shopping_list.completed",
|
||||
"comment.added",
|
||||
] as const;
|
||||
|
||||
type WebhookEventType = (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 WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
|
||||
const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
|
||||
const [url, setUrl] = useState("");
|
||||
const [selectedEvents, setSelectedEvents] = useState<WebhookEventType[]>([]);
|
||||
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: WebhookEventType) {
|
||||
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/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 create 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 create webhook");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: string) {
|
||||
try {
|
||||
const res = await fetch(`/api/v1/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/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("Failed to copy to clipboard");
|
||||
}
|
||||
}
|
||||
|
||||
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/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/webhooks/${webhookId}/redeliver`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ deliveryId }),
|
||||
});
|
||||
if (res.ok) {
|
||||
toast.success("Redelivery queued");
|
||||
} else {
|
||||
toast.error("Failed to redeliver");
|
||||
}
|
||||
} finally {
|
||||
setRedelivering(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="text-sm text-muted-foreground mb-4">
|
||||
<Link href="/settings/webhooks/docs" className="text-primary hover:underline">
|
||||
View webhook docs & Zapier integration →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Create form */}
|
||||
<form onSubmit={handleCreate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="webhook-url">Endpoint URL</Label>
|
||||
<Input
|
||||
id="webhook-url"
|
||||
type="url"
|
||||
placeholder="https://example.com/webhook"
|
||||
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">
|
||||
Select which events trigger this webhook. Leave all unchecked to receive all events.
|
||||
</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>
|
||||
|
||||
{/* New secret reveal */}
|
||||
{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 signing secret — it will not be shown again.
|
||||
</p>
|
||||
<p className="text-xs text-yellow-700 dark:text-yellow-300">
|
||||
Use it to verify the <code className="font-mono">X-Epicure-Signature</code> header on incoming requests.
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* Webhook list */}
|
||||
{webhookList.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No webhooks 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>
|
||||
)}
|
||||
{w.events.length === 0 && (
|
||||
<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>
|
||||
|
||||
{/* Delivery history */}
|
||||
{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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user