Skip to content

Instantly share code, notes, and snippets.

@fredkingham
Last active November 29, 2022 14:07
Show Gist options
  • Save fredkingham/8a2a8f51fa87c093f2bdf5ea7c256012 to your computer and use it in GitHub Desktop.
Save fredkingham/8a2a8f51fa87c093f2bdf5ea7c256012 to your computer and use it in GitHub Desktop.
Merge or delete the easy non zero patients
from opal.models import Patient
from elcid.models import Demographics
from intrahospital_api import loader
from opal.core import subrecords
from django.db import transaction
@transaction.atomic
def update_patients_with_leading_zero_with_no_counter_part():
# patients with leading 0s but no duplicate, remove the 0, re-sync all upstream
cnt = 0
demos = Demographics.objects.filter(hospital_number__startswith='0').select_related('patient')
for demo in demos:
mrn = demo.hospital_number.lstrip('0')
if mrn and not Demographics.objects.filter(hospital_number=mrn).exists():
demo.hospital_number = mrn
demo.save()
loader.load_patient(demo.patient)
cnt += 1
print(f'updated {cnt} patients who had no non zero')
def delete_only_zero_patients():
# patients with all 00s and no other data, delete the patients
cnt = 0
demos = Demographics.objects.filter(hospital_number__startswith='0').filter(hospital_number__endswith='0').select_related(
'patient'
)
for demo in demos:
if not demo.hospital_number.lstrip('0'):
demo.patient.delete()
cnt += 1
print(f'updated {cnt} patients who were only zeros')
subrecordsToIgnore = set([
'InitialPatientLoad',
'Demographics',
'ContactInformation',
'NextOfKinDetails',
'GPDetails',
'ICUHandover',
'ExternalDemographics',
])
@transaction.atomic
def has_elcid_native_records(patient):
result = []
for subrecord in subrecords.episode_subrecords():
if subrecord._is_singleton:
result.extend(subrecord.objects.filter(episode__patient_id=patient.id).exclude(updated=None))
else:
result.extend(subrecord.objects.filter(episode__patient_id=patient.id))
for subrecord in subrecords.patient_subrecords():
if subrecord.__name__ in subrecordsToIgnore:
continue
if subrecord._is_singleton:
result.extend(subrecord.objects.filter(patient_id=patient.id).exclude(updated=None))
else:
result.extend(subrecord.objects.filter(patient_id=patient.id))
return result
@transaction.atomic
def delete_non_populated_non_zero_counter_parts():
demos = Demographics.objects.filter(hospital_number__startswith='0').filter(hospital_number__endswith='0')
for demo in demos:
without_hn = demo.hospital_number.lstrip('0')
if not without_hn:
continue
patients = Patient.objects.filter(demographics__hospital_number=without_hn)
cnt = patients.count()
if not cnt:
continue
if patients.count() > 1:
raise ValueError(f'hn {without_hn} is attached to multiple patients')
patient = patients.get()
if not has_elcid_native_records(patient):
patient.delete()
return update_patients_with_leading_zero_with_no_counter_part()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment