# Piano di Miglioramento: LLGSummaries2

## Analisi dello Stato Attuale

### Struttura dello Script
Lo script [`LLGSummaries2.php`](../app/Console/Commands/LLGSummaries2.php) elabora statistiche aggregate per:
- **Log Windows**: hostname, category, severity, event_id, users
- **Log Syslog**: hostname, priority, facility
- **Alerts**: conteggio per alert attivi

### Campi Disponibili in logs_ms365
Dal controller [`LogsMs365Controller.php`](../app/Admin/Controllers/LogsMs365Controller.php):

| Campo | Descrizione | Utilità per Summaries |
|-------|-------------|----------------------|
| `typology_id` | Tipo: 1=AzureAD, 2=OneDrive, 3=SharePoint, 5=Exchange, 6=Teams | ✅ Aggregazione principale |
| `workload` | Workload MS365 | ✅ Alternativa a typology_id |
| `operation` | Tipo operazione es. FilePreviewed, UserLoggedIn | ✅ Molto utile |
| `result_status` | Stato: Success, Failure, PartiallySucceeded | ✅ Utile per errori |
| `user_id` | Utente che ha eseguito l'azione | ✅ Aggregazione utenti |
| `client_ip` | IP del client | ⚠️ Opzionale, molti valori |
| `item_type` | Tipo oggetto es. File, Folder | ✅ Utile |
| `source_file_name` | Nome file | ⚠️ Troppe variabili |

---

## Migliorie Proposte per il Codice Esistente

### 1. Refactoring: Estrazione Metodi Privati

**Problema**: Il metodo `handle()` è troppo lungo (~350 righe)

**Soluzione**: Estrarre metodi privati

```php
private function processWindowsLogs(string $add_sql, string $created_at): void
private function processSyslogLogs(string $add_sql, string $created_at): void  
private function processAlerts(string $created_at, int $created_at_timestamp_start, int $created_at_timestamp_end): array
private function normalizeSeverity(string $severity): string
private function saveSummary(array $data): void
```

### 2. Ottimizzazione: Inserimento Batch

**Problema**: Ogni `save()` è una query INSERT separata

**Soluzione**: Usare `insert()` batch

```php
// Invece di N save()
Summaries::insert($batchData);
```

### 3. Gestione Transazioni

**Aggiungere**: Transazione per ogni licenza

```php
DB::connection('logs')->transaction(function () use ($dbName) {
    // Tutte le operazioni per questa licenza
});
```

### 4. Progress Bar per CLI

```php
$this->output->progressStart(count($licenses));
// Nel loop
$this->output->progressAdvance();
$this->output->progressFinish();
```

### 5. Logging Strutturato

```php
Log::info('LLGSummaries2: Processing license', [
    'license' => $dbName,
    'records_processed' => $count
]);
```

---

## Nuove Aggregazioni per logs_ms365

### Struttura Proposta

```mermaid
flowchart TD
    A[logs_ms365] --> B[WORKLOADS]
    A --> C[OPERATIONS]
    A --> D[USERS]
    A --> E[STATUS]
    
    B --> B1[WORKLOADS - TOTALS]
    B --> B2[WORKLOADS - OPERATIONS]
    B --> B3[WORKLOADS - STATUS]
    
    C --> C1[OPERATIONS - TOTALS]
    
    D --> D1[USERS - OPERATIONS]
    D --> D2[USERS - WORKLOADS]
    
    E --> E1[STATUS - TOTALS]
    E --> E2[STATUS - BY WORKLOAD]
```

### Tabella Summaries per MS365

| summary_category | summary_typology | summary_sub_typology | summary_key | summary_related_key | Descrizione |
|------------------|------------------|---------------------|-------------|---------------------|-------------|
| MS365 | WORKLOADS | TOTALS | AzureAD, OneDrive, etc | null | Conteggio per workload |
| MS365 | WORKLOADS | OPERATIONS | operation_name | workload | Operazioni per workload |
| MS365 | WORKLOADS | STATUS | Success/Failure | workload | Status per workload |
| MS365 | OPERATIONS | TOTALS | operation_name | null | Conteggio globale operazioni |
| MS365 | USERS | OPERATIONS | operation | user_id | Operazioni per utente |
| MS365 | USERS | WORKLOADS | workload | user_id | Workload per utente |
| MS365 | STATUS | TOTALS | Success/Failure | null | Conteggio globale status |

