Просмотр исходного кода

refactor(asaas): remove white-label subaccount code

Drops CreateAsaasSubaccountJob, AsaasAccountService, UnitPaymentAccount, the asaas-onboard endpoint/route and the Unit paymentAccount relation.
ebagabee 1 месяц назад
Родитель
Сommit
becc737884

+ 0 - 21
app/Http/Controllers/UnitController.php

@@ -82,25 +82,4 @@ public function selectList(): JsonResponse
 
 
         return $this->successResponse(payload: $items);
         return $this->successResponse(payload: $items);
     }
     }
-
-    public function onboardAsaas(int $id, \App\Services\Integrations\Asaas\AsaasAccountService $asaasService): JsonResponse
-    {
-        $unit = $this->service->findById($id);
-
-        try {
-            $account = $asaasService->ensureSubaccount($unit);
-            
-            return $this->successResponse(
-                payload: $account,
-                message: 'Subconta do Asaas ativada com sucesso.',
-                code: 200
-            );
-            
-        } catch (\Exception $e) {
-            return $this->errorResponse(
-                message: 'Falha ao ativar subconta: ' . $e->getMessage(),
-                code: 400
-            );
-        }
-    }
 }
 }

+ 0 - 73
app/Jobs/CreateAsaasSubaccountJob.php

@@ -1,73 +0,0 @@
-<?php
-
-namespace App\Jobs;
-
-use App\Exceptions\AsaasException;
-use App\Models\Unit;
-use App\Services\Integrations\Asaas\AsaasAccountService;
-use Exception;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\Middleware\WithoutOverlapping;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Log;
-
-class CreateAsaasSubaccountJob implements ShouldQueue
-{
-    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
-
-    public int $unitId;
-    public int $tries = 3;
-
-    public function __construct(int $unitId)
-    {
-        $this->unitId = $unitId;
-    }
-
-    /**
-     * Serializa os jobs por unidade: evita que duas execuções concorrentes
-     * criem a subconta ao mesmo tempo (o POST /accounts do Asaas não é idempotente).
-     */
-    public function middleware(): array
-    {
-        return [(new WithoutOverlapping($this->unitId))->releaseAfter(10)->expireAfter(60)];
-    }
-
-    public function handle(AsaasAccountService $accountService): void
-    {
-        $unit = Unit::find($this->unitId);
-
-        if (!$unit) {
-            Log::warning("CreateAsaasSubaccountJob: Unidade {$this->unitId} não encontrada.");
-            return;
-        }
-
-        try {
-            $accountService->ensureSubaccount($unit);
-            Log::info("CreateAsaasSubaccountJob: Subconta criada com sucesso para a Unidade {$unit->id}.");
-        } catch (AsaasException $e) {
-            // Erros 4xx (ex.: e-mail/CNPJ já em uso) são permanentes: retentar só
-            // recriaria a colisão. Falha imediatamente, sem consumir as outras tentativas.
-            if ($e->getCode() >= 400 && $e->getCode() < 500) {
-                Log::error("CreateAsaasSubaccountJob: Erro permanente do Asaas para Unidade {$unit->id} — sem retry.", [
-                    'error' => $e->getMessage(),
-                ]);
-                $this->fail($e);
-                return;
-            }
-
-            // 5xx / instabilidade: deixa o mecanismo de retry agir.
-            Log::error("CreateAsaasSubaccountJob: Falha transitória para Unidade {$unit->id}.", [
-                'error' => $e->getMessage(),
-            ]);
-            throw $e;
-        } catch (Exception $e) {
-            Log::error("CreateAsaasSubaccountJob: Falha ao criar subconta para Unidade {$unit->id}.", [
-                'error' => $e->getMessage(),
-            ]);
-            throw $e;
-        }
-    }
-}

+ 0 - 5
app/Models/Unit.php

@@ -104,9 +104,4 @@ public function groups(): BelongsToMany
     {
     {
         return $this->belongsToMany(Group::class, 'group_units');
         return $this->belongsToMany(Group::class, 'group_units');
     }
     }
-
-    public function paymentAccount(): \Illuminate\Database\Eloquent\Relations\HasOne
-    {
-        return $this->hasOne(UnitPaymentAccount::class, 'unit_id');
-    }
 }
 }

+ 0 - 26
app/Models/UnitPaymentAccount.php

@@ -1,26 +0,0 @@
-<?php
-
-namespace App\Models;
-
-use Illuminate\Database\Eloquent\Factories\HasFactory;
-use Illuminate\Database\Eloquent\Model;
-use Illuminate\Database\Eloquent\Relations\BelongsTo;
-
-class UnitPaymentAccount extends Model
-{
-    use HasFactory;
-
-    protected $table = 'unit_payment_accounts';
-
-    protected $guarded = ['id'];
-
-    protected $casts = [
-        'onboarded_at' => 'datetime',
-        'asaas_api_key' => 'encrypted', 
-    ];
-
-    public function unit(): BelongsTo
-    {
-        return $this->belongsTo(Unit::class);
-    }
-}

