# ISO8583 Transaction Test Suite

A comprehensive Elixir-based testing framework for verifying ISO8583 transaction processing through jPOS servers. This framework includes **195 test cases** across 5 transaction types (SALE, VOID, REVERSAL, REFUND, LOGON) with extensive edge case coverage.

## Features

- ✅ **Comprehensive Test Coverage**: 195 test cases across 5 transaction types
- ✅ **Multiple Transaction Types**: SALE, VOID, REVERSAL, REFUND, and LOGON
- ✅ **ISO8583 ISO87B Format**: Full BCD-packed packet building and parsing
- ✅ **Automated Validation**: Multi-level response validation
- ✅ **Detailed Reporting**: Both summary and detailed reports with hex dumps
- ✅ **Flexible Configuration**: Command-line options for easy customization
- ✅ **Real Device Simulation**: Uses actual TID/MID credentials
- ✅ **Edge Case Coverage**: Extensive testing of boundary conditions and error scenarios

## Project Structure

```
jposTestCases/
├── lib/
│   ├── iso8583/
│   │   ├── packet_builder.ex    # ISO8583 packet construction
│   │   └── parser.ex            # Response parsing
│   ├── csv_loader.ex            # CSV test case loader
│   ├── test_engine.ex           # Test execution engine
│   ├── validator.ex             # Response validation
│   └── reporter.ex              # Report generation
├── test_cases/
│   ├── sale_test_cases.csv      # SALE transaction tests (50 cases)
│   ├── void_test_cases.csv      # VOID transaction tests (30 cases)
│   ├── refund_test_cases.csv    # REFUND transaction tests (35 cases)
│   ├── reversal_test_cases.csv  # REVERSAL transaction tests (40 cases)
│   └── logon_test_cases.csv     # LOGON transaction tests (40 cases)
├── reports/                     # Generated test reports
├── run_tests.exs                # Main test runner
└── README.md                    # This file
```

## Prerequisites

- **Elixir** (version 1.12 or higher)
- **jPOS Server** running and accessible
- Network connectivity to jPOS server

## Installation

1. Clone or copy this directory to your system
2. Ensure Elixir is installed:
   ```bash
   elixir --version
   ```
3. Ensure jPOS server is running on the configured port (default: 14001)

## Usage

### Basic Usage

**Test connectivity first:**
```bash
elixir test_connectivity.exs
```

**Run transaction tests:**
```bash
# Run SALE tests (50 cases)
elixir run_tests.exs --type sale

# Run VOID tests (30 cases)
elixir run_tests.exs --type void

# Run REFUND tests (35 cases)
elixir run_tests.exs --type refund

# Run REVERSAL tests (40 cases)
elixir run_tests.exs --type reversal

# Run LOGON tests (40 cases)
elixir run_tests.exs --type logon

# Run ALL tests (195 cases)
elixir run_tests.exs --type all
```

### Advanced Options

```bash
elixir run_tests.exs [OPTIONS]

Options:
  --type TYPE        Transaction type (sale, void, reversal, refund, all)
                     Default: sale
  --host HOST        jPOS server host (default: localhost)
  --port PORT        jPOS server port (default: 14001)
  --timeout MS       Transaction timeout in ms (default: 15000)
  --filter IDS       Comma-separated test IDs to run
  --reports DIR      Reports output directory (default: reports)
```

### Examples

**Run specific test cases:**
```bash
elixir run_tests.exs --type sale --filter SALE-001,SALE-002,SALE-010
```

**Run with custom server:**
```bash
elixir run_tests.exs --type sale --host 192.168.1.100 --port 9103
```

**Test specific transaction combinations:**
```bash
# Test SALE and VOID together
elixir run_tests.exs --type sale --filter SALE-001
elixir run_tests.exs --type void --filter VOID-001

# Test network operations
elixir run_tests.exs --type logon --filter LOGON-001,LOGON-002,LOGON-019

# Run all 195 tests
elixir run_tests.exs --type all
```

**Run with longer timeout:**
```bash
elixir run_tests.exs --type sale --timeout 30000
```

## Test Cases Overview

### Complete Test Suite: 195 Test Cases

