# 📊 ROA2WEB - SCHEMĂ GRAFICĂ ARHITECTURĂ

Această schemă prezintă arhitectura completă a aplicației ROA2WEB, incluzând frontend-ul Vue.js, backend-ul FastAPI, middleware-ul de autentificare și conexiunea la baza de date Oracle.

## 🏗️ **ARHITECTURA GENERALĂ**

```
┌─────────────────────────────────────────────────────────────────────────────────┐
│                                  🌐 CLIENT                                      │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ HTTP Requests
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                               🖥️  FRONTEND                                      │
│                          Vue.js 3 + PrimeVue + Vite                           │
│  Port: 5173 (dev) / 3000 (prod)                                               │
│                                                                                │
│  📁 Components:                   📦 Stores (Pinia):                          │
│  • LoginView.vue                  • auth.js (JWT tokens)                      │
│  • DashboardView.vue             • companies.js                               │
│  • InvoicesView.vue              • dashboard.js                               │
│  • BankCashRegisterView.vue      • invoices.js                               │
│                                   • treasury.js                               │
│  🔧 Services:                                                                  │
│  • api.js (Axios HTTP client)                                                 │
│  • JWT token management                                                       │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ API Calls (axios)
                  │ Authorization: Bearer <JWT>
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                              🚀 BACKEND API                                    │
│                              FastAPI + Uvicorn                                │
│  Port: 8000                                                                   │
│                                                                                │
│  🛡️  MIDDLEWARE LAYER:                                                         │
│  ┌─────────────────────────────────────────────────────────────────────────┐  │
│  │  1. CORSMiddleware (Frontend communication)                             │  │
│  │  2. AuthenticationMiddleware (JWT validation)                           │  │
│  │     • Token extraction from Authorization header                       │  │
│  │     • JWT verification & user data injection                           │  │
│  │     • Rate limiting (5 req/5min per IP)                               │  │
│  │     • Security headers injection                                       │  │
│  │     • Excluded paths: ["/", "/docs", "/health", "/api/auth/login"]    │  │
│  └─────────────────────────────────────────────────────────────────────────┘  │
│                                                                                │
│  🛤️  API ROUTES:                                                              │
│  • /api/auth/login (POST) - User authentication                              │
│  • /api/companies (GET) - Company list                                       │
│  • /api/dashboard (GET) - Dashboard data                                     │
│  • /api/invoices (GET) - Invoice reports                                     │
│  • /api/treasury (GET) - Treasury/Bank data                                  │
│  • /api/trial-balance (GET) - Trial Balance (Balanță de Verificare)         │
│  • /health (GET) - Health check                                              │
│                                                                                │
│  📊 SERVICES (with caching):                                                   │
│  • invoice_service.py (@cached: invoices, schema)                            │
│  • dashboard_service.py (@cached: dashboard_summary, trends, etc.)           │
│  • treasury_service.py (@cached: treasury, schema)                           │
│                                                                                │
│  ⚡ CACHE LAYER (Two-Tier):                                                    │
│  ┌─────────────────────────────────────────────────────────────────────────┐  │
│  │  L1 (Memory): Fast in-memory cache (LRU, max 1000 entries)             │  │
│  │  L2 (SQLite): Persistent cache database (./cache_data/)                │  │
│  │                                                                         │  │
│  │  Features:                                                              │  │
│  │  • Automatic TTL per cache type (schema: 24h, invoices: 10min, etc.)   │  │
│  │  • Performance tracking & benchmarking                                 │  │
│  │  • Per-user cache enable/disable                                       │  │
│  │  • Event-based invalidation (optional)                                 │  │
│  │  • Cache hit/miss metrics in response headers                          │  │
│  │                                                                         │  │
│  │  Usage: @cached(cache_type='...', key_params=['company', 'username'])  │  │
│  └─────────────────────────────────────────────────────────────────────────┘  │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ Database Queries (on cache miss)
                  │ SSH Tunnel Required
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                         🔐 SSH TUNNEL LAYER                                    │
│  ./ssh_tunnel.sh (Local port forwarding)                                      │
│  Local: localhost:1526 ➜ Remote: oracle_server:1521                          │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ Encrypted connection
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                           🏛️  ORACLE DATABASE                                  │
│  Schema: CONTAFIN_ORACLE                                                       │
│  Port: 1521 (remote) / 1526 (local via tunnel)                               │
│                                                                                │
│  📋 Main Tables/Views:                                                         │
│  • UTILIZATORI (Users)                                                        │
│  • V_NOM_FIRME (Companies)                                                    │
│  • VDEF_UTIL_FIRME (User-Company relations)                                  │
│  • Financial data tables (invoices, payments, etc.)                          │
│                                                                                │
│  🔧 Stored Procedures:                                                         │
│  • pack_drepturi.verificautilizator (Authentication)                         │
└─────────────────────────────────────────────────────────────────────────────────┘
```

