# Hospital Management Solution — Project Documentation  
## Integrated Hospital ERP + CRM Platform (Lead → Patient → Treatment → Billing)

**Purpose:** This document is the single source of truth for the Hospital Management Solution.  
**For AI agents:** Use with `docs/AGENT_AUDIT_GUIDE.md` to audit the codebase, find missing topics, and implement all steps below.

---

# Part A — Business Context (Reference)

## Executive Summary

Cloud-based Hospital ERP + CRM that enables:
- Centralized lead & enquiry management
- Seamless lead-to-patient conversion
- Hospital operational management (appointments, billing, basic EMR)
- Multi-hospital, multi-role access
- Actionable analytics for hospitals and platform owners

## Business Goals & KPIs

| Metric | Target |
|--------|--------|
| Time to respond to new enquiry | &lt; 15 minutes |
| Enquiry-to-patient conversion | Increase 20–30% |
| No-show rate for appointments | &lt; 10% |
| Billing/invoice accuracy | &gt; 99% |

## Scope (Phase 1)

- Lead and enquiry system
- Patient registration
- Appointment scheduling
- Billing and payment management
- Dashboards and reports
- Role-based access

## Stakeholders & Personas

| Persona | Key Needs |
|---------|-----------|
| CRM Agent | Quick access to enquiries, follow-ups, reminders |
| Hospital Admin | Visibility of hospital activities, system control |
| Doctor | Organized appointment schedule |
| Billing Executive | Accurate billing and payment tracking |
| Management | Reports on patients, conversions, revenue |

---

# Part B — System Overview & Roles

## System Type

- **Type:** Web-based SaaS  
- **Access:** Multi-tenant (multiple hospitals)  
- **Deployment:** Cloud-hosted  

## User Roles & Permissions (Checklist)

| Role | Permissions | Verify in codebase |
|------|-------------|---------------------|
| Super Admin | Platform configuration, all data | Routes, middleware, controller scope |
| Hospital Admin | Hospital setup, reports | Routes, middleware, hospital_id scope |
| CRM Agent | Leads & enquiries | Routes, middleware, lead/assignment |
| Doctor | Appointments, patient view | Routes, middleware, doctor scope |
| Billing Executive | Billing & payments | Routes, middleware |
| Viewer | Read-only dashboards | If in scope: role + read-only UI |

---

# Part C — Functional Requirements (Audit Checklist)

## 1. Lead & Enquiry Management (CRM Module)

### 1.1 Lead Creation

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| L1.1 | Enquiry received via: Website form, WhatsApp, Phone, Walk-in, Marketing campaign | Public lead form + source field |
| L1.2 | System creates new lead record; unique **Lead ID** auto-generated | Lead model, migration, controller store |
| L1.3 | **Mandatory:** Patient name, Contact number, Enquiry type, Source | Validation in store/update |
| L1.4 | Lead status set to **New** by default | Default in model or migration |

### 1.2 Lead Assignment

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| L2.1 | Lead assigned to a specific hospital user (CRM user) | assigned_user_id / assignment logic |
| L2.2 | Assignment: Automatic (rules) or Manual (hospital admin) | Assign to agent flow; bulk assign |

### 1.3 Lead Follow-up and Tracking

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| L3.1 | Every interaction recorded: call details, notes | Call logs / notes on lead or related table |
| L3.2 | Follow-up reminders with date and time | Follow-up/reminder entity or field |
| L3.3 | Lead status: New → Contacted | Status transitions in controller |
| L3.4 | System tracks time in each stage | Timestamps / stage history if required |

### 1.4 Lead Qualification

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| L4.1 | If not interested → status **Closed – Lost** | Status option + update |
| L4.2 | If interested → status **Qualified** | Status option + update |
| L4.3 | Only Qualified leads can move forward (e.g. convert) | Validation before conversion |

---

## 2. Lead to Patient Conversion Flow

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| CV1 | Only leads with status **Qualified** can be converted | Check in convert action |
| CV2 | Conversion creates **patient record** | Patient::create in convert |
| CV3 | Unique **Patient ID** generated on conversion | patient_uid or similar |
| CV4 | Lead details remain linked: source, call logs, notes, follow-up history | Lead–patient mapping table / relations |
| CV5 | No lead data deleted; lead record **read-only** after conversion | No delete; optional read-only flag |
| CV6 | Patient profile is main record going forward | All new actions use patient_id |

---

## 3. Patient Management Flow

