Files
HiveGrid-Wireframes/hivegrid-cloud/docs/boilerplate-mapping/M25-calendar-sync.md
T

117 lines
18 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Boilerplate-Abgleich — Modul M25 (Calendar-Sync)
**Modul-ID:** M25 (Block 5 / Pflichtenheft 25.x)
**Name:** Calendar-Sync (Google + Microsoft, bidirektional)
**Milestones:** M118 (Google+MS via Apps-Engine), M119 (Termin-Sync + Konflikt), M120 (Display + Modul-Verknüpfung + Activity-Stream)
**Block:** block5.md §§ 25.1–25.7 (+ Phase-2 25.8)
**Reuse-Level:** **low**
> Begründung Reuse-Level: Es gibt in der Boilerplate **keinen** Calendar-, OAuth2-Connect-, Google-Calendar- oder Microsoft-Graph-Code und **kein** zugehöriges Datenmodell. Die fünf fachlichen Kern-Entitäten (`CalendarConnection`, `CalendarEvent`, `CalendarEventMapping`, `CalendarSyncCursor`, `CalendarWebhookEvent`), das `CalendarAdapter`-Interface, der bidirektionale Sync, das Webhook-Push-Subsystem und die Verfügbarkeits-Berechnung müssen komplett neu gebaut werden. Was vorhanden ist, ist **Querschnitt-Fundament** (Token-Verschlüsselung, SSRF-Schutz, Outbox/Queue/Cron, Notifications, Audit, Adapter-Registry, Webhook-HMAC-Verify, EU-Provider-Pattern) — solide, aber nur Bausteine, kein fertiges Modul. Damit klar über „none", aber nicht „medium".
---
## Übernehmbar aus Boilerplate
| Boilerplate-Pfad | Was | Wie nutzbar |
|---|---|---|
| `packages/foundation/src/adapters.ts` | `defineAdapter()` / `getAdapter()` + `AdapterStatus` (`not_configured`/`configured`/`healthy`/`degraded`/`unavailable`) | als-vorlage — Registry-Muster für das `CalendarAdapter`-Interface (Block G). Das vorhandene `AdapterDefinition` ist generisch (`key`/`status`/`adapter`); die calendar-spezifische Methoden-Signatur (`initiateOAuth`/`fetchEventsDelta`/`createEvent`…) ist neu zu definieren. Status-Enum 1:1 nutzbar für Connection-Health. |
| `apps/web/app/utils/api/.server/CryptoApi.ts` | AES-256-GCM `encrypt`/`decrypt` (versionierter Payload `version:iv:tag:ciphertext`), Key via Hash | anpassen — direktes Vorbild für `oauth_refresh_token`/`oauth_access_token` at-rest (Block C, Token-Storage). Spec verlangt envelope-encryption mit tenant-spezifischem KMS-Schlüssel — CryptoApi ist single-key; für Tenant-Key/KMS erweitern. |
| `apps/web/app/utils/leads/marketingIntegrations.db.server.ts` | `encryptSensitive`/`decryptSensitive` über `SENSITIVE_KEYS` + `CRYPTO_TAG`-Präfix; „Admin-UI zeigt entschlüsselte Secrets nie erneut" | als-vorlage — exakt das Pattern für selektiv verschlüsselte Token-Felder in `CalendarConnection` + Never-Redisplay-Regel (Block C: „Logging niemals Token-Klartext"). |
| `packages/foundation/src/outbound-http.ts` (Subpath `@toolctrl/foundation/outbound-http`) | `fetchOutboundHttpWithRedirects`, `validateOutboundHttpUrl`, SSRF-Block (private/internal IPv4+IPv6, DNS-Resolve, Redirect-Limit, Timeout, Response-Size-Limit) | 1:1 — für jeden ausgehenden Provider-Call (Google/MS Token-Endpoint, Calendar-API, Webhook-Subscribe). Pflicht-Querschnitt. |
| `packages/api-client-ts/src/webhooks.ts` + `apps/api/src/webhooks/mailersend-signature.ts` | HMAC-SHA256-Verify mit `timingSafeEqual`, Timestamp-Toleranz, Header-Parsing (`webhook-signature`), typisierte Failure-Codes | als-vorlage — Vorbild für `verifyWebhookSignature(headers, body)` (Block G/E). Provider-spezifisch anzupassen (Google `X-Goog-Channel-Token`, MS `clientState`) — nicht HMAC, aber Verify-Struktur (constant-time, fail-closed, Failure-Codes) übernehmbar. |
| `packages/db/src/outbox.ts` + `prisma/schema/outbox.prisma` (`OutboxEvent`) | `publishOutboxEvent(tx, args)` in `$transaction`, `dispatchKey @unique` (Idempotenz), `eventType`-Pattern `<domain>.<entity>.<verb>` | 1:1 — Webhook-Empfang → DB-Write → async Verarbeitung (Block E, Schritt 3-5). `CalendarWebhookEvent` kann eigenständig sein ODER über Outbox laufen; Outbox-Idempotenz (`dispatchKey`) deckt „Provider duplizieren Notifications" (Block E Idempotenz) ab. |
| `apps/worker/src/outbox/event-router.ts` (`DEFAULT_OUTBOX_ROUTING`) | Prefix→Queue-Routing (longest-prefix-wins) | anpassen — neuen Prefix `calendar.` (z.B. `calendar.sync.*`) ergänzen, auf eine Worker-Queue routen. |
| `packages/queue` (`enqueueJob`, `buildIdempotentJobId`, Prioritäten) + `apps/worker` (Handler-Registry, Cron-Scheduler `*-cron.ts`, Gruppen/Concurrency) | BullMQ-Wrapper + single-instance Cron-Scheduler-Muster (`dsgvo-grace-cron.ts`, `lead-stale-trigger.ts`, `ai-cost-*-cron.ts`) | als-vorlage — (a) Sync-Worker (Webhook-Delta-Pull), (b) **Webhook-Subscription-Renewal-Cron** (Block E: alle 6h, Subscriptions die in 24h ablaufen). Cron-Job-Skelett + Idempotenz direkt übernehmbar. |
| `packages/foundation/src/notifications.ts` (`notify`, `bundleNotifications`, `assertI18nKey`, `NotificationPreferenceChannel` IN_APP/EMAIL) + `prisma/schema/notifications.prisma` | Tenant-pflichtige Notifications mit Preference-Check, Upsert per `sourceKey`, Bündelung | 1:1 — Konflikt-Notifications (Block F), Verbindungsfehler-Mails (Block C Re-Connect), „externe Version gewinnt"-Hinweis. INTEGRATION-CONTRACTS §7 verlangt ohnehin `notify()` statt Direkt-Mail. |
| `packages/foundation/src/audit.ts` (`auditEvent`, `withAuditMiddleware`) + `prisma/schema/core.prisma` (`AuditEvent`, Hash-Chain) | Audit-Trail mit Tamper-Evidence | 1:1 — Connect/Disconnect/Konflikte (AV #6, Spec „Audit-Trail-Default"). Da OAuth-Connect/Webhook-Calls außerhalb Prisma laufen, **manuelles** `auditEvent` nötig (INTEGRATION-CONTRACTS §6 Ausnahme). |
| `packages/foundation/src/permissions.ts` (`withTenantScope`, `withPermission`, `withOwnerCheck`, `requirePermission`; 404-statt-403) | Tenant-Scope + Permission- + Owner-Gating | 1:1 — `calendar.connect_own` (Owner-Check `connection.user_id = self`) + `calendar.admin` (Block I). Permission-Denied → 404 deckt Bauprinzip A.5.3 / DoD ab. |
| `prisma/schema/permissions.prisma` (`Role`/`Permission`/`RolePermission`/`UserRole`) | RBAC-Fundament | als-vorlage — die zwei atomaren Permissions + Bundles (Block I) sind neu zu seeden; das Modell trägt sie. HiveGrid-seitig `packages/entitlements/src/permissions.ts` (INTEGRATION-CONTRACTS §10). |
| `packages/foundation/src/idempotency.ts` (`withIdempotency`) + `prisma/schema/core.prisma` (`IdempotencyKey`) | Replay-sichere Mutationen, In-Process-Lock, Fingerprint-Hash | anpassen — für Webhook-Verarbeitung + Create/Update-Push (Optimistic-Locking-Ergänzung, Block F). |
| `packages/feature-flags` (`evaluateFlag`, Targeting, React-Hooks) + `prisma/schema/featureFlags.prisma` | Feature-Flag-Engine | 1:1 — DoD verlangt „Modul ohne Deploy abschaltbar". Connect-Button + Routes hinter `calendar`-Flag. |
| `packages/i18n` (Namespaces/Locales, `formatDate`/`formatRelativeTime`, `assertI18nKey`) | i18n + locale-explizite Datums-Formatierung | 1:1 — alle Klartext-Hinweise (Block J), Termin-Zeiten in Detail-View. DoD: alle UI-Texte als i18n-Keys. |
| `packages/view-models/src/index.ts` (`VMState`, `ActionCallbacks`, `RegistryGate`, `SidebarRegistryItem`, `ready`/`empty`) | VM-State-Maschine + Shell-Registry-Typen | 1:1 — Loader baut VM, UI empfängt nur VM+Actions (DoD Code-Layer + INTEGRATION-CONTRACTS §11). Loading-/Empty-/Error-State (Klartext-DoD). |
| `packages/foundation/src/errors.ts` (`CatalogError`, `foundationErrors`, `toPinoLogObject`) | Strukturierte Klartext-Fehler (`code`/`status`/`i18nKey`) | als-vorlage — Adapter-Klartext-Codes (Block G: `auth_token_expired`, `rate_limit_exceeded`, `provider_outage` …). Catalog-Einträge sind HiveGrid-spezifisch neu zu registrieren. |
| `packages/logger` (`createLogger` mit Redaction von `token`/`secret`/`apiKey`/`authorization`) | Pino-Logger mit Secret-Redaction | 1:1 — Block C „Logging niemals Token-Klartext" wird durch die eingebauten Redact-Paths abgedeckt. |
| `prisma/schema/notifications.prisma` (`DeviceToken`) + `apps/worker/src/jobs/push-notification.ts` | Push-Token + Push-Versand | 1:1 — Termin-Erinnerungen / Konflikt-Push (Pflichtenheft 22.7.4). Über `notify()` (Kanal-Entscheidung im Notification-Service). |
| `prisma/schema/entityBuilder.prisma` (`EntityView.layout` kennt `"calendar"`) | EntityView-Calendar-Layout-Enum (No-Code-Builder) | als-vorlage (schwach) — nur ein Layout-String, **keine** fertige Calendar-View-Component. Für M120 (Tag/Woche/Monat-Display) liefert die BP keinen Renderer; Component ist neu (Subframe-Design + ui-hivegrid). |
| `apps/api` (Hono-App, `route-access-inventory.ts`, `webhook-signature`-Route-Klasse, `error-envelope`, `request-id`, `body-limit`) | Public-API-Runtime mit Auth-Klassen-Matrix inkl. `webhook-signature` | als-vorlage — die öffentlichen Webhook-Endpoints `/webhooks/calendar/{provider}` (Block E, keine User-Auth, Provider-Signature) passen in die bestehende `webhook-signature`-Route-Klasse + Middleware-Kette. |
| `prisma/schema/appsEngine.prisma` (`App`, `DataConnection`, `AppSyncRun`, `AppSyncRunLog`, `AppSyncItem`) | Data-Sync-„Apps-Engine": App-Installation pro Tenant, **`DataConnection.config` = „Encrypted JSON credentials"**, Sync-Run mit `executionMode` manual/scheduled/webhook + Metriken (`itemsProcessed/Created/Updated/Failed`) + Rollback (`AppSyncItem.rolledBackData`) | als-vorlage — **wichtigstes Boilerplate-Modell für M118** (Milestone-Titel: „via Apps-Engine"). `DataConnection` kann die OAuth2-Verbindung tragen ODER als Muster für `CalendarConnection` dienen. `AppSyncRun`/`AppSyncRunLog` ist ein fertiges Sync-Lauf-/Log-Modell (Sync-Status, Konflikt-Logs Block F „letzte 50 Konflikte"). **Aber:** keine Provider-Logik, kein Cursor/Webhook-Modell, kein Event-Cache — nur Hülle. Entscheidung nötig: `appsEngine`-Modelle wiederverwenden vs. dedizierte `Calendar*`-Modelle in `app.prisma`. |
---
## Vorhandene Daten-Modelle (konkrete Prisma-Modelle mit Pfad)
Es gibt **kein** Calendar-spezifisches Prisma-Modell. Nutzbare/angrenzende Modelle:
- `prisma/schema/appsEngine.prisma` — `App`, `DataConnection` (verschlüsselte Credentials), `AppSyncRun`, `AppSyncRunLog`, `AppSyncItem`. **Am nächsten** an „Connection + Sync-Lauf + Konflikt-Log". Deckt aber `CalendarEvent`-Cache, `CalendarEventMapping`, `CalendarSyncCursor`, `CalendarWebhookEvent` **nicht** ab.
- `prisma/schema/outbox.prisma` — `OutboxEvent` (`dispatchKey @unique`, Idempotenz, `priority`, `lockedUntil`). Für Webhook→Worker-Entkopplung + Dedup.
- `prisma/schema/notifications.prisma` — `NotificationDelivery`, `UserNotificationPreference`, `DeviceToken`. Konflikt-/Fehler-Notifications + Push.
- `prisma/schema/core.prisma` — `AuditEvent` (Connect/Disconnect/Konflikt-Audit), `IdempotencyKey`, `Credential` (globaler Secret-Store, `value Json`).
- `prisma/schema/accounts.prisma` — `User`, `Tenant`, `TenantUser` (User-/Tenant-Anker; pro-User-Connection-Scoping). `WorkspaceAuthProvider` (inbound SSO/OIDC — **nicht** outbound OAuth-Connect, nur als Feld-Vorbild `authorizationUrl`/`tokenUrl`/`clientId`).
- `prisma/schema/permissions.prisma` — `Permission`/`Role`/`UserRole` für `calendar.connect_own` / `calendar.admin`.
- `prisma/schema/featureFlags.prisma` — `FeatureFlag` (Modul-Abschaltung).
- `prisma/schema/app.prisma` — **leerer Platzhalter** (`// custom database models`): vorgesehener Ort für die neuen `Calendar*`-Modelle.
**Neu zu erstellende Modelle (alle, gemäß Spec Block A):** `CalendarConnection`, `CalendarEvent`, `CalendarEventMapping`, `CalendarSyncCursor`, `CalendarWebhookEvent` — in `prisma/schema/app.prisma` (oder eigene `calendar.prisma`). Pflicht: tenant-scoped + RLS, FK auf `User`/`Tenant`, Eintrag in `packages/db/src/dsgvo/user-fk-map.ts` (CI-Gate bricht sonst — DSGVO Block, Spec „Account-Löschung → harte Löschung der Event-Caches").
---
## Lücken / komplett neu zu bauen
**Datenmodell**
- Alle fünf `Calendar*`-Modelle inkl. Indizes/Constraints (Block A) — nicht vorhanden.
- `user-fk-map.ts`-Einträge für die neuen User-FK-Modelle (DSGVO, Pflicht-Gate).
**Provider-Integration (Kern, fehlt vollständig)**
- `CalendarAdapter`-Interface mit allen Methoden (Block G): `initiateOAuth`, `handleOAuthCallback`, `refreshAccessToken`, `listCalendars`, `subscribeWebhook`/`unsubscribeWebhook`/`renewWebhook`, `fetchEventsInitial`/`fetchEventsDelta`, `createEvent`/`updateEvent`/`deleteEvent`, `verifyWebhookSignature`.
- **Google-Adapter** (Calendar API v3, Push-Notification-Channels, `syncToken`, `If-Match`/etag) — neu.
- **Microsoft-Adapter** (Graph Calendar, Subscriptions/`deltaLink`, `clientState`, Azure-AD-Multi-Tenant-App + Admin-Consent-Flow) — neu.
- OAuth2-Connect-Flow Ende-zu-Ende (state-Token signiert mit `tenant_id+user_id`, code↔token-Exchange, User-Info-Fetch) — **kein** outbound-OAuth-Connect existiert (nur inbound SSO/OIDC + ein GitHub-Service `apps/web/app/utils/integrations/githubService.ts`, das als loses Vorbild taugt).
**Sync-Engine (fehlt)**
- Bidirektionaler Sync (Block D): Schreib-Pfad HiveGrid→extern (Booking/Projekt/Plantafel/Tasks-Spiegelung, Mehrfach-Provider-Mappings), Lese-Pfad extern→HiveGrid (Initial-Full-Pull -7/+60, inkrementell via Cursor, „Free"-Filter, Private→„Privat"-Titel-Reduktion).
- Konflikt-Handling Last-Write-Wins-mit-Sichtbarkeit (Block F): 412-Precondition-Failed-Behandlung, „externe Version gewinnt" + Restore-Option, Mapping-Cleanup bei extern gelöschten Events, `last_known_internal_version_token`-Check.
**Webhook-Subsystem (fehlt fachlich)**
- Provider-Webhook-Empfangs-Endpoints `/webhooks/calendar/{provider}` mit Provider-spezifischer Signature-Verifikation (Google `X-Goog-Channel-Token`, MS `clientState`) — generisches HMAC-Verify-Muster vorhanden, aber Provider-Logik neu.
- **Subscription-Renewal-Cron** (Google ~1 Woche, MS ~3 Tage; alle 6h, Renewal in 24h-Fenster) — Cron-Skelett vorhanden, Logik neu.
- 410-Gone → Full-Resync.
**Verfügbarkeits-Berechnung (fehlt, Block H)**
- Slot-Engine: Working-Hours + interne Events + externe Busy-Events + Plantafel → freie Slots; 30-Tage-Slot-Cache mit Invalidierung bei `CalendarEvent`-Update; DSGVO-Filterung (Booking erhält nur `is_available`-Boolean, nie Event-Inhalt). Hängt an Modul 6/M126.
**Querschnitt-Wiring (HiveGrid-seitig neu zu verdrahten)**
- Sidebar-Eintrag „Termine" (Gruppe ARBEITEN, M120) + Settings-Eintrag „Integrationen → Kalender" in `packages/ui-hivegrid/src/app-shell/sidebar.config.ts`.
- Routes (Block B / INTEGRATION-CONTRACTS §3): `settings/integrationen/calendar/...` + Connect/Callback + `:connection_id`-Detail.
- Calendar-Display-Component (Tag/Woche/Monat) für M120 — kein BP-Renderer vorhanden (Subframe-Design Pflicht, siehe Memory `feedback_subframe_mandatory`).
- Activity-Stream-Hooks (`logActivity`): `calendar_connected`/`_disconnected`/`_sync_error`/`appointment_synced_external` — bewusst NICHT pro Event-Update (M120 / INTEGRATION-CONTRACTS §5).
- Off-Boarding-Hook (Block I / Modul 27): User-Deaktivierung → Connections `paused`, Webhooks abmelden; Hard-Delete → Caches hart löschen.
- Tenant-spezifische KMS/Envelope-Encryption für Refresh-Tokens (Spec verlangt Tenant-Key; CryptoApi ist single-key — Erweiterung nötig).
**Anti-Liste (Phase 2, NICHT bauen):** iCal-Feed, Resource-Calendar, Tenant-Zentral-Connection, Apple/iCloud-CalDAV, FastMail, konfigurierbares Sync-Fenster, Multi-Calendar-Settings-UI, Color-Sync, KI-Konflikt-Resolution, erweiterte Zeitzonen, Recurring-Event-Single-Instance-Edits.
---
## Empfohlenes Vorgehen
1. **Querschnitt zuerst aus BP verdrahten (1:1):** `withTenantScope`/`withPermission`/`withOwnerCheck` (Permissions), `notify`/`auditEvent` (Konflikt/Connect-Audit), `VMState`/`ActionCallbacks` (VM-Layer), `i18n`-Keys + `formatDate`, `feature-flags` (Modul-Abschaltung), `outbound-http` (SSRF für alle Provider-Calls), `logger` (Token-Redaction). Permissions `calendar.connect_own`/`calendar.admin` in `packages/entitlements/src/permissions.ts` + seed.
2. **Datenmodell (M118):** Die fünf `Calendar*`-Modelle in `app.prisma`/`calendar.prisma` anlegen (Block A, inkl. Indizes/Unique-Constraints), `user-fk-map.ts` ergänzen, Forward-Only-Migration mit Inverse-SQL-Kommentar (DoD). **Vorab entscheiden:** `appsEngine`-Modelle (`DataConnection`/`AppSyncRun`/`AppSyncRunLog`) wiederverwenden für Connection+Sync-Lauf+Konflikt-Log, oder dedizierte Modelle — `appsEngine` ist die nächste Vorlage, deckt aber Cache/Cursor/Webhook nicht und vermischt zwei „Apps-Engine"-Bedeutungen (siehe Inventur integrations-ki §4.4).
3. **Token-Storage (M118):** `CryptoApi`/`marketingIntegrations`-Verschlüsselungs-Pattern als Vorlage; auf Tenant-Key/KMS-Envelope erweitern (Spec/AV #13). Never-Redisplay-Regel übernehmen.
4. **Adapter-Pattern (M118):** `CalendarAdapter`-Interface (Block G) definieren; Google- und MS-Adapter neu implementieren; Klartext-Fehler-Codes als `CatalogError`-Katalog (Block G/J) registrieren. OAuth-Connect/Callback-Routes über `apps/api`-Webhook/Auth-Klassen-Muster + `outbound-http`.
5. **Webhook + Sync-Worker (M118→M119):** Public Webhook-Endpoints (Provider-Signature-Verify nach `mailersend-signature`-Muster) → `CalendarWebhookEvent`/Outbox (`dispatchKey`-Idempotenz) → BullMQ-Sync-Worker (Cursor-Delta-Pull). `calendar.`-Prefix in `event-router.ts`. Renewal-Cron nach `*-cron.ts`-Muster.
6. **Bidirektionaler Sync + Konflikt (M119):** Schreib-Pfad (Spiegelung Booking/Projekt/Plantafel, Mehrfach-Provider-Mappings), Lese-Pfad (Privacy-Reduktion), Last-Write-Wins-mit-Restore-Option via `notify`.
7. **Verfügbarkeit + Display (M119/M120):** Slot-Engine + Cache (an Modul 6/M126 koppeln); Calendar-View-Component via Subframe neu (kein BP-Renderer); Activity-Stream-Hooks; Sidebar/Route/Breadcrumb-Wiring; Off-Boarding-Hook.
8. **DoD-Schluss je Milestone:** Smoke-Test je Route, Hot-Swap-Drill gegen `ui-mock`, Visual-Snapshot, Permission-Denied→404, Feature-Flag, Customer-Portal-Sichtbarkeit explizit (default NICHT sichtbar).
---
### Quellen-Hinweis
Alle Aussagen direkt in `/Users/raffaelsheikh/Documents/GitHub/boilerplate` verifiziert (Greps auf `calendar|ical|google.?calendar|microsoft.?graph|oauth2|encrypt`, gelesene Dateien: `foundation/src/adapters.ts`, `CryptoApi.ts`, `marketingIntegrations.db.server.ts`, `api-client-ts/src/webhooks.ts`, `mailersend-signature.ts`, `appsEngine.prisma`, `entityBuilder.prisma`, `outbox/event-router.ts`). **Kein** Calendar-/OAuth-Connect-/Provider-Code gefunden.