Files
api/src/__tests__/portal.test.ts
T
Flea Flicker 277f459237
CI / Test (pull_request) Successful in 26s
CI / Lint & Typecheck (pull_request) Successful in 29s
CI / Build & Push Docker Images (pull_request) Successful in 1m15s
fix(GRO-2342): portal waitlist card populates service {id, name}
Cosmetic follow-up to GRO-2319 (Phase 4 review by CTO). The synthetic
waitlist card on GET /portal/appointments returned service: {id} only,
so the portal fell back to the literal 'Service' label. CMPO spec did
not call for a service name on the waitlist card, but populating the
real name is non-urgent and closes the cosmetic gap.

- src/routes/portal.ts: include a services SELECT (in addition to
  pets and staff) covering both appointment and waitlist serviceIds.
  serviceMap feeds a service.name lookup. The synthetic waitlist
  card's service object is now {id, name} — same shape the
  appointments join returns — so the portal renders the real name.
  The appointments join also gains a name (consistent shape, no
  regression for the existing path).
- src/__tests__/portal.test.ts: mock the services table and assert
  service: {id, name} on both the synthetic waitlist card and the
  appointment card.
- UAT_PLAYBOOK.md: TC-API-8.20 covering the waitlist card service
  name (TC-API-8.19 retained verbatim for the original GRO-2319
  surfacing contract).

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-10 09:11:08 +00:00

