# Phase 2 Frontend - Components Ready ✅

## Summary

Phase 2 frontend components are now created and ready for integration into the registration page!

## Components Created

### 1. DocumentUploadField Component ✅
**File**: `afinet-portal/src/components/forms/document-upload-field.jsx`

**Features**:
- Drag & drop file upload
- Click to browse
- Multiple file support (configurable max)
- File validation (size, type)
- Visual file list with icons
- Remove file functionality
- Progress indicators
- Required field validation
- File size display (human-readable)
- Supported formats: PDF, JPG, JPEG, PNG, DOC, DOCX
- Max file size: 10MB

**Props**:
```javascript
<DocumentUploadField
  documentType="company_profile"
  label="Company Profile"
  description="Detailed company profile document"
  required={true}
  maxFiles={1}
  onFilesChange={(type, files) => handleDocumentChange(type, files)}
  existingFiles={[]}
/>
```

### 2. PartnerTypeTabs Component ✅
**File**: `afinet-portal/src/components/forms/partner-type-tabs.jsx`

**Features**:
- Two tab options: Local / International
- Visual selection with icons
- Descriptions for each type
- Selected state indicator
- Responsive design (stacks on mobile)
- Smooth transitions

**Props**:
```javascript
<PartnerTypeTabs
  selectedType="local"
  onTypeChange={(type) => setPartnerType(type)}
/>
```

### 3. Document Configuration ✅
**File**: `afinet-portal/src/config/wholesale-documents.js`

**Features**:
- Complete document requirements for both partner types
- Helper functions:
  - `getRequiredDocuments(partnerType)` - Get all documents for a type
  - `getDocumentConfig(partnerType, documentType)` - Get specific document config
  - `validateAllDocuments(partnerType, uploadedDocuments)` - Validate all uploads

**Usage**:
```javascript
import { 
  getRequiredDocuments, 
  validateAllDocuments 
} from '@/config/wholesale-documents';

// Get documents for local partners
const documents = getRequiredDocuments('local');

// Validate all uploads
const validation = validateAllDocuments('local', uploadedDocuments);
// Returns: { isValid, missing, total, uploaded }
```

## Document Requirements

### Local Partners (10 Documents)
1. Company Profile (1 file)
2. CR14 (1 file)
3. Certificate of Incorporation (1 file)
4. Tax Clearance (1 file)
5. Director National ID #1 (2 files - front/back)
6. Director National ID #2 (2 files - front/back)
7. Director Proof of Residence #1 (1 file)
8. Director Proof of Residence #2 (1 file)
9. ZIMRA Registration Certificate (1 file)
10. POTRAZ License (1 file)

### International Partners (7 Documents)
1. Certificate of Incorporation/Business Registration (1 file)
2. Articles of Association/Memorandum (1 file)
3. Shareholder IDs (up to 10 files)
4. List of Directors (1 file)
5. Tax Identification Number (1 file)
6. NDA Document (1 file)
7. MSA Document (1 file)

## Integration Guide

### Step 1: Update Registration Page State

Add these state variables to your registration page:

```javascript
const [wholesalePartnerType, setWholesalePartnerType] = useState('local');
const [uploadedDocuments, setUploadedDocuments] = useState({});
```

### Step 2: Add Partner Type Selection

For wholesale customers, add the partner type selector:

```javascript
{customerType === 'wholesale' && (
  <PartnerTypeTabs
    selectedType={wholesalePartnerType}
    onTypeChange={setWholesalePartnerType}
  />
)}
```

### Step 3: Add Document Upload Fields

Render document fields based on partner type:

```javascript
import { getRequiredDocuments } from '@/config/wholesale-documents';

{customerType === 'wholesale' && (
  <div className="space-y-4">
    <h3 className="text-lg font-semibold text-gray-900">
      Required Documents
    </h3>
    
    {getRequiredDocuments(wholesalePartnerType).map((doc) => (
      <DocumentUploadField
        key={doc.type}
        documentType={doc.type}
        label={doc.label}
        description={doc.description}
        required={doc.required}
        maxFiles={doc.maxFiles}
        onFilesChange={handleDocumentChange}
        existingFiles={uploadedDocuments[doc.type] || []}
      />
    ))}
  </div>
)}
```

### Step 4: Handle Document Changes

```javascript
const handleDocumentChange = (documentType, files) => {
  setUploadedDocuments(prev => ({
    ...prev,
    [documentType]: files
  }));
};
```

### Step 5: Validate Before Submit

