# Client Dashboard - Copilot Instructions

## Projektübersicht

### Was ist das Client Dashboard?

**Client Dashboard** ist eine Full-Stack-Webanwendung für **Clients der Domains `knowledgeagent.com` und `knowledgeagent.de`**, um sich sicher anmelden und auf ihr persönliches Dashboard zuzugreifen. Die Anwendung konzentriert sich auf **Sicherheit** (WebAuthn/Passkeys), **Benutzererlebnis** (PWA, Offline-Support) und **flexible Authentifizierung** (OTP, Passwort, Passkeys).

### Wie funktioniert die Anwendung?

1. **Benutzer-Login** (2-stufig):
   - Benutzer gibt E-Mail ein → Backend prüft Domain
   - Je nach Domain wird Standard-Authentifizierungsmethode vorgeschlagen:
     - `knowledgeagent.com` → OTP (One-Time-Password)
     - `knowledgeagent.de` → Password (klassisches Passwort)
   - Benutzer wählt Authentifizierungsmethode (OTP/Password/Passkey)
   - Nach erfolgreicher Authentifizierung erhält Benutzer JWT-Token

2. **Dashboard-Access**:
   - Nach erfolgreicher Anmeldung zeigt Frontend das personalisierte Dashboard
   - Frontend speichert Session lokal (via Pinia Persistence)
   - PWA ermöglicht Offline-Zugriff auf gecachte Daten

3. **Architektur-Übersicht**:
   ```
   User Browser
   ├── Frontend (Vue 3 + Quasar)
   │   ├── Login Form
   │   ├── Dashboard UI
   │   └── Service Worker (PWA)
   │
   └→ HTTPS API (Symfony Backend)
       ├── Authentication API (/login, /login/verify)
       ├── User API (/user/profile, /user/data)
       └── Dashboard API (/dashboard/...)
       
   ↓ Database (MySQL/MariaDB)
   └── Users, LoginAttempts, Sessions, etc.
   ```

### Tech Stack

**Client Dashboard** ist eine Full-Stack-Anwendung bestehend aus:
- **Backend**: Symfony 7.4 mit PHP 8.2+, REST API mit JSON
- **Frontend**: Vue 3 + Quasar + Pinia, als PWA deployed
- **Database**: Doctrine ORM mit Migrations (MySQL/MariaDB)
- **Authentication**: WebAuthn (Passkeys) + 2-Step Login (OTP/Password), JWT Tokens
- **Infrastructure**: XAMPP mit Apache (SSL), localhost auf `client-dashboard.local`

---

## Backend (Symfony 7.4 + PHP 8.2)

### Projektstruktur
```
backend/
├── src/
│   ├── Kernel.php                  # Symfony Kernel
│   ├── Api/                        # API Controller & Response Handling
│   ├── Controller/                 # HTTP Controller
│   ├── Entity/                     # Doctrine Entities
│   ├── Enum/                       # PHP Enums
│   ├── EventSubscriber/            # Symfony Event Subscriber
│   ├── Logging/                    # Logging Services
│   ├── Repository/                 # Doctrine Repository
│   ├── Security/                   # Security & Authentication
│   └── Service/                    # Business Logic Services
├── config/
│   ├── packages/                   # Feature-spezifische Config
│   ├── routes/                     # API Route Config
│   ├── services.yaml               # Service Container Config
│   └── bundles.php                 # Bundle Registration
├── migrations/                     # Doctrine Migrations (versioniert)
├── templates/                      # Twig Templates (Email, etc.)
├── public/
│   └── index.php                   # Symfony Entry Point
├── tests/                          # Unit/Integration Tests
└── vendor/                         # Dependencies (Composer)
```

### Key Dependencies
- **Doctrine ORM** & **Migrations Bundle**: Database persistence & versioning
- **Symfony Security Bundle**: Authentication & Authorization
- **WebAuthn Symfony Bundle**: Passkey/FIDO2 support
- **Nelmio CORS Bundle**: Cross-Origin Resource Sharing
- **Monolog Bundle**: Structured Logging
- **Symfony Mailer**: Email Service
- **Symfony Mercure**: Real-time messaging

