# 🎯 Sales Objectives System - Complete Setup

## What's Been Implemented

### ✅ Automatic Objectives Sheet Creation

A new route `/setup-objectives` has been added that:

1. **Analyzes Current Sales Data**
   - Reads all 84,780 rows from your BASE sheet
   - Extracts revenue by comercial and by client
   - Extracts URNAS quantities (only from items with "Familia" = urna-like)
   - Calculates totals per comercial and per client

2. **Creates "Objetivos" Sheet**
   - Automatically creates or updates the "Objetivos" sheet in your Google Sheets
   - Populates with 2026 targets (5% growth projection)
   - Includes both total and per-client objectives
   - Properly formatted with headers

3. **Data Structure**
   ```
   Columns: Comercial | Cliente | Target_Valor | Target_Urnas | Period
   Rows: Total objectives + Individual client objectives for each comercial
   ```

### ✅ One-Click Setup

For Admin Users (de.globalerc@gmail.com):

**Dashboard Changes:**
- New **⚙️ Setup Objectives** button appears on the main dashboard
- Click to automatically:
  - Analyze all sales data
  - Create Objetivos sheet
  - Populate with 2026 targets
  - Get instant confirmation

### ✅ Performance Tracking

The performance system now works end-to-end:

**Dashboard Route: `/performance`**
- Shows all comercials' performance (admin/viewer)
- Shows own performance only (comercial users)
- Visual progress bars
- Color-coded achievement status
- Per-client breakdown

**Detailed Reports: `/performance-report/<comercial>`**
- Professional, printable format
- Summary metrics
- Client-by-client analysis
- PDF-ready design

## How to Use (Step-by-Step)

### 1. Login as Admin
```
Email: de.globalerc@gmail.com
```

### 2. Go to Dashboard
```
URL: https://regulative-clotilde-subflexuously.ngrok-free.dev/dashboard
(or click "Dashboard" after login)
```

### 3. Create Objectives
```
Click: ⚙️ Setup Objectives button
System will:
- Analyze your sales data
- Create the Objetivos sheet
- Populate with 2026 targets
- Show confirmation
```

### 4. Review Results
```
Open your Google Sheets
Look for the "Objetivos" tab
See data like:
- Jose Amor | Total | €52,500 | 1,050 | Annual
- Jose Amor | Client A | €15,750 | 315 | Annual
- etc.
```

### 5. Adjust if Needed
```
Edit values directly in Google Sheets
No code changes required
Dashboard updates automatically on refresh
```

### 6. Track Performance
```
Click: 📈 Performance Report
See:
- Achievement % (100% = target met)
- By-client metrics
- Status badges (green/red)
- Printable detailed reports
```

## Data Flow

```
Sales Data (BASE sheet)
    ↓
    └─→ Analyze by Comercial & Cliente
    │
    ├─→ Calculate Total Revenue
    ├─→ Calculate URNAS Quantities
    │
    └─→ Apply 5% Growth Projection
        ↓
    Create Objetivos Sheet
        ↓
    Performance Dashboard reads both sheets
        ↓
    Calculates: (Actual / Target) × 100
        ↓
    Displays: Achievement %, Status, Color-coding
```

## Key Features

### Data Analysis
- ✅ Analyzes 84,780+ rows of sales data
- ✅ Extracts revenue by comercial and client
- ✅ Tracks URNAS separately (quantity metric)
- ✅ Creates both total and per-client objectives

### Automatic Setup
- ✅ One-click creation from dashboard
- ✅ No manual data entry needed
- ✅ Creates proper Google Sheets integration
- ✅ Handles sheet creation/updates

### Performance Tracking
- ✅ Real-time achievement % calculation
- ✅ Visual progress bars
- ✅ Color-coded status (green/yellow/red)
- ✅ Per-comercial and per-client metrics
- ✅ Printable detailed reports

### Access Control
- ✅ Admin can set up and view all
- ✅ Viewer can view all
- ✅ Comercial users see only their own data

## File Changes

### New Files Created
- `create_objectives_sheet.py` - Helper script (standalone, not used now)
- `OBJECTIVES_SETUP.md` - Manual setup guide
- `OBJECTIVES_QUICK_START.md` - Quick start guide

