> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lovi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Notifiche Vocali

> Guida completa per implementare notifiche vocali automatizzate

## Introduzione

Le notifiche vocali permettono di raggiungere i clienti attraverso chiamate telefoniche automatizzate quando WhatsApp non è disponibile o preferibile. Questa guida copre l'implementazione completa delle notifiche vocali nell'API Lovi.

## 📞 Funzionalità Base

### Invio Notifica Vocale Semplice

**Chiamata Base:**

```javascript theme={null}
await loviService.sendVoiceNotification({
  contact: { number: "34666033135" },
  message: "Ciao Mario, il tuo appuntamento è confermato per domani alle 10:00",
  voice: "it-IT-Standard-A", // Voce italiana maschile
  language: "it-IT"
});
```

**Con Template Vocale:**

```javascript theme={null}
await loviService.sendVoiceNotification({
  contact: { number: "34666033135" },
  template: "appointment_confirmation_voice",
  variables: {
    name: "Mario",
    date: "domani",
    time: "10:00"
  },
  voice: "it-IT-Wavenet-A"
});
```

### Parametri Richiesti

| Parametro        | Tipo   | Descrizione                                | Esempio                    |
| ---------------- | ------ | ------------------------------------------ | -------------------------- |
| `contact.number` | string | Numero telefono destinatario (solo numeri) | `"34666033135"`            |
| `message`        | string | Testo da convertire in voce                | `"Il tuo ordine è pronto"` |
| `voice`          | string | Identificatore voce da utilizzare          | `"it-IT-Standard-A"`       |
| `language`       | string | Codice lingua BCP-47                       | `"it-IT"`                  |

## 🎵 Configurazione Voce

### Voci Disponibili

**Italiano:**

* `it-IT-Standard-A` (Femminile, standard)
* `it-IT-Standard-B` (Maschile, standard)
* `it-IT-Wavenet-A` (Femminile, alta qualità)
* `it-IT-Wavenet-B` (Maschile, alta qualità)
* `it-IT-Neural2-A` (Femminile, neurale)
* `it-IT-Neural2-B` (Maschile, neurale)

**Altre Lingue:**

* `es-ES-Standard-A` (Spagnolo)
* `fr-FR-Standard-A` (Francese)
* `de-DE-Standard-A` (Tedesco)
* `en-GB-Standard-A` (Inglese britannico)
* `en-US-Standard-A` (Inglese americano)

### Configurazioni Avanzate

**Personalizzazione Voce:**

```javascript theme={null}
await loviService.sendVoiceNotification({
  contact: { number: "34666033135" },
  message: "Benvenuto nel nostro servizio clienti",
  voice_config: {
    voice: "it-IT-Wavenet-A",
    speaking_rate: 1.0,     // Velocità: 0.25 - 4.0
    pitch: 0.0,            // Tono: -20.0 - 20.0
    volume_gain_db: 0.0    // Volume: -96.0 - 16.0
  }
});
```

## 📋 Template Vocali

### Creazione Template Vocale

**Template Semplice:**

```json theme={null}
{
  "name": "order_ready_voice",
  "language": "it-IT",
  "content": "Ciao {{name}}, il tuo ordine numero {{order_id}} è pronto per il ritiro presso {{store_location}}",
  "voice": "it-IT-Standard-A",
  "variables": ["name", "order_id", "store_location"]
}
```

**Template con Pause e Intonazione:**

```json theme={null}
{
  "name": "appointment_reminder_voice",
  "language": "it-IT", 
  "content": "Promemoria appuntamento. <break time=\"500ms\"/> Ciao {{name}}. <break time=\"300ms\"/> Il tuo appuntamento con {{doctor}} è previsto per {{date}} alle {{time}}. <break time=\"500ms\"/> Ti aspettiamo presso {{clinic}}.",
  "voice": "it-IT-Wavenet-A",
  "variables": ["name", "doctor", "date", "time", "clinic"]
}
```

### Utilizzo Template Vocali

**Invio con Template:**

