# SAP Business One ↔ Plesk Synchronisations-Webapp

Eine Enterprise-Webapp zur automatischen Synchronisation zwischen SAP Business One (Systemhaus One) und Plesk Webservern für die Abrechnung von Verbrauchskosten.

## 📁 Projektstruktur

```
sap-sync-app/
├── backend/              # Rust Backend (Axum + Tokio)
│   ├── src/
│   │   ├── main.rs       # Entry Point
│   │   ├── config/       # Configuration Management
│   │   ├── db/           # Database Pool & Migrations
│   │   ├── handlers/     # API Endpoints
│   │   ├── models/       # Data Models
│   │   ├── routes/       # API Routes
│   │   ├── services/     # Business Logic
│   │   ├── utils/        # Utilities
│   │   └── state.rs      # Application State
│   ├── Cargo.toml        # Rust Dependencies
│   └── Dockerfile        # Backend Container
├── frontend/             # React Frontend (MUI)
│   ├── src/
│   │   ├── App.tsx       # Main Application
│   │   ├── components/   # React Components
│   │   ├── contexts/     # Auth & I18n Contexts
│   │   ├── pages/        # React Pages
│   │   └── main.tsx      # Entry Point
│   ├── package.json      # Node Dependencies
│   └── Dockerfile        # Frontend Container
├── database/
│   ├── init.sql          # PostgreSQL Schema
│   └── seeds/            # Seed Data
├── nginx/
│   └── nginx.conf        # Reverse Proxy Config
├── docker-compose.yml    # Multi-Service Setup
├── .env.example          # Environment Template
└── README.md             # This File
```

## ✅ Features (Phase 1 & 2)

### Authentication & Security
- ✅ **Session-based Auth**: PostgreSQL Session Store
- ✅ **Password Policy**: Min 8 chars, Groß-/Kleinbuchstaben, Ziffern, Sonderzeichen
- ✅ **Brute Force Protection**: 5 fehlgeschlagene Versuche → 1 Stunde Lockout
- ✅ **CSRF Protection**: Token-basiert (24h expiry)
- ✅ **MFA**: Optional TOTP (Google Authenticator, Authy)
- ✅ **Secure Cookies**: HTTP-only, Secure, SameSite Strict

### SAP Integration
- ✅ **Service Layer API Client**: REST API Verbindung
- ✅ **OAuth2 Authentication**: Sichere Authentifizierung
- ✅ **Customer Management**: Get, Create, Update
- ✅ **Item Management**: Für Abonnements
- ✅ **Contract Management**: Vertragsdaten
- ✅ **Connection Testing**: Health Checks

### Plesk Integration
- ✅ **REST API Client**: Plesk API v2
- ✅ **Customer Management**: CRUD Operations
- ✅ **Subscription Management**: Webspaces, Domains
- ✅ **Usage Metrics**: CPU, RAM, Disk, Bandwidth
- ✅ **Connection Testing**: Health Checks

### Sync Engine
- ✅ **Worker Pool**: Tokio-basierte Parallelverarbeitung
- ✅ **Conflict Resolution**: 4 Strategien (SAP First, Plesk First, Manual, Timestamp)
- ✅ **Bidirectional Sync**: SAP ↔ Plesk
- ✅ **Progress Tracking**: Echtzeit-Status
- ✅ **Error Handling**: Retry Logic
- ✅ **Job Queue**: Asynchrone Verarbeitung

### Reports & Analytics
- ✅ **Revenue Report**: Umsatzübersicht
- ✅ **Usage Report**: Verbrauchsmetriken
- ✅ **Sync History**: Synchronisations-Historie
- ✅ **Export**: CSV, Excel (xlsx), PDF

### Notifications
- ✅ **Email Notifications**: SMTP (Lettre)
- ✅ **Webhooks**: HTTP Callbacks
- ✅ **Dashboard Alerts**: Real-time Status
- ✅ **Error Notifications**: Bei Fehlern

### Frontend
- ✅ **Dashboard**: Übersicht, Status, Stats
- ✅ **Sync Control**: Start, Stop, Monitor
- ✅ **Reports**: Charts, Export
- ✅ **Settings**: Profile, Security, Sync Config
- ✅ **Multi-Language**: DE, FR, EN, SPA

### Infrastructure
- ✅ **Docker Compose**: Multi-Container Setup
- ✅ **Nginx**: Reverse Proxy, SSL, Rate Limiting
- ✅ **PostgreSQL**: Database
- ✅ **Redis**: Caching
- ✅ **pgAdmin**: Database Management UI
- ✅ **MailHog**: SMTP Test Server

## 🛠 Tech Stack

