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
|
2016-10-03 20:40:15 +08:00
|
|
|
def index
|
2023-04-06 20:57:00 +08:00
|
|
|
page = (params[:page] || 1).to_i
|
|
|
|
notifications = load_notifications.page(page).per(Constants::INFINITE_SCROLL_LIMIT).without_count
|
2016-09-29 20:49:58 +08:00
|
|
|
|
2023-07-18 19:36:41 +08:00
|
|
|
render json: {
|
|
|
|
notifications: notification_serializer(notifications),
|
|
|
|
next_page: notifications.next_page
|
|
|
|
}
|
2023-04-12 17:14:53 +08:00
|
|
|
|
|
|
|
UserNotification.where(
|
2023-04-14 19:16:34 +08:00
|
|
|
notification_id: notifications.except(:select).where.not(type_of: 2).select(:id)
|
2023-04-12 17:14:53 +08:00
|
|
|
).seen_by_user(current_user)
|
|
|
|
|
|
|
|
current_user.user_system_notifications.where(
|
2023-04-14 19:16:34 +08:00
|
|
|
system_notification_id: notifications.except(:select).where(type_of: 2).select(:id)
|
2023-04-12 17:14:53 +08:00
|
|
|
).mark_as_seen
|
|
|
|
end
|
|
|
|
|
|
|
|
def unseen_counter
|
|
|
|
render json: {
|
|
|
|
unseen: load_notifications.where(checked: false).size
|
|
|
|
}
|
2016-09-29 20:49:58 +08:00
|
|
|
end
|
|
|
|
|
2023-04-06 20:57:00 +08:00
|
|
|
private
|
|
|
|
|
|
|
|
def load_notifications
|
|
|
|
user_notifications = current_user.notifications
|
|
|
|
.select(:id, :type_of, :title, :message, :created_at, 'user_notifications.checked')
|
|
|
|
system_notifications = current_user.system_notifications
|
|
|
|
.select(
|
|
|
|
:id,
|
|
|
|
'2 AS type_of',
|
|
|
|
:title,
|
|
|
|
'description AS message',
|
|
|
|
:created_at,
|
|
|
|
'CASE WHEN seen_at IS NULL THEN false ELSE true END AS checked'
|
|
|
|
)
|
|
|
|
notifications =
|
|
|
|
case params[:type]
|
|
|
|
when 'message'
|
|
|
|
user_notifications
|
|
|
|
when 'system'
|
|
|
|
Notification.from("(#{system_notifications.to_sql}) AS notifications")
|
|
|
|
else
|
|
|
|
Notification.from(
|
|
|
|
"((#{user_notifications.to_sql}) UNION ALL (#{system_notifications.to_sql})) AS notifications"
|
|
|
|
)
|
2016-09-29 20:49:58 +08:00
|
|
|
end
|
2023-04-06 20:57:00 +08:00
|
|
|
notifications.order(created_at: :desc)
|
2016-09-28 22:03:52 +08:00
|
|
|
end
|
2023-04-14 17:38:28 +08:00
|
|
|
|
|
|
|
def notification_serializer(notifications)
|
|
|
|
notifications.map do |notification|
|
|
|
|
{
|
|
|
|
id: notification.id,
|
|
|
|
type_of: notification.type_of,
|
|
|
|
title: notification.title,
|
|
|
|
message: notification.message,
|
|
|
|
created_at: I18n.l(notification.created_at, format: :full),
|
2023-04-14 20:46:57 +08:00
|
|
|
today: notification.created_at.today?,
|
2023-04-17 21:23:52 +08:00
|
|
|
checked: notification.checked,
|
|
|
|
action_url: (system_notification_path(notification.id) if notification.type_of == 'system_message')
|
2023-04-14 17:38:28 +08:00
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|
2016-09-28 22:03:52 +08:00
|
|
|
end
|