SyncFranchiseeChargeJob.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // Asaas é opcional: se a matriz não tiver chave configurada, o recebível
  31. // segue como 'pending' para baixa manual — nenhuma cobrança é emitida.
  32. if (empty(config('services.asaas.api_key'))) {
  33. Log::info("Asaas não configurado na matriz. Recebível #{$this->receive->id} seguirá para baixa manual.");
  34. return;
  35. }
  36. // Garantir que a Unidade é um Customer na conta-mãe do Asaas
  37. $unit = $this->receive->unit;
  38. if (!$unit) {
  39. Log::error("Recebível #{$this->receive->id} sem Unidade vinculada. Abortando integração.");
  40. return;
  41. }
  42. try {
  43. $asaasCustomerId = $customerService->ensureFranchiseeCustomer($unit);
  44. $this->receive->update(['asaas_customer_id' => $asaasCustomerId]);
  45. // Gerar a cobrança no Asaas
  46. $payload = [
  47. 'customer' => $asaasCustomerId,
  48. 'billingType' => 'UNDEFINED', // Deixa o pagador escolher PIX/Boleto
  49. 'value' => (float) $this->receive->value,
  50. 'dueDate' => $this->receive->due_date->format('Y-m-d'),
  51. 'description' => $this->receive->history ?? 'Cobrança Ginástica do Cérebro (TBR)',
  52. 'externalReference' => "TBR_{$this->receive->id}",
  53. ];
  54. $response = $client->post('/payments', $payload);
  55. // Atualiza o banco com o link do boleto
  56. $this->receive->update([
  57. 'asaas_id' => $response['id'],
  58. 'invoice_url' => $response['invoiceUrl'],
  59. 'billing_type' => $response['billingType'] ?? 'UNDEFINED',
  60. 'status' => ReceivableStatus::AWAITING_PAYMENT,
  61. 'asaas_status' => $response['status'],
  62. ]);
  63. Log::info("Cobrança do Asaas gerada com sucesso para Recebível #{$this->receive->id}");
  64. } catch (Exception $e) {
  65. Log::error("Erro ao gerar cobrança no Asaas para Recebível #{$this->receive->id}: " . $e->getMessage());
  66. throw $e; // Re-joga a exceção para que o Job tente novamente depois
  67. }
  68. }
  69. }