> ## 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.

# Programmazione Notifiche

> Guida completa per programmare e gestire l'invio programmato di notifiche

## Introduzione

La funzionalità di programmazione permette di pianificare l'invio di notifiche WhatsApp per momenti specifici nel futuro. Questa guida copre tutti gli aspetti della programmazione, dalla creazione alla gestione delle notifiche programmate.

## ⏰ Programmazione Base

### Invio Immediato vs Programmato

**Invio Immediato:**

```javascript theme={null}
await loviService.sendNotification({
  contact: { number: "34666033135" },
  template: "welcome_user"
});
// Inviato immediatamente
```

**Invio Programmato:**

```javascript theme={null}
await loviService.sendNotification({
  contact: { number: "34666033135" },
  template: "welcome_user",
  datetime_sending: "2024-12-25T09:00:00Z"
});
// Programmato per Natale alle 9:00 UTC
```

### Formati Data/Ora

**Formati Supportati:**

```javascript theme={null}
// ISO 8601 (Raccomandato)
"2024-12-25T09:00:00Z"
"2024-12-25T09:00:00+01:00"
"2024-12-25T09:00:00"

// Formato Europeo (Accettato)
"25-12-2024 09:00:00"

// Timestamp Unix
1703492400
```

**Conversioni Comuni:**

```javascript theme={null}
// JavaScript
const christmas = new Date("2024-12-25T09:00:00Z");
const timestamp = christmas.getTime();

// Python
from datetime import datetime
christmas = datetime(2024, 12, 25, 9, 0, 0)
timestamp = christmas.timestamp()

// PHP
$christmas = new DateTime("2024-12-25T09:00:00Z");
$timestamp = $christmas->getTimestamp();
```

## 📅 Gestione Programmazioni

### Creazione Programmazione

**Programmazione Semplice:**

```javascript theme={null}
const result = await loviService.scheduleNotification({
  contact: { number: "34666033135" },
  template: "appointment_reminder",
  datetime_sending: "2024-12-25T09:00:00Z",
  variables: {
    name: "Mario",
    date: "25 dicembre",
    time: "10:00"
  }
});

console.log(result.notification_id); // ID per riferimento futuro
```

**Programmazione Ricorrente:**

```javascript theme={null}
// Promemoria settimanale
const weeklyReminder = {
  contact: { number: "34666033135" },
  template: "weekly_update",
  schedule: {
    type: "recurring",
    frequency: "weekly", // daily, weekly, monthly
    start_date: "2024-01-01T09:00:00Z",
    end_date: "2024-12-31T09:00:00Z",
    days_of_week: [1, 3, 5] // Lunedì, mercoledì, venerdì
  }
};
```

### Recupero Programmazioni

**Lista Programmazioni:**

```javascript theme={null}
const schedules = await loviService.getScheduledNotifications({
  status: "pending", // pending, sent, cancelled
  limit: 50,
  offset: 0
});
```

**Programmazione per ID:**

```javascript theme={null}
const schedule = await loviService.getScheduledNotification(notificationId);
```

### Modifica Programmazioni

**Aggiorna Orario:**

```javascript theme={null}
await loviService.updateScheduledNotification(notificationId, {
  datetime_sending: "2024-12-25T10:00:00Z" // Cambia orario
});
```

**Aggiorna Contenuto:**

```javascript theme={null}
await loviService.updateScheduledNotification(notificationId, {
  variables: {
    name: "Mario Rossi", // Nuovo nome
    date: "26 dicembre"  // Nuova data
  }
});
```

### Cancellazione Programmazioni

**Cancella Singola:**

```javascript theme={null}
await loviService.cancelScheduledNotification(notificationId);
```

**Cancella Multiple:**

```javascript theme={null}
await loviService.cancelScheduledNotifications({
  contact_number: "34666033135",
  template: "appointment_reminder"
});
```

## 📊 Stati e Ciclo di Vita

### Stati Programmazione

| Stato        | Descrizione                      |
| ------------ | -------------------------------- |
| `scheduled`  | Programmata e in attesa di invio |
| `processing` | In elaborazione per l'invio      |
| `sent`       | Inviata con successo             |
| `failed`     | Invio fallito                    |
| `cancelled`  | Cancellata dall'utente           |

### Transizioni Stato

```mermaid theme={null}
graph TD
    A[scheduled] --> B[processing]
    B --> C[sent]
    B --> D[failed]
    A --> E[cancelled]
    D --> F[retry_scheduled]
    F --> B
```

### Gestione Errori

**Riproduzione Automatica:**

```javascript theme={null}
// Configurazione retry per fallimenti
const schedule = await loviService.scheduleNotification({
  contact: { number: "34666033135" },
  template: "important_alert",
  datetime_sending: "2024-12-25T09:00:00Z",
  retry_policy: {
    max_attempts: 3,
    retry_interval: 3600, // 1 ora
    backoff_multiplier: 2   // Backoff esponenziale
  }
});
```

## 🎯 Casi d'Uso Avanzati

### Campagne Marketing

**Programmazione Campagna:**

```javascript theme={null}
async function scheduleHolidayCampaign() {
  const contacts = await getCustomerSegment("active_customers");
  const sendTimes = [
    "2024-12-01T10:00:00Z", // Inizio campagna
    "2024-12-15T10:00:00Z", // Metà dicembre  
    "2024-12-24T10:00:00Z"  // Vigilia Natale
  ];
  
  for (const contact of contacts) {
    for (const sendTime of sendTimes) {
      await loviService.scheduleNotification({
        contact: { number: contact.phone },
        template: "holiday_offer",
        datetime_sending: sendTime,
        variables: {
          name: contact.name,
          discount: "20%",
          expiry: "31 dicembre"
        }
      });
    }
  }
}
```

