def call(team_workgroup:, subteam_name:, urns:, programmes: [], **)
MavisCLI.load_rails
team = Team.find_by(workgroup: team_workgroup)
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
programmes =
(programmes.empty? ? team.programmes : Programme.find_all(programmes))
academic_year = AcademicYear.pending
locations = []
unless urns_are_valid?(urns, team, academic_year, locations)
warn "URN validation failed."
return
end
ActiveRecord::Base.transaction do
locations.each do |location|
if (
existing_team_locations =
location
.team_locations
.includes(:team, :subteam)
.where(academic_year:)
)
existing_team_locations.each do |existing_team_location|
warn "#{location.urn_and_site} previously belonged to #{existing_team_location.name}."
end
end
location.attach_to_team!(team, academic_year:, subteam:)
location.import_year_groups_from_gias!(academic_year:)
location.import_default_programme_year_groups!(
programmes,
academic_year:
)
end
patients_to_update =
Patient
.joins(:patient_locations)
.where(patient_locations: { location: locations })
.distinct
PatientTeamUpdater.call(patient_scope: patients_to_update)
end
end