# Application Detail API Documentation

## Overview

The Application Detail API provides a comprehensive view of individual loan applications for mobile app users. This endpoint allows users to view all details of their submitted applications including personal information, documents, status history, and more.

## API Endpoint

### Get Individual Application Details (Mobile App)

**Endpoint:** `GET /api/loan-applications/user/application/:id`

**Access:** Private (Requires authentication)

**Description:** Retrieves detailed information about a specific loan application belonging to the authenticated user.

#### Request

```http
GET /api/loan-applications/user/application/507f1f77bcf86cd799439011
Authorization: Bearer <user-token>
```

#### Response

**Success Response (200 OK):**

```json
{
  "success": true,
  "message": "Application details retrieved successfully",
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "loanType": "personal",
    "loanAmount": 500000,
    "loanPurpose": "Home renovation",
    "monthlyIncome": 75000,
    "employmentType": "salaried",
    "status": "pending",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:30:00.000Z",
    
    "personalInfo": {
      "name": "John Doe",
      "email": "john.doe@example.com",
      "phone": "9876543210",
      "aadharNumber": "123456789012",
      "panNumber": "ABCDE1234F"
    },
    
    "address": {
      "street": "123 Main Street",
      "city": "Mumbai",
      "state": "Maharashtra",
      "pincode": "400001"
    },
    
    "category": {
      "_id": "507f1f77bcf86cd799439012",
      "name": "Personal Loan",
      "description": "Quick personal loans for various purposes"
    },
    
    "documents": {
      "aadharCard": "https://your-domain.com/uploads/users/123/aadharCard-1234567890.jpg",
      "panCard": "https://your-domain.com/uploads/users/123/panCard-1234567890.jpg",
      "incomeProof": "https://your-domain.com/uploads/users/123/incomeProof-1234567890.pdf",
      "bankStatement": null,
      "addressProof": null,
      "otherDocuments": [
        "https://your-domain.com/uploads/users/123/otherDoc1-1234567890.pdf"
      ]
    },
    
    "statusHistory": [
      {
        "status": "pending",
        "comment": "Application submitted",
        "updatedBy": "John Doe",
        "updatedAt": "2025-01-15T10:30:00.000Z"
      }
    ],
    
    "assignedTo": {
      "_id": "507f1f77bcf86cd799439013",
      "name": "Loan Officer",
      "email": "officer@chittifinserv.com",
      "phone": "9876543211"
    },
    
    "additionalInfo": {
      "isActive": true,
      "isVerified": false,
      "verificationDate": null,
      "approvalDate": null,
      "disbursementDate": null
    }
  }
}
```

**Error Responses:**

**404 Not Found:**
```json
{
  "success": false,
  "message": "Application not found"
}
```

**403 Forbidden:**
```json
{
  "success": false,
  "message": "Access denied. This application does not belong to you."
}
```

**401 Unauthorized:**
```json
{
  "success": false,
  "message": "Authentication failed. Please login again."
}
```

**500 Internal Server Error:**
```json
{
  "success": false,
  "message": "Server error",
  "error": "Error details"
}
```

## Data Structure

### Application Detail Model

| Field | Type | Description |
|-------|------|-------------|
| `_id` | String | Application ID |
| `loanType` | String | Type of loan (personal, business, home, car, etc.) |
| `loanAmount` | Number | Requested loan amount |
| `loanPurpose` | String | Purpose of the loan |
| `monthlyIncome` | Number | Monthly income of the applicant |
| `employmentType` | String | Employment type (salaried, self-employed, business, etc.) |
| `status` | String | Current application status |
| `createdAt` | DateTime | Application creation date |
| `updatedAt` | DateTime | Last update date |

### Personal Information

| Field | Type | Description |
|-------|------|-------------|
| `name` | String | Applicant's full name |
| `email` | String | Applicant's email address |
| `phone` | String | Applicant's phone number |
| `aadharNumber` | String | Aadhar card number (optional) |
| `panNumber` | String | PAN card number (optional) |

### Address Information

| Field | Type | Description |
|-------|------|-------------|
| `street` | String | Street address |
| `city` | String | City name |
| `state` | String | State name |
| `pincode` | String | PIN code |

### Category Information

| Field | Type | Description |
|-------|------|-------------|
| `_id` | String | Category ID |
| `name` | String | Category name |
| `description` | String | Category description (optional) |