### Conventions & Patterns

#### Entities & Database
- **Locations**: `src/Entity/` Doctrine Entities
- **Naming**: PascalCase (z.B. `User`, `LoginAttempt`)
- **Repositories**: `src/Repository/` mit entsprechender Entity
- **Migrations**: Werden automatisch generiert, versioniert im `migrations/` Ordner
- **Timestamps**: Alle Entities sollten `createdAt` und `updatedAt` Felder haben

#### API Controller & Routes
- **Locations**: `src/Api/` für REST Endpoints
- **Naming**: Controller mit suffix `Controller` (z.B. `LoginController`)
- **Routes**: In `config/routes/` definiert, nicht als Annotations
- **Response Format**: JSON mit standardisiertem Response-Format
- **HTTP Methods**: RESTful GET, POST, PUT, DELETE, PATCH
- **Status Codes**: 
  - 200 Success
  - 201 Created
  - 400 Bad Request
  - 401 Unauthorized
  - 403 Forbidden
  - 404 Not Found
  - 500 Internal Server Error

#### Services & Business Logic
- **Locations**: `src/Service/` für Business Logic
- **Naming**: Suffix `Service` (z.B. `LoginService`, `UserService`)
- **Dependency Injection**: Via constructor injection, auto-wiring enabled
- **Interfaces**: Service-Interfaces in `src/Service/Interface/`

#### Security & Authentication
- **Locations**: `src/Security/` für Auth-Guards, Voter, UserProvider
- **Current Flow**: 2-Step Login mit OTP/Password, optional WebAuthn
- **Domains**: Nur `knowledgeagent.com` und `knowledgeagent.de` erlaubt
- **Default Methods**: 
  - `knowledgeagent.com` → OTP
  - `knowledgeagent.de` → Password

#### Logging
- **Locations**: `src/Logging/` für Custom Log Handler/Formatter
- **Config**: `config/packages/monolog.yaml`
- **Levels**: DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL

### Common Tasks

#### Entity erstellen
```bash
cd backend
php bin/console make:entity YourEntity
php bin/console make:migration
php bin/console doctrine:migrations:migrate
```

#### Controller erstellen
```bash
cd backend
php bin/console make:controller Api/YourController
```

#### Service testen
- Unit Tests in `tests/` mirrors `src/` structure
- Run: `php bin/console test` oder `php bin/phpunit`

---

## Frontend (Vue 3 + Quasar + Pinia)

### Projektstruktur
```
frontend/
├── src/
│   ├── App.vue                     # Root Component
│   ├── assets/                     # Static Assets (Bilder, Fonts)
│   ├── boot/                       # Quasar Boot Files (App Init)
│   ├── components/                 # Reusable Vue Components
│   ├── composables/                # Vue Composables (Logik-Sharing)
│   ├── config/                     # App Configuration
│   ├── css/                        # Global & Component Styles
│   ├── i18n/                       # Vue i18n Internationalization
│   ├── layouts/                    # Layout Components
│   ├── pages/                      # Page/Route Components
│   ├── router/                     # Vue Router Configuration
│   ├── services/                   # API Services & Helpers
│   ├── stores/                     # Pinia State Management
│   └── utils/                      # Utility Functions
├── src-pwa/                        # PWA Config (Service Worker, etc)
├── public/
│   └── icons/                      # App Icons
├── index.html                      # HTML Entry Point
├── quasar.config.js                # Quasar Build Config
├── eslint.config.js                # ESLint Rules
├── postcss.config.js               # PostCSS Config
├── jsconfig.json                   # JS Path Aliases
└── package.json                    # Dependencies
```

