# Frontend Wholesale Approval Implementation

## Overview
Updated the frontend registration flow to support POTRAZ license upload for wholesale customers and handle the approval workflow.

---

## Files Modified

### 1. `afinet-portal/src/app/(auth)/register/page.js`

#### New Features Added:

**State Management:**
- `potrazFile` - Stores the uploaded POTRAZ license file
- `registrationSuccess` - Tracks successful registration
- `requiresApproval` - Indicates if approval is needed
- `fileInputRef` - Reference to file input element

**File Upload Handling:**
```javascript
const handleFileChange = (event) => {
  // Validates file type (PDF, JPG, PNG)
  // Validates file size (max 5MB)
  // Shows success/error toast
}

const removeFile = () => {
  // Clears selected file
}
```

**Form Submission:**
- Creates FormData for file upload
- Includes POTRAZ license for wholesale customers
- Handles approval response
- Shows success message for wholesale (pending approval)
- Redirects to login for business customers

**UI Components Added:**

1. **POTRAZ License Upload Section** (Wholesale Only)
   - Drag-and-drop style upload area
   - File type and size validation
   - File preview with remove option
   - Visual feedback with icons

2. **Success Message Screen** (Wholesale Pending Approval)
   - Confirmation icon
   - Clear messaging about approval process
   - Timeline of what happens next
   - Links to login and home page

**Icons Added:**
- `Upload` - File upload icon
- `FileText` - Document preview icon
- `X` - Remove file icon

---

### 2. `afinet-portal/src/hooks/use-auth.js`

#### Updated Functions:

**register(data, isFormData = false)**
- Added `isFormData` parameter to handle file uploads
- Returns `requires_approval` flag for wholesale customers
- Throws error instead of returning error object (for better error handling)
- No automatic redirect - handled by component

**login(email, password)**
- Enhanced error handling for approval status
- Detects `approval_status` in error response
- Shows specific messages for:
  - Pending approval (5 second toast)
  - Rejected approval (6 second toast with reason)
- Displays rejection reason if provided

---

### 3. `afinet-portal/src/lib/api.js`

#### Updated API Endpoint:

**authAPI.register(data, isFormData = false)**
```javascript
register: (data, isFormData = false) => {
  if (isFormData) {
    return api.post('/auth/register', data, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }
  return api.post('/auth/register', data);
}
```

- Automatically sets correct Content-Type for file uploads
- Maintains backward compatibility with JSON registration

---

## User Flow

### Wholesale Customer Registration:

1. **Select Account Type**
   - Customer clicks "Wholesale Partner" card

2. **Fill Registration Form**
   - Company information (required)
   - TIN, VAT, industry (required)
   - Contact person details
   - POTRAZ license upload (required)

3. **Upload POTRAZ License**
   - Click "Choose File" button
   - Select PDF, JPG, or PNG (max 5MB)
   - See file preview with name and size
   - Option to remove and re-upload

4. **Submit Registration**
   - Form validates all required fields
   - Uploads file with registration data
   - Backend creates customer with `approval_status = 'pending'`
   - Backend sends email to admin with POTRAZ license

5. **Success Message**
   - Shows confirmation screen
   - Explains approval process
   - Provides timeline (1-2 business days)
   - Links to login page

6. **Login Attempt (Before Approval)**
   - Customer tries to login
   - Receives error: "Your account is pending approval..."
   - Cannot access portal until approved

7. **After Approval**
   - Admin approves in Odoo
   - Customer receives approval email (TODO)
   - Customer can now login successfully

### Business Customer Registration:

1. **Select Account Type**
   - Customer clicks "Business Customer" card

2. **Fill Registration Form**
   - Basic information
   - Optional company details
   - No POTRAZ license required

3. **Submit Registration**
   - Auto-approved (`approval_status = 'approved'`)
   - Success toast message
   - Redirected to login after 2 seconds

4. **Login**
   - Can login immediately
   - Full portal access

---

## Validation Rules

### POTRAZ License Upload:

**File Types Allowed:**
- PDF (.pdf)
- JPEG (.jpg, .jpeg)
- PNG (.png)

**File Size:**
- Maximum: 5MB
- Validation on frontend and backend

**Required:**
- Only for wholesale customers
- Form submission blocked if missing

---

## Error Handling

### Registration Errors:

**File Upload Errors:**
- Invalid file type → Toast error
- File too large → Toast error
- Missing file (wholesale) → Toast error

**API Errors:**
- Validation errors → Multiple toast messages
- Duplicate email (409) → Specific error message
- Server error (500) → Generic error message

### Login Errors:

**Approval Status Errors (403):**
- `pending` → "Your account is pending approval..." (5s toast)
- `rejected` → "Your account was rejected. Reason: ..." (6s toast)

**Other Errors:**
- Invalid credentials (401)
- Account not found (404)
- Account disabled (403)
- Too many attempts (429)

---

## UI/UX Improvements

### Visual Feedback:

1. **File Upload Area**
   - Hover effect on border
   - Upload icon and instructions
   - File size and type hints

2. **File Preview**
   - Document icon
   - File name and size
   - Remove button with hover effect
   - Light purple background

3. **Success Screen**
   - Large checkmark icon
   - Clear heading and description
   - Yellow info box with timeline
   - Gray help box with contact info
   - Action buttons (Login / Home)

### Color Coding:

- **Wholesale**: Purple theme (`bg-primary`)
- **Business**: Green theme (`bg-secondary`)
- **Success**: Green checkmark
- **Warning**: Yellow info box
- **Error**: Red toast messages

---

## Testing Checklist

### Wholesale Registration:
- [ ] Can select wholesale partner category
- [ ] All required fields validated
- [ ] POTRAZ license upload works
- [ ] File type validation works
- [ ] File size validation works
- [ ] Can remove and re-upload file
- [ ] Success message displays correctly
- [ ] Cannot login before approval
- [ ] Approval status error shows correctly

### Business Registration:
- [ ] Can select business customer category
- [ ] Optional fields work correctly
- [ ] No POTRAZ license required
- [ ] Auto-approved after registration
- [ ] Can login immediately
- [ ] Redirects to dashboard

### File Upload:
- [ ] PDF files accepted
- [ ] JPG/JPEG files accepted
- [ ] PNG files accepted
- [ ] Other file types rejected
- [ ] Files over 5MB rejected
- [ ] File preview shows correctly
- [ ] Remove file works

### Error Handling:
- [ ] Missing required fields show errors
- [ ] Invalid email format rejected
- [ ] Password mismatch detected
- [ ] Duplicate email shows error
- [ ] Network errors handled gracefully

---

## Future Enhancements

### Email Notifications:
- [ ] Send pending approval email to wholesale customer
- [ ] Send approval confirmation email
- [ ] Send rejection email with reason

### Admin Dashboard:
- [ ] View pending registrations
- [ ] Review POTRAZ license inline
- [ ] Approve/reject with notes
- [ ] View approval history

### Customer Portal:
- [ ] Show approval status in profile
- [ ] Allow re-upload of POTRAZ license
- [ ] View rejection reason
- [ ] Request re-review

### Analytics:
- [ ] Track registration conversion rates
- [ ] Monitor approval times
- [ ] Identify common rejection reasons

---

## Related Documentation

- `WHOLESALE_APPROVAL_WORKFLOW.md` - Complete backend workflow
- `REGISTRATION_ODOO_FIELD_MAPPING.md` - Field mappings to Odoo

---

## Support

For issues or questions:
- Check browser console for errors
- Review network tab for API responses
- Check Laravel logs: `afinet-portal-backend/storage/logs/laravel.log`
- Verify file upload permissions on server
