# Debugging Inventory Processing API

## Quick Test Commands

### Method 1: Using the test script (Recommended)
```bash
php /var/www/html/TAF/test_inventory_process.php
```

### Method 2: Using curl
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' \
  -v
```

### Method 3: Using the bash test script
```bash
/var/www/html/TAF/test_api.sh
```

---

## Debug Output Locations

### 1. Apache/PHP Error Log
```bash
# View live logs
tail -f /var/log/apache2/error.log

# Or project-specific log
tail -f /var/www/html/TAF/logs/error.log

# Filter for inventory-related logs
tail -f /var/log/apache2/error.log | grep -i inventory
```

### 2. API Response
The API now returns detailed debug information:
```json
{
  "success": true,
  "message": "Inventory transactions processed successfully",
  "unprocessed_count_before": 10,
  "processed_count": 10,
  "still_unprocessed": 0,
  "processing_time_ms": 45.23,
  "debug": {
    "method": "POST",
    "timestamp": "2025-10-01 14:30:00",
    "sample_txns": [...]
  }
}
```

---

## Debug Log Format

All operations now log with the prefix `[InventoryService]` or `INVENTORY PROCESS TRANSACTIONS`:

```
=== INVENTORY PROCESS TRANSACTIONS START ===
Request Method: POST
Request URI: /api/inventory/processTransactions
Creating InventoryService instance
[InventoryService] processInventoryTransactions() START
[InventoryService] Beginning database transaction
[InventoryService] Querying unprocessed transactions with row locking
[InventoryService] Found 5 unprocessed transactions
[InventoryService] Aggregating changes by product and branch
[InventoryService] Aggregated into 3 unique product-branch combinations
[InventoryService] Processing update for key: abc123-branch456
[InventoryService] Looking up product_batch_number for product_id: abc123
[InventoryService] Found batch_number_id: batch789
[InventoryService] Checking for existing inventory record
[InventoryService] Updating existing inventory: 10 + (-2) = 8
[InventoryService] Update completed
[InventoryService] Processed 3 updates, skipped 0
[InventoryService] Marking 5 transactions as processed
[InventoryService] Transactions marked as processed
[InventoryService] Committing transaction
[InventoryService] Transaction committed successfully
[InventoryService] processInventoryTransactions() END - SUCCESS
=== INVENTORY PROCESS TRANSACTIONS END (SUCCESS) ===
```

---

## Common Issues & Solutions

### Issue 1: No output or 404 error

**Symptoms:**
- curl returns 404
- No logs appear
- Empty response

**Debug Steps:**
```bash
# 1. Check if router is working
curl http://localhost/api/pos/products

# 2. Check router.php for errors
tail -f /var/log/apache2/error.log

# 3. Verify controller exists
ls -la /var/www/html/TAF/api/controllers/InventoryController.php

# 4. Test with other inventory endpoints
curl http://localhost/api/inventory/getInventory
```

**Solution:**
- Ensure router.php is correctly routing to InventoryController
- Check Apache .htaccess or nginx config
- Verify namespace and class names match

---

### Issue 2: POST doesn't work but GET does

**Symptoms:**
- GET requests work fine
- POST returns 405 Method Not Allowed
- Router says "Action not implemented"

**Debug Steps:**
```bash
# Check the actual HTTP method being received
tail -f /var/log/apache2/error.log | grep "Request Method"

# Test with verbose curl
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' \
  -v 2>&1 | grep "< HTTP"
```

**Solution:**
- Ensure method is `public function processTransactions()` (not `public function postProcessTransactions()`)
- Check router.php logic for POST handling
- Verify no .htaccess rules blocking POST

---

### Issue 3: Method called but no transactions processed

**Symptoms:**
- API returns success
- `processed_count: 0`
- Transactions still in database with `processed_at = NULL`

**Debug Steps:**
```bash
# 1. Check error logs for detailed info
tail -f /var/log/apache2/error.log | grep "\[InventoryService\]"

# 2. Query database directly
sudo -u postgres psql TAF -c "
  SELECT COUNT(*) as unprocessed 
  FROM inventory_txn 
  WHERE processed_at IS NULL 
  AND isDeleted = false;
"

# 3. Check for missing batch numbers
sudo -u postgres psql TAF -c "
  SELECT DISTINCT it.product_id, p.name
  FROM inventory_txn it
  LEFT JOIN product_batch_number pbn ON it.product_id = pbn.product_id
  LEFT JOIN products p ON it.product_id = p.product_id
  WHERE pbn.product_batch_number_id IS NULL
  AND it.processed_at IS NULL
  LIMIT 10;