### 3.1 Patient Registration

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| P1.1 | Patient entry: (1) Converted lead, (2) Manual registration at front desk | Convert flow + manual create patient |
| P1.2 | Unique **Patient ID** generated | patient_uid / Patient_ID in DB |
| P1.3 | Basic details: Name, Age, Gender, Contact | Patient model + form |
| P1.4 | Check existing by **contact number**; use existing record if found; no duplicates | Duplicate check in store |

### 3.2 Patient Record Management

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| P2.1 | One profile per patient: personal details + all visits | Patient show view + visits relation |
| P2.2 | Every appointment linked to same Patient ID | appointments.patient_id |
| P2.3 | All bills linked to patient + visit | invoices patient_id, visit_id |
| P2.4 | Patient history: appointments, visits, bills in one place | Medical history / billing history views |

---

## 4. Appointment Management Flow

### 4.1 Doctor Setup

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| AP1.1 | Hospital admin creates doctor profile | Doctor CRUD, hospital_id |
| AP1.2 | Doctor details: name, department, available days, time slots | Doctor model + form |
| AP1.3 | Doctor linked to hospital; availability used for booking | Doctor model, availability fields/logic |

### 4.2 Appointment Booking

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| AP2.1 | Appointment from: Qualified Lead OR existing Patient | Create from lead convert or from patient |
| AP2.2 | User selects: Doctor, Date, Time slot, Appointment type | Form + validation |
| AP2.3 | System checks doctor and slot availability | Availability check before save |
| AP2.4 | If available: create appointment; status **Scheduled** | Appointment::create, status default |
| AP2.5 | Appointment linked to Patient ID and Doctor ID | appointment patient_id, doctor_id |

### 4.3 Appointment Status

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| AP3.1 | Automatic reminders before appointment | Reminder job/queue or integration |
| AP3.2 | After scheduled time: **Completed** / **No-show** / **Cancelled** | Status update actions |
| AP3.3 | Completed appointments proceed to Visit and Billing | Flow to consultation/invoice |

---

## 5. Consultation Flow

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| CO1 | Patient arrives; doctor completes consultation | Consultation create from appointment |
| CO2 | Appointment marked **Completed** | Appointment status update |
| CO3 | Consultation details saved against patient visit | Consultation model linked to appointment/visit |

---

## 6. Billing & Payments Flow

### 6.1 Billing Setup

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| B1.1 | Hospital admin configures: service list, charges, tax rules | Service master CRUD, hospital-level config |
| B1.2 | Only authorized billing users create/update bills | Role check (Billing Executive, etc.) |

### 6.2 Bill Creation

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| B2.1 | Billing only after appointment **Completed** or visit **Completed** | Validation before invoice create |
| B2.2 | Select patient and visit; add services/packages | Invoice create form |
| B2.3 | System calculates: total, tax, final payable | Calculation in controller/service |
| B2.4 | Unique **Invoice ID** generated | invoice_number or id |
| B2.5 | Bill linked to Patient ID and Visit ID | invoice patient_id, visit_id |
| B2.6 | Bill status **Pending** by default | Default status |

### 6.3 Payment Collection

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| B3.1 | Payment modes: Cash, Card, UPI | Payment mode field/options |
| B3.2 | Record: amount, mode, date | Payment model/store |
| B3.3 | Status: **Paid** / **Partial** / **Pending** | Invoice/payment status update |
| B3.4 | Generate invoice and payment receipt | Invoice PDF, receipt view/download |

### 6.4 Billing Closure & Reporting

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| B4.1 | Completed payment → bill locked from editing | Lock logic or status |
| B4.2 | Data available for revenue, pending payment, patient billing history | Reports + patient billing history |
| B4.3 | Corrections require admin approval | If in scope: approval workflow |

---

## 7. Follow-up & Closure Flow

| ID | Requirement | Implementation check |
|----|-------------|------------------------|
| F1 | If further treatment needed → schedule follow-up appointment | Appointment create from patient |
| F2 | Reminders for future visits | Same as AP3.1 |
| F3 | Visit journey closed once billing completed | Status/closure concept |

---

## 8. End-to-End Business Flow (Verification Order)

Verify this sequence is supported in the app:

1. Lead generated → captured in CRM  
2. Assigned to hospital  
3. Contact attempt → status Contacted  
4. Lead qualified? → No: Close as Lost | Yes: continue  
5. Appointment scheduled  
6. Patient registration (convert or manual)  
7. Consultation  
8. Billing generated  
9. Payment received  
10. Follow-up scheduled (if needed)  

