// AK-P16a (P16) Calendar-Sync (Google) — aligned to ENTITY-MODEL Domäne 9 // (M25-calendar-sync). v1 = Google only; Outlook/Microsoft → v2 (the provider // enum + adapter interface stay provider-agnostic). // // AD-21: self-contained schema. `tenantId` / `userId` are BARE String scalars // (no `@relation` to Tenant/User) → zero merge-conflict surface against // core.prisma/accounts.prisma. Intra-module relations (Connection → Event / // Mapping / Cursor / WebhookEvent / Conflict) stay inside this file. // // Connection is PER-USER (not per-tenant): each user connects their own Google // account. OAuth refresh/access tokens are stored ENVELOPE-ENCRYPTED via the // per-tenant DEK seam (AD-8, packages/db/src/crypto/tenant-envelope.server.ts), // never plain. The Apps-Engine `App` catalog (appsEngine.prisma) is referenced // READ-ONLY through the bare `dataConnectionId` scalar — calendar owns its own // per-user connection lifecycle (RLS here is tenant- AND owner-scoped in code). // // RLS is LIVE since 20260713190000_appwide_rls_cutover (ENABLE+FORCE on all // calendar tables); prisma/rls/calendar-isolation.sql remains the // feature-branch template for db-push-only databases. Tables are tracked in // 20260703150000_ak_schema_parity_catchup. Leak-protection (DoD 3): // external event contents are owner-only; availability exposes busy slots only. /// Calendar provider. v1 = google; microsoft → v2 (interface stays agnostic). enum CalendarProvider { google } /// Sync direction of a connection (M25 Block D). Default bidirectional. enum CalendarSyncDirection { bidirectional hivegrid_to_external_only external_to_hivegrid_only } /// Lifecycle status of a calendar connection (M25 Block A/C). enum CalendarConnectionStatus { active paused error revoked } /// Whether an event originates in HiveGrid or is a read-only external mirror. enum CalendarEventSource { hivegrid_internal external_synced } /// Worker processing state of an inbound webhook notification (M25 Block E). enum CalendarWebhookProcessingStatus { pending processing completed failed skipped } /// How a sync conflict was resolved (M25 Block F — Last-Write-Wins variants). enum CalendarConflictResolution { external_won hivegrid_won external_deleted hivegrid_deleted } /// A user's connection to an external calendar provider. PER-USER, tenant-scoped /// for isolation. The OAuth tokens are AES-256-GCM per-tenant-DEK envelopes /// (AD-8); never selected into a list view-model. `dataConnectionId` is an /// OPTIONAL read-only reference to the Apps-Engine DataConnection catalog entry /// (bare scalar, AD-21) — calendar runs autonomously if the catalog row is absent. model CalendarConnection { id String @id @default(cuid()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt tenantId String userId String provider CalendarProvider @default(google) // User-visible account identity (for the connection card). externalAccountEmail String externalAccountId String // Sensitive: per-tenant envelope ciphertext (AD-8). Never serialised to a VM. oauthRefreshTokenCiphertext String? oauthAccessTokenCiphertext String? oauthAccessTokenExpiresAt DateTime? // Granted OAuth scopes; a reduction by the user triggers a Klartext re-connect. oauthScopes String[] // Provider push-subscription handle (Google channel.id) + renewal anchor. webhookSubscriptionId String? webhookSubscriptionExpiresAt DateTime? // JSON list of selected external calendars to sync (default: primary). selectedCalendars Json @default("[]") syncDirection CalendarSyncDirection @default(bidirectional) status CalendarConnectionStatus @default(active) lastSyncAt DateTime? // Klartext failure detail when status = error (M002). lastErrorText String? // Read-only Apps-Engine catalog reference (AD-21 bare scalar, optional). dataConnectionId String? isDemoData Boolean @default(false) archivedAt DateTime? events CalendarEvent[] mappings CalendarEventMapping[] syncCursors CalendarSyncCursor[] webhookEvents CalendarWebhookEvent[] conflicts CalendarConflict[] @@unique([tenantId, userId, provider, externalAccountId]) @@index([tenantId, userId, status, archivedAt]) @@index([tenantId, webhookSubscriptionExpiresAt]) } /// Cache of external events + HiveGrid-internal events. Tenant- and owner-scoped. /// External events are owner-only (leak-protection, DoD 3); availability reads /// only `isBusyForAvailability` busy intervals, never titles. `internalEntityLink` /// is a polymorphic JSON pointer to a Booking/Projekt/Plantafel entity. model CalendarEvent { id String @id @default(cuid()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt tenantId String userId String connectionId String? source CalendarEventSource provider CalendarProvider? externalEventId String? externalCalendarId String? title String? description String? location String? startsAt DateTime endsAt DateTime isAllDay Boolean @default(false) timeZone String? recurrenceRule String? attendees Json @default("[]") // Provider concurrency token (Google etag) for conflict detection. etag String? lastModifiedExternal DateTime? isBusyForAvailability Boolean @default(true) internalEntityLink Json? // Monotonic HiveGrid-side version for optimistic locking (M25 Block F). versionToken Int @default(0) isDemoData Boolean @default(false) archivedAt DateTime? connection CalendarConnection? @relation(fields: [connectionId], references: [id], onDelete: SetNull) mappings CalendarEventMapping[] @@unique([tenantId, userId, provider, externalEventId]) @@index([tenantId, userId, startsAt]) @@index([tenantId, userId, lastModifiedExternal(sort: Desc)]) @@index([tenantId, source, archivedAt]) } /// Links a HiveGrid-internal event to its external mirror(s). One internal event /// can map to several providers/calendars (e.g. Google + Microsoft in v2). model CalendarEventMapping { id String @id @default(cuid()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt tenantId String internalEventId String externalEventId String provider CalendarProvider externalCalendarId String connectionId String lastSyncedAt DateTime? lastKnownExternalEtag String? lastKnownInternalVersionToken Int? internalEvent CalendarEvent @relation(fields: [internalEventId], references: [id], onDelete: Cascade) connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade) @@unique([internalEventId, provider, externalCalendarId]) @@index([tenantId, connectionId]) @@index([tenantId, connectionId, provider, externalEventId]) } /// Per-connection-per-calendar delta cursor (Google syncToken). Drives the /// incremental external→HiveGrid sync (M25 Block D/E). model CalendarSyncCursor { id String @id @default(cuid()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt tenantId String connectionId String externalCalendarId String cursorToken String? lastFullSyncAt DateTime? connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade) @@unique([connectionId, externalCalendarId]) @@index([tenantId, connectionId]) } /// Persisted inbound webhook notification (idempotency + retry, M25 Block E). /// A fast 200 is returned to the provider; a worker drains `pending` rows. model CalendarWebhookEvent { id String @id @default(cuid()) receivedAt DateTime @default(now()) tenantId String connectionId String provider CalendarProvider notificationPayload Json processingStatus CalendarWebhookProcessingStatus @default(pending) processingErrorText String? processedAt DateTime? // Provider-specific resource state (Google X-Goog-Resource-State). externalResourceState String? connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade) @@index([tenantId, processingStatus, receivedAt]) @@index([tenantId, connectionId]) } /// A resolved sync conflict (DoD 4). The connection-detail view shows the latest /// 50 with a Klartext description + how it was resolved (Last-Write-Wins). model CalendarConflict { id String @id @default(cuid()) createdAt DateTime @default(now()) tenantId String connectionId String userId String internalEventId String? externalEventId String? resolution CalendarConflictResolution // Klartext description shown in the conflict log (M002/M003 key + rendered text). descriptionText String isDemoData Boolean @default(false) connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade) @@index([tenantId, connectionId, createdAt(sort: Desc)]) @@index([tenantId, userId]) }