2021-02-04 21:08:20 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class UserAssignment < ApplicationRecord
|
2023-01-03 21:43:03 +08:00
|
|
|
attr_accessor :assign
|
|
|
|
|
2022-06-24 16:44:28 +08:00
|
|
|
before_validation -> { self.team ||= (assignable.is_a?(Team) ? assignable : assignable.team) }
|
2022-10-20 21:35:43 +08:00
|
|
|
after_create :assign_team_child_objects, if: -> { assignable.is_a?(Team) }
|
2022-10-10 21:27:42 +08:00
|
|
|
after_update :update_team_children_assignments, if: -> { assignable.is_a?(Team) && saved_change_to_user_role_id? }
|
|
|
|
before_destroy :unassign_team_child_objects, if: -> { assignable.is_a?(Team) }
|
2022-06-24 16:44:28 +08:00
|
|
|
|
2021-10-19 22:00:52 +08:00
|
|
|
belongs_to :assignable, polymorphic: true, touch: true
|
2021-02-04 21:08:20 +08:00
|
|
|
belongs_to :user_role
|
|
|
|
belongs_to :user
|
2022-06-24 16:44:28 +08:00
|
|
|
belongs_to :team
|
2021-10-05 19:45:52 +08:00
|
|
|
belongs_to :assigned_by, class_name: 'User', optional: true
|
2021-06-12 15:36:41 +08:00
|
|
|
|
|
|
|
enum assigned: { automatically: 0, manually: 1 }, _suffix: true
|
2021-11-22 17:47:20 +08:00
|
|
|
|
2022-06-24 16:44:28 +08:00
|
|
|
validates :user, uniqueness: { scope: %i(assignable team_id) }
|
2022-06-28 19:13:36 +08:00
|
|
|
|
2022-12-22 20:27:46 +08:00
|
|
|
def last_assignable_owner?
|
|
|
|
assignable_owners.count == 1 && user_role.owner?
|
|
|
|
end
|
|
|
|
|
2022-06-28 19:13:36 +08:00
|
|
|
private
|
|
|
|
|
2022-10-20 21:35:43 +08:00
|
|
|
def assign_team_child_objects
|
|
|
|
UserAssignments::CreateTeamUserAssignmentsService.new(self).call
|
2022-10-06 04:40:46 +08:00
|
|
|
end
|
|
|
|
|
2022-10-10 21:27:42 +08:00
|
|
|
def update_team_children_assignments
|
2022-10-20 21:35:43 +08:00
|
|
|
UserAssignments::UpdateTeamUserAssignmentsService.new(self).call
|
2022-06-28 19:13:36 +08:00
|
|
|
end
|
2022-10-06 04:40:46 +08:00
|
|
|
|
2022-10-10 21:27:42 +08:00
|
|
|
def unassign_team_child_objects
|
2022-10-20 21:35:43 +08:00
|
|
|
UserAssignments::RemoveTeamUserAssignmentsService.new(self).call
|
2022-10-06 04:40:46 +08:00
|
|
|
end
|
2022-12-22 20:27:46 +08:00
|
|
|
|
|
|
|
def assignable_owners
|
|
|
|
@assignable_owners ||= assignable.user_assignments
|
|
|
|
.includes(:user_role)
|
|
|
|
.where(user_roles: { name: I18n.t('user_roles.predefined.owner') })
|
|
|
|
end
|
2021-02-04 21:08:20 +08:00
|
|
|
end
|