Skip to content

Commit f18a2a7

Browse files
committed
Phase 16: in-app notifications generated hourly by pg_cron (applied migrations, live test passed)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016UBL2N1CcnAWZVRkTYV5oB
1 parent 213ed60 commit f18a2a7

13 files changed

Lines changed: 397 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"use server";
2+
3+
import { revalidatePath } from "next/cache";
4+
import { notificationReadSchema } from "@kkingg/schemas";
5+
import { firstIssue, flash } from "../../../lib/form";
6+
import { createClient } from "../../../lib/supabase/server";
7+
8+
const PATH = "/notifications";
9+
10+
export async function markRead(formData: FormData) {
11+
const parsed = notificationReadSchema.safeParse(Object.fromEntries(formData));
12+
if (!parsed.success) flash(PATH, "error", firstIssue(parsed.error));
13+
const supabase = await createClient();
14+
const { error } = await supabase
15+
.from("notifications")
16+
.update({ read_at: new Date().toISOString() })
17+
.eq("id", parsed.data.id)
18+
.is("read_at", null);
19+
if (error) flash(PATH, "error", "Could not update the notification");
20+
revalidatePath(PATH);
21+
flash(PATH, "message", "Marked as read");
22+
}
23+
24+
export async function markAllRead() {
25+
const supabase = await createClient();
26+
const { error } = await supabase
27+
.from("notifications")
28+
.update({ read_at: new Date().toISOString() })
29+
.is("read_at", null);
30+
if (error) flash(PATH, "error", "Could not update the notifications");
31+
revalidatePath(PATH);
32+
flash(PATH, "message", "All marked as read");
33+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { requireModule } from "../../../lib/modules";
2+
import { getAppContext } from "../../../lib/session";
3+
import { createClient } from "../../../lib/supabase/server";
4+
import type { FlashParams } from "../../../lib/form";
5+
import { Card, Empty, Flash, PageHeader, subtleButton } from "../../../components/ui";
6+
import { markAllRead, markRead } from "./actions";
7+
8+
type Search = FlashParams & { view?: string };
9+
10+
export default async function NotificationsPage({
11+
searchParams,
12+
}: {
13+
searchParams: Promise<Search>;
14+
}) {
15+
const ctx = await getAppContext();
16+
requireModule(ctx, "notifications");
17+
const { error, message, view } = await searchParams;
18+
const supabase = await createClient();
19+
const unreadOnly = view === "unread";
20+
21+
let q = supabase
22+
.from("notifications")
23+
.select("id, kind, title, body, link, read_at, created_at")
24+
.order("created_at", { ascending: false })
25+
.limit(100);
26+
if (unreadOnly) q = q.is("read_at", null);
27+
const [{ data }, { count }] = await Promise.all([
28+
q,
29+
supabase.from("notifications").select("id", { count: "exact", head: true }).is("read_at", null),
30+
]);
31+
const items = data ?? [];
32+
33+
return (
34+
<div className="mx-auto max-w-3xl">
35+
<PageHeader
36+
title="Notifications"
37+
subtitle="Created automatically about once an hour for upcoming dates, wishlist deadlines, venture tasks, due puzzles and reminders. In-app only."
38+
/>
39+
<Flash error={error} message={message} />
40+
<Card>
41+
<p className="mb-3 flex items-center gap-4 text-sm">
42+
<a
43+
href="/notifications"
44+
className={!unreadOnly ? "font-medium text-primary" : "text-muted"}
45+
>
46+
All
47+
</a>
48+
<a
49+
href="/notifications?view=unread"
50+
className={unreadOnly ? "font-medium text-primary" : "text-muted"}
51+
>
52+
Unread ({count ?? 0})
53+
</a>
54+
{(count ?? 0) > 0 && (
55+
<form action={markAllRead} className="ml-auto">
56+
<button className={subtleButton}>Mark all read</button>
57+
</form>
58+
)}
59+
</p>
60+
{items.length === 0 ? (
61+
<Empty>
62+
{unreadOnly
63+
? "Nothing unread."
64+
: "No notifications yet. They appear when something you track is coming up."}
65+
</Empty>
66+
) : (
67+
<ul className="divide-y divide-border text-sm">
68+
{items.map((n) => (
69+
<li
70+
key={n.id}
71+
className={`flex items-start gap-3 py-3 ${n.read_at ? "text-muted" : ""}`}
72+
>
73+
<span className="flex-1">
74+
{n.link ? (
75+
<a href={n.link} className={n.read_at ? "" : "font-medium text-primary"}>
76+
{n.title}
77+
</a>
78+
) : (
79+
<span className={n.read_at ? "" : "font-medium"}>{n.title}</span>
80+
)}
81+
{n.body && <span className="block text-xs text-muted">{n.body}</span>}
82+
<span className="block text-xs text-muted">
83+
{n.created_at.slice(0, 16).replace("T", " ")} UTC
84+
</span>
85+
</span>
86+
{!n.read_at && (
87+
<form action={markRead}>
88+
<input type="hidden" name="id" value={n.id} />
89+
<button className={subtleButton}>Mark read</button>
90+
</form>
91+
)}
92+
</li>
93+
))}
94+
</ul>
95+
)}
96+
</Card>
97+
</div>
98+
);
99+
}

‎apps/web/components/icons.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
Box,
3+
Bell,
34
Briefcase,
45
Film,
56
Heart,
@@ -30,6 +31,7 @@ const icons: Record<string, LucideIcon> = {
3031
repeat: Repeat,
3132
lightbulb: Lightbulb,
3233
lock: Lock,
34+
bell: Bell,
3335
briefcase: Briefcase,
3436
film: Film,
3537
heart: Heart,

‎apps/web/lib/registry.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,12 @@ registry.register({
160160
status: "active",
161161
nav: { label: "Entertainment", href: "/entertainment", icon: "film", order: 95 },
162162
});
163+
164+
registry.register({
165+
id: "notifications",
166+
name: "Notifications",
167+
description: "Inbox for deadlines, dates and reminders",
168+
version: "0.1.0",
169+
status: "active",
170+
nav: { label: "Notifications", href: "/notifications", icon: "bell", order: 5 },
171+
});

‎apps/web/lib/supabase/database.types.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,6 +1306,34 @@ export type Database = {
13061306
};
13071307
Relationships: [];
13081308
};
1309+
notifications: {
1310+
Row: {
1311+
body: string;
1312+
created_at: string;
1313+
dedupe_key: string;
1314+
id: string;
1315+
kind: string;
1316+
link: string | null;
1317+
read_at: string | null;
1318+
title: string;
1319+
user_id: string;
1320+
};
1321+
Insert: {
1322+
body?: string;
1323+
created_at?: string;
1324+
dedupe_key: string;
1325+
id?: string;
1326+
kind: string;
1327+
link?: string | null;
1328+
read_at?: string | null;
1329+
title: string;
1330+
user_id: string;
1331+
};
1332+
Update: {
1333+
read_at?: string | null;
1334+
};
1335+
Relationships: [];
1336+
};
13091337
study_notes: {
13101338
Row: {
13111339
body: string;
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
-- Phase 16 (part 1): an in-app notification inbox filled by a scheduled database job. No keys or external services involved.
2+
-- Users can read their notifications and mark them read (only the read_at column); they cannot create, edit or delete them.
3+
-- Rows are created only by public.generate_notifications(), which runs as the database owner from pg_cron and is not callable
4+
-- through the API. Each notification has a dedupe key so repeated runs never create duplicates.
5+
6+
create table public.notifications (
7+
id uuid primary key default gen_random_uuid(),
8+
user_id uuid not null references auth.users (id) on delete cascade,
9+
kind text not null check (kind in ('date','application','venture_task','puzzles','reminder')),
10+
title text not null check (char_length(title) between 1 and 200),
11+
body text not null default '' check (char_length(body) <= 500),
12+
link text check (link is null or link ~ '^/[A-Za-z0-9/_-]*$'),
13+
dedupe_key text not null check (char_length(dedupe_key) <= 200),
14+
read_at timestamptz,
15+
created_at timestamptz not null default now(),
16+
unique (user_id, dedupe_key)
17+
);
18+
create index notifications_inbox_idx on public.notifications (user_id, created_at desc);
19+
20+
alter table public.notifications enable row level security;
21+
create policy notifications_select on public.notifications for select to authenticated using (user_id = (select auth.uid()));
22+
create policy notifications_update on public.notifications for update to authenticated
23+
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
24+
revoke update on public.notifications from authenticated, anon;
25+
grant update (read_at) on public.notifications to authenticated;
26+
27+
create or replace function public.generate_notifications()
28+
returns int
29+
language plpgsql
30+
security definer
31+
set search_path = ''
32+
as $$
33+
declare
34+
n int := 0;
35+
c int;
36+
begin
37+
drop table if exists pg_temp._u;
38+
create temporary table pg_temp._u on commit drop as
39+
select au.id as user_id,
40+
(now() at time zone case when exists (select 1 from pg_catalog.pg_timezone_names z where z.name = s.timezone)
41+
then s.timezone else 'UTC' end)::date as today
42+
from auth.users au
43+
left join public.user_settings s on s.user_id = au.id;
44+
45+
-- Important dates in the next 3 days (29 February is observed on 28 February in non-leap years).
46+
insert into public.notifications (user_id, kind, title, body, link, dedupe_key)
47+
select d.user_id, 'date',
48+
d.title || case t.off when 0 then ' is today' when 1 then ' is tomorrow' else ' is in ' || t.off || ' days' end,
49+
d.kind, '/personal', 'date:' || d.id || ':' || (u.today + t.off)
50+
from public.important_dates d
51+
join pg_temp._u u on u.user_id = d.user_id
52+
cross join generate_series(0, 3) as t(off)
53+
where d.deleted_at is null
54+
and (
55+
(d.month = extract(month from u.today + t.off) and d.day = extract(day from u.today + t.off))
56+
or (d.month = 2 and d.day = 29 and extract(month from u.today + t.off) = 2 and extract(day from u.today + t.off) = 28
57+
and not ((extract(year from u.today + t.off)::int % 4 = 0 and extract(year from u.today + t.off)::int % 100 <> 0)
58+
or extract(year from u.today + t.off)::int % 400 = 0))
59+
)
60+
on conflict (user_id, dedupe_key) do nothing;
61+
get diagnostics c = row_count; n := n + c;
62+
63+
-- Job applications still on the wishlist whose deadline is within 3 days.
64+
insert into public.notifications (user_id, kind, title, body, link, dedupe_key)
65+
select a.user_id, 'application', 'Deadline: ' || a.company || ' (' || a.role || ')',
66+
'Due ' || a.deadline, '/career', 'application:' || a.id || ':' || a.deadline
67+
from public.job_applications a
68+
join pg_temp._u u on u.user_id = a.user_id
69+
where a.deleted_at is null and a.status = 'wishlist'
70+
and a.deadline between u.today and u.today + 3
71+
on conflict (user_id, dedupe_key) do nothing;
72+
get diagnostics c = row_count; n := n + c;
73+
74+
-- Venture tasks due tomorrow or earlier (up to 7 days overdue) and not done.
75+
insert into public.notifications (user_id, kind, title, body, link, dedupe_key)
76+
select t.user_id, 'venture_task', 'Task due: ' || t.title, 'Due ' || t.due_on, '/business/' || t.venture_id,
77+
'vtask:' || t.id || ':' || t.due_on
78+
from public.venture_tasks t
79+
join pg_temp._u u on u.user_id = t.user_id
80+
where t.deleted_at is null and t.status <> 'done'
81+
and t.due_on between u.today - 7 and u.today + 1
82+
on conflict (user_id, dedupe_key) do nothing;
83+
get diagnostics c = row_count; n := n + c;
84+
85+
-- Chess puzzles due for review: one notification per user per day.
86+
insert into public.notifications (user_id, kind, title, body, link, dedupe_key)
87+
select p.user_id, 'puzzles', p.cnt || (case when p.cnt = 1 then ' puzzle is' else ' puzzles are' end) || ' due for review',
88+
'', '/chess/train', 'puzzles:' || u.today
89+
from (select user_id, count(*) as cnt from public.chess_puzzles
90+
where deleted_at is null and next_due_at <= now() group by user_id) p
91+
join pg_temp._u u on u.user_id = p.user_id
92+
on conflict (user_id, dedupe_key) do nothing;
93+
get diagnostics c = row_count; n := n + c;
94+
95+
-- Reminders whose time has come: notify once and mark them sent.
96+
insert into public.notifications (user_id, kind, title, body, link, dedupe_key)
97+
select r.user_id, 'reminder', left(r.message, 200), '', '/', 'reminder:' || r.id
98+
from public.reminders r
99+
where r.remind_at <= now() and r.sent_at is null and r.dismissed_at is null
100+
on conflict (user_id, dedupe_key) do nothing;
101+
get diagnostics c = row_count; n := n + c;
102+
update public.reminders set sent_at = now()
103+
where remind_at <= now() and sent_at is null and dismissed_at is null;
104+
105+
return n;
106+
end $$;
107+
108+
revoke all on function public.generate_notifications() from public, anon, authenticated;
109+
110+
insert into public.module_registry (id, name, description, version, status, nav_label, nav_href, nav_icon, nav_order) values
111+
('notifications', 'Notifications', 'Inbox for deadlines, dates and reminders', '0.1.0', 'active', 'Notifications', '/notifications', 'bell', 5);
112+
113+
insert into public.workspace_modules (workspace_id, module_id)
114+
select w.id, 'notifications' from public.workspaces w
115+
on conflict do nothing;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
-- Phase 16: run the notification generator hourly (at minute 7). Requires the pg_cron extension (available on Supabase).
2+
create extension if not exists pg_cron;
3+
select cron.schedule('generate-notifications', '7 * * * *', 'select public.generate_notifications()');

0 commit comments

Comments
 (0)