2023-04-06 20:57:00 +08:00
|
|
|
# frozen_string_literal: true
|
2016-10-03 20:40:15 +08:00
|
|
|
|
2023-04-06 20:57:00 +08:00
|
|
|
class UserNotificationsController < ApplicationController
|
2023-11-10 17:06:00 +08:00
|
|
|
prepend_before_action -> { request.env['devise.skip_trackable'] = true }, only: :unseen_counter
|
|
|
|
|
2016-10-03 20:40:15 +08:00
|
|
|
def index
|
2023-10-17 18:02:55 +08:00
|
|
|
page = (params.dig(:page, :number) || 1).to_i
|
2024-10-14 16:20:43 +08:00
|
|
|
notifications = load_notifications
|
2016-09-29 20:49:58 +08:00
|
|
|
|
2024-10-14 16:20:43 +08:00
|
|
|
case params[:tab]
|
|
|
|
when 'all'
|
|
|
|
notifications = notifications.where.not(read_at: nil)
|
|
|
|
when 'unread'
|
|
|
|
notifications = notifications.where(read_at: nil)
|
|
|
|
end
|
|
|
|
|
|
|
|
notifications = notifications.page(page).per(Constants::INFINITE_SCROLL_LIMIT)
|
2023-04-12 17:14:53 +08:00
|
|
|
|
2024-10-14 16:20:43 +08:00
|
|
|
render json: notifications, each_serializer: NotificationSerializer
|
2023-04-12 17:14:53 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def unseen_counter
|
|
|
|
render json: {
|
2023-10-11 19:43:20 +08:00
|
|
|
unseen: load_notifications.where(read_at: nil).size
|
2023-04-12 17:14:53 +08:00
|
|
|
}
|
2016-09-29 20:49:58 +08:00
|
|
|
end
|
|
|
|
|
2024-10-14 16:20:43 +08:00
|
|
|
def mark_all_read
|
|
|
|
load_notifications.mark_as_read!
|
|
|
|
render json: { success: true }
|
|
|
|
end
|
|
|
|
|
|
|
|
def toggle_read
|
|
|
|
notification = current_user.notifications.find(params[:id])
|
|
|
|
notification.update(read_at: (params[:mark_as_read] ? DateTime.now : nil))
|
|
|
|
render json: notification, serializer: NotificationSerializer
|
|
|
|
end
|
|
|
|
|
2023-04-06 20:57:00 +08:00
|
|
|
private
|
|
|
|
|
|
|
|
def load_notifications
|
2023-07-25 20:48:03 +08:00
|
|
|
current_user.notifications
|
2023-12-12 21:08:42 +08:00
|
|
|
.in_app
|
2023-07-25 21:58:40 +08:00
|
|
|
.order(created_at: :desc)
|
2016-09-28 22:03:52 +08:00
|
|
|
end
|
|
|
|
end
|