# Wholesale Customer Approval Workflow

## Overview
Wholesale customers (partners, ISPs, telecom companies) require approval before accessing the portal. This document outlines the complete approval workflow.

---

## Database Changes

### Migration: `2026_02_25_000001_add_approval_fields_to_customers.php`

Added fields to `customers` table:
- `approval_status` (enum: pending, approved, rejected) - Default: 'pending'
- `approved_at` (timestamp, nullable) - When approved/rejected
- `approved_by` (string, nullable) - Who approved (admin name/ID)
- `rejection_reason` (text, nullable) - Reason if rejected
- `potraz_license_path` (string, nullable) - Path to uploaded POTRAZ license

---

## Registration Flow

### 1. Customer Type Selection
- **Business Customers**: Auto-approved, can login immediately
- **Wholesale Customers**: Require approval, cannot login until approved

### 2. Wholesale Registration Process

#### Frontend (register/page.js)
- Customer selects "Wholesale Partner" category
- Form includes:
  - Company information (required)
  - TIN number (required)
  - VAT number (required)
  - Industry (required)
  - POTRAZ license upload (required)
  - Contact person details

#### Backend (AuthController.php - register method)
1. Validates registration data including file upload
2. Sets `approval_status = 'pending'` for wholesale customers
3. Stores POTRAZ license in `storage/app/potraz_licenses/`
4. Creates customer in portal database
5. Creates customer in Odoo with:
   - `active = false` (blocks customer in Odoo)
   - Comment field includes: "APPROVAL STATUS: PENDING"
   - All company details (TIN, VAT, industry)
6. Sends email notification to admin (COMPANY_MAIL)
7. Returns response with `requires_approval: true`

---

## Email Notifications

### Admin Notification
**File**: `app/Mail/WholesaleRegistrationNotification.php`
**Template**: `resources/views/emails/wholesale-registration.blade.php`

**Sent to**: `COMPANY_MAIL` (configured in .env)
**Includes**:
- Company information (name, TIN, VAT, industry, website)
- Contact person details
- Portal customer ID
- Odoo partner ID
- POTRAZ license as attachment
- Link to view customer in Odoo

**Action Required**:
1. Review POTRAZ license
2. Verify company credentials
3. Check TIN/VAT numbers
4. Approve or reject in Odoo

### Customer Notification (TODO)
- **Pending**: Email confirming registration is under review
- **Approved**: Email with login instructions
- **Rejected**: Email with rejection reason and support contact

---

## Login Restrictions

### AuthController.php - login method
Checks approval status before allowing login:

```php
if ($customer->type === 'wholesale' && $customer->approval_status !== 'approved') {
    return response()->json([
        'success' => false,
        'message' => 'Your account is pending approval...',
        'approval_status' => $customer->approval_status,
    ], 403);
}
```

### Middleware: CheckApprovalStatus
**File**: `app/Http/Middleware/CheckApprovalStatus.php`

Blocks unapproved wholesale customers from accessing protected routes.

**Usage**: Add to route groups that require approval:
```php
Route::middleware(['auth:sanctum', 'check.approval'])->group(function () {
    // Protected routes
});
```

---

## Odoo Integration

### Customer Creation
When wholesale customer registers:
- `active = false` - Customer is archived/blocked
- `comment` field includes approval status
- All company details synced (TIN, VAT, industry)

### Approval in Odoo
Sales team can approve by:
1. Opening customer record in Odoo
2. Reviewing POTRAZ license and details
3. Setting `active = true` to approve
4. Or adding rejection notes in comment field

### Sync Back to Portal (TODO)
Need to implement webhook or sync job to:
1. Detect when Odoo partner `active` field changes
2. Update portal `approval_status` accordingly
3. Send approval/rejection email to customer

---

## Customer Model Methods

### New Methods Added

```php
// Check if customer is approved
public function isApproved()

// Check if customer is pending approval
public function isPendingApproval()

// Check if customer type needs approval
public function needsApproval()
```

---

## Configuration

### Environment Variables (.env)

```env
# Company email for admin notifications
COMPANY_MAIL=admin@afinet.co.zw

# Mail configuration
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_FROM_ADDRESS=notifications@afinet.co.zw
MAIL_FROM_NAME="AFINET Customer Portal"
```

---

## File Storage

### POTRAZ License Upload
- **Storage Path**: `storage/app/potraz_licenses/`
- **Naming**: `potraz_{timestamp}_{original_filename}`
- **Allowed Types**: PDF, JPG, JPEG, PNG
- **Max Size**: 5MB
- **Access**: Attached to admin email, stored for compliance

---

## API Response Examples