| Transaction Type | Test Cases | MTI Request | MTI Response | Processing Code |
|------------------|------------|-------------|--------------|------------------|
| SALE | 50 | 0200 | 0210 | 000000 |
| VOID | 30 | 0200 | 0210 | 200000 |
| REFUND | 35 | 0200 | 0210 | 200000 |
| REVERSAL | 40 | 0400 | 0410 | 000000 |
| LOGON | 40 | 0800 | 0810 | 990000 |

### SALE Test Cases (50 cases)

The SALE test suite includes:

### ✅ Happy Path Scenarios
- Valid purchases with different card brands (Visa, Mastercard, Amex, Discover)
- Various amount ranges ($0.01 to $999.99)
- Different POS entry modes (manual, chip, contactless)
- Multiple NIIs and merchant configurations

### ❌ Declined Transactions
- Insufficient funds
- Expired cards
- Do not honor
- Pick up card
- Withdrawal limits exceeded
- Frequency limits exceeded
- Invalid merchant
- Refer to issuer
- System malfunctions

### 🔍 Edge Cases
- Invalid card numbers (too short, too long)
- Zero and negative amounts
- Maximum STAN values
- Duplicate STAN detection
- Format errors
- Boundary conditions
- Multi-currency support
- Different card number lengths (13-19 digits)

### VOID Test Cases (30 cases)
- **Valid Voids (18 cases)**: Same-day voids, different card brands, various amounts
- **Invalid Voids (7 cases)**: Non-existent transactions, already voided, zero amounts
- **Edge Cases (5 cases)**: Boundary STANs, partial void attempts, sequential voids

### REFUND Test Cases (35 cases)
- **Valid Refunds (20 cases)**: Full/partial refunds, standalone credits, different card brands
- **Invalid Refunds (9 cases)**: Non-existent original sales, excessive amounts, invalid cards
- **Edge Cases (6 cases)**: Boundary amounts, sequential refunds, multi-currency

### REVERSAL Test Cases (40 cases)
- **Valid Reversals (25 cases)**: Timeout reversals, communication failures, network errors, system malfunctions
- **Invalid Reversals (6 cases)**: Non-existent transactions, invalid processing codes
- **Edge Cases (9 cases)**: Maximum STANs, boundary amounts, sequential reversals

### LOGON Test Cases (40 cases)
- **Network Management (21 cases)**: Sign-on/sign-off, echo tests, heartbeats, key exchange, periodic checks
- **Invalid Logons (7 cases)**: Invalid TID/MID, zero STAN, invalid NIIs, duplicate STANs
- **Edge Cases (12 cases)**: Boundary STANs, rapid sequences, batch/settlement coordination

### 📊 Test Categories Summary

| Category | SALE | VOID | REFUND | REVERSAL | LOGON | Total |
|----------|------|------|--------|----------|-------|-------|
| Valid Scenarios | 20 | 18 | 20 | 25 | 21 | 104 |
| Invalid/Declined | 15 | 7 | 9 | 6 | 7 | 44 |
| Format Errors | 8 | - | - | - | - | 8 |
| Edge Cases | 7 | 5 | 6 | 9 | 12 | 39 |
| **Total** | **50** | **30** | **35** | **40** | **40** | **195** |

## Test Case Format

Each test case in the CSV includes:

```csv
test_id,scenario,description,tid,mid,stan,amount,pan,processing_code,mti,nii,expected_mti_response,expected_response_code,validation_rules
```

**Example:**
```csv
SALE-001,valid_purchase_visa,Valid Visa purchase $10.00,12345678,123456789012345,000001,000000001000,4111111111111111,000000,0200,782,0210,00,check_approval
```

## Reports

After each test run, two reports are generated:

### 1. Summary Report
- Overall statistics (pass/fail/error counts)
- Success rate
- Quick test results table
- Failed test summary

**Example:** `reports/summary_20260519T123045.txt`

### 2. Detailed Report
- Complete test information for each case
- Validation details
- Parsed response fields
- Hex dumps of request and response packets
- Field-by-field breakdown

**Example:** `reports/detailed_20260519T123045.txt`

## Validation Rules

The framework supports various validation rules:

- **check_approval**: Verifies approval code (DE38) is present
- **check_decline_code**: Validates decline response codes
- **check_format_error**: Checks for format error responses
- **check_fields**: Ensures critical fields are present