### Documents

| Field | Type | Description |
|-------|------|-------------|
| `aadharCard` | String | Aadhar card document URL (optional) |
| `panCard` | String | PAN card document URL (optional) |
| `incomeProof` | String | Income proof document URL (optional) |
| `bankStatement` | String | Bank statement document URL (optional) |
| `addressProof` | String | Address proof document URL (optional) |
| `otherDocuments` | Array | Array of other document URLs |

### Status History

| Field | Type | Description |
|-------|------|-------------|
| `status` | String | Status value |
| `comment` | String | Status update comment |
| `updatedBy` | String | Name of person who updated the status |
| `updatedAt` | DateTime | Status update timestamp |

### Assigned To

| Field | Type | Description |
|-------|------|-------------|
| `_id` | String | Assigned person's ID |
| `name` | String | Assigned person's name |
| `email` | String | Assigned person's email |
| `phone` | String | Assigned person's phone |

### Additional Information

| Field | Type | Description |
|-------|------|-------------|
| `isActive` | Boolean | Whether the application is active |
| `isVerified` | Boolean | Whether the application is verified |
| `verificationDate` | DateTime | Verification date (optional) |
| `approvalDate` | DateTime | Approval date (optional) |
| `disbursementDate` | DateTime | Disbursement date (optional) |

## Security Features

1. **Authentication Required**: All requests must include a valid JWT token
2. **User Authorization**: Users can only view their own applications
3. **Input Validation**: Application ID is validated for format and existence
4. **Error Handling**: Comprehensive error handling with appropriate HTTP status codes

## Mobile App Integration

### Flutter Implementation

```dart
// Fetch application details
final response = await repository.getApplicationById(applicationId);
final applicationDetail = ApplicationDetailModel.fromJson(response['data']);

// Navigate to detail screen
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => ApplicationDetailScreen(
      applicationId: applicationId,
    ),
  ),
);
```

### Features Available in Mobile App

1. **Complete Application View**: All submitted information
2. **Document Viewer**: View uploaded documents with external browser
3. **Status Timeline**: Visual representation of application progress
4. **Contact Information**: Assigned loan officer details
5. **Real-time Updates**: Refresh functionality for latest status

## Error Handling

### Common Error Scenarios

1. **Application Not Found**: 404 error when application ID doesn't exist
2. **Access Denied**: 403 error when user tries to access another user's application
3. **Authentication Failed**: 401 error when token is invalid or expired
4. **Server Error**: 500 error for internal server issues

### Error Recovery

- **Retry Mechanism**: Mobile app provides retry button for failed requests
- **User Feedback**: Clear error messages for different scenarios
- **Graceful Degradation**: App continues to function even if detail view fails

## Performance Considerations

1. **Efficient Queries**: Optimized database queries with proper indexing
2. **Response Caching**: Mobile app can cache responses for offline viewing
3. **Lazy Loading**: Documents are loaded on-demand
4. **Compression**: API responses are compressed for faster transmission

## Future Enhancements

1. **Real-time Updates**: WebSocket integration for live status updates
2. **Document Preview**: In-app document viewing without external browser
3. **Push Notifications**: Status change notifications
4. **Offline Support**: Cached application details for offline viewing
5. **Analytics**: Track user engagement with application details

## Testing

### API Testing

```bash
# Test with valid application ID
curl -X GET "http://localhost:5000/api/loan-applications/user/application/507f1f77bcf86cd799439011" \
  -H "Authorization: Bearer <user-token>"

# Test with invalid application ID
curl -X GET "http://localhost:5000/api/loan-applications/user/application/invalid-id" \
  -H "Authorization: Bearer <user-token>"

# Test without authentication
curl -X GET "http://localhost:5000/api/loan-applications/user/application/507f1f77bcf86cd799439011"
```

### Mobile App Testing

1. **Valid Application**: Test with existing application ID
2. **Invalid Application**: Test with non-existent application ID
3. **Network Issues**: Test with poor network connectivity
4. **Authentication**: Test with expired/invalid tokens
5. **Document Viewing**: Test document URL opening functionality

## Support

For technical support or questions about this API:

- **Email**: support@chittifinserv.com
- **Documentation**: Check the main API documentation
- **Issues**: Report bugs through the development team 