2016-10-17 22:11:33 -04:00
|
|
|
module Labels
|
2016-10-19 09:53:31 -04:00
|
|
|
class FindOrCreateService
|
2016-10-17 22:11:33 -04:00
|
|
|
def initialize(current_user, project, params = {})
|
|
|
|
@current_user = current_user
|
|
|
|
@project = project
|
2017-03-29 07:45:15 -04:00
|
|
|
@params = params.dup.with_indifferent_access
|
2016-10-17 22:11:33 -04:00
|
|
|
end
|
|
|
|
|
2016-10-28 05:31:45 -04:00
|
|
|
def execute(skip_authorization: false)
|
|
|
|
@skip_authorization = skip_authorization
|
2016-10-17 22:11:33 -04:00
|
|
|
find_or_create_label
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-10-28 05:31:45 -04:00
|
|
|
attr_reader :current_user, :project, :params, :skip_authorization
|
2016-10-17 22:11:33 -04:00
|
|
|
|
|
|
|
def available_labels
|
2016-10-28 05:31:45 -04:00
|
|
|
@available_labels ||= LabelsFinder.new(
|
|
|
|
current_user,
|
|
|
|
project_id: project.id
|
|
|
|
).execute(skip_authorization: skip_authorization)
|
2016-10-17 22:11:33 -04:00
|
|
|
end
|
|
|
|
|
2016-11-10 05:23:44 -05:00
|
|
|
# Only creates the label if current_user can do so, if the label does not exist
|
|
|
|
# and the user can not create the label, nil is returned
|
2016-10-17 22:11:33 -04:00
|
|
|
def find_or_create_label
|
|
|
|
new_label = available_labels.find_by(title: title)
|
2016-11-10 05:23:44 -05:00
|
|
|
|
|
|
|
if new_label.nil? && (skip_authorization || Ability.allowed?(current_user, :admin_label, project))
|
2017-03-29 07:45:15 -04:00
|
|
|
new_label = Labels::CreateService.new(params).execute(project: project)
|
2016-11-10 05:23:44 -05:00
|
|
|
end
|
2016-10-17 22:11:33 -04:00
|
|
|
|
|
|
|
new_label
|
|
|
|
end
|
|
|
|
|
|
|
|
def title
|
|
|
|
params[:title] || params[:name]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|