# Billing Module - Complete Test & Verification Guide

## Prerequisites Checklist

Before testing, ensure:
- [ ] Database schema applied (`php bin/console doctrine:schema:update --force`)
- [ ] ROLE_BILLING assigned to test user
- [ ] Hospital GSTIN entered in System → Hospitals
- [ ] At least 1 Lab Test Charge configured
- [ ] At least 1 Radiology Test Charge configured
- [ ] ABDM Laravel app running (`php artisan serve` at D:\abdm\folder\abdm)
- [ ] `.env.local` has `ABDM_APP_URL=http://127.0.0.1:8000`
- [ ] Cache cleared (`php bin/console cache:clear`)

---

## Test 1: Auto-Draft Invoice Creation

### Scenario:
Create a new case with medicines → Verify Draft invoice auto-creates

### Steps:
1. **Log in as Doctor**
2. Go to **Cases → New Case**
3. Fill out patient info
4. **Add Medicines:**
   - Select a medicine from stock
   - Set quantity (e.g., 2)
   - Set dosage (e.g., 1 tab × 2 times)
   - Click **Add Medicine**
5. **Save Case**
   - Click **Save** button
   - Verify case is created successfully

### Verification:
1. **Check Case Billing Panel:**
   - Go back to case (Cases → show case)
   - Scroll down to **"Billing"** section
   - Should show: Draft invoice with status badge (yellow/warning)
   - Should show: Invoice Number (e.g., `INV/hNum-001/2026-27/0001`)
   - Should show: Grand Total (calculated from medicines)

2. **Check Database:**
   ```bash
   mysql -e "SELECT id, invoice_number, status, grand_total FROM invoices 
             WHERE case_id = <case_id> AND status = 'Draft';"
   ```
   Should return 1 row with status = 'Draft'

3. **Check Line Items:**
   ```bash
   mysql -e "SELECT description, source_type, quantity, unit_price, line_total 
             FROM invoice_line_items WHERE invoice_id = <invoice_id>;"
   ```
   Should show dispensed medicines as Pharmacy line items

**Result:** ✅ PASS if Draft invoice appears automatically
**Result:** ❌ FAIL if no invoice appears or errors in var/log/dev.log

---

## Test 2: Manual Invoice Generation with "Create & Issue Bill"

### Scenario:
Use the "Create & Issue Bill" quick-action button → Generate invoice → Add service charge → Issue

### Steps:
1. **Log in as Billing Staff**
   - Must have ROLE_BILLING assigned

2. **Navigate to Case Show Page**
   - Go to **Cases** → select a case with medicines
   - Scroll to **"Quick Billing"** section
   - Should see: "Billable Items Found" alert + large green **"Create & Issue Bill"** button

3. **Click "Create & Issue Bill"**
   - System redirects to invoice show page
   - Flash message appears:
     - ✓ `"Invoice INV/... drafted for amount Rs. X.XX"`
     - ℹ️ `"Add any service charges if needed, then issue to link it to the patient's PHR"`

4. **(Optional) Add Service Charge:**
   - Under **"Add Service Charge"** section
   - Select a service (e.g., "Bed Charge")
   - Quantity = 1 (default)
   - Click **Add**
   - Flash: `"Service charge added"`
   - Verify grand total increased

5. **Issue Invoice:**
   - Click **Issue Invoice** button
   - Confirmation dialog appears: "Issue this invoice? Line items cannot be changed afterwards."
   - Click **OK**
   - Flash messages:
     - ✓ `"Invoice INV/... issued"`
     - ℹ️ `"This invoice has been automatically linked to the patient's PHR"`

### Verification:
1. **Invoice Status Changed:**
   ```bash
   mysql -e "SELECT status, amount_paid, balance_due FROM invoices 
             WHERE invoice_number = 'INV/...';"
   ```
   Should show: status = 'Issued'

2. **ABDM Record Created:**
   ```bash
   # Query ABDM database (if separate from HMIS)
   mysql -h <abdm_host> -D <abdm_db> -e \
   "SELECT invoice_number, invoice_date, total_amount, amount_paid, balance_due 
    FROM cnmgts_patient_abha_m2_records 
    WHERE hi_type = 'Invoice' AND invoice_number = 'INV/...';"
   ```
   Should return 1 row with matching amounts

