# Agent Login with Company Registration Status Check

This document explains the company registration status validation during agent login flow.

## Overview

When an agent attempts to login (via OTP), the system now automatically checks if the agent's company registration status is active. If the company registration is inactive, the agent will not be able to:
1. Generate an OTP
2. Complete the login process (OTP verification)

## Flow Diagram

```
Agent Enters Mobile Number
    ↓
System checks: Is agent active?
    ↓ (Yes)
System checks: Does agent belong to a company?
    ↓ (Yes)
System checks: Does company have a registration ID?
    ↓ (Yes)
System checks: Is registration status active?
    ↓ (Yes)
Generate OTP and send to agent
    ↓
Agent enters OTP
    ↓
System verifies OTP
    ↓
System checks registration status again
    ↓ (Active)
Login successful
```

## Implementation Details

### 1. OTP Generation Stage (POST /?generate_otp)

Before generating an OTP, the system checks:
- Agent account status is "active"
- Agent's company exists
- Company has a valid registration ID (reg_id)
- Registration status is "active"

**Error Response (Company Registration Inactive):**
```json
{
  "status": "error",
  "message": "Your company registration is not active. Please contact administrator.",
  "registration_status": "inactive"
}
```

### 2. OTP Verification Stage (POST /?verify_otp)

After verifying the OTP code, before completing login, the system checks:
- Agent account status is still "active"
- Agent's company exists
- Company has a valid registration ID (reg_id)
- Registration status is still "active"

**Error Response (Company Registration Inactive):**
```json
{
  "status": "error",
  "message": "Company registration is not active. Please contact administrator.",
  "registration_status": "inactive"
}
```

## Testing Scenarios

### Scenario 1: Login with Active Company Registration

**Step 1: Generate OTP**
```bash
curl -X POST 'https://dayloanapp.xesstechlink.com/?generate_otp' \
  -H 'content-type: application/json' \
  -d '{
    "mobile_no": "9123456789"
  }'
```

**Expected Response:**
```json
{
  "status": "success",
  "message": "OTP generated successfully",
  "otp": "123456",
  "expires_in": 300,
  "user_type": "agent"
}
```

**Step 2: Verify OTP**
```bash
curl -X POST 'https://dayloanapp.xesstechlink.com/?verify_otp' \
  -H 'content-type: application/json' \
  -d '{
    "mobile_no": "9123456789",
    "otp": "123456",
    "device_id": "device_123_xyz"
  }'
```

**Expected Response:**
```json
{
  "status": "success",
  "message": "Login successful",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "jwt_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "auth_token": "abc123...",
  "token_expires": "2024-01-16T10:30:00.000Z",
  "user_type": "agent",
  "agent": {
    "id": 5,
    "name": "Rajesh Kumar",
    "mobile_no": "9123456789",
    "status": "active",
    "com_id": 1,
    ...
  }
}
```

---

### Scenario 2: Login Attempt with Inactive Company Registration

**Step 1: Generate OTP (WILL FAIL)**
```bash
curl -X POST 'https://dayloanapp.xesstechlink.com/?generate_otp' \
  -H 'content-type: application/json' \
  -d '{
    "mobile_no": "9123456789"
  }'
```

**Expected Response (403 Forbidden):**
```json
{
  "status": "error",
  "message": "Your company registration is not active. Please contact administrator.",
  "registration_status": "inactive"
}
```

The agent will NOT receive an OTP and cannot proceed with login.

---

### Scenario 3: Company Registration Deactivated During Login Process

If an admin deactivates the company registration between OTP generation and verification:

**Step 1: Generate OTP (SUCCESS - Registration was active)**
```bash
curl -X POST 'https://dayloanapp.xesstechlink.com/?generate_otp' \
  -H 'content-type: application/json' \
  -d '{
    "mobile_no": "9123456789"
  }'
```

**Response:**
```json
{
  "status": "success",
  "message": "OTP generated successfully",
  "otp": "123456",
  "expires_in": 300,
  "user_type": "agent"
}
```

**[Admin deactivates company registration here]**

**Step 2: Verify OTP (WILL FAIL - Registration now inactive)**
```bash
curl -X POST 'https://dayloanapp.xesstechlink.com/?verify_otp' \
  -H 'content-type: application/json' \
  -d '{
    "mobile_no": "9123456789",
    "otp": "123456",
    "device_id": "device_123_xyz"
  }'
```

**Expected Response (403 Forbidden):**
```json
{
  "status": "error",
  "message": "Company registration is not active. Please contact administrator.",
  "registration_status": "inactive"
}
```

---

## Error Messages