## ISO8583 Field Support

Currently supported fields:

| Field | Description | Format |
|-------|-------------|--------|
| DE2 | PAN | LLVAR BCD |
| DE3 | Processing Code | BCD (3 bytes) |
| DE4 | Amount | BCD (6 bytes) |
| DE11 | STAN | BCD (3 bytes) |
| DE12 | Time | BCD (3 bytes) |
| DE13 | Date | BCD (2 bytes) |
| DE14 | Expiry | BCD (2 bytes) |
| DE22 | POS Entry Mode | BCD (2 bytes) |
| DE23 | Card Sequence | BCD (2 bytes) |
| DE24 | NII | BCD (2 bytes) |
| DE25 | POS Condition Code | BCD (1 byte) |
| DE35 | Track 2 | LLVAR BCD |
| DE38 | Approval Code | ASCII (6 bytes) |
| DE39 | Response Code | ASCII (2 bytes) |
| DE41 | Terminal ID | ASCII (8 bytes) |
| DE42 | Merchant ID | ASCII (15 bytes) |
| DE49 | Currency Code | ASCII (3 bytes) |

## Response Code Reference

Common response codes:

| Code | Description |
|------|-------------|
| 00 | Approved |
| 01 | Refer to card issuer |
| 03 | Invalid merchant |
| 04 | Pick up card |
| 05 | Do not honor |
| 12 | Invalid transaction |
| 13 | Invalid amount |
| 14 | Invalid card number |
| 30 | Format error |
| 51 | Insufficient funds |
| 54 | Expired card |
| 55 | Incorrect PIN |
| 58 | Transaction not permitted |
| 61 | Exceeds withdrawal limit |
| 65 | Exceeds frequency limit |
| 91 | Issuer inoperative |
| 96 | System malfunction |

## Adding New Test Cases

1. Open the appropriate CSV file (e.g., `test_cases/sale_test_cases.csv`)
2. Add a new row with all required fields
3. Run the tests:
   ```bash
   elixir run_tests.exs --type sale
   ```

## Extending the Framework

### Adding New Test Cases

To add new test cases to existing transaction types:

1. Open the appropriate CSV file (e.g., `test_cases/sale_test_cases.csv`)
2. Add a new row with all required fields
3. Run the tests: `elixir run_tests.exs --type sale`

### Adding New Transaction Types

To add support for new transaction types (e.g., Pre-Authorization):

1. Create CSV file: `test_cases/preauth_test_cases.csv`
2. Add test cases with appropriate MTI, processing code, and fields
3. Run with: `elixir run_tests.exs --type preauth`

## Troubleshooting

### Connection Failed
```
❌ ERROR: Cannot connect to jPOS server at localhost:14001
```
**Solution**: Ensure jPOS server is running and the port is correct.

### No Test Cases Loaded
```
❌ ERROR: No test cases loaded. Check CSV file path.
```
**Solution**: Verify the CSV file exists in `test_cases/` directory.

### Parse Errors
If responses fail to parse, check:
- jPOS server ISO8583 packager configuration
- Expected packet format (ISO87B BCD-packed)
- Field definitions match server configuration

## Configuration

Default configuration:
```elixir
%{
  host: "localhost",
  port: 14001,
  timeout: 15_000,  # 15 seconds
  reports_dir: "reports"
}
```

Override via command-line options or modify in `run_tests.exs`.

## Contributing

To extend this framework:

1. Add new test cases to CSV files
2. Implement additional validation rules in `lib/validator.ex`
3. Add support for new ISO8583 fields in `packet_builder.ex` and `parser.ex`
4. Create new transaction type test suites

## License

Internal use only.

## Support

For questions or issues, contact the development team.

---

## Summary

✅ **195 comprehensive test cases** across 5 transaction types  
✅ **Complete ISO8583 support** for jPOS server testing  
✅ **Edge case coverage** for all transaction scenarios  
✅ **Professional reporting** with hex dumps and validation details  
✅ **Production-ready** framework for transaction verification  

**Version:** 1.0.0  
**Last Updated:** May 19, 2026  
**Test Coverage:** 195 test cases (SALE: 50, VOID: 30, REFUND: 35, REVERSAL: 40, LOGON: 40)
