# ERP Integration Guide for ATS

## Table of Contents
1. [Introduction](#introduction)
2. [Setup and Configuration](#setup-and-configuration)
3. [API Documentation](#api-documentation)
4. [Creating Job Postings](#creating-job-postings)
5. [Updating Job Postings](#updating-job-postings)
6. [Monitoring and Troubleshooting](#monitoring-and-troubleshooting)
7. [Best Practices](#best-practices)
8. [Appendix](#appendix)

## Introduction

This guide explains how to integrate your ERP system with the Applicant Tracking System (ATS) for seamless job posting management. The integration allows you to automatically create and update job postings in the ATS directly from your ERP system.

### Benefits
- **Automated Job Management**: Create and update job postings without manual data entry
- **Data Consistency**: Ensure job information is synchronized across systems
- **Audit Trail**: Complete logging of all integration activities
- **Security**: Secure API-based communication with authentication

### System Requirements
- ERP system with HTTP request capabilities
- HTTPS support (required for production)
- JSON data format support
- Access to ATS base URL (e.g., https://your-ats-domain.com/recruitment/)

## Setup and Configuration

### 1. Configure Source in ATS Admin

1. Log in to the ATS Django admin interface
2. Navigate to **Recruitment > Sources**
3. Click **Add Source** to create a new integration source
4. Fill in the following information:

#### Basic Information
- **Name**: Unique identifier for your ERP system (e.g., "Main_ERP")
- **Source Type**: "ERP"
- **Description**: Brief description of the integration

#### Technical Details
- **IP Address**: Your ERP system's IP address (for logging)
- **API Key**: Generate a secure API key for authentication
- **API Secret**: Generate a secure API secret for authentication
- **Trusted IPs**: Comma-separated list of IP addresses allowed to make requests (e.g., "192.168.1.100,10.0.0.50")

#### Integration Status
- **Is Active**: Enable the integration
- **Integration Version**: Your ERP integration version (e.g., "1.0")
- **Sync Status**: Set to "IDLE" initially

5. Save the source configuration

### 2. Test the Connection

Use the health check endpoint to verify connectivity:

```bash
curl -X GET https://your-ats-domain.com/recruitment/integration/erp/health/
```

Expected response:
```json
{
  "status": "healthy",
  "timestamp": "2025-10-06T14:30:00Z",
  "services": {
    "erp_integration": "available",
    "database": "connected"
  }
}
```

## API Documentation

### Base URL
```
https://your-ats-domain.com/recruitment/integration/erp/
```

### Authentication

Include your API key in either of these ways:
- **Header**: `X-API-Key: your_api_key_here`
- **Query Parameter**: `?api_key=your_api_key_here`

### Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/` | GET | Health check and API info |
| `/create-job/` | POST | Create a new job posting |
| `/update-job/` | POST | Update an existing job posting |
| `/health/` | GET | Health check |

### Response Format

All responses follow this structure:

```json
{
  "status": "success" | "error",
  "message": "Human-readable message",
  "data": { ... },  // Present for successful requests
  "processing_time": 0.45  // In seconds
}
```

## Creating Job Postings

### Step-by-Step Guide

1. Prepare your job data in JSON format
2. Send a POST request to `/create-job/`
3. Verify the response and check for errors
4. Monitor the integration logs for confirmation

### Request Format

```json
{
  "action": "create_job",
  "source_name": "Main_ERP",
  "title": "Senior Software Engineer",
  "department": "Information Technology",
  "job_type": "full-time",
  "workplace_type": "hybrid",
  "location_city": "Riyadh",
  "location_state": "Riyadh",
  "location_country": "Saudi Arabia",
  "description": "We are looking for an experienced software engineer...",
  "qualifications": "Bachelor's degree in Computer Science...",
  "salary_range": "SAR 18,000 - 25,000",
  "benefits": "Health insurance, Annual leave...",
  "application_url": "https://careers.yourcompany.com/job/12345",
  "application_deadline": "2025-12-31",
  "application_instructions": "Submit your resume and cover letter...",
  "auto_publish": true
}
```

### Required Fields

| Field | Type | Description |
|-------|------|-------------|
| `action` | String | Must be "create_job" |
| `source_name` | String | Name of the configured source |
| `title` | String | Job title |
| `application_url` | String | URL where candidates apply |

### Optional Fields

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `department` | String | - | Department/Division |
| `job_type` | String | "FULL_TIME" | FULL_TIME, PART_TIME, CONTRACT, INTERNSHIP, FACULTY, TEMPORARY |
| `workplace_type` | String | "ON_SITE" | ON_SITE, REMOTE, HYBRID |
| `location_city` | String | - | City |
| `location_state` | String | - | State/Province |
| `location_country` | String | "United States" | Country |
| `description` | String | - | Job description |
| `qualifications` | String | - | Required qualifications |
| `salary_range` | String | - | Salary information |
| `benefits` | String | - | Benefits offered |
| `application_deadline` | String | - | Application deadline (YYYY-MM-DD) |
| `application_instructions` | String | - | Special instructions for applicants |
| `auto_publish` | Boolean | false | Automatically publish the job |

### Example Request

```bash
curl -X POST https://your-ats-domain.com/recruitment/integration/erp/create-job/ \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{
    "action": "create_job",
    "source_name": "Main_ERP",
    "title": "Senior Software Engineer",
    "department": "Information Technology",
    "job_type": "full-time",
    "workplace_type": "hybrid",
    "location_city": "Riyadh",
    "location_country": "Saudi Arabia",
    "description": "We are looking for an experienced software engineer...",
    "application_url": "https://careers.yourcompany.com/job/12345",
    "auto_publish": true
  }'
```

### Example Response

```json
{
  "status": "success",
  "message": "Job created successfully",
  "data": {
    "job_id": "KAAUH-2025-0001",
    "title": "Senior Software Engineer",
    "status": "PUBLISHED",
    "created_at": "2025-10-06T14:30:00Z"
  },
  "processing_time": 0.32
}
```

## Updating Job Postings

### Step-by-Step Guide

1. Obtain the internal job ID from the ATS (from creation response or job listing)
2. Prepare your update data in JSON format
3. Send a POST request to `/update-job/`
4. Verify the response and check for errors

### Request Format

```json
{
  "action": "update_job",
  "source_name": "Main_ERP",
  "job_id": "KAAUH-2025-0001",
  "title": "Senior Software Engineer (Updated)",
  "department": "Information Technology",
  "salary_range": "SAR 20,000 - 28,000",
  "status": "PUBLISHED"
}
```

### Required Fields

| Field | Type | Description |
|-------|------|-------------|
| `action` | String | Must be "update_job" |
| `source_name` | String | Name of the configured source |
| `job_id` | String | Internal job ID from ATS |

### Optional Fields

All fields from the create job are available for update, except:
- `auto_publish` (not applicable for updates)

### Example Request

```bash
curl -X POST https://your-ats-domain.com/recruitment/integration/erp/update-job/ \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{
    "action": "update_job",
    "source_name": "Main_ERP",
    "job_id": "KAAUH-2025-0001",
    "salary_range": "SAR 20,000 - 28,000",
    "application_deadline": "2026-01-15"
  }'
```

### Example Response

```json
{
  "status": "success",
  "message": "Job updated successfully",
  "data": {
    "job_id": "KAAUH-2025-0001",
    "title": "Senior Software Engineer",
    "status": "PUBLISHED",
    "updated_at": "2025-10-06T14:35:00Z"
  },
  "processing_time": 0.28
}
```

## Monitoring and Troubleshooting

### Viewing Integration Logs

1. Log in to the ATS Django admin interface
2. Navigate to **Recruitment > Integration Logs**
3. Use the following filters to monitor activity:
   - **Source**: Filter by your ERP system
   - **Action**: Filter by REQUEST/RESPONSE/ERROR
   - **Status Code**: Filter by HTTP status codes
   - **Date Range**: View logs for specific time periods

### Common Error Codes

| Status Code | Description | Solution |
|-------------|-------------|----------|
| 400 Bad Request | Invalid request data | Check required fields and data types |
| 401 Unauthorized | Invalid API key | Verify API key is correct and active |
| 403 Forbidden | IP not trusted | Add your ERP IP to trusted IPs list |
| 404 Not Found | Source not found | Verify source name or ID is correct |
| 409 Conflict | Job already exists | Check if job with same title already exists |
| 500 Internal Error | Server error | Contact ATS support |

### Health Check

Regularly test the connection:

```bash
curl -X GET https://your-ats-domain.com/recruitment/integration/erp/health/
```

### Performance Monitoring

Monitor response times and processing durations in the integration logs. If processing times exceed 2 seconds, investigate performance issues.

### Troubleshooting Steps

1. **Check Authentication**
   - Verify API key is correct
   - Ensure source is active

2. **Check IP Whitelisting**
   - Verify your ERP IP is in the trusted list

3. **Validate Request Data**
   - Check required fields are present
   - Verify data types are correct
   - Ensure URLs are valid

4. **Check Logs**
   - View integration logs for error details
   - Check request/response data in logs

5. **Test with Minimal Data**
   - Send a request with only required fields
   - Gradually add optional fields

## Best Practices

### Security
- Use HTTPS for all requests
- Rotate API keys regularly
- Store API keys securely in your ERP system
- Limit trusted IPs to only necessary systems

### Data Validation
- Validate all data before sending
- Use consistent date formats (YYYY-MM-DD)
- Sanitize special characters in text fields
- Test with sample data before production

### Error Handling
- Implement retry logic for transient errors
- Log all integration attempts locally
- Set up alerts for frequent failures
- Have a manual fallback process

### Maintenance
- Regularly review integration logs
- Monitor API performance metrics
- Keep API keys and credentials updated
- Schedule regular health checks

### Performance
- Batch multiple job operations when possible
- Avoid sending unnecessary data
- Use compression for large requests
- Monitor response times

## Appendix

### Complete Field Reference

#### Job Types
- `FULL_TIME`: Full-time position
- `PART_TIME`: Part-time position
- `CONTRACT`: Contract position
- `INTERNSHIP`: Internship position
- `FACULTY`: Faculty/academic position
- `TEMPORARY`: Temporary position

#### Workplace Types
- `ON_SITE`: On-site work
- `REMOTE`: Remote work
- `HYBRID`: Hybrid (combination of on-site and remote)

#### Status Values
- `DRAFT`: Job is in draft status
- `PUBLISHED`: Job is published and active
- `CLOSED`: Job is closed to applications
- `ARCHIVED`: Job is archived

### Error Code Dictionary

| Code | Error | Description |
|------|-------|-------------|
| `MISSING_FIELD` | Required field is missing | Check all required fields are provided |
| `INVALID_TYPE` | Invalid data type | Verify field data types match requirements |
| `INVALID_URL` | Invalid application URL | Ensure URL is properly formatted |
| `JOB_EXISTS` | Job already exists | Use update action instead of create |
| `INVALID_SOURCE` | Source not found | Verify source name or ID |
| `IP_NOT_ALLOWED` | IP not trusted | Add IP to trusted list |

### Sample Scripts

#### Python Example

```python
import requests
import json

# Configuration
ATS_BASE_URL = "https://your-ats-domain.com/recruitment/integration/erp/"
API_KEY = "your_api_key_here"
SOURCE_NAME = "Main_ERP"

# Create job
def create_job(job_data):
    url = f"{ATS_BASE_URL}create-job/"
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": API_KEY
    }

    payload = {
        "action": "create_job",
        "source_name": SOURCE_NAME,
        **job_data
    }

    response = requests.post(url, headers=headers, json=payload)
    return response.json()

# Update job
def update_job(job_id, update_data):
    url = f"{ATS_BASE_URL}update-job/"
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": API_KEY
    }

    payload = {
        "action": "update_job",
        "source_name": SOURCE_NAME,
        "job_id": job_id,
        **update_data
    }

    response = requests.post(url, headers=headers, json=payload)
    return response.json()

# Example usage
job_data = {
    "title": "Software Engineer",
    "department": "IT",
    "application_url": "https://careers.example.com/job/123"
}

result = create_job(job_data)
print(json.dumps(result, indent=2))
```

### Contact Information

For technical support:
- **Email**: support@ats-domain.com
- **Phone**: +966 50 123 4567
- **Support Hours**: Sunday - Thursday, 8:00 AM - 4:00 PM (GMT+3)

---

*Last Updated: October 6, 2025*
*Version: 1.0*
