# Telegram Mini App - Requirements & Specifications

## Project Overview

A Telegram Mini App that enables users to participate in a gaming campaign investment program with a multi-level referral system. The app will auto-register users on first launch and provide daily rewards based on investment tiers.

**Related Documents:**
- **MLM Business Rules:** See `/docs/mlm-business-rules.md` for investment tiers, commission structures, and deposit/withdrawal rules (business-focused with tables)
- **Frontend Architecture:** See `/docs/frontend-architecture.md` for detailed frontend technology stack and implementation guidance
- **Backend Architecture:** See `/docs/backend-architecture.md` for Django backend architecture and implementation details

---

## Core Requirements

### 1. User Registration & Authentication

**Requirements:**
- Auto-register users on first launch using Telegram user details
- Store user information from Telegram (user ID, username, first name, last name, etc.)
- Maintain user session state

**Decisions:**
- **Telegram user data to capture:** All available data (user_id, username, first_name, last_name, language_code, photo_url)
- **Multiple devices/sessions:** Yes, support multiple devices/sessions for the same user
- **Additional verification:** No email or phone number verification required beyond Telegram auth
- **Deleted Telegram account:** No action required if a user deletes their Telegram account

---

### 2. Referral System

**Requirements:**
- Users can share referral links
- Users can send direct invites via Telegram (UI only)
- Track referral relationships (all levels tracked, commission calculation up to 3 levels)
- Calculate referral commissions based on referrals' daily earnings

**Referral Commission Structure:**
- See `/docs/mlm-business-rules.md` for complete commission structure table
- Level 1: 50% of referral's daily earning
- Level 2: 30% of referral's daily earning
- Level 3: 20% of referral's daily earning

**Decisions:**
- **Referral link format:** `https://t.me/botname?start=REF123456` (standard Telegram deep link format)
- **Referral code generation:** Random 10-character code using combination of 0-9 and a-z (lowercase). Unique index in database ensures uniqueness. On unique constraint violation during database insert, retry up to 10 times before failing. With 36 possible characters (0-9, a-z) and 10 characters length, collision probability is extremely low.
- **Link uniqueness:** Each user has one unique referral link
- **Link expiration:** No expiration - referral links are permanent
- **Link click behavior:** When a user clicks a referral link, they are redirected to the mini app immediately and auto-registered as a new user
- **Circular referral prevention:** If User A refers User B, and later User B tries to refer User A, the system will detect that User A is an existing user. No new registration will occur, and the app will load normally for User A
- **Invite mechanism:** UI only - users can send direct invites through the mini app interface (not via bot commands)
- **Referral source tracking:** No need to track whether referral came from link vs direct invite
- **Commission compounding:** No, commissions do not compound. Each commission payout is calculated independently based on each referral's daily reward earnings

**Referral Commission Calculation Example:**

Multi-level marketing structure where commissions are calculated based on each downline's daily reward earnings, paid up to 3 levels up the chain.

**Example Scenario:**
- User A recruits User B
- User B recruits User C
- User C recruits User D
- User D recruits User E

**When User E earns a daily reward of $100:**
- User D (Level 1 from E) receives: 50% of $100 = **$50**
- User C (Level 2 from E) receives: 30% of $100 = **$30**
- User B (Level 3 from E) receives: 20% of $100 = **$20**
- User A receives: **$0** (Level 4, beyond the 3-level limit)

**When User D earns a daily reward:**
- The same mechanism applies: User C gets 50%, User B gets 30%, User A gets 20%
- Each commission payout is tracked independently for each daily reward earned by each referral (downline)

**Key Points:**
- Commissions are calculated on the **daily reward amount** earned by the downline, not on the investment amount
- Each daily reward triggers a separate commission calculation up the chain (up to 3 levels)
- Commissions do not compound - Level 2 gets 30% of the downline's daily reward, not 30% of Level 1's commission

---

### 3. Credit Balance System

**Requirements:**
- Users have a credit balance account
- Credits can be used for investments
- Credits are credited from daily rewards and referral commissions
- All transactions must be tracked

