📚 System Logic Documentation

Back to Home

System Business Logic Documentation

📋 This document explains how the medical report generator works

Table of Contents

  1. How It Works
  2. Supported Test Types
  3. Region/Lab Detection
  4. Excel File Requirements
  5. Report Generation Rules
  6. File Naming Rules
  7. Date Handling
  8. Multi-Test Support
  9. Adding a New Test Type
  10. Adding a New Region/Lab

How It Works

Step-by-Step Process

  1. Upload Excel File
  2. You upload an Excel file (.xlsx) with patient information
  3. The system validates the file has all required columns

  4. Process Each Patient

  5. For each row in the Excel file, the system:

    • Reads patient information
    • Identifies which test(s) were requested
    • Selects the correct template for each test
    • Generates individual reports
  6. Download Reports

  7. All reports are packaged into a ZIP file
  8. Each report is a Word document (.docx)
  9. Reports maintain all template formatting and styling

What Happens to Your Data

Excel Row → Read Patient Info → Detect Test Type(s) → Select Template(s) → Generate Report(s) → ZIP File

Important: One patient can generate multiple reports if they have multiple test types!


Supported Test Types

The system recognizes these test patterns in the "Xét nghiệm" column:

Test Code Pattern to Look For Template Used
HPV "HPV Genotyping" HPV_{REGION}.docx
STD "Sexually Transmissible Disease" STD_{REGION}.docx
GBS "PCR GBS (Group B Streptococcus)" GBS_{REGION}.docx
CTNG "Neisseria gonorrhoeae-Chlamydia trachomatis DNA" CTNG_{REGION}.docx
HBV "HBV DNA" HBV_{REGION}.docx
HCV "HCV RNA Realtime" HCV_{REGION}.docx

Note: {REGION} is automatically detected from the "Bác sĩ" column (see Region/Lab Detection section below).


Region/Lab Detection

The system automatically selects the appropriate regional template based on the health facility name in the "Bác sĩ" column.

Supported Labs

Lab Code Lab Name Trigger Patterns
SG Sư Vạn Hạnh Default (all other facilities)
HN HN/ĐN "TÂM AN ĐÀ NẴNG" or "TÂM AN HÀ NỘI"
GIAAN Gia An "BV Đa Khoa Vạn Gia An"
Thủ Đức "Tâm An Thủ Đức"
JIO JIO Health "C- Mother Clinic" or "Home Visit"

How Region Detection Works

  1. System reads the "Bác sĩ" column value
  2. Checks if it contains any of the trigger patterns
  3. If a match is found, uses that region's template
  4. If no match is found, defaults to SG (Sư Vạn Hạnh)

Examples

"Bác sĩ" Value Detected Region Template Used
"BS. Phòng Khám ABC" SG HPV_SG.docx
"TÂM AN ĐÀ NẴNG" HN HPV_HN.docx
"TÂM AN HÀ NỘI" HN HPV_HN.docx
"BV Đa Khoa Vạn Gia An" GIAAN HPV_GIAAN.docx
"Tâm An Thủ Đức" HPV_TĐ.docx
"C- Mother Clinic" JIO HPV_JIO.docx
"Home Visit" JIO HPV_JIO.docx

Important: Each region may have different placeholder values and formatting in their templates.


Test Type Examples

What You Write in "Xét nghiệm" Reports Generated
HPV Genotyping: 1 HPV report
Sexually Transmissible Disease: 1 STD report
HPV Genotyping:x, STD: 2 reports (HPV + STD)
HBV DNA:, HCV RNA Realtime: 2 reports (HBV + HCV)

Note: If the system doesn't recognize the test type, that row will be skipped with a warning.


Excel File Requirements

Required Columns

These columns must exist in your Excel file:

Column Name What It Means Example
STT Sample tracking number 240126-9797
Ngày ĐK Registration date 2026-01-24
PID Patient ID (optional but recommended) PTS 01
Họ tên Patient name NGUYỄN VĂN A
Bác sĩ Doctor/Health facility Phòng Khám ABC
Năm sinh Birth year 1990
Tuổi Age 36
G.Tính Sex (M/F) M
Địa chỉ Address 123 Đường ABC, Quận 1
Xét nghiệm Test type(s) HPV Genotyping:

Required Values

These columns cannot be empty: - STT - Must have a value - Họ tên - Must have patient name

Optional Columns

  • Chẩn đoán - Diagnosis
  • SĐT - Phone number
  • Kết luận - Conclusion

Report Generation Rules

Rule 1: One Test Type = One Report

Each test type generates a separate report file.

Example: - Patient has: HPV Genotyping:, STD: - System generates: 2 separate Word documents

Rule 2: Report Uses Correct Template

The system automatically selects the correct template based on: 1. Test type (from "Xét nghiệm" column) 2. Region/Lab (from "Bác sĩ" column)

Examples: - HPV test + TÂM AN HÀ NỘI → Uses HPV_HN.docx - STD test + C- Mother Clinic → Uses STD_JIO.docx - GBS test + Other facility → Uses GBS_SG.docx (default)

