# Google Sign-In - Odoo Integration

## Summary

**YES - Google sign-in DOES create a customer in Odoo automatically.**

When a user signs in with Google for the first time, the system:
1. Creates a customer record in the local database
2. Immediately creates a corresponding partner record in Odoo
3. Links the two records via `odoo_partner_id`

## Flow Diagram

```
User clicks "Sign in with Google"
         ↓
Google returns ID token (JWT)
         ↓
Backend verifies token with Google
         ↓
Extract: email, name, google_sub
         ↓
Check if customer exists by email
         ↓
    ┌────────────────┐
    │ Customer Exists│
    └────────────────┘
         ↓
    Update google_sub
    Return token
         
    ┌──────────────────┐
    │ New Customer     │
    └──────────────────┘
         ↓
    Create in local DB
         ↓
    Create in Odoo ✅
         ↓
    Link via odoo_partner_id
         ↓
    Return token
```

## Implementation Details

### Endpoint
**POST** `/api/auth/google`

**Request:**
```json
{
  "credential": "eyJhbGciOiJSUzI1NiIsImtpZCI6..." // Google ID token (JWT)
}
```

### Google Token Payload
The system extracts:
- `sub` - Google's unique user ID (stored as `google_sub`)
- `email` - User's email address
- `name` - User's full name

### Local Customer Creation

**File:** `afinet-portal-backend/app/Http/Controllers/API/AuthController.php`
**Method:** `googleAuth()`

**Customer Data:**
```php
Customer::create([
    'name' => $name,                              // From Google
    'email' => $email,                            // From Google
    'phone' => '',                                // Empty (can be added later)
    'password' => Str::random(32),                // Random (not used for Google auth)
    'company_name' => null,
    'type' => 'business',                         // Default type
    'vat_number' => null,
    'account_number' => 'CUST-' . strtoupper(uniqid()),
    'account_status' => 'active',
]);
```

### Odoo Customer Creation

**Data Sent to Odoo:**
```php
$odooCustomerData = [
    'name' => $name,              // User's full name from Google
    'email' => $email,            // Email from Google
    'phone' => $phone,            // Empty string
    'customer_rank' => 1,         // Marks as customer
    'is_company' => false,        // Individual, not company
    'street' => '',               // Empty (can be updated later)
    'city' => '',                 // Empty (can be updated later)
];
```

**Odoo Model:** `res.partner`

**Method:** `OdooService->createCustomer()`

### Success Flow

1. Customer created in local database
2. `OdooService->createCustomer()` called
3. Odoo returns `partner_id`
4. Local customer updated with:
   - `odoo_partner_id` = Odoo's partner ID
   - `odoo_synced` = true
   - `odoo_synced_at` = current timestamp
5. Success logged
6. Authentication token returned to user

### Error Handling

**If Odoo creation fails:**
- Customer is still created locally
- Error is logged (not thrown)
- User can still sign in
- Odoo sync can be retried later

**Log Entry:**
```
Failed to create Google customer in Odoo
- customer_id: 123
- error: [error message]
```

## What's Missing in Google Sign-In

Compared to regular registration, Google sign-in customers have:

### Empty Fields:
- `phone` - Not provided by Google
- `company_name` - Not collected
- `vat_number` - Not collected
- `street` - Not collected
- `city` - Not collected
- `country_id` - Intentionally omitted to avoid foreign key issues

### Default Values:
- `type` = 'business' (retail customer)
- `is_company` = false (individual)
- `customer_rank` = 1 (marks as customer in Odoo)
- `account_status` = 'active'

## Odoo Record Details

### What Appears in Odoo:
- **Name:** User's full name from Google
- **Email:** User's email from Google
- **Type:** Individual (not company)
- **Customer:** Yes (customer_rank = 1)
- **Phone:** Empty
- **Address:** Empty

### What Can Be Updated Later:
Users can complete their profile through:
- Profile settings page
- Checkout process
- KYC document upload
- Quotation request

## Comparison: Google vs Regular Registration

| Field | Google Sign-In | Regular Registration |
|-------|---------------|---------------------|
| Name | ✅ From Google | ✅ User input |
| Email | ✅ From Google | ✅ User input |
| Phone | ❌ Empty | ✅ User input |
| Password | 🔒 Random (unused) | ✅ User input |
| Company Name | ❌ Null | ✅ User input |
| Type | 🔧 Default: business | ✅ User selects |
| Odoo Creation | ✅ Automatic | ✅ Automatic |
| Odoo Sync | ✅ Immediate | ✅ Immediate |

## Benefits

1. **Seamless Experience** - Users can sign in with one click
2. **Automatic Odoo Sync** - No manual intervention needed
3. **Verified Email** - Google verifies email ownership
4. **Secure** - No password to manage for Google users
5. **Fast Onboarding** - Minimal friction to start using the portal

## Limitations

1. **Incomplete Profile** - Users need to add phone, address, etc.
2. **No Company Info** - Business details not collected initially
3. **KYC Required** - Still need to upload documents for purchases
4. **Limited Odoo Data** - Basic partner record only

## Recommendations

### For Better User Experience:
1. Show profile completion prompt after Google sign-in
2. Request phone number on first login
3. Guide users to complete KYC before making purchases
4. Add company information collection for business users

### For Better Odoo Integration:
1. Add profile update sync to Odoo
2. Sync phone number when added
3. Sync address when provided
4. Update `is_company` flag if user adds company details

## Code Location

**Controller:** `afinet-portal-backend/app/Http/Controllers/API/AuthController.php`
**Method:** `googleAuth()`
**Service:** `afinet-portal-backend/app/Services/OdooService.php`
**Method:** `createCustomer()`

## Testing

To verify Google sign-in creates Odoo customer:

1. Sign in with Google (new account)
2. Check logs for: "Google customer created in Odoo"
3. Verify in database: `customers` table has `odoo_partner_id`
4. Check Odoo: Search for partner by email
5. Confirm partner exists with correct data

## Logging

**Success Log:**
```
Google customer created in Odoo
- customer_id: 123
- odoo_partner_id: 456
```

**Failure Log:**
```
Failed to create Google customer in Odoo
- customer_id: 123
- error: Connection timeout
```

## Security Notes

- Google token is verified with Google's servers
- Invalid tokens are rejected
- Email uniqueness is enforced
- Random password prevents unauthorized access
- Only Google authentication works for these accounts
- `google_sub` links account to Google identity