---

## 9. Dashboards & Reports

### Hospital Dashboard

| ID | Metric | Implementation check |
|----|--------|------------------------|
| D1 | Total leads | Query + widget |
| D2 | Conversion rate | Calculation + widget |
| D3 | Appointments today | Query + widget |
| D4 | Revenue summary | Query + widget |
| D5 | Pending payments | Query + widget |

### Super Admin Dashboard

| ID | Metric | Implementation check |
|----|--------|------------------------|
| D6 | Hospital-wise performance | Multi-hospital aggregates |
| D7 | Lead source ROI | By source reporting |
| D8 | Revenue analytics | Reports |
| D9 | SLA adherence | If SLA defined: metrics |

---

# Part D — Business Rules (BR) — Full Checklist

Each rule must be enforced in code (validation, flow, or DB).

| Rule ID | Business Rule | Where to verify |
|---------|----------------|------------------|
| BR-01 | Every enquiry creates one lead with unique Lead ID | Lead create, unique id generation |
| BR-02 | Name, contact number, enquiry type, source mandatory to save lead | Lead validation |
| BR-03 | Lead status = New when created | Lead default status |
| BR-04 | Each lead assigned to one hospital and one agent | Assignment logic, hospital_id, assigned_user_id |
| BR-05 | Leads not contacted within defined time → auto reassigned | Job/scheduler or manual reassign |
| BR-06 | All interactions logged against lead | Notes/calls table or fields |
| BR-07 | Only Qualified leads can move forward | Conversion + any “next step” checks |
| BR-08 | Only Qualified leads can be converted to patients | Convert action validation |
| BR-09 | Converting lead must create patient record | Convert action |
| BR-10 | Unique Patient ID generated on conversion | Patient create, UID |
| BR-11 | All lead details remain linked to patient | Lead–patient mapping, relations |
| BR-12 | No lead data deleted on conversion | No delete in convert |
| BR-13 | After conversion, lead record read-only | Policy or UI |
| BR-14 | Patient profile = main record for future actions | All flows use patient |
| BR-15 | Patient registered from converted lead OR manually | Convert + manual registration |
| BR-16 | Every patient has unique Patient ID | patient_uid / Patient_ID |
| BR-17 | One patient = one active patient record (no duplicates by contact) | Duplicate check |
| BR-18 | Patient registration: name and contact minimum | Patient validation |
| BR-19 | All visits linked to same Patient ID | visit patient_id |
| BR-20 | All appointments and bills linked to patient | FKs in DB + relations |
| BR-21 | Doctor profile exists before booking | Doctor must exist |
| BR-22 | Appointments only for available doctor slots | Availability check |
| BR-23 | Appointment linked to patient record | appointment patient_id |
| BR-24 | Appointment status default = Scheduled | Default |
| BR-25 | Appointment status updated after scheduled time | Status update actions |
| BR-26 | Cancelled/No-show cannot generate billing | Invoice create validation |
| BR-27 | Automatic reminders before appointment | Reminder implementation |
| BR-28 | Billing only for completed visits | Invoice create validation |
| BR-29 | Every bill has unique Invoice ID | Invoice id/number |
| BR-30 | Bill linked to one patient and one visit | invoice patient_id, visit_id |
| BR-31 | Bill status default = Pending | Default |
| BR-32 | Payment modes: Cash, Card, UPI only | Validation/enum |
| BR-33 | Completed bill not editable without admin | Lock or permission check |
| BR-34 | Cancelled/No-show appointments cannot generate bills | Same as BR-26 |

---

# Part E — User Stories (US) — Acceptance Criteria Checklist