**Financial Precision:**
- **Decimal precision:** 8 decimals for all financial amounts (balances, investments, rewards, commissions, deposits, withdrawals)
- **Rounding:** Round to nearest (standard rounding)
- **Rationale:** 8 decimals handles very small amounts and is crypto-friendly (matches most cryptocurrency precision standards)

**Decisions:**
- **Initial credit balance:** 0 (no welcome bonus)
- **Withdrawal:** Yes, users can withdraw credits via payment gateway (API will be provided later)
  - See `/docs/mlm-business-rules.md` for complete withdrawal rules table (minimum, fees, processing time, supported cryptocurrencies)
  - **Minimum withdrawal:** $10
  - **Withdrawal fees:** 1% of withdrawal amount + fixed fee ($3 for Tron, $2 for other blockchains)
  - **Processing time:** Within 5 business days
  - **Supported cryptocurrencies:** USDT on Tron and BNB
- **Deposit:** Yes, users can deposit credits via crypto payment gateway
  - See `/docs/mlm-business-rules.md` for complete deposit rules table (minimum, maximum, forfeiture, supported cryptocurrencies)
  - **Minimum deposit:** $5 (deposits less than $5 will be forfeited)
  - **Maximum deposit:** No maximum limit
  - **Supported cryptocurrencies:** USDT on Tron and BNB
  - System will request a unique deposit address before showing it to the user
  - Since crypto deposits are on-chain, the crypto payment gateway will callback on status
- **Transaction history:** Yes, all transactions must be tracked
- **Failed transactions:** Failed transactions are not stored in the database

**Wallet Transaction Lifecycle:**
- **Statuses:** `completed`, `cancelled`
- **Failed transactions:** Not stored in database (only successful and cancelled transactions are recorded)

**Deposit Transaction Lifecycle:**
- **Statuses:** `processing`, `completed`, `forfeited`
- **`processing`:** Payment gateway callback received on on-chain deposit
- **`completed`:** When number of confirmations exceeds certain threshold for specific blockchain
- **`forfeited`:** When deposit amount is less than minimum ($5)

**Withdrawal Transaction Lifecycle:**
- **Statuses:** `pending`, `processing`, `completed`, `cancelled`
- **`pending`:** Initial user request
- **`processing`:** Only applies when withdrawal is sent for automated processing via payment gateway API. For manual processing (amount larger than threshold, admin configurable), status changes directly to `completed` when admin manually processes it
- **`completed`:** Withdrawal successfully processed
- **`cancelled`:** User or admin request to cancel withdrawal. System automatically refunds the withdrawal amount (including fees) back to user's wallet upon cancellation

---

### 4. Gaming Campaign Investment

**Requirements:**
- Users can invest credits into the gaming campaign
- Investment amount determines tier classification
- Each investment is tracked independently (both daily reward percentage and duration)
- Daily rewards are calculated based on the tier of each individual investment
- Invested amount is not withdrawable - once invested, it generates daily rewards until the investment contract ends
- When an investment contract ends, no principal will be returned

**Investment Tiers, Daily Reward Rates & Contract Durations:**
- See `/docs/mlm-business-rules.md` for complete investment tiers table
- **Tier 1:** ≤ $100 (less than or equal to $100) → 1% daily → 120 days duration
- **Tier 2:** ≤ $500 (less than or equal to $500) → 1.5% daily → 130 days duration
- **Tier 3:** ≤ $1,000 (less than or equal to $1,000) → 2% daily → 140 days duration
- **Tier 4:** ≤ $2,000 (less than or equal to $2,000) → 2.5% daily → 150 days duration
- **Tier 5:** ≤ $5,000 (less than or equal to $5,000) → 3% daily → 160 days duration
- **Tier 6:** > $5,000 (greater than $5,000) → 3.5% daily → 180 days duration

