Implement tasks 40, 41, 42: web push, notification bus, reminders engine

Task 40 — Web Push (VAPID):
- Add web-push package + @types/web-push
- pnpm vapid:generate script prints VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, NEXT_PUBLIC_VAPID_PUBLIC_KEY
- push_subscriptions schema + migration 0013
- _core/push.ts: sendPush() iterates subscriptions, prunes 404/410 stale entries
- SW push/notificationclick event handlers added to generated sw.js template
- PushOptIn client component on /settings (opt-in, disable, send test)

Task 42 — Notification bus + ntfy adapter:
- notifications table + notif_push/notif_inapp/notif_ntfy user columns (migration 0013)
- _core/notify.ts: notify() fans out to push, in-app DB, and optional ntfy POST
- NotificationBell server component in AppNav: unread badge, dropdown inbox, mark-read
- NotifyChannelToggles client component in /settings

Task 41 — Reminders engine:
- fired_at + created_by added to reminders; default channel changed to 'auto'
- _core/reminders.ts: scheduleReminder (upsert), cancelReminder, listReminders, tickReminders
- tickReminders uses pg_try_advisory_xact_lock for horizontal-scale safety
- src/instrumentation.ts starts reminder worker (30s tick) on Node.js boot
- Notes actions use scheduleReminder/cancelReminder instead of raw SQL
- Calendar createEvent: optional remindMinutesBefore, deleteEvent: cancelReminder
- Calendar-shell: "Remind me 30 min before" checkbox on new event form

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
ginnoir
2026-05-06 16:55:02 -05:00
co-authored by Claude Sonnet 4.6
parent ec20f1bc87
commit b6abe052c9
25 changed files with 986 additions and 85 deletions
+44 -8
View File
@@ -1,14 +1,36 @@
import Link from "next/link";
import { Settings } from "lucide-react";
import { desc, eq } from "drizzle-orm";
import { getRegistry } from "@/modules/_core/registry";
import type { DashboardMeta } from "@/app/d/actions";
import { notifications } from "@/modules/_core/schema";
import { db } from "@/lib/db";
import { auth } from "@/lib/auth";
import { DashboardSwitcher } from "./dashboard-switcher";
import { DashboardTab } from "./dashboard-tab";
import { NotificationBell } from "./notification-bell";
export function AppNav({ dashboards = [] }: { dashboards?: DashboardMeta[] }) {
async function getNotifications(userId: string) {
const rows = await db
.select()
.from(notifications)
.where(eq(notifications.userId, userId))
.orderBy(desc(notifications.createdAt))
.limit(20);
const unread = rows.filter((n) => !n.readAt).length;
return { rows, unread };
}
export async function AppNav({ dashboards = [] }: { dashboards?: DashboardMeta[] }) {
const { modules } = getRegistry();
const navItems = modules.flatMap((m) => (m.nav ? [m.nav] : []));
const session = await auth();
const userId = session?.user?.id;
const { rows: notifRows, unread } = userId
? await getNotifications(userId)
: { rows: [], unread: 0 };
return (
<header className="border-b">
<nav className="px-4 py-3 flex items-center gap-6">
@@ -24,13 +46,27 @@ export function AppNav({ dashboards = [] }: { dashboards?: DashboardMeta[] }) {
{item.label}
</Link>
))}
<Link
href="/settings"
className="ml-auto text-muted-foreground hover:text-foreground transition-colors"
aria-label="Settings"
>
<Settings className="size-4" />
</Link>
<div className="ml-auto flex items-center gap-3">
{userId && (
<NotificationBell
initialUnread={unread}
initialItems={notifRows.map((n) => ({
id: n.id,
title: n.title,
body: n.body,
url: n.url ?? null,
createdAt: n.createdAt,
}))}
/>
)}
<Link
href="/settings"
className="text-muted-foreground hover:text-foreground transition-colors"
aria-label="Settings"
>
<Settings className="size-4" />
</Link>
</div>
</nav>
{dashboards.length > 0 && (
+112
View File
@@ -0,0 +1,112 @@
"use client";
import { useEffect, useRef, useState, useTransition } from "react";
import { Bell } from "lucide-react";
import { markNotificationRead, markAllNotificationsRead } from "@/app/settings/notify-actions";
type NotifItem = {
id: string;
title: string;
body: string;
url: string | null;
createdAt: Date;
};
export function NotificationBell({
initialUnread,
initialItems,
}: {
initialUnread: number;
initialItems: NotifItem[];
}) {
const [open, setOpen] = useState(false);
const [unread, setUnread] = useState(initialUnread);
const [items, setItems] = useState(initialItems);
const [isPending, startTransition] = useTransition();
const panelRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
function handleClick(e: MouseEvent) {
if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [open]);
function markRead(id: string) {
setItems((prev) => prev.map((n) => (n.id === id ? { ...n, readAt: new Date() } : n)));
setUnread((u) => Math.max(0, u - 1));
startTransition(() => markNotificationRead(id));
}
function markAll() {
setItems((prev) => prev.map((n) => ({ ...n, readAt: new Date() })));
setUnread(0);
startTransition(() => markAllNotificationsRead());
}
return (
<div className="relative" ref={panelRef}>
<button
type="button"
aria-label={`Notifications${unread > 0 ? ` (${unread} unread)` : ""}`}
onClick={() => setOpen((o) => !o)}
className="relative text-muted-foreground hover:text-foreground transition-colors"
>
<Bell className="size-4" />
{unread > 0 && (
<span className="absolute -top-1 -right-1 flex size-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground">
{unread > 9 ? "9+" : unread}
</span>
)}
</button>
{open && (
<div className="absolute right-0 top-8 z-50 w-80 rounded-lg border bg-background shadow-lg">
<div className="flex items-center justify-between border-b px-4 py-2">
<span className="text-sm font-semibold">Notifications</span>
{unread > 0 && (
<button
type="button"
onClick={markAll}
disabled={isPending}
className="text-xs text-muted-foreground hover:text-foreground"
>
Mark all read
</button>
)}
</div>
<ul className="max-h-80 overflow-y-auto divide-y">
{items.length === 0 && (
<li className="px-4 py-6 text-center text-sm text-muted-foreground">
No notifications
</li>
)}
{items.map((n) => {
const isUnread = !("readAt" in n && (n as { readAt?: Date }).readAt);
return (
<li key={n.id}>
<button
type="button"
className={`w-full text-left px-4 py-3 hover:bg-accent transition-colors ${isUnread ? "font-medium" : "opacity-60"}`}
onClick={() => {
if (isUnread) markRead(n.id);
if (n.url) window.location.href = n.url;
setOpen(false);
}}
>
<p className="text-sm">{n.title}</p>
<p className="text-xs text-muted-foreground mt-0.5">{n.body}</p>
</button>
</li>
);
})}
</ul>
</div>
)}
</div>
);
}
+60
View File
@@ -0,0 +1,60 @@
"use client";
import { useTransition } from "react";
import { setNotifChannel } from "@/app/settings/notify-actions";
type Channel = "push" | "inapp" | "ntfy";
const LABEL: Record<Channel, string> = {
push: "Web push",
inapp: "In-app inbox",
ntfy: "ntfy",
};
export function NotifyChannelToggles({
push,
inapp,
ntfy,
ntfyConfigured,
}: {
push: boolean;
inapp: boolean;
ntfy: boolean;
ntfyConfigured: boolean;
}) {
const [isPending, startTransition] = useTransition();
function toggle(channel: Channel, enabled: boolean) {
startTransition(async () => {
await setNotifChannel(channel, enabled);
});
}
const channels: { key: Channel; value: boolean; disabled?: boolean }[] = [
{ key: "push", value: push },
{ key: "inapp", value: inapp },
{ key: "ntfy", value: ntfy, disabled: !ntfyConfigured },
];
return (
<div className="space-y-3">
{channels.map(({ key, value, disabled }) => (
<label key={key} className="flex items-center justify-between gap-4">
<span className="text-sm">
{LABEL[key]}
{key === "ntfy" && !ntfyConfigured && (
<span className="ml-2 text-xs text-muted-foreground">(NTFY_URL not configured)</span>
)}
</span>
<input
type="checkbox"
checked={value}
disabled={isPending || disabled}
onChange={(e) => toggle(key, e.target.checked)}
className="size-4 cursor-pointer"
/>
</label>
))}
</div>
);
}
+92
View File
@@ -0,0 +1,92 @@
"use client";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { subscribeToPush, unsubscribeFromPush, sendTestNotification } from "@/app/settings/push-actions";
const VAPID_KEY = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY ?? "";
function urlBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer> {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
const raw = atob(base64);
const buf = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) buf[i] = raw.charCodeAt(i);
return buf;
}
export function PushOptIn() {
const [status, setStatus] = useState<"idle" | "subscribed" | "denied" | "unsupported">(
"idle",
);
const [endpoint, setEndpoint] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const [testSent, setTestSent] = useState(false);
if (!VAPID_KEY) return null;
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
return <p className="text-sm text-muted-foreground">Push notifications not supported in this browser.</p>;
}
async function subscribe() {
try {
const registration = await navigator.serviceWorker.ready;
const sub = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_KEY),
});
const json = sub.toJSON() as { endpoint: string; keys: { p256dh: string; auth: string } };
startTransition(async () => {
await subscribeToPush(json, navigator.userAgent);
setEndpoint(json.endpoint);
setStatus("subscribed");
});
} catch {
setStatus("denied");
}
}
async function unsubscribe() {
if (!endpoint) return;
const registration = await navigator.serviceWorker.ready;
const sub = await registration.pushManager.getSubscription();
if (sub) await sub.unsubscribe();
startTransition(async () => {
await unsubscribeFromPush(endpoint);
setEndpoint(null);
setStatus("idle");
});
}
function sendTest() {
startTransition(async () => {
await sendTestNotification();
setTestSent(true);
setTimeout(() => setTestSent(false), 3000);
});
}
if (status === "denied") {
return <p className="text-sm text-destructive">Notification permission denied. Enable it in browser settings.</p>;
}
if (status === "subscribed") {
return (
<div className="flex items-center gap-3">
<span className="text-sm text-green-600 dark:text-green-400">Push notifications enabled</span>
<Button size="sm" variant="outline" onClick={sendTest} disabled={isPending}>
{testSent ? "Sent!" : "Send test"}
</Button>
<Button size="sm" variant="destructive" onClick={unsubscribe} disabled={isPending}>
Disable
</Button>
</div>
);
}
return (
<Button size="sm" onClick={subscribe} disabled={isPending}>
Enable push notifications
</Button>
);
}