Retrospring/app/controllers/notifications_controller.rb

69 lines
2.1 KiB
Ruby
Raw Normal View History

2022-03-26 10:42:49 -07:00
# frozen_string_literal: true
2014-12-09 13:35:11 -08:00
class NotificationsController < ApplicationController
2020-04-18 16:45:50 -07:00
before_action :authenticate_user!
2014-12-12 08:54:13 -08:00
after_action :mark_notifications_as_read, only: %i[index]
TYPE_MAPPINGS = {
2022-07-21 07:30:04 -07:00
"answer" => Notification::QuestionAnswered.name,
"comment" => Notification::Commented.name,
"commentsmile" => Notification::CommentSmiled.name,
"relationship" => Notification::StartedFollowing.name,
2022-07-21 07:56:05 -07:00
"smile" => Notification::Smiled.name
}.freeze
2014-12-09 13:35:11 -08:00
def index
@type = TYPE_MAPPINGS[params[:type]] || params[:type]
@notifications = cursored_notifications_for(type: @type, last_id: params[:last_id])
2023-02-02 01:38:41 -08:00
paginate_notifications
@counters = count_unread_by_type
2015-01-08 09:22:27 -08:00
respond_to do |format|
format.html
format.turbo_stream { render layout: false, status: :see_other }
2015-01-08 09:22:27 -08:00
end
2014-12-09 13:35:11 -08:00
end
def read
2023-03-10 12:08:28 -08:00
current_user.notifications.where(new: true).update_all(new: false) # rubocop:disable Rails/SkipsModelValidations
respond_to do |format|
format.turbo_stream do
render "navigation/notifications", locals: { notifications: [], notification_count: nil }
2023-03-10 12:08:28 -08:00
end
end
end
private
2023-02-02 01:38:41 -08:00
def paginate_notifications
@notifications_last_id = @notifications.map(&:id).min
@more_data_available = !cursored_notifications_for(type: @type, last_id: @notifications_last_id, size: 1).count.zero?
end
def count_unread_by_type
Notification.where(recipient: current_user, new: true)
.group(:target_type)
.count(:target_type)
end
def mark_notifications_as_read
# using .dup to not modify @notifications -- useful in tests
2023-01-24 06:57:34 -08:00
@notifications&.dup&.update_all(new: false) # rubocop:disable Rails/SkipsModelValidations
end
def cursored_notifications_for(type:, last_id:, size: nil)
cursor_params = { last_id: last_id, size: size }.compact
case type
2022-03-26 10:42:49 -07:00
when "all"
Notification.cursored_for(current_user, **cursor_params)
2022-03-26 10:42:49 -07:00
when "new"
Notification.cursored_for(current_user, new: true, **cursor_params)
else
Notification.cursored_for_type(current_user, type, **cursor_params)
end
end
2014-12-09 13:35:11 -08:00
end