Rule 3: Patient Information is Filled In

The system replaces placeholder values in the template with actual patient data: - Report ID (from STT column) - Patient Name - Health Facility/Doctor - Birth Year - Sex - Address - Registration Date - Report Date

Rule 4: Dates are Formatted Consistently

All dates in reports follow the format: DD/MM/YYYY

Example: 24/01/2026


File Naming Rules

Generated report files follow this naming pattern:

With PID (Patient ID)

{TEST_TYPE} - {PID} - {PATIENT_NAME} - {REPORT_ID}.docx

Example:

HPV - PTS 01 - NGUYỄN VĂN A - 9851.docx
STD - PTS 02 - TRẦN THỊ B - 9632.docx

Without PID

{TEST_TYPE} - {PATIENT_NAME} - {REPORT_ID}.docx

Example:

GBS - LÊ VĂN C - 1018.docx

ZIP File Name

medical_reports_{TIMESTAMP}.zip

Example: medical_reports_20260126_143055.zip


Date Handling

Registration Date (Ngày ĐK)

  • Source: "Ngày ĐK" column in Excel
  • Used for: Date sample was received
  • Format: Must be a valid date (Excel date format is fine)

Report Date

You have two options:

Option 1: Use Today's Date (Default) - Don't select a date in the form - System automatically uses today's date

Option 2: Use Custom Date - Select a date using the date picker on the upload page - This date will be used for ALL reports in the batch - Useful for backdating reports

STT Column Format

The STT column contains the sample tracking number in this format:

DDMMYY-XXXXX

Example: 240126-9797 - 240126 = 24/01/2026 (date part - not used for date_received anymore) - 9797 = Report ID

Note: The system now uses "Ngày ĐK" column for the registration date, not the STT date part.


Multi-Test Support

How It Works

One patient row can request multiple tests, and the system will generate multiple reports.

Example Scenario

Excel Row: - Họ tên: NGUYỄN VĂN A - PID: PTS 01 - STT: 240126-9851 - Xét nghiệm: HPV Genotyping:x, Sexually Transmissible Disease:

Generated Reports: 1. HPV - PTS 01 - NGUYỄN VĂN A - 9851.docx 2. STD - PTS 01 - NGUYỄN VĂN A - 9851.docx

Benefits

  • No need to duplicate patient information
  • One Excel row can generate multiple reports
  • Saves time and reduces errors
  • All reports for the same patient use the same data

Common Scenarios

Scenario 1: Standard Single Test

Input: - 10 patients, each with one test type

Output: - 10 report files in ZIP

Scenario 2: Mixed Test Types

Input: - 5 patients with HPV - 3 patients with STD - 2 patients with both HPV and STD

Output: - 12 report files in ZIP (5 + 3 + 4)

Scenario 3: Batch with Custom Report Date

Input: - Upload 20 patients - Select report date: 20/01/2026

Output: - All 20 reports use 20/01/2026 as the report date - Registration dates remain from "Ngày ĐK" column


Error Handling

What Gets Skipped

The system will skip rows if: - Patient name (Họ tên) is empty - STT is empty - Test type is not recognized - Template file doesn't exist (even after fallback to SG)

Note: If a region-specific template is missing, the system automatically falls back to the SG (Sư Vạn Hạnh) template.

What You'll See

  • Rows processed successfully: Reports generated
  • Rows with errors: Warning message shown
  • Empty rows: Skipped automatically
  • Unknown test types: Skipped with warning

Best Practices

1. Prepare Your Excel File

  • Use the example file as a template
  • Fill in all required columns
  • Use correct test type names
  • Double-check patient names and IDs

2. Verify Before Upload

  • Check the file statistics preview
  • Look for warnings about unknown test types
  • Ensure row counts match expectations

3. Choose Report Date Wisely

  • Leave blank for current date
  • Select past date only if backdating is intentional
  • Remember: ALL reports in the batch use the same report date

4. Review Generated Files

  • Check ZIP file contains expected number of reports
  • Verify file names are correct
  • Spot-check a few reports for accuracy

Summary

Key Points to Remember

  1. ✅ One Excel row can generate multiple reports
  2. ✅ Test type in "Xét nghiệm" determines which test template to use
  3. ✅ Region/Lab in "Bác sĩ" determines which regional template to use
  4. ✅ System supports 5 labs: Sư Vạn Hạnh (SG), HN/ĐN, Gia An, Thủ Đức, and JIO Health
  5. ✅ Report date can be customized or defaults to today
  6. ✅ File names include test type, patient ID, name, and report ID
  7. ✅ All reports are packaged in a timestamped ZIP file
  8. ✅ Empty rows and unknown test types are skipped
  9. ✅ Missing regional templates automatically fall back to SG templates

Support

If you encounter issues: - Check your Excel file has all required columns - Verify test type names match exactly - Ensure patient names and STT are not empty - Review the file statistics table before generating - Check the "By Lab & Test Type" table to verify region detection - If wrong templates are used, verify the "Bác sĩ" column contains correct facility names


