653 lines
19 KiB
TypeScript
653 lines
19 KiB
TypeScript
import type {
|
|
AdminAvailabilityOverride,
|
|
AdminAvailabilityRule,
|
|
AdminBookingPage,
|
|
AdminMeetingType,
|
|
Prisma,
|
|
PrismaClient,
|
|
} from "../generated/prisma/client/client.js";
|
|
import type { AdminPermissionName } from "./admin-permissions.js";
|
|
import {
|
|
type AdminSalesActor,
|
|
writeAdminSalesAudit,
|
|
} from "./admin-sales-core.server.js";
|
|
|
|
const MAX_NAME_LENGTH = 120;
|
|
const MAX_DESCRIPTION_LENGTH = 2_000;
|
|
const MAX_QUESTION_COUNT = 20;
|
|
|
|
export const DEFAULT_ADMIN_MEETING_TYPES = Object.freeze([
|
|
Object.freeze({
|
|
name: "Erstgespräch",
|
|
slug: "erstgespraech",
|
|
durationMinutes: 30,
|
|
}),
|
|
Object.freeze({
|
|
name: "Demo",
|
|
slug: "demo",
|
|
durationMinutes: 45,
|
|
}),
|
|
]);
|
|
|
|
export type AdminMeetingQuestion = {
|
|
readonly key: string;
|
|
readonly label: string;
|
|
readonly type: "short_text" | "long_text" | "single_select";
|
|
readonly required: boolean;
|
|
readonly options?: readonly string[];
|
|
};
|
|
|
|
export type SaveAdminMeetingTypeInput = {
|
|
readonly id?: string | null;
|
|
readonly name: string;
|
|
readonly slug: string;
|
|
readonly description?: string | null;
|
|
readonly durationMinutes: number;
|
|
readonly bufferBeforeMinutes: number;
|
|
readonly bufferAfterMinutes: number;
|
|
readonly slotIncrementMinutes: number;
|
|
readonly minimumNoticeMinutes: number;
|
|
readonly bookingHorizonDays: number;
|
|
readonly hostAdminUserIds: readonly string[];
|
|
readonly intakeQuestions: readonly AdminMeetingQuestion[];
|
|
readonly reminderOffsetsMinutes: readonly number[];
|
|
readonly active: boolean;
|
|
readonly actor: AdminSalesActor;
|
|
};
|
|
|
|
export type ReplaceAdminAvailabilityInput = {
|
|
readonly adminUserId: string;
|
|
readonly timeZone: string;
|
|
readonly rules: readonly {
|
|
readonly dayOfWeek:
|
|
| "monday"
|
|
| "tuesday"
|
|
| "wednesday"
|
|
| "thursday"
|
|
| "friday"
|
|
| "saturday"
|
|
| "sunday";
|
|
readonly startMinutes: number;
|
|
readonly endMinutes: number;
|
|
}[];
|
|
readonly overrides: readonly {
|
|
readonly date: Date;
|
|
readonly kind: "unavailable" | "custom_window";
|
|
readonly startMinutes?: number | null;
|
|
readonly endMinutes?: number | null;
|
|
readonly reason?: string | null;
|
|
}[];
|
|
readonly actor: AdminSalesActor;
|
|
};
|
|
|
|
export type SaveAdminBookingPageInput = {
|
|
readonly id?: string | null;
|
|
readonly meetingTypeId: string;
|
|
readonly slug: string;
|
|
readonly title: string;
|
|
readonly description?: string | null;
|
|
readonly published: boolean;
|
|
readonly maxBookingsPerEmailPerDay: number;
|
|
readonly actor: AdminSalesActor;
|
|
};
|
|
|
|
export type AdminBookingSettingsRepository = {
|
|
saveMeetingType(
|
|
input: SaveAdminMeetingTypeInput
|
|
): Promise<AdminMeetingType>;
|
|
replaceAvailability(
|
|
input: ReplaceAdminAvailabilityInput
|
|
): Promise<{
|
|
readonly rules: readonly AdminAvailabilityRule[];
|
|
readonly overrides: readonly AdminAvailabilityOverride[];
|
|
}>;
|
|
saveBookingPage(input: SaveAdminBookingPageInput): Promise<AdminBookingPage>;
|
|
};
|
|
|
|
export function createAdminBookingSettingsService(input: {
|
|
readonly repository: AdminBookingSettingsRepository;
|
|
readonly authorize: (
|
|
permission: AdminPermissionName
|
|
) => Promise<void> | void;
|
|
}) {
|
|
return {
|
|
async saveMeetingType(command: SaveAdminMeetingTypeInput) {
|
|
await input.authorize("admin_sales.booking.manage");
|
|
return input.repository.saveMeetingType(normalizeMeetingType(command));
|
|
},
|
|
|
|
async replaceOwnAvailability(command: ReplaceAdminAvailabilityInput) {
|
|
await input.authorize("admin_sales.booking.manage");
|
|
const normalized = normalizeAvailability(command);
|
|
if (normalized.adminUserId !== normalized.actor.adminUserId) {
|
|
throw new AdminBookingSettingsError("owner_mismatch");
|
|
}
|
|
return input.repository.replaceAvailability(normalized);
|
|
},
|
|
|
|
async saveBookingPage(command: SaveAdminBookingPageInput) {
|
|
await input.authorize("admin_sales.booking.manage");
|
|
return input.repository.saveBookingPage(normalizeBookingPage(command));
|
|
},
|
|
};
|
|
}
|
|
|
|
type AdminBookingSettingsPrismaClient = Pick<
|
|
PrismaClient,
|
|
| "$transaction"
|
|
| "adminUser"
|
|
| "adminMeetingType"
|
|
| "adminBookingPage"
|
|
| "adminAvailabilityRule"
|
|
| "adminAvailabilityOverride"
|
|
>;
|
|
|
|
export function createPrismaAdminBookingSettingsRepository(
|
|
client: AdminBookingSettingsPrismaClient
|
|
): AdminBookingSettingsRepository {
|
|
return {
|
|
saveMeetingType: (command) =>
|
|
client.$transaction(async (tx) => {
|
|
const eligibleHosts = await tx.adminUser.findMany({
|
|
where: {
|
|
id: { in: [...command.hostAdminUserIds] },
|
|
status: "active",
|
|
roles: {
|
|
some: {
|
|
role: {
|
|
active: true,
|
|
permissions: {
|
|
some: {
|
|
permission: {
|
|
name: "admin_sales.booking.manage",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
select: { id: true },
|
|
});
|
|
if (eligibleHosts.length !== command.hostAdminUserIds.length) {
|
|
throw new AdminBookingSettingsError("host_ineligible");
|
|
}
|
|
const data = {
|
|
createdByAdminUserId: command.actor.adminUserId,
|
|
name: command.name,
|
|
slug: command.slug,
|
|
description: command.description,
|
|
durationMinutes: command.durationMinutes,
|
|
bufferBeforeMinutes: command.bufferBeforeMinutes,
|
|
bufferAfterMinutes: command.bufferAfterMinutes,
|
|
slotIncrementMinutes: command.slotIncrementMinutes,
|
|
minimumNoticeMinutes: command.minimumNoticeMinutes,
|
|
bookingHorizonDays: command.bookingHorizonDays,
|
|
hostAdminUserIds: [...command.hostAdminUserIds],
|
|
intakeQuestions:
|
|
command.intakeQuestions as unknown as Prisma.InputJsonValue,
|
|
reminderOffsetsMinutes: [...command.reminderOffsetsMinutes],
|
|
active: command.active,
|
|
archivedAt: null,
|
|
};
|
|
const meetingType = command.id
|
|
? await tx.adminMeetingType.update({
|
|
where: { id: command.id },
|
|
data,
|
|
})
|
|
: await tx.adminMeetingType.create({ data });
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "configuration_changed",
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
summary: "Meeting-Typ konfiguriert",
|
|
payload: {
|
|
meetingTypeId: meetingType.id,
|
|
hostCount: command.hostAdminUserIds.length,
|
|
},
|
|
},
|
|
});
|
|
await writeAdminSalesAudit(tx, {
|
|
actor: command.actor,
|
|
action: command.id
|
|
? "admin.sales.meeting_type.updated"
|
|
: "admin.sales.meeting_type.created",
|
|
targetType: "AdminMeetingType",
|
|
targetId: meetingType.id,
|
|
after: {
|
|
name: meetingType.name,
|
|
durationMinutes: meetingType.durationMinutes,
|
|
hostAdminUserIds: meetingType.hostAdminUserIds,
|
|
},
|
|
});
|
|
return meetingType;
|
|
}),
|
|
|
|
saveBookingPage: (command) =>
|
|
client.$transaction(async (tx) => {
|
|
const meetingType = await tx.adminMeetingType.findFirst({
|
|
where: {
|
|
id: command.meetingTypeId,
|
|
active: true,
|
|
archivedAt: null,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
if (!meetingType) {
|
|
throw new AdminBookingSettingsError("meeting_type_unavailable");
|
|
}
|
|
const data = {
|
|
createdByAdminUserId: command.actor.adminUserId,
|
|
meetingTypeId: command.meetingTypeId,
|
|
slug: command.slug,
|
|
title: command.title,
|
|
description: command.description,
|
|
published: command.published,
|
|
maxBookingsPerEmailPerDay:
|
|
command.maxBookingsPerEmailPerDay,
|
|
archivedAt: null,
|
|
};
|
|
const page = command.id
|
|
? await tx.adminBookingPage.update({
|
|
where: { id: command.id },
|
|
data,
|
|
})
|
|
: await tx.adminBookingPage.create({ data });
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "configuration_changed",
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
summary: "Buchungsseite konfiguriert",
|
|
payload: {
|
|
bookingPageId: page.id,
|
|
published: page.published,
|
|
},
|
|
},
|
|
});
|
|
await writeAdminSalesAudit(tx, {
|
|
actor: command.actor,
|
|
action: command.id
|
|
? "admin.sales.booking_page.updated"
|
|
: "admin.sales.booking_page.created",
|
|
targetType: "AdminBookingPage",
|
|
targetId: page.id,
|
|
after: {
|
|
meetingTypeId: page.meetingTypeId,
|
|
slug: page.slug,
|
|
published: page.published,
|
|
},
|
|
});
|
|
return page;
|
|
}),
|
|
|
|
replaceAvailability: (command) =>
|
|
client.$transaction(async (tx) => {
|
|
const archivedAt = new Date();
|
|
await Promise.all([
|
|
tx.adminAvailabilityRule.updateMany({
|
|
where: {
|
|
adminUserId: command.adminUserId,
|
|
archivedAt: null,
|
|
},
|
|
data: { archivedAt },
|
|
}),
|
|
tx.adminAvailabilityOverride.updateMany({
|
|
where: {
|
|
adminUserId: command.adminUserId,
|
|
archivedAt: null,
|
|
},
|
|
data: { archivedAt },
|
|
}),
|
|
]);
|
|
if (command.rules.length > 0) {
|
|
await tx.adminAvailabilityRule.createMany({
|
|
data: command.rules.map((rule) => ({
|
|
adminUserId: command.adminUserId,
|
|
dayOfWeek: rule.dayOfWeek,
|
|
startMinutes: rule.startMinutes,
|
|
endMinutes: rule.endMinutes,
|
|
timeZone: command.timeZone,
|
|
})),
|
|
});
|
|
}
|
|
if (command.overrides.length > 0) {
|
|
await tx.adminAvailabilityOverride.createMany({
|
|
data: command.overrides.map((override) => ({
|
|
adminUserId: command.adminUserId,
|
|
date: override.date,
|
|
kind: override.kind,
|
|
startMinutes: override.startMinutes,
|
|
endMinutes: override.endMinutes,
|
|
timeZone: command.timeZone,
|
|
reason: override.reason,
|
|
})),
|
|
});
|
|
}
|
|
const [rules, overrides] = await Promise.all([
|
|
tx.adminAvailabilityRule.findMany({
|
|
where: {
|
|
adminUserId: command.adminUserId,
|
|
archivedAt: null,
|
|
},
|
|
orderBy: [
|
|
{ dayOfWeek: "asc" },
|
|
{ startMinutes: "asc" },
|
|
{ id: "asc" },
|
|
],
|
|
}),
|
|
tx.adminAvailabilityOverride.findMany({
|
|
where: {
|
|
adminUserId: command.adminUserId,
|
|
archivedAt: null,
|
|
},
|
|
orderBy: [{ date: "asc" }, { startMinutes: "asc" }, { id: "asc" }],
|
|
}),
|
|
]);
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "configuration_changed",
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
summary: "Kalender-Verfügbarkeit aktualisiert",
|
|
payload: {
|
|
ruleCount: rules.length,
|
|
overrideCount: overrides.length,
|
|
timeZone: command.timeZone,
|
|
},
|
|
},
|
|
});
|
|
await writeAdminSalesAudit(tx, {
|
|
actor: command.actor,
|
|
action: "admin.sales.availability.replaced",
|
|
targetType: "AdminUser",
|
|
targetId: command.adminUserId,
|
|
after: {
|
|
ruleCount: rules.length,
|
|
overrideCount: overrides.length,
|
|
timeZone: command.timeZone,
|
|
},
|
|
});
|
|
return { rules, overrides };
|
|
}),
|
|
};
|
|
}
|
|
|
|
function normalizeMeetingType(
|
|
input: SaveAdminMeetingTypeInput
|
|
): SaveAdminMeetingTypeInput {
|
|
const hostAdminUserIds = uniqueIds(input.hostAdminUserIds);
|
|
if (hostAdminUserIds.length === 0) {
|
|
throw new AdminBookingSettingsError("host_required");
|
|
}
|
|
const intakeQuestions = input.intakeQuestions.map(normalizeQuestion);
|
|
if (intakeQuestions.length > MAX_QUESTION_COUNT) {
|
|
throw new AdminBookingSettingsError("too_many_questions");
|
|
}
|
|
return {
|
|
id: optionalId(input.id),
|
|
name: requiredText(input.name, "name", MAX_NAME_LENGTH),
|
|
slug: normalizeSlug(input.slug),
|
|
description: optionalText(input.description, MAX_DESCRIPTION_LENGTH),
|
|
durationMinutes: positiveInt(input.durationMinutes, "durationMinutes", 480),
|
|
bufferBeforeMinutes: nonNegativeInt(
|
|
input.bufferBeforeMinutes,
|
|
"bufferBeforeMinutes",
|
|
240
|
|
),
|
|
bufferAfterMinutes: nonNegativeInt(
|
|
input.bufferAfterMinutes,
|
|
"bufferAfterMinutes",
|
|
240
|
|
),
|
|
slotIncrementMinutes: positiveInt(
|
|
input.slotIncrementMinutes,
|
|
"slotIncrementMinutes",
|
|
240
|
|
),
|
|
minimumNoticeMinutes: nonNegativeInt(
|
|
input.minimumNoticeMinutes,
|
|
"minimumNoticeMinutes",
|
|
43_200
|
|
),
|
|
bookingHorizonDays: positiveInt(
|
|
input.bookingHorizonDays,
|
|
"bookingHorizonDays",
|
|
365
|
|
),
|
|
hostAdminUserIds,
|
|
intakeQuestions,
|
|
reminderOffsetsMinutes: uniquePositiveInts(
|
|
input.reminderOffsetsMinutes,
|
|
43_200
|
|
),
|
|
active: input.active,
|
|
actor: normalizeActor(input.actor),
|
|
};
|
|
}
|
|
|
|
function normalizeBookingPage(
|
|
input: SaveAdminBookingPageInput
|
|
): SaveAdminBookingPageInput {
|
|
return {
|
|
id: optionalId(input.id),
|
|
meetingTypeId: requiredText(
|
|
input.meetingTypeId,
|
|
"meetingTypeId",
|
|
191
|
|
),
|
|
slug: normalizeSlug(input.slug),
|
|
title: requiredText(input.title, "title", MAX_NAME_LENGTH),
|
|
description: optionalText(input.description, MAX_DESCRIPTION_LENGTH),
|
|
published: input.published,
|
|
maxBookingsPerEmailPerDay: positiveInt(
|
|
input.maxBookingsPerEmailPerDay,
|
|
"maxBookingsPerEmailPerDay",
|
|
100
|
|
),
|
|
actor: normalizeActor(input.actor),
|
|
};
|
|
}
|
|
|
|
function normalizeAvailability(
|
|
input: ReplaceAdminAvailabilityInput
|
|
): ReplaceAdminAvailabilityInput {
|
|
const timeZone = normalizeTimeZone(input.timeZone);
|
|
const rules = input.rules.map((rule) => ({
|
|
dayOfWeek: rule.dayOfWeek,
|
|
startMinutes: minuteOfDay(rule.startMinutes, false),
|
|
endMinutes: minuteOfDay(rule.endMinutes, true),
|
|
}));
|
|
for (const rule of rules) {
|
|
if (rule.endMinutes <= rule.startMinutes) {
|
|
throw new AdminBookingSettingsError("invalid_window");
|
|
}
|
|
}
|
|
const overrides = input.overrides.map((override) => {
|
|
const date = validDate(override.date);
|
|
if (override.kind === "unavailable") {
|
|
return {
|
|
date,
|
|
kind: override.kind,
|
|
startMinutes: null,
|
|
endMinutes: null,
|
|
reason: optionalText(override.reason, 500),
|
|
};
|
|
}
|
|
const startMinutes = minuteOfDay(override.startMinutes, false);
|
|
const endMinutes = minuteOfDay(override.endMinutes, true);
|
|
if (endMinutes <= startMinutes) {
|
|
throw new AdminBookingSettingsError("invalid_window");
|
|
}
|
|
return {
|
|
date,
|
|
kind: override.kind,
|
|
startMinutes,
|
|
endMinutes,
|
|
reason: optionalText(override.reason, 500),
|
|
};
|
|
});
|
|
return {
|
|
adminUserId: requiredText(input.adminUserId, "adminUserId", 191),
|
|
timeZone,
|
|
rules,
|
|
overrides,
|
|
actor: normalizeActor(input.actor),
|
|
};
|
|
}
|
|
|
|
function normalizeQuestion(
|
|
question: AdminMeetingQuestion
|
|
): AdminMeetingQuestion {
|
|
const options =
|
|
question.type === "single_select"
|
|
? uniqueTexts(question.options ?? [], 100)
|
|
: undefined;
|
|
if (question.type === "single_select" && options?.length === 0) {
|
|
throw new AdminBookingSettingsError("question_options_required");
|
|
}
|
|
return Object.freeze({
|
|
key: normalizeSlug(question.key),
|
|
label: requiredText(question.label, "question.label", 200),
|
|
type: question.type,
|
|
required: question.required,
|
|
options,
|
|
});
|
|
}
|
|
|
|
function normalizeActor(actor: AdminSalesActor): AdminSalesActor {
|
|
return {
|
|
...actor,
|
|
adminUserId: requiredText(
|
|
actor.adminUserId,
|
|
"actor.adminUserId",
|
|
191
|
|
),
|
|
reason: requiredText(actor.reason, "actor.reason", 500),
|
|
};
|
|
}
|
|
|
|
function normalizeSlug(value: string): string {
|
|
const normalized = value
|
|
.trim()
|
|
.toLowerCase()
|
|
.normalize("NFKD")
|
|
.replace(/[\u0300-\u036f]/gu, "")
|
|
.replace(/[^a-z0-9]+/gu, "-")
|
|
.replace(/^-+|-+$/gu, "");
|
|
if (!normalized || normalized.length > 120) {
|
|
throw new AdminBookingSettingsError("invalid_slug");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeTimeZone(value: string): string {
|
|
const timeZone = requiredText(value, "timeZone", 100);
|
|
try {
|
|
new Intl.DateTimeFormat("de-DE", { timeZone }).format(new Date());
|
|
} catch {
|
|
throw new AdminBookingSettingsError("invalid_time_zone");
|
|
}
|
|
return timeZone;
|
|
}
|
|
|
|
function positiveInt(value: number, field: string, max: number): number {
|
|
if (!Number.isInteger(value) || value <= 0 || value > max) {
|
|
throw new AdminBookingSettingsError("invalid_input", field);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function nonNegativeInt(value: number, field: string, max: number): number {
|
|
if (!Number.isInteger(value) || value < 0 || value > max) {
|
|
throw new AdminBookingSettingsError("invalid_input", field);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function minuteOfDay(
|
|
value: number | null | undefined,
|
|
allowEndOfDay: boolean
|
|
): number {
|
|
return nonNegativeInt(
|
|
value ?? -1,
|
|
"minuteOfDay",
|
|
allowEndOfDay ? 1_440 : 1_439
|
|
);
|
|
}
|
|
|
|
function validDate(value: Date): Date {
|
|
if (!Number.isFinite(value.getTime())) {
|
|
throw new AdminBookingSettingsError("invalid_date");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function uniqueIds(values: readonly string[]): readonly string[] {
|
|
return Object.freeze(
|
|
[...new Set(values.map((value) => value.trim()).filter(Boolean))].sort()
|
|
);
|
|
}
|
|
|
|
function uniqueTexts(values: readonly string[], max: number): readonly string[] {
|
|
return Object.freeze(
|
|
[
|
|
...new Set(
|
|
values
|
|
.map((value) => requiredText(value, "option", max))
|
|
.filter(Boolean)
|
|
),
|
|
].sort()
|
|
);
|
|
}
|
|
|
|
function uniquePositiveInts(
|
|
values: readonly number[],
|
|
max: number
|
|
): readonly number[] {
|
|
return Object.freeze(
|
|
[...new Set(values.map((value) => positiveInt(value, "offset", max)))].sort(
|
|
(left, right) => right - left
|
|
)
|
|
);
|
|
}
|
|
|
|
function optionalId(value: string | null | undefined): string | null {
|
|
return value ? requiredText(value, "id", 191) : null;
|
|
}
|
|
|
|
function requiredText(value: string, field: string, max: number): string {
|
|
const normalized = value.trim();
|
|
if (!normalized || normalized.length > max) {
|
|
throw new AdminBookingSettingsError("invalid_input", field);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function optionalText(
|
|
value: string | null | undefined,
|
|
max: number
|
|
): string | null {
|
|
if (!value?.trim()) return null;
|
|
return requiredText(value, "optionalText", max);
|
|
}
|
|
|
|
export class AdminBookingSettingsError extends Error {
|
|
constructor(
|
|
readonly code:
|
|
| "invalid_input"
|
|
| "invalid_slug"
|
|
| "invalid_time_zone"
|
|
| "invalid_date"
|
|
| "invalid_window"
|
|
| "host_required"
|
|
| "host_ineligible"
|
|
| "meeting_type_unavailable"
|
|
| "owner_mismatch"
|
|
| "too_many_questions"
|
|
| "question_options_required",
|
|
readonly field?: string
|
|
) {
|
|
super(code);
|
|
this.name = "AdminBookingSettingsError";
|
|
}
|
|
}
|