import { createAdminBookingLifecycleService, createPrismaAdminBookingLifecycleRepository, } from "@hivegrid/db/admin-booking-lifecycle.server"; import type { DbClient } from "@hivegrid/db/client.server"; import { openAdminConnectionCredentials, sealAdminConnectionCredentials, } from "@hivegrid/db/crypto/admin-connection-envelope.server"; import { googleAdminBookingProvider, microsoftAdminBookingProvider, type AdminBookingProviderPort, } from "./admin-booking-provider.server.js"; import { refreshAccessToken, resolveGoogleOAuthConfig, } from "./google/googleCalendarApi.js"; import { refreshMicrosoftCalendarToken, resolveMicrosoftCalendarOAuthConfig, } from "./microsoft/graphCalendarApi.js"; type AdminBookingWorkerClient = Pick< DbClient, | "$transaction" | "adminBooking" | "adminCalendarConnection" | "adminDataConnection" | "adminConnectionCredential" >; type CredentialBundle = { readonly accessToken: string; readonly refreshToken: string; readonly expiresAt: string; readonly scopes: readonly string[]; }; type AdminBookingProviderEvent = { readonly bookingId: string; readonly adminUserId: string; readonly calendarConnectionId: string; readonly provider: "google_calendar" | "microsoft_calendar"; readonly accessToken: string; readonly externalEventId?: string | null; readonly externalEventVersion?: string | null; readonly calendarId: string; readonly subject: string; readonly bodyText?: string | null; readonly startsAt: Date; readonly endsAt: Date; readonly timeZone: string; readonly attendee: { readonly email: string; readonly name: string }; }; type AdminBookingWorkerDependencies = { readonly loadEvent: ( bookingId: string, adminUserId: string ) => Promise; readonly createEvent: ( event: AdminBookingProviderEvent ) => Promise<{ readonly externalEventId: string; readonly opaqueVersion?: string | null; }>; readonly updateEvent: ( event: AdminBookingProviderEvent, externalEventId: string, opaqueVersion?: string | null ) => Promise<{ readonly externalEventId: string; readonly opaqueVersion?: string | null; }>; readonly deleteEvent: (event: AdminBookingProviderEvent) => Promise; readonly confirm: (input: { readonly bookingId: string; readonly adminUserId: string; readonly calendarConnectionId: string; readonly providerEventId: string; readonly providerEventVersion?: string | null; readonly syncedAt: Date; }) => Promise; readonly markFailed: (input: { readonly bookingId: string; readonly adminUserId: string; readonly errorCode: string; }) => Promise; readonly now: () => Date; }; export function createAdminBookingOutboxDependencies(input: { readonly client: AdminBookingWorkerClient; readonly env?: NodeJS.ProcessEnv; readonly now?: () => Date; }): AdminBookingWorkerDependencies { const env = input.env ?? process.env; const now = input.now ?? (() => new Date()); const lifecycle = createAdminBookingLifecycleService({ repository: createPrismaAdminBookingLifecycleRepository( input.client as never ), authorize: () => undefined, }); return { now, loadEvent: (bookingId, adminUserId) => loadProviderEvent(input.client, { bookingId, adminUserId, env, now, }), createEvent: (event) => providerFor(event.provider).createEvent(event.accessToken, event), updateEvent: (event, externalEventId, opaqueVersion) => providerFor(event.provider).updateEvent( event.accessToken, externalEventId, event, opaqueVersion ), deleteEvent: async (event) => { if (!event.externalEventId) return; await providerFor(event.provider).deleteEvent( event.accessToken, event.calendarId, event.externalEventId ); }, confirm: async (command) => { await lifecycle.confirmProviderEvent(command); }, markFailed: async (command) => { await lifecycle.markProviderSyncFailed(command); }, }; } async function loadProviderEvent( client: AdminBookingWorkerClient, input: { readonly bookingId: string; readonly adminUserId: string; readonly env: NodeJS.ProcessEnv; readonly now: () => Date; } ): Promise { const booking = await client.adminBooking.findFirst({ where: { id: input.bookingId, adminUserId: input.adminUserId }, include: { meetingType: { select: { name: true, description: true } }, participants: { where: { isOrganizer: false }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], take: 1, select: { email: true, name: true }, }, calendarConnection: { include: { dataConnection: { include: { credential: true }, }, }, }, }, }); if (!booking) throw new AdminBookingWorkerError("booking_unavailable"); const calendar = booking.calendarConnection ?? (await client.adminCalendarConnection.findFirst({ where: { adminUserId: input.adminUserId, status: "active", archivedAt: null, dataConnection: { status: { in: ["active", "degraded"] }, archivedAt: null, }, }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], include: { dataConnection: { include: { credential: true }, }, }, })); if (!calendar) { throw new AdminBookingWorkerError("calendar_unavailable"); } const provider = calendar.dataConnection.provider; if ( provider !== "google_calendar" && provider !== "microsoft_calendar" ) { throw new AdminBookingWorkerError("provider_unavailable"); } const credentials = await freshCredentials(client, { connection: calendar.dataConnection, provider, adminUserId: input.adminUserId, env: input.env, now: input.now, }); const attendee = booking.participants[0]; if (!attendee) throw new AdminBookingWorkerError("attendee_unavailable"); return { bookingId: booking.id, adminUserId: booking.adminUserId, calendarConnectionId: calendar.id, provider, accessToken: credentials.accessToken, externalEventId: booking.providerEventId, externalEventVersion: booking.providerEventVersion, calendarId: calendar.externalCalendarId, subject: booking.meetingType.name, bodyText: booking.meetingType.description, startsAt: booking.startsAt, endsAt: booking.endsAt, timeZone: calendar.timeZone, attendee, }; } async function freshCredentials( client: AdminBookingWorkerClient, input: { readonly connection: { readonly id: string; readonly adminUserId: string; readonly tokenExpiresAt: Date | null; readonly credential: { readonly wrappedDek: Uint8Array; readonly ciphertext: string; readonly keyVersion: number; readonly revokedAt: Date | null; } | null; }; readonly provider: "google_calendar" | "microsoft_calendar"; readonly adminUserId: string; readonly env: NodeJS.ProcessEnv; readonly now: () => Date; } ): Promise { const credential = input.connection.credential; if ( input.connection.adminUserId !== input.adminUserId || !credential || credential.revokedAt ) { throw new AdminBookingWorkerError("credential_unavailable"); } const current = parseCredentialBundle( await openAdminConnectionCredentials(credential) ); const expiresAt = input.connection.tokenExpiresAt ?? new Date(current.expiresAt); if ( Number.isFinite(expiresAt.getTime()) && expiresAt.getTime() > input.now().getTime() + 60_000 ) { return current; } const refreshed = input.provider === "google_calendar" ? await refreshGoogle(input.env, current) : await refreshMicrosoft(input.env, current); const envelope = await sealAdminConnectionCredentials( JSON.stringify(refreshed) ); await client.$transaction(async (tx) => { await tx.adminDataConnection.update({ where: { id: input.connection.id, adminUserId: input.adminUserId, }, data: { status: "active", tokenExpiresAt: new Date(refreshed.expiresAt), scopes: [...refreshed.scopes], lastHealthCheckAt: input.now(), healthMessageKey: "admin.sales.booking.calendars.health.connected", }, }); await tx.adminConnectionCredential.update({ where: { connectionId: input.connection.id }, data: { wrappedDek: Uint8Array.from(envelope.wrappedDek), ciphertext: envelope.ciphertext, keyVersion: envelope.keyVersion, rotatedAt: input.now(), revokedAt: null, }, }); }); return refreshed; } async function refreshGoogle( env: NodeJS.ProcessEnv, current: CredentialBundle ): Promise { const config = resolveGoogleOAuthConfig(env); if (!config) throw new AdminBookingWorkerError("provider_not_configured"); const refreshed = await refreshAccessToken(config, current.refreshToken); return { accessToken: refreshed.accessToken, refreshToken: refreshed.refreshToken ?? current.refreshToken, expiresAt: refreshed.expiresAt.toISOString(), scopes: refreshed.scopes.length > 0 ? refreshed.scopes : current.scopes, }; } async function refreshMicrosoft( env: NodeJS.ProcessEnv, current: CredentialBundle ): Promise { const config = resolveMicrosoftCalendarOAuthConfig(env); if (!config) throw new AdminBookingWorkerError("provider_not_configured"); const refreshed = await refreshMicrosoftCalendarToken( config, current.refreshToken ); return { accessToken: refreshed.accessToken, refreshToken: refreshed.refreshToken ?? current.refreshToken, expiresAt: refreshed.expiresAt.toISOString(), scopes: refreshed.scopes.length > 0 ? refreshed.scopes : current.scopes, }; } function parseCredentialBundle(value: string): CredentialBundle { let raw: unknown; try { raw = JSON.parse(value); } catch { throw new AdminBookingWorkerError("invalid_credential"); } if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new AdminBookingWorkerError("invalid_credential"); } const record = raw as Record; if ( typeof record.accessToken !== "string" || typeof record.refreshToken !== "string" || typeof record.expiresAt !== "string" || !Array.isArray(record.scopes) || record.scopes.some((scope) => typeof scope !== "string") ) { throw new AdminBookingWorkerError("invalid_credential"); } return { accessToken: record.accessToken, refreshToken: record.refreshToken, expiresAt: record.expiresAt, scopes: record.scopes as string[], }; } function providerFor( provider: AdminBookingProviderEvent["provider"] ): AdminBookingProviderPort { return provider === "google_calendar" ? googleAdminBookingProvider : microsoftAdminBookingProvider; } export class AdminBookingWorkerError extends Error { constructor(readonly code: string) { super(code); this.name = "AdminBookingWorkerError"; } }