### Key Dependencies
- **Vue 3**: Progressive framework
- **Quasar**: Full-stack Vue UI framework
- **Pinia**: State management (successor to Vuex)
- **Vue Router**: Routing
- **Vue i18n**: Internationalization
- **Axios**: HTTP Client
- **SimpleWebAuthn**: WebAuthn/Passkey library
- **Workbox**: PWA Service Worker

### Conventions & Patterns

#### Components
- **Locations**: `src/components/` für reusable Komponenten
- **Naming**: PascalCase (z.B. `UserCard.vue`, `LoginForm.vue`)
- **Scoping**: Styles sind scoped (keine global conflicts)
- **Props**: Documented mit JSDoc/TypeScript hints
- **Emits**: Documented für custom events

#### Pages & Routing
- **Locations**: `src/pages/` für Route-Components
- **Routing**: `src/router/` enthält Route-Definitionen
- **Layout**: Pages nutzen Layouts aus `src/layouts/`
- **Naming**: File-Namen entsprechen Route-Namen

#### State Management (Pinia)
- **Stores**: `src/stores/` mit einem Store pro Feature
- **Naming**: `useXxxStore()` convention (z.B. `useUserStore()`)
- **State**: Nur reaktive Daten
- **Getters**: Computed properties
- **Actions**: Async operations, API calls
- **Persistence**: `pinia-plugin-persistedstate` für lokale Speicherung

#### Services & API
- **Locations**: `src/services/` für API-Services und Logik
- **Naming**: `xxxService.js` (z.B. `loginService.js`, `userService.js`)
- **API Client**: Axios instance mit base URL und Interceptors
- **Error Handling**: Try-Catch oder Promise rejection handling
- **Authentication**: Token management in Store, automatisch in API calls

#### Composables
- **Locations**: `src/composables/` für wiederverwendbare Logik
- **Naming**: `useXxx()` convention (z.B. `useAuth()`, `useForm()`)
- **Usage**: Import und direkter Aufruf in Components
- **Return**: Reaktive Refs/Computed, Functions

#### Styling
- **Framework**: Quasar CSS + Tailwind (if configured)
- **Locations**: Global in `src/css/`, scoped in Components
- **Variables**: CSS Custom Properties für Theme-Farben
- **Responsive**: Quasar breakpoints (xs, sm, md, lg, xl)

#### i18n & Internationalization
- **Locations**: `src/i18n/` mit Message Files
- **Usage**: `$t('key')` in Templates, `useI18n()` in Scripts
- **Namespacing**: Organized by feature (z.B. `login.de.json`)

### Common Tasks

#### Komponente erstellen
1. Datei in `src/components/MyComponent.vue` erstellen
2. Template, Script, Scoped Style schreiben
3. Props und Emits dokumentieren
4. In Parent-Component importieren und verwenden

#### Store erstellen
```javascript
// src/stores/useMyStore.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useMyStore = defineStore('my', () => {
  const data = ref([]);
  
  const getter = computed(() => data.value.length);
  
  const action = async () => { /* ... */ };
  
  return { data, getter, action };
});
```

#### API Service erstellen
```javascript
// src/services/myService.js
import axios from 'axios';

const client = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
});

export const myService = {
  async fetchData() {
    const response = await client.get('/endpoint');
    return response.data;
  },
};
```

#### Page mit Routing erstellen
1. Komponente in `src/pages/MyPage.vue` erstellen
2. Route in `src/router/routes.js` hinzufügen
3. Optional: Layout zuweisen

---

## API Conventions

### Base URL
- **Development**: `https://client-dashboard.local/api`
- **Staging/Prod**: wird in `.env` konfiguriert

### Request Format
```javascript
{
  "email": "user@example.com",
  "method": "otp" // or "password"
}
```

### Response Format
```javascript
{
  "success": true,
  "message": "Human-readable message",
  "data": { /* optional payload */ },
  "errors": [ /* optional error array */ ]
}
```

### Error Handling
- **400 Bad Request**: Invalid input, missing fields
- **401 Unauthorized**: Invalid token/session
- **403 Forbidden**: Domain not allowed, Permission denied
- **404 Not Found**: Resource doesn't exist
- **500 Server Error**: Unexpected error

