#!/usr/bin/env python """ Test script for HIS Integration with all patient types Tests the new HISPatientDataView endpoint with all 4 patient types: 1. Inpatient (PatientType: "1") 2. OPD (PatientType: "2" or "O") 3. EMS/Emergency (PatientType: "3" or "E") 4. Day Case (PatientType: "4" or "D") """ import os import sys import django import json from datetime import datetime, timedelta # Setup Django sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev') django.setup() from django.test import Client from apps.organizations.models import Hospital from apps.surveys.models import SurveyTemplate, SurveyInstance, SurveyStatus from apps.organizations.models import Patient def parse_date(date_obj: datetime) -> str: """Format date as DD-Mon-YYYY HH:MM""" months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] return f"{date_obj.day:02d}-{months[date_obj.month-1]}-{date_obj.year} {date_obj.hour:02d}:{date_obj.minute:02d}" def create_test_his_data(patient_type: str, patient_name: str, is_discharged: bool = True) -> dict: """Create test HIS patient data""" dob = datetime.now() - timedelta(days=30*365) # 30 years old admit_date = datetime.now() - timedelta(hours=5) discharge_date = admit_date + timedelta(hours=4) if is_discharged else None hospital = Hospital.objects.filter(status='active').first() hospital_name = hospital.name if hospital else "Test Hospital" his_data = { "FetchPatientDataTimeStampList": [{ "Type": "Patient Demographic details", "PatientID": "TEST-001", "AdmissionID": f"ADM-{patient_type}", "HospitalID": "1", "HospitalName": hospital_name, "PatientType": patient_type, "AdmitDate": parse_date(admit_date), "DischargeDate": parse_date(discharge_date) if discharge_date else None, "RegCode": "TEST.12345678", "SSN": "1234567890", "PatientName": patient_name, "GenderID": "1", "Gender": "Male", "FullAge": "30 Year(s)", "PatientNationality": "Saudi", "MobileNo": "0501234567", "Email": f"{patient_name.lower().replace(' ', '.')}@test.com", "DOB": parse_date(dob), "ConsultantID": "101", "PrimaryDoctor": "1001-Test Doctor", "CompanyID": "10001", "GradeID": "1001", "CompanyName": "Test Company", "GradeName": "A", "InsuranceCompanyName": "Test Insurance", "BillType": "CR", "IsVIP": "0" }], "FetchPatientDataTimeStampVisitDataList": [ {"Type": "Consultation", "BillDate": parse_date(admit_date + timedelta(minutes=30))}, {"Type": "Doctor Visited", "BillDate": parse_date(admit_date + timedelta(minutes=60))}, {"Type": "Clinical Condtion", "BillDate": parse_date(admit_date + timedelta(minutes=90))}, {"Type": "ChiefComplaint", "BillDate": parse_date(admit_date + timedelta(minutes=120))}, {"Type": "Prescribed Drugs", "BillDate": parse_date(admit_date + timedelta(minutes=150))} ], "Code": 200, "Status": "Success", "Message": "", "Message2L": "", "MobileNo": "", "ValidateMessage": "" } return his_data def test_patient_type(client: Client, patient_type: str, patient_name: str, expected_survey_type: str): """Test a specific patient type""" print(f"\n{'='*70}") print(f"Testing PatientType: {patient_type} ({expected_survey_type})") print(f"{'='*70}") # Create test HIS data his_data = create_test_his_data(patient_type, patient_name, is_discharged=True) # Send request to API print(f"\n๐Ÿ“ค Sending HIS patient data for: {patient_name}") print(f" PatientType: {patient_type}") response = client.post( '/api/integrations/events/', data=json.dumps(his_data), content_type='application/json' ) print(f"\n๐Ÿ“ฅ Response Status: {response.status_code}") if response.status_code == 200: result = response.json() print(f"\nโœ… SUCCESS") print(f" Message: {result.get('message')}") if result.get('patient'): patient = result['patient'] print(f"\n ๐Ÿ‘ค Patient Created:") print(f" ID: {patient.get('id')}") print(f" MRN: {patient.get('mrn')}") print(f" Name: {patient.get('name')}") if result.get('survey'): survey = result['survey'] print(f"\n ๐Ÿ“‹ Survey Created:") print(f" ID: {survey.get('id')}") print(f" Status: {survey.get('status')}") print(f" URL: {survey.get('survey_url')}") # Verify survey was created in database survey_id = result.get('survey', {}).get('id') if survey_id: survey = SurveyInstance.objects.filter(id=survey_id).first() if survey: print(f"\n ๐Ÿ” Database Verification:") print(f" Survey Found: Yes") print(f" Template: {survey.survey_template.name}") print(f" Patient: {survey.patient}") print(f" Status: {survey.status}") print(f" Delivery Channel: {survey.delivery_channel}") # Check if template matches expected type template_name = survey.survey_template.name.upper() if expected_survey_type.upper() in template_name: print(f" โœ… Template Type: CORRECT ({expected_survey_type})") else: print(f" โš ๏ธ Template Type: MISMATCH") print(f" Expected: {expected_survey_type}") print(f" Found: {survey.survey_template.name}") return True else: print(f"\n โŒ Database Verification:") print(f" Survey Found: NO") return False else: print(f"\nโŒ FAILED") print(f" Response: {response.json()}") return False def main(): """Run tests for all patient types""" print("="*70) print("๐Ÿงช HIS INTEGRATION TEST - All Patient Types") print("="*70) # Create test client client = Client() # Check if we have active survey templates templates = SurveyTemplate.objects.filter(is_active=True) if not templates.exists(): print("\nโš ๏ธ WARNING: No active survey templates found!") print(" Please create survey templates before running tests.") print("\n Required templates:") print(" - Inpatient Survey (or contains 'INPATIENT')") print(" - OPD Survey (or contains 'OPD')") print(" - EMS Survey (or contains 'EMS')") print(" - Day Case Survey (or contains 'DAY CASE')") return print(f"\n๐Ÿ“‹ Found {templates.count()} active survey template(s):") for template in templates: print(f" - {template.name}") # Test all patient types test_cases = [ ("1", "Test Inpatient", "Inpatient"), ("2", "Test OPD Patient", "OPD"), ("O", "Test OPD Patient Alt", "OPD"), ("3", "Test EMS Patient", "EMS"), ("E", "Test EMS Patient Alt", "EMS"), ("4", "Test Day Case Patient", "Day Case"), ("D", "Test Day Case Patient Alt", "Day Case"), ] results = [] for patient_type, patient_name, expected_type in test_cases: success = test_patient_type(client, patient_type, patient_name, expected_type) results.append({ 'patient_type': patient_type, 'patient_name': patient_name, 'expected_type': expected_type, 'success': success }) # Print summary print(f"\n{'='*70}") print("๐Ÿ“Š TEST SUMMARY") print(f"{'='*70}") total = len(results) successful = sum(1 for r in results if r['success']) failed = total - successful print(f"\nTotal Tests: {total}") print(f"Successful: {successful}") print(f"Failed: {failed}") if successful == total: print(f"\nโœ… ALL TESTS PASSED!") else: print(f"\nโŒ SOME TESTS FAILED:") for result in results: if not result['success']: print(f" - {result['patient_name']} (Type {result['patient_type']})") print(f"{'='*70}\n") if __name__ == "__main__": main()