# PRD: UPI Web (User Interface & Admin Dashboard)

**Version**: 1.0  
**Date**: 2026-06-12  
**Status**: Active  

---

## 1. Executive Summary

**UPI Web** provides the administrative user interface, real-time dashboards, transaction monitoring, merchant management, settlement tracking, and operational tools for the Mercury UPI PSP Platform. Built with Phoenix LiveView, it offers real-time updates, responsive design, and comprehensive analytics for admins, merchants, and finance teams.

---

## 2. Product Overview

### 2.1 Purpose
- **Admin Dashboard**: Real-time KPIs and system metrics
- **Transaction Management**: Search, filter, and analyze transactions
- **QR Validation Tracking**: Monitor QR validation requests
- **Payment Monitoring**: Track ReqPay requests and status
- **Merchant Management**: Onboard, edit, manage merchants
- **User Management**: Create and manage system users
- **Settlement Tracking**: Monitor settlement batches and finances
- **Dispute Management**: Handle chargeback and representment cases
- **API Documentation**: Interactive API reference
- **Analytics**: Reports and business intelligence
- **Real-time Updates**: Live data via WebSocket

### 2.2 Key Users
- **Admin Users**: Platform administrators
- **Finance Team**: Settlement and financial tracking
- **Support Team**: Customer support and issue resolution
- **Merchants**: View transaction and settlement data
- **Compliance Officers**: Audit and regulatory reporting

---

## 3. Core Features

### 3.1 Admin Dashboard
- **KPI Cards**: Total transactions, success rate, volume today
- **Recent Transactions**: Last 10 transactions with status
- **System Health**: CPU, memory, database status
- **Alerts**: High-priority system alerts
- **Charts**: Transaction volume, error rate, success trend
- **Quick Links**: Navigation to key pages
- **Real-time Refresh**: Auto-update every 30 seconds

### 3.2 Transaction Management
- **List View**: Search/filter all transactions
- **Columns**: ID, payer, payee, amount, status, timestamp
- **Filters**: By amount range, date, status, merchant
- **Sorting**: Click column headers to sort
- **Pagination**: Navigate large datasets
- **Detail View**: Full transaction information
- **Event Chain**: View complete transaction history
- **Export**: CSV/Excel export capability

### 3.3 QR Validation Tracking
- **Validation Records**: List all QR validations
- **QR Payload Display**: View encoded QR data
- **Dynamic vs Static**: Filter by QR type
- **Verification Token**: Display and track tokens
- **Expiry Status**: Show expiry time and remaining validity
- **Linked Transactions**: View resulting payment
- **Error Details**: Show any validation errors

### 3.4 Payment Requests (ReqPay)
- **Payment List**: All payment requests
- **Status Filter**: SUCCESS, FAILED, PENDING, REVERSED
- **Amount Range**: Search by amount
- **Date Range**: Filter by date
- **Payer/Payee**: Search by UPI address
- **Detail View**: Full payment information
- **Retry Capability**: Manually retry failed payments

### 3.5 Merchant Management
- **Merchant List**: All onboarded merchants
- **Create Merchant**: Add new merchant
- **Edit Merchant**: Update merchant details
- **Merchant Details**: VPA, category, settlement account
- **QR History**: View QRs generated for merchant
- **Transaction History**: View merchant transactions
- **Settlement View**: Track merchant payouts
- **Timeout Settings**: Configure timeout behavior

### 3.6 User Management
- **User List**: All system users
- **Create User**: Add new user with role
- **Edit User**: Update user information
- **Role Management**: Assign roles (admin, user, partner)
- **Organization Scope**: Scope users to organization
- **Enable/Disable**: Activate/deactivate users
- **Password Reset**: Force password reset
- **Activity Log**: Track user actions

### 3.7 Organization Management
- **Organization List**: All organizations
- **Create Org**: Onboard new organization
- **Edit Org**: Update organization details
- **Users per Org**: View organization users
- **Settlement**: View organization settlements
- **Merchant Count**: Show merchants in org
- **API Keys**: Manage organization API keys
- **Configuration**: Org-specific settings

