# Signup Validation Rules

This document outlines the validation rules and requirements for the multi-step signup process in the Assist Solutions Portal.

## Overview

The signup process has been redesigned as a multi-step form to improve user experience and add comprehensive validation checks before account creation.

## Step 1: Customer Number Validation

### Validation Rules

1. **SF Number Format**: Must be a valid customer number format
2. **ID Mapping Check**: Verify the SF number is not already mapped to an existing user
3. **Salesforce Account Existence**: Confirm the SF number exists in Salesforce

### Implementation Details

- **Frontend**: Real-time validation as user types
- **Backend**: Comprehensive check before proceeding to next step
- **Error Handling**: Clear error messages for each validation failure

## Step 2: Salesforce Account Validation

### WH Account Field Check

The system must verify that the `WH_Account__c` field in the Salesforce Account object is **blank/null**.

#### Requirements

- **Field Name**: `WH_Account__c` (custom field on Account object)
- **Validation**: Must be empty/null for new account creation
- **Purpose**: Prevents duplicate account creation for existing WHMCS customers

#### Field Details

- **Field Type**: Text Area (255 characters)
- **Field API Name**: `WH_Account__c`
- **Purpose**: Stores WHMCS client information in format "#{clientId} - {clientName}"

#### Business Logic

- **If WH_Account\_\_c is empty/null**: Proceed with new account creation
- **If WH_Account\_\_c is not empty**: User already has an account, redirect to login page
- **Error Message**: "You already have an account. Please use the login page to access your existing account."
- **After successful signup**: Populate WH_Account\_\_c with "#{whmcsClientId} - {firstName} {lastName}"

#### Example Values

- Empty: `null` or `""`
- Populated: `"#9883 - Temuulen Ankhbayar"`

## Step 3: Personal Information

### Required Fields

- First Name
- Last Name
- Email Address
- Email Confirmation
- Password
- Password Confirmation

### Validation Rules

- **Email**: Valid format with confirmation matching
- **Password**: Minimum 8 characters with uppercase, lowercase, number, and special character
- **Names**: Non-empty strings

## Step 3: Contact & Address Information

### Required Fields (WHMCS Billing Requirements)

- **Phone Number** (required) - Must be provided for billing account
- **Address Line 1** (required) - Street address for billing
- **City** (required) - City for billing address
- **State/Prefecture** (required) - State or prefecture for billing
- **Postal Code** (required) - Postal/ZIP code for billing
- **Country** (required) - Must be valid ISO 2-letter country code

### Optional Fields

- **Company** (optional) - Business name if applicable
- **Address Line 2** (optional) - Apartment, suite, etc.
- **Nationality** (optional) - User's nationality
- **Date of Birth** (optional) - User's birth date
- **Gender** (optional) - Male, Female, or Other

### Validation Rules

- **Phone**: Must be non-empty string (international format recommended)
- **Address Fields**: All required address fields must be non-empty
- **Country**: Must be valid ISO 2-letter country code (e.g., "JP" for Japan, "US" for United States)
- **Country Selection**: Dropdown with common countries and their ISO codes
- **Postal Code**: Must be non-empty (format varies by country)

## Technical Implementation

### Backend Validation Flow

1. **Step 1 Validation**:

   ```typescript
   // Check ID mapping for existing SF number
   const existingMapping = await mappingsService.findBySfNumber(sfNumber);
   if (existingMapping) {
     throw new BadRequestException("Customer number already registered");
   }

   // Check Salesforce account exists
   const sfAccount = await salesforceService.findAccountByCustomerNumber(sfNumber);
   if (!sfAccount) {
     throw new BadRequestException("Customer number not found in Salesforce");
   }
   ```

2. **Step 2 Validation**:

   ```typescript
   // Check WH Account field is empty
   const accountDetails = await salesforceService.getAccountDetails(sfAccount.id);
   if (accountDetails.WH_Account__c && accountDetails.WH_Account__c.trim() !== "") {
     throw new BadRequestException(
       "You already have an account. Please use the login page to access your existing account."
     );
   }
   ```

3. **Step 3 Validation (WHMCS Requirements)**:

   ```typescript
   // Validate required WHMCS fields before account creation
   if (
     !address?.line1 ||
     !address?.city ||
     !address?.state ||
     !address?.postalCode ||
     !address?.country
   ) {
     throw new BadRequestException(
       "Complete address information is required for billing account creation"
     );
   }

   if (!phone) {
     throw new BadRequestException("Phone number is required for billing account creation");
   }

   // Country must be valid ISO 2-letter code
   if (!/^[A-Z]{2}$/.test(address.country)) {
     throw new BadRequestException("Country must be a valid ISO 2-letter code");
   }
   ```