| US ID | User Story | Acceptance criteria to verify |
|-------|------------|------------------------------|
| US-01 | As an agent, I want to create a lead so enquiries are recorded | Lead saved with unique ID, status New |
| US-02 | As an admin, I want leads assigned to agents | Assignment automatic or manual |
| US-03 | As an agent, I want to track follow-ups | Calls, notes, reminders can be added |
| US-04 | As an agent, I want to qualify leads | Only Qualified leads move to next step |
| US-05 | As an agent, I want to convert qualified lead to patient | Conversion only for Qualified |
| US-06 | As a system user, I want patient details created on conversion | Patient record + unique Patient ID |
| US-07 | As a user, I want lead history linked to patient | Source, calls, notes, follow-ups in patient profile |
| US-08 | As a manager, I want lead data preserved for reporting | Lead read-only, in reports after conversion |
| US-09 | As a front desk user, I want to register a patient | Patient record, unique Patient ID |
| US-10 | As a system user, I want leads to convert into patients | Patient created during conversion |
| US-11 | As a user, I want one patient record for all visits | All appointments same Patient ID |
| US-12 | As a billing user, I want bills linked to patients | Bills under correct patient profile |
| US-13 | As a hospital admin, I want patient history in one place | Visit, appointment, billing in one record |
| US-14 | As an admin, I want to create doctor profiles | Doctor saved with availability |
| US-15 | As a user, I want to book appointments for patients | Appointment only for available slots |
| US-16 | As a user, I want appointments linked to patients and doctors | Patient ID and Doctor ID on appointment |
| US-17 | As a user, I want appointment status updates after visit | Completed, No-show, Cancelled |
| US-18 | As a patient, I want reminders before appointment | Reminder sent before appointment |
| US-19 | As a billing user, I want to create bill for patient visit | Bill only for completed visits |
| US-20 | As a billing user, I want system-calculated amounts | Total and tax auto-calculated |
| US-21 | As a billing user, I want to record payments | Payment saved with mode and status |
| US-22 | As a patient, I want receipt after payment | Invoice and receipt generated |
| US-23 | As a manager, I want billing reports | Bills in revenue and pending reports |

---

# Part F — Data Tables / Entities (Schema Checklist)

Verify these exist (migrations/models) with required fields.

### Lead

- Lead ID (unique), patient name, contact number, enquiry type, source, status, hospital_id, assigned user, timestamps.

### Patient Master

- Patient_ID (unique), Patient_Name, Age, Gender, Contact_Number, Email (optional), Registration_Source (converted lead / manual), Created_Date, Status.

### Patient Visit

- Visit_ID, Patient_ID (FK), Visit_Date, Visit_Type (OPD/Consultation), Doctor_ID, Visit_Status (Completed/No-show), Notes.

### Appointment

- Appointment_ID, Patient_ID (FK), Doctor_ID (FK), Appointment_Date, Time_Slot, Appointment_Type, Status (Scheduled/Completed/No-show/Cancelled), Created_From (Lead/Patient), Created_Date.

### Appointment Reminder (if in scope)

- Reminder_ID, Appointment_ID (FK), Reminder_Type (SMS/WhatsApp), Reminder_Time, Status (Sent/Failed).

### Doctor

- Doctor_ID, Doctor_Name, Department, Available_Days, Time_Slots, Hospital_ID (FK), Status.

### Billing (Invoice)

- Invoice_ID, Patient_ID (FK), Visit_ID (FK), Invoice_Date, Total_Amount, Tax_Amount, Net_Amount, Payment_Status (Pending/Partial/Paid).

### Billing Item

- Item_ID, Invoice_ID (FK), Service_Name, Quantity, Unit_Price, Line_Total.

### Payment

- Payment_ID, Invoice_ID (FK), Payment_Date, Amount_Paid, Payment_Mode (Cash/Card/UPI), Payment_Status.

### Service Master

- Service_ID, Service_Name, Service_Type (Consultation/Procedure), Price, Tax_Applicable.

### Lead–Patient Mapping

- Lead_ID, Patient_ID, Conversion_Date, Converted_By.

### Hospital (multi-tenant)

- Hospital_ID, name, and any config fields.

---

# Part G — Flow Diagram Reference

**Intended flow:** Lead → Captured in CRM → Assigned to Hospital → Contact → Qualified? → (No: Close Lost | Yes: Appointment → Patient Registration → Consultation → Billing → Payment → Follow-up).

Ensure routes and controllers support each step.

---

# Part H — Agent Audit Instructions

1. **Read** this entire document and Part A–G.
2. **List** every BR (BR-01 to BR-34), every US (US-01 to US-23), and every functional requirement row (L1.1–B4.3, D1–D9, etc.).
3. **Map** each to: Route → Controller method → View (if any) → Model/DB.
4. **Report** gaps: Missing, Broken, or Incomplete (see `AGENT_AUDIT_GUIDE.md`).
5. **Implement** missing or broken items in order: routes → controllers → views → models/migrations → authorization.
6. **Re-verify** against this document and the End-to-End Flow (Part 8).

Use `docs/AGENT_AUDIT_GUIDE.md` for the detailed step-by-step audit process.
