183 lines
8.6 KiB
TypeScript
183 lines
8.6 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) through the interim ~/ui screen (AD-28) incl. the reschedule slot
|
|
// picker (loader recomputes candidate slots per `?slotsDate=` via the slot engine)
|
|
// and the admin re-assign provider picker. Owner-checked (read_own sees only own;
|
|
// write/admin acts), CSRF on every mutation.
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigate, useParams } from "react-router";
|
|
import { useEffect } from "react";
|
|
import { formatInTimeZone } from "date-fns-tz";
|
|
import { buildBookingDetailVM, type BookingDetailVM, type BookingProviderOption, type RescheduleSlotOption } from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { formatDateTime } from "~/locale/format";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { loadBookingContext, requireBookingPermission, requireAppointmentOwner, bookingHasPermission, 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 { loadSlotsForDate } from "~/modules/booking/services/SlotQueryService.server";
|
|
import { getTenantUsers } from "~/utils/db/tenants.db.server";
|
|
import { markAppointmentHeld, markAppointmentNoShow, cancelAppointment, rescheduleAppointment, reassignAppointment } from "~/modules/booking/services/BookingLifecycleService.server";
|
|
import { BookingDetailPage } from "~/components/screens/booking/BookingDetailPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
vm: BookingDetailVM;
|
|
/** Candidate slots for `?slotsDate=`; null when no date was requested. */
|
|
rescheduleSlots: RescheduleSlotOption[] | null;
|
|
slotsDate: string | null;
|
|
/** Names the bookings list the detail was reached through (tenant > Buchungen > Buchung). */
|
|
breadcrumbAncestors: { label: string; href: string }[];
|
|
};
|
|
|
|
type ActionData = {
|
|
intent?: string;
|
|
ok?: true;
|
|
messageKey?: string;
|
|
error?: string;
|
|
};
|
|
|
|
const BOOKING_SUCCESS_KEYS: Readonly<Record<string, string>> = {
|
|
held: "bookings.toast.held",
|
|
no_show: "bookings.toast.noShow",
|
|
cancel: "bookings.toast.cancelled",
|
|
reschedule: "bookings.toast.rescheduled",
|
|
reassign: "bookings.toast.reassigned",
|
|
};
|
|
|
|
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/u;
|
|
const DAY_MS = 86_400_000;
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t, locale } = 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 canWrite = bookingHasPermission(ctx, BOOKING_PERMISSIONS.write);
|
|
const canAdmin = ctx.permissions.includes(BOOKING_PERMISSIONS.admin);
|
|
const now = new Date();
|
|
|
|
// Re-assign candidates (admin only): active tenant members.
|
|
let providerOptions: BookingProviderOption[] = [];
|
|
if (canAdmin) {
|
|
const members = await getTenantUsers(ctx.tenantId);
|
|
providerOptions = members.map((member) => ({
|
|
id: member.userId,
|
|
label: [member.user.firstName, member.user.lastName].filter(Boolean).join(" ") || member.user.email,
|
|
}));
|
|
}
|
|
|
|
// Reschedule picker: recompute the provider's bookable slots for a requested
|
|
// date via the same engine the public flow uses (busy calendar incl. Google).
|
|
const url = new URL(request.url);
|
|
const slotsDateParam = url.searchParams.get("slotsDate");
|
|
const slotsDate = slotsDateParam && DATE_RE.test(slotsDateParam) ? slotsDateParam : null;
|
|
let rescheduleSlots: RescheduleSlotOption[] | null = null;
|
|
if (slotsDate && canWrite && appt.status === "scheduled") {
|
|
const slots = await loadSlotsForDate({ tenantId: ctx.tenantId, providerUserIds: [appt.providerUserId], date: slotsDate, config: appt.pageConfig, now });
|
|
rescheduleSlots = slots.map((slot) => ({ startAtIso: slot.startAt.toISOString(), label: formatInTimeZone(slot.startAt, appt.timezone, "HH:mm") }));
|
|
}
|
|
|
|
const vm = buildBookingDetailVM({
|
|
id: appt.id,
|
|
status: appt.status,
|
|
// Locale-aware + fixed app time zone (Europe/Berlin) instead of the server default.
|
|
whenLabel: formatDateTime(appt.startAt, locale),
|
|
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,
|
|
canWrite,
|
|
canAdmin,
|
|
providerOptions,
|
|
minRescheduleDateIso: formatInTimeZone(now, appt.timezone, "yyyy-MM-dd"),
|
|
maxRescheduleDateIso: formatInTimeZone(new Date(now.getTime() + appt.pageConfig.maxAdvanceDays * DAY_MS), appt.timezone, "yyyy-MM-dd"),
|
|
});
|
|
return Response.json({
|
|
title: `${t("bookings.detail.title")} | ${process.env.APP_NAME}`,
|
|
vm,
|
|
rescheduleSlots,
|
|
slotsDate,
|
|
breadcrumbAncestors: [{ label: t("bookings.list.title"), href: bookingsListPath(params.tenant ?? "") }],
|
|
} 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 = String(form.get("intent") ?? "");
|
|
try {
|
|
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({ intent, error: "bookings.error.invalidSlot" } satisfies ActionData, { 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({ intent, error: "bookings.error.providerRequired" } satisfies ActionData, { status: 400 });
|
|
}
|
|
await reassignAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, newProviderUserId, actorUserId: ctx.userId });
|
|
} else {
|
|
return Response.json({ intent, error: "bookings.error.invalidAction" } satisfies ActionData, { status: 400 });
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof Response) throw error;
|
|
return Response.json({ intent, error: "bookings.error.lifecycleFailed" } satisfies ActionData, { status: 400 });
|
|
}
|
|
return Response.json({ intent, ok: true, messageKey: BOOKING_SUCCESS_KEYS[intent] } satisfies ActionData);
|
|
};
|
|
|
|
export default function BookingDetailRoute() {
|
|
const { vm, rescheduleSlots, slotsDate } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const navigate = useNavigate();
|
|
const params = useParams();
|
|
const rootData = useRootData();
|
|
|
|
useSaveToast(actionData);
|
|
|
|
useEffect(() => {
|
|
if (actionData?.ok) navigate(bookingsListPath(params.tenant ?? ""));
|
|
}, [actionData, navigate, params.tenant]);
|
|
|
|
return <BookingDetailPage vm={vm} csrf={rootData.csrf ?? null} rescheduleSlots={rescheduleSlots} slotsDate={slotsDate} />;
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|