| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace App\Jobs;
- use App\Models\StudentContractInstallment;
- use App\Models\UnitPaymentAccount;
- use App\Services\Integrations\Asaas\AsaasClient;
- use App\Services\Integrations\Asaas\AsaasCustomerService;
- use Exception;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use Illuminate\Support\Facades\Crypt;
- use Illuminate\Support\Facades\Log;
- class SyncStudentChargeJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public int $installmentId;
- public int $tries = 3;
- public function __construct(int $installmentId)
- {
- $this->installmentId = $installmentId;
- }
- public function handle(AsaasCustomerService $customerService): void
- {
- $installment = StudentContractInstallment::with(['student', 'unit', 'studentContract'])->find($this->installmentId);
- if (!$installment) {
- Log::warning("SyncStudentChargeJob: Parcela {$this->installmentId} não encontrada.");
- return;
- }
- if ($installment->asaas_id) {
- Log::info("SyncStudentChargeJob: Parcela {$installment->id} já possui asaas_id ({$installment->asaas_id}). Ignorando.");
- return;
- }
- if ($installment->value <= 0) {
- Log::info("SyncStudentChargeJob: Parcela {$installment->id} possui valor zerado. Ignorando Asaas.");
- return;
- }
- // Pegar a API Key da Subconta da Franquia
- $paymentAccount = UnitPaymentAccount::where('unit_id', $installment->unit_id)->first();
-
- if (!$paymentAccount || empty($paymentAccount->asaas_api_key)) {
- throw new Exception("Unidade {$installment->unit_id} não possui subconta Asaas ou API Key configurada.");
- }
- $apiKey = Crypt::decryptString($paymentAccount->asaas_api_key);
- // Garantir que o Aluno seja um Customer na subconta
- $asaasCustomerId = $customerService->ensureStudentCustomer($installment->student, $apiKey);
- $installment->update(['asaas_customer_id' => $asaasCustomerId]);
- // Criar a Cobrança no Asaas usando a apiKey da franquia
- $client = new AsaasClient($apiKey);
- $payload = [
- 'customer' => $asaasCustomerId,
- 'billingType' => 'UNDEFINED', // Deixa o aluno escolher PIX ou BOLETO
- 'value' => $installment->value,
- 'dueDate' => \Carbon\Carbon::parse($installment->due_date)->format('Y-m-d'),
- 'description' => "Mensalidade / {$installment->history} - {$installment->student->name}",
- // Prefixo crucial para o webhook identificar qual tabela procurar!
- 'externalReference' => "STU_{$installment->id}",
- 'postalService' => false,
- ];
- // Lidar com juros e multas padrão do Asaas ou do contrato se houver:
- // $payload['interest'] = ['value' => 1];
- // $payload['fine'] = ['value' => 2];
- try {
- $response = $client->post('/payments', $payload);
- // 4. Salvar as referências no nosso banco local
- $installment->update([
- 'asaas_id' => $response['id'],
- 'invoice_url' => $response['invoiceUrl'] ?? null,
- 'asaas_status' => $response['status'] ?? 'PENDING',
- 'billing_type' => $response['billingType'] ?? null,
- ]);
- Log::info("SyncStudentChargeJob: Cobrança criada no Asaas para a parcela {$installment->id} (Subconta da Unidade {$installment->unit_id}).");
- } catch (Exception $e) {
- Log::error("SyncStudentChargeJob: Erro ao criar cobrança no Asaas. " . $e->getMessage(), [
- 'installment_id' => $installment->id,
- 'payload' => $payload
- ]);
- throw $e;
- }
- }
- }
|