Skip to content

Commit ec2b067

Browse files
authored
Merge pull request #5187 from nhsuk/cleanup-patient-locations-multiple-schools
Add rake task to clean up stale patient locations after school moves
2 parents 5efbc92 + 11e7cad commit ec2b067

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)