# Phase 2 Features Plan (Frontend Visuals)

## Goal

Add richer UI/UX and supporting behaviors to the existing Telegram Earn mini app for referrals, investments, wallet deposit/withdrawal flows, transaction history, and theme switching.

## Scope

This phase is **primarily frontend** (visuals + new pages/modals + grouping/filtering). However, several items require **new/updated backend APIs** to supply aggregated values (ROI totals, referral investment summaries, wallet transaction history, deposit address retrieval, withdrawal lifecycle).

## Feature Set

### 1) Referrals Tab: “My Network” → referral investment summary

**What to add**
- Under the existing **“My Network”** section, display:
  - For each **direct referral (Level 1 / downline)**, display:
    - **Active investment (amount)**
    - **Total investment (amount)**

**Definition (to confirm)**
- **Active investment**: sum of `Investment.amount` where `status in (pending, active)` for that downline user.
- **Total investment**: sum of `Investment.amount` where `status in (pending, active, completed)` for that downline user.

**Downline scope (to confirm)**
- **Direct referrals only (Level 1).**

**Display rules (confirmed)**
- Show **sum of amounts** (not count).
- The totals are calculated per downline user (e.g., Downline A: $2000/$3000, Downline B: $500/$500).

**Acceptance criteria**
- The “My Network” section shows both numbers with 8-decimal financial formatting.
- Loading / empty states are handled (0 values when no referrals or no investments).

**Backend/API dependency**
- Add an endpoint (or extend existing referral summary endpoint) to return:
  - Per direct referral (Level 1), return:
    - `level1_active_investment_total`
    - `level1_total_investment_total`

---

### 2) Invest Tab: richer investment records + ROI details + status grouping

#### 2.1 Investment record: additional fields

**What to add per investment record**
- **Total ROI generated**:
  - **Amount**: sum of ROI (reward) amounts generated for this investment.
  - **Percent**: `(roi_total_amount / investment.amount) * 100`.
- **Maturity progress**:
  - A progress bar showing how close the investment is to maturity.
  - Progress should be based on the contract schedule (start/end) rather than “number of ROI records” to avoid display anomalies.
- **“View ROI records” button**:
  - Opens a list (modal or detail page) of ROI records for that investment.
  - Each record shows:
    - ROI date
    - ROI percent (daily rate)
    - ROI amount
- **Investment made date & time**:
  - Show full timestamp (not date-only).
  - Also show **start date & time** so users know when the investment begins generating rewards.

**Suggested UI structure**
- Investment list grouped by status (see 2.3).
- Each investment card/row includes:
  - Amount, tier, daily ROI %, duration
  - Created timestamp
  - ROI total amount + ROI total %
  - Progress bar with “X days remaining / matured” label
  - Action: “View ROI records”

**Acceptance criteria**
- ROI totals are correct and formatted to 8 decimals.
- ROI percent is shown with reasonable precision (e.g., 2 decimals) while amount remains 8 decimals.
- Maturity progress never exceeds 100% and is stable across timezones.
- Investment timestamp includes time.

**Backend/API dependency**
- Investment list API should supply enough data to compute:
  - `created_at` (datetime)
  - `start_date` / `end_date` OR `duration_days` + a reference start
- ROI totals should be readable without iterating ROI records:
  - **Backend change**: when calculating ROI/rewards for an investment, store/increment the accumulated ROI percent on the investment record.
  - Investment APIs should expose accumulated fields (confirmed):
    - `roi_total_amount`
    - `roi_total_percent`

#### 2.2 ROI records view

**What to show**
- A per-investment ROI history list/table:
  - `reward_date`
  - `daily_reward_rate` (percent)
  - `reward_amount`
  - (optional) distribution timestamp if stored

**Acceptance criteria**
- Supports pagination or virtual list if record count is large.
- Sorting is stable and **latest-first**.

**Backend/API dependency**
- Endpoint to list ROI (reward) records for an investment (e.g., `GET /investments/:id/rewards`).

#### 2.3 Group investments by status

**What to add**
- Group investment list into sections:
  - `pending`
  - `active`
  - `completed`

**Acceptance criteria**
- Grouping is consistent with backend statuses.
- Each group has correct empty state.

---

### 3) Profile Tab: Deposit button + deposit instructions + deposit history

**What to add**
- Next to wallet balance, add:
  - **Deposit** button: opens deposit instructions and displays a USDT deposit address + QR.
  - **Deposit history** button: navigates to a deposit history screen.