### Query SQL per Aggregazioni MS365

#### 1. Per Workload/Typology
```sql
SELECT 
    COALESCE(workload, 'UNKNOWN') as workload,
    COUNT(*) as tot_rows 
FROM logs_ms365 
WHERE created_at >= :start AND created_at < :end
GROUP BY workload
```

#### 2. Per Workload + Operation
```sql
SELECT 
    COALESCE(workload, 'UNKNOWN') as workload,
    operation,
    COUNT(*) as tot_rows 
FROM logs_ms365 
WHERE created_at >= :start AND created_at < :end
GROUP BY workload, operation
```

#### 3. Per Workload + Result Status
```sql
SELECT 
    COALESCE(workload, 'UNKNOWN') as workload,
    result_status,
    COUNT(*) as tot_rows 
FROM logs_ms365 
WHERE created_at >= :start AND created_at < :end
GROUP BY workload, result_status
```

#### 4. Per Utente + Operation
```sql
SELECT 
    user_id,
    operation,
    COUNT(*) as tot_rows 
FROM logs_ms365 
WHERE created_at >= :start AND created_at < :end
  AND user_id IS NOT NULL
  AND user_id NOT LIKE '%$%'
  AND user_id NOT LIKE '%NT AUTHORITY%'
GROUP BY user_id, operation
```

#### 5. Per Utente + Workload
```sql
SELECT 
    user_id,
    workload,
    COUNT(*) as tot_rows 
FROM logs_ms365 
WHERE created_at >= :start AND created_at < :end
  AND user_id IS NOT NULL
  AND user_id NOT LIKE '%$%'
GROUP BY user_id, workload
```

---

## Piano di Implementazione

> **DECISIONE UTENTE**: Priorità al refactoring del codice esistente. MS365 sarà implementato successivamente.

### Fase 1: Refactoring Codice Esistente ⬅️ PRIORITÀ
- [ ] Estrarre metodo `processWindowsLogs()`
- [ ] Estrarre metodo `processSyslogLogs()`
- [ ] Estrarre metodo `processAlerts()`
- [ ] Estrarre metodo `normalizeSeverity()`
- [ ] Estrarre metodo `saveSummaryBatch()` per inserimento batch
- [ ] Aggiungere progress bar
- [ ] Testare che tutto funzioni come prima

### Fase 2: Ottimizzazioni
- [ ] Implementare inserimento batch con `insert()`
- [ ] Aggiungere transazioni per licenza
- [ ] Aggiungere logging strutturato
- [ ] Testare performance

### Fase 3: Aggiunta MS365 (POSTICIPATO)
- [ ] Aggiungere metodo `processMs365Logs()`
- [ ] Implementare query di aggregazione
- [ ] Normalizzare result_status (come severity)
- [ ] Filtrare utenti di sistema
- [ ] Testare con dati reali

### Fase 4: Test e Validazione
- [ ] Test unitari per ogni metodo
- [ ] Test di integrazione con vari dataset
- [ ] Verifica performance su grandi volumi
- [ ] Documentazione aggiornata

---

## Note Tecniche

### Normalizzazione Result Status

```php
private function normalizeResultStatus(string $status): string
{
    return match (strtoupper($status)) {
        'SUCCEEDED', 'SUCCESS' => 'SUCCESS',
        'FAILED', 'FAILURE', 'ERROR' => 'FAILURE',
        'PARTIALLYSUCCEEDED' => 'PARTIAL',
        default => 'UNKNOWN',
    };
}
```

### Filtri Utenti MS365

Escludere utenti di sistema:
- Utenti che contengono `$` (account computer)
- `NT AUTHORITY\SYSTEM`
- `NT AUTHORITY\LOCAL SERVICE`
- `NT AUTHORITY\NETWORK SERVICE`
- Utenti che iniziano con `AAD_` (Azure AD service accounts)

---

## Domande per l'Utente

1. **Priorità**: Preferisci prima il refactoring o l'aggiunta di MS365?
2. **Workload**: Quali workload MS365 sono più importanti da tracciare?
3. **Retention**: Confermi i 60 giorni di retention per i summaries?
4. **Scheduling**: Lo script viene eseguito ogni ora? C'è bisogno di renderlo più frequente?
