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
@@ -45,8 +45,18 @@ export function RegisterForm() {
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input label="First Name" placeholder="Alex" error={errors.firstName?.message} {...register("firstName")} />
|
||||
<Input label="Last Name" placeholder="Chen" error={errors.lastName?.message} {...register("lastName")} />
|
||||
<Input
|
||||
label="First Name"
|
||||
placeholder="Alex"
|
||||
error={errors.firstName?.message}
|
||||
{...register("firstName")}
|
||||
/>
|
||||
<Input
|
||||
label="Last Name"
|
||||
placeholder="Chen"
|
||||
error={errors.lastName?.message}
|
||||
{...register("lastName")}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
label="Email Address"
|
||||
@@ -78,23 +88,30 @@ export function RegisterForm() {
|
||||
/>
|
||||
|
||||
{formError && (
|
||||
<p role="alert" className="text-sm font-medium text-red-500">
|
||||
<p role="alert" className="text-danger text-sm font-medium">
|
||||
{formError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<p className="px-1 text-[10px] leading-relaxed text-muted">
|
||||
By creating an account, you agree to our <a href="#" className="underline">Terms of Service</a> and{" "}
|
||||
<a href="#" className="underline">Privacy Policy</a>.
|
||||
<p className="text-muted px-1 text-[10px] leading-relaxed">
|
||||
By creating an account, you agree to our{" "}
|
||||
<a href="#" className="underline">
|
||||
Terms of Service
|
||||
</a>{" "}
|
||||
and{" "}
|
||||
<a href="#" className="underline">
|
||||
Privacy Policy
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
|
||||
<Button type="submit" className="mt-4 w-full" isLoading={isSubmitting}>
|
||||
Sign Up
|
||||
</Button>
|
||||
|
||||
<p className="mt-10 text-center text-sm text-muted">
|
||||
<p className="text-muted mt-10 text-center text-sm">
|
||||
Already have an account?{" "}
|
||||
<Link href="/sign-in" className="border-b border-ink font-bold text-ink">
|
||||
<Link href="/sign-in" className="border-ink text-ink border-b font-bold">
|
||||
Log in
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@@ -60,7 +60,7 @@ export function SignInForm() {
|
||||
when that lands; no dead link to it here in the meantime. */}
|
||||
|
||||
{formError && (
|
||||
<p role="alert" className="text-sm font-medium text-red-500">
|
||||
<p role="alert" className="text-danger text-sm font-medium">
|
||||
{formError}
|
||||
</p>
|
||||
)}
|
||||
@@ -73,25 +73,25 @@ export function SignInForm() {
|
||||
<div className="mt-10">
|
||||
<div className="relative mb-8 flex items-center justify-center">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-line" />
|
||||
<div className="border-line w-full border-t" />
|
||||
</div>
|
||||
<span className="relative bg-stone px-4 text-[10px] font-bold uppercase tracking-widest text-muted">
|
||||
<span className="bg-stone text-muted relative px-4 text-[10px] font-bold tracking-widest uppercase">
|
||||
Or continue with
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="w-full normal-case tracking-normal"
|
||||
className="w-full tracking-normal normal-case"
|
||||
onClick={() => signIn("google", { callbackUrl })}
|
||||
>
|
||||
Continue with Google
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="mt-10 text-center text-sm text-muted">
|
||||
<p className="text-muted mt-10 text-center text-sm">
|
||||
Don't have an account?{" "}
|
||||
<Link href="/register" className="border-b-2 border-ink font-bold text-ink">
|
||||
<Link href="/register" className="border-ink text-ink border-b-2 font-bold">
|
||||
Create one
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@@ -8,7 +8,7 @@ export function SignOutButton() {
|
||||
return (
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full text-red-500 hover:bg-red-50"
|
||||
className="text-danger hover:bg-danger/10 w-full"
|
||||
onClick={() => signOut({ callbackUrl: "/" })}
|
||||
>
|
||||
<LogOut className="h-4 w-4" aria-hidden="true" />
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PermissionDeniedError, assertCanAccessAppointment, canAccessAppointment } from "../authorization";
|
||||
|
||||
describe("assertCanAccessAppointment", () => {
|
||||
it("allows a registered customer to access their own appointment", () => {
|
||||
expect(() =>
|
||||
assertCanAccessAppointment({ customer: { userId: "user_1" } }, "user_1"),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("denies a different signed-in user from accessing a registered customer's appointment", () => {
|
||||
expect(() => assertCanAccessAppointment({ customer: { userId: "user_1" } }, "user_2")).toThrow(
|
||||
PermissionDeniedError,
|
||||
);
|
||||
});
|
||||
|
||||
it("denies an unauthenticated caller from accessing a registered customer's appointment", () => {
|
||||
expect(() => assertCanAccessAppointment({ customer: { userId: "user_1" } }, undefined)).toThrow(
|
||||
PermissionDeniedError,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows access to a guest appointment (no linked user) regardless of session — the documented guest access model", () => {
|
||||
expect(() => assertCanAccessAppointment({ customer: { userId: null } }, undefined)).not.toThrow();
|
||||
expect(() => assertCanAccessAppointment({ customer: { userId: null } }, "some_other_user")).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("canAccessAppointment", () => {
|
||||
it("mirrors assertCanAccessAppointment as a boolean", () => {
|
||||
expect(canAccessAppointment({ customer: { userId: "user_1" } }, "user_1")).toBe(true);
|
||||
expect(canAccessAppointment({ customer: { userId: "user_1" } }, "user_2")).toBe(false);
|
||||
expect(canAccessAppointment({ customer: { userId: null } }, undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,422 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { Weekday } from "@/generated/prisma/enums";
|
||||
import { addDays, todayIn, wallClockToInstant, weekdayOf } from "@/lib/time/business-time";
|
||||
import type { CalendarDate } from "@/lib/time/business-time";
|
||||
import { cancelBooking, createBooking, rescheduleBooking } from "@/services/scheduling/booking.service";
|
||||
import { listAppointments } from "@/services/scheduling/appointment.service";
|
||||
import {
|
||||
cleanupTestBusiness,
|
||||
createTestBusiness,
|
||||
createTestCustomer,
|
||||
createTestGuestCustomer,
|
||||
createTestStaff,
|
||||
prisma,
|
||||
} from "@/services/scheduling/__tests__/fixtures";
|
||||
import type { TestBusiness } from "@/services/scheduling/__tests__/fixtures";
|
||||
import { resolveCustomerForBooking } from "@/services/customer/customer.service";
|
||||
import { assertCanAccessAppointment, canAccessAppointment, PermissionDeniedError } from "@/features/booking/authorization";
|
||||
import { getFirstFriendlyMessage } from "@/features/booking/error-messages";
|
||||
|
||||
/**
|
||||
* Covers the customer-facing booking journeys added in Phase 4 — guest
|
||||
* identity resolution, ownership enforcement, and the "book again"
|
||||
* repricing rule — against a real database. Deliberately exercises the
|
||||
* domain services directly (CustomerService, BookingService,
|
||||
* AppointmentService, authorization.ts), the same layer Phase 3's suite
|
||||
* tests: the Server Actions above them are thin orchestration (collect
|
||||
* input, call these, map errors), verified instead by the Playwright
|
||||
* journeys.
|
||||
*/
|
||||
|
||||
function nextWeekday(timezone: string, target: Weekday, minDaysAhead = 7): CalendarDate {
|
||||
let date = addDays(todayIn(timezone), minDaysAhead);
|
||||
for (let i = 0; i < 8; i++) {
|
||||
if (weekdayOf(date) === target) return date;
|
||||
date = addDays(date, 1);
|
||||
}
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
|
||||
describe("customer booking flows (integration)", () => {
|
||||
let business: TestBusiness;
|
||||
let monday: CalendarDate;
|
||||
let guestProfileIds: string[];
|
||||
|
||||
beforeEach(async () => {
|
||||
business = await createTestBusiness();
|
||||
monday = nextWeekday(business.timezone, Weekday.MONDAY);
|
||||
guestProfileIds = [];
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (guestProfileIds.length > 0) {
|
||||
await prisma.customerProfile.deleteMany({ where: { id: { in: guestProfileIds } } }).catch(() => {});
|
||||
}
|
||||
await cleanupTestBusiness(business);
|
||||
});
|
||||
|
||||
describe("guest booking", () => {
|
||||
it("creates a new guest CustomerProfile and books under it", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const guest = { firstName: "Jordan", lastName: "Blake", email: "Jordan.Blake@Example.com", phone: "+44 7700 900111" };
|
||||
|
||||
const resolved = await resolveCustomerForBooking(prisma, { businessId: business.businessId, guest });
|
||||
guestProfileIds.push(resolved.customerId);
|
||||
expect(resolved.isNewProfile).toBe(true);
|
||||
|
||||
const result = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: resolved.customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (!result.success) return;
|
||||
expect(result.appointment.customer.isGuest).toBe(true);
|
||||
expect(result.appointment.customer.userId).toBeNull();
|
||||
// Stored lowercased even though the caller typed mixed case.
|
||||
expect(result.appointment.customer.email).toBe("jordan.blake@example.com");
|
||||
});
|
||||
|
||||
it("reuses an existing guest profile when email and phone both match, without overwriting its stored name", async () => {
|
||||
const existing = await createTestGuestCustomer({ email: "sam.reed@example.com", phone: "+44 7700 900222" });
|
||||
guestProfileIds.push(existing.customerId);
|
||||
|
||||
const resolved = await resolveCustomerForBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
// Different casing on the email, but same identifiers — should still match.
|
||||
guest: { firstName: "Samuel", lastName: "Reed", email: "SAM.REED@example.com", phone: existing.phone },
|
||||
});
|
||||
|
||||
expect(resolved.isNewProfile).toBe(false);
|
||||
expect(resolved.customerId).toBe(existing.customerId);
|
||||
|
||||
const profile = await prisma.customerProfile.findUniqueOrThrow({ where: { id: existing.customerId } });
|
||||
expect(profile.firstName).toBe("Guest"); // unchanged — reuse never overwrites on match
|
||||
});
|
||||
|
||||
it("never merges two guests who share only one identifier — creates a separate profile instead", async () => {
|
||||
const existing = await createTestGuestCustomer({ email: "shared.inbox@example.com", phone: "+44 7700 900333" });
|
||||
guestProfileIds.push(existing.customerId);
|
||||
|
||||
// Same email (shared household inbox), different phone — must not be treated as the same person.
|
||||
const resolved = await resolveCustomerForBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
guest: { firstName: "Different", lastName: "Person", email: existing.email, phone: "+44 7700 900444" },
|
||||
});
|
||||
guestProfileIds.push(resolved.customerId);
|
||||
|
||||
expect(resolved.isNewProfile).toBe(true);
|
||||
expect(resolved.customerId).not.toBe(existing.customerId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("authenticated booking", () => {
|
||||
it("books under the caller's own profile and is idempotent across repeated calls", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId, userId } = await createTestCustomer(business);
|
||||
|
||||
const resolvedAgain = await resolveCustomerForBooking(prisma, { businessId: business.businessId, userId });
|
||||
expect(resolvedAgain.isNewProfile).toBe(false);
|
||||
expect(resolvedAgain.customerId).toBe(customerId);
|
||||
|
||||
const result = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (!result.success) return;
|
||||
expect(result.appointment.customer.userId).toBe(userId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("multi-service, specific-barber booking", () => {
|
||||
it("books both selected services with one specific barber", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId } = await createTestCustomer(business);
|
||||
|
||||
const result = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId, business.beardTrimServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (!result.success) return;
|
||||
expect(result.appointment.staffId).toBe(staffId);
|
||||
expect(result.appointment.services.map((s) => s.serviceId).sort()).toEqual(
|
||||
[business.haircutServiceId, business.beardTrimServiceId].sort(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("any-barber booking", () => {
|
||||
it("auto-assigns whichever eligible barber is less busy that day", async () => {
|
||||
const { staffId: busyStaffId } = await createTestStaff(business);
|
||||
const { staffId: freeStaffId } = await createTestStaff(business);
|
||||
const { customerId } = await createTestCustomer(business);
|
||||
|
||||
// Give the first barber an existing appointment that day so the second is strictly less busy.
|
||||
const existing = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId: busyStaffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 9 * 60, business.timezone),
|
||||
});
|
||||
expect(existing.success).toBe(true);
|
||||
|
||||
const anyBarber = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
// staffId omitted — "any available barber"
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 11 * 60, business.timezone),
|
||||
});
|
||||
|
||||
expect(anyBarber.success).toBe(true);
|
||||
if (!anyBarber.success) return;
|
||||
expect(anyBarber.appointment.staffId).toBe(freeStaffId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("slot becomes unavailable before confirmation", () => {
|
||||
it("rejects the second confirmation with a customer-friendly message once someone else has taken the slot", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId: customerAId } = await createTestCustomer(business);
|
||||
const { customerId: customerBId } = await createTestCustomer(business);
|
||||
const startAt = wallClockToInstant(monday, 10 * 60, business.timezone);
|
||||
|
||||
// Customer B confirms first, while customer A's draft still points at the same slot.
|
||||
const first = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: customerBId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt,
|
||||
});
|
||||
expect(first.success).toBe(true);
|
||||
|
||||
const second = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: customerAId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt,
|
||||
});
|
||||
|
||||
expect(second.success).toBe(false);
|
||||
if (second.success) return;
|
||||
expect(getFirstFriendlyMessage(second.validation)).toBe(
|
||||
"That time was just booked by someone else — please choose another.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("customer appointment retrieval", () => {
|
||||
it("only returns the requesting customer's own appointments, filtered by status", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId: ownCustomerId } = await createTestCustomer(business);
|
||||
const { customerId: otherCustomerId } = await createTestCustomer(business);
|
||||
|
||||
const confirmed = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: ownCustomerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 9 * 60, business.timezone),
|
||||
});
|
||||
expect(confirmed.success).toBe(true);
|
||||
|
||||
const othersAppointment = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: otherCustomerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 11 * 60, business.timezone),
|
||||
});
|
||||
expect(othersAppointment.success).toBe(true);
|
||||
|
||||
const upcoming = await listAppointments(prisma, {
|
||||
customerId: ownCustomerId,
|
||||
statuses: ["PENDING", "CONFIRMED"],
|
||||
});
|
||||
expect(upcoming).toHaveLength(1);
|
||||
expect(upcoming[0]!.customerId).toBe(ownCustomerId);
|
||||
|
||||
const cancelledList = await listAppointments(prisma, { customerId: ownCustomerId, statuses: ["CANCELLED"] });
|
||||
expect(cancelledList).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancellation", () => {
|
||||
it("a guest can cancel their own booking without a cancelledByUserId", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const guest = await createTestGuestCustomer();
|
||||
guestProfileIds.push(guest.customerId);
|
||||
|
||||
const created = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: guest.customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
if (!created.success) throw new Error("setup failed");
|
||||
|
||||
const result = await cancelBooking(prisma, { appointmentId: created.appointment.id, reason: "Can't make it" });
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.appointment?.status).toBe("CANCELLED");
|
||||
expect(result.appointment?.cancelledByUserId).toBeNull();
|
||||
expect(result.appointment?.cancellationReason).toBe("Can't make it");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rescheduling", () => {
|
||||
it("supports moving to a different barber, not just a different time", async () => {
|
||||
const { staffId: originalStaffId } = await createTestStaff(business);
|
||||
const { staffId: newStaffId } = await createTestStaff(business);
|
||||
const { customerId } = await createTestCustomer(business);
|
||||
|
||||
const created = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId: originalStaffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
if (!created.success) throw new Error("setup failed");
|
||||
|
||||
const rescheduled = await rescheduleBooking(prisma, {
|
||||
appointmentId: created.appointment.id,
|
||||
staffId: newStaffId,
|
||||
startAt: wallClockToInstant(monday, 14 * 60, business.timezone),
|
||||
});
|
||||
|
||||
expect(rescheduled.success).toBe(true);
|
||||
if (!rescheduled.success) return;
|
||||
expect(rescheduled.appointment.staffId).toBe(newStaffId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("book again", () => {
|
||||
it("reprices at the current service price, never the old completed appointment's snapshot", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId } = await createTestCustomer(business);
|
||||
|
||||
const original = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId], // £20 at the time of fixtures.ts
|
||||
startAt: wallClockToInstant(monday, 9 * 60, business.timezone),
|
||||
});
|
||||
if (!original.success) throw new Error("setup failed");
|
||||
await prisma.appointment.update({ where: { id: original.appointment.id }, data: { status: "COMPLETED" } });
|
||||
expect(Number(original.appointment.services[0]!.priceAtBooking)).toBe(20);
|
||||
|
||||
// Price goes up before the customer books again.
|
||||
await prisma.service.update({ where: { id: business.haircutServiceId }, data: { price: 35 } });
|
||||
|
||||
const tuesday = addDays(monday, 1);
|
||||
const rebooked = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(tuesday, 9 * 60, business.timezone),
|
||||
});
|
||||
|
||||
expect(rebooked.success).toBe(true);
|
||||
if (!rebooked.success) return;
|
||||
// The new booking snapshots today's price, not the £20 from the completed appointment.
|
||||
expect(Number(rebooked.appointment.services[0]!.priceAtBooking)).toBe(35);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ownership enforcement", () => {
|
||||
it("a registered customer's appointment is only accessible to that exact session user", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId, userId: ownerUserId } = await createTestCustomer(business);
|
||||
const { userId: strangerUserId } = await createTestCustomer(business);
|
||||
|
||||
const created = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
if (!created.success) throw new Error("setup failed");
|
||||
|
||||
expect(() => assertCanAccessAppointment(created.appointment, ownerUserId)).not.toThrow();
|
||||
expect(() => assertCanAccessAppointment(created.appointment, strangerUserId)).toThrow(PermissionDeniedError);
|
||||
expect(() => assertCanAccessAppointment(created.appointment, undefined)).toThrow(PermissionDeniedError);
|
||||
expect(canAccessAppointment(created.appointment, strangerUserId)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat the appointment id alone as permission — an unrelated session cannot claim it", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const { customerId, userId: ownerUserId } = await createTestCustomer(business);
|
||||
|
||||
const created = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 10 * 60, business.timezone),
|
||||
});
|
||||
if (!created.success) throw new Error("setup failed");
|
||||
|
||||
expect(created.appointment.customer.userId).toBe(ownerUserId);
|
||||
const randomOtherId = "some-other-user-id-that-is-not-the-owner";
|
||||
expect(canAccessAppointment(created.appointment, randomOtherId)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("guest data isolation", () => {
|
||||
it("keeps two guests' profiles and appointments completely separate", async () => {
|
||||
const { staffId } = await createTestStaff(business);
|
||||
const guestA = await createTestGuestCustomer();
|
||||
const guestB = await createTestGuestCustomer();
|
||||
guestProfileIds.push(guestA.customerId, guestB.customerId);
|
||||
|
||||
const apptA = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: guestA.customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 9 * 60, business.timezone),
|
||||
});
|
||||
const apptB = await createBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
customerId: guestB.customerId,
|
||||
staffId,
|
||||
serviceIds: [business.haircutServiceId],
|
||||
startAt: wallClockToInstant(monday, 11 * 60, business.timezone),
|
||||
});
|
||||
expect(apptA.success).toBe(true);
|
||||
expect(apptB.success).toBe(true);
|
||||
|
||||
const guestAAppointments = await listAppointments(prisma, { customerId: guestA.customerId });
|
||||
expect(guestAAppointments).toHaveLength(1);
|
||||
expect(guestAAppointments[0]!.customerId).toBe(guestA.customerId);
|
||||
|
||||
// Resolving guest A's own details again must never return guest B's profile.
|
||||
const resolvedA = await resolveCustomerForBooking(prisma, {
|
||||
businessId: business.businessId,
|
||||
guest: { firstName: "Guest", lastName: "Customer", email: guestA.email, phone: guestA.phone },
|
||||
});
|
||||
expect(resolvedA.customerId).toBe(guestA.customerId);
|
||||
expect(resolvedA.customerId).not.toBe(guestB.customerId);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BOOKING_VALIDATION_ERROR_CODES } from "@/services/scheduling/types";
|
||||
import { getFirstFriendlyMessage, getFriendlyMessage, getFriendlyValidationMessages } from "../error-messages";
|
||||
|
||||
describe("getFriendlyMessage", () => {
|
||||
it("has a specific, non-empty message for every code the domain layer can produce", () => {
|
||||
for (const code of BOOKING_VALIDATION_ERROR_CODES) {
|
||||
const message = getFriendlyMessage(code);
|
||||
expect(message.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("never leaks the raw code into the message", () => {
|
||||
for (const code of BOOKING_VALIDATION_ERROR_CODES) {
|
||||
expect(getFriendlyMessage(code)).not.toContain(code);
|
||||
}
|
||||
});
|
||||
|
||||
it("gives SLOT_UNAVAILABLE a message that doesn't sound like an internal error", () => {
|
||||
expect(getFriendlyMessage("SLOT_UNAVAILABLE").toLowerCase()).toContain("booked");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFriendlyValidationMessages", () => {
|
||||
it("maps every issue in a validation result", () => {
|
||||
const messages = getFriendlyValidationMessages({
|
||||
valid: false,
|
||||
issues: [
|
||||
{ code: "STAFF_ON_BREAK", message: "internal" },
|
||||
{ code: "BELOW_MIN_NOTICE", message: "internal" },
|
||||
],
|
||||
});
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages[0]).toBe(getFriendlyMessage("STAFF_ON_BREAK"));
|
||||
expect(messages[1]).toBe(getFriendlyMessage("BELOW_MIN_NOTICE"));
|
||||
});
|
||||
|
||||
it("returns an empty array for a valid result", () => {
|
||||
expect(getFriendlyValidationMessages({ valid: true, issues: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFirstFriendlyMessage", () => {
|
||||
it("returns the first issue's friendly message", () => {
|
||||
const message = getFirstFriendlyMessage({
|
||||
valid: false,
|
||||
issues: [
|
||||
{ code: "BUSINESS_CLOSED", message: "internal" },
|
||||
{ code: "STAFF_ON_LEAVE", message: "internal" },
|
||||
],
|
||||
});
|
||||
expect(message).toBe(getFriendlyMessage("BUSINESS_CLOSED"));
|
||||
});
|
||||
|
||||
it("falls back gracefully when there are no issues", () => {
|
||||
expect(getFirstFriendlyMessage({ valid: true, issues: [] })).toMatch(/went wrong/i);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Customer-facing ownership checks. Kept in the feature/action layer, not
|
||||
* the domain services — AppointmentService/BookingService are also used
|
||||
* by (future) staff/owner tooling, where an entirely different
|
||||
* permission rule applies ("any staff member in this business"). This
|
||||
* file is specifically "can THIS customer touch THIS appointment", so it
|
||||
* lives next to the customer-facing actions that need it, per Phase 2's
|
||||
* "permission enforcement happens again at the server-action layer"
|
||||
* principle.
|
||||
*/
|
||||
|
||||
export class PermissionDeniedError extends Error {
|
||||
constructor(message = "You don't have permission to access this appointment.") {
|
||||
super(message);
|
||||
this.name = "PermissionDeniedError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface OwnableAppointment {
|
||||
customer: { userId: string | null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Ownership rule:
|
||||
* - A REGISTERED customer's appointment (customer.userId is set) always
|
||||
* requires the requesting session to match that exact user. An
|
||||
* appointment id alone is never sufficient — see the Phase 4 brief's
|
||||
* explicit "Appointment IDs are not treated as permission".
|
||||
* - A GUEST appointment (customer.userId is null) has no stronger
|
||||
* credential available in this phase — no magic-link/OTP system was
|
||||
* built (explicitly deferred, see docs/phase-4-summary.md). Access is
|
||||
* by the appointment's own unguessable id, the same "order tracking"
|
||||
* pattern many guest-checkout systems use. This is a deliberate,
|
||||
* documented scope limitation, not an oversight.
|
||||
*/
|
||||
export function assertCanAccessAppointment(appointment: OwnableAppointment, sessionUserId: string | undefined): void {
|
||||
if (appointment.customer.userId && appointment.customer.userId !== sessionUserId) {
|
||||
throw new PermissionDeniedError();
|
||||
}
|
||||
}
|
||||
|
||||
export function canAccessAppointment(appointment: OwnableAppointment, sessionUserId: string | undefined): boolean {
|
||||
try {
|
||||
assertCanAccessAppointment(appointment, sessionUserId);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { MonthCalendar } from "@/components/ui/month-calendar";
|
||||
import { Select } from "@/components/ui/select";
|
||||
import { EmptyState } from "@/components/feedback/empty-state";
|
||||
import { CardSkeleton } from "@/components/feedback/skeleton";
|
||||
import { CalendarX2 } from "lucide-react";
|
||||
import {
|
||||
getAvailableBarbersAction,
|
||||
getAvailableDatesAction,
|
||||
getAvailableTimeSlotsAction,
|
||||
} from "../actions/availability";
|
||||
|
||||
interface Staff {
|
||||
id: string;
|
||||
name: string;
|
||||
avatarUrl: string | null;
|
||||
}
|
||||
interface TimeSlot {
|
||||
startMinutes: number;
|
||||
startAt: string;
|
||||
endAt: string;
|
||||
staffOptions: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Local calendar-date components, not `.toISOString().slice(0, 10)` — that
|
||||
* converts to UTC first, which silently shifts the date back a day for
|
||||
* anyone in a timezone ahead of UTC (e.g. the business's own Europe/London
|
||||
* during BST). `date` here is always local midnight from MonthCalendar's
|
||||
* own `new Date(year, month, day)`, so reading the local parts back out is
|
||||
* the correct inverse.
|
||||
*/
|
||||
function toYMD(date: Date): string {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interactive barber/date/time core, shared between the booking flow
|
||||
* (/book/barber-time) and rescheduling (/appointments/[id]/reschedule) —
|
||||
* per the Phase 4 brief's explicit instruction to reuse this selection UI
|
||||
* rather than building it twice. All availability comes from the Phase 3
|
||||
* AvailabilityService via the existing Server Actions; nothing here
|
||||
* computes a slot itself.
|
||||
*/
|
||||
export function BarberDateTimePicker(props: {
|
||||
businessId: string;
|
||||
businessTimezone: string;
|
||||
serviceIds: string[];
|
||||
initialStaffId?: string;
|
||||
initialDate?: string;
|
||||
onContinue: (selection: {
|
||||
staffId?: string;
|
||||
date: string;
|
||||
startAt: string;
|
||||
}) => Promise<{ success: boolean; error?: string }>;
|
||||
continueLabel?: string;
|
||||
}) {
|
||||
const {
|
||||
businessId,
|
||||
businessTimezone,
|
||||
serviceIds,
|
||||
initialStaffId,
|
||||
initialDate,
|
||||
onContinue,
|
||||
continueLabel = "Continue",
|
||||
} = props;
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const [staffOptions, setStaffOptions] = useState<Staff[]>([]);
|
||||
const [selectedStaffId, setSelectedStaffId] = useState<string>(initialStaffId ?? "any");
|
||||
const [month, setMonth] = useState(() =>
|
||||
initialDate ? new Date(`${initialDate}T00:00:00`) : new Date(),
|
||||
);
|
||||
const [availableDates, setAvailableDates] = useState<Set<string>>(new Set());
|
||||
const [selectedDate, setSelectedDate] = useState<Date | undefined>(
|
||||
initialDate ? new Date(`${initialDate}T00:00:00`) : undefined,
|
||||
);
|
||||
const [slots, setSlots] = useState<TimeSlot[]>([]);
|
||||
const [selectedSlot, setSelectedSlot] = useState<TimeSlot | undefined>();
|
||||
const [slotsPending, startSlotsTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getAvailableBarbersAction({ businessId, serviceIds }).then((res) => setStaffOptions(res.staff));
|
||||
}, [businessId, serviceIds]);
|
||||
|
||||
useEffect(() => {
|
||||
const from = new Date(month.getFullYear(), month.getMonth(), 1);
|
||||
const to = new Date(month.getFullYear(), month.getMonth() + 1, 0);
|
||||
getAvailableDatesAction({
|
||||
businessId,
|
||||
serviceIds,
|
||||
staffId: selectedStaffId === "any" ? undefined : selectedStaffId,
|
||||
fromDate: toYMD(from),
|
||||
toDate: toYMD(to),
|
||||
}).then((res) => setAvailableDates(new Set(res.dates)));
|
||||
}, [businessId, serviceIds, month, selectedStaffId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedDate) return;
|
||||
// The fetch (and every state update it produces) runs inside the
|
||||
// transition callback, after an `await` — not synchronously at the
|
||||
// top of the effect body — so this stays clear of the
|
||||
// set-state-in-effect pitfall while still giving us a pending flag.
|
||||
startSlotsTransition(async () => {
|
||||
const res = await getAvailableTimeSlotsAction({
|
||||
businessId,
|
||||
serviceIds,
|
||||
staffId: selectedStaffId === "any" ? undefined : selectedStaffId,
|
||||
date: toYMD(selectedDate),
|
||||
});
|
||||
setSlots(res.slots);
|
||||
setSelectedSlot(undefined);
|
||||
});
|
||||
}, [businessId, serviceIds, selectedDate, selectedStaffId]);
|
||||
const effectiveSlots = !selectedDate ? EMPTY_SLOTS : slots;
|
||||
|
||||
const handleContinue = () => {
|
||||
if (!selectedDate || !selectedSlot) return;
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await onContinue({
|
||||
staffId: selectedStaffId === "any" ? undefined : selectedStaffId,
|
||||
date: toYMD(selectedDate),
|
||||
startAt: selectedSlot.startAt,
|
||||
});
|
||||
if (!result.success) setError(result.error ?? "Please choose a different time.");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="pb-32">
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
<section className="px-6">
|
||||
<h2 className="text-muted mb-3 text-xs font-bold tracking-widest uppercase">Barber</h2>
|
||||
<Select
|
||||
value={selectedStaffId}
|
||||
onChange={(e) => {
|
||||
setSelectedStaffId(e.target.value);
|
||||
setSelectedDate(undefined);
|
||||
}}
|
||||
>
|
||||
<option value="any">Anyone available</option>
|
||||
{staffOptions.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</section>
|
||||
|
||||
<section className="px-6">
|
||||
<h2 className="text-muted mb-3 text-xs font-bold tracking-widest uppercase">Date</h2>
|
||||
<MonthCalendar
|
||||
month={month}
|
||||
onMonthChange={setMonth}
|
||||
selectedDate={selectedDate}
|
||||
onSelectDate={setSelectedDate}
|
||||
isDateDisabled={(date) => !availableDates.has(toYMD(date))}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{selectedDate && (
|
||||
<section className="px-6">
|
||||
<h2 className="text-muted mb-3 text-xs font-bold tracking-widest uppercase">Time</h2>
|
||||
{slotsPending ? (
|
||||
<CardSkeleton />
|
||||
) : effectiveSlots.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={CalendarX2}
|
||||
title="No times available"
|
||||
description="Try a different date or barber."
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{effectiveSlots.map((slot) => (
|
||||
<button
|
||||
key={slot.startAt}
|
||||
type="button"
|
||||
onClick={() => setSelectedSlot(slot)}
|
||||
aria-pressed={selectedSlot?.startAt === slot.startAt}
|
||||
className={
|
||||
selectedSlot?.startAt === slot.startAt
|
||||
? "border-accent bg-accent/10 rounded-xl border-2 px-5 py-3 text-sm font-bold"
|
||||
: "border-line hover:border-ink rounded-xl border bg-white px-5 py-3 text-sm font-medium"
|
||||
}
|
||||
>
|
||||
{new Date(slot.startAt).toLocaleTimeString("en-GB", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: businessTimezone,
|
||||
})}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-line fixed inset-x-0 bottom-0 z-40 border-t bg-white/95 px-6 py-4 backdrop-blur">
|
||||
<div className="mx-auto max-w-2xl">
|
||||
{error && (
|
||||
<p role="alert" className="text-danger mb-3 text-sm font-medium">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={handleContinue}
|
||||
isLoading={isPending}
|
||||
disabled={!selectedSlot}
|
||||
>
|
||||
{continueLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const EMPTY_SLOTS: TimeSlot[] = [];
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { startRebookAction } from "../actions/draft";
|
||||
|
||||
export function BookAgainButton({ appointmentId, className }: { appointmentId: string; className?: string }) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={className}
|
||||
isLoading={isPending}
|
||||
onClick={() => startTransition(() => startRebookAction({ appointmentId }))}
|
||||
>
|
||||
Book Again
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/modal";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { cancelCustomerAppointmentAction } from "../actions/customer-appointments";
|
||||
|
||||
export function CancelAppointmentDialog({ appointmentId }: { appointmentId: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [reason, setReason] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<{ wasLateCancellation?: boolean } | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const router = useRouter();
|
||||
|
||||
const handleConfirm = () => {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const res = await cancelCustomerAppointmentAction({
|
||||
appointmentId,
|
||||
reason: reason || undefined,
|
||||
});
|
||||
if (!res.success) {
|
||||
setError(res.error ?? "Something went wrong. Please try again.");
|
||||
return;
|
||||
}
|
||||
setResult({ wasLateCancellation: res.wasLateCancellation });
|
||||
});
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
setResult(null);
|
||||
setReason("");
|
||||
setError(null);
|
||||
if (result) router.refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="destructive" size="sm" onClick={() => setOpen(true)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
title={result ? "Appointment Cancelled" : "Cancel Appointment?"}
|
||||
>
|
||||
{result ? (
|
||||
<div className="space-y-4">
|
||||
<p role="status" className="text-muted text-sm">
|
||||
Your appointment has been cancelled. It won't be deleted from your history.
|
||||
</p>
|
||||
{result.wasLateCancellation && (
|
||||
<p className="border-warning/30 bg-warning/10 text-warning-foreground rounded-lg border p-3 text-xs">
|
||||
This was a late cancellation, outside the free-cancellation window. The business may
|
||||
apply a late-cancellation policy.
|
||||
</p>
|
||||
)}
|
||||
<Button className="w-full" onClick={handleClose}>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<p className="text-muted text-sm">
|
||||
This can't be undone. You can add an optional reason below.
|
||||
</p>
|
||||
<Textarea
|
||||
placeholder="Reason (optional)"
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" className="text-danger text-sm font-medium">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-3">
|
||||
<Button variant="secondary" className="flex-1" onClick={handleClose}>
|
||||
Keep it
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="flex-1"
|
||||
onClick={handleConfirm}
|
||||
isLoading={isPending}
|
||||
>
|
||||
Cancel it
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { confirmBookingAction } from "../actions/confirm";
|
||||
|
||||
export function ConfirmBookingButton({ businessId }: { businessId: string }) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const handleConfirm = () => {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await confirmBookingAction(businessId);
|
||||
if (!result.success) setError(result.error ?? "Something went wrong. Please try again.");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{error && (
|
||||
<p role="alert" className="text-danger mb-3 text-sm font-medium">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button className="w-full" onClick={handleConfirm} isLoading={isPending}>
|
||||
Confirm Booking
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useState, useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { saveDetailsStepAction } from "../actions/draft";
|
||||
|
||||
const guestFormSchema = z.object({
|
||||
firstName: z.string().trim().min(1, "First name is required"),
|
||||
lastName: z.string().trim().min(1, "Last name is required"),
|
||||
email: z.email("Enter a valid email address"),
|
||||
phone: z.string().trim().min(1, "Phone number is required"),
|
||||
notes: z.string().max(2000).optional(),
|
||||
policyAcknowledged: z.literal(true, { error: "Please acknowledge the cancellation policy" }),
|
||||
});
|
||||
|
||||
const authenticatedFormSchema = z.object({
|
||||
notes: z.string().max(2000).optional(),
|
||||
policyAcknowledged: z.literal(true, { error: "Please acknowledge the cancellation policy" }),
|
||||
});
|
||||
|
||||
export function DetailsForm(props: {
|
||||
businessId: string;
|
||||
cancellationPolicy?: string;
|
||||
isAuthenticated: boolean;
|
||||
prefill?: { firstName: string; lastName: string; email: string; phone: string };
|
||||
initialNotes?: string;
|
||||
}) {
|
||||
const { businessId, cancellationPolicy, isAuthenticated, prefill, initialNotes } = props;
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const schema = isAuthenticated ? authenticatedFormSchema : guestFormSchema;
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setError,
|
||||
formState: { errors },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} = useForm<any>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
firstName: prefill?.firstName ?? "",
|
||||
lastName: prefill?.lastName ?? "",
|
||||
email: prefill?.email ?? "",
|
||||
phone: prefill?.phone ?? "",
|
||||
notes: initialNotes ?? "",
|
||||
policyAcknowledged: false,
|
||||
},
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const onSubmit = (data: any) => {
|
||||
setServerError(null);
|
||||
startTransition(async () => {
|
||||
const result = await saveDetailsStepAction({ businessId, ...data });
|
||||
if (!result.success) {
|
||||
setServerError(result.error ?? "Please check the highlighted fields.");
|
||||
if (result.fieldErrors) {
|
||||
for (const [field, messages] of Object.entries(result.fieldErrors)) {
|
||||
if (messages?.[0]) setError(field, { message: messages[0] });
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
noValidate
|
||||
className="mx-auto max-w-2xl space-y-6 px-6 py-6"
|
||||
>
|
||||
{!isAuthenticated && (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="First Name"
|
||||
error={errors.firstName?.message as string}
|
||||
{...register("firstName")}
|
||||
/>
|
||||
<Input
|
||||
label="Last Name"
|
||||
error={errors.lastName?.message as string}
|
||||
{...register("lastName")}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
label="Email Address"
|
||||
type="email"
|
||||
error={errors.email?.message as string}
|
||||
{...register("email")}
|
||||
/>
|
||||
<Input
|
||||
label="Phone Number"
|
||||
type="tel"
|
||||
error={errors.phone?.message as string}
|
||||
{...register("phone")}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAuthenticated && prefill && (
|
||||
<div className="rounded-jumbo border-line border bg-white p-5">
|
||||
<p className="text-muted text-[10px] font-bold tracking-widest uppercase">Booking as</p>
|
||||
<p className="mt-1 text-sm font-bold">
|
||||
{prefill.firstName} {prefill.lastName}
|
||||
</p>
|
||||
<p className="text-muted text-xs">
|
||||
{prefill.email}
|
||||
{prefill.phone ? ` · ${prefill.phone}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Textarea
|
||||
label="Booking Notes (optional)"
|
||||
placeholder="e.g. skin sensitivity, specific style requests…"
|
||||
error={errors.notes?.message as string}
|
||||
{...register("notes")}
|
||||
/>
|
||||
|
||||
{cancellationPolicy && (
|
||||
<div className="border-line text-muted rounded-xl border bg-white p-4 text-xs">
|
||||
{cancellationPolicy}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Checkbox label="I acknowledge the cancellation policy" {...register("policyAcknowledged")} />
|
||||
{errors.policyAcknowledged && (
|
||||
<p role="alert" className="text-danger -mt-4 text-xs font-medium">
|
||||
{errors.policyAcknowledged.message as string}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{serverError && (
|
||||
<p role="alert" className="text-danger text-sm font-medium">
|
||||
{serverError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" isLoading={isPending}>
|
||||
Continue to Review
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
"use client";
|
||||
|
||||
import { Plus, Check } from "lucide-react";
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TopNav } from "@/components/navigation/top-nav";
|
||||
import { saveServicesStepAction } from "../actions/draft";
|
||||
import type { AvailableService } from "@/services/scheduling/availability.service";
|
||||
|
||||
export function ServiceSelector(props: {
|
||||
businessId: string;
|
||||
services: AvailableService[];
|
||||
categoryNames: Record<string, string>;
|
||||
categoryOrder: string[];
|
||||
initialSelectedServiceIds: string[];
|
||||
rebooking: boolean;
|
||||
}) {
|
||||
const {
|
||||
businessId,
|
||||
services,
|
||||
categoryNames,
|
||||
categoryOrder,
|
||||
initialSelectedServiceIds,
|
||||
rebooking,
|
||||
} = props;
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>(initialSelectedServiceIds);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const byCategory = new Map<string, AvailableService[]>();
|
||||
for (const service of services) {
|
||||
const list = byCategory.get(service.categoryId) ?? [];
|
||||
list.push(service);
|
||||
byCategory.set(service.categoryId, list);
|
||||
}
|
||||
const orderedIds = [...categoryOrder, ...byCategory.keys()].filter(
|
||||
(id, i, arr) => arr.indexOf(id) === i,
|
||||
);
|
||||
return orderedIds
|
||||
.map((id) => ({
|
||||
id,
|
||||
name: categoryNames[id] ?? "Services",
|
||||
services: byCategory.get(id) ?? [],
|
||||
}))
|
||||
.filter((g) => g.services.length > 0);
|
||||
}, [services, categoryNames, categoryOrder]);
|
||||
|
||||
const selectedServices = services.filter((s) => selectedIds.includes(s.id));
|
||||
const totalDuration = selectedServices.reduce((sum, s) => sum + s.durationMinutes, 0);
|
||||
const totalPrice = selectedServices.reduce((sum, s) => sum + Number(s.price), 0);
|
||||
|
||||
const toggle = (id: string) => {
|
||||
setSelectedIds((prev) => (prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id]));
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await saveServicesStepAction({ businessId, serviceIds: selectedIds });
|
||||
if (!result.success) setError(result.error ?? "Please select at least one service.");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="pb-32">
|
||||
<TopNav title="Select Services" onBack={true} sticky className="bg-stone" />
|
||||
|
||||
{rebooking && (
|
||||
<div className="border-accent/30 bg-accent/10 text-ink mx-6 mt-4 rounded-xl border p-3 text-xs">
|
||||
Booking again — we've preselected your previous services. Prices and availability are
|
||||
current, not from your last visit.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<main className="mx-auto max-w-2xl space-y-8 px-6 py-6">
|
||||
{grouped.map((group) => (
|
||||
<section key={group.id}>
|
||||
<h2 className="mb-3 text-sm font-bold">{group.name}</h2>
|
||||
<div className="divide-line rounded-jumbo border-line divide-y border bg-white">
|
||||
{group.services.map((service) => {
|
||||
const selected = selectedIds.includes(service.id);
|
||||
return (
|
||||
<button
|
||||
key={service.id}
|
||||
type="button"
|
||||
onClick={() => toggle(service.id)}
|
||||
aria-pressed={selected}
|
||||
className="flex w-full items-center justify-between gap-4 px-5 py-4 text-left"
|
||||
>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-sm font-medium">{service.name}</h3>
|
||||
<p className="text-muted mt-1 text-xs">{service.durationMinutes}m</p>
|
||||
</div>
|
||||
<span className="font-bold">£{Number(service.price).toFixed(2)}</span>
|
||||
<span
|
||||
className={
|
||||
selected
|
||||
? "bg-accent flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-white"
|
||||
: "border-line text-muted flex h-8 w-8 shrink-0 items-center justify-center rounded-full border"
|
||||
}
|
||||
>
|
||||
{selected ? (
|
||||
<Check className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
{grouped.length === 0 && (
|
||||
<p className="text-muted text-sm">No services are available online right now.</p>
|
||||
)}
|
||||
</main>
|
||||
|
||||
<div className="border-line fixed inset-x-0 bottom-0 z-40 border-t bg-white/95 px-6 py-4 backdrop-blur">
|
||||
<div className="mx-auto max-w-2xl">
|
||||
{error && (
|
||||
<p role="alert" className="text-danger mb-3 text-sm font-medium">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-muted text-xs font-bold tracking-widest uppercase">
|
||||
{selectedServices.length} selected · {totalDuration}m
|
||||
</p>
|
||||
<p className="text-xl font-semibold">£{totalPrice.toFixed(2)}</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
isLoading={isPending}
|
||||
disabled={selectedIds.length === 0}
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { BookingValidationErrorCode, ValidationResult } from "@/services/scheduling/types";
|
||||
|
||||
/**
|
||||
* Maps the typed error codes the Phase 3 services already return into
|
||||
* customer-friendly copy. The only place raw codes get translated —
|
||||
* every booking-flow page imports from here rather than inlining its own
|
||||
* message strings, so the wording only needs to change in one place.
|
||||
*/
|
||||
const FRIENDLY_MESSAGES: Record<BookingValidationErrorCode, string> = {
|
||||
INVALID_INPUT: "Something about that wasn't quite right. Please try again.",
|
||||
NO_SERVICES_SELECTED: "Please select at least one service.",
|
||||
SERVICES_SPAN_MULTIPLE_BUSINESSES: "One or more selected services aren't available here.",
|
||||
STAFF_CANNOT_PERFORM_SERVICE: "This barber doesn't offer one of the selected services.",
|
||||
BUSINESS_CLOSED: "The business is closed at this time — please choose another slot.",
|
||||
STAFF_NOT_WORKING: "This barber isn't working at that time — please choose another slot or barber.",
|
||||
STAFF_ON_BREAK: "This barber is on a break at that time — please choose another slot.",
|
||||
STAFF_ON_LEAVE: "This barber is away on that date — please choose another barber or date.",
|
||||
SLOT_UNAVAILABLE: "That time was just booked by someone else — please choose another.",
|
||||
INSUFFICIENT_DURATION:
|
||||
"There isn't enough time left that day for the selected services — try an earlier time or fewer services.",
|
||||
BELOW_MIN_NOTICE: "This time is too soon — please choose a later time.",
|
||||
BEYOND_MAX_ADVANCE: "This date is too far ahead to book yet — please choose a nearer date.",
|
||||
BUSINESS_DAILY_LIMIT_REACHED: "This business is fully booked that day — please choose another date.",
|
||||
STAFF_DAILY_LIMIT_REACHED: "This barber is fully booked that day — please choose another barber or date.",
|
||||
APPOINTMENT_NOT_FOUND: "We couldn't find that appointment.",
|
||||
INVALID_STATUS_TRANSITION: "This appointment can no longer be changed.",
|
||||
STAFF_NOT_FOUND: "We couldn't find that barber.",
|
||||
CUSTOMER_NOT_FOUND: "We couldn't find your customer details.",
|
||||
BUSINESS_NOT_FOUND: "We couldn't find this business.",
|
||||
};
|
||||
|
||||
const FALLBACK_MESSAGE = "Something went wrong with this booking. Please try again.";
|
||||
|
||||
export function getFriendlyMessage(code: BookingValidationErrorCode): string {
|
||||
return FRIENDLY_MESSAGES[code] ?? FALLBACK_MESSAGE;
|
||||
}
|
||||
|
||||
export function getFriendlyValidationMessages(validation: ValidationResult): string[] {
|
||||
if (validation.issues.length === 0) return [];
|
||||
return validation.issues.map((issue) => getFriendlyMessage(issue.code));
|
||||
}
|
||||
|
||||
export function getFirstFriendlyMessage(validation: ValidationResult): string {
|
||||
const [first] = validation.issues;
|
||||
return first ? getFriendlyMessage(first.code) : FALLBACK_MESSAGE;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ export const rescheduleBookingSchema = z.object({
|
||||
|
||||
export const cancelBookingSchema = z.object({
|
||||
appointmentId: z.string(),
|
||||
cancelledByUserId: z.string(),
|
||||
cancelledByUserId: z.string().optional(),
|
||||
reason: z.string().optional(),
|
||||
});
|
||||
|
||||
@@ -58,3 +58,42 @@ export const updateBookingNotesSchema = z.object({
|
||||
appointmentId: z.string(),
|
||||
notes: z.string().max(2000),
|
||||
});
|
||||
|
||||
// ── Customer booking-flow draft steps ────────────────────────────────────
|
||||
|
||||
export const saveServicesStepSchema = z.object({
|
||||
businessId: z.string(),
|
||||
serviceIds: z.array(z.string()).min(1, "Select at least one service"),
|
||||
});
|
||||
|
||||
export const saveBarberTimeStepSchema = z.object({
|
||||
businessId: z.string(),
|
||||
staffId: z.string().optional(),
|
||||
date: z.string(),
|
||||
startAt: z.iso.datetime(),
|
||||
});
|
||||
|
||||
export const saveDetailsStepSchema = z.object({
|
||||
businessId: z.string(),
|
||||
firstName: z.string().trim().min(1, "First name is required").optional(),
|
||||
lastName: z.string().trim().min(1, "Last name is required").optional(),
|
||||
email: z.email("Enter a valid email address").optional(),
|
||||
phone: z.string().trim().min(1, "Phone number is required").optional(),
|
||||
notes: z.string().max(2000).optional(),
|
||||
policyAcknowledged: z.boolean(),
|
||||
});
|
||||
|
||||
export const startRebookSchema = z.object({
|
||||
appointmentId: z.string(),
|
||||
});
|
||||
|
||||
export const customerCancelSchema = z.object({
|
||||
appointmentId: z.string(),
|
||||
reason: z.string().max(500).optional(),
|
||||
});
|
||||
|
||||
export const customerRescheduleSchema = z.object({
|
||||
appointmentId: z.string(),
|
||||
staffId: z.string().optional(),
|
||||
startAt: z.iso.datetime(),
|
||||
});
|
||||
Reference in new issue
Block a user