# Dashboard Demo Seed Scripts

Comprehensive demo data seeding scripts for the JTBD-aligned dashboard.

## 🎯 Purpose

These scripts create realistic demo data to showcase all dashboard features and user flows:

- **Time-based Action Queue** (URGENT/TODAY/WEEK grouping)
- **AI Prevented Issues** (showcasing AI value)
- **Execution Progress Tracking** (production/deliveries/approvals)
- **Stock Receipt Modal** workflows
- **Health Status** tri-state checklist
- **All Alert Types** with full enrichment

## 📋 Available Scripts

### 1. `seed_dashboard_comprehensive.py` ⭐ **RECOMMENDED**

**Comprehensive dashboard demo covering ALL scenarios**

**What it seeds:**
- 🔴 **URGENT** actions (<6h deadline): 3 alerts
  - PO approval escalation (72h aged, 2h deadline)
  - Delivery overdue (4h late, supplier contact needed)
  - Batch at risk (missing ingredients, 5h window)

- 🟡 **TODAY** actions (<24h deadline): 3 alerts
  - PO approval needed (dairy products, 20h deadline)
  - Delivery arriving soon (8h, prep required)
  - Low stock warning (yeast, order today recommended)

- 🟢 **THIS WEEK** actions (<7d deadline): 2 alerts
  - Weekend demand surge prediction
  - Stock receipt incomplete (2 days old)

- ✅ **AI PREVENTED ISSUES**: 3 alerts
  - Prevented stockout (PO created, €250 saved)
  - Prevented waste (production adjusted, €120 saved)
  - Prevented delay (batches rescheduled, €85 saved)

**Expected Dashboard State:**
```
Health Status: YELLOW (actions needed)
├─ ⚡ AI Handled: 3 issues (€455 saved)
└─ ⚠️  Needs You: 8 actions

Action Queue: 8 total actions
├─ 🔴 URGENT: 3
├─ 🟡 TODAY: 3
└─ 🟢 WEEK: 2

AI Impact: €455 in prevented costs
```

**Usage:**
```bash
# Quick start
python services/demo_session/scripts/seed_dashboard_comprehensive.py

# With custom tenant
DEMO_TENANT_ID=your-tenant-id python services/demo_session/scripts/seed_dashboard_comprehensive.py

# With custom RabbitMQ
RABBITMQ_URL=amqp://user:pass@host:5672/ python services/demo_session/scripts/seed_dashboard_comprehensive.py
```

---

### 2. `seed_enriched_alert_demo.py`

**Legacy enriched alert demo** (basic scenarios)

Seeds 5 basic alert types with automatic enrichment:
- Low stock (AI handled)
- Supplier delay (critical)
- Waste trend (standard)
- Forecast anomaly (info)
- Equipment maintenance (medium)

**Usage:**
```bash
python services/demo_session/scripts/seed_enriched_alert_demo.py
```

**Note:** For full dashboard testing, use `seed_dashboard_comprehensive.py` instead.

---

## 🚀 Quick Start

### Prerequisites

1. **RabbitMQ running:**
   ```bash
   kubectl get pods | grep rabbitmq
   # Should show: rabbitmq-0  1/1  Running
   ```

2. **Alert Processor service running:**
   ```bash
   kubectl get pods -l app.kubernetes.io/name=alert-processor-service
   # Should show: alert-processor-service-xxx  1/1  Running
   ```

3. **Python dependencies:**
   ```bash
   pip install -r requirements.txt
   ```

### Running the Demo

```bash
# 1. Navigate to project root
cd /path/to/bakery-ia

# 2. Load environment variables (if needed)
source .env

# 3. Run comprehensive dashboard seeder
python services/demo_session/scripts/seed_dashboard_comprehensive.py
```

### Expected Output

