# 📦 Inventory Module - Setup Guide

## Overview

The Inventory Module is a **completely independent system** from the Sales Dashboard. They share only:
- Authentication (Google OAuth)
- User interface framework
- Role-based access control

**No data dependencies** - Each system has its own Google Sheet and operates autonomously.

---

## Features

✅ **View Current Stock Levels** - Real-time inventory display  
✅ **Low Stock Alerts** - Red highlighting for items below minimum  
✅ **Search & Filter** - Find products quickly  
✅ **Summary Statistics** - Total items, low stock count, total quantity  
✅ **Role-Based Access** - Admins + Warehouse team  

---

## Setup Steps

### Step 1: Create Inventory Google Sheet

1. Go to [Google Sheets](https://sheets.google.com)
2. Click **"+ New"** → **"Spreadsheet"**
3. Name it: `Inventário - Globale RC` (or any name)
4. Create the first sheet with these 25 columns:

| # | Column | Type | Example |
|---|--------|------|---------|
| 1 | Linha | Text | A1, B2 (warehouse position) |
| 2 | Quantidade em stock | Number | 45 |
| 3 | Tipo | Text | Morada, Urna, etc |
| 4 | Ref | Text | REF-001 |
| 5 | Modelo | Text | Modelo A |
| 6 | Submodelo | Text | Submodelo 1 |
| 7 | Tipo de tampa | Text | Madeira, Metal |
| 8 | Medida | Number | 50 (cm) |
| 9 | Tipo de Medida | Text | cm, mm, in |
| 10 | Madeira | Text | Carvalho, Pinho |
| 11 | Laminado | Text | Sim, Não |
| 12 | Cor | Text | Branco, Cinzento |
| 13 | Acabamento | Text | Polido, Mate |
| 14 | Zinco/Inox | Text | Zinco, Inox, Nenhum |
| 15 | Estofo | Text | Veludo, Algodão |
| 16 | Tecido | Text | Cor Tecido |
| 17 | Renda | Text | Sim, Não |
| 18 | Conjunto | Text | Sim, Não |
| 19 | Asas | Text | Sim, Não |
| 20 | Qtd Asas | Number | 2 |
| 21 | Cruz/Cristo | Text | Sim, Não |
| 22 | Fecho | Text | Tipo Fecho |
| 23 | Acessórios | Text | Descrição |
| 24 | Extras/Observações | Text | Notas adicionais |
| 25 | Cliente | Text | Client name |

**Example Row:**
```
Linha: A1
Quantidade em stock: 5
Tipo: Morada
Ref: MOD-001
Modelo: Morada Premium
Submodelo: Modelo 1
Tipo de tampa: Madeira
Medida: 60
Tipo de Medida: cm
Madeira: Carvalho
Laminado: Não
Cor: Branco
Acabamento: Polido
Zinco/Inox: Inox
Estofo: Veludo
Tecido: Azul Marinho
Renda: Sim
Conjunto: Sim
Asas: Sim
Qtd Asas: 2
Cruz/Cristo: Não
Fecho: Fecho Dourado
Acessórios: Almofada extra
Extras/Observações: Stock limitado
Cliente: ACME Corp
```

### Step 2: Share Sheet with Google OAuth Account

1. Click **"Share"** button (top right)
2. Enter the email: `de.globalerc@gmail.com` (your OAuth account)
3. Give **Editor** access
4. Click **"Share"**

### Step 3: Get Sheet ID

1. Open the sheet
2. Copy the URL: `https://docs.google.com/spreadsheets/d/**SHEET-ID**/edit`
3. Copy the `SHEET-ID` part

Example:
```
URL: https://docs.google.com/spreadsheets/d/1ayEGU0h_R7CY55COC1U94-p0rJch109YBGvezjYjHWw/edit
SHEET-ID: 1ayEGU0h_R7CY55COC1U94-p0rJch109YBGvezjYjHWw
```

### Step 4: Configure in `app.py`

Open `app.py` and update the Inventory section (around line 37):

```python
# ============================================================================
# INVENTORY MODULE CONFIGURATION (Separate System)
# ============================================================================
INVENTORY_SPREADSHEET_ID = "YOUR-SHEET-ID-HERE"  # ← Paste your Sheet ID here
```

Example:
```python
INVENTORY_SPREADSHEET_ID = "1ayEGU0h_R7CY55COC1U94-p0rJch109YBGvezjYjHWw"
```

### Step 5: Add Warehouse Team (Optional)

Edit the `WAREHOUSE_EMAILS` section in `app.py`:

```python
WAREHOUSE_EMAILS = {
    "warehouse1@globalerc.com",
    "warehouse2@globalerc.com",
    # Add more warehouse team emails here
}
```

Also add them to `USERS_ROLES`:

```python
USERS_ROLES = {
    # ... existing users ...
    "warehouse1@globalerc.com": "warehouse",
    "warehouse2@globalerc.com": "warehouse",
}
```

### Step 6: Restart Flask

```powershell
# Kill existing Flask
taskkill /F /IM python.exe 2>$null

# Restart
python app.py
```

---

## Usage

### Accessing Inventory

1. Login to dashboard: `https://your-ngrok-url/`
2. Click **"📦 Inventário"** tab in the navigation
3. View all inventory items

### Features

#### Search & Filter
- **Search box**: Type product code or location
- **Filter checkbox**: Show only items with low stock

#### Status Indicators

| Status | Color | Meaning |
|--------|-------|---------|
| ✓ Normal | Green | Stock is above minimum |
| ⚠️ Crítico | Red | Stock is BELOW minimum |

#### Summary Stats
- **Total de Produtos**: Count of all inventory items
- **Stock Baixo**: Number of items below minimum
- **Quantidade Total**: Sum of all quantities

---

## How It Works

### Data Flow

```
Google Sheets (Inventory) 
    ↓
API: /get-inventory-data
    ↓
Caching Layer (5 min TTL)
    ↓
inventory.html (Frontend)
    ↓
User Display
```

### Access Control

```
Admin Role (always access)
    ↓ YES ↓
Warehouse Role (if email in WAREHOUSE_EMAILS)
    ↓ YES ↓
Others (denied)
```

### Low Stock Detection

```
For each item:
    if Quantidade < Stock Mínimo:
        Mark as "Crítico" (red)
    else:
        Mark as "Normal" (green)
```

---

## Troubleshooting

### "Inventário não configurado" Error
**Problem**: Sheet ID not set  
**Solution**: Add `INVENTORY_SPREADSHEET_ID` in `app.py` line 40

### "Acesso Negado" Error
**Problem**: User doesn't have inventory access  
**Solution** (Admin only):
1. Email must be in `ADMIN_EMAILS` OR `WAREHOUSE_EMAILS`
2. Check spelling and lowercase emails
3. Add to `USERS_ROLES` mapping

### Data Not Loading
**Problem**: No items showing  
**Solution**:
1. Check Google Sheet has at least 1 row of data
2. Column names must match exactly (including spaces)
3. Run refresh button 🔄
4. Check Flask console for errors

### Column Names Not Matching
**Current column names (exact match required):**
```
- Código do Produto
- Localização
- Quantidade
- Stock Mínimo
- Ponto de Reorder
- Status
```

If your sheet has different names, edit `INVENTORY_COLUMNS` in `app.py`:

```python
INVENTORY_COLUMNS = [
    'Your Actual Column Name 1',
    'Your Actual Column Name 2',
    # ... etc
]
```

---

## Future Enhancements

Possible additions (not currently included):

- ✓ Stock movements (add this later)
- ✓ Edit/update items (dashboard only)
- ✓ Automated low stock alerts (email/SMS)
- ✓ Multi-location support
- ✓ Product photos/barcodes
- ✓ Inventory reports & analytics

---

## Files Changed

```
app.py
├── Added INVENTORY_SPREADSHEET_ID config
├── Added WAREHOUSE_EMAILS role
├── Added /inventory route
├── Added /get-inventory-data endpoint
└── Added /set-inventory-spreadsheet endpoint

templates/
├── base.html (added inventory nav link)
└── inventory.html (new file)
```

---

## Quick Start Summary

1. ✅ Create Google Sheet with 6 columns
2. ✅ Share with Google OAuth account
3. ✅ Copy Sheet ID
4. ✅ Paste into `app.py` line ~40
5. ✅ Add warehouse team emails (optional)
6. ✅ Restart Flask
7. ✅ Access `/inventory` route

**That's it!** Your inventory system is ready to use.

---

## Support

If something doesn't work:
1. Check Flask console for error messages
2. Verify column names match exactly
3. Ensure sheet is shared with OAuth account
4. Clear cache: Restart Flask app
5. Check network tab in browser DevTools for API errors
