Phase 4
Seed data extended with a second barber (different hours/services), a beard-trim service + category, breaks, time off, a guest customer, and appointments in all three key states — verified against a live throwaway Postgres. 14 new integration tests (38 total with Phase 3's) covering guest/authenticated booking, any-barber assignment, slot-conflict handling, ownership enforcement, guest-data isolation, and book-again repricing. Playwright E2E suite for the 6 required customer journeys, with its own global-setup.ts that migrates and seeds a database automatically. Full verification pass, which caught and fixed three real bugs along the way (not just test-workarounds): A date off-by-one bug in the calendar picker that made real weekdays show as closed for anyone in a UTC+ timezone (including the business's own). A dialog that could vanish mid-confirmation on cancellation, before the customer could read the late-cancellation notice. A silent test-cleanup leak in the Phase 3 fixtures that had been leaking stray businesses since Phase 3. Plus a baseline desktop-responsive fix (centered max-w-2xl columns) across Home/Appointments/Settings/booking flow, since desktop had been effectively unstyled. Final state: 90 unit tests, 38 integration tests, and all 6 E2E journeys passing together on a fresh database; clean tsc, eslint, and next build. Full writeup with routes, security model, guest-matching rules, known limitations, and what to check before Phase 5 is in docs/phase-4-summary.md.
This commit is contained in:
66 files changed
+4599
-107
No files matched your search
@@ -0,0 +1,68 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { auth } from "@/auth";
|
||||
import { clearDraft, readDraft, writeLastBookingReference } from "@/lib/booking-draft/cookie";
|
||||
import { prisma } from "@/lib/db/prisma";
|
||||
import { resolveCustomerForBooking } from "@/services/customer/customer.service";
|
||||
import { createBooking } from "@/services/scheduling/booking.service";
|
||||
import { getFirstFriendlyMessage } from "../error-messages";
|
||||
|
||||
export interface ConfirmBookingResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The only action that actually creates an appointment. Resolves *which*
|
||||
* customer this is via CustomerService (never trusts a client-supplied
|
||||
* customerId — see docs/phase-4-summary.md, "Security"), then hands off
|
||||
* entirely to BookingService.createBooking, which re-validates the slot
|
||||
* inside a transaction before committing — this action does not decide
|
||||
* whether the slot is actually available.
|
||||
*/
|
||||
export async function confirmBookingAction(businessId: string): Promise<ConfirmBookingResult> {
|
||||
const draft = await readDraft(businessId);
|
||||
|
||||
if (draft.serviceIds.length === 0 || !draft.startAt) {
|
||||
return { success: false, error: "Your booking details are incomplete — please start again." };
|
||||
}
|
||||
if (!draft.policyAcknowledged) {
|
||||
return { success: false, error: "Please acknowledge the cancellation policy to continue." };
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
|
||||
let customerId: string;
|
||||
try {
|
||||
if (session?.user?.id) {
|
||||
const resolved = await resolveCustomerForBooking(prisma, { businessId, userId: session.user.id });
|
||||
customerId = resolved.customerId;
|
||||
} else {
|
||||
if (!draft.guest) {
|
||||
return { success: false, error: "Please provide your contact details first." };
|
||||
}
|
||||
const resolved = await resolveCustomerForBooking(prisma, { businessId, guest: draft.guest });
|
||||
customerId = resolved.customerId;
|
||||
}
|
||||
} catch {
|
||||
return { success: false, error: "We couldn't confirm your details. Please try again." };
|
||||
}
|
||||
|
||||
const result = await createBooking(prisma, {
|
||||
businessId,
|
||||
customerId,
|
||||
serviceIds: draft.serviceIds,
|
||||
staffId: draft.staffId,
|
||||
startAt: new Date(draft.startAt),
|
||||
notes: draft.notes,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return { success: false, error: getFirstFriendlyMessage(result.validation) };
|
||||
}
|
||||
|
||||
await writeLastBookingReference(result.appointment.id);
|
||||
await clearDraft();
|
||||
redirect("/book/confirmation");
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { auth } from "@/auth";
|
||||
import { prisma } from "@/lib/db/prisma";
|
||||
import { getAppointmentById } from "@/services/scheduling/appointment.service";
|
||||
import { cancelBooking, rescheduleBooking } from "@/services/scheduling/booking.service";
|
||||
import { assertCanAccessAppointment, PermissionDeniedError } from "../authorization";
|
||||
import { getFirstFriendlyMessage } from "../error-messages";
|
||||
import { customerCancelSchema, customerRescheduleSchema } from "../schemas";
|
||||
|
||||
/**
|
||||
* Every mutation here re-checks ownership against the current session
|
||||
* before touching anything — never trusts that "the client only shows
|
||||
* this button for your own appointments" is actually true, since the
|
||||
* action can be called directly regardless of what the UI renders.
|
||||
*/
|
||||
|
||||
export interface CustomerAppointmentActionResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
wasLateCancellation?: boolean;
|
||||
}
|
||||
|
||||
export async function cancelCustomerAppointmentAction(input: unknown): Promise<CustomerAppointmentActionResult> {
|
||||
const parsed = customerCancelSchema.safeParse(input);
|
||||
if (!parsed.success) return { success: false, error: "Please try again." };
|
||||
|
||||
const appointment = await getAppointmentById(prisma, parsed.data.appointmentId);
|
||||
if (!appointment) return { success: false, error: "We couldn't find that appointment." };
|
||||
|
||||
const session = await auth();
|
||||
try {
|
||||
assertCanAccessAppointment(appointment, session?.user?.id);
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) return { success: false, error: error.message };
|
||||
throw error;
|
||||
}
|
||||
|
||||
const result = await cancelBooking(prisma, {
|
||||
appointmentId: parsed.data.appointmentId,
|
||||
cancelledByUserId: session?.user?.id,
|
||||
reason: parsed.data.reason,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return { success: false, error: getFirstFriendlyMessage(result.validation) };
|
||||
}
|
||||
|
||||
// Deliberately not revalidating here (unlike reschedule) — every affected
|
||||
// page is already `dynamic = "force-dynamic"`, so revalidatePath buys no
|
||||
// extra freshness, and doing it immediately would drop the cancelled
|
||||
// appointment out of the Upcoming list mid-render, unmounting this very
|
||||
// dialog before the customer can read the late-cancellation notice or
|
||||
// click "Done". The dialog's own onClose already calls router.refresh().
|
||||
return { success: true, wasLateCancellation: result.wasLateCancellation };
|
||||
}
|
||||
|
||||
export async function rescheduleCustomerAppointmentAction(input: unknown): Promise<CustomerAppointmentActionResult> {
|
||||
const parsed = customerRescheduleSchema.safeParse(input);
|
||||
if (!parsed.success) return { success: false, error: "Please choose a valid time." };
|
||||
|
||||
const appointment = await getAppointmentById(prisma, parsed.data.appointmentId);
|
||||
if (!appointment) return { success: false, error: "We couldn't find that appointment." };
|
||||
|
||||
const session = await auth();
|
||||
try {
|
||||
assertCanAccessAppointment(appointment, session?.user?.id);
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) return { success: false, error: error.message };
|
||||
throw error;
|
||||
}
|
||||
|
||||
const result = await rescheduleBooking(prisma, {
|
||||
appointmentId: parsed.data.appointmentId,
|
||||
staffId: parsed.data.staffId,
|
||||
startAt: new Date(parsed.data.startAt),
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return { success: false, error: getFirstFriendlyMessage(result.validation) };
|
||||
}
|
||||
|
||||
revalidatePath("/appointments");
|
||||
revalidatePath(`/appointments/${parsed.data.appointmentId}`);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { auth } from "@/auth";
|
||||
import { clearDraft, readDraft, writeDraft } from "@/lib/booking-draft/cookie";
|
||||
import { guestDetailsSchema } from "@/lib/booking-draft/schema";
|
||||
import { prisma } from "@/lib/db/prisma";
|
||||
import { getAppointmentById } from "@/services/scheduling/appointment.service";
|
||||
import { validateBookingSlot } from "@/services/scheduling/availability.service";
|
||||
import { assertCanAccessAppointment, PermissionDeniedError } from "../authorization";
|
||||
import { getFirstFriendlyMessage } from "../error-messages";
|
||||
import { saveBarberTimeStepSchema, saveDetailsStepSchema, saveServicesStepSchema, startRebookSchema } from "../schemas";
|
||||
|
||||
/**
|
||||
* Step-by-step booking draft actions. Each one: parses input, calls a
|
||||
* domain service where a real check is needed (never re-implements one),
|
||||
* persists the relevant slice of the draft, and redirects to the next
|
||||
* step. See src/lib/booking-draft for the storage mechanism.
|
||||
*/
|
||||
|
||||
export interface StepActionResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
fieldErrors?: Record<string, string[] | undefined>;
|
||||
}
|
||||
|
||||
export async function saveServicesStepAction(input: unknown): Promise<StepActionResult> {
|
||||
const parsed = saveServicesStepSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Please select at least one service.", fieldErrors: parsed.error.flatten().fieldErrors };
|
||||
}
|
||||
|
||||
const draft = await readDraft(parsed.data.businessId);
|
||||
const previousServiceIds = [...draft.serviceIds].sort().join(",");
|
||||
const nextServiceIds = [...parsed.data.serviceIds].sort().join(",");
|
||||
const servicesChanged = previousServiceIds !== nextServiceIds;
|
||||
|
||||
await writeDraft({
|
||||
...draft,
|
||||
businessId: parsed.data.businessId,
|
||||
serviceIds: parsed.data.serviceIds,
|
||||
// Changing the service selection can invalidate a previously chosen
|
||||
// slot (different duration), so clear it — but only if it actually
|
||||
// changed, so re-confirming the same services without edits doesn't
|
||||
// lose progress for no reason.
|
||||
...(servicesChanged ? { staffId: undefined, date: undefined, startAt: undefined } : {}),
|
||||
});
|
||||
|
||||
redirect("/book/barber-time");
|
||||
}
|
||||
|
||||
export async function saveBarberTimeStepAction(input: unknown): Promise<StepActionResult> {
|
||||
const parsed = saveBarberTimeStepSchema.safeParse(input);
|
||||
if (!parsed.success) return { success: false, error: "Please choose a valid time." };
|
||||
|
||||
const draft = await readDraft(parsed.data.businessId);
|
||||
if (draft.serviceIds.length === 0) {
|
||||
return { success: false, error: "Please select a service first." };
|
||||
}
|
||||
|
||||
// Only re-validate here when a specific barber was chosen — "any
|
||||
// available barber" is resolved to a specific one by BookingService
|
||||
// itself at confirm time (see booking.service.ts), and re-implementing
|
||||
// that resolution here just to pre-validate would duplicate its logic,
|
||||
// which the brief explicitly prohibits.
|
||||
if (parsed.data.staffId) {
|
||||
const { validation } = await validateBookingSlot(prisma, {
|
||||
businessId: parsed.data.businessId,
|
||||
serviceIds: draft.serviceIds,
|
||||
staffId: parsed.data.staffId,
|
||||
startAt: new Date(parsed.data.startAt),
|
||||
});
|
||||
if (!validation.valid) {
|
||||
return { success: false, error: getFirstFriendlyMessage(validation) };
|
||||
}
|
||||
}
|
||||
|
||||
await writeDraft({ ...draft, staffId: parsed.data.staffId, date: parsed.data.date, startAt: parsed.data.startAt });
|
||||
redirect("/book/details");
|
||||
}
|
||||
|
||||
export async function saveDetailsStepAction(input: unknown): Promise<StepActionResult> {
|
||||
const parsed = saveDetailsStepSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Please check the highlighted fields.", fieldErrors: parsed.error.flatten().fieldErrors };
|
||||
}
|
||||
|
||||
const draft = await readDraft(parsed.data.businessId);
|
||||
if (!draft.startAt) {
|
||||
return { success: false, error: "Please choose a date and time first." };
|
||||
}
|
||||
if (!parsed.data.policyAcknowledged) {
|
||||
return { success: false, error: "Please acknowledge the cancellation policy to continue." };
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user) {
|
||||
const guestParsed = guestDetailsSchema.safeParse({
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
email: parsed.data.email,
|
||||
phone: parsed.data.phone,
|
||||
});
|
||||
if (!guestParsed.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Please fill in your contact details.",
|
||||
fieldErrors: guestParsed.error.flatten().fieldErrors,
|
||||
};
|
||||
}
|
||||
await writeDraft({
|
||||
...draft,
|
||||
guest: guestParsed.data,
|
||||
notes: parsed.data.notes,
|
||||
policyAcknowledged: true,
|
||||
});
|
||||
} else {
|
||||
await writeDraft({
|
||||
...draft,
|
||||
guest: undefined,
|
||||
notes: parsed.data.notes,
|
||||
policyAcknowledged: true,
|
||||
});
|
||||
}
|
||||
|
||||
redirect("/book/review");
|
||||
}
|
||||
|
||||
export async function startRebookAction(input: unknown): Promise<void> {
|
||||
const parsed = startRebookSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
redirect("/appointments");
|
||||
}
|
||||
|
||||
const appointment = await getAppointmentById(prisma, parsed.data.appointmentId);
|
||||
if (!appointment) {
|
||||
redirect("/appointments");
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
try {
|
||||
assertCanAccessAppointment(appointment, session?.user?.id);
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
redirect("/appointments");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Only preselect services that are still active — an inactive service
|
||||
// can't be booked again, and the customer picks a fresh replacement
|
||||
// instead of silently having it dropped with no explanation.
|
||||
const activeServiceIds = appointment.services.filter((line) => line.service.isActive).map((line) => line.serviceId);
|
||||
|
||||
// Only preselect the original barber if they're still active and bookable online.
|
||||
const staffId = appointment.staff.status === "ACTIVE" && appointment.staff.isBookableOnline ? appointment.staffId : undefined;
|
||||
|
||||
await clearDraft();
|
||||
await writeDraft({
|
||||
businessId: appointment.businessId,
|
||||
serviceIds: activeServiceIds,
|
||||
staffId,
|
||||
policyAcknowledged: false,
|
||||
rebookFromAppointmentId: appointment.id,
|
||||
});
|
||||
|
||||
redirect("/book");
|
||||
}
|
||||
Reference in new issue
Block a user