# 🏦 Mercury UPI PSP Platform

[![NPCI Compliant](https://img.shields.io/badge/NPCI-Compliant-green.svg)](https://www.npci.org.in/)
[![Elixir](https://img.shields.io/badge/Elixir-1.17+-purple.svg)](https://elixir-lang.org/)
[![Phoenix](https://img.shields.io/badge/Phoenix-1.7+-orange.svg)](https://phoenixframework.org/)
[![License](https://img.shields.io/badge/License-Proprietary-red.svg)](LICENSE)

**Enterprise-grade UPI Payment Service Provider (PSP) platform built with Elixir/Phoenix for high-performance, fault-tolerant payment processing with complete NPCI specification compliance.**

## 🎯 Overview

Mercury UPI PSP is a complete implementation of the Unified Payments Interface (UPI) Payment Service Provider specification as defined by the National Payments Corporation of India (NPCI). The platform is designed for international payment corridors with robust transaction orchestration, real-time processing, and enterprise-grade security.

### ✨ Key Features

- **🏛️ Complete NPCI Compliance**: All 8 mandatory UPI APIs implemented and tested
- **🌍 International Transactions**: Multi-corridor support with FX conversion
- **⚡ High Performance**: Sub-100ms transaction response times
- **🔒 Enterprise Security**: End-to-end encryption with audit trails
- **🚀 Fault Tolerant**: Elixir/OTP supervision trees with automatic recovery
- **📊 Real-time Monitoring**: Comprehensive logging and alerting
- **🔄 Transaction Orchestration**: State machine-based payment processing
- **🌐 Partner Integration**: Flexible adapter pattern for multiple partners

## 🆕 Latest Implementation (September 2025)

### **🎉 Complete NPCI UPI Implementation with QR Validation & Heartbeat**
- ✅ **ReqHbt/RespHbt** - Heartbeat functionality for system health monitoring
- ✅ **ReqValQr/RespValQr** - International QR validation with multi-currency support
- ✅ **ECDSA Signatures** - Cryptographic security for QR code validation
- ✅ **FX Processing** - Real-time foreign exchange with markup calculation
- ✅ **XML Compliance** - Full NPCI namespace and schema validation
- ✅ **Audit Trails** - Complete transaction logging and timing metrics

**📖 [Complete Implementation Guide](docs/implementation/NPCI_UPI_COMPLETE_IMPLEMENTATION.md)** | **🧪 [Testing Guide](manual_testing/scripts/test_npci_qr_validation.sh)**

## 📁 Project Structure

```
mercury_upi_psp/
├── lib/                          # Application source code
│   ├── da_product_app/          # Core business logic
│   └── da_product_app_web/      # Web interface and APIs
├── docs/                        # 📚 Documentation
│   ├── api/                     # API documentation
│   ├── implementation/          # Implementation guides
│   └── guides/                  # Setup and development guides
├── manual_testing/              # 🧪 Testing resources
│   ├── scripts/                 # Testing shell scripts
│   ├── xml_samples/             # XML test files
│   ├── postman/                 # Postman collections
│   └── *.exs                    # Manual testing scripts
├── test/                        # Automated tests
├── priv/                        # Static assets and migrations
├── config/                      # Configuration files
└── deps/                        # Dependencies
```

## 🏗️ Architecture

### Core Components

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   NPCI APIs     │    │  Partner APIs   │    │  Admin Portal   │
│  (UPI Protocol) │    │   (Business)    │    │  (Management)   │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────────────────────────────────────────────────────┐
│                  Web Layer                               │
├─────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ UPI XML     │  │Transaction  │  │ Partner     │             │
│  │ Schema      │  │ Manager     │  │ Adapters    │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
├─────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ Event       │  │ FX Rate     │  │ Risk        │             │
│  │ Sourcing    │  │ Service     │  │ Management  │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
├─────────────────────────────────────────────────────────────────┤
│                     Data Layer                                  │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │    MySQL    │  │    Oban     │  │   Redis     │             │
│  │ (Primary)   │  │ (Jobs)      │  │ (Planned)   │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
└─────────────────────────────────────────────────────────────────┘
```

### Technology Stack

- **Backend**: Elixir 1.17+ with Phoenix 1.7+
- **Database**: MySQL 8.0+ with Ecto
- **Job Processing**: Oban for background jobs
- **Caching**: Redis (planned for >100K daily transactions)
- **Frontend**: Phoenix LiveView with Tailwind CSS
- **Monitoring**: Built-in telemetry and logging
- **Security**: Industry-standard encryption and compliance

## 🚀 Quick Start

### Prerequisites

- **Elixir**: 1.17 or higher
- **Erlang/OTP**: 26 or higher
- **MySQL**: 8.0 or higher
- **Redis**: 6 or higher (optional, planned for high-load scenarios >100K daily transactions)
- **Node.js**: 18+ (for asset compilation)

### Installation

1. **Clone the repository**
   ```bash
   git clone https://github.com/momentpay/upi_psp_platform.git
   cd upi_psp_platform
   ```

2. **Install dependencies**
   ```bash
   mix deps.get
   ```

3. **Setup database**
   ```bash
   mix ecto.setup
   ```

4. **Install Node.js dependencies**
   ```bash
   cd assets && npm install && cd ..
   ```

5. **Start the Phoenix server**
   ```bash
   mix phx.server
   ```

6. **Visit the application**
   ```
   http://localhost:4000
   ```

### Docker Setup (Optional)

```bash
# Build the Docker image
docker build -t mercury-upi-psp .

# Run with docker-compose
docker-compose up -d
```

## 📚 API Documentation

### 🏛️ NPCI → PSP Interface (Official UPI APIs)

**Base URL**: `/api/v1/upi/`

| Method | Endpoint | Description | NPCI API |
|--------|----------|-------------|----------|
| POST | `/validate-qr` | QR code validation and verification | ReqValQR / RespValQR |
| POST | `/process-payment` | Payment transaction processing | ReqPay / RespPay |
| POST | `/check-transaction` | Transaction status inquiry | ReqChkTxn / RespChkTxn |
| POST | `/heartbeat` | System health check | ReqHbt / RespHbt |

### 🤝 Partner → PSP Interface (Business APIs)

**Base URL**: `/api/v1/`

| Method | Endpoint | Description | Use Case |
|--------|----------|-------------|----------|
| POST | `/qr-generate` | Generate dynamic QR codes | Partner merchant QR creation |
| GET | `/qr-status/:id` | Check QR status and usage | Partner QR monitoring |
| POST | `/upi/batch-process` | Bulk transaction processing | High-volume operations |
| POST | `/upi/reconcile` | Settlement reconciliation | Daily settlement matching |

### 📋 API Examples

#### QR Code Validation
```bash
curl -X POST http://localhost:4000/api/v1/upi/validate-qr \
  -H "Content-Type: application/xml" \
  -d @sample_qr_validation.xml
```

#### Payment Processing
```bash
curl -X POST http://localhost:4000/api/v1/upi/process-payment \
  -H "Content-Type: application/xml" \
  -d @sample_payment_request.xml
```

## 📚 Documentation & Testing

### 📖 Documentation
- **📁 [Complete Documentation](docs/)**: Organized documentation hub
- **🔗 [API Reference](docs/api/)**: Complete API documentation  
- **🚀 [Implementation Guides](docs/implementation/)**: Step-by-step implementation
- **📋 [Setup Guides](docs/guides/)**: Configuration and development guides

### 🧪 Testing Resources
- **📁 [Manual Testing](manual_testing/)**: All testing resources  
- **🔧 [Test Scripts](manual_testing/scripts/)**: Automated testing scripts
- **📄 [XML Samples](manual_testing/xml_samples/)**: Test XML files
- **🌐 [Postman Collection](manual_testing/postman/)**: API testing collection
- **🏪 [Merchant API Testing](manual_testing/scripts/README.md)**: Comprehensive merchant API testing suite
- **📖 [API Testing Guide](docs/api/MERCHANT_API_TESTING_GUIDE.md)**: Detailed testing documentation

### Run Automated Tests
```bash
# Run all tests
mix test

# Run tests with coverage
mix test --cover

# Run specific test module
mix test test/da_product_app_web/controllers/api/v1/upi_controller_test.exs
```

### API Testing with Postman
Import the Postman collection from `manual_testing/postman/Mercury_UPI_PSP_Postman_Collection.json`:

1. Open Postman
2. Import → `manual_testing/postman/Mercury_UPI_PSP_Postman_Collection.json`
3. Set environment variables for your testing setup
4. Run the complete test suite

### Manual Testing Scripts
```bash
# Test all UPI APIs
./manual_testing/scripts/test_complete_upi_apis.sh

# Test NPCI callbacks
./manual_testing/scripts/test_npci_callbacks.sh

# Test QR validation
./manual_testing/scripts/test_npci_qr_validation.sh

# Verify TideWave integration
./manual_testing/scripts/verify_tidewave.sh

# 🏪 Merchant API Testing (NEW)
# Quick merchant API tests
./manual_testing/scripts/test_merchant_apis.sh --quick

# Comprehensive merchant API test suite
./manual_testing/scripts/test_merchant_apis.sh --full

# Python-based comprehensive testing with reporting
python3 manual_testing/scripts/merchant_api_tester.py --verbose

# Test merchant APIs with performance benchmarks
python3 manual_testing/scripts/merchant_api_tester.py --include-performance
```

### Interactive API Documentation & Testing
Visit `/api-docs` in your running application for:
- **🏪 Live Merchant API Testing**: Interactive testing interface with validation
- **📝 Request Templates**: Pre-built templates for different merchant types
- **✅ Real-time Validation**: Request validation and error checking
- **📊 Response Analysis**: Detailed response inspection and timing
- **🔍 Testing Scenarios**: Guided testing workflows and best practices

### Elixir Testing Scripts
```bash
# Quick testing utilities
mix run manual_testing/quick_test.exs

# Manual testing procedures
mix run manual_testing/manual_test.exs

# International payment testing
mix run manual_testing/test_international_reqpay.exs
```

## 🛠️ Development

### Project Structure
```
lib/
├── da_product_app/                 # Core business logic
│   ├── transactions/              # Transaction management
│   ├── adapters/                  # External partner adapters
│   ├── foreign_exchange/          # FX rate services
│   └── repo.ex                    # Database interface
├── da_product_app_web/            # Web interface
│   ├── controllers/               # HTTP controllers
│   ├── live/                      # LiveView modules
│   ├── upi_xml_schema.ex         # UPI XML parsing
│   └── upi_transaction_manager.ex # Transaction orchestration
└── da_product_app_web.ex          # Web module entry point

config/                            # Configuration files
├── config.exs                     # Base configuration
├── dev.exs                        # Development settings
├── prod.exs                       # Production settings
└── test.exs                       # Test configuration

priv/
├── repo/migrations/               # Database migrations
└── static/                        # Static assets
```

### Key Modules

- **`UpiXmlSchema`**: Complete XML parsing for all UPI message types
- **`UpiTransactionManager`**: Transaction state machine and orchestration
- **`UpiInternationalService`**: International payment corridor handling
- **`TransactionService`**: Core transaction business logic
- **Partner Adapters**: Flexible integration with international partners

### Configuration

#### Environment Variables
```bash
# Database
DATABASE_URL="mysql://username:password@localhost/mercury_upi_psp_dev"

# Security
SECRET_KEY_BASE="your-secret-key-base"
PHX_HOST="localhost"

# External Services
PARTNER_API_URL="https://api.partner.com"
PARTNER_API_KEY="your-partner-api-key"

# Monitoring
ENABLE_TELEMETRY=true
LOG_LEVEL=info

# Redis (when enabled for high-load scenarios)
REDIS_URL="redis://localhost:6379"
ENABLE_REDIS_CACHE=false
```

#### Database Configuration
```elixir
# config/dev.exs
config :da_product_app, DaProductApp.Repo,
  username: "root",
  password: "password",
  hostname: "localhost",
  database: "mercury_upi_psp_dev",
  pool_size: 10,
  adapter: Ecto.Adapters.MyXQL

# Redis configuration (when enabled for high-load scenarios)
config :da_product_app, :redis,
  url: System.get_env("REDIS_URL") || "redis://localhost:6379",
  enabled: System.get_env("ENABLE_REDIS_CACHE") == "true"
```

## 🚀 Deployment

### Production Setup

1. **Environment Configuration**
   ```bash
   export MIX_ENV=prod
   export DATABASE_URL="mysql://username:password@host:3306/mercury_upi_psp_prod"
   export SECRET_KEY_BASE="..."
   # Enable Redis for production high-load scenarios
   export REDIS_URL="redis://redis-host:6379"
   export ENABLE_REDIS_CACHE=true
   ```

2. **Build Release**
   ```bash
   mix deps.get --only prod
   MIX_ENV=prod mix compile
   MIX_ENV=prod mix assets.deploy
   MIX_ENV=prod mix release
   ```

3. **Database Migration**
   ```bash
   _build/prod/rel/da_product_app/bin/da_product_app eval "DaProductApp.Release.migrate"
   ```

4. **Start Production Server**
   ```bash
   _build/prod/rel/da_product_app/bin/da_product_app start
   ```

### Docker Deployment
```dockerfile
# Production Dockerfile example
FROM elixir:1.17-alpine AS build
# ... build steps ...

FROM alpine:3.18
RUN apk add --no-cache openssl ncurses-libs libstdc++
COPY --from=build /app/_build/prod/rel/da_product_app ./
EXPOSE 4000
CMD ["./bin/da_product_app", "start"]
```

### Health Checks
The application provides health check endpoints:

- **Application Health**: `GET /health`
- **Database Health**: `GET /health/db`
- **Partner Connectivity**: `GET /health/partners`
- **Redis Health**: `GET /health/redis` (when enabled)

### Scaling Strategy

#### Current Setup (< 100K daily transactions)
- **Primary Database**: MySQL 8.0+ for all transactional data
- **Job Processing**: Oban with MySQL backend for background jobs
- **Caching**: Application-level caching with ETS tables

#### High-Load Setup (> 100K daily transactions)
When transaction volume exceeds 100,000 per day, the following components are activated:

- **Redis Caching Layer**: 
  - QR code validation cache (TTL: 5 minutes)
  - Partner API response cache (TTL: 1 minute)
  - FX rate cache (TTL: 30 seconds)
  - Session management for high-frequency partners

- **Database Optimization**:
  - Read replicas for reporting queries
  - Connection pooling optimization
  - Query result caching for frequent lookups

- **Performance Monitoring**:
  - Real-time transaction volume tracking
  - Automatic Redis enablement based on load thresholds
  - Performance alerts and scaling recommendations

## 📊 Monitoring & Observability

### Telemetry Events
The application emits comprehensive telemetry events:

- `[:upi, :transaction, :start]`
- `[:upi, :transaction, :stop]`
- `[:upi, :payment, :processed]`
- `[:partner, :api, :request]`
- `[:database, :query, :duration]`

### Logging
Structured logging with correlation IDs:

```elixir
Logger.info("Payment processed", %{
  org_txn_id: "TXN123456",
  amount: "100.00",
  currency: "USD",
  partner: "sandbox",
  duration_ms: 95
})
```

### Metrics Dashboard
Access real-time metrics at: `http://localhost:4000/dashboard`

## 🔒 Security

### Compliance
- **NPCI Guidelines**: Full compliance with UPI specifications
- **PCI DSS**: Payment card industry standards
- **ISO 27001**: Information security management
- **Data Protection**: GDPR and local privacy regulations

### Security Features
- End-to-end encryption for all payment data
- API authentication and authorization
- Rate limiting and DDoS protection
- Audit logging for all transactions
- Secure key management
- Regular security assessments

## 🤝 Contributing

### Development Guidelines for Internal Developer

1. **Code Style**: Follow Elixir community conventions
2. **Testing**: Maintain >90% test coverage
3. **Documentation**: Document all public APIs
4. **Security**: Security review for all changes
5. **Performance**: Profile performance-critical paths

### Pull Request Process

1. Clone the repository
2. Create a feature branch
3. Write tests for new functionality
4. Ensure all tests pass
5. Submit pull request with detailed description

### Code Review Checklist

- [ ] Code follows Elixir style guidelines
- [ ] All tests pass
- [ ] Documentation is updated
- [ ] Security implications reviewed
- [ ] Performance impact assessed

## 📄 License

**Proprietary License** - This software is proprietary . 

For licensing inquiries, contact: [licensing@momentpay.in](mailto:licensing@momentpay.in)

## 📞 Support

### Technical Support
- **Email**: [support@momentpay.in](mailto:support@momentpay.in)
- **Documentation**: [Internal Documentation Portal](https://momentpay.in)
- **Slack**: #momentpay

### Emergency Contact
- **24/7 Hotline**: +1-XXX-XXX-XXXX
- **Incident Response**: [incident@momentpay.in](mailto:incident@momentpay.in)

## 📈 Roadmap

### Current Version: v1.0.0
- ✅ Complete NPCI UPI API implementation
- ✅ International payment corridors
- ✅ Real-time transaction processing
- ✅ Partner adapter framework

### Upcoming Features
- 🔄 **v1.1.0**: Enhanced fraud detection
- 🔄 **v1.2.0**: Mobile SDK for partner integration
- 🔄 **v1.3.0**: Advanced analytics dashboard
- 🔄 **v2.0.0**: Multi-tenant architecture

---

**Built with ❤️ by the MomentPay Team using [Erlang - Elixir - Phoenix]**
