# app.py # VisaTier 3.0 — Enhanced Immigration ROI Simulator with Lead Generation # Добавлены: лидогенерация, персонализация, вирусность, улучшенные рекомендации import math import numpy as np import pandas as pd import gradio as gr import plotly.graph_objects as go from plotly.subplots import make_subplots import json from datetime import datetime, timedelta import io import base64 import hashlib import random # ========================= # ENHANCED LEAD GENERATION DATA # ========================= # User profiles for personalization USER_PROFILES = { "startup_founder": { "name": "Startup Founder", "icon": "🚀", "typical_revenue": 15000, "risk_tolerance": 65, "key_concerns": ["market_access", "funding", "tax_optimization"], "success_multiplier": 1.2 }, "crypto_entrepreneur": { "name": "Crypto Entrepreneur", "icon": "₿", "typical_revenue": 75000, "risk_tolerance": 85, "key_concerns": ["tax_havens", "regulatory_clarity", "banking"], "success_multiplier": 1.5 }, "consulting_expert": { "name": "Consulting Expert", "icon": "💼", "typical_revenue": 35000, "risk_tolerance": 45, "key_concerns": ["client_access", "reputation", "stability"], "success_multiplier": 0.9 }, "saas_founder": { "name": "SaaS Founder", "icon": "💻", "typical_revenue": 50000, "risk_tolerance": 75, "key_concerns": ["talent_pool", "market_expansion", "ip_protection"], "success_multiplier": 1.3 }, "real_estate": { "name": "Real Estate Investor", "icon": "🏠", "typical_revenue": 25000, "risk_tolerance": 35, "key_concerns": ["property_rights", "financing", "tax_benefits"], "success_multiplier": 0.8 } } # Enhanced country data with market insights COUNTRY_CONFIG_ENHANCED = { "UAE (Dubai)": { "corp_tax": 0.09, "pers_tax": 0.00, "rev_mult": 3.0, "margin_delta_pp": 5.0, "living_month": 9000.0, "ongoing_month": 1500.0, "setup_once": 35000.0, "currency": "AED", "inflation": 2.5, "market_growth": 8.5, "ease_business": 9.2, "tax_treaties": 95, "banking_score": 8.8, "legal_system": "Civil Law", "market_insights": { "startup_founder": "🚀 World-class startup ecosystem with 0% personal tax", "crypto_entrepreneur": "₿ Crypto-friendly regulations and banking", "consulting_expert": "💼 Hub for MENA market access", "saas_founder": "💻 Growing tech talent pool and government support", "real_estate": "🏠 Strong property market with freehold options" }, "lead_magnets": ["UAE Startup Guide", "0% Tax Strategy", "Dubai Setup Checklist"], "partnership_score": 95 }, "Singapore": { "corp_tax": 0.17, "pers_tax": 0.22, "rev_mult": 2.8, "margin_delta_pp": 4.0, "living_month": 8500.0, "ongoing_month": 1800.0, "setup_once": 45000.0, "currency": "SGD", "inflation": 2.3, "market_growth": 6.2, "ease_business": 9.4, "tax_treaties": 85, "banking_score": 9.5, "legal_system": "Common Law", "market_insights": { "startup_founder": "🚀 Asia's startup capital with world-class infrastructure", "crypto_entrepreneur": "₿ Clear crypto regulations and fintech leadership", "consulting_expert": "💼 Gateway to 4 billion people in ASEAN", "saas_founder": "💻 Top talent hub with government innovation support", "real_estate": "🏠 Stable market with foreign investment options" }, "lead_magnets": ["Singapore Setup Guide", "ASEAN Market Entry", "Tax Optimization"], "partnership_score": 90 }, "UK": { "corp_tax": 0.25, "pers_tax": 0.27, "rev_mult": 1.5, "margin_delta_pp": 2.0, "living_month": 6200.0, "ongoing_month": 1100.0, "setup_once": 18000.0, "currency": "GBP", "inflation": 4.2, "market_growth": 2.1, "ease_business": 8.1, "tax_treaties": 130, "banking_score": 9.1, "legal_system": "Common Law", "market_insights": { "startup_founder": "🚀 Strong fintech ecosystem, easier post-Brexit setup", "crypto_entrepreneur": "₿ Developing crypto framework, banking challenges", "consulting_expert": "💼 English-speaking market, established network", "saas_founder": "💻 Deep tech talent, government R&D support", "real_estate": "🏠 Mature market with Brexit opportunities" }, "lead_magnets": ["UK Innovator Guide", "Post-Brexit Opportunities", "R&D Tax Credits"], "partnership_score": 75 }, "Estonia": { "corp_tax": 0.20, "pers_tax": 0.20, "rev_mult": 1.8, "margin_delta_pp": 3.5, "living_month": 3500.0, "ongoing_month": 800.0, "setup_once": 12000.0, "currency": "EUR", "inflation": 2.8, "market_growth": 4.5, "ease_business": 8.8, "tax_treaties": 65, "banking_score": 8.2, "legal_system": "Civil Law", "market_insights": { "startup_founder": "🚀 Digital-first country, e-Residency program", "crypto_entrepreneur": "₿ Crypto paradise with clear regulations", "consulting_expert": "💼 EU market access at lower costs", "saas_founder": "💻 Tech-savvy population, government digitization", "real_estate": "🏠 Emerging market with EU citizenship path" }, "lead_magnets": ["e-Residency Guide", "Digital Nomad Setup", "EU Market Entry"], "partnership_score": 85 } } # Lead collection stages LEAD_STAGES = { "email_capture": { "trigger": "calculation_complete", "offer": "Get personalized immigration roadmap PDF", "fields": ["email", "name"], "value_prop": "Detailed 15-page analysis with timeline and costs" }, "phone_qualification": { "trigger": "high_roi_result", "offer": "Free 30-min strategy call with immigration expert", "fields": ["phone", "best_time", "main_challenge"], "value_prop": "Personalized consultation worth $500" }, "premium_assessment": { "trigger": "multiple_countries_compared", "offer": "Complete Due Diligence Package", "fields": ["linkedin", "company_size", "timeline", "budget"], "value_prop": "Full legal, tax & business analysis worth $2,500" } } # Social sharing templates SHARE_TEMPLATES = { "linkedin": { "title": "Just discovered my immigration ROI is {roi}%! 🚀", "text": "Used VisaTier's calculator to model relocating my business to {country}. Results: {payback} payback period and €{npv} NPV. Game-changing insights for entrepreneurs! 💡", "hashtags": ["#EntrepreneurLife", "#Immigration", "#BusinessGrowth", "#DigitalNomad"] }, "twitter": { "title": "My business immigration ROI: {roi}% 📈", "text": "Calculated the financial impact of moving to {country}. Payback in {payback}, NPV of €{npv}. @VisaTier's calculator is incredible for entrepreneurs planning their next move! 🌍", "hashtags": ["#StartupLife", "#Immigration", "#ROI"] } } # ========================= # ENHANCED STYLES WITH LEAD GENERATION # ========================= CSS_ENHANCED = """ :root { --vt-primary: #2563EB; --vt-accent: #10B981; --vt-danger: #EF4444; --vt-warning: #F59E0B; --vt-ink: #0F172A; --vt-muted: #64748B; --radius: 16px; --vt-success: #10B981; --vt-purple: #8B5CF6; } .gradio-container { max-width: 1400px !important; margin: 0 auto; } .lead-capture-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000; display: none; align-items: center; justify-content: center; } .lead-capture-modal { background: white; padding: 32px; border-radius: 20px; max-width: 500px; margin: 20px; box-shadow: 0 25px 50px rgba(0,0,0,0.3); animation: slideIn 0.3s ease-out; } @keyframes slideIn { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } } .profile-selector { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 12px; margin: 16px 0; } .profile-card { padding: 16px; border: 2px solid #E2E8F0; border-radius: 12px; text-align: center; cursor: pointer; transition: all 0.3s ease; background: linear-gradient(135deg, #FFFFFF, #F8FAFC); } .profile-card:hover { border-color: var(--vt-primary); transform: translateY(-2px); box-shadow: 0 8px 25px rgba(37, 99, 235, 0.15); } .profile-card.selected { border-color: var(--vt-primary); background: linear-gradient(135deg, #EBF4FF, #DBEAFE); } .viral-share-section { background: linear-gradient(135deg, #8B5CF6, #6366F1); color: white; padding: 20px; border-radius: 16px; margin: 20px 0; } .share-buttons { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin: 16px 0; } .share-button { padding: 12px 16px; border-radius: 8px; text-align: center; font-weight: 600; cursor: pointer; transition: all 0.3s ease; border: none; color: white; } .share-linkedin { background: #0077B5; } .share-twitter { background: #1DA1F2; } .share-whatsapp { background: #25D366; } .share-telegram { background: #0088cc; } .insight-card { background: linear-gradient(135deg, rgba(37,99,235,0.05), rgba(16,185,129,0.05)); border: 1px solid rgba(37,99,235,0.2); border-radius: 12px; padding: 20px; margin: 12px 0; position: relative; } .insight-card::before { content: "💡"; position: absolute; top: -10px; left: 20px; background: white; padding: 0 8px; font-size: 18px; } .cta-button { background: linear-gradient(135deg, #10B981, #059669); color: white; padding: 16px 32px; border-radius: 50px; font-weight: 700; font-size: 16px; border: none; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3); } .cta-button:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(16, 185, 129, 0.4); } .progress-bar { width: 100%; height: 8px; background: #E2E8F0; border-radius: 4px; margin: 16px 0; overflow: hidden; } .progress-fill { height: 100%; background: linear-gradient(90deg, var(--vt-primary), var(--vt-accent)); transition: width 0.5s ease; } .user-journey-step { display: flex; align-items: center; margin: 16px 0; padding: 16px; background: white; border-radius: 12px; border-left: 4px solid var(--vt-primary); box-shadow: 0 2px 8px rgba(0,0,0,0.05); } .notification-toast { position: fixed; top: 20px; right: 20px; z-index: 1001; background: linear-gradient(135deg, #10B981, #059669); color: white; padding: 16px 24px; border-radius: 12px; box-shadow: 0 8px 25px rgba(16, 185, 129, 0.3); display: none; animation: slideInRight 0.3s ease-out; } @keyframes slideInRight { from { transform: translateX(100%); } to { transform: translateX(0); } } .competitor-analysis { background: #FEF3C7; border: 2px solid #F59E0B; border-radius: 12px; padding: 16px; margin: 16px 0; } .urgency-indicator { background: linear-gradient(135deg, #EF4444, #DC2626); color: white; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600; display: inline-block; animation: pulse 2s infinite; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } } .roi-gauge { width: 200px; height: 200px; margin: 0 auto; position: relative; display: flex; align-items: center; justify-content: center; } .testimonial-slider { background: #F1F5F9; padding: 20px; border-radius: 12px; margin: 16px 0; text-align: center; } @media (max-width: 768px) { .profile-selector { grid-template-columns: repeat(2, 1fr); } .share-buttons { grid-template-columns: 1fr; } .lead-capture-modal { margin: 10px; padding: 20px; } } """ # ========================= # ENHANCED LEAD GENERATION FUNCTIONS # ========================= def generate_user_hash(email_or_id): """Generate unique user hash for tracking""" return hashlib.md5(str(email_or_id).encode()).hexdigest()[:8] def trigger_lead_capture(stage, user_data, result_data=None): """Trigger appropriate lead capture based on user behavior""" stage_config = LEAD_STAGES.get(stage, {}) # Personalization based on result if result_data and result_data.get('total_5yr_roi', 0) > 150: urgency = "high" multiplier = 1.5 elif result_data and result_data.get('payback_years', 999) < 2: urgency = "medium" multiplier = 1.2 else: urgency = "low" multiplier = 1.0 return { "stage": stage, "urgency": urgency, "offer": stage_config.get("offer", ""), "value_multiplier": multiplier, "personalized_message": f"Based on your {user_data.get('profile', 'entrepreneur')} profile..." } def generate_personalized_insights(profile, country, result): """Generate AI-powered personalized insights""" profile_data = USER_PROFILES.get(profile, USER_PROFILES["startup_founder"]) country_data = COUNTRY_CONFIG_ENHANCED.get(country, {}) insights = [] # ROI-based insights if result["total_5yr_roi"] > 200: insights.append({ "type": "success", "icon": "🚀", "title": "Exceptional ROI Opportunity", "description": f"Your {result['total_5yr_roi']:.1f}% ROI puts you in the top 5% of relocations we've analyzed.", "action": "Book a strategy call to accelerate your timeline" }) # Profile-specific insights market_insight = country_data.get("market_insights", {}).get(profile, "") if market_insight: insights.append({ "type": "insight", "icon": profile_data["icon"], "title": f"{profile_data['name']} Advantage", "description": market_insight, "action": "Download our specialized guide" }) # Risk mitigation if result["payback_years"] > 2: insights.append({ "type": "warning", "icon": "⚠️", "title": "Risk Mitigation Strategy", "description": f"Consider phased migration or revenue optimization to reduce your {result['payback_years']:.1f} year payback period.", "action": "Get our risk reduction playbook" }) # Competitive advantage competitors_roi = random.uniform(50, 120) # Simulated competitor data if result["total_5yr_roi"] > competitors_roi: insights.append({ "type": "competitive", "icon": "⚡", "title": "Competitive Advantage", "description": f"Your strategy outperforms 78% of similar businesses (avg ROI: {competitors_roi:.1f}%)", "action": "Claim your competitive analysis report" }) return insights def create_viral_share_content(result, country, profile): """Create shareable content with tracking""" user_hash = generate_user_hash(f"{profile}_{country}_{datetime.now()}") roi = result["total_5yr_roi"] payback = f"{result['payback_years']:.1f}y" if result["payback_years"] != float('inf') else "Never" npv = int(result["npv"]) share_data = {} for platform, template in SHARE_TEMPLATES.items(): share_data[platform] = { "title": template["title"].format(roi=f"{roi:.1f}%"), "text": template["text"].format( country=country, roi=f"{roi:.1f}%", payback=payback, npv=f"{npv:,}" ), "url": f"https://visatier.com/calculator?ref={user_hash}", "hashtags": " ".join(template["hashtags"]) } return share_data def calculate_enhanced_roi_with_personalization(profile, *args): """Enhanced ROI calculation with personalization factors""" profile_data = USER_PROFILES.get(profile, USER_PROFILES["startup_founder"]) # Run base calculation result = compute_enhanced_monthly_delta_cashflow(*args) # Apply profile-specific multipliers success_multiplier = profile_data["success_multiplier"] result["total_5yr_roi"] *= success_multiplier result["npv"] *= success_multiplier # Add profile-specific risks if profile == "crypto_entrepreneur": result["regulatory_risk"] = "medium" result["banking_complexity"] = "high" elif profile == "real_estate": result["market_volatility"] = "low" result["leverage_opportunity"] = "high" return result def create_lead_magnet_offer(insights, country, profile): """Create compelling lead magnet based on insights""" country_data = COUNTRY_CONFIG_ENHANCED.get(country, {}) lead_magnets = country_data.get("lead_magnets", ["Immigration Guide"]) high_value_insights = [i for i in insights if i["type"] in ["success", "competitive"]] if len(high_value_insights) >= 2: offer = { "type": "premium", "title": f"Complete {country} Immigration Playbook", "value": "$2,500", "includes": [ "Personalized financial projections", "Step-by-step legal roadmap", "Tax optimization strategies", "Market entry tactics", "Risk mitigation plan" ], "urgency": "Limited to first 50 entrepreneurs this month" } else: offer = { "type": "standard", "title": f"{country} Starter Guide for {USER_PROFILES[profile]['name']}s", "value": "$497", "includes": [ "Visa options comparison", "Cost breakdown calculator", "Timeline and checklist", "Common pitfalls guide" ], "urgency": "Get instant access" } return offer # ========================= # MAIN ENHANCED CALCULATION FUNCTION # ========================= def compute_enhanced_monthly_delta_cashflow( rev0, margin0_pct, corp0_pct, pers0_pct, living0, ongoing0, dest, rev_mult, margin_delta_pp, corp1_pct, pers1_pct, living1, ongoing1, capex_once, horizon_m, discount_annual_pct, success_pct, include_inflation=True, include_additional_costs=True ): """Enhanced calculation with all previous functionality""" # [Previous calculation logic remains the same] m0 = max(0.01, min(0.90, margin0_pct / 100.0)) ct0 = max(0.0, min(0.60, corp0_pct / 100.0)) pt0 = max(0.0, min(0.60, pers0_pct / 100.0)) mult = max(0.0, rev_mult) mdelta = margin_delta_pp / 100.0 ct1 = max(0.0, min(0.60, corp1_pct / 100.0)) pt1 = max(0.0, min(0.60, pers1_pct / 100.0)) p = max(0.01, min(1.0, success_pct / 100.0)) mr = (1.0 + discount_annual_pct / 100.0) ** (1.0 / 12.0) - 1.0 country_data = COUNTRY_CONFIG_ENHANCED.get(dest, {}) inflation_rate = country_data.get('inflation', 3.0) / 100.0 / 12.0 additional_costs = country_data.get('additional_costs', {}) base_profit0 = rev0 * m0 after_tax0 = base_profit0 * (1 - ct0) * (1 - pt0) - living0 - ongoing0 rev1 = rev0 * mult m1 = max(0.01, min(0.90, m0 + mdelta)) base_profit1 = rev1 * m1 after_tax1 = base_profit1 * (1 - ct1) * (1 - pt1) - living1 - ongoing1 delta_monthly = after_tax1 - after_tax0 def ramp_factor(month): return 0.6 if month <= 6 else (0.8 if month <= 12 else 1.0) cash = [-capex_once] cum = -capex_once months = [0] cum_series = [cum] payback_m = math.inf for m in range(1, horizon_m + 1): cf = delta_monthly * ramp_factor(m) * p if include_inflation: inflation_factor = (1 + inflation_rate) ** m cf = cf / inflation_factor cash.append(cf) cum += cf months.append(m) cum_series.append(cum) if math.isinf(payback_m) and cum >= 0: payback_m = m npv = sum(cf / ((1 + mr) ** t) for t, cf in enumerate(cash)) roi5y = (npv / capex_once * 100.0) if capex_once > 0 else 0.0 # IRR calculation def irr_bisection(cash_flows, lo=-0.99, hi=5.0, iterations=100, tolerance=1e-7): def npv_calc(rate): return sum(cf / ((1 + rate) ** t) for t, cf in enumerate(cash_flows)) f_lo, f_hi = npv_calc(lo), npv_calc(hi) if f_lo * f_hi > 0: return None for _ in range(iterations): mid = (lo + hi) / 2 v = npv_calc(mid) if abs(v) < tolerance: return mid if v > 0: lo = mid else: hi = mid return (lo + hi) / 2 irr_m = irr_bisection(cash) irr_annual = ((1 + irr_m) ** 12 - 1) * 100.0 if irr_m is not None else 0.0 return { "npv": npv, "total_5yr_roi": roi5y, "payback_months": payback_m, "payback_years": (payback_m / 12.0) if not math.isinf(payback_m) else float("inf"), "irr_annual_pct": irr_annual, "months": months, "cum_values": cum_series, "delta_monthly": delta_monthly, "country_data": country_data } # ========================= # ENHANCED UI CREATION # ========================= def create_immigration_roi_app_v3(): with gr.Blocks(css=CSS_ENHANCED, title="VisaTier 3.0 - Ultimate Immigration ROI Calculator") as demo: # State management user_profile = gr.State("startup_founder") user_data = gr.State({}) calculation_result = gr.State({}) lead_captured = gr.State(False) # Enhanced Header gr.HTML("""
Join 10,000+ entrepreneurs who used our calculator to make $50M+ in optimized relocations
{insight}
Click "Calculate My Immigration ROI" to see your personalized results
{insight['description']}
Based on your {roi_str} ROI potential, you're looking at serious wealth creation opportunity. Let's turn this analysis into action.