2021-06-06 15:54:47 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Assignable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2021-09-30 17:32:11 +08:00
|
|
|
include Canaid::Helpers::PermissionsHelper
|
|
|
|
|
2021-06-06 15:54:47 +08:00
|
|
|
has_many :user_assignments, as: :assignable, dependent: :destroy
|
|
|
|
|
2021-10-05 19:45:52 +08:00
|
|
|
default_scope { includes(user_assignments: :user_role).distinct }
|
2021-06-06 15:54:47 +08:00
|
|
|
|
2021-09-30 17:32:11 +08:00
|
|
|
scope :readable_by_user, lambda { |user|
|
|
|
|
joins(user_assignments: :user_role)
|
|
|
|
.where(user_assignments: { user: user })
|
|
|
|
.where('? = ANY(user_roles.permissions)', "::#{self.class.to_s.split('::').first}Permissions".constantize::READ)
|
|
|
|
}
|
|
|
|
|
2021-10-01 18:20:24 +08:00
|
|
|
scope :managable_by_user, lambda { |user|
|
|
|
|
joins(user_assignments: :user_role)
|
|
|
|
.where(user_assignments: { user: user })
|
|
|
|
.where('? = ANY(user_roles.permissions)', "::#{self.class.to_s.split('::').first}Permissions".constantize::MANAGE)
|
|
|
|
}
|
|
|
|
|
2021-10-14 19:13:29 +08:00
|
|
|
after_create do
|
2021-09-30 17:32:11 +08:00
|
|
|
UserAssignment.create!(
|
2021-06-19 23:17:57 +08:00
|
|
|
user: created_by,
|
|
|
|
assignable: self,
|
2021-10-04 17:20:47 +08:00
|
|
|
assigned: :manually, # we set this to manually since was the user action to create the item
|
2021-09-15 20:39:47 +08:00
|
|
|
user_role: UserRole.find_by(name: I18n.t('user_roles.predefined.owner'))
|
2021-06-19 23:17:57 +08:00
|
|
|
)
|
|
|
|
|
2021-10-04 21:47:28 +08:00
|
|
|
UserAssignments::GenerateUserAssignmentsJob.perform_later(self, created_by)
|
2021-06-06 15:54:47 +08:00
|
|
|
end
|
2021-10-26 18:06:26 +08:00
|
|
|
|
|
|
|
def role_for_user(user)
|
|
|
|
user_assignments.find_by(user: user)&.user_role
|
|
|
|
end
|
2021-06-06 15:54:47 +08:00
|
|
|
end
|
|
|
|
end
|