# NPCI UPI Rules Implementation Gap Analysis

## 🚨 CRITICAL GAPS IDENTIFIED

### 1. Transaction Type-Specific Validation (HIGH PRIORITY)

**Current Issue**: Our implementation uses generic field validation regardless of transaction type.

**NPCI Requirement**: Different mandatory fields based on txn type (PAY/COLLECT/DEBIT/CREDIT/REVERSAL)

**Required Fix**:
```elixir
# Need to add in UpiXmlSchema.ex
defp validate_req_pay_fields_by_type(data) do
  case data.txn_type do
    "PAY" ->
      validate_pay_transaction_fields(data)
    "COLLECT" ->
      validate_collect_transaction_fields(data)
    "DEBIT" ->
      validate_debit_transaction_fields(data)
    "CREDIT" ->
      validate_credit_transaction_fields(data)
    "REVERSAL" ->
      validate_reversal_transaction_fields(data)
    _ ->
      {:error, "Invalid transaction type"}
  end
end
```

### 2. Message ID & Transaction ID Format (HIGH PRIORITY)

**Current Issue**: Random ID generation instead of NPCI format

**NPCI Requirement**: 35 digits = 3-digit bank participation code + 32-digit UUID

**Required Fix**:
```elixir
# Need bank participation code from NPCI
@bank_participation_code "001"  # Mercury's assigned code

defp generate_npci_msg_id do
  uuid = :crypto.strong_rand_bytes(16) |> Base.encode16(case: :upper)
  "#{@bank_participation_code}#{uuid}"
end
```

### 3. Device Tag Validation (MEDIUM PRIORITY)

**Current Issue**: No device tag parsing or validation

**NPCI Requirement**: Comprehensive device validation for fraud prevention

**Required Fix**:
```elixir
defp validate_device_tags(data) do
  required_device_fields = [:mobile, :location, :ip, :type, :id, :os, :app]
  # Implement device-specific validation
end
```

### 4. Approval Number Generation (HIGH PRIORITY)

**Current Issue**: No approval number in successful responses

**NPCI Requirement**: 6-digit alphanumeric approval number for SUCCESS result

**Required Fix**:
```elixir
defp generate_approval_number do
  :crypto.strong_rand_bytes(3) |> Base.encode16(case: :upper)
end
```

### 5. Merchant Category Code Validation (MEDIUM PRIORITY)

**Current Issue**: No MCC validation

**NPCI Requirement**: 4-digit MCC for entities, "0000" for individuals

**Required Fix**:
```elixir
defp validate_merchant_code(type, code) do
  case type do
    "PERSON" -> code == "0000"
    "ENTITY" -> String.match?(code, ~r/^\d{4}$/) and code != "0000"
    _ -> false
  end
end
```

## 📊 Implementation Priority Matrix

| Rule Category | Priority | Impact | Implementation Effort |
|---------------|----------|--------|----------------------|
| Transaction Type Validation | HIGH | Critical for NPCI compliance | Medium |
| ID Format Compliance | HIGH | Required for interoperability | Low |
| Device Validation | MEDIUM | Fraud prevention | High |
| Approval Numbers | HIGH | Transaction completion | Low |
| MCC Validation | MEDIUM | Business compliance | Low |

## 🎯 Recommended Implementation Plan

### Phase 1 (Immediate - Week 1)
1. Fix Message ID and Transaction ID format to NPCI specification
2. Add approval number generation for successful transactions
3. Update version number to "2.0" in all responses

### Phase 2 (Week 2)
1. Implement transaction type-specific field validation
2. Add MCC validation logic
3. Enhance error handling for rule violations

### Phase 3 (Week 3-4)
1. Implement comprehensive device tag validation
2. Add merchant tag validation for entities
3. Complete rule coverage testing

## ✅ Already Compliant Rules

- Timestamp format (Rule 020)
- Basic XML structure
- Error code mapping
- Response structure
- Basic field validation

## 🔧 Quick Fixes Needed

```elixir
# Update in UpiXmlSchema.ex
def generate_resp_val_qr(response_data) do
  xml = """
  <?xml version="1.0" encoding="UTF-8"?>
  <RespValQr>
    <Head ver="2.0" ts="#{get_timestamp()}" orgId="#{response_data.org_id}" msgId="#{generate_npci_msg_id()}"/>
    <Resp reqMsgId="#{response_data.req_msg_id}" result="#{response_data.result}" errCode="#{response_data.err_code}" approvalNum="#{response_data.approval_num}"/>
    <!-- Rest of XML -->
  </RespValQr>
  """
end
```

This analysis shows our implementation covers basic functionality but needs rule-specific validation enhancements for full NPCI compliance.
