# Backend Specification

## 1. System Summary

**System Name:** Healthcare Management System

**Description:**  
A comprehensive web-based application to streamline healthcare operations including patient records, appointments, consultations, billing, and reporting. The system supports role-based workflows for administrators, doctors, nurses, receptionists, and billing officers to manage the complete patient care lifecycle from registration through billing.

**Core Modules:**
- **Department Management:** Organizational units and department configuration
- **User Management:** User accounts, authentication, authorization, and audit trail
- **Patient Management:** Patient demographics, registration, and medical history
- **Insurance Management:** Insurance provider directory and coverage policies
- **Appointment Management:** Appointment scheduling, calendar, and status management
- **Clinical Management:** Clinical workflows including consultations, prescriptions, vital signs, and lab orders
- **Billing Management:** Billing, invoicing, payment processing, and service catalog
- **Reporting:** Report generation, analytics, and business intelligence

## 2. Source Input Summary

**DDL Schema:**  
19 tables including departments, users, patients, appointments, consultations, prescriptions, vital_signs, medical_records, lab_tests, invoices, payments, services, insurance_providers, reports, audit_logs, and invoice_line_items.

**PRD Documentation:**  
5 core pages (Dashboard, Patient Management, Appointment & Scheduling, Clinical & Consultation, Billing & Reports) with detailed role-based workflows for administrators, doctors, nurses, receptionists, and billing officers.

**Source Files:**
- DDL file: `/home/ubuntu/dpg/pipeline/step-02-prd-generation/output/20260514_063824/schema.sql`
- PRD file: `/home/ubuntu/dpg/pipeline/step-02-prd-generation/output/20260514_063824/full_prd.md`

## 3. Generation Mode

**Mode:** Strict

The backend strictly adheres to the provided DDL schema and PRD specifications. All entities, fields, relationships, and workflows are implemented exactly as defined in the source documents. No additional features or modifications are introduced beyond what is explicitly documented.

## 4. Backend Scope

The backend provides a complete RESTful API supporting:

1. **CRUD Operations** for all core entities (departments, users, patients, appointments, consultations, prescriptions, vital signs, lab tests, invoices, payments, services, insurance providers, reports)
2. **Detail Endpoints** with eager-loaded relationships for complex data retrieval
3. **Batch Write Services** for transactional operations spanning multiple entities
4. **Workflow Endpoints** for specific business processes (check-in, payment processing, report generation)
5. **Audit Logging** for all user actions
6. **Role-Based Access Control** enforcement

**Technology Stack:**
- FastAPI framework
- SQLAlchemy ORM with SQLite database
- Pydantic v2 for request/response validation
- Service layer pattern for business logic
- Dependency injection for database sessions

## 5. Roles

The system supports five distinct user roles with specific permissions:

| Role | Label | Permissions |
|------|-------|-------------|
| Administrator | ADMINISTRATOR | Full system access; manage users, departments, system configuration |
| Doctor | DOCTOR | View/edit consultations, prescriptions, lab tests; view patient records |
| Nurse | NURSE | Record vital signs, view appointments, limited patient record access |
| Receptionist | RECEPTIONIST | Manage appointments, patient registration, check-in patients |
| Billing Officer | BILLING_OFFICER | Create invoices, process payments, generate billing reports |

## 6. Entities and Fields

### Department

**Table:** `departments`  
**Description:** Organizational units within the healthcare facility

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| name | str | Yes | Department name (unique) |
| description | Optional[str] | No | Department description |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Insuranceprovider

**Table:** `insurance_providers`  
**Description:** Insurance companies accepted by the facility

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| name | str | Yes | Insurance provider name |
| contact_person | Optional[str] | No | Contact person name |
| phone | Optional[str] | No | Contact phone number |
| email | Optional[str] | No | Contact email address |
| address | Optional[str] | No | Provider address |
| coverage_policy | Optional[str] | No | Coverage policy details |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### User

**Table:** `users`  
**Description:** System users including administrators, doctors, nurses, receptionists, and billing officers

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| email | str | Yes | User email (unique) |
| password_hash | str | Yes | Hashed password |
| first_name | str | Yes | User first name |
| last_name | str | Yes | User last name |
| role | str | Yes | User role (administrator, doctor, nurse, receptionist, billing_officer) |
| phone | Optional[str] | No | User phone number |
| department_id | Optional[str] | No | Department assignment |
| is_active | bool | Yes | Active status flag |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `is_active`

### Patient

