UserAccessLogService.php 1.8 KB

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