module Eco module API module Organization class PolicyGroups < Eco::Language::Models::Collection # build the shortcuts of Collection attr_collection :id, :name def initialize(policy_groups = [], klass: Ecoportal::API::Internal::PolicyGroup) @klass = Ecoportal::API::Internal::PolicyGroup @caches_init = false super(policy_groups, klass: @klass) init_caches end def ids @by_id.keys end def names @by_name.keys end def to_id(name) case name when Enumerable name.map do |n| policy_group(n)&.id end.compact else policy_group(name)&.id end end def to_name(id) case id when Enumerable id.map do |n| policy_group(n)&.name end.compact else policy_group(id)&.name end end def policy_group(id_name) self[id_name] end def [](id_name) @by_id[policy_group_id(id_name)] end def user_pg_ids(initial: [], final: [], non_custom: (non_custom_not_used = true; []), preserve_custom: true) non_custom = to_id([non_custom].flatten.compact) initial = to_id([initial].flatten.compact) final = to_id([final].flatten.compact) unless initial.is_a?(Array) && final.is_a?(Array) && non_custom.is_a?(Array) raise "Expected Array for :initial, :final and :custom" end if !non_custom_not_used && preserve_custom initial_custom = initial - non_custom final += initial_custom end new_pg_ids = final - initial # keep same order as they where (initial & final) + new_pg_ids end private def policy_group_name(id_name) (@by_id[id_name] || @by_name[id_name&.downcase])&.name&.downcase end def policy_group_id(id_name) (@by_name[id_name&.downcase] || @by_id[id_name])&.id end def init_caches return if @caches_init @by_id = map { |pg| [pg.id, pg] }.to_h @by_name = map { |pg| [pg.name&.downcase, pg] }.to_h @caches_init = true end end end end end