169 lines
7.5 KiB
TypeScript
169 lines
7.5 KiB
TypeScript
// 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<LoaderData>();
|
|
const rootData = useRootData();
|
|
|
|
return (
|
|
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.booking.detail">
|
|
<h1 className="text-foreground text-xl font-semibold">{vm.pageTitle}</h1>
|
|
<p className="text-muted-foreground mt-1 text-sm">
|
|
{vm.whenLabel} · {t(vm.statusKey)}
|
|
</p>
|
|
|
|
<section className="mt-6">
|
|
<h2 className="font-medium">{t("bookings.detail.customer")}</h2>
|
|
<p>
|
|
{vm.customerName} {vm.customerEmail ? `· ${vm.customerEmail}` : ""}
|
|
</p>
|
|
</section>
|
|
|
|
{vm.intake.length > 0 ? (
|
|
<section className="mt-4">
|
|
<h2 className="font-medium">{t("bookings.detail.intake")}</h2>
|
|
<dl className="mt-1 text-sm">
|
|
{vm.intake.map((entry) => (
|
|
<div key={entry.key} className="flex gap-2">
|
|
<dt className="text-muted-foreground">{entry.key}</dt>
|
|
<dd>{entry.value}</dd>
|
|
</div>
|
|
))}
|
|
</dl>
|
|
</section>
|
|
) : null}
|
|
|
|
{vm.cancellationReason ? <p className="mt-4 text-sm text-red-600">{vm.cancellationReason}</p> : null}
|
|
|
|
{vm.canAct && vm.status === "scheduled" ? (
|
|
<section className="mt-8 flex flex-wrap gap-3" data-ui-id="ui.booking.detail.actions">
|
|
<Form method="post">
|
|
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
|
<input type="hidden" name="intent" value="held" />
|
|
<button type="submit" className="rounded border px-3 py-1">
|
|
{t("bookings.actions.markHeld")}
|
|
</button>
|
|
</Form>
|
|
<Form method="post">
|
|
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
|
<input type="hidden" name="intent" value="no_show" />
|
|
<button type="submit" className="rounded border px-3 py-1">
|
|
{t("bookings.actions.markNoShow")}
|
|
</button>
|
|
</Form>
|
|
<Form method="post" className="flex items-center gap-2">
|
|
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
|
<input type="hidden" name="intent" value="cancel" />
|
|
<input name="reason" placeholder={t("bookings.actions.cancelReason")} className="rounded border px-2 py-1 text-sm" />
|
|
<button type="submit" className="rounded border border-red-300 px-3 py-1 text-red-600">
|
|
{t("bookings.actions.cancel")}
|
|
</button>
|
|
</Form>
|
|
</section>
|
|
) : null}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|