summaryrefslogtreecommitdiff
path: root/app/controllers/boards/lists_controller.rb
blob: 08b4748d7e1c7b6eb444e7e428eacb72979aa06e (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
83
84
85
86
87
88
89
# frozen_string_literal: true

module Boards
  class ListsController < Boards::ApplicationController
    include BoardsResponses

    before_action :authorize_admin_list, only: [:create, :destroy, :generate]
    before_action :authorize_read_list, only: [:index]
    skip_before_action :authenticate_user!, only: [:index]

    def index
      lists = Boards::Lists::ListService.new(board.parent, current_user).execute(board)

      render json: serialize_as_json(lists)
    end

    def create
      list = Boards::Lists::CreateService.new(board.parent, current_user, create_list_params).execute(board)

      if list.valid?
        render json: serialize_as_json(list)
      else
        render json: list.errors, status: :unprocessable_entity
      end
    end

    def update
      list = board.lists.movable.find(params[:id])
      service = Boards::Lists::UpdateService.new(board_parent, current_user, update_list_params)
      result = service.execute(list)

      if result[:status] == :success
        head :ok
      else
        head result[:http_status]
      end
    end

    def destroy
      list = board.lists.destroyable.find(params[:id])
      service = Boards::Lists::DestroyService.new(board_parent, current_user)

      if service.execute(list)
        head :ok
      else
        head :unprocessable_entity
      end
    end

    def generate
      service = Boards::Lists::GenerateService.new(board_parent, current_user)

      if service.execute(board)
        lists = board.lists.movable.preload_associations(current_user)
        render json: serialize_as_json(lists)
      else
        head :unprocessable_entity
      end
    end

    private

    def list_creation_attrs
      %i[label_id]
    end

    def create_list_params
      params.require(:list).permit(list_creation_attrs)
    end

    def update_list_params
      params.require(:list).permit(:collapsed, :position)
    end

    def serialize_as_json(resource)
      resource.as_json(serialization_attrs)
    end

    def serialization_attrs
      {
        only: [:id, :list_type, :position],
        methods: [:title],
        label: true,
        collapsed: true,
        current_user: current_user
      }
    end
  end
end