UserNotificationController.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. ];
  25. public function index(Request $request)
  26. {
  27. session(['gp_notifications' => $request->query()]);
  28. $model = new UserNotification;
  29. $userId = $request->user()->id;
  30. $q = $model::query()->where('user_id', $userId);
  31. $this->data['filters']['type'] = [
  32. 'title' => 'Тип',
  33. 'values' => UserNotification::TYPE_NAMES,
  34. ];
  35. $this->data['filters']['event'] = [
  36. 'title' => 'Событие',
  37. 'values' => UserNotification::EVENT_NAMES,
  38. ];
  39. $this->createDateFilters($model, 'created_at');
  40. $this->acceptFilters($q, $request);
  41. $this->acceptSearch($q, $request);
  42. $this->setSortAndOrderBy($model, $request);
  43. $this->applyStableSorting($q);
  44. $this->data['notifications'] = $q->paginate($this->data['per_page'])->withQueryString();
  45. return view('notifications.index', $this->data);
  46. }
  47. public function markRead(Request $request, UserNotification $notification): JsonResponse
  48. {
  49. if ($notification->user_id !== $request->user()->id) {
  50. abort(403);
  51. }
  52. if (!$notification->isRead()) {
  53. $notification->update(['read_at' => now()]);
  54. }
  55. return response()->json([
  56. 'ok' => true,
  57. 'unread' => UserNotification::query()
  58. ->where('user_id', $request->user()->id)
  59. ->whereNull('read_at')
  60. ->count(),
  61. ]);
  62. }
  63. public function unreadCount(Request $request): JsonResponse
  64. {
  65. return response()->json([
  66. 'count' => UserNotification::query()
  67. ->where('user_id', $request->user()->id)
  68. ->whereNull('read_at')
  69. ->count(),
  70. ]);
  71. }
  72. }