2021-06-01 12:20:20 +00:00
|
|
|
# Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
|
|
|
|
|
2018-06-25 10:35:57 +00:00
|
|
|
module HasGroupRelationDefinition
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
|
|
|
|
self.table_name = "groups_#{group_relation_model_identifier}s"
|
|
|
|
self.primary_keys = ref_key, :group_id, :access
|
|
|
|
|
2019-07-04 11:16:55 +00:00
|
|
|
belongs_to group_relation_model_identifier, optional: true
|
|
|
|
belongs_to :group, optional: true
|
2018-06-25 10:35:57 +00:00
|
|
|
|
|
|
|
validates :access, presence: true
|
|
|
|
validate :validate_access
|
|
|
|
|
2022-01-31 13:56:58 +00:00
|
|
|
after_commit :touch_related
|
2018-06-25 10:35:57 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def group_relation_instance
|
|
|
|
@group_relation_instance ||= send(group_relation_model_identifier)
|
|
|
|
end
|
|
|
|
|
|
|
|
def group_relation_model_identifier
|
|
|
|
@group_relation_model_identifier ||= self.class.group_relation_model_identifier
|
|
|
|
end
|
|
|
|
|
|
|
|
def touch_related
|
|
|
|
# rubocop:disable Rails/SkipsModelValidations
|
|
|
|
group.touch if group&.persisted?
|
|
|
|
group_relation_instance.touch if group_relation_instance&.persisted?
|
|
|
|
# rubocop:enable Rails/SkipsModelValidations
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_access
|
|
|
|
query = self.class.where(
|
|
|
|
group_relation_model_identifier => group_relation_instance,
|
|
|
|
group: group
|
|
|
|
)
|
|
|
|
|
|
|
|
query = if access == 'full'
|
|
|
|
query.where.not(access: 'full')
|
|
|
|
else
|
|
|
|
query.where(access: 'full')
|
|
|
|
end
|
|
|
|
|
|
|
|
return if !query.exists?
|
2018-10-09 06:17:41 +00:00
|
|
|
|
2018-06-25 10:35:57 +00:00
|
|
|
errors.add(:access, "#{group_relation_model_identifier.to_s.capitalize} can have full or granular access to group")
|
|
|
|
end
|
|
|
|
|
|
|
|
# methods defined here are going to extend the class, not the instance of it
|
|
|
|
class_methods do
|
|
|
|
|
|
|
|
def group_relation_model_identifier
|
|
|
|
@group_relation_model_identifier ||= model_name.singular.split('_').first.to_sym
|
|
|
|
end
|
|
|
|
|
|
|
|
def ref_key
|
2020-08-21 08:18:31 +00:00
|
|
|
@ref_key ||= :"#{group_relation_model_identifier}_id"
|
2018-06-25 10:35:57 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|