### Successful Wholesale Registration
```json
{
  "success": true,
  "message": "Registration successful. Your account is pending approval. You will receive an email once approved.",
  "customer": { ... },
  "access_token": null,
  "approval_status": "pending",
  "requires_approval": true
}
```

### Login Attempt (Pending Approval)
```json
{
  "success": false,
  "message": "Your account is pending approval. You will receive an email once your account is approved by our team.",
  "approval_status": "pending"
}
```

### Login Attempt (Rejected)
```json
{
  "success": false,
  "message": "Your account registration was rejected. Please contact support for more information.",
  "approval_status": "rejected",
  "rejection_reason": "Invalid POTRAZ license"
}
```

---

## Approval Management

### Odoo-Based Approval System

The approval status is **automatically synced from Odoo's `active` field**. No admin portal is needed.

#### How It Works:

1. **Customer Registers** (Wholesale)
   - Portal creates customer in Odoo with `active = false` (archived)
   - Admin receives email with POTRAZ license
   - Customer cannot login (blocked)

2. **Admin Reviews in Odoo**
   - Go to Contacts → Filters → Archived
   - Find customer and review POTRAZ license
   - Verify credentials

3. **Admin Approves**
   - Click "Unarchive" or set `active = true`
   - Save

4. **Portal Syncs Automatically**
   - **Scheduled Sync**: Every 10 minutes via `customers:sync-approval-status` command
   - **Real-Time Sync**: On customer login attempt (immediate approval)

5. **Customer Can Login**
   - Within 10 minutes (scheduled sync)
   - Or immediately on next login attempt (real-time sync)

#### Sync Mechanisms:

**1. Scheduled Sync (Every 10 Minutes)**
```bash
php artisan customers:sync-approval-status
```
- Runs automatically via Laravel scheduler
- Checks all pending wholesale customers
- Updates approval status based on Odoo `active` field

**2. Real-Time Sync (On Login)**
- When wholesale customer tries to login
- Portal queries Odoo in real-time
- If `active = true`, auto-approves and allows login
- No waiting for scheduled sync

#### Manual Sync:
```bash
# Sync all pending customers
php artisan customers:sync-approval-status

# Sync specific customer
php artisan customers:sync-approval-status --customer-id=5

# Sync all wholesale customers
php artisan customers:sync-approval-status --all
```

See `ODOO_APPROVAL_SYNC.md` for detailed documentation.

---

## Testing Checklist

- [ ] Wholesale customer can register with POTRAZ license
- [ ] Admin receives email with attachment
- [ ] Wholesale customer cannot login (pending)
- [ ] Business customer can register and login immediately
- [ ] Odoo customer created with active=false for wholesale
- [ ] Middleware blocks unapproved customers from protected routes
- [ ] Approval status displayed correctly in responses
- [ ] File upload validation works (size, type)
- [ ] Email notifications sent successfully

---

## Security Considerations

1. **File Upload Security**
   - Validate file types (PDF, images only)
   - Limit file size (5MB max)
   - Store outside public directory
   - Scan for malware (future enhancement)

2. **Access Control**
   - Unapproved customers cannot access any portal features
   - Middleware enforces approval check on all protected routes
   - Odoo blocks unapproved customers (active=false)

3. **Data Privacy**
   - POTRAZ licenses stored securely
   - Only admins can access uploaded documents
   - Rejection reasons logged for compliance

---

## Support & Troubleshooting

### Common Issues

**Issue**: Admin not receiving emails
- Check COMPANY_MAIL in .env
- Verify SMTP configuration
- Check Laravel logs: `storage/logs/laravel.log`

**Issue**: File upload fails
- Check storage permissions: `storage/app/potraz_licenses/`
- Verify file size and type
- Check PHP upload limits in php.ini

**Issue**: Customer stuck in pending status
- Manually update in database if needed
- Check Odoo sync status
- Review approval workflow logs

---

## Related Files

### Backend
- `database/migrations/2026_02_25_000001_add_approval_fields_to_customers.php`
- `app/Models/Customer.php`
- `app/Http/Controllers/API/AuthController.php`
- `app/Http/Middleware/CheckApprovalStatus.php`
- `app/Mail/WholesaleRegistrationNotification.php`
- `resources/views/emails/wholesale-registration.blade.php`
- `bootstrap/app.php`

### Frontend (TODO)
- `afinet-portal/src/app/(auth)/register/page.js` - Add file upload
- Handle approval status in login response
- Show pending approval message

### Documentation
- `REGISTRATION_ODOO_FIELD_MAPPING.md` - Field mappings
- `WHOLESALE_APPROVAL_WORKFLOW.md` - This file