| Error Message | When It Occurs | Status Code |
|--------------|----------------|-------------|
| "Your account is not active. Please contact administrator." | Agent's personal account status is not active | 403 |
| "Your company registration is not active. Please contact administrator." | Company registration is inactive during OTP generation | 403 |
| "Company registration is not active. Please contact administrator." | Company registration is inactive during OTP verification | 403 |
| "Company not found. Please contact administrator." | Agent's company record doesn't exist | 403 |
| "Company registration not found. Please contact administrator." | Company's registration record doesn't exist | 403 |

---

## Admin Actions to Resolve

If agents are blocked due to inactive company registration, admins need to:

### Check Company Registration Status
```bash
curl -X GET 'https://dayloanapp.xesstechlink.com/admin/company/registration' \
  -H 'authorization: Bearer ADMIN_JWT_TOKEN' \
  -H 'content-type: application/json'
```

### Activate Company Registration
```bash
curl -X PUT 'https://dayloanapp.xesstechlink.com/admin/registration/1/status' \
  -H 'authorization: Bearer ADMIN_JWT_TOKEN' \
  -H 'content-type: application/json' \
  -d '{
    "status": "active"
  }'
```

Or using POST:
```bash
curl -X POST 'https://dayloanapp.xesstechlink.com/admin/registration/update-status' \
  -H 'authorization: Bearer ADMIN_JWT_TOKEN' \
  -H 'content-type: application/json' \
  -d '{
    "registration_id": 1,
    "status": "active"
  }'
```

---

## Database Schema

### registration table
```sql
CREATE TABLE `registration` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `com_name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `mob_num` varchar(20) DEFAULT NULL,
  `status` varchar(20) DEFAULT 'active',
  PRIMARY KEY (`id`)
);
```

### company table
```sql
CREATE TABLE `company` (
  `com_id` int(11) NOT NULL AUTO_INCREMENT,
  `reg_id` int(11) DEFAULT NULL,
  `com_name` varchar(255) NOT NULL,
  ...
  PRIMARY KEY (`com_id`),
  FOREIGN KEY (`reg_id`) REFERENCES `registration` (`id`)
);
```

### collection_agent table
```sql
CREATE TABLE `collection_agent` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `com_id` int(11) DEFAULT NULL,
  `mobile_no` varchar(15) NOT NULL,
  `status` enum('active','inactive') DEFAULT 'active',
  ...
  PRIMARY KEY (`id`)
);
```

---

## Security Benefits

1. **Centralized Control**: Admins can disable access for all agents of a company by deactivating the registration
2. **Compliance**: Ensure only licensed/registered companies can operate
3. **Subscription Management**: Integrate with payment/subscription systems to auto-disable expired registrations
4. **Data Integrity**: Prevent operations by agents of suspended companies

---

## Mobile App Integration Recommendations

### 1. Handle Error Gracefully
```javascript
async function agentLogin(mobileNo, otp, deviceId) {
  try {
    const response = await verifyOTP(mobileNo, otp, deviceId);
    if (response.status === 'success') {
      // Login successful
      saveToken(response.token);
      navigateToHome();
    }
  } catch (error) {
    if (error.status === 403) {
      if (error.message.includes('company registration')) {
        // Show company-specific error
        showAlert(
          'Company Inactive',
          'Your company registration is not active. Please contact your administrator.',
          'error'
        );
      } else if (error.message.includes('account is not active')) {
        // Show agent-specific error
        showAlert(
          'Account Inactive',
          'Your account is not active. Please contact your administrator.',
          'error'
        );
      }
    }
  }
}
```

### 2. Show Appropriate Support Contact
```javascript
if (error.message.includes('company registration')) {
  showSupportDialog({
    title: 'Company Registration Inactive',
    message: error.message,
    supportPhone: companyAdminPhone,
    supportEmail: companyAdminEmail
  });
}
```

---

## Related Documentation

- [AGENT_COMPANY_STATUS_API.md](./AGENT_COMPANY_STATUS_API.md) - API to check company status after login
- [ADMIN_COMPANY_REGISTRATION.md](./ADMIN_COMPANY_REGISTRATION.md) - Admin endpoints for managing registrations
- [AGENT_LOGIN_API.md](./AGENT_LOGIN_API.md) - Complete agent login documentation

---

## Notes

- The registration status check is performed at both OTP generation and verification stages for maximum security
- Registration status is case-insensitive (both "active" and "Active" are accepted)
- If a company doesn't have a registration ID (reg_id), the check is skipped (for backward compatibility)
- This check does NOT affect admin logins - only collection agents are validated

