# Transaction Processing Lifecycle

This document describes the transaction processing lifecycle implementation that manages payment transactions through three distinct phases using dedicated database tables.

## Overview

The system implements a robust transaction processing flow that ensures data integrity and provides comprehensive transaction tracking through the following stages:

1. **Temporary Transaction** (`pos_temp_transaction`) - Active/in-progress transactions
2. **Successful Transaction** (`pos_transaction`) - Successfully completed transactions  
3. **Failed Transaction** (`pos_failed_transaction`) - Failed or declined transactions

## Architecture

### Core Components

- **Transaction Entities**: JPA entities for the three transaction tables
- **TransactionAuxUtils**: Core utility class for database operations
- **TransactionLifecycleService**: Service layer for transaction lifecycle management
- **TransactionRouter**: Updated to integrate the new lifecycle management

### Transaction Flow

```
1. Request Received → Extract DE-41 (Terminal ID)
2. Terminal Lookup → Find POS and Acquirer Terminal
3. Terminal Busy Check → Verify no existing temp transaction
4. Create Temp Transaction → Insert into pos_temp_transaction
5. Send to Bank → Process with acquirer
6. Receive Response → Get bank response
7. Success/Failure → Move to pos_transaction or pos_failed_transaction
8. Cleanup → Remove from pos_temp_transaction
```

## Database Schema

All three tables have identical structure with the following key columns:

### Terminal & Merchant Information
- `s_tid` - Source Terminal ID (POS terminal)
- `s_mid` - Source Merchant ID (POS merchant)  
- `b_tid` - Bank Terminal ID (Acquirer terminal)
- `b_mid` - Bank Merchant ID (Acquirer merchant)

### Transaction Data
- `mti` - Message Type Indicator
- `proc_code` - Processing Code
- `total_amount` - Transaction amount
- `response_code` - Transaction response code
- `approval_code` - Authorization approval code

### Card Information
- `masked_card_no` - Masked PAN for security
- `encrypted_track2` - Encrypted track 2 data
- `emv_data` - EMV chip data

### Audit Information
- `created_dateTime` - Transaction creation time
- `updated_dateTime` - Last update time
- `metadata` - Additional transaction metadata

## Key Features

### 1. Terminal Busy Protection
Prevents concurrent transactions on the same terminal by checking `pos_temp_transaction` table:

```java
boolean isBusy = transactionAuxUtils.isTerminalBusy(bankTid, bankMid);
if (isBusy) {
    // Return "Terminal is busy" error
}
```

### 2. Atomic Operations
All transaction moves between tables are atomic:

```java
// Success flow
transactionAuxUtils.moveTempToSuccess(tempTransactionId, successTransaction);

// Failure flow  
transactionAuxUtils.moveTempToFailed(tempTransactionId, failedTransaction);
```

### 3. Comprehensive Error Handling
Robust error handling ensures temp transactions are always cleaned up:

```java
try {
    // Process transaction
} catch (Exception e) {
    // Move temp to failed table
    cleanupTransaction(tempTransactionId, e.getMessage());
}
```

## Usage Examples

### Using TransactionLifecycleService

```java
TransactionLifecycleService lifecycleService = new TransactionLifecycleService();

// Start transaction
PosTempTransaction tempTxn = lifecycleService.startTransaction(request, posTerminal, acquirerTerminal);

// Process with bank...
ISOMsg response = processWithBank(request);

// Complete transaction
boolean success = lifecycleService.completeTransaction(tempTxn.getId(), response);
```

### Direct Usage with TransactionAuxUtils

```java
TransactionAuxUtils utils = new TransactionAuxUtils();

// Check terminal availability
if (utils.isTerminalBusy(bankTid, bankMid)) {
    return generateBusyError();
}

// Create and insert temp transaction
PosTempTransaction tempTxn = utils.createTempTransactionFromISO(request, posTerminal, acquirerTerminal);
tempTxn = utils.insertTempTransaction(tempTxn);

// After bank response
if (isSuccess(response)) {
    PosTransaction successTxn = utils.createSuccessTransactionFromTemp(tempTxn, response);
    utils.moveTempToSuccess(tempTxn.getId(), successTxn);
} else {
    PosFailedTransaction failedTxn = utils.createFailedTransactionFromTemp(tempTxn, response);
    utils.moveTempToFailed(tempTxn.getId(), failedTxn);
}
```

## Database Setup

1. Run the SQL schema script:
```bash
mysql -u username -p database_name < transaction_lifecycle_schema.sql
```

2. Configure persistence.xml to include the new entities:
```xml
<persistence-unit name="jpos-tcpay-local">
    <class>org.jpos.tcpay.db.entity.PosTransaction</class>
    <class>org.jpos.tcpay.db.entity.PosTempTransaction</class>
    <class>org.jpos.tcpay.db.entity.PosFailedTransaction</class>
    <!-- other entities -->
</persistence-unit>
```

## Performance Considerations

### Critical Indexes
The following indexes are essential for performance:

- `pos_temp_transaction(b_tid, b_mid)` - Terminal busy checks
- `pos_temp_transaction(s_tid)` - Source terminal lookups
- `pos_transaction(created_dateTime)` - Time-based queries
- `pos_transaction(response_code)` - Success/failure reporting

### Monitoring
Monitor the `pos_temp_transaction` table:
- Should typically be empty or have very few records
- Long-running temp transactions may indicate system issues
- Consider implementing cleanup jobs for orphaned temp transactions

## Error Codes

The system uses standard ISO 8583 response codes:

- `00` - Approved
- `10` - Approved, partial amount
- `11` - Approved, VIP
- `76` - Blocked terminal (busy)
- `91` - No response from issuer  
- `96` - System error

## Security Considerations

- PAN data is always masked in database
- Track 2 data is encrypted before storage
- EMV data is stored as-is for reconciliation
- All database operations use transactions for consistency

## Troubleshooting

### Common Issues

1. **Terminal Always Busy**
   - Check for orphaned temp transactions
   - Verify cleanup procedures are running

2. **Temp Transactions Not Moving**
   - Check database transaction isolation
   - Verify error handling is working

3. **Performance Issues**
   - Ensure indexes are created
   - Monitor temp table size
   - Consider partitioning for high volume

### Logging
All operations are logged with transaction IDs for traceability:

```
INFO: Created temp transaction with ID: 12345 for terminal: TERM001
INFO: Transaction successful for terminal TERM001, response code: 00
INFO: Moved transaction to success table for terminal TERM001
```