SyncFranchiseeChargeJob.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\FranchiseeAccountReceive;
  4. use App\Enums\ReceivableStatus;
  5. use App\Services\Integrations\Asaas\AsaasClient;
  6. use App\Services\Integrations\Asaas\AsaasCustomerService;
  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\SerializesModels;
  12. use Exception;
  13. use Illuminate\Support\Facades\Log;
  14. class SyncFranchiseeChargeJob implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public $receive;
  18. /**
  19. * Create a new job instance.
  20. */
  21. public function __construct(FranchiseeAccountReceive $receive)
  22. {
  23. $this->receive = $receive;
  24. }
  25. /**
  26. * Execute the job.
  27. */
  28. public function handle(AsaasClient $client, AsaasCustomerService $customerService): void
  29. {
  30. // 1. Garantir que a Unidade é um Customer na conta-mãe do Asaas
  31. $unit = $this->receive->unit;
  32. if (!$unit) {
  33. Log::error("Recebível #{$this->receive->id} sem Unidade vinculada. Abortando integração.");
  34. return;
  35. }
  36. try {
  37. $asaasCustomerId = $customerService->ensureFranchiseeCustomer($unit);
  38. $this->receive->update(['asaas_customer_id' => $asaasCustomerId]);
  39. // 2. Gerar a cobrança no Asaas
  40. $payload = [
  41. 'customer' => $asaasCustomerId,
  42. 'billingType' => 'UNDEFINED', // Deixa o pagador escolher PIX/Boleto
  43. 'value' => (float) $this->receive->value,
  44. 'dueDate' => $this->receive->due_date->format('Y-m-d'),
  45. 'description' => $this->receive->history ?? 'Cobrança Ginástica do Cérebro (TBR)',
  46. 'externalReference' => (string) $this->receive->id, // Para conciliarmos no webhook depois
  47. ];
  48. $response = $client->post('/payments', $payload);
  49. // 3. Atualiza o banco com o link do boleto
  50. $this->receive->update([
  51. 'asaas_id' => $response['id'],
  52. 'invoice_url' => $response['invoiceUrl'],
  53. 'billing_type' => $response['billingType'] ?? 'UNDEFINED',
  54. 'status' => ReceivableStatus::AWAITING_PAYMENT,
  55. 'asaas_status' => $response['status'],
  56. ]);
  57. Log::info("Cobrança do Asaas gerada com sucesso para Recebível #{$this->receive->id}");
  58. } catch (Exception $e) {
  59. Log::error("Erro ao gerar cobrança no Asaas para Recebível #{$this->receive->id}: " . $e->getMessage());
  60. throw $e; // Re-joga a exceção para que o Job tente novamente depois
  61. }
  62. }
  63. }