UserNotificationController.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. 'read_at' => $notification->read_at->format('d.m.Y H:i:s'),
  59. 'unread' => UserNotification::query()
  60. ->where('user_id', $request->user()->id)
  61. ->whereNull('read_at')
  62. ->count(),
  63. ]);
  64. }
  65. public function unreadCount(Request $request): JsonResponse
  66. {
  67. return response()->json([
  68. 'count' => UserNotification::query()
  69. ->where('user_id', $request->user()->id)
  70. ->whereNull('read_at')
  71. ->count(),
  72. ]);
  73. }
  74. }