**Table:** `patients`  
**Description:** Individuals receiving healthcare services

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| patient_number | str | Yes | Unique patient identification number |
| first_name | str | Yes | Patient first name |
| last_name | str | Yes | Patient last name |
| date_of_birth | date | Yes | Patient date of birth |
| gender | str | Yes | Patient gender (male, female, other) |
| phone | Optional[str] | No | Patient phone number |
| email | Optional[str] | No | Patient email address |
| address | Optional[str] | No | Patient street address |
| city | Optional[str] | No | Patient city |
| state | Optional[str] | No | Patient state/province |
| postal_code | Optional[str] | No | Patient postal code |
| country | Optional[str] | No | Patient country |
| emergency_contact_name | Optional[str] | No | Emergency contact person name |
| emergency_contact_phone | Optional[str] | No | Emergency contact phone number |
| emergency_contact_relationship | Optional[str] | No | Emergency contact relationship to patient |
| insurance_provider_id | Optional[str] | No | Primary insurance provider |
| insurance_policy_number | Optional[str] | No | Insurance policy number |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Medicalrecord

**Table:** `medical_records`  
**Description:** Comprehensive health record for each patient

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| patient_id | str | Yes | Patient reference (unique) |
| blood_type | Optional[str] | No | Patient blood type |
| allergies | Optional[str] | No | Known allergies |
| chronic_conditions | Optional[str] | No | Chronic medical conditions |
| family_medical_history | Optional[str] | No | Family medical history |
| surgical_history | Optional[str] | No | Past surgeries |
| immunization_history | Optional[str] | No | Immunization records |
| notes | Optional[str] | No | Additional medical notes |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Appointment

**Table:** `appointments`  
**Description:** Scheduled visits between patients and healthcare providers

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| patient_id | str | Yes | Patient reference |
| doctor_id | str | Yes | Assigned doctor reference |
| department_id | Optional[str] | No | Department reference |
| appointment_date | date | Yes | Appointment date |
| appointment_time | time | Yes | Appointment time |
| duration_minutes | int | Yes | Appointment duration in minutes |
| appointment_type | str | Yes | Type of appointment (consultation, follow_up, emergency, routine_checkup, procedure) |
| status | str | Yes | Appointment status (scheduled, confirmed, checked_in, in_progress, completed, cancelled, no_show) |
| reason | Optional[str] | No | Reason for visit |
| notes | Optional[str] | No | Additional notes |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `status`

### Vitalsign

**Table:** `vital_signs`  
**Description:** Patient vital measurements captured during visits

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| patient_id | str | Yes | Patient reference |
| recorded_by_user_id | str | Yes | User who recorded vitals |
| recorded_at | datetime | Yes | Recording timestamp |
| systolic_bp | Optional[int] | No | Systolic blood pressure |
| diastolic_bp | Optional[int] | No | Diastolic blood pressure |
| pulse_rate | Optional[int] | No | Pulse rate in bpm |
| temperature_celsius | Optional[float] | No | Body temperature in Celsius |
| respiratory_rate | Optional[int] | No | Respiratory rate |
| weight_kg | Optional[float] | No | Weight in kilograms |
| height_cm | Optional[float] | No | Height in centimeters |
| oxygen_saturation | Optional[int] | No | Oxygen saturation percentage |
| notes | Optional[str] | No | Additional notes |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Consultation

**Table:** `consultations`  
**Description:** Medical consultation sessions with examination findings and diagnoses

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| appointment_id | Optional[str] | No | Related appointment (unique) |
| patient_id | str | Yes | Patient reference |
| doctor_id | str | Yes | Doctor conducting consultation |
| consultation_date | datetime | Yes | Consultation date and time |
| chief_complaint | Optional[str] | No | Patient's chief complaint |
| present_illness | Optional[str] | No | History of present illness |
| examination_findings | Optional[str] | No | Physical examination findings |
| diagnosis | Optional[str] | No | Medical diagnosis |
| treatment_plan | Optional[str] | No | Treatment plan and recommendations |
| notes | Optional[str] | No | Additional clinical notes |
| follow_up_required | bool | Yes | Follow-up required flag |
| follow_up_date | Optional[date] | No | Recommended follow-up date |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Prescription

**Table:** `prescriptions`  
**Description:** Medication orders created by doctors

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| consultation_id | str | Yes | Related consultation |
| patient_id | str | Yes | Patient reference |
| doctor_id | str | Yes | Prescribing doctor |
| medication_name | str | Yes | Name of medication |
| dosage | str | Yes | Dosage strength |
| frequency | str | Yes | Dosage frequency |
| duration | str | Yes | Treatment duration |
| quantity | Optional[int] | No | Quantity to dispense |
| route | Optional[str] | No | Route of administration |
| special_instructions | Optional[str] | No | Special instructions |
| is_active | bool | Yes | Active status flag |
| prescribed_date | date | Yes | Prescription issue date |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `is_active`

### Service

**Table:** `services`  
**Description:** Medical services offered by the facility

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| name | str | Yes | Service name |
| description | Optional[str] | No | Service description |
| service_type | str | Yes | Service type (consultation, procedure, lab_test, imaging, therapy, surgery, vaccination, other) |
| default_price | float | Yes | Default price |
| default_duration_minutes | Optional[int] | No | Default duration in minutes |
| department_id | Optional[str] | No | Department offering service |
| is_active | bool | Yes | Active status flag |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `is_active`

