# Merchant API Testing Documentation

This directory contains comprehensive testing tools and documentation for the Merchant APIs in the UPI PSP platform.

## Overview

The merchant APIs allow partners to enroll, manage, and monitor their merchants for UPI payment processing. This testing suite provides automated testing, manual testing guides, and integration with the live API documentation interface.

## Files Structure

```
├── docs/api/
│   └── MERCHANT_API_TESTING_GUIDE.md     # Comprehensive testing guide
├── manual_testing/scripts/
│   ├── merchant_api_tester.py            # Python automated testing suite
│   ├── test_merchant_apis.sh             # Bash testing script
│   └── README.md                         # This file
└── lib/da_product_app_web/live/api_docs_live/
    ├── api_docs_live.ex                  # LiveView with enhanced merchant API docs
    └── api_docs_live.html.heex           # Interactive testing interface
```

## Quick Start

### 1. Set up Environment

```bash
# Required environment variables
export API_TOKEN="your_partner_api_token_here"
export BASE_URL="https://api.mercurypay.com"  # or your dev environment
export PARTNER_ID="PARTNER_001"              # your partner ID
```

### 2. Run Quick Tests (Bash)

```bash
# Basic functionality test
./test_merchant_apis.sh --quick

# Comprehensive test suite  
./test_merchant_apis.sh --full

# Error scenarios only
./test_merchant_apis.sh --errors-only
```

### 3. Run Advanced Tests (Python)

```bash
# Install dependencies (if needed)
pip install requests

# Run comprehensive test suite
python3 merchant_api_tester.py --verbose

# Include performance tests
python3 merchant_api_tester.py --verbose --include-performance

# Custom configuration
python3 merchant_api_tester.py \
  --base-url "https://staging.api.mercurypay.com" \
  --partner-id "PARTNER_DEV" \
  --verbose
```

### 4. Interactive Testing

Access the live API documentation interface:
- Navigate to `/api-docs` in your Phoenix application
- Select "🤝 Partner → PSP Interface" group
- Choose any merchant-related endpoint
- Use the interactive testing features with templates and validation

## API Endpoints Tested

### Merchant Management
- `POST /api/v1/partners/:partner_id/merchants` - Create merchant
- `GET /api/v1/partners/:partner_id/merchants` - List merchants
- `GET /api/v1/partners/:partner_id/merchants/:id` - Get merchant details
- `PUT /api/v1/partners/:partner_id/merchants/:id` - Update merchant
- `PATCH /api/v1/partners/:partner_id/merchants/:id/status` - Update status

### Merchant Operations
- `GET /api/v1/partners/:partner_id/merchants/:id/validate` - Validate merchant
- `POST /api/v1/partners/:partner_id/merchants/:id/check-limits` - Check limits

### Search & Analytics
- `GET /api/v1/partners/:partner_id/merchants-search` - Search merchants
- `GET /api/v1/partners/:partner_id/merchants-stats` - Get statistics

### QR Code Management
- `POST /api/v1/qr-generate` - Generate QR code
- `GET /api/v1/qr-status/:id` - Check QR status

## Testing Features

### 1. Bash Script (`test_merchant_apis.sh`)

**Pros:**
- Simple, no dependencies
- Quick setup and execution
- Works on any Unix-like system
- Good for CI/CD pipelines

**Features:**
- Basic CRUD operations testing
- Error scenario validation
- Multiple merchant types (retail, restaurant, international)
- Status transition testing
- QR code generation and validation

**Usage Examples:**
```bash
# Quick health check
./test_merchant_apis.sh --quick

# Full test suite
API_TOKEN="your_token" ./test_merchant_apis.sh --full

# Test only error handling
./test_merchant_apis.sh --errors-only
```

### 2. Python Script (`merchant_api_tester.py`)

**Pros:**
- Advanced features and reporting
- Detailed performance metrics
- JSON report generation
- Comprehensive error handling
- Rate limiting tests

**Features:**
- Multiple merchant business types
- Status transition workflows
- Transaction limit testing
- Search functionality validation
- Performance benchmarking
- Detailed JSON reports
- Resource cleanup tracking

**Usage Examples:**
```bash
# Comprehensive testing with detailed output
python3 merchant_api_tester.py --verbose

# Include performance tests (rate limiting)
python3 merchant_api_tester.py --include-performance

# Custom environment
python3 merchant_api_tester.py \
  --base-url "https://dev.api.mercurypay.com" \
  --partner-id "DEV_PARTNER" \
  --verbose
```

### 3. Interactive API Documentation

**Features:**
- Live endpoint testing
- Request validation
- Sample data templates
- Merchant-specific testing guides
- Error scenario examples
- Performance metrics display

**Merchant Templates Available:**
- Retail Store
- Restaurant
- E-commerce
- International Business

**Testing Scenarios:**
- Success cases
- Validation errors
- Business rule violations
- Rate limiting behavior

## Test Data Templates

### Retail Merchant
```json
{
  "merchant_code": "RETAIL001",
  "brand_name": "ABC Electronics Store",
  "merchant_vpa": "abcelectronics@upi",
  "business_type": "RETAIL",
  "corridors": ["DOMESTIC"],
  "contact_email": "owner@abcelectronics.com",
  "contact_phone": "+91-9876543210"
}
```