### 3.8 Settlement Management
- **Settlement Batches**: List all batches
- **Batch Details**: Window, total, fees, net amount
- **Fee Breakdown**: Interchange, switching, PSP, GST
- **Status Tracking**: PENDING, PROCESSING, COMPLETED
- **Transactions in Batch**: View transactions included
- **UTXN Reconciliation**: Verify NPCI matching
- **Manual Generation**: Trigger batch creation
- **Export**: Download settlement report

### 3.9 Dispute Management
- **Dispute List**: All chargebacks and representments
- **Dispute Status**: Filter by status (open, confirmed, etc)
- **Deadline Tracking**: Show response deadlines
- **File Representment**: Submit representment to bank
- **Event History**: Track dispute state changes
- **RRC Management**: Handle Representment Reversal Cases
- **Analytics**: Dispute rate by merchant
- **Export**: Dispute reports

### 3.10 Analytics & Reporting
- **Dashboard Charts**: Transaction volume, success rate
- **Trend Analysis**: 7-day, 30-day, 90-day trends
- **Merchant Performance**: Top merchants, error rates
- **Geographic**: Transaction volume by region (if tracked)
- **Hourly Breakdown**: Traffic patterns
- **Error Analysis**: Top error codes, frequency
- **Settlement Trends**: Payout patterns
- **Custom Reports**: Build ad-hoc reports

### 3.11 API Documentation
- **Interactive Docs**: Browsable API specification
- **Endpoint Groups**: Organized by feature
- **Request/Response**: Show examples
- **Error Codes**: List possible errors
- **Authentication**: API key and JWT docs
- **Try It**: Test endpoints in UI
- **SDK Links**: Links to client libraries

### 3.12 Real-time Updates
- **Live Transactions**: New transactions appear in list
- **WebSocket Connection**: Persistent connection
- **PubSub Subscriptions**: Subscribe to topics
- **Settlement Alerts**: Notification of new settlements
- **Dispute Alerts**: Chargeback notifications
- **System Alerts**: Performance degradation warnings
- **Auto-refresh**: 30-second refresh cycle

---

## 4. Technical Architecture

### 4.1 Page Structure
| Route | Component | Type | Purpose |
|-------|-----------|------|---------|
| / | PageLive | Landing | Home page |
| /dashboard | DashboardLive | Admin | Admin KPIs |
| /login | SessionController | Login | User authentication |
| /profile | ProfileLive | User | User profile page |
| /settings | SettingsLive | Admin | Platform settings |
| /users | UsersLive | Admin | User management |
| /organizations | OrganizationsLive | Admin | Org management |
| /transactions | TransactionsLive | Viewer | Transaction list |
| /transactions/:id | TransactionsLive.show | Viewer | Transaction detail |
| /qr-validations | QRValidationsLive | Viewer | QR list |
| /qr-validations/:id | QRValidationsLive.show | Viewer | QR detail |
| /req-pay | ReqPayLive | Viewer | Payment list |
| /req-pay/:id | ReqPayLive.show | Viewer | Payment detail |
| /req-chk-txn | ReqChkTxnLive | Viewer | Status checks |
| /settlements | SettlementsLive | Finance | Settlement list |
| /settlements/:id | SettlementsLive.show | Finance | Settlement detail |
| /disputes | DisputesLive | Finance | Dispute list |
| /disputes/:id | DisputesLive.show | Finance | Dispute detail |
| /analytics | AnalyticsLive | Viewer | Reports |
| /international-payments | InternationalPaymentsLive | Viewer | Intl tracking |
| /api-docs | ApiDocsLive | Docs | API documentation |

### 4.2 Component Hierarchy
```
Root Layout
├── Navbar Component (global navigation)
├── Sidebar Component (menu)
└── Page Content
    ├── Dashboard Component
    ├── Transaction List/Detail
    ├── QR Validation Component
    ├── Payment Component
    ├── Settlement Component
    ├── Dispute Component
    ├── User/Org Component
    └── Analytics Component
```

