# Client Intelligence Panel - Implementation Guide

## Overview
The **Client Intelligence Panel** is a strategic analytics feature for commercial agents that displays comprehensive client data analysis including revenue trends, product mix, margins, purchase frequency, and smart product recommendations.

## Features Implemented

### 1. **Revenue Analysis (Last 3 Years)**
- Displays revenue by calendar year
- Shows year-over-year trends
- Visual bar chart for quick comparison
- KPI card showing current year revenue and trend vs. previous year

### 2. **Product Mix Breakdown (Last 12 Months)**
- Revenue breakdown by product line/family
- Percentage share calculation
- Doughnut chart visualization
- Table with detailed breakdown

### 3. **Average Margin Analysis**
- Average margin percentage (last 12 months)
- Margin in euros (calculated or direct from data)
- Graceful fallback: "Margem não disponível" if data missing
- Supports margin calculation from cost data if margin column doesn't exist

### 4. **Purchase Frequency**
- Number of orders in last 12 months
- Average days between orders
- Frequency label: Semanal, Mensal, Trimestral, Anual
- Estimated order interval in days

### 5. **Average Order Value (AOV)**
- Total revenue / number of unique order periods (last 12 months)
- Quick reference for order size trends

### 6. **Last Visit Date**
- Displays date of most recent client visit
- Shows days since last visit
- Integrates with visit logs if available
- Graceful "Sem registos de visita" message if no visits

### 7. **Intelligent Product Recommendations**
- Identifies "similar clients" by revenue band (±25%)
- Analyzes what similar clients buy
- Recommends missing product lines with:
  - Product name
  - Count of similar clients buying it
  - Percentage of similar clients
  - Clear explanation of why recommended
- Top 5 recommendations displayed
- Data-driven, explainable engine (no ML black box)

### 8. **Security & Authorization**
- Only logged-in users can access
- Commercial agents see only their assigned clients
- Proper role-based access control integration

## File Structure

```
Sales Dashboard App_VScode/
├── client_intelligence_helper.py        ← Analytics engine & calculations
├── templates/
│   └── client_intelligence.html         ← Frontend display template
└── app.py                               ← Route + integration (modified)
```

## How to Use

### For End Users (Commercial Agents)

1. **From Dashboard**: 
   - Navigate to dashboard
   - Find client in the data table
   - Click "View Intelligence" (when implemented as button)

2. **Direct URL**:
   ```
   http://localhost:5000/client-intelligence?cliente=José%20Silva
   ```

3. **From Client Details**:
   - Go to any client's details page
   - Click "Inteligência de Cliente" button (when added)

### Understanding the Panel

The panel is organized in 6 rows:

**Row 1: KPI Cards** (4 metrics at a glance)
- Faturação Este Ano (current year revenue)
- Margem Média (12-month average margin)
- Encomendas (orders in last 12 months)
- Valor Médio Encomenda (average order value)

**Row 2: Revenue & Product Mix** (2 columns)
- Left: 3-year revenue trend chart + table
- Right: Product mix pie chart + breakdown table

**Row 3: Recommendations**
- Top 5 product opportunities
- Why each is recommended
- Count/percentage of similar clients buying it

**Row 4: Quick Actions**
- "Voltar ao Dashboard" button
- "Detalhes do Cliente" link
- "Registar Visita" modal launcher

## Data Flow

```
User clicks "View Intelligence" 
    ↓
Route: /client-intelligence?cliente=ClientName
    ↓
flask: client_intelligence() route 
    ├─ Validates user authorization (RBAC)
    ├─ Loads sales data from Google Sheets
    ├─ Loads visit logs (if available)
    ├─ Calls cih.generate_client_intelligence_profile()
    └─ Renders template with profile data
```

## Core Functions in `client_intelligence_helper.py`

### Analysis Functions
- `compute_revenue_last_3_years(client_sales_df)` - 3-year revenue breakdown
- `compute_product_mix(client_sales_df)` - Product line analysis (last 12m)
- `compute_avg_margin(client_sales_df)` - Margin calculation
- `compute_purchase_frequency(client_sales_df)` - Order frequency
- `compute_avg_order_value(client_sales_df)` - AOV calculation
- `get_last_visit(visit_logs_df, client_name)` - Last visit lookup

### Recommendation Engine
- `get_similar_clients(all_sales_df, client_name)` - Find comparable clients
- `recommend_missing_products(all_sales_df, client_name, similar_clients_list)` - Generate recommendations

### Main Entry Point
- `generate_client_intelligence_profile(all_sales_df, client_name, visit_logs_df)` - Complete profile

