UnitPaymentAccountService.php 1018 B

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. namespace App\Services;
  3. use App\Models\UnitPaymentAccount;
  4. class UnitPaymentAccountService
  5. {
  6. public function getByUnitId(int $unitId): ?UnitPaymentAccount
  7. {
  8. return UnitPaymentAccount::where('unit_id', $unitId)->first();
  9. }
  10. /**
  11. * Cria/atualiza a conta de pagamento da unidade.
  12. *
  13. * Quando a chave vem vazia, a integração é considerada limpa (status pending).
  14. */
  15. public function upsertAsaasApiKey(int $unitId, ?string $apiKey): UnitPaymentAccount
  16. {
  17. $apiKey = $apiKey !== null ? trim($apiKey) : null;
  18. $hasKey = $apiKey !== null && $apiKey !== '';
  19. $model = UnitPaymentAccount::firstOrNew(['unit_id' => $unitId]);
  20. $model->asaas_api_key = $hasKey ? $apiKey : null;
  21. $model->status = $hasKey ? UnitPaymentAccount::STATUS_ACTIVE : UnitPaymentAccount::STATUS_PENDING;
  22. $model->onboarded_at = $hasKey ? ($model->onboarded_at ?? now()) : null;
  23. $model->save();
  24. return $model->fresh();
  25. }
  26. }