### Labtest

**Table:** `lab_tests`  
**Description:** Laboratory test orders and results

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| patient_id | str | Yes | Patient reference |
| consultation_id | Optional[str] | No | Related consultation |
| ordered_by_doctor_id | str | Yes | Doctor who ordered test |
| test_name | str | Yes | Name of lab test |
| test_type | Optional[str] | No | Type of test |
| ordered_date | datetime | Yes | Test order date |
| sample_collected_date | Optional[datetime] | No | Sample collection date |
| result_date | Optional[datetime] | No | Result availability date |
| result_value | Optional[str] | No | Test result value |
| result_unit | Optional[str] | No | Result unit of measurement |
| reference_range | Optional[str] | No | Normal reference range |
| status | str | Yes | Test status (ordered, sample_collected, in_progress, completed, cancelled) |
| notes | Optional[str] | No | Additional notes |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `status`

### Invoice

**Table:** `invoices`  
**Description:** Billing documents for services rendered

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| invoice_number | str | Yes | Unique invoice number |
| patient_id | str | Yes | Patient reference |
| appointment_id | Optional[str] | No | Related appointment |
| invoice_date | date | Yes | Invoice date |
| due_date | Optional[date] | No | Payment due date |
| subtotal | float | Yes | Subtotal before tax and discount |
| tax_amount | float | Yes | Tax amount |
| discount_amount | float | Yes | Discount amount |
| total_amount | float | Yes | Total amount due |
| amount_paid | float | Yes | Amount already paid |
| balance_due | float | Yes | Outstanding balance |
| status | str | Yes | Invoice status (draft, issued, partially_paid, paid, overdue, cancelled) |
| notes | Optional[str] | No | Additional notes |
| created_by_user_id | Optional[str] | No | User who created invoice |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `status`

### Invoicelineitem

**Table:** `invoice_line_items`  
**Description:** Individual line items on an invoice

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| invoice_id | str | Yes | Parent invoice reference |
| service_id | Optional[str] | No | Service reference |
| description | str | Yes | Line item description |
| quantity | int | Yes | Quantity |
| unit_price | float | Yes | Unit price |
| line_total | float | Yes | Line total amount |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Payment

**Table:** `payments`  
**Description:** Financial transactions and payment records

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| invoice_id | str | Yes | Invoice reference |
| patient_id | str | Yes | Patient reference |
| payment_date | datetime | Yes | Payment date and time |
| amount | float | Yes | Payment amount |
| payment_method | str | Yes | Payment method (cash, credit_card, debit_card, insurance, bank_transfer, cheque, other) |
| transaction_reference | Optional[str] | No | Transaction reference number |
| notes | Optional[str] | No | Additional notes |
| processed_by_user_id | Optional[str] | No | User who processed payment |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Report

**Table:** `reports`  
**Description:** System-generated analytical reports and metrics

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| report_name | str | Yes | Report name |
| report_type | str | Yes | Report type (patient_statistics, revenue, appointment_summary, service_utilization, doctor_performance, billing_summary, operational_metrics) |
| generated_by_user_id | str | Yes | User who generated report |
| start_date | Optional[date] | No | Report start date |
| end_date | Optional[date] | No | Report end date |
| parameters | Optional[dict] | No | Report parameters (JSONB) |
| file_path | Optional[str] | No | Generated file path |
| status | str | Yes | Generation status (generating, completed, failed) |
| generated_at | Optional[datetime] | No | Report generation timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** `status`

### Auditlog

**Table:** `audit_logs`  
**Description:** System audit trail for all user actions

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | Optional[str] | No | User who performed action |
| action | str | Yes | Action performed |
| entity_type | str | Yes | Entity type affected |
| entity_id | Optional[str] | No | Entity ID affected |
| old_values | Optional[dict] | No | Old values before change (JSONB) |
| new_values | Optional[dict] | No | New values after change (JSONB) |
| ip_address | Optional[str] | No | User IP address |
| user_agent | Optional[str] | No | User agent string |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

## 7. Enumerations

### UserRole

| Value | Label |
|-------|-------|
| Administrator | ADMINISTRATOR |
| Doctor | DOCTOR |
| Nurse | NURSE |
| Receptionist | RECEPTIONIST |
| Billing Officer | BILLING_OFFICER |

### Gender

| Value | Label |
|-------|-------|
| Male | MALE |
| Female | FEMALE |
| Other | OTHER |

### AppointmentType

| Value | Label |
|-------|-------|
| Consultation | CONSULTATION |
| Follow Up | FOLLOW_UP |
| Emergency | EMERGENCY |
| Routine Checkup | ROUTINE_CHECKUP |
| Procedure | PROCEDURE |