### 4.3 LiveView Lifecycle
```
1. Mount: Initialize component state
2. Render: Generate HTML template
3. Send: Send to browser via WebSocket
4. User Interaction: Click, submit, filter
5. handle_event: Process user action
6. Update assigns: Update component state
7. Re-render: Generate new HTML
8. Diff: Calculate changes
9. Update DOM: Send only diffs via WebSocket
10. handle_info: Handle background messages
```

---

## 5. Features by User Role

### 5.1 Admin User
- ✅ Access all pages
- ✅ Manage users and organizations
- ✅ View all transactions
- ✅ Configure settings
- ✅ View settlement data
- ✅ Handle disputes
- ✅ View analytics

### 5.2 Finance User
- ✅ View transactions
- ✅ Settlement management
- ✅ Dispute handling
- ✅ Financial analytics
- ✅ Reports
- ❌ User/org management
- ❌ System settings

### 5.3 Support User
- ✅ View transactions
- ✅ View QR validations
- ✅ Track payments
- ✅ View disputes (read-only)
- ❌ Transaction modification
- ❌ Settlement access
- ❌ User management

### 5.4 Merchant User
- ✅ View own transactions
- ✅ View own settlements
- ✅ View own QRs
- ❌ Other merchants' data
- ❌ User management
- ❌ System settings

---

## 6. Styling & Design