## ⚡ **ARHITECTURA CACHE (TWO-TIER L1 + L2)**

```
┌─────────────────────────────────────────────────────────────────────────────────┐
│                        🔥 CACHE LAYER ARCHITECTURE                             │
└─────────────────────────────────────────────────────────────────────────────────┘

API Request (service method decorated with @cached)
    ↓
┌─────────────────────────────────────────────────────────────────────────────────┐
│ 1. Check if Cache Enabled (Global + Per-User)                                 │
│    • Global setting: CACHE_ENABLED=True/False                                 │
│    • Per-user setting: SQLite user_settings table                             │
└───┬─────────────────────────────────────────────────────────────────────────────┘
    ↓ (if disabled: query Oracle directly)
┌───▼─────────────────────────────────────────────────────────────────────────────┐
│ 2. Generate Cache Key                                                          │
│    • Pattern: {cache_type}:{param1}:{param2}:...                              │
│    • Example: "invoices:123:user1:2024-01"                                    │
└───┬─────────────────────────────────────────────────────────────────────────────┘
    ↓
┌───▼─────────────────────────────────────────────────────────────────────────────┐
│ 3. Try L1 (Memory Cache)                                                       │
│    • Python dict with TTL                                                      │
│    • LRU eviction (max 1000 entries)                                          │
│    • ⚡ Ultra-fast (microseconds)                                              │
│    └─→ HIT? Return value + track performance (L1)                             │
└───┬─────────────────────────────────────────────────────────────────────────────┘
    ↓ (if MISS)
┌───▼─────────────────────────────────────────────────────────────────────────────┐
│ 4. Try L2 (SQLite Cache)                                                       │
│    • Persistent database (./cache_data/roa2web_cache.db)                      │
│    • Indexed by key, company_id, cache_type                                   │
│    • 🗄️ Slower than L1 but faster than Oracle                                 │
│    └─→ HIT? Populate L1 + return value + track performance (L2)               │
└───┬─────────────────────────────────────────────────────────────────────────────┘
    ↓ (if MISS)
┌───▼─────────────────────────────────────────────────────────────────────────────┐
│ 5. CACHE MISS - Query Oracle                                                   │
│    • Execute actual database query                                             │
│    • Measure execution time (benchmark)                                        │
│    • Store result in L1 + L2                                                   │
│    • Track performance (cache miss)                                            │
└─────────────────────────────────────────────────────────────────────────────────┘

📊 CACHE TYPES & TTL (Time To Live):

• schema:              24 hours  (CACHE_TTL_SCHEMA=86400)
• companies:           30 min    (CACHE_TTL_COMPANIES=1800)
• dashboard_summary:   30 min    (CACHE_TTL_DASHBOARD_SUMMARY=1800)
• dashboard_trends:    30 min    (CACHE_TTL_DASHBOARD_TRENDS=1800)
• invoices:            10 min    (CACHE_TTL_INVOICES=600)
• invoices_summary:    15 min    (CACHE_TTL_INVOICES_SUMMARY=900)
• treasury:            10 min    (CACHE_TTL_TREASURY=600)
• trial_balance:       10 min    (CACHE_TTL_TRIAL_BALANCE=600)

🔧 CACHE MANAGEMENT ENDPOINTS:

• GET  /api/cache/stats            - Cache statistics (hits, misses, performance)
• POST /api/cache/invalidate       - Invalidate cache (all/company/type)
• GET  /api/cache/user-settings    - Get user cache settings
• POST /api/cache/user-settings    - Enable/disable cache for user

📈 PERFORMANCE TRACKING:

Each cached request includes metadata:
• cache_hit: true/false (was result from cache?)
• cache_source: "L1" | "L2" | null (which cache tier?)
• response_time_ms: float (total response time)
• time_saved_ms: float (estimated time saved vs Oracle query)
```

## 🔄 **FLUX DE AUTENTIFICARE**

```
1. User Login (Frontend)
   ↓
2. POST /api/auth/login (Backend)
   ↓
3. Oracle Authentication via SSH Tunnel
   • pack_drepturi.verificautilizator(username, password)
   ↓
4. JWT Token Generation (Backend)
   • Access Token (30 min)
   • Refresh Token (7 days)
   • User data + companies + permissions
   ↓
5. Token Storage (Frontend - Pinia Store)
   ↓
6. Subsequent API Requests
   • Authorization: Bearer <token>
   • AuthenticationMiddleware validation
   • User data injection in request.state
```