### Frontend Multi-Step Form

- **Step 1**: Customer Number input with real-time validation and SF/WHMCS checks
- **Step 2**: Personal information form (name, email, password)
- **Step 3**: Contact and address information with WHMCS billing requirements

### Error Handling

- **Step-specific errors**: Clear messages for each validation step
- **Progressive disclosure**: Show only relevant fields for current step
- **Back navigation**: Allow users to go back and modify previous steps
- **WHMCS Integration Errors**: Specific error messages for billing account creation failures
- **Country Validation**: Clear feedback for invalid country selection
- **Required Field Validation**: Real-time validation for all required WHMCS fields

## Security Considerations

### Rate Limiting

- **Step 1**: 10 attempts per 15 minutes per IP
- **Step 2**: 5 attempts per 15 minutes per IP
- **Overall**: 3 complete signups per 15 minutes per IP

### Audit Logging

- Log all validation attempts (successful and failed)
- Track which step failed for analytics
- Record IP addresses and timestamps

## Future Enhancements

### Potential Improvements

1. **Email Verification**: Send verification email before account activation
2. **Phone Verification**: SMS verification for phone numbers
3. **Address Validation**: Integration with address validation services
4. **Document Upload**: Allow users to upload supporting documents
5. **Progress Saving**: Save partial progress for returning users

### Integration Points

1. **Salesforce**: Real-time account validation
2. **WHMCS**: Check for existing client records
3. **Email Service**: Welcome emails and verification
4. **Audit System**: Comprehensive logging of all actions

## WHMCS Integration Requirements

### Required WHMCS Fields

The following fields are **required** by WHMCS for client creation, despite being marked as "optional" in some interfaces:

#### Mandatory Fields

- **firstname** (First Name) - Required
- **lastname** (Last Name) - Required
- **email** (Email Address) - Required
- **phonenumber** (Phone Number) - Required for billing
- **address1** (Address Line 1) - Required for billing
- **city** (City) - Required for billing
- **state** (State/Prefecture) - Required for billing
- **postcode** (Postal Code) - Required for billing
- **country** (Country) - Required, must be valid ISO 2-letter code
- **password2** (Password) - Required for new client creation

#### Optional Fields

- **companyname** (Company) - Optional
- **address2** (Address Line 2) - Optional
- **customfields** (Custom Fields) - Optional, includes Customer Number, DOB, Gender, Nationality

### Common WHMCS Validation Errors

- **"Valid country required"** - Country must be ISO 2-letter code (e.g., "JP" not "Japan")
- **"Email address already exists"** - Email is already registered in WHMCS
- **"Invalid phone number format"** - Phone number format validation failed
- **"Address validation failed"** - Required address fields are missing or invalid

### Country Code Mapping

The system uses ISO 3166-1 alpha-2 country codes:

- **JP** = Japan
- **US** = United States
- **GB** = United Kingdom
- **CA** = Canada
- **AU** = Australia
- **DE** = Germany
- **FR** = France
- (See frontend dropdown for complete list)

## Configuration

### Environment Variables

```bash
# Salesforce Configuration
SALESFORCE_WH_ACCOUNT_FIELD=WH_Account__c
SALESFORCE_CUSTOMER_NUMBER_FIELD=SF_Account_No__c

# Validation Settings
SIGNUP_STEP1_RATE_LIMIT=10
SIGNUP_STEP2_RATE_LIMIT=5
SIGNUP_TOTAL_RATE_LIMIT=3
SIGNUP_RATE_LIMIT_WINDOW=900000  # 15 minutes in milliseconds
```

### Field Mappings

- **Customer Number**: `SF_Account_No__c` in Salesforce Account
- **WH Account**: `WH_Account__c` in Salesforce Account (Text Area 255 chars)
- **ID Mapping**: Portal User ID ↔ WHMCS Client ID ↔ Salesforce Account ID
- **Country Codes**: ISO 2-letter codes (JP=Japan, US=United States, etc.)
- **WHMCS Custom Fields**: Customer Number, DOB, Gender, Nationality (configurable IDs)

## Testing Requirements

### Unit Tests

- Validate each step independently
- Test error conditions for each validation rule
- Mock external service calls (Salesforce, WHMCS)

### Integration Tests

- End-to-end signup flow
- Cross-system data consistency
- Error handling and rollback scenarios

### User Acceptance Tests

- Multi-step form navigation
- Error message clarity
- Mobile responsiveness
- Accessibility compliance
