import "server-only"; import { asc, eq } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; import { calendarEvents, editorialAccounts, eventResponses } from "@/db/schema"; import type * as schema from "@/db/schema"; import { albumGrantService, AlbumGrantError } from "@/modules/albums/grants"; import { isoDateInBerlin, isValidIsoDate, shiftIsoDate, } from "@/modules/announcements/service"; import { writeAudit } from "@/modules/audit/write"; import { immichClient } from "@/modules/immich/client"; import type { ImmichClient } from "@/modules/immich/types"; import { consumeRateLimit, calendarSelfGrantPolicy } from "@/modules/security/rate-limit"; import { enforceRateLimit, RateLimitExceededError, type ConsumeRateLimit, } from "@/modules/security/rate-limit-guard"; import { matchEventAlbum } from "./event-albums"; export const CALENDAR_EVENT_MAX_TITLE_LENGTH = 200; /** Past events stay visible (and self-serviceable) for this many days. */ export const CALENDAR_PAST_DAYS = 30; export type EventResponseStatus = "attending" | "not_attending"; export type CalendarEvent = { id: string; title: string; eventDate: string; immichAlbumId: string | null; createdAt: Date; }; export type LinkedAlbum = { id: string; albumName: string }; export type EditorialCalendarEvent = CalendarEvent & { album: LinkedAlbum | null; isGranted: boolean; response: EventResponseStatus | null; }; export type AdminCalendarEvent = CalendarEvent & { album: LinkedAlbum | null; responses: Array<{ editorialId: string; editorialName: string; status: EventResponseStatus; }>; }; export type CalendarError = | "INVALID_TITLE" | "INVALID_EVENT_DATE" | "INVALID_ALBUM" | "INVALID_STATUS" | "EVENT_NOT_FOUND" | "EVENT_ALBUM_UNAVAILABLE" | "IMMICH_UNAVAILABLE" | "RATE_LIMITED"; export class CalendarServiceError extends Error { readonly name = "CalendarServiceError"; constructor( readonly code: CalendarError, readonly retryAfterSeconds?: number, ) { super(code); } } export type CalendarRepository = { insertEvent(input: { title: string; eventDate: string; immichAlbumId: string | null; adminUserId: string; }): Promise; getEvent(id: string): Promise; listEvents(): Promise; deleteEvent(id: string): Promise; upsertResponse(input: { eventId: string; editorialId: string; status: EventResponseStatus; }): Promise; listResponsesForEditorial(editorialId: string): Promise>; listAllResponses(): Promise< Array<{ eventId: string; editorialId: string; editorialName: string; status: EventResponseStatus }> >; }; export type CalendarDependencies = { repository: CalendarRepository; immich: Pick; grants: Pick< typeof albumGrantService, "getGrantedAlbumIds" | "grantAlbum" | "revokeSelfServiceGrantsForAlbum" >; audit: { writeAudit: typeof writeAudit }; consumeRateLimit: ConsumeRateLimit; }; const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; export function createCalendarService({ repository, immich, grants, audit, consumeRateLimit: consume, }: CalendarDependencies) { async function loadAlbumsOrNull() { try { return await immich.listAlbums(); } catch { return null; } } return { async createEvent(input: { title: string; eventDate: string; immichAlbumId?: string | null; adminUserId: string; }): Promise { const title = input.title.trim(); if (title.length === 0 || title.length > CALENDAR_EVENT_MAX_TITLE_LENGTH) { throw new CalendarServiceError("INVALID_TITLE"); } if (!isValidIsoDate(input.eventDate)) { throw new CalendarServiceError("INVALID_EVENT_DATE"); } let immichAlbumId: string | null = null; if (input.immichAlbumId) { if (!UUID_PATTERN.test(input.immichAlbumId)) { throw new CalendarServiceError("INVALID_ALBUM"); } const albums = await loadAlbumsOrNull(); if (!albums) { throw new CalendarServiceError("IMMICH_UNAVAILABLE"); } const album = albums.find( (candidate) => candidate.id.toLowerCase() === input.immichAlbumId!.toLowerCase(), ); if (!album) { throw new CalendarServiceError("INVALID_ALBUM"); } immichAlbumId = album.id; } const created = await repository.insertEvent({ title, eventDate: input.eventDate, immichAlbumId, adminUserId: input.adminUserId, }); await audit.writeAudit({ type: "calendar_event_created", actorUserId: input.adminUserId, actorType: "admin", entityType: "calendar_event", entityId: created.id, metadata: { title: created.title, eventDate: created.eventDate, immichAlbumId }, }); return created; }, async deleteEvent(input: { id: string; adminUserId: string }): Promise { const event = await repository.getEvent(input.id); if (!event) { throw new CalendarServiceError("EVENT_NOT_FOUND"); } // Revoking self-service grants keeps the calendar authoritative: an // album that leaves the calendar loses self-service access. Admin and // auto-rule grants are untouched (auto assignment outranks the calendar). const albums = (await loadAlbumsOrNull()) ?? []; const album = matchEventAlbum(event, albums); const revoked = album ? await grants.revokeSelfServiceGrantsForAlbum(album.id) : 0; const deleted = await repository.deleteEvent(input.id); if (!deleted) { throw new CalendarServiceError("EVENT_NOT_FOUND"); } await audit.writeAudit({ type: "calendar_event_deleted", actorUserId: input.adminUserId, actorType: "admin", entityType: "calendar_event", entityId: deleted.id, metadata: { title: deleted.title, eventDate: deleted.eventDate, revokedSelfServiceGrants: revoked, }, }); }, /** Editorial calendar: upcoming events plus the recent past window. */ async listEditorialEvents( editorialId: string, now: Date, ): Promise<{ events: EditorialCalendarEvent[]; immichUnavailable: boolean }> { const today = isoDateInBerlin(now); const minDate = shiftIsoDate(today, -CALENDAR_PAST_DAYS); const [allEvents, albums, grantedAlbumIds, responses] = await Promise.all([ repository.listEvents(), loadAlbumsOrNull(), grants.getGrantedAlbumIds(editorialId), repository.listResponsesForEditorial(editorialId), ]); const granted = new Set(grantedAlbumIds.map((id) => id.toLowerCase())); const responseByEvent = new Map(responses.map((response) => [response.eventId, response.status])); const events = allEvents .filter((event) => event.eventDate >= minDate) .map((event) => { const album = albums ? matchEventAlbum(event, albums) : null; return { ...event, album: album ? { id: album.id, albumName: album.albumName } : null, isGranted: album ? granted.has(album.id.toLowerCase()) : false, response: responseByEvent.get(event.id) ?? null, }; }); return { events, immichUnavailable: albums === null }; }, /** Admin overview: every event with its linked album and all RSVPs. */ async listAdminEvents(): Promise<{ events: AdminCalendarEvent[]; immichUnavailable: boolean }> { const [allEvents, albums, responses] = await Promise.all([ repository.listEvents(), loadAlbumsOrNull(), repository.listAllResponses(), ]); const responsesByEvent = new Map(); for (const response of responses) { const list = responsesByEvent.get(response.eventId) ?? []; list.push({ editorialId: response.editorialId, editorialName: response.editorialName, status: response.status, }); responsesByEvent.set(response.eventId, list); } const events = allEvents.map((event) => { const album = albums ? matchEventAlbum(event, albums) : null; return { ...event, album: album ? { id: album.id, albumName: album.albumName } : null, responses: responsesByEvent.get(event.id) ?? [], }; }); return { events, immichUnavailable: albums === null }; }, async respond(input: { eventId: string; editorialId: string; actorUserId: string; status: EventResponseStatus; }): Promise { if (input.status !== "attending" && input.status !== "not_attending") { throw new CalendarServiceError("INVALID_STATUS"); } const event = await repository.getEvent(input.eventId); if (!event) { throw new CalendarServiceError("EVENT_NOT_FOUND"); } await repository.upsertResponse({ eventId: input.eventId, editorialId: input.editorialId, status: input.status, }); await audit.writeAudit({ type: "event_response_recorded", actorUserId: input.actorUserId, actorType: "editorial", entityType: "calendar_event", entityId: input.eventId, metadata: { status: input.status, title: event.title, eventDate: event.eventDate }, }); }, /** * Editorial self-service: grant access to the album linked to a calendar * event. The event (admin-created) is the trust boundary; only its linked * album is grantable, never arbitrary Immich albums. Idempotent: an * existing active grant is left as-is. */ async selfGrantAlbum(input: { eventId: string; editorialId: string; actorUserId: string; }): Promise { try { await enforceRateLimit(consume, `calendar-self-grant:${input.editorialId}`, calendarSelfGrantPolicy); } catch (error) { if (error instanceof RateLimitExceededError) { throw new CalendarServiceError("RATE_LIMITED", error.retryAfterSeconds); } throw error; } const event = await repository.getEvent(input.eventId); if (!event) { throw new CalendarServiceError("EVENT_NOT_FOUND"); } const albums = await loadAlbumsOrNull(); if (!albums) { throw new CalendarServiceError("IMMICH_UNAVAILABLE"); } const album = matchEventAlbum(event, albums); if (!album) { throw new CalendarServiceError("EVENT_ALBUM_UNAVAILABLE"); } try { await grants.grantAlbum({ editorialId: input.editorialId, immichAlbumId: album.id, adminUserId: null, source: "self_service", }); } catch (error) { if (error instanceof AlbumGrantError && error.code === "ALBUM_NOT_ASSIGNABLE") { throw new CalendarServiceError("EVENT_ALBUM_UNAVAILABLE"); } if (error instanceof AlbumGrantError && error.code === "IMMICH_UNAVAILABLE") { throw new CalendarServiceError("IMMICH_UNAVAILABLE"); } throw error; } await audit.writeAudit({ type: "album_self_granted", actorUserId: input.actorUserId, actorType: "editorial", entityType: "album_grant", entityId: album.id, metadata: { editorialId: input.editorialId, eventId: input.eventId, albumName: album.albumName, }, }); return { id: album.id, albumName: album.albumName }; }, }; } export function createCalendarRepository(database: NodePgDatabase): CalendarRepository { const eventColumns = { id: calendarEvents.id, title: calendarEvents.title, eventDate: calendarEvents.eventDate, immichAlbumId: calendarEvents.immichAlbumId, createdAt: calendarEvents.createdAt, }; return { async insertEvent(input) { const [row] = await database .insert(calendarEvents) .values({ title: input.title, eventDate: input.eventDate, immichAlbumId: input.immichAlbumId, createdByUserId: input.adminUserId, }) .returning(eventColumns); return row; }, async getEvent(id) { const [row] = await database .select(eventColumns) .from(calendarEvents) .where(eq(calendarEvents.id, id)) .limit(1); return row ?? null; }, async listEvents() { return database .select(eventColumns) .from(calendarEvents) .orderBy(asc(calendarEvents.eventDate), asc(calendarEvents.createdAt)); }, async deleteEvent(id) { return database.transaction(async (transaction) => { const [event] = await transaction .select(eventColumns) .from(calendarEvents) .where(eq(calendarEvents.id, id)) .for("update") .limit(1); if (!event) { return null; } await transaction.delete(eventResponses).where(eq(eventResponses.eventId, id)); await transaction.delete(calendarEvents).where(eq(calendarEvents.id, id)); return event; }); }, async upsertResponse(input) { await database .insert(eventResponses) .values({ eventId: input.eventId, editorialAccountId: input.editorialId, status: input.status, updatedAt: new Date(), }) .onConflictDoUpdate({ target: [eventResponses.eventId, eventResponses.editorialAccountId], set: { status: input.status, updatedAt: new Date() }, }); }, async listResponsesForEditorial(editorialId) { const rows = await database .select({ eventId: eventResponses.eventId, status: eventResponses.status }) .from(eventResponses) .where(eq(eventResponses.editorialAccountId, editorialId)); return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus })); }, async listAllResponses() { const rows = await database .select({ eventId: eventResponses.eventId, editorialId: editorialAccounts.id, editorialName: editorialAccounts.name, status: eventResponses.status, }) .from(eventResponses) .innerJoin(editorialAccounts, eq(eventResponses.editorialAccountId, editorialAccounts.id)) .orderBy(asc(editorialAccounts.name)); return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus })); }, }; } export const calendarService = createCalendarService({ repository: createCalendarRepository(db), immich: immichClient, grants: albumGrantService, audit: { writeAudit }, consumeRateLimit, });