553 lines
19 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { Hono } from "hono";
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
const APPOINTMENT_ID = "660e8400-e29b-41d4-a716-446655440002";
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
const pastDate = () => new Date(Date.now() - 5 * 60 * 1000);
const ACTIVE_SESSION = {
id: SESSION_ID,
clientId: CLIENT_ID,
status: "active" as const,
expiresAt: futureDate(),
createdAt: new Date(),
};
const EXPIRED_SESSION = {
id: SESSION_ID,
clientId: CLIENT_ID,
status: "active" as const,
expiresAt: pastDate(),
createdAt: new Date(),
};
const APPOINTMENT = {
id: APPOINTMENT_ID,
clientId: CLIENT_ID,
startTime: futureDate(),
endTime: futureDate(),
customerNotes: null,
confirmationToken: "secret-token-leak-test",
status: "scheduled" as const,
confirmationStatus: "pending" as const,
confirmedAt: null,
cancelledAt: null,
};
let selectSessionRow: Record<string, unknown> | null = null;
let selectAppointmentRow: Record<string, unknown> | null = null;
let selectWaitlistRows: Record<string, unknown>[] = [];
let selectPetRows: Record<string, unknown>[] = [];
let selectStaffRows: Record<string, unknown>[] = [];
let selectServiceRows: Record<string, unknown>[] = [];
let updatedValues: Record<string, unknown>[] = [];
function resetMock() {
selectSessionRow = null;
selectAppointmentRow = null;
selectWaitlistRows = [];
selectPetRows = [];
selectStaffRows = [];
selectServiceRows = [];
updatedValues = [];
}
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") {
return () => chain;
}
// @ts-expect-error proxy
return target[prop];
},
});
return chain;
}
const impersonationSessions = new Proxy(
{ _name: "impersonationSessions" },
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
);
const appointments = new Proxy(
{ _name: "appointments" },
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
);
const mkTable = (name: string) =>
new Proxy({ _name: name }, { get: (t, p) => (p === "_name" ? name : { table: name, column: p }) });
const waitlistEntries = mkTable("waitlistEntries");
const pets = mkTable("pets");
const staff = mkTable("staff");
const services = mkTable("services");
return {
getDb: () => ({
select: () => ({
from: (table: { _name: string }) => {
if (table._name === "impersonationSessions") {
return makeChainable(selectSessionRow ? [selectSessionRow] : []);
}
if (table._name === "appointments") {
return makeChainable(selectAppointmentRow ? [selectAppointmentRow] : []);
}
if (table._name === "waitlistEntries") {
return makeChainable(selectWaitlistRows);
}
if (table._name === "pets") {
return makeChainable(selectPetRows);
}
if (table._name === "staff") {
return makeChainable(selectStaffRows);
}
if (table._name === "services") {
return makeChainable(selectServiceRows);
}
return makeChainable([]);
},
}),
update: () => ({
set: (vals: Record<string, unknown>) => ({
where: () => ({
returning: () => {
if (selectAppointmentRow) {
const updated = { ...selectAppointmentRow, ...vals };
updatedValues.push(vals);
return [updated];
}
return [];
},
}),
}),
}),
}),
impersonationSessions,
appointments,
waitlistEntries,
pets,
staff,
services,
eq: vi.fn(),
and: vi.fn(),
inArray: vi.fn(),
};
});
const { portalRouter } = await import("../routes/portal.js");
const app = new Hono();
app.route("/portal", portalRouter);
function jsonPatch(path: string, body: unknown, headers?: Record<string, string>) {
return app.request(path, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
...headers,
},
body: JSON.stringify(body),
});
}
beforeEach(() => resetMock());
// GRO-2319 item 2: the portal Upcoming list renders active waitlist entries as
// synthetic `waitlisted` cards, so GET /portal/appointments must surface them.
describe("GET /portal/appointments (waitlist surfacing — GRO-2319)", () => {
it("returns active waitlist entries as synthetic waitlisted cards", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
selectWaitlistRows = [
{
id: "11111111-1111-1111-1111-111111111111",
petId: "pet-1",
serviceId: "svc-1",
preferredDate: "2099-01-01",
preferredTime: "13:00:00",
},
];
selectPetRows = [{ id: "pet-1", name: "Rex", photoKey: null }];
const res = await app.request("/portal/appointments", {
headers: { "X-Impersonation-Session-Id": SESSION_ID },
});
expect(res.status).toBe(200);
const body = await res.json();
const waitlistCard = body.appointments.find(
(a: { status: string }) => a.status === "waitlisted",
);
expect(waitlistCard).toBeTruthy();
expect(waitlistCard.id).toBe("waitlist:11111111-1111-1111-1111-111111111111");
expect(waitlistCard.pet.name).toBe("Rex");
expect(waitlistCard.confirmationStatus).toBeNull();
// startTime is derived from preferredDate + preferredTime so the card sorts
// and classifies as Upcoming.
expect(waitlistCard.startTime).toBeTruthy();
});
it("omits the waitlist section when the client has no active entries", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
selectWaitlistRows = [];
const res = await app.request("/portal/appointments", {
headers: { "X-Impersonation-Session-Id": SESSION_ID },
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.appointments.some((a: { status: string }) => a.status === "waitlisted")).toBe(false);
});
});
// GRO-2342: GET /portal/appointments must populate the synthetic waitlist
// card's `service` object with the full service record (id + name) — same
// shape the appointments join returns — so the portal renders the real
// service name in place of the fallback "Service" label.
describe("GET /portal/appointments (waitlist service name — GRO-2342)", () => {
it("returns service {id, name} on the synthetic waitlist card", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
selectWaitlistRows = [
{
id: "22222222-2222-2222-2222-222222222222",
petId: "pet-1",
serviceId: "svc-1",
preferredDate: "2099-01-01",
preferredTime: "13:00:00",
},
];
selectPetRows = [{ id: "pet-1", name: "Rex", photoKey: null }];
selectServiceRows = [{ id: "svc-1", name: "Full Groom" }];
const res = await app.request("/portal/appointments", {
headers: { "X-Impersonation-Session-Id": SESSION_ID },
});
expect(res.status).toBe(200);
const body = await res.json();
const waitlistCard = body.appointments.find(
(a: { status: string }) => a.status === "waitlisted",
);
expect(waitlistCard).toBeTruthy();
expect(waitlistCard.service).toEqual({ id: "svc-1", name: "Full Groom" });
});
it("returns service {id, name} on the appointment card (same shape)", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, serviceId: "svc-appt" };
selectServiceRows = [{ id: "svc-appt", name: "Bath & Brush" }];
const res = await app.request("/portal/appointments", {
headers: { "X-Impersonation-Session-Id": SESSION_ID },
});
expect(res.status).toBe(200);
const body = await res.json();
const apptCard = body.appointments.find(
(a: { status: string }) => a.status === "scheduled",
);
expect(apptCard).toBeTruthy();
expect(apptCard.service).toEqual({ id: "svc-appt", name: "Bath & Brush" });
});
});
describe("PATCH /portal/appointments/:id/notes", () => {
it("returns updated appointment with safe fields only", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Please be gentle with Fido" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toHaveProperty("id");
expect(body).toHaveProperty("customerNotes", "Please be gentle with Fido");
expect(body).toHaveProperty("updatedAt");
expect(body).not.toHaveProperty("confirmationToken");
expect(body).not.toHaveProperty("clientId");
});
it("returns 401 without X-Impersonation-Session-Id header", async () => {
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" }
);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 401 with expired session", async () => {
selectSessionRow = EXPIRED_SESSION;
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 401 with ended session", async () => {
selectSessionRow = null;
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 403 when appointment belongs to different client", async () => {
selectSessionRow = { ...ACTIVE_SESSION, clientId: "different-client-id" };
selectAppointmentRow = { ...APPOINTMENT };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(403);
const body = await res.json();
expect(body.error).toBe("Forbidden");
});
it("returns 422 for past appointment", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, startTime: pastDate() };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
const body = await res.json();
expect(body.error).toMatch(/past|in-progress|cannot edit/i);
});
it("returns 422 when appointment is in progress", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, startTime: new Date(Date.now() - 2 * 60 * 1000) };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 404 when appointment not found", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = null;
const res = await jsonPatch(
`/portal/appointments/nonexistent-id/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(404);
});
it("accepts notes at exactly 500 characters", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
const longNote = "a".repeat(500);
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: longNote },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.customerNotes).toBe(longNote);
});
it("rejects notes exceeding 500 characters", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
const longNote = "a".repeat(501);
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: longNote },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(400);
});
});
// ─── POST /portal/appointments/:id/confirm ────────────────────────────────────
function jsonPost(path: string, headers?: Record<string, string>) {
return app.request(path, {
method: "POST",
headers,
});
}
describe("POST /portal/appointments/:id/confirm", () => {
it("confirms a pending appointment and returns updated status", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, confirmationStatus: "pending" };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.confirmationStatus).toBe("confirmed");
expect(body).toHaveProperty("confirmedAt");
});
it("returns 401 without X-Impersonation-Session-Id header", async () => {
const res = await jsonPost(`/portal/appointments/${APPOINTMENT_ID}/confirm`);
expect(res.status).toBe(401);
});
it("returns 401 with expired session", async () => {
selectSessionRow = EXPIRED_SESSION;
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(401);
});
it("returns 403 when appointment belongs to a different client", async () => {
selectSessionRow = { ...ACTIVE_SESSION, clientId: "different-client-id" };
selectAppointmentRow = { ...APPOINTMENT };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(403);
});
it("returns 422 when appointment is in the past", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, startTime: pastDate() };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 422 when appointment is not pending confirmation", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, confirmationStatus: "confirmed" };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 422 when cancelling an already-cancelled appointment", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, status: "cancelled", confirmationStatus: "cancelled" };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 404 when appointment not found", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = null;
const res = await jsonPost(
`/portal/appointments/nonexistent-id/confirm`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(404);
});
});
// ─── POST /portal/appointments/:id/cancel ─────────────────────────────────────
describe("POST /portal/appointments/:id/cancel", () => {
it("cancels a pending appointment and returns updated status", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, confirmationStatus: "pending" };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.status).toBe("cancelled");
expect(body.confirmationStatus).toBe("cancelled");
expect(body).toHaveProperty("cancelledAt");
});
it("returns 401 without X-Impersonation-Session-Id header", async () => {
const res = await jsonPost(`/portal/appointments/${APPOINTMENT_ID}/cancel`);
expect(res.status).toBe(401);
});
it("returns 401 with expired session", async () => {
selectSessionRow = EXPIRED_SESSION;
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(401);
});
it("returns 403 when appointment belongs to a different client", async () => {
selectSessionRow = { ...ACTIVE_SESSION, clientId: "different-client-id" };
selectAppointmentRow = { ...APPOINTMENT };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(403);
});
it("returns 422 when appointment is in the past", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, startTime: pastDate() };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 422 when appointment is already cancelled", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, status: "cancelled", confirmationStatus: "cancelled" };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 422 when appointment is already completed", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, status: "completed" };
const res = await jsonPost(
`/portal/appointments/${APPOINTMENT_ID}/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 404 when appointment not found", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = null;
const res = await jsonPost(
`/portal/appointments/nonexistent-id/cancel`,
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(404);
});
});