3. **Check var/log/dev.log:**
   ```bash
   tail -50 var/log/dev.log | grep -i "invoice\|abdm"
   ```
   Should NOT show errors

**Result:** ✅ PASS if invoice issues and ABDM record created
**Result:** ❌ FAIL if no ABDM record or errors in logs

---

## Test 3: GST Calculation Verification

### Scenario:
Verify GST math is correct on Draft invoice before issuing

### Steps:
1. **View Draft Invoice Details:**
   - On invoice show page
   - Scroll to **Billing Summary** table
   - Check columns: Description, Qty, Unit Price, GST %, Amount

2. **Manually Verify One Line Item:**
   - Example: Lab test "Haemoglobin" with:
     - Configured charge: Rs. 50
     - Configured GST: 5%
     - Expected unit price (GST-inclusive): 50 + (50 × 5%) = Rs. 52.50
   
   - On invoice:
     - Unit Price should show: 52.50
     - GST % should show: 5
     - Amount (qty × unit price) should show: 52.50

3. **Verify Grand Total:**
   - Sum all line amounts = Subtotal
   - Grand Total should equal Subtotal (no CGST/SGST split shown)
   - Formula: Grand Total = (Subtotal - Discount) = All line amounts

### Verification:
```bash
# Query database to double-check amounts
mysql -e "SELECT 
  SUM(line_total) AS subtotal, 
  SUM(quantity * unit_price) AS calculated_subtotal,
  grand_total 
FROM invoice_line_items 
WHERE invoice_id = <invoice_id>;"
```

Subtotal should match grand_total (no discount applied)

**Result:** ✅ PASS if all math is correct
**Result:** ❌ FAIL if amounts don't match or formula wrong

---

## Test 4: Invoice PDF Generation

### Scenario:
Generate and verify invoice PDF looks correct

### Steps:
1. **Navigate to Invoice Show Page**
   - On any issued invoice
   - Click **View / Print PDF** button
   - PDF should download or open in browser

2. **Verify PDF Content:**
   - [ ] Hospital name and GSTIN visible at top
   - [ ] Patient details correct
   - [ ] Invoice number and date correct
   - [ ] Line items table with all columns: Description, HSN/SAC, Qty, Unit Price, GST %, Amount
   - [ ] Subtotal shown
   - [ ] Grand Total in bold
   - [ ] Balance Due in red
   - [ ] QR code for verification
   - [ ] ABDM consent footer at bottom
   - [ ] No broken formatting or overlapping text
   - [ ] All amounts match invoice show page

3. **Print Test:**
   - If browser PDF viewer, click **Print**
   - Should print with proper formatting
   - No page breaks cutting line items

### Verification:
- PDF renders without errors
- All required GST fields present
- Matches invoice show page amounts exactly

**Result:** ✅ PASS if PDF is complete and correct
**Result:** ❌ FAIL if missing fields, wrong amounts, or formatting issues

---

## Test 5: PHR Linking (End-to-End)

### Scenario:
After issuing an invoice, verify it appears in the patient's PHR and ABDM record has all details

### Steps:
1. **Issue an Invoice:**
   - Follow Test 2 to create and issue an invoice
   - Note the invoice number and amount

2. **Check ABDM Record:**
   ```bash
   mysql -h <abdm_host> -D <abdm_db> -e \
   "SELECT id, invoice_number, invoice_date, total_amount, amount_paid, balance_due, created_at 
    FROM cnmgts_patient_abha_m2_records 
    WHERE hi_type = 'Invoice' 
    ORDER BY created_at DESC LIMIT 1 \G"
   ```
   Verify:
   - invoice_number matches
   - total_amount matches
   - amount_paid = 0 (if no payment yet)
   - balance_due = total_amount

3. **Check Line Items in ABDM:**
   ```bash
   mysql -h <abdm_host> -D <abdm_db> -e \
   "SELECT description, hsn_sac_code, quantity, unit_price, gst_rate, amount 
    FROM cnmgts_patient_abha_m2_invoice_items 
    WHERE m2_record_id = <m2_record_id> 
    ORDER BY sort_order;"
   ```
   Should show all line items from invoice