### Backend
- **Language**: Rust 1.75+
- **Framework**: Axum 0.7
- **Async Runtime**: Tokio 1.35
- **Database**: PostgreSQL 15 + sqlx 0.7
- **HTTP Client**: reqwest 0.11
- **Auth**: tower-session + PostgreSQL Store
- **Security**: Argon2, CSRF, TOTP

### Frontend
- **Framework**: React 18
- **Build Tool**: Vite 5
- **UI Library**: Material UI 5.14
- **Routing**: React Router 6
- **HTTP Client**: Axios 1.6
- **Charts**: Recharts 2.10
- **i18n**: i18next 23

### Infrastructure
- **Container**: Docker 24+
- **Orchestration**: Docker Compose
- **Proxy**: Nginx Alpine
- **Database**: PostgreSQL 15 Alpine
- **Cache**: Redis 7 Alpine
- **Management**: pgAdmin 4

## 🚀 Quick Start

### 1. Voraussetzungen

- Docker 24.0+ installiert
- Docker Compose 2.20+ installiert
- Git installiert
- Min. 4 GB RAM, 20 GB Speicher

### 2. Installation

```bash
# Repository klonen
git clone <repository-url>
cd sap-sync-app

# Umgebungsvariablen konfigurieren
cp .env.example .env
# .env mit echten Werten bearbeiten

# Alle Services starten
docker-compose up -d

# Logs überprüfen
docker-compose logs -f
```

### 3. Erste Schritte

```bash
# Admin-User erstellen (wird beim ersten Start automatisch erstellt)
# Default: username: admin, password: <generiert>

# Zugriff:
# Frontend:      http://localhost:3000
# Backend API:   http://localhost:3001/api
# pgAdmin:       http://localhost:8080
# MailHog:       http://localhost:8025
```

### 4. SAP & Plesk konfigurieren

1. **SAP Service Layer**: 
   - URL und Credentials in `.env` eintragen
   - `APP__SAP__URL` und `APP__SAP__CREDENTIALS`

2. **Plesk API**:
   - API Key generieren in Plesk
   - In `.env` eintragen: `APP__PLESK__API_KEY`

3. **Sync konfigurieren**:
   - Frontend öffnen → Settings → Sync Settings
   - Default Direction wählen
   - Conflict Resolution festlegen

## 📊 API Endpoints

### Authentication
```
POST   /api/auth/login              # Login
POST   /api/auth/logout             # Logout
GET    /api/auth/me                 # Current User
POST   /api/auth/change-password    # Change Password
GET    /api/auth/csrf-token         # Get CSRF Token
```

### Sync Management
```
GET    /api/sync/status             # Sync Status
POST   /api/sync/start              # Start Sync
POST   /api/sync/stop               # Stop Sync
GET    /api/sync/jobs               # List Jobs
GET    /api/sync/jobs/:id           # Job Details
```

### Configuration
```
GET    /api/config                  # Get Config
PUT    /api/config                  # Update Config
```

### Reports
```
GET    /api/reports/revenue         # Revenue Report
GET    /api/reports/usage           # Usage Report
GET    /api/reports/sync-history    # Sync History
GET    /api/reports/export/:format  # Export (csv/xlsx/pdf)
```

### Health & Monitoring
```
GET    /api/health                  # Overall Health
GET    /api/health/sap              # SAP Connection
GET    /api/health/plesk            # Plesk Connection
```

### Notifications
```
GET    /api/notifications           # List Notifications
PUT    /api/notifications/:id/read  # Mark as Read
POST   /api/webhooks                # Create Webhook
GET    /api/webhooks                # List Webhooks
```

## 🔧 Konfiguration

### .env Beispiel

```env
# Database
DB_PASSWORD=your_secure_password
DATABASE_URL=postgresql://sap_user:${DB_PASSWORD}@pgsql:5432/sap_sync

# Backend
APP__SERVER__HOST=0.0.0.0
APP__SERVER__PORT=3001
APP__SESSION__SECURE=false
APP__MFA__ENABLED=true

# SAP Connection
APP__SAP__URL=https://sap-server:50000/b1s/v1
APP__SAP__COMPANY_DB=SBODemoDE
APP__SAP__USERNAME=manager
APP__SAP__PASSWORD=manager

# Plesk Connection
APP__PLESK__URL=https://plesk-server:8443/api/v2
APP__PLESK__API_KEY=your-api-key

# Email (SMTP)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your_email@gmail.com
SMTP_PASSWORD=your_app_password
SMTP_FROM=noreply@sap-sync.local

# Frontend
VITE_API_URL=http://localhost:3001/api
```

## 🗄️ Datenbank-Schema

