Files
Sistema-Educativo-Laravel/app/Jobs/EnviarPromocionJob.php
fernando 61b18df8e8 feat: WhatsApp promociones — fechas en español, status webhook y analytics inspector
- Corrige formato de fechas a español con Carbon isoFormat('D [de] MMMM')
- Webhook procesa statuses de Meta (delivered/read/failed) y actualiza pivot alumno_promocion
- Analytics: nuevas métricas de entregados/leídos, embudo de entrega, filtro por tipo
- Inspector de payload raw por log con modal y botón copiar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 15:42:26 -06:00

86 lines
2.6 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\Alumno;
use App\Models\Promocion;
use App\Models\WhatsappLog;
use App\Services\WhatsAppService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class EnviarPromocionJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 60;
public function __construct(
public Promocion $promocion,
public Alumno $alumno
) {}
public function handle(WhatsAppService $whatsapp): void
{
$this->alumno->refresh();
if ($this->alumno->opt_out) {
return;
}
$telefono = $this->alumno->telefonoWhatsapp();
if (!$telefono) {
WhatsappLog::create([
'alumno_id' => $this->alumno->id,
'telefono' => 'sin_telefono',
'tipo' => 'error',
'mensaje' => 'Alumno sin teléfono registrado',
'payload' => ['promocion_id' => $this->promocion->id],
]);
$this->actualizarPivot('fallido', null);
return;
}
try {
$nombre = $this->alumno->alumnos()->first()?->name ?? 'estudiante';
$mensajeId = $whatsapp->enviarPromocion($telefono, $this->promocion, $nombre);
} catch (\RuntimeException $e) {
WhatsappLog::create([
'alumno_id' => $this->alumno->id,
'telefono' => $telefono,
'tipo' => 'error',
'mensaje' => $e->getMessage(),
'payload' => ['promocion_id' => $this->promocion->id],
]);
$this->actualizarPivot('fallido', null);
return;
}
WhatsappLog::create([
'alumno_id' => $this->alumno->id,
'telefono' => $telefono,
'tipo' => 'enviado',
'mensaje' => $this->promocion->titulo,
'payload' => ['promocion_id' => $this->promocion->id, 'whatsapp_id' => $mensajeId],
]);
$this->actualizarPivot('enviado', $mensajeId);
}
private function actualizarPivot(string $status, ?string $mensajeId): void
{
$this->promocion->alumnos()->updateExistingPivot($this->alumno->id, [
'status_envio' => $status,
'enviado_at' => now(),
'whatsapp_mensaje_id' => $mensajeId,
]);
}
}