# Billing Module Setup & Installation Guide

## Step 1: Database Schema Setup

```bash
# Check what schema changes are pending
php bin/console doctrine:schema:update --dump-sql

# Apply all schema changes
php bin/console doctrine:schema:update --force

# Verify tables were created
php bin/console dbal:run-sql "SHOW TABLES LIKE 'invoice%'"
# Should show: invoices, invoice_line_items
```

## Step 2: Assign Billing Staff Role

### Option A: Via SQL
```sql
-- Add ROLE_BILLING to a test user
INSERT INTO user_role (user_id, role, created_at) 
SELECT id, 'ROLE_BILLING', NOW() 
FROM users 
WHERE email = 'billing@hospital.local' AND id NOT IN (
  SELECT user_id FROM user_role WHERE role = 'ROLE_BILLING'
);
```

### Option B: Via Admin Dashboard
1. Go to **System → Users**
2. Find a billing staff member
3. Click **Edit**
4. Check **Billing Staff** role
5. Save

## Step 3: Verify Hospital GSTIN (for GST invoices)

### Via Admin Dashboard:
1. Go to **System → Hospitals**
2. Click your hospital
3. Enter **GSTIN** (15-character code like `18AAQCS1234H1Z0`)
4. Save

### Via SQL:
```sql
UPDATE hospitals SET gstin = '18AAQCS1234H1Z0' WHERE id = 1;
```

## Step 4: Configure HSN/SAC Codes (Optional but Recommended)

These are GST line-item classification codes. If left blank, "—" shows on invoices.

### For Services:
1. Go to **System → Billing Services**
2. Edit each service
3. Enter **HSN/SAC Code** (e.g., `998362` for bed/nursing/diagnostic services)
4. Save

### For Lab Tests:
1. Go to **System → Masters → Lab Tests**
2. Edit a test
3. Enter **HSN/SAC Code** (e.g., `998366` for diagnostic services)
4. Save

### For Radiology Tests:
1. Go to **System → Billing → Radiology Test Charges**
2. Click **Edit** on a test charge
3. HSN/SAC is auto-populated from the RadiologyTest
4. Save

### For Pharmacy:
- Automatically uses medicine's GST rate
- HSN/SAC optional (defaults to "—")

## Step 5: Configure Lab & Radiology Pricing

Charges are per-hospital and per-test/procedure. Without charges configured, Draft invoices won't include those line items.

### Lab Test Charges:
1. Go to **System → Billing → Lab Test Charges**
2. Click **Add**
3. Select **Lab Test** (e.g., "Haemoglobin")
4. Enter **Charges** (e.g., 50.00 = Rs. 50)
5. Enter **GST %** (e.g., 5 for 5% GST)
6. Save
   - Billed Amount = Rs. 50 + (50 × 5%) = Rs. 52.50
   - Invoice shows: `Haemoglobin | 1 | 52.50 | 5% | 52.50`

### Radiology Test Charges:
1. Go to **System → Billing → Radiology Test Charges**
2. Click **Add**
3. Select **Radiology Test** (e.g., "Chest X-Ray")
4. Enter **Charges** (e.g., 150.00)
5. Enter **GST %** (e.g., 5)
6. Save

**Note:** If a test has NO charge configured, it won't appear on Draft invoices.

## Step 6: ABDM App Configuration

### Start the ABDM Laravel App:
```bash
cd "D:\abdm folder\abdm"
php artisan serve
# Runs on http://127.0.0.1:8000
```

### Configure HMIS to Point to ABDM App:
In `.env.local`:
```bash
# Option 1: Local ABDM app
ABDM_APP_URL=http://127.0.0.1:8000

# Option 2: ngrok tunnel (if ABDM app is on different network)
ABDM_APP_URL=https://1234-56-789-10-11.ngrok.io
```

### Verify Connection:
```bash
php bin/console dbal:run-sql "SELECT 1" --connection=cnmgts
# Should work if ABDM app database is accessible
```

## Step 7: Test End-to-End Flow

### 1. Create a Test Case:
- Go to **Cases → New Case**
- Select a patient
- Add medicines (or order lab/radiology tests)
- Save

### 2. Navigate to Case Show:
- You should see **"Quick Billing" panel** with:
  - Billable items summary
  - Large **"Create & Issue Bill"** button

### 3. Click "Create & Issue Bill":
- Draft invoice is created automatically
- Redirect to invoice show page
- Flash: `"Invoice INV/... drafted for amount Rs. X.XX"`
- **DO NOT ISSUE YET** — first verify the calculation

### 4. Edit Invoice (Optional):
- Add service charges if needed
- Verify line items match actual case billables
- Check totals are correct

### 5. Issue Invoice:
- Click **Issue Invoice** button
- Flash messages:
  - ✓ `"Invoice INV/... issued"`
  - ℹ️ `"This invoice has been automatically linked to the patient's PHR"`

### 6. Verify ABDM Linking:
```bash
# Check ABDM database for the pushed record
mysql -h 127.0.0.1 -u root -ppassword abdm_local -e \
"SELECT * FROM cnmgts_patient_abha_m2_records 
 WHERE hi_type = 'Invoice' 
 ORDER BY created_at DESC LIMIT 1;"

# Should show: invoice_number, invoice_date, total_amount, amount_paid, balance_due
```

### 7. Test PHR Visibility (if patient console available):
- Log in as patient
- Navigate to "My Records" or "Care Contexts"
- Invoice should appear with download option

## Step 8: Verify in var/log/dev.log

```bash
# Watch for any errors during invoice creation/issue
tail -f var/log/dev.log | grep -i "invoice\|abdm\|error"
```

---

## Troubleshooting Checklist

- [ ] Database tables created (`invoices`, `invoice_line_items`, `hospital_radiology_charges`)
- [ ] Billing staff user has `ROLE_BILLING` role assigned
- [ ] Hospital has GSTIN entered (System → Hospitals)
- [ ] At least one Lab Test Charge configured (if lab tests will be billed)
- [ ] At least one Radiology Test Charge configured (if radiology will be billed)
- [ ] ABDM Laravel app is running on port 8000
- [ ] `.env.local` has `ABDM_APP_URL` pointing to running ABDM app
- [ ] Test case has medicines (or lab/rad tests) before generating invoice
- [ ] No errors in `var/log/dev.log` after issue
- [ ] ABDM record created in `cnmgts_patient_abha_m2_records` table

---

## Configuration Files to Review

1. **HMIS Security**: `config/packages/security.yaml`
   - Line ~40: `ROLE_BILLING: [ROLE_STOCK_ACCESS]`

2. **HMIS Report Registry**: `src/Service/ReportTypeRegistry.php`
   - Line ~57: Invoice HI type registered

3. **HMIS Abha Service**: `src/Service/Abha.php`
   - `autoLinkAndNotify()` calls on Invoice issue
   - Invoice context builder methods

4. **ABDM App Invoice Support**: `D:\abdm folder\abdm\app\Http\Controllers\API\M2HIPController.php`
   - Line ~1207: Invoice in hi_type validator
   - Line ~1219: `savePatientRecord()` handles invoice_* fields
   - Line ~2850: `getBundle()` builds FHIR Invoice resource

---

## Quick Reference: Invoice Status Flow

```
Draft
  ↓ (edit, add lines)
  ↓
Issued ← (auto-links to ABDM)
  ↓ (record payment)
  ↓
PartiallyPaid (some paid, balance due)
  ↓ (record remaining payment)
  ↓
Paid
```

---

## Support

If issues persist after following this guide, check **BILLING_DEBUG.md** for detailed troubleshooting steps.
