| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- namespace App\Jobs;
- use App\Models\FranchiseeAccountReceive;
- use App\Enums\ReceivableStatus;
- use App\Services\Integrations\Asaas\AsaasClient;
- use App\Services\Integrations\Asaas\AsaasCustomerService;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use Exception;
- use Illuminate\Support\Facades\Log;
- class SyncFranchiseeChargeJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public $receive;
- /**
- * Create a new job instance.
- */
- public function __construct(FranchiseeAccountReceive $receive)
- {
- $this->receive = $receive;
- }
- /**
- * Execute the job.
- */
- public function handle(AsaasClient $client, AsaasCustomerService $customerService): void
- {
- // Asaas é opcional: se a matriz não tiver chave configurada, o recebível
- // segue como 'pending' para baixa manual — nenhuma cobrança é emitida.
- if (empty(config('services.asaas.api_key'))) {
- Log::info("Asaas não configurado na matriz. Recebível #{$this->receive->id} seguirá para baixa manual.");
- return;
- }
- // Garantir que a Unidade é um Customer na conta-mãe do Asaas
- $unit = $this->receive->unit;
- if (!$unit) {
- Log::error("Recebível #{$this->receive->id} sem Unidade vinculada. Abortando integração.");
- return;
- }
- try {
- $asaasCustomerId = $customerService->ensureFranchiseeCustomer($unit);
- $this->receive->update(['asaas_customer_id' => $asaasCustomerId]);
-
- // Gerar a cobrança no Asaas
- $payload = [
- 'customer' => $asaasCustomerId,
- 'billingType' => 'UNDEFINED', // Deixa o pagador escolher PIX/Boleto
- 'value' => (float) $this->receive->value,
- 'dueDate' => $this->receive->due_date->format('Y-m-d'),
- 'description' => $this->receive->history ?? 'Cobrança Ginástica do Cérebro (TBR)',
- 'externalReference' => "TBR_{$this->receive->id}",
- ];
- $response = $client->post('/payments', $payload);
- // Atualiza o banco com o link do boleto
- $this->receive->update([
- 'asaas_id' => $response['id'],
- 'invoice_url' => $response['invoiceUrl'],
- 'billing_type' => $response['billingType'] ?? 'UNDEFINED',
- 'status' => ReceivableStatus::AWAITING_PAYMENT,
- 'asaas_status' => $response['status'],
- ]);
- Log::info("Cobrança do Asaas gerada com sucesso para Recebível #{$this->receive->id}");
- } catch (Exception $e) {
- Log::error("Erro ao gerar cobrança no Asaas para Recebível #{$this->receive->id}: " . $e->getMessage());
- throw $e; // Re-joga a exceção para que o Job tente novamente depois
- }
- }
- }
|