# LuckyChit - Technical Architecture Document

## System Architecture Overview

### High-Level Architecture
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Mobile App    │    │   Web Dashboard │    │   Admin Panel   │
│   (Flutter)     │    │   (React)       │    │   (React)       │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 │
                    ┌─────────────────┐
                    │   API Gateway   │
                    │   (Kong/Nginx)  │
                    └─────────────────┘
                                 │
                    ┌─────────────────┐
                    │   Load Balancer │
                    │   (AWS ALB)     │
                    └─────────────────┘
                                 │
         ┌───────────────────────┼───────────────────────┐
         │                       │                       │
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  Auth Service   │    │  Payment Service│    │  Lottery Service│
│  (Node.js)      │    │  (Node.js)      │    │  (Node.js)      │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 │
                    ┌─────────────────┐
                    │   PostgreSQL    │
                    │   (Primary DB)  │
                    └─────────────────┘
                                 │
                    ┌─────────────────┐
                    │     Redis       │
                    │   (Cache/Queue) │
                    └─────────────────┘
```

## Microservices Architecture

### 1. Authentication Service
**Purpose**: Handle user authentication, KYC verification, and session management

**Key Components**:
- JWT token generation and validation
- OTP-based authentication
- Aadhaar/PAN verification integration
- Session management with Redis
- Role-based access control (RBAC)

**API Endpoints**:
```
POST /auth/register
POST /auth/login
POST /auth/verify-otp
POST /auth/kyc/verify-aadhaar
POST /auth/kyc/verify-pan
POST /auth/refresh-token
DELETE /auth/logout
```

### 2. Payment Service
**Purpose**: Handle all payment-related operations and integrations

**Key Components**:
- Razorpay integration
- UPI payment processing
- Payment status tracking
- Refund management
- Payment analytics

**API Endpoints**:
```
POST /payments/create-order
POST /payments/process-upi
GET /payments/status/:id
POST /payments/refund
GET /payments/history
POST /payments/webhook
```

### 3. Lottery Service
**Purpose**: Handle lottery draw execution and result management

**Key Components**:
- Provably fair algorithm implementation
- Draw scheduling and execution
- Result verification and broadcasting
- Audit trail management
- Winner notification system

**API Endpoints**:
```
POST /lottery/initiate-draw
GET /lottery/eligible-members
POST /lottery/execute-draw
GET /lottery/results/:drawId
GET /lottery/verify-result/:drawId
GET /lottery/history
```

### 4. Chit Group Service
**Purpose**: Manage chit group operations and member management

**Key Components**:
- Group creation and configuration
- Member invitation and approval
- Group status tracking
- Commission calculation
- Group analytics

**API Endpoints**:
```
POST /groups/create
GET /groups/:id
PUT /groups/:id
POST /groups/:id/invite
POST /groups/:id/join
GET /groups/:id/members
PUT /groups/:id/members/:memberId
```

### 5. Notification Service
**Purpose**: Handle all notification and communication

**Key Components**:
- Push notifications (FCM)
- SMS notifications
- Email notifications
- In-app notifications
- Notification preferences

**API Endpoints**:
```
POST /notifications/send
POST /notifications/bulk
GET /notifications/history
PUT /notifications/preferences
POST /notifications/subscribe
```

## Database Schema Design

### Core Tables

#### Users Table
```sql
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    mobile_number VARCHAR(15) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE,
    full_name VARCHAR(255) NOT NULL,
    profile_photo_url TEXT,
    aadhaar_number VARCHAR(12),
    pan_number VARCHAR(10),
    kyc_status ENUM('pending', 'verified', 'rejected') DEFAULT 'pending',
    bank_account_details JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);