**Decisions:**
- **Tier classification:** Based on USD equivalent
- **Minimum investment:** $10
- **Maximum investment:** No maximum limit per user
- **Multiple investments:** Yes, users can have multiple concurrent investments
- **Investment tracking:** Each investment is tracked independently with its own tier, reward rate, and duration
- **Partial withdrawal:** Not allowed - invested amounts cannot be withdrawn mid-cycle
- **Tier independence:** Since each investment is tracked independently, there is no upgrade/downgrade of tier. The percentage and duration follow per investment and are not lump sum. Each investment operates independently with its own tier classification

**Investment Transaction Lifecycle:**
- **Statuses:** `pending`, `active`, `completed`
- **`pending`:** Investment created, waiting for reward calculation to start
- **`active`:** Investment enters reward calculation phase (daily rewards are being calculated)
- **`completed`:** Reward calculation ended (investment contract duration completed)
- **Error handling/rollback:** Will be defined in technical specification

---

### 5. Daily Reward Calculation & Distribution

**Requirements:**
- First reward calculation starts at 00:00 on the day after investment
- Rewards are held for 24 hours before being credited
- Each investment has its own independent reward calculation cycle
- Each investment's reward is calculated independently based on its tier

**Reward Calculation Timing:**
- **Timezone:** UTC+8 hours
- **Investment timing example:** Investment made at 23:59:59 on the 5th will have the first calculation on 6th 00:00 (the next second), and will have the reward distributed on 7th 00:00
- **Calculation vs Distribution:** Although the reward is "calculated" on the 6th, the system actually calculates and distributes on the 7th 00:00
- **Daylight Saving Time:** No DST handling required
- **Weekends/Holidays:** Yes, rewards are calculated on weekends and holidays

**System Reliability:**
- **Cronjob mechanism:** A cronjob runs every 5 minutes
- When it's 00:00, the cronjob starts the calculation task and creates an entry in the database
- When the next 5-minute cronjob runs, it detects the job is already started and won't start it again
- This ensures that when the system is down and resumes, the cronjob will start for the day

**Investment Expiration:**
- When an investment contract ends, the last day's reward will be issued and distributed
- Commission for the last day's reward will be calculated immediately after the reward is distributed
- **Example:** Investment duration of 5 days, user invests on 5th Dec, first reward distribution at 7th Dec, last reward will be at 11th Dec, and commission for the 11th will be calculated as usual

**Decisions:**
- **Pending rewards display:** No, pending rewards (calculated but not yet credited) should not be shown to users
- **Multiple concurrent investments:** Each investment's reward is calculated independently based on its tier - Yes

---

### 6. Referral Commission Calculation

**Requirements:**
- See `/docs/mlm-business-rules.md` for complete commission structure and calculation rules
- Commissions are calculated based on referrals' daily earnings (not investment amount)
- Paid up to 3 levels
- Commission rates: Level 1 (50%), Level 2 (30%), Level 3 (20%)
- Each commission payout is tracked independently for each daily reward earned by each referral (downline)

**Commission Calculation Logic:**
- When a downline earns a daily reward, the system searches up the referral chain (up to 3 levels)
- Level 1 upline receives 50% of the downline's daily reward
- Level 2 upline receives 30% of the downline's daily reward
- Level 3 upline receives 20% of the downline's daily reward
- Commissions do NOT compound - each level receives a percentage of the original daily reward amount, not a percentage of the previous level's commission

**Example:**
If User E (downline) earns $100 daily reward:
- User D (Level 1) gets: 50% × $100 = $50
- User C (Level 2) gets: 30% × $100 = $30 (NOT 30% of $50)
- User B (Level 3) gets: 20% × $100 = $20 (NOT 20% of $30)

**Investment Contract Expiration:**
- When a referral's investment contract expires, the last day's reward will be issued and commission for that last day will be calculated as usual
- Commissions stop after the last day's reward is distributed, since there's no more daily reward generated
- Commissions are calculated based on generated daily rewards only

