# 🎯 Live Terminal Output for Inventory Processing

## Overview

The inventory processing API now outputs logs **directly to the terminal in real-time** when called via curl, making debugging instant and visible.

---

## 🚀 Quick Start

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

### Using the test script:
```bash
./test_inventory_live.sh
```

### With custom URL:
```bash
./test_inventory_live.sh http://your-domain.com/api/inventory/processTransactions
```

---

## 📺 What You'll See

### Example Terminal Output:

```
=== INVENTORY PROCESS TRANSACTIONS START ===
Request Method: POST
Request URI: /api/inventory/processTransactions
Creating InventoryService instance
Querying unprocessed transactions count
Found 5 unprocessed transactions
Unprocessed transactions details:
  Txn 0: ID=txn-001, Product=prod-abc, Change=-2, Branch=branch-123
  Txn 1: ID=txn-002, Product=prod-def, Change=-3, Branch=branch-123
  Txn 2: ID=txn-003, Product=prod-ghi, Change=-1, Branch=branch-456

Calling processInventoryTransactions()
[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: prod-abc-branch-123
[InventoryService] Looking up product_batch_number for product_id: prod-abc
[InventoryService] Found batch_number_id: batch-001
[InventoryService] Checking for existing inventory record
[InventoryService] Updating existing inventory: 100 + (-2) = 98
[InventoryService] Update completed
[InventoryService] Processing update for key: prod-def-branch-123
[InventoryService] Looking up product_batch_number for product_id: prod-def
[InventoryService] Found batch_number_id: batch-002
[InventoryService] Checking for existing inventory record
[InventoryService] Updating existing inventory: 50 + (-3) = 47
[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

Processing completed in 42.15ms
Actually processed: 5 transactions
Still unprocessed: 0 transactions
=== INVENTORY PROCESS TRANSACTIONS END (SUCCESS) ===

=== JSON RESPONSE ===
{"success":true,"message":"Inventory transactions processed successfully",...}
```

---

## 🎨 Output Format

The output is structured in three parts:

### 1. **Live Processing Logs** (streamed in real-time)
```
=== INVENTORY PROCESS TRANSACTIONS START ===
...processing logs...
=== INVENTORY PROCESS TRANSACTIONS END (SUCCESS) ===
```

### 2. **Summary Stats**
```
Processing completed in 42.15ms
Actually processed: 5 transactions
Still unprocessed: 0 transactions
```

### 3. **JSON Response** (at the end)
```
=== JSON RESPONSE ===
{"success":true,...}
```

---

## 📋 Testing Commands

### 1. Basic Test
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}'
```

### 2. With Pretty JSON at End
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | tail -1 | jq .
```

### 3. Save Logs to File
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | tee inventory_process_$(date +%Y%m%d_%H%M%S).log
```

### 4. Show Only Processing Logs (no JSON)
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | sed '/=== JSON RESPONSE ===/q' | head -n -1
```

### 5. Show Only JSON Response
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | grep -A 9999 '=== JSON RESPONSE ===' | tail -n +2 | jq .
```

### 6. Watch for Errors in Real-Time
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | grep --color=always -E 'ERROR|WARNING|$'
```

---

## 🔍 What to Look For

### ✅ **Success Indicators**
```
[InventoryService] Transaction committed successfully
[InventoryService] processInventoryTransactions() END - SUCCESS
=== INVENTORY PROCESS TRANSACTIONS END (SUCCESS) ===
```

### ⚠️ **Warnings (Partial Success)**
```
[InventoryService] WARNING: No batch number found for product_id: xyz - SKIPPING
[InventoryService] Processed 3 updates, skipped 2
```

### ❌ **Errors**
```
[InventoryService] EXCEPTION caught: Database connection failed
[InventoryService] Rolling back transaction
=== INVENTORY PROCESS TRANSACTIONS END (ERROR) ===
```

### 💤 **No Work Needed**
```
Found 0 unprocessed transactions
No transactions to process - returning early
```

---

## 🛠️ Advanced Usage

### Color-Coded Output
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | \
  sed 's/ERROR/\x1b[31mERROR\x1b[0m/g' | \
  sed 's/WARNING/\x1b[33mWARNING\x1b[0m/g' | \
  sed 's/SUCCESS/\x1b[32mSUCCESS\x1b[0m/g'
```

### Pipe to Less for Scrolling
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | less -R
```

