# Collection Agent API Test Script

This document describes how to use the test script to verify all Collection Agent API endpoints.

## Prerequisites

1. **Server Running**: Make sure your API server is running on `http://localhost:3000` (or update the `BASE_URL` in the test script)

2. **Database Setup**: Ensure your database has:
   - At least one collection agent with a valid mobile number
   - At least one loan entry with a valid loan_id
   - Line entries and area entries configured

3. **Dependencies**: All npm packages should be installed
   ```bash
   npm install
   ```

## Configuration

Before running tests, you may need to update the test configuration in `test_collection_agent_api.js`:

```javascript
const TEST_CONFIG = {
  mobile_no: '9876543210',      // Update with a valid collection agent mobile number
  test_loan_id: 'LOAN001',       // Update with a valid loan_id from your database
  test_com_id: 1                 // Update with a valid company ID
};
```

Or set environment variables:
```bash
export TEST_MOBILE_NO=9876543210
export TEST_LOAN_ID=LOAN001
export TEST_COM_ID=1
export API_URL=http://localhost:3000
```

## Running the Tests

### Option 1: Using npm script
```bash
npm test
```

### Option 2: Direct execution
```bash
node test_collection_agent_api.js
```

## Test Coverage

The test script covers the following endpoints and scenarios:

### 1. Authentication Tests
- ✅ Generate OTP
- ✅ Verify OTP and get auth token
- ✅ Check authentication status

### 2. Collection Agent Tests
- ✅ Get collection agent details
- ✅ Get collection details (based on line and area)
- ✅ Get areas by line

### 3. Loan Management Tests
- ✅ Get loan details (with pending dues count and balance)
- ✅ Error handling for invalid loan ID

### 4. Receipt Management Tests
- ✅ Insert receipt (with all required fields)
- ✅ Get today's collection history
- ✅ Error handling for missing required fields

### 5. Expense Management Tests
- ✅ Insert expense entry
- ✅ Get today's expense list

### 6. Statistics Tests
- ✅ Get collection statistics (counts and amounts)

### 7. Error Handling Tests
- ✅ Unauthenticated request handling
- ✅ Missing required fields
- ✅ Invalid loan ID

## Test Output

The test script provides detailed output for each test:

```
🧪 Testing: Generate OTP
   OTP generated for 9876543210
   OTP: 123456
✅ PASSED: Generate OTP

🧪 Testing: Verify OTP and Authenticate
   Auth token received: abc123def456...
✅ PASSED: Verify OTP and Authenticate
```

## Expected Results

A successful test run should show:
- All tests passing (✅)
- Detailed information for each endpoint
- Summary at the end with pass/fail counts

Example output:
```
============================================================
Test Summary
============================================================
✅ Passed: 15
❌ Failed: 0
📊 Total: 15
============================================================
```

## Troubleshooting

### Issue: "Failed to generate OTP"
- **Solution**: Check that the mobile number exists in the `collection_agent` table
- Verify the server is running and accessible

### Issue: "OTP verification failed"
- **Solution**: Make sure you're using the OTP from the generate OTP response
- Check that OTP hasn't expired (5 minutes default)
- Verify the mobile number matches

### Issue: "Loan not found"
- **Solution**: Update `TEST_CONFIG.test_loan_id` with a valid loan_id from your database
- Ensure the loan belongs to the same company as the test agent

### Issue: "Agent not found"
- **Solution**: Verify the collection agent exists in the database
- Check that the agent has `com_id`, `line`, and other required fields set

### Issue: "No areas found"
- **Solution**: Ensure `line_entry` table has entries for the agent's line
- Verify `area` field is populated in line entries

## Test Data Requirements

For comprehensive testing, ensure your database has:

1. **Collection Agent**:
   - Valid mobile number
   - `com_id` set
   - `line` assigned
   - `status` = 'active'

2. **Loan Entry**:
   - Valid `loan_id`
   - `com_id` matching agent's company
   - `area` matching agent's line areas
   - `next_due_date` set (current or past date for testing)

3. **Line Entry**:
   - `line` matching agent's line
   - `area` values populated
   - `com_id` matching agent's company

## Customizing Tests

You can modify the test script to:
- Add more test cases
- Test specific scenarios
- Change test data
- Add performance benchmarks

## Notes

- The test script creates actual records in the database (receipts, expenses)
- You may want to clean up test data after running tests
- Some tests depend on previous tests (e.g., authentication must succeed before other tests)
- Tests run sequentially to maintain dependencies

## Cleanup

After running tests, you may want to remove test data:

```sql
-- Remove test receipts (adjust conditions as needed)
DELETE FROM loan_receipt WHERE remark LIKE '%Test receipt from automated test script%';

-- Remove test expenses (adjust conditions as needed)
DELETE FROM expense WHERE reason LIKE '%Test expense%';
```