**Decisions:**
- **Commission calculation timing:** Same day, immediately after reward calculation
- **Commission crediting:** Immediately (no 24-hour hold period like daily rewards)
- **Commission calculation basis:** Gross daily reward (no fees deducted)
- **Pending commission display:** There should be no pending commission since it's distributed once it's calculated. However, the initial state of the commission is "pending". Once all commissions are calculated, the next process will distribute them. There might be a few minutes before it transitions from pending to distributed. In this case, we will show both the pending and distributed commissions to users

---

## Technical Architecture

### Backend

**Technology Stack:**
- **Framework:** Django (Python)
  - Excellent for financial calculations (decimal precision handling)
  - Strong built-in admin panel for monitoring transactions and investments
  - Django REST Framework for robust API development
  - Better suited for complex business logic (MLM calculations, tier management)
  - Strong security features out of the box
  - Good for cron-based scheduled tasks
- **Database:** MySQL
- **Job queue system:** Cronjob (no separate job queue system needed)
- **Cron job handling:** Manual cronjob settings in OS (system-level cron configuration)
- **Caching:** Not needed at the moment (can be added later if needed)
- **API rate limiting:** Yes, should be implemented

**Telegram Bot API Integration:**
- **Recommended approach:** Use official Telegram Bot API libraries
  - **For Django:** Use `python-telegram-bot` library or `aiogram` (async framework)
- **Key integration points:**
  - Validate Telegram Web App `initData` for authentication
  - Handle deep linking for referral links (`/start REF123456`)
  - Process user data from Telegram Mini App launch
  - Send notifications (optional, for future features)

**Webhook Endpoints:**
- **Yes, webhooks are recommended** for Telegram Bot API integration
- **Why webhooks:**
  - More efficient than polling (real-time updates)
  - Required for handling deep links and `/start` command parameters
  - Better for handling user interactions and commands
  - Lower server load compared to polling
  - Essential for proper referral link handling when users click referral links
- **Implementation:**
  - Set up webhook endpoint: `/webhook/telegram` or `/api/telegram/webhook`
  - Handle incoming updates (messages, callback queries, etc.)
  - Process `/start` command with referral parameters
  - Validate webhook requests using Telegram's secret token

**📄 Full Backend Architecture Documentation:** See `/docs/backend-architecture.md` for comprehensive Django implementation details, code examples, and architecture guidance.

### Frontend

**Technology Stack:**
- **Framework:** React 18+ with TypeScript (recommended)
- **Telegram Web App SDK:** Yes, essential for Telegram Mini App integration
- **Build Process:** Vite (recommended)
- **PWA Capabilities:** No
- **State Management:** Zustand (client state) + TanStack Query (server state)
- **Routing:** Yes, React Router v6

**📄 Full Frontend Architecture Documentation:** See `/docs/frontend-architecture.md` for comprehensive details, code examples, and implementation guidance.

---

## Infrastructure & Deployment

**Decisions:**
- **Hosting:** Cloud server (AWS, Google Cloud, Azure, or similar cloud provider)
- **SSL certificates:** Yes, using Let's Encrypt (will be set up manually on the server)
- **Backups:** Manual backup process (no automated backup system at this time)
- **Staging environment:** Manual setup (no automated staging deployment)
- **Expected user scale:** Tens of thousands of users (affects infrastructure decisions - need scalable architecture)

---

## Logging & Monitoring

**Decisions:**
- **Comprehensive logging:** Yes, comprehensive logging is required
- **User activity logging:** All user activities must be logged
- **Create/Update/Delete operations:** Record comprehensive data including:
  - **Request metadata:** User ID, IP address, timestamp, HTTP method, endpoint URL
  - **Query parameters:** All query string parameters (filters, pagination, sorting)
  - **Response metadata:** HTTP status code, response time, record count returned
  - **POST data:** Record all POST data and request body content
  - **Update operations:** When changing content, record the previous state (before update) and new state (after update)
  - **Filter criteria:** Record any filters applied (date ranges, user filters, status filters, etc.)
  - **Pagination info:** Page number, page size, total records (if applicable)