```

#### Chit Groups Table
```sql
CREATE TABLE chit_groups (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    total_value DECIMAL(15,2) NOT NULL,
    monthly_installment DECIMAL(15,2) NOT NULL,
    duration_months INTEGER NOT NULL,
    max_members INTEGER NOT NULL,
    foreman_commission_percentage DECIMAL(5,2) NOT NULL,
    draw_date INTEGER NOT NULL, -- Day of month
    status ENUM('forming', 'active', 'completed', 'cancelled') DEFAULT 'forming',
    foreman_id UUID REFERENCES users(id),
    invite_code VARCHAR(10) UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

#### Group Members Table
```sql
CREATE TABLE group_members (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    group_id UUID REFERENCES chit_groups(id),
    user_id UUID REFERENCES users(id),
    status ENUM('pending', 'active', 'suspended', 'removed') DEFAULT 'pending',
    joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(group_id, user_id)
);
```

#### Monthly Draws Table
```sql
CREATE TABLE monthly_draws (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    group_id UUID REFERENCES chit_groups(id),
    month INTEGER NOT NULL,
    year INTEGER NOT NULL,
    draw_date TIMESTAMP NOT NULL,
    eligible_members JSONB NOT NULL,
    winner_id UUID REFERENCES users(id),
    prize_amount DECIMAL(15,2),
    server_seed VARCHAR(255),
    client_seed VARCHAR(255),
    nonce INTEGER,
    result_hash VARCHAR(255),
    status ENUM('pending', 'completed', 'cancelled') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(group_id, month, year)
);
```

#### Payments Table
```sql
CREATE TABLE payments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    group_id UUID REFERENCES chit_groups(id),
    user_id UUID REFERENCES users(id),
    month INTEGER NOT NULL,
    year INTEGER NOT NULL,
    amount DECIMAL(15,2) NOT NULL,
    payment_method ENUM('upi', 'net_banking', 'card') NOT NULL,
    transaction_id VARCHAR(255),
    status ENUM('pending', 'success', 'failed', 'refunded') DEFAULT 'pending',
    paid_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(group_id, user_id, month, year)
);
```

#### Payouts Table
```sql
CREATE TABLE payouts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    draw_id UUID REFERENCES monthly_draws(id),
    winner_id UUID REFERENCES users(id),
    amount DECIMAL(15,2) NOT NULL,
    bank_transaction_id VARCHAR(255),
    status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
    paid_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## Provably Fair Lottery Algorithm

### Implementation Details

```javascript
const crypto = require('crypto');

class ProvablyFairLottery {
  constructor() {
    this.serverSeed = this.generateServerSeed();
    this.serverSeedHash = this.hashSeed(this.serverSeed);
  }

  generateServerSeed() {
    return crypto.randomBytes(32).toString('hex');
  }

  hashSeed(seed) {
    return crypto.createHash('sha256').update(seed).digest('hex');
  }

  generateResult(clientSeed, nonce, eligibleMembers) {
    const combined = this.serverSeed + clientSeed + nonce.toString();
    const hash = crypto.createHash('sha256').update(combined).digest('hex');
    
    // Use first 8 characters of hash to generate random number
    const randomNumber = parseInt(hash.substring(0, 8), 16);
    
    // Map to eligible member index
    const winnerIndex = randomNumber % eligibleMembers.length;
    
    return {
      winnerId: eligibleMembers[winnerIndex].id,
      serverSeed: this.serverSeed,
      serverSeedHash: this.serverSeedHash,
      clientSeed,
      nonce,
      resultHash: hash,
      proof: {
        combined,
        randomNumber,
        winnerIndex
      }
    };
  }

  verifyResult(serverSeed, clientSeed, nonce, resultHash, eligibleMembers, winnerId) {
    const combined = serverSeed + clientSeed + nonce.toString();
    const calculatedHash = crypto.createHash('sha256').update(combined).digest('hex');
    
    if (calculatedHash !== resultHash) {
      return false;
    }
    
    const randomNumber = parseInt(calculatedHash.substring(0, 8), 16);
    const winnerIndex = randomNumber % eligibleMembers.length;
    
    return eligibleMembers[winnerIndex].id === winnerId;
  }
}
```

## Security Implementation

### 1. API Security
- **Rate Limiting**: Implement rate limiting using Redis
- **Input Validation**: Joi schema validation for all inputs
- **SQL Injection Prevention**: Parameterized queries only
- **CORS Configuration**: Strict CORS policies
- **API Versioning**: Version all APIs for backward compatibility

### 2. Authentication & Authorization
```javascript
// JWT Token Structure
const tokenPayload = {
  userId: user.id,
  role: user.role,
  permissions: user.permissions,
  iat: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60) // 24 hours
};

// Role-based Access Control
const permissions = {
  FOREMAN: ['create_group', 'manage_members', 'initiate_draw', 'manage_payouts'],
  MEMBER: ['join_group', 'make_payment', 'view_results', 'view_ledger'],
  ADMIN: ['manage_users', 'view_analytics', 'system_config']
};
```

### 3. Data Encryption
```javascript
// AES-256 Encryption for sensitive data
const crypto = require('crypto');