```
================================================================================
🚀 SEEDING COMPREHENSIVE DASHBOARD DEMO DATA
================================================================================

📋 Configuration:
   Tenant ID: demo-tenant-bakery-ia
   RabbitMQ: amqp://guest:guest@localhost:5672/

📊 Dashboard Scenarios to Seed:
   🔴 URGENT actions (<6h): 3
   🟡 TODAY actions (<24h): 3
   🟢 WEEK actions (<7d): 2
   ✅ AI Prevented Issues: 3
   📦 Total Alerts: 11

📤 Publishing Alerts:
────────────────────────────────────────────────────────────────────────────────
   1. ✅ [🔴 URGENT] URGENT: PO Approval Needed - Yeast Supplier
   2. ✅ [🔴 URGENT] Delivery Overdue: Flour Delivery
   3. ✅ [🔴 URGENT] Batch At Risk: Missing Ingredients
   4. ✅ [🟡 TODAY] PO Approval: Butter & Dairy Products
   5. ✅ [🟡 TODAY] Delivery Arriving in 8 Hours: Sugar & Ingredients
   6. ✅ [🟡 TODAY] Low Stock: Fresh Yeast
   7. ✅ [🟢 WEEK] Weekend Demand Surge Predicted
   8. ✅ [🟢 WEEK] Stock Receipt Pending: Flour Delivery
   9. ✅ [✅ PREVENTED] ✅ AI Prevented Stockout: Flour
  10. ✅ [✅ PREVENTED] ✅ AI Prevented Waste: Reduced Monday Production
  11. ✅ [✅ PREVENTED] ✅ AI Prevented Delay: Rescheduled Conflicting Batches

✅ Published 11/11 alerts successfully

================================================================================
🎉 DASHBOARD DEMO SEEDED SUCCESSFULLY!
================================================================================
```

---

## 🔍 Verification

### 1. Check Alert Processing

```bash
# View alert-processor logs (real-time)
kubectl logs -f deployment/alert-processor-service | grep 'enriched_alert'

# Should see:
# alert_enriched  alert_id=xxx  type_class=action_needed  priority_score=92
# alert_enriched  alert_id=xxx  type_class=prevented_issue  priority_score=35
```

### 2. Access Dashboard

```bash
# Port forward if needed
kubectl port-forward svc/frontend-service 3000:3000

# Open browser
open http://localhost:3000/dashboard
```

### 3. Verify Dashboard Sections

**✅ Health Status Card:**
- Should show YELLOW status
- Tri-state checklist items visible
- AI prevented issues badge showing "3 issues prevented"

**✅ Action Queue Card:**
- 🔴 URGENT section with 3 items (2h countdown visible)
- 🟡 TODAY section with 3 items
- 🟢 THIS WEEK section with 2 items

**✅ Orchestration Summary:**
- "User Needed: 8" in yellow (clickable)
- "AI Prevented: 3 issues" in green badge

**✅ AI Impact Card:**
- Shows €455 total savings
- Lists 3 prevented issues

---

## 🧪 Testing Scenarios

### Scenario 1: Urgent Action with Countdown

**Test:** PO Approval Escalation (2h deadline)

1. Navigate to dashboard
2. Find "URGENT: PO Approval Needed - Yeast Supplier" in 🔴 URGENT section
3. Verify countdown timer shows ~2 hours
4. Click "Approve" button
5. Verify alert moves to resolved/archived

**Expected Smart Actions:**
- ✅ Approve PO (primary, green)
- ⚙️ Modify PO (secondary)
- ❌ Reject PO (danger, red)

---

### Scenario 2: Stock Receipt Modal

**Test:** Mark Delivery as Received

1. Find "Delivery Arriving in 8 Hours" in 🟡 TODAY section
2. Click "Mark as Received" button
3. **Stock Receipt Modal should open:**
   - Shows PO details (supplier, items)
   - Lot input fields for each line item
   - Quantity validation (lots must sum to actual)
   - Mandatory expiration dates
4. Fill in lot details:
   - Lot number (e.g., "LOT-2024-089")
   - Quantity per lot
   - Expiration date (required)
   - Warehouse location
5. Click "Confirm Receipt"
6. Verify inventory is updated

**Expected Validation:**
- ❌ Error if lot quantities don't sum to actual quantity
- ❌ Error if expiration date missing
- ✅ Success toast on confirmation

---

### Scenario 3: AI Prevented Issue Showcase

**Test:** View AI Value Proposition

1. Find "✅ AI Prevented Stockout: Flour" in alert list
2. Verify prevented issue badge (⚡ lightning bolt)
3. Click to expand reasoning
4. **Should show:**
   - AI action taken: "Purchase order created automatically"
   - Savings: €250
   - Reasoning: "Detected stock would run out in 1.8 days..."
   - Business impact: "Secured 4 production batches"

5. Navigate to Orchestration Summary Card
6. Verify "AI Prevented: 3 issues" badge shows €455 total

---

### Scenario 4: Call Supplier (External Action)

**Test:** Supplier contact integration

1. Find "Delivery Overdue: Flour Delivery" in 🔴 URGENT section
2. Click "Call Supplier" button
3. **Expected behavior:**
   - Phone dialer opens with +34-555-5678
   - OR clipboard copies phone number
   - Toast notification confirms action

