# V2-Docker System Documentation

## Overview

V2-Docker is a comprehensive system featuring a License Server, Admin Panel, Lead Management, and Monitoring Stack. This document consolidates all architecture and implementation details.

## License Server Architecture

### Core Principles
- Designed to avoid refactoring
- Microservices architecture
- Hardware-based license binding
- Offline grace period support (7 days)
- Version control with update enforcement

### Core Functionalities

#### 1. License Validation
- Real-time license verification
- Hardware binding (MAC address, CPU ID, system UUID)
- Version compatibility checks
- Usage limit enforcement

#### 2. Activation Management
- Initial activation with hardware fingerprint
- Multi-activation support
- Deactivation capabilities
- Transfer between systems

#### 3. Usage Monitoring
- Active user tracking
- Feature usage statistics
- Heartbeat monitoring (15-minute intervals)
- Historical data analysis

### Microservices Architecture

#### Aktive Services
1. **License Server** (`v2_lizenzserver`) - Core license validation
   - Vollständig implementiert
   - API-Endpunkte für Aktivierung, Verifizierung, Info
   - Läuft auf internem Port über Nginx

2. **Admin Panel** (`v2_adminpanel`) - Web-basierte Verwaltung
   - Vollständig implementiert auf Port 80
   - Customer, License, Resource Management
   - Integrierte Backup-Funktionalität
   - Lead Management System

#### Geplante Services (Code vorhanden, nicht aktiv)
1. **Analytics Service** - Usage statistics and reporting
   - Code in `/v2_lizenzserver/services/analytics/`
   - Auskommentiert in docker-compose.yaml
   
2. **Admin API Service** - Dedizierte Admin API
   - Code in `/v2_lizenzserver/services/admin/`
   - Auskommentiert in docker-compose.yaml

3. **Auth Service** - Zentralisierte Authentifizierung
   - Code in `/lizenzserver/services/auth/`
   - Auskommentiert in docker-compose.yaml

#### Konzeptionelle Services (nur in Planung)
1. **Notification Service** - Email/webhook notifications
2. **Dedicated Backup Service** - Automated backups (derzeit im Admin Panel integriert)

#### Infrastructure Services (aktiv)
- **PostgreSQL** - Hauptdatenbank
- **Redis** - Caching
- **RabbitMQ** - Message Queue
- **Nginx** - Reverse Proxy

#### Communication
- REST APIs für externe Kommunikation
- Redis für Caching
- RabbitMQ für asynchrone Verarbeitung (vorbereitet)

### Database Schema

#### Core Tables
- `licenses` - License definitions
- `license_activations` - Active installations
- `license_heartbeats` - Usage tracking (partitioned monthly)
- `license_usage_stats` - Aggregated statistics
- `license_features` - Feature flags
- `license_limits` - Usage limits

#### Partitioning Strategy
- Monthly partitions for `license_heartbeats`
- Automatic partition creation
- 90-day retention policy

### Security Concepts
- JWT-based authentication
- API key management
- Rate limiting (100 requests/minute)
- Hardware fingerprint validation
- Encrypted communication

### Implementation Status (June 19, 2025)

#### Completed
- ✅ License Server mit API-Endpunkten
  - POST /api/license/activate
  - POST /api/license/verify  
  - GET /api/license/info/{license_key}
  - POST /api/version/check
  - GET /api/version/latest
- ✅ Admin Panel mit voller Funktionalität
  - Customer Management
  - License Management
  - Resource Management
  - Session Management
  - Lead Management
  - Batch Operations
  - Export/Import
- ✅ Monitoring Stack (Prometheus, Grafana, Alertmanager)
- ✅ Docker Services Konfiguration
- ✅ JWT/API Key Management
- ✅ Backup-System (integriert im Admin Panel)
- ✅ 2FA-Authentifizierung
- ✅ Audit Logging
- ✅ Rate Limiting

#### Code vorhanden aber nicht aktiviert
- ⏸️ Analytics Service (auskommentiert)
- ⏸️ Admin API Service (auskommentiert)  
- ⏸️ Auth Service (auskommentiert)

#### Geplant
- 📋 Notification Service
- 📋 Erweiterte Analytics
- 📋 Machine Learning Integration

## Lead Management System

### Status
**Vollständig implementiert** als Teil des Admin Panels unter `/leads/`

### Architecture
- **Modular Architecture**: Clean separation of concerns
- **Service Layer Pattern**: Business logic in `leads/services.py`
- **Repository Pattern**: Data access in `leads/repositories.py`
- **Blueprint Integration**: Routes in `leads/routes.py`

### Data Model (implementiert)
```
lead_institutions
├── lead_contact_persons (1:n)
├── lead_notes (1:n)
├── lead_tags (n:m)
└── lead_activities (1:n)
```

### Implementierte Features
1. ✅ Institution Management (CRUD)
2. ✅ Contact Person Management
3. ✅ Notes mit Versionierung
4. ✅ Tag-System
5. ✅ Activity Tracking
6. ✅ Export/Import Funktionalität
7. ✅ Erweiterte Suche und Filter
8. ✅ Statistik-Dashboard

