Skip to content

Commit 11e7cad

Browse files
committed
Add rake task to clean up stale patient locations after school moves
When a patient moves school, their old `PatientLocation` record should be deleted if it's safe to do so. However, due to how `safe_to_destroy?` was previously defined, old `PatientLocations` were retained if the patient had any attendance records at that location, even from previous academic years. This caused patients to appear in sessions for multiple schools simultaneously, even if they had moved before any sessions at their old school took place, leading to potentially misleading communications. The underlying issue was fixed in PR #5115 by scoping attendance_records to the `PatientLocation`'s academic year. This rake task cleans up the existing stale records that accumulated before that fix. Jira-Issue: MAV-2540
1 parent 5efbc92 commit 11e7cad

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

lib/tasks/patient_locations.rake

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# frozen_string_literal: true
2+
3+
namespace :patient_locations do
4+
desc "Remove stale patient locations from previous schools"
5+
task cleanup_post_school_move: :environment do
6+
dry_run = ENV.fetch("DRY_RUN", "true") == "true"
7+
8+
puts "Starting cleanup of stale patient locations from previous schools"
9+
puts "DRY RUN MODE - No records will be destroyed" if dry_run
10+
11+
patients_with_multiple_locations =
12+
Patient.where(
13+
id:
14+
PatientLocation
15+
.where.not(location_id: Location.clinic)
16+
.where(academic_year: AcademicYear.current)
17+
.group(:patient_id)
18+
.having("COUNT(*) > 1")
19+
.select(:patient_id)
20+
)
21+
22+
total = patients_with_multiple_locations.count
23+
puts "Found #{total} patients with multiple locations"
24+
25+
progress_bar =
26+
# rubocop:disable Rails/SaveBang
27+
ProgressBar.create(
28+
total:,
29+
format: "%a %b\u{15E7}%i %p%% %t",
30+
progress_mark: " ",
31+
remainder_mark: "\u{FF65}"
32+
)
33+
# rubocop:enable Rails/SaveBang
34+
35+
safe_to_destroy_count = 0
36+
37+
patients_with_multiple_locations.find_each do |patient|
38+
patient_locations_to_destroy =
39+
patient
40+
.patient_locations
41+
.where(academic_year: AcademicYear.current)
42+
.where.not(location_id: patient.school_id)
43+
44+
safe_to_destroy_count += patient_locations_to_destroy.count
45+
46+
patient_locations_to_destroy.destroy_all unless dry_run
47+
48+
progress_bar.increment
49+
end
50+
51+
puts(
52+
if dry_run
53+
"Would destroy: #{safe_to_destroy_count}"
54+
else
55+
"Safely destroyed: #{safe_to_destroy_count}"
56+
end
57+
)
58+
end
59+
end

0 commit comments

Comments
 (0)