announcements_controller.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # frozen_string_literal: true
  2. class Admin::AnnouncementsController < Admin::BaseController
  3. before_action :set_announcements, only: :index
  4. before_action :set_announcement, except: [:index, :new, :create]
  5. def index
  6. authorize :announcement, :index?
  7. end
  8. def new
  9. authorize :announcement, :create?
  10. @announcement = Announcement.new
  11. end
  12. def edit
  13. authorize :announcement, :update?
  14. end
  15. def create
  16. authorize :announcement, :create?
  17. @announcement = Announcement.new(resource_params)
  18. if @announcement.save
  19. PublishScheduledAnnouncementWorker.perform_async(@announcement.id) if @announcement.published?
  20. log_action :create, @announcement
  21. redirect_to admin_announcements_path, notice: @announcement.published? ? I18n.t('admin.announcements.published_msg') : I18n.t('admin.announcements.scheduled_msg')
  22. else
  23. render :new
  24. end
  25. end
  26. def update
  27. authorize :announcement, :update?
  28. if @announcement.update(resource_params)
  29. PublishScheduledAnnouncementWorker.perform_async(@announcement.id) if @announcement.published?
  30. log_action :update, @announcement
  31. redirect_to admin_announcements_path, notice: I18n.t('admin.announcements.updated_msg')
  32. else
  33. render :edit
  34. end
  35. end
  36. def publish
  37. authorize :announcement, :update?
  38. @announcement.publish!
  39. PublishScheduledAnnouncementWorker.perform_async(@announcement.id)
  40. log_action :update, @announcement
  41. redirect_to admin_announcements_path, notice: I18n.t('admin.announcements.published_msg')
  42. end
  43. def unpublish
  44. authorize :announcement, :update?
  45. @announcement.unpublish!
  46. UnpublishAnnouncementWorker.perform_async(@announcement.id)
  47. log_action :update, @announcement
  48. redirect_to admin_announcements_path, notice: I18n.t('admin.announcements.unpublished_msg')
  49. end
  50. def destroy
  51. authorize :announcement, :destroy?
  52. @announcement.destroy!
  53. UnpublishAnnouncementWorker.perform_async(@announcement.id) if @announcement.published?
  54. log_action :destroy, @announcement
  55. redirect_to admin_announcements_path, notice: I18n.t('admin.announcements.destroyed_msg')
  56. end
  57. private
  58. def set_announcements
  59. @announcements = AnnouncementFilter.new(filter_params).results.reverse_chronological.page(params[:page])
  60. end
  61. def set_announcement
  62. @announcement = Announcement.find(params[:id])
  63. end
  64. def filter_params
  65. params.slice(*AnnouncementFilter::KEYS).permit(*AnnouncementFilter::KEYS)
  66. end
  67. def resource_params
  68. params.require(:announcement).permit(:text, :scheduled_at, :starts_at, :ends_at, :all_day)
  69. end
  70. end