# Community Management - Implementierungsübersicht ## Übersicht Das Community Management System ermöglicht die zentrale Verwaltung von Social Media Interaktionen (Kommentare, DMs, Mentions) mit KI-gestützter Analyse und automatisierten Workflows. ## Architektur ``` ┌─────────────────────────────────────────────────────────────────────┐ │ Payload CMS Admin │ ├─────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │ │ │ Social │ │ Social │ │ Community │ │ │ │ Platforms │──│ Accounts │──│ Interactions │ │ │ │ (YouTube, │ │ (Kanäle, │ │ (Kommentare, DMs) │ │ │ │ LinkedIn) │ │ Tokens) │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────────────────┘ │ │ │ │ │ │ │ ┌────────────────────────┼───────────────┐ │ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │ │ │ Community │ │ Community │ │ Users │ │ │ │ │ Rules │ │ Templates │ │ (communityRole) │ │ │ │ │ (Automation)│ │ (Antworten) │ │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ Integration Services │ ├─────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────┐ ┌──────────────────────────────────────┐ │ │ │ YouTubeClient │ │ ClaudeAnalysisService │ │ │ │ (googleapis) │ │ (@anthropic-ai/sdk) │ │ │ │ │ │ │ │ │ │ - getComments │ │ - analyzeComment (Sentiment) │ │ │ │ - replyComment │ │ - generateReply (KI-Antwort) │ │ │ │ - markAsSpam │ │ - analyzeCommentsBatch │ │ │ └──────────────────┘ └──────────────────────────────────────┘ │ │ │ │ │ │ └──────────────┬───────────────┘ │ │ ▼ │ │ ┌──────────────────────┐ │ │ │ CommentsSyncService │ │ │ │ (Orchestrierung) │ │ │ └──────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ ``` ## Collections ### 1. SocialPlatforms (`social-platforms`) **Zweck:** Definiert unterstützte Social Media Plattformen. **Pfad:** `src/collections/SocialPlatforms.ts` **Felder:** | Feld | Typ | Beschreibung | |------|-----|--------------| | name | text | Plattformname (z.B. "YouTube") | | slug | text | Unique Identifier | | icon | text | Emoji oder Icon-Name | | color | text | Hex-Farbcode für UI | | isActive | checkbox | Plattform aktiv? | | apiStatus | select | disconnected / development / connected | | apiConfig | group | API-Konfiguration (Typ, URL, Auth) | | apiConfig.scopes | array | OAuth Scopes | | rateLimits | group | API Rate Limits | | interactionTypes | array | Unterstützte Interaktionstypen | **Seed-Daten:** YouTube wird automatisch bei Migration erstellt. --- ### 2. SocialAccounts (`social-accounts`) **Zweck:** Verknüpft Plattformen mit konkreten Accounts/Kanälen. **Pfad:** `src/collections/SocialAccounts.ts` **Felder:** | Feld | Typ | Beschreibung | |------|-----|--------------| | platform | relationship | → social-platforms | | linkedChannel | relationship | → youtube-channels | | displayName | text | Anzeigename | | accountHandle | text | @handle | | externalId | text | Plattform-ID | | credentials | group | OAuth Tokens (verschlüsselt) | | syncSettings | group | Auto-Sync Konfiguration | | stats | group | Follower, Posts, Last Sync | **Besonderheit:** `linkedChannel` verbindet mit bestehenden YouTube-Kanälen aus dem YouTube Operations Hub. --- ### 3. CommunityInteractions (`community-interactions`) **Zweck:** Zentrale Sammlung aller eingehenden Interaktionen. **Pfad:** `src/collections/CommunityInteractions.ts` **Felder:** | Feld | Typ | Beschreibung | |------|-----|--------------| | platform | relationship | → social-platforms | | socialAccount | relationship | → social-accounts | | linkedContent | relationship | → youtube-content | | type | select | comment / reply / dm / mention | | externalId | text | Unique ID von der Plattform | | parentInteraction | relationship | → self (für Antwort-Threads) | | **Author-Gruppe** | | | | author.name | text | Autorname | | author.handle | text | @handle | | author.isVerified | checkbox | Verifizierter Account? | | author.isSubscriber | checkbox | Abonnent? | | author.subscriberCount | number | Follower des Autors | | **Inhalt** | | | | message | textarea | Nachrichtentext | | messageHtml | textarea | HTML-Version | | publishedAt | date | Veröffentlichungsdatum | | attachments | array | Bilder, Videos | | **KI-Analyse** | | | | analysis.sentiment | select | positive / neutral / negative / mixed | | analysis.sentimentScore | number | -1.0 bis 1.0 | | analysis.confidence | number | 0-100% | | analysis.topics | array | Erkannte Themen | | analysis.suggestedTemplate | relationship | → community-templates | | analysis.suggestedReply | textarea | KI-generierter Antwortvorschlag | | **Flags** | | | | flags.isMedicalQuestion | checkbox | Medizinische Frage? | | flags.requiresEscalation | checkbox | Eskalation nötig? | | flags.isSpam | checkbox | Spam? | | flags.isFromInfluencer | checkbox | Von Influencer? | | **Workflow** | | | | status | select | new / read / in_progress / awaiting / responded / closed | | priority | select | urgent / high / normal / low | | assignedTo | relationship | → users | | responseDeadline | date | Antwort-Frist | | **Antwort** | | | | response.text | textarea | Gesendete Antwort | | response.usedTemplate | relationship | → community-templates | | response.sentAt | date | Gesendet am | | response.sentBy | relationship | → users | | **Engagement** | | | | engagement.likes | number | Likes | | engagement.replies | number | Anzahl Antworten | | engagement.isHearted | checkbox | Geherzt? | | engagement.isPinned | checkbox | Angepinnt? | **Hooks:** - `beforeChange`: Setzt automatisch `priority: urgent` wenn `flags.isMedicalQuestion` oder `flags.requiresEscalation` --- ### 4. CommunityTemplates (`community-templates`) **Zweck:** Vordefinierte Antwortvorlagen. **Pfad:** `src/collections/CommunityTemplates.ts` **Felder:** | Feld | Typ | Beschreibung | |------|-----|--------------| | name | text (localized) | Template-Name | | template | textarea (localized) | Antworttext mit Variablen | | category | select | greeting / thank_you / question / support / medical / promotion | | platforms | relationship | → social-platforms (hasMany) | | channel | relationship | → youtube-channels | | variables | array | Verfügbare Variablen | | variables.variable | text | z.B. `{{author_name}}` | | variables.description | text | Beschreibung | | variables.defaultValue | text | Fallback-Wert | | autoSuggestKeywords | array | Keywords für Auto-Suggest | | requiresReview | checkbox | Muss vor Senden geprüft werden? | | usageCount | number | Verwendungszähler | **Lokalisierung:** `name` und `template` sind mehrsprachig (de/en). --- ### 5. CommunityRules (`community-rules`) **Zweck:** Automatisierungsregeln für eingehende Interaktionen. **Pfad:** `src/collections/CommunityRules.ts` **Felder:** | Feld | Typ | Beschreibung | |------|-----|--------------| | name | text | Regelname | | priority | number | Ausführungsreihenfolge (niedrig = zuerst) | | isActive | checkbox | Regel aktiv? | | platforms | relationship | → social-platforms (hasMany) | | channel | relationship | → youtube-channels | | **Trigger** | | | | trigger.type | select | keyword / sentiment / influencer / medical / new_subscriber | | trigger.keywords | array | Keyword-Liste mit Match-Typ | | trigger.sentimentValues | array | positive / negative / mixed | | trigger.influencerMinFollowers | number | Min. Follower für Influencer | | **Actions** | | | | actions | array | Auszuführende Aktionen | | actions.action | select | set_priority / assign_to / apply_template / flag / auto_reply / notify | | actions.value | text | Wert (z.B. "urgent") | | actions.targetUser | relationship | → users | | actions.targetTemplate | relationship | → community-templates | | **Stats** | | | | stats.timesTriggered | number | Ausführungszähler | | stats.lastTriggeredAt | date | Letzte Ausführung | --- ## Access Control **Datei:** `src/lib/communityAccess.ts` ### Rollen-Hierarchie ``` communityRole: none → Kein Zugriff viewer → Nur Lesen moderator → Lesen + Bearbeiten zugewiesener Interaktionen manager → Vollzugriff (CRUD auf alle Community-Collections) ``` ### Access Functions | Funktion | Beschreibung | |----------|--------------| | `isCommunityManager` | Prüft `communityRole === 'manager'` oder `isSuperAdmin` | | `isCommunityModeratorOrAbove` | Prüft `communityRole in ['moderator', 'manager']` | | `hasCommunityAccess` | Prüft `communityRole !== 'none'` | | `canAccessAssignedInteractions` | Moderator sieht nur zugewiesene Interaktionen | ### Integration mit YouTube-Rollen Community-Rollen ergänzen die bestehenden YouTube-Rollen: - Ein User kann `youtubeRole: 'manager'` UND `communityRole: 'moderator'` haben - Super-Admins haben automatisch vollen Zugriff --- ## Integration Services ### YouTubeClient **Datei:** `src/lib/integrations/youtube/YouTubeClient.ts` **Abhängigkeit:** `googleapis` ```typescript class YouTubeClient { constructor(accessToken: string, refreshToken?: string) // Kommentare abrufen async getVideoComments(videoId: string, maxResults?: number) async getChannelComments(channelId: string, maxResults?: number) // Aktionen async replyToComment(parentId: string, text: string) async markAsSpam(commentId: string) async deleteComment(commentId: string) // Token Management async refreshAccessToken(): Promise // Stats async getChannelStats(channelId: string) } ``` --- ### ClaudeAnalysisService **Datei:** `src/lib/integrations/claude/ClaudeAnalysisService.ts` **Abhängigkeit:** `@anthropic-ai/sdk` ```typescript interface CommentAnalysis { sentiment: 'positive' | 'neutral' | 'negative' | 'mixed' sentimentScore: number // -1.0 bis 1.0 confidence: number // 0-100 topics: string[] isMedicalQuestion: boolean requiresEscalation: boolean isSpam: boolean suggestedReply?: string language: string } class ClaudeAnalysisService { constructor(apiKey?: string) async analyzeComment( comment: string, context?: { channelName?: string; videoTitle?: string } ): Promise async generateReply( comment: string, template?: string, context?: object ): Promise async analyzeCommentsBatch( comments: Array<{ id: string; text: string }> ): Promise> } ``` --- ### CommentsSyncService **Datei:** `src/lib/integrations/youtube/CommentsSyncService.ts` **Orchestriert** YouTubeClient + ClaudeAnalysisService: ```typescript class CommentsSyncService { constructor(payload: Payload) async syncCommentsForAccount( socialAccountId: number, options?: { maxComments?: number analyzeWithAI?: boolean } ): Promise } ``` **Ablauf:** 1. Social Account laden 2. YouTube-Kommentare abrufen 3. Für jeden neuen Kommentar: - Claude-Analyse durchführen - CommunityInteraction erstellen/aktualisieren 4. Sync-Timestamp aktualisieren --- ## API Endpoints ### POST `/api/community/sync-comments` **Zweck:** Manueller Kommentar-Sync für einen Account. **Auth:** Erforderlich (communityRole >= moderator) **Body:** ```json { "socialAccountId": 1, "maxComments": 100, "analyzeWithAI": true } ``` **Response:** ```json { "success": true, "synced": 47, "created": 12, "updated": 35, "errors": [] } ``` --- ### POST `/api/community/reply` **Zweck:** Antwort auf eine Interaktion senden. **Auth:** Erforderlich (communityRole >= moderator) **Body:** ```json { "interactionId": 123, "text": "Vielen Dank für Ihren Kommentar!", "templateId": 5 } ``` **Response:** ```json { "success": true, "externalReplyId": "Ugw8x7y9z..." } ``` --- ## Datenbank-Schema ### Haupt-Tabellen | Tabelle | Beschreibung | |---------|--------------| | `social_platforms` | Plattform-Definitionen | | `social_accounts` | Account-Konfigurationen | | `community_interactions` | Alle Interaktionen | | `community_templates` | Antwortvorlagen | | `community_templates_locales` | Lokalisierte Felder | | `community_rules` | Automatisierungsregeln | ### Array-Tabellen | Tabelle | Parent | |---------|--------| | `social_platforms_api_config_scopes` | social_platforms | | `social_platforms_interaction_types` | social_platforms | | `community_interactions_attachments` | community_interactions | | `community_interactions_analysis_topics` | community_interactions | | `community_templates_variables` | community_templates | | `community_templates_auto_suggest_keywords` | community_templates | | `community_rules_trigger_keywords` | community_rules | | `community_rules_trigger_sentiment_values` | community_rules | | `community_rules_actions` | community_rules | ### Relationship-Tabellen | Tabelle | Beschreibung | |---------|--------------| | `community_templates_rels` | Templates ↔ Platforms | | `community_rules_rels` | Rules ↔ Platforms | ### Users-Erweiterung ```sql ALTER TABLE users ADD COLUMN community_role enum_users_community_role; -- Values: 'none', 'viewer', 'moderator', 'manager' ``` --- ## Migrationen | Migration | Beschreibung | |-----------|--------------| | `20260113_180000_add_community_phase1` | Erstellt alle Community-Tabellen | | `20260114_200000_fix_community_role_enum` | Konvertiert community_role zu ENUM | --- ## Umgebungsvariablen ```env # YouTube API (für Comment-Sync) YOUTUBE_CLIENT_ID=your-client-id YOUTUBE_CLIENT_SECRET=your-client-secret # Claude AI (für Sentiment-Analyse) ANTHROPIC_API_KEY=your-api-key ``` --- ## Erweiterungsmöglichkeiten ### Neue Plattform hinzufügen 1. **SocialPlatform erstellen** im Admin 2. **Client-Klasse implementieren** in `src/lib/integrations/{platform}/` 3. **SyncService erweitern** für neue Plattform ### Neue Automatisierungsregel 1. **Trigger-Typ hinzufügen** in `CommunityRules.ts` 2. **Action-Handler implementieren** im Rules-Engine (noch zu implementieren) ### Dashboard (Phase 2) Geplante Features: - Interaktions-Inbox mit Filtern - Sentiment-Übersicht (Charts) - Response-Time-Tracking - Team-Performance-Metriken --- ## Dateien-Übersicht ``` src/ ├── collections/ │ ├── SocialPlatforms.ts │ ├── SocialAccounts.ts │ ├── CommunityInteractions.ts │ ├── CommunityTemplates.ts │ ├── CommunityRules.ts │ └── Users.ts (erweitert um communityRole) ├── lib/ │ ├── communityAccess.ts │ └── integrations/ │ ├── youtube/ │ │ ├── YouTubeClient.ts │ │ └── CommentsSyncService.ts │ └── claude/ │ └── ClaudeAnalysisService.ts ├── app/(payload)/api/community/ │ ├── sync-comments/route.ts │ └── reply/route.ts └── migrations/ ├── 20260113_180000_add_community_phase1.ts └── 20260114_200000_fix_community_role_enum.ts ```