# Copyright (c) 2025 Patrick Motsch # All rights reserved. """ CommCoach Feature Container - Main Module. Handles feature initialization and RBAC catalog registration. """ import logging from typing import Dict, List, Any from modules.shared.i18nRegistry import t logger = logging.getLogger(__name__) FEATURE_CODE = "commcoach" FEATURE_LABEL = t("Kommunikations-Coach", context="UI") FEATURE_ICON = "mdi-account-voice" UI_OBJECTS = [ { "objectKey": "ui.feature.commcoach.dashboard", "label": t("Dashboard", context="UI"), "meta": {"area": "dashboard"} }, { "objectKey": "ui.feature.commcoach.assistant", "label": t("Assistent", context="UI"), "meta": {"area": "assistant"} }, { "objectKey": "ui.feature.commcoach.modules", "label": t("Module", context="UI"), "meta": {"area": "modules"} }, { "objectKey": "ui.feature.commcoach.session", "label": t("Session", context="UI"), "meta": {"area": "session"} }, { "objectKey": "ui.feature.commcoach.dossier", "label": t("Dossier", context="UI"), "meta": {"area": "dossier"} }, { "objectKey": "ui.feature.commcoach.settings", "label": t("Einstellungen", context="UI"), "meta": {"area": "settings"} }, ] DATA_OBJECTS = [ # ── Record-Hierarchie: TrainingModule → Session → Message/Score, TrainingModule → Task ── { "objectKey": "data.feature.commcoach.TrainingModule", "label": t("Trainings-Modul", context="UI"), "meta": { "table": "TrainingModule", "fields": ["id", "title", "moduleType", "status", "lastSessionAt"], "isParent": True, "displayFields": ["title", "moduleType", "status"], } }, { "objectKey": "data.feature.commcoach.CoachingSession", "label": t("Coaching-Session", context="UI"), "meta": { "table": "CoachingSession", "fields": ["id", "moduleId", "status", "summary", "startedAt", "endedAt", "competenceScore"], "isParent": True, "parentTable": "TrainingModule", "parentKey": "moduleId", "displayFields": ["startedAt", "status"], } }, { "objectKey": "data.feature.commcoach.CoachingMessage", "label": t("Coaching-Nachricht", context="UI"), "meta": { "table": "CoachingMessage", "fields": ["id", "sessionId", "moduleId", "role", "content", "contentType"], "parentTable": "CoachingSession", "parentKey": "sessionId", } }, { "objectKey": "data.feature.commcoach.CoachingScore", "label": t("Coaching-Score", context="UI"), "meta": { "table": "CoachingScore", "fields": ["id", "sessionId", "moduleId", "dimension", "score", "trend"], "parentTable": "CoachingSession", "parentKey": "sessionId", } }, { "objectKey": "data.feature.commcoach.CoachingTask", "label": t("Coaching-Aufgabe", context="UI"), "meta": { "table": "CoachingTask", "fields": ["id", "moduleId", "title", "status", "priority", "dueDate"], "parentTable": "TrainingModule", "parentKey": "moduleId", } }, # ── Stammdaten (sessionübergreifend, scoped per userId) ────────────────── { "objectKey": "data.feature.commcoach.userData", "label": t("Stammdaten", context="UI"), "meta": {"isGroup": True} }, { "objectKey": "data.feature.commcoach.CoachingUserProfile", "label": t("Benutzerprofil", context="UI"), "meta": { "table": "CoachingUserProfile", "group": "data.feature.commcoach.userData", "fields": ["id", "userId", "dailyReminderEnabled", "streakDays", "totalSessions"], } }, { "objectKey": "data.feature.commcoach.CoachingPersona", "label": t("Coaching-Persona", context="UI"), "meta": { "table": "CoachingPersona", "group": "data.feature.commcoach.userData", "fields": ["id", "key", "label", "gender", "category"], } }, { "objectKey": "data.feature.commcoach.ModulePersonaMapping", "label": t("Modul-Persona-Zuordnung", context="UI"), "meta": { "table": "ModulePersonaMapping", "group": "data.feature.commcoach.userData", "fields": ["id", "moduleId", "personaId", "instanceId"], } }, { "objectKey": "data.feature.commcoach.CoachingBadge", "label": t("Coaching-Auszeichnung", context="UI"), "meta": { "table": "CoachingBadge", "group": "data.feature.commcoach.userData", "fields": ["id", "badgeKey", "awardedAt"], } }, { "objectKey": "data.feature.commcoach.*", "label": t("Alle CommCoach-Daten", context="UI"), "meta": {"wildcard": True} }, ] RESOURCE_OBJECTS = [ { "objectKey": "resource.feature.commcoach.module.create", "label": t("Modul erstellen", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/modules", "method": "POST"} }, { "objectKey": "resource.feature.commcoach.module.archive", "label": t("Modul archivieren", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/modules/{moduleId}/archive", "method": "POST"} }, { "objectKey": "resource.feature.commcoach.session.start", "label": t("Session starten", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/modules/{moduleId}/sessions/start", "method": "POST"} }, { "objectKey": "resource.feature.commcoach.session.complete", "label": t("Session abschliessen", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/sessions/{sessionId}/complete", "method": "POST"} }, { "objectKey": "resource.feature.commcoach.task.manage", "label": t("Aufgaben verwalten", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/modules/{moduleId}/tasks", "method": "POST"} }, { "objectKey": "resource.feature.commcoach.persona.manage", "label": t("Persona verwalten", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/personas", "method": "POST"} }, { "objectKey": "resource.feature.commcoach.modulePersonas.manage", "label": t("Modul-Persona-Zuordnung verwalten", context="UI"), "meta": {"endpoint": "/api/commcoach/{instanceId}/modules/{moduleId}/personas", "method": "PUT"} }, ] TEMPLATE_ROLES = [ { "roleLabel": "commcoach-viewer", "description": "Kommunikations-Coach Betrachter - Coaching-Daten ansehen (nur lesen)", "accessRules": [ {"context": "UI", "item": "ui.feature.commcoach.dashboard", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.assistant", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.modules", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.session", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.dossier", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.settings", "view": True}, {"context": "DATA", "item": None, "view": True, "read": "m", "create": "n", "update": "n", "delete": "n"}, {"context": "RESOURCE", "item": None, "view": False}, ], }, { "roleLabel": "commcoach-user", "description": "Kommunikations-Coach Benutzer - Kann eigene Coaching-Module und Sessions verwalten", "accessRules": [ {"context": "UI", "item": "ui.feature.commcoach.dashboard", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.assistant", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.modules", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.session", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.dossier", "view": True}, {"context": "UI", "item": "ui.feature.commcoach.settings", "view": True}, {"context": "DATA", "item": "data.feature.commcoach.TrainingModule", "view": True, "read": "m", "create": "m", "update": "m", "delete": "m"}, {"context": "DATA", "item": "data.feature.commcoach.CoachingSession", "view": True, "read": "m", "create": "m", "update": "m", "delete": "n"}, {"context": "DATA", "item": "data.feature.commcoach.CoachingMessage", "view": True, "read": "m", "create": "m", "update": "n", "delete": "n"}, {"context": "DATA", "item": "data.feature.commcoach.CoachingTask", "view": True, "read": "m", "create": "m", "update": "m", "delete": "m"}, {"context": "DATA", "item": "data.feature.commcoach.CoachingScore", "view": True, "read": "m", "create": "n", "update": "n", "delete": "n"}, {"context": "DATA", "item": "data.feature.commcoach.CoachingUserProfile", "view": True, "read": "m", "create": "m", "update": "m", "delete": "n"}, {"context": "RESOURCE", "item": "resource.feature.commcoach.module.create", "view": True}, {"context": "RESOURCE", "item": "resource.feature.commcoach.module.archive", "view": True}, {"context": "RESOURCE", "item": "resource.feature.commcoach.session.start", "view": True}, {"context": "RESOURCE", "item": "resource.feature.commcoach.session.complete", "view": True}, {"context": "RESOURCE", "item": "resource.feature.commcoach.task.manage", "view": True}, ], }, { "roleLabel": "commcoach-admin", "description": "Kommunikations-Coach Admin - Alle UI- und API-Aktionen; Daten nur eigene Datensaetze", "accessRules": [ {"context": "UI", "item": None, "view": True}, {"context": "RESOURCE", "item": None, "view": True}, {"context": "DATA", "item": None, "view": True, "read": "m", "create": "m", "update": "m", "delete": "m"}, ], }, ] def getFeatureDefinition() -> Dict[str, Any]: return { "code": FEATURE_CODE, "label": FEATURE_LABEL, "icon": FEATURE_ICON, "autoCreateInstance": False, } def getUiObjects() -> List[Dict[str, Any]]: return UI_OBJECTS def getResourceObjects() -> List[Dict[str, Any]]: return RESOURCE_OBJECTS def getTemplateRoles() -> List[Dict[str, Any]]: return TEMPLATE_ROLES def getDataObjects() -> List[Dict[str, Any]]: return DATA_OBJECTS def registerFeature(catalogService) -> bool: try: for uiObj in UI_OBJECTS: catalogService.registerUiObject( featureCode=FEATURE_CODE, objectKey=uiObj["objectKey"], label=uiObj["label"], meta=uiObj.get("meta") ) for resObj in RESOURCE_OBJECTS: catalogService.registerResourceObject( featureCode=FEATURE_CODE, objectKey=resObj["objectKey"], label=resObj["label"], meta=resObj.get("meta") ) for dataObj in DATA_OBJECTS: catalogService.registerDataObject( featureCode=FEATURE_CODE, objectKey=dataObj["objectKey"], label=dataObj["label"], meta=dataObj.get("meta") ) _runMigrations() _syncTemplateRolesToDb() _seedBuiltinPersonas() _registerScheduler() logger.info(f"Feature '{FEATURE_CODE}' registered {len(UI_OBJECTS)} UI, {len(RESOURCE_OBJECTS)} resource, {len(DATA_OBJECTS)} data objects") return True except Exception as e: logger.error(f"Failed to register feature '{FEATURE_CODE}': {e}") return False def _runMigrations(): """Idempotent DB migrations for CommCoach feature. Runs on every bootstrap; each step checks preconditions before executing. """ try: from .interfaceFeatureCommcoach import commcoachDatabase from modules.shared.configuration import APP_CONFIG import psycopg2 from psycopg2.extras import RealDictCursor conn = psycopg2.connect( host=APP_CONFIG.get("DB_HOST", "localhost"), database=commcoachDatabase, user=APP_CONFIG.get("DB_USER"), password=APP_CONFIG.get("DB_PASSWORD_SECRET"), port=int(APP_CONFIG.get("DB_PORT", 5432)), cursor_factory=RealDictCursor, ) conn.autocommit = False cur = conn.cursor() def _tableExists(name): cur.execute( "SELECT 1 FROM information_schema.tables WHERE LOWER(table_name) = LOWER(%s) AND table_schema = 'public'", (name,), ) return cur.fetchone() is not None def _columnExists(table, column): cur.execute( "SELECT 1 FROM information_schema.columns WHERE LOWER(table_name) = LOWER(%s) AND LOWER(column_name) = LOWER(%s) AND table_schema = 'public'", (table, column), ) return cur.fetchone() is not None migrated = False # M1: Rename table CoachingContext -> TrainingModule if _tableExists("CoachingContext") and not _tableExists("TrainingModule"): cur.execute('ALTER TABLE "CoachingContext" RENAME TO "TrainingModule"') logger.info("Migration M1: Renamed table CoachingContext -> TrainingModule") migrated = True # M2: Rename contextId -> moduleId on child tables for childTable in ["CoachingSession", "CoachingMessage", "CoachingTask", "CoachingScore"]: if _tableExists(childTable) and _columnExists(childTable, "contextId") and not _columnExists(childTable, "moduleId"): cur.execute(f'ALTER TABLE "{childTable}" RENAME COLUMN "contextId" TO "moduleId"') logger.info(f"Migration M2: Renamed contextId -> moduleId on {childTable}") migrated = True # M3: Add moduleType column with default 'coaching' if _tableExists("TrainingModule") and not _columnExists("TrainingModule", "moduleType"): cur.execute('ALTER TABLE "TrainingModule" ADD COLUMN "moduleType" TEXT DEFAULT \'coaching\'') cur.execute('UPDATE "TrainingModule" SET "moduleType" = \'coaching\' WHERE "moduleType" IS NULL') logger.info("Migration M3: Added moduleType column to TrainingModule") migrated = True # M4: Add personaId column if _tableExists("TrainingModule") and not _columnExists("TrainingModule", "personaId"): cur.execute('ALTER TABLE "TrainingModule" ADD COLUMN "personaId" TEXT') logger.info("Migration M4: Added personaId column to TrainingModule") migrated = True # M5: Add kpiTargets column if _tableExists("TrainingModule") and not _columnExists("TrainingModule", "kpiTargets"): cur.execute('ALTER TABLE "TrainingModule" ADD COLUMN "kpiTargets" TEXT') logger.info("Migration M5: Added kpiTargets column to TrainingModule") migrated = True # M6: Drop category column (replaced by moduleType) if _tableExists("TrainingModule") and _columnExists("TrainingModule", "category"): cur.execute('ALTER TABLE "TrainingModule" DROP COLUMN "category"') logger.info("Migration M6: Dropped category column from TrainingModule") migrated = True # M7: Convert goals from JSON array to plain text if _tableExists("TrainingModule") and _columnExists("TrainingModule", "goals"): cur.execute(""" UPDATE "TrainingModule" SET "goals" = subq.plainText FROM ( SELECT id, string_agg(elem->>'text', E'\\n') AS plainText FROM "TrainingModule", LATERAL jsonb_array_elements("goals"::jsonb) AS elem WHERE "goals" IS NOT NULL AND "goals" LIKE '[%' GROUP BY id ) subq WHERE "TrainingModule".id = subq.id """) rowCount = cur.rowcount if rowCount > 0: logger.info(f"Migration M7: Converted {rowCount} goals fields from JSON to plain text") migrated = True # M8: Create ModulePersonaMapping table if not _tableExists("ModulePersonaMapping"): cur.execute(""" CREATE TABLE "ModulePersonaMapping" ( id TEXT PRIMARY KEY, "moduleId" TEXT NOT NULL, "personaId" TEXT NOT NULL, "instanceId" TEXT NOT NULL, "createdAt" TEXT, "updatedAt" TEXT, UNIQUE("moduleId", "personaId") ) """) cur.execute('CREATE INDEX IF NOT EXISTS idx_mpm_module ON "ModulePersonaMapping" ("moduleId")') cur.execute('CREATE INDEX IF NOT EXISTS idx_mpm_persona ON "ModulePersonaMapping" ("personaId")') logger.info("Migration M8: Created ModulePersonaMapping table") migrated = True if migrated: conn.commit() logger.info("CommCoach DB migrations committed") else: conn.rollback() cur.close() conn.close() except ImportError: logger.debug("psycopg2 not available, skipping CommCoach DB migrations") except Exception as e: logger.warning(f"CommCoach DB migration failed (non-fatal): {e}") def _seedBuiltinPersonas(): """Seed builtin roleplay personas into the database.""" try: from .serviceCommcoachPersonas import seedBuiltinPersonas from .interfaceFeatureCommcoach import getInterface from modules.interfaces.interfaceDbApp import getRootInterface systemUser = getRootInterface().currentUser interface = getInterface(systemUser) seedBuiltinPersonas(interface) except Exception as e: logger.warning(f"CommCoach persona seeding failed (non-fatal): {e}") def _registerScheduler(): """Register CommCoach scheduled jobs (daily reminders).""" try: from modules.shared.eventManagement import eventManager from .serviceCommcoachScheduler import registerScheduledJobs registerScheduledJobs(eventManager) except Exception as e: logger.warning(f"CommCoach scheduler registration failed (non-fatal): {e}") def _syncTemplateRolesToDb() -> int: try: from modules.interfaces.interfaceDbApp import getRootInterface from modules.datamodels.datamodelRbac import Role, AccessRule, AccessRuleContext from modules.datamodels.datamodelUtils import coerce_text_multilingual rootInterface = getRootInterface() existingRoles = rootInterface.getRolesByFeatureCode(FEATURE_CODE) templateRoles = [r for r in existingRoles if r.mandateId is None] existingRoleLabels = {r.roleLabel: str(r.id) for r in templateRoles} createdCount = 0 for roleTemplate in TEMPLATE_ROLES: roleLabel = roleTemplate["roleLabel"] if roleLabel in existingRoleLabels: roleId = existingRoleLabels[roleLabel] _ensureAccessRulesForRole(rootInterface, roleId, roleTemplate.get("accessRules", [])) else: newRole = Role( roleLabel=roleLabel, description=coerce_text_multilingual(roleTemplate.get("description", {})), featureCode=FEATURE_CODE, mandateId=None, featureInstanceId=None, isSystemRole=False ) createdRole = rootInterface.db.recordCreate(Role, newRole.model_dump()) roleId = createdRole.get("id") _ensureAccessRulesForRole(rootInterface, roleId, roleTemplate.get("accessRules", [])) logger.info(f"Created template role '{roleLabel}' with ID {roleId}") createdCount += 1 if createdCount > 0: logger.info(f"Feature '{FEATURE_CODE}': Created {createdCount} template roles") return createdCount except Exception as e: logger.error(f"Error syncing template roles for feature '{FEATURE_CODE}': {e}") return 0 def _ensureAccessRulesForRole(rootInterface, roleId: str, ruleTemplates: List[Dict[str, Any]]) -> int: from modules.datamodels.datamodelRbac import AccessRule, AccessRuleContext existingRules = rootInterface.getAccessRulesByRole(roleId) existingSignatures = set() for rule in existingRules: sig = (rule.context.value if rule.context else None, rule.item) existingSignatures.add(sig) createdCount = 0 for template in ruleTemplates: context = template.get("context", "UI") item = template.get("item") sig = (context, item) if sig in existingSignatures: continue if context == "UI": contextEnum = AccessRuleContext.UI elif context == "DATA": contextEnum = AccessRuleContext.DATA elif context == "RESOURCE": contextEnum = AccessRuleContext.RESOURCE else: contextEnum = context newRule = AccessRule( roleId=roleId, context=contextEnum, item=item, view=template.get("view", False), read=template.get("read"), create=template.get("create"), update=template.get("update"), delete=template.get("delete"), ) rootInterface.db.recordCreate(AccessRule, newRule.model_dump()) createdCount += 1 if createdCount > 0: logger.debug(f"Created {createdCount} AccessRules for role {roleId}") return createdCount