UserNotificationController.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\UserNotification;
  4. use Illuminate\Http\JsonResponse;
  5. use Illuminate\Http\Request;
  6. class UserNotificationController extends Controller
  7. {
  8. protected array $data = [
  9. 'active' => 'notifications',
  10. 'title' => 'Уведомления',
  11. 'id' => 'notifications',
  12. 'header' => [
  13. 'created_at' => 'Дата',
  14. 'type' => 'Тип',
  15. 'event' => 'Событие',
  16. 'message' => 'Сообщение',
  17. 'read_at' => 'Прочитано',
  18. ],
  19. 'searchFields' => [
  20. 'message',
  21. ],
  22. 'ranges' => [],
  23. 'filters' => [],
  24. 'dates' => [],
  25. ];
  26. public function index(Request $request)
  27. {
  28. session(['gp_notifications' => $request->query()]);
  29. $model = new UserNotification;
  30. $userId = $request->user()->id;
  31. $q = $model::query()->where('user_id', $userId);
  32. $this->data['filters']['type'] = [
  33. 'title' => 'Тип',
  34. 'values' => UserNotification::TYPE_NAMES,
  35. ];
  36. $this->data['filters']['event'] = [
  37. 'title' => 'Событие',
  38. 'values' => UserNotification::EVENT_NAMES,
  39. ];
  40. $this->createDateFilters($model, 'created_at');
  41. $this->acceptFilters($q, $request);
  42. $this->acceptSearch($q, $request);
  43. $this->setSortAndOrderBy($model, $request);
  44. $this->applyStableSorting($q);
  45. $this->data['notifications'] = $q->paginate($this->data['per_page'])->withQueryString();
  46. return view('notifications.index', $this->data);
  47. }
  48. public function markRead(Request $request, UserNotification $notification): JsonResponse
  49. {
  50. if ($notification->user_id !== $request->user()->id) {
  51. abort(403);
  52. }
  53. if (!$notification->isRead()) {
  54. $notification->update(['read_at' => now()]);
  55. }
  56. return response()->json([
  57. 'ok' => true,
  58. 'unread' => UserNotification::query()
  59. ->where('user_id', $request->user()->id)
  60. ->whereNull('read_at')
  61. ->count(),
  62. ]);
  63. }
  64. public function unreadCount(Request $request): JsonResponse
  65. {
  66. return response()->json([
  67. 'count' => UserNotification::query()
  68. ->where('user_id', $request->user()->id)
  69. ->whereNull('read_at')
  70. ->count(),
  71. ]);
  72. }
  73. }