Adding a New Test Type

Adding a new test type requires configuration and template files for each region.

Step 1: Add Configuration

Edit template_selector.py and add an entry to the TEST_TYPES dictionary:

TEST_TYPES = {
    # ... existing types ...
    "NEW": {
        "pattern": "New Test Name",  # Pattern to match in "Xét nghiệm" column
        "template_placeholders": {
            "SG": {
                "report_id_placeholder": "1234",
                "patient_name_placeholder": "SAMPLE NAME",
                "health_facility_placeholder": "Sample Facility",
                "age_placeholder": "1990",
                "sex_placeholder": "Nam",
            },
            "HN": {
                "report_id_placeholder": "5678",
                "patient_name_placeholder": "NGUYEN VAN A",
                "health_facility_placeholder": "TÂM AN HÀ NỘI",
                "age_placeholder": "1985",
                "sex_placeholder": "Nam",
            },
            # Add entries for GIAAN, TĐ, JIO as needed
        },
        "default_result": None,  # Or region-specific dict if needed
    },
}

Step 2: Add Template Files

Create template files for each region you support:

test_templates/NEW_SG.docx      # Sư Vạn Hạnh (required - used as fallback)
test_templates/NEW_HN.docx      # HN/ĐN (optional)
test_templates/NEW_GIAAN.docx   # Gia An (optional)
test_templates/NEW_TĐ.docx      # Thủ Đức (optional)
test_templates/NEW_JIO.docx     # JIO Health (optional)

Replace NEW with your test code (e.g., HIV, COVID, etc.).

Note: If a region-specific template doesn't exist, the system automatically falls back to the SG template.

Configuration Fields

Field Required Description
pattern Yes The exact text to search for in "Xét nghiệm" column
template_placeholders Yes Placeholder values in the template to replace
default_result No Default result text (used for HBV/HCV type tests)

Verification

After adding a new test type: 1. Run tests: pytest tests/test_template_selector.py 2. Start server and test with sample data 3. Verify the new test type appears in /api/config endpoint


Adding a New Region/Lab

Adding support for a new regional lab requires updating configuration and creating templates.

Step 1: Add Region Mapping

Edit template_selector.py and add an entry to the REGION_MAPPINGS dictionary:

REGION_MAPPINGS = {
    "HN": ["TÂM AN ĐÀ NẴNG", "TÂM AN HÀ NỘI"],
    "GIAAN": ["BV Đa Khoa Vạn Gia An"],
    "TĐ": ["Tâm An Thủ Đức"],
    "JIO": ["C- Mother Clinic", "Home Visit"],
    "NEW_REGION": ["Pattern 1", "Pattern 2"],  # Add your region here
}

The patterns are case-sensitive and use substring matching (contains).

Step 2: Add Region Placeholders

For each test type in TEST_TYPES, add placeholder configuration for the new region:

"HPV": {
    "pattern": "HPV Genotyping",
    "template_placeholders": {
        # ... existing regions ...
        "NEW_REGION": {
            "report_id_placeholder": "9999",
            "patient_name_placeholder": "SAMPLE NAME",
            "health_facility_placeholder": "New Facility Name",
            "age_placeholder": "1990",
            "sex_placeholder": "Nam",
        },
    },
    "default_result": None,
},

Repeat for all 6 test types: HPV, STD, GBS, CTNG, HBV, HCV.

Step 3: Create Template Files

Create Word document templates for all test types:

test_templates/HPV_NEW_REGION.docx
test_templates/STD_NEW_REGION.docx
test_templates/GBS_NEW_REGION.docx
test_templates/CTNG_NEW_REGION.docx
test_templates/HBV_NEW_REGION.docx
test_templates/HCV_NEW_REGION.docx

Step 4: Update UI (Optional)

Update templates/index.html to add the new region to the documentation:

<li><strong>NEW_REGION</strong> - When "Bác sĩ" contains "Pattern 1" or "Pattern 2"</li>

Also update the JavaScript display labels if you want a friendly name:

const regionLabels = {
  "SG": "Sư Vạn Hạnh",
  "HN": "HN/ĐN",
  "TĐ": "Thủ Đức",
  "GIAAN": "Gia An",
  "JIO": "JIO",
  "NEW_REGION": "Friendly Name"  // Add this
};

Step 5: Update Default Results (if applicable)

If the region has different default result text for HBV/HCV tests:

"HBV": {
    # ... existing config ...
    "default_result": {
        "SG": "Dưới ngưỡng phát hiện (Không có nghĩa là âm tính)",
        "HN": "Dưới ngưỡng phát hiện",
        "NEW_REGION": "Your custom text here",
    },
},

Verification

After adding a new region: 1. Test region detection with sample "Bác sĩ" values 2. Verify correct templates are selected 3. Generate test reports to ensure all placeholders work 4. Check the statistics table shows the new region correctly


Last Updated: 2026-01-27