375 lines
13 KiB
Python
375 lines
13 KiB
Python
#!/usr/bin/env python
|
|
"""
|
|
Test Simplified Survey Integration
|
|
|
|
This script tests the simplified flow where surveys are created directly
|
|
based on PatientType without journey tracking.
|
|
|
|
Test Coverage:
|
|
1. OPD patients get OPD surveys
|
|
2. Inpatient patients get Inpatient surveys
|
|
3. EMS patients get EMS surveys
|
|
4. Discharged patients receive surveys
|
|
5. Non-discharged patients don't receive surveys
|
|
6. Survey instances are created correctly
|
|
7. SMS delivery is attempted
|
|
"""
|
|
import os
|
|
import sys
|
|
import django
|
|
from datetime import datetime, timedelta
|
|
|
|
# Setup Django
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev')
|
|
django.setup()
|
|
|
|
from apps.surveys.models import SurveyTemplate, SurveyInstance
|
|
from apps.organizations.models import Hospital, Patient
|
|
from apps.integrations.services.his_adapter import HISAdapter
|
|
|
|
|
|
def create_test_hospitals():
|
|
"""Create test hospitals if they don't exist"""
|
|
hospitals = []
|
|
|
|
hospital_data = [
|
|
("ALH-main", "Al Hammadi Hospital - Main"),
|
|
("NUZHA-UAT", "Al Hammadi Hospital - Nuzha"),
|
|
]
|
|
|
|
for code, name in hospital_data:
|
|
hospital, created = Hospital.objects.get_or_create(
|
|
code=code,
|
|
defaults={
|
|
'name': name,
|
|
'status': 'active'
|
|
}
|
|
)
|
|
hospitals.append(hospital)
|
|
if created:
|
|
print(f"✓ Created hospital: {name}")
|
|
|
|
return hospitals
|
|
|
|
|
|
def create_test_surveys(hospital):
|
|
"""Create test survey templates for each type"""
|
|
survey_types = [
|
|
("OPD Survey", "Outpatient Department Survey"),
|
|
("INPATIENT Survey", "Inpatient Care Survey"),
|
|
("EMS Survey", "Emergency Medical Services Survey"),
|
|
]
|
|
|
|
created_surveys = []
|
|
|
|
for name, description in survey_types:
|
|
survey, created = SurveyTemplate.objects.get_or_create(
|
|
name=name,
|
|
hospital=hospital,
|
|
defaults={
|
|
'description': description,
|
|
'is_active': True,
|
|
'survey_type': 'patient_satisfaction'
|
|
}
|
|
)
|
|
created_surveys.append(survey)
|
|
if created:
|
|
print(f"✓ Created survey template: {name}")
|
|
|
|
return created_surveys
|
|
|
|
|
|
def generate_test_his_data(patient_type: str, is_discharged: bool = True, hospital_name: str = "Al Hammadi Hospital - Main") -> dict:
|
|
"""Generate test HIS data with specific PatientType and discharge status"""
|
|
admit_date = datetime.now() - timedelta(hours=6)
|
|
discharge_date = admit_date + timedelta(hours=5) if is_discharged else None
|
|
|
|
his_data = {
|
|
"FetchPatientDataTimeStampList": [{
|
|
"Type": "Patient Demographic details",
|
|
"PatientID": "TEST-001",
|
|
"AdmissionID": "ADM-TEST-001",
|
|
"HospitalID": "1",
|
|
"HospitalName": hospital_name,
|
|
"PatientType": patient_type,
|
|
"AdmitDate": admit_date.strftime("%d-%b-%Y %H:%M"),
|
|
"DischargeDate": discharge_date.strftime("%d-%b-%Y %H:%M") if discharge_date else None,
|
|
"RegCode": "ALHH.TEST001",
|
|
"SSN": "1234567890",
|
|
"PatientName": "Test Patient One",
|
|
"GenderID": "1",
|
|
"Gender": "Male",
|
|
"FullAge": "35 Year(s)",
|
|
"PatientNationality": "Saudi",
|
|
"MobileNo": "0512345678",
|
|
"Email": "test@example.com",
|
|
"DOB": "01-Jan-1990 00:00",
|
|
"ConsultantID": "101",
|
|
"PrimaryDoctor": "1001-Ahmed Al-Saud",
|
|
"CompanyID": "10001",
|
|
"GradeID": "1001",
|
|
"CompanyName": "Al Hammadi for Mgmt / Arabian Shield",
|
|
"GradeName": "A",
|
|
"InsuranceCompanyName": "Arabian Shield Cooperative Insurance Company",
|
|
"BillType": "CR",
|
|
"IsVIP": "0"
|
|
}],
|
|
"FetchPatientDataTimeStampVisitDataList": [],
|
|
"Code": 200,
|
|
"Status": "Success",
|
|
"Message": "",
|
|
"Message2L": "",
|
|
"MobileNo": "",
|
|
"ValidateMessage": ""
|
|
}
|
|
|
|
return his_data
|
|
|
|
|
|
def test_opd_survey(hospital):
|
|
"""Test that OPD patient type gets OPD survey"""
|
|
print("\n" + "="*70)
|
|
print("TEST 1: OPD Patient Survey")
|
|
print("="*70)
|
|
|
|
# Test with "2" (OPD)
|
|
his_data = generate_test_his_data("2", is_discharged=True, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
print(f"PatientType: 2 (OPD)")
|
|
print(f"Result: {result['message']}")
|
|
print(f"Survey Created: {result['survey'] is not None}")
|
|
print(f"Survey Type: {result['survey'].survey_template.name if result['survey'] else 'N/A'}")
|
|
|
|
if result['success'] and result['survey']:
|
|
survey = result['survey']
|
|
if 'OPD' in survey.survey_template.name.upper():
|
|
print("✅ PASS: OPD patient received OPD survey")
|
|
return True
|
|
else:
|
|
print("❌ FAIL: OPD patient did not receive OPD survey")
|
|
return False
|
|
else:
|
|
print("❌ FAIL: Survey not created")
|
|
return False
|
|
|
|
|
|
def test_inpatient_survey(hospital):
|
|
"""Test that Inpatient patient type gets Inpatient survey"""
|
|
print("\n" + "="*70)
|
|
print("TEST 2: Inpatient Patient Survey")
|
|
print("="*70)
|
|
|
|
# Test with "1" (Inpatient)
|
|
his_data = generate_test_his_data("1", is_discharged=True, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
print(f"PatientType: 1 (Inpatient)")
|
|
print(f"Result: {result['message']}")
|
|
print(f"Survey Created: {result['survey'] is not None}")
|
|
print(f"Survey Type: {result['survey'].survey_template.name if result['survey'] else 'N/A'}")
|
|
|
|
if result['success'] and result['survey']:
|
|
survey = result['survey']
|
|
if 'INPATIENT' in survey.survey_template.name.upper():
|
|
print("✅ PASS: Inpatient patient received Inpatient survey")
|
|
return True
|
|
else:
|
|
print("❌ FAIL: Inpatient patient did not receive Inpatient survey")
|
|
return False
|
|
else:
|
|
print("❌ FAIL: Survey not created")
|
|
return False
|
|
|
|
|
|
def test_ems_survey(hospital):
|
|
"""Test that EMS patient type gets EMS survey"""
|
|
print("\n" + "="*70)
|
|
print("TEST 3: EMS Patient Survey")
|
|
print("="*70)
|
|
|
|
# Test with "3" (EMS)
|
|
his_data = generate_test_his_data("3", is_discharged=True, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
print(f"PatientType: 3 (EMS)")
|
|
print(f"Result: {result['message']}")
|
|
print(f"Survey Created: {result['survey'] is not None}")
|
|
print(f"Survey Type: {result['survey'].survey_template.name if result['survey'] else 'N/A'}")
|
|
|
|
if result['success'] and result['survey']:
|
|
survey = result['survey']
|
|
if 'EMS' in survey.survey_template.name.upper():
|
|
print("✅ PASS: EMS patient received EMS survey")
|
|
return True
|
|
else:
|
|
print("❌ FAIL: EMS patient did not receive EMS survey")
|
|
return False
|
|
else:
|
|
print("❌ FAIL: Survey not created")
|
|
return False
|
|
|
|
|
|
def test_not_discharged_no_survey(hospital):
|
|
"""Test that non-discharged patients don't receive surveys"""
|
|
print("\n" + "="*70)
|
|
print("TEST 4: Non-Discharged Patient (No Survey)")
|
|
print("="*70)
|
|
|
|
# Test without discharge date
|
|
his_data = generate_test_his_data("2", is_discharged=False, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
print(f"PatientType: 2 (OPD)")
|
|
print(f"Discharged: No")
|
|
print(f"Result: {result['message']}")
|
|
print(f"Survey Created: {result['survey'] is not None}")
|
|
|
|
if result['success'] and result['survey'] is None:
|
|
if 'not discharged' in result['message'].lower():
|
|
print("✅ PASS: Non-discharged patient did not receive survey")
|
|
return True
|
|
else:
|
|
print("❌ FAIL: Unexpected result for non-discharged patient")
|
|
return False
|
|
else:
|
|
print("❌ FAIL: Survey was created for non-discharged patient")
|
|
return False
|
|
|
|
|
|
def test_alternative_patient_type_codes(hospital):
|
|
"""Test alternative PatientType codes (O for OPD, E for EMS)"""
|
|
print("\n" + "="*70)
|
|
print("TEST 5: Alternative PatientType Codes")
|
|
print("="*70)
|
|
|
|
# Test "O" (OPD alternative)
|
|
his_data = generate_test_his_data("O", is_discharged=True, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
print(f"PatientType: O (OPD alternative)")
|
|
print(f"Result: {result['message']}")
|
|
print(f"Survey Type: {result['survey'].survey_template.name if result['survey'] else 'N/A'}")
|
|
|
|
opd_pass = False
|
|
if result['success'] and result['survey']:
|
|
if 'OPD' in result['survey'].survey_template.name.upper():
|
|
opd_pass = True
|
|
print("✅ PASS: PatientType 'O' mapped to OPD survey")
|
|
else:
|
|
print("❌ FAIL: PatientType 'O' did not map to OPD survey")
|
|
|
|
# Test "E" (EMS alternative)
|
|
his_data = generate_test_his_data("E", is_discharged=True, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
print(f"\nPatientType: E (EMS alternative)")
|
|
print(f"Result: {result['message']}")
|
|
print(f"Survey Type: {result['survey'].survey_template.name if result['survey'] else 'N/A'}")
|
|
|
|
ems_pass = False
|
|
if result['success'] and result['survey']:
|
|
if 'EMS' in result['survey'].survey_template.name.upper():
|
|
ems_pass = True
|
|
print("✅ PASS: PatientType 'E' mapped to EMS survey")
|
|
else:
|
|
print("❌ FAIL: PatientType 'E' did not map to EMS survey")
|
|
|
|
return opd_pass and ems_pass
|
|
|
|
|
|
def test_survey_metadata(hospital):
|
|
"""Test that survey metadata is correctly stored"""
|
|
print("\n" + "="*70)
|
|
print("TEST 6: Survey Metadata")
|
|
print("="*70)
|
|
|
|
his_data = generate_test_his_data("1", is_discharged=True, hospital_name=hospital.name)
|
|
result = HISAdapter.process_his_data(his_data)
|
|
|
|
if result['success'] and result['survey']:
|
|
survey = result['survey']
|
|
metadata = survey.metadata
|
|
|
|
print(f"Survey ID: {survey.id}")
|
|
print(f"Patient: {survey.patient.get_full_name()}")
|
|
print(f"Hospital: {survey.hospital.name}")
|
|
print(f"Delivery Channel: {survey.delivery_channel}")
|
|
print(f"Recipient Phone: {survey.recipient_phone}")
|
|
print(f"\nMetadata:")
|
|
for key, value in metadata.items():
|
|
print(f" {key}: {value}")
|
|
|
|
# Check critical metadata
|
|
checks = {
|
|
'admission_id': 'ADM-TEST-001' in metadata.get('admission_id', ''),
|
|
'patient_type': metadata.get('patient_type') == '1',
|
|
'insurance_company': 'Arabian Shield' in metadata.get('insurance_company', '')
|
|
}
|
|
|
|
all_pass = all(checks.values())
|
|
|
|
if all_pass:
|
|
print("\n✅ PASS: All metadata fields correctly stored")
|
|
else:
|
|
print("\n❌ FAIL: Some metadata fields missing or incorrect")
|
|
for key, value in checks.items():
|
|
if not value:
|
|
print(f" - {key}: FAILED")
|
|
|
|
return all_pass
|
|
else:
|
|
print("❌ FAIL: Survey not created")
|
|
return False
|
|
|
|
|
|
def main():
|
|
"""Run all tests"""
|
|
print("="*70)
|
|
print("🧪 SIMPLIFIED SURVEY INTEGRATION TESTS")
|
|
print("="*70)
|
|
print("\nTesting direct survey creation based on PatientType")
|
|
print("without journey tracking complexity\n")
|
|
|
|
# Setup test data
|
|
print("Setting up test environment...")
|
|
hospitals = create_test_hospitals()
|
|
hospital = hospitals[0]
|
|
create_test_surveys(hospital)
|
|
print("✓ Test environment ready\n")
|
|
|
|
# Run tests
|
|
results = {
|
|
'OPD Survey': test_opd_survey(hospital),
|
|
'Inpatient Survey': test_inpatient_survey(hospital),
|
|
'EMS Survey': test_ems_survey(hospital),
|
|
'Non-Discharged No Survey': test_not_discharged_no_survey(hospital),
|
|
'Alternative PatientType Codes': test_alternative_patient_type_codes(hospital),
|
|
'Survey Metadata': test_survey_metadata(hospital)
|
|
}
|
|
|
|
# Print summary
|
|
print("\n" + "="*70)
|
|
print("📊 TEST SUMMARY")
|
|
print("="*70)
|
|
|
|
passed = sum(results.values())
|
|
total = len(results)
|
|
|
|
for test_name, result in results.items():
|
|
status = "✅ PASS" if result else "❌ FAIL"
|
|
print(f"{status}: {test_name}")
|
|
|
|
print(f"\nTotal: {passed}/{total} tests passed ({(passed/total)*100:.1f}%)")
|
|
print("="*70)
|
|
|
|
if passed == total:
|
|
print("\n🎉 All tests passed! Simplified integration is working correctly.")
|
|
return 0
|
|
else:
|
|
print(f"\n⚠️ {total - passed} test(s) failed. Please review the output above.")
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main()) |