diff --git a/appdoc/doc_workflow_actions_rbac_concept.md b/appdoc/doc_workflow_actions_rbac_concept.md index cc762ee..8079558 100644 --- a/appdoc/doc_workflow_actions_rbac_concept.md +++ b/appdoc/doc_workflow_actions_rbac_concept.md @@ -24,37 +24,36 @@ class MethodOutlook(MethodBase): # Actions werden deklarativ definiert self._actions = { - "readEmails": ActionDefinition( + "readEmails": WorkflowActionDefinition( actionId="outlook.readEmails", # Für RBAC: RESOURCE context description="Read emails from Outlook mailbox", parameters={ - "connectionReference": ActionParameter( + "connectionReference": WorkflowActionParameter( name="connectionReference", - type=str, - frontendType="select", - frontendOptions="user.connection", + type="str", + frontendType=FrontendType.USER_CONNECTION, required=True, description="Microsoft connection label" ), - "query": ActionParameter( + "query": WorkflowActionParameter( name="query", - type=str, - frontendType="text", + type="str", + frontendType=FrontendType.TEXT, required=False, description="Search query for emails" ), - "folder": ActionParameter( + "folder": WorkflowActionParameter( name="folder", - type=str, - frontendType="select", + type="str", + frontendType=FrontendType.SELECT, frontendOptions="outlook.folder", required=False, description="Folder name (e.g., 'Inbox', 'Drafts')" ), - "limit": ActionParameter( + "limit": WorkflowActionParameter( name="limit", - type=int, - frontendType="number", + type="int", + frontendType=FrontendType.NUMBER, required=False, default=50, description="Maximum number of emails to return" @@ -62,7 +61,7 @@ class MethodOutlook(MethodBase): }, execute=self._executeReadEmails # Funktion als Attribut ), - "sendEmail": ActionDefinition( + "sendEmail": WorkflowActionDefinition( actionId="outlook.sendEmail", description="Send email via Outlook", parameters={...}, @@ -90,17 +89,24 @@ Custom-Types unterstützen dynamische Option-Listen über API-Endpoints: ## Datenmodelle -### ActionParameter +### WorkflowActionParameter -**WICHTIG**: Frontend-Types werden global definiert in `modules/shared/frontendTypes.py` und nicht redundant in Actions. +**WICHTIG**: +- Frontend-Types werden global definiert in `modules/shared/frontendTypes.py` und nicht redundant in Actions +- Diese Klasse heißt `WorkflowActionParameter` (nicht `ActionParameter`) um Konflikte mit `ActionParameters` aus `datamodelChat.py` zu vermeiden ```python from typing import Optional, Any, Union, List, Dict from pydantic import BaseModel, Field from modules.shared.frontendTypes import FrontendType # Globale Definition -class ActionParameter(BaseModel): - """Parameter definition for an action""" +class WorkflowActionParameter(BaseModel): + """ + Parameter schema definition for a workflow action. + + This defines the structure and UI rendering for a single action parameter, + NOT the actual parameter values (those are in ActionDefinition.parameters). + """ name: str = Field(description="Parameter name") type: str = Field(description="Python type as string (e.g., 'str', 'int', 'bool', 'List[str]')") frontendType: FrontendType = Field(description="UI rendering type (from global FrontendType enum)") @@ -124,26 +130,39 @@ class ActionParameter(BaseModel): Für Custom-Types wird `frontendOptions` automatisch auf den entsprechenden API-Endpoint gesetzt (z.B. `"user.connection"`). -### ActionDefinition +### WorkflowActionDefinition + +**WICHTIG**: Diese Klasse heißt `WorkflowActionDefinition` (nicht `ActionDefinition`) um Konflikte mit der bestehenden `ActionDefinition` aus `datamodelWorkflow.py` zu vermeiden: +- **Bestehende `ActionDefinition`**: Für Workflow-Execution-Planning (enthält konkrete Werte: `action`, `actionObjective`, `parameters` mit Werten) +- **Neue `WorkflowActionDefinition`**: Für Action-Schema-Definitionen (enthält Metadaten: `actionId`, `description`, `parameters` als Schemas) ```python -from typing import Dict, Callable, Awaitable +from typing import Dict, Callable, Awaitable, Optional, List from pydantic import BaseModel, Field +from modules.datamodels.datamodelChat import ActionResult -class ActionDefinition(BaseModel): - """Complete definition of an action""" +class WorkflowActionDefinition(BaseModel): + """ + Complete schema definition of a workflow action. + + This defines the metadata, parameters, and execution function for an action. + This is different from datamodelWorkflow.ActionDefinition which contains + actual execution values (action, actionObjective, parameters with values). + + This class defines the ACTION SCHEMA, not the execution plan. + """ actionId: str = Field( description="Unique action identifier for RBAC (format: 'module.actionName', e.g., 'outlook.readEmails')" ) description: str = Field(description="Action description") - parameters: Dict[str, ActionParameter] = Field( + parameters: Dict[str, WorkflowActionParameter] = Field( default_factory=dict, - description="Parameter definitions" + description="Parameter schema definitions" ) - execute: Callable[[Dict[str, Any]], Awaitable[ActionResult]] = Field( - description="Execution function - async function that takes parameters dict and returns ActionResult" + execute: Optional[Callable[[Dict[str, Any]], Awaitable[ActionResult]]] = Field( + None, + description="Execution function - async function that takes parameters dict and returns ActionResult. Set dynamically." ) - # Optional metadata category: Optional[str] = Field(None, description="Action category for grouping") tags: List[str] = Field(default_factory=list, description="Tags for search/filtering") ``` @@ -163,7 +182,7 @@ class MethodBase: self.logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}") # Actions werden als Dictionary definiert - self._actions: Dict[str, ActionDefinition] = {} + self._actions: Dict[str, WorkflowActionDefinition] = {} # Nach Initialisierung: Actions registrieren self._registerActions() @@ -185,7 +204,7 @@ class MethodBase: if not self._checkActionPermission(actionDef.actionId): continue # Skip if user doesn't have permission - # Konvertiere ActionDefinition zu altem Format für Kompatibilität + # Konvertiere WorkflowActionDefinition zu altem Format für Kompatibilität result[actionName] = { 'description': actionDef.description, 'parameters': self._convertParametersToOldFormat(actionDef.parameters), @@ -215,8 +234,8 @@ class MethodBase: return permissions.view - def _convertParametersToOldFormat(self, parameters: Dict[str, ActionParameter]) -> Dict[str, Dict[str, Any]]: - """Convert ActionParameter dict to old format for compatibility""" + def _convertParametersToOldFormat(self, parameters: Dict[str, WorkflowActionParameter]) -> Dict[str, Dict[str, Any]]: + """Convert WorkflowActionParameter dict to old format for compatibility""" result = {} for paramName, param in parameters.items(): result[paramName] = { @@ -229,10 +248,10 @@ class MethodBase: } return result - def _createActionWrapper(self, actionDef: ActionDefinition): + def _createActionWrapper(self, actionDef: WorkflowActionDefinition): """Create wrapper function that matches old action signature""" async def wrapper(parameters: Dict[str, Any], *args, **kwargs): - # Parameter-Validierung basierend auf ActionParameter definitions + # Parameter-Validierung basierend auf WorkflowActionParameter definitions validatedParams = self._validateParameters(parameters, actionDef.parameters) # Execute action @@ -241,7 +260,7 @@ class MethodBase: wrapper.is_action = True return wrapper - def _validateParameters(self, parameters: Dict[str, Any], paramDefs: Dict[str, ActionParameter]) -> Dict[str, Any]: + def _validateParameters(self, parameters: Dict[str, Any], paramDefs: Dict[str, WorkflowActionParameter]) -> Dict[str, Any]: """Validate parameters against definitions""" validated = {} @@ -291,34 +310,95 @@ class MethodBase: ### Schritt 1: Neue Datenmodelle erstellen +**WICHTIG**: Die bestehenden Klassen `ActionDefinition` (in `datamodelWorkflow.py`) und `ActionParameters` (in `datamodelChat.py`) haben einen anderen Zweck: +- `ActionDefinition` (existing): Für Workflow-Execution-Planning (enthält konkrete Werte) +- `ActionParameters` (existing): Einfacher Parameter-Wrapper + +**Lösung**: Neue Klassen mit klaren Namen für Action-Schema-Definitionen erstellen. + **Datei**: `gateway/modules/datamodels/datamodelWorkflowActions.py` ```python from typing import Optional, Any, Union, List, Dict, Callable, Awaitable -from enum import Enum from pydantic import BaseModel, Field from modules.datamodels.datamodelChat import ActionResult from modules.shared.frontendTypes import FrontendType # Globale Definition verwenden +from modules.shared.attributeUtils import registerModelLabels -class ActionParameter(BaseModel): - """Parameter definition for an action""" - name: str - type: str # String representation of type: "str", "int", "bool", "List[str]", etc. - frontendType: FrontendType - frontendOptions: Optional[Union[str, List[Dict[str, Any]]]] = None - required: bool = False - default: Optional[Any] = None - description: str = "" - validation: Optional[Dict[str, Any]] = None +class WorkflowActionParameter(BaseModel): + """ + Parameter schema definition for a workflow action. + + This defines the structure and UI rendering for a single action parameter, + NOT the actual parameter values (those are in ActionDefinition.parameters). + """ + name: str = Field(description="Parameter name") + type: str = Field(description="Python type as string: 'str', 'int', 'bool', 'List[str]', etc.") + frontendType: FrontendType = Field(description="UI rendering type (from global FrontendType enum)") + frontendOptions: Optional[Union[str, List[Dict[str, Any]]]] = Field( + None, + description="Options for select/multiselect/custom types. String reference (e.g., 'user.connection') or static list. For custom types, this is automatically set to the API endpoint." + ) + required: bool = Field(False, description="Whether parameter is required") + default: Optional[Any] = Field(None, description="Default value") + description: str = Field("", description="Parameter description") + validation: Optional[Dict[str, Any]] = Field( + None, + description="Validation rules (e.g., {'min': 1, 'max': 100})" + ) -class ActionDefinition(BaseModel): - """Complete definition of an action""" - actionId: str # Format: "module.actionName" (e.g., "outlook.readEmails") - description: str - parameters: Dict[str, ActionParameter] = Field(default_factory=dict) - execute: Optional[Callable] = None # Will be set dynamically - category: Optional[str] = None - tags: List[str] = Field(default_factory=list) +class WorkflowActionDefinition(BaseModel): + """ + Complete schema definition of a workflow action. + + This defines the metadata, parameters, and execution function for an action. + This is different from datamodelWorkflow.ActionDefinition which contains + actual execution values (action, actionObjective, parameters with values). + + This class defines the ACTION SCHEMA, not the execution plan. + """ + actionId: str = Field( + description="Unique action identifier for RBAC (format: 'module.actionName', e.g., 'outlook.readEmails')" + ) + description: str = Field(description="Action description") + parameters: Dict[str, WorkflowActionParameter] = Field( + default_factory=dict, + description="Parameter schema definitions" + ) + execute: Optional[Callable] = Field( + None, + description="Execution function - async function that takes parameters dict and returns ActionResult. Set dynamically." + ) + category: Optional[str] = Field(None, description="Action category for grouping") + tags: List[str] = Field(default_factory=list, description="Tags for search/filtering") + +# Register model labels for UI +registerModelLabels( + "WorkflowActionDefinition", + {"en": "Workflow Action Definition", "fr": "Définition d'action de workflow"}, + { + "actionId": {"en": "Action ID", "fr": "ID d'action"}, + "description": {"en": "Description", "fr": "Description"}, + "parameters": {"en": "Parameters", "fr": "Paramètres"}, + "category": {"en": "Category", "fr": "Catégorie"}, + "tags": {"en": "Tags", "fr": "Étiquettes"}, + }, +) + +registerModelLabels( + "WorkflowActionParameter", + {"en": "Workflow Action Parameter", "fr": "Paramètre d'action de workflow"}, + { + "name": {"en": "Name", "fr": "Nom"}, + "type": {"en": "Type", "fr": "Type"}, + "frontendType": {"en": "Frontend Type", "fr": "Type frontend"}, + "frontendOptions": {"en": "Frontend Options", "fr": "Options frontend"}, + "required": {"en": "Required", "fr": "Requis"}, + "default": {"en": "Default", "fr": "Par défaut"}, + "description": {"en": "Description", "fr": "Description"}, + "validation": {"en": "Validation", "fr": "Validation"}, + }, +) ``` ### Schritt 2: MethodBase erweitern @@ -357,25 +437,25 @@ def __init__(self, services): self.description = "Handle Microsoft Outlook email operations" self._actions = { - "readEmails": ActionDefinition( + "readEmails": WorkflowActionDefinition( actionId="outlook.readEmails", description="Read emails from Outlook mailbox", parameters={ - "connectionReference": ActionParameter( + "connectionReference": WorkflowActionParameter( name="connectionReference", type="str", frontendType=FrontendType.USER_CONNECTION, # Custom type - automatisch API-Endpoint required=True, description="Microsoft connection label" ), - "query": ActionParameter( + "query": WorkflowActionParameter( name="query", type="str", frontendType=FrontendType.TEXT, required=False, description="Search query for emails" ), - "folder": ActionParameter( + "folder": WorkflowActionParameter( name="folder", type="str", frontendType=FrontendType.SELECT, @@ -383,7 +463,7 @@ def __init__(self, services): required=False, description="Folder name (e.g., 'Inbox', 'Drafts')" ), - "limit": ActionParameter( + "limit": WorkflowActionParameter( name="limit", type="int", frontendType=FrontendType.NUMBER, @@ -501,7 +581,7 @@ def createActionRules(db: DatabaseConnector): ## Vorteile ### 1. Keine Duplikation -- Parameter werden nur einmal definiert (in `ActionDefinition`) +- Parameter werden nur einmal definiert (in `WorkflowActionDefinition`) - Keine Docstring-Parsing mehr nötig - Type-Safety durch Pydantic Models @@ -614,7 +694,7 @@ Führt eine Action aus (mit RBAC-Check). - **Verwendung**: Für Parameter wie `connectionReference` in Outlook/SharePoint Actions - **Beispiel**: ```python - ActionParameter( + WorkflowActionParameter( name="connectionReference", type="str", frontendType=FrontendType.USER_CONNECTION, @@ -629,7 +709,7 @@ Führt eine Action aus (mit RBAC-Check). - **Verwendung**: Für Parameter wie `documentList` in Actions, die auf vorherige Action-Ergebnisse verweisen - **Beispiel**: ```python - ActionParameter( + WorkflowActionParameter( name="documentList", type="List[str]", frontendType=FrontendType.DOCUMENT_REFERENCE, diff --git a/ui_nyla/ARCHITECTURE_DIAGRAMS.md b/ui_nyla/ARCHITECTURE_DIAGRAMS.md new file mode 100644 index 0000000..af876de --- /dev/null +++ b/ui_nyla/ARCHITECTURE_DIAGRAMS.md @@ -0,0 +1,484 @@ +# Architektur Diagramme - Frontend Nyla + +Diese Datei enthält visuelle Diagramme der Frontend-Architektur im Mermaid-Format. + +## 1. High-Level Architektur + +```mermaid +graph TB + subgraph "Entry Point" + A[main.tsx] --> B[App.tsx] + end + + subgraph "Infrastructure Layer" + B --> C[LanguageProvider] + B --> D[AuthProvider] + B --> E[Router] + end + + subgraph "Routing Layer" + E --> F[Login] + E --> G[Register] + E --> H[ProtectedRoute] + end + + subgraph "Application Layer" + H --> I[Home] + I --> J[Sidebar] + I --> K[PageManager] + end + + subgraph "Pages" + K --> L[Dashboard] + K --> M[Dateien] + K --> N[Connections] + K --> O[Workflows] + K --> P[Prompts] + K --> Q[TeamBereich] + K --> R[Einstellungen] + end + + style A fill:#e1f5ff + style B fill:#e1f5ff + style C fill:#fff4e1 + style D fill:#fff4e1 + style E fill:#fff4e1 + style I fill:#e8f5e9 + style K fill:#e8f5e9 +``` + +## 2. Component Hierarchy + +```mermaid +graph TD + A[App.tsx] --> B[Router] + B --> C[Home] + C --> D[Sidebar] + C --> E[PageManager] + + E --> F[Dashboard] + E --> G[Dateien] + E --> H[Connections] + E --> I[Workflows] + + F --> J[DashboardChat] + J --> K[DashboardChatArea] + K --> L[DashboardChatAreaMessageList] + K --> M[DashboardChatAreaInput] + K --> N[DashboardChatAreaConnectedFiles] + + G --> O[DateienTable] + O --> P[FilePreview] + P --> Q[FileRenderers] + + H --> R[ConnectionsTable] + R --> S[ConnectionEditModal] + + style A fill:#ffebee + style C fill:#e3f2fd + style E fill:#e8f5e9 + style F fill:#fff3e0 + style G fill:#fff3e0 + style H fill:#fff3e0 +``` + +## 3. Data Flow Architecture + +```mermaid +graph LR + subgraph "UI Layer" + A[Page Component] --> B[Feature Component] + end + + subgraph "Business Logic Layer" + B --> C[Custom Hook] + C --> D[useApiRequest] + end + + subgraph "API Layer" + D --> E[api.ts] + E --> F[Axios Instance] + F --> G[Backend API] + end + + subgraph "State Management" + C --> H[React State] + H --> I[Context API] + end + + G -.Response.-> F + F -.Data.-> D + D -.State Update.-> C + C -.Re-render.-> B + + style A fill:#e1f5ff + style C fill:#fff4e1 + style E fill:#e8f5e9 + style G fill:#fce4ec +``` + +## 4. Authentication Flow + +```mermaid +sequenceDiagram + participant User + participant App + participant AuthProvider + participant MSAL + participant ProtectedRoute + participant Backend + + User->>App: Access Protected Route + App->>AuthProvider: Check Auth Status + AuthProvider->>MSAL: Get Account + MSAL-->>AuthProvider: Account Status + + alt Not Authenticated + AuthProvider-->>App: No Account + App->>ProtectedRoute: Redirect to Login + ProtectedRoute->>User: Show Login Page + User->>MSAL: Login Request + MSAL->>Backend: OAuth Flow + Backend-->>MSAL: Token + MSAL-->>AuthProvider: Account + Token + AuthProvider->>App: Authenticated + end + + AuthProvider->>ProtectedRoute: Allow Access + ProtectedRoute->>App: Render Protected Content +``` + +## 5. Page Management Flow + +```mermaid +stateDiagram-v2 + [*] --> PageManager: Route Change + + PageManager --> CheckConfig: Get Page Config + CheckConfig --> LoadPage: Config Found & Enabled + CheckConfig --> ErrorPage: Config Not Found + + LoadPage --> CheckInstance: Page Instance Exists? + + CheckInstance --> ReuseInstance: Yes (Preserved) + CheckInstance --> CreateInstance: No + + ReuseInstance --> ShowPage: Activate Instance + CreateInstance --> LazyLoad: Load Component + LazyLoad --> ShowPage: Component Loaded + + ShowPage --> AnimateIn: Framer Motion + AnimateIn --> Active: Page Active + + Active --> AnimateOut: Navigate Away + AnimateOut --> Cleanup: Non-Preserved + AnimateOut --> Hide: Preserved + + Cleanup --> [*] + Hide --> [*] + ErrorPage --> [*] +``` + +## 6. Workflow Management Flow + +```mermaid +graph TB + subgraph "Dashboard Page" + A[Dashboard.tsx] --> B[useWorkflowManager] + end + + subgraph "Workflow Manager Hook" + B --> C[useWorkflow] + B --> D[useWorkflowStatus] + B --> E[useWorkflowMessages] + B --> F[useWorkflowLogs] + B --> G[useWorkflowOperations] + end + + subgraph "Workflows Hook" + C --> H[useApiRequest] + D --> H + E --> H + F --> H + G --> H + end + + subgraph "API Layer" + H --> I[api.ts] + I --> J[Backend API] + end + + subgraph "Polling Logic" + B --> K{Polling Active?} + K -->|Yes| L[Poll Every 2s] + L --> D + L --> E + L --> F + K -->|No| M[Stop Polling] + end + + style A fill:#e1f5ff + style B fill:#fff4e1 + style H fill:#e8f5e9 + style I fill:#fce4ec +``` + +## 7. File Upload & Preview Flow + +```mermaid +sequenceDiagram + participant User + participant DateienPage + participant DateienTable + participant useFileOperations + participant api.ts + participant Backend + participant FilePreview + + User->>DateienPage: Upload File + DateienPage->>DateienTable: File Selected + DateienTable->>useFileOperations: uploadFile(file) + useFileOperations->>api.ts: POST /api/files/ + api.ts->>Backend: Upload Request + Backend-->>api.ts: File Metadata + api.ts-->>useFileOperations: Response + useFileOperations-->>DateienTable: Success + + User->>DateienTable: Click File + DateienTable->>FilePreview: Show Preview + FilePreview->>FilePreview: Detect File Type + FilePreview->>FilePreview: Select Renderer + FilePreview->>api.ts: GET /api/files/{id}/content + api.ts->>Backend: File Content Request + Backend-->>api.ts: File Content + api.ts-->>FilePreview: Content Data + FilePreview-->>User: Render Preview +``` + +## 8. Internationalization Flow + +```mermaid +graph TB + subgraph "Initialization" + A[App.tsx] --> B[LanguageProvider] + B --> C{Check localStorage} + C -->|Found| D[Load Saved Language] + C -->|Not Found| E[Detect Browser Language] + D --> F[loadLanguage] + E --> F + end + + subgraph "Language Loading" + F --> G{Language Code} + G -->|de| H[locales/de.ts] + G -->|en| I[locales/en.ts] + G -->|fr| J[locales/fr.ts] + H --> K[Translation Object] + I --> K + J --> K + end + + subgraph "Usage" + K --> L[LanguageContext State] + L --> M[useLanguage Hook] + M --> N[Component] + N --> O[t function] + O --> P[Translation Key] + P --> K + end + + style A fill:#e1f5ff + style B fill:#fff4e1 + style K fill:#e8f5e9 + style N fill:#fce4ec +``` + +## 9. Component Dependency Graph + +```mermaid +graph TD + subgraph "Core Components" + A[PageManager] --> B[pageConfigs] + B --> C[Lazy Pages] + end + + subgraph "Feature Components" + D[DashboardChat] --> E[DashboardChatArea] + E --> F[DashboardChatAreaMessageList] + E --> G[DashboardChatAreaInput] + E --> H[DashboardChatAreaConnectedFiles] + + I[DateienTable] --> J[FilePreview] + J --> K[FileRenderers] + + L[ConnectionsTable] --> M[ConnectionEditModal] + + N[PromptsTable] --> O[Popup] + O --> P[EditForm] + end + + subgraph "Hooks Layer" + Q[useWorkflowManager] --> R[useWorkflows] + R --> S[useApiRequest] + + T[useConnections] --> S + U[useFiles] --> S + V[usePrompts] --> S + end + + subgraph "API Layer" + S --> W[api.ts] + W --> X[Backend] + end + + C --> D + C --> I + C --> L + C --> N + + D --> Q + I --> U + L --> T + N --> V + + style A fill:#e1f5ff + style S fill:#fff4e1 + style W fill:#e8f5e9 + style X fill:#fce4ec +``` + +## 10. State Management Architecture + +```mermaid +graph TB + subgraph "Global State" + A[LanguageContext] --> B[Current Language] + A --> C[Translations] + + D[AuthProvider] --> E[MSAL Instance] + D --> F[Account State] + end + + subgraph "Component State" + G[useState] --> H[Local Component State] + I[useReducer] --> J[Complex State Logic] + end + + subgraph "Derived State" + K[useMemo] --> L[Computed Values] + M[useCallback] --> N[Memoized Functions] + end + + subgraph "Server State" + O[useApiRequest] --> P[Loading State] + O --> Q[Error State] + O --> R[Data State] + end + + B --> G + C --> G + E --> D + F --> D + + H --> K + J --> K + + P --> G + Q --> G + R --> G + + style A fill:#e1f5ff + style D fill:#e1f5ff + style O fill:#fff4e1 + style G fill:#e8f5e9 +``` + +## 11. Build & Deployment Flow + +```mermaid +graph LR + subgraph "Development" + A[Source Code] --> B[Vite Dev Server] + B --> C[Hot Module Replacement] + C --> D[Browser] + end + + subgraph "Build Process" + E[Source Code] --> F[TypeScript Compiler] + F --> G[Vite Build] + G --> H[Bundle Optimization] + H --> I[Static Assets] + end + + subgraph "Environment" + J[.env.dev] --> B + K[.env.int] --> G + L[.env.prod] --> G + end + + subgraph "Deployment" + I --> M[Static Web App] + M --> N[Azure Static Web Apps] + end + + style A fill:#e1f5ff + style B fill:#fff4e1 + style G fill:#e8f5e9 + style N fill:#fce4ec +``` + +## 12. Error Handling Flow + +```mermaid +graph TD + A[API Request] --> B{Request Success?} + + B -->|Yes| C[Return Data] + B -->|No| D[Error Handler] + + D --> E{Error Type?} + + E -->|401 Unauthorized| F[Clear Token] + F --> G[Redirect to Login] + + E -->|Validation Error| H[Format Validation Errors] + H --> I[Display User-Friendly Message] + + E -->|Network Error| J[Display Network Error] + + E -->|Server Error| K[Format Server Error] + K --> I + + E -->|Unknown Error| L[Display Generic Error] + + I --> M[Update UI State] + J --> M + L --> M + + style A fill:#e1f5ff + style D fill:#ffebee + style M fill:#e8f5e9 +``` + +--- + +## Diagramm-Erklärungen + +### Farbcodierung +- **Blau (#e1f5ff)**: Entry Points & Core Components +- **Orange (#fff4e1)**: Business Logic & Hooks +- **Grün (#e8f5e9)**: API Layer & Data +- **Rosa (#fce4ec)**: External Services & Backend + +### Diagramm-Typen +1. **High-Level Architektur**: Gesamtübersicht der Anwendung +2. **Component Hierarchy**: Komponenten-Struktur und Verschachtelung +3. **Data Flow**: Datenfluss durch die Anwendung +4. **Sequence Diagrams**: Zeitliche Abläufe von Prozessen +5. **State Diagrams**: Zustandsübergänge +6. **Dependency Graphs**: Abhängigkeiten zwischen Modulen + +--- + +*Zuletzt aktualisiert: 2025-01-15* + diff --git a/ui_nyla/DEPENDENCY_MAP.md b/ui_nyla/DEPENDENCY_MAP.md new file mode 100644 index 0000000..6a5cc27 --- /dev/null +++ b/ui_nyla/DEPENDENCY_MAP.md @@ -0,0 +1,516 @@ +# Dependency Map - Frontend Nyla + +Diese Datei enthält eine detaillierte Dependency Map aller Code-Elemente im Frontend Nyla. + +## Legende + +- `→` = Import/Dependency +- `[Module]` = Modul/Namespace +- `(Hook)` = React Hook +- `(Component)` = React Component +- `(Context)` = React Context +- `(Type)` = TypeScript Type/Interface + +--- + +## 1. Application Entry & Core + +### main.tsx +``` +main.tsx + → react (StrictMode) + → react-dom/client (createRoot) + → App.tsx +``` + +### App.tsx +``` +App.tsx + → react-router-dom (BrowserRouter, Routes, Route) + → react (useEffect) + → pages/Login (Login) + → pages/Register (Register) + → auth/authProvider (AuthProvider) + → auth/ProtectedRoute (ProtectedRoute) + → contexts/LanguageContext (LanguageProvider) + → pages/Home/Home (Home) + → assets/styles/light.css + → index.css +``` + +--- + +## 2. Authentication Layer + +### auth/authProvider.tsx +``` +auth/authProvider.tsx + → @azure/msal-browser (AuthenticationResult, EventType, PublicClientApplication) + → @azure/msal-react (MsalProvider) + → auth/authConfig (msalConfig) + → react (ReactNode, useEffect, useState) +``` + +### auth/ProtectedRoute.tsx +``` +auth/ProtectedRoute.tsx + → react-router-dom (Navigate) + → hooks/useAuthentication (useAuth) + → react (ReactNode) +``` + +### hooks/useAuthentication.ts +``` +hooks/useAuthentication.ts + → @azure/msal-react (useMsal, useIsAuthenticated) + → api.ts (api) + → react (useState, useCallback, useEffect) +``` + +--- + +## 3. API Layer + +### api.ts +``` +api.ts + → axios (axios.create, AxiosInstance) + → [Environment Variables] +``` + +### hooks/useApi.ts +``` +hooks/useApi.ts + → api.ts (api) + → react (useState, useCallback) +``` + +--- + +## 4. Context Layer + +### contexts/LanguageContext.tsx +``` +contexts/LanguageContext.tsx + → react (createContext, useContext, useState, useEffect, ReactNode) + → locales/index (loadLanguage) + → locales/types (Language, TranslationKeys) +``` + +### locales/index.ts +``` +locales/index.ts + → locales/de (de) + → locales/en (en) + → locales/fr (fr) + → locales/types (Language, TranslationKeys, LanguageLoader) +``` + +--- + +## 5. Page Management System + +### components/PageManager/PageManager.tsx +``` +PageManager.tsx + → react (useEffect, useState, Suspense) + → react-router-dom (useLocation) + → framer-motion (motion, AnimatePresence) + → components/PageManager/pageConfigs (pageConfigs) + → components/PageManager/PageManager.module.css +``` + +### components/PageManager/pageConfigs.ts +``` +pageConfigs.ts + → react (lazy) + → components/PageManager/pageConfigInterface (PageConfig) + → pages/Home/Dashboard (Dashboard) [lazy] + → pages/Home/Dateien (Dateien) [lazy] + → pages/Home/TeamBereich (TeamBereich) [lazy] + → pages/Home/Connections (Connections) [lazy] + → pages/Home/Workflows (Workflows) [lazy] + → pages/Home/Einstellungen (Einstellungen) [lazy] + → pages/Home/Prompts (Prompts) [lazy] + → react-icons/* (Icons) +``` + +### components/PageManager/pageConfigInterface.ts +``` +pageConfigInterface.ts + → react (ComponentType) + → react-icons (IconType) +``` + +--- + +## 6. Sidebar System + +### components/Sidebar/Sidebar.tsx +``` +Sidebar.tsx + → react (React) + → components/Sidebar/SidebarItem (SidebarItem) + → components/Sidebar/SidebarUser (SidebarUser) + → hooks/useSidebar (useSidebarFromPageConfigs) + → components/Sidebar/sidebarLogic (useSidebarLogic) + → components/Sidebar/sidebarTypes (SidebarProps) + → components/Sidebar/SidebarStyles/Sidebar.module.css + → react-icons/go (GoSidebarExpand, GoSidebarCollapse) +``` + +### hooks/useSidebar.ts +``` +useSidebar.ts + → components/PageManager/pageConfigs (getSidebarItems) + → react (useMemo) +``` + +### components/Sidebar/sidebarLogic.ts +``` +sidebarLogic.ts + → react-router-dom (useLocation, useNavigate) + → react (useState, useCallback, useEffect) +``` + +--- + +## 7. Dashboard & Workflow System + +### pages/Home/Dashboard.tsx +``` +Dashboard.tsx + → react (useState, useCallback, useRef, useEffect) + → react-router-dom (useSearchParams) + → hooks/useWorkflows (useWorkflows) + → components/Dashboard/DashboardChat/dashboardChatAreaTypes (Workflow) + → components/Dashboard/DashboardChat/useWorkflowManager (useWorkflowManager) + → contexts/LanguageContext (useLanguage) + → components/Dashboard/DashboardChat/DashboardChat (DashboardChat) + → pages/Home/HomeStyles/Dashboard.module.css + → components/PageManager/pages.module.css + → react-icons/io (IoMdArrowDropdown, IoMdClose) +``` + +### components/Dashboard/DashboardChat/DashboardChat.tsx +``` +DashboardChat.tsx + → react (React) + → components/Dashboard/DashboardChat/DashboardChatArea (DashboardChatArea) + → components/Dashboard/DashboardChat/dashboardChatAreaTypes (DashboardChatProps) + → components/Dashboard/DashboardChatAreaStyles/DashboardChat.module.css +``` + +### components/Dashboard/DashboardChat/DashboardChatArea.tsx +``` +DashboardChatArea.tsx + → react (useState, useEffect, useRef, useCallback, useMemo) + → components/Dashboard/DashboardChat/DashboardChatAreaMessageList (DashboardChatAreaMessageList) + → components/Dashboard/DashboardChat/DashboardChatAreaInput (DashboardChatAreaInput) + → components/Dashboard/DashboardChat/DashboardChatAreaConnectedFiles (DashboardChatAreaConnectedFiles) + → components/Dashboard/DashboardChat/DashboardChatAreaFilePreview (DashboardChatAreaFilePreview) + → components/Dashboard/DashboardChat/DashboardChatAreaLogItem (DashboardChatAreaLogItem) + → components/Dashboard/DashboardChat/dashboardChatAreaTypes (Types) + → components/Dashboard/DashboardChatAreaStyles/*.module.css +``` + +### components/Dashboard/DashboardChat/useWorkflowManager.ts +``` +useWorkflowManager.ts + → react (useState, useEffect, useCallback, useRef, useMemo) + → hooks/useWorkflows (useWorkflow, useWorkflowStatus, useWorkflowMessages, useWorkflowLogs, useWorkflowOperations, StartWorkflowRequest) + → components/Dashboard/DashboardChat/dashboardChatAreaTypes (WorkflowState, WorkflowActions) +``` + +### hooks/useWorkflows.ts +``` +useWorkflows.ts + → react (useState, useEffect) + → hooks/useApi (useApiRequest) + → components/Dashboard/DashboardChat/dashboardChatAreaTypes (Workflow, WorkflowMessage, WorkflowStats, WorkflowDocument, WorkflowLog) +``` + +--- + +## 8. Connections Module + +### pages/Home/Connections.tsx +``` +Connections.tsx + → react (useState) + → components/Connections (ConnectionsTable, useConnectionsLogic) + → contexts/LanguageContext (useLanguage) + → components/PageManager/pages.module.css + → react-icons/io (IoIosLink) +``` + +### components/Connections/ConnectionsTable.tsx +``` +ConnectionsTable.tsx + → react (useState, useEffect) + → components/Connections/connectionsLogic (useConnectionsLogic) + → components/Connections/ConnectionEditModal (ConnectionEditModal) + → components/Connections/ConnectionsErrorDisplay (ConnectionsErrorDisplay) + → hooks/useConnections (useConnections) + → contexts/LanguageContext (useLanguage) + → components/Connections/ConnectionsTable.module.css +``` + +### components/Connections/connectionsLogic.tsx +``` +connectionsLogic.tsx + → react (useState, useCallback) + → hooks/useConnections (useConnections, useConnectionOperations) + → components/Connections/connectionsInterfaces (Connection Types) +``` + +### hooks/useConnections.ts +``` +useConnections.ts + → react (useState, useEffect, useCallback) + → hooks/useApi (useApiRequest) + → components/Connections/connectionsInterfaces (Connection Types) +``` + +--- + +## 9. Files Module + +### pages/Home/Dateien.tsx +``` +Dateien.tsx + → react (useRef, useState) + → components/Dateien (DateienTable) + → hooks/useFiles (useFileOperations) + → contexts/LanguageContext (useLanguage) + → components/PageManager/pages.module.css + → pages/Home/HomeStyles/Dateien.module.css + → react-icons/io (IoMdCloudUpload) +``` + +### components/Dateien/DateienTable.tsx +``` +DateienTable.tsx + → react (useState, useEffect, useCallback) + → components/Dateien/dateienLogic (useDateienLogic) + → components/FilePreview (FilePreview) + → hooks/useFiles (useFiles, useFileOperations) + → contexts/LanguageContext (useLanguage) + → components/Dateien/DateienTable.module.css +``` + +### hooks/useFiles.ts +``` +useFiles.ts + → react (useState, useEffect, useCallback) + → hooks/useApi (useApiRequest) +``` + +### components/FilePreview/FilePreview.tsx +``` +FilePreview.tsx + → react (useState, useEffect) + → components/FilePreview/renderers/* (Alle Renderer) + → components/FilePreview/FilePreview.module.css +``` + +### components/FilePreview/renderers/* +``` +renderers/ + → ApplicationRenderer.tsx + → ErrorRenderer.tsx + → HtmlRenderer.tsx + → ImageRenderer.tsx + → JsonRenderer.tsx + → LoadingRenderer.tsx + → PdfRenderer.tsx + → TextRenderer.tsx + → UnsupportedRenderer.tsx + → index.ts (Exports) +``` + +--- + +## 10. Prompts Module + +### pages/Home/Prompts.tsx +``` +Prompts.tsx + → react (useState) + → components/Prompts (PromptsTable) + → components/Popup (Popup, EditForm) + → hooks/usePrompts (usePrompts, usePromptOperations) + → contexts/LanguageContext (useLanguage) + → components/PageManager/pages.module.css + → react-icons/io (IoMdAdd) +``` + +### components/Prompts/PromptsTable.tsx +``` +PromptsTable.tsx + → react (useState, useEffect) + → components/Prompts/promptsLogic (usePromptsLogic) + → hooks/usePrompts (usePrompts, usePromptOperations) + → contexts/LanguageContext (useLanguage) + → components/Prompts/PromptsTable.module.css +``` + +### hooks/usePrompts.ts +``` +usePrompts.ts + → react (useState, useEffect, useCallback) + → hooks/useApi (useApiRequest) + → components/Prompts/promptsTypes (Prompt Types) +``` + +--- + +## 11. Workflows Module + +### pages/Home/Workflows.tsx +``` +Workflows.tsx + → components/Workflows (WorkflowsTable) + → contexts/LanguageContext (useLanguage) + → components/PageManager/pages.module.css + → pages/Home/HomeStyles/Workflows.module.css +``` + +### components/Workflows/WorkflowsTable.tsx +``` +WorkflowsTable.tsx + → react (useState, useEffect) + → components/Workflows/workflowsLogic (useWorkflowsLogic) + → hooks/useWorkflows (useWorkflows) + → contexts/LanguageContext (useLanguage) + → components/Workflows/WorkflowsTable.module.css +``` + +--- + +## 12. Popup/Modal System + +### components/Popup/Popup.tsx +``` +Popup.tsx + → react (useEffect, ReactNode) + → components/Popup/Popup.module.css +``` + +### components/Popup/EditForm.tsx +``` +EditForm.tsx + → react (useState, useEffect, useCallback) + → components/Popup/EditForm.module.css +``` + +### components/Popup/ViewForm.tsx +``` +ViewForm.tsx + → react (ReactNode) + → components/Popup/ViewForm.module.css +``` + +--- + +## 13. Form Generator + +### components/FormGenerator/FormGenerator.tsx +``` +FormGenerator.tsx + → react (useState, useEffect) + → components/FormGenerator/FormGenerator.module.css +``` + +--- + +## 14. Users & Settings + +### pages/Home/Einstellungen.tsx +``` +Einstellungen.tsx + → react (useState, useEffect, useRef) + → hooks/useUsers (useCurrentUser, useUser, User) + → contexts/LanguageContext (useLanguage, Language) + → components/settings/settingsUser (SettingsUser) + → components/PageManager/pages.module.css + → pages/Home/HomeStyles/Einstellungen.module.css +``` + +### hooks/useUsers.ts +``` +useUsers.ts + → react (useState, useEffect, useCallback) + → hooks/useApi (useApiRequest) +``` + +--- + +## 15. Team/Mitglieder Module + +### pages/Home/TeamBereich.tsx +``` +TeamBereich.tsx + → components/Mitglieder/MitgliederTable (MitgliederTable) + → components/PageManager/pages.module.css +``` + +### components/Mitglieder/MitgliederTable.tsx +``` +MitgliederTable.tsx + → react (useState, useEffect) + → components/Mitglieder/mitgliederLogic (useMitgliederLogic) + → contexts/LanguageContext (useLanguage) + → components/Mitglieder/MitgliederTable.module.css +``` + +--- + +## 16. SharePoint Test Module + +### pages/Home/TestSharepoint.tsx +``` +TestSharepoint.tsx + → react (useState) + → components/TestSharepoint (TestSharepointTable, useTestSharepointLogic) + → contexts/LanguageContext (useLanguage) + → components/PageManager/pages.module.css + → pages/Home/HomeStyles/TestSharepoint.module.css + → react-icons/io (IoIosRefresh, IoIosLink) +``` + +### hooks/useSharePointTest.ts +``` +useSharePointTest.ts + → react (useState, useEffect, useCallback) + → hooks/useApi (useApiRequest) +``` + +--- + +## Dependency Summary + +### Most Imported Modules +1. **react** - In fast allen Komponenten und Hooks +2. **react-router-dom** - Für Routing und Navigation +3. **hooks/useApi** - Für API-Aufrufe +4. **contexts/LanguageContext** - Für Internationalisierung +5. **components/PageManager/pageConfigs** - Für Seiten-Konfiguration + +### Core Infrastructure Dependencies +- `api.ts` → Alle API-Hooks +- `hooks/useApi.ts` → Alle Feature-Hooks +- `contexts/LanguageContext.tsx` → Alle Komponenten mit i18n +- `components/PageManager/pageConfigs.ts` → PageManager & Sidebar + +### External Library Dependencies +- **@azure/msal-*** → Authentication +- **axios** → HTTP Client +- **framer-motion** → Animations +- **react-icons** → Icons +- **xstate** → State Machine (optional) + +--- + +*Zuletzt aktualisiert: 2025-01-15* + diff --git a/ui_nyla/README.md b/ui_nyla/README.md new file mode 100644 index 0000000..4f93bb6 --- /dev/null +++ b/ui_nyla/README.md @@ -0,0 +1,627 @@ +# Frontend Nyla - UI Dokumentation + +## Übersicht + +Das Frontend Nyla ist eine React-basierte Single-Page-Application (SPA), die mit TypeScript entwickelt wurde. Die Anwendung verwendet Vite als Build-Tool und React Router für das Routing. Die Architektur folgt einem modularen Ansatz mit klarer Trennung von Komponenten, Hooks, Seiten und Geschäftslogik. + +--- + +## 1. Architektur + +### 1.1 Architektur-Übersicht + +Die Anwendung folgt einer **layered architecture** mit folgenden Ebenen: + +``` +┌─────────────────────────────────────────────────────────┐ +│ Presentation Layer │ +│ (Pages, Components, UI Elements) │ +├─────────────────────────────────────────────────────────┤ +│ Business Logic Layer │ +│ (Hooks, Logic Files, State Management) │ +├─────────────────────────────────────────────────────────┤ +│ Data Access Layer │ +│ (API Client, Authentication) │ +├─────────────────────────────────────────────────────────┤ +│ Infrastructure Layer │ +│ (Contexts, Providers, Configuration) │ +└─────────────────────────────────────────────────────────┘ +``` + +### 1.2 Kern-Architektur-Prinzipien + +#### 1.2.1 Component-Based Architecture +- **Komponenten** sind in Feature-Module organisiert +- Jedes Feature-Modul enthält: + - UI-Komponenten (`.tsx`) + - Styles (`.module.css`) + - Geschäftslogik (`*Logic.tsx`) + - Type-Definitionen (`*Types.ts`, `*Interfaces.ts`) + - Index-Dateien für saubere Exports + +#### 1.2.2 Custom Hooks Pattern +- Geschäftslogik wird in wiederverwendbare Hooks extrahiert +- Hooks kapseln API-Aufrufe und State-Management +- Beispiel: `useWorkflows`, `useFiles`, `useConnections` + +#### 1.2.3 Page Management System +- **PageManager** verwaltet dynamisches Laden und Caching von Seiten +- Unterstützt: + - Lazy Loading für bessere Performance + - State Preservation für bestimmte Seiten + - Lifecycle-Hooks (onActivate, onDeactivate, onLoad, onUnload) + - Animations-basierte Seitenübergänge + +#### 1.2.4 Context API für Global State +- **LanguageContext**: Internationalisierung (i18n) +- **AuthProvider**: Azure MSAL-basierte Authentifizierung + +### 1.3 Technologie-Stack + +- **Framework**: React 19.1.0 +- **Build Tool**: Vite 5.4.10 +- **Language**: TypeScript 5.8.3 +- **Routing**: React Router DOM 7.7.1 +- **State Management**: React Hooks + Context API +- **HTTP Client**: Axios 1.8.3 +- **Authentication**: Azure MSAL (@azure/msal-browser, @azure/msal-react) +- **Animations**: Framer Motion 12.7.3 +- **State Machine**: XState 5.20.1 +- **Styling**: CSS Modules +- **Icons**: React Icons 5.5.0 + +### 1.4 Authentifizierung & Sicherheit + +- **Azure MSAL Integration**: OAuth2/OIDC-basierte Authentifizierung +- **Protected Routes**: Route-Guards für geschützte Bereiche +- **Token Management**: Automatische Token-Erneuerung und -Validierung +- **API Interceptors**: Automatisches Hinzufügen von Authorization-Headern + +### 1.5 Internationalisierung (i18n) + +- Unterstützte Sprachen: Deutsch (de), Englisch (en), Französisch (fr) +- Dynamisches Laden von Übersetzungen +- Browser-Sprache-Erkennung +- Persistierung der Sprachauswahl in localStorage + +--- + +## 2. Struktur + +### 2.1 Verzeichnisstruktur + +``` +frontend_nyla/ +├── src/ +│ ├── api.ts # Zentraler API-Client (Axios) +│ ├── App.tsx # Root-Komponente mit Routing +│ ├── main.tsx # Application Entry Point +│ ├── index.css # Global Styles +│ │ +│ ├── auth/ # Authentifizierung +│ │ ├── authConfig.ts # MSAL Konfiguration +│ │ ├── authProvider.tsx # MSAL Provider Component +│ │ └── ProtectedRoute.tsx # Route Guard Component +│ │ +│ ├── components/ # Wiederverwendbare Komponenten +│ │ ├── Connections/ # Connections Feature Module +│ │ ├── Dashboard/ # Dashboard Feature Module +│ │ │ └── DashboardChat/ # Chat-Komponente mit Sub-Komponenten +│ │ ├── Dateien/ # Dateien Feature Module +│ │ ├── FilePreview/ # File Preview mit Renderers +│ │ ├── FormGenerator/ # Dynamischer Form-Generator +│ │ ├── Mitglieder/ # Mitglieder Feature Module +│ │ ├── PageManager/ # Seiten-Management System +│ │ ├── Popup/ # Modal/Popup Komponenten +│ │ ├── Prompts/ # Prompts Feature Module +│ │ ├── Sidebar/ # Sidebar Navigation +│ │ ├── TestSharepoint/ # SharePoint Test Feature +│ │ └── Workflows/ # Workflows Feature Module +│ │ +│ ├── contexts/ # React Contexts +│ │ └── LanguageContext.tsx # i18n Context +│ │ +│ ├── hooks/ # Custom React Hooks +│ │ ├── useApi.ts # Generic API Request Hook +│ │ ├── useAuthentication.ts # Auth Hooks +│ │ ├── useConnections.ts # Connections Hooks +│ │ ├── useFiles.ts # Files Hooks +│ │ ├── usePrompts.ts # Prompts Hooks +│ │ ├── useSharePointTest.ts # SharePoint Test Hooks +│ │ ├── useSidebar.ts # Sidebar Hooks +│ │ ├── useUsers.ts # Users Hooks +│ │ └── useWorkflows.ts # Workflows Hooks +│ │ +│ ├── locales/ # Übersetzungen +│ │ ├── de.ts # Deutsche Übersetzungen +│ │ ├── en.ts # Englische Übersetzungen +│ │ ├── fr.ts # Französische Übersetzungen +│ │ ├── index.ts # Locale Loader +│ │ └── types.ts # Type Definitions +│ │ +│ ├── pages/ # Seiten-Komponenten +│ │ ├── Login.tsx # Login-Seite +│ │ ├── Register.tsx # Registrierungs-Seite +│ │ └── Home/ # Haupt-Anwendungsbereich +│ │ ├── Home.tsx # Home Container +│ │ ├── Dashboard.tsx # Dashboard-Seite +│ │ ├── Dateien.tsx # Dateien-Seite +│ │ ├── Connections.tsx # Connections-Seite +│ │ ├── Workflows.tsx # Workflows-Seite +│ │ ├── Prompts.tsx # Prompts-Seite +│ │ ├── TeamBereich.tsx # Team-Bereich-Seite +│ │ ├── Einstellungen.tsx # Einstellungen-Seite +│ │ ├── TestSharepoint.tsx # SharePoint Test-Seite +│ │ └── HomeStyles/ # Seiten-spezifische Styles +│ │ +│ └── assets/ # Statische Assets +│ └── styles/ +│ ├── light.css # Light Theme CSS Variables +│ └── dark.css # Dark Theme CSS Variables +│ +├── public/ # Öffentliche Assets +├── documentation/ # Dokumentation +├── .env.dev # Development Environment Variables +├── .env.int # Integration Environment Variables +├── .env.prod # Production Environment Variables +├── vite.config.ts # Vite Konfiguration +├── tsconfig.json # TypeScript Konfiguration +└── package.json # Dependencies & Scripts +``` + +### 2.2 Feature-Module Struktur + +Jedes Feature-Modul folgt einem konsistenten Muster: + +``` +FeatureModule/ +├── ComponentName.tsx # Haupt-Komponente +├── ComponentName.module.css # Komponenten-Styles +├── featureLogic.tsx # Geschäftslogik +├── featureTypes.ts # TypeScript Types +├── featureInterfaces.ts # TypeScript Interfaces (optional) +└── index.ts # Public API Export +``` + +**Beispiel: Connections Module** +``` +Connections/ +├── ConnectionsTable.tsx # Haupt-Tabellen-Komponente +├── ConnectionsTable.module.css # Tabellen-Styles +├── ConnectionEditModal.tsx # Edit-Modal Komponente +├── ConnectionEditModal.module.css # Modal-Styles +├── ConnectionsErrorDisplay.tsx # Error-Display Komponente +├── ConnectionsErrorDisplay.module.css +├── connectionsLogic.tsx # Geschäftslogik +├── connectionsInterfaces.ts # Type Definitions +└── index.ts # Exports +``` + +### 2.3 Seiten-Struktur + +Seiten sind in `pages/Home/` organisiert und verwenden: +- **Shared Styles**: `pages.module.css` für gemeinsame Seiten-Styles +- **Feature Components**: Importieren entsprechende Komponenten aus `components/` +- **Hooks**: Nutzen Custom Hooks für Daten-Fetching und State-Management +- **Language Context**: Nutzen `useLanguage()` für i18n + +### 2.4 Naming Conventions + +- **Komponenten**: PascalCase (z.B. `DashboardChat.tsx`) +- **Hooks**: camelCase mit "use" Prefix (z.B. `useWorkflows.ts`) +- **Logic Files**: camelCase mit "Logic" Suffix (z.B. `connectionsLogic.tsx`) +- **Types/Interfaces**: camelCase mit "Types"/"Interfaces" Suffix +- **CSS Modules**: `.module.css` Suffix +- **Internal Functions**: Prefix mit `_` (z.B. `_internalFunction()`) + +--- + +## 3. Dependency Map + +### 3.1 Dependency Graph - High Level + +``` +main.tsx + └── App.tsx + ├── LanguageProvider (contexts/LanguageContext.tsx) + ├── AuthProvider (auth/authProvider.tsx) + └── Router (react-router-dom) + ├── Login (pages/Login.tsx) + ├── Register (pages/Register.tsx) + └── Home (pages/Home/Home.tsx) + ├── Sidebar (components/Sidebar/) + └── PageManager (components/PageManager/) + └── [Lazy Loaded Pages] +``` + +### 3.2 Core Dependencies + +#### 3.2.1 Application Entry Point + +**main.tsx** +- Abhängigkeiten: `react`, `react-dom`, `App.tsx` +- Verantwortlichkeit: React Root erstellen und App rendern + +**App.tsx** +- Abhängigkeiten: + - `react-router-dom` (Router, Routes, Route) + - `contexts/LanguageContext` (LanguageProvider) + - `auth/authProvider` (AuthProvider) + - `auth/ProtectedRoute` (ProtectedRoute) + - `pages/Login` (Login) + - `pages/Register` (Register) + - `pages/Home/Home` (Home) +- Verantwortlichkeit: Routing-Setup, Provider-Wrapper, Theme-Management + +#### 3.2.2 Authentication Layer + +**auth/authProvider.tsx** +- Abhängigkeiten: + - `@azure/msal-browser` (PublicClientApplication, AuthenticationResult) + - `@azure/msal-react` (MsalProvider) + - `auth/authConfig` (msalConfig) +- Verantwortlichkeit: MSAL Initialisierung, Account Management + +**auth/ProtectedRoute.tsx** +- Abhängigkeiten: + - `react-router-dom` (Navigate) + - `hooks/useAuthentication` (useAuth) +- Verantwortlichkeit: Route Protection, Redirect bei fehlender Authentifizierung + +#### 3.2.3 API Layer + +**api.ts** +- Abhängigkeiten: `axios` +- Verantwortlichkeit: + - Axios Instance mit Base URL + - Request Interceptor (Token Injection) + - Response Interceptor (401 Handling, Redirect) + +**hooks/useApi.ts** +- Abhängigkeiten: `api.ts` +- Verantwortlichkeit: Generic API Request Hook mit Error Handling + +### 3.3 Component Dependencies + +#### 3.3.1 PageManager System + +**components/PageManager/PageManager.tsx** +- Abhängigkeiten: + - `react-router-dom` (useLocation) + - `framer-motion` (motion, AnimatePresence) + - `components/PageManager/pageConfigs` (pageConfigs) +- Verantwortlichkeit: + - Dynamisches Laden von Seiten + - State Preservation + - Page Lifecycle Management + - Animations + +**components/PageManager/pageConfigs.ts** +- Abhängigkeiten: + - `react` (lazy) + - `components/PageManager/pageConfigInterface` (PageConfig) + - Alle Page-Komponenten (lazy loaded) +- Verantwortlichkeit: Seiten-Konfiguration, Sidebar-Metadaten + +#### 3.3.2 Sidebar System + +**components/Sidebar/Sidebar.tsx** +- Abhängigkeiten: + - `components/Sidebar/SidebarItem` (SidebarItem) + - `components/Sidebar/SidebarUser` (SidebarUser) + - `hooks/useSidebar` (useSidebarFromPageConfigs) + - `components/Sidebar/sidebarLogic` (useSidebarLogic) +- Verantwortlichkeit: Sidebar Container, Navigation Rendering + +**hooks/useSidebar.ts** +- Abhängigkeiten: + - `components/PageManager/pageConfigs` (getSidebarItems) +- Verantwortlichkeit: Sidebar-Daten aus Page-Configs extrahieren + +#### 3.3.3 Dashboard & Workflow System + +**pages/Home/Dashboard.tsx** +- Abhängigkeiten: + - `components/Dashboard/DashboardChat` (DashboardChat) + - `hooks/useWorkflows` (useWorkflows) + - `components/Dashboard/DashboardChat/useWorkflowManager` (useWorkflowManager) + - `contexts/LanguageContext` (useLanguage) +- Verantwortlichkeit: Dashboard-Seite, Workflow-Management + +**components/Dashboard/DashboardChat/DashboardChat.tsx** +- Abhängigkeiten: + - `components/Dashboard/DashboardChat/DashboardChatArea` (DashboardChatArea) +- Verantwortlichkeit: Chat Container + +**components/Dashboard/DashboardChat/useWorkflowManager.ts** +- Abhängigkeiten: + - `hooks/useWorkflows` (useWorkflow, useWorkflowStatus, useWorkflowMessages, useWorkflowLogs, useWorkflowOperations) + - `components/Dashboard/DashboardChat/dashboardChatAreaTypes` (WorkflowState, WorkflowActions) +- Verantwortlichkeit: Workflow State Management, Polling Logic, Optimistic Updates + +**hooks/useWorkflows.ts** +- Abhängigkeiten: + - `hooks/useApi` (useApiRequest) + - `components/Dashboard/DashboardChat/dashboardChatAreaTypes` (Workflow Types) +- Verantwortlichkeit: Workflow API Calls, Data Fetching + +### 3.4 Feature Module Dependencies + +#### 3.4.1 Connections Module + +**components/Connections/ConnectionsTable.tsx** +- Abhängigkeiten: + - `components/Connections/connectionsLogic` (useConnectionsLogic) + - `components/Connections/ConnectionEditModal` (ConnectionEditModal) + - `components/Connections/ConnectionsErrorDisplay` (ConnectionsErrorDisplay) + - `hooks/useConnections` (useConnections) + - `contexts/LanguageContext` (useLanguage) + +**hooks/useConnections.ts** +- Abhängigkeiten: + - `hooks/useApi` (useApiRequest) + - `components/Connections/connectionsInterfaces` (Connection Types) + +#### 3.4.2 Files Module + +**components/Dateien/DateienTable.tsx** +- Abhängigkeiten: + - `components/Dateien/dateienLogic` (useDateienLogic) + - `components/FilePreview` (FilePreview) + - `hooks/useFiles` (useFiles, useFileOperations) + - `contexts/LanguageContext` (useLanguage) + +**hooks/useFiles.ts** +- Abhängigkeiten: + - `hooks/useApi` (useApiRequest) + +**components/FilePreview/FilePreview.tsx** +- Abhängigkeiten: + - `components/FilePreview/renderers/*` (Verschiedene Renderer) +- Verantwortlichkeit: File-Type Detection, Renderer Selection + +#### 3.4.3 Prompts Module + +**components/Prompts/PromptsTable.tsx** +- Abhängigkeiten: + - `components/Prompts/promptsLogic` (usePromptsLogic) + - `components/Popup` (Popup, EditForm) + - `hooks/usePrompts` (usePrompts, usePromptOperations) + - `contexts/LanguageContext` (useLanguage) + +**hooks/usePrompts.ts** +- Abhängigkeiten: + - `hooks/useApi` (useApiRequest) + +### 3.5 Context Dependencies + +**contexts/LanguageContext.tsx** +- Abhängigkeiten: + - `locales/index` (loadLanguage) + - `locales/types` (Language, TranslationKeys) +- Verantwortlichkeit: i18n State Management, Translation Loading + +**locales/index.ts** +- Abhängigkeiten: + - `locales/de` (deutsche Übersetzungen) + - `locales/en` (englische Übersetzungen) + - `locales/fr` (französische Übersetzungen) +- Verantwortlichkeit: Dynamisches Laden von Übersetzungen + +### 3.6 Dependency Flow Diagram + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Pages Layer │ +│ (Dashboard, Dateien, Connections, Workflows, etc.) │ +└────────────┬───────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Components Layer │ +│ (Feature Components, UI Components) │ +└────────────┬───────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Hooks Layer │ +│ (useWorkflows, useFiles, useConnections, etc.) │ +└────────────┬───────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ API Layer │ +│ (useApi.ts → api.ts → Backend) │ +└─────────────────────────────────────────────────────────────┘ + +┌─────────────────────────────────────────────────────────────┐ +│ Infrastructure Layer │ +│ (Contexts, Providers, Configuration) │ +│ │ +│ LanguageContext ──→ locales/ │ +│ AuthProvider ──→ @azure/msal-* │ +│ PageManager ──→ pageConfigs ──→ Lazy Pages │ +└─────────────────────────────────────────────────────────────┘ +``` + +### 3.7 External Dependencies + +#### React Ecosystem +- `react`, `react-dom`: Core React Library +- `react-router-dom`: Client-side Routing +- `@azure/msal-browser`, `@azure/msal-react`: Azure Authentication + +#### UI & Styling +- `framer-motion`: Animations +- `react-icons`: Icon Library +- CSS Modules: Scoped Styling + +#### State Management +- `xstate`, `@xstate/react`: State Machine (für komplexe Workflows) + +#### HTTP & Data +- `axios`: HTTP Client +- `jwt-decode`: JWT Token Decoding + +#### Utilities +- `js-cookie`: Cookie Management +- `react-dropzone`: File Upload + +### 3.8 Critical Dependency Paths + +#### Authentication Flow +``` +App.tsx + └── AuthProvider + └── ProtectedRoute + └── Home + └── [All Protected Pages] +``` + +#### Data Fetching Flow +``` +Page Component + └── Feature Component + └── Custom Hook (useWorkflows, useFiles, etc.) + └── useApiRequest + └── api.ts (Axios) + └── Backend API +``` + +#### Page Loading Flow +``` +App.tsx + └── Router + └── Home + └── PageManager + └── pageConfigs + └── Lazy Component + └── Page Component +``` + +#### Internationalization Flow +``` +App.tsx + └── LanguageProvider + └── [All Components] + └── useLanguage() + └── locales/[lang].ts +``` + +--- + +## 4. Wichtige Architektur-Entscheidungen + +### 4.1 Lazy Loading +- Seiten werden lazy geladen für bessere Initial Load Performance +- Implementiert via `React.lazy()` in `pageConfigs.ts` + +### 4.2 State Preservation +- Dashboard-Seite behält State bei Navigation +- Implementiert via `preserveState` Flag in PageConfig +- PageManager verwaltet preserved Instances separat + +### 4.3 CSS Modules +- Scoped Styling für bessere Isolation +- Konfiguriert in `vite.config.ts` + +### 4.4 Error Handling +- Zentralisiertes Error Handling in `useApi.ts` +- Formatierung von Backend-Errors für konsistente UX + +### 4.5 Theme Management +- CSS Variables für Light/Dark Theme +- Persistierung in localStorage +- Automatische Browser-Präferenz-Erkennung + +--- + +## 5. Entwicklung & Build + +### 5.1 Development Scripts +- `npm run dev`: Development Server (Port 5176, Mode: dev) +- `npm run dev:prod`: Development mit Production Environment +- `npm run dev:int`: Development mit Integration Environment + +### 5.2 Build Scripts +- `npm run build`: Standard Build +- `npm run build:prod`: Production Build +- `npm run build:int`: Integration Build + +### 5.3 Environment Variables +- Präfix: `VITE_` +- Konfiguriert in `.env.dev`, `.env.int`, `.env.prod` +- Zugriff via `import.meta.env.VITE_*` + +--- + +## 6. Best Practices & Patterns + +### 6.1 Component Organization +- Feature-basierte Organisation +- Separation of Concerns (UI, Logic, Types) +- Index-Dateien für saubere Exports + +### 6.2 Hook Patterns +- Custom Hooks für wiederverwendbare Logik +- API-Hooks nutzen `useApiRequest` für Konsistenz +- State Management in Hooks, nicht in Components + +### 6.3 Type Safety +- TypeScript für alle Dateien +- Zentrale Type-Definitionen in Feature-Modulen +- Interfaces für API-Responses + +### 6.4 Code Style +- camelCase für Variablen und Funktionen +- PascalCase für Komponenten +- `_` Prefix für interne Funktionen +- Keine snake_case + +--- + +## 7. Erweiterungen & Wartung + +### 7.1 Neue Seite hinzufügen +1. Page-Komponente in `pages/Home/` erstellen +2. Lazy Import in `pageConfigs.ts` hinzufügen +3. PageConfig mit Metadaten erstellen +4. Bei Bedarf Feature-Komponenten erstellen + +### 7.2 Neues Feature-Modul hinzufügen +1. Verzeichnis in `components/` erstellen +2. Komponenten, Logic, Types, Styles hinzufügen +3. Index-Datei für Exports erstellen +4. Custom Hook in `hooks/` erstellen (falls API-Calls benötigt) + +### 7.3 Neue API-Endpoints integrieren +1. Hook in `hooks/` erstellen oder erweitern +2. `useApiRequest` nutzen für API-Calls +3. Types für Request/Response definieren +4. Error Handling implementieren + +--- + +## 8. Anhang + +### 8.1 Abkürzungen +- **SPA**: Single-Page Application +- **MSAL**: Microsoft Authentication Library +- **i18n**: Internationalization +- **API**: Application Programming Interface +- **CSS**: Cascading Style Sheets +- **TSX**: TypeScript XML (React Components) + +### 8.2 Wichtige Dateien Referenz +- `main.tsx`: Application Entry Point +- `App.tsx`: Root Component & Routing +- `api.ts`: API Client Configuration +- `components/PageManager/pageConfigs.ts`: Seiten-Konfiguration +- `contexts/LanguageContext.tsx`: i18n Context +- `auth/authProvider.tsx`: Authentication Provider + +--- + +*Dokumentation erstellt: 2025-01-15* +*Version: 1.0* +