Przeglądaj źródła

refactor(asaas): stop dispatching student charges

Installments are still generated/calculated; Asaas billing returns with the Franchisee module (per-unit account).
ebagabee 1 miesiąc temu
rodzic
commit
30f86d20e8

+ 0 - 102
app/Jobs/SyncStudentChargeJob.php

@@ -1,102 +0,0 @@
-<?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;
-        }
-    }
-}

+ 2 - 9
app/Services/StudentContractService.php

@@ -129,16 +129,9 @@ private function generateInstallments(StudentContract $contract): void
         }
 
         if (!empty($rows)) {
+            // As parcelas são registradas/calculadas normalmente. A cobrança no Asaas
+            // da franquia será reintroduzida no módulo Franchisee (conta própria por unidade).
             StudentContractInstallment::insert($rows);
-
-            // Dispatch Asaas sync for the generated installments
-            $installments = StudentContractInstallment::where('student_contract_id', $contract->id)
-                ->where('status', 'pending')
-                ->get();
-
-            foreach ($installments as $installment) {
-                \App\Jobs\SyncStudentChargeJob::dispatch($installment->id);
-            }
         }
     }