2019-02-12 03:35:34 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
module Labels
|
|
|
|
class AvailableLabelsService
|
|
|
|
attr_reader :current_user, :parent, :params
|
|
|
|
|
|
|
|
def initialize(current_user, parent, params)
|
|
|
|
@current_user = current_user
|
|
|
|
@parent = parent
|
|
|
|
@params = params
|
|
|
|
end
|
|
|
|
|
2019-08-30 03:51:45 -04:00
|
|
|
def find_or_create_by_titles(key = :labels, find_only: false)
|
2019-08-14 23:43:33 -04:00
|
|
|
labels = params.delete(key)
|
2019-02-12 03:35:34 -05:00
|
|
|
|
|
|
|
return [] unless labels
|
|
|
|
|
2021-04-30 08:12:30 -04:00
|
|
|
labels = labels.split(',').map(&:strip) if labels.is_a?(String)
|
|
|
|
existing_labels = LabelsFinder.new(current_user, finder_params(labels)).execute.index_by(&:title)
|
2019-02-12 03:35:34 -05:00
|
|
|
|
|
|
|
labels.map do |label_name|
|
|
|
|
label = Labels::FindOrCreateService.new(
|
|
|
|
current_user,
|
|
|
|
parent,
|
|
|
|
include_ancestor_groups: true,
|
2021-04-30 08:12:30 -04:00
|
|
|
title: label_name,
|
|
|
|
existing_labels_by_title: existing_labels
|
2019-08-30 03:51:45 -04:00
|
|
|
).execute(find_only: find_only)
|
2019-02-12 03:35:34 -05:00
|
|
|
|
|
|
|
label
|
|
|
|
end.compact
|
|
|
|
end
|
|
|
|
|
|
|
|
def filter_labels_ids_in_param(key)
|
2020-08-13 11:10:03 -04:00
|
|
|
ids = Array.wrap(params[key])
|
2020-06-11 08:08:54 -04:00
|
|
|
return [] if ids.empty?
|
2019-02-12 03:35:34 -05:00
|
|
|
|
|
|
|
# rubocop:disable CodeReuse/ActiveRecord
|
2020-07-14 14:09:55 -04:00
|
|
|
existing_ids = available_labels.id_in(ids).pluck(:id)
|
2019-02-12 03:35:34 -05:00
|
|
|
# rubocop:enable CodeReuse/ActiveRecord
|
2020-06-11 08:08:54 -04:00
|
|
|
ids.map(&:to_i) & existing_ids
|
2019-02-12 03:35:34 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def available_labels
|
|
|
|
@available_labels ||= LabelsFinder.new(current_user, finder_params).execute
|
|
|
|
end
|
|
|
|
|
2020-08-06 14:09:41 -04:00
|
|
|
private
|
|
|
|
|
2021-04-30 08:12:30 -04:00
|
|
|
def finder_params(titles = nil)
|
|
|
|
finder_params = { include_ancestor_groups: true }
|
|
|
|
finder_params[:title] = titles if titles
|
2019-02-12 03:35:34 -05:00
|
|
|
|
|
|
|
case parent
|
|
|
|
when Group
|
2021-04-30 08:12:30 -04:00
|
|
|
finder_params[:group_id] = parent.id
|
|
|
|
finder_params[:only_group_labels] = true
|
2019-02-12 03:35:34 -05:00
|
|
|
when Project
|
2021-04-30 08:12:30 -04:00
|
|
|
finder_params[:project_id] = parent.id
|
2019-02-12 03:35:34 -05:00
|
|
|
end
|
|
|
|
|
2021-04-30 08:12:30 -04:00
|
|
|
finder_params
|
2019-02-12 03:35:34 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|