119 lines
4.9 KiB
TypeScript
119 lines
4.9 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { getPayload } from "payload";
|
|
import config from "@payload-config";
|
|
import { getAvailableSlots } from "@/lib/booking/slots";
|
|
import { withBookingTransaction } from "@/lib/booking/transaction";
|
|
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
|
|
import { berlinDayBounds } from "@/lib/calendar/timezone";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
type Body = {
|
|
offerSlug?: unknown;
|
|
start?: unknown;
|
|
appointmentType?: unknown;
|
|
message?: unknown;
|
|
};
|
|
|
|
export async function POST(request: Request) {
|
|
let body: Body;
|
|
try {
|
|
body = await request.json();
|
|
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
|
|
} catch {
|
|
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
|
|
}
|
|
|
|
const offerSlug = typeof body.offerSlug === "string" ? body.offerSlug : "";
|
|
const startISO = typeof body.start === "string" ? body.start : "";
|
|
const appointmentType = body.appointmentType;
|
|
if (appointmentType !== "online" && appointmentType !== "onsite") return NextResponse.json({ error: "Ungültige Terminart." }, { status: 400 });
|
|
const message = typeof body.message === "string" ? body.message.trim().slice(0, 2000) : "";
|
|
|
|
if (!offerSlug || !startISO) {
|
|
return NextResponse.json({ error: "Angebot und Termin sind erforderlich." }, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
const payload = await getPayload({ config });
|
|
const { user } = await payload.auth({ headers: request.headers });
|
|
if (!user || user.collection !== "customers") {
|
|
return NextResponse.json({ error: "Bitte melde dich an, um einen Termin anzufragen." }, { status: 401 });
|
|
}
|
|
if (!user.emailVerified) {
|
|
return NextResponse.json({ error: "Bitte bestätige zuerst deine E-Mail-Adresse.", code: "EMAIL_NOT_VERIFIED" }, { status: 403 });
|
|
}
|
|
|
|
if (!checkRateLimit(`booking:ip:${getClientIp(request)}`, { max: 30, windowMs: 3600000 }) ||
|
|
!checkRateLimit(`booking:customer:${user.id}`, { max: 10, windowMs: 3600000 })) {
|
|
return NextResponse.json({ error: "Zu viele Terminanfragen. Bitte versuche es später erneut." }, { status: 429 });
|
|
}
|
|
|
|
const { docs } = await payload.find({
|
|
collection: "offers",
|
|
where: { slug: { equals: offerSlug } },
|
|
limit: 1,
|
|
overrideAccess: false,
|
|
});
|
|
const offer = docs[0];
|
|
if (!offer || !offer.bookable || !offer.durationMinutes) {
|
|
return NextResponse.json({ error: "Dieses Angebot ist nicht buchbar." }, { status: 404 });
|
|
}
|
|
|
|
const start = new Date(startISO);
|
|
if (Number.isNaN(start.getTime()) || start < new Date()) {
|
|
return NextResponse.json({ error: "Bitte wähle einen gültigen, zukünftigen Termin." }, { status: 400 });
|
|
}
|
|
const end = new Date(start.getTime() + offer.durationMinutes * 60_000);
|
|
|
|
// Re-validate the slot is actually free right now (defense against a
|
|
// stale slot list) - the hard, race-safe check still runs again when
|
|
// Anna confirms (see collections/BookingRequests.ts).
|
|
const dayBounds = berlinDayBounds(start);
|
|
return await withBookingTransaction(payload, dayBounds.key, async (req) => {
|
|
const { docs: existing } = await payload.find({ collection: "booking-requests", req, depth: 0, limit: 1,
|
|
where: { and: [
|
|
{ user: { equals: user.id } }, { offer: { equals: offer.id } },
|
|
{ startTime: { equals: start.toISOString() } }, { appointmentType: { equals: appointmentType } },
|
|
{ status: { in: ["pending", "confirmed"] } },
|
|
] },
|
|
});
|
|
if (existing[0]) return NextResponse.json({ ok: true });
|
|
const slotsByDay = await getAvailableSlots(payload, {
|
|
durationMinutes: offer.durationMinutes!,
|
|
req,
|
|
from: dayBounds.start,
|
|
to: dayBounds.end,
|
|
});
|
|
const key = dayBounds.key;
|
|
const isStillFree = (slotsByDay.get(key) ?? []).some((s) => s.start.getTime() === start.getTime());
|
|
if (!isStillFree) {
|
|
return NextResponse.json({ error: "Dieser Termin ist leider nicht mehr verfügbar." }, { status: 409 });
|
|
}
|
|
|
|
await payload.create({
|
|
collection: "booking-requests",
|
|
req,
|
|
data: {
|
|
user: user.id,
|
|
offer: offer.id,
|
|
date: start.toISOString(),
|
|
startTime: start.toISOString(),
|
|
endTime: end.toISOString(),
|
|
appointmentType,
|
|
// Calendar bookings use already published availability, so a slot
|
|
// selected here is booked immediately. The separate contact form
|
|
// remains the path for requests that need personal coordination.
|
|
status: "confirmed",
|
|
userMessage: message || undefined,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json({ ok: true });
|
|
});
|
|
} catch (error) {
|
|
console.error("booking request failed", error);
|
|
return NextResponse.json({ error: "Die Anfrage konnte nicht gesendet werden. Bitte versuche es später erneut." }, { status: 500 });
|
|
}
|
|
}
|