### AppointmentStatus

| Value | Label |
|-------|-------|
| Scheduled | SCHEDULED |
| Confirmed | CONFIRMED |
| Checked In | CHECKED_IN |
| In Progress | IN_PROGRESS |
| Completed | COMPLETED |
| Cancelled | CANCELLED |
| No Show | NO_SHOW |

### ServiceType

| Value | Label |
|-------|-------|
| Consultation | CONSULTATION |
| Procedure | PROCEDURE |
| Lab Test | LAB_TEST |
| Imaging | IMAGING |
| Therapy | THERAPY |
| Surgery | SURGERY |
| Vaccination | VACCINATION |
| Other | OTHER |

### LabTestStatus

| Value | Label |
|-------|-------|
| Ordered | ORDERED |
| Sample Collected | SAMPLE_COLLECTED |
| In Progress | IN_PROGRESS |
| Completed | COMPLETED |
| Cancelled | CANCELLED |

### InvoiceStatus

| Value | Label |
|-------|-------|
| Draft | DRAFT |
| Issued | ISSUED |
| Partially Paid | PARTIALLY_PAID |
| Paid | PAID |
| Overdue | OVERDUE |
| Cancelled | CANCELLED |

### PaymentMethod

| Value | Label |
|-------|-------|
| Cash | CASH |
| Credit Card | CREDIT_CARD |
| Debit Card | DEBIT_CARD |
| Insurance | INSURANCE |
| Bank Transfer | BANK_TRANSFER |
| Cheque | CHEQUE |
| Other | OTHER |

### ReportType

| Value | Label |
|-------|-------|
| Patient Statistics | PATIENT_STATISTICS |
| Revenue | REVENUE |
| Appointment Summary | APPOINTMENT_SUMMARY |
| Service Utilization | SERVICE_UTILIZATION |
| Doctor Performance | DOCTOR_PERFORMANCE |
| Billing Summary | BILLING_SUMMARY |
| Operational Metrics | OPERATIONAL_METRICS |

### ReportStatus

| Value | Label |
|-------|-------|
| Generating | GENERATING |
| Completed | COMPLETED |
| Failed | FAILED |

## 8. Relationships

| Relationship | Navigation Required |
|--------------|---------------------|
| User belongs to one Department | Yes |
| Patient belongs to one InsuranceProvider | Yes |
| MedicalRecord belongs to one Patient | Yes |
| Appointment belongs to one Patient | Yes |
| Appointment belongs to one User (doctor) | Yes |
| Appointment belongs to one Department | Yes |
| VitalSign belongs to one Patient | Yes |
| VitalSign belongs to one User (recorded_by) | Yes |
| Consultation belongs to one Patient | Yes |
| Consultation belongs to one User (doctor) | Yes |
| Consultation belongs to one Appointment | Yes |
| Prescription belongs to one Consultation | Yes |
| Prescription belongs to one Patient | Yes |
| Prescription belongs to one User (doctor) | Yes |
| Service belongs to one Department | Yes |
| LabTest belongs to one Patient | Yes |
| LabTest belongs to one Consultation | Yes |
| LabTest belongs to one User (ordered_by_doctor) | Yes |
| Invoice belongs to one Patient | Yes |
| Invoice belongs to one Appointment | Yes |
| Invoice belongs to one User (created_by) | Yes |
| InvoiceLineItem belongs to one Invoice | Yes |
| InvoiceLineItem belongs to one Service | Yes |
| Payment belongs to one Invoice | Yes |
| Payment belongs to one Patient | Yes |
| Payment belongs to one User (processed_by) | Yes |
| Report belongs to one User (generated_by) | Yes |
| AuditLog belongs to one User | No |

## 9. API Endpoints

### Department Endpoints

- `POST /departments` - Create new department
- `GET /departments` - List all departments with pagination and filtering
- `GET /departments/{id}` - Retrieve department by ID
- `PUT /departments/{id}` - Update department
- `DELETE /departments/{id}` - Delete department

### Insurance Provider Endpoints

- `POST /insurance-providers` - Create new insurance provider
- `GET /insurance-providers` - List all insurance providers with pagination and filtering
- `GET /insurance-providers/{id}` - Retrieve insurance provider by ID
- `PUT /insurance-providers/{id}` - Update insurance provider
- `DELETE /insurance-providers/{id}` - Delete insurance provider

### User Endpoints

- `POST /users` - Create new user account
- `GET /users` - List all users with pagination and filtering
- `GET /users/{id}` - Retrieve user by ID
- `GET /users/{id}/details` - Retrieve user with department details
- `PUT /users/{id}` - Update user
- `DELETE /users/{id}` - Delete user

### Patient Endpoints

