Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/admin-booking.server.ts
T

676 lines
21 KiB
TypeScript

import type {
AdminBooking,
Prisma,
PrismaClient,
} from "../generated/prisma/client/client.js";
import {
selectAdminBookingHost,
type AdminBookingRoundRobinCandidate,
} from "./admin-booking-round-robin.js";
import { writeAdminSalesAudit } from "./admin-sales-core.server.js";
import { publishOutboxEvent } from "./outbox.js";
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/u;
const MAX_NAME_LENGTH = 120;
const MAX_ANSWER_LENGTH = 4_000;
const DAY_MS = 86_400_000;
export type ReserveAdminBookingInput = {
readonly bookingPageId: string;
readonly startsAt: Date;
readonly endsAt: Date;
readonly bookerTimeZone: string;
readonly bookerFirstName: string;
readonly bookerLastName: string;
readonly bookerEmail: string;
readonly bookerLocale?: string | null;
readonly intakeAnswers: Readonly<Record<string, string>>;
readonly availableHostAdminUserIds: readonly string[];
readonly manualHostAdminUserId?: string | null;
readonly dealId?: string | null;
readonly idempotencyKey: string;
readonly manageTokenExpiresAt: Date;
readonly reschedule?: {
readonly previousBookingId: string;
readonly manageTokenVersion: number;
readonly manageTokenExpiresAfter: Date;
readonly manageNonceHash: string;
};
};
export type ReservedAdminBooking = {
readonly booking: AdminBooking;
readonly selectedHostAdminUserId: string;
readonly contactCreated: boolean;
};
export type AdminBookingRepository = {
reserve(input: ReserveAdminBookingInput): Promise<ReservedAdminBooking>;
};
export function createAdminBookingService(input: {
readonly repository: AdminBookingRepository;
}) {
return {
async reserve(command: ReserveAdminBookingInput) {
return input.repository.reserve(normalizeReservation(command));
},
};
}
type AdminBookingPrismaClient = Pick<
PrismaClient,
| "$transaction"
| "adminBooking"
| "adminBookingPage"
| "adminUser"
| "adminAvailabilityOverride"
| "adminBookingAssignment"
| "adminContact"
| "adminDeal"
>;
export function createPrismaAdminBookingRepository(
client: AdminBookingPrismaClient,
dependencies: { readonly now?: () => Date } = {}
): AdminBookingRepository {
const now = dependencies.now ?? (() => new Date());
return {
reserve: (command) =>
client.$transaction(
async (tx) => {
const existing = await tx.adminBooking.findUnique({
where: { idempotencyKey: command.idempotencyKey },
include: { assignment: true },
});
if (existing?.assignment) {
return {
booking: existing,
selectedHostAdminUserId:
existing.assignment.selectedHostAdminUserId,
contactCreated: false,
};
}
const page = await tx.adminBookingPage.findFirst({
where: {
id: command.bookingPageId,
published: true,
archivedAt: null,
meetingType: { active: true, archivedAt: null },
},
include: { meetingType: true },
});
if (!page) throw new AdminBookingError("page_unavailable");
assertPageRules(page, command, now());
const previousBooking = command.reschedule
? await tx.adminBooking.findFirst({
where: {
id: command.reschedule.previousBookingId,
bookingPageId: page.id,
status: {
in: [
"reserved",
"confirmed",
"provider_sync_failed",
],
},
manageTokenVersion:
command.reschedule.manageTokenVersion,
manageTokenExpiresAt: {
gt: command.reschedule.manageTokenExpiresAfter,
},
OR: [
{ lastManageNonceHash: null },
{
lastManageNonceHash: {
not: command.reschedule.manageNonceHash,
},
},
],
},
})
: null;
if (command.reschedule && !previousBooking) {
throw new AdminBookingError("booking_unavailable");
}
const candidatePool = await loadRoundRobinCandidates(tx, {
hostAdminUserIds: page.meetingType.hostAdminUserIds,
startsAt: command.startsAt,
endsAt: command.endsAt,
availableHostAdminUserIds:
command.availableHostAdminUserIds,
});
const selection = selectAdminBookingHost({
candidates: candidatePool.candidates,
availableHostAdminUserIds:
candidatePool.availableHostAdminUserIds,
manualHostAdminUserId: command.manualHostAdminUserId,
});
const selectedHostAdminUserId =
selection.selectedHostAdminUserId;
const slotReservationKey = [
selectedHostAdminUserId,
command.startsAt.toISOString(),
command.endsAt.toISOString(),
].join(":");
const [contactMatch, conflictingBooking, dailyCount] =
await Promise.all([
resolveBookingContact(tx, command),
tx.adminBooking.findFirst({
where: {
adminUserId: selectedHostAdminUserId,
status: {
in: ["reserved", "confirmed"],
},
startsAt: { lt: command.endsAt },
endsAt: { gt: command.startsAt },
},
select: { id: true },
}),
tx.adminBooking.count({
where: {
bookingPageId: page.id,
participants: {
some: { email: command.bookerEmail },
},
createdAt: {
gte: startOfUtcDay(now()),
lt: endOfUtcDay(now()),
},
status: { not: "cancelled" },
},
}),
]);
if (conflictingBooking) {
throw new AdminBookingError("slot_taken");
}
if (dailyCount >= page.maxBookingsPerEmailPerDay) {
throw new AdminBookingError("rate_limited");
}
if (command.dealId) {
await assertDealLink(tx, command.dealId, contactMatch.contact.id);
}
if (
previousBooking &&
previousBooking.contactId !== contactMatch.contact.id
) {
throw new AdminBookingError("booking_unavailable");
}
const booking = await tx.adminBooking.create({
data: {
adminUserId: selectedHostAdminUserId,
bookingPageId: page.id,
meetingTypeId: page.meetingType.id,
contactId: contactMatch.contact.id,
dealId: command.dealId,
startsAt: command.startsAt,
endsAt: command.endsAt,
bookerTimeZone: command.bookerTimeZone,
status: "reserved",
idempotencyKey: command.idempotencyKey,
slotReservationKey,
intakeAnswers:
command.intakeAnswers as Prisma.InputJsonValue,
manageTokenExpiresAt: command.manageTokenExpiresAt,
rescheduledFromId: previousBooking?.id,
participants: {
create: {
adminUserId: selectedHostAdminUserId,
email: command.bookerEmail,
name: `${command.bookerFirstName} ${command.bookerLastName}`,
locale: command.bookerLocale,
timeZone: command.bookerTimeZone,
isOrganizer: false,
},
},
assignment: {
create: {
adminUserId: selectedHostAdminUserId,
kind: command.manualHostAdminUserId
? "manual"
: "round_robin",
selectedHostAdminUserId,
overriddenByAdminUserId:
command.manualHostAdminUserId
? page.createdByAdminUserId
: null,
eligibleHostAdminUserIds: [
...selection.eligibleHostAdminUserIds,
],
excludedHosts:
selection.excludedHosts as unknown as Prisma.InputJsonValue,
loadSnapshot:
selection.loadSnapshot as unknown as Prisma.InputJsonValue,
selectionReason: selection.selectionReason,
},
},
reminders: {
create: page.meetingType.reminderOffsetsMinutes
.filter(
(offset) =>
command.startsAt.getTime() -
offset * 60_000 >
now().getTime()
)
.map((offset) => ({
adminUserId: selectedHostAdminUserId,
offsetMinutes: offset,
scheduledFor: new Date(
command.startsAt.getTime() - offset * 60_000
),
idempotencyKey: `${command.idempotencyKey}:reminder:${offset}`,
})),
},
},
});
if (previousBooking && command.reschedule) {
await tx.adminBooking.update({
where: { id: previousBooking.id },
data: {
status: "rescheduled",
manageTokenVersion: { increment: 1 },
lastManageNonceHash:
command.reschedule.manageNonceHash,
reminders: {
updateMany: {
where: {
status: { in: ["pending", "processing"] },
},
data: { status: "cancelled" },
},
},
},
});
}
await tx.adminActivity.create({
data: {
type: "meeting",
actorAdminUserId: page.createdByAdminUserId,
companyId: contactMatch.contact.companyId,
contactId: contactMatch.contact.id,
dealId: command.dealId,
bookingId: booking.id,
summary: previousBooking
? `${page.meetingType.name} umgebucht`
: `${page.meetingType.name} gebucht`,
payload: {
startsAt: command.startsAt.toISOString(),
endsAt: command.endsAt.toISOString(),
hostAdminUserId: selectedHostAdminUserId,
source: "public_booking_page",
...(previousBooking
? {
previousBookingId: previousBooking.id,
replacementBookingId: booking.id,
sequenceStopEvent: "booking_rescheduled",
}
: {}),
},
},
});
await publishOutboxEvent(tx, {
tenantId: null,
type: previousBooking
? "booking.provider.reschedule"
: "booking.provider.create",
dispatchKey: previousBooking
? `admin-booking:${previousBooking.id}:provider-reschedule:${booking.id}`
: `admin-booking:${booking.id}:provider-create`,
payload: previousBooking
? {
previousBookingId: previousBooking.id,
replacementBookingId: booking.id,
adminUserId: selectedHostAdminUserId,
}
: {
bookingId: booking.id,
adminUserId: selectedHostAdminUserId,
},
});
await writeAdminSalesAudit(tx, {
actor: {
adminUserId: page.createdByAdminUserId,
reason: "Öffentliche Terminbuchung",
},
action: previousBooking
? "admin.sales.booking.rescheduled"
: "admin.sales.booking.reserved",
targetType: "AdminBooking",
targetId: booking.id,
after: {
contactId: contactMatch.contact.id,
dealId: command.dealId,
startsAt: command.startsAt.toISOString(),
selectedHostAdminUserId,
assignmentKind: command.manualHostAdminUserId
? "manual"
: "round_robin",
...(previousBooking
? { previousBookingId: previousBooking.id }
: {}),
},
});
return {
booking,
selectedHostAdminUserId,
contactCreated: contactMatch.created,
};
},
{ isolationLevel: "Serializable" }
),
};
}
async function loadRoundRobinCandidates(
tx: Prisma.TransactionClient,
input: {
readonly hostAdminUserIds: readonly string[];
readonly startsAt: Date;
readonly endsAt: Date;
readonly availableHostAdminUserIds: readonly string[];
}
): Promise<{
readonly candidates: readonly AdminBookingRoundRobinCandidate[];
readonly availableHostAdminUserIds: readonly string[];
}> {
const date = new Date(
Date.UTC(
input.startsAt.getUTCFullYear(),
input.startsAt.getUTCMonth(),
input.startsAt.getUTCDate()
)
);
const [users, absences, activeLoads, lastAssignments, conflicts] =
await Promise.all([
tx.adminUser.findMany({
where: {
id: { in: [...input.hostAdminUserIds] },
status: "active",
roles: {
some: {
role: {
active: true,
permissions: {
some: {
permission: {
name: "admin_sales.booking.manage",
},
},
},
},
},
},
},
select: { id: true },
}),
tx.adminAvailabilityOverride.findMany({
where: {
adminUserId: { in: [...input.hostAdminUserIds] },
date,
kind: "unavailable",
archivedAt: null,
},
select: { adminUserId: true },
}),
tx.adminBooking.groupBy({
by: ["adminUserId"],
where: {
adminUserId: { in: [...input.hostAdminUserIds] },
status: { in: ["reserved", "confirmed"] },
startsAt: { gte: input.startsAt },
},
_count: { _all: true },
}),
tx.adminBookingAssignment.groupBy({
by: ["selectedHostAdminUserId"],
where: {
selectedHostAdminUserId: {
in: [...input.hostAdminUserIds],
},
},
_max: { createdAt: true },
}),
tx.adminBooking.findMany({
where: {
adminUserId: { in: [...input.hostAdminUserIds] },
status: { in: ["reserved", "confirmed"] },
startsAt: { lt: input.endsAt },
endsAt: { gt: input.startsAt },
},
select: { adminUserId: true },
}),
]);
const eligible = new Set(users.map((user) => user.id));
const absent = new Set(absences.map((item) => item.adminUserId));
const conflicted = new Set(
conflicts.map((item) => item.adminUserId)
);
const available = new Set(
input.availableHostAdminUserIds.filter(
(adminUserId) => !conflicted.has(adminUserId)
)
);
const loadByHost = new Map(
activeLoads.map((item) => [
item.adminUserId,
item._count._all,
])
);
const lastByHost = new Map(
lastAssignments.map((item) => [
item.selectedHostAdminUserId,
item._max.createdAt,
])
);
return {
candidates: input.hostAdminUserIds.map((adminUserId) => ({
adminUserId,
eligible: eligible.has(adminUserId),
absent: absent.has(adminUserId),
activeBookingCount: loadByHost.get(adminUserId) ?? 0,
lastAssignedAt: lastByHost.get(adminUserId) ?? null,
})),
availableHostAdminUserIds: [...available],
};
}
async function resolveBookingContact(
tx: Prisma.TransactionClient,
command: ReserveAdminBookingInput
): Promise<{
readonly contact: {
readonly id: string;
readonly companyId: string | null;
};
readonly created: boolean;
}> {
const matches = await tx.adminContact.findMany({
where: {
normalizedEmail: command.bookerEmail,
archivedAt: null,
},
select: { id: true, companyId: true },
take: 2,
});
if (matches.length > 1) {
throw new AdminBookingError("contact_ambiguous");
}
if (matches[0]) return { contact: matches[0], created: false };
const contact = await tx.adminContact.create({
data: {
firstName: command.bookerFirstName,
lastName: command.bookerLastName,
email: command.bookerEmail,
normalizedEmail: command.bookerEmail,
locale: command.bookerLocale,
timeZone: command.bookerTimeZone,
},
select: { id: true, companyId: true },
});
return { contact, created: true };
}
async function assertDealLink(
tx: Prisma.TransactionClient,
dealId: string,
contactId: string
): Promise<void> {
const deal = await tx.adminDeal.findFirst({
where: {
id: dealId,
status: "open",
archivedAt: null,
contacts: { some: { contactId } },
},
select: { id: true },
});
if (!deal) throw new AdminBookingError("deal_unavailable");
}
function assertPageRules(
page: {
readonly allowedEmailDomains: readonly string[];
readonly meetingType: { readonly durationMinutes: number };
},
command: ReserveAdminBookingInput,
now: Date
): void {
if (command.startsAt <= now || command.endsAt <= command.startsAt) {
throw new AdminBookingError("invalid_slot");
}
if (
command.endsAt.getTime() - command.startsAt.getTime() !==
page.meetingType.durationMinutes * 60_000
) {
throw new AdminBookingError("invalid_slot");
}
const domain = command.bookerEmail.split("@")[1];
if (
page.allowedEmailDomains.length > 0 &&
!page.allowedEmailDomains.includes(domain)
) {
throw new AdminBookingError("email_domain_denied");
}
}
function normalizeReservation(
command: ReserveAdminBookingInput
): ReserveAdminBookingInput {
const bookerEmail = command.bookerEmail.trim().toLowerCase();
if (!EMAIL_PATTERN.test(bookerEmail)) {
throw new AdminBookingError("invalid_email");
}
const firstName = normalizeName(command.bookerFirstName);
const lastName = normalizeName(command.bookerLastName);
assertTimeZone(command.bookerTimeZone);
if (
!command.idempotencyKey.trim() ||
command.idempotencyKey.length > 200 ||
command.manageTokenExpiresAt.getTime() <= command.startsAt.getTime()
) {
throw new AdminBookingError("invalid_request");
}
if (
command.reschedule &&
(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/u.test(
command.reschedule.previousBookingId
) ||
!Number.isSafeInteger(command.reschedule.manageTokenVersion) ||
command.reschedule.manageTokenVersion < 1 ||
!Number.isFinite(
command.reschedule.manageTokenExpiresAfter.getTime()
) ||
!/^[a-f0-9]{64}$/u.test(
command.reschedule.manageNonceHash
))
) {
throw new AdminBookingError("invalid_request");
}
const intakeAnswers = Object.fromEntries(
Object.entries(command.intakeAnswers).map(([key, value]) => {
const normalizedKey = key.trim();
const normalizedValue = value.trim();
if (
!normalizedKey ||
normalizedKey.length > 80 ||
normalizedValue.length > MAX_ANSWER_LENGTH
) {
throw new AdminBookingError("invalid_answers");
}
return [normalizedKey, normalizedValue];
})
);
return {
...command,
bookerFirstName: firstName,
bookerLastName: lastName,
bookerEmail,
bookerLocale: command.bookerLocale?.trim() || null,
intakeAnswers,
availableHostAdminUserIds: [
...new Set(command.availableHostAdminUserIds),
],
manualHostAdminUserId:
command.manualHostAdminUserId?.trim() || null,
dealId: command.dealId?.trim() || null,
idempotencyKey: command.idempotencyKey.trim(),
};
}
function normalizeName(value: string): string {
const normalized = value.trim().replace(/\s+/gu, " ");
if (!normalized || normalized.length > MAX_NAME_LENGTH) {
throw new AdminBookingError("invalid_name");
}
return normalized;
}
function assertTimeZone(timeZone: string): void {
try {
new Intl.DateTimeFormat("de-DE", { timeZone }).format(new Date());
} catch {
throw new AdminBookingError("invalid_time_zone");
}
}
function startOfUtcDay(value: Date): Date {
return new Date(
Date.UTC(
value.getUTCFullYear(),
value.getUTCMonth(),
value.getUTCDate()
)
);
}
function endOfUtcDay(value: Date): Date {
return new Date(startOfUtcDay(value).getTime() + DAY_MS);
}
export class AdminBookingError extends Error {
readonly code:
| "invalid_email"
| "invalid_name"
| "invalid_time_zone"
| "invalid_request"
| "invalid_answers"
| "page_unavailable"
| "invalid_slot"
| "email_domain_denied"
| "contact_ambiguous"
| "deal_unavailable"
| "booking_unavailable"
| "slot_taken"
| "rate_limited";
constructor(code: AdminBookingError["code"]) {
super(code);
this.name = "AdminBookingError";
this.code = code;
}
}