// AK-P16b · booking detail route (M06 Block D). Shows the appointment + intake // answers and exposes the lifecycle actions (held / no-show / cancel / reschedule // / re-assign). The final picker UI waits for David D-P16, but the server action // contract is complete. Owner-checked (read_own sees only own; write/admin acts), // CSRF on every mutation. import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData, Form } from "react-router"; import { useTranslation } from "react-i18next"; import { getTranslations } from "~/locale/i18next.server"; import { validateCSRFToken } from "~/utils/session.server"; import { useRootData } from "~/utils/data/useRootData"; import { loadBookingContext, requireBookingPermission, requireAppointmentOwner, BOOKING_PERMISSIONS } from "~/modules/booking/routes/bookingAccess.server"; import { BOOKING_MODULE_KEY, bookingsListPath, notFoundResponse } from "~/modules/booking/routes/bookingRoutePaths"; import { getAppointmentDetail } from "~/modules/booking/db/booking.db.server"; import { markAppointmentHeld, markAppointmentNoShow, cancelAppointment, rescheduleAppointment, reassignAppointment } from "~/modules/booking/services/BookingLifecycleService.server"; import ServerError from "~/components/ui/errors/ServerError"; interface DetailVM { id: string; status: string; statusKey: string; whenLabel: string; pageTitle: string; customerName: string; customerEmail: string; intake: { key: string; value: string }[]; cancellationReason: string | null; canAct: boolean; } type LoaderData = { title: string; vm: DetailVM }; export const loader = async ({ request, params }: LoaderFunctionArgs) => { const { t } = await getTranslations(request); const ctx = await loadBookingContext({ request, params, requireModule: true }); requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn); const appt = await getAppointmentDetail(ctx.tenantId, params.id ?? ""); if (!appt) { throw notFoundResponse(); } requireAppointmentOwner(ctx, appt.providerUserId); const vm: DetailVM = { id: appt.id, status: appt.status, statusKey: `bookings.status.${appt.status}`, whenLabel: new Date(appt.startAt).toLocaleString(), pageTitle: appt.pageTitle, customerName: appt.customerName, customerEmail: appt.customerEmail, intake: Object.entries(appt.intakeAnswers).map(([key, value]) => ({ key, value: value === null ? "" : String(value) })), cancellationReason: appt.cancellationReason, canAct: ctx.permissions.includes(BOOKING_PERMISSIONS.write) || ctx.permissions.includes(BOOKING_PERMISSIONS.admin), }; return Response.json({ title: `${t("bookings.detail.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData); }; export const action = async ({ request, params }: ActionFunctionArgs) => { const ctx = await loadBookingContext({ request, params, requireModule: true }); requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn); await validateCSRFToken(request); const appt = await getAppointmentDetail(ctx.tenantId, params.id ?? ""); if (!appt) { throw notFoundResponse(); } requireAppointmentOwner(ctx, appt.providerUserId); const form = await request.formData(); const intent = form.get("intent"); if (intent === "held") { requireBookingPermission(ctx, BOOKING_PERMISSIONS.write); await markAppointmentHeld(ctx.tenantId, appt.id, ctx.userId); } else if (intent === "no_show") { requireBookingPermission(ctx, BOOKING_PERMISSIONS.write); await markAppointmentNoShow(ctx.tenantId, appt.id, ctx.userId); } else if (intent === "cancel") { requireBookingPermission(ctx, BOOKING_PERMISSIONS.write); await cancelAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, reason: (form.get("reason") as string | null)?.trim() || "—", byKind: "provider", actorUserId: ctx.userId }); } else if (intent === "reschedule") { requireBookingPermission(ctx, BOOKING_PERMISSIONS.write); const newStartAt = new Date((form.get("newStartAt") as string | null) ?? ""); if (Number.isNaN(newStartAt.getTime())) { return Response.json({ ok: false, error: "bookings.error.invalidSlot" }, { status: 400 }); } await rescheduleAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, newStartAt, actorUserId: ctx.userId }); } else if (intent === "reassign") { requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin); const newProviderUserId = (form.get("newProviderUserId") as string | null)?.trim(); if (!newProviderUserId) { return Response.json({ ok: false, error: "bookings.error.providerRequired" }, { status: 400 }); } await reassignAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, newProviderUserId, actorUserId: ctx.userId }); } return redirect(bookingsListPath(params.tenant ?? "")); }; export default function BookingDetailRoute() { const { t } = useTranslation(); const { vm } = useLoaderData(); const rootData = useRootData(); return (

{vm.pageTitle}

{vm.whenLabel} · {t(vm.statusKey)}

{t("bookings.detail.customer")}

{vm.customerName} {vm.customerEmail ? `· ${vm.customerEmail}` : ""}

{vm.intake.length > 0 ? (

{t("bookings.detail.intake")}

{vm.intake.map((entry) => (
{entry.key}
{entry.value}
))}
) : null} {vm.cancellationReason ?

{vm.cancellationReason}

: null} {vm.canAct && vm.status === "scheduled" ? (
{rootData.csrf && }
{rootData.csrf && }
{rootData.csrf && }
) : null}
); } export function ErrorBoundary() { return ; } export const handle = { moduleKey: BOOKING_MODULE_KEY };