- `POST /patients` - Create new patient (auto-creates medical record)
- `GET /patients` - List all patients with pagination and filtering
- `GET /patients/{id}` - Retrieve patient by ID
- `GET /patients/{id}/details` - Retrieve patient with insurance, medical record, and appointments
- `PUT /patients/{id}` - Update patient
- `DELETE /patients/{id}` - Delete patient

### Medical Record Endpoints

- `POST /medical-records` - Create new medical record
- `GET /medical-records` - List all medical records with pagination and filtering
- `GET /medical-records/{id}` - Retrieve medical record by ID
- `PUT /medical-records/{id}` - Update medical record
- `DELETE /medical-records/{id}` - Delete medical record

### Appointment Endpoints

- `POST /appointments` - Create new appointment
- `GET /appointments` - List all appointments with pagination and filtering
- `GET /appointments/{id}` - Retrieve appointment by ID
- `GET /appointments/{id}/details` - Retrieve appointment with patient, doctor, and department details
- `PUT /appointments/{id}` - Update appointment
- `DELETE /appointments/{id}` - Delete appointment
- `POST /appointments/{id}/check-in` - Check in patient for appointment
- `POST /appointments/{id}/cancel` - Cancel appointment
- `POST /appointments/{id}/complete` - Mark appointment as completed

### Vital Sign Endpoints

- `POST /vital-signs` - Record new vital signs
- `GET /vital-signs` - List all vital signs with pagination and filtering
- `GET /vital-signs/{id}` - Retrieve vital signs by ID
- `PUT /vital-signs/{id}` - Update vital signs
- `DELETE /vital-signs/{id}` - Delete vital signs

### Consultation Endpoints

- `POST /consultations` - Create new consultation
- `GET /consultations` - List all consultations with pagination and filtering
- `GET /consultations/{id}` - Retrieve consultation by ID
- `GET /consultations/{id}/details` - Retrieve consultation with patient, doctor, prescriptions, and lab tests
- `PUT /consultations/{id}` - Update consultation
- `DELETE /consultations/{id}` - Delete consultation
- `POST /consultations/{id}/complete` - Complete consultation with prescriptions and lab orders

### Prescription Endpoints

- `POST /prescriptions` - Create new prescription
- `GET /prescriptions` - List all prescriptions with pagination and filtering
- `GET /prescriptions/{id}` - Retrieve prescription by ID
- `PUT /prescriptions/{id}` - Update prescription
- `DELETE /prescriptions/{id}` - Delete prescription

### Service Endpoints

- `POST /services` - Create new service
- `GET /services` - List all services with pagination and filtering
- `GET /services/{id}` - Retrieve service by ID
- `PUT /services/{id}` - Update service
- `DELETE /services/{id}` - Delete service

### Lab Test Endpoints

- `POST /lab-tests` - Order new lab test
- `GET /lab-tests` - List all lab tests with pagination and filtering
- `GET /lab-tests/{id}` - Retrieve lab test by ID
- `PUT /lab-tests/{id}` - Update lab test
- `DELETE /lab-tests/{id}` - Delete lab test
- `POST /lab-tests/{id}/collect-sample` - Mark sample as collected
- `POST /lab-tests/{id}/enter-results` - Enter lab test results

### Invoice Endpoints

- `POST /invoices` - Create new invoice with line items
- `GET /invoices` - List all invoices with pagination and filtering
- `GET /invoices/{id}` - Retrieve invoice by ID
- `GET /invoices/{id}/details` - Retrieve invoice with patient, line items, and payments
- `PUT /invoices/{id}` - Update invoice
- `DELETE /invoices/{id}` - Delete invoice
- `POST /invoices/{id}/issue` - Issue invoice to patient

### Invoice Line Item Endpoints

- `POST /invoice-line-items` - Create new invoice line item
- `GET /invoice-line-items` - List all invoice line items with pagination and filtering
- `GET /invoice-line-items/{id}` - Retrieve invoice line item by ID
- `PUT /invoice-line-items/{id}` - Update invoice line item
- `DELETE /invoice-line-items/{id}` - Delete invoice line item

### Payment Endpoints

- `POST /payments` - Record new payment
- `POST /payments/process` - Process payment and update invoice
- `GET /payments` - List all payments with pagination and filtering
- `GET /payments/{id}` - Retrieve payment by ID
- `PUT /payments/{id}` - Update payment
- `DELETE /payments/{id}` - Delete payment

### Report Endpoints

- `POST /reports` - Create new report request
- `POST /reports/generate` - Generate report with parameters
- `GET /reports` - List all reports with pagination and filtering
- `GET /reports/{id}` - Retrieve report by ID
- `GET /reports/{id}/download` - Download generated report file
- `PUT /reports/{id}` - Update report
- `DELETE /reports/{id}` - Delete report

### Audit Log Endpoints

- `GET /audit-logs` - List all audit logs with pagination and filtering

