diff --git a/app/models/class_import.rb b/app/models/class_import.rb index 4e59873b4..caf69065d 100644 --- a/app/models/class_import.rb +++ b/app/models/class_import.rb @@ -56,10 +56,12 @@ def postprocess_rows! unknown_patients = session.patients - patients - unknown_patients.each do |unknown_patient| - unknown_patient.update!(school: nil) - end - - session.patients.delete(unknown_patients) + session + .patient_sessions + .where(patient: unknown_patients) + .find_each do |patient_session| + patient_session.patient.update!(school: nil) + patient_session.destroy! if patient_session.added_to_session? + end end end diff --git a/app/models/immunisation_import.rb b/app/models/immunisation_import.rb index e08be63b3..b9d1adf78 100644 --- a/app/models/immunisation_import.rb +++ b/app/models/immunisation_import.rb @@ -148,9 +148,12 @@ def postprocess_rows! .includes(:vaccination_records) .select { _1.vaccinated?(programme) } - PatientSession.where( - session: team.sessions.upcoming, - patient: already_vaccinated_patients - ).delete_all + PatientSession + .where( + session: team.sessions.upcoming, + patient: already_vaccinated_patients + ) + .select(&:added_to_session?) + .each(&:destroy!) end end diff --git a/app/models/session.rb b/app/models/session.rb index 162651f74..1d860df1a 100644 --- a/app/models/session.rb +++ b/app/models/session.rb @@ -131,6 +131,7 @@ def create_patient_sessions! required_programmes.all? { |programme| patient.vaccinated?(programme) } end + # First we remove patients from any other upcoming sessions. unvaccinated_patients.each do |patient| sessions_other_than_self = patient.upcoming_sessions.reject { _1 == self } next if sessions_other_than_self.empty? @@ -142,6 +143,7 @@ def create_patient_sessions! .each(&:destroy!) end + # Next we can add the unvaccinated patients to this session. PatientSession.import!( %i[patient_id session_id], unvaccinated_patients.map { [_1.id, id] }, diff --git a/spec/models/class_import_spec.rb b/spec/models/class_import_spec.rb index 335426133..7ca59329f 100644 --- a/spec/models/class_import_spec.rb +++ b/spec/models/class_import_spec.rb @@ -355,6 +355,20 @@ expect { record! }.to change { existing_patient.reload.school }.to(nil) expect(session.reload.patients).not_to include(existing_patient) end + + context "when the patient has been seen" do + let(:existing_patient) do + create(:patient, :consent_given_triage_not_needed, session:) + end + + it "doesn't remove the patient from the session" do + expect(session.patients).to include(existing_patient) + expect { record! }.to change { existing_patient.reload.school }.to( + nil + ) + expect(session.reload.patients).to include(existing_patient) + end + end end end end