"
```

**Solution:**
Look for log entries like:
- `WARNING: No batch number found for product_id: xyz` → Need to create batch numbers
- `EXCEPTION caught:` → Check stack trace for database errors
- `skipped N updates` → Products missing batch numbers

---

### Issue 4: Database transaction fails

**Symptoms:**
- Error: "Failed to process inventory transactions"
- Logs show "Rolling back transaction"
- All transactions remain unprocessed

**Debug Steps:**
```bash
# Check for exception details
tail -f /var/log/apache2/error.log | grep -A 10 "EXCEPTION caught"

# Check database locks
sudo -u postgres psql TAF -c "
  SELECT pid, usename, state, query 
  FROM pg_stat_activity 
  WHERE state != 'idle';
"

# Check for constraint violations
sudo -u postgres psql TAF -c "
  SELECT conname, contype 
  FROM pg_constraint 
  WHERE conrelid = 'inventory'::regclass;
"
```

**Solution:**
Common causes:
- Foreign key violations → Ensure products and branches exist
- Null constraint violations → Check branch_id and product_id are set
- Deadlocks → Retry after a moment

---

## Troubleshooting Checklist

### Before calling API:

1. ✅ Check unprocessed transactions exist:
   ```sql
   SELECT COUNT(*) FROM inventory_txn WHERE processed_at IS NULL;
   ```

2. ✅ Verify products have batch numbers:
   ```sql
   SELECT COUNT(*) FROM product_batch_number WHERE isDeleted = false;
   ```

3. ✅ Check logs directory is writable:
   ```bash
   ls -la /var/www/html/TAF/logs/
   ```

### After calling API:

1. ✅ Check HTTP response code (should be 200)
2. ✅ Verify `success: true` in JSON response
3. ✅ Check `processed_count` matches expected
4. ✅ Review error logs for warnings
5. ✅ Query database to confirm transactions marked as processed

---

## SQL Queries for Debugging

### Count unprocessed transactions
```sql
SELECT COUNT(*) as unprocessed_count
FROM inventory_txn
WHERE processed_at IS NULL
AND isDeleted = false;
```

### View unprocessed transactions
```sql
SELECT 
  inventory_txn_id,
  product_id,
  change,
  branch_id,
  reason,
  updatedAt
FROM inventory_txn
WHERE processed_at IS NULL
AND isDeleted = false
ORDER BY updatedAt DESC
LIMIT 20;
```

### Find products without batch numbers
```sql
SELECT DISTINCT 
  it.product_id,
  p.name as product_name,
  COUNT(*) as pending_txns
FROM inventory_txn it
LEFT JOIN product_batch_number pbn ON it.product_id = pbn.product_id AND pbn.isDeleted = false
LEFT JOIN products p ON it.product_id = p.product_id
WHERE pbn.product_batch_number_id IS NULL
AND it.processed_at IS NULL
GROUP BY it.product_id, p.name;
```

### Check inventory before and after
```sql
-- Before processing
SELECT 
  i.inventory_id,
  p.name,
  i.current_qty,
  i.updatedAt
FROM inventory i
JOIN product_batch_number pbn ON i.product_batch_number_id = pbn.product_batch_number_id
JOIN products p ON pbn.product_id = p.product_id
WHERE i.isDeleted = false
ORDER BY i.updatedAt DESC;
```

### View processing history
```sql
SELECT 
  DATE_TRUNC('minute', processed_at) as minute,
  COUNT(*) as txns_processed,
  SUM(change) as total_change
FROM inventory_txn
WHERE processed_at IS NOT NULL
GROUP BY DATE_TRUNC('minute', processed_at)
ORDER BY minute DESC
LIMIT 20;
```

---

## Performance Debugging

### Check processing time
The API response includes `processing_time_ms`. Typical times:
- 1-10 txns: 10-50ms
- 10-50 txns: 50-200ms
- 50-100 txns: 200-500ms
- 100+ txns: 500ms-2s

### Slow query identification
```sql
-- PostgreSQL slow query log
ALTER SYSTEM SET log_min_duration_statement = 100; -- log queries > 100ms
SELECT pg_reload_conf();
```

### Add index for performance
```sql
CREATE INDEX idx_inventory_txn_processing 
ON inventory_txn(processed_at, isDeleted) 
WHERE processed_at IS NULL;
```

---

## Contact & Support

If issues persist after following this guide:

1. Collect the following information:
   - Error logs (last 100 lines with inventory mentions)
   - API response JSON
   - Database query results (unprocessed count, batch number check)
   - PHP version and PostgreSQL version

2. Create a minimal reproduction case:
   ```bash
   # Run the test script and save output
   php /var/www/html/TAF/test_inventory_process.php > debug_output.txt 2>&1
   ```

3. Include stack traces from error logs

4. Note any recent changes to:
   - Database schema
   - Product/inventory setup
   - API routing