- **Retrieval operations:** Log comprehensive data for queryability in admin panel:
  - **Request metadata:** User ID, IP address, timestamp, HTTP method, endpoint URL
  - **Query parameters:** All query string parameters (filters, pagination, sorting)
  - **Response metadata:** HTTP status code, response time, record count returned
  - **Filter criteria:** Record any filters applied (date ranges, user filters, status filters, etc.)
  - **Pagination info:** Page number, page size, total records
  - **Purpose:** Enable admin panel to query logs by user, date range, endpoint, filters, etc.
  - **Note:** Database table information can be derived from the endpoint URL, so it doesn't need to be explicitly logged
- **Financial transactions:** All financial transactions must be logged (as part of audit logs)

---

## Security

**Decisions:**
- **Telegram Web App data validation (initData):** **YES, validation is REQUIRED and CRITICAL**
  - **Why validation is necessary:** Even though Telegram sends the data, it can be tampered with:
    - Data can be intercepted and modified in transit
    - Malicious clients can send fake initData
    - Without validation, attackers could impersonate users or access other users' accounts
  - **How Telegram's hash validation works:**
    - Telegram includes a `hash` parameter in the initData string
    - The hash is calculated by Telegram using HMAC-SHA-256 algorithm
    - **Hash calculation:** `HMAC-SHA-256(secret_key, data_check_string)`
      - `secret_key` = SHA-256 hash of your Bot Token (provided by Telegram)
      - `data_check_string` = All key-value pairs from initData (except the `hash` itself), sorted alphabetically, formatted as `key=value\n`
    - **Validation process:**
      1. Extract the `hash` from initData
      2. Remove `hash` from the data
      3. Sort remaining key-value pairs alphabetically
      4. Create `data_check_string` in format: `key1=value1\nkey2=value2\n...`
      5. Calculate `HMAC-SHA-256(secret_key, data_check_string)`
      6. Compare calculated hash with provided `hash` - they must match exactly
      7. Additionally check `auth_date` to ensure data isn't too old (recommend max 24 hours)
      8. Verify `user_id` matches the authenticated user
  - **Implementation:**
    - **Django:** Use `python-telegram-bot` library or implement custom validation
    - Always validate initData on the backend before trusting any user data
    - **Reference:** Telegram Bot API documentation for Web Apps - "Validating data received from the Web App"
- **CSRF protection:** Yes, CSRF protection should be implemented
  - Use framework-provided CSRF tokens for web forms
  - For API endpoints, use CSRF tokens or SameSite cookie attributes
  - Telegram Mini Apps should include CSRF tokens in API requests
- **Sensitive data encryption:**
  - **Passwords:** Hashed (using bcrypt, Argon2, or similar secure hashing algorithm)
  - **Data encryption analysis:**
    - **Balances/Transactions:** Not encrypted - database operations require direct queries and calculations (add/deduct operations). Encryption would prevent efficient database operations and queries.
    - **API keys/secrets/database credentials:** Stored in environment variables (not encrypted in database, but secured via environment variable management)
    - **Session tokens:** Handled by Django framework or third-party plugins (JWT tokens are signed, not encrypted)
    - **Personal Identifiable Information (PII):** User IDs, usernames, names - stored as plaintext for normal operations (can be encrypted if compliance requires)
    - **Referral codes:** Stored as plaintext for quick lookups (can be hashed if enumeration prevention is needed)
  - **Current encryption requirements:**
    - **At rest:** No encryption needed at the moment for the above data types
    - **In transit:** Use TLS/SSL for all API communications (HTTPS)
    - **Future considerations:** If compliance requirements change (GDPR, financial regulations), consider encrypting PII and implementing field-level encryption for sensitive data
- **API authentication tokens:** Yes, using JWT (JSON Web Tokens)
  - Generate JWT tokens after successful Telegram authentication
  - Include user_id, expiration time, and other necessary claims
  - Sign tokens with a secret key
  - **Token expiration:** 30 days
  - Implement token refresh mechanism if needed