class DataEncryption {
  constructor(secretKey) {
    this.algorithm = 'aes-256-gcm';
    this.secretKey = Buffer.from(secretKey, 'hex');
  }

  encrypt(text) {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipher(this.algorithm, this.secretKey);
    cipher.setAAD(Buffer.from('lucky-chit', 'utf8'));
    
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    
    const authTag = cipher.getAuthTag();
    
    return {
      encrypted,
      iv: iv.toString('hex'),
      authTag: authTag.toString('hex')
    };
  }

  decrypt(encryptedData) {
    const decipher = crypto.createDecipher(this.algorithm, this.secretKey);
    decipher.setAAD(Buffer.from('lucky-chit', 'utf8'));
    decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'hex'));
    
    let decrypted = decipher.update(encryptedData.encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
  }
}
```

## Deployment Architecture

### AWS Infrastructure

#### Compute Layer
- **EC2 Auto Scaling Groups**: For application servers
- **ECS Fargate**: For containerized services
- **Lambda Functions**: For serverless operations

#### Data Layer
- **RDS PostgreSQL**: Primary database with Multi-AZ deployment
- **ElastiCache Redis**: Caching and session storage
- **S3**: File storage and backups

#### Network Layer
- **VPC**: Private subnets for application servers
- **ALB**: Application Load Balancer for traffic distribution
- **CloudFront**: CDN for static assets
- **Route 53**: DNS management

#### Monitoring & Logging
- **CloudWatch**: Application and infrastructure monitoring
- **CloudTrail**: API call logging
- **X-Ray**: Distributed tracing
- **SNS**: Alert notifications

### CI/CD Pipeline

```yaml
# GitHub Actions Workflow
name: Deploy LuckyChit

on:
  push:
    branches: [main, develop]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run Tests
        run: npm test
        
  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Build Docker Images
        run: docker build -t luckychit:${{ github.sha }} .
        
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to AWS
        run: |
          aws ecs update-service --cluster luckychit --service api --force-new-deployment
```

## Performance Optimization

### 1. Database Optimization
- **Indexing Strategy**: Composite indexes for common queries
- **Query Optimization**: Use EXPLAIN ANALYZE for slow queries
- **Connection Pooling**: PgBouncer for connection management
- **Read Replicas**: For read-heavy operations

### 2. Caching Strategy
```javascript
// Multi-layer caching
const cacheLayers = {
  L1: 'In-memory (Node.js)', // Session data, user info
  L2: 'Redis', // API responses, payment status
  L3: 'CDN', // Static assets, images
  L4: 'Database' // Persistent data
};

// Cache invalidation strategy
const cacheInvalidation = {
  'user:profile': 'TTL: 1 hour',
  'group:members': 'TTL: 30 minutes',
  'payment:status': 'TTL: 5 minutes',
  'lottery:results': 'TTL: 24 hours'
};
```

### 3. API Performance
- **Response Compression**: Gzip compression for all responses
- **Pagination**: Implement cursor-based pagination
- **GraphQL**: For complex data fetching
- **CDN**: For static assets and API responses

## Monitoring & Alerting

### Key Metrics
```javascript
const metrics = {
  // Application Metrics
  'api.response_time': 'p95 < 500ms',
  'api.error_rate': '< 1%',
  'payment.success_rate': '> 99%',
  'lottery.draw_time': '< 30 seconds',
  
  // Business Metrics
  'users.active_daily': 'Track growth',
  'groups.created_monthly': 'Track adoption',
  'payments.volume_daily': 'Track revenue',
  
  // Infrastructure Metrics
  'cpu.utilization': '< 70%',
  'memory.utilization': '< 80%',
  'disk.usage': '< 85%',
  'database.connections': '< 80% of max'
};
```

### Alerting Rules
```yaml
alerts:
  - name: "High Error Rate"
    condition: "api.error_rate > 5%"
    duration: "5 minutes"
    action: "slack-notification"
    
  - name: "Payment Gateway Down"
    condition: "payment.success_rate < 90%"
    duration: "2 minutes"
    action: "pager-duty"
    
  - name: "Database High Load"
    condition: "database.connections > 90%"
    duration: "10 minutes"
    action: "email-notification"
```

This technical architecture provides a robust, scalable, and secure foundation for the LuckyChit application, ensuring it can handle the demands of a fintech application while maintaining transparency and trust.