## 10. Workflow Logic

### Patient Registration Workflow

1. **Create Patient:** Receptionist creates new patient record with demographics
2. **Auto-Create Medical Record:** System automatically creates associated medical record
3. **Validation:** System validates patient_number uniqueness
4. **Audit:** System logs patient creation action

### Appointment Scheduling Workflow

1. **Select Patient:** Receptionist searches and selects patient
2. **Select Doctor/Department:** Choose available doctor and department
3. **Select Time Slot:** System validates no double-booking for doctor
4. **Create Appointment:** System creates appointment with status "scheduled"
5. **Send Confirmation:** System generates confirmation (requires external integration)
6. **Audit:** System logs appointment creation

### Patient Check-In Workflow

1. **Update Status:** Receptionist marks appointment as "checked_in"
2. **Record Vital Signs:** Nurse records patient vital signs
3. **Validation:** System ensures vital signs recorded before consultation
4. **Audit:** System logs check-in and vital signs recording

### Consultation Workflow

1. **Start Consultation:** Doctor updates appointment status to "in_progress"
2. **Review History:** Doctor views patient medical record and current vitals
3. **Record Examination:** Doctor enters chief complaint, present illness, examination findings
4. **Enter Diagnosis:** Doctor records diagnosis and treatment plan
5. **Create Prescriptions:** Doctor creates multiple prescriptions (batch operation)
   - System validates against patient allergies
   - System warns if medication matches known allergies
6. **Order Lab Tests:** Doctor orders required lab tests (batch operation)
7. **Complete Consultation:** System marks consultation as complete
8. **Update Medical Record:** System updates patient medical record with new information
9. **Audit:** System logs all consultation activities

### Prescription Creation Workflow

1. **Select Medications:** Doctor selects medications from catalog
2. **Specify Details:** Enter dosage, frequency, duration, quantity
3. **Validate Allergies:** System checks patient allergies and displays warnings
4. **Generate Prescription:** System creates prescription record with is_active=true
5. **Print:** System generates printable prescription (requires report generation)
6. **Audit:** System logs prescription creation

### Lab Test Ordering Workflow

1. **Order Tests:** Doctor creates lab test orders with status "ordered"
2. **Issue Requisition:** System generates lab requisition form
3. **Collect Sample:** Lab staff updates status to "sample_collected"
4. **Process Sample:** Lab updates status to "in_progress"
5. **Enter Results:** Lab staff enters result_value, result_unit, reference_range
6. **Complete:** System updates status to "completed"
7. **Review Results:** Doctor reviews completed test results
8. **Audit:** System logs all lab test activities

### Invoice Generation Workflow

1. **Retrieve Consultation:** Billing officer selects completed consultation
2. **Add Service Line Items:** Add services rendered with quantities and prices
3. **Apply Insurance:** Calculate insurance coverage (manual process)
4. **Calculate Totals:** System calculates subtotal, tax, discount, total
5. **Generate Invoice:** Create invoice with status "draft"
6. **Review and Issue:** Billing officer reviews and issues invoice (status="issued")
7. **Audit:** System logs invoice creation and issuance

### Payment Processing Workflow

1. **Patient Payment:** Patient makes payment via selected method
2. **Record Payment:** Billing officer creates payment record
3. **Update Invoice:** System recalculates invoice amounts:
   - amount_paid = sum of all payments
   - balance_due = total_amount - amount_paid
   - status = "partially_paid" or "paid"
4. **Generate Receipt:** System generates payment receipt
5. **Audit:** System logs payment processing

### Report Generation Workflow

1. **Select Report Type:** User selects report type from available templates
2. **Specify Parameters:** User enters date range and other parameters
3. **Create Report Request:** System creates report record with status "generating"
4. **Query Data:** Background process queries relevant data
5. **Generate File:** System creates PDF/Excel file
6. **Update Status:** System updates status to "completed" or "failed"
7. **Download:** User downloads generated report file
8. **Audit:** System logs report generation

## 11. Business Logic

### Core Business Rules

1. **Unique Identifiers:**
   - Patient ID and patient_number must be unique across the system
   - Invoice numbers must be unique and sequential
   - User email addresses must be unique

2. **Appointment Scheduling:**
   - Appointment date cannot be in the past
   - No double-booking: same doctor cannot have overlapping appointments
   - Only active users and patients can be scheduled for appointments
   - Appointment duration must be positive integer

3. **Consultation Rules:**
   - Consultation can only be created from appointments with status "checked_in"
   - Vital signs must be recorded before consultation can begin
   - Only doctors can create prescriptions and order lab tests
   - Completed consultations cannot be edited after 24 hours

4. **Prescription Management:**
   - System must warn if prescribed medication matches patient allergies
   - Only doctors can create and modify prescriptions
   - Prescription validity is 30 days from issue date
   - Active prescriptions (is_active=true) appear in patient's current medications

