# HiveGrid Intel — Requirements (SPEC Extraction) Extracted from 36 module specs + 1 INTEGRATION-CONTRACTS spec. One REQ-{slug} entry per major requirement cluster per spec. extracted: 2026-06-07 --- ## Modul 1 — CRM-Kern source: _bmad-output/specs/M01-crm-kern.md ### REQ-crm-datenmodell Typisierte First-Class-Prisma-Tabellen für Contact, Company, Lead, ContactCompanyRelation, ContactEmail, ContactPhone, Activity, CustomFieldDefinition, CustomFieldValue, Tag, EntityTag. Kein polymorphes Entity/Row/RowValue-Schema (AD-2). RLS-Policies auf allen Tabellen (AD-1). Acceptance criteria: - Contact hat: id, tenant_id, salutation, title, first_name (Pflicht), last_name (Pflicht), address_*, birthdate, notes, language, assigned_to_user_id, lead_source, is_endkunde, archived_at - Company hat: id, tenant_id, name (Pflicht), legal_form, vat_id, tax_number, industry, website, address_*, notes, assigned_to_user_id, archived_at - Lead hat: id, tenant_id, first_name, last_name, email, phone (alle nullable), message, source (Enum), status (Enum: new|qualified|converted|lost|spam), assigned_to_user_id, converted_to_contact_id, converted_to_deal_id, archived_at - ContactCompanyRelation: M:N mit role, is_primary, since_date, until_date - Index auf tenant_id, archived_at, last_activity_at; trigram-Index auf Namensfeldern ### REQ-crm-listen-views Kontakt-Liste und Firmen-Liste mit server-seitiger Filter-/Sortier-/Paginierungs-Logik, Bulk-Actions, Export als CSV. Acceptance criteria: - Server-side-Filter (kein Client-side bei 10.000+ Einträgen) - Cursor-basierte Pagination (50/Page, "Mehr laden") - Bulk-Actions: Tag hinzufügen/entfernen, Verantwortlicher zuweisen, Archivieren, CSV-Export - Filter: Verantwortlicher, Tags (AND/OR), Firma, Erstellt-Datum, Custom-Felder - Spalten-Konfiguration per User (persistiert) ### REQ-crm-detail-views Kontakt-Detail, Firma-Detail, Lead-Detail mit Inline-Edit, Activity-Stream, verknüpften Entitäten, Custom-Feldern. Acceptance criteria: - Inline-Edit pro Feld mit Save/Cancel - Activity-Stream-Komponente integriert - Verknüpfungs-Verwaltung (Firmen ↔ Kontakt mit Rolle, M:N) - Permissions: crm.read_own (404 statt 403 bei Fremdzugriff), crm.write, crm.delete, crm.admin ### REQ-crm-lead-promotion Lead-zu-Contact-Promotions-Modal mit Auto-Email-Match-Check und Transaktions-Sicherheit. Acceptance criteria: - 4 Optionen: (a) existing Contact aktualisieren, (b) neuen anlegen, (c) manuell zuordnen, (d) als Spam markieren - Optional: Firma suchen/anlegen + Rolle, Deal anlegen (Default ja) - Transaktionale Anlage: Contact + ggf. Company + ContactCompanyRelation + ggf. Deal; Lead.status = converted + FKs gesetzt ### REQ-crm-activity-stream Zentrale Activity-Tabelle (Event-Sourcing) mit allen Modulen als Schreiber; chronologische Stream-View pro Entität. Acceptance criteria: - Felder: id, tenant_id, created_at, actor_user_id, actor_kind, activity_type (Enum), subject_type, subject_id, related_entity_refs[], metadata, summary_text (DE, Pflicht) - 18+ Activity-Typen (call_inbound, email_sent, deal_stage_changed, lead_promoted, automation_triggered usw.) - Activities sind read-only (nicht löschbar) - Index auf tenant_id, subject_type, subject_id, created_at DESC - Filter nach Typ, Actor, Zeitraum; Cursor-basierte Pagination ### REQ-crm-custom-felder CustomFieldDefinition + CustomFieldValue pro Tenant, anwendbar auf Contact/Company/Lead/Deal. Acceptance criteria: - Typen: text, number, date, select, multiselect, boolean, url, email - field_key (snake_case, unique pro applicable_to + tenant) unveränderlich; nur label änderbar - Verwaltungs-Route: Drag-&-Drop-Sortierung, Add/Edit/Archive/Hard-Delete - Anwendung in Listen-Views als Filter und Spalte (Phase 1) - SHK-Branchen-Template-Defaults: geseedet beim Tenant-Anlegen (nicht hardcoded) ### REQ-crm-duplikat-erkennung Live-Match-Check beim Anlegen + Bulk-Duplikat-Tool für Admins. Acceptance criteria: - Hard-Match: Email exakt (case-insensitive), Telefon exakt (normalisiert) - Soft-Match: Name + Firma identisch, Name + PLZ identisch - Live-Check debounced beim Tippen von Email/Telefon - Bulk-Duplikat-Tool: Side-by-Side-Anzeige, Field-by-Field-Merge, Skip-Funktion - Permission: Inline-Hinweis für crm.write; Bulk-Tool nur crm.admin ### REQ-crm-tags Tag-System mit ad-hoc-Erstellung, Farbgebung, Entity-übergreifend. Acceptance criteria: - Tag: id, tenant_id, name (unique pro Tenant + applicable_to), color (8 vordefinierte Farben), applicable_to[] - Ad-hoc-Erstellung mit crm.write-Permission - Verwaltungs-Route: Umbenennen, Farbe ändern, Merge, Hard-Delete, Auto-Cleanup-Toggle - Verwendung in Listen-Filter (AND/OR), Automation-Engine als Trigger/Action ### REQ-crm-permissions Permission-Bundle crm.* für alle CRM-Entitäten. Acceptance criteria: - Permissions: crm.read_own, crm.read_all, crm.write, crm.delete, crm.admin - Owner-Check: 404 (nicht 403) bei Fremdzugriff mit read_own - Server-side Permission-Filter in allen Listen (Permissions-aware-Default, AV #5) - Audit-Trail für alle schreibenden Aktionen (AV #6) --- ## Modul 2 — Lead-Inbox source: _bmad-output/specs/M02-lead-inbox.md ### REQ-lead-inbox-liste Lead-Inbox als Arbeitsplatz mit Status-Filter, Triage-Quick-Actions, Bulk-Operations. Acceptance criteria: - Default-Filter: Status new + qualified; Spam ausgeblendet; Konvertierte ausgeblendet - Quick-Actions pro Zeile ohne Drilldown: Zuweisen, Status setzen, Zu Contact promovieren, Spam markieren - Saved Views (User-spezifisch, max. 5 in Phase 1) - Real-time-Refresh bei neuem Lead (SSE oder Polling 30 Sek) - Index auf tenant_id, status, created_at DESC; trigram auf email, phone, last_name ### REQ-lead-quellen-auto-anlage Automatische Lead-Anlage aus Form-Submission, eingehender Mail, AirCall-Inbound-Anruf. Acceptance criteria: - Form → Lead (source=form, metadata.form_id, metadata.submission_id) - Mail → Lead (source=email, kein Auto-Merge, Mensch entscheidet) - AirCall-Inbound unbekannte Nummer → Lead (source=phone, Verantwortlicher = AirCall-Empfänger) - Manuell: Route /leads/new mit Inline-Match-Check - Trigger für Automation-Engine: lead.created-Event ### REQ-lead-status-workflow Status-Enum (new|qualified|converted|lost|spam) mit definierten Übergängen und DSGVO-Auto-Lösch. Acceptance criteria: - Spam → Hard-Delete nach 30 Tagen (täglicher Cron) - Lost → Hard-Delete nach 90 Tagen (Tenant-Admin-konfigurierbar, 0=nie) - converted ist Terminal-Status (nicht änderbar) - Vor Hard-Delete: anonymisierter Activity-Trail bleibt, Audit-Log-Eintrag bleibt ### REQ-lead-anti-spam Rate-Limiting und Anomalie-Detection für Lead-Quellen. Acceptance criteria: - Hard-Limit: 100/h pro Quelle, 20/h pro IP (konfigurierbar) - Anomalie-Detection: 10x-Normal-Rate-Spike → Auto-Pause + Tenant-Admin-Notification - Auto-Mark-as-Spam-Heuristiken optional (IP-Blocklist, Disposable-Email, Honeypot, <3-Sek-Submission) - Quarantäne-Modus (Standard): Spam-Verdacht → Status new mit Marker, KEIN Auto-Spam - Klartext-Notification mit [Reaktivieren]-Aktion ### REQ-lead-statistiken Statistiken-Page mit KPIs, Quellen-Aufschlüsselung, Trend-Charts. Acceptance criteria: - KPI-Kacheln: Eingegangene Leads, Konvertierungsrate Lead→Contact, Lead→Deal-won, Reaktionszeit, Spam-Quote, Open-Leads - Aufschlüsselung nach Quelle, Verantwortlichem, Tag, Wochentag/Tageszeit, Status-Verteilung - Aggregat-Query mit Materialized View oder Cron-aggregierter Statistik-Tabelle (täglich neu) - Permission: read_own = nur eigene; Verantwortlichen-Aufschlüsselung nur mit read_all ### REQ-lead-permissions Permission-Bundle leads.* mit Owner-Check-Logik. Acceptance criteria: - Permissions: leads.read_own, leads.read_all, leads.write, leads.delete, leads.admin - Promotion: erfordert leads.write UND crm.write - Bulk-Export: leads.admin - Permission-aware Server-side-Filter in allen Listen --- ## Modul 3 — Sales-Pipeline source: _bmad-output/specs/M03-sales-pipeline.md ### REQ-sales-datenmodell Multi-Pipeline-Architektur mit Pipeline, PipelineStage, Deal, LostReason, HiveNumberSeq. Acceptance criteria: - Pipeline hat: id, tenant_id, name, is_default, position, archived_at - PipelineStage hat: stage_kind (open|won|lost), win_probability (0–100), auto_archive_after_days, color - Validation: Pipeline muss mind. 1 won- und 1 lost-Stage haben - Deal hat: deal_number (fortlaufend über HiveNumberSeq), pipeline_id, stage_id, title (Pflicht), volume (numeric 12,2), currency, expected_close_date, actual_close_date, contact_id (Pflicht), company_id, lead_id, lost_reason_id, won_handoff_project_id - LostReason: Pflicht bei Stage=lost; SHK-Template seedet 5 Standard-Reasons ### REQ-sales-kanban-listen-view Kanban-View (Drag-&-Drop) und Listen-View (tabellarisch), beide mit Filter, Bulk-Actions, Real-Time-Updates. Acceptance criteria: - Drag in won-Stage: Bestätigungs-Dialog mit Won-Handoff-Option - Drag in lost-Stage: Bestätigungs-Dialog erzwingt lost_reason-Auswahl - Reverse-Window: Won/Lost innerhalb 24h zurücknehmbar - Real-Time-Updates bei Stage-Wechsel durch andere User (WebSocket oder SSE) - Aggregat-Cache pro Stage (Anzahl + Volumen-Summe), invalidiert bei Stage-Wechsel ### REQ-sales-deal-lifecycle Deal-Anlage aus mehreren Quellen, Stage-Wechsel-Validation, Won-Handoff zu M4, Auto-Archive. Acceptance criteria: - Anlage-Quellen: manuell, Lead-Promotion, Form-Submission, Email, Anruf, Automation - Won-Handoff: Trigger M4 zur Projekt-Anlage mit Mapping Deal-Felder → Projekt-Felder; Deal.won_handoff_project_id gesetzt - Auto-Archive: Won nach 30 Tagen, Lost nach 90 Tagen (konfigurierbar) - Stage-Stuck-Detection: Daily-Cron markiert Deals länger als Schwelle in Stage; Automation-Trigger deal.stuck.in_stage ### REQ-sales-forecast-kpis Forecast-Berechnung, KPIs pro Vertriebler, Stage-Conversion-Rates, Lost-Reason-Auswertung. Acceptance criteria: - Pipeline-Forecast: Summe volume × stage.win_probability / 100 (nach Zeitraum aufteilbar) - KPIs: aktive Deals, Won-Rate, Cycle-Time, Stuck-Deals, Aktivitäts-Metriken - Stage-Conversion-Rates aus Activity-Daten - Aggregat-Cache pro Pipeline + Zeitraum ### REQ-sales-field-level-permissions Field-Level-Permissions für Volumen und Aggregate. Acceptance criteria: - Permissions: deals.read_volume_own, deals.read_volume_all, deals.read_aggregates, deals.read_close_date_all - Volumen ohne Permission: zeigt "—" (kein expliziter Fehler) - Aggregat-Volumen pro Stage-Spalte ausgeblendet ohne read_aggregates - SHK-Rollen-Template-Defaults geseedet --- ## Modul 4 — Auftrags-/Projektpipeline source: _bmad-output/specs/M04-auftragspipeline.md ### REQ-projekt-datenmodell ProjectPipeline, ProjectPipelineStage, Project, ProjectMember, ScheduleEntry, AcceptanceProtocol, ProjectTemplate. Acceptance criteria: - Multi-Pipeline analog M03 (SHK-Pipelines geseedet) - Project: id, tenant_id, deal_source_id, pipeline_id, stage_id, title, volume, contact_id, company_id, assigned_to_user_id, archived_at - ProjectMember: Rollen-basiert (Projektleiter, Bauleiter, Monteur) - AcceptanceProtocol: digitale Abnahme mit Unterschrift - ProjectTemplate: wiederverwendbare Vorlagen mit Stages + Standard-Tasks ### REQ-projekt-plantafel Plantafel-Ansicht für Ressourcen-Scheduling und Auftragszuweisung. Acceptance criteria: - ScheduleEntry: project_id, user_id (Monteur), date, start_time, end_time - Plantafel zeigt Auftrage pro Monteur/Tag - Konflikte erkennbar (Überschneidungen) - Bearbeitung offline möglich (AD-17) ### REQ-projekt-abnahme Abnahme-Protokoll direkt im Projekt mit digitaler Unterschrift. Acceptance criteria: - AcceptanceProtocol: project_id, signed_by_customer_name, signature_data (Base64), signed_at, form_answers (JSONB) - Abnahme-Templates aus M05 Form-Builder verwendbar - Offline-Abnahme mit Sync-Queue (AD-17) --- ## Modul 5 — Form Builder source: _bmad-output/specs/M05-form-builder.md ### REQ-form-datenmodell Form, FormField, FormSubmission, FormSubmissionAnswer, FormFile, FormLink, FormAction, FormActionLog. Acceptance criteria: - Form: id, tenant_id, slug (unique), title, description, status (draft|published|archived), settings (JSONB) - FormField: Typen text, email, phone, number, date, select, multiselect, checkbox, file, signature, textarea, hidden - FormSubmission: form_id, tenant_id, submitted_at, ip_address, answers (JSONB), source_url - FormLink: öffentliche Share-URL + embed_code - FormAction: Lead-anlegen, Deal-anlegen, Task-anlegen, Webhook, Email, Notification ### REQ-form-editor Drag-&-Drop-Form-Editor mit Echtzeit-Vorschau, Validierung, Conditional Logic. Acceptance criteria: - Drag-&-Drop für Feld-Reihenfolge - Conditional-Logic: Feld X anzeigen wenn Feld Y = Wert Z (Phase 1: einfache Bedingungen) - Form-Templates (SHK-Vorlagen geseedet) - Embed-Code für iFrame-Einbettung - Honeypot-Feld (Anti-Spam-Kooperation mit M02) ### REQ-form-actions Form-Actions nach Submission: Lead/Deal/Task anlegen, Webhook, Email, Automation-Trigger. Acceptance criteria: - Field-Mapping konfigurierbar (Form-Feld → Ziel-Entitäts-Feld) - Multiple Actions pro Form möglich - FormActionLog: Protokollierung jeder Action-Ausführung - Fehler in Action: Submission selbst bleibt gespeichert; ActionLog markiert Fehler --- ## Modul 6 — Booking source: _bmad-output/specs/M06-booking.md ### REQ-booking-datenmodell BookingPage, BookingPageProvider, AvailabilityRule, AvailabilityException, Appointment. Acceptance criteria: - BookingPage: tenant_id, slug (unique), title, duration_minutes, buffer_before/after, max_advance_days, min_notice_hours - AvailabilityRule: weekday, start_time, end_time, timezone - AvailabilityException: specific_date, is_blocked, slots[] - Appointment: booking_page_id, contact_id (oder anonymer Guest), start_at, end_at, status (scheduled|completed|cancelled), confirmation_token ### REQ-booking-slot-kalkulierung Slot-Berechnung unter Berücksichtigung von Verfügbarkeitsregeln, Ausnahmen, Kalender-Sync und Puffer. Acceptance criteria: - Slots berechnet aus AvailabilityRules + AvailabilityExceptions + verbundene Kalender-Events (M25) - Puffer vor/nach Termin berücksichtigt - Timezone-aware Darstellung - Public Booking Page ohne Auth erreichbar (Route /buch/{tenant}/{slug}) ### REQ-booking-integrationen Lead-Inbox-Integration, Activity-Stream, Form-Submission-Verknüpfung, Bestätigungs-Email. Acceptance criteria: - Neuer Termin → Appointment-Bestätigungs-Email (via M09/M22) - Termin → Activity-Eintrag appointment_scheduled - Kein passender Contact → Lead angelegt (source=booking) - iFrame-Embed-Code verfügbar --- ## Modul 7 — Angebot + Signatur source: _bmad-output/specs/M07-angebot-signatur.md ### REQ-signatur-datenmodell DealSignatureDocument, DealSignatureSigner, DealSignatureStatusTransition, SignatureProviderConnection. Acceptance criteria: - DealSignatureDocument: deal_id, provider (pandadoc|docusign), provider_doc_id, status (draft|sent|viewed|signed|declined|expired), pdf_url - DealSignatureSigner: document_id, name, email, role, signed_at, signature_provider_signer_id - Multi-Signer-Workflow: Reihenfolge konfigurierbar (sequenziell oder parallel) - SignatureWebhookEvent: Inbound-Webhooks von PandaDoc/DocuSign prozessiert ### REQ-signatur-provider PandaDoc/DocuSign-Integration über Apps-Engine (M33a). Acceptance criteria: - OAuth-Connect-Flow via M33a DataConnection - PDF-Upload + Provider-spezifisches Feld-Mapping - Webhook-Verarbeitung für Status-Updates - Fallback: einfacher PDF-Upload mit manueller Signatur-Erfassung (Phase 2) --- ## Modul 9 — Email-Inbox source: _bmad-output/specs/M09-email-inbox.md ### REQ-email-datenmodell EmailIntegrationMailbox, EmailIntegrationMessage, EmailIntegrationSyncCursor, TenantSendingDomain, TenantInboundAddress. Acceptance criteria: - EmailIntegrationMailbox: tenant_id, provider (gmail|outlook), oauth_token (verschlüsselt AD-8), sync_status, last_synced_at - EmailIntegrationMessage: mailbox_id, provider_message_id (unique), thread_id, from_email, subject, body_text, body_html, direction (inbound|outbound), linked_contact_id, linked_lead_id - TenantSendingDomain: DKIM/SPF/DMARC-Einträge; Scaleway für inbound - Cursor-basierter Sync (Gmail API History, Microsoft Graph delta) ### REQ-email-sync-strategie Bidirektionaler Sync Gmail/Outlook mit Provider-Adapter-Pattern. Acceptance criteria: - ProviderAdapter-Interface: connect(), sync(), send(), getThread() - GmailAdapter und OutlookAdapter implementieren Interface - Gmail: Pub/Sub-Webhooks für inbound; Outlook: Microsoft Graph subscriptions - Auto-Matching: Absender-Email → Contact/Lead (kein Auto-Merge, nur Link) - Unbekannter Absender → Lead angelegt (source=email) ### REQ-email-inbox-view Inbox-View, Compose, Thread-View mit Permission-Scoping. Acceptance criteria: - Inbox: alle eingehenden Mails, gefiltert per Mailbox + Status (ungelesen/gelesen) - Thread-View: chronologisch, mit verknüpftem Contact/Lead/Deal sichtbar - Compose mit Vorauffüllung Empfänger (aus CRM-Context) - Gesendet via verbundene Mailbox oder Scaleway TEM als Fallback --- ## Modul 10 — Email-Marketing source: _bmad-output/specs/M10-email-marketing.md ### REQ-marketing-datenmodell Campaign, OutboundEmail, OutboundEmailOpen/Click, EmailTemplate, EmailSender, RecipientSegment, EmailSuppressionList. Acceptance criteria: - Campaign: tenant_id, name, status (draft|scheduled|sending|sent|cancelled), subject, from_sender_id, recipient_segment_id, scheduled_at, sent_at, stats (JSONB) - OutboundEmail: campaign_id, contact_id, email_address, status (queued|sent|bounced|spam|unsubscribed), sent_at - Tracking: pixel für Opens (1x1 PNG), Link-Rewriting für Clicks; DSGVO-konform (nur aggregiert publishen) - EmailSuppressionList: hard-bounce, unsubscribe, spam-report auto-hinzufügen ### REQ-marketing-double-optin Double-Opt-In-Workflow mit DSGVO-Compliance. Acceptance criteria: - Opt-In per Form-Submission (M05) → Bestätigungs-Email → Klick-Confirmation-Token - Status: pending_confirmation → confirmed → aktiv - Unsubscribe: One-Click (Liste in jeder Mail Pflicht per Gesetz) - Suppression-List-Check vor jedem Versand ### REQ-marketing-versand BullMQ-basierter Versand mit Rate-Limiting, SMTP-Provider-Abstraktion (Scaleway TEM). Acceptance criteria: - BullMQ-Queue für async Versand; Rate-Limit konfigurierbar (Provider-abhängig) - Bounce-Handling: soft bounce → retry; hard bounce → suppression - Automation-Engine-Integration: Trigger campaign.sent, Aktion send-campaign-email --- ## Modul 12 — Telefonie (AirCall) source: _bmad-output/specs/M12-telefonie.md ### REQ-telefonie-datenmodell TelephonyConnection, TelephonyUserBinding, TelephonyCallSession, TelephonyWebhookEvent. Acceptance criteria: - TelephonyConnection: tenant_id, provider=aircall, oauth_tokens (verschlüsselt AD-8), status - TelephonyUserBinding: connection_id, user_id, aircall_user_id (1:1 Mapping) - TelephonyCallSession: session_id (provider), direction (inbound|outbound), from_number, to_number, contact_id, lead_id, deal_id, recording_url, transcript_url, duration_seconds, status ### REQ-telefonie-provider-adapter TelephonyProviderInterface mit AirCallAdapter; Click-to-Call, Inbound-Webhook-Verarbeitung. Acceptance criteria: - Provider-Interface: initiateCall(), handleInboundWebhook(), getRecording() - Click-to-Call aus Contact/Deal/Lead-Detail-View - Inbound-Webhook: AirCall sendet Ereignisse → matching → Contact/Lead - Unbekannte Nummer → Lead (source=phone) - Activity-Eintrag call_inbound / call_outbound pro Session --- ## Modul 13 — Team-Chat source: _bmad-output/specs/M13-team-chat.md ### REQ-chat-datenmodell TeamChat (Channel), TeamChatMember, TeamChatMessage, TeamChatPinnedMessage, TeamChatReaction, TeamChatThread, TeamChatRead. Acceptance criteria: - 3 Channel-Typen: public (alle), private (invite-only), entity-linked (zu Contact/Deal/Projekt gebunden) - Nachrichten: id, channel_id, user_id, body (Markdown), attachments[], reply_to_message_id, edited_at, deleted_at - Threads: verankert an Message (wie Slack) - Reactions: Emoji per Message, mehrere User pro Emoji - TeamChatRead: Last-Read-Pointer pro User pro Channel für Ungelesen-Zähler ### REQ-chat-realtime WebSocket-basiertes Real-Time-Messaging mit Presence, Typing-Indicator, Read-Receipts. Acceptance criteria: - WebSocket-Room-Layer (AD-9): ein Room pro Channel - Presence: User online/offline/away über Redis - Typing-Indicator: debounced - Push-Notifications bei Mention oder DM (via M22/FCM/APNs) - Redis-Pub/Sub für Scale-Out ### REQ-chat-features Link-Previews, File-Uploads, Mentions, Such-Funktion, gelinkte Channels. Acceptance criteria: - Link-Preview: OGP-Fetch server-side (kein Client-Tracking) - File-Upload via M23 (Datei-Speicher) - @Mention auto-complete mit User-Vorschlägen; Notification an genannten User - Suche im Chat-Verlauf (Postgres-FTS auf body) - Entity-linked Channel: sichtbar im Deal/Projekt-Detail --- ## Modul 14 — HR-Hub source: _bmad-output/specs/M14-hr-hub.md ### REQ-hr-datenmodell HrEmployeeProfile, HrAnnouncement, EmployeeVacationRequest, EmployeeSickLeaveReport, EmployeePayslip, EmployeePasswordSafeVault/Entry, HrSurvey, HrRequest. Acceptance criteria: - HrEmployeeProfile: user_id (1:1), position, department, entry_date, emergency_contact, profile_photo_url, manager_user_id - EmployeeVacationRequest: user_id, start_date, end_date, days_count, status (pending|approved|rejected|cancelled), approver_user_id - EmployeePayslip: verschlüsselt (AES-256-GCM mit Per-Tenant-DEK, AD-8), nur für betreffenden MA + HR sichtbar - EmployeePasswordSafeVault/Entry: AES-256-GCM verschlüsselt (AD-8), KMS-gestützt ### REQ-hr-passwort-safe Verschlüsselter Passwort-Safe pro Mitarbeiter mit KMS-backed Envelope-Encryption. Acceptance criteria: - Verschlüsselung: Per-Tenant-DEK via Scaleway Key Manager (AD-8) - Vault-Entries: title, username, password_encrypted, url, notes_encrypted - Export nur für den MA selbst (und HR-Admin) - Audit-Trail für jeden Zugriff (AV #6) - DSGVO-Export (M35) inkludiert Vault-Daten ### REQ-hr-urlaub-krank Urlaubs-Anfrage-Workflow und Krankmeldungs-Erfassung mit Approval-Flow. Acceptance criteria: - Vacation-Request: mehrstufiger Approval (Manager → HR), konfigurierbar - Abwesenheits-Kalender (Übersicht für HR + Projektleiter) - SickLeaveReport: user_id, start_date, back_expected_date, uploaded_certificate_file_id - Integration M25 (Calendar): Abwesenheit als Kalender-Event --- ## Modul 15 — Customer-Portal source: _bmad-output/specs/M15-customer-portal.md ### REQ-portal-datenmodell PortalUser, CustomerPortalSession, CustomerPortalProjectAccess, CustomerPortalProjectDocument, PortalConfiguration, PortalEmailTemplate. Acceptance criteria: - PortalUser: tenant_id, email (unique pro Tenant), display_name, linked_contact_id, status (active|invited|deactivated) - CustomerPortalSession: Magic-Link-Auth (kein Passwort in Phase 1); 24h-Token - CustomerPortalProjectAccess: explizite Freigabe pro Projekt durch Tenant-Admin - PortalConfiguration: Tenant-Admin konfiguriert: enabled, logo, welcome_text, visible_sections[] ### REQ-portal-auth-magic-link Magic-Link-Authentication für Endkunden (separate Auth-Welt, kein Generalschlüssel, AD-3). Acceptance criteria: - Magic-Link per Email (Token 24h gültig, one-time) - CustomerPortalSession: IP-gebunden, 8h-Inaktivität - Kein Zugriff auf Tenant-App-Daten (vollständig getrennte Route /portal/{tenant}/...) - DSGVO-Lösch-Workflow: PortalUser-Löschung entfernt Zugänge + Activity-Trail ### REQ-portal-projekt-sicht Projekt-Sicht für Endkunden: Status, Dokumente, File-Upload, Portal-Forms. Acceptance criteria: - Nur Projekte sichtbar, die explizit freigegeben (CustomerPortalProjectAccess) - Dokumente: Tenant-Admin released CustomerPortalProjectDocument (nicht automatisch alle Files) - File-Upload: Endkunde lädt Dokumente hoch (via M23, tenant-prefix) - Portal-Forms: M05-Forms im Portal-Kontext ausfüllbar - Default-Sichtbarkeit für neue Funktionen: NICHT sichtbar (AD-18) --- ## Modul 17 — Automation Engine source: _bmad-output/specs/M17-automation-engine.md ### REQ-automation-datenmodell AutomationRule, AutomationRuleStep, AutomationExecution, AutomationStepExecution, AutomationCredential, AutomationTemplate. Acceptance criteria: - AutomationRule: flow_data (JSON Graph: Nodes + Edges), enabled, created_via (manual|template|ki_natural_language), executions_count_30d - AutomationRuleStep: node_type (trigger|action|condition|delay|loop), config (JSONB), position, connections[] - AutomationExecution: rule_id, trigger_payload, status (running|completed|failed|cancelled), started_at, finished_at, retries - AutomationStepExecution: execution_id, step_id, input, output, status, error_message ### REQ-automation-trigger-library Phase-1-Trigger-Library (Geerkens-fokussiert) über alle Module. Acceptance criteria: - CRM: lead.created, lead.status_changed, contact.created, contact.updated - Sales: deal.created, deal.stage_changed, deal.won, deal.lost, deal.stuck - Projekte: project.created, project.stage_changed - Email: email.received - Forms: form.submitted - Kalender: appointment.scheduled - Zeit-Trigger: cron (Schedule), delay - Webhook: incoming_webhook ### REQ-automation-action-library Phase-1-Action-Library über alle Module. Acceptance criteria: - CRM: create-contact, update-contact, create-lead, assign-lead, set-tag, create-deal, update-deal-stage - Notifications: send-notification, send-email, send-whatsapp (Phase 2) - KWP: kwp.push_auftrag - HTTP: http-request (externe Webhooks) - Tasks: create-task - Automation-interne: if/else, delay, loop ### REQ-automation-flow-editor Graph-basierter visueller Flow-Editor mit KI-Erstellung per natürlicher Sprache. Acceptance criteria: - Graph-Bibliothek (Flow-kompatibel) mit Nodes + Edges - KI-Erstellung: User beschreibt auf Deutsch → KI generiert flow_data (AD-16) - Dry-Run: Execution ohne echte Seiteneffekte, zeigt expected Steps + Output - 24h-Undo für alle Automation-Executions (reversible Actions) ### REQ-automation-schutz Loop-Guard, Rate-Limit, Anomalie-Detection, Idempotenz. Acceptance criteria: - Loop-Guard: max. 10 Re-Trigger derselben Rule durch eigene Executions innerhalb 60 Sek → Auto-Disable + Alert - Rate-Limit pro Rule: max. 1000 Executions/24h (konfigurierbar) - Idempotency-Key per Execution (dedupliziert Retry-Storm) - Resume-Mode: bei transientem Fehler in Step N → Retry ab Step N (nicht ab Step 0) - Trigger-Volumen-Metering: Zählung pro Tenant für Billing (AD-15) --- ## Modul 18 — KI-Layer source: _bmad-output/specs/M18-ki-layer.md ### REQ-ki-llm-gateway EU-only LLM-Gateway mit Multi-Provider-Abstraktion und Token-Tracking. Acceptance criteria: - Unterstützte Provider: Scaleway, Mistral, AlephAlpha (alle EU-ansässig, LP-13) - LlmGatewayProvider: provider_key, base_url, api_key_encrypted (AD-8), models[], status - AiTokenUsage: tenant_id, user_id, provider, model, prompt_tokens, completion_tokens, cost_eur, created_at - AiCredits: Pro-Tenant-Credit-Konto; Deduktion bei Nutzung; Preis-Modell Pay-as-you-go (AD-15) ### REQ-ki-rag-embeddings RAG-Pipeline mit pgvector für semantische Suche und KI-Kontext. Acceptance criteria: - TenantEmbedding: entity_type, entity_id, embedding (vector(1024)), model_id, created_at - Embeddings via Scaleway EU-Endpoint (1024-dim, AD-5) - Outbox-Pattern für Embedding-Job-Queue - Retrieval: Top-K similar via pgvector (<=> cosine distance), gefiltert nach tenant_id + RLS ### REQ-ki-whisper Whisper-Transkription für Anruf-Aufzeichnungen und Sprachnotizen. Acceptance criteria: - Whisper-Job: audio_file_id → text_transcript, language_detected - EU-Whisper-Endpoint (Scaleway) - Transkript gespeichert in TelephonyCallSession.transcript_url (M12) - Nutzung: Token-Tracking, AiCredits-Deduktion ### REQ-ki-hivemind HiveMind-KI-Assistent: kontextueller Chat-Assistent mit RAG-Anbindung. Acceptance criteria: - Conversation: tenant_id, user_id, context_entity_type, context_entity_id, messages[] - ConversationMessage: role (user|assistant|system), content, token_count, model_id - Sicherheit: Promptfoo-basiertes Testing; AV #20 (KI darf keine destruktiven Aktionen ohne User-Bestätigung ausführen) --- ## Modul 19 — KWP-Integration source: _bmad-output/specs/M19-kwp-integration.md ### REQ-kwp-datenmodell KwpSettings, KwpRegistry, KwpProjectQueue, KwpProjectNumberSequence, KwpApiKey, KwpDocument, KwpErrorReport, KwpSchemaSnapshot. Acceptance criteria: - KwpSettings: tenant_id, data_connection_id (FK M33a DataConnection), kwp_db_host/port/name NICHT in Cloud gespeichert (DSGVO) - KwpRegistry: mapping HiveGrid-entity_id ↔ kwp_entity_id (bidirektional) - KwpProjectQueue: Cloud-Side-Queue für Push-Operationen (Auftrag-Push zu KWP) - KwpApiKey: Token für kwpsync.exe-Auth (verschlüsselt AD-8) - KwpSchemaSnapshot: letztes bekanntes MSSQL-Schema (Basis für Schema-Drift-Sentinel) ### REQ-kwp-architektur Drei-Komponenten-Architektur: HiveGrid Cloud, kwpsync.exe (Windows-Client), KWP MSSQL-DB. Acceptance criteria: - kwpsync.exe: Windows-Service, Polling-Loop 30 Sek, Heartbeat 5 Min, lokale SQLite-Queue, Auto-Update - Bidirektional: HiveGrid→KWP (Auftrags-Push via Automation M17-Action kwp.push_auftrag), KWP→HiveGrid (Stammdaten-Pull, Belege) - Adapter-Pattern: KWP als DataConnection type=windows_client in M33a Apps-Engine - KWP-API-Recut (siehe ADR-Notiz): bei nativer API wird windows_client zu rest-api ### REQ-kwp-schema-drift Schema-Drift-Sentinel für MSSQL-Schema-Änderungen. Acceptance criteria: - KwpSchemaSnapshot: regelmäßig aktualisiert durch kwpsync.exe - Drift-Detection: Vergleich aktuelle Schema vs. Snapshot → Alert wenn Spalten/Tabellen fehlen - Tenant-Admin-Notification + KwpErrorReport bei Drift - Adapter-Interface-Test gegen Schema-Snapshot --- ## Modul 20 — Dashboard source: _bmad-output/specs/M20-dashboard.md ### REQ-dashboard-datenmodell Dashboard, DashboardLayout, WidgetCatalog, WidgetInstance. Acceptance criteria: - Dashboard: tenant_id, user_id (null = tenant-wide), name, is_default - DashboardLayout: dashboard_id, layout_data (JSON: react-grid-layout-kompatibel) - WidgetInstance: dashboard_id, widget_type (aus WidgetCatalog), config (JSONB), position, size - Role-Default-Layouts: per Rolle vorkonfigurierte Dashboard-Layouts (SHK-Template geseedet) ### REQ-dashboard-widgets Widget-Katalog mit Datenquellen aus Sales, Projekte, Tasks, HR, KI. Acceptance criteria: - Sales-Widgets: Pipeline-Forecast, Deal-Funnel, Won-Rate, Top-Vertriebler - Projekt-Widgets: Offene Aufträge, Plantafel-Übersicht, Abnahmen-Queue - Task-Widgets: My-Tasks, Overdue-Tasks, Team-Tasks - HR-Widgets: Abwesenheiten, Ankündigungen - KI-Widget: AI-Credit-Usage - Realtime-Update via WebSocket oder SSE für Live-Daten (AD-9) - Aggregat-Cache mit TTL (konfigurierbar pro Widget-Typ) --- ## Modul 21 — Audit-Log source: _bmad-output/specs/M21-audit-log.md ### REQ-audit-datenmodell AuditEntry, AuditExportJob, AuditRetentionPolicy (append-only). Acceptance criteria: - AuditEntry: id (UUID), tenant_id (null=plattformweit), created_at, actor_user_id, actor_type (user|system|automation|admin), action (string), entity_type, entity_id, before_state (JSONB), after_state (JSONB), ip_address, previous_hash, current_hash (SHA-256-Kette) - Hash-Kette: current_hash = SHA256(previous_hash + payload) — Tamper-Nachweisbarkeit - Append-only: kein UPDATE oder DELETE auf AuditEntry (DB-Constraint) - Prisma-Middleware: alle write-Operationen auto-generieren AuditEntry (AV #6) ### REQ-audit-retention-export Retention-Policy, Legal-Hold, Export-Jobs, DSGVO-Compliance. Acceptance criteria: - AuditRetentionPolicy: tenant_id, retention_days (Default 3650 = 10 Jahre), legal_hold (Boolean) - Legal-Hold sperrt Löschung auch nach Retention-Ende - AuditExportJob: tenant_id, requested_by, date_from/to, status, download_url (Scaleway Storage) - Export: komprimiertes NDJSON oder CSV in Scaleway Object Storage - Cron-Job für auto-Löschung nach Retention ### REQ-audit-permissions Audit-Zugriff permission-gegated. Acceptance criteria: - audit.read: Tenant-Admin kann eigene Audit-Einträge lesen - audit.export: Tenant-Admin kann Export anfordern - audit_event-Typ in Activity-Stream: nur sichtbar mit audit.read (M01 Block E) - Plattform-Admin: sieht plattformweite Einträge (tenantId=null) über AdminAuditLog-View --- ## Modul 22 — Notifications source: _bmad-output/specs/M22-notifications.md ### REQ-notification-datenmodell Notification, NotificationPreference, NotificationDevice, NotificationBundle, NotificationQuietHours. Acceptance criteria: - Notification: tenant_id, recipient_user_id, category, template, payload (JSONB), channels_sent[], status, read_at, created_at - NotificationPreference: user_id, category, in_app_enabled, email_enabled, push_enabled - NotificationDevice: user_id, device_token, platform (ios|android), last_seen_at - NotificationBundle: Anti-Spam-Bündelung: gleichartige Notifications innerhalb X Minuten zu einer Zusammenfassung - NotificationQuietHours: user_id, start_time, end_time, timezone, days_of_week[] ### REQ-notification-versand-pipeline Drei-Kanal-Versand (In-App via SSE, Email via Provider, Mobile-Push via FCM/APNs) über BullMQ. Acceptance criteria: - notify()-Aufruf aus @hivegrid/notifications: immer via Service, nie direkter Email/Push-Versand aus Modul (INTEGRATION-CONTRACTS §7) - Service entscheidet Kanal anhand NotificationPreference + QuietHours - In-App: SSE-Stream (AD-9); Push: FCM (Android) + APNs (iOS); Email: via Provider (AD-6-pending) - Novu als Notification-Middleware oder eigene BullMQ-Pipeline (Design-Entscheidung offen) --- ## Modul 23 — Files source: _bmad-output/specs/M23-files.md ### REQ-files-datenmodell File, FileVersion, FileChunk, FileUploadProgress, FileEntityLink. Acceptance criteria: - File: tenant_id, storage_key (Scaleway S3), filename, mime_type, size_bytes, uploaded_by_user_id, preview_url - FileVersion: file_id, version_number, storage_key, size_bytes, created_at - FileChunk: Chunked-Upload-State (für Dateien >5MB) - FileEntityLink: file_id, entity_type, entity_id (polymorphe Verknüpfung) - S3-Pfad: tenants/{tenant_id}/files/{file_id}/{version}/ (AD-1 RLS auf Storage) ### REQ-files-upload-preview Chunked-Upload, Preview-Generierung, Versionierung. Acceptance criteria: - Chunked-Upload via Resumable-Upload-API (TUS-Protokoll oder eigene Implementierung) - Preview: PDF → PNG-Thumbnail; Bilder → WebP-Resize; Andere → Generic-Icon - Versionierung: neue Version ersetzt nicht die alte (immer als FileVersion gespeichert) - Customer-Portal-Upload: Endkunden können über M15 Dateien hochladen (im Tenant-Prefix) --- ## Modul 24 — Globale Suche source: _bmad-output/specs/M24-globale-suche.md ### REQ-suche-datenmodell SearchIndexEntry, RecentSearch, EmbeddingProviderJob. Acceptance criteria: - SearchIndexEntry: tenant_id, entity_type, entity_id, searchable_text, embedding (vector(1024)), last_indexed_at - RecentSearch: user_id, query, entity_type, selected_entity_id, created_at (letzten 10) - Outbox-Pattern: Embed-Job nach Entity-Mutation in Queue ### REQ-suche-hybrid Hybrid-Suche: Postgres-FTS + pgvector-Embeddings via RRF-Fusion (AD-5). Acceptance criteria: - Keyword: tsvector + GIN-Index auf searchable_text (Postgres-FTS) - Semantisch: pgvector cosine similarity auf embedding-Spalte - RRF (Reciprocal Rank Fusion) kombiniert beide Ergebnislisten - Permission-aware: SearchAdapter filtert nach User-Permissions vor Rückgabe - SearchAdapter-Interface: jedes Modul registriert Entitäten via indexed-entities.ts in packages/search/ (AD-10, INTEGRATION-CONTRACTS §8) ### REQ-suche-ui Cmd+K-Modal und Vollbild-Such-View. Acceptance criteria: - Cmd+K öffnet Modal überall in der App (global Hotkey) - Debounced (300ms), min. 2 Zeichen - Vollbild-Such-View: persistierte Suche, Filter, Ergebnis-Seiten - RecentSearch angezeigt bei leerer Query --- ## Modul 25 — Calendar-Sync source: _bmad-output/specs/M25-calendar-sync.md ### REQ-kalender-datenmodell CalendarConnection, CalendarEvent, CalendarEventMapping, CalendarSyncCursor, CalendarWebhookEvent. Acceptance criteria: - CalendarConnection: user_id, provider (google|microsoft), oauth_tokens (verschlüsselt AD-8), status - CalendarEvent: connection_id, provider_event_id, title, start_at, end_at, is_busy, is_all_day, ical_uid - CalendarEventMapping: hg_entity_type, hg_entity_id, calendar_event_id (bidirektionale Verknüpfung) - CalendarSyncCursor: last_sync_token / delta_link pro Connection ### REQ-kalender-sync-adapter Bidirektionaler Sync über CalendarAdapter-Interface. Acceptance criteria: - CalendarAdapter-Interface: connect(), syncFull(), syncDelta(), createEvent(), updateEvent(), deleteEvent() - GoogleCalendarAdapter + OutlookAdapter implementieren Interface - OAuth-Token-Refresh automatisch - Webhook-Subscriptions für Push-Updates (Google Push Notifications, Outlook Subscriptions) - HiveGrid-seitige Änderungen (Appointment via M06): Event in verbundenem Kalender anlegen --- ## Modul 26 — Tasks source: _bmad-output/specs/M26-tasks.md ### REQ-tasks-datenmodell Task, TaskWatcher. Acceptance criteria: - Task: id, tenant_id, title (Pflicht), description, status (open|in_progress|completed|cancelled), priority (low|medium|high|urgent), due_date, assigned_to_user_id, created_by_user_id, entity_type, entity_id (nullable — Verknüpfung), completed_at, archived_at, reminder_at - TaskWatcher: task_id, user_id (follow-Funktion) - Entity-Verknüpfung: Task kann mit Contact, Company, Lead, Deal, Project, Group verknüpft sein ### REQ-tasks-reminder-archivierung Reminder-System und Auto-Archivierung abgeschlossener Tasks. Acceptance criteria: - Reminder: M22-Notification bei due_date - X; konfigurierbar (15min, 1h, 1d vor Fälligkeit) - Auto-Archivierung: abgeschlossene Tasks nach 30 Tagen (Cron-Job) - Erstellungs-Quellen: manuell, Form-Action (M05), Automation-Action (M17), Chat-Shortcut (M13) --- ## Modul 27 — Auth / Multi-Tenancy / Permissions source: _bmad-output/specs/M27-auth-multi-tenancy.md ### REQ-auth-multi-tenancy Self-Service-Signup, Tenant-Slug, URL-Struktur (app.hivegrid.de, admin.hivegrid.de). Acceptance criteria: - Signup: Firmennamen → auto-generierter Slug (Umlaute transkribiert, lowercase, Bindestrich); User darf editieren; Live-Validierung auf Eindeutigkeit - Slug nach Anlage unveränderlich (nur Plattform-Admin-Migrationstool) - Reserved Words: admin, app, api, www, help, support, marketing, dev, test, signup, login, auth, static, assets, public, settings, portal, buch, f ### REQ-auth-methoden Email+Passwort, TOTP (2FA), Magic-Link für Customer-Portal. Acceptance criteria: - NIST-konformes Passwort (min 8 Zeichen, max 128, keine Komplexitäts-Erzwingung, Breach-Check via Pwned-Passwords) - TOTP: RFC 6238, TOTP-Secret gespeichert verschlüsselt (AD-8), Backup-Codes - Magic-Link: nur für Customer-Portal (M15), verboten für Mandanten-App-Login und Admin (AD-3) - Auto-Logout: bei Passwort-/2FA-/Email-Änderung alle Sessions revoken (AD-4) ### REQ-auth-rbac Rollen-basiertes Permission-System mit Bundles und Tenant-Admin-Verwaltung. Acceptance criteria: - Role: id, tenant_id, name, is_system (nicht editierbar), permissions[] (JSON-Array) - User ↔ Role: M:N (User kann mehrere Rollen haben) - Permission-Keys in packages/entitlements/src/permissions.ts (INTEGRATION-CONTRACTS §10) - SHK-Template: 6 Standard-Rollen geseedet (Partner-Liste 19.06.: Geschäftsführer, Projektleiter, Verwaltung, Vertriebler, Kundensupporter, Monteur) - Permission-Check: server-side middleware + client-side hide (niemals nur client-side) ### REQ-auth-user-lifecycle User-Einladung, Onboarding, Deaktivierung, DSGVO-Löschung. Acceptance criteria: - Einladung: Token per Email (48h gültig), User setzt Passwort bei Annahme - Deaktivierung: Sessions revoken, User nicht löschbar wenn Daten vorhanden (Soft-Deactivation) - DSGVO-Löschung: User-PII anonymisiert, nicht hard-deleted wenn Audit-Trail vorhanden ### REQ-auth-api-keys API-Key-System für technische Integrationen. Acceptance criteria: - ApiKey: tenant_id, key_hash (SHA-256), name, scopes[], last_used_at, expires_at - Key wird einmalig bei Erstellung angezeigt (danach nur Hash) - Scopes: fein-granular analog Permission-System - Rate-Limit: 1000 Req/Min (Default, konfigurierbar) --- ## Modul 28 — Subscriptions/Billing source: _bmad-output/specs/M28-subscriptions-billing.md ### REQ-billing-datenmodell TenantSubscription, SubscriptionProduct, SubscriptionPrice, SubscriptionFeature, TenantSubscriptionUsageRecord, Credit. Acceptance criteria: - TenantSubscription: tenant_id, stripe_customer_id, stripe_subscription_id, product_id, status (active|trialing|frozen|cancelled), trial_ends_at, current_period_start/end, seat_count - Stripe-Webhook-Verarbeitung: checkout.session.completed, invoice.payment_succeeded, invoice.payment_failed, customer.subscription.deleted - Frozen-Modus: Zugriff eingeschränkt (Read-Only-Middleware), Warnungen in App - AI-Credits: Credit-Konto pro Tenant, verknüpft mit Subscription-Plan ### REQ-billing-trial-dunning Trial-Phase, Dunning-Workflow, Setup-Fee. Acceptance criteria: - Trial: 14 Tage Default, keine Kreditkarte erforderlich - Dunning: bei fehlgeschlagener Zahlung → Email-Sequenz (Tag 1, 3, 7), dann Frozen-Modus - Setup-Fee: einmalige Gebühr bei Enterprise-Buchung (Stripe-Checkout-Session) - Preise selbst geparkt (AD-15); Engine muss aber bereit sein --- ## Modul 29 — Onboarding source: _bmad-output/specs/M29-onboarding.md ### REQ-onboarding-wizard Branchen-getriebener Onboarding-Wizard nach Self-Service-Signup. Acceptance criteria: - OnboardingSession: tenant_id, current_step_id, completed_at, filter_answers (JSONB) - Wizard-Schritte: Branche bestätigen → Teamgröße → Feature-Auswahl → Demo-Daten? → Einladungen - SHK-Template: vorausgewählt wenn Branche = SHK - OnboardingFilter: Branchen-spezifische Zweige im Wizard ### REQ-onboarding-demo-daten Demo-Daten-Provisioning auf Wunsch beim Onboarding. Acceptance criteria: - OnboardingDemoProvisioning: tenant_id, status (pending|running|completed|failed) - Demo-Daten: 5 Beispiel-Contacts, 3 Deals, 2 Projekte, Form-Submission, Tasks - Lösch-Funktion: Demo-Daten komplett entfernbar (Bulk-Delete per Flag is_demo_data=true) - KI-Walkthrough optional nach Onboarding (AD-16) --- ## Modul 30 — i18n source: _bmad-output/specs/M30-i18n.md ### REQ-i18n-architektur Locale-File-Struktur, Language-Resolution, Build-Validierung. Acceptance criteria: - Locale-Files: packages/i18n/src/locales/{lang}/{modul}.json (INTEGRATION-CONTRACTS §9) - Naming: {modul}.{bereich}.{key} (z.B. sales.kanban.empty_state) - Language-Resolution: User-Preference → Tenant-Default → de (Fallback) - ESLint-Rule blockt JSX-Text-Nodes ohne t(); Build-Lint blockt Hard-Strings - ICU-Pluralization: {count, plural, one {# Datei} other {# Dateien}} - DeepL-Pipeline für automatische Übersetzungs-Vorschläge (Phase 2) ### REQ-i18n-outbound Sprachauswahl für Outbound-Kommunikation (Email, Push, WhatsApp). Acceptance criteria: - Contact.language (DE/EN, Default DE) steuert Sprache der automatischen Kommunikation - Notification-Templates in DE + EN Pflicht für Phase 1 - M22 notify()-Aufruf übergibt context_language; Service wählt Template --- ## Modul 31 — Branding source: _bmad-output/specs/M31-branding.md ### REQ-branding-theme-phase1 User-Level Theme-Preference (Light/Dark/System) in Phase 1. Acceptance criteria: - User.theme_preference (light|dark|system, Default system) - Cookie für SSR-Kompatibilität (kein Flash of wrong theme) - CSS-Variablen für Theme-Switching ### REQ-branding-tenant-phase2 Tenant-Branding, White-Label, Custom-Domain (Phase 2). Acceptance criteria: - TenantBranding: logo_url, primary_color, secondary_color, custom_domain - Feature-Gate: branding.white_label (nur in Enterprise-Plan) - Email-Templates mit Tenant-Logo - Capacitor-App-Theming (AD-17, Mobile-App) --- ## Modul 32 — Feature-Flags source: _bmad-output/specs/M32-feature-flags.md ### REQ-feature-flags-system Platform-Admin-Feature-Flag-System für per-Tenant-Aktivierung. Acceptance criteria: - FeatureFlag: key (unique), name, description, default_value (Boolean), type (boolean|percentage|json) - TenantFeatureFlag: tenant_id, flag_key, value, activated_at, activated_by_admin_id - FeatureFlagFilter: Regeln für automatische Aktivierung (Branche, Teamgröße, Plan) - tenantHasFlag(tenantId, flagKey): Helper-Funktion; gecacht in Redis (TTL 5 Min) - Änderungen geloggt in AdminAuditLog (M37) --- ## Modul 33a — Apps-Engine source: _bmad-output/specs/M33a-apps-engine.md ### REQ-apps-engine-datenmodell DataConnection, AppSyncRun, AppSyncRunLog, AppSyncItem, Adapter-Registry. Acceptance criteria: - DataConnection: tenant_id, app_key (gmail|outlook|aircall|kwp|stripe|pandadoc|...), status (connected|disconnected|error), credentials_encrypted (AD-8), config (JSONB), last_synced_at - AppSyncRun: connection_id, status (running|completed|failed), started_at, finished_at, items_processed - AppSyncItem: run_id, external_id, action (create|update|delete), payload_hash, status - Adapter-Registry: app_key → Adapter-Klasse (type-safe Registry) ### REQ-apps-engine-lifecycle App-Connect-Flow, Sync-Mechanik, Connection-Health-Monitoring. Acceptance criteria: - OAuth2-Connect-Flow für Gmail, Outlook, AirCall, PandaDoc - API-Key-Connect für KWP (type=windows_client), Stripe - Sync-Intervalle: konfiguierbar per App (Push-Webhook bevorzugt, Pull als Fallback) - Connection-Health: Heartbeat-Check, Auto-Reconnect-Versuch, Tenant-Admin-Alert bei Fehler - Settings-UI: /settings/integrationen/{app_key}; Einstiegspunkt für alle Integrations --- ## Modul 34 — Public API & Webhooks source: _bmad-output/specs/M34-public-api.md ### REQ-public-api-read Phase-1 Read-Only REST-API für Contacts, Deals, Leads, Projects, Tasks, Companies. Acceptance criteria: - Endpoints: GET /api/v1/contacts, /deals, /leads, /projects, /tasks, /companies (je List + Detail) - Auth: API-Key (Bearer), Permission-Scoped (M27 API-Keys) - Rate-Limit: 1000 Req/Min Default (Redis-backed) - OpenAPI-Spec: automatisch generiert (z.B. via @asteasolutions/zod-to-openapi) - IntegrationApiRequest: Logging aller API-Zugriffe für Audit + Rate-Limit ### REQ-public-webhooks Incoming Lead-Push Webhooks + Outgoing Webhook-Subscriptions. Acceptance criteria: - IncomingWebhookIngestion: tenant_id, source_key, payload, processed_at; Lead aus Payload anlegen - WebhookSubscription: tenant_id, event_type (deal.won, lead.created, ...), target_url, secret, active - WebhookDelivery + WebhookDeliveryAttempt: Retry-Logik (exponentielles Backoff, max 5 Versuche) - Signatur-Validierung: HMAC-SHA256 im X-HiveGrid-Signature-Header --- ## Modul 35 — DSGVO-Export / Account-Löschung source: _bmad-output/specs/M35-dsgvo-export.md ### REQ-dsgvo-export GDPR-Daten-Export als ZIP via BullMQ-Worker. Acceptance criteria: - GdprExportJob: user_id, tenant_id, requested_at, status (pending|running|completed|failed), download_url (Scaleway, 72h signed URL) - Export-Inhalt: alle personenbezogenen Daten des Users (Profile, Activities, Chat-Messages, Files-Metadata, Custom-Field-Values, Audit-Trail-Auszug) - ZIP + NDJSON-Format - Download-Link-Email via M22 ### REQ-dsgvo-tenant-deletion Tenant-Account-Löschung mit Crypto-Shredding. Acceptance criteria: - TenantDeletionRequest: tenant_id, requested_by_user_id, reason, scheduled_for (14-Tage-Frist) - Crypto-Shredding: Per-Tenant-DEK löschen → alle verschlüsselten Daten unlesbar (AD-8) - Stripe-Subscription canceln vor Löschung - pgvector-Embeddings, Redis-Cache, Scaleway-Storage-Objekte alle entfernen - AvvAcceptance + Subprocessor-Liste in Privacy-Hub-Route anzeigbar --- ## Modul 36 — Mobile-App source: _bmad-output/specs/M36-mobile-app.md ### REQ-mobile-capacitor Capacitor-Wrapper für iOS/Android mit nativem Zugriff auf Kamera, Biometrie, Push. Acceptance criteria: - Capacitor 6.x, iOS ≥ 16, Android ≥ 10 - Face-ID / Touch-ID / Fingerprint für App-Lock (zusätzlich zur Session) - Kamera für Foto-Upload + QR-Code-Scan (Bauteil-Scan Phase 2) - Deeplinks: hivegrid://... → App-Route-Mapping - Privacy-Manifest (Apple): NSCameraUsageDescription, NSFaceIDUsageDescription u.a. ### REQ-mobile-offline-sync Voller Offline-Betrieb mit IndexedDB + Sync-Queue (AD-17). Acceptance criteria: - OfflineSyncQueue: queued_at, entity_type, operation (create|update|delete), payload, synced_at, conflict_resolution - IndexedDB: lokale Kopie von aktuellen Aufträgen, Kontakten, Tasks (Subset) - Conflict-Resolution: "KWP gewinnt" bei KWP-Sync-Konflikten; "Last-Write-Wins" für HiveGrid-interne Konflikte - Service-Worker für Asset-Caching - Offline-Indikatoren (Klartext: "Du arbeitest offline — Änderungen werden synchronisiert sobald Verbindung besteht") ### REQ-mobile-push Push-Notifications über APNs (iOS) und FCM (Android). Acceptance criteria: - NotificationDevice: registration_token, platform, user_id, tenant_id, last_seen_at - Token-Rotation bei App-Neustart - M22 notify()-Aufruf → Push-Kanal wenn NotificationDevice registriert - Foreground/Background-Handling unterschiedlich --- ## Modul 37 — Plattform-Admin source: _bmad-output/specs/M37-plattform-admin.md ### REQ-plattform-admin-identität Getrennte AdminUser-Welt (AD-3) auf admin.hivegrid.de. Acceptance criteria: - AdminUser: id, email, password_hash, totp_secret (verschlüsselt AD-8), status (active|suspended), roles[] - AdminSession: session_id, admin_user_id, ip_address, user_agent, created_at, last_active_at, expires_at; server-side in Postgres (AD-4) - AdminRole + AdminPermission: RBAC für Plattform-Admin-Aktionen - Magic-Link verboten (AD-3) - IP-Binding der Session ### REQ-plattform-admin-features Tenant-Management, Subscription-Verwaltung, Feature-Flags, Worker-Queue-Monitoring. Acceptance criteria: - Tenant-Liste + Detail: Subscription-Status, Last-Login, Feature-Flags, Admin-Notes (AdminTenantNote) - Subscription: manuelle Overrides, Trial-Verlängerung, Plan-Wechsel - Feature-Flags verwalten (M32-Integration) - Worker-Queue-Monitoring: BullMQ-Queue-Status, failed Jobs, Retry - Support-Inbox: AdminSupportTicket aus M39 Feedback-Widget - Admin-Lead-Management: Interesse-Anfragen für Sales-Pipeline der HiveGrid GmbH selbst --- ## Modul 38 — Help-Center (öffentlich) source: _bmad-output/specs/M38-help-center.md ### REQ-help-center Öffentliches file-basiertes Markdown-Help-Center mit Suche und SEO. Acceptance criteria: - Markdown-Files in content/help/{lang}/{category}/{slug}.md - Kategorien + Artikel-Index bei Build generiert - Suche: FlexSearch (client-side für Phase 1), Postgres-FTS als Fallback-Server-Route - Deep-Links: aus App heraus per Artikel-Key verlinkbar - SEO: SSR-gerenderter HTML, OG-Meta-Tags, sitemap.xml - Routen: /help/{lang}/{category}/{slug} (INTEGRATION-CONTRACTS §3) --- ## Modul 39 — Help-Desk / Support source: _bmad-output/specs/M39-help-desk.md ### REQ-feedback-widget In-App Feedback-Widget + Platform-Admin-Support-Inbox. Acceptance criteria: - Feedback: tenant_id, user_id, category (bug|feature|question|other), message, screenshot_url, page_url, created_at - Rate-Limit: max 10 Submissions pro User pro Stunde - Attachments: file_ids[] (via M23) - Activity-Log: jeder Feedback-Status-Wechsel geloggt - AdminSupportTicket in M37: Plattform-Admin sieht alle Feedbacks als Support-Queue - Audit-Trail für Support-Team-Aktionen --- ## INTEGRATION-CONTRACTS — Querschnitt source: docs/INTEGRATION-CONTRACTS.md ### REQ-integration-sidebar Alle neuen Modul-Bereiche müssen in der Sidebar-Konfiguration registriert sein. Acceptance criteria: - Registrierung in apps/web/app/application/sidebar/ (AD-10, nicht packages/ui-hivegrid/sidebar.config.ts) - SidebarEntry: id (kebab-case), group (eine der 6), label (i18n-Key), icon (lucide-react), route, permission, badge?, order, feature_flag? - Neue Funktion ohne Sidebar-Eintrag: nicht akzeptiert ### REQ-integration-routes Verbindliche URL-Schemata (INTEGRATION-CONTRACTS §3). Acceptance criteria: - Mandanten-App: app.hivegrid.de/{modul}/... (Tenant aus Session/Subdomain, NICHT im Pfad) - Plattform-Admin: admin.hivegrid.de/{bereich}/... - Customer-Portal: app.hivegrid.de/portal/{tenant}/... - Public-Forms: app.hivegrid.de/f/{tenant}/{slug} - Public-Booking: app.hivegrid.de/b/{tenant}/{slug} - Public-Help: app.hivegrid.de/help/{lang}/{kategorie}/{slug} - Public-API: app.hivegrid.de/api/v1/{resource} ### REQ-integration-activity-wiring Jede schreibende Aktion mit Entitäts-Bezug muss logActivity() aufrufen. Acceptance criteria: - logActivity() aus @hivegrid/activity (INTEGRATION-CONTRACTS §5) - Signatur: {tenantId, actorId, actorType, entityType, entityId, type, payload} - Trennung: logActivity() ist NICHT der Audit-Eintrag (Audit läuft über Prisma-Middleware separat) ### REQ-integration-audit-wiring Audit ist automatisch via Prisma-Middleware; Ausnahmen manuell. Acceptance criteria: - Prisma-Middleware in M21 generiert AuditEntry für alle write-Operationen automatisch - Ausnahmen (S3-Upload, externe Webhooks): manuell über auditEvent() aus @hivegrid/audit - Keine manuelle Audit-Implementierung in Modul-Code nötig (Verantwortung bei M21-Middleware) ### REQ-integration-notification-wiring Benachrichtigungen immer über notify(), nie direkter Kanal-Zugriff. Acceptance criteria: - notify() aus @hivegrid/notifications (INTEGRATION-CONTRACTS §7) - Signatur: {tenantId, recipientId, category, template, payload, priority} - Service (M22) entscheidet Kanal + Bündelung + Ruhezeiten ### REQ-integration-view-model-pflicht Jede Route muss im Loader ein View-Model bauen. Acceptance criteria: - Loader in app/routes/** gibt View-Model zurück - UI-Components in packages/ui-app/** empfangen NUR VM + Action-Callbacks - Kein direkter Store/DB-Zugriff in UI-Components ### REQ-integration-smoke-tests Jede neue Route bekommt einen Smoke-Test. Acceptance criteria: - Smoke-Test in e2e/smoke/{modul}.spec.ts - Smoke-Tests laufen gegen packages/ui-mock (Hot-Swap-Architektur) - Schlagen Smoke-Tests mit ui-mock fehl → Hot-Swap-Architektur verletzt