### Promemoria Appuntamenti

**Sistema Promemoria:**

```javascript theme={null}
async function scheduleAppointmentReminders(appointment) {
  const reminders = [
    { template: "24h_reminder", hours: 24 },
    { template: "2h_reminder", hours: 2 },
    { template: "15m_reminder", minutes: 15 }
  ];
  
  for (const reminder of reminders) {
    const reminderTime = calculateReminderTime(appointment.datetime, reminder);
    
    await loviService.scheduleNotification({
      contact: { number: appointment.customer_phone },
      template: reminder.template,
      datetime_sending: reminderTime,
      variables: {
        name: appointment.customer_name,
        service: appointment.service,
        date: formatDate(appointment.datetime),
        time: formatTime(appointment.datetime),
        location: appointment.location
      }
    });
  }
}
```

### Notifiche Batch

**Programmazione Bulk:**

```javascript theme={null}
async function scheduleBulkNotifications(notifications, batchSize = 100) {
  const batches = chunkArray(notifications, batchSize);
  
  for (let i = 0; i < batches.length; i++) {
    const batch = batches[i];
    const baseTime = new Date("2024-12-25T09:00:00Z");
    const batchTime = new Date(baseTime.getTime() + i * 60000); // +1 minuto per batch
    
    const schedulePromises = batch.map(notification =>
      loviService.scheduleNotification({
        ...notification,
        datetime_sending: batchTime.toISOString()
      })
    );
    
    await Promise.all(schedulePromises);
    
    // Pausa tra batch per evitare limiti di tariffa
    if (i < batches.length - 1) {
      await sleep(1000);
    }
  }
}
```

## ⚙️ Configurazioni Avanzate

### Fusi Orari

**Gestione Fuso Orario:**

```javascript theme={null}
// Invio nel fuso orario del destinatario
await loviService.scheduleNotification({
  contact: { 
    number: "34666033135",
    timezone: "Europe/Rome" // Fuso orario italiano
  },
  template: "morning_greeting",
  datetime_sending: "2024-12-25T08:00:00", // 8:00 locale
  timezone_aware: true
});
```

### Condizioni di Invio

**Invio Condizionale:**

```javascript theme={null}
await loviService.scheduleNotification({
  contact: { number: "34666033135" },
  template: "weather_alert",
  datetime_sending: "2024-12-25T06:00:00Z",
  conditions: {
    weather: "rain", // Invia solo se piove
    location: "Rome, Italy"
  }
});
```

### Priorità e Code

**Notifiche Prioritarie:**

```javascript theme={null}
await loviService.scheduleNotification({
  contact: { number: "34666033135" },
  template: "emergency_alert",
  datetime_sending: "2024-12-25T09:00:00Z",
  priority: "high", // high, normal, low
  queue: "emergency" // Coda specifica
});
```

## 📈 Monitoraggio e Analisi

### Metriche Programmazione

**Statistiche Invio:**

```javascript theme={null}
const stats = await loviService.getSchedulingStats({
  start_date: "2024-12-01",
  end_date: "2024-12-31",
  group_by: "day" // hour, day, week, month
});

// Risultato:
// {
//   "total_scheduled": 1250,
//   "total_sent": 1245,
//   "total_failed": 5,
//   "average_delay": 0.2, // minuti
//   "by_day": [...]
// }
```

### Report Consegnabilità

**Analisi Consegnabilità:**

```javascript theme={null}
const deliveryReport = await loviService.getDeliveryReport(notificationId);

// Risultato:
// {
//   "notification_id": "uuid-123",
//   "status": "sent",
//   "sent_at": "2024-12-25T09:00:15Z",
//   "delivered_at": "2024-12-25T09:00:20Z",
//   "read_at": "2024-12-25T09:05:30Z",
//   "delivery_status": "delivered",
//   "failure_reason": null
// }
```

## 🔧 Manutenzione Programmazioni

### Pulizia Programmazioni

**Rimuovi Programmazioni Scadute:**

```javascript theme={null}
await loviService.cleanupExpiredSchedules({
  older_than_days: 30,
  status: "sent"
});
```

### Archiviazione

**Archivia Vecchie Programmazioni:**

```javascript theme={null}
await loviService.archiveSchedules({
  date_before: "2024-01-01",
  status: ["sent", "failed"]
});
```

## 🚨 Limitazioni e Considerazioni

### Limiti Programmazione

* **Orario Massimo Futuro**: 90 giorni
* **Orario Minimo Futuro**: 5 minuti
* **Programmazioni Attive per Account**: 100.000
* **Rate Creazione**: 1000 programmazioni al minuto

### Best Practice

**Ottimizzazione Orari:**

```javascript theme={null}
// ✅ Buoni orari
"2024-12-25T09:00:00Z" // Orario lavorativo
"2024-12-25T19:00:00Z" // Sera

// ❌ Orari da evitare
"2024-12-25T03:00:00Z" // Notte fonda
"2024-12-25T12:00:00Z" // Ora pranzo
```

**Gestione Errori:**

```javascript theme={null}
try {
  await loviService.scheduleNotification(notificationData);
} catch (error) {
  if (error.code === 'INVALID_SCHEDULE_TIME') {
    // Suggerisci nuovo orario
    const suggestedTime = suggestValidTime(notificationData.datetime_sending);
    await loviService.scheduleNotification({
      ...notificationData,
      datetime_sending: suggestedTime
    });
  }
}
```

La programmazione è uno strumento potente per ottimizzare le comunicazioni WhatsApp. Utilizzala strategicamente per massimizzare l'impatto dei tuoi messaggi.