### Haupttabellen
- **users**: Admin-Benutzer
- **sessions**: Session Management
- **customers**: SAP ↔ Plesk Customer Mapping
- **subscriptions**: Abonnements/Verträge
- **usage_metrics**: Verbrauchsdaten
- **sync_jobs**: Sync-Jobs Queue
- **sync_logs**: Synchronisations-Logs
- **notifications**: Benachrichtigungen
- **webhooks**: Webhook-Konfiguration
- **config**: System-Konfiguration

### Erweiterte Features
- **JSONB Columns**: Flexible Datenspeicherung
- **GIN/GIST Indexes**: Schnelle JSON-Suche
- **Materialized Views**: Dashboard Performance
- **Triggers**: Automatische Timestamps
- **Full-text Search**: Kunden-Suche

## 🔒 Sicherheit

### Password Policy
- Min 8 Zeichen
- Min 1 Großbuchstabe (A-Z)
- Min 1 Kleinbuchstabe (a-z)
- Min 1 Ziffer (0-9)
- Min 1 Sonderzeichen (!@#$%&*)

### Session Security
- HTTP-only Cookies
- Secure Flag (HTTPS)
- SameSite Strict
- 30 Minuten Expiry
- Remember Me (7 Tage)

### Rate Limiting
- General API: 10 req/s
- Auth Endpoints: 5 req/min
- Nginx Built-in

## 📈 Performance

### Backend
- Async Rust (Tokio)
- Connection Pooling (sqlx)
- Worker Pool (Sync Engine)
- JSONB Queries (PostgreSQL)

### Frontend
- React 18 (Concurrent Rendering)
- Vite (Fast Build)
- Code Splitting
- Lazy Loading

## 🧪 Testing

```bash
# Backend Tests
cd backend
cargo test

# Frontend Tests
cd frontend
npm test

# Integration Tests
docker-compose -f docker-compose.test.yml up
```

## 📦 Production Deployment

### Plesk Deployment

1. **Docker auf Plesk Server**:
   ```bash
   # Docker installieren
   curl -fsSL https://get.docker.com | bash
   
   # Repository klonen
   git clone <repo> /opt/sap-sync
   cd /opt/sap-sync
   ```

2. **SSL Zertifikate**:
   ```bash
   # Certbot für Let's Encrypt
   certbot certonly --standalone -d your-domain.com
   
   # Zertifikate kopieren
   cp /etc/letsencrypt/live/your-domain.com/fullchain.pem nginx/ssl/cert.pem
   cp /etc/letsencrypt/live/your-domain.com/privkey.pem nginx/ssl/key.pem
   ```

3. **Environment konfigurieren**:
   ```bash
   cp .env.example .env
   # .env bearbeiten mit Production-Werten
   ```

4. **Services starten**:
   ```bash
   docker-compose up -d
   ```

5. **Plesk Proxy**:
   - Nginx Proxy in Plesk konfigurieren
   - Domain → Apache & nginx Settings → Additional nginx directives
   ```nginx
   location / {
       proxy_pass http://localhost:3000;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
   }
   ```

## 🐛 Troubleshooting

### Backend startet nicht
```bash
# Logs prüfen
docker-compose logs backend

# Database Connection testen
docker-compose exec backend psql $DATABASE_URL -c "SELECT 1"
```

### Frontend Build Fehler
```bash
# Dependencies neu installieren
cd frontend
rm -rf node_modules package-lock.json
npm install
npm run build
```

### SAP/Plesk Connection Failed
```bash
# Connection testen
curl -X GET http://localhost:3001/api/health/sap
curl -X GET http://localhost:3001/api/health/plesk

# Credentials prüfen
docker-compose exec backend env | grep SAP
docker-compose exec backend env | grep PLESK
```

## 📝 Development

### Backend Development
```bash
cd backend

# Rust installieren (falls nicht vorhanden)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Cargo Watch für Hot Reload
cargo install cargo-watch
cargo watch -x run

# Tests
cargo test
```

### Frontend Development
```bash
cd frontend

# Dependencies
npm install

# Dev Server
npm run dev

# Build
npm run build
```

## 📄 License

MIT License - siehe LICENSE Datei

## 🤝 Contributing

1. Fork erstellen
2. Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Committen (`git commit -m 'Add some AmazingFeature'`)
4. Push (`git push origin feature/AmazingFeature`)
5. Pull Request öffnen

## 📞 Support

- **Issues**: GitHub Issues
- **Documentation**: `/docs` Ordner
- **Email**: support@sap-sync.local

---

**Erstellt mit ❤️ für Enterprise SAP ↔ Plesk Synchronisation**