def call(team_workgroup:, subteam_name:, names:, **)
MavisCLI.load_rails
team = Team.find_by(workgroup: team_workgroup)
academic_year = AcademicYear.pending
if team.nil?
warn "Could not find team with workgroup #{team_workgroup}."
return
end
subteam = team.subteams.find_by(name: subteam_name)
if subteam.nil?
warn "Could not find subteam with name #{subteam_name}."
return
end
ActiveRecord::Base.transaction do
names.each do |name|
location = Location.clinic.find_by(name:)
if location.nil?
warn "Could not find clinic with name #{name}."
next
end
if (
existing_team_locations =
location
.team_locations
.includes(:team, :subteam)
.where(academic_year:)
)
existing_team_locations.each do |existing_team_location|
warn "#{name} previously belonged to #{existing_team_location.name}."
end
end
location.attach_to_team!(team, academic_year:, subteam:)
patients_to_update =
Patient
.joins(:patient_locations)
.where(patient_locations: { location: })
.distinct
PatientTeamUpdater.call(patient_scope: patients_to_update)
end
end
end