- **Audit logs for financial transactions:** Yes, as mentioned in logging requirements above
  - All financial transactions (deposits, withdrawals, investments, rewards, commissions) must be logged
  - Include: user_id, transaction type, amount, timestamp, previous balance, new balance, transaction status
  - Record all POST data and state changes for financial operations
  - Maintain immutable audit trail for compliance and security purposes

---

## Edge Cases & Scenarios

### Investment Scenarios

1. **User invests $50 (Tier 1), then invests $60 more (Tier 1)**
   - Each investment is tracked independently
   - The $50 investment has its own 120-day contract at 1% daily
   - The $60 investment has its own 120-day contract at 1% daily
   - Both investments generate rewards independently

2. **User invests $600 (Tier 3), then that investment expires**
   - When the $600 investment expires, the last day's reward will be issued
   - Commission for the last day's reward will be calculated as usual
   - No principal is returned
   - Other active investments continue independently with their own tiers, reward rates, and durations
   - No tier recalculation needed since each investment operates independently
   - **Example:** Investment duration of 5 days, user invests on 5th Dec, first reward distribution at 7th Dec, last reward will be at 11th Dec, and commission for the 11th will be calculated as usual

3. **User invests multiple times in one day**
   - Each investment is tracked independently with its own tier, reward rate, and duration
   - Each investment has its own reward cycle starting from the day after investment
   - Example: User invests $100 (Tier 1) and $500 (Tier 2) on the same day
     - $100 investment: 1% daily, 120 days, first reward calculated next day 00:00
     - $500 investment: 1.5% daily, 130 days, first reward calculated next day 00:00
     - Both investments operate independently

4. **User invests $50 (Tier 1), then invests $500 more (Tier 2)**
   - The $50 investment continues at Tier 1 (1%, 120 days)
   - The new $500 investment operates at Tier 2 (1.5%, 130 days)
   - Both investments are tracked independently

### Referral Scenarios