### API Endpoints
- GET /leads/ - Übersicht
- GET/POST /leads/create - Neue Institution
- GET/POST /leads/edit/{id} - Bearbeiten
- POST /leads/delete/{id} - Löschen
- GET /leads/export - Export
- POST /leads/import - Import
- GET /leads/api/stats - Statistiken

## Monitoring Stack

### Components
- **Prometheus**: Metrics collection
- **Grafana**: Visualization (port 3001)
- **Alertmanager**: Alert management (port 9093)
- **Node Exporter**: System metrics
- **Postgres Exporter**: Database metrics
- **cAdvisor**: Container metrics

### Dashboards
1. System Overview
2. License Server Metrics
3. Database Performance
4. Container Resources
5. Admin Panel Usage

### Alert Rules
- High CPU usage (>80%)
- High memory usage (>90%)
- Database connection issues
- License server downtime
- Disk space warnings

## Admin Panel

### Implementierte Features
1. **Authentication & Security**
   - ✅ Login mit 2FA-Unterstützung
   - ✅ Session Management
   - ✅ Rate Limiting
   - ✅ IP-Blocking bei fehlgeschlagenen Logins
   - ✅ Audit Logging aller Aktionen

2. **Customer Management**
   - ✅ CRUD-Operationen für Kunden
   - ✅ Kundensuche mit Autocomplete
   - ✅ Kunden-Lizenz-Übersicht
   - ✅ Quick Stats pro Kunde

3. **License Management**
   - ✅ Lizenzerstellung (Einzel und Batch)
   - ✅ Lizenzbearbeitung und -löschung
   - ✅ Bulk-Operationen (Aktivieren/Deaktivieren)
   - ✅ Device Management pro Lizenz
   - ✅ Resource Allocation
   - ✅ Quick Edit Funktionalität

4. **Monitoring & Analytics**
   - ✅ Dashboard mit Live-Statistiken
   - ✅ Lizenzserver-Monitoring
   - ✅ Anomalie-Erkennung
   - ✅ Session-Überwachung
   - ✅ Resource-Auslastung

5. **System Administration**
   - ✅ Backup & Restore
   - ✅ Export-Funktionen (CSV)
   - ✅ Audit Log Viewer
   - ✅ Blocked IPs Management
   - ✅ Feature Flags Konfiguration

### Technical Stack
- **Backend**: Flask 3.0.3 mit Blueprints
- **Database**: PostgreSQL mit Partitionierung
- **Frontend**: Bootstrap 5.3, jQuery, Select2
- **Real-time**: AJAX, Server-Sent Events
- **Security**: bcrypt, pyotp (2FA), JWT

## Deployment Configuration

### Docker Services

#### Aktive Services
- `v2_db`: PostgreSQL database (Port 5432)
- `v2_adminpanel`: Admin interface (Port 80)
- `v2_nginx`: Reverse proxy (Ports 80, 443)
- `v2_lizenzserver`: License server (interner Port)
- `redis`: Redis cache (Port 6379)
- `rabbitmq`: Message queue (Ports 5672, 15672)

#### Monitoring Stack (aktiv)
- `prometheus`: Metrics collection (Port 9090)
- `grafana`: Monitoring dashboards (Port 3001)
- `alertmanager`: Alert management (Port 9093)
- `postgres-exporter`: PostgreSQL metrics
- `redis-exporter`: Redis metrics  
- `node-exporter`: System metrics
- `nginx-exporter`: Nginx metrics
- `cadvisor`: Container metrics (Port 8081)

#### Auskommentierte Services
- `auth-service`: Authentication service (würde auf Port 5001 laufen)
- `analytics-service`: Analytics service (würde auf Port 5003 laufen)
- `admin-api-service`: Admin API service (würde auf Port 5004 laufen)

### Environment Variables

#### Erforderlich
- `DATABASE_URL`: PostgreSQL Verbindung
- `SECRET_KEY`: Flask Session Secret
- `JWT_SECRET`: JWT Token Signierung
- `API_KEY`: Lizenzserver API Key

#### Optional mit Defaults
- `MONITORING_ENABLED`: "true" (Feature Flag)
- `SESSION_LIFETIME_MINUTES`: 30
- `PERMANENT_SESSION_LIFETIME_DAYS`: 7  
- `LOGIN_RATE_LIMIT`: "5 per minute"
- `API_RATE_LIMIT`: "100 per minute"
- `MAX_LOGIN_ATTEMPTS`: 5
- `LOGIN_LOCKOUT_DURATION`: 900 (Sekunden)
- `LIZENZSERVER_BASE_URL`: "http://v2_lizenzserver:8000"
- `REDIS_HOST`: "redis"
- `REDIS_PORT`: 6379

### Network Configuration
- Internal network for service communication
- External access through Nginx
- SSL/TLS termination at proxy level

## Testing Strategy

### Unit Tests
- Service layer logic
- API endpoint validation
- Database operations

### Integration Tests
- Service communication
- Database transactions
- API workflows

### Performance Tests
- Load testing
- Stress testing
- Scalability verification

## Future Roadmap

### Phase 1: Core Completion
- Finish analytics service
- Complete backup automation
- Implement all monitoring dashboards

### Phase 2: Advanced Features
- Machine learning for usage prediction
- Advanced reporting
- Multi-tenant support

### Phase 3: Enterprise Features
- High availability setup
- Disaster recovery
- Advanced security features