**Deposit instructions content**
- Network choices supported: USDT on Tron and USDT on BNB.
- Minimum deposit: $5 (less than $5 is forfeited).

**Acceptance criteria**
- Address can be copied.
- QR is visible and scannable.
- User can view deposit history with statuses: `processing`, `completed`, `forfeited`.

**Backend/API dependency**
- API to request/generate a unique deposit address **before showing it**.
- API to fetch deposit history (either a dedicated deposit endpoint or filterable wallet transaction endpoint).

---

### 4) Profile Tab: Withdraw button + withdrawal page + history + cancel pending

**What to add**
- Next to wallet balance, add a **Withdraw** button that navigates to a withdrawal page.

**Withdrawal page**
- Inputs:
  - USDT address
  - Network selection (Tron / BNB)
  - Withdrawal amount
- Validation rules (from requirements):
  - Minimum withdrawal: $10
  - Fee: 1% + fixed fee ($3 Tron, $2 BNB)
- Show calculation:
  - Requested amount
  - Fee amount
  - Net amount

**Withdrawal history page**
- List withdrawals with statuses: `pending`, `processing`, `completed`, `cancelled`.
- Allow **cancel** action only when status is `pending`.

**Acceptance criteria**
- Form blocks invalid amounts (below minimum, above available balance, etc.).
- Canceling a pending withdrawal updates history state and wallet balance per backend behavior.

**Backend/API dependency**
- Endpoint to create withdrawal.
- Endpoint to list user withdrawals.
- Endpoint to cancel pending withdrawal; cancellation must refund amount (including fees) per rules.

---

### 5) Light/Dark mode switching

**What to add**
- Allow user to switch between light/dark mode.

**Behavioral rules (recommended)**
- Default theme follows Telegram `WebApp.colorScheme`.
- User can override via an in-app toggle; persist preference locally (Zustand + localStorage).
- If user has set an override, the app uses it; otherwise it follows Telegram.

**Acceptance criteria**
- Toggle takes effect immediately.
- Theme is preserved across app restarts.

---

### 6) History Tab: switch data source to `wallet_transaction`

**What to change**
- The History tab currently displays records from the `Transaction` table.
- Change it to display records from `wallet_transaction`, which includes **all types of transactions**.

**Acceptance criteria**
- History tab includes all wallet transaction types required by the business flows (deposit, withdrawal, ROI rewards, commissions, investment-related movements, cancellations).
- Filtering and labels are correct and user-friendly.

**Backend/API dependency**
- **Investigate** whether `wallet_transaction` is already implemented in backend + exposed via API.
- If missing, implement the necessary models/serializers/endpoints.
- Provide/confirm an API endpoint that returns `wallet_transaction` records for the authenticated user.
- Ensure payload includes:
  - type
  - amount
  - status
  - created_at
  - any metadata needed for UI (e.g., blockchain, tx hash, explorer link)

---

### 7) Invest Tab: show tier table (amount / ROI / duration)

**What to add**
- A simple table on the Invest tab showing all tiers:
  - Tier
  - Investment amount range
  - Daily ROI %
  - Duration (days)

**Source of truth**
- Tiers from `/docs/mlm-business-rules.md`:
  - Tier 1: ≤ $100 → 1.0% → 120 days
  - Tier 2: ≤ $500 → 1.5% → 130 days
  - Tier 3: ≤ $1,000 → 2.0% → 140 days
  - Tier 4: ≤ $2,000 → 2.5% → 150 days
  - Tier 5: ≤ $5,000 → 3.0% → 160 days
  - Tier 6: > $5,000 → 3.5% → 180 days

**Acceptance criteria**
- Table is readable on mobile, with a compact layout.
- Values match the business rules exactly.

## Cross-cutting UI/Engineering Notes

- **Financial precision**: all amounts displayed with 8 decimals (per requirements).
- **Timezone**: display timestamps in a consistent manner (prefer user locale, but calculations must respect backend UTC+8 rules where applicable).
- **Routing**: new pages (Deposit, Withdraw, ROI records) should be added to the existing React Router setup.
- **UX states**: loading, empty, and error states must exist for each new section.

## Open Questions (need confirmation)

1. Confirm `wallet_transaction` schema and desired mapping to History UI labels/types.

## Deliverables

- Updated Referrals tab UI (My Network totals).
- Updated Invest tab UI (tier table + grouped investment list + ROI totals/progress + ROI records view).
- Deposit instructions + address/QR + deposit history page.
- Withdrawal request page + withdrawal history page with cancel pending.
- Theme toggle support.
- History tab migrated to `wallet_transaction` feed.