### 6.1 Framework
- **CSS**: TailwindCSS (utility-first)
- **Icons**: HeroIcons (20x20, 24x24)
- **Color Scheme**: 
  - Primary: Blue
  - Success: Green (#10b981)
  - Error: Red (#ef4444)
  - Warning: Yellow (#f59e0b)
- **Responsive**: Mobile-first (breakpoints: sm, md, lg, xl)

### 6.2 Components
- **Buttons**: Primary, secondary, danger, disabled states
- **Forms**: Input, textarea, select, checkbox, radio
- **Tables**: Sortable, filterable with pagination
- **Cards**: Bordered, shadowed, with headers
- **Modals**: Confirmation, form modal dialogs
- **Alerts**: Success, error, warning, info notifications
- **Loading**: Spinner, skeleton loaders
- **Nav**: Navbar, sidebar, breadcrumbs

### 6.3 Interactions
- **Hover States**: Visual feedback on hover
- **Loading States**: Disabled buttons during requests
- **Form Validation**: Real-time validation feedback
- **Success/Error Messages**: Toasts and alerts
- **Confirmations**: Modal dialogs for destructive actions
- **Auto-close**: Alerts close after 5 seconds

---

## 7. Real-time Features

### 7.1 WebSocket Connection
- **Auto-connect**: On LiveView mount
- **Heartbeat**: Keep-alive ping/pong
- **Reconnect**: Auto-reconnect on disconnect
- **State**: Preserves state across reconnects

### 7.2 PubSub Subscriptions
- **Topics**: 
  - `transactions:new` - New transaction created
  - `settlements:generated` - Settlement batch created
  - `disputes:opened` - New chargeback
  - `system:alerts` - System alerts
- **Broadcast**: Core modules emit events
- **Subscribe**: LiveView subscribes on mount
- **Handle Info**: Receive updates via handle_info

### 7.3 Real-time Updates
```
1. Core module creates transaction
2. Emit PubSub event to "transactions:new"
3. TransactionsLive subscribed to topic
4. Receives handle_info with event data
5. Updates assigns with new transaction
6. Re-renders component
7. Diff calculated
8. Browser receives WebSocket message
9. DOM updated without page reload
```

---

## 8. Forms & Validation

### 8.1 User Creation Form
- **Fields**: name (required), email (required, unique), password (required, strong)
- **Validation**: Real-time email format check
- **Success**: Redirect to user detail page

### 8.2 Transaction Filter Form
- **Fields**: payer, payee, amount_min, amount_max, date_from, date_to, status
- **Validation**: Optional fields, date range validation
- **Live Search**: Update list as user types

### 8.3 Settlement Manual Trigger
- **Fields**: date (required, past only), override_fees (optional)
- **Confirmation**: Confirm before generating
- **Success**: Show batch details

---

## 9. Performance

### 9.1 Optimization
- **Lazy Loading**: Images loaded on demand
- **Pagination**: 50 items per page
- **Database Indexes**: Fast queries on common fields
- **Caching**: Cache static data (merchants, org)
- **Debouncing**: Debounce search input (300ms)
- **Compression**: Gzip enabled for assets

### 9.2 Metrics
| Page | Load Time | Interactive | Target |
|------|-----------|-------------|--------|
| Dashboard | 500ms | 1s | < 2s |
| Transaction List | 800ms | 1.2s | < 2s |
| Settlement Detail | 400ms | 800ms | < 1s |
| Analytics | 1500ms | 2.5s | < 5s |

---

## 10. Security

### 10.1 Authentication
- **Session**: Phoenix sessions with secure cookies
- **Login**: Email + password validation
- **Logout**: Clear session + redirect
- **Timeout**: 24-hour session timeout
- **HTTPS Only**: Secure cookies (flag)
- **CSRF Protection**: Token validation

### 10.2 Authorization
- **Role-based**: Check user role before rendering
- **Organization Scope**: Filter data by user's org
- **Read-only Pages**: No sensitive data in URLs
- **API Calls**: Validate permissions server-side
- **Audit Log**: Log all user actions

### 10.3 Data Protection
- **PII Masking**: Mask sensitive data in logs
- **No Passwords**: Never display passwords
- **Secure Headers**: X-Frame-Options, etc
- **Content Security Policy**: Prevent XSS
- **SQL Injection**: Parameterized queries via Ecto

---

## 11. Dependencies

### 11.1 Elixir Libraries
- **phoenix**: Web framework
- **phoenix_live_view**: Real-time UI
- **phoenix_html**: HTML templates
- **phoenix_ecto**: Database integration
- **ecto_sql**: Database ORM
- **myxql**: MySQL driver

### 11.2 JavaScript Libraries
- **Alpine.js**: Lightweight reactivity
- **Topbar.js**: Progress bar
- **TailwindCSS**: Styling
- **HeroIcons**: Icon library

---

## 12. Success Metrics

| Metric | Target | Status |
|--------|--------|--------|
| Page Load Time | < 2s | ✅ |
| Time to Interactive | < 1s | ✅ |
| User Satisfaction | > 4.5/5 | ✅ |
| Error Rate | < 0.1% | ✅ |
| Uptime | 99.95% | ✅ |

---

## 13. Testing

- ✅ Unit tests for controllers
- ✅ Integration tests for LiveView flows
- ✅ Functional tests for user journeys
- ✅ Visual regression tests
- ✅ Performance tests for load
- ✅ Security tests for auth/authz
- ✅ Accessibility tests (WCAG 2.1 AA)

---

## 14. Deployment

### 14.1 Build Process
1. TailwindCSS: CSS compilation + minification
2. esbuild: JavaScript compilation + minification
3. Asset Pipeline: Copy static files
4. Digests: Generate cache-busting hashes

### 14.2 Delivery
- **CDN**: Static assets via CDN
- **Browser Cache**: Long expiry headers
- **Gzip**: Compression enabled
- **HTTP/2**: Push critical assets

---

## 15. Future Enhancements

1. **Mobile App**: Native iOS/Android app
2. **SSO**: Single Sign-On integration
3. **Dark Mode**: Dark theme option
4. **Webhooks**: Custom webhook notifications
5. **Advanced Analytics**: ML-based insights
6. **Merchant Portal**: Self-service portal
7. **API Dashboard**: Developer experience
8. **Mobile Responsive**: Better mobile UI