### Count Processed Transactions
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | grep "Actually processed:" | grep -oP '\d+'
```

### Extract Processing Time
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' | grep "Processing completed in" | grep -oP '\d+\.\d+'
```

---

## 🧪 Testing Different Scenarios

### Test with No Transactions
Just call the API when the queue is empty:
```bash
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}'
```

Expected output:
```
Found 0 unprocessed transactions
No transactions to process - returning early
```

### Test with Many Transactions
Create test transactions first, then process:
```bash
# Create test transactions (example)
curl -X POST http://localhost/api/pos/sale \
  -H "Content-Type: application/json" \
  -d '{"items":[{"product_id":"...","qty":2}],...}'

# Process them
curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}'
```

### Test Error Handling
The logs will show detailed error information if something goes wrong.

---

## 🎯 Integration with Other Tools

### Use with watch for Auto-Refresh
```bash
watch -n 5 'curl -s -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" -d "{}" | head -20'
```

### Cron Job with Logging
```bash
# Add to crontab
*/5 * * * * curl -X POST http://localhost/api/inventory/processTransactions \
  -H "Content-Type: application/json" -d '{}' \
  >> /var/www/html/TAF/logs/inventory_cron.log 2>&1
```

### Webhook Integration
```bash
# Call from external system
curl -X POST https://your-domain.com/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{}'
```

---

## 📊 Output Examples

### Successful Processing (5 transactions)
```
=== INVENTORY PROCESS TRANSACTIONS START ===
Request Method: POST
Request URI: /api/inventory/processTransactions
Found 5 unprocessed transactions
[InventoryService] Found 5 unprocessed transactions
[InventoryService] Aggregated into 3 unique product-branch combinations
[InventoryService] Processed 3 updates, skipped 0
[InventoryService] Marking 5 transactions as processed
[InventoryService] Transaction committed successfully
Processing completed in 38.42ms
Actually processed: 5 transactions
=== INVENTORY PROCESS TRANSACTIONS END (SUCCESS) ===
```

### With Warnings (some products missing batch numbers)
```
Found 10 unprocessed transactions
[InventoryService] Found 10 unprocessed transactions
[InventoryService] WARNING: No batch number found for product_id: xyz - SKIPPING
[InventoryService] WARNING: No batch number found for product_id: abc - SKIPPING
[InventoryService] Processed 8 updates, skipped 2
Actually processed: 8 transactions
Still unprocessed: 2 transactions
```

### Error Case (database issue)
```
Found 5 unprocessed transactions
[InventoryService] EXCEPTION caught: SQLSTATE[23503]: Foreign key violation
[InventoryService] Rolling back transaction
ERROR in processTransactions: SQLSTATE[23503]: Foreign key violation
=== INVENTORY PROCESS TRANSACTIONS END (ERROR) ===
```

---

## 🎬 Getting Started

1. **Run the test script:**
   ```bash
   cd /var/www/html/TAF
   ./test_inventory_live.sh
   ```

2. **Or use curl directly:**
   ```bash
   curl -X POST http://localhost/api/inventory/processTransactions \
     -H "Content-Type: application/json" \
     -d '{}'
   ```

3. **Watch the logs stream in real-time!**

---

## 💡 Pro Tips

1. **Save successful runs for comparison:**
   ```bash
   curl -s -X POST http://localhost/api/inventory/processTransactions \
     -H "Content-Type: application/json" -d '{}' \
     > success_baseline.log
   ```

2. **Diff against baseline:**
   ```bash
   diff success_baseline.log <(curl -s -X POST ... )
   ```

3. **Monitor processing time trends:**
   ```bash
   for i in {1..10}; do
     curl -s -X POST http://localhost/api/inventory/processTransactions \
       -H "Content-Type: application/json" -d '{}' \
       | grep "Processing completed in"
     sleep 5
   done
   ```

4. **Alert on errors:**
   ```bash
   result=$(curl -s -X POST ...)
   if echo "$result" | grep -q "ERROR"; then
     mail -s "Inventory Processing Error" admin@example.com <<< "$result"
   fi
   ```

---

## 🎉 Summary

✅ **Real-time output** - See logs as they happen  
✅ **No waiting** - Instant feedback in terminal  
✅ **Both logs and JSON** - Detailed logs + structured response  
✅ **Easy to pipe** - Works with all standard Unix tools  
✅ **Color coding support** - Add your own colors with sed  
✅ **Perfect for debugging** - See exactly what's happening  

**Just curl and watch!** 🚀