4. **(If Patient PHR Available) View in PHR:**
   - Log in as patient (or patient's representative)
   - Navigate to "Care Contexts" or "My Records"
   - Invoice should appear with:
     - Invoice number as title
     - Issue date
     - Amount
     - Option to view full PDF

### Verification:
- ABDM record created with Invoice HI type
- All line items copied to invoice_items table
- Amounts match HMIS invoice exactly
- Patient can view in PHR (if applicable)

**Result:** ✅ PASS if ABDM record complete and linked to PHR
**Result:** ❌ FAIL if record missing, amounts don't match, or PHR can't display it

---

## Test 6: Payment Recording

### Scenario:
Record a payment against an invoice → Verify balance updates

### Steps:
1. **Navigate to Issued Invoice**
   - Go to **Billing** list
   - Click on any Issued invoice

2. **Record a Payment:**
   - Scroll to **"Record Payment"** section
   - Enter **Amount** (e.g., 500)
   - Select **Mode** (e.g., Cash)
   - Reference (auto-fills with invoice number)
   - Click **Record Payment**
   - Flash: `"Payment recorded"`

3. **Verify Updates:**
   - Amount Paid increases
   - Balance Due decreases
   - Invoice status changes:
     - If balance_due = 0: status = 'Paid' (green badge)
     - If balance_due > 0: status = 'PartiallyPaid' (blue badge)

### Verification:
```bash
mysql -e "SELECT status, amount_paid, balance_due FROM invoices 
          WHERE invoice_number = 'INV/...';"

mysql -e "SELECT amount, mode, status FROM payment_transactions 
          WHERE invoice_id = <invoice_id>;"
```

**Result:** ✅ PASS if payment recorded and balance updates
**Result:** ❌ FAIL if amounts don't update or status doesn't change

---

## Test 7: Multiple Invoices per Case

### Scenario:
Verify a case can have multiple invoices (Draft + Issued, different periods)

### Steps:
1. **Create and Issue First Invoice** (Test 2)
   - Should be Issued status

2. **Click "Generate Invoice" Again**
   - Should create a NEW Draft invoice (different number)
   - Only includes NEW billables added after first invoice
   - Does NOT re-bill already-invoiced items

3. **Verify Both Invoices Exist:**
   - On case Billing panel
   - Should show 2 invoices: one Issued, one Draft
   - Different invoice numbers
   - Different line items

### Verification:
```bash
mysql -e "SELECT invoice_number, status, grand_total FROM invoices 
          WHERE case_id = <case_id> 
          ORDER BY invoice_date DESC;"
```

Should show 2+ rows with different numbers and statuses

**Result:** ✅ PASS if multiple invoices coexist without duplication
**Result:** ❌ FAIL if new invoice re-includes old items or doesn't create

---

## Full Test Matrix

| Test | Pass Criteria | Status |
|------|---------------|--------|
| 1. Auto-Draft | Draft invoice auto-creates on case save with medicines | ⬜ |
| 2. Quick Action | "Create & Issue Bill" generates and issues invoice | ⬜ |
| 3. GST Math | All amounts correct, no CGST/SGST split shown | ⬜ |
| 4. PDF | PDF renders with all required fields and matches amounts | ⬜ |
| 5. ABDM Linking | Record created in ABDM with all line items | ⬜ |
| 6. Payment | Payment records and updates balance correctly | ⬜ |
| 7. Multiple Invoices | Case can have multiple invoices without duplication | ⬜ |

---

## If Tests Fail

1. **Check var/log/dev.log for errors:**
   ```bash
   tail -200 var/log/dev.log
   ```

2. **Review BILLING_DEBUG.md for troubleshooting steps**

3. **Verify prerequisites are all complete:**
   - Schema applied
   - Roles assigned
   - Hospital GSTIN set
   - Charges configured
   - ABDM app running

4. **Common issues:**
   - No Draft invoice → Check listener registered (`php bin/console debug:container --tag doctrine.orm.entity_listener`)
   - No ABDM record → Check `ABDM_APP_URL` in `.env.local`
   - PDF errors → Check template exists (`templates/cases/reports/invoice_print.html.twig`)
   - Wrong amounts → Check charge configuration and GST % rates
