Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0334539d02 | |||
| a9b9a0a733 | |||
| dce9c96442 | |||
| 22135859c2 | |||
| a5115f5291 | |||
| e64538822d | |||
| a70dbbd2c1 | |||
| a61614c4a9 | |||
| 28a78a79d5 | |||
| 35c72a6c4b | |||
| 2d88f18f75 | |||
| 9363929f32 | |||
| 2c2a69f20b | |||
| e52d561454 | |||
| 49dd698d22 | |||
| 305394baaf | |||
| 706c91b3ac | |||
| 39f5c83049 | |||
| 6c0cdb33fe | |||
| 2134676f10 | |||
| dec4112ee5 |
@@ -11,6 +11,10 @@ AUTH_DISABLED=false
|
|||||||
OIDC_ISSUER=https://authentik.example.com
|
OIDC_ISSUER=https://authentik.example.com
|
||||||
OIDC_AUDIENCE=groombook
|
OIDC_AUDIENCE=groombook
|
||||||
|
|
||||||
|
# ── Webhooks ─────────────────────────────────────────────────────────────────
|
||||||
|
# Telnyx webhook secret for validating inbound message webhooks.
|
||||||
|
TELNYX_WEBHOOK_SECRET=your-telnyx-webhook-secret-here
|
||||||
|
|
||||||
# ── Setup Wizard ─────────────────────────────────────────────────────────────
|
# ── Setup Wizard ─────────────────────────────────────────────────────────────
|
||||||
# When SKIP_OOBE=true, the setup wizard is bypassed regardless of whether a
|
# When SKIP_OOBE=true, the setup wizard is bypassed regardless of whether a
|
||||||
# super user exists in the database. Useful in dev/test environments where the
|
# super user exists in the database. Useful in dev/test environments where the
|
||||||
|
|||||||
@@ -24,8 +24,7 @@
|
|||||||
"nodemailer": "^6.9.16",
|
"nodemailer": "^6.9.16",
|
||||||
"stripe": "^22.0.0",
|
"stripe": "^22.0.0",
|
||||||
"telnyx": "^1.23.0",
|
"telnyx": "^1.23.0",
|
||||||
"uuid": "^11.0.5",
|
"uuid": "^11.1.1",
|
||||||
|
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { Hono } from "hono";
|
||||||
|
|
||||||
|
// ─── Mock data ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const STAFF_ROW = {
|
||||||
|
id: "staff-uuid-1",
|
||||||
|
email: "groomer@groombook.com",
|
||||||
|
name: "Groomer",
|
||||||
|
role: "groomer" as const,
|
||||||
|
businessId: "business-uuid-1",
|
||||||
|
active: true,
|
||||||
|
userId: null,
|
||||||
|
oidcSub: null,
|
||||||
|
isSuperUser: false,
|
||||||
|
icalToken: null,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const BUSINESS_SETTINGS = {
|
||||||
|
id: "business-uuid-1",
|
||||||
|
businessName: "Test Salon",
|
||||||
|
};
|
||||||
|
|
||||||
|
const CONV_1 = {
|
||||||
|
id: "conv-uuid-1",
|
||||||
|
businessId: "business-uuid-1",
|
||||||
|
clientId: "client-uuid-1",
|
||||||
|
channel: "sms",
|
||||||
|
externalNumber: "+15551111111",
|
||||||
|
businessNumber: "+15552222222",
|
||||||
|
lastMessageAt: new Date("2025-01-10T10:00:00Z"),
|
||||||
|
status: "active",
|
||||||
|
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2025-01-10T10:00:00Z"),
|
||||||
|
staffReadAt: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const MSG_INBOUND_1 = {
|
||||||
|
id: "msg-uuid-1",
|
||||||
|
conversationId: "conv-uuid-1",
|
||||||
|
direction: "inbound",
|
||||||
|
body: "Hello",
|
||||||
|
status: "delivered",
|
||||||
|
sentByStaffId: null,
|
||||||
|
createdAt: new Date("2025-01-10T09:00:00Z"),
|
||||||
|
deliveredAt: new Date("2025-01-10T09:01:00Z"),
|
||||||
|
};
|
||||||
|
|
||||||
|
const MSG_OUTBOUND_1 = {
|
||||||
|
id: "msg-uuid-2",
|
||||||
|
conversationId: "conv-uuid-1",
|
||||||
|
direction: "outbound",
|
||||||
|
body: "Hi Alice!",
|
||||||
|
status: "delivered",
|
||||||
|
sentByStaffId: "staff-uuid-1",
|
||||||
|
createdAt: new Date("2025-01-10T10:00:00Z"),
|
||||||
|
deliveredAt: new Date("2025-01-10T10:01:00Z"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Queue-based mock DB ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
let selectRows: Record<string, unknown>[] = [];
|
||||||
|
let selectRows2: Record<string, unknown>[] = [];
|
||||||
|
let selectRows3: Record<string, unknown>[] = [];
|
||||||
|
let updatedValues: Record<string, unknown>[] = [];
|
||||||
|
let selectCallCount = 0;
|
||||||
|
|
||||||
|
function resetMock() {
|
||||||
|
selectRows = [];
|
||||||
|
selectRows2 = [];
|
||||||
|
selectRows3 = [];
|
||||||
|
updatedValues = [];
|
||||||
|
selectCallCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetAll() {
|
||||||
|
resetMock();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
}
|
||||||
|
|
||||||
|
const mockSendMessage = vi.hoisted(() => vi.fn());
|
||||||
|
|
||||||
|
vi.mock("@groombook/db", () => {
|
||||||
|
function makeChainable(data: unknown[]): unknown {
|
||||||
|
const arr = [...data];
|
||||||
|
const chain = new Proxy(arr, {
|
||||||
|
get(target, prop) {
|
||||||
|
if (prop === "where" || prop === "orderBy" || prop === "limit" || prop === "innerJoin") {
|
||||||
|
return () => chain;
|
||||||
|
}
|
||||||
|
if (prop === "from") {
|
||||||
|
return (table: unknown) => {
|
||||||
|
const tableName = (table as { _name?: string })._name;
|
||||||
|
const rows = tableName === "businessSettings" ? [BUSINESS_SETTINGS] : selectRows;
|
||||||
|
return makeChainable(rows);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// @ts-expect-error proxy
|
||||||
|
return target[prop];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return chain;
|
||||||
|
}
|
||||||
|
|
||||||
|
const conversations = new Proxy(
|
||||||
|
{ _name: "conversations" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "conversations" : { table: "conversations", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
|
const messages = new Proxy(
|
||||||
|
{ _name: "messages" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "messages" : { table: "messages", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
|
const clients = new Proxy(
|
||||||
|
{ _name: "clients" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "clients" : { table: "clients", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
|
const businessSettings = new Proxy(
|
||||||
|
{ _name: "businessSettings" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "businessSettings" : { table: "businessSettings", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
getDb: () => ({
|
||||||
|
select: () => ({
|
||||||
|
from: (table: unknown) => {
|
||||||
|
const tableName = (table as { _name?: string })._name;
|
||||||
|
if (tableName === "businessSettings") return makeChainable([BUSINESS_SETTINGS]);
|
||||||
|
if (tableName === "messages") {
|
||||||
|
// Return selectRows3 if it has data (POST re-query), else cycle through selectRows/selectRows2
|
||||||
|
if (selectRows3.length > 0) {
|
||||||
|
return makeChainable(selectRows3);
|
||||||
|
}
|
||||||
|
if (selectCallCount === 0 || selectCallCount === 1) {
|
||||||
|
const rows = selectCallCount === 0 ? selectRows : selectRows2;
|
||||||
|
selectCallCount++;
|
||||||
|
return makeChainable(rows);
|
||||||
|
}
|
||||||
|
return makeChainable(selectRows);
|
||||||
|
}
|
||||||
|
return makeChainable(selectRows);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
update: () => ({
|
||||||
|
set: (vals: Record<string, unknown>) => ({
|
||||||
|
where: () => {
|
||||||
|
updatedValues.push(vals);
|
||||||
|
return { returning: () => [vals] };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
insert: () => ({
|
||||||
|
values: (vals: Record<string, unknown>) => {
|
||||||
|
return { returning: () => [{ ...vals, id: "msg-uuid-new" }] };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
conversations,
|
||||||
|
messages,
|
||||||
|
clients,
|
||||||
|
businessSettings,
|
||||||
|
eq: vi.fn((a, b) => ({ type: "eq", a, b })),
|
||||||
|
and: vi.fn((...args) => ({ type: "and", args })),
|
||||||
|
desc: vi.fn((col) => ({ type: "desc", col })),
|
||||||
|
lt: vi.fn((a, b) => ({ type: "lt", a, b })),
|
||||||
|
sql: vi.fn(() => ({ __type: "sql" })),
|
||||||
|
isNull: vi.fn((col) => ({ type: "isNull", col })),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("../services/messaging/outbound.js", () => ({
|
||||||
|
sendMessage: mockSendMessage,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── App setup ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const { conversationsRouter } = await import("../routes/conversations.js");
|
||||||
|
|
||||||
|
const app = new Hono();
|
||||||
|
app.use("*", async (c, next) => {
|
||||||
|
// @ts-expect-error — test-only context injection
|
||||||
|
c.set("staff", STAFF_ROW);
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
app.route("/conversations", conversationsRouter);
|
||||||
|
|
||||||
|
function jsonRequest(method: string, path: string, body?: unknown) {
|
||||||
|
return app.request(path, {
|
||||||
|
method,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => resetAll());
|
||||||
|
|
||||||
|
// ─── GET /conversations ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("GET /api/conversations", () => {
|
||||||
|
it("returns conversations sorted by recency with unread count", async () => {
|
||||||
|
selectRows = [
|
||||||
|
{ ...CONV_1, clientName: "Alice", clientPhone: "+15551111111", channel: "sms" },
|
||||||
|
];
|
||||||
|
selectRows2 = [{ count: "1" }];
|
||||||
|
const res = await app.request("/conversations");
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.items).toHaveLength(1);
|
||||||
|
expect(body.items[0]!.id).toBe("conv-uuid-1");
|
||||||
|
expect(body.items[0]!.clientName).toBe("Alice");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports cursor-based pagination", async () => {
|
||||||
|
selectRows = [];
|
||||||
|
const res = await app.request("/conversations?cursor=conv-uuid-1&limit=1");
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("enforces max limit of 50", async () => {
|
||||||
|
selectRows = [];
|
||||||
|
const res = await app.request("/conversations?limit=200");
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── GET /conversations/:id/messages ─────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("GET /api/conversations/:id/messages", () => {
|
||||||
|
it("returns paginated messages and marks conversation as read", async () => {
|
||||||
|
selectRows = [{ ...MSG_INBOUND_1 }, { ...MSG_OUTBOUND_1 }];
|
||||||
|
const res = await app.request("/conversations/conv-uuid-1/messages");
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.items).toHaveLength(2);
|
||||||
|
expect(body.items[0]!.id).toBe("msg-uuid-1");
|
||||||
|
expect(updatedValues.some((u) => u.staffReadAt !== undefined)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 404 when conversation belongs to different business", async () => {
|
||||||
|
selectRows = [];
|
||||||
|
const res = await app.request("/conversations/conv-uuid-other/messages");
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 when not authenticated", async () => {
|
||||||
|
const appNoAuth = new Hono();
|
||||||
|
appNoAuth.route("/conversations", conversationsRouter);
|
||||||
|
const res = await appNoAuth.request("/conversations/conv-uuid-1/messages");
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── POST /conversations/:id/messages ─────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("POST /api/conversations/:id/messages", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
resetMock();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
selectRows = [{ ...CONV_1, clientName: "Alice", clientPhone: "+15551111111", channel: "sms" }];
|
||||||
|
selectRows2 = [];
|
||||||
|
selectRows3 = [{ id: "msg-uuid-new", conversationId: "conv-uuid-1", direction: "outbound" as const, body: "Hello Alice!", status: "queued" as const, sentByStaffId: "staff-uuid-1", createdAt: new Date(), deliveredAt: null }];
|
||||||
|
updatedValues = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends via outbound service and returns 201", async () => {
|
||||||
|
mockSendMessage.mockResolvedValueOnce({
|
||||||
|
messageId: "msg-uuid-new",
|
||||||
|
providerMessageId: "provider-msg-1",
|
||||||
|
status: "queued",
|
||||||
|
suppressed: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await jsonRequest("POST", "/conversations/conv-uuid-1/messages", {
|
||||||
|
body: "Hello Alice!",
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(201);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.id).toBe("msg-uuid-new");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 409 when client opted out", async () => {
|
||||||
|
mockSendMessage.mockResolvedValueOnce({ suppressed: true });
|
||||||
|
|
||||||
|
const res = await jsonRequest("POST", "/conversations/conv-uuid-1/messages", {
|
||||||
|
body: "Hello",
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.error).toMatch(/opted out/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 404 for cross-tenant conversation", async () => {
|
||||||
|
selectRows = [];
|
||||||
|
const res = await jsonRequest("POST", "/conversations/conv-uuid-other/messages", {
|
||||||
|
body: "Hello",
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects empty body", async () => {
|
||||||
|
const res = await jsonRequest("POST", "/conversations/conv-uuid-1/messages", {
|
||||||
|
body: "",
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects body over 1600 chars", async () => {
|
||||||
|
const res = await jsonRequest("POST", "/conversations/conv-uuid-1/messages", {
|
||||||
|
body: "a".repeat(1601),
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -72,6 +72,11 @@ vi.mock("@groombook/db", () => {
|
|||||||
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const impersonationAuditLogs = new Proxy(
|
||||||
|
{ _name: "impersonationAuditLogs" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "impersonationAuditLogs" : { table: "impersonationAuditLogs", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getDb: () => ({
|
getDb: () => ({
|
||||||
select: () => ({
|
select: () => ({
|
||||||
@@ -99,9 +104,15 @@ vi.mock("@groombook/db", () => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
insert: () => ({
|
||||||
|
values: () => ({
|
||||||
|
returning: () => [],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
impersonationSessions,
|
impersonationSessions,
|
||||||
appointments,
|
appointments,
|
||||||
|
impersonationAuditLogs,
|
||||||
eq: vi.fn(),
|
eq: vi.fn(),
|
||||||
and: vi.fn(),
|
and: vi.fn(),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -40,13 +40,17 @@ const EXPIRED_SESSION = {
|
|||||||
let selectRows: Record<string, unknown>[] = [];
|
let selectRows: Record<string, unknown>[] = [];
|
||||||
let selectSessionRow: Record<string, unknown> | null = null;
|
let selectSessionRow: Record<string, unknown> | null = null;
|
||||||
let insertedValues: Record<string, unknown>[] = [];
|
let insertedValues: Record<string, unknown>[] = [];
|
||||||
|
let insertedAuditValues: Record<string, unknown>[] = [];
|
||||||
let updatedValues: Record<string, unknown>[] = [];
|
let updatedValues: Record<string, unknown>[] = [];
|
||||||
|
let lastInsertTable: string | null = null;
|
||||||
|
|
||||||
function resetMock() {
|
function resetMock() {
|
||||||
selectRows = [];
|
selectRows = [];
|
||||||
selectSessionRow = null;
|
selectSessionRow = null;
|
||||||
insertedValues = [];
|
insertedValues = [];
|
||||||
|
insertedAuditValues = [];
|
||||||
updatedValues = [];
|
updatedValues = [];
|
||||||
|
lastInsertTable = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
vi.mock("@groombook/db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
@@ -89,6 +93,11 @@ vi.mock("@groombook/db", () => {
|
|||||||
{ get: (t, p) => (p === "_name" ? "services" : { table: "services", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "services" : { table: "services", column: p }) }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const impersonationAuditLogs = new Proxy(
|
||||||
|
{ _name: "impersonationAuditLogs" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "impersonationAuditLogs" : { table: "impersonationAuditLogs", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
const appointments = new Proxy(
|
const appointments = new Proxy(
|
||||||
{ _name: "appointments" },
|
{ _name: "appointments" },
|
||||||
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
||||||
@@ -107,9 +116,13 @@ vi.mock("@groombook/db", () => {
|
|||||||
return makeChainable([]);
|
return makeChainable([]);
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
insert: () => ({
|
insert: (table: { _name: string }) => ({
|
||||||
values: (vals: Record<string, unknown>) => {
|
values: (vals: Record<string, unknown>) => {
|
||||||
insertedValues.push(vals);
|
if (table._name === "impersonationAuditLogs") {
|
||||||
|
insertedAuditValues.push(vals);
|
||||||
|
} else {
|
||||||
|
insertedValues.push(vals);
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
returning: () => [{ ...WAITLIST_ENTRY, ...vals, id: "waitlist-uuid-new" }],
|
returning: () => [{ ...WAITLIST_ENTRY, ...vals, id: "waitlist-uuid-new" }],
|
||||||
};
|
};
|
||||||
@@ -143,6 +156,7 @@ vi.mock("@groombook/db", () => {
|
|||||||
pets,
|
pets,
|
||||||
services,
|
services,
|
||||||
appointments,
|
appointments,
|
||||||
|
impersonationAuditLogs,
|
||||||
eq: vi.fn(),
|
eq: vi.fn(),
|
||||||
and: vi.fn(),
|
and: vi.fn(),
|
||||||
lt: vi.fn(),
|
lt: vi.fn(),
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { groomingLogsRouter } from "./routes/groomingLogs.js";
|
|||||||
import { impersonationRouter } from "./routes/impersonation.js";
|
import { impersonationRouter } from "./routes/impersonation.js";
|
||||||
import { settingsRouter } from "./routes/settings.js";
|
import { settingsRouter } from "./routes/settings.js";
|
||||||
import { authProviderRouter } from "./routes/authProvider.js";
|
import { authProviderRouter } from "./routes/authProvider.js";
|
||||||
|
import { conversationsRouter } from "./routes/conversations.js";
|
||||||
import { searchRouter } from "./routes/search.js";
|
import { searchRouter } from "./routes/search.js";
|
||||||
import { getObject } from "./lib/s3.js";
|
import { getObject } from "./lib/s3.js";
|
||||||
import { calendarRouter } from "./routes/calendar.js";
|
import { calendarRouter } from "./routes/calendar.js";
|
||||||
@@ -273,6 +274,7 @@ api.route("/admin/settings", settingsRouter);
|
|||||||
api.route("/admin/auth-provider", authProviderRouter);
|
api.route("/admin/auth-provider", authProviderRouter);
|
||||||
api.route("/admin/seed", adminSeedRouter);
|
api.route("/admin/seed", adminSeedRouter);
|
||||||
api.route("/search", searchRouter);
|
api.route("/search", searchRouter);
|
||||||
|
api.route("/conversations", conversationsRouter);
|
||||||
|
|
||||||
const port = Number(process.env.PORT ?? 3000);
|
const port = Number(process.env.PORT ?? 3000);
|
||||||
await initAuth();
|
await initAuth();
|
||||||
|
|||||||
@@ -97,6 +97,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
window: 10,
|
window: 10,
|
||||||
storage: "memory",
|
storage: "memory",
|
||||||
customRules: {
|
customRules: {
|
||||||
|
"/sign-in/social": { max: 10, window: 60 },
|
||||||
|
"/sign-in/email": { max: 10, window: 60 },
|
||||||
|
"/sign-up/email": { max: 5, window: 60 },
|
||||||
"/get-session": false,
|
"/get-session": false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -247,6 +250,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
window: 10,
|
window: 10,
|
||||||
storage: "memory",
|
storage: "memory",
|
||||||
customRules: {
|
customRules: {
|
||||||
|
"/sign-in/social": { max: 10, window: 60 },
|
||||||
|
"/sign-in/email": { max: 10, window: 60 },
|
||||||
|
"/sign-up/email": { max: 5, window: 60 },
|
||||||
"/get-session": false,
|
"/get-session": false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ if (process.env.AUTH_DISABLED === "true") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
||||||
if (c.req.path.startsWith("/api/auth/")) {
|
const path = c.req.path;
|
||||||
|
if (path.startsWith("/api/auth/") || path.startsWith("/api/webhooks/")) {
|
||||||
await next();
|
await next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
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 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),
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/conversations — List conversations
|
||||||
|
conversationsRouter.get("/", async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const staffRow = c.get("staff");
|
||||||
|
if (!staffRow) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
|
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
|
||||||
|
.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(eq(conversations.businessId, settings.id))
|
||||||
|
.orderBy(desc(conversations.lastMessageAt))
|
||||||
|
.limit(limit + 1);
|
||||||
|
|
||||||
|
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(
|
||||||
|
rows.map(async (row) => {
|
||||||
|
const [unreadRow] = await db
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(messages)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(messages.conversationId, row.id),
|
||||||
|
eq(messages.direction, "inbound"),
|
||||||
|
sql`${messages.createdAt} > COALESCE(${row.staffReadAt}, '1970-01-01'::timestamp)`
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
const [lastMsg] = await db
|
||||||
|
.select({
|
||||||
|
body: messages.body,
|
||||||
|
direction: messages.direction,
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const lastRow = rows[rows.length - 1];
|
||||||
|
const nextCursor = hasMore && lastRow ? lastRow.id : null;
|
||||||
|
return c.json({ items, nextCursor });
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/conversations/:id/messages — List 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 conversationId = c.req.param("id");
|
||||||
|
const cursor = c.req.query("cursor") || undefined;
|
||||||
|
const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
|
||||||
|
|
||||||
|
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 })
|
||||||
|
.from(conversations)
|
||||||
|
.where(
|
||||||
|
and(eq(conversations.id, conversationId), eq(conversations.businessId, settings.id))
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
if (!conv) return c.json({ error: "Not found" }, 404);
|
||||||
|
|
||||||
|
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
|
||||||
|
.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,
|
||||||
|
})
|
||||||
|
.from(messages)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(messages.conversationId, conversationId),
|
||||||
|
lt(messages.createdAt, cursorRow.createdAt)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.orderBy(desc(messages.createdAt))
|
||||||
|
.limit(limit + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await query;
|
||||||
|
const hasMore = rows.length > limit;
|
||||||
|
if (hasMore) rows.pop();
|
||||||
|
|
||||||
|
const lastRow = rows[rows.length - 1];
|
||||||
|
const nextCursor = hasMore && lastRow ? lastRow.id : null;
|
||||||
|
return c.json({ items: rows, nextCursor });
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/conversations/:id/messages — Send a message
|
||||||
|
conversationsRouter.post(
|
||||||
|
"/:id/messages",
|
||||||
|
zValidator("json", sendMessageSchema),
|
||||||
|
async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
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 })
|
||||||
|
.from(conversations)
|
||||||
|
.where(
|
||||||
|
and(eq(conversations.id, conversationId), eq(conversations.businessId, settings.id))
|
||||||
|
)
|
||||||
|
.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 (result.suppressed) {
|
||||||
|
return c.json({ error: "Client has opted out of SMS" }, 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
.from(messages)
|
||||||
|
.where(eq(messages.id, result.messageId))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
return c.json(msg, 201);
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -14,7 +14,8 @@ import {
|
|||||||
clients,
|
clients,
|
||||||
sql,
|
sql,
|
||||||
} from "@groombook/db";
|
} from "@groombook/db";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv, StaffRole } from "../middleware/rbac.js";
|
||||||
|
import { requireRole } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const invoicesRouter = new Hono<AppEnv>();
|
export const invoicesRouter = new Hono<AppEnv>();
|
||||||
|
|
||||||
@@ -460,6 +461,9 @@ invoicesRouter.post(
|
|||||||
if (invoice.status !== "paid") {
|
if (invoice.status !== "paid") {
|
||||||
return c.json({ error: "Refund only allowed on paid invoices" }, 422);
|
return c.json({ error: "Refund only allowed on paid invoices" }, 422);
|
||||||
}
|
}
|
||||||
|
if (!invoice.stripePaymentIntentId) {
|
||||||
|
return c.json({ error: "Invoice has no Stripe payment intent" }, 422);
|
||||||
|
}
|
||||||
|
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
if (body.idempotencyKey) {
|
if (body.idempotencyKey) {
|
||||||
@@ -472,16 +476,9 @@ invoicesRouter.post(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let refundId: string;
|
const result = await processRefund(id, body.amountCents);
|
||||||
|
if (!result) return c.json({ error: "Refund failed" }, 500);
|
||||||
if (invoice.stripePaymentIntentId) {
|
const refundId = result.refundId;
|
||||||
const result = await processRefund(id, body.amountCents);
|
|
||||||
if (!result) return c.json({ error: "Refund failed" }, 500);
|
|
||||||
refundId = result.refundId;
|
|
||||||
} else {
|
|
||||||
// Manual refund — no Stripe call needed
|
|
||||||
refundId = `manual_${id}_${Date.now()}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
await tx.insert(refunds).values({
|
await tx.insert(refunds).values({
|
||||||
invoiceId: id,
|
invoiceId: id,
|
||||||
@@ -496,7 +493,7 @@ invoicesRouter.post(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Payment stats for admin dashboard
|
// Payment stats for admin dashboard
|
||||||
invoicesRouter.get("/stats/summary", async (c) => {
|
invoicesRouter.get("/stats/summary", requireRole("manager" as StaffRole), async (c) => {
|
||||||
try {
|
try {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { createHmac } from "crypto";
|
import { validateTelnyxSignature } from "../../services/sms.js";
|
||||||
import {
|
import {
|
||||||
handleMessageReceived,
|
handleMessageReceived,
|
||||||
handleMessageFinalized,
|
handleMessageFinalized,
|
||||||
@@ -8,32 +8,6 @@ import {
|
|||||||
|
|
||||||
export const telnyxWebhooksRouter = new Hono();
|
export const telnyxWebhooksRouter = new Hono();
|
||||||
|
|
||||||
function validateTelnyxSignature(rawBody: string, signature: string | null): boolean {
|
|
||||||
if (!signature) return false;
|
|
||||||
const secret = process.env.TELNYX_WEBHOOK_SECRET;
|
|
||||||
if (!secret) return false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const hmac = createHmac("sha256", secret);
|
|
||||||
const expected = `sha256=${hmac.update(rawBody).digest("hex")}`;
|
|
||||||
|
|
||||||
const sigBuf = Buffer.from(signature);
|
|
||||||
const expBuf = Buffer.from(expected);
|
|
||||||
|
|
||||||
if (sigBuf.length !== expBuf.length) return false;
|
|
||||||
|
|
||||||
let diff = 0;
|
|
||||||
for (let i = 0; i < sigBuf.length; i++) {
|
|
||||||
const sigByte = sigBuf[i] ?? 0;
|
|
||||||
const expByte = expBuf[i] ?? 0;
|
|
||||||
diff |= sigByte ^ expByte;
|
|
||||||
}
|
|
||||||
return diff === 0;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
telnyxWebhooksRouter.post("/messaging", async (c) => {
|
telnyxWebhooksRouter.post("/messaging", async (c) => {
|
||||||
const signature = c.req.header("telnyx-signature");
|
const signature = c.req.header("telnyx-signature");
|
||||||
|
|
||||||
@@ -44,7 +18,7 @@ telnyxWebhooksRouter.post("/messaging", async (c) => {
|
|||||||
return c.json({ error: "Could not read body" }, 400);
|
return c.json({ error: "Could not read body" }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!validateTelnyxSignature(rawBody, signature ?? null)) {
|
if (!validateTelnyxSignature(rawBody, signature)) {
|
||||||
return c.json({ error: "Invalid signature" }, 401);
|
return c.json({ error: "Invalid signature" }, 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ vi.mock("@groombook/db", () => ({
|
|||||||
conversations: { id: "", businessId: "", clientId: "", externalNumber: "", businessNumber: "", channel: "", lastMessageAt: null, status: "", createdAt: null, updatedAt: null },
|
conversations: { id: "", businessId: "", clientId: "", externalNumber: "", businessNumber: "", channel: "", lastMessageAt: null, status: "", createdAt: null, updatedAt: null },
|
||||||
messages: { id: "", conversationId: "", direction: "", body: "", status: "", providerMessageId: "", sentByStaffId: null, createdAt: null, deliveredAt: null, readByClientAt: null },
|
messages: { id: "", conversationId: "", direction: "", body: "", status: "", providerMessageId: "", sentByStaffId: null, createdAt: null, deliveredAt: null, readByClientAt: null },
|
||||||
businessSettings: { id: "", messagingPhoneNumber: "" },
|
businessSettings: { id: "", messagingPhoneNumber: "" },
|
||||||
|
clients: { id: "", name: "", email: "", phone: "", status: "" },
|
||||||
eq: vi.fn(),
|
eq: vi.fn(),
|
||||||
and: vi.fn(),
|
and: vi.fn(),
|
||||||
sql: vi.fn(),
|
sql: vi.fn(),
|
||||||
@@ -52,10 +53,14 @@ const makePayload = (
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("signature validation via route", () => {
|
describe("signature validation via route", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
it("returns 401 when telnyx-signature header is missing", async () => {
|
it("returns 401 when telnyx-signature header is missing", async () => {
|
||||||
const { telnyxWebhooksRouter } = await import("../../../routes/webhooks/telnyx.js");
|
const { telnyxWebhooksRouter } = await import("../../../routes/webhooks/telnyx.js");
|
||||||
const payload = JSON.stringify(makePayload("message.received", "msg-123", "+1555111", "+1555222"));
|
const payload = JSON.stringify(makePayload("message.received", "msg-123", "+1555111", "+1555222"));
|
||||||
const req = new Request("http://localhost/api/webhooks/telnyx/messaging", {
|
const req = new Request("http://localhost/messaging", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: payload,
|
body: payload,
|
||||||
@@ -68,7 +73,7 @@ describe("signature validation via route", () => {
|
|||||||
process.env.TELNYX_WEBHOOK_SECRET = "test-secret";
|
process.env.TELNYX_WEBHOOK_SECRET = "test-secret";
|
||||||
const { telnyxWebhooksRouter } = await import("../../../routes/webhooks/telnyx.js");
|
const { telnyxWebhooksRouter } = await import("../../../routes/webhooks/telnyx.js");
|
||||||
const payload = JSON.stringify(makePayload("message.received", "msg-123", "+1555111", "+1555222"));
|
const payload = JSON.stringify(makePayload("message.received", "msg-123", "+1555111", "+1555222"));
|
||||||
const req = new Request("http://localhost/api/webhooks/telnyx/messaging", {
|
const req = new Request("http://localhost/messaging", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -123,6 +128,33 @@ describe("findOrCreateConversation", () => {
|
|||||||
const result = await findOrCreateConversation("biz-1", "+1555111", "+1555222");
|
const result = await findOrCreateConversation("biz-1", "+1555111", "+1555222");
|
||||||
expect(result.id).toBe("conv-2");
|
expect(result.id).toBe("conv-2");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("creates placeholder client for unknown phone then creates conversation", async () => {
|
||||||
|
mockDb.select
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
from: vi.fn().mockReturnValue({
|
||||||
|
where: vi.fn().mockReturnValue({
|
||||||
|
limit: vi.fn().mockReturnValue([]),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
from: vi.fn().mockReturnValue({
|
||||||
|
where: vi.fn().mockReturnValue({
|
||||||
|
limit: vi.fn().mockReturnValue([]),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
mockDb.insert.mockReturnValue({
|
||||||
|
values: vi.fn().mockReturnValue({
|
||||||
|
returning: vi.fn().mockReturnValue([{ id: "conv-3", clientId: "client-3" }]),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await findOrCreateConversation("biz-1", "+1555111", "+1555222");
|
||||||
|
expect(result.id).toBe("conv-3");
|
||||||
|
expect(result.clientId).toBe("client-3");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("upsertMessage", () => {
|
describe("upsertMessage", () => {
|
||||||
@@ -174,17 +206,16 @@ describe("handleMessageReceived", () => {
|
|||||||
mockDb.insert.mockReset();
|
mockDb.insert.mockReset();
|
||||||
mockDb.update.mockReset();
|
mockDb.update.mockReset();
|
||||||
mockDb.returning.mockReset();
|
mockDb.returning.mockReset();
|
||||||
});
|
mockDb.select.mockImplementation(() => ({
|
||||||
|
|
||||||
it("returns 404 when no business owns the to number", async () => {
|
|
||||||
mockDb.select.mockReturnValue({
|
|
||||||
from: vi.fn().mockReturnValue({
|
from: vi.fn().mockReturnValue({
|
||||||
where: vi.fn().mockReturnValue({
|
where: vi.fn().mockReturnValue({
|
||||||
limit: vi.fn().mockReturnValue([]),
|
limit: vi.fn().mockReturnValue([]),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
});
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 404 when no business owns the to number", async () => {
|
||||||
const payload = makePayload("message.received", "msg-123", "+1555111", "+1555000");
|
const payload = makePayload("message.received", "msg-123", "+1555111", "+1555000");
|
||||||
await expect(handleMessageReceived(payload)).rejects.toThrow("No business owns messaging number");
|
await expect(handleMessageReceived(payload)).rejects.toThrow("No business owns messaging number");
|
||||||
});
|
});
|
||||||
@@ -194,35 +225,33 @@ describe("handleMessageReceived", () => {
|
|||||||
.mockReturnValueOnce({
|
.mockReturnValueOnce({
|
||||||
from: vi.fn().mockReturnValue({
|
from: vi.fn().mockReturnValue({
|
||||||
where: vi.fn().mockReturnValue({
|
where: vi.fn().mockReturnValue({
|
||||||
limit: vi.fn().mockReturnValue([]),
|
limit: vi.fn().mockReturnValue([{ id: "biz-1" }]),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.mockReturnValueOnce({
|
.mockReturnValueOnce({
|
||||||
from: vi.fn().mockReturnValue({
|
from: vi.fn().mockReturnValue({
|
||||||
where: vi.fn().mockReturnValue({
|
where: vi.fn().mockReturnValue({
|
||||||
limit: vi.fn().mockReturnValue([{ id: "biz-1" }]),
|
limit: vi.fn().mockReturnValue([]),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
mockDb.insert
|
||||||
mockDb.insert.mockReturnValue({
|
.mockReturnValueOnce({
|
||||||
values: vi.fn().mockReturnValue({
|
values: vi.fn().mockReturnValue({
|
||||||
returning: vi.fn().mockReturnValue([{ id: "conv-new", clientId: "client-1" }]),
|
returning: vi.fn().mockReturnValue([{ id: "client-new" }]),
|
||||||
}),
|
}),
|
||||||
});
|
})
|
||||||
mockDb.update.mockReturnValue({
|
.mockReturnValueOnce({
|
||||||
|
values: vi.fn().mockReturnValue({
|
||||||
|
returning: vi.fn().mockReturnValue([{ id: "conv-new", clientId: "client-new" }]),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
mockDb.update.mockReturnValueOnce({
|
||||||
set: vi.fn().mockReturnValue({
|
set: vi.fn().mockReturnValue({
|
||||||
where: vi.fn().mockReturnValue({}),
|
where: vi.fn().mockReturnValue({}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
mockDb.select.mockReturnValueOnce({
|
|
||||||
from: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue({
|
|
||||||
limit: vi.fn().mockReturnValue([]),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
mockDb.insert.mockReturnValueOnce({
|
mockDb.insert.mockReturnValueOnce({
|
||||||
values: vi.fn().mockReturnValue({
|
values: vi.fn().mockReturnValue({
|
||||||
returning: vi.fn().mockReturnValue([{ id: "msg-new" }]),
|
returning: vi.fn().mockReturnValue([{ id: "msg-new" }]),
|
||||||
@@ -238,6 +267,13 @@ describe("handleMessageReceived", () => {
|
|||||||
describe("handleMessageFinalized", () => {
|
describe("handleMessageFinalized", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
|
mockDb.select.mockReset();
|
||||||
|
mockDb.from.mockReset();
|
||||||
|
mockDb.where.mockReset();
|
||||||
|
mockDb.limit.mockReset();
|
||||||
|
mockDb.insert.mockReset();
|
||||||
|
mockDb.update.mockReset();
|
||||||
|
mockDb.returning.mockReset();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when message not found", async () => {
|
it("returns null when message not found", async () => {
|
||||||
@@ -264,7 +300,9 @@ describe("handleMessageFinalized", () => {
|
|||||||
});
|
});
|
||||||
mockDb.update.mockReturnValue({
|
mockDb.update.mockReturnValue({
|
||||||
set: vi.fn().mockReturnValue({
|
set: vi.fn().mockReturnValue({
|
||||||
where: vi.fn().mockReturnValue({}),
|
where: vi.fn().mockReturnValue({
|
||||||
|
returning: vi.fn().mockReturnValue([{ id: "msg-1" }]),
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ vi.mock("uuid", () => ({
|
|||||||
v4: () => mockUuidv4(),
|
v4: () => mockUuidv4(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const { sendMessage, MissingTenantPhoneNumberError } = await import("../outbound.ts");
|
const { sendMessage, MissingTenantPhoneNumberError } = await import("../outbound.js");
|
||||||
|
|
||||||
describe("sendMessage", () => {
|
describe("sendMessage", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getDb, conversations, messages, businessSettings, eq, and, sql } from "@groombook/db";
|
import { getDb, conversations, messages, businessSettings, clients, eq, and } from "@groombook/db";
|
||||||
import { v4 as uuidv4 } from "uuid";
|
import { v4 as uuidv4 } from "uuid";
|
||||||
|
|
||||||
export interface TelnyxMessageReceivedPayload {
|
export interface TelnyxMessageReceivedPayload {
|
||||||
@@ -42,18 +42,28 @@ export async function findOrCreateConversation(
|
|||||||
return { id: existing.id, clientId: existing.clientId };
|
return { id: existing.id, clientId: existing.clientId };
|
||||||
}
|
}
|
||||||
|
|
||||||
const [business] = await db
|
const [existingClient] = await db
|
||||||
.select({ primaryClientId: sql<string>`${businessSettings.id}` })
|
.select({ id: clients.id })
|
||||||
.from(businessSettings)
|
.from(clients)
|
||||||
.where(eq(businessSettings.id, businessId))
|
.where(eq(clients.phone, clientPhone))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
const clientId = business?.primaryClientId ?? uuidv4();
|
const clientId = existingClient?.id ?? uuidv4();
|
||||||
|
|
||||||
|
if (!existingClient) {
|
||||||
|
await db.insert(clients).values({
|
||||||
|
id: clientId,
|
||||||
|
name: clientPhone,
|
||||||
|
email: `sms-${uuidv4()}@placeholder.local`,
|
||||||
|
phone: clientPhone,
|
||||||
|
status: "active",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const [created] = await db
|
const [created] = await db
|
||||||
.insert(conversations)
|
.insert(conversations)
|
||||||
.values({
|
.values({
|
||||||
id: uuidv4(),
|
id: crypto.randomUUID(),
|
||||||
businessId,
|
businessId,
|
||||||
clientId,
|
clientId,
|
||||||
channel: "sms",
|
channel: "sms",
|
||||||
@@ -89,22 +99,33 @@ export async function upsertMessage(
|
|||||||
return { id: existing.id, isNew: false };
|
return { id: existing.id, isNew: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
const [inserted] = await db
|
try {
|
||||||
.insert(messages)
|
const [inserted] = await db
|
||||||
.values({
|
.insert(messages)
|
||||||
id: uuidv4(),
|
.values({
|
||||||
conversationId,
|
id: crypto.randomUUID(),
|
||||||
direction,
|
conversationId,
|
||||||
body,
|
direction,
|
||||||
status,
|
body,
|
||||||
providerMessageId,
|
status,
|
||||||
sentByStaffId: sentByStaffId ?? null,
|
providerMessageId,
|
||||||
})
|
sentByStaffId: sentByStaffId ?? null,
|
||||||
.returning({ id: messages.id });
|
})
|
||||||
|
.returning({ id: messages.id });
|
||||||
|
|
||||||
if (!inserted) throw new Error("Failed to insert message");
|
if (!inserted) throw new Error("Failed to insert message");
|
||||||
|
return { id: inserted.id, isNew: true };
|
||||||
return { id: inserted.id, isNew: true };
|
} catch (err) {
|
||||||
|
if (err instanceof Error && err.message.includes("unique")) {
|
||||||
|
const [existing] = await db
|
||||||
|
.select({ id: messages.id })
|
||||||
|
.from(messages)
|
||||||
|
.where(eq(messages.providerMessageId, providerMessageId))
|
||||||
|
.limit(1);
|
||||||
|
if (existing) return { id: existing.id, isNew: false };
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveBusinessIdByMessagingNumber(toNumber: string): Promise<string | null> {
|
export async function resolveBusinessIdByMessagingNumber(toNumber: string): Promise<string | null> {
|
||||||
@@ -165,16 +186,13 @@ export async function handleMessageFinalized(payload: TelnyxMessageReceivedPaylo
|
|||||||
|
|
||||||
let newStatus = existing.status;
|
let newStatus = existing.status;
|
||||||
if (payload.data.event_type === "message.finalized") {
|
if (payload.data.event_type === "message.finalized") {
|
||||||
const deliveryReceipt = message as { direction?: string; to?: Array<{ phone: string }> };
|
newStatus = "delivered";
|
||||||
if (deliveryReceipt.direction === "inbound") {
|
|
||||||
newStatus = "delivered";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newStatus !== existing.status) {
|
if (newStatus !== existing.status) {
|
||||||
await db
|
await db
|
||||||
.update(messages)
|
.update(messages)
|
||||||
.set({ status: newStatus, deliveredAt: new Date(), updatedAt: new Date() })
|
.set({ status: newStatus, deliveredAt: new Date() })
|
||||||
.where(eq(messages.id, existing.id));
|
.where(eq(messages.id, existing.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -127,13 +127,12 @@ export async function sendMessage(opts: SendMessageOptions): Promise<SendMessage
|
|||||||
.set({
|
.set({
|
||||||
status: "sent",
|
status: "sent",
|
||||||
providerMessageId: result.messageId,
|
providerMessageId: result.messageId,
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
})
|
||||||
.where(eq(messages.id, queuedMessage.id));
|
.where(eq(messages.id, queuedMessage.id));
|
||||||
|
|
||||||
await db
|
await db
|
||||||
.update(conversations)
|
.update(conversations)
|
||||||
.set({ lastMessageAt: new Date(), updatedAt: new Date() })
|
.set({ lastMessageAt: new Date() })
|
||||||
.where(eq(conversations.id, conversationId));
|
.where(eq(conversations.id, conversationId));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -152,7 +151,6 @@ export async function sendMessage(opts: SendMessageOptions): Promise<SendMessage
|
|||||||
status: "failed",
|
status: "failed",
|
||||||
errorCode,
|
errorCode,
|
||||||
errorMessage,
|
errorMessage,
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
})
|
||||||
.where(eq(messages.id, queuedMessage.id));
|
.where(eq(messages.id, queuedMessage.id));
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,35 @@ function isE164(phone: string): boolean {
|
|||||||
return /^\+[1-9]\d{7,14}$/.test(phone);
|
return /^\+[1-9]\d{7,14}$/.test(phone);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function validateTelnyxSignature(
|
||||||
|
rawBody: string,
|
||||||
|
signature: string | undefined | null
|
||||||
|
): boolean {
|
||||||
|
if (!signature) return false;
|
||||||
|
const secret = process.env.TELNYX_WEBHOOK_SECRET;
|
||||||
|
if (!secret) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const hmac = createHmac("sha256", secret);
|
||||||
|
const expected = `sha256=${hmac.update(rawBody).digest("hex")}`;
|
||||||
|
|
||||||
|
const sigBuf = Buffer.from(signature);
|
||||||
|
const expBuf = Buffer.from(expected);
|
||||||
|
|
||||||
|
if (sigBuf.length !== expBuf.length) return false;
|
||||||
|
|
||||||
|
let diff = 0;
|
||||||
|
for (let i = 0; i < sigBuf.length; i++) {
|
||||||
|
const sigByte = sigBuf[i] ?? 0;
|
||||||
|
const expByte = expBuf[i] ?? 0;
|
||||||
|
diff |= sigByte ^ expByte;
|
||||||
|
}
|
||||||
|
return diff === 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function sendSms(
|
export async function sendSms(
|
||||||
to: string,
|
to: string,
|
||||||
body: string,
|
body: string,
|
||||||
@@ -74,33 +103,7 @@ export class TelnyxProvider implements SmsProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
validateWebhookSignature(req: Request): boolean {
|
validateWebhookSignature(req: Request): boolean {
|
||||||
const secret = process.env.TELNYX_WEBHOOK_SECRET;
|
return validateTelnyxSignature(JSON.stringify(req.body), req.headers.get("telnyx-signature"));
|
||||||
if (!secret) return false;
|
|
||||||
|
|
||||||
const signature = req.headers.get("telnyx-signature");
|
|
||||||
if (!signature) return false;
|
|
||||||
|
|
||||||
const payload = JSON.stringify(req.body);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const hmac = createHmac("sha256", secret);
|
|
||||||
const expected = `sha256=${hmac.update(payload).digest("hex")}`;
|
|
||||||
|
|
||||||
const sigBuf = Buffer.from(signature);
|
|
||||||
const expBuf = Buffer.from(expected);
|
|
||||||
|
|
||||||
if (sigBuf.length !== expBuf.length) return false;
|
|
||||||
|
|
||||||
let diff = 0;
|
|
||||||
for (let i = 0; i < sigBuf.length; i++) {
|
|
||||||
const sigByte = sigBuf[i] ?? 0;
|
|
||||||
const expByte = expBuf[i] ?? 0;
|
|
||||||
diff |= sigByte ^ expByte;
|
|
||||||
}
|
|
||||||
return diff === 0;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -72,9 +72,15 @@ test.describe("Portal Data Integrity", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("billing section renders without JS errors", async ({ page }) => {
|
test("billing section renders without JS errors", async ({ page }) => {
|
||||||
// Mock billing endpoint
|
// Mock portal billing endpoints
|
||||||
await page.route("**/api/billing**", (route) =>
|
await page.route("**/api/portal/config**", (route) =>
|
||||||
route.fulfill({ json: { invoices: [], balanceCents: 0 } })
|
route.fulfill({ json: { stripePublishableKey: "" } })
|
||||||
|
);
|
||||||
|
await page.route("**/api/portal/invoices**", (route) =>
|
||||||
|
route.fulfill({ json: [] })
|
||||||
|
);
|
||||||
|
await page.route("**/api/portal/payment-methods**", (route) =>
|
||||||
|
route.fulfill({ json: [] })
|
||||||
);
|
);
|
||||||
|
|
||||||
const consoleErrors: string[] = [];
|
const consoleErrors: string[] = [];
|
||||||
|
|||||||
@@ -82,3 +82,13 @@ input:focus, select:focus, textarea:focus {
|
|||||||
::-webkit-scrollbar-thumb:hover {
|
::-webkit-scrollbar-thumb:hover {
|
||||||
background: #94a3b8;
|
background: #94a3b8;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ─── Scrollbar hide utility ─── */
|
||||||
|
.scrollbar-hide {
|
||||||
|
-ms-overflow-style: none;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-hide::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ function BillingPaymentsInner({ sessionId, readOnly }: BillingPaymentsProps) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex gap-2 flex-wrap overflow-x-auto">
|
<div className="flex gap-2 overflow-x-auto scrollbar-hide">
|
||||||
{([
|
{([
|
||||||
{ id: "invoices" as const, label: "Invoices", icon: DollarSign },
|
{ id: "invoices" as const, label: "Invoices", icon: DollarSign },
|
||||||
{ id: "payment" as const, label: "Payment Methods", icon: CreditCard },
|
{ id: "payment" as const, label: "Payment Methods", icon: CreditCard },
|
||||||
|
|||||||
@@ -182,7 +182,7 @@ export function PetProfiles({ sessionId, readOnly }: Props) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div className="flex gap-1 bg-white rounded-xl border border-stone-200 p-1 overflow-x-auto">
|
<div className="flex gap-1 bg-white rounded-xl border border-stone-200 p-1 overflow-x-auto scrollbar-hide">
|
||||||
{([
|
{([
|
||||||
{ id: "info", label: "Basic Info", icon: PawPrint },
|
{ id: "info", label: "Basic Info", icon: PawPrint },
|
||||||
{ id: "medical", label: "Medical", icon: Heart },
|
{ id: "medical", label: "Medical", icon: Heart },
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
# 10DLC Pilot Tenant Registration Runbook
|
||||||
|
|
||||||
|
Authored for GRO-106 Phase 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pre-Flight Checklist
|
||||||
|
|
||||||
|
Before starting Telnyx registration, collect the following:
|
||||||
|
|
||||||
|
| Item | Details |
|
||||||
|
|------|---------|
|
||||||
|
| Legal business name | Exact name on EIN / business registration |
|
||||||
|
| EIN (Employer Identification Number) | 9-digit IRS format: XX-XXXXXXX |
|
||||||
|
| Business type | Sole Proprietor / LLC / Corporation |
|
||||||
|
| Primary contact email | General contact address (postmaster@, info@, etc.) |
|
||||||
|
| Primary contact phone | Direct line for carrier verification |
|
||||||
|
| Website URL | Must be live and contain privacy policy |
|
||||||
|
| Sample message templates | See [Sample Templates](#sample-message-templates) below |
|
||||||
|
| Messaging use case | Customer Care / Account Notification |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Telnyx Account Requirements
|
||||||
|
|
||||||
|
- Active Telnyx account with billing configured.
|
||||||
|
- Role required: **Admin** or **Super User** to register brands and campaigns.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Brand Registration
|
||||||
|
|
||||||
|
### Via Telnyx Console
|
||||||
|
|
||||||
|
1. Log in to [Telnyx Portal](https://portal.telnyx.com).
|
||||||
|
2. Navigate to **Messaging → A2P 10DLC → Brands**.
|
||||||
|
3. Click **Register Brand**.
|
||||||
|
4. Fill in:
|
||||||
|
- **Brand Name**: Legal business name
|
||||||
|
- **Legal Company Name**: Exact EIN name
|
||||||
|
- **Company Type**: Select from dropdown
|
||||||
|
- **EIN**: XX-XXXXXXX
|
||||||
|
- **Primary Contact**: Name, email, phone
|
||||||
|
- **Website**: Must be accessible
|
||||||
|
- **BusinessVertical**: Select appropriate vertical
|
||||||
|
5. Acknowledge the **Terms of Service**.
|
||||||
|
6. Submit.
|
||||||
|
|
||||||
|
### Via API
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST https://api.telnyx.com/v2/10dlc/brands \
|
||||||
|
-H "Authorization: Bearer $TELNYX_API_KEY" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"name": "Your Legal Business Name",
|
||||||
|
"legal_company_name": "Your Legal Business Name",
|
||||||
|
"company_type": "llc",
|
||||||
|
"ein": "XX-XXXXXXX",
|
||||||
|
"primary_contact": {
|
||||||
|
"name": "Jane Doe",
|
||||||
|
"email": "compliance@example.com",
|
||||||
|
"phone": "+1XXXXXXXXXX"
|
||||||
|
},
|
||||||
|
"website": "https://www.example.com",
|
||||||
|
"business_vertical": "PROFESSIONAL_SERVICES"
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response fields to record:**
|
||||||
|
- `brand_id` — required for campaign registration
|
||||||
|
- `brand_score` — affects campaign vetting speed
|
||||||
|
|
||||||
|
### Expected Fees
|
||||||
|
|
||||||
|
| Fee Type | Amount |
|
||||||
|
|----------|--------|
|
||||||
|
| Brand registration fee | ~$0 (no direct fee from Telnyx) |
|
||||||
|
| Campaign registration fee | ~$15–$25 per campaign (Telnyx fee, subject to change) |
|
||||||
|
| Carrier fees | Passed through from T-Mobile/AT&T/Verizon |
|
||||||
|
|
||||||
|
### Expected Approval Window
|
||||||
|
|
||||||
|
- **Vetting by Telnyx**: 1–3 business days after submission.
|
||||||
|
- **Carrier (T-Mobile/AT&T/Verizon) review**: 2–5 business days after Telnyx approval.
|
||||||
|
- Total end-to-end: **3–8 business days**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Campaign Registration
|
||||||
|
|
||||||
|
### Use Case Selection
|
||||||
|
|
||||||
|
- **Primary**: Customer Care
|
||||||
|
- **Secondary**: Account Notification
|
||||||
|
|
||||||
|
### Via Telnyx Console
|
||||||
|
|
||||||
|
1. Navigate to **Messaging → A2P 10DLC → Campaigns**.
|
||||||
|
2. Click **Register Campaign**.
|
||||||
|
3. Select **Brand** (use the brand registered in Step 2).
|
||||||
|
4. Fill in:
|
||||||
|
- **Campaign Name**: e.g., `groombook-pilot-customer-care`
|
||||||
|
- **Use Case**: Customer Care / Account Notification
|
||||||
|
- **Sample Messages**: Paste exactly the templates from [Sample Templates](#sample-message-templates) below.
|
||||||
|
- **Description**: Brief description of messaging program
|
||||||
|
- **Estimated Volume**: Enter monthly estimate (e.g., 500)
|
||||||
|
5. Submit.
|
||||||
|
|
||||||
|
### Via API
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST https://api.telnyx.com/v2/10dlc/campaigns \
|
||||||
|
-H "Authorization: Bearer $TELNYX_API_KEY" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"brand_id": "YOUR_BRAND_ID",
|
||||||
|
"name": "groombook-pilot-customer-care",
|
||||||
|
"use_case": "CUSTOMER_CARE",
|
||||||
|
"sample_messages": [
|
||||||
|
"Hi {{first_name}}, this is a reminder from {{business_name}} that your appointment is scheduled for {{date}} at {{time}}. Reply STOP to opt out.",
|
||||||
|
"Your appointment with {{business_name}} is confirmed for {{date}}. Need to reschedule? Reply HELP or call us at {{phone}}."
|
||||||
|
],
|
||||||
|
"description": "Appointment reminders and account notifications for grooming clients",
|
||||||
|
"estimated_monthly_volume": 500
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response fields to record:**
|
||||||
|
- `campaign_id` — required for messaging profile
|
||||||
|
- `status` — initially `PENDING`, transitions to `ACTIVE` after carrier approval
|
||||||
|
|
||||||
|
### Campaign Vetting — STOP/HELP Language Requirements
|
||||||
|
|
||||||
|
Every campaign **must** include compliant STOP/HELP messaging. The following must appear in your sample messages or be included in your terms of service:
|
||||||
|
|
||||||
|
- **STOP**: Users can text `STOP` to opt out of all messages.
|
||||||
|
- **HELP**: Users can text `HELP` to receive contact information.
|
||||||
|
|
||||||
|
Example STOP/HELP block:
|
||||||
|
|
||||||
|
```
|
||||||
|
Text STOP to opt out. Text HELP for help. Msg & data rates may apply.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Messaging Profile + Phone Number Provisioning
|
||||||
|
|
||||||
|
### Create Messaging Profile
|
||||||
|
|
||||||
|
1. In Telnyx Portal, navigate to **Messaging → Messaging Profiles**.
|
||||||
|
2. Click **Create Messaging Profile**.
|
||||||
|
3. Name it (e.g., `groombook-pilot-prod`).
|
||||||
|
4. Copy the **Messaging Profile ID** (`messaging_profile_id`) — record this in the DB.
|
||||||
|
|
||||||
|
### Provision a 10DLC Phone Number
|
||||||
|
|
||||||
|
1. Navigate to **Messaging → Phone Numbers**.
|
||||||
|
2. Search for a number in your desired area code.
|
||||||
|
3. Confirm the number is 10DLC-capable.
|
||||||
|
4. Purchase the number.
|
||||||
|
|
||||||
|
### Associate Number with Messaging Profile
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Assign number to messaging profile
|
||||||
|
curl -X PATCH https://api.telnyx.com/v2/phone_numbers/YOUR_PHONE_NUMBER_ID \
|
||||||
|
-H "Authorization: Bearer $TELNYX_API_KEY" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"messaging_profile_id": "YOUR_MESSAGING_PROFILE_ID"
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Record in Database
|
||||||
|
|
||||||
|
Once GRO-981 lands, record the following against the business record:
|
||||||
|
|
||||||
|
### SQL Path (when GRO-981 is complete)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE businesses
|
||||||
|
SET
|
||||||
|
messaging_phone_number = '+1XXXXXXXXXX',
|
||||||
|
telnyx_messaging_profile_id = 'YOUR_MESSAGING_PROFILE_ID',
|
||||||
|
telnyx_brand_id = 'YOUR_BRAND_ID',
|
||||||
|
telnyx_campaign_id = 'YOUR_CAMPAIGN_ID',
|
||||||
|
telnyx_brand_status = 'APPROVED',
|
||||||
|
telnyx_campaign_status = 'ACTIVE',
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = 'pilot_business_id';
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Admin Path (before GRO-981)
|
||||||
|
|
||||||
|
Until GRO-981 is complete, use the Telnyx Portal to verify and record values manually in your internal ops sheet:
|
||||||
|
|
||||||
|
| Field | Value |
|
||||||
|
|-------|-------|
|
||||||
|
| `messagingPhoneNumber` | +1XXXXXXXXXX |
|
||||||
|
| `telnyxMessagingProfileId` | xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
|
||||||
|
| `telnyxBrandId` | xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
|
||||||
|
| `telnyxCampaignId` | xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
|
||||||
|
| `brandStatus` | APPROVED / PENDING |
|
||||||
|
| `campaignStatus` | ACTIVE / PENDING |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sample Message Templates
|
||||||
|
|
||||||
|
These must match exactly what your system will send. Vetting reviewers compare templates against actual traffic.
|
||||||
|
|
||||||
|
### Transactional Appointment Reminder
|
||||||
|
|
||||||
|
```
|
||||||
|
Hi {{first_name}}, this is a reminder from {{business_name}} that your appointment is scheduled for {{date}} at {{time}}. Reply STOP to opt out. Msg & data rates may apply.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Staff Message
|
||||||
|
|
||||||
|
```
|
||||||
|
Your appointment with {{business_name}} is confirmed for {{date}}. Need to reschedule? Reply HELP for assistance or call us at {{phone}}. Msg & data rates may apply.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Failure Modes + Retry Guidance
|
||||||
|
|
||||||
|
### Vetting Rejection — Brand
|
||||||
|
|
||||||
|
| Rejection Reason | Common Fix |
|
||||||
|
|-----------------|------------|
|
||||||
|
| Legal name mismatch with EIN | Ensure exact EIN name matches legal company name exactly |
|
||||||
|
| Website not accessible / missing privacy policy | Add privacy policy page to website before resubmitting |
|
||||||
|
| Incomplete primary contact | Provide direct phone and real email (no noreply) |
|
||||||
|
| High-risk business vertical | Contact Telnyx support for pre-screening before resubmitting |
|
||||||
|
|
||||||
|
### Campaign Rejection
|
||||||
|
|
||||||
|
| Rejection Reason | Common Fix |
|
||||||
|
|-----------------|------------|
|
||||||
|
| Sample messages do not match actual traffic | Update sample messages to match exactly what the system sends |
|
||||||
|
| Missing STOP/HELP language | Add compliant STOP/HELP block to sample messages |
|
||||||
|
| Volume estimate too low/high | Revise estimate to be realistic |
|
||||||
|
| Use case mismatch | Re-select use case that matches actual messaging |
|
||||||
|
|
||||||
|
### Re-submission
|
||||||
|
|
||||||
|
After fixing the rejection reason, re-submit via the same API endpoint. Telnyx will re-run vetting (typically 24–48 hours).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cost Summary
|
||||||
|
|
||||||
|
### Telnyx Fees (as of 2026)
|
||||||
|
|
||||||
|
| Fee Type | Amount | Notes |
|
||||||
|
|----------|--------|-------|
|
||||||
|
| 10DLC number (monthly) | ~$1.00–$2.50/number | Varies by type and area code |
|
||||||
|
| Outbound message | $0.005–$0.015/message | Depends on destination carrier |
|
||||||
|
| Inbound message | Included | No charge for received messages |
|
||||||
|
| Campaign registration | ~$15–$25 one-time | Per campaign, subject to change |
|
||||||
|
|
||||||
|
### Carrier Fees (T-Mobile / AT&T / Verizon)
|
||||||
|
|
||||||
|
| Carrier | Outbound Fee | Notes |
|
||||||
|
|---------|-------------|-------|
|
||||||
|
| T-Mobile | ~$0.005–$0.01/message | Varies by message size (segment) |
|
||||||
|
| AT&T | ~$0.005–$0.015/message | Varies by message size (segment) |
|
||||||
|
| Verizon | ~$0.005–$0.01/message | Varies by message size (segment) |
|
||||||
|
|
||||||
|
**Note**: Carrier fees are subject to change. Check [Telnyx pricing page](https://telnyx.com/pricing) and carrier fee schedules for current rates.
|
||||||
|
|
||||||
|
### Example Monthly Cost (Pilot — 500 messages/month)
|
||||||
|
|
||||||
|
| Line Item | Cost |
|
||||||
|
|-----------|------|
|
||||||
|
| 1x 10DLC number | ~$2.00 |
|
||||||
|
| 500 outbound messages | ~$5.00–$7.50 |
|
||||||
|
| Carrier pass-through | ~$2.50–$7.50 |
|
||||||
|
| **Estimated Monthly Total** | **~$9.50–$17.00** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rollback / De-provisioning
|
||||||
|
|
||||||
|
If the pilot tenant must be de-provisioned:
|
||||||
|
|
||||||
|
1. Release the phone number: Telnyx Portal → Phone Numbers → Release.
|
||||||
|
2. Archive the campaign: set status to `INACTIVE` via API or console.
|
||||||
|
3. Remove DB record: clear `messagingPhoneNumber`, `telnyxMessagingProfileId`, `telnyxCampaignId` fields in the business record.
|
||||||
|
4. Brand can remain registered (no harm) but will not be used.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contacts
|
||||||
|
|
||||||
|
| Resource | Contact |
|
||||||
|
|----------|---------|
|
||||||
|
| Telnyx Support | support@telnyx.com |
|
||||||
|
| Telnyx Dashboard | portal.telnyx.com |
|
||||||
|
| Internal Engineering | Raise issue in GRO-106 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_Owner: Engineering · Last updated: 2026-05-04_
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# GroomBook Runbooks
|
||||||
|
|
||||||
|
Operational runbooks for GroomBook staff and operators.
|
||||||
|
|
||||||
|
| Runbook | Description | Status |
|
||||||
|
|---------|-------------|--------|
|
||||||
|
| [10DLC Pilot Registration](./10dlc-pilot-registration.md) | Register a pilot grooming business as an A2P 10DLC brand + campaign on Telnyx | Active |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_To add a runbook, create a markdown file in this directory and update this table._
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "conversations" ADD COLUMN "staff_read_at" timestamp;
|
||||||
@@ -218,6 +218,13 @@
|
|||||||
"when": 1775828067192,
|
"when": 1775828067192,
|
||||||
"tag": "0030_messaging",
|
"tag": "0030_messaging",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 31,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1778818472097,
|
||||||
|
"tag": "0032_staff_read_at",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -444,6 +444,7 @@ export const conversations = pgTable(
|
|||||||
status: text("status").notNull().default("active"),
|
status: text("status").notNull().default("active"),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
|
staffReadAt: timestamp("staff_read_at"),
|
||||||
},
|
},
|
||||||
(t) => [
|
(t) => [
|
||||||
index("idx_conversations_business_id_last_message_at").on(
|
index("idx_conversations_business_id_last_message_at").on(
|
||||||
@@ -477,7 +478,6 @@ export const messages = pgTable(
|
|||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
deliveredAt: timestamp("delivered_at"),
|
deliveredAt: timestamp("delivered_at"),
|
||||||
readByClientAt: timestamp("read_by_client_at"),
|
readByClientAt: timestamp("read_by_client_at"),
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
|
||||||
},
|
},
|
||||||
(t) => [
|
(t) => [
|
||||||
index("idx_messages_conversation_id_created_at").on(
|
index("idx_messages_conversation_id_created_at").on(
|
||||||
|
|||||||
Generated
+19
@@ -46,6 +46,9 @@ importers:
|
|||||||
telnyx:
|
telnyx:
|
||||||
specifier: ^1.23.0
|
specifier: ^1.23.0
|
||||||
version: 1.27.0
|
version: 1.27.0
|
||||||
|
uuid:
|
||||||
|
specifier: ^11.1.1
|
||||||
|
version: 11.1.1
|
||||||
zod:
|
zod:
|
||||||
specifier: ^4.3.6
|
specifier: ^4.3.6
|
||||||
version: 4.3.6
|
version: 4.3.6
|
||||||
@@ -59,6 +62,9 @@ importers:
|
|||||||
'@types/nodemailer':
|
'@types/nodemailer':
|
||||||
specifier: ^6.4.17
|
specifier: ^6.4.17
|
||||||
version: 6.4.23
|
version: 6.4.23
|
||||||
|
'@types/uuid':
|
||||||
|
specifier: ^10.0.0
|
||||||
|
version: 10.0.0
|
||||||
'@vitest/coverage-v8':
|
'@vitest/coverage-v8':
|
||||||
specifier: ^3.2.4
|
specifier: ^3.2.4
|
||||||
version: 3.2.4(vitest@3.2.4(@types/node@22.19.15)(jiti@2.6.1)(jsdom@26.1.0)(lightningcss@1.32.0)(terser@5.46.1)(tsx@4.21.0))
|
version: 3.2.4(vitest@3.2.4(@types/node@22.19.15)(jiti@2.6.1)(jsdom@26.1.0)(lightningcss@1.32.0)(terser@5.46.1)(tsx@4.21.0))
|
||||||
@@ -2334,6 +2340,9 @@ packages:
|
|||||||
'@types/use-sync-external-store@0.0.6':
|
'@types/use-sync-external-store@0.0.6':
|
||||||
resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}
|
resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}
|
||||||
|
|
||||||
|
'@types/uuid@10.0.0':
|
||||||
|
resolution: {integrity: sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==}
|
||||||
|
|
||||||
'@typescript-eslint/eslint-plugin@8.57.1':
|
'@typescript-eslint/eslint-plugin@8.57.1':
|
||||||
resolution: {integrity: sha512-Gn3aqnvNl4NGc6x3/Bqk1AOn0thyTU9bqDRhiRnUWezgvr2OnhYCWCgC8zXXRVqBsIL1pSDt7T9nJUe0oM0kDQ==}
|
resolution: {integrity: sha512-Gn3aqnvNl4NGc6x3/Bqk1AOn0thyTU9bqDRhiRnUWezgvr2OnhYCWCgC8zXXRVqBsIL1pSDt7T9nJUe0oM0kDQ==}
|
||||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||||
@@ -4344,12 +4353,18 @@ packages:
|
|||||||
peerDependencies:
|
peerDependencies:
|
||||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||||
|
|
||||||
|
uuid@11.1.1:
|
||||||
|
resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
uuid@8.3.2:
|
uuid@8.3.2:
|
||||||
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
|
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
|
||||||
|
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
uuid@9.0.1:
|
uuid@9.0.1:
|
||||||
resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}
|
resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}
|
||||||
|
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
victory-vendor@37.3.6:
|
victory-vendor@37.3.6:
|
||||||
@@ -6910,6 +6925,8 @@ snapshots:
|
|||||||
|
|
||||||
'@types/use-sync-external-store@0.0.6': {}
|
'@types/use-sync-external-store@0.0.6': {}
|
||||||
|
|
||||||
|
'@types/uuid@10.0.0': {}
|
||||||
|
|
||||||
'@typescript-eslint/eslint-plugin@8.57.1(@typescript-eslint/parser@8.57.1(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3)':
|
'@typescript-eslint/eslint-plugin@8.57.1(@typescript-eslint/parser@8.57.1(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.4(jiti@2.6.1))(typescript@5.9.3)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@eslint-community/regexpp': 4.12.2
|
'@eslint-community/regexpp': 4.12.2
|
||||||
@@ -9014,6 +9031,8 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
react: 19.2.4
|
react: 19.2.4
|
||||||
|
|
||||||
|
uuid@11.1.1: {}
|
||||||
|
|
||||||
uuid@8.3.2: {}
|
uuid@8.3.2: {}
|
||||||
|
|
||||||
uuid@9.0.1: {}
|
uuid@9.0.1: {}
|
||||||
|
|||||||
Reference in New Issue
Block a user