```javascript theme={null}
await loviService.sendVoiceNotification({
  contact: { number: "34666033135" },
  template: "appointment_reminder_voice",
  variables: {
    name: "Mario Rossi",
    doctor: "Dott. Bianchi",
    date: "15 dicembre",
    time: "10:30",
    clinic: "Clinica Centrale"
  }
});
```

## ⏰ Programmazione Notifiche Vocali

### Invio Programmato

**Programmazione Semplice:**

```javascript theme={null}
await loviService.scheduleVoiceNotification({
  contact: { number: "34666033135" },
  message: "Promemoria: appuntamento domani alle 9:00",
  datetime_sending: "2024-12-24T20:00:00Z", // Sera prima
  voice: "it-IT-Standard-A"
});
```

**Programmazione Ricorrente:**

```javascript theme={null}
await loviService.scheduleVoiceNotification({
  contact: { number: "34666033135" },
  template: "daily_medication_reminder",
  schedule: {
    type: "recurring",
    frequency: "daily",
    start_date: "2024-01-01T08:00:00Z",
    end_date: "2024-01-31T08:00:00Z",
    days_of_week: [1,2,3,4,5] // Lun-Ven
  },
  variables: {
    name: "Mario",
    medication: "insulina",
    dosage: "10 unità"
  }
});
```

## 📞 Gestione Chiamate

### Stati Chiamata

| Stato       | Descrizione                      |
| ----------- | -------------------------------- |
| `queued`    | In coda per l'invio              |
| `ringing`   | Squillando                       |
| `answered`  | Risposta dal destinatario        |
| `completed` | Chiamata completata con successo |
| `busy`      | Linea occupata                   |
| `no_answer` | Nessuna risposta                 |
| `failed`    | Chiamata fallita                 |

### Monitoraggio Chiamate

**Stato Chiamata:**

```javascript theme={null}
const callStatus = await loviService.getVoiceCallStatus(callId);
// Risultato: { status: "completed", duration: 25, cost: 0.05 }
```

**Report Chiamate:**

```javascript theme={null}
const report = await loviService.getVoiceCallReport({
  start_date: "2024-12-01",
  end_date: "2024-12-31",
  status: "completed"
});
// Risultato: statistiche di chiamate completate
```

## 🎯 Casi d'Uso

### Assistenza Sanitaria

**Promemoria Appuntamenti Medici:**

```javascript theme={null}
async function scheduleMedicalReminders(appointments) {
  for (const appointment of appointments) {
    // Chiamata 24 ore prima
    await loviService.scheduleVoiceNotification({
      contact: { number: appointment.patient_phone },
      template: "medical_appointment_reminder",
      datetime_sending: calculateReminderTime(appointment.datetime, -24),
      variables: {
        name: appointment.patient_name,
        doctor: appointment.doctor_name,
        specialty: appointment.specialty,
        date: formatDate(appointment.datetime),
        time: formatTime(appointment.datetime),
        location: appointment.clinic_address
      }
    });
    
    // SMS follow-up se chiamata non risponde
    await loviService.scheduleNotification({
      contact: { number: appointment.patient_phone },
      template: "appointment_reminder_sms",
      datetime_sending: calculateReminderTime(appointment.datetime, -2),
      variables: { /* stesse variabili */ }
    });
  }
}
```

### E-commerce

**Conferma Ordini:**

```javascript theme={null}
async function sendOrderVoiceConfirmation(order) {
  await loviService.sendVoiceNotification({
    contact: { number: order.customer_phone },
    template: "order_voice_confirmation",
    variables: {
      name: order.customer_name,
      order_number: order.id,
      total: formatCurrency(order.total),
      delivery_date: formatDate(order.delivery_date),
      items: order.items.map(item => item.name).join(", ")
    }
  });
}
```

### Servizi di Emergenza

**Allerte di Sicurezza:**

```javascript theme={null}
async function sendEmergencyAlert(emergency) {
  const contacts = await getAffectedContacts(emergency.area);
  
  for (const contact of contacts) {
    await loviService.sendVoiceNotification({
      contact: { number: contact.phone },
      message: `Allerta di emergenza. ${emergency.message}. Si prega di seguire le istruzioni delle autorità locali.`,
      voice: "it-IT-Neural2-A", // Voce chiara e autorevole
      priority: "high",
      retry_on_failure: true,
      max_attempts: 5
    });
  }
}
```

