installment = $installment; } public function handle(): void { $installment = $this->installment->fresh(['student']); if (!$installment || $installment->status === 'cancelled') { return; } if ($installment->asaas_id) { Log::info("Parcela #{$installment->id} já possui cobrança Asaas. Ignorando."); return; } $account = UnitPaymentAccount::where('unit_id', $installment->unit_id)->first(); if (!$account || empty($account->asaas_api_key)) { Log::info("Unidade {$installment->unit_id} sem Asaas. Parcela #{$installment->id} segue para baixa manual."); return; } $client = new AsaasClient($account->asaas_api_key); $customerService = new AsaasCustomerService($client); try { $customerId = $customerService->ensureStudentCustomer($installment->student); $response = $client->post('/payments', [ 'customer' => $customerId, 'billingType' => 'UNDEFINED', 'value' => (float) $installment->value, 'dueDate' => $installment->due_date->format('Y-m-d'), 'description' => trim(($installment->history ?? 'Mensalidade') . ' ' . $installment->order), 'externalReference' => "STU_{$installment->id}", ]); $installment->update([ 'asaas_customer_id' => $customerId, 'asaas_id' => $response['id'], 'invoice_url' => $response['invoiceUrl'] ?? null, 'billing_type' => $response['billingType'] ?? 'UNDEFINED', 'asaas_status' => $response['status'] ?? null, ]); Log::info("Cobrança Asaas gerada para parcela #{$installment->id}."); } catch (Exception $e) { Log::error("Erro ao gerar cobrança Asaas da parcela #{$installment->id}: " . $e->getMessage()); throw $e; } } }