1. **User A refers User B, User B refers User C**
   - When User B earns daily reward: User A gets Level 1 commission (50% of B's daily reward)
   - When User C earns daily reward: User B gets Level 1 commission (50% of C's daily reward), User A gets Level 2 commission (30% of C's daily reward)
   - Each commission is calculated independently based on each downline's daily reward amount

2. **User refers themselves using a different account**
   - **Decision:** Self-referral prevention is not required. The system serves as a gaming system and no strict KYC (Know Your Customer) verification is required. Users can refer themselves using different Telegram accounts if they choose to do so.

3. **Referral chain breaks (user's investment contract expires)**
   - When a referral's investment contract expires, the last day's reward will be issued and commission for that last day will be calculated as usual
   - Commissions stop after the last day's reward is distributed, since there's no more daily reward generated
   - Commissions are calculated based on generated daily rewards only

4. **Circular referral attempt**
   - If User A refers User B, and later User B tries to refer User A via referral link, the system detects User A is already registered and no new registration occurs. The app loads normally for User A.

### Timing Scenarios

1. **User invests at 23:59:59**
   - Investment made at 23:59:59 on the 5th will have the first calculation on 6th 00:00 (the next second)
   - Reward will be distributed on 7th 00:00
   - Although "calculated" on the 6th, the system actually calculates and distributes on the 7th 00:00

2. **System maintenance during reward calculation time**
   - Cronjob runs every 5 minutes
   - At 00:00, cronjob starts calculation task and creates DB entry
   - Next 5-minute cronjob detects job already started and won't start again
   - Ensures when system resumes, cronjob will start for the day

3. **Timezone handling**
   - All calculations use UTC+8 hours
   - No DST handling required

---

## UI/UX Considerations

**Decisions:**
- **Pages/screens required:**
  - **Dashboard/home:** Includes user investment records
  - **Investment page:** For making new investments and viewing active investments
  - **Referral page:** With link sharing functionality
  - **Transaction history:** Separated by transaction type (wallet/deposit/withdrawal/investment)
  - **Profile/settings:** User profile and app settings
  - **Deposit page:** For making deposits
  - **Withdrawal page:** For withdrawal requests. Shows recent withdrawal history of all users at the bottom, including the amount and link to blockchain explorer
- **Real-time balance updates:** No
- **Notifications for reward credits:** No (reason: if user has 20 investment records, the user will get 20 notifications every day, which is too many)
- **Language support:** English and Chinese
- **Dark mode:** Yes, should be implemented

---

## Testing & Quality Assurance

**Decisions:**
- **Testing strategy:** Unit tests (required). Additional testing types recommended below.
- **Test types required:** Yes, unit tests, integration tests, and E2E tests
  - **Unit tests:** Test individual functions/methods in isolation
  - **Integration tests:** Test interactions between components (e.g., API endpoints with database, reward calculation with commission calculation)
  - **E2E (End-to-End) tests:** Test complete user workflows from start to finish (e.g., user registration → deposit → investment → reward calculation → withdrawal). Simulates real user interactions across the entire application stack (frontend, backend, database)
  
  **E2E Testing Implementation for React Frontend:**
  
  E2E tests for React applications require browser automation tools that can interact with the UI, simulate user actions (clicks, typing, navigation), and verify UI state and API responses. Here's how to implement E2E tests:
  
  **Recommended Tools:**
  - **Playwright** (recommended) or **Cypress** - Modern browser automation frameworks
  - **React Testing Library** - For component-level testing (complements E2E tests)
  - **MSW (Mock Service Worker)** - Optional, for mocking API responses during E2E tests
  
  **E2E Test Implementation Approach:**
  
  1. **Setup Test Environment:**
     - Install Playwright or Cypress
     - Configure test browser (Chromium, Firefox, WebKit)
     - Set up test database (separate from development/production)
     - Configure API endpoints (can point to test backend or use mocks)
  
  2. **Test Structure:**
     ```
     e2e/
       ├── fixtures/          # Test data, mock users, test accounts
       ├── pages/             # Page Object Model (POM) - reusable page interactions
       ├── workflows/         # Complete user workflows
       └── tests/             # Test files
           ├── registration.spec.ts
           ├── deposit.spec.ts
           ├── investment.spec.ts
           └── referral.spec.ts
     ```
  
  3. **Example E2E Test Flow (Playwright):**
     ```typescript
     // e2e/tests/investment-flow.spec.ts
     import { test, expect } from '@playwright/test';
     import { DashboardPage } from '../pages/DashboardPage';
     import { InvestmentPage } from '../pages/InvestmentPage';
     
     test('User can complete investment flow', async ({ page }) => {
       // 1. Navigate to app (simulate Telegram Mini App launch)
       await page.goto('https://app.example.com');
       
       // 2. Verify user is logged in (auto-registration via Telegram)
       const dashboard = new DashboardPage(page);
       await expect(dashboard.balance).toBeVisible();
       
       // 3. Navigate to deposit page and make deposit
       await dashboard.navigateToDeposit();
       await page.fill('[data-testid="deposit-amount"]', '100');
       await page.click('[data-testid="submit-deposit"]');
       
       // 4. Verify deposit success (check balance update)
       await expect(dashboard.balance).toContainText('100.00000000');
       
       // 5. Navigate to investment page
       await dashboard.navigateToInvestment();
       const investmentPage = new InvestmentPage(page);
       
       // 6. Make investment
       await investmentPage.invest('100');
       
       // 7. Verify investment appears in dashboard
       await dashboard.navigateToHome();
       await expect(dashboard.investmentList).toContainText('$100');
       await expect(dashboard.investmentList).toContainText('Tier 1');
     });
     ```
  
  4. **Page Object Model (POM) Pattern:**
     ```typescript
     // e2e/pages/DashboardPage.ts
     export class DashboardPage {
       constructor(private page: Page) {}
       
       get balance() { return this.page.locator('[data-testid="user-balance"]'); }
       get investmentList() { return this.page.locator('[data-testid="investment-list"]'); }
       
       async navigateToDeposit() {
         await this.page.click('[data-testid="nav-deposit"]');
       }
       
       async navigateToInvestment() {
         await this.page.click('[data-testid="nav-investment"]');
       }
     }
     ```
  
  5. **Testing React Components in E2E Context:**
     - E2E tests interact with the rendered DOM, not React components directly
     - Use `data-testid` attributes in React components for reliable element selection:
       ```tsx
       // React component
       <button data-testid="submit-investment" onClick={handleInvest}>
         Invest
       </button>
       ```
     - E2E tests verify user-visible behavior, not internal component state
  
  6. **API Integration in E2E Tests:**
     - **Option A:** Point E2E tests to a test backend server (recommended for full integration)
     - **Option B:** Use MSW to mock API responses (faster, but less realistic)
     - **Option C:** Hybrid approach - mock external services (payment gateway), use real backend for core features
  
  7. **Telegram Mini App Specific Considerations:**
     - Mock Telegram Web App SDK (`window.Telegram.WebApp`) in test environment
     - Simulate Telegram initData for authentication
     - Test referral link handling (`?start=REF123456`)
     - Test dark mode switching (Telegram theme changes)
  
  8. **Complete Workflow Example:**
     ```typescript
     test('Complete referral and commission flow', async ({ page, context }) => {
       // User A: Register and invest
       const userA = await createTestUser('userA');
       await loginAsUser(page, userA);
       await makeDeposit(page, 500);
       await makeInvestment(page, 500);
       
       // User B: Register via User A's referral link
       const referralLink = await getReferralLink(page);
       const userB = await createTestUser('userB');
       await page.goto(`https://app.example.com?start=${referralLink}`);
       
       // User B: Invest
       await makeDeposit(page, 100);
       await makeInvestment(page, 100);
       
       // Simulate reward calculation (trigger cronjob or API call)
       await triggerRewardCalculation();
       
       // Verify User A received commission
       await loginAsUser(page, userA);
       await page.goto('/referral');
       await expect(page.locator('[data-testid="commission-amount"]'))
         .toContainText('0.50000000'); // 50% of $1 daily reward
     });
     ```
  
  9. **Best Practices:**
     - Use `data-testid` attributes instead of CSS selectors (more stable)
     - Keep tests independent (clean up test data between tests)
     - Use fixtures for test data setup
     - Run tests in headless mode in CI/CD, headed mode for debugging
     - Take screenshots on test failures for debugging
     - Test critical user paths (happy paths) and edge cases
     - Keep E2E tests focused on user workflows, not implementation details
  
  10. **CI/CD Integration:**
      - Run E2E tests in CI pipeline before deployment
      - Use Docker containers for consistent test environment
      - Parallelize test execution for faster feedback
      - Generate test reports and coverage metrics
- **Reward calculation accuracy testing:** Up to 8 decimal precision test is required. Test all tier calculations, edge cases (boundary values), and rounding behavior
- **Referral commission calculation testing:** Test every possible combination:
  - 1 level referral chain
  - 2 level referral chain
  - 3 level referral chain
  - Different investment amounts (affecting daily reward percentage and amount)
  - Different tier combinations across referral levels
  - Edge cases (boundary values, multiple investments per user)
- **Test accounts:** Yes, implement test accounts for different scenarios (different tiers, referral levels, investment statuses, etc.)

---

## Next Steps

1. **Review requirements** with stakeholders
2. **Design database schema** for users, investments, referrals, transactions
3. **Create API specifications** for all endpoints
4. **Design UI mockups** for key screens
5. **Set up development environment** and project structure
6. **Implement core features** incrementally
7. **Test thoroughly** before production deployment

---

## Additional Notes

- Consider implementing a comprehensive admin dashboard for monitoring and management
- Consider implementing analytics to track user behavior and campaign performance
- Consider implementing fraud detection mechanisms
- Consider implementing user support/help system
- Consider implementing multi-language support from the start if targeting international users