**Metadata displayed:**
- Supplier: Harinera San José
- Phone: +34-555-5678
- Email: pedidos@harinerasj.es
- Hours overdue: 4

---

### Scenario 5: Navigation to Linked Pages

**Test:** Smart action navigation

1. Find "Batch At Risk: Missing Ingredients" in 🔴 URGENT
2. Click "View Production" button
3. **Should navigate to:** `/production?batch_id=batch-chocolate-cake-evening`
4. Production page shows batch details
5. Missing ingredients highlighted

---

## 🐛 Troubleshooting

### Issue: Alerts not appearing in dashboard

**Check:**
```bash
# 1. Verify RabbitMQ is running
kubectl get pods | grep rabbitmq

# 2. Check alert-processor logs
kubectl logs deployment/alert-processor-service --tail=100

# 3. Verify alerts.exchange exists
# (Check RabbitMQ management UI: localhost:15672)

# 4. Check for errors in seeder output
python services/demo_session/scripts/seed_dashboard_comprehensive.py 2>&1 | grep ERROR
```

**Common Fixes:**
- Restart alert-processor: `kubectl rollout restart deployment/alert-processor-service`
- Re-run seeder with debug: `python -u services/demo_session/scripts/seed_dashboard_comprehensive.py`
- Check RabbitMQ queue: `raw_alerts_queue` should have consumers

---

### Issue: Countdown timer not working

**Check:**
```bash
# Verify urgency_context.auto_action_countdown_seconds is set
# Should be in alert metadata
```

**Fix:** Re-run seeder to ensure urgency_context is populated

---

### Issue: Stock Receipt Modal not opening

**Check:**
```bash
# 1. Verify modal component is imported in DashboardPage
grep -r "StockReceiptModal" frontend/src/pages/app/DashboardPage.tsx

# 2. Check browser console for errors
# Look for: "delivery:mark-received event not handled"

# 3. Verify smartActionHandlers.ts is loaded
```

**Fix:** Ensure event listener is registered in DashboardPage.tsx

---

## 📊 Data Reference

### Alert Type Classes

- `action_needed` - Requires user decision (yellow)
- `prevented_issue` - AI already handled (blue/green)
- `trend_warning` - Proactive insight (info)
- `escalation` - Time-sensitive with countdown (red)
- `information` - Pure informational (gray)

### Priority Levels

- `critical` (90-100) - Needs decision in 2 hours
- `important` (70-89) - Needs decision today
- `standard` (50-69) - Review when convenient
- `info` (0-49) - For awareness

### Time Groups

- 🔴 **URGENT** - Deadline <6 hours
- 🟡 **TODAY** - Deadline <24 hours
- 🟢 **THIS WEEK** - Deadline <7 days

---

## 🔄 Resetting Demo Data

To clear all demo alerts and start fresh:

```bash
# 1. Delete all alerts for demo tenant
# (This requires admin access to alert-processor DB)

# 2. Or restart alert-processor (clears in-memory cache)
kubectl rollout restart deployment/alert-processor-service

# 3. Re-run seeder
python services/demo_session/scripts/seed_dashboard_comprehensive.py
```

---

## 📝 Notes

- **Automatic Enrichment:** All alerts are automatically enriched by alert-processor service
- **Priority Scoring:** Multi-factor algorithm considers urgency, impact, user agency
- **Smart Actions:** Dynamically generated based on alert type and context
- **Real-time Updates:** Dashboard subscribes to SSE for live alert updates
- **i18n Support:** All alerts support EN/ES/EU languages

---

## 🚀 Next Steps

After seeding:

1. **Test all smart actions** (approve, reject, call, navigate, etc.)
2. **Verify performance** (<500ms dashboard load time)
3. **Test responsive design** (mobile, tablet, desktop)
4. **Check translations** (switch language in UI)
5. **Test SSE updates** (create new alert, see real-time update)

---

## 🤝 Contributing

To add new demo scenarios:

1. Edit `seed_dashboard_comprehensive.py`
2. Add new alert to appropriate function (`create_urgent_actions()`, etc.)
3. Include full metadata for enrichment
4. Test enrichment output
5. Update this README with new scenario

---

## 📚 Related Documentation

- [Alert Type Schemas](../../../shared/schemas/alert_types.py)
- [Dashboard Service API](../../../services/orchestrator/app/api/dashboard.py)
- [Smart Action Handlers](../../../frontend/src/utils/smartActionHandlers.ts)
- [JTBD Implementation Status](../../../docs/JTBD-IMPLEMENTATION-STATUS.md)
