ProcessAsaasWebhookJob.php 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace App\Jobs;
  3. use App\Enums\ReceivableStatus;
  4. use App\Models\FranchiseeAccountReceive;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. use Illuminate\Support\Facades\Log;
  11. class ProcessAsaasWebhookJob implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. private const EVENT_STATUS_MAP = [
  15. 'PAYMENT_RECEIVED' => ReceivableStatus::PAID,
  16. 'PAYMENT_CONFIRMED' => ReceivableStatus::PAID,
  17. 'PAYMENT_OVERDUE' => ReceivableStatus::OVERDUE,
  18. 'PAYMENT_DELETED' => ReceivableStatus::CANCELLED,
  19. 'PAYMENT_REFUNDED' => ReceivableStatus::CANCELLED,
  20. ];
  21. public array $payload;
  22. public function __construct(array $payload)
  23. {
  24. $this->payload = $payload;
  25. }
  26. public function handle(): void
  27. {
  28. $event = $this->payload['event'] ?? null;
  29. $payment = $this->payload['payment'] ?? [];
  30. if (!$event || empty($payment)) {
  31. Log::warning('Asaas Webhook Job: payload incompleto', $this->payload);
  32. return;
  33. }
  34. $newStatus = self::EVENT_STATUS_MAP[$event] ?? null;
  35. if (!$newStatus) {
  36. Log::info("Asaas Webhook Job: evento '{$event}' ignorado (não mapeado).");
  37. return;
  38. }
  39. $externalReference = $payment['externalReference'] ?? null;
  40. $asaasId = $payment['id'] ?? null;
  41. $receive = null;
  42. $type = 'unknown';
  43. if ($externalReference) {
  44. // Recebível de Franquia (TBR) cobrado pela conta da Matriz.
  45. if (str_starts_with($externalReference, 'TBR_')) {
  46. $id = str_replace('TBR_', '', $externalReference);
  47. $receive = FranchiseeAccountReceive::find($id);
  48. $type = 'FranchiseeAccountReceive';
  49. }
  50. // Backward compatibility para faturas de teste geradas antes do prefixo
  51. elseif (is_numeric($externalReference)) {
  52. $receive = FranchiseeAccountReceive::find($externalReference);
  53. $type = 'FranchiseeAccountReceive (legacy)';
  54. }
  55. }
  56. // Fallback por asaas_id caso externalReference venha nulo
  57. if (!$receive && $asaasId) {
  58. $receive = FranchiseeAccountReceive::where('asaas_id', $asaasId)->first();
  59. if ($receive) {
  60. $type = 'FranchiseeAccountReceive (by asaas_id)';
  61. }
  62. }
  63. if (!$receive) {
  64. Log::warning("Asaas Webhook Job: registro não encontrado", [
  65. 'externalReference' => $externalReference,
  66. 'asaas_id' => $asaasId,
  67. 'event' => $event,
  68. ]);
  69. return;
  70. }
  71. // Comparação segura de status (a model pode expor enum ou string).
  72. $currentStatus = $receive->status instanceof ReceivableStatus ? $receive->status->value : $receive->status;
  73. $newStatusValue = $newStatus instanceof ReceivableStatus ? $newStatus->value : $newStatus;
  74. // Idempotência
  75. if ($currentStatus === ReceivableStatus::PAID->value && $newStatusValue === ReceivableStatus::PAID->value) {
  76. Log::info("Asaas Webhook Job: registro {$type} #{$receive->id} já está pago. Ignorando duplicata.");
  77. return;
  78. }
  79. $updateData = [
  80. 'status' => $newStatusValue,
  81. 'asaas_status' => $payment['status'] ?? $event,
  82. ];
  83. if ($newStatusValue === ReceivableStatus::PAID->value) {
  84. $updateData['payment_date'] = $payment['paymentDate'] ?? $payment['confirmedDate'] ?? now();
  85. $updateData['paid_value'] = $payment['value'] ?? $receive->value;
  86. }
  87. $receive->update($updateData);
  88. Log::info("Asaas Webhook Job: {$type} #{$receive->id} atualizado para '{$newStatusValue}'", [
  89. 'event' => $event,
  90. 'asaas_id' => $asaasId,
  91. ]);
  92. }
  93. }