BigW Consortium Gitlab

milestones_controller.rb 1.97 KB
Newer Older
1
class Groups::MilestonesController < Groups::ApplicationController
2
  include GlobalMilestones
3

4
  before_action :group_projects
5
  before_action :milestone, only: [:show, :update]
6
  before_action :authorize_admin_milestones!, only: [:new, :create, :update]
7

8
  def index
9 10 11 12 13
    respond_to do |format|
      format.html do
        @milestones = Kaminari.paginate_array(milestones).page(params[:page])
      end
    end
14
  end
15

16
  def new
17
    @milestone = Milestone.new
18 19 20
  end

  def create
21
    project_ids = params[:milestone][:project_ids].reject(&:blank?)
22 23
    title = milestone_params[:title]

24
    if create_milestones(project_ids)
Felipe Artur committed
25
      redirect_to milestone_path(title)
26
    else
Felipe Artur committed
27
      render_new_with_error(project_ids.empty?)
28 29 30
    end
  end

31 32 33
  def show
  end

34
  def update
35 36
    @milestone.milestones.each do |milestone|
      Milestones::UpdateService.new(milestone.project, current_user, milestone_params).execute(milestone)
37 38
    end

39
    redirect_back_or_default(default: milestone_path(@milestone.title))
40 41
  end

42 43
  private

44
  def create_milestones(project_ids)
Felipe Artur committed
45
    return false unless project_ids.present?
Felipe Artur committed
46

Felipe Artur committed
47 48 49
    ActiveRecord::Base.transaction do
      @projects.where(id: project_ids).each do |project|
        Milestones::CreateService.new(project, current_user, milestone_params).execute
50
      end
Felipe Artur committed
51 52 53
    end

    true
54
  rescue ActiveRecord::ActiveRecordError => e
Felipe Artur committed
55 56
    flash.now[:alert] = "An error occurred while creating the milestone: #{e.message}"
    false
57 58
  end

Felipe Artur committed
59
  def render_new_with_error(empty_project_ids)
60
    @milestone = Milestone.new(milestone_params)
Felipe Artur committed
61
    @milestone.errors.add(:project_id, "Please select at least one project.") if empty_project_ids
62 63 64
    render :new
  end

65
  def authorize_admin_milestones!
66
    return render_404 unless can?(current_user, :admin_milestones, group)
67 68
  end

69 70
  def milestone_params
    params.require(:milestone).permit(:title, :description, :due_date, :state_event)
71
  end
72

73
  def milestone_path(title)
74
    group_milestone_path(@group, title.to_slug.to_s, title: title)
75
  end
76
end