# Billing Module Debugging Checklist

## Auto-Draft Invoice Not Creating

### 1. Check Database Schema
```bash
php bin/console doctrine:schema:update --dump-sql
# Verify tables exist:
# - invoices
# - invoice_line_items  
# - hospital_radiology_charges
```

### 2. Check Listener Registration
```bash
php bin/console debug:container --tag doctrine.orm.entity_listener
# Should show: App\Entity\Listener\CaseInvoiceDraftListener
```

### 3. Check Cache
```bash
php bin/console cache:clear --no-warmup
```

### 4. Verify in Database
After creating a case with medicines, check:
```sql
SELECT * FROM invoices WHERE case_id = <case_id> AND status = 'Draft';
SELECT * FROM invoice_line_items WHERE invoice_id = <invoice_id>;
```

---

## Invoice Not Linking to PHR

### 1. Check ABDM App is Running
```bash
# Terminal 1: Run ABDM Laravel app
cd D:\abdm\ folder\abdm
php artisan serve
# Should be at http://127.0.0.1:8000
```

### 2. Check ABDM_APP_URL Environment
```bash
# In HMIS .env.local, verify:
ABDM_APP_URL=http://127.0.0.1:8000
# Or set ngrok tunnel if using that
```

### 3. Check Invoice HI Type Registration
```bash
# In HMIS: src/Service/ReportTypeRegistry.php
# Line 57 should have:
new ReportType('Invoice', 'Invoice', 'cases/reports/invoice_print.html.twig', ['ROLE_BILLING'])
```

### 4. Verify autoLinkAndNotify is Called
In `InvoiceController::issue()` (line 211), verify:
```php
$abha->autoLinkAndNotify($invoice->getCase(), 'Invoice');
```

### 5. Check ABDM App Side
In Laravel app (`M2HIPController.php`):
```bash
# Line ~1200: hi_type validator includes 'Invoice'
# Line ~1220: savePatientRecord() saves invoice_* fields
# Line ~2850: getBundle() has elseif ($hiType == 'Invoice') branch
```

### 6. Test ABDM Record Creation
After issuing an invoice, query the ABDM database:
```sql
-- ABDM app database
SELECT * FROM cnmgts_patient_abha_m2_records 
WHERE hi_type = 'Invoice' 
ORDER BY created_at DESC LIMIT 1;

SELECT * FROM cnmgts_patient_abha_m2_invoice_items 
WHERE m2_record_id = <record_id>;
```

---

## Invoice PDF Not Rendering

### 1. Check Template Path
Verify file exists:
```bash
ls -la templates/cases/reports/invoice_print.html.twig
```

### 2. Check Dompdf Options
In `Abha::renderPdfBytes()`, verify Dompdf is configured:
- `isRemoteEnabled` = false
- No CSS var() used in template
- WinAnsi fonts only (no Unicode symbols like ₹)

### 3. Test PDF Generation
```bash
curl "http://localhost:8000/billing/1/pdf?id=<encrypted_invoice_id>"
# Should return PDF binary, not HTML error
```

---

## Billing Staff Can't See Invoices

### 1. Check Role is Assigned
```sql
SELECT * FROM user_role WHERE user_id = <billing_staff_id> AND role = 'ROLE_BILLING';
```

### 2. Check Security Config
`config/packages/security.yaml` line ~40:
```yaml
ROLE_BILLING: [ROLE_STOCK_ACCESS]
```

### 3. Check Menu Visibility
`templates/parts/topnav.html.twig` line ~58:
```twig
{% if is_granted('ROLE_BILLING') or is_granted('ROLE_ADMIN') %}
  Billing menu should be visible
{% endif %}
```

---

## Common Issues & Fixes

### Issue: "Invoice table doesn't exist" error
**Fix**: Apply schema migration
```bash
php bin/console dbal:run-sql "SHOW TABLES LIKE 'invoices'"
# If not shown, run:
php bin/console doctrine:schema:update --force
```

### Issue: "ABDM app connection refused"
**Fix**: Start the ABDM Laravel app
```bash
cd D:\abdm\ folder\abdm
php artisan serve
# Verify ABDM_APP_URL env points to :8000
```

### Issue: "Invoice appears in Draft but never auto-links"
**Fix**: Check abha_link_retries table (retry queue)
```sql
SELECT * FROM abha_link_retries 
WHERE case_id = <case_id> AND hi_type = 'Invoice'
ORDER BY created_at DESC;
-- Check last_error column for ABDM failure reason
-- If stuck, retry manually:
php bin/console app:abha:retry-links
```

### Issue: "LineItems missing from invoice PDF"
**Fix**: Verify invoice_line_items were saved
```sql
SELECT COUNT(*) FROM invoice_line_items WHERE invoice_id = <id>;
```

---

## Quick Test Workflow

1. **Create a test case** with medicines
2. **Navigate to Cases** → Find case → **Click "Create & Issue Bill"**
3. **Verify:**
   - ✓ Draft invoice created with auto-calculated total
   - ✓ Can edit and add service charges
   - ✓ Click Issue → becomes Issued status
   - ✓ Flash message: "automatically linked to the patient's PHR"
4. **Check ABDM app:**
   ```bash
   SELECT * FROM cnmgts_patient_abha_m2_records 
   WHERE hi_type = 'Invoice' AND care_context_reference = '<case_id>'
   ```
   Should show one recent record with invoice_number, total_amount, etc.

5. **Check PHR:**
   - Log in as patient
   - View "My Records"  
   - Invoice should appear as a Care Context

---

## Support Commands

```bash
# Clear everything and start fresh
php bin/console cache:clear
php bin/console doctrine:schema:update --force

# Test auto-linking retry queue
php bin/console app:abha:retry-links

# View ABDM app logs (if using ngrok tunnel)
# Check: D:\abdm\ folder\abdm\storage\logs\laravel.log

# Verify Doctrine listener is loaded
php bin/console debug:container --tag doctrine.orm.entity_listener
```

---

## Still Not Working?

1. Check `var/log/dev.log` for errors
2. Run `php bin/console lint:twig templates/` to verify templates
3. Verify all tables were created: `php bin/console doctrine:schema:update --dump-sql`
4. Test individual components:
   - Can you create an invoice manually via `/billing/new/1`?
   - Can you issue it without ABDM_APP_URL set (test locally)?
   - Does the PDF render standalone?