5. **Lab Test Processing:**
   - Lab test results can only be entered after sample is collected
   - Status transitions: ordered → sample_collected → in_progress → completed
   - Cannot skip status transitions

6. **Invoice and Payment Rules:**
   - Invoice can only be generated after consultation is completed
   - Payment amount cannot exceed invoice total
   - Outstanding balance = Total Amount - Sum of Payments
   - Invoice status automatically updates based on payments:
     - balance_due = 0: status = "paid"
     - balance_due > 0 and amount_paid > 0: status = "partially_paid"
     - balance_due > 0 and due_date < today: status = "overdue"

7. **Financial Calculations:**
   - Line item total = quantity × unit_price
   - Invoice subtotal = sum of all line item totals
   - Invoice total = subtotal + tax_amount - discount_amount
   - Discount cannot exceed subtotal amount

### Role-Based Access Control

1. **Administrator:**
   - Full system access
   - Create/edit/deactivate user accounts
   - Configure departments and services
   - View all reports and audit logs

2. **Doctor:**
   - View and edit consultations, prescriptions, lab tests
   - View patient medical records
   - Cannot access billing information
   - Cannot modify user accounts

3. **Nurse:**
   - Record vital signs
   - View appointments and basic patient information
   - Cannot view detailed medical records
   - Cannot create prescriptions or consultations

4. **Receptionist:**
   - Manage appointments and patient registration
   - Check in patients
   - Cannot view detailed medical records
   - Cannot access billing information

5. **Billing Officer:**
   - Create invoices and process payments
   - Generate billing reports
   - Cannot modify medical records
   - Cannot create prescriptions or consultations

### Audit Trail

- All user actions must be logged in audit_logs
- Log includes: user_id, action, entity_type, entity_id, old_values, new_values
- Track IP address and user agent for security
- Audit logs are append-only (cannot be deleted)

## 12. Validation Rules

### Email and Contact Validation

- Email must be in valid email format (regex pattern validation)
- Email must be unique for users
- Phone numbers should follow consistent format

### Date and Time Validation

- Date of birth cannot be in the future
- Appointment date cannot be in the past
- Consultation date should match appointment date
- Follow-up dates must be after consultation date

### Vital Signs Validation

- Systolic blood pressure must be greater than diastolic blood pressure
- Temperature must be within valid range (95°F - 110°F / 35°C - 43.3°C)
- Pulse rate must be between 40 and 200 bpm
- Oxygen saturation must be between 70% and 100%
- Respiratory rate must be positive integer
- Weight and height must be positive numbers

### Financial Validation

- Line item quantity must be greater than zero
- Unit price cannot be negative
- Discount cannot exceed subtotal amount
- Payment amount must be positive
- Payment amount cannot exceed invoice balance_due
- All monetary values must have maximum 2 decimal places

### Password Validation

- Password must meet complexity requirements:
  - Minimum 8 characters
  - Must contain alphanumeric characters
  - Should include uppercase, lowercase, numbers, and special characters
- Passwords must be hashed using bcrypt or Argon2

### Entity-Specific Validation

- Appointment duration must be between 15 and 480 minutes
- Service default_price must be positive
- Prescription quantity must be positive integer
- Invoice line item quantity must be at least 1
- Report date ranges: start_date must be before or equal to end_date

## 13. Implementation Notes

### Technology Stack

- **Framework:** FastAPI for high-performance async API development
- **ORM:** SQLAlchemy ORM for database abstraction and relationship management
- **Database:** SQLite for development and testing (production will use PostgreSQL)
- **Validation:** Pydantic v2 for request/response schema validation and serialization
- **Dependency Injection:** FastAPI's Depends() for database session management (get_db)
- **Package Management:** uv for fast, reliable dependency management
- **Documentation:** Automatic OpenAPI (Swagger) documentation at `/docs` and ReDoc at `/redoc`

### Architecture Pattern

- **Service Layer Pattern:** Business logic encapsulated in service classes, separated from API routes
- **Repository Pattern:** Data access logic abstracted in repository classes
- **DTO Pattern:** Pydantic models for request/response schemas distinct from SQLAlchemy models

### Database Session Management

- Database sessions managed via FastAPI dependency injection
- Each request gets isolated database session using `Depends(get_db)`
- Sessions automatically committed on success, rolled back on exception
- Connection pooling configured for concurrent request handling

### API Design

- RESTful conventions for all endpoints
- Consistent response formats with status, data, and error fields
- Pagination support for all list endpoints (page, page_size parameters)
- Filtering and sorting support via query parameters
- HTTP status codes: 200 (success), 201 (created), 400 (validation error), 404 (not found), 500 (server error)

### Error Handling

- Custom exception classes for business logic errors
- Global exception handler for consistent error responses
- Detailed validation errors from Pydantic
- Audit logging of all errors and exceptions

