# 🎯 Sales Dashboard - Complete Operations Guide

## System Health Check

✅ **App Status**: HEALTHY
- Python syntax: Valid
- DEV mode: Working (localhost:5000)
- PROD mode: Configured (0.0.0.0:5000)
- Database: Connected (Google Sheets)
- Authentication: OAuth2 (Google/Microsoft)
- Role-based access: Enabled (admin, comercial, viewer, warehouse)

---

## 📚 Quick Navigation

| Role | Need? | Start Here |
|------|-------|-----------|
| **Developer** | Develop/test features | → [Development Mode Guide](#development-mode-guide) |
| **Sales Manager** | Use production dashboard | → [Sales User Guide](#sales-user-guide) |
| **IT Admin** | Deploy/maintain systems | → [Operations Guide](#operations--deployment-guide) |

---

## Development Mode Guide

### For: Developers building new features

#### Starting DEV Environment

```powershell
# Single PowerShell window
.\run_dev.ps1

# What happens:
# - Flask starts on http://localhost:5000
# - Debug mode ENABLED (auto-reload on file changes)
# - Only accessible from your PC (127.0.0.1)
# - User info & DEV badge visible in header
```

#### What You See in DEV

**Header shows:**
```
🌍 Globale RC logo
📊 Dashboard de Vendas
🔵 DEV (blue badge) ← Confirms dev mode
👤 [Your Name] [YOUR ROLE] ← Your user identity
```

#### Making Changes

**When you edit `.py` files:**
```
1. Save file in VS Code
2. Flask detects change automatically
3. Server reloads in terminal
4. Refresh browser - see changes immediately
```

**Example workflow:**
```python
# Edit app.py - Add a new feature
# Save file
# See: "Restarting with reloader" in terminal
# Refresh http://localhost:5000/dashboard
# ✓ New feature works!
```

#### Testing During Development

**Test dashboard locally:**
```powershell
# While .\run_dev.ps1 is running in another window
curl http://localhost:5000/dashboard

# Or open browser:
http://localhost:5000/dashboard
```

**Test OAuth locally:**
```
1. Click Google/Microsoft login button
2. You're redirected to OAuth provider
3. Login with your account
4. Redirected back to http://localhost:5000/oauth2callback
5. Dashboard loads with your role
```

#### Common Development Tasks

| Task | How To |
|------|--------|
| Add new metric | Edit `app.py` → add calculation → save |
| Modify dashboard layout | Edit HTML in `app.py` → refresh browser |
| Debug data | Add `print()` in code → check terminal output |
| Test with different roles | Use Google Workspace account with different role |
| Reset data | Restart Flask, Google Sheets updates auto |

#### Development Ports & Access

| Port | Purpose | Access |
|------|---------|--------|
| 5000 | Flask (DEV) | Only localhost (127.0.0.1) |
| 4040 | Ngrok API (if using) | Local only |

---

## Sales User Guide

### For: Sales force using the dashboard

#### Accessing the Dashboard

**Once deployed to production:**
```
1. Open browser
2. Go to: https://sales.globalerc.pt/dashboard
3. Click "Login with Google" or "Login with Microsoft"
4. Enter credentials
5. ✓ Dashboard loads
```

#### What You See

**Dashboard Header:**
```
🌍 Globale RC logo
📊 Dashboard de Vendas
🟢 PROD (green badge) ← Production mode
👤 José Amor COMERCIAL ← Your role
```

**Navigation Tabs:**
```
📊 Vendas (Sales) ← Only for comercial/admin
📦 Inventário (Inventory) ← Only for warehouse/admin
```

#### Features Available

**📉 Priority Actions (Ações Prioritárias da Semana)**
- Shows clients with revenue drops >20% YoY
- Click "Contactar Cliente" to prepare for outreach
- Shows:
  - Current year revenue
  - Previous year revenue
  - Percentage change (red = decrease)

**🎯 Commercial Dashboard (for comercial role users)**
- Revenue metrics
- Client performance
- Actionable insights
- Filtered to your assigned clients only

**📦 Inventory Management (for warehouse role users)**
- Stock levels
- Product tracking
- Warehouse operations

#### User Filtering by Role

| Feature | Admin | Comercial | Warehouse | Viewer |
|---------|-------|-----------|-----------|--------|
| View Dashboard | ✓ | ✓ | ✗ | ✓ |
| View Inventory | ✓ | ✗ | ✓ | ✗ |
| Edit Settings | ✓ | ✗ | ✗ | ✗ |
| See All Data | ✓ | Own clients | Own products | Limited |

#### Using Priority Actions

**Workflow:**

1. **Review Weekly Actions**
   ```
   🎯 Ações Prioritárias da Semana
   📉 Queda de Faturação (>20%) - 10 customers
   ```

2. **For each customer with revenue drop:**
   - Read current and previous year revenue
   - Review percentage drop
   - Click "Contactar Cliente" button

3. **Follow up:**
   - Call/email the client
   - Discuss revenue decline
   - Identify solutions
   - Document action taken

#### Troubleshooting User Issues

| Problem | Solution |
|---------|----------|
| "Can't login" | Verify Google/Microsoft account is in system |
| "No data showing" | Refresh page, check Google Sheets connection |
| "Can't see Inventory tab" | You don't have warehouse role - contact admin |
| "Wrong data filtering" | Check your assigned clients - contact admin |

---

## Operations & Deployment Guide

### For: IT Admin / DevOps maintaining the system

#### System Architecture

```
┌─────────────────────────────────────────┐
│   DEVELOPMENT MODE (Developer Only)    │
│  http://localhost:5000 (127.0.0.1:5000) │
│  ✓ Auto-reload on code changes          │
│  ✓ Debug logging enabled                │
│  ✓ No firewall/networking needed        │
└─────────────────────────────────────────┘
                    ↕
        Develop & Test Features Here
                    ↕
┌─────────────────────────────────────────┐
│   PRODUCTION MODE (Sales Force)         │
│   https://sales.globalerc.pt (443/80)   │
│   ✓ Nginx reverse proxy                 │
│   ✓ SSL/TLS encryption                  │
│   ✓ Full network accessible             │
│   • Requires: DNS + Port Forwarding      │
└─────────────────────────────────────────┘
```

#### Deployment Checklist

**Before Going Live:**
```powershell
# 1. Test DEV mode
.\run_dev.ps1
# Verify: http://localhost:5000 → Status 200

# 2. Verify PROD configuration
# Check: run_prod.ps1 exists and has correct FLASK_MODE

# 3. Configure DNS (at domain registrar)
# Old: 94.46.169.199
# New: 78.137.202.90

# 4. Configure router port forwarding
# Port 80 → 192.168.10.67:80
# Port 443 → 192.168.10.67:443

# 5. Install Nginx
choco install nginx

# 6. Copy configuration
Copy-Item nginx.conf C:\nginx\conf\nginx.conf -Force

# 7. Install SSL certificate
# Option: ZeroSSL (https://zerossl.com)
# Path: C:\certbot\live\sales.globalerc.pt\
#   - fullchain.pem
#   - privkey.pem

# 8. Update Google OAuth
# Add: https://sales.globalerc.pt/oauth2callback

# 9. Test PROD mode
.\run_prod.ps1
# Separate window: cd C:\nginx; .\nginx.exe

# 10. Test from another device/network
# https://sales.globalerc.pt
```

#### Running Both Modes

**DEV Mode (for developers):**
```powershell
# Terminal 1 - Start Flask (DEV)
.\run_dev.ps1

# Accessible at: http://localhost:5000
# Features: Auto-reload, debug logging, local only
```

**PROD Mode (for sales team):**
```powershell
# Terminal 1 - Start Flask (PROD)
.\run_prod.ps1

# Terminal 2 - Start Nginx (reverse proxy)
cd C:\nginx
.\nginx.exe

# Accessible at: https://sales.globalerc.pt
# Features: SSL, firewall-ready, network accessible
```

#### Daily Operations

**Restart Services (if needed):**
```powershell
# 1. Stop all services
Get-Process python | Stop-Process -Force
Get-Process nginx | Stop-Process -Force

# 2. Verify ports are free
netstat -an | findstr :5000
netstat -an | findstr :443

# 3. Restart in correct mode
.\run_dev.ps1    # For development
# OR
.\run_prod.ps1   # For production
```

**Monitor Status:**
```powershell
# Check Flask
Get-Process python
Get-NetTCPConnection -LocalPort 5000 | Select-Object State

# Check Nginx
Get-Process nginx
Get-NetTCPConnection -LocalPort 443 | Select-Object State

# Check logs
notepad C:\nginx\logs\error.log
notepad C:\nginx\logs\access.log
```

#### Backup & Recovery

**Backup data:**
```powershell
# Configuration files
Copy-Item app.py app.py.backup
Copy-Item nginx.conf nginx.conf.backup

# Google Sheets
# Automatic - managed by Google (check Google Drive)
```

**Recover from failure:**
```powershell
# 1. Check error logs
cat C:\nginx\logs\error.log

# 2. Test Flask syntax
python -m py_compile app.py

# 3. Restart services
.\run_dev.ps1  # Test in dev first
.\run_prod.ps1 # Then prod
```

#### Monitoring Checklist

**Daily:**
- [ ] Check dashboard loads at https://sales.globalerc.pt
- [ ] Verify login works (test account)
- [ ] Check no errors in nginx logs
- [ ] Verify HTTPS certificate valid

**Weekly:**
- [ ] Review error logs
- [ ] Check user access patterns
- [ ] Verify data freshness (Google Sheets sync)
- [ ] Test with different user roles

**Monthly:**
- [ ] Review SSL certificate expiration (renew if <3 months)
- [ ] Analyze usage statistics
- [ ] Update dependencies if needed
- [ ] Full system backup

#### Emergency Procedures

**If production is down:**
```powershell
# 1. Check what's running
Get-Process python, nginx

# 2. Check ports
Get-NetTCPConnection -LocalPort 80, 443, 5000

# 3. Check Nginx config
cd C:\nginx
.\nginx.exe -t

# 4. Check Flask syntax
python -m py_compile app.py

# 5. Restart services
Kill-Service flask (if registered as service)
Get-Process python | Stop-Process -Force

# 6. Start in DEV mode first to test
.\run_dev.ps1

# 7. If DEV works, start PROD
.\run_prod.ps1
cd C:\nginx; .\nginx.exe
```

---

## System Features & Configuration

### Authentication

**Supported Providers:**
- Google OAuth 2.0
- Microsoft OAuth 2.0 (Entra ID)

**OAuth Configuration:**
```python
# credentials.json location: project root
# Redirect URIs configured:
# - DEV: http://localhost:5000/oauth2callback
# - PROD: https://sales.globalerc.pt/oauth2callback
```

### Role-Based Access Control

**Roles Defined:**
```
admin        → Full access to all features
comercial    → Sales dashboard + assigned clients only
warehouse    → Inventory management only
viewer       → Read-only dashboard
```

**Role Assignment:**
```python
# app.py lines ~350-380
# Edit RBAC_CONFIG to assign roles by email
RBAC_CONFIG = {
    'admin': ['admin@globalerc.pt'],
    'comercial': ['jose.amor@globalerc.pt', 'helder.oliveira@globalerc.pt'],
    'warehouse': ['warehouse@globalerc.pt'],
}
```

### Data Source

**Google Sheets Integration:**
```
Spreadsheet ID: 1ayEGU0h_R7CY55COC1U94-p0rJch109YBGvezjYjHWw
Service Account: credentials.json
Sync: Real-time on page load
```

### Key Files

| File | Purpose |
|------|---------|
| `app.py` | Main Flask application (7700+ lines) |
| `run_dev.ps1` | Start development mode |
| `run_prod.ps1` | Start production mode |
| `nginx.conf` | Reverse proxy & HTTPS config |
| `priority_actions_helper.py` | Logic for priority actions feature |
| `requirements.txt` | Python dependencies |

---

## Troubleshooting Matrix

| Symptom | Cause | Fix |
|---------|-------|-----|
| "Connection refused" on localhost:5000 | Flask not running | Run `.\run_dev.ps1` |
| "Port 5000 in use" | Flask already running | Kill: `Get-Process python \| Stop-Process -Force` |
| "HTTPS certificate error" | SSL cert expired/invalid | Renew from ZeroSSL |
| "Users can't login" | OAuth redirect URI wrong | Check Google Cloud Console |
| "No data loading" | Google Sheets permission denied | Check service account credentials |
| "Wrong user role" | RBAC_CONFIG not updated | Edit RBAC_CONFIG in app.py |
| "Nginx won't start" | Port 443 in use or config error | Run `.\nginx.exe -t` to test |

---

## Deployment Timeline

**First Time Setup: ~2 hours**
1. DNS update (propagation: 5-15 min)
2. Router configuration (10 min)
3. Nginx installation (5 min)
4. SSL certificate (15 min)
5. Service startup & testing (20 min)

**Regular Maintenance: ~10 min/week**
1. Check logs (5 min)
2. Verify services running (5 min)

**Feature Development: Varies**
1. Edit in DEV (flex time)
2. Test locally (varies)
3. Deploy to PROD (5 min once tested)

---

## Contact & Support

**For Issues:**
- Check TROUBLESHOOTING section above
- Review error logs: `C:\nginx\logs\`
- Test in DEV mode first
- Check Google OAuth credentials

**For Feature Requests:**
- Edit `app.py` in DEV mode
- Test thoroughly
- Deploy when ready

---

**Last Updated:** March 5, 2026
**System Status:** ✅ Healthy
**Version:** 1.0 (Dashboard + Priority Actions + RBAC)
