From 038ffa3558ac172ab95b4d32a1dc6485c1f024ee Mon Sep 17 00:00:00 2001 From: Raj Patel Date: Wed, 21 Oct 2026 18:35:01 -0700 Subject: [PATCH] Add direct messaging between registered users --- app/(site)/messages/[id]/Thread.tsx | 2 +- app/(site)/messages/[id]/page.tsx | 6 +-- app/(site)/messages/new/RecipientButton.tsx | 11 ++++++ app/(site)/messages/new/actions.test.ts | 20 ++++++++++ app/(site)/messages/new/actions.ts | 15 ++++++++ app/(site)/messages/new/page.tsx | 37 +++++++++++++++++++ app/(site)/messages/page.tsx | 12 +++--- .../20261027000000_direct_messages.sql | 7 ++++ lib/data.ts | 18 ++++----- lib/directMessages.test.ts | 35 ++++++++++++++++++ lib/directMessages.ts | 30 +++++++++++++++ lib/directThreads.test.ts | 26 +++++++++++++ 12 files changed, 200 insertions(+), 19 deletions(-) create mode 100644 app/(site)/messages/new/RecipientButton.tsx create mode 100644 app/(site)/messages/new/actions.test.ts create mode 100644 app/(site)/messages/new/actions.ts create mode 100644 app/(site)/messages/new/page.tsx create mode 100644 db/migrations/20261027000000_direct_messages.sql create mode 100644 lib/directMessages.test.ts create mode 100644 lib/directMessages.ts create mode 100644 lib/directThreads.test.ts diff --git a/app/(site)/messages/[id]/Thread.tsx b/app/(site)/messages/[id]/Thread.tsx index 88580b8..37215c4 100644 --- a/app/(site)/messages/[id]/Thread.tsx +++ b/app/(site)/messages/[id]/Thread.tsx @@ -78,7 +78,7 @@ export function Thread({ conversationId, me, other, initial }: { conversationId:
{messages.length === 0 && (

- say hi to {other.displayName || other.netid} — ask if it’s still available, how it fits, or when to pick up. + say hi to {other.displayName || other.netid} — write your first message below.

)} {messages.map((m, i) => { diff --git a/app/(site)/messages/[id]/page.tsx b/app/(site)/messages/[id]/page.tsx index ef7508e..1e3fd7c 100644 --- a/app/(site)/messages/[id]/page.tsx +++ b/app/(site)/messages/[id]/page.tsx @@ -39,9 +39,9 @@ async function Conversation({ params }: { params: PageProps<"/messages/[id]">["p {personLabel(other)} - {iAmSeller ? "· buyer" : "· seller"} + {listing && {iAmSeller ? "· buyer" : "· seller"}} - + {listing && {/* eslint-disable-next-line @next/next/no-img-element */} @@ -51,7 +51,7 @@ async function Conversation({ params }: { params: PageProps<"/messages/[id]">["p {listing.status === "sold" ? " · sold" : ""} - + }
diff --git a/app/(site)/messages/new/RecipientButton.tsx b/app/(site)/messages/new/RecipientButton.tsx new file mode 100644 index 0000000..c0fd3fd --- /dev/null +++ b/app/(site)/messages/new/RecipientButton.tsx @@ -0,0 +1,11 @@ +"use client"; +import { useActionState } from "react"; +import { newMessageAction } from "./actions"; +export function RecipientButton({ netid }: { netid: string }) { + const [state, action, pending] = useActionState(newMessageAction, {}); + return
+ + + {state.error &&

{state.error}

} +
; +} diff --git a/app/(site)/messages/new/actions.test.ts b/app/(site)/messages/new/actions.test.ts new file mode 100644 index 0000000..00824ea --- /dev/null +++ b/app/(site)/messages/new/actions.test.ts @@ -0,0 +1,20 @@ +import { beforeEach, expect, it, vi } from "vitest"; +const m = vi.hoisted(() => ({ user: vi.fn(), start: vi.fn(), redirect: vi.fn() })); +vi.mock("@/lib/auth", () => ({requireUser: m.user})); +vi.mock("@/lib/directMessages", () => ({startDirectConversation: m.start})); +vi.mock("next/navigation", () => ({redirect: m.redirect})); +import { newMessageAction } from "./actions"; +const form = () => { const f = new FormData(); f.set("recipient","ao5729"); f.set("viewer","fake"); return f; }; +beforeEach(() => {vi.resetAllMocks();m.user.mockResolvedValue({netid:"rp4348"});}); +it("requires a signed-in user before creating a conversation",async()=>{ + m.user.mockRejectedValue(new Error("login")); + await expect(newMessageAction({},form())).rejects.toThrow("login");expect(m.start).not.toHaveBeenCalled(); +}); +it("uses the session identity and redirects to the selected thread",async()=>{ + m.start.mockResolvedValue("thread");await newMessageAction({},form()); + expect(m.start).toHaveBeenCalledWith("rp4348","ao5729");expect(m.redirect).toHaveBeenCalledWith("/messages/thread"); +}); +it("shows recipient errors without redirecting",async()=>{ + m.start.mockRejectedValue(new Error("not registered")); + expect(await newMessageAction({},form())).toEqual({error:"not registered"});expect(m.redirect).not.toHaveBeenCalled(); +}); diff --git a/app/(site)/messages/new/actions.ts b/app/(site)/messages/new/actions.ts new file mode 100644 index 0000000..a1ee6c9 --- /dev/null +++ b/app/(site)/messages/new/actions.ts @@ -0,0 +1,15 @@ +"use server"; +import { redirect } from "next/navigation"; +import { requireUser } from "@/lib/auth"; +import { startDirectConversation } from "@/lib/directMessages"; + +export async function newMessageAction(_: { error?: string }, form: FormData): Promise<{ error?: string }> { + const user = await requireUser("/messages/new"); + let id: string; + try { + id = await startDirectConversation(user.netid, String(form.get("recipient") ?? "")); + } catch (e) { + return { error: e instanceof Error ? e.message : "Could not open the conversation." }; + } + redirect(`/messages/${id}`); +} diff --git a/app/(site)/messages/new/page.tsx b/app/(site)/messages/new/page.tsx new file mode 100644 index 0000000..732eff7 --- /dev/null +++ b/app/(site)/messages/new/page.tsx @@ -0,0 +1,37 @@ +import Link from "next/link"; +import { Suspense } from "react"; +import { requireUser } from "@/lib/auth"; +import { searchRecipients } from "@/lib/directMessages"; +import { personLabel } from "@/lib/rules"; +import { Avatar } from "../../_components/Avatar"; +import { RecipientButton } from "./RecipientButton"; + +type Search = Promise<{ q?: string | string[] }>; +export default function NewMessagePage({ searchParams }: { searchParams: Search }) { + return
+ ← messages +

new message

+

find a registered person by name or netid.

+ loading…

}>
+
; +} +async function Recipients({ searchParams }: { searchParams: Search }) { + const user = await requireUser("/messages/new"); + const params = await searchParams; + const q = typeof params.q === "string" ? params.q.slice(0, 80) : ""; + const people = await searchRecipients(user.netid, q); + return <> +
+ + +
+ {q.trim() && people.length === 0 &&

no registered people found. try their netid.

} +
+ {people.map(person =>
+ +
{personLabel(person)}
{person.netid}
+ +
)} +
+ ; +} diff --git a/app/(site)/messages/page.tsx b/app/(site)/messages/page.tsx index 4fccf93..e6ead6b 100644 --- a/app/(site)/messages/page.tsx +++ b/app/(site)/messages/page.tsx @@ -12,9 +12,9 @@ export default function MessagesPage() { return (
-

messages

+

messages

+ new message

- questions and pickup plans, one conversation per item. + message someone directly, or keep talking about an item.

loading…

}> @@ -33,7 +33,7 @@ async function Inbox() { if (!rows.length) { return (
- no messages yet. open any listing and tap message seller to ask a question. + no messages yet. choose new message to start a conversation.
); } @@ -45,7 +45,7 @@ async function Inbox() {
{personLabel(r.other)} - · {r.listing.title} + {r.listing && · {r.listing.title}}
{r.lastFromMe ? "you: " : ""} @@ -56,10 +56,10 @@ async function Inbox() { {r.lastMessageAt && {ago(r.lastMessageAt, now)}} {r.unread && }
- + {r.listing && {/* eslint-disable-next-line @next/next/no-img-element */} - + } ))}
diff --git a/db/migrations/20261027000000_direct_messages.sql b/db/migrations/20261027000000_direct_messages.sql new file mode 100644 index 0000000..a44d4f1 --- /dev/null +++ b/db/migrations/20261027000000_direct_messages.sql @@ -0,0 +1,7 @@ +-- Direct conversations share the existing participant checks and message storage. +-- Existing item conversations retain their listing foreign key and uniqueness. +alter table conversations alter column listing_id drop not null; +alter table conversations add constraint direct_conversation_order + check (listing_id is not null or buyer_netid collate "C" < seller_netid collate "C"); +create unique index conversations_direct_pair on conversations (buyer_netid, seller_netid) + where listing_id is null; diff --git a/lib/data.ts b/lib/data.ts index dd0ad58..1941cb9 100644 --- a/lib/data.ts +++ b/lib/data.ts @@ -558,17 +558,17 @@ export interface Message { } export interface Conversation extends ConversationState { id: string; - listingId: string; + listingId: string | null; } export interface ConversationView { conversation: Conversation; - listing: { id: string; title: string; priceCents: number; photoUrl: string; status: ListingStatus }; + listing: { id: string; title: string; priceCents: number; photoUrl: string; status: ListingStatus } | null; other: Person; messages: Message[]; } export interface InboxRow { id: string; - listing: { id: string; title: string; photoUrl: string }; + listing: { id: string; title: string; photoUrl: string } | null; other: Person; lastMessage: string | null; lastMessageAt: string | null; @@ -578,7 +578,7 @@ export interface InboxRow { const toConversation = (r: Row): Conversation => ({ id: r.id as string, - listingId: r.listing_id as string, + listingId: r.listing_id as string | null, buyerNetid: r.buyer_netid as string, sellerNetid: r.seller_netid as string, lastMessageAt: r.last_message_at as string | null, @@ -634,15 +634,15 @@ export async function conversationFor(id: string, viewer: string): Promise sql()`select * from messages where conversation_id = ${c.id} order by created_at`), ]); - if (!listing) return null; + if (c.listingId && !listing) return null; await markRead(c, viewer); return { conversation: c, - listing: { id: listing.id, title: listing.title, priceCents: listing.priceCents, photoUrl: listing.photoUrls[0], status: listing.status }, + listing: listing ? { id: listing.id, title: listing.title, priceCents: listing.priceCents, photoUrl: listing.photoUrls[0], status: listing.status } : null, other: who.get(otherNetid) ?? { netid: otherNetid, displayName: null, avatarUrl: null }, messages: rows.map(toMessage), }; @@ -676,7 +676,7 @@ export async function messagesSince(conversationId: string, viewer: string, afte export async function inbox(viewer: string): Promise { const rows = await step("load inbox", () => sql()` select c.*, l.title as listing_title, l.photo_paths as listing_photo_paths - from conversations c join listings l on l.id = c.listing_id + from conversations c left join listings l on l.id = c.listing_id where (c.buyer_netid = ${viewer} or c.seller_netid = ${viewer}) and c.last_message_at is not null order by c.last_message_at desc`); const convs = rows.map((r) => ({ c: toConversation(r), l: r })); @@ -693,7 +693,7 @@ export async function inbox(viewer: string): Promise { const lastBody = new Map(lasts.map((r) => [r.conversation_id as string, r.body as string])); return convs.map(({ c, l }, i) => ({ id: c.id, - listing: { id: c.listingId, title: l.listing_title as string, photoUrl: photoUrl((l.listing_photo_paths as string[])[0]) }, + listing: c.listingId ? { id: c.listingId, title: l.listing_title as string, photoUrl: photoUrl((l.listing_photo_paths as string[])[0]) } : null, other: who.get(others[i]) ?? { netid: others[i], displayName: null, avatarUrl: null }, lastMessage: lastBody.get(c.id) ?? null, lastMessageAt: c.lastMessageAt, diff --git a/lib/directMessages.test.ts b/lib/directMessages.test.ts new file mode 100644 index 0000000..3b97f65 --- /dev/null +++ b/lib/directMessages.test.ts @@ -0,0 +1,35 @@ +import { beforeEach, expect, it, vi } from "vitest"; +const {query}=vi.hoisted(()=>({query:vi.fn()})); +vi.mock("server-only",()=>({})); +vi.mock("./db",()=>({sql:()=>query})); +import { startDirectConversation, searchRecipients } from "./directMessages"; +beforeEach(()=>vi.resetAllMocks()); +it("blocks self and system recipients before querying",async()=>{ + for(const id of ["rp4348","listserv","seed-person","e2e-admin",""]) await expect(startDirectConversation("rp4348",id)).rejects.toThrow(); + expect(query).not.toHaveBeenCalled(); +}); +it("rejects unregistered recipients",async()=>{ + query.mockResolvedValueOnce([]); + await expect(startDirectConversation("rp4348","missing")).rejects.toThrow("registered"); + expect(query).toHaveBeenCalledTimes(1); +}); +it("uses the same ordered pair in either direction",async()=>{ + query.mockResolvedValue([{id:"thread",netid:"ao5729"}]); + expect(await startDirectConversation("rp4348","ao5729")).toBe("thread"); + expect(query.mock.calls[1].slice(1)).toEqual(["ao5729","rp4348"]); + query.mockClear(); + await startDirectConversation("ao5729","rp4348"); + expect(query.mock.calls[1].slice(1)).toEqual(["ao5729","rp4348"]); + expect(query.mock.calls[1][0].join("?")).toContain("on conflict"); +}); +it("does not list the user directory without a search",async()=>{ + expect(await searchRecipients("rp4348"," ")).toEqual([]); + expect(query).not.toHaveBeenCalled(); +}); +it("returns only public profile fields and uses literal bounded search",async()=>{ + query.mockResolvedValue([{netid:"ao5729",display_name:"Amel",avatar_path:null,phone:"private",payments:[{handle:"private"}]}]); + expect(await searchRecipients("rp4348"," Amel ")).toEqual([{netid:"ao5729",displayName:"Amel",avatarUrl:null}]); + const statement=query.mock.calls[0][0].join("?"); + expect(statement).toContain("limit 20");expect(statement).toContain("netid not like 'seed-%'"); + expect(query.mock.calls[0].slice(1)).toEqual(["rp4348","amel","amel"]); +}); diff --git a/lib/directMessages.ts b/lib/directMessages.ts new file mode 100644 index 0000000..eca0536 --- /dev/null +++ b/lib/directMessages.ts @@ -0,0 +1,30 @@ +import "server-only"; +import { sql, type Row } from "./db"; +import { isReservedNetid } from "./cas"; +import { avatarUrl } from "./storage"; +import type { Person } from "./data"; + +// Callers must supply the viewer from the verified session. +export async function searchRecipients(viewer: string, input: string): Promise { + const term = input.trim().toLowerCase().slice(0, 80); + if (!term) return []; + const rows = await sql()`select netid, display_name, avatar_path from users + where netid <> ${viewer} and netid <> 'listserv' and netid not like 'seed-%' and netid not like 'e2e-%' + and (strpos(lower(netid), ${term}) > 0 or strpos(lower(coalesce(display_name, '')), ${term}) > 0) + order by netid limit 20`; + return rows.map(r => ({ netid: r.netid as string, displayName: r.display_name as string | null, avatarUrl: r.avatar_path ? avatarUrl(r.avatar_path as string) : null })); +} + +export async function startDirectConversation(viewer: string, input: string): Promise { + const recipient = input.trim().toLowerCase(); + if (!/^[a-z0-9_]+$/.test(recipient) || recipient === viewer || isReservedNetid(recipient)) throw new Error("Choose another registered person."); + const [user] = await sql()`select netid from users where netid = ${recipient}`; + if (!user) throw new Error("That person has not registered yet."); + // Stable ordering plus a unique index handles simultaneous starts from either side. + const [first, second] = [viewer, recipient].sort(); + const [row] = await sql()`insert into conversations (listing_id, buyer_netid, seller_netid) + values (null, ${first}, ${second}) + on conflict (buyer_netid, seller_netid) where listing_id is null + do update set buyer_netid = excluded.buyer_netid returning id`; + return row.id as string; +} diff --git a/lib/directThreads.test.ts b/lib/directThreads.test.ts new file mode 100644 index 0000000..1102e9a --- /dev/null +++ b/lib/directThreads.test.ts @@ -0,0 +1,26 @@ +import { beforeEach, expect, it, vi } from "vitest"; +const { query } = vi.hoisted(() => ({ query: vi.fn() })); +vi.mock("server-only", () => ({})); +vi.mock("./db", () => ({ sql: () => (first: unknown, ...values: unknown[]) => Array.isArray(first) && "raw" in first ? query(first, ...values) : first })); +import { conversationFor, sendMessage, inbox } from "./data"; +const id = "10000000-0000-4000-8000-000000000001"; +const row = { id, listing_id: null, buyer_netid: "ao5729", seller_netid: "rp4348", last_message_at: "2026-10-21T10:00:00Z", last_sender_netid: "ao5729", buyer_read_at: null, seller_read_at: null }; +beforeEach(() => vi.resetAllMocks()); +it("opens direct threads without looking up a listing", async () => { + query.mockResolvedValueOnce([row]).mockResolvedValueOnce([{netid: "ao5729", display_name: "Amel", avatar_path: null}]).mockResolvedValueOnce([]).mockResolvedValueOnce([]); + const view = await conversationFor(id, "rp4348"); + expect(view?.listing).toBeNull(); expect(view?.other.netid).toBe("ao5729"); + expect(query.mock.calls.some(c => c[0].join("").includes("from listings"))).toBe(false); +}); +it("rejects outsiders when opening or sending to a direct conversation", async () => { + query.mockResolvedValue([row]); + expect(await conversationFor(id, "outsider")).toBeNull(); + await expect(sendMessage(id, "outsider", "hi")).rejects.toThrow("doesn't exist"); + expect(query.mock.calls.every(c => c[0].join("").includes("select * from conversations"))).toBe(true); +}); +it("includes direct conversations in the inbox without a listing thumbnail", async () => { + query.mockResolvedValueOnce([row]).mockResolvedValueOnce([{netid: "ao5729", display_name: "Amel", avatar_path: null}]).mockResolvedValueOnce([{conversation_id: id,body: "hello"}]); + const rows = await inbox("rp4348"); + expect(rows[0]).toMatchObject({id,listing: null,lastMessage: "hello",unread: true}); + expect(query.mock.calls[0][0].join("")).toContain("left join listings"); +});