| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- namespace App\Jobs;
- use App\Enums\ReceivableStatus;
- use App\Models\FranchiseeAccountReceive;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use Illuminate\Support\Facades\Log;
- class ProcessAsaasWebhookJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- private const EVENT_STATUS_MAP = [
- 'PAYMENT_RECEIVED' => ReceivableStatus::PAID,
- 'PAYMENT_CONFIRMED' => ReceivableStatus::PAID,
- 'PAYMENT_OVERDUE' => ReceivableStatus::OVERDUE,
- 'PAYMENT_DELETED' => ReceivableStatus::CANCELLED,
- 'PAYMENT_REFUNDED' => ReceivableStatus::CANCELLED,
- ];
- public array $payload;
- public function __construct(array $payload)
- {
- $this->payload = $payload;
- }
- public function handle(): void
- {
- $event = $this->payload['event'] ?? null;
- $payment = $this->payload['payment'] ?? [];
- if (!$event || empty($payment)) {
- Log::warning('Asaas Webhook Job: payload incompleto', $this->payload);
- return;
- }
- $newStatus = self::EVENT_STATUS_MAP[$event] ?? null;
- if (!$newStatus) {
- Log::info("Asaas Webhook Job: evento '{$event}' ignorado (não mapeado).");
- return;
- }
- $externalReference = $payment['externalReference'] ?? null;
- $asaasId = $payment['id'] ?? null;
- $receive = null;
- if ($externalReference) {
- $receive = FranchiseeAccountReceive::find($externalReference);
- }
- if (!$receive && $asaasId) {
- $receive = FranchiseeAccountReceive::where('asaas_id', $asaasId)->first();
- }
- if (!$receive) {
- Log::warning("Asaas Webhook Job: recebível não encontrado", [
- 'externalReference' => $externalReference,
- 'asaas_id' => $asaasId,
- 'event' => $event,
- ]);
- return;
- }
- // Se já está pago, não processa de novo
- if ($receive->status === ReceivableStatus::PAID && $newStatus === ReceivableStatus::PAID) {
- Log::info("Asaas Webhook Job: recebível #{$receive->id} já está pago. Ignorando duplicata.");
- return;
- }
- // Atualizar o status
- $updateData = [
- 'status' => $newStatus,
- 'asaas_status' => $payment['status'] ?? $event,
- ];
- // Se foi pago, registrar a data de pagamento e o valor pago
- if ($newStatus === ReceivableStatus::PAID) {
- $updateData['payment_date'] = $payment['paymentDate'] ?? $payment['confirmedDate'] ?? now();
- $updateData['paid_value'] = $payment['value'] ?? $receive->value;
- }
- $receive->update($updateData);
- Log::info("Asaas Webhook Job: recebível #{$receive->id} atualizado para '{$newStatus->value}'", [
- 'event' => $event,
- 'asaas_id' => $asaasId,
- ]);
- }
- }
|