## ⚙️ Configurazioni Avanzate

### Interattività

**Chiamate Interattive:**

```javascript theme={null}
await loviService.sendInteractiveVoiceNotification({
  contact: { number: "34666033135" },
  script: [
    {
      type: "speak",
      text: "Premi 1 per confermare, 2 per riprogrammare, 3 per cancellare"
    },
    {
      type: "gather",
      num_digits: 1,
      timeout: 10,
      on_gather: {
        "1": { action: "confirm_appointment" },
        "2": { action: "reschedule_appointment" },
        "3": { action: "cancel_appointment" }
      }
    }
  ]
});
```

### Callback e Webhook

**Configurazione Callback:**

```javascript theme={null}
await loviService.sendVoiceNotification({
  contact: { number: "34666033135" },
  message: "Conferma appuntamento",
  webhook: {
    url: "https://api.myapp.com/voice-callback",
    events: ["answered", "completed", "failed"],
    method: "POST"
  }
});
```

## 📊 Analisi e Ottimizzazione

### Metriche Vocali

**Statistiche Performance:**

```javascript theme={null}
const voiceStats = await loviService.getVoiceStatistics({
  start_date: "2024-12-01",
  end_date: "2024-12-31"
});

// Risultato:
// {
//   "total_calls": 1250,
//   "answered_calls": 980,
//   "average_duration": 24,
//   "answer_rate": 78.4,
//   "cost_per_call": 0.08
// }
```

### Ottimizzazione Qualità

**Test Qualità Voce:**

```javascript theme={null}
const qualityTest = await loviService.testVoiceQuality({
  message: "Questo è un test di qualità vocale",
  voices: ["it-IT-Standard-A", "it-IT-Wavenet-A", "it-IT-Neural2-A"],
  language: "it-IT"
});

// Risultato: confronto qualità e preferenze
```

## 🚨 Limitazioni e Sicurezza

### Limitazioni Tecniche

* **Lunghezza Messaggio**: Max 5000 caratteri
* **Durata Chiamata**: Max 10 minuti
* **Rate di Chiamata**: 10 chiamate simultanee per account
* **Numeri Supportati**: Solo numeri verificati

### Considerazioni di Sicurezza

**Privacy Dati:**

```javascript theme={null}
// Assicurati che i dati vocali siano criptati
const encryptedMessage = encryptSensitiveData(message);

// Utilizza HTTPS per i webhook
const webhookConfig = {
  url: "https://secure-api.myapp.com/voice-webhook",
  headers: {
    "Authorization": `Bearer ${secureToken}`,
    "Content-Type": "application/json"
  }
};
```

**Conformità GDPR:**

* Ottieni consenso esplicito prima delle chiamate
* Fornisci opt-out chiaro
* Registra tutte le interazioni vocali
* Elimina registrazioni dopo il periodo di retention

### Best Practice

**Ottimizzazione Script Vocali:**

```javascript theme={null}
// ✅ Script efficace
"Ciao Mario. Il tuo appuntamento è confermato per domani alle 10:00 presso la Clinica Centrale. Ti aspettiamo. Grazie."

// ❌ Script da evitare
"Ehm, uh, ciao, questo è un messaggio automatico della Clinica Centrale per ricordarti che hai un appuntamento domani alle dieci in punto, quindi se puoi venire sarebbe bello, grazie e arrivederci."
```

**Gestione Errori:**

```javascript theme={null}
try {
  await loviService.sendVoiceNotification(voiceData);
} catch (error) {
  if (error.code === 'INVALID_PHONE_NUMBER') {
    await logInvalidNumber(voiceData.contact.number);
  } else if (error.code === 'VOICE_SYNTHESIS_FAILED') {
    await fallbackToTextMessage(voiceData);
  }
}
```

Le notifiche vocali offrono un canale alternativo efficace quando WhatsApp non è sufficiente. Utilizzale strategicamente per migliorare l'esperienza cliente e l'efficacia delle comunicazioni.
