HH/fix_survey_hospital.py

76 lines
2.6 KiB
Python

#!/usr/bin/env python
"""
Fix survey hospital assignments to match user hospitals
"""
import os
import django
# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev')
django.setup()
from apps.surveys.models import SurveyInstance, SurveyTemplate
from apps.organizations.models import Hospital
print("="*70)
print("FIXING SURVEY HOSPITAL ASSIGNMENTS")
print("="*70)
# Get hospitals
alhammadi_main = Hospital.objects.filter(code='ALH-main').first()
alhammadi_hh = Hospital.objects.filter(code='HH').first()
print(f"\nAl Hammadi Hospital (ALH-main): {alhammadi_main.name if alhammadi_main else 'NOT FOUND'}")
print(f"Alhammadi Hospital (HH): {alhammadi_hh.name if alhammadi_hh else 'NOT FOUND'}")
# Check which hospital surveys are in
surveys = SurveyInstance.objects.select_related('survey_template__hospital')
surveys_with_main = surveys.filter(survey_template__hospital=alhammadi_main).count()
surveys_with_hh = surveys.filter(survey_template__hospital=alhammadi_hh).count()
print(f"\nSurveys in ALH-main hospital: {surveys_with_main}")
print(f"Surveys in HH hospital: {surveys_with_hh}")
# Fix: Move surveys from ALH-main to HH if HH exists and has no surveys
if alhammadi_hh and surveys_with_main > 0 and surveys_with_hh == 0:
print(f"\nMoving {surveys_with_main} surveys from ALH-main to HH...")
# Update templates
templates = SurveyTemplate.objects.filter(hospital=alhammadi_main)
updated_count = templates.update(hospital=alhammadi_hh)
print(f"✓ Updated {updated_count} survey templates")
# Verify
surveys_after = SurveyInstance.objects.filter(
survey_template__hospital=alhammadi_hh
).count()
print(f"✓ Now {surveys_after} surveys in HH hospital")
else:
if not alhammadi_hh:
print("\nCannot fix: HH hospital not found")
elif surveys_with_hh > 0:
print(f"\nNo need to fix: HH already has {surveys_with_hh} surveys")
elif surveys_with_main == 0:
print("\nNo need to fix: ALH-main has no surveys")
print("\n" + "="*70)
print("Current Hospital Assignment Summary")
print("="*70)
for hospital in Hospital.objects.all():
survey_count = SurveyInstance.objects.filter(
survey_template__hospital=hospital
).count()
template_count = SurveyTemplate.objects.filter(
hospital=hospital
).count()
print(f"\n{hospital.name} ({hospital.code}):")
print(f" Templates: {template_count}")
print(f" Surveys: {survey_count}")
print("\n" + "="*70)
print("FIX COMPLETE")
print("="*70)
print("\nNow visit the page as test.user or mohamad.a al gailani")
print("The charts should display data!")