summaryrefslogtreecommitdiff
path: root/app/controllers/admin/topics_controller.rb
blob: 345a778772dba5b8c50465ac343a942b6e90b213 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# frozen_string_literal: true

class Admin::TopicsController < Admin::ApplicationController
  include SendFileUpload
  include PreviewMarkdown

  before_action :topic, only: [:edit, :update, :destroy]

  feature_category :projects

  def index
    @topics = Projects::TopicsFinder.new(params: params.permit(:search)).execute.page(params[:page]).without_count
  end

  def new
    @topic = Projects::Topic.new
  end

  def edit
  end

  def create
    @topic = Projects::Topic.new(topic_params)

    if @topic.save
      redirect_to edit_admin_topic_path(@topic), notice: format(_('Topic %{topic_name} was successfully created.'), topic_name: @topic.name)
    else
      render "new"
    end
  end

  def update
    if @topic.update(topic_params)
      redirect_to edit_admin_topic_path(@topic), notice: _('Topic was successfully updated.')
    else
      render "edit"
    end
  end

  def destroy
    @topic.destroy!

    redirect_to admin_topics_path,
                status: :found,
                notice: format(_('Topic %{topic_name} was successfully removed.'), topic_name: @topic.title_or_name)
  end

  def merge
    source_topic = Projects::Topic.find(merge_params[:source_topic_id])
    target_topic = Projects::Topic.find(merge_params[:target_topic_id])

    response = ::Topics::MergeService.new(source_topic, target_topic).execute
    return render status: :bad_request, json: { type: :alert, message: response.message } if response.error?

    message = _('Topic %{source_topic} was successfully merged into topic %{target_topic}.')
    flash[:toast] = format(message, source_topic: source_topic.name, target_topic: target_topic.name)
    redirect_to admin_topics_path, status: :found
  end

  private

  def topic
    @topic ||= Projects::Topic.find(params[:id])
  end

  def topic_params
    params.require(:projects_topic).permit(allowed_topic_params)
  end

  def allowed_topic_params
    [
      :avatar,
      :description,
      :name,
      :title
    ]
  end

  def merge_params
    params.permit([:source_topic_id, :target_topic_id])
  end
end