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:
2026-05-14 10:27:06 +00:00
committed by Flea Flicker [agent]
parent f43e566dbd
commit c4978be280
9 changed files with 3728 additions and 185 deletions
+2
View File
@@ -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);
+125 -184
View File
@@ -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);
}