+ 0 - 101
app/Services/Integrations/Asaas/AsaasAccountService.php

@@ -1,101 +0,0 @@
-<?php
-
-namespace App\Services\Integrations\Asaas;
-
-use App\Exceptions\AsaasException;
-use App\Models\Unit;
-use App\Models\UnitPaymentAccount;
-use Exception;
-use Illuminate\Support\Facades\Log;
-
-class AsaasAccountService
-{
-    protected AsaasClient $client;
-
-    public function __construct(AsaasClient $client)
-    {
-        $this->client = $client;
-    }
-
-    public function ensureSubaccount(Unit $unit): UnitPaymentAccount
-    {
-        $existingAccount = UnitPaymentAccount::where('unit_id', $unit->id)->first();
-       
-        if ($existingAccount && $existingAccount->asaas_account_id) {
-            return $existingAccount;
-        }
-
-        if (empty($unit->cnpj)) {
-            throw new Exception("A unidade {$unit->fantasy_name} não possui um CNPJ cadastrado. O CNPJ é obrigatório para criar a subconta.");
-        }
-
-        // Garante a chave de criptografia ANTES de chamar o Asaas. Sem APP_KEY, o
-        // POST cria a subconta lá, mas o save local falha ao encriptar a apiKey
-        // (cast 'encrypted') -> subconta órfã: apiKey perdida e e-mail/CNPJ travados.
-        if (empty(config('app.key'))) {
-            throw new Exception("APP_KEY não configurada. Abortando antes de criar a subconta no Asaas para evitar conta órfã (Unidade {$unit->id}).");
-        }
-
-        $payload = [
-            'name' => $unit->fantasy_name ?? $unit->social_reason ?? 'Unidade Ginástica do Cérebro',
-            'email' => $unit->email,
-            'cpfCnpj' => preg_replace('/[^0-9]/', '', $unit->cnpj),
-            'mobilePhone' => preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? ''),
-            'address' => $unit->street,
-            'addressNumber' => $unit->address_number ?? 'S/N',
-            'province' => $unit->neighborhood,
-            'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code),
-            'companyType' => 'LIMITED',
-            'incomeValue' => 10000.00, // Renda/Faturamento exigido pelo Asaas
-        ];
-
-        try {
-            $response = $this->client->post('/accounts', $payload);
-        } catch (AsaasException $e) {
-            // Colisão de e-mail (400): diagnostica se a conta é SUA (órfã, recuperável
-            // só pelo painel) ou EXTERNA (e-mail em uso fora do seu parent -> trocar e-mail).
-            if ($e->getCode() === 400 && str_contains($e->getMessage(), 'já está em uso')) {
-                $this->logEmailCollision($unit);
-            }
-            throw $e;
-        }
-
-        return UnitPaymentAccount::updateOrCreate(
-            ['unit_id' => $unit->id],
-            [
-                'asaas_account_id' => $response['id'],
-                'asaas_wallet_id' => $response['walletId'],
-                // Cast 'encrypted' do model encripta no save; e SyncStudentChargeJob
-                // espera mais uma camada manual. Mantém o encryptString para casar.
-                'asaas_api_key' => \Illuminate\Support\Facades\Crypt::encryptString($response['apiKey']),
-                'status' => 'ACTIVE',
-                'onboarded_at' => now(),
-            ]
-        );
-    }
-
-    /**
-     * Loga, no erro de e-mail em uso, se a conta colidente pertence ao seu parent
-     * (subconta órfã) ou é externa — para acelerar o diagnóstico.
-     */
-    private function logEmailCollision(Unit $unit): void
-    {
-        try {
-            $accounts = $this->client->get('/accounts', ['email' => $unit->email])['data'] ?? [];
-
-            if (count($accounts) > 0) {
-                Log::warning("Asaas: e-mail {$unit->email} já é uma SUBCONTA SUA (órfã). Recuperável só pelo painel/encerramento.", [
-                    'unit_id' => $unit->id,
-                    'asaas_account_id' => $accounts[0]['id'] ?? null,
-                    'wallet_id' => $accounts[0]['walletId'] ?? null,
-                ]);
-            } else {
-                Log::warning("Asaas: e-mail {$unit->email} está em uso em conta EXTERNA (fora do seu parent). Cadastre a unidade com outro e-mail.", [
-                    'unit_id' => $unit->id,
-                ]);
-            }
-        } catch (\Throwable $t) {
-            // Diagnóstico é best-effort: nunca mascara o erro original do POST.
-        }
-    }
-}

+ 0 - 3
routes/authRoutes/unit.php

@@ -23,9 +23,6 @@
     Route::get('/{id}', 'show')
     Route::get('/{id}', 'show')
         ->middleware('permission:unit,view');
         ->middleware('permission:unit,view');
 
 
-    Route::post('/{id}/asaas-onboard', 'onboardAsaas')
-        ->middleware('permission:unit,edit');
-
     Route::put('/{id}', 'update')
     Route::put('/{id}', 'update')
         ->middleware('permission:unit,edit');
         ->middleware('permission:unit,edit');