### Security Considerations

- Password hashing using bcrypt with salt
- Sensitive fields (password_hash) excluded from API responses
- Input sanitization to prevent SQL injection
- CORS configuration for cross-origin requests
- Rate limiting for API endpoints (future enhancement)

### Performance Optimization

- Eager loading for detail endpoints to prevent N+1 queries
- Database indexes on foreign keys and frequently queried fields
- Batch operations for creating multiple related records
- Response caching for frequently accessed read-only data (future enhancement)

### Testing Strategy

- Unit tests for service layer business logic
- Integration tests for API endpoints
- Database fixtures for test data
- Mock external dependencies (email, SMS gateways)
- Test coverage target: >80%

## 14. Assumptions

1. **Deployment Environment:**
   - System will be deployed on HTTPS domain with valid SSL certificate
   - Single-facility deployment initially (multi-facility out of scope)
   - Server timezone set to UTC for consistent timestamp handling

2. **Database:**
   - PostgreSQL database for production deployment
   - Database supports UUID data types for primary keys
   - All timestamps stored in UTC
   - Daily automated backups configured at infrastructure level

3. **Authentication:**
   - User passwords encrypted using bcrypt or Argon2
   - Session timeout after 30 minutes of inactivity
   - JWT tokens for API authentication (future implementation)

4. **Business Processes:**
   - Insurance coverage calculation is manual (no real-time verification with insurance companies)
   - Prescription validity is 30 days from issue date
   - Appointment reminders handled by external service
   - Lab results entered manually (no equipment integration)

5. **External Integrations:**
   - SMS and email notifications require external gateway integration (out of scope)
   - Payment gateway integration for credit/debit card processing (future enhancement)
   - Pharmacy system integration for e-prescriptions (future enhancement)

6. **Localization:**
   - System supports single language (English) initially
   - Currency display in USD
   - Date format: YYYY-MM-DD (ISO 8601)
   - Time format: 24-hour clock

7. **Data Retention:**
   - Audit logs retained indefinitely
   - Soft delete for most entities (mark as inactive rather than hard delete)
   - Medical records never deleted (regulatory compliance)

8. **Concurrency:**
   - Optimistic locking for concurrent updates
   - Last-write-wins strategy for conflict resolution
   - No pessimistic locking required

## 15. Future Improvements

### Phase 2 Enhancements

1. **Database Migrations:**
   - Implement Alembic for database schema version control
   - Automated migration scripts for production deployments
   - Rollback capability for failed migrations

2. **Production Database:**
   - Migrate from SQLite to PostgreSQL for production
   - Configure connection pooling and read replicas
   - Implement database partitioning for large tables

3. **Authentication and Authorization:**
   - Implement JWT-based authentication
   - Refresh token mechanism for extended sessions
   - Role-Based Access Control (RBAC) enforcement at API level
   - Two-factor authentication (2FA) for sensitive operations

4. **Testing:**
   - Comprehensive unit test suite with pytest
   - Integration tests for API endpoints
   - End-to-end tests for critical workflows
   - Performance and load testing
   - Test coverage reporting and enforcement

5. **Containerization:**
   - Docker containerization for consistent deployment
   - Docker Compose for local development environment
   - Kubernetes manifests for production orchestration

### Phase 3 Enhancements

6. **Mobile Applications:**
   - Native mobile app for patients (iOS and Android)
   - Mobile app for healthcare providers
   - Offline support for mobile devices

7. **Telemedicine:**
   - Video consultation capability
   - Screen sharing for remote diagnosis
   - Chat functionality for patient-doctor communication

8. **Advanced Integrations:**
   - Integration with pharmacy systems for e-prescriptions
   - Integration with lab equipment for automatic result import
   - Payment gateway integration for online payments
   - Insurance verification API integration

9. **Patient Portal:**
   - Self-service appointment booking
   - View medical history and test results
   - Prescription refill requests
   - Secure messaging with healthcare providers

10. **Analytics and Intelligence:**
    - Advanced analytics dashboard with interactive charts
    - Predictive modeling for patient outcomes
    - AI-assisted diagnosis suggestions
    - Resource utilization optimization

11. **Multi-Facility Support:**
    - Centralized data management across multiple facilities
    - Cross-facility patient transfers
    - Consolidated reporting across facilities

12. **Enhanced Features:**
    - Inventory management for medications and supplies
    - Multi-language support with i18n
    - Real-time notifications using WebSockets
    - Document management for medical records (PDF, images)
    - E-signature support for digital prescriptions and consents
    - Barcode/QR code scanning for patient identification

13. **Compliance and Security:**
    - HIPAA compliance audit and certification
    - Data encryption at rest and in transit
    - Advanced audit logging with tamper detection
    - Automated backup and disaster recovery
    - Security penetration testing and remediation
