UserAccessLogService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Services;
  3. use App\Models\UserAccessLog;
  4. use App\Support\Cpf;
  5. use Illuminate\Pagination\LengthAwarePaginator;
  6. class UserAccessLogService
  7. {
  8. public function getAllPaginated(array $filters = [], int $perPage = 10): LengthAwarePaginator
  9. {
  10. $query = UserAccessLog::with(['user:id,name,type'])
  11. ->orderBy('accessed_at', 'desc');
  12. if (!empty($filters['last_per_user'])) {
  13. $query->whereIn('id', function ($sub) {
  14. $sub->selectRaw('MAX(id)')
  15. ->from('users_access_logs')
  16. ->groupBy('user_id');
  17. });
  18. }
  19. if (!empty($filters['type'])) {
  20. $query->whereHas('user', fn($q) => $q->where('type', $filters['type']));
  21. }
  22. if (!empty($filters['search'])) {
  23. $term = '%' . mb_strtolower($filters['search']) . '%';
  24. $cpfTerm = ($digits = Cpf::digits($filters['search'])) ? '%' . $digits . '%' : null;
  25. $query->where(function ($q) use ($term, $cpfTerm) {
  26. $q->whereHas('user', function ($u) use ($term, $cpfTerm) {
  27. $u->whereRaw('UNACCENT(LOWER(users.name)) LIKE UNACCENT(?)', [$term])
  28. ->orWhereRaw('UNACCENT(LOWER(COALESCE(users.registration, \'\'))) LIKE UNACCENT(?)', [$term])
  29. ->orWhereRaw('LOWER(users.type) LIKE ?', [$term]);
  30. if ($cpfTerm) {
  31. $u->orWhere('users.cpf', 'LIKE', $cpfTerm);
  32. }
  33. })
  34. ->orWhereRaw("TO_CHAR(users_access_logs.accessed_at, 'DD/MM/YYYY HH24:MI:SS') LIKE ?", [$term]);
  35. });
  36. }
  37. if (!empty($filters['date_from'])) {
  38. $query->whereDate('accessed_at', '>=', $filters['date_from']);
  39. }
  40. if (!empty($filters['date_to'])) {
  41. $query->whereDate('accessed_at', '<=', $filters['date_to']);
  42. }
  43. return $query->paginate($perPage);
  44. }
  45. }