## 🚦 **MIDDLEWARE AUTHENTICATION FLOW**

```
Incoming Request
    ↓
┌─────────────────┐
│ Rate Limiting   │ → 429 if exceeded (5 req/5min per IP)
└─────┬───────────┘
      ↓
┌─────────────────┐
│ Path Exclusion  │ → Skip auth for /docs, /health, /api/auth/login
└─────┬───────────┘
      ↓
┌─────────────────┐
│ Token Extract   │ → 401 if missing Authorization header
└─────┬───────────┘
      ↓
┌─────────────────┐
│ JWT Validation  │ → 401 if invalid/expired/malformed
└─────┬───────────┘
      ↓
┌─────────────────┐
│ User Injection  │ → request.state.user = CurrentUser
└─────┬───────────┘    → request.state.is_authenticated = True
      ↓               → request.state.token_data = TokenData
┌─────────────────┐
│ Security Headers│ → X-Content-Type-Options, X-Frame-Options
└─────┬───────────┘    → X-XSS-Protection, X-Process-Time
      ↓
┌─────────────────┐
│ Route Handler   │
└─────────────────┘
```

## 🗂️ **STRUCTURA DE FIȘIERE**

### Frontend (Vue.js)
```
frontend/
├── src/
│   ├── components/
│   │   ├── dashboard/
│   │   ├── layout/
│   │   ├── reports/
│   │   └── ui/
│   ├── stores/ (Pinia)
│   │   ├── auth.js
│   │   ├── companies.js
│   │   ├── dashboard.js
│   │   ├── invoices.js
│   │   └── treasury.js
│   ├── services/
│   │   └── api.js
│   ├── views/
│   │   ├── LoginView.vue
│   │   ├── DashboardView.vue
│   │   ├── InvoicesView.vue
│   │   └── BankCashRegisterView.vue
│   └── router/
└── tests/ (Playwright E2E)
```

### Backend (FastAPI)
```
backend/
├── app/
│   ├── main.py
│   ├── routers/
│   │   ├── auth.py
│   │   ├── companies.py
│   │   ├── dashboard.py
│   │   ├── invoices.py
│   │   └── treasury.py
│   ├── services/
│   │   ├── invoice_service.py
│   │   ├── dashboard_service.py
│   │   └── treasury_service.py
│   └── models/
└── shared/
    ├── auth/
    │   ├── middleware.py
    │   ├── jwt_handler.py
    │   ├── auth_service.py
    │   └── models.py
    └── database/
        └── oracle_pool.py
```

## 🔧 **TEHNOLOGII UTILIZATE**

### Frontend Stack
- **Vue.js 3** - Framework JavaScript reactiv
- **PrimeVue** - UI Component Library
- **Pinia** - State Management
- **Vite** - Build Tool & Dev Server
- **Axios** - HTTP Client
- **Vue Router** - Client-side routing
- **Chart.js** - Data visualization
- **Playwright** - E2E Testing

### Backend Stack
- **FastAPI** - Python Web Framework
- **Uvicorn** - ASGI Server
- **PyJWT** - JWT Token handling
- **cx_Oracle** - Oracle Database driver
- **Pydantic** - Data validation
- **Python-dotenv** - Environment variables

### Database & Infrastructure
- **Oracle Database** - Persistent data storage
- **SSH Tunnel** - Secure database connection (Linux/development)
- **Docker** - Containerization (Linux production)
- **Nginx** - Reverse proxy & static files (Linux production)
- **Windows Server + IIS** - Windows production deployment
- **NSSM** - Windows service manager

## 🪟 **ARHITECTURA WINDOWS SERVER/IIS**

### Deployment pe Windows Server

ROA2WEB poate fi deployment pe Windows Server folosind IIS și Windows Services, fără Docker:

```
┌─────────────────────────────────────────────────────────────────────────────────┐
│                                  🌐 CLIENT                                      │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ HTTP/HTTPS Requests
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                           🪟 IIS WEB SERVER                                    │
│  Port: 80/443 (HTTPS with SSL certificate)                                   │
│                                                                                │
│  📁 Static Files Serving:          🔀 URL Rewrite Module:                    │
│  • Frontend (Vue.js build)         • /api/* → Backend Service                │
│  • web.config configuration        • /* → index.html (SPA routing)           │
│  • Compression & Caching           • Application Request Routing (ARR)       │
│                                                                                │
│  ⚙️  Application Pool:                                                        │
│  • ROA2WEB-AppPool (.NET not required)                                       │
│  • Integrated pipeline mode                                                  │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ Reverse Proxy to Backend
                  │ http://localhost:8000/api/*
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                        🔧 WINDOWS SERVICE                                      │
│  Service Name: ROA2WEB-Backend                                                │
│  Manager: NSSM (Non-Sucking Service Manager)                                 │
│  Port: 8000 (localhost only)                                                  │
│                                                                                │
│  📊 Backend Components:                                                        │
│  • FastAPI + Uvicorn (Python 3.11+)                                          │
│  • Auto-start on Windows boot                                                │
│  • Auto-restart on failure (5 sec delay)                                     │
│  • Logging to file (stdout/stderr)                                           │
│                                                                                │
│  📁 Installation Location:                                                     │
│  • C:\inetpub\wwwroot\roa2web\backend\                                       │
└─────────────────┬───────────────────────────────────────────────────────────────┘
                  │ Direct Database Connection
                  │ No SSH Tunnel Required
                  ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                      🏛️  ORACLE DATABASE (Local/Network)                      │
│  Connection: Direct TCP/IP (localhost:1521 or network)                        │
│  Schema: CONTAFIN_ORACLE                                                       │
│                                                                                │
│  📋 Same Tables/Views as Linux deployment                                      │
│  🔧 Same Stored Procedures                                                     │
└─────────────────────────────────────────────────────────────────────────────────┘
```

### Diferențe între Linux și Windows Deployment

| Aspect | Linux (Docker) | Windows (IIS) |
|--------|----------------|---------------|
| **Web Server** | Nginx (container) | IIS (native) |
| **Backend Runtime** | Docker container | Windows Service (NSSM) |
| **Database Access** | SSH Tunnel required | Direct connection |
| **SSL/TLS** | Let's Encrypt (certbot) | IIS SSL certificates |
| **Service Management** | Docker Compose | PowerShell + Services.msc |
| **Deployment** | `./scripts/deploy.sh` | `Deploy-ROA2WEB.ps1` |
| **Logs** | Docker logs | Windows Event Log + Files |
| **Auto-start** | Docker restart policies | Windows Service auto-start |

### Structura Fișiere Windows Deployment

```
C:\inetpub\wwwroot\roa2web\
├── backend\                      # FastAPI application
│   ├── app\
│   │   ├── main.py
│   │   ├── routers\
│   │   ├── services\
│   │   └── models\
│   ├── shared\                  # Shared components
│   │   ├── auth\
│   │   ├── database\
│   │   └── utils\
│   ├── requirements.txt
│   ├── .env                     # Production config
│   └── logs\
│
├── frontend\                     # Vue.js build output
│   ├── index.html
│   ├── assets\
│   ├── web.config               # IIS configuration
│   └── ...
│
├── logs\                         # Service logs
│   ├── backend-stdout.log
│   └── backend-stderr.log
│
└── backups\                      # Deployment backups
    └── backup-YYYYMMDD-HHMMSS\
```

### Comenzi Windows Deployment

```powershell
# Instalare inițială
.\Install-ROA2WEB.ps1

# Deployment actualizări
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\path\to\deploy-package"

# Management serviciu
.\Start-ROA2WEB.ps1
.\Stop-ROA2WEB.ps1
.\Restart-ROA2WEB.ps1

# Verificare status
Get-Service ROA2WEB-Backend
Get-Website ROA2WEB

# Logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50 -Wait
```

Pentru detalii complete despre deployment pe Windows, consultați:
- `/deployment/windows/docs/WINDOWS_DEPLOYMENT.md`
- `/deployment/windows/README.md`

## ⚙️ **COMENZI DE DEZVOLTARE**

### Start SSH Tunnel
```bash
cd /mnt/d/PROIECTE/roa-flask/roa2web
./ssh_tunnel.sh start
```

### Backend Development
```bash
cd reports-app/backend/
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
```

### Frontend Development
```bash
cd reports-app/frontend/
npm install
npm run dev
```

### Testing
```bash
cd shared/
python -m pytest -v
```

## 🛡️ **SECURITATE**

### Middleware de Autentificare
- **JWT Token Validation** - Verificare automată pentru toate endpoint-urile protejate
- **Rate Limiting** - Protecție împotriva atacurilor brute force
- **Security Headers** - X-Content-Type-Options, X-Frame-Options, X-XSS-Protection
- **CORS Protection** - Configurare restrictivă pentru frontend-uri autorizate

### Baza de Date
- **SSH Tunnel** - Conexiune criptată la Oracle
- **Schema Dedicată** - CONTAFIN_ORACLE pentru izolare
- **Stored Procedures** - Validare securizată de utilizatori

---

*Această schemă oferă o vedere de ansamblu asupra arhitecturii ROA2WEB și poate fi utilizată pentru documentare, onboarding și planificarea dezvoltării viitoare.*