### Restaurant
```json
{
  "merchant_code": "REST001", 
  "brand_name": "Delicious Restaurant",
  "merchant_vpa": "restaurant@upi",
  "business_type": "FOOD_AND_BEVERAGE",
  "corridors": ["DOMESTIC"],
  "contact_email": "manager@restaurant.com"
}
```

### International Business
```json
{
  "merchant_code": "INTL001",
  "brand_name": "Global Import Export",
  "merchant_vpa": "globalimport@upi",
  "business_type": "IMPORT_EXPORT", 
  "corridors": ["SGD-INR", "USD-INR", "EUR-INR"],
  "fbar_number": "FBAR123456789"
}
```

## Common Test Scenarios

### 1. Complete Merchant Lifecycle
1. Create merchant
2. Validate merchant
3. Check transaction limits
4. Generate QR code
5. Update merchant status
6. Search for merchant
7. Get statistics

### 2. Error Handling
1. Duplicate merchant code
2. Invalid VPA format
3. Missing required fields
4. Non-existent merchant access
5. Invalid partner access
6. Rate limit testing

### 3. Status Transitions
1. ACTIVE → SUSPENDED
2. SUSPENDED → ACTIVE  
3. ACTIVE → INACTIVE
4. INACTIVE → ACTIVE (requires approval)

### 4. International Merchant Testing
1. Multi-corridor setup
2. FBAR compliance
3. Currency validation
4. Cross-border limits

## Expected Response Codes

| Operation | Success | Client Error | Server Error |
|-----------|---------|--------------|--------------|
| Create Merchant | 201 | 400, 409, 422 | 500 |
| List Merchants | 200 | 400, 403 | 500 |
| Get Merchant | 200 | 404, 403 | 500 |
| Update Merchant | 200 | 400, 404, 422 | 500 |
| Update Status | 200 | 400, 404 | 500 |
| Validate | 200 | 404, 403 | 500 |
| Check Limits | 200 | 400, 404 | 500 |
| Search | 200 | 400, 403 | 500 |
| Statistics | 200 | 403 | 500 |
| Generate QR | 201 | 400, 404 | 500 |
| QR Status | 200 | 404, 403 | 500 |

## Performance Benchmarks

| Endpoint | Target Response Time | Rate Limit |
|----------|---------------------|------------|
| Create Merchant | < 500ms | 50/min |
| List Merchants | < 200ms | 100/min |
| Get Details | < 100ms | 200/min |
| Update Operations | < 300ms | 100/min |
| Search | < 400ms | 100/min |
| Statistics | < 1000ms | 20/min |

## Troubleshooting

### Common Issues

1. **401 Unauthorized**
   ```bash
   # Check token format
   echo "Authorization: Bearer $API_TOKEN"
   ```

2. **429 Rate Limited**
   ```bash
   # Check rate limit headers
   curl -I -H "Authorization: Bearer $API_TOKEN" "$BASE_URL/api/v1/partners/$PARTNER_ID/merchants"
   ```

3. **422 Validation Error**
   ```bash
   # Check request body format
   echo "$request_data" | jq .
   ```

4. **404 Not Found**
   ```bash
   # Verify partner and merchant IDs
   curl -H "Authorization: Bearer $API_TOKEN" "$BASE_URL/api/v1/partners/$PARTNER_ID/merchants"
   ```

### Debug Mode

Enable verbose output for detailed debugging:

```bash
# Bash script
./test_merchant_apis.sh --full 2>&1 | tee test_output.log

# Python script  
python3 merchant_api_tester.py --verbose 2>&1 | tee test_output.log

# curl debugging
curl -v -H "Authorization: Bearer $API_TOKEN" "$BASE_URL/api/v1/partners/$PARTNER_ID/merchants"
```

## Integration with CI/CD

### GitHub Actions Example
```yaml
name: Merchant API Tests

on: [push, pull_request]

jobs:
  api-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Run Merchant API Tests
        env:
          API_TOKEN: ${{ secrets.TEST_API_TOKEN }}
          BASE_URL: ${{ secrets.TEST_BASE_URL }}
          PARTNER_ID: ${{ secrets.TEST_PARTNER_ID }}
        run: |
          cd manual_testing/scripts
          ./test_merchant_apis.sh --full
```

### Docker Testing
```dockerfile
FROM python:3.9-alpine

WORKDIR /app
COPY manual_testing/scripts/ .

RUN pip install requests

CMD ["python3", "merchant_api_tester.py", "--verbose"]
```

## Contributing

When adding new tests or modifying existing ones:

1. Update both bash and Python scripts
2. Add corresponding documentation
3. Update the interactive API docs if needed
4. Test with different environments
5. Update expected response codes if APIs change

## Support

For issues or questions:
1. Check the comprehensive testing guide in `docs/api/MERCHANT_API_TESTING_GUIDE.md`
2. Use the interactive API documentation at `/api-docs`
3. Review error scenarios in test scripts
4. Contact the development team for API-specific issues

## License

This testing suite is part of the UPI PSP platform and follows the same license terms.