## Adding the Link to UI

To integrate "View Intelligence" button in your existing UI, add this to your template where clients are listed:

```html
<!-- Option 1: In a client table row -->
<td>
    <a href="/client-intelligence?cliente={{ cliente_name | urlencode }}" 
       class="btn btn-sm btn-info">
        <i class="fas fa-chart-line"></i> Inteligência
    </a>
</td>

<!-- Option 2: In a modal or detail view -->
<a href="/client-intelligence?cliente={{ profile.cliente_name | urlencode }}" 
   class="btn btn-success">
    <i class="fas fa-lightbulb"></i> Ver Inteligência do Cliente
</a>

<!-- Option 3: Context menu or dropdown -->
<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle">Ações</button>
    <ul class="dropdown-menu">
        <li>
            <a href="/client-details?cliente={{ cliente_name | urlencode }}">
                Ver Detalhes Completos
            </a>
        </li>
        <li>
            <a href="/client-intelligence?cliente={{ cliente_name | urlencode }}">
                <i class="fas fa-chart-line"></i> Inteligência
            </a>
        </li>
        <li>
            <a href="/visit-report?cliente={{ cliente_name | urlencode }}">
                Registar Visita
            </a>
        </li>
    </ul>
</div>
```

## Data Assumptions & Fallback Behavior

| Scenario | Behavior |
|----------|----------|
| **Empty/missing data** | Shows error message, graceful page display |
| **No margin data** | Displays "Margem não disponível" in KPI card |
| **No visit logs** | Displays "Sem registos de visita" |
| **No recommendations** | Hides recommendation section |
| **Missing product line column** | Skips product mix calculations |
| **Invalid date format** | Safely ignores malformed dates |
| **Access denied** | Returns 403 Forbidden |

## Customization Options

### Change Similarity Mode
In `get_similar_clients()`, modify:
```python
similarity_mode='revenue_band'  # Options: 'revenue_band' (current), 'all'
```

### Adjust Revenue Band Tolerance
In `get_similar_clients()`, change:
```python
min_rev = target_revenue * 0.75  # ±25% current
max_rev = target_revenue * 1.25
```

### Modify Recommendation Count
In `recommend_missing_products()`, change:
```python
return missing_recommendations[:5]  # Currently top 5
```

### Change Frequency Labels
In `compute_purchase_frequency()`, modify thresholds:
```python
if avg_days < 15:
    label = 'Semanal/Bi-semanal'  # Change thresholds here
elif avg_days < 40:
    label = 'Mensal'
```

## Performance Notes

- **Caching**: Leverages existing app.py caching (300s TTL)
- **Data Processing**: Uses pandas for efficient grouping/aggregation
- **Visit Logs**: Loaded on-demand from Google Sheets (add caching if slow)
- **Typical Load Time**: <1s for small datasets (~10k rows)

## Future Enhancements

1. **ML-based recommendations** - Replace rule-based engine with clustering
2. **Custom similarity metrics** - Add zona/segment-based similarity
3. **Trend forecasting** - Predict next quarter revenue
4. **Margin optimization** - Highlight highest-margin products
5. **Risk scoring** - Flag at-risk clients (declining revenue)
6. **Churn probability** - Estimate likelihood of losing client
7. **Export to PDF** - Generate printable client intelligence report
8. **Calendar integration** - Suggest optimal visit frequency

## Troubleshooting

### "Acesso negado" error
- **Cause**: User is comercial role but client not assigned
- **Fix**: Add client to user's assigned comercials in `SALES_ACCESS_MAP`

### Empty recommendations
- **Cause**: No similar clients found or all buy same products
- **Fix**: Check revenue band tolerance, consider 'all' mode

### Performance issues
- **Cause**: Large dataset or slow Google Sheets connection
- **Fix**: Add caching for visit_logs, increase cache TTL

### Charts not rendering
- **Cause**: Chart.js library not loaded
- **Fix**: Check browser console for errors, verify CDN link

## Testing Checklist

- [ ] Access as admin user → should see all clients
- [ ] Access as comercial user → should see only assigned clients
- [ ] Access with invalid client name → shows error gracefully
- [ ] Charts render correctly on desktop and mobile
- [ ] Recommendations appear only when appropriate
- [ ] Revenue trends match client details page
- [ ] All KPI cards show correct values
- [ ] "Margem não disponível" displays when no margin data
- [ ] Visit history correctly integrated
- [ ] URL parameters properly encoded
- [ ] Print functionality works (Ctrl+P)
