ClientPaymentMethodService.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ClientPaymentMethod;
  4. use App\Services\Pagarme\PagarmeCardService;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\DB;
  7. class ClientPaymentMethodService
  8. {
  9. public function __construct(
  10. private readonly PagarmeCardService $pagarmeCardService,
  11. ) {}
  12. public function getByClientId(int $clientId): Collection
  13. {
  14. return ClientPaymentMethod::where('client_id', $clientId)
  15. ->orderBy('is_active', 'desc')
  16. ->orderBy('created_at', 'desc')
  17. ->get();
  18. }
  19. public function findById(int $id): ?ClientPaymentMethod
  20. {
  21. return ClientPaymentMethod::find($id);
  22. }
  23. public function create(array $data): ClientPaymentMethod
  24. {
  25. return DB::transaction(function () use ($data) {
  26. if ($data['is_active'] ?? true) {
  27. $this->deactivateOtherCards($data['client_id']);
  28. }
  29. $paymentMethod = ClientPaymentMethod::create($data);
  30. $cardId = $this->pagarmeCardService->createCardForPaymentMethod($paymentMethod);
  31. if (empty($cardId)) {
  32. throw new \RuntimeException('Nao foi possivel salvar o cartao no Pagar.me.');
  33. }
  34. return $paymentMethod->fresh();
  35. });
  36. }
  37. public function update(ClientPaymentMethod $paymentMethod, array $data): ClientPaymentMethod
  38. {
  39. if (isset($data['is_active']) && $data['is_active']) {
  40. $this->deactivateOtherCards($paymentMethod->client_id, $paymentMethod->id);
  41. }
  42. $paymentMethod->update($data);
  43. return $paymentMethod->fresh();
  44. }
  45. public function delete(ClientPaymentMethod $paymentMethod): bool
  46. {
  47. return $paymentMethod->delete();
  48. }
  49. private function deactivateOtherCards(int $clientId, ?int $exceptId = null): void
  50. {
  51. $query = ClientPaymentMethod::where('client_id', $clientId);
  52. if ($exceptId) {
  53. $query->where('id', '!=', $exceptId);
  54. }
  55. $query->update(['is_active' => false]);
  56. }
  57. }