import type { AdminCalendarConnection, AdminCalendarSyncCursor, 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_LABEL_LENGTH = 200; const MAX_TIME_ZONE_LENGTH = 100; const MAX_CURSOR_LENGTH = 32_768; const MAX_BUSY_INTERVALS = 10_000; export type ActivateAdminCalendarInput = { readonly adminUserId: string; readonly dataConnectionId: string; readonly externalCalendarId: string; readonly externalCalendarLabel?: string | null; readonly timeZone: string; readonly actor: AdminSalesActor; }; export type AdminCalendarBusyInterval = { readonly externalEventId: string; readonly startsAt: string; readonly endsAt: string; readonly opaqueVersion?: string; }; export type ApplyAdminCalendarSyncInput = { readonly adminUserId: string; readonly calendarConnectionId: string; readonly externalCalendarId: string; readonly busyIntervals: readonly AdminCalendarBusyInterval[]; readonly cursorToken?: string | null; readonly deltaLink?: string | null; readonly fullSync: boolean; readonly syncedAt: Date; }; export type AdminCalendarRepository = { activate( input: ActivateAdminCalendarInput ): Promise; applySync( input: ApplyAdminCalendarSyncInput ): Promise; requireRecovery(input: { readonly adminUserId: string; readonly calendarConnectionId: string; readonly externalCalendarId: string; readonly errorCode: string; readonly requestedAt: Date; }): Promise; disconnect(input: { readonly adminUserId: string; readonly calendarConnectionId: string; readonly actor: AdminSalesActor; }): Promise; }; export function createAdminCalendarService(input: { readonly repository: AdminCalendarRepository; readonly authorize: ( permission: AdminPermissionName ) => Promise | void; }) { return { async activate(command: ActivateAdminCalendarInput) { await input.authorize("admin_sales.booking.manage"); return input.repository.activate(normalizeActivate(command)); }, async applySync(command: ApplyAdminCalendarSyncInput) { return input.repository.applySync(normalizeSync(command)); }, async requireRecovery(command: { readonly adminUserId: string; readonly calendarConnectionId: string; readonly externalCalendarId: string; readonly errorCode: string; readonly requestedAt: Date; }) { return input.repository.requireRecovery({ adminUserId: requiredId(command.adminUserId, "adminUserId"), calendarConnectionId: requiredId( command.calendarConnectionId, "calendarConnectionId" ), externalCalendarId: requiredText( command.externalCalendarId, "externalCalendarId", MAX_LABEL_LENGTH ), errorCode: requiredText(command.errorCode, "errorCode", 120), requestedAt: validDate(command.requestedAt, "requestedAt"), }); }, async disconnect(command: { readonly adminUserId: string; readonly calendarConnectionId: string; readonly actor: AdminSalesActor; }) { await input.authorize("admin_sales.booking.manage"); return input.repository.disconnect({ adminUserId: requiredId(command.adminUserId, "adminUserId"), calendarConnectionId: requiredId( command.calendarConnectionId, "calendarConnectionId" ), actor: normalizeActor(command.actor), }); }, }; } type AdminCalendarPrismaClient = Pick< PrismaClient, | "$transaction" | "adminDataConnection" | "adminCalendarConnection" | "adminCalendarSyncCursor" >; export function createPrismaAdminCalendarRepository( client: AdminCalendarPrismaClient ): AdminCalendarRepository { return { activate: (command) => client.$transaction(async (tx) => { const dataConnection = await tx.adminDataConnection.findFirst({ where: { id: command.dataConnectionId, adminUserId: command.adminUserId, capability: "calendar", provider: { in: ["google_calendar", "microsoft_calendar"] }, status: { in: ["active", "degraded"] }, archivedAt: null, }, select: { id: true }, }); if (!dataConnection) { throw new AdminCalendarServiceError("connection_unavailable"); } const calendar = await tx.adminCalendarConnection.upsert({ where: { dataConnectionId: command.dataConnectionId }, create: { adminUserId: command.adminUserId, dataConnectionId: command.dataConnectionId, externalCalendarId: command.externalCalendarId, externalCalendarLabel: command.externalCalendarLabel, timeZone: command.timeZone, status: "active", healthMessageKey: "admin.sales.booking.calendars.health.connected", }, update: { externalCalendarId: command.externalCalendarId, externalCalendarLabel: command.externalCalendarLabel, timeZone: command.timeZone, status: "active", archivedAt: null, lastErrorCode: null, healthMessageKey: "admin.sales.booking.calendars.health.connected", }, }); await tx.adminCalendarSyncCursor.upsert({ where: { admin_calendar_cursor_external_key: { calendarConnectionId: calendar.id, externalCalendarId: command.externalCalendarId, }, }, create: { adminUserId: command.adminUserId, calendarConnectionId: calendar.id, externalCalendarId: command.externalCalendarId, status: "pending", }, update: { adminUserId: command.adminUserId, status: "pending", lastErrorCode: null, }, }); await tx.adminActivity.create({ data: { type: "configuration_changed", actorAdminUserId: command.actor.adminUserId, summary: "Persönlichen Kalender verbunden", payload: { calendarConnectionId: calendar.id, externalCalendarId: command.externalCalendarId, }, }, }); await writeAdminSalesAudit(tx, { actor: command.actor, action: "admin.sales.calendar.connected", targetType: "AdminCalendarConnection", targetId: calendar.id, after: { dataConnectionId: command.dataConnectionId, externalCalendarId: command.externalCalendarId, timeZone: command.timeZone, }, }); return calendar; }), applySync: (command) => client.$transaction(async (tx) => { const cursor = await tx.adminCalendarSyncCursor.update({ where: { admin_calendar_cursor_external_key: { calendarConnectionId: command.calendarConnectionId, externalCalendarId: command.externalCalendarId, }, adminUserId: command.adminUserId, }, data: { cursorToken: command.cursorToken, deltaLink: command.deltaLink, busyIntervals: command.busyIntervals as unknown as Prisma.InputJsonValue, status: "active", lastIncrementalSyncAt: command.syncedAt, lastFullSyncAt: command.fullSync ? command.syncedAt : undefined, recoveryRequestedAt: null, lastErrorCode: null, }, }); await tx.adminCalendarConnection.update({ where: { id: command.calendarConnectionId, adminUserId: command.adminUserId, }, data: { status: "active", lastSyncAt: command.syncedAt, lastErrorCode: null, healthMessageKey: "admin.sales.booking.calendars.health.synced", }, }); return cursor; }), requireRecovery: (command) => client.$transaction(async (tx) => { const cursor = await tx.adminCalendarSyncCursor.update({ where: { admin_calendar_cursor_external_key: { calendarConnectionId: command.calendarConnectionId, externalCalendarId: command.externalCalendarId, }, adminUserId: command.adminUserId, }, data: { cursorToken: null, deltaLink: null, status: "recovery_required", recoveryRequestedAt: command.requestedAt, lastErrorCode: command.errorCode, }, }); await tx.adminCalendarConnection.update({ where: { id: command.calendarConnectionId, adminUserId: command.adminUserId, }, data: { status: "degraded", lastErrorCode: command.errorCode, healthMessageKey: "admin.sales.booking.calendars.health.recoveryRequired", }, }); return cursor; }), disconnect: (command) => client.$transaction(async (tx) => { const disconnected = await tx.adminCalendarConnection.update({ where: { id: command.calendarConnectionId, adminUserId: command.adminUserId, }, data: { status: "revoked", archivedAt: new Date(), healthMessageKey: "admin.sales.booking.calendars.health.disconnected", }, }); await tx.adminActivity.create({ data: { type: "configuration_changed", actorAdminUserId: command.actor.adminUserId, summary: "Persönlichen Kalender getrennt", payload: { calendarConnectionId: disconnected.id }, }, }); await writeAdminSalesAudit(tx, { actor: command.actor, action: "admin.sales.calendar.disconnected", targetType: "AdminCalendarConnection", targetId: disconnected.id, after: { status: "revoked" }, }); return disconnected; }), }; } function normalizeActivate( input: ActivateAdminCalendarInput ): ActivateAdminCalendarInput { return { adminUserId: requiredId(input.adminUserId, "adminUserId"), dataConnectionId: requiredId( input.dataConnectionId, "dataConnectionId" ), externalCalendarId: requiredText( input.externalCalendarId, "externalCalendarId", MAX_LABEL_LENGTH ), externalCalendarLabel: optionalText( input.externalCalendarLabel, MAX_LABEL_LENGTH ), timeZone: normalizeTimeZone(input.timeZone), actor: normalizeActor(input.actor), }; } function normalizeSync( input: ApplyAdminCalendarSyncInput ): ApplyAdminCalendarSyncInput { if (input.busyIntervals.length > MAX_BUSY_INTERVALS) { throw new AdminCalendarServiceError("busy_snapshot_too_large"); } const busyIntervals = input.busyIntervals.map((interval) => { const startsAt = validDate(new Date(interval.startsAt), "startsAt"); const endsAt = validDate(new Date(interval.endsAt), "endsAt"); if (endsAt <= startsAt) { throw new AdminCalendarServiceError("invalid_busy_interval"); } return Object.freeze({ externalEventId: requiredText( interval.externalEventId, "externalEventId", MAX_LABEL_LENGTH ), startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString(), opaqueVersion: optionalText(interval.opaqueVersion, 1_000) ?? undefined, }); }); if (Boolean(input.cursorToken) === Boolean(input.deltaLink)) { throw new AdminCalendarServiceError("invalid_provider_cursor"); } return { adminUserId: requiredId(input.adminUserId, "adminUserId"), calendarConnectionId: requiredId( input.calendarConnectionId, "calendarConnectionId" ), externalCalendarId: requiredText( input.externalCalendarId, "externalCalendarId", MAX_LABEL_LENGTH ), busyIntervals, cursorToken: optionalText(input.cursorToken, MAX_CURSOR_LENGTH), deltaLink: optionalText(input.deltaLink, MAX_CURSOR_LENGTH), fullSync: input.fullSync, syncedAt: validDate(input.syncedAt, "syncedAt"), }; } function normalizeActor(actor: AdminSalesActor): AdminSalesActor { return { ...actor, adminUserId: requiredId(actor.adminUserId, "actor.adminUserId"), reason: requiredText(actor.reason, "actor.reason", 500), }; } function normalizeTimeZone(value: string): string { const timeZone = requiredText(value, "timeZone", MAX_TIME_ZONE_LENGTH); try { new Intl.DateTimeFormat("de-DE", { timeZone }).format(new Date()); } catch { throw new AdminCalendarServiceError("invalid_time_zone"); } return timeZone; } function requiredId(value: string, field: string): string { return requiredText(value, field, 191); } function requiredText(value: string, field: string, max: number): string { const normalized = value.trim(); if (!normalized || normalized.length > max) { throw new AdminCalendarServiceError("invalid_input", field); } return normalized; } function optionalText( value: string | null | undefined, max: number ): string | null { if (value == null || !value.trim()) return null; const normalized = value.trim(); if (normalized.length > max) { throw new AdminCalendarServiceError("invalid_input"); } return normalized; } function validDate(value: Date, field: string): Date { if (!Number.isFinite(value.getTime())) { throw new AdminCalendarServiceError("invalid_input", field); } return value; } export class AdminCalendarServiceError extends Error { constructor( readonly code: | "invalid_input" | "invalid_time_zone" | "connection_unavailable" | "invalid_provider_cursor" | "invalid_busy_interval" | "busy_snapshot_too_large", readonly field?: string ) { super(code); this.name = "AdminCalendarServiceError"; } }