receive = $receive; } /** * Execute the job. */ public function handle(AsaasClient $client, AsaasCustomerService $customerService): void { // 1. 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]); // 2. 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' => (string) $this->receive->id, // Para conciliarmos no webhook depois ]; $response = $client->post('/payments', $payload); // 3. 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 } } }