CreateAsaasSubaccountJob.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Jobs;
  3. use App\Exceptions\AsaasException;
  4. use App\Models\Unit;
  5. use App\Services\Integrations\Asaas\AsaasAccountService;
  6. use Exception;
  7. use Illuminate\Bus\Queueable;
  8. use Illuminate\Contracts\Queue\ShouldQueue;
  9. use Illuminate\Foundation\Bus\Dispatchable;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. use Illuminate\Queue\Middleware\WithoutOverlapping;
  12. use Illuminate\Queue\SerializesModels;
  13. use Illuminate\Support\Facades\Log;
  14. class CreateAsaasSubaccountJob implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public int $unitId;
  18. public int $tries = 3;
  19. public function __construct(int $unitId)
  20. {
  21. $this->unitId = $unitId;
  22. }
  23. /**
  24. * Serializa os jobs por unidade: evita que duas execuções concorrentes
  25. * criem a subconta ao mesmo tempo (o POST /accounts do Asaas não é idempotente).
  26. */
  27. public function middleware(): array
  28. {
  29. return [(new WithoutOverlapping($this->unitId))->releaseAfter(10)->expireAfter(60)];
  30. }
  31. public function handle(AsaasAccountService $accountService): void
  32. {
  33. $unit = Unit::find($this->unitId);
  34. if (!$unit) {
  35. Log::warning("CreateAsaasSubaccountJob: Unidade {$this->unitId} não encontrada.");
  36. return;
  37. }
  38. try {
  39. $accountService->ensureSubaccount($unit);
  40. Log::info("CreateAsaasSubaccountJob: Subconta criada com sucesso para a Unidade {$unit->id}.");
  41. } catch (AsaasException $e) {
  42. // Erros 4xx (ex.: e-mail/CNPJ já em uso) são permanentes: retentar só
  43. // recriaria a colisão. Falha imediatamente, sem consumir as outras tentativas.
  44. if ($e->getCode() >= 400 && $e->getCode() < 500) {
  45. Log::error("CreateAsaasSubaccountJob: Erro permanente do Asaas para Unidade {$unit->id} — sem retry.", [
  46. 'error' => $e->getMessage(),
  47. ]);
  48. $this->fail($e);
  49. return;
  50. }
  51. // 5xx / instabilidade: deixa o mecanismo de retry agir.
  52. Log::error("CreateAsaasSubaccountJob: Falha transitória para Unidade {$unit->id}.", [
  53. 'error' => $e->getMessage(),
  54. ]);
  55. throw $e;
  56. } catch (Exception $e) {
  57. Log::error("CreateAsaasSubaccountJob: Falha ao criar subconta para Unidade {$unit->id}.", [
  58. 'error' => $e->getMessage(),
  59. ]);
  60. throw $e;
  61. }
  62. }
  63. }