# 🚀 Umbrix Mini App - Полная Архитектура (PRO LEVEL) ## Принципы (Best Practices): 1. **Telegram Bot = Минимум** - только /start → Open WebApp 2. **Mini App = Все** - вся логика, UI, воронка продаж 3. **No localStorage** - только API + MariaDB 4. **Telegram WebApp SDK** - интеграция с Telegram UI --- ## 📱 **User Journey (Воронка Продаж)** ### **Scenario 1: Новый пользователь БЕЗ реферала** ``` 1. User clicks: https://t.me/Dorod_vps_bot 2. Bot sends: "👋 Привет! 🚀 Открыть Umbrix" → WebApp button 3. User opens: https://app.umbrix.net 4. Mini App shows: Onboarding Flow ├── Welcome Screen (Telegram.WebApp.initData) ├── Language Selection (RU/EN/UZ) ├── Plan Selection (Shared/Dedicated/Premium) └── Create Account Button 5. Account created → Dashboard 6. Dashboard shows: ├── Subscription Status (Active / Expired / Trial) ├── QR Code + Links ├── Referral Button → Copy link ├── Help Button └── Settings Button ``` ### **Scenario 2: Новый пользователь С рефералом** ``` 1. User clicks: https://t.me/Dorod_vps_bot?start=ref_john_doe 2. Bot extracts: referrerId = "john_doe" 3. Bot opens: https://app.umbrix.net?ref=john_doe 4. Mini App shows: "🎁 Вы перешли по ссылке от john_doe! +7 дней бесплатно" 5. Onboarding Flow (same as above) 6. On Account Create: ├── POST /api/create-user (with referrerId) ├── POST /api/referral/track (award +7 days to john_doe) └── Both get bonuses 7. Dashboard → показывает trial статус + bonus days ``` ### **Scenario 3: Существующий пользователь (возврат)** ``` 1. User opens: https://t.me/Dorod_vps_bot → WebApp 2. Mini App detects: Telegram.WebApp.initDataUnsafe.user.id 3. API Check: GET /api/user-subscription?telegramId=12345 4. Response: { hasSubscription: true, token: "...", status: "active" } 5. Mini App redirects: /dashboard (skip onboarding) 6. Dashboard shows: ├── Subscription details ├── Days remaining: "23 дня осталось" ├── QR Code + Links └── Referral stats: "3 друга, +21 день заработано" ``` ### **Scenario 4: Пользователь с истекшей подпиской** ``` 1. API Check: { hasSubscription: true, status: "expired" } 2. Dashboard shows: ├── ⚠️ "Подписка истекла 5 дней назад" ├── "Пригласите 2 друзей для продления" (gamification) ├── "Или оплатите" → Payment Button └── Referral progress bar: [■■■□□] 3/5 friends ``` --- ## 🗂️ **Структура файлов Mini App** ``` /app ├── page.tsx # 🏠 Landing / Onboarding (если новый user) ├── dashboard/ │ └── page.tsx # 📊 Dashboard (если есть подписка) ├── plans/ │ └── page.tsx # 💎 Plan Selection (выбор тарифа) ├── referral/ │ └── page.tsx # 🎁 Referral Stats (уже есть!) ├── help/ │ └── page.tsx # ❓ Help / FAQ (уже есть!) ├── setup/ │ └── page.tsx # 🔧 Setup Wizard (инструкции по настройке) └── subscription/ └── [token]/ └── page.tsx # 📲 Subscription Details (QR код, ссылки) /components ├── OnboardingFlow.tsx # 🎬 Onboarding steps (language, plan, create) ├── PlanCard.tsx # 💳 Plan card (Shared/Dedicated/Premium) ├── SubscriptionStatus.tsx # ✅ Status badge (Active/Expired/Trial) ├── ReferralProgress.tsx # 📈 Progress bar (3/5 friends) ├── QRCodeModal.tsx # ✅ Уже есть ├── ReferralModal.tsx # ✅ Уже есть └── SetupWizard.tsx # ✅ Уже есть /lib ├── telegram-webapp.ts # 🔌 Telegram WebApp SDK wrapper ├── marzban-api.ts # ✅ Уже есть └── constants.ts # ✅ Уже есть ``` --- ## 🎨 **UI Components (Telegram WebApp Style)** ### **1. OnboardingFlow.tsx** ```tsx // Multi-step onboarding (Welcome → Language → Plan → Create) // Uses Telegram.WebApp.BackButton, .MainButton // Stores state in React (NOT localStorage) ``` ### **2. PlanCard.tsx** ```tsx // Карточка тарифа с ценой, features, "Выбрать" кнопкой // Props: { plan, price, features[], selected, onClick } // Design: Telegram-style card (rounded, shadow, accent color) ``` ### **3. SubscriptionStatus.tsx** ```tsx // Badge: "✅ Активна до 15.03.2026" / "⚠️ Истекла" / "🎁 Trial (7 дней)" // Color-coded: green/red/blue // Props: { status, expiryDate, daysRemaining } ``` ### **4. ReferralProgress.tsx** ```tsx // Progress bar: [■■■□□] 3/5 friends → +30 days bonus! // Shows: current referrals, next milestone, bonus amount // Props: { referralCount, bonusDays } ``` --- ## 🔄 **API Endpoints (уже есть + новые)** ### **Existing:** - ✅ POST /api/create-user - ✅ GET /api/user-subscription - ✅ POST /api/referral/track - ✅ GET /api/referral/stats ### **New (to add):** ```typescript // Check if user exists by Telegram ID GET /api/user-check?telegramId=12345 Response: { exists: boolean, username?: string, status?: string } // Get plan details GET /api/plans Response: { plans: [{ id, name, price, features[] }] } // Create payment link POST /api/create-payment Body: { username, plan, amount } Response: { paymentUrl: string, orderId: string } ``` --- ## 📋 **Implementation Priority** ### **Phase 1: Core Flow (СЕЙЧАС)** 1. ✅ Упростить n8n workflow (DONE) 2. Create OnboardingFlow.tsx (Welcome → Language → Plan → Create) 3. Update app/page.tsx (detect new vs existing user) 4. Create app/dashboard/page.tsx (show subscription status) 5. Create PlanCard.tsx component ### **Phase 2: Referral Integration** 6. Update OnboardingFlow to accept ?ref=USERNAME 7. Pass referrerId to /api/create-user 8. Add ReferralProgress.tsx to dashboard 9. Test full referral flow ### **Phase 3: Payment** 10. Add /api/plans endpoint 11. Add /api/create-payment endpoint 12. Integrate payment gateway (crypto) 13. Add webhook for payment confirmation ### **Phase 4: Polish** 14. Telegram WebApp SDK integration (BackButton, MainButton, theme) 15. i18n (RU/EN/UZ) 16. Error handling + loading states 17. Analytics (track conversions) --- ## 🎯 **Key Differences from Current Code** | Current | New (PRO) | |---------|-----------| | Bot имеет 3 команды + кнопки | Bot только /start → WebApp | | Нет onboarding flow | Full onboarding в Mini App | | localStorage для данных | API + MariaDB only | | Нет gamification | Referral progress bar | | Нет выбора плана в UI | Plan selection screen | | Нет payment flow | Integrated payment | | Нет Telegram theme | Uses Telegram.WebApp.themeParams | --- ## 💡 **Pro Tips** 1. **Telegram WebApp SDK**: используй `Telegram.WebApp.MainButton` для кнопок действий 2. **No localStorage**: только API, чтобы работало на всех устройствах 3. **Gamification**: показывай прогресс реферальной программы (мотивация!) 4. **Mobile-first**: Mini App всегда открывается на мобильном 5. **Fast loading**: минимизируй API calls, cache в React state 6. **Error handling**: graceful fallback если нет Telegram.WebApp 7. **i18n ready**: структура для перевода на другие языки --- ## 🚀 **Next Steps** Создам полную структуру Mini App с учетом этой архитектуры!