```javascript
import { validateAllDocuments } from '@/config/wholesale-documents';

const onSubmit = async (data) => {
  // Validate documents for wholesale customers
  if (customerType === 'wholesale') {
    const validation = validateAllDocuments(wholesalePartnerType, uploadedDocuments);
    
    if (!validation.isValid) {
      toast.error(`Please upload all required documents. Missing: ${validation.missing.length}`);
      return;
    }
  }
  
  // ... rest of submit logic
};
```

### Step 6: Prepare FormData for Submission

```javascript
const formData = new FormData();

// Add all form fields
Object.keys(data).forEach(key => {
  if (data[key]) {
    formData.append(key, data[key]);
  }
});

// Add customer type and partner type
formData.append('type', customerType);
if (customerType === 'wholesale') {
  formData.append('wholesale_partner_type', wholesalePartnerType);
  
  // Add all documents
  Object.keys(uploadedDocuments).forEach(docType => {
    const files = uploadedDocuments[docType];
    files.forEach((file, index) => {
      formData.append(`document_${docType}`, file);
    });
  });
}

// Submit
await registerUser(formData, true);
```

## Visual Flow

```
┌─────────────────────────────────────────┐
│  WHOLESALE PARTNER REGISTRATION         │
├─────────────────────────────────────────┤
│                                         │
│  ┌──────────────┐  ┌────────────────┐ │
│  │   LOCAL      │  │ INTERNATIONAL  │ │
│  │  (Selected)  │  │                │ │
│  └──────────────┘  └────────────────┘ │
│                                         │
│  Company Information                    │
│  ├─ Company Name    [____________]     │
│  ├─ Email           [____________]     │
│  └─ Phone           [____________]     │
│                                         │
│  Required Documents (10)                │
│  ├─ Company Profile                    │
│  │   ┌─────────────────────────────┐  │
│  │   │ 📄 Drag & drop or click     │  │
│  │   │    to upload                │  │
│  │   └─────────────────────────────┘  │
│  │   ✓ company_profile.pdf (2.3 MB)  │
│  │                                     │
│  ├─ CR14                               │
│  │   ┌─────────────────────────────┐  │
│  │   │ 📄 Drag & drop or click     │  │
│  │   └─────────────────────────────┘  │
│  │                                     │
│  └─ ... (8 more documents)             │
│                                         │
│  [Submit Registration]                  │
└─────────────────────────────────────────┘
```

## Styling

All components use Tailwind CSS and match your existing design system:
- Primary color: `#4A5633` (dark green)
- Consistent spacing and typography
- Responsive design
- Smooth transitions
- Accessible (keyboard navigation, ARIA labels)

## File Validation

### Client-Side:
- File type: PDF, JPG, JPEG, PNG, DOC, DOCX
- Max size: 10MB per file
- Max files per document type (configurable)
- Real-time validation with toast notifications

### Server-Side:
- Backend validates again (never trust client)
- Stores in `storage/app/public/customer_documents/{customer_id}/`
- Uploads to Odoo as attachments
- Logs all operations

## Next Steps

### To Complete Integration:

1. **Update Registration Page** (`afinet-portal/src/app/(auth)/register/page.js`):
   - Import new components
   - Add partner type state
   - Add document upload state
   - Render components conditionally
   - Update form submission

2. **Test Flow**:
   - Select wholesale account type
   - Choose local/international
   - Upload all required documents
   - Validate before submit
   - Submit and verify backend receives files

3. **Error Handling**:
   - Show validation errors
   - Handle upload failures
   - Display missing documents
   - Retry mechanism

4. **Success State**:
   - Show upload progress
   - Confirmation message
   - List uploaded documents
   - Pending approval notice

## API Integration

The components are ready to work with your backend API:

```javascript
// Backend expects FormData with:
POST /api/auth/register

Fields:
- type: "wholesale"
- wholesale_partner_type: "local" or "international"
- ... (other registration fields)

Files:
- document_company_profile: File
- document_cr14: File
- document_certificate_of_incorporation: File
- ... (all other documents)
```

## Testing Checklist

- [ ] Partner type tabs switch correctly
- [ ] Document fields render based on partner type
- [ ] File upload works (drag & drop)
- [ ] File upload works (click to browse)
- [ ] Multiple files upload (for fields that allow it)
- [ ] File validation works (size, type)
- [ ] Remove file works
- [ ] Required field validation works
- [ ] Form submission includes all files
- [ ] Backend receives files correctly
- [ ] Documents uploaded to Odoo
- [ ] Email sent with attachments

## Support

All components are self-contained and documented. They follow React best practices and are fully typed with PropTypes (can add TypeScript if needed).

---

**Status**: ✅ Components Ready - Integration Needed
**Next**: Update registration page to use these components
**Estimated Time**: 30-45 minutes for integration
