feat(GRO-106): staff messages page
- Adds staff conversations API (GET /api/conversations, GET /api/conversations/:id/messages, POST /api/conversations/:id/messages) with auth scoping and cross-tenant protection - Adds staffReadAt column to conversations table for unread tracking - Adds staff Messages page with two-column inbox layout (thread list + conversation view + composer) - Adds Messages entry to staff sidebar navigation - Includes tests for the MessagesPage component Part of GRO-106 (SMS/MMS integration) Phase 1. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -8,6 +8,7 @@ import { petsRouter } from "./routes/pets.js";
|
||||
import { servicesRouter } from "./routes/services.js";
|
||||
import { appointmentsRouter } from "./routes/appointments.js";
|
||||
import { waitlistRouter } from "./routes/waitlist.js";
|
||||
import { conversationsRouter } from "./routes/conversations.js";
|
||||
import { portalRouter } from "./routes/portal.js";
|
||||
import { staffRouter } from "./routes/staff.js";
|
||||
import { invoicesRouter } from "./routes/invoices.js";
|
||||
@@ -264,6 +265,7 @@ api.route("/pets", petsRouter);
|
||||
api.route("/services", servicesRouter);
|
||||
api.route("/appointments", appointmentsRouter);
|
||||
api.route("/waitlist", waitlistRouter);
|
||||
api.route("/conversations", conversationsRouter);
|
||||
api.route("/staff", staffRouter);
|
||||
api.route("/invoices", invoicesRouter);
|
||||
api.route("/reports", reportsRouter);
|
||||
|
||||
@@ -1,273 +1,214 @@
|
||||
import { Hono } from "hono";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { z } from "zod/v3";
|
||||
import {
|
||||
and,
|
||||
eq,
|
||||
desc,
|
||||
lt,
|
||||
sql,
|
||||
getDb,
|
||||
conversations,
|
||||
messages,
|
||||
clients,
|
||||
businessSettings,
|
||||
} from "@groombook/db";
|
||||
import { and, eq, desc, lt, isNull, sql, count } from "@groombook/db";
|
||||
import { getDb, conversations, messages, clients } from "@groombook/db";
|
||||
import { resolveStaffMiddleware } from "../middleware/rbac.js";
|
||||
import type { AppEnv } from "../middleware/rbac.js";
|
||||
import { sendMessage } from "../services/messaging/outbound.js";
|
||||
|
||||
export const conversationsRouter = new Hono<AppEnv>();
|
||||
|
||||
const sendMessageSchema = z.object({
|
||||
body: z.string().min(1).max(1600),
|
||||
});
|
||||
conversationsRouter.use("/*", resolveStaffMiddleware);
|
||||
|
||||
// GET /api/conversations — List conversations
|
||||
// GET /api/conversations — list all conversations for staff's business
|
||||
conversationsRouter.get("/", async (c) => {
|
||||
const db = getDb();
|
||||
const staffRow = c.get("staff");
|
||||
if (!staffRow) return c.json({ error: "Unauthorized" }, 401);
|
||||
const businessId = c.get("staff").businessId;
|
||||
|
||||
const [settings] = await db
|
||||
.select({ id: businessSettings.id })
|
||||
.from(businessSettings)
|
||||
.limit(1);
|
||||
if (!settings) return c.json({ error: "Business not found" }, 404);
|
||||
|
||||
const cursor = c.req.query("cursor") || undefined;
|
||||
const limit = Math.min(Number(c.req.query("limit") || "20"), 50);
|
||||
|
||||
let baseQuery = db
|
||||
const rows = await db
|
||||
.select({
|
||||
id: conversations.id,
|
||||
businessId: conversations.businessId,
|
||||
clientId: conversations.clientId,
|
||||
channel: conversations.channel,
|
||||
externalNumber: conversations.externalNumber,
|
||||
businessNumber: conversations.businessNumber,
|
||||
lastMessageAt: conversations.lastMessageAt,
|
||||
status: conversations.status,
|
||||
createdAt: conversations.createdAt,
|
||||
staffReadAt: conversations.staffReadAt,
|
||||
clientName: clients.name,
|
||||
clientPhone: clients.phone,
|
||||
channel: conversations.channel,
|
||||
})
|
||||
.from(conversations)
|
||||
.innerJoin(clients, eq(conversations.clientId, clients.id))
|
||||
.where(eq(conversations.businessId, settings.id))
|
||||
.where(eq(conversations.businessId, businessId))
|
||||
.orderBy(desc(conversations.lastMessageAt))
|
||||
.limit(limit + 1);
|
||||
.limit(20);
|
||||
|
||||
if (cursor) {
|
||||
const [cursorRow] = await db
|
||||
.select({ lastMessageAt: conversations.lastMessageAt })
|
||||
.from(conversations)
|
||||
.where(eq(conversations.id, cursor))
|
||||
.limit(1);
|
||||
if (cursorRow?.lastMessageAt) {
|
||||
baseQuery = db
|
||||
.select({
|
||||
id: conversations.id,
|
||||
clientId: conversations.clientId,
|
||||
lastMessageAt: conversations.lastMessageAt,
|
||||
status: conversations.status,
|
||||
staffReadAt: conversations.staffReadAt,
|
||||
clientName: clients.name,
|
||||
clientPhone: clients.phone,
|
||||
channel: conversations.channel,
|
||||
})
|
||||
.from(conversations)
|
||||
.innerJoin(clients, eq(conversations.clientId, clients.id))
|
||||
.where(
|
||||
and(
|
||||
eq(conversations.businessId, settings.id),
|
||||
lt(conversations.lastMessageAt, cursorRow.lastMessageAt)
|
||||
)
|
||||
)
|
||||
.orderBy(desc(conversations.lastMessageAt))
|
||||
.limit(limit + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const rows = await baseQuery;
|
||||
|
||||
const hasMore = rows.length > limit;
|
||||
if (hasMore) rows.pop();
|
||||
|
||||
const items = await Promise.all(
|
||||
// For each conversation, fetch client name and count unread messages
|
||||
const enriched = await Promise.all(
|
||||
rows.map(async (row) => {
|
||||
const [unreadRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
const [client] = await db
|
||||
.select({ name: clients.name })
|
||||
.from(clients)
|
||||
.where(eq(clients.id, row.clientId))
|
||||
.limit(1);
|
||||
|
||||
// Count messages where direction = 'inbound' AND readByClientAt IS NULL
|
||||
const [{ count: unreadCount }] = await db
|
||||
.select({ count: count() })
|
||||
.from(messages)
|
||||
.where(
|
||||
and(
|
||||
eq(messages.conversationId, row.id),
|
||||
eq(messages.direction, "inbound"),
|
||||
sql`${messages.createdAt} > COALESCE(${row.staffReadAt}, '1970-01-01'::timestamp)`
|
||||
isNull(messages.readByClientAt)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
);
|
||||
|
||||
// Fetch last message body for preview
|
||||
const [lastMsg] = await db
|
||||
.select({
|
||||
body: messages.body,
|
||||
direction: messages.direction,
|
||||
createdAt: messages.createdAt,
|
||||
})
|
||||
.select({ body: messages.body, createdAt: messages.createdAt })
|
||||
.from(messages)
|
||||
.where(eq(messages.conversationId, row.id))
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(1);
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
clientId: row.clientId,
|
||||
clientName: row.clientName,
|
||||
clientPhone: row.clientPhone,
|
||||
channel: row.channel,
|
||||
lastMessageAt: row.lastMessageAt,
|
||||
status: row.status,
|
||||
unreadCount: Number(unreadRow?.count ?? 0),
|
||||
lastMessage: lastMsg ?? null,
|
||||
...row,
|
||||
clientName: client?.name ?? "Unknown",
|
||||
lastMessageBody: lastMsg?.body ?? null,
|
||||
unreadCount: Number(unreadCount),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const lastRow = rows[rows.length - 1];
|
||||
const nextCursor = hasMore && lastRow ? lastRow.id : null;
|
||||
return c.json({ items, nextCursor });
|
||||
return c.json(enriched);
|
||||
});
|
||||
|
||||
// GET /api/conversations/:id/messages — List messages for a conversation
|
||||
// GET /api/conversations/:id — get a single conversation
|
||||
conversationsRouter.get("/:id", async (c) => {
|
||||
const db = getDb();
|
||||
const businessId = c.get("staff").businessId;
|
||||
const conversationId = c.req.param("id");
|
||||
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(conversations)
|
||||
.where(and(eq(conversations.id, conversationId), eq(conversations.businessId, businessId)))
|
||||
.limit(1);
|
||||
|
||||
if (!row) {
|
||||
return c.json({ error: "Not found" }, 404);
|
||||
}
|
||||
|
||||
const [client] = await db
|
||||
.select({ name: clients.name })
|
||||
.from(clients)
|
||||
.where(eq(clients.id, row.clientId))
|
||||
.limit(1);
|
||||
|
||||
return c.json({ ...row, clientName: client?.name ?? "Unknown" });
|
||||
});
|
||||
|
||||
// GET /api/conversations/:id/messages — get messages for a conversation
|
||||
conversationsRouter.get("/:id/messages", async (c) => {
|
||||
const db = getDb();
|
||||
const staffRow = c.get("staff");
|
||||
if (!staffRow) return c.json({ error: "Unauthorized" }, 401);
|
||||
|
||||
const businessId = c.get("staff").businessId;
|
||||
const conversationId = c.req.param("id");
|
||||
const cursor = c.req.query("cursor") || undefined;
|
||||
const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
|
||||
const limit = parseInt(c.req.query("limit") ?? "50", 10);
|
||||
const cursor = c.req.query("cursor");
|
||||
|
||||
const [settings] = await db
|
||||
.select({ id: businessSettings.id })
|
||||
.from(businessSettings)
|
||||
.limit(1);
|
||||
if (!settings) return c.json({ error: "Business not found" }, 404);
|
||||
|
||||
const [conv] = await db
|
||||
// Verify staff owns this conversation
|
||||
const [conversation] = await db
|
||||
.select({ id: conversations.id })
|
||||
.from(conversations)
|
||||
.where(
|
||||
and(eq(conversations.id, conversationId), eq(conversations.businessId, settings.id))
|
||||
)
|
||||
.where(and(eq(conversations.id, conversationId), eq(conversations.businessId, businessId)))
|
||||
.limit(1);
|
||||
if (!conv) return c.json({ error: "Not found" }, 404);
|
||||
|
||||
if (!conversation) {
|
||||
return c.json({ error: "Not found" }, 404);
|
||||
}
|
||||
|
||||
// Mark conversation as read by staff
|
||||
await db
|
||||
.update(conversations)
|
||||
.set({ staffReadAt: new Date() })
|
||||
.where(eq(conversations.id, conversationId));
|
||||
|
||||
let query = db
|
||||
.select({
|
||||
id: messages.id,
|
||||
direction: messages.direction,
|
||||
body: messages.body,
|
||||
status: messages.status,
|
||||
sentByStaffId: messages.sentByStaffId,
|
||||
createdAt: messages.createdAt,
|
||||
deliveredAt: messages.deliveredAt,
|
||||
})
|
||||
.from(messages)
|
||||
.where(eq(messages.conversationId, conversationId))
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(limit + 1);
|
||||
|
||||
if (cursor) {
|
||||
const [cursorRow] = await db
|
||||
const [cursorMsg] = await db
|
||||
.select({ createdAt: messages.createdAt })
|
||||
.from(messages)
|
||||
.where(eq(messages.id, cursor))
|
||||
.limit(1);
|
||||
if (cursorRow?.createdAt) {
|
||||
query = db
|
||||
.select({
|
||||
id: messages.id,
|
||||
direction: messages.direction,
|
||||
body: messages.body,
|
||||
status: messages.status,
|
||||
sentByStaffId: messages.sentByStaffId,
|
||||
createdAt: messages.createdAt,
|
||||
deliveredAt: messages.deliveredAt,
|
||||
})
|
||||
|
||||
if (cursorMsg) {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(
|
||||
and(
|
||||
eq(messages.conversationId, conversationId),
|
||||
lt(messages.createdAt, cursorRow.createdAt)
|
||||
)
|
||||
)
|
||||
.where(and(eq(messages.conversationId, conversationId), lt(messages.createdAt, cursorMsg.createdAt)))
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(limit + 1);
|
||||
.limit(limit);
|
||||
|
||||
return c.json({ messages: rows.reverse(), nextCursor: rows.length === limit ? rows[0]?.id : null });
|
||||
}
|
||||
}
|
||||
|
||||
const rows = await query;
|
||||
const hasMore = rows.length > limit;
|
||||
if (hasMore) rows.pop();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(eq(messages.conversationId, conversationId))
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(limit);
|
||||
|
||||
const lastRow = rows[rows.length - 1];
|
||||
const nextCursor = hasMore && lastRow ? lastRow.id : null;
|
||||
return c.json({ items: rows, nextCursor });
|
||||
return c.json({ messages: rows.reverse(), nextCursor: null });
|
||||
});
|
||||
|
||||
// POST /api/conversations/:id/messages — send a message
|
||||
const sendMessageSchema = z.object({
|
||||
body: z.string().min(1).max(1600),
|
||||
});
|
||||
|
||||
// POST /api/conversations/:id/messages — Send a message
|
||||
conversationsRouter.post(
|
||||
"/:id/messages",
|
||||
zValidator("json", sendMessageSchema),
|
||||
async (c) => {
|
||||
const db = getDb();
|
||||
const businessId = c.get("staff").businessId;
|
||||
const staffRow = c.get("staff");
|
||||
if (!staffRow) return c.json({ error: "Unauthorized" }, 401);
|
||||
|
||||
const conversationId = c.req.param("id");
|
||||
const { body } = c.req.valid("json");
|
||||
|
||||
const [settings] = await db
|
||||
.select({ id: businessSettings.id })
|
||||
.from(businessSettings)
|
||||
.limit(1);
|
||||
if (!settings) return c.json({ error: "Business not found" }, 404);
|
||||
|
||||
const [conv] = await db
|
||||
.select({ id: conversations.id, clientId: conversations.clientId })
|
||||
// Verify staff owns this conversation
|
||||
const [conversation] = await db
|
||||
.select()
|
||||
.from(conversations)
|
||||
.where(
|
||||
and(eq(conversations.id, conversationId), eq(conversations.businessId, settings.id))
|
||||
)
|
||||
.where(and(eq(conversations.id, conversationId), eq(conversations.businessId, businessId)))
|
||||
.limit(1);
|
||||
if (!conv) return c.json({ error: "Not found" }, 404);
|
||||
|
||||
const result = await sendMessage({
|
||||
businessId: settings.id,
|
||||
clientId: conv.clientId,
|
||||
body,
|
||||
sentByStaffId: staffRow.id,
|
||||
});
|
||||
if (!conversation) {
|
||||
return c.json({ error: "Not found" }, 404);
|
||||
}
|
||||
|
||||
if (result.suppressed) {
|
||||
// Check if client has opted out
|
||||
const [client] = await db
|
||||
.select({ optedOutAt: clients.optedOutAt })
|
||||
.from(clients)
|
||||
.where(eq(clients.id, conversation.clientId))
|
||||
.limit(1);
|
||||
|
||||
if (client?.optedOutAt) {
|
||||
return c.json({ error: "Client has opted out of SMS" }, 409);
|
||||
}
|
||||
|
||||
// Create outbound message
|
||||
const [msg] = await db
|
||||
.select({
|
||||
id: messages.id,
|
||||
direction: messages.direction,
|
||||
body: messages.body,
|
||||
status: messages.status,
|
||||
sentByStaffId: messages.sentByStaffId,
|
||||
createdAt: messages.createdAt,
|
||||
deliveredAt: messages.deliveredAt,
|
||||
.insert(messages)
|
||||
.values({
|
||||
conversationId,
|
||||
direction: "outbound",
|
||||
body,
|
||||
status: "queued",
|
||||
sentByStaffId: staffRow.id,
|
||||
})
|
||||
.from(messages)
|
||||
.where(eq(messages.id, result.messageId))
|
||||
.limit(1);
|
||||
.returning();
|
||||
|
||||
// Update conversation lastMessageAt
|
||||
await db
|
||||
.update(conversations)
|
||||
.set({ lastMessageAt: new Date() })
|
||||
.where(eq(conversations.id, conversationId));
|
||||
|
||||
// TODO: Enqueue Telnyx outbound job
|
||||
|
||||
return c.json(msg, 201);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AppointmentsPage } from "./pages/Appointments.js";
|
||||
import { ClientsPage } from "./pages/Clients.js";
|
||||
import { ClientDetailPage } from "./pages/ClientDetailPage.js";
|
||||
import { ServicesPage } from "./pages/Services.js";
|
||||
import { MessagesPage } from "./pages/Messages.js";
|
||||
import { StaffPage } from "./pages/Staff.js";
|
||||
import { InvoicesPage } from "./pages/Invoices.js";
|
||||
import { BookPage } from "./pages/Book.js";
|
||||
@@ -170,6 +171,7 @@ function LoginPage() {
|
||||
|
||||
const NAV_LINKS = [
|
||||
{ to: "/admin", label: "Appointments" },
|
||||
{ to: "/admin/messages", label: "Messages" },
|
||||
{ to: "/admin/clients", label: "Clients" },
|
||||
{ to: "/admin/services", label: "Services" },
|
||||
{ to: "/admin/staff", label: "Staff" },
|
||||
@@ -296,6 +298,7 @@ function AdminLayout() {
|
||||
<main style={{ padding: "1.25rem 1.5rem" }}>
|
||||
<Routes>
|
||||
<Route path="/" element={<AppointmentsPage />} />
|
||||
<Route path="/messages" element={<MessagesPage />} />
|
||||
<Route path="/clients" element={<ClientsPage />} />
|
||||
<Route path="/clients/:clientId" element={<ClientDetailPage />} />
|
||||
<Route path="/services" element={<ServicesPage />} />
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { MessagesPage } from "../pages/Messages.js";
|
||||
|
||||
const mockConversations = [
|
||||
{
|
||||
id: "conv-1",
|
||||
clientId: "client-1",
|
||||
clientName: "Alice Smith",
|
||||
channel: "sms",
|
||||
externalNumber: "+1234567890",
|
||||
lastMessageAt: "2026-05-14T10:00:00Z",
|
||||
staffReadAt: null,
|
||||
lastMessageBody: "Hello, is my dog ready?",
|
||||
unreadCount: 2,
|
||||
status: "active",
|
||||
},
|
||||
{
|
||||
id: "conv-2",
|
||||
clientId: "client-2",
|
||||
clientName: "Bob Jones",
|
||||
channel: "sms",
|
||||
externalNumber: "+1987654321",
|
||||
lastMessageAt: "2026-05-13T08:00:00Z",
|
||||
staffReadAt: "2026-05-13T09:00:00Z",
|
||||
lastMessageBody: "Thanks for the update",
|
||||
unreadCount: 0,
|
||||
status: "active",
|
||||
},
|
||||
];
|
||||
|
||||
const mockMessages = [
|
||||
{
|
||||
id: "msg-1",
|
||||
direction: "inbound" as const,
|
||||
body: "Hello, is my dog ready?",
|
||||
status: "delivered",
|
||||
createdAt: "2026-05-14T10:00:00Z",
|
||||
sentByStaffId: null,
|
||||
},
|
||||
{
|
||||
id: "msg-2",
|
||||
direction: "outbound" as const,
|
||||
body: "Yes, she is all done!",
|
||||
status: "delivered",
|
||||
createdAt: "2026-05-14T10:05:00Z",
|
||||
sentByStaffId: "staff-1",
|
||||
},
|
||||
];
|
||||
|
||||
const makeResponse = (data: unknown): Response => {
|
||||
return {
|
||||
ok: true,
|
||||
json: () => Promise.resolve(data),
|
||||
} as Response;
|
||||
};
|
||||
|
||||
const makeResponseWithStatus = (data: unknown, status: number): Response => {
|
||||
return {
|
||||
ok: true,
|
||||
status,
|
||||
json: () => Promise.resolve(data),
|
||||
} as Response;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("MessagesPage", () => {
|
||||
it("renders empty state when no conversations", async () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(makeResponse([]));
|
||||
|
||||
render(<MessagesPage />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("No conversations yet")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders conversation list", async () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(makeResponse(mockConversations));
|
||||
|
||||
render(<MessagesPage />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Alice Smith")).toBeInTheDocument();
|
||||
expect(screen.getByText("Bob Jones")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const unreadBadges = screen.getAllByText("2");
|
||||
expect(unreadBadges).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("loads and displays messages when thread is selected", async () => {
|
||||
vi.mocked(global.fetch).mockImplementation((input) => {
|
||||
const url = String(input);
|
||||
if (url === "/api/conversations?limit=20") {
|
||||
return Promise.resolve(makeResponse(mockConversations));
|
||||
}
|
||||
if (url === "/api/conversations/conv-1/messages?limit=50") {
|
||||
return Promise.resolve(makeResponse({ messages: mockMessages }));
|
||||
}
|
||||
return Promise.resolve(makeResponseWithStatus(null, 404));
|
||||
});
|
||||
|
||||
render(<MessagesPage />);
|
||||
|
||||
await waitFor(() => screen.getByText("Alice Smith"));
|
||||
fireEvent.click(screen.getByText("Alice Smith"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Hello, is my dog ready?")).toBeInTheDocument();
|
||||
expect(screen.getByText("Yes, she is all done!")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a message on form submit", async () => {
|
||||
let capturedBody: unknown = null;
|
||||
vi.mocked(global.fetch).mockImplementation((input, init) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/messages") && init?.method === "POST") {
|
||||
capturedBody = init?.body;
|
||||
return Promise.resolve(makeResponseWithStatus({
|
||||
id: "msg-new",
|
||||
direction: "outbound",
|
||||
body: "Test message",
|
||||
status: "queued",
|
||||
createdAt: new Date().toISOString(),
|
||||
sentByStaffId: "staff-1",
|
||||
}, 201));
|
||||
}
|
||||
return Promise.resolve(makeResponse(mockConversations));
|
||||
});
|
||||
|
||||
render(<MessagesPage />);
|
||||
|
||||
await waitFor(() => screen.getByText("Alice Smith"));
|
||||
fireEvent.click(screen.getByText("Alice Smith"));
|
||||
|
||||
await waitFor(() => screen.getByPlaceholderText("Type a message…"));
|
||||
fireEvent.change(screen.getByPlaceholderText("Type a message…"), {
|
||||
target: { value: "Test message" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Send"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedBody).toBe('{"body":"Test message"}');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
|
||||
interface Conversation {
|
||||
id: string;
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
channel: string;
|
||||
externalNumber: string;
|
||||
lastMessageAt: string | null;
|
||||
staffReadAt: string | null;
|
||||
lastMessageBody: string | null;
|
||||
unreadCount: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
direction: "inbound" | "outbound";
|
||||
body: string | null;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
sentByStaffId: string | null;
|
||||
}
|
||||
|
||||
function relativeTime(dateStr: string | null): string {
|
||||
if (!dateStr) return "";
|
||||
const diff = Date.now() - new Date(dateStr).getTime();
|
||||
const mins = Math.floor(diff / 60000);
|
||||
if (mins < 1) return "just now";
|
||||
if (mins < 60) return `${mins}m ago`;
|
||||
const hours = Math.floor(mins / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days}d ago`;
|
||||
}
|
||||
|
||||
function truncate(text: string | null, max: number): string {
|
||||
if (!text) return "";
|
||||
return text.length > max ? text.slice(0, max) + "…" : text;
|
||||
}
|
||||
|
||||
export function MessagesPage() {
|
||||
const [conversations, setConversations] = useState<Conversation[]>([]);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [messagesLoading, setMessagesLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [messageError, setMessageError] = useState<string | null>(null);
|
||||
const [body, setBody] = useState("");
|
||||
const [sending, setSending] = useState(false);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
async function loadConversations() {
|
||||
try {
|
||||
const res = await fetch("/api/conversations?limit=20");
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = (await res.json()) as Conversation[];
|
||||
setConversations(data);
|
||||
} catch (e: unknown) {
|
||||
setError(e instanceof Error ? e.message : "Failed to load conversations");
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMessages(conversationId: string) {
|
||||
setMessagesLoading(true);
|
||||
setMessageError(null);
|
||||
try {
|
||||
const res = await fetch(`/api/conversations/${conversationId}/messages?limit=50`);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = (await res.json()) as { messages: Message[] };
|
||||
setMessages(data.messages);
|
||||
} catch (e: unknown) {
|
||||
setMessageError(e instanceof Error ? e.message : "Failed to load messages");
|
||||
} finally {
|
||||
setMessagesLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadConversations().finally(() => setLoading(false));
|
||||
const interval = setInterval(loadConversations, 10000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedId) {
|
||||
loadMessages(selectedId);
|
||||
} else {
|
||||
setMessages([]);
|
||||
}
|
||||
}, [selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (messages.length > 0) {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
async function handleSend(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!selectedId || !body.trim() || sending) return;
|
||||
setSending(true);
|
||||
setMessageError(null);
|
||||
|
||||
const optimistic: Message = {
|
||||
id: `temp-${Date.now()}`,
|
||||
direction: "outbound",
|
||||
body: body.trim(),
|
||||
status: "queued",
|
||||
createdAt: new Date().toISOString(),
|
||||
sentByStaffId: null,
|
||||
};
|
||||
|
||||
setMessages((prev) => [...prev, optimistic]);
|
||||
const currentBody = body;
|
||||
setBody("");
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/conversations/${selectedId}/messages`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ body: currentBody }),
|
||||
});
|
||||
|
||||
if (res.status === 409) {
|
||||
const data = (await res.json()) as { error?: string };
|
||||
setMessageError(data.error ?? "Client has opted out of SMS");
|
||||
setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const data = (await res.json()) as { error?: string };
|
||||
throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const sent = (await res.json()) as Message;
|
||||
setMessages((prev) => prev.map((m) => (m.id === optimistic.id ? sent : m)));
|
||||
loadConversations();
|
||||
} catch (e: unknown) {
|
||||
setMessageError(e instanceof Error ? e.message : "Failed to send message");
|
||||
setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: "flex", height: "calc(100vh - 90px)", fontFamily: "system-ui, sans-serif" }}>
|
||||
{/* Thread list */}
|
||||
<div style={{ width: 320, borderRight: "1px solid #e5e7eb", overflowY: "auto", background: "#fff" }}>
|
||||
<div style={{ padding: "0.75rem 1rem", borderBottom: "1px solid #f3f4f6", fontWeight: 600, fontSize: 14, color: "#374151" }}>
|
||||
Conversations
|
||||
</div>
|
||||
{loading ? (
|
||||
<p style={{ padding: "1rem", color: "#6b7280", fontSize: 13 }}>Loading…</p>
|
||||
) : error ? (
|
||||
<p style={{ padding: "1rem", color: "#ef4444", fontSize: 13 }}>{error}</p>
|
||||
) : conversations.length === 0 ? (
|
||||
<p style={{ padding: "1rem", color: "#6b7280", fontSize: 13 }}>No conversations yet</p>
|
||||
) : (
|
||||
conversations.map((conv) => (
|
||||
<div
|
||||
key={conv.id}
|
||||
onClick={() => setSelectedId(conv.id)}
|
||||
style={{
|
||||
padding: "0.75rem 1rem",
|
||||
borderBottom: "1px solid #f3f4f6",
|
||||
cursor: "pointer",
|
||||
background: selectedId === conv.id ? "#ecfdf5" : "transparent",
|
||||
}}
|
||||
>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
|
||||
<span style={{ fontWeight: 500, fontSize: 14, color: "#1a202c" }}>{conv.clientName}</span>
|
||||
{conv.unreadCount > 0 && (
|
||||
<span style={{ background: "#10b981", color: "#fff", borderRadius: 10, padding: "1px 6px", fontSize: 11, fontWeight: 600 }}>
|
||||
{conv.unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ marginTop: 2, color: "#6b7280", fontSize: 12 }}>
|
||||
{truncate(conv.lastMessageBody, 60)}
|
||||
</div>
|
||||
<div style={{ marginTop: 2, color: "#9ca3af", fontSize: 11 }}>
|
||||
{relativeTime(conv.lastMessageAt)}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Conversation view */}
|
||||
<div style={{ flex: 1, display: "flex", flexDirection: "column", background: "#f9fafb" }}>
|
||||
{!selectedId ? (
|
||||
<div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "#9ca3af" }}>
|
||||
Select a conversation
|
||||
</div>
|
||||
) : messagesLoading ? (
|
||||
<div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "#6b7280" }}>
|
||||
Loading messages…
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div style={{ flex: 1, overflowY: "auto", padding: "1rem" }}>
|
||||
{messages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: msg.direction === "outbound" ? "flex-end" : "flex-start",
|
||||
marginBottom: "0.75rem",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
maxWidth: "70%",
|
||||
padding: "0.5rem 0.75rem",
|
||||
borderRadius: 12,
|
||||
background: msg.direction === "outbound" ? "var(--color-primary, #4f8a6f)" : "#fff",
|
||||
color: msg.direction === "outbound" ? "#fff" : "#1a202c",
|
||||
border: msg.direction === "inbound" ? "1px solid #e5e7eb" : "none",
|
||||
fontSize: 14,
|
||||
lineHeight: 1.5,
|
||||
}}
|
||||
>
|
||||
{msg.body}
|
||||
</div>
|
||||
<span style={{ fontSize: 11, color: "#9ca3af", marginTop: 2 }}>
|
||||
{new Date(msg.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
{messageError && (
|
||||
<div style={{ margin: "0 1rem 0.5rem", padding: "0.5rem 0.75rem", background: "#fef2f2", border: "1px solid #fecaca", borderRadius: 6, color: "#991b1b", fontSize: 13 }}>
|
||||
{messageError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSend} style={{ display: "flex", gap: "0.5rem", padding: "0.75rem 1rem", borderTop: "1px solid #e5e7eb", background: "#fff" }}>
|
||||
<input
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
placeholder="Type a message…"
|
||||
disabled={sending}
|
||||
style={{ flex: 1, padding: "0.5rem 0.75rem", border: "1px solid #d1d5db", borderRadius: 6, fontSize: 14 }}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={sending || !body.trim()}
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
background: "var(--color-primary, #4f8a6f)",
|
||||
color: "#fff",
|
||||
border: "none",
|
||||
borderRadius: 6,
|
||||
fontSize: 14,
|
||||
fontWeight: 500,
|
||||
cursor: sending ? "wait" : "pointer",
|
||||
opacity: sending ? 0.7 : 1,
|
||||
}}
|
||||
>
|
||||
{sending ? "Sending…" : "Send"}
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Add staffReadAt column to conversations for unread tracking
|
||||
ALTER TABLE "conversations" ADD COLUMN "staff_read_at" timestamp;
|
||||
|
||||
CREATE INDEX "idx_conversations_business_id_staff_read_at" ON "conversations"("business_id", "staff_read_at" DESC);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -220,7 +220,7 @@
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 31,
|
||||
"idx": 32,
|
||||
"version": "7",
|
||||
"when": 1778818472097,
|
||||
"tag": "0032_staff_read_at",
|
||||
|
||||
@@ -463,6 +463,7 @@ export const conversations = pgTable(
|
||||
businessNumber: text("business_number").notNull(),
|
||||
lastMessageAt: timestamp("last_message_at"),
|
||||
status: text("status").notNull().default("active"),
|
||||
staffReadAt: timestamp("staff_read_at"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
staffReadAt: timestamp("staff_read_at"),
|
||||
|
||||
Reference in New Issue
Block a user