Vai al contenuto principale

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:
await loviService.sendNotification({
  contact: { number: "34666033135" },
  template: "welcome_user"
});
// Inviato immediatamente
Invio Programmato:
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:
// 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
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:
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:
// 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:
const schedules = await loviService.getScheduledNotifications({
  status: "pending", // pending, sent, cancelled
  limit: 50,
  offset: 0
});
Programmazione per ID:
const schedule = await loviService.getScheduledNotification(notificationId);

Modifica Programmazioni

Aggiorna Orario:
await loviService.updateScheduledNotification(notificationId, {
  datetime_sending: "2024-12-25T10:00:00Z" // Cambia orario
});
Aggiorna Contenuto:
await loviService.updateScheduledNotification(notificationId, {
  variables: {
    name: "Mario Rossi", // Nuovo nome
    date: "26 dicembre"  // Nuova data
  }
});

Cancellazione Programmazioni

Cancella Singola:
await loviService.cancelScheduledNotification(notificationId);
Cancella Multiple:
await loviService.cancelScheduledNotifications({
  contact_number: "34666033135",
  template: "appointment_reminder"
});

📊 Stati e Ciclo di Vita

Stati Programmazione

StatoDescrizione
scheduledProgrammata e in attesa di invio
processingIn elaborazione per l’invio
sentInviata con successo
failedInvio fallito
cancelledCancellata dall’utente

Transizioni Stato

Gestione Errori

Riproduzione Automatica:
// 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:
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:
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:
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:
// 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:
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:
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:
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à:
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:
await loviService.cleanupExpiredSchedules({
  older_than_days: 30,
  status: "sent"
});

Archiviazione

Archivia Vecchie Programmazioni:
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:
// ✅ 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:
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.