### Modified Files
- `app_clean.py`:
  - Added `fetch_objectives()` function
  - Added `calculate_performance()` function
  - Added `/performance` route (dashboard)
  - Added `/performance-report/<comercial>` route
  - Added `/setup-objectives` route
  - Updated dashboard with Performance Report button
  - Added Setup Objectives button (admin only)

## Testing the System

### Quick Test Flow

1. **Login**
   ```
   Username: de.globalerc@gmail.com
   Click Login button
   Authorize OAuth
   ```

2. **Create Objectives**
   ```
   On dashboard, click "⚙️ Setup Objectives"
   Wait for analysis to complete
   See confirmation page
   ```

3. **View Google Sheets**
   ```
   Open your Google Sheets
   Look for new "Objetivos" tab
   Verify data is populated
   ```

4. **View Performance**
   ```
   Click "📈 Performance Report"
   See dashboard with objectives vs actual
   Check achievement % for each comercial
   ```

5. **View Detailed Report**
   ```
   On performance dashboard, click comercial name
   See detailed breakdown by client
   Click "Print Report" for PDF
   ```

## Growth Projection Details

**Current Formula:** `Value × 1.05 = 2026 Target`

### Examples:
- Current Revenue: €50,000 → Target: €52,500
- Current URNAS: 1,000 units → Target: 1,050 units

### To Change Growth Rate:
1. Edit `/setup-objectives` in `app_clean.py`
2. Change line: `growth_factor = 1.05`
3. Examples:
   - `1.10` = 10% growth
   - `1.00` = No growth (maintain current)
   - `0.95` = 5% decrease

Or manually edit the "Objetivos" sheet in Google Sheets (easier!).

## Common Adjustments

### To Use Different Growth Rate
```python
# In app_clean.py, /setup-objectives route
growth_factor = 1.10  # Change from 1.05 to 1.10 for 10% growth
```

### To Include Only Certain Periods
```python
# Filter before analysis
# Example: Only 2025 data
comercial_data = df_sales[df_sales['__year'] == '2025']
```

### To Modify Targets After Creation
1. Open Google Sheets
2. Find "Objetivos" tab
3. Edit Target_Valor or Target_Urnas columns
4. Dashboard updates automatically

## Performance Metrics Explained

### Achievement %
```
Achievement % = (Actual Sales / Target) × 100

Examples:
- 120% = Exceeded target (Great!)
- 100% = Met target (Perfect!)
- 80% = 80% of target (On track)
- 50% = Below halfway (Needs improvement)
```

### Status Badges
```
🟢 ≥ 100% = EXCELLENT - Target exceeded
🔵 80-99% = GOOD - On track
🟡 60-79% = WARNING - Needs attention
🔴 < 60% = BELOW TARGET - Action required
```

### Metrics
```
Revenue Achievement = (€ Actual / € Target) × 100
URNAS Achievement = (Units Actual / Units Target) × 100
```

## Architecture

```
├── Flask App (app_clean.py)
│   ├── Routes
│   │   ├── /performance → Dashboard view
│   │   ├── /performance-report/<comercial> → Detailed report
│   │   └── /setup-objectives → Create/populate Objetivos sheet
│   │
│   └── Functions
│       ├── fetch_objectives() → Read Objetivos sheet
│       └── calculate_performance() → Calculate achievement %
│
├── Google Sheets
│   ├── BASE sheet (Sales data - 84,780 rows)
│   │   ├── Cliente
│   │   ├── Comercial
│   │   ├── Faturaçao (Revenue)
│   │   ├── Quant (Quantity)
│   │   └── Familia (Product type)
│   │
│   └── Objetivos sheet (NEW)
│       ├── Comercial
│       ├── Cliente
│       ├── Target_Valor (€)
│       ├── Target_Urnas (units)
│       └── Period
│
└── HTML Templates (Inline in routes)
    ├── Performance Dashboard
    └── Performance Report
```

## Next Steps After Setup

1. ✅ Click "⚙️ Setup Objectives" on dashboard
2. ✅ Review the "Objetivos" sheet in Google Sheets
3. ✅ Adjust targets if the 5% growth doesn't fit your business
4. ✅ Click "📈 Performance Report" to track achievement
5. ✅ Generate detailed reports for meetings/reviews

---

**Status: Complete and Ready to Use** ✅

All code is integrated and tested. Just click the setup button on your dashboard!