### Authentication Flow
1. **Step 1**: `POST /login` mit Email
   - Response: `nextStep` (otp/password), `availableMethods` (array)
2. **Step 2**: `POST /login/verify` mit OTP oder Password
   - Response: `token`, `user` info
3. **Usage**: Token in `Authorization: Bearer {token}` Header

---

## Development Guidelines

### Code Style
- **Backend**: PSR-12 PHP Coding Standard
- **Frontend**: ESLint Rules (enforced via `npm run lint`)
- **Formatting**: 
  - Backend: PHP-CS-Fixer
  - Frontend: Prettier (`npm run format`)

### Version Control
- **Main Branch**: Production-ready code
- **Dev Branch**: Development/Staging
- **Feature Branches**: `feature/feature-name`
- **Bug Fixes**: `fix/bug-name`
- **Commit Messages**: Descriptive, English language

### Documentation
- **README.md**: Top-level project documentation
- **LOGIN_API_GUIDE.md**: Login API specification
- **Code Comments**: Für komplexe Logik, nicht offensichtlichen Code

### Debugging
- **Backend Logs**: `var/log/` (configured in `monolog.yaml`)
- **Frontend DevTools**: Browser DevTools, Vue DevTools Extension
- **Database**: Doctrine CLI (`php bin/console doctrine:...`)

### Testing
- **Backend**: PHPUnit (in `tests/` directory)
- **Frontend**: Vitest (if configured)
- **Before Commit**: Lint, Format, Test

---

## Common Workflows

### Adding a New Feature
1. **Backend**:
   - Erstelle Entity in `src/Entity/`
   - Erstelle Migration: `php bin/console make:migration`
   - Führe Migration aus: `php bin/console doctrine:migrations:migrate`
   - Erstelle Service in `src/Service/`
   - Erstelle Controller/Route in `src/Api/` und `config/routes/`

2. **Frontend**:
   - Erstelle Store wenn State benötigt: `src/stores/`
   - Erstelle Service für API Calls: `src/services/`
   - Erstelle Components: `src/components/`
   - Erstelle Page wenn neue Route: `src/pages/`
   - Füge Route hinzu: `src/router/`

3. **Testing**:
   - Backend: Unit Test in `tests/`
   - Frontend: Component Test (if configured)

### Debugging Login Issues
1. Check Email domain (nur `knowledgeagent.com` / `knowledgeagent.de`)
2. Check method availability in `availableMethods` response
3. Verify OTP generation and delivery
4. Check token expiration in backend logs
5. Verify CORS configuration in `config/packages/nelmio_cors.yaml`

### Deployment
1. **Backend**:
   - `composer install --no-dev`
   - `php bin/console doctrine:migrations:migrate`
   - Clear cache: `php bin/console cache:clear`

2. **Frontend**:
   - `pnpm install` (oder `npm install`)
   - `npm run build` (oder `npm run build:pwa`)
   - Deploy `dist/` folder

---

## Useful Commands

### Backend
```bash
# Start Dev Server
cd backend && php -S localhost:8000 -t public

# Database
php bin/console doctrine:database:create
php bin/console doctrine:migrations:migrate
php bin/console doctrine:fixtures:load

# Cache
php bin/console cache:clear
php bin/console cache:warmup

# Code Quality
php bin/console lint:php
php bin/console lint:yaml
```

### Frontend
```bash
# Development
npm run dev

# Build
npm run build
npm run build:pwa

# Code Quality
npm run lint
npm run format
```

---

## File Structure Best Practices

### Adding New Files
- Follow existing naming conventions
- Place files in appropriate directories
- Update imports in parent components
- Document if affecting other parts

### Removing Files
- Check for usages: `grep -r "FileName"`
- Update imports in referencing files
- Commit with clear message

### Refactoring
- Test before and after changes
- Run linting and formatting
- Update documentation if needed
- Keep commits atomic and descriptive
