diff --git a/apps/api/src/__tests__/portal.test.ts b/apps/api/src/__tests__/portal.test.ts index 907d879..73f05ff 100644 --- a/apps/api/src/__tests__/portal.test.ts +++ b/apps/api/src/__tests__/portal.test.ts @@ -31,6 +31,10 @@ const APPOINTMENT = { endTime: futureDate(), customerNotes: null, confirmationToken: "secret-token-leak-test", + status: "scheduled" as const, + confirmationStatus: "pending" as const, + confirmedAt: null, + cancelledAt: null, }; let selectSessionRow: Record | null = null; @@ -246,4 +250,174 @@ describe("PATCH /portal/appointments/:id/notes", () => { ); expect(res.status).toBe(400); }); +}); + +// ─── POST /portal/appointments/:id/confirm ──────────────────────────────────── + +function jsonPost(path: string, headers?: Record) { + 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); + }); }); \ No newline at end of file diff --git a/apps/api/src/routes/portal.ts b/apps/api/src/routes/portal.ts index b7c9fa4..663b87c 100644 --- a/apps/api/src/routes/portal.ts +++ b/apps/api/src/routes/portal.ts @@ -76,6 +76,133 @@ portalRouter.patch( } ); +// ─── Appointment confirm/cancel ────────────────────────────────────────────── + +portalRouter.post("/appointments/:id/confirm", async (c) => { + const db = getDb(); + const id = c.req.param("id"); + + const sessionId = c.req.header("X-Impersonation-Session-Id"); + if (!sessionId) { + return c.json({ error: "Unauthorized" }, 401); + } + + const [session] = await db + .select() + .from(impersonationSessions) + .where( + and( + eq(impersonationSessions.id, sessionId), + eq(impersonationSessions.status, "active") + ) + ) + .limit(1); + + if (!session || session.expiresAt <= new Date()) { + return c.json({ error: "Unauthorized" }, 401); + } + + const [appt] = await db + .select() + .from(appointments) + .where(eq(appointments.id, id)) + .limit(1); + + if (!appt) { + return c.json({ error: "Not found" }, 404); + } + + if (appt.clientId !== session.clientId) { + return c.json({ error: "Forbidden" }, 403); + } + + if (appt.startTime <= new Date()) { + return c.json({ error: "Cannot confirm a past or in-progress appointment" }, 422); + } + + if (appt.confirmationStatus !== "pending") { + return c.json({ error: "Appointment is not pending confirmation" }, 422); + } + + if (appt.status === "cancelled" || appt.status === "completed") { + return c.json({ error: "Cannot confirm a cancelled or completed appointment" }, 422); + } + + const [updated] = await db + .update(appointments) + .set({ confirmationStatus: "confirmed", confirmedAt: new Date(), updatedAt: new Date() }) + .where(eq(appointments.id, id)) + .returning(); + + return c.json({ + id: updated!.id, + confirmationStatus: updated!.confirmationStatus, + confirmedAt: updated!.confirmedAt, + updatedAt: updated!.updatedAt, + }); +}); + +portalRouter.post("/appointments/:id/cancel", async (c) => { + const db = getDb(); + const id = c.req.param("id"); + + const sessionId = c.req.header("X-Impersonation-Session-Id"); + if (!sessionId) { + return c.json({ error: "Unauthorized" }, 401); + } + + const [session] = await db + .select() + .from(impersonationSessions) + .where( + and( + eq(impersonationSessions.id, sessionId), + eq(impersonationSessions.status, "active") + ) + ) + .limit(1); + + if (!session || session.expiresAt <= new Date()) { + return c.json({ error: "Unauthorized" }, 401); + } + + const [appt] = await db + .select() + .from(appointments) + .where(eq(appointments.id, id)) + .limit(1); + + if (!appt) { + return c.json({ error: "Not found" }, 404); + } + + if (appt.clientId !== session.clientId) { + return c.json({ error: "Forbidden" }, 403); + } + + if (appt.startTime <= new Date()) { + return c.json({ error: "Cannot cancel a past or in-progress appointment" }, 422); + } + + if (appt.status === "cancelled" || appt.status === "completed") { + return c.json({ error: "Appointment is already cancelled or completed" }, 422); + } + + const [updated] = await db + .update(appointments) + .set({ status: "cancelled", confirmationStatus: "cancelled", cancelledAt: new Date(), updatedAt: new Date() }) + .where(eq(appointments.id, id)) + .returning(); + + return c.json({ + id: updated!.id, + status: updated!.status, + confirmationStatus: updated!.confirmationStatus, + cancelledAt: updated!.cancelledAt, + updatedAt: updated!.updatedAt, + }); +}); + // ─── Client-facing waitlist routes ─────────────────────────────────────────── const createWaitlistEntrySchema = z.object({ diff --git a/apps/web/src/__tests__/Appointments.test.tsx b/apps/web/src/__tests__/Appointments.test.tsx index ade71a7..efd3a9d 100644 --- a/apps/web/src/__tests__/Appointments.test.tsx +++ b/apps/web/src/__tests__/Appointments.test.tsx @@ -1,7 +1,7 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen, fireEvent, waitFor } from "@testing-library/react"; import type { Appointment } from "../portal/mockData.js"; -import { parseTimeTo24Hour, isUpcoming, CustomerNotesSection } from "../portal/sections/Appointments.js"; +import { parseTimeTo24Hour, isUpcoming, CustomerNotesSection, ConfirmationSection } from "../portal/sections/Appointments.js"; const UPCOMING_APPT: Appointment = { id: "appt-1", @@ -18,6 +18,7 @@ const UPCOMING_APPT: Appointment = { status: "confirmed", notes: "", customerNotes: "", + confirmationStatus: "pending", }; const PAST_APPT: Appointment = { @@ -191,4 +192,191 @@ describe("CustomerNotesSection", () => { render(); expect(screen.queryByRole("button", { name: /Save Notes/i })).not.toBeInTheDocument(); }); +}); + +describe("ConfirmationSection", () => { + beforeEach(() => { + vi.clearAllMocks(); + global.fetch = vi.fn(); + vi.stubGlobal("confirm", vi.fn(() => true)); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("renders pending badge when confirmationStatus is pending", () => { + render(); + expect(screen.getByText("Pending confirmation")).toBeInTheDocument(); + }); + + it("renders confirmed badge when confirmationStatus is confirmed", () => { + render(); + expect(screen.getByText("✓ Confirmed")).toBeInTheDocument(); + }); + + it("renders cancelled badge when confirmationStatus is cancelled", () => { + render(); + expect(screen.getByText("Cancelled")).toBeInTheDocument(); + }); + + it("shows Confirm Appointment button when status is pending", () => { + render(); + expect(screen.getByRole("button", { name: /Confirm Appointment/i })).toBeInTheDocument(); + }); + + it("does not show Confirm button when already confirmed", () => { + render(); + expect(screen.queryByRole("button", { name: /Confirm Appointment/i })).not.toBeInTheDocument(); + }); + + it("does not show Confirm button when cancelled", () => { + render(); + expect(screen.queryByRole("button", { name: /Confirm Appointment/i })).not.toBeInTheDocument(); + }); + + it("calls confirm API and updates local status on success", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: true, + json: async () => ({ id: "appt-1", confirmationStatus: "confirmed" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + "/api/portal/appointments/appt-1/confirm", + expect.objectContaining({ method: "POST" }) + ); + }); + await waitFor(() => { + expect(screen.getByText("✓ Confirmed")).toBeInTheDocument(); + }); + }); + + it("sends X-Impersonation-Session-Id header when session exists", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: true, + json: async () => ({ id: "appt-1", confirmationStatus: "confirmed" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + "/api/portal/appointments/appt-1/confirm", + expect.objectContaining({ + headers: expect.objectContaining({ + "X-Impersonation-Session-Id": "test-session-id", + }), + }) + ); + }); + }); + + it("does not send X-Impersonation-Session-Id header when sessionId is null", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: true, + json: async () => ({ id: "appt-1", confirmationStatus: "confirmed" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + "/api/portal/appointments/appt-1/confirm", + expect.objectContaining({ + headers: expect.not.objectContaining({ + "X-Impersonation-Session-Id": expect.anything(), + }), + }) + ); + }); + }); + + it("shows error message when confirm API returns 401", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: false, + status: 401, + json: async () => ({ error: "Unauthorized" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(screen.getByText(/Unauthorized/i)).toBeInTheDocument(); + }); + }); + + it("shows error message when confirm API returns 403", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: false, + status: 403, + json: async () => ({ error: "Forbidden" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(screen.getByText(/Forbidden/i)).toBeInTheDocument(); + }); + }); + + it("shows error message when confirm API returns 422 (invalid state)", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: false, + status: 422, + json: async () => ({ error: "Cannot confirm - appointment is not in pending state" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(screen.getByText(/Cannot confirm/i)).toBeInTheDocument(); + }); + }); + + it("does not call confirm API if user cancels the confirmation dialog", async () => { + vi.stubGlobal("confirm", vi.fn(() => false)); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + expect(global.fetch).not.toHaveBeenCalled(); + }); + + it("shows loading state while confirming", async () => { + vi.mocked(global.fetch).mockReturnValue(new Promise(() => {})); // Never resolves + + render(); + // Get button reference before clicking + const btn = screen.getByRole("button", { name: /Confirm Appointment/i }); + fireEvent.click(btn); + + await waitFor(() => { + expect(screen.getByText(/Confirming.../i)).toBeInTheDocument(); + }); + // Button is disabled while loading + expect(btn).toBeDisabled(); + }); + + it("shows success message briefly after confirm", async () => { + vi.mocked(global.fetch).mockResolvedValue({ + ok: true, + json: async () => ({ id: "appt-1", confirmationStatus: "confirmed" }), + } as Response); + + render(); + fireEvent.click(screen.getByRole("button", { name: /Confirm Appointment/i })); + + await waitFor(() => { + expect(screen.getByText(/Confirmed!/i)).toBeInTheDocument(); + }); + }); }); \ No newline at end of file diff --git a/apps/web/src/portal/mockData.ts b/apps/web/src/portal/mockData.ts index 190b41a..330cfe8 100644 --- a/apps/web/src/portal/mockData.ts +++ b/apps/web/src/portal/mockData.ts @@ -41,6 +41,7 @@ export interface Appointment { duration: number; price: number; status: "confirmed" | "pending" | "waitlisted" | "completed" | "cancelled"; + confirmationStatus: "pending" | "confirmed" | "cancelled"; notes: string; customerNotes: string; reportCardId?: string; @@ -177,21 +178,21 @@ export const UPCOMING_APPOINTMENTS: Appointment[] = [ id: "a1", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie", services: ["Full Groom"], addOns: ["De-shedding Treatment"], date: "2026-03-21", time: "10:00 AM", duration: 120, price: 145, - status: "confirmed", notes: "Spring shed is heavy — extra undercoat work needed", + status: "confirmed", confirmationStatus: "confirmed", notes: "Spring shed is heavy — extra undercoat work needed", customerNotes: "", }, { id: "a2", petId: "p2", petName: "Mochi", groomerId: "g3", groomerName: "Morgan", services: ["Full Groom"], addOns: ["Teeth Brushing"], date: "2026-03-25", time: "2:00 PM", duration: 100, price: 90, - status: "confirmed", notes: "First visit with Morgan — patient with anxious pets", + status: "confirmed", confirmationStatus: "confirmed", notes: "First visit with Morgan — patient with anxious pets", customerNotes: "", }, { id: "a3", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie", services: ["Bath & Brush"], addOns: [], date: "2026-04-18", time: "11:00 AM", duration: 45, price: 55, - status: "pending", notes: "", + status: "pending", confirmationStatus: "pending", notes: "", customerNotes: "", }, ]; @@ -201,56 +202,56 @@ export const PAST_APPOINTMENTS: Appointment[] = [ id: "pa1", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie", services: ["Full Groom"], addOns: ["De-shedding Treatment", "Blueberry Facial"], date: "2026-02-15", time: "10:00 AM", duration: 130, price: 160, - status: "completed", notes: "", reportCardId: "rc1", + status: "completed", confirmationStatus: "confirmed", notes: "", reportCardId: "rc1", customerNotes: "", }, { id: "pa2", petId: "p2", petName: "Mochi", groomerId: "g2", groomerName: "Alex", services: ["Full Groom"], addOns: ["Teeth Brushing"], date: "2026-02-20", time: "1:00 PM", duration: 100, price: 88, - status: "completed", notes: "", reportCardId: "rc2", + status: "completed", confirmationStatus: "confirmed", notes: "", reportCardId: "rc2", customerNotes: "", }, { id: "pa3", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie", services: ["Bath & Brush"], addOns: [], date: "2026-01-18", time: "9:00 AM", duration: 45, price: 55, - status: "completed", notes: "", + status: "completed", confirmationStatus: "confirmed", notes: "", customerNotes: "", }, { id: "pa4", petId: "p2", petName: "Mochi", groomerId: "g2", groomerName: "Alex", services: ["Puppy's First Groom"], addOns: [], date: "2026-01-10", time: "3:00 PM", duration: 60, price: 62, - status: "completed", notes: "", + status: "completed", confirmationStatus: "confirmed", notes: "", customerNotes: "", }, { id: "pa5", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie", services: ["Full Groom"], addOns: ["Nail Grinding"], date: "2025-12-20", time: "10:00 AM", duration: 105, price: 132, - status: "completed", notes: "Holiday groom", + status: "completed", confirmationStatus: "confirmed", notes: "Holiday groom", customerNotes: "", }, { id: "pa6", petId: "p1", petName: "Biscuit", groomerId: "g2", groomerName: "Alex", services: ["Full Groom"], addOns: [], date: "2025-11-15", time: "11:00 AM", duration: 90, price: 110, - status: "completed", notes: "", + status: "completed", confirmationStatus: "confirmed", notes: "", customerNotes: "", }, { id: "pa7", petId: "p2", petName: "Mochi", groomerId: "g3", groomerName: "Morgan", services: ["Bath & Brush"], addOns: [], date: "2025-11-08", time: "2:00 PM", duration: 45, price: 48, - status: "completed", notes: "", + status: "completed", confirmationStatus: "confirmed", notes: "", customerNotes: "", }, { id: "pa8", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie", services: ["Bath & Brush"], addOns: ["De-shedding Treatment"], date: "2025-10-12", time: "10:00 AM", duration: 75, price: 85, - status: "completed", notes: "", + status: "completed", confirmationStatus: "confirmed", notes: "", customerNotes: "", }, ]; diff --git a/apps/web/src/portal/sections/Appointments.tsx b/apps/web/src/portal/sections/Appointments.tsx index bd38475..04c2bc1 100644 --- a/apps/web/src/portal/sections/Appointments.tsx +++ b/apps/web/src/portal/sections/Appointments.tsx @@ -41,6 +41,12 @@ const STATUS_COLORS: Record = { cancelled: "bg-red-100 text-red-600", }; +const CONFIRMATION_STATUS_COLORS: Record = { + confirmed: "bg-green-100 text-green-700", + pending: "bg-amber-100 text-amber-700", + cancelled: "bg-red-100 text-red-600", +}; + export function AppointmentsSection({ readOnly, sessionId }: Props) { const [showBooking, setShowBooking] = useState(false); const [expandedId, setExpandedId] = useState(null); @@ -165,14 +171,15 @@ function AppointmentCard({ {isUpcoming(appt) && !readOnly && ( )} + {isUpcoming(appt) && ( + + )} {appt.status !== "completed" && appt.status !== "cancelled" && !readOnly && (
- +
)} {appt.reportCardId && ( @@ -188,6 +195,116 @@ function AppointmentCard({ ); } +export function ConfirmationSection({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) { + const [confirming, setConfirming] = useState(false); + const [confirmError, setConfirmError] = useState(null); + const [confirmSuccess, setConfirmSuccess] = useState(false); + // Local state mirrors confirmationStatus so the badge updates immediately after confirm + const [localStatus, setLocalStatus] = useState(appt.confirmationStatus); + + async function handleConfirm() { + if (!window.confirm("Confirm this appointment?")) return; + setConfirming(true); + setConfirmError(null); + try { + const headers: Record = {}; + if (sessionId) { + headers["X-Impersonation-Session-Id"] = sessionId; + } + const res = await fetch(`/api/portal/appointments/${appt.id}/confirm`, { + method: "POST", + headers, + }); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: "Failed to confirm" })); + throw new Error(err.error || `HTTP ${res.status}`); + } + setLocalStatus("confirmed"); + setConfirmSuccess(true); + setTimeout(() => setConfirmSuccess(false), 2000); + } catch (e) { + setConfirmError(e instanceof Error ? e.message : "Failed to confirm"); + } finally { + setConfirming(false); + } + } + + const currentStatus = localStatus ?? appt.confirmationStatus; + const statusLabel = currentStatus === "confirmed" + ? "✓ Confirmed" + : currentStatus === "pending" + ? "Pending confirmation" + : "Cancelled"; + + return ( +
+
+
+ + {statusLabel} + +
+ {!confirmSuccess && currentStatus === "pending" && ( + + )} + {confirmSuccess && ( + Confirmed! + )} +
+ {confirmError &&

{confirmError}

} +
+ ); +} + +function CancelAppointmentButton({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) { + const [cancelling, setCancelling] = useState(false); + const [cancelError, setCancelError] = useState(null); + + async function handleCancel() { + if (!window.confirm("Cancel this appointment? This cannot be undone.")) return; + setCancelling(true); + setCancelError(null); + try { + const headers: Record = {}; + if (sessionId) { + headers["X-Impersonation-Session-Id"] = sessionId; + } + const res = await fetch(`/api/portal/appointments/${appt.id}/cancel`, { + method: "POST", + headers, + }); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: "Failed to cancel" })); + throw new Error(err.error || `HTTP ${res.status}`); + } + window.location.reload(); + } catch (e) { + setCancelError(e instanceof Error ? e.message : "Failed to cancel"); + setCancelling(false); + } + } + + return ( + <> + + {cancelError &&

{cancelError}

} + + ); +} + export function CustomerNotesSection({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) { const [notes, setNotes] = useState(appt.customerNotes || ""); const [saving, setSaving] = useState(false);