# Odoo Customer Sync & First-Time Login Setup

## Overview
This document explains how to sync ALL Odoo customers to the portal database and allow them to set their passwords for first-time login.

## Architecture

### Customer Flow
```
Odoo Customer (hundreds) 
    ↓
Sync to Portal DB (with temp password)
    ↓
Customer visits portal
    ↓
First-time setup: Set password
    ↓
Full portal access
```

## Components Created

### 1. Backend Controller
**File**: `afinet-portal-backend/app/Http/Controllers/API/FirstTimeLoginController.php`

**Endpoints**:
- `POST /api/auth/check-email` - Check if email exists in system
- `POST /api/auth/send-setup-link` - Send password setup link via email
- `POST /api/auth/set-password` - Set password with token verification
- `POST /api/auth/quick-setup` - Quick setup and login in one step

### 2. Frontend Page
**File**: `afinet-portal/src/app/(auth)/first-time-setup/page.js`

**Features**:
- Step 1: Enter email to check if account exists
- Step 2: Set password and automatically login
- Validates password strength (min 8 characters)
- Confirms password match
- Auto-redirects to dashboard after setup

### 3. Sync Script
**File**: `sync-all-odoo-customers-to-portal.php`

**What it does**:
- Fetches ALL customers from Odoo (res.partner)
- Syncs them to portal database
- Sets temporary passwords
- Skips customers without email
- Skips child contacts (only main customers)
- Updates existing customers
- Creates new customers

## How to Use

### Step 1: Sync Odoo Customers to Portal

```bash
php sync-all-odoo-customers-to-portal.php
```

**Expected Output**:
```
🔄 SYNCING ALL ODOO CUSTOMERS TO PORTAL
========================================

📥 Fetching customers from Odoo...
✅ Found 500 customers in Odoo

🔄 Starting sync...

✨ Created: Company ABC (ID: 123)
✅ Updated: Company XYZ (ID: 456)
⏭️  Skipped: No Email Customer (ID: 789) - No valid email

📊 SYNC SUMMARY
===============

Total Odoo customers: 500
✨ Created: 350
✅ Updated: 100
⏭️  Skipped: 50
❌ Errors: 0

🎉 Successfully synced 450 customers to portal!
```

### Step 2: Customer First-Time Login

**Option A: Direct Setup (Recommended)**
1. Customer visits: `https://portal.example.com/first-time-setup`
2. Enters their email
3. System checks if email exists
4. Customer sets password
5. Automatically logged in

**Option B: Email Link (Future Enhancement)**
1. Customer requests password setup link
2. Receives email with secure token
3. Clicks link to set password
4. Sets password and logs in

### Step 3: Regular Login
After password is set, customers use regular login:
- Visit: `https://portal.example.com/login`
- Enter email and password
- Access full portal

## API Usage Examples

### Check if Email Exists
```javascript
POST /api/auth/check-email
{
  "email": "customer@example.com"
}

Response:
{
  "success": true,
  "exists": true,
  "has_password": false,
  "message": "Account found. Please set your password to continue.",
  "data": {
    "name": "John Doe",
    "email": "customer@example.com",
    "account_number": "CUST-ABC123",
    "from_odoo": true
  }
}
```

### Quick Setup and Login
```javascript
POST /api/auth/quick-setup
{
  "email": "customer@example.com",
  "password": "SecurePass123",
  "password_confirmation": "SecurePass123"
}

Response:
{
  "success": true,
  "message": "Welcome! Your account is now active.",
  "data": {
    "customer": {
      "id": 123,
      "name": "John Doe",
      "email": "customer@example.com",
      "account_number": "CUST-ABC123"
    },
    "access_token": "1|abc123...",
    "token_type": "Bearer"
  }
}
```

## Database Structure

### Customers Table
```sql
- id
- account_number (CUST-XXXXX)
- name
- email
- password (bcrypt hashed)
- odoo_partner_id (link to Odoo)
- odoo_last_sync
- email_verified_at
- created_at
- updated_at
```

### Password Resets Table (for email links)
```sql
- email
- token (hashed)
- created_at
```

## Security Features

1. **Password Requirements**:
   - Minimum 8 characters
   - Must be confirmed
   - Bcrypt hashed

2. **Token Verification**:
   - Secure random tokens
   - 24-hour expiration
   - One-time use

3. **Email Verification**:
   - Email marked as verified after password setup
   - Prevents unauthorized access

## Maintenance

### Regular Sync
Run the sync script periodically to keep portal in sync with Odoo:

```bash
# Daily cron job
0 2 * * * cd /path/to/project && php sync-all-odoo-customers-to-portal.php
```

### Monitor Sync Status
```php
// Check sync statistics
$totalPortal = DB::table('customers')->count();
$linkedToOdoo = DB::table('customers')->whereNotNull('odoo_partner_id')->count();
$withPassword = DB::table('customers')->whereNotNull('email_verified_at')->count();

echo "Total customers: {$totalPortal}\n";
echo "Linked to Odoo: {$linkedToOdoo}\n";
echo "With password set: {$withPassword}\n";
```

## Benefits

✅ **Single Source of Truth**: Odoo remains the master customer database  
✅ **Self-Service**: Customers can set their own passwords  
✅ **No Manual Work**: Automatic sync keeps data current  
✅ **Secure**: Proper password hashing and token verification  
✅ **User-Friendly**: Simple 2-step process for customers  
✅ **Scalable**: Handles hundreds of customers easily  

## Troubleshooting

### Customer Can't Find Email
- Check if email exists in Odoo
- Verify email is valid (not "No email", "n/a", etc.)
- Check if customer is a child contact (only main customers synced)

### Password Setup Fails
- Verify password meets requirements (min 8 chars)
- Check passwords match
- Ensure customer hasn't already set password

### Sync Issues
- Check Odoo API connection
- Verify customer has valid email
- Check database permissions
- Review sync script logs

## Next Steps

1. Run initial sync: `php sync-all-odoo-customers-to-portal.php`
2. Test first-time setup with a test customer
3. Set up automated daily sync (cron job)
4. Create email template for password setup links (optional)
5. Add link to first-time setup on login page
6. Monitor customer adoption

## Support

For issues or questions:
- Check logs: `storage/logs/laravel.log`
- Review sync output
- Test with a known Odoo customer
- Verify API connectivity to Odoo
