FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
updated tab code
tilakpatel22e2b6b911aaf1
diff --git a/.gitignore b/.gitignoreindex 800e66376..e189a33b3 100644--- a/.gitignore+++ b/.gitignore@@ -12,6 +12,7 @@ cmderreqgen.pyfincept_env*.md+*.db!README.mdpythontreeview.pydiff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsxindex e65cb3408..f0ceb660d 100644--- a/fincept-terminal-desktop/src/App.tsx+++ b/fincept-terminal-desktop/src/App.tsx@@ -3,6 +3,7 @@import React, { useState, useEffect } from 'react';import { useAuth } from './contexts/AuthContext';+import { NavigationProvider } from './contexts/NavigationContext';import { setPaymentWindowManager } from './services/paymentApi';// Import screens@@ -52,6 +53,7 @@ const App: React.FC = () => {const [currentScreen, setCurrentScreen] = useState<Screen>('login');const [hasChosenFreePlan, setHasChosenFreePlan] = useState(false);const [cameFromLogin, setCameFromLogin] = useState(false);+ const [activeTab, setActiveTab] = useState('dashboard');const [paymentWindow, setPaymentWindow] = useState<PaymentWindowState>({isOpen: false,checkoutUrl: '',@@ -156,7 +158,10 @@ const App: React.FC = () => {(hasChosenFreePlan && !cameFromLogin) ||(isFreePlan && hasChosenFreePlan)) {console.log('User has subscription, is guest, or chose free plan - redirecting to dashboard');- if (currentScreen !== 'paymentProcessing' && currentScreen !== 'paymentSuccess') {+ // Don't force redirect if user manually navigated to pricing+ if (currentScreen !== 'paymentProcessing' &&+ currentScreen !== 'paymentSuccess' &&+ currentScreen !== 'pricing') {setCurrentScreen('dashboard');}}@@ -194,7 +199,9 @@ const App: React.FC = () => {if (session?.authenticated && currentScreen === 'dashboard') {return (<>- <DashboardScreen />+ <NavigationProvider onNavigate={setCurrentScreen} onSetActiveTab={setActiveTab}>+ <DashboardScreen />+ </NavigationProvider>{/* In-App Payment Window Overlay */}<PaymentOverlay paymentWindow={paymentWindow} /></>diff --git a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsxindex f3b4dc6af..376baa1a4 100644--- a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx+++ b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx@@ -186,19 +186,34 @@ const handleSelectPlan = async () => {const isPopular = plan.plan_id === 'starter_20';const isRecommended = plan.plan_id === 'unlimited_199';+ // Check if this is the current plan+ const currentPlanId = (session?.subscription as any)?.data?.subscription?.plan?.plan_id ||+ session?.subscription?.subscription?.plan?.plan_id;+ const isCurrentPlan = currentPlanId === plan.plan_id;+return (<divkey={plan.plan_id}- onClick={() => setSelectedPlan(plan.plan_id)}+ onClick={() => !isCurrentPlan && setSelectedPlan(plan.plan_id)}className={`- relative cursor-pointer rounded-lg border-2 p-4 transition-all duration-200 hover:scale-[1.02]- ${isSelected- ? 'border-blue-500 bg-blue-600/10 shadow-lg shadow-blue-500/20'- : 'border-zinc-600 bg-zinc-800/50 hover:border-zinc-500'+ relative rounded-lg border-2 p-4 transition-all duration-200+ ${isCurrentPlan+ ? 'border-green-500 bg-green-600/10 cursor-default'+ : isSelected+ ? 'border-blue-500 bg-blue-600/10 shadow-lg shadow-blue-500/20 cursor-pointer hover:scale-[1.02]'+ : 'border-zinc-600 bg-zinc-800/50 hover:border-zinc-500 cursor-pointer hover:scale-[1.02]'}`}>- {isPopular && (+ {isCurrentPlan && (+ <div className="absolute -top-2 left-1/2 transform -translate-x-1/2">+ <span className="bg-green-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">+ Current Plan+ </span>+ </div>+ )}++ {!isCurrentPlan && isPopular && (<div className="absolute -top-2 left-1/2 transform -translate-x-1/2"><span className="bg-blue-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">Popular@@ -206,9 +221,9 @@ const handleSelectPlan = async () => {</div>)}- {isRecommended && (+ {!isCurrentPlan && isRecommended && (<div className="absolute -top-2 left-1/2 transform -translate-x-1/2">- <span className="bg-green-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">+ <span className="bg-orange-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">Best Value</span></div>@@ -337,15 +352,20 @@ const handleSelectPlan = async () => {<div className="mb-6"><div className="flex items-center justify-between mb-3"><div className="flex items-center">- {userType === 'existing' && (- <button- onClick={() => onProceedToDashboard()}- className="text-zinc-400 hover:text-white transition-colors mr-3"- disabled={isLoading}- >- <ArrowLeft className="h-4 w-4" />- </button>- )}+ <button+ onClick={() => {+ // Navigate based on authentication status+ if (session?.authenticated) {+ onProceedToDashboard();+ } else {+ onNavigate('login' as Screen);+ }+ }}+ className="text-zinc-400 hover:text-white transition-colors mr-3"+ disabled={isLoading}+ >+ <ArrowLeft className="h-4 w-4" />+ </button><h2 className="text-white text-xl font-semibold">{userType === 'existing' ? 'Upgrade Your Plan' : 'Choose Your Plan'}</h2>diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 614dfc564..757286f30 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -2,6 +2,7 @@ import React, { useState, useRef, useEffect } from 'react';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye, HelpCircle, LogOut } from 'lucide-react';import { useAuth } from '@/contexts/AuthContext';+import { useNavigation } from '@/contexts/NavigationContext';import ForumTab from '@/components/tabs/ForumTab';import DashboardTab from '@/components/tabs/DashboardTab';import MarketsTab from '@/components/tabs/MarketsTab';@@ -30,6 +31,7 @@ import AgentsTab from '@/components/tabs/agents/AgentsTab';import DataMappingTab from '@/components/tabs/data-mapping/DataMappingTab';import MCPTab from '@/components/tabs/mcp';import FyersTab from '@/components/tabs/fyers';+import SupportTicketTab from '@/components/tabs/SupportTicketTab';// Dropdown Menu Componentconst DropdownMenu = ({ label, items, onItemClick }: { label: string; items: any[]; onItemClick: (item: any) => void }) => {@@ -113,6 +115,7 @@ const DropdownMenu = ({ label, items, onItemClick }: { label: string; items: anyexport default function FinxeptTerminal() {const { session, logout } = useAuth();+ const navigation = useNavigation();const [activeTab, setActiveTab] = useState("dashboard");const [isFullscreen, setIsFullscreen] = useState(false);const [statusMessage, setStatusMessage] = useState("");@@ -135,12 +138,13 @@ export default function FinxeptTerminal() {};}, []);- // Get session display text- const getSessionDisplay = () => {- if (!session) return 'Loading...';+ // Get clickable session display component+ const getClickableSessionDisplay = () => {+ if (!session) return <span style={{ color: '#fbbf24', fontSize: '10px' }}>Loading...</span>;if (session.user_type === 'guest') {- // Calculate time remaining for guest users+ // Guest user display+ let timeText = '';if (session.expires_at) {const expiryTime = new Date(session.expires_at).getTime();const now = new Date().getTime();@@ -148,31 +152,70 @@ export default function FinxeptTerminal() {const minutesRemaining = Math.floor(((expiryTime - now) % (1000 * 60 * 60)) / (1000 * 60));if (hoursRemaining > 0) {- return `👤 Guest (${hoursRemaining}h ${minutesRemaining}m remaining)`;+ timeText = ` (${hoursRemaining}h ${minutesRemaining}m remaining)`;} else if (minutesRemaining > 0) {- return `👤 Guest (${minutesRemaining}m remaining)`;+ timeText = ` (${minutesRemaining}m remaining)`;} else {- return '👤 Guest (Expired)';+ timeText = ' (Expired)';}}- return '👤 Guest User';++ return (+ <span style={{ color: '#fbbf24', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span+ onClick={() => setActiveTab('profile')}+ style={{ cursor: 'pointer', textDecoration: 'underline' }}+ title="Go to Profile"+ >+ 👤 Guest+ </span>+ <span>{timeText}</span>+ <span style={{ color: '#787878' }}>|</span>+ <span+ onClick={() => navigation.navigateToPricing()}+ style={{ cursor: 'pointer', textDecoration: 'underline' }}+ title="View Plans"+ >+ 📦 View Plans+ </span>+ </span>+ );} else if (session.user_type === 'registered') {const username = session.user_info?.username || session.user_info?.email || 'User';const accountType = session.user_info?.account_type || 'free';const hasSubscription = (session.subscription as any)?.data?.has_subscription || session.subscription?.has_subscription;+ const planName = hasSubscription+ ? ((session.subscription as any)?.data?.subscription?.plan?.name || session.subscription?.subscription?.plan?.name || accountType)+ : (accountType === 'free' ? 'Free Plan' : accountType.charAt(0).toUpperCase() + accountType.slice(1));- // Show account type badge- if (hasSubscription) {- const planName = (session.subscription as any)?.data?.subscription?.plan?.name || session.subscription?.subscription?.plan?.name || accountType;- return `👤 ${username} | 📦 ${planName} | ✅ Active`;- } else if (accountType === 'free') {- return `👤 ${username} | 📦 Free Plan`;- } else {- return `👤 ${username} | 📦 ${accountType.charAt(0).toUpperCase() + accountType.slice(1)}`;- }+ return (+ <span style={{ color: '#fbbf24', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span+ onClick={() => setActiveTab('profile')}+ style={{ cursor: 'pointer', textDecoration: 'underline' }}+ title="Go to Profile"+ >+ 👤 {username}+ </span>+ <span style={{ color: '#787878' }}>|</span>+ <span+ onClick={() => navigation.navigateToPricing()}+ style={{ cursor: 'pointer', textDecoration: 'underline' }}+ title={hasSubscription ? 'Change Plan' : 'View Plans'}+ >+ 📦 {planName}+ </span>+ {hasSubscription && (+ <>+ <span style={{ color: '#787878' }}>|</span>+ <span>✅ Active</span>+ </>+ )}+ </span>+ );}- return 'Unknown Session';+ return <span style={{ color: '#fbbf24', fontSize: '10px' }}>Unknown Session</span>;};const toggleFullscreen = () => {@@ -376,7 +419,7 @@ export default function FinxeptTerminal() {>{isFullscreen ? <Minimize size={14} /> : <Maximize size={14} />}</button>- <span style={{ color: '#fbbf24', fontSize: '10px' }}>{getSessionDisplay()}</span>+ {getClickableSessionDisplay()}<buttononClick={async () => {setStatusMessage("Logging out...");@@ -629,6 +672,12 @@ export default function FinxeptTerminal() {style={activeTab === 'datamapping' ? tabStyles.active : tabStyles.default}>Data Mapping+ <TabsTrigger+ value="support"+ style={activeTab === 'support' ? tabStyles.active : tabStyles.default}+ >+ Support+ </TabsTrigger></TabsTrigger></TabsList></Tabs>@@ -766,6 +815,9 @@ export default function FinxeptTerminal() {<TabsContent value="datasources" className="h-full m-0 p-0"><DataSourcesTab /></TabsContent>+ <TabsContent value="support" className="h-full m-0 p-0">+ <SupportTicketTab />+ </TabsContent><TabsContent value="agents" className="h-full m-0 p-0"><AgentsTab /></TabsContent>diff --git a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsxindex 47f38b34d..dd0d32bff 100644--- a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx@@ -1,4 +1,6 @@import React, { useState, useEffect } from 'react';+import { useAuth } from '../../contexts/AuthContext';+import { ForumApiService, ForumPost as APIForumPost, ForumCategory, ForumStats, ForumComment as APIForumComment } from '../../services/forumApi';interface ForumPost {id: string;@@ -7,15 +9,26 @@ interface ForumPost {title: string;content: string;category: string;+ categoryId: number;tags: string[];views: number;replies: number;likes: number;+ dislikes: number;sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL';priority: 'HOT' | 'TRENDING' | 'NORMAL';verified: boolean;}+interface ForumComment {+ id: string;+ author: string;+ content: string;+ time: string;+ likes: number;+ dislikes: number;+}+interface ForumUser {username: string;reputation: number;@@ -25,10 +38,47 @@ interface ForumUser {}const ForumTab: React.FC = () => {+ const { session } = useAuth();const [currentTime, setCurrentTime] = useState(new Date());const [activeCategory, setActiveCategory] = useState('ALL');- const [sortBy, setSortBy] = useState('LATEST');+ const [sortBy, setSortBy] = useState('latest');const [onlineUsers, setOnlineUsers] = useState(1247);+ const [isLoading, setIsLoading] = useState(false);++ // Modal states+ const [showCreatePost, setShowCreatePost] = useState(false);+ const [showPostDetail, setShowPostDetail] = useState(false);+ const [showSearch, setShowSearch] = useState(false);+ const [showProfile, setShowProfile] = useState(false);+ const [showEditProfile, setShowEditProfile] = useState(false);++ // Selected data+ const [selectedPost, setSelectedPost] = useState<ForumPost | null>(null);+ const [postComments, setPostComments] = useState<ForumComment[]>([]);+ const [selectedUsername, setSelectedUsername] = useState<string>('');++ // Form states+ const [newPostTitle, setNewPostTitle] = useState('');+ const [newPostContent, setNewPostContent] = useState('');+ const [newComment, setNewComment] = useState('');+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<ForumPost[]>([]);++ // Profile states+ const [userProfile, setUserProfile] = useState<any>(null);+ const [profileEdit, setProfileEdit] = useState({+ display_name: '',+ bio: '',+ avatar_color: '#FFA500',+ signature: ''+ });++ // API Data states+ const [categories, setCategories] = useState<Array<{ name: string; count: number; color: string; id: number }>>([]);+ const [forumPosts, setForumPosts] = useState<ForumPost[]>([]);+ const [forumStats, setForumStats] = useState<ForumStats | null>(null);+ const [trendingTopics, setTrendingTopics] = useState<Array<{ topic: string; mentions: number; sentiment: string; change: string }>>([]);+ const [recentActivity, setRecentActivity] = useState<Array<{ user: string; action: string; target: string; time: string }>>([]);// Bloomberg color schemeconst BLOOMBERG_ORANGE = '#FFA500';@@ -43,137 +93,7 @@ const ForumTab: React.FC = () => {const BLOOMBERG_DARK_BG = '#000000';const BLOOMBERG_PANEL_BG = '#0a0a0a';- useEffect(() => {- const timer = setInterval(() => {- setCurrentTime(new Date());- setOnlineUsers(prev => prev + Math.floor(Math.random() * 10) - 5);- }, 5000);- return () => clearInterval(timer);- }, []);-- const forumPosts: ForumPost[] = [- {- id: '1',- time: '16:52:18',- author: 'QuantTrader_Pro',- title: 'Fed Rate Decision Analysis - 75bps Cut Implications for Q2 2024',- content: 'Deep analysis of the Federal Reserve\'s emergency rate cut decision. Historical precedents from 2008 and 2020 suggest this could trigger a sustained equity rally. My quant models show S&P 500 has 78% probability of hitting 4,950 within 30 days. Key sectors to watch: Tech (AI infrastructure), Regional Banks (benefiting from rate cuts), Real Estate (commercial REITs). However, watch for potential stagflation risks if inflation doesn\'t respond as expected. Technical analysis shows strong support at 4,750 with RSI indicating oversold conditions in previous weeks. Options market is pricing in 15% move in either direction - suggesting high uncertainty. My personal position: Long QQQ calls, Short VIX, Hedged with TLT puts.',- category: 'MARKETS',- tags: ['FED', 'RATES', 'ANALYSIS', 'S&P500'],- views: 8924,- replies: 156,- likes: 342,- sentiment: 'BULLISH',- priority: 'HOT',- verified: true- },- {- id: '2',- time: '16:48:33',- author: 'TechInvestor88',- title: 'NVIDIA Q4 Earnings Preview - AI Chip Demand Analysis',- content: 'NVDA earnings expected next week. My channel checks with data center operators suggest GPU orders are up 40% QoQ. H100 chips still have 6-month waiting lists. Competition from AMD and custom chips (Google TPU, Amazon Trainium) not materially impacting market share yet. Guidance will be key - looking for $30B+ revenue guidance for FY2024. Stock trading at 45x forward earnings which seems reasonable given 50%+ revenue growth. Potential risks: export restrictions to China (20% of revenue), datacenter capex slowdown, margin compression from next-gen Blackwell chips. My play: Selling $650 puts, buying $750 calls for earnings week. High IV makes this attractive. What are your thoughts on the competitive landscape?',- category: 'TECH',- tags: ['NVDA', 'EARNINGS', 'AI', 'SEMICONDUCTORS'],- views: 6234,- replies: 89,- likes: 278,- sentiment: 'BULLISH',- priority: 'TRENDING',- verified: true- },- {- id: '3',- time: '16:45:12',- author: 'CryptoWhale_2024',- title: 'Bitcoin ETF Approval - Historical Analysis of Gold ETF Launch 2004',- content: 'Now that spot BTC ETFs are approved, I did historical analysis of what happened when Gold ETF (GLD) launched in Nov 2004. Gold was at $450/oz and rallied to $1,900/oz over next 7 years (322% gain). Key differences: Gold already had massive institutional adoption, BTC is earlier in adoption curve. Similarities: Both are "digital gold" narratives, both faced regulatory skepticism, both had futures products before ETFs. My projection: BTC could see $100K within 12-18 months as institutional allocations begin. Fidelity alone has $4.5T AUM - even 1% allocation would be $45B into BTC market. However, watch for: Grayscale GBTC redemptions (discount now closed), Mt. Gox distribution, regulatory changes. I\'m holding long-term, targeting $150K by end of 2025.',- category: 'CRYPTO',- tags: ['BTC', 'ETF', 'INSTITUTIONS', 'GOLD'],- views: 5823,- replies: 142,- likes: 401,- sentiment: 'BULLISH',- priority: 'HOT',- verified: true- },- {- id: '4',- time: '16:41:45',- author: 'EnergyAnalyst_TX',- title: 'Saudi Arabia Production Cuts - Oil Supply Dynamics Through 2024',- content: 'Saudi extending voluntary 1M bpd cuts through Q2. This is critical because global oil inventories are already at 5-year lows. US SPR still depleted (365M barrels vs 650M historical). Demand side: China reopening could add 1.5M bpd demand, US summer driving season approaching. Supply side: US shale growth plateauing at 13M bpd, OPEC+ discipline stronger than expected. My price targets: Brent $95-105 range for Q2/Q3, potential spike to $120 if geopolitical tensions escalate (Middle East, Russia). How to play: Long XLE (energy sector ETF), individual picks - CVX and XOM for stability + dividends, smaller E&Ps for leverage (DVN, FANG). Alternative plays: Refined products (crack spreads widening), tanker stocks (shipping rates up 40% YoY). Risks: Demand destruction above $100/bbl, surprise OPEC production increases.',- category: 'ENERGY',- tags: ['OIL', 'OPEC', 'COMMODITIES', 'ENERGY'],- views: 4156,- replies: 67,- likes: 189,- sentiment: 'BULLISH',- priority: 'TRENDING',- verified: true- },- {- id: '5',- time: '16:38:22',- author: 'BankingInsider',- title: 'JPMorgan Q4 Beat - What It Means for Regional Banks',- content: 'JPM crushed earnings with $15.2B profit. Key takeaway: Net Interest Margin held up despite rate uncertainty. Credit quality remains strong (provisions down 34%). But here\'s what matters for regional banks (KRE, RF, CFG): JPM benefited from deposit flight FROM regional banks after SVB collapse. They gained $200B+ in deposits at near-zero cost. Regional banks face opposite dynamic: deposit costs up 200bps, commercial real estate exposure (office vacancy at 20%+ in major cities), wholesale funding pressure. My contrarian take: Some regional banks are now oversold. Look at tangible book value - many trading at 0.7x TBV. Potential acquisitions by larger banks could unlock value. Playing this with: Long USB and TFC (strong balance sheets), short SBNY and PACW (CRE exposure). Rate cuts actually help net interest income for banks - flattening curve is positive.',- category: 'BANKING',- tags: ['JPM', 'BANKS', 'EARNINGS', 'FINANCIALS'],- views: 3642,- replies: 78,- likes: 156,- sentiment: 'NEUTRAL',- priority: 'NORMAL',- verified: true- },- {- id: '6',- time: '16:35:01',- author: 'GlobalMacro_Trader',- title: 'China $2.8T Infrastructure Plan - Supply Chain and Commodity Implications',- content: 'China announced massive Belt & Road 2.0 initiative. This is bigger than most realize. $2.8T over 5 years = $560B annually (compare to China\'s 2023 GDP of $18T, this is 3% of GDP). Focus areas: AI infrastructure, renewable energy (solar/wind), digital connectivity, ports/logistics. Commodity implications: Steel demand up (already seeing Chinese rebar futures +8%), Copper demand massive (EV charging, grid infrastructure), Rare earths (tech components), Lithium (battery supply chain). Equity plays: Chinese infrastructure stocks (obviously), but ALSO emerging market infrastructure plays (Indonesia, Vietnam, Pakistan). Commodity plays: FCX (copper), ALB (lithium), MP (rare earths). Currency implications: Yuan strength short-term as capital flows in, but medium-term weakness as China exports inflation via commodity demand. This is 2008-2010 China stimulus playbook 2.0. Worked then, could work again.',- category: 'GLOBAL',- tags: ['CHINA', 'INFRASTRUCTURE', 'COMMODITIES', 'EM'],- views: 3198,- replies: 54,- likes: 134,- sentiment: 'BULLISH',- priority: 'NORMAL',- verified: false- },- {- id: '7',- time: '16:32:18',- author: 'OptionsFlow_Alert',- title: 'Massive Call Sweeps in Tech Stocks - Someone Knows Something',- content: 'Unusual options activity detected across multiple tech names. MSFT: 50,000 calls at $400 strike expiring March (premium paid: $45M). GOOGL: 30,000 calls at $150 strike Feb expiry ($22M premium). META: 25,000 calls at $380 strike March ($31M). These are NOT retail traders - this is institutional flow, paying up for upside. Timing suspicious: 2 days before big tech earnings start. Either hedge funds positioning for earnings beats, or insiders know something about AI monetization that market doesn\'t. Historical precedent: Similar unusual activity preceded NVDA\'s 60% rally last year. My interpretation: Smart money is betting on AI revenue acceleration across cloud/advertising. Playing this with: Long dated calls on QQQ and XLK, selling near-term puts to finance. Risk/reward heavily skewed to upside if thesis correct. Monitoring daily options flow for any reversals.',- category: 'OPTIONS',- tags: ['OPTIONS', 'TECH', 'FLOW', 'UNUSUAL_ACTIVITY'],- views: 7234,- replies: 134,- likes: 423,- sentiment: 'BULLISH',- priority: 'HOT',- verified: true- },- {- id: '8',- time: '16:28:45',- author: 'MacroHedgeFund',- title: 'Yield Curve Un-Inversion - Historical Recession Indicator Analysis',- content: 'The 2-10 year Treasury yield curve just un-inverted after 18 months inverted. Historical data: Every recession since 1970 was preceded by curve inversion FOLLOWED by un-inversion. Average lag between un-inversion and recession: 6-12 months. Current situation: Curve un-inverting due to Fed rate cuts (short end falling faster than long end). Question is whether this is "soft landing" scenario or delayed recession. Bull case: Inflation under control, employment strong, consumer spending resilient, corporate earnings growing. Bear case: Leading indicators weak (PMI, LEI, yield curve), commercial real estate stress, consumer credit deteriorating, geopolitical risks. My positioning: Cautiously bullish equities but hedged with TLT (long duration treasuries rally in recession), Gold (safe haven), defensive sectors (utilities, consumer staples). Time horizon matters - 6 month view bullish, 12-18 month view increasingly cautious.',- category: 'MACRO',- tags: ['BONDS', 'RECESSION', 'YIELD_CURVE', 'MACRO'],- views: 4523,- replies: 89,- likes: 267,- sentiment: 'NEUTRAL',- priority: 'TRENDING',- verified: true- }- ];-+ // Top contributors - static for nowconst topContributors: ForumUser[] = [{ username: 'QuantTrader_Pro', reputation: 8947, posts: 1234, joined: '2021-03-15', status: 'ONLINE' },{ username: 'CryptoWhale_2024', reputation: 7823, posts: 892, joined: '2020-11-22', status: 'ONLINE' },@@ -183,17 +103,444 @@ const ForumTab: React.FC = () => {{ username: 'EnergyAnalyst_TX', reputation: 5892, posts: 521, joined: '2021-09-30', status: 'ONLINE' }];- const categories = [- { name: 'ALL', count: 8947, color: BLOOMBERG_WHITE },- { name: 'MARKETS', count: 2341, color: BLOOMBERG_BLUE },- { name: 'TECH', count: 1876, color: BLOOMBERG_PURPLE },- { name: 'CRYPTO', count: 1654, color: BLOOMBERG_CYAN },- { name: 'OPTIONS', count: 1234, color: BLOOMBERG_YELLOW },- { name: 'BANKING', count: 987, color: BLOOMBERG_GREEN },- { name: 'ENERGY', count: 876, color: BLOOMBERG_ORANGE },- { name: 'MACRO', count: 654, color: BLOOMBERG_RED },- { name: 'GLOBAL', count: 543, color: BLOOMBERG_PURPLE }- ];+ // Get API credentials+ const getApiCredentials = () => {+ const apiKey = session?.api_key || localStorage.getItem('fincept_api_key');+ const deviceId = session?.device_id || localStorage.getItem('fincept_device_id');+ return { apiKey, deviceId };+ };++ // Convert API post to UI format+ const convertApiPostToUIFormat = (apiPost: APIForumPost): ForumPost => {+ const voteScore = apiPost.likes - apiPost.dislikes;+ const sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL' = voteScore > 10 ? 'BULLISH' : voteScore < -5 ? 'BEARISH' : 'NEUTRAL';+ const priority: 'HOT' | 'TRENDING' | 'NORMAL' = apiPost.likes > 300 ? 'HOT' : apiPost.likes > 150 ? 'TRENDING' : 'NORMAL';++ const tagMatches = apiPost.content.match(/#\w+/g) || [];+ const tags = tagMatches.slice(0, 5).map(tag => tag.substring(1));++ return {+ id: apiPost.post_uuid,+ time: new Date(apiPost.created_at).toLocaleTimeString('en-US', { hour12: false }),+ author: apiPost.author_display_name || 'Anonymous',+ title: apiPost.title,+ content: apiPost.content,+ category: apiPost.category_name?.toUpperCase() || 'GENERAL',+ categoryId: apiPost.category_id,+ tags: tags.length > 0 ? tags : ['DISCUSSION'],+ views: apiPost.views || 0,+ replies: apiPost.reply_count || 0,+ likes: apiPost.likes || 0,+ dislikes: apiPost.dislikes || 0,+ sentiment,+ priority,+ verified: apiPost.likes > 100+ };+ };++ // Convert API comment to UI format+ const convertApiCommentToUIFormat = (apiComment: APIForumComment): ForumComment => {+ return {+ id: apiComment.comment_uuid,+ author: apiComment.author_display_name || 'Anonymous',+ content: apiComment.content,+ time: new Date(apiComment.created_at).toLocaleTimeString('en-US', { hour12: false }),+ likes: apiComment.likes || 0,+ dislikes: apiComment.dislikes || 0+ };+ };++ // ENDPOINT 1: Fetch forum categories+ const fetchCategories = async () => {+ try {+ const { apiKey, deviceId } = getApiCredentials();+ const response = await ForumApiService.getCategories(apiKey, deviceId);++ if (response.success && response.data?.data?.categories) {+ const apiCategories = response.data.data.categories;+ const categoryColors = [+ BLOOMBERG_BLUE, BLOOMBERG_PURPLE, BLOOMBERG_CYAN, BLOOMBERG_YELLOW,+ BLOOMBERG_GREEN, BLOOMBERG_ORANGE, BLOOMBERG_RED, BLOOMBERG_PURPLE+ ];++ const formattedCategories = [+ { name: 'ALL', count: apiCategories.reduce((sum: number, cat: ForumCategory) => sum + cat.post_count, 0), color: BLOOMBERG_WHITE, id: 0 },+ ...apiCategories.map((cat: ForumCategory, index: number) => ({+ name: cat.name.toUpperCase(),+ count: cat.post_count,+ color: categoryColors[index % categoryColors.length],+ id: cat.id+ }))+ ];++ setCategories(formattedCategories);+ }+ } catch (error) {+ console.error('Error fetching categories:', error);+ }+ };++ // ENDPOINT 2 & 6: Fetch forum posts (by category or trending)+ const fetchPosts = async () => {+ setIsLoading(true);+ try {+ const { apiKey, deviceId } = getApiCredentials();+ let response;++ if (activeCategory === 'ALL') {+ if (sortBy === 'popular') {+ response = await ForumApiService.getTrendingPosts(20, 'week', apiKey, deviceId);+ } else {+ const categoryId = categories.find(c => c.name !== 'ALL')?.id || 1;+ response = await ForumApiService.getPostsByCategory(categoryId, sortBy, 20, apiKey, deviceId);+ }+ } else {+ const categoryId = categories.find(c => c.name === activeCategory)?.id;+ if (categoryId) {+ response = await ForumApiService.getPostsByCategory(categoryId, sortBy, 20, apiKey, deviceId);+ }+ }++ if (response?.success && response.data?.data) {+ const posts = response.data.data.posts || [];+ const formattedPosts = posts.map(convertApiPostToUIFormat);+ setForumPosts(formattedPosts);+ }+ } catch (error) {+ console.error('Error fetching posts:', error);+ } finally {+ setIsLoading(false);+ }+ };++ // ENDPOINT 5: Fetch forum statistics+ const fetchForumStats = async () => {+ try {+ const { apiKey, deviceId } = getApiCredentials();+ const response = await ForumApiService.getForumStats(apiKey, deviceId);++ if (response.success && response.data?.data) {+ setForumStats(response.data.data);+ if (response.data.data.active_users) {+ setOnlineUsers(response.data.data.active_users);+ }+ }+ } catch (error) {+ console.error('Error fetching forum stats:', error);+ }+ };++ // ENDPOINT 7: Create new post+ const handleCreatePost = async () => {+ // Validation+ if (!newPostTitle.trim()) {+ alert('Please enter a post title');+ return;+ }+ if (newPostTitle.trim().length < 5) {+ alert('Post title must be at least 5 characters long');+ return;+ }+ if (newPostTitle.trim().length > 500) {+ alert('Post title must be less than 500 characters');+ return;+ }+ if (!newPostContent.trim()) {+ alert('Please enter post content');+ return;+ }+ if (newPostContent.trim().length < 10) {+ alert('Post content must be at least 10 characters long');+ return;+ }++ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) {+ alert('You must be logged in to create posts');+ return;+ }++ const categoryId = categories.find(c => c.name === activeCategory)?.id || categories[1]?.id || 1;++ try {+ const response = await ForumApiService.createPost(+ categoryId,+ { title: newPostTitle.trim(), content: newPostContent.trim() },+ apiKey,+ deviceId+ );++ if (response.success) {+ alert('Post created successfully!');+ setShowCreatePost(false);+ setNewPostTitle('');+ setNewPostContent('');+ fetchPosts(); // Refresh posts+ } else {+ alert(`Failed to create post: ${response.error || response.data?.message || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Error creating post:', error);+ alert('Error creating post');+ }+ };++ // ENDPOINT 3 & 4: View post details with comments+ const handleViewPost = async (post: ForumPost) => {+ setSelectedPost(post);+ setShowPostDetail(true);++ const { apiKey, deviceId } = getApiCredentials();+ try {+ const response = await ForumApiService.getPostDetails(post.id, apiKey, deviceId);++ if (response.success && response.data?.data) {+ const comments = response.data.data.comments || [];+ const formattedComments = comments.map(convertApiCommentToUIFormat);+ setPostComments(formattedComments);+ }+ } catch (error) {+ console.error('Error fetching post details:', error);+ }+ };++ // ENDPOINT 8: Add comment to post+ const handleAddComment = async () => {+ if (!newComment.trim() || !selectedPost) return;++ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) {+ alert('You must be logged in to comment');+ return;+ }++ try {+ const response = await ForumApiService.addComment(+ selectedPost.id,+ { content: newComment },+ apiKey,+ deviceId+ );++ if (response.success) {+ setNewComment('');+ // Refresh post details+ handleViewPost(selectedPost);+ } else {+ alert(`Failed to add comment: ${response.error || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Error adding comment:', error);+ alert('Error adding comment');+ }+ };++ // ENDPOINT 9: Vote on post+ const handleVotePost = async (postId: string, voteType: 'up' | 'down') => {+ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) {+ alert('You must be logged in to vote');+ return;+ }++ try {+ const response = await ForumApiService.voteOnPost(postId, voteType, apiKey, deviceId);++ if (response.success) {+ fetchPosts(); // Refresh posts to show updated vote counts+ if (selectedPost && selectedPost.id === postId) {+ handleViewPost(selectedPost); // Refresh post detail if viewing+ }+ } else {+ alert(`Vote failed: ${response.error || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Error voting on post:', error);+ }+ };++ // ENDPOINT 10: Vote on comment+ const handleVoteComment = async (commentId: string, voteType: 'up' | 'down') => {+ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) {+ alert('You must be logged in to vote');+ return;+ }++ try {+ const response = await ForumApiService.voteOnComment(commentId, voteType, apiKey, deviceId);++ if (response.success && selectedPost) {+ handleViewPost(selectedPost); // Refresh comments+ }+ } catch (error) {+ console.error('Error voting on comment:', error);+ }+ };++ // ENDPOINT 4: Search forum+ const handleSearch = async () => {+ if (!searchQuery.trim()) return;++ const { apiKey, deviceId } = getApiCredentials();+ setIsLoading(true);++ try {+ const response = await ForumApiService.searchPosts(searchQuery, 'all', 20, apiKey, deviceId);++ if (response.success && response.data?.data?.results?.posts) {+ const posts = response.data.data.results.posts;+ const formattedPosts = posts.map(convertApiPostToUIFormat);+ setSearchResults(formattedPosts);+ }+ } catch (error) {+ console.error('Error searching:', error);+ } finally {+ setIsLoading(false);+ }+ };++ // ENDPOINT 12: Get my profile+ const handleViewMyProfile = async () => {+ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) {+ alert('You must be logged in to view profile');+ return;+ }++ try {+ const response = await ForumApiService.getMyProfile(apiKey, deviceId);++ if (response.success && response.data?.data?.profile) {+ const profile = response.data.data.profile;+ setUserProfile(profile);+ setProfileEdit({+ display_name: profile.display_name || '',+ bio: profile.bio || '',+ avatar_color: profile.avatar_color || '#FFA500',+ signature: profile.signature || ''+ });+ setShowProfile(true);+ }+ } catch (error) {+ console.error('Error fetching profile:', error);+ alert('Error loading profile');+ }+ };++ // ENDPOINT 11: Get user profile+ const handleViewUserProfile = async (username: string) => {+ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) {+ alert('You must be logged in to view profiles');+ return;+ }++ setSelectedUsername(username);++ try {+ const response = await ForumApiService.getUserProfile(username, apiKey, deviceId);++ if (response.success && response.data?.data?.profile) {+ setUserProfile(response.data.data.profile);+ setShowProfile(true);+ }+ } catch (error) {+ console.error('Error fetching user profile:', error);+ alert('Error loading user profile');+ }+ };++ // ENDPOINT 13: Update profile+ const handleUpdateProfile = async () => {+ const { apiKey, deviceId } = getApiCredentials();+ if (!apiKey) return;++ try {+ const response = await ForumApiService.updateProfile(profileEdit, apiKey, deviceId);++ if (response.success) {+ alert('Profile updated successfully!');+ setShowEditProfile(false);+ handleViewMyProfile(); // Refresh profile+ } else {+ alert(`Failed to update profile: ${response.error || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Error updating profile:', error);+ alert('Error updating profile');+ }+ };++ // Generate trending topics from posts+ const generateTrendingTopics = () => {+ const topicsMap: { [key: string]: { count: number; sentiment: string } } = {};++ forumPosts.forEach(post => {+ post.tags.forEach(tag => {+ const topic = `#${tag}`;+ if (!topicsMap[topic]) {+ topicsMap[topic] = { count: 0, sentiment: 'NEUTRAL' };+ }+ topicsMap[topic].count += 1;+ if (post.sentiment === 'BULLISH') topicsMap[topic].sentiment = 'BULLISH';+ });+ });++ const trending = Object.entries(topicsMap)+ .map(([topic, data]) => ({+ topic,+ mentions: data.count * 100,+ sentiment: data.sentiment,+ change: `+${Math.floor(Math.random() * 200 + 50)}%`+ }))+ .sort((a, b) => b.mentions - a.mentions)+ .slice(0, 6);++ setTrendingTopics(trending);+ };++ // Generate recent activity from posts+ const generateRecentActivity = () => {+ const activities = forumPosts.slice(0, 5).map((post, index) => ({+ user: post.author,+ action: index % 3 === 0 ? 'posted' : index % 3 === 1 ? 'replied to' : 'liked',+ target: post.title.substring(0, 30) + '...',+ time: `${(index + 1) * 3} min ago`+ }));++ setRecentActivity(activities);+ };++ // Initial load+ useEffect(() => {+ fetchCategories();+ fetchForumStats();+ }, []);++ // Fetch posts when category or sort changes+ useEffect(() => {+ if (categories.length > 0) {+ fetchPosts();+ }+ }, [activeCategory, sortBy, categories]);++ // Generate derived data+ useEffect(() => {+ if (forumPosts.length > 0) {+ generateTrendingTopics();+ generateRecentActivity();+ }+ }, [forumPosts]);++ // Update clock+ useEffect(() => {+ const timer = setInterval(() => {+ setCurrentTime(new Date());+ setOnlineUsers(prev => Math.max(1000, prev + Math.floor(Math.random() * 10) - 5));+ }, 5000);+ return () => clearInterval(timer);+ }, []);const getPriorityColor = (priority: string) => {switch (priority) {@@ -217,6 +564,665 @@ const ForumTab: React.FC = () => {? forumPosts: forumPosts.filter(post => post.category === activeCategory);+ const totalPosts = forumStats?.total_posts || categories.find(c => c.name === 'ALL')?.count || 0;+ const postsToday = Math.floor(totalPosts * 0.003);++ // Modal components - useMemo to prevent re-creation and fix input focus+ const CreatePostModal = React.useMemo(() => {+ if (!showCreatePost) return null;+ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.85)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_PANEL_BG,+ border: `2px solid ${BLOOMBERG_ORANGE}`,+ padding: '16px',+ width: '600px',+ maxHeight: '80vh',+ overflow: 'auto'+ }}>+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>+ CREATE NEW POST+ </div>+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', marginBottom: '4px' }}>+ Title: <span style={{ color: newPostTitle.length < 5 ? BLOOMBERG_RED : BLOOMBERG_GREEN }}>+ ({newPostTitle.length}/500 chars - min 5)+ </span>+ </div>+ <input+ type="text"+ value={newPostTitle}+ onChange={(e) => setNewPostTitle(e.target.value)}+ maxLength={500}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${newPostTitle.length > 0 && newPostTitle.length < 5 ? BLOOMBERG_RED : BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '12px',+ fontFamily: 'Consolas, monospace'+ }}+ placeholder="Enter post title (minimum 5 characters)..."+ />+ </div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', marginBottom: '4px' }}>+ Content: <span style={{ color: newPostContent.length < 10 ? BLOOMBERG_RED : BLOOMBERG_GREEN }}>+ ({newPostContent.length}/10000 chars - min 10)+ </span>+ </div>+ <textarea+ value={newPostContent}+ onChange={(e) => setNewPostContent(e.target.value)}+ maxLength={10000}+ rows={10}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${newPostContent.length > 0 && newPostContent.length < 10 ? BLOOMBERG_RED : BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace',+ resize: 'vertical'+ }}+ placeholder="Enter post content (minimum 10 characters)... Use #tags for topics"+ />+ </div>++ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>+ <button+ onClick={() => setShowCreatePost(false)}+ style={{+ backgroundColor: BLOOMBERG_GRAY,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '6px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleCreatePost}+ style={{+ backgroundColor: BLOOMBERG_ORANGE,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '6px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ CREATE POST+ </button>+ </div>+ </div>+ </div>+ );+ }, [showCreatePost, newPostTitle, newPostContent, handleCreatePost, BLOOMBERG_ORANGE, BLOOMBERG_GRAY, BLOOMBERG_DARK_BG, BLOOMBERG_WHITE, BLOOMBERG_RED, BLOOMBERG_GREEN, BLOOMBERG_PANEL_BG]);++ const PostDetailModal = React.useMemo(() => {+ if (!showPostDetail || !selectedPost) return null;+ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.85)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_PANEL_BG,+ border: `2px solid ${BLOOMBERG_ORANGE}`,+ padding: '16px',+ width: '800px',+ maxHeight: '80vh',+ overflow: 'auto'+ }}>+ {selectedPost && (+ <>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold' }}>+ POST DETAILS+ </div>+ <button+ onClick={() => setShowPostDetail(false)}+ style={{+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '2px 8px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ CLOSE [X]+ </button>+ </div>+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>++ {/* Post content */}+ <div style={{ marginBottom: '16px' }}>+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '8px', fontSize: '10px' }}>+ <span style={{ color: BLOOMBERG_CYAN }}>@{selectedPost.author}</span>+ <span style={{ color: BLOOMBERG_GRAY }}>•</span>+ <span style={{ color: BLOOMBERG_BLUE }}>[{selectedPost.category}]</span>+ <span style={{ color: getSentimentColor(selectedPost.sentiment) }}>{selectedPost.sentiment}</span>+ </div>++ <div style={{ color: BLOOMBERG_WHITE, fontSize: '13px', fontWeight: 'bold', marginBottom: '8px' }}>+ {selectedPost.title}+ </div>++ <div style={{ color: BLOOMBERG_GRAY, fontSize: '11px', lineHeight: '1.5', marginBottom: '8px', whiteSpace: 'pre-wrap' }}>+ {selectedPost.content}+ </div>++ <div style={{ display: 'flex', gap: '12px', fontSize: '10px', marginBottom: '8px' }}>+ <button+ onClick={() => handleVotePost(selectedPost.id, 'up')}+ style={{+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG_GREEN}`,+ color: BLOOMBERG_GREEN,+ padding: '4px 12px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ ▲ UPVOTE ({selectedPost.likes})+ </button>+ <button+ onClick={() => handleVotePost(selectedPost.id, 'down')}+ style={{+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG_RED}`,+ color: BLOOMBERG_RED,+ padding: '4px 12px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ ▼ DOWNVOTE ({selectedPost.dislikes})+ </button>+ </div>+ </div>++ <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '12px', marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>+ COMMENTS ({postComments.length})+ </div>++ {/* Add comment form */}+ <div style={{ marginBottom: '12px' }}>+ <textarea+ value={newComment}+ onChange={(e) => setNewComment(e.target.value)}+ maxLength={2000}+ rows={3}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace',+ marginBottom: '4px'+ }}+ placeholder="Add a comment..."+ />+ <button+ onClick={handleAddComment}+ style={{+ backgroundColor: BLOOMBERG_ORANGE,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '4px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ POST COMMENT+ </button>+ </div>++ {/* Comments list */}+ {postComments.map((comment, index) => (+ <div key={comment.id} style={{+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',+ padding: '8px',+ marginBottom: '6px',+ borderLeft: `2px solid ${BLOOMBERG_BLUE}`+ }}>+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '4px', fontSize: '9px' }}>+ <span style={{ color: BLOOMBERG_CYAN }}>@{comment.author}</span>+ <span style={{ color: BLOOMBERG_GRAY }}>•</span>+ <span style={{ color: BLOOMBERG_GRAY }}>{comment.time}</span>+ </div>++ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px', marginBottom: '4px', whiteSpace: 'pre-wrap' }}>+ {comment.content}+ </div>++ <div style={{ display: 'flex', gap: '8px', fontSize: '9px' }}>+ <button+ onClick={() => handleVoteComment(comment.id, 'up')}+ style={{+ backgroundColor: 'transparent',+ border: 'none',+ color: BLOOMBERG_GREEN,+ cursor: 'pointer',+ fontSize: '9px'+ }}+ >+ ▲ {comment.likes}+ </button>+ <button+ onClick={() => handleVoteComment(comment.id, 'down')}+ style={{+ backgroundColor: 'transparent',+ border: 'none',+ color: BLOOMBERG_RED,+ cursor: 'pointer',+ fontSize: '9px'+ }}+ >+ ▼ {comment.dislikes}+ </button>+ </div>+ </div>+ ))}+ </div>+ </>+ )}+ </div>+ </div>+ );+ }, [showPostDetail, selectedPost, postComments, newComment, handleAddComment, handleVotePost, handleVoteComment, getSentimentColor, BLOOMBERG_ORANGE, BLOOMBERG_GRAY, BLOOMBERG_WHITE, BLOOMBERG_DARK_BG, BLOOMBERG_PANEL_BG, BLOOMBERG_CYAN, BLOOMBERG_BLUE, BLOOMBERG_GREEN, BLOOMBERG_RED, BLOOMBERG_YELLOW]);++ const SearchModal = React.useMemo(() => {+ if (!showSearch) return null;+ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.85)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_PANEL_BG,+ border: `2px solid ${BLOOMBERG_ORANGE}`,+ padding: '16px',+ width: '700px',+ maxHeight: '80vh',+ overflow: 'auto'+ }}>+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>+ SEARCH FORUM+ </div>+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>++ <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>+ <input+ type="text"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyPress={(e) => e.key === 'Enter' && handleSearch()}+ style={{+ flex: 1,+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '8px',+ fontSize: '12px',+ fontFamily: 'Consolas, monospace'+ }}+ placeholder="Search posts and comments..."+ />+ <button+ onClick={handleSearch}+ style={{+ backgroundColor: BLOOMBERG_ORANGE,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '8px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ SEARCH+ </button>+ <button+ onClick={() => {+ setShowSearch(false);+ setSearchResults([]);+ setSearchQuery('');+ }}+ style={{+ backgroundColor: BLOOMBERG_GRAY,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '8px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ CLOSE+ </button>+ </div>++ {isLoading && (+ <div style={{ color: BLOOMBERG_YELLOW, textAlign: 'center', padding: '20px' }}>+ SEARCHING...+ </div>+ )}++ {searchResults.length > 0 && (+ <div>+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '11px', marginBottom: '8px' }}>+ FOUND {searchResults.length} RESULTS+ </div>+ {searchResults.map((post, index) => (+ <div+ key={post.id}+ onClick={() => {+ setShowSearch(false);+ handleViewPost(post);+ }}+ style={{+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',+ padding: '8px',+ marginBottom: '6px',+ borderLeft: `3px solid ${getPriorityColor(post.priority)}`,+ cursor: 'pointer'+ }}+ >+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>+ {post.title}+ </div>+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', marginBottom: '4px' }}>+ {post.content.substring(0, 150)}...+ </div>+ <div style={{ display: 'flex', gap: '8px', fontSize: '9px' }}>+ <span style={{ color: BLOOMBERG_CYAN }}>@{post.author}</span>+ <span style={{ color: BLOOMBERG_BLUE }}>[{post.category}]</span>+ <span style={{ color: BLOOMBERG_GREEN }}>👍 {post.likes}</span>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+ }, [showSearch, searchQuery, searchResults, isLoading, handleSearch, handleViewPost, getPriorityColor, BLOOMBERG_ORANGE, BLOOMBERG_GRAY, BLOOMBERG_DARK_BG, BLOOMBERG_WHITE, BLOOMBERG_PANEL_BG, BLOOMBERG_YELLOW, BLOOMBERG_CYAN, BLOOMBERG_BLUE, BLOOMBERG_GREEN]);++ const ProfileModal = React.useMemo(() => {+ if (!showProfile || !userProfile) return null;+ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.85)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_PANEL_BG,+ border: `2px solid ${BLOOMBERG_ORANGE}`,+ padding: '16px',+ width: '600px',+ maxHeight: '80vh',+ overflow: 'auto'+ }}>+ {userProfile && (+ <>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold' }}>+ FORUM PROFILE+ </div>+ <button+ onClick={() => {+ setShowProfile(false);+ setUserProfile(null);+ }}+ style={{+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '2px 8px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ CLOSE [X]+ </button>+ </div>+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_CYAN, fontSize: '16px', fontWeight: 'bold', marginBottom: '8px' }}>+ @{userProfile.username}+ </div>+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '12px', marginBottom: '4px' }}>+ {userProfile.display_name || 'No display name set'}+ </div>+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '11px', marginBottom: '12px', fontStyle: 'italic' }}>+ {userProfile.bio || 'No bio available'}+ </div>++ <div style={{ display: 'flex', gap: '16px', fontSize: '11px', marginBottom: '12px' }}>+ <div>+ <span style={{ color: BLOOMBERG_GRAY }}>Posts: </span>+ <span style={{ color: BLOOMBERG_WHITE }}>{userProfile.post_count || 0}</span>+ </div>+ <div>+ <span style={{ color: BLOOMBERG_GRAY }}>Comments: </span>+ <span style={{ color: BLOOMBERG_WHITE }}>{userProfile.comment_count || 0}</span>+ </div>+ <div>+ <span style={{ color: BLOOMBERG_GRAY }}>Reputation: </span>+ <span style={{ color: BLOOMBERG_GREEN }}>{userProfile.reputation || 0}</span>+ </div>+ </div>++ {userProfile.signature && (+ <div style={{+ backgroundColor: 'rgba(255,255,255,0.02)',+ padding: '8px',+ marginBottom: '12px',+ borderLeft: `2px solid ${BLOOMBERG_YELLOW}`+ }}>+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', marginBottom: '4px' }}>SIGNATURE:</div>+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', fontStyle: 'italic' }}>+ {userProfile.signature}+ </div>+ </div>+ )}++ {!selectedUsername && (+ <button+ onClick={() => {+ setShowProfile(false);+ setShowEditProfile(true);+ }}+ style={{+ backgroundColor: BLOOMBERG_ORANGE,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '6px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ EDIT PROFILE+ </button>+ )}+ </div>+ </>+ )}+ </div>+ </div>+ );+ }, [showProfile, userProfile, selectedUsername, BLOOMBERG_ORANGE, BLOOMBERG_GRAY, BLOOMBERG_WHITE, BLOOMBERG_DARK_BG, BLOOMBERG_PANEL_BG, BLOOMBERG_CYAN, BLOOMBERG_GREEN, BLOOMBERG_YELLOW]);++ const EditProfileModal = React.useMemo(() => {+ if (!showEditProfile) return null;+ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.85)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_PANEL_BG,+ border: `2px solid ${BLOOMBERG_ORANGE}`,+ padding: '16px',+ width: '600px',+ maxHeight: '80vh',+ overflow: 'auto'+ }}>+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>+ EDIT PROFILE+ </div>+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', marginBottom: '4px' }}>Display Name:</div>+ <input+ type="text"+ value={profileEdit.display_name}+ onChange={(e) => setProfileEdit({ ...profileEdit, display_name: e.target.value })}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '12px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', marginBottom: '4px' }}>Bio:</div>+ <textarea+ value={profileEdit.bio}+ onChange={(e) => setProfileEdit({ ...profileEdit, bio: e.target.value })}+ rows={4}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', marginBottom: '4px' }}>Signature:</div>+ <input+ type="text"+ value={profileEdit.signature}+ onChange={(e) => setProfileEdit({ ...profileEdit, signature: e.target.value })}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '12px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>+ <button+ onClick={() => setShowEditProfile(false)}+ style={{+ backgroundColor: BLOOMBERG_GRAY,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '6px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleUpdateProfile}+ style={{+ backgroundColor: BLOOMBERG_ORANGE,+ color: BLOOMBERG_DARK_BG,+ border: 'none',+ padding: '6px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer'+ }}+ >+ SAVE CHANGES+ </button>+ </div>+ </div>+ </div>+ );+ }, [showEditProfile, profileEdit, handleUpdateProfile, BLOOMBERG_ORANGE, BLOOMBERG_GRAY, BLOOMBERG_DARK_BG, BLOOMBERG_WHITE, BLOOMBERG_PANEL_BG]);+return (<div style={{height: '100%',@@ -242,18 +1248,18 @@ const ForumTab: React.FC = () => {<span style={{ color: BLOOMBERG_WHITE }}>|</span><span style={{ color: BLOOMBERG_YELLOW }}>USERS ONLINE: {onlineUsers.toLocaleString()}</span><span style={{ color: BLOOMBERG_WHITE }}>|</span>- <span style={{ color: BLOOMBERG_CYAN }}>POSTS TODAY: 2,847</span>+ <span style={{ color: BLOOMBERG_CYAN }}>POSTS TODAY: {postsToday.toLocaleString()}</span><span style={{ color: BLOOMBERG_WHITE }}>|</span><span style={{ color: BLOOMBERG_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span></div><div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}><span style={{ color: BLOOMBERG_GRAY }}>TRENDING:</span>- <span style={{ color: BLOOMBERG_RED }}>FED_RATES</span>- <span style={{ color: BLOOMBERG_CYAN }}>BTC_ETF</span>- <span style={{ color: BLOOMBERG_PURPLE }}>NVDA_EARNINGS</span>- <span style={{ color: BLOOMBERG_ORANGE }}>OIL_SUPPLY</span>- <span style={{ color: BLOOMBERG_GREEN }}>AI_REVENUE</span>+ {trendingTopics.slice(0, 5).map((topic, i) => (+ <span key={i} style={{ color: i % 2 === 0 ? BLOOMBERG_RED : i % 3 === 0 ? BLOOMBERG_CYAN : BLOOMBERG_PURPLE }}>+ {topic.topic.replace('#', '').toUpperCase()}+ </span>+ ))}<span style={{ color: BLOOMBERG_WHITE }}>|</span><span style={{ color: BLOOMBERG_GRAY }}>SENTIMENT:</span><span style={{ color: BLOOMBERG_GREEN }}>BULLISH 68%</span>@@ -271,32 +1277,32 @@ const ForumTab: React.FC = () => {}}><div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>{[- { key: "F1", label: "ALL", filter: "ALL" },- { key: "F2", label: "MARKETS", filter: "MARKETS" },- { key: "F3", label: "TECH", filter: "TECH" },- { key: "F4", label: "CRYPTO", filter: "CRYPTO" },- { key: "F5", label: "OPTIONS", filter: "OPTIONS" },- { key: "F6", label: "BANKING", filter: "BANKING" },- { key: "F7", label: "ENERGY", filter: "ENERGY" },- { key: "F8", label: "MACRO", filter: "MACRO" },- { key: "F9", label: "POST", filter: "POST" },- { key: "F10", label: "SEARCH", filter: "SEARCH" },- { key: "F11", label: "PROFILE", filter: "PROFILE" },- { key: "F12", label: "SETTINGS", filter: "SETTINGS" }+ { key: "F1", label: "ALL", action: () => setActiveCategory('ALL') },+ { key: "F2", label: categories[1]?.name || "MARKETS", action: () => setActiveCategory(categories[1]?.name || "MARKETS") },+ { key: "F3", label: categories[2]?.name || "TECH", action: () => setActiveCategory(categories[2]?.name || "TECH") },+ { key: "F4", label: categories[3]?.name || "CRYPTO", action: () => setActiveCategory(categories[3]?.name || "CRYPTO") },+ { key: "F5", label: categories[4]?.name || "OPTIONS", action: () => setActiveCategory(categories[4]?.name || "OPTIONS") },+ { key: "F6", label: categories[5]?.name || "BANKING", action: () => setActiveCategory(categories[5]?.name || "BANKING") },+ { key: "F7", label: categories[6]?.name || "ENERGY", action: () => setActiveCategory(categories[6]?.name || "ENERGY") },+ { key: "F8", label: categories[7]?.name || "MACRO", action: () => setActiveCategory(categories[7]?.name || "MACRO") },+ { key: "F9", label: "POST", action: () => setShowCreatePost(true) },+ { key: "F10", label: "SEARCH", action: () => setShowSearch(true) },+ { key: "F11", label: "PROFILE", action: () => handleViewMyProfile() },+ { key: "F12", label: "SETTINGS", action: () => setShowEditProfile(true) }].map(item => (<button key={item.key}- onClick={() => item.filter !== 'POST' && item.filter !== 'SEARCH' && item.filter !== 'PROFILE' && item.filter !== 'SETTINGS' && setActiveCategory(item.filter)}+ onClick={item.action}style={{- backgroundColor: activeCategory === item.filter ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,+ backgroundColor: activeCategory === item.label ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,border: `1px solid ${BLOOMBERG_GRAY}`,- color: activeCategory === item.filter ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,+ color: activeCategory === item.label ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,padding: '2px 4px',fontSize: '9px',height: '16px',display: 'flex',alignItems: 'center',justifyContent: 'center',- fontWeight: activeCategory === item.filter ? 'bold' : 'normal',+ fontWeight: activeCategory === item.label ? 'bold' : 'normal',cursor: 'pointer'}}><span style={{ color: BLOOMBERG_YELLOW }}>{item.key}:</span>@@ -349,12 +1355,15 @@ const ForumTab: React.FC = () => {TOP CONTRIBUTORS</div>{topContributors.map((user, index) => (- <div key={index} style={{- padding: '3px',- marginBottom: '2px',- backgroundColor: 'rgba(255,255,255,0.02)',- fontSize: '9px'- }}>+ <div key={index}+ onClick={() => handleViewUserProfile(user.username)}+ style={{+ padding: '3px',+ marginBottom: '2px',+ backgroundColor: 'rgba(255,255,255,0.02)',+ fontSize: '9px',+ cursor: 'pointer'+ }}><div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}><span style={{ color: BLOOMBERG_WHITE }}>{user.username}</span><span style={{ color: user.status === 'ONLINE' ? BLOOMBERG_GREEN : BLOOMBERG_GRAY }}>@@ -374,9 +1383,9 @@ const ForumTab: React.FC = () => {FORUM STATISTICS</div><div style={{ fontSize: '9px', lineHeight: '1.4', color: BLOOMBERG_GRAY }}>- <div>Total Posts: 894,234</div>- <div>Total Users: 47,832</div>- <div>Posts Today: 2,847</div>+ <div>Total Posts: {totalPosts.toLocaleString()}</div>+ <div>Total Users: {(forumStats?.total_comments || 47832).toLocaleString()}</div>+ <div>Posts Today: {postsToday.toLocaleString()}</div><div>Active Now: {onlineUsers}</div><div style={{ color: BLOOMBERG_GREEN }}>Avg Response: 12 min</div></div>@@ -394,26 +1403,27 @@ const ForumTab: React.FC = () => {<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}><div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>FORUM POSTS [{activeCategory}]+ {isLoading && <span style={{ color: BLOOMBERG_YELLOW, marginLeft: '8px' }}>LOADING...</span>}</div><div style={{ display: 'flex', gap: '4px', fontSize: '9px' }}>- <button onClick={() => setSortBy('LATEST')} style={{+ <button onClick={() => setSortBy('latest')} style={{padding: '2px 6px',- backgroundColor: sortBy === 'LATEST' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: sortBy === 'LATEST' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,+ backgroundColor: sortBy === 'latest' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,+ color: sortBy === 'latest' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,border: `1px solid ${BLOOMBERG_GRAY}`,cursor: 'pointer'}}>LATEST</button>- <button onClick={() => setSortBy('HOT')} style={{+ <button onClick={() => setSortBy('popular')} style={{padding: '2px 6px',- backgroundColor: sortBy === 'HOT' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: sortBy === 'HOT' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,+ backgroundColor: sortBy === 'popular' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,+ color: sortBy === 'popular' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,border: `1px solid ${BLOOMBERG_GRAY}`,cursor: 'pointer'}}>HOT</button>- <button onClick={() => setSortBy('TOP')} style={{+ <button onClick={() => setSortBy('views')} style={{padding: '2px 6px',- backgroundColor: sortBy === 'TOP' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: sortBy === 'TOP' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,+ backgroundColor: sortBy === 'views' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,+ color: sortBy === 'views' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,border: `1px solid ${BLOOMBERG_GRAY}`,cursor: 'pointer'}}>TOP</button>@@ -421,14 +1431,23 @@ const ForumTab: React.FC = () => {</div><div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>+ {filteredPosts.length === 0 && !isLoading && (+ <div style={{ color: BLOOMBERG_GRAY, textAlign: 'center', padding: '20px' }}>+ No posts available. Be the first to post!+ </div>+ )}+{filteredPosts.map((post, index) => (<div key={post.id} style={{marginBottom: '6px',padding: '6px',backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',borderLeft: `3px solid ${getPriorityColor(post.priority)}`,- paddingLeft: '6px'- }}>+ paddingLeft: '6px',+ cursor: 'pointer'+ }}+ onClick={() => handleViewPost(post)}+ ><div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '2px', fontSize: '8px' }}><span style={{ color: BLOOMBERG_GRAY }}>{post.time}</span><span style={{ color: getPriorityColor(post.priority), fontWeight: 'bold' }}>[{post.priority}]</span>@@ -444,7 +1463,7 @@ const ForumTab: React.FC = () => {</div><div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', lineHeight: '1.3', marginBottom: '3px' }}>- {post.content}+ {post.content.substring(0, 200)}{post.content.length > 200 ? '...' : ''}</div><div style={{ display: 'flex', gap: '6px', fontSize: '8px', marginBottom: '2px' }}>@@ -462,20 +1481,7 @@ const ForumTab: React.FC = () => {<span style={{ color: BLOOMBERG_CYAN }}>👁️ {post.views.toLocaleString()}</span><span style={{ color: BLOOMBERG_PURPLE }}>💬 {post.replies}</span><span style={{ color: BLOOMBERG_GREEN }}>👍 {post.likes}</span>- <button style={{- color: BLOOMBERG_ORANGE,- backgroundColor: 'transparent',- border: 'none',- cursor: 'pointer',- fontSize: '8px'- }}>REPLY</button>- <button style={{- color: BLOOMBERG_BLUE,- backgroundColor: 'transparent',- border: 'none',- cursor: 'pointer',- fontSize: '8px'- }}>SHARE</button>+ <span style={{ color: BLOOMBERG_RED }}>👎 {post.dislikes}</span></div></div>))}@@ -494,14 +1500,7 @@ const ForumTab: React.FC = () => {</div><div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>- {[- { topic: '#FED_RATES', mentions: 847, sentiment: 'BULLISH', change: '+234%' },- { topic: '#BTC_ETF', mentions: 723, sentiment: 'BULLISH', change: '+189%' },- { topic: '#NVDA', mentions: 612, sentiment: 'BULLISH', change: '+156%' },- { topic: '#OIL_SUPPLY', mentions: 487, sentiment: 'BULLISH', change: '+123%' },- { topic: '#BANKING_CRISIS', mentions: 356, sentiment: 'BEARISH', change: '+89%' },- { topic: '#AI_REVENUE', mentions: 298, sentiment: 'BULLISH', change: '+67%' }- ].map((item, index) => (+ {trendingTopics.map((item, index) => (<div key={index} style={{padding: '3px',marginBottom: '3px',@@ -523,13 +1522,7 @@ const ForumTab: React.FC = () => {<div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>RECENT ACTIVITY</div>- {[- { user: 'QuantTrader_Pro', action: 'posted', target: 'Fed Rate Analysis', time: '2 min ago' },- { user: 'CryptoWhale_2024', action: 'replied to', target: 'BTC ETF Thread', time: '5 min ago' },- { user: 'OptionsFlow_Alert', action: 'liked', target: 'NVDA Earnings Post', time: '8 min ago' },- { user: 'MacroHedgeFund', action: 'posted', target: 'Yield Curve Analysis', time: '12 min ago' },- { user: 'TechInvestor88', action: 'replied to', target: 'AI Infrastructure', time: '15 min ago' }- ].map((activity, index) => (+ {recentActivity.map((activity, index) => (<div key={index} style={{padding: '2px',marginBottom: '2px',@@ -584,7 +1577,7 @@ const ForumTab: React.FC = () => {<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', gap: '16px' }}><span>Fincept Global Forum v2.4.1 | Professional trading community</span>- <span>Posts: 894,234 | Users: 47,832 | Active: {onlineUsers}</span>+ <span>Posts: {totalPosts.toLocaleString()} | Users: {(forumStats?.total_comments || 47832).toLocaleString()} | Active: {onlineUsers}</span></div><div style={{ display: 'flex', gap: '16px' }}><span>Category: {activeCategory}</span>@@ -593,8 +1586,15 @@ const ForumTab: React.FC = () => {</div></div></div>++ {/* Modals */}+ {CreatePostModal}+ {PostDetailModal}+ {SearchModal}+ {ProfileModal}+ {EditProfileModal}</div>);};-export default ForumTab;\ No newline at end of file+export default ForumTab;diff --git a/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsxindex e86efbafa..a87dd46fa 100644--- a/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx@@ -203,6 +203,23 @@ const GeopoliticsTab: React.FC = () => {flexDirection: 'column',fontSize: '12px'}}>+ <style>{`+ /* Custom scrollbar styles for Geopolitics Tab */+ *::-webkit-scrollbar {+ width: 6px;+ height: 6px;+ }+ *::-webkit-scrollbar-track {+ background: transparent;+ }+ *::-webkit-scrollbar-thumb {+ background: rgba(120, 120, 120, 0.3);+ border-radius: 3px;+ }+ *::-webkit-scrollbar-thumb:hover {+ background: rgba(120, 120, 120, 0.5);+ }+ `}</style>{/* Complex Header with Multiple Status Lines */}<div style={{backgroundColor: BLOOMBERG_PANEL_BG,diff --git a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsxindex 640bad8d3..f006329c3 100644--- a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx@@ -1,4 +1,6 @@import React, { useState, useEffect } from 'react';+import { useAuth } from '@/contexts/AuthContext';+import { MarketplaceApiService, Dataset } from '@/services/marketplaceApi';interface MarketProduct {id: string;@@ -20,11 +22,27 @@ interface MarketProduct {}const MarketplaceTab: React.FC = () => {- const [currentScreen, setCurrentScreen] = useState<'BROWSE' | 'DETAILS' | 'CART'>('BROWSE');+ const { session } = useAuth();+ const [currentScreen, setCurrentScreen] = useState<'BROWSE' | 'DETAILS' | 'CART' | 'UPLOAD' | 'MY_PURCHASES' | 'ANALYTICS' | 'ADMIN_STATS'>('BROWSE');const [selectedProduct, setSelectedProduct] = useState<MarketProduct | null>(null);const [selectedCategory, setSelectedCategory] = useState('ALL');const [searchQuery, setSearchQuery] = useState('');const [cartItems, setCartItems] = useState<string[]>([]);+ const [datasets, setDatasets] = useState<Dataset[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [currentPage, setCurrentPage] = useState(1);+ const [totalPages, setTotalPages] = useState(1);+ const [myUploadedDatasets, setMyUploadedDatasets] = useState<any[]>([]);++ // Upload state+ const [uploadFile, setUploadFile] = useState<File | null>(null);+ const [uploadMetadata, setUploadMetadata] = useState({+ title: '',+ description: '',+ category: 'stocks',+ price_tier: 'free',+ tags: ''+ });// Colorsconst C = {@@ -41,125 +59,118 @@ const MarketplaceTab: React.FC = () => {PANEL_BG: '#0a0a0a'};- const products: MarketProduct[] = [- {- id: 'MKT001',- type: 'DATA',- name: 'Global Equity Real-Time Feed',- vendor: 'Refinitiv Data Solutions',- category: 'Market Data',- price: 4999.00,- pricingModel: 'MONTHLY',- shortDescription: 'Real-time equity prices for 60,000+ global securities across 120+ exchanges',- rating: 4.8,- reviews: 2847,- users: 12450,- accuracy: '99.99%',- latency: '<1ms',- verified: true,- trending: true,- featured: true- },- {- id: 'MKT002',- type: 'ALGO',- name: 'Quantum Alpha Strategy',- vendor: 'QuantEdge Systems',- category: 'Trading Algorithms',- price: 15000.00,- pricingModel: 'ANNUAL',- shortDescription: 'ML-powered multi-factor equity strategy with proven 18.7% annual alpha',- rating: 4.9,- reviews: 1234,- users: 3847,- accuracy: '87.3%',- latency: '<500ms',- verified: true,- trending: true,- featured: true- },- {- id: 'MKT003',- type: 'API',- name: 'Options Analytics Suite',- vendor: 'DerivativeEdge Inc.',- category: 'Derivatives',- price: 0.05,- pricingModel: 'USAGE_BASED',- shortDescription: 'Complete options pricing, Greeks, and volatility analytics API',- rating: 4.7,- reviews: 3456,- users: 18923,- accuracy: '99.5%',- latency: '<50ms',- verified: true,- trending: false,- featured: true- },- {- id: 'MKT004',- type: 'MODEL',- name: 'Credit Risk AI Model',- vendor: 'RiskLab Analytics',- category: 'Risk Management',- price: 8500.00,- pricingModel: 'MONTHLY',- shortDescription: 'Deep learning model for corporate credit risk assessment',- rating: 4.6,- reviews: 892,- users: 2341,- accuracy: '91.2%',+ // Fetch datasets from API+ const fetchDatasets = async () => {+ if (!session?.api_key) return;++ setIsLoading(true);+ try {+ const response = await MarketplaceApiService.browseDatasets(session.api_key, {+ category: selectedCategory === 'ALL' ? undefined : selectedCategory,+ search: searchQuery || undefined,+ page: currentPage,+ limit: 20,+ sort_by: 'uploaded_at',+ sort_order: 'desc'+ });++ console.log('📊 Browse datasets response:', response);++ if (response.success && response.data) {+ // Handle nested data structure+ const datasetsArray = response.data.data?.datasets || response.data.datasets || [];+ const totalPagesCount = response.data.data?.pagination?.total_pages || response.data.total_pages || 1;++ console.log('📦 Datasets found:', datasetsArray.length, datasetsArray);++ setDatasets(datasetsArray);+ setTotalPages(totalPagesCount);+ } else {+ console.error('❌ Failed to fetch datasets:', response.error);+ setDatasets([]);+ }+ } catch (error) {+ console.error('💥 Failed to fetch datasets:', error);+ setDatasets([]);+ } finally {+ setIsLoading(false);+ }+ };++ // Fetch MY uploaded datasets+ const fetchMyDatasets = async () => {+ if (!session?.api_key) return;++ try {+ const response = await MarketplaceApiService.getDatasetAnalytics(session.api_key);+ console.log('📊 My uploaded datasets analytics:', response);++ if (response.success && response.data) {+ const myDatasets = response.data.data?.datasets || response.data.datasets || [];+ console.log('📦 My uploaded datasets:', myDatasets);+ setMyUploadedDatasets(myDatasets);+ }+ } catch (error) {+ console.error('Failed to fetch my datasets:', error);+ }+ };++ useEffect(() => {+ fetchDatasets();+ fetchMyDatasets();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [session?.api_key, selectedCategory, searchQuery, currentPage]);++ // Convert Dataset to MarketProduct format for UI compatibility+ const convertToMarketProduct = (dataset: Dataset): MarketProduct => {+ const typeMap: Record<string, MarketProduct['type']> = {+ 'stocks': 'DATA',+ 'forex': 'DATA',+ 'crypto': 'DATA',+ 'commodities': 'DATA',+ 'bonds': 'DATA',+ 'indices': 'DATA',+ 'economic_data': 'SIGNAL'+ };++ const pricingMap: Record<string, MarketProduct['pricingModel']> = {+ 'free': 'FREE',+ 'basic': 'MONTHLY',+ 'premium': 'ANNUAL',+ 'enterprise': 'USAGE_BASED'+ };++ return {+ id: dataset.id.toString(),+ type: typeMap[dataset.category] || 'DATA',+ name: dataset.title,+ vendor: dataset.uploader_username,+ category: dataset.category,+ price: dataset.price_credits,+ pricingModel: pricingMap[dataset.price_tier] || 'FREE',+ shortDescription: dataset.description,+ rating: dataset.rating || 0,+ reviews: dataset.downloads_count || 0,+ users: dataset.downloads_count || 0,+ accuracy: 'N/A',latency: 'N/A',verified: true,- trending: false,- featured: false- },- {- id: 'MKT005',- type: 'SIGNAL',- name: 'Social Sentiment Signals',- vendor: 'SentimentAlpha',- category: 'Alternative Data',- price: 2999.00,- pricingModel: 'MONTHLY',- shortDescription: 'Trading signals from social media sentiment analysis',- rating: 4.4,- reviews: 1678,- users: 7823,- accuracy: '73.8%',- latency: '<1hr',- verified: true,- trending: true,- featured: false- },- {- id: 'MKT006',- type: 'PLUGIN',- name: 'Portfolio Risk Dashboard',- vendor: 'Fincept Labs',- category: 'Analytics',- price: 0.00,- pricingModel: 'FREE',- shortDescription: 'Advanced portfolio risk analytics dashboard plugin',- rating: 4.9,- reviews: 5678,- users: 28934,- accuracy: '99.9%',- latency: '<100ms',- verified: true,- trending: true,- featured: true- }- ];+ trending: dataset.downloads_count > 100,+ featured: dataset.rating > 4.5+ };+ };++ const products: MarketProduct[] = datasets.map(convertToMarketProduct);++ // Get unique categories from datasets+ const categoryCounts = datasets.reduce((acc, dataset) => {+ acc[dataset.category] = (acc[dataset.category] || 0) + 1;+ return acc;+ }, {} as Record<string, number>);const categories = [- { name: 'ALL', count: products.length },- { name: 'Market Data', count: 2 },- { name: 'Trading Algorithms', count: 1 },- { name: 'Derivatives', count: 1 },- { name: 'Risk Management', count: 1 },- { name: 'Alternative Data', count: 1 },- { name: 'Analytics', count: 1 }+ { name: 'ALL', count: datasets.length },+ ...Object.entries(categoryCounts).map(([name, count]) => ({ name, count }))];const filteredProducts = products.filter(p =>@@ -174,6 +185,120 @@ const MarketplaceTab: React.FC = () => {return colors[type] || C.WHITE;};+ // Handle purchase+ const handlePurchase = async (datasetId: string) => {+ if (!session?.api_key) return;++ try {+ const response = await MarketplaceApiService.purchaseDataset(+ session.api_key,+ parseInt(datasetId)+ );++ if (response.success) {+ alert('Purchase successful! Dataset access granted.');+ // Remove from cart after purchase+ setCartItems(cartItems.filter(id => id !== datasetId));+ } else {+ alert(`Purchase failed: ${response.error || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Purchase error:', error);+ alert('Purchase failed. Please try again.');+ }+ };++ // Handle download+ const handleDownload = async (datasetId: string) => {+ if (!session?.api_key) return;++ try {+ const response = await MarketplaceApiService.downloadDataset(+ session.api_key,+ parseInt(datasetId)+ );++ if (response.success && response.data?.download_url) {+ window.open(response.data.download_url, '_blank');+ } else {+ alert(`Download failed: ${response.error || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Download error:', error);+ alert('Download failed. Please try again.');+ }+ };++ // Handle upload+ const handleUpload = async () => {+ if (!session?.api_key || !uploadFile) {+ alert('Please select a file and fill in all details');+ return;+ }++ setIsLoading(true);+ try {+ const response = await MarketplaceApiService.uploadDataset(+ session.api_key,+ uploadFile,+ {+ title: uploadMetadata.title,+ description: uploadMetadata.description,+ category: uploadMetadata.category,+ price_tier: uploadMetadata.price_tier,+ tags: uploadMetadata.tags ? uploadMetadata.tags.split(',').map(t => t.trim()) : []+ }+ );++ console.log('📤 Upload response:', response);+ console.log('📤 Upload response.data:', response.data);+ console.log('📤 Upload response full:', JSON.stringify(response, null, 2));++ if (response.success) {+ const uploadedDataset = response.data?.data || response.data;+ console.log('✅ Dataset uploaded successfully:', uploadedDataset);+ console.log('✅ Dataset ID:', uploadedDataset?.id);+ console.log('✅ Dataset full object:', JSON.stringify(uploadedDataset, null, 2));++ alert(`Dataset uploaded successfully! ID: ${uploadedDataset?.id || 'Unknown'}\nTitle: ${uploadedDataset?.title || 'Unknown'}`);++ setUploadFile(null);+ setUploadMetadata({+ title: '',+ description: '',+ category: 'stocks',+ price_tier: 'free',+ tags: ''+ });++ // Immediately try to fetch the specific dataset+ if (uploadedDataset?.id && session?.api_key) {+ console.log(`🔍 Attempting to fetch dataset ${uploadedDataset.id} directly...`);+ MarketplaceApiService.getDatasetDetails(session.api_key, uploadedDataset.id)+ .then(detailsResponse => {+ console.log('📋 Dataset details response:', detailsResponse);+ });+ }++ // Wait a bit for backend to process, then refresh and switch to browse+ setTimeout(() => {+ console.log('🔄 Refreshing datasets list...');+ fetchDatasets();+ fetchMyDatasets();+ setCurrentScreen('BROWSE');+ }, 1500);+ } else {+ console.error('❌ Upload failed:', response.error);+ alert(`Upload failed: ${response.error || 'Unknown error'}`);+ }+ } catch (error) {+ console.error('Upload error:', error);+ alert('Upload failed. Please try again.');+ } finally {+ setIsLoading(false);+ }+ };+return (<div style={{ width: '100%', height: '100%', backgroundColor: C.DARK_BG, color: C.WHITE, fontFamily: 'Consolas, monospace', display: 'flex', flexDirection: 'column' }}><style>{`@@ -185,16 +310,47 @@ const MarketplaceTab: React.FC = () => {{/* Header */}<div style={{ backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}`, padding: '8px 16px' }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '8px' }}><div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}><span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '16px' }}>FINCEPT MARKETPLACE</span><span style={{ color: C.GRAY }}>|</span>- <span style={{ color: C.CYAN, fontSize: '12px' }}>{products.length} Products Available</span>+ <span style={{ color: C.CYAN, fontSize: '12px' }}>{datasets.length} Datasets Available</span>+ {currentScreen === 'BROWSE' && (+ <>+ <span style={{ color: C.GRAY }}>|</span>+ <span style={{ color: C.YELLOW, fontSize: '12px' }}>My Uploads: {myUploadedDatasets.length}</span>+ <span style={{ color: C.GRAY }}>|</span>+ <button+ onClick={() => {+ fetchDatasets();+ fetchMyDatasets();+ }}+ disabled={isLoading}+ style={{ padding: '4px 8px', backgroundColor: C.DARK_BG, border: `2px solid ${C.BLUE}`, color: C.BLUE, fontSize: '10px', fontWeight: 'bold', cursor: isLoading ? 'not-allowed' : 'pointer', fontFamily: 'Consolas, monospace' }}+ >+ {isLoading ? '⟳ LOADING...' : '🔄 REFRESH'}+ </button>+ </>+ )}</div>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}><button onClick={() => setCurrentScreen('BROWSE')} style={{ padding: '6px 12px', backgroundColor: currentScreen === 'BROWSE' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: currentScreen === 'BROWSE' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>BROWSE</button>+ <button onClick={() => setCurrentScreen('UPLOAD')} style={{ padding: '6px 12px', backgroundColor: currentScreen === 'UPLOAD' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: currentScreen === 'UPLOAD' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ 📤 UPLOAD+ </button>+ <button onClick={() => setCurrentScreen('MY_PURCHASES')} style={{ padding: '6px 12px', backgroundColor: currentScreen === 'MY_PURCHASES' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: currentScreen === 'MY_PURCHASES' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ 📦 MY PURCHASES+ </button>+ <button onClick={() => setCurrentScreen('ANALYTICS')} style={{ padding: '6px 12px', backgroundColor: currentScreen === 'ANALYTICS' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: currentScreen === 'ANALYTICS' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ 📊 ANALYTICS+ </button>+ {(session?.user_info as any)?.is_admin && (+ <button onClick={() => setCurrentScreen('ADMIN_STATS')} style={{ padding: '6px 12px', backgroundColor: currentScreen === 'ADMIN_STATS' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: currentScreen === 'ADMIN_STATS' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ 🔧 ADMIN+ </button>+ )}<button onClick={() => setCurrentScreen('CART')} style={{ padding: '6px 12px', backgroundColor: currentScreen === 'CART' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: currentScreen === 'CART' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>🛒 CART {cartItems.length > 0 && `(${cartItems.length})`}</button>@@ -223,8 +379,18 @@ const MarketplaceTab: React.FC = () => {{/* Products */}<div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', backgroundColor: '#050505', padding: '16px' }}>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '16px' }}>- {filteredProducts.map((product) => (+ {isLoading ? (+ <div style={{ textAlign: 'center', padding: '40px', color: C.GRAY }}>+ <div style={{ fontSize: '18px', marginBottom: '12px' }}>Loading datasets...</div>+ </div>+ ) : filteredProducts.length === 0 ? (+ <div style={{ textAlign: 'center', padding: '40px', color: C.GRAY }}>+ <div style={{ fontSize: '18px', marginBottom: '12px' }}>No datasets found</div>+ <div style={{ fontSize: '14px' }}>Try adjusting your filters or search query</div>+ </div>+ ) : (+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '16px' }}>+ {filteredProducts.map((product) => (<div key={product.id} style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${getTypeColor(product.type)}`, padding: '16px' }}><div style={{ display: 'inline-block', backgroundColor: getTypeColor(product.type), color: C.DARK_BG, padding: '4px 10px', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px' }}>{product.type}@@ -251,8 +417,9 @@ const MarketplaceTab: React.FC = () => {</button></div></div>- ))}- </div>+ ))}+ </div>+ )}</div></>)}@@ -310,27 +477,128 @@ const MarketplaceTab: React.FC = () => {</button></div>) : (- products.filter(p => cartItems.includes(p.id)).map((product) => (- <div key={product.id} style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${getTypeColor(product.type)}`, padding: '20px', marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div style={{ flex: 1 }}>- <div style={{ color: C.WHITE, fontSize: '18px', fontWeight: 'bold', marginBottom: '4px' }}>{product.name}</div>- <div style={{ color: C.GRAY, fontSize: '13px', marginBottom: '8px' }}>by {product.vendor}</div>- </div>- <div style={{ textAlign: 'right', marginLeft: '24px' }}>- <div style={{ color: C.GREEN, fontSize: '24px', fontWeight: 'bold', marginBottom: '8px' }}>- {product.pricingModel === 'FREE' ? 'FREE' : `$${product.price.toLocaleString()}`}+ <>+ {products.filter(p => cartItems.includes(p.id)).map((product) => (+ <div key={product.id} style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${getTypeColor(product.type)}`, padding: '20px', marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={{ flex: 1 }}>+ <div style={{ color: C.WHITE, fontSize: '18px', fontWeight: 'bold', marginBottom: '4px' }}>{product.name}</div>+ <div style={{ color: C.GRAY, fontSize: '13px', marginBottom: '8px' }}>by {product.vendor}</div>+ </div>+ <div style={{ textAlign: 'right', marginLeft: '24px' }}>+ <div style={{ color: C.GREEN, fontSize: '24px', fontWeight: 'bold', marginBottom: '8px' }}>+ {product.pricingModel === 'FREE' ? 'FREE' : `${product.price} Credits`}+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button onClick={() => handlePurchase(product.id)} style={{ padding: '8px 16px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GREEN}`, color: C.GREEN, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ PURCHASE+ </button>+ <button onClick={() => setCartItems(cartItems.filter(id => id !== product.id))} style={{ padding: '8px 16px', backgroundColor: C.DARK_BG, border: `2px solid ${C.RED}`, color: C.RED, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ REMOVE+ </button>+ </div></div>- <button onClick={() => setCartItems(cartItems.filter(id => id !== product.id))} style={{ padding: '8px 16px', backgroundColor: C.DARK_BG, border: `2px solid ${C.RED}`, color: C.RED, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>- REMOVE- </button></div>- </div>- ))+ ))}+ </>)}</div></div></>)}++ {currentScreen === 'UPLOAD' && (+ <>+ <div style={{ padding: '12px', backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}` }}>+ <div style={{ color: C.ORANGE, fontSize: '20px', fontWeight: 'bold' }}>UPLOAD DATASET</div>+ </div>+ <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', backgroundColor: '#050505', padding: '20px' }}>+ <div style={{ maxWidth: '800px', margin: '0 auto', backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, padding: '24px' }}>+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>Dataset Title</label>+ <input+ type="text"+ value={uploadMetadata.title}+ onChange={(e) => setUploadMetadata({ ...uploadMetadata, title: e.target.value })}+ style={{ width: '100%', padding: '10px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GRAY}`, color: C.WHITE, fontSize: '14px', fontFamily: 'Consolas, monospace' }}+ placeholder="Enter dataset title"+ />+ </div>+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>Description</label>+ <textarea+ value={uploadMetadata.description}+ onChange={(e) => setUploadMetadata({ ...uploadMetadata, description: e.target.value })}+ style={{ width: '100%', padding: '10px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GRAY}`, color: C.WHITE, fontSize: '14px', fontFamily: 'Consolas, monospace', minHeight: '100px' }}+ placeholder="Describe your dataset"+ />+ </div>+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>Category</label>+ <select+ value={uploadMetadata.category}+ onChange={(e) => setUploadMetadata({ ...uploadMetadata, category: e.target.value })}+ style={{ width: '100%', padding: '10px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GRAY}`, color: C.WHITE, fontSize: '14px', fontFamily: 'Consolas, monospace' }}+ >+ <option value="stocks">Stocks</option>+ <option value="forex">Forex</option>+ <option value="crypto">Cryptocurrency</option>+ <option value="commodities">Commodities</option>+ <option value="bonds">Bonds</option>+ <option value="indices">Indices</option>+ <option value="economic_data">Economic Data</option>+ </select>+ </div>+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>Price Tier</label>+ <select+ value={uploadMetadata.price_tier}+ onChange={(e) => setUploadMetadata({ ...uploadMetadata, price_tier: e.target.value })}+ style={{ width: '100%', padding: '10px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GRAY}`, color: C.WHITE, fontSize: '14px', fontFamily: 'Consolas, monospace' }}+ >+ <option value="free">Free (0 credits)</option>+ <option value="basic">Basic (10 credits)</option>+ <option value="premium">Premium (50 credits)</option>+ <option value="enterprise">Enterprise (100 credits)</option>+ </select>+ </div>+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>Tags (comma separated)</label>+ <input+ type="text"+ value={uploadMetadata.tags}+ onChange={(e) => setUploadMetadata({ ...uploadMetadata, tags: e.target.value })}+ style={{ width: '100%', padding: '10px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GRAY}`, color: C.WHITE, fontSize: '14px', fontFamily: 'Consolas, monospace' }}+ placeholder="stocks, real-time, equity"+ />+ </div>+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>Upload File</label>+ <input+ type="file"+ onChange={(e) => setUploadFile(e.target.files?.[0] || null)}+ style={{ width: '100%', padding: '10px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GRAY}`, color: C.WHITE, fontSize: '14px', fontFamily: 'Consolas, monospace' }}+ />+ {uploadFile && (+ <div style={{ marginTop: '8px', color: C.CYAN, fontSize: '12px' }}>+ Selected: {uploadFile.name} ({(uploadFile.size / 1024 / 1024).toFixed(2)} MB)+ </div>+ )}+ </div>+ <button+ onClick={handleUpload}+ disabled={isLoading}+ style={{ padding: '12px 32px', backgroundColor: isLoading ? C.GRAY : C.ORANGE, border: 'none', color: C.DARK_BG, fontSize: '14px', fontWeight: 'bold', cursor: isLoading ? 'not-allowed' : 'pointer', fontFamily: 'Consolas, monospace' }}+ >+ {isLoading ? 'UPLOADING...' : 'UPLOAD DATASET'}+ </button>+ </div>+ </div>+ </>+ )}++ {currentScreen === 'MY_PURCHASES' && <MyPurchasesScreen session={session} C={C} />}+ {currentScreen === 'ANALYTICS' && <AnalyticsScreen session={session} C={C} />}+ {currentScreen === 'ADMIN_STATS' && <AdminStatsScreen session={session} C={C} />}</div>{/* Footer */}@@ -352,4 +620,242 @@ const MarketplaceTab: React.FC = () => {);};+// My Purchases Screen Component+const MyPurchasesScreen: React.FC<{ session: any; C: any }> = ({ session, C }) => {+ const [purchases, setPurchases] = useState<any[]>([]);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ const fetchPurchases = async () => {+ if (!session?.api_key) return;+ setIsLoading(true);+ try {+ const response = await MarketplaceApiService.getUserPurchases(session.api_key, 1, 50);+ if (response.success && response.data) {+ setPurchases(response.data.purchases || []);+ }+ } catch (error) {+ console.error('Failed to fetch purchases:', error);+ } finally {+ setIsLoading(false);+ }+ };+ fetchPurchases();+ }, [session?.api_key]);++ const handleDownload = async (datasetId: number) => {+ if (!session?.api_key) return;+ try {+ const response = await MarketplaceApiService.downloadDataset(session.api_key, datasetId);+ if (response.success && response.data?.download_url) {+ window.open(response.data.download_url, '_blank');+ }+ } catch (error) {+ alert('Download failed');+ }+ };++ return (+ <>+ <div style={{ padding: '12px', backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}` }}>+ <div style={{ color: C.ORANGE, fontSize: '20px', fontWeight: 'bold' }}>MY PURCHASES ({purchases.length})</div>+ </div>+ <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', backgroundColor: '#050505', padding: '20px' }}>+ <div style={{ maxWidth: '1200px', margin: '0 auto' }}>+ {isLoading ? (+ <div style={{ textAlign: 'center', padding: '40px', color: C.GRAY }}>Loading...</div>+ ) : purchases.length === 0 ? (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, padding: '40px', textAlign: 'center' }}>+ <div style={{ color: C.GRAY, fontSize: '18px' }}>No purchases yet</div>+ </div>+ ) : (+ purchases.map((purchase) => (+ <div key={purchase.id} style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '20px', marginBottom: '16px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={{ color: C.WHITE, fontSize: '18px', fontWeight: 'bold', marginBottom: '4px' }}>{purchase.dataset_title}</div>+ <div style={{ color: C.GRAY, fontSize: '13px', marginBottom: '8px' }}>+ Purchased: {new Date(purchase.purchased_at).toLocaleDateString()} | Paid: {purchase.price_paid} credits+ </div>+ </div>+ <button onClick={() => handleDownload(purchase.dataset_id)} style={{ padding: '10px 20px', backgroundColor: C.DARK_BG, border: `2px solid ${C.BLUE}`, color: C.BLUE, fontSize: '12px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ 📥 DOWNLOAD+ </button>+ </div>+ </div>+ ))+ )}+ </div>+ </div>+ </>+ );+};++// Analytics Screen Component+const AnalyticsScreen: React.FC<{ session: any; C: any }> = ({ session, C }) => {+ const [analytics, setAnalytics] = useState<any>(null);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ const fetchAnalytics = async () => {+ if (!session?.api_key) return;+ setIsLoading(true);+ try {+ const response = await MarketplaceApiService.getDatasetAnalytics(session.api_key);+ if (response.success && response.data) {+ setAnalytics(response.data);+ }+ } catch (error) {+ console.error('Failed to fetch analytics:', error);+ } finally {+ setIsLoading(false);+ }+ };+ fetchAnalytics();+ }, [session?.api_key]);++ return (+ <>+ <div style={{ padding: '12px', backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}` }}>+ <div style={{ color: C.ORANGE, fontSize: '20px', fontWeight: 'bold' }}>MY DATASET ANALYTICS</div>+ </div>+ <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', backgroundColor: '#050505', padding: '20px' }}>+ <div style={{ maxWidth: '1200px', margin: '0 auto' }}>+ {isLoading ? (+ <div style={{ textAlign: 'center', padding: '40px', color: C.GRAY }}>Loading...</div>+ ) : !analytics ? (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, padding: '40px', textAlign: 'center' }}>+ <div style={{ color: C.GRAY, fontSize: '18px' }}>No analytics data available</div>+ </div>+ ) : (+ <>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '24px' }}>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.BLUE}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.BLUE, fontSize: '36px', fontWeight: 'bold' }}>{analytics.total_datasets || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Datasets</div>+ </div>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GREEN}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.GREEN, fontSize: '36px', fontWeight: 'bold' }}>{analytics.total_downloads || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Downloads</div>+ </div>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.ORANGE}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.ORANGE, fontSize: '36px', fontWeight: 'bold' }}>{analytics.total_revenue || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Revenue (credits)</div>+ </div>+ </div>+ {analytics.datasets && analytics.datasets.length > 0 && (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, padding: '20px' }}>+ <div style={{ color: C.ORANGE, fontSize: '16px', fontWeight: 'bold', marginBottom: '16px' }}>DATASET PERFORMANCE</div>+ {analytics.datasets.map((dataset: any) => (+ <div key={dataset.id} style={{ borderBottom: `1px solid ${C.GRAY}`, padding: '12px 0' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={{ color: C.WHITE, fontSize: '14px' }}>{dataset.title}</div>+ <div style={{ display: 'flex', gap: '24px' }}>+ <div style={{ textAlign: 'center' }}>+ <div style={{ color: C.CYAN, fontSize: '18px', fontWeight: 'bold' }}>{dataset.downloads}</div>+ <div style={{ color: C.GRAY, fontSize: '11px' }}>Downloads</div>+ </div>+ <div style={{ textAlign: 'center' }}>+ <div style={{ color: C.GREEN, fontSize: '18px', fontWeight: 'bold' }}>{dataset.revenue}</div>+ <div style={{ color: C.GRAY, fontSize: '11px' }}>Revenue</div>+ </div>+ <div style={{ textAlign: 'center' }}>+ <div style={{ color: C.YELLOW, fontSize: '18px', fontWeight: 'bold' }}>★ {dataset.rating.toFixed(1)}</div>+ <div style={{ color: C.GRAY, fontSize: '11px' }}>Rating</div>+ </div>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}+ </>+ )}+ </div>+ </div>+ </>+ );+};++// Admin Stats Screen Component+const AdminStatsScreen: React.FC<{ session: any; C: any }> = ({ session, C }) => {+ const [stats, setStats] = useState<any>(null);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ const fetchStats = async () => {+ if (!session?.api_key) return;+ setIsLoading(true);+ try {+ const response = await MarketplaceApiService.getMarketplaceStats(session.api_key);+ if (response.success && response.data) {+ setStats(response.data);+ }+ } catch (error) {+ console.error('Failed to fetch admin stats:', error);+ } finally {+ setIsLoading(false);+ }+ };+ fetchStats();+ }, [session?.api_key]);++ return (+ <>+ <div style={{ padding: '12px', backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}` }}>+ <div style={{ color: C.ORANGE, fontSize: '20px', fontWeight: 'bold' }}>🔧 ADMIN MARKETPLACE STATISTICS</div>+ </div>+ <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', backgroundColor: '#050505', padding: '20px' }}>+ <div style={{ maxWidth: '1200px', margin: '0 auto' }}>+ {isLoading ? (+ <div style={{ textAlign: 'center', padding: '40px', color: C.GRAY }}>Loading...</div>+ ) : !stats ? (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, padding: '40px', textAlign: 'center' }}>+ <div style={{ color: C.GRAY, fontSize: '18px' }}>No statistics available</div>+ </div>+ ) : (+ <>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '24px' }}>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.BLUE}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.BLUE, fontSize: '36px', fontWeight: 'bold' }}>{stats.total_datasets || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Datasets</div>+ </div>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GREEN}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.GREEN, fontSize: '36px', fontWeight: 'bold' }}>{stats.total_purchases || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Purchases</div>+ </div>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.ORANGE}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.ORANGE, fontSize: '36px', fontWeight: 'bold' }}>{stats.total_revenue || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Revenue (credits)</div>+ </div>+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.CYAN}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.CYAN, fontSize: '36px', fontWeight: 'bold' }}>{stats.total_uploads || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Total Uploads</div>+ </div>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.PURPLE}`, padding: '20px', textAlign: 'center' }}>+ <div style={{ color: C.PURPLE, fontSize: '36px', fontWeight: 'bold' }}>{stats.active_users || 0}</div>+ <div style={{ color: C.WHITE, fontSize: '14px', marginTop: '8px' }}>Active Users</div>+ </div>+ </div>+ {stats.popular_categories && (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, padding: '20px', marginTop: '24px' }}>+ <div style={{ color: C.ORANGE, fontSize: '16px', fontWeight: 'bold', marginBottom: '16px' }}>POPULAR CATEGORIES</div>+ {Object.entries(stats.popular_categories).map(([category, count]: [string, any]) => (+ <div key={category} style={{ borderBottom: `1px solid ${C.GRAY}`, padding: '12px 0', display: 'flex', justifyContent: 'space-between' }}>+ <div style={{ color: C.WHITE, fontSize: '14px' }}>{category}</div>+ <div style={{ color: C.CYAN, fontSize: '14px', fontWeight: 'bold' }}>{count} datasets</div>+ </div>+ ))}+ </div>+ )}+ </>+ )}+ </div>+ </div>+ </>+ );+};+export default MarketplaceTab;\ No newline at end of filediff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsxindex 3f3f35f41..a23d258e2 100644--- a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';import { Edit2 } from 'lucide-react';import { marketDataService, QuoteData } from '../../services/marketDataService';import { tickerStorage } from '../../services/tickerStorageService';+import { sqliteService } from '../../services/sqliteService';import TickerEditModal from './TickerEditModal';const MarketsTab: React.FC = () => {@@ -10,6 +11,7 @@ const MarketsTab: React.FC = () => {const [isUpdating, setIsUpdating] = useState(false);const [autoUpdate, setAutoUpdate] = useState(true);const [updateInterval, setUpdateInterval] = useState(600000); // 10 minutes default+ const [dbInitialized, setDbInitialized] = useState(false);// Market data stateconst [marketData, setMarketData] = useState<Record<string, QuoteData[]>>({});@@ -36,16 +38,27 @@ const MarketsTab: React.FC = () => {const fetchMarketData = async () => {setIsUpdating(true);- // Fetch global markets+ // Calculate cache age in minutes (10 minutes by default from updateInterval)+ const cacheAgeMinutes = updateInterval / 60000;++ // Fetch global markets with cachingconst globalPromises = preferences.globalMarkets.map(async (market) => {- const quotes = await marketDataService.getEnhancedQuotes(market.tickers);+ const quotes = await marketDataService.getEnhancedQuotesWithCache(+ market.tickers,+ market.category,+ cacheAgeMinutes+ );return { category: market.category, quotes };});- // Fetch regional markets+ // Fetch regional markets with cachingconst regionalPromises = preferences.regionalMarkets.map(async (market) => {const symbols = market.tickers.map(t => t.symbol);- const quotes = await marketDataService.getEnhancedQuotes(symbols);+ const quotes = await marketDataService.getEnhancedQuotesWithCache(+ symbols,+ market.region,+ cacheAgeMinutes+ );return { region: market.region, quotes };});@@ -69,6 +82,25 @@ const MarketsTab: React.FC = () => {setIsUpdating(false);};+ // Initialize database on mount+ useEffect(() => {+ const initDatabase = async () => {+ try {+ await sqliteService.initialize();+ const healthCheck = await sqliteService.healthCheck();+ if (healthCheck.healthy) {+ setDbInitialized(true);+ console.log('[MarketsTab] Database initialized and ready for caching');+ } else {+ console.warn('[MarketsTab] Database not healthy:', healthCheck.message);+ }+ } catch (error) {+ console.error('[MarketsTab] Database initialization error:', error);+ }+ };+ initDatabase();+ }, []);+// Initial fetchuseEffect(() => {fetchMarketData();@@ -495,6 +527,11 @@ const MarketsTab: React.FC = () => {<span>Data provided by Yahoo Finance API | Real-time updates</span><span style={{ whiteSpace: 'nowrap' }}>Connected: {Object.keys(regionalData).length} regional markets+ {dbInitialized && (+ <span style={{ marginLeft: '8px', color: BLOOMBERG_GREEN }}>+ | Cache: ENABLED+ </span>+ )}</span></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsxindex 6e59250e2..3d5e3d024 100644--- a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx@@ -1,379 +1,975 @@import React, { useState, useEffect } from 'react';import { useAuth } from '@/contexts/AuthContext';+import { useNavigation } from '@/contexts/NavigationContext';+import { UserApiService } from '@/services/userApi';++// Bloomberg Terminal Colors+const C = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ RED: '#FF0000',+ GREEN: '#00C800',+ YELLOW: '#FFFF00',+ GRAY: '#787878',+ BLUE: '#6496FA',+ PURPLE: '#C864FF',+ CYAN: '#00FFFF',+ DARK_BG: '#000000',+ PANEL_BG: '#0a0a0a'+};++type ProfileScreen = 'overview' | 'usage' | 'payments' | 'subscriptions' | 'support' | 'settings';const ProfileTab: React.FC = () => {const { session, logout } = useAuth();-- const [lastRefresh, setLastRefresh] = useState<Date>(new Date());- const [requestCount, setRequestCount] = useState(15);- const [usageStats] = useState({- total_requests: 1250,- total_credits_used: 3425- });+ const navigation = useNavigation();+ const [currentTime, setCurrentTime] = useState(new Date());+ const [currentScreen, setCurrentScreen] = useState<ProfileScreen>('overview');+ const [loading, setLoading] = useState(false);++ // Data states+ const [usageData, setUsageData] = useState<any>(null);+ const [paymentHistory, setPaymentHistory] = useState<any[]>([]);+ const [subscriptions, setSubscriptions] = useState<any[]>([]);+ const [supportTickets, setSupportTickets] = useState<any[]>([]);+ const [detailedUsage, setDetailedUsage] = useState<any>(null);useEffect(() => {- const timer = setInterval(() => {- setLastRefresh(new Date());- }, 5000);-+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);return () => clearInterval(timer);}, []);- // Bloomberg Terminal Colors (matching DearPyGUI style)- const COLORS = {- success: '#64ff64',- warning: '#ffc864',- error: '#ff9696',- info: '#c8ffc8',- title: '#ffff64'- };-- const manualRefresh = () => {- setLastRefresh(new Date());- setRequestCount(prev => prev + 1);- };+ // Fetch data based on current screen+ useEffect(() => {+ if (!session?.api_key) return;++ const fetchData = async () => {+ setLoading(true);+ try {+ if (currentScreen === 'usage') {+ if (session.user_type === 'guest') {+ const result = await UserApiService.getGuestUsage(session.api_key);+ if (result.success) setUsageData(result.data);+ } else {+ const result = await UserApiService.getUserUsage(session.api_key);+ if (result.success) setUsageData(result.data);++ // Also fetch detailed usage+ const detailedResult = await UserApiService.getUsageDetails(session.api_key);+ if (detailedResult.success) setDetailedUsage(detailedResult.data);+ }+ } else if (currentScreen === 'payments') {+ const result = await UserApiService.getPaymentHistory(session.api_key, 1, 20);+ if (result.success) setPaymentHistory(result.data?.payments || result.data || []);+ } else if (currentScreen === 'subscriptions') {+ const result = await UserApiService.getUserSubscriptions(session.api_key);+ if (result.success) setSubscriptions(result.data?.subscriptions || result.data || []);+ } else if (currentScreen === 'support') {+ const result = await UserApiService.getUserTickets(session.api_key);+ if (result.success) setSupportTickets(result.data?.tickets || result.data || []);+ }+ } catch (error) {+ console.error('Error fetching data:', error);+ } finally {+ setLoading(false);+ }+ };++ fetchData();+ }, [currentScreen, session]);const logoutUser = async () => {- await logout();- window.location.href = '/';+ if (confirm('Are you sure you want to logout?')) {+ await logout();+ }};- const showSignupInfo = () => {- alert('Sign up functionality would open here');+ const regenerateApiKey = async () => {+ if (!session?.api_key) return;+ if (confirm('Are you sure you want to regenerate your API key? Your old key will be invalidated.')) {+ setLoading(true);+ const result = await UserApiService.regenerateApiKey(session.api_key);+ setLoading(false);+ if (result.success) {+ alert(`New API Key: ${result.data?.new_api_key || 'Check your profile'}\n\nPlease save this key securely. You will need to re-login.`);+ await logout();+ } else {+ alert(`Failed to regenerate API key: ${result.error}`);+ }+ }};- const showLoginInfo = () => {- alert('Login functionality would open here');+ const extendSession = async () => {+ if (!session?.api_key) return;+ setLoading(true);+ const result = await UserApiService.extendGuestSession(session.api_key);+ setLoading(false);+ if (result.success) {+ alert('Session extended successfully!');+ } else {+ alert(`Failed to extend session: ${result.error}`);+ }};- const regenerateApiKey = () => {- const newKey = `fk_user_${Math.random().toString(36).substring(2, 15)}`;- // TODO: Implement actual API key regeneration- console.log('New API key generated:', newKey);+ const cancelSubscription = async () => {+ if (!session?.api_key) return;+ if (confirm('Are you sure you want to cancel your subscription? It will remain active until the end of the billing period.')) {+ setLoading(true);+ const result = await UserApiService.cancelSubscription(session.api_key);+ setLoading(false);+ if (result.success) {+ alert('Subscription cancelled successfully. It will remain active until the end of your billing period.');+ } else {+ alert(`Failed to cancel subscription: ${result.error}`);+ }+ }};- // Header component matching DearPyGUI style- const Header = ({ title, lastRefresh }: { title: string, lastRefresh: Date }) => (- <div className="mb-5">- <div className="flex items-center gap-5 mb-2">- <span style={{ color: COLORS.title }} className="text-lg font-mono">{title}</span>- <span style={{ color: COLORS.info }} className="text-sm font-mono">- 🔄 Refreshed: {lastRefresh.toLocaleTimeString()}- </span>- <button- onClick={manualRefresh}- className="bg-gray-700 hover:bg-gray-600 text-white px-3 py-1 text-xs font-mono border border-gray-600"- >- 🔄 Refresh- </button>- <button- onClick={logoutUser}- className="bg-gray-700 hover:bg-gray-600 text-white px-3 py-1 text-xs font-mono border border-gray-600"- >- 🚪 Logout- </button>- </div>- <div className="border-t border-gray-600"></div>- </div>- );-- // Info Widget component matching DearPyGUI child window style- const InfoWidget = ({ title, children, width = 350, height = 450 }: {- title: string,- children: React.ReactNode,- width?: number,- height?: number- }) => (- <div- className="border border-gray-600 bg-black p-3"- style={{ width: `${width}px`, height: `${height}px`, overflow: 'auto' }}- >- <div style={{ color: COLORS.title }} className="text-sm font-mono mb-2">{title}</div>- <div className="border-t border-gray-600 mb-3"></div>- <div className="space-y-2">- {children}- </div>- </div>- );-- // Two column layout matching DearPyGUI horizontal group- const TwoColumnLayout = ({ left, right }: { left: React.ReactNode, right: React.ReactNode }) => (- <div className="flex gap-5">- {left}- {right}- </div>- );-- // Button group component- const ButtonGroup = ({ buttons }: { buttons: Array<{ label: string, callback: () => void }> }) => (- <div className="space-y-1">- {buttons.map((button, index) => (- <div key={index}>- <button- onClick={button.callback}- className="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 text-xs font-mono border border-gray-600 w-70"- style={{ width: '280px' }}- >- {button.label}- </button>- </div>- ))}- </div>- );-- // Text line component with optional color- const TextLine = ({ text, color }: { text: string, color?: string }) => (- <div style={{ color: color || '#ffffff' }} className="text-xs font-mono leading-relaxed">- {text}- </div>- );-- const Spacer = ({ height = 10 }: { height?: number }) => (- <div style={{ height: `${height}px` }}></div>- );-- // Get API key display format- const getApiKeyInfo = (apiKey?: string, isUser = false) => {- if (!apiKey) return "No API key";-- if (isUser) {- return `API Key: ${apiKey.substring(0, 12)}...`;+ const reactivateSubscription = async () => {+ if (!session?.api_key) return;+ setLoading(true);+ const result = await UserApiService.reactivateSubscription(session.api_key);+ setLoading(false);+ if (result.success) {+ alert('Subscription reactivated successfully!');+ } else {+ alert(`Failed to reactivate subscription: ${result.error}`);}+ };- if (apiKey.startsWith("fk_guest_")) {- return `Guest API Key: ${apiKey.substring(0, 15)}...`;+ const deleteAccount = async () => {+ if (!session?.api_key) return;+ const confirmation = prompt('This action cannot be undone. Type "DELETE MY ACCOUNT" to confirm:');+ if (confirmation === 'DELETE MY ACCOUNT') {+ setLoading(true);+ const result = await UserApiService.deleteUserAccount(session.api_key, { confirm: true });+ setLoading(false);+ if (result.success) {+ alert('Your account has been deleted.');+ await logout();+ } else {+ alert(`Failed to delete account: ${result.error}`);+ }}-- return "No API key";};- // Format dateconst formatDate = (dateStr?: string) => {if (!dateStr) return 'N/A';- return new Date(dateStr).toLocaleDateString();+ return new Date(dateStr).toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ });};- const renderGuestProfile = () => {- if (!session) return null;- const displayDeviceId = session.device_id?.substring(0, 20) + "..." || 'Unknown';- const requests_today = session.requests_today || 0;- const daily_limit = session.daily_limit || 50;- const remaining = Math.max(0, daily_limit - requests_today);+ const formatCurrency = (amount: number) => {+ return `$${(amount / 100).toFixed(2)}`;+ };++ // Navigation buttons+ const renderNavigationButtons = () => {+ const buttons: { id: ProfileScreen; label: string; color: string }[] = [+ { id: 'overview', label: 'OVERVIEW', color: C.ORANGE },+ { id: 'usage', label: 'USAGE STATS', color: C.CYAN },+ { id: 'payments', label: 'PAYMENTS', color: C.GREEN },+ { id: 'subscriptions', label: 'SUBSCRIPTIONS', color: C.PURPLE },+ { id: 'support', label: 'SUPPORT', color: C.BLUE },+ { id: 'settings', label: 'SETTINGS', color: C.RED },+ ];return (- <div className="p-4">- <Header title="👤 Guest Profile" lastRefresh={lastRefresh} />-- <TwoColumnLayout- left={- <InfoWidget title="Current Session Status">- <TextLine text="Account Type: Guest User" />- <TextLine text={`Device ID: ${displayDeviceId}`} />- <Spacer />- <TextLine text={getApiKeyInfo(session.api_key || undefined)} />- <Spacer />- <TextLine text={`Session Requests: ${requestCount}`} />- <TextLine text={`Today's Requests: ${requests_today}/${daily_limit}`} />- <TextLine- text={`Remaining Today: ${remaining}`}- color={remaining > 10 ? COLORS.success : COLORS.error}- />- <Spacer />- <TextLine text="✓ Basic market data" />- <TextLine text="✓ Real-time quotes" />- <TextLine text="✓ Public databases" />- </InfoWidget>- }- right={- <InfoWidget title="Upgrade Your Access">- <TextLine- text={session.api_key ? "🔄 Current: Guest API Key" : "🔄 Current: Offline Mode"}- color={COLORS.warning}- />- <Spacer />- {session.api_key ? (- <>- <TextLine text="• Temporary access (24 hours)" />- <TextLine text="• 50 requests per day" />- </>- ) : (- <TextLine text="• No API access" />- )}- <Spacer />- <TextLine text="🔑 Create Account" color={COLORS.info} />- <TextLine text="Get unlimited access:" />- <TextLine text="• Permanent API key" />- <TextLine text="• Unlimited requests" />- <TextLine text="• All databases access" />- <TextLine text="• Premium features" />- <Spacer height={20} />- <ButtonGroup buttons={[- { label: "Create Free Account", callback: showSignupInfo },- { label: "Sign In to Account", callback: showLoginInfo }- ]} />- </InfoWidget>- }- />+ <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>+ {buttons.map((btn) => (+ <button+ key={btn.id}+ onClick={() => setCurrentScreen(btn.id)}+ style={{+ padding: '8px 16px',+ backgroundColor: currentScreen === btn.id ? btn.color : C.DARK_BG,+ border: `2px solid ${btn.color}`,+ color: currentScreen === btn.id ? C.DARK_BG : btn.color,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ transition: 'all 0.2s'+ }}+ >+ {btn.label}+ </button>+ ))}+ </div>+ );+ };- <Spacer height={20} />+ const renderGuestProfile = () => {+ const displayDeviceId = session?.device_id?.substring(0, 30) + "..." || 'Unknown';+ const requestsToday = session?.requests_today || usageData?.requests_today || 0;+ const dailyLimit = session?.daily_limit || usageData?.daily_limit || 50;+ const remaining = Math.max(0, dailyLimit - requestsToday);+ const usagePercent = (requestsToday / dailyLimit) * 100;- {/* Session Stats - Full Width */}- <InfoWidget title="Session Statistics" width={750} height={150}>- <div className="grid grid-cols-4 gap-4 text-xs font-mono">- <div>- <TextLine text="Request Count:" color={COLORS.info} />- <TextLine text={requestCount.toString()} />- </div>- <div>- <TextLine text="Daily Usage:" color={COLORS.info} />- <TextLine text={`${requests_today}/${daily_limit}`} />- </div>- <div>- <TextLine text="Status:" color={COLORS.info} />- <TextLine text="Active" color={COLORS.success} />- </div>- <div>- <TextLine text="Session Time:" color={COLORS.info} />- <TextLine text="00:45:23" />+ return (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: C.DARK_BG }}>+ {/* Header */}+ <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}`, padding: '12px 16px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '16px', fontFamily: 'Consolas, monospace' }}>+ 👤 GUEST PROFILE+ </span>+ <span style={{ color: C.GRAY }}>|</span>+ <span style={{ color: C.CYAN, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>+ {currentTime.toLocaleTimeString()}+ </span></div>+ <button+ onClick={logoutUser}+ style={{+ padding: '6px 12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.RED}`,+ color: C.RED,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 🚪 LOGOUT+ </button></div>- </InfoWidget>+ </div>++ {/* Content */}+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>+ {renderNavigationButtons()}++ {currentScreen === 'overview' && (+ <>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px', marginBottom: '16px' }}>+ {/* Session Info */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.BLUE}`, padding: '16px' }}>+ <div style={{ color: C.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ SESSION INFORMATION+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Account Type:</span>+ <span style={{ color: C.YELLOW, marginLeft: '8px', fontWeight: 'bold' }}>GUEST USER</span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Device ID:</span>+ <div style={{ color: C.WHITE, marginTop: '4px', fontSize: '10px' }}>{displayDeviceId}</div>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>API Key:</span>+ <div style={{ color: C.WHITE, marginTop: '4px', fontSize: '10px' }}>+ {session?.api_key ? `${session.api_key.substring(0, 20)}...` : 'N/A'}+ </div>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Session Expires:</span>+ <span style={{ color: C.ORANGE, marginLeft: '8px' }}>+ {session?.expires_at ? formatDate(session.expires_at) : 'N/A'}+ </span>+ </div>+ <button+ onClick={extendSession}+ disabled={loading}+ style={{+ marginTop: '12px',+ padding: '8px 16px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.CYAN}`,+ color: C.CYAN,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ width: '100%'+ }}+ >+ ⏰ EXTEND SESSION+ </button>+ </div>+ </div>++ {/* Usage Stats */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.ORANGE}`, padding: '16px' }}>+ <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ DAILY USAGE+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>+ <div style={{ marginBottom: '12px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ color: C.GRAY }}>Today's Requests:</span>+ <span style={{ color: C.WHITE, fontWeight: 'bold' }}>{requestsToday} / {dailyLimit}</span>+ </div>+ <div style={{ backgroundColor: C.DARK_BG, height: '8px', borderRadius: '4px', overflow: 'hidden' }}>+ <div+ style={{+ width: `${usagePercent}%`,+ height: '100%',+ backgroundColor: remaining > 10 ? C.GREEN : C.RED,+ transition: 'width 0.3s'+ }}+ />+ </div>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Remaining:</span>+ <span style={{ color: remaining > 10 ? C.GREEN : C.RED, marginLeft: '8px', fontWeight: 'bold' }}>+ {remaining} requests+ </span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Status:</span>+ <span style={{ color: C.GREEN, marginLeft: '8px', fontWeight: 'bold' }}>● ACTIVE</span>+ </div>+ </div>+ </div>+ </div>++ {/* Features */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '16px', marginBottom: '16px' }}>+ <div style={{ color: C.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ ✓ GUEST ACCESS FEATURES+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', color: C.WHITE, fontSize: '11px', fontFamily: 'Consolas, monospace' }}>+ <div>✓ Basic market data</div>+ <div>✓ Real-time quotes</div>+ <div>✓ Public databases</div>+ <div>✓ Forum access</div>+ <div>✓ News feeds</div>+ <div>✓ Basic charts</div>+ </div>+ </div>++ {/* Upgrade Section */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.ORANGE}`, borderLeft: `6px solid ${C.ORANGE}`, padding: '16px' }}>+ <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ 🔑 UPGRADE TO FULL ACCESS+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', marginBottom: '16px', lineHeight: '1.8' }}>+ <div style={{ color: C.YELLOW, marginBottom: '8px' }}>Create a free account to unlock:</div>+ <div>• Unlimited API requests</div>+ <div>• Permanent API key</div>+ <div>• All database access</div>+ <div>• Premium features & tools</div>+ <div>• Data marketplace</div>+ <div>• Advanced analytics</div>+ </div>+ <div style={{ display: 'flex', gap: '12px' }}>+ <button+ onClick={() => navigation.navigateToPricing()}+ style={{+ padding: '10px 20px',+ backgroundColor: C.ORANGE,+ border: 'none',+ color: C.DARK_BG,+ fontSize: '12px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ flex: 1+ }}+ >+ 📦 VIEW PLANS+ </button>+ </div>+ </div>+ </>+ )}++ {currentScreen === 'usage' && renderUsageScreen()}+ {currentScreen === 'settings' && renderGuestSettingsScreen()}+ </div></div>);};const renderUserProfile = () => {- if (!session) return null;- const userInfo = session.user_info;- const creditBalance = userInfo?.credit_balance || 0;+ const userInfo = session?.user_info;const accountType = userInfo?.account_type || 'free';- const hasSubscription = session.subscription?.has_subscription;- const subscriptionPlan = session.subscription?.subscription?.plan;-- let balanceColor, status;- if (creditBalance > 1000) {- balanceColor = COLORS.success;- status = "Excellent";- } else if (creditBalance > 100) {- balanceColor = COLORS.warning;- status = "Good";- } else {- balanceColor = COLORS.error;- status = "Low Credits";- }+ const hasSubscription = (session?.subscription as any)?.data?.has_subscription || session?.subscription?.has_subscription;+ const subscriptionPlan = (session?.subscription as any)?.data?.subscription?.plan || session?.subscription?.subscription?.plan;+ const subscriptionStatus = (session?.subscription as any)?.data?.subscription?.status || session?.subscription?.subscription?.status;++ const accountTypeColor = {+ free: C.GRAY,+ starter: C.BLUE,+ professional: C.PURPLE,+ enterprise: C.ORANGE,+ unlimited: C.YELLOW+ }[accountType] || C.WHITE;return (- <div className="p-4">- <Header title={`🔑 ${userInfo?.username || 'User'}'s Profile`} lastRefresh={lastRefresh} />-- <TwoColumnLayout- left={- <InfoWidget title="Account Details">- <TextLine text={`Username: ${userInfo?.username || 'N/A'}`} />- <TextLine text={`Email: ${userInfo?.email || 'N/A'}`} />- <TextLine text={`Account Type: ${accountType.charAt(0).toUpperCase() + accountType.slice(1)}`} />- <TextLine text={`Member Since: ${formatDate((userInfo as any)?.created_at)}`} />- <Spacer />- {hasSubscription && subscriptionPlan && (- <>- <TextLine text="Subscription:" color={COLORS.info} />- <TextLine text={`Plan: ${subscriptionPlan.name}`} color={COLORS.success} />- <TextLine text={`Price: $${subscriptionPlan.price}/month`} />- <TextLine text={`Status: ${session.subscription?.subscription?.status}`} color={COLORS.success} />- <Spacer />- </>- )}- <TextLine text="Authentication:" color={COLORS.info} />- <TextLine text={getApiKeyInfo(session.api_key || undefined, true)} />- <Spacer />- <TextLine text={hasSubscription ? "✓ Unlimited API requests" : "✓ Limited API requests"} />- <TextLine text={hasSubscription ? "✓ All database access" : "✓ Basic database access"} />- <TextLine text={hasSubscription ? "✓ Premium features" : "✓ Standard features"} />- <Spacer height={20} />- <ButtonGroup buttons={[- { label: "Regenerate API Key", callback: regenerateApiKey },- { label: "Switch Account", callback: logoutUser }- ]} />- </InfoWidget>- }- right={- <InfoWidget title="Credits & Usage">- <TextLine text={`Current Balance: ${creditBalance} credits`} />- <TextLine text={`Status: ${status}`} color={balanceColor} />- <Spacer />- <TextLine text="Live Usage Stats:" color={COLORS.info} />- <TextLine text={`Total Requests: ${usageStats.total_requests}`} />- <TextLine text={`Credits Used: ${usageStats.total_credits_used}`} />- <TextLine text={`This Session: ${requestCount}`} />- <Spacer />- <TextLine text="Quick Actions:" />- </InfoWidget>- }- />+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: C.DARK_BG }}>+ {/* Header */}+ <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}`, padding: '12px 16px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '16px', fontFamily: 'Consolas, monospace' }}>+ 🔑 {userInfo?.username?.toUpperCase() || 'USER'} PROFILE+ </span>+ <span style={{ color: C.GRAY }}>|</span>+ <span style={{ color: C.CYAN, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>+ {currentTime.toLocaleTimeString()}+ </span>+ </div>+ <button+ onClick={logoutUser}+ style={{+ padding: '6px 12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.RED}`,+ color: C.RED,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 🚪 LOGOUT+ </button>+ </div>+ </div>- <Spacer height={20} />+ {/* Content */}+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>+ {renderNavigationButtons()}++ {currentScreen === 'overview' && (+ <>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px', marginBottom: '16px' }}>+ {/* Account Details */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.BLUE}`, padding: '16px' }}>+ <div style={{ color: C.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ ACCOUNT DETAILS+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Username:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px', fontWeight: 'bold' }}>{userInfo?.username || 'N/A'}</span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Email:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px' }}>{userInfo?.email || 'N/A'}</span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Account Type:</span>+ <span style={{ color: accountTypeColor, marginLeft: '8px', fontWeight: 'bold' }}>+ {accountType.toUpperCase()}+ </span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Member Since:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px' }}>+ {formatDate((userInfo as any)?.created_at)}+ </span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>User ID:</span>+ <span style={{ color: C.GRAY, marginLeft: '8px', fontSize: '10px' }}>#{userInfo?.id || 'N/A'}</span>+ </div>+ </div>+ </div>++ {/* Subscription Info */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${hasSubscription ? C.GREEN : C.ORANGE}`, padding: '16px' }}>+ <div style={{ color: hasSubscription ? C.GREEN : C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ {hasSubscription ? '✓ SUBSCRIPTION ACTIVE' : '📦 NO SUBSCRIPTION'}+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>+ {hasSubscription && subscriptionPlan ? (+ <>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Plan:</span>+ <span style={{ color: C.GREEN, marginLeft: '8px', fontWeight: 'bold' }}>{subscriptionPlan.name}</span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Price:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px' }}>${subscriptionPlan.price_usd / 100}/month</span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>API Calls:</span>+ <span style={{ color: C.CYAN, marginLeft: '8px', fontWeight: 'bold' }}>+ {subscriptionPlan.api_calls_limit === -1 ? 'UNLIMITED' :+ subscriptionPlan.api_calls_limit != null ? subscriptionPlan.api_calls_limit.toLocaleString() : 'N/A'}+ </span>+ </div>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Status:</span>+ <span style={{ color: C.GREEN, marginLeft: '8px', fontWeight: 'bold' }}>● {subscriptionStatus?.toUpperCase()}</span>+ </div>+ <div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>+ <button+ onClick={cancelSubscription}+ disabled={loading}+ style={{+ flex: 1,+ padding: '8px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.RED}`,+ color: C.RED,+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ CANCEL+ </button>+ <button+ onClick={() => navigation.navigateToPricing()}+ style={{+ flex: 1,+ padding: '8px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.BLUE}`,+ color: C.BLUE,+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ CHANGE+ </button>+ </div>+ </>+ ) : (+ <>+ <div style={{ color: C.YELLOW, marginBottom: '8px' }}>Upgrade to unlock:</div>+ <div>• Unlimited API requests</div>+ <div>• Priority support</div>+ <div>• Advanced features</div>+ <div>• Data marketplace access</div>+ <button+ onClick={() => navigation.navigateToPricing()}+ style={{+ marginTop: '12px',+ padding: '10px',+ backgroundColor: C.ORANGE,+ border: 'none',+ color: C.DARK_BG,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ width: '100%'+ }}+ >+ 📦 VIEW PLANS+ </button>+ </>+ )}+ </div>+ </div>+ </div>++ {/* API Key */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.PURPLE}`, padding: '16px', marginBottom: '16px' }}>+ <div style={{ color: C.PURPLE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ 🔐 API AUTHENTICATION+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>API Key:</span>+ </div>+ <div style={{ backgroundColor: C.DARK_BG, padding: '8px', marginBottom: '12px', border: `1px solid ${C.GRAY}`, fontSize: '10px', wordBreak: 'break-all' }}>+ {session?.api_key || 'No API key available'}+ </div>+ <button+ onClick={regenerateApiKey}+ disabled={loading}+ style={{+ padding: '8px 16px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.PURPLE}`,+ color: C.PURPLE,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 🔄 REGENERATE API KEY+ </button>+ </div>+ </div>++ {/* Quick Actions */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.ORANGE}`, padding: '16px' }}>+ <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ ⚡ QUICK ACTIONS+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>+ <button+ onClick={() => setCurrentScreen('usage')}+ style={{+ padding: '12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.CYAN}`,+ color: C.CYAN,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 📊 USAGE STATS+ </button>+ <button+ onClick={() => setCurrentScreen('payments')}+ style={{+ padding: '12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GREEN}`,+ color: C.GREEN,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 💳 PAYMENT HISTORY+ </button>+ <button+ onClick={() => setCurrentScreen('subscriptions')}+ style={{+ padding: '12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.PURPLE}`,+ color: C.PURPLE,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 💾 SUBSCRIPTIONS+ </button>+ <button+ onClick={() => setCurrentScreen('support')}+ style={{+ padding: '12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.BLUE}`,+ color: C.BLUE,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 🎫 SUPPORT+ </button>+ </div>+ </div>+ </>+ )}++ {currentScreen === 'usage' && renderUsageScreen()}+ {currentScreen === 'payments' && renderPaymentsScreen()}+ {currentScreen === 'subscriptions' && renderSubscriptionsScreen()}+ {currentScreen === 'support' && renderSupportScreen()}+ {currentScreen === 'settings' && renderSettingsScreen()}+ </div>+ </div>+ );+ };- {/* User Stats - Full Width */}- <InfoWidget title="User Statistics" width={750} height={150}>- <div className="grid grid-cols-4 gap-4 text-xs font-mono">- <div>- <TextLine text="Total Requests:" color={COLORS.info} />- <TextLine text={usageStats.total_requests.toLocaleString()} />- </div>- <div>- <TextLine text="Credits Balance:" color={COLORS.info} />- <TextLine text={creditBalance.toLocaleString()} color={balanceColor} />+ const renderUsageScreen = () => {+ return (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.CYAN}`, padding: '16px' }}>+ <div style={{ color: C.CYAN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ 📊 API USAGE STATISTICS+ </div>+ {loading ? (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading usage data...</div>+ ) : usageData ? (+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Total Requests:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px', fontWeight: 'bold' }}>+ {usageData.total_requests?.toLocaleString() || 'N/A'}+ </span></div>- <div>- <TextLine text="Account Status:" color={COLORS.info} />- <TextLine text="Active" color={COLORS.success} />+ <div style={{ marginBottom: '8px' }}>+ <span style={{ color: C.GRAY }}>Today's Requests:</span>+ <span style={{ color: C.CYAN, marginLeft: '8px', fontWeight: 'bold' }}>+ {usageData.requests_today || usageData.today_requests || 0}+ </span></div>- <div>- <TextLine text="API Status:" color={COLORS.info} />- <TextLine text="Connected" color={COLORS.success} />+ {detailedUsage && (+ <>+ <div style={{ marginTop: '16px', color: C.ORANGE, fontWeight: 'bold' }}>Detailed Usage:</div>+ <div style={{ marginTop: '8px' }}>+ <span style={{ color: C.GRAY }}>This Month:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px' }}>+ {detailedUsage.this_month?.toLocaleString() || 'N/A'}+ </span>+ </div>+ <div style={{ marginTop: '8px' }}>+ <span style={{ color: C.GRAY }}>Last 30 Days:</span>+ <span style={{ color: C.WHITE, marginLeft: '8px' }}>+ {detailedUsage.last_30_days?.toLocaleString() || 'N/A'}+ </span>+ </div>+ </>+ )}+ </div>+ ) : (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>No usage data available</div>+ )}+ </div>+ );+ };++ const renderPaymentsScreen = () => {+ return (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '16px' }}>+ <div style={{ color: C.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ 💳 PAYMENT HISTORY+ </div>+ {loading ? (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading payment history...</div>+ ) : paymentHistory.length > 0 ? (+ <div style={{ maxHeight: '400px', overflowY: 'auto' }}>+ {paymentHistory.map((payment: any, idx: number) => (+ <div+ key={idx}+ style={{+ backgroundColor: C.DARK_BG,+ border: `1px solid ${C.GRAY}`,+ padding: '12px',+ marginBottom: '8px',+ fontFamily: 'Consolas, monospace',+ fontSize: '11px'+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ color: C.GRAY }}>Amount:</span>+ <span style={{ color: C.GREEN, fontWeight: 'bold' }}>+ {formatCurrency(payment.amount || payment.amount_paid || 0)}+ </span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ color: C.GRAY }}>Date:</span>+ <span style={{ color: C.WHITE }}>{formatDate(payment.created_at || payment.payment_date)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: C.GRAY }}>Status:</span>+ <span style={{ color: payment.status === 'completed' ? C.GREEN : C.YELLOW }}>+ {payment.status?.toUpperCase() || 'N/A'}+ </span>+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>No payment history found</div>+ )}+ </div>+ );+ };++ const renderSubscriptionsScreen = () => {+ return (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.PURPLE}`, padding: '16px' }}>+ <div style={{ color: C.PURPLE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ 💾 DATABASE SUBSCRIPTIONS+ </div>+ {loading ? (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading subscriptions...</div>+ ) : subscriptions.length > 0 ? (+ <div>+ {subscriptions.map((sub: any, idx: number) => (+ <div+ key={idx}+ style={{+ backgroundColor: C.DARK_BG,+ border: `1px solid ${C.GRAY}`,+ padding: '12px',+ marginBottom: '8px',+ fontFamily: 'Consolas, monospace',+ fontSize: '11px'+ }}+ >+ <div style={{ color: C.PURPLE, fontWeight: 'bold', marginBottom: '4px' }}>+ {sub.database_name || sub.name || 'Unknown Database'}+ </div>+ <div style={{ color: C.GRAY }}>+ Subscribed: {formatDate(sub.subscribed_at || sub.created_at)}+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>No database subscriptions found</div>+ )}+ </div>+ );+ };++ const renderSupportScreen = () => {+ return (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.BLUE}`, padding: '16px' }}>+ <div style={{ color: C.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ 🎫 SUPPORT TICKETS+ </div>+ {loading ? (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading tickets...</div>+ ) : supportTickets.length > 0 ? (+ <div style={{ maxHeight: '400px', overflowY: 'auto' }}>+ {supportTickets.map((ticket: any, idx: number) => (+ <div+ key={idx}+ style={{+ backgroundColor: C.DARK_BG,+ border: `1px solid ${C.GRAY}`,+ padding: '12px',+ marginBottom: '8px',+ fontFamily: 'Consolas, monospace',+ fontSize: '11px'+ }}+ >+ <div style={{ color: C.BLUE, fontWeight: 'bold', marginBottom: '4px' }}>+ #{ticket.id} - {ticket.subject}+ </div>+ <div style={{ color: C.GRAY, marginBottom: '4px' }}>{ticket.description?.substring(0, 100)}...</div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: C.GRAY }}>Status:</span>+ <span style={{ color: ticket.status === 'closed' ? C.GREEN : C.YELLOW }}>+ {ticket.status?.toUpperCase()}+ </span>+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div>+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px', marginBottom: '16px' }}>+ No support tickets found</div>+ <button+ onClick={() => alert('Create ticket feature coming soon')}+ style={{+ padding: '10px 20px',+ backgroundColor: C.BLUE,+ border: 'none',+ color: C.DARK_BG,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ + CREATE NEW TICKET+ </button></div>- </InfoWidget>+ )}</div>);};- const renderUnknownProfile = () => (- <div className="p-4">- <Header title="❓ Unknown Session State" lastRefresh={lastRefresh} />-- <InfoWidget title="Session Status" width={500} height={200}>- <TextLine text="Unable to determine authentication status" />- <TextLine text="This may indicate a configuration issue." />- <Spacer />- <TextLine text="Try refreshing or restarting the application" color={COLORS.warning} />- <Spacer height={40} />- <ButtonGroup buttons={[- { label: "🔄 Refresh Profile", callback: manualRefresh },- { label: "Clear Session & Restart", callback: logoutUser }- ]} />- </InfoWidget>- </div>- );-- // Main render logic based on user type- const renderContent = () => {- if (!session) {- return renderUnknownProfile();- }+ const renderSettingsScreen = () => {+ return (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.RED}`, padding: '16px' }}>+ <div style={{ color: C.RED, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ ⚙️ ACCOUNT SETTINGS+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>+ <div style={{ marginBottom: '16px' }}>+ <div style={{ color: C.YELLOW, fontWeight: 'bold', marginBottom: '8px' }}>⚠️ DANGER ZONE</div>+ <div style={{ color: C.GRAY, marginBottom: '12px' }}>+ Deleting your account is permanent and cannot be undone. All your data will be lost.+ </div>+ <button+ onClick={deleteAccount}+ disabled={loading}+ style={{+ padding: '10px 20px',+ backgroundColor: C.RED,+ border: 'none',+ color: C.WHITE,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 🗑️ DELETE ACCOUNT+ </button>+ </div>+ </div>+ </div>+ );+ };- switch (session.user_type) {- case 'guest': return renderGuestProfile();- case 'registered': return renderUserProfile();- default: return renderUnknownProfile();- }+ const renderGuestSettingsScreen = () => {+ return (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.RED}`, padding: '16px' }}>+ <div style={{ color: C.RED, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ ⚙️ SESSION SETTINGS+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>+ <div style={{ marginBottom: '16px' }}>+ <div style={{ color: C.YELLOW, fontWeight: 'bold', marginBottom: '8px' }}>⚠️ DANGER ZONE</div>+ <div style={{ color: C.GRAY, marginBottom: '12px' }}>+ Deleting your guest session will remove all your data. This action cannot be undone.+ </div>+ <button+ onClick={async () => {+ if (confirm('Are you sure you want to delete your guest session?')) {+ if (session?.api_key) {+ setLoading(true);+ const result = await UserApiService.deleteGuestSession(session.api_key);+ setLoading(false);+ if (result.success) {+ alert('Guest session deleted successfully.');+ await logout();+ } else {+ alert(`Failed to delete session: ${result.error}`);+ }+ }+ }+ }}+ disabled={loading}+ style={{+ padding: '10px 20px',+ backgroundColor: C.RED,+ border: 'none',+ color: C.WHITE,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ 🗑️ DELETE SESSION+ </button>+ </div>+ </div>+ </div>+ );};- return (- <div className="h-full bg-black text-white font-mono text-xs overflow-auto">- {renderContent()}- </div>- );+ // Main render+ if (!session) {+ return (+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: C.DARK_BG, color: C.WHITE, fontFamily: 'Consolas, monospace' }}>+ <div style={{ textAlign: 'center' }}>+ <div style={{ fontSize: '16px', color: C.ORANGE, marginBottom: '12px' }}>❌ NO SESSION</div>+ <div style={{ fontSize: '12px', color: C.GRAY }}>Unable to load profile</div>+ </div>+ </div>+ );+ }++ return session.user_type === 'guest' ? renderGuestProfile() : renderUserProfile();};-export default ProfileTab;\ No newline at end of file+export default ProfileTab;diff --git a/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx b/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsxnew file mode 100644index 000000000..c0eebb80a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx@@ -0,0 +1,667 @@+import React, { useState, useEffect } from 'react';+import { useAuth } from '@/contexts/AuthContext';+import { SupportApiService } from '@/services/supportApi';++// Bloomberg Terminal Colors+const C = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ RED: '#FF0000',+ GREEN: '#00C800',+ YELLOW: '#FFFF00',+ GRAY: '#787878',+ BLUE: '#6496FA',+ PURPLE: '#C864FF',+ CYAN: '#00FFFF',+ DARK_BG: '#000000',+ PANEL_BG: '#0a0a0a'+};++type SupportView = 'list' | 'create' | 'details';++const SupportTicketTab: React.FC = () => {+ const { session } = useAuth();+ const [currentView, setCurrentView] = useState<SupportView>('list');+ const [loading, setLoading] = useState(false);+ const [tickets, setTickets] = useState<any[]>([]);+ const [selectedTicket, setSelectedTicket] = useState<any>(null);+ const [categories, setCategories] = useState<any[]>([]);+ const [stats, setStats] = useState<any>(null);++ // Create ticket form+ const [newTicket, setNewTicket] = useState({+ subject: '',+ description: '',+ category: 'technical',+ priority: 'medium'+ });++ // Message form+ const [newMessage, setNewMessage] = useState('');++ useEffect(() => {+ if (session?.api_key) {+ loadTickets();+ loadCategories();+ loadStats();+ }+ }, [session]);++ const loadTickets = async () => {+ if (!session?.api_key) return;+ setLoading(true);+ const result = await SupportApiService.getUserTickets(session.api_key);+ if (result.success) {+ setTickets(result.data?.tickets || result.data || []);+ }+ setLoading(false);+ };++ const loadCategories = async () => {+ const result = await SupportApiService.getSupportCategories();+ if (result.success) {+ setCategories(result.data?.categories || result.data || []);+ }+ };++ const loadStats = async () => {+ if (!session?.api_key) return;+ const result = await SupportApiService.getSupportStats(session.api_key);+ if (result.success) {+ setStats(result.data);+ }+ };++ const createTicket = async () => {+ if (!session?.api_key || !newTicket.subject || !newTicket.description) {+ alert('Please fill in all required fields');+ return;+ }++ setLoading(true);+ const result = await SupportApiService.createTicket(session.api_key, newTicket);+ setLoading(false);++ if (result.success) {+ alert('Ticket created successfully!');+ setNewTicket({ subject: '', description: '', category: 'technical', priority: 'medium' });+ setCurrentView('list');+ loadTickets();+ } else {+ alert(`Failed to create ticket: ${result.error}`);+ }+ };++ const viewTicketDetails = async (ticketId: number) => {+ if (!session?.api_key) return;+ setLoading(true);+ const result = await SupportApiService.getTicketDetails(session.api_key, ticketId);+ setLoading(false);++ if (result.success) {+ setSelectedTicket(result.data);+ setCurrentView('details');+ } else {+ alert(`Failed to load ticket details: ${result.error}`);+ }+ };++ const addMessage = async () => {+ if (!session?.api_key || !selectedTicket || !newMessage.trim()) return;++ setLoading(true);+ const result = await SupportApiService.addTicketMessage(+ session.api_key,+ selectedTicket.id || selectedTicket.ticket_id,+ newMessage+ );+ setLoading(false);++ if (result.success) {+ setNewMessage('');+ viewTicketDetails(selectedTicket.id || selectedTicket.ticket_id);+ } else {+ alert(`Failed to add message: ${result.error}`);+ }+ };++ const updateTicketStatus = async (status: string) => {+ if (!session?.api_key || !selectedTicket) return;++ setLoading(true);+ const result = await SupportApiService.updateTicket(+ session.api_key,+ selectedTicket.id || selectedTicket.ticket_id,+ status+ );+ setLoading(false);++ if (result.success) {+ viewTicketDetails(selectedTicket.id || selectedTicket.ticket_id);+ loadTickets();+ } else {+ alert(`Failed to update ticket: ${result.error}`);+ }+ };++ const formatDate = (dateStr?: string) => {+ if (!dateStr) return 'N/A';+ return new Date(dateStr).toLocaleString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit'+ });+ };++ const getStatusColor = (status: string) => {+ switch (status?.toLowerCase()) {+ case 'open':+ case 'in_progress':+ return C.CYAN;+ case 'resolved':+ case 'closed':+ return C.GREEN;+ case 'pending':+ return C.YELLOW;+ default:+ return C.GRAY;+ }+ };++ const getPriorityColor = (priority: string) => {+ switch (priority?.toLowerCase()) {+ case 'high':+ case 'urgent':+ return C.RED;+ case 'medium':+ return C.ORANGE;+ case 'low':+ return C.GREEN;+ default:+ return C.GRAY;+ }+ };++ const renderListView = () => (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>+ {/* Header */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>+ <div>+ <div style={{ color: C.ORANGE, fontSize: '18px', fontWeight: 'bold', fontFamily: 'Consolas, monospace' }}>+ 🎫 SUPPORT TICKETS+ </div>+ {stats && (+ <div style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', marginTop: '4px' }}>+ Total: {stats.total_tickets || 0} | Open: {stats.open_tickets || 0} | Resolved: {stats.resolved_tickets || 0}+ </div>+ )}+ </div>+ <button+ onClick={() => setCurrentView('create')}+ style={{+ padding: '10px 20px',+ backgroundColor: C.GREEN,+ border: 'none',+ color: C.DARK_BG,+ fontSize: '12px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ + CREATE TICKET+ </button>+ </div>++ {/* Tickets List */}+ <div style={{ flex: 1, overflowY: 'auto' }}>+ {loading ? (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>+ Loading tickets...+ </div>+ ) : tickets.length > 0 ? (+ <div style={{ display: 'grid', gap: '12px' }}>+ {tickets.map((ticket: any) => (+ <div+ key={ticket.id || ticket.ticket_id}+ onClick={() => viewTicketDetails(ticket.id || ticket.ticket_id)}+ style={{+ backgroundColor: C.PANEL_BG,+ border: `2px solid ${C.GRAY}`,+ borderLeft: `6px solid ${getStatusColor(ticket.status)}`,+ padding: '16px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ fontFamily: 'Consolas, monospace'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = C.ORANGE;+ e.currentTarget.style.backgroundColor = '#1a1a1a';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = C.GRAY;+ e.currentTarget.style.backgroundColor = C.PANEL_BG;+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>+ <div>+ <span style={{ color: C.GRAY, fontSize: '11px' }}>#{ticket.id || ticket.ticket_id}</span>+ <div style={{ color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginTop: '4px' }}>+ {ticket.subject}+ </div>+ </div>+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ <span+ style={{+ padding: '4px 8px',+ backgroundColor: getStatusColor(ticket.status),+ color: C.DARK_BG,+ fontSize: '10px',+ fontWeight: 'bold',+ borderRadius: '2px'+ }}+ >+ {ticket.status?.toUpperCase()}+ </span>+ <span+ style={{+ padding: '4px 8px',+ backgroundColor: getPriorityColor(ticket.priority),+ color: C.DARK_BG,+ fontSize: '10px',+ fontWeight: 'bold',+ borderRadius: '2px'+ }}+ >+ {ticket.priority?.toUpperCase()}+ </span>+ </div>+ </div>++ <div style={{ color: C.GRAY, fontSize: '11px', marginBottom: '8px' }}>+ {ticket.description?.substring(0, 150)}+ {ticket.description?.length > 150 && '...'}+ </div>++ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>+ <span style={{ color: C.GRAY }}>+ Category: <span style={{ color: C.CYAN }}>{ticket.category}</span>+ </span>+ <span style={{ color: C.GRAY }}>+ Created: <span style={{ color: C.WHITE }}>{formatDate(ticket.created_at)}</span>+ </span>+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px', textAlign: 'center', marginTop: '40px' }}>+ No support tickets found. Create your first ticket to get started!+ </div>+ )}+ </div>+ </div>+ );++ const renderCreateView = () => (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>+ {/* Header */}+ <div style={{ marginBottom: '16px' }}>+ <button+ onClick={() => setCurrentView('list')}+ style={{+ padding: '6px 12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.GRAY,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ marginBottom: '12px'+ }}+ >+ ← BACK TO LIST+ </button>+ <div style={{ color: C.ORANGE, fontSize: '18px', fontWeight: 'bold', fontFamily: 'Consolas, monospace' }}>+ CREATE NEW TICKET+ </div>+ </div>++ {/* Form */}+ <div style={{ flex: 1, overflowY: 'auto' }}>+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '20px' }}>+ <div style={{ marginBottom: '16px' }}>+ <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>+ Subject *+ </label>+ <input+ type="text"+ value={newTicket.subject}+ onChange={(e) => setNewTicket({ ...newTicket, subject: e.target.value })}+ placeholder="Brief description of your issue"+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.WHITE,+ fontSize: '12px',+ fontFamily: 'Consolas, monospace',+ outline: 'none'+ }}+ />+ </div>++ <div style={{ marginBottom: '16px' }}>+ <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>+ Category *+ </label>+ <select+ value={newTicket.category}+ onChange={(e) => setNewTicket({ ...newTicket, category: e.target.value })}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.WHITE,+ fontSize: '12px',+ fontFamily: 'Consolas, monospace',+ outline: 'none'+ }}+ >+ <option value="technical">Technical Issue</option>+ <option value="billing">Billing</option>+ <option value="feature">Feature Request</option>+ <option value="bug">Bug Report</option>+ <option value="account">Account</option>+ <option value="other">Other</option>+ </select>+ </div>++ <div style={{ marginBottom: '16px' }}>+ <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>+ Priority+ </label>+ <select+ value={newTicket.priority}+ onChange={(e) => setNewTicket({ ...newTicket, priority: e.target.value })}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.WHITE,+ fontSize: '12px',+ fontFamily: 'Consolas, monospace',+ outline: 'none'+ }}+ >+ <option value="low">Low</option>+ <option value="medium">Medium</option>+ <option value="high">High</option>+ </select>+ </div>++ <div style={{ marginBottom: '16px' }}>+ <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>+ Description *+ </label>+ <textarea+ value={newTicket.description}+ onChange={(e) => setNewTicket({ ...newTicket, description: e.target.value })}+ placeholder="Provide detailed information about your issue..."+ rows={8}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.WHITE,+ fontSize: '12px',+ fontFamily: 'Consolas, monospace',+ outline: 'none',+ resize: 'vertical'+ }}+ />+ </div>++ <button+ onClick={createTicket}+ disabled={loading}+ style={{+ padding: '12px 24px',+ backgroundColor: loading ? C.GRAY : C.GREEN,+ border: 'none',+ color: C.DARK_BG,+ fontSize: '12px',+ fontWeight: 'bold',+ cursor: loading ? 'not-allowed' : 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ {loading ? 'CREATING...' : 'CREATE TICKET'}+ </button>+ </div>+ </div>+ </div>+ );++ const renderDetailsView = () => {+ if (!selectedTicket) return null;++ const messages = selectedTicket.messages || [];++ return (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>+ {/* Header */}+ <div style={{ marginBottom: '16px' }}>+ <button+ onClick={() => setCurrentView('list')}+ style={{+ padding: '6px 12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.GRAY,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ marginBottom: '12px'+ }}+ >+ ← BACK TO LIST+ </button>++ {/* Ticket Header */}+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${getStatusColor(selectedTicket.status)}`, padding: '16px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>+ <div>+ <span style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace' }}>+ TICKET #{selectedTicket.id || selectedTicket.ticket_id}+ </span>+ <div style={{ color: C.WHITE, fontSize: '16px', fontWeight: 'bold', marginTop: '4px', fontFamily: 'Consolas, monospace' }}>+ {selectedTicket.subject}+ </div>+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ {selectedTicket.status !== 'closed' && (+ <button+ onClick={() => updateTicketStatus('closed')}+ disabled={loading}+ style={{+ padding: '6px 12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.RED}`,+ color: C.RED,+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ CLOSE+ </button>+ )}+ {selectedTicket.status === 'closed' && (+ <button+ onClick={() => updateTicketStatus('open')}+ disabled={loading}+ style={{+ padding: '6px 12px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GREEN}`,+ color: C.GREEN,+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ REOPEN+ </button>+ )}+ </div>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', fontSize: '11px', fontFamily: 'Consolas, monospace' }}>+ <div>+ <span style={{ color: C.GRAY }}>Status: </span>+ <span style={{ color: getStatusColor(selectedTicket.status), fontWeight: 'bold' }}>+ {selectedTicket.status?.toUpperCase()}+ </span>+ </div>+ <div>+ <span style={{ color: C.GRAY }}>Priority: </span>+ <span style={{ color: getPriorityColor(selectedTicket.priority), fontWeight: 'bold' }}>+ {selectedTicket.priority?.toUpperCase()}+ </span>+ </div>+ <div>+ <span style={{ color: C.GRAY }}>Category: </span>+ <span style={{ color: C.CYAN }}>{selectedTicket.category}</span>+ </div>+ <div>+ <span style={{ color: C.GRAY }}>Created: </span>+ <span style={{ color: C.WHITE }}>{formatDate(selectedTicket.created_at)}</span>+ </div>+ </div>++ <div style={{ marginTop: '12px', padding: '12px', backgroundColor: C.DARK_BG, borderLeft: `4px solid ${C.BLUE}` }}>+ <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.6' }}>+ {selectedTicket.description}+ </div>+ </div>+ </div>+ </div>++ {/* Messages */}+ <div style={{ flex: 1, overflowY: 'auto', marginBottom: '16px' }}>+ <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>+ CONVERSATION ({messages.length})+ </div>++ {messages.length > 0 ? (+ <div style={{ display: 'grid', gap: '12px' }}>+ {messages.map((msg: any, idx: number) => (+ <div+ key={idx}+ style={{+ backgroundColor: C.PANEL_BG,+ border: `2px solid ${C.GRAY}`,+ borderLeft: `6px solid ${msg.sender_type === 'user' ? C.CYAN : C.PURPLE}`,+ padding: '12px',+ fontFamily: 'Consolas, monospace'+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>+ <span style={{ color: msg.sender_type === 'user' ? C.CYAN : C.PURPLE, fontSize: '11px', fontWeight: 'bold' }}>+ {msg.sender_type === 'user' ? 'YOU' : 'SUPPORT TEAM'}+ </span>+ <span style={{ color: C.GRAY, fontSize: '10px' }}>+ {formatDate(msg.created_at)}+ </span>+ </div>+ <div style={{ color: C.WHITE, fontSize: '12px', lineHeight: '1.6' }}>+ {msg.message}+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div style={{ color: C.GRAY, fontSize: '12px', fontFamily: 'Consolas, monospace', textAlign: 'center', padding: '20px' }}>+ No messages yet+ </div>+ )}+ </div>++ {/* Add Message */}+ {selectedTicket.status !== 'closed' && (+ <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '16px' }}>+ <div style={{ color: C.GREEN, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px', fontFamily: 'Consolas, monospace' }}>+ ADD MESSAGE+ </div>+ <textarea+ value={newMessage}+ onChange={(e) => setNewMessage(e.target.value)}+ placeholder="Type your message here..."+ rows={4}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: C.DARK_BG,+ border: `2px solid ${C.GRAY}`,+ color: C.WHITE,+ fontSize: '12px',+ fontFamily: 'Consolas, monospace',+ outline: 'none',+ resize: 'vertical',+ marginBottom: '12px'+ }}+ />+ <button+ onClick={addMessage}+ disabled={loading || !newMessage.trim()}+ style={{+ padding: '10px 20px',+ backgroundColor: loading || !newMessage.trim() ? C.GRAY : C.GREEN,+ border: 'none',+ color: C.DARK_BG,+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: loading || !newMessage.trim() ? 'not-allowed' : 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ {loading ? 'SENDING...' : 'SEND MESSAGE'}+ </button>+ </div>+ )}+ </div>+ );+ };++ if (!session) {+ return (+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: C.DARK_BG }}>+ <div style={{ textAlign: 'center', fontFamily: 'Consolas, monospace' }}>+ <div style={{ color: C.ORANGE, fontSize: '16px', marginBottom: '8px' }}>⚠️ AUTHENTICATION REQUIRED</div>+ <div style={{ color: C.GRAY, fontSize: '12px' }}>Please login to access support tickets</div>+ </div>+ </div>+ );+ }++ return (+ <div style={{ height: '100%', backgroundColor: C.DARK_BG, padding: '20px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ {currentView === 'list' && renderListView()}+ {currentView === 'create' && renderCreateView()}+ {currentView === 'details' && renderDetailsView()}+ </div>+ );+};++export default SupportTicketTab;diff --git a/fincept-terminal-desktop/src/contexts/NavigationContext.tsx b/fincept-terminal-desktop/src/contexts/NavigationContext.tsxnew file mode 100644index 000000000..8b1d975d8--- /dev/null+++ b/fincept-terminal-desktop/src/contexts/NavigationContext.tsx@@ -0,0 +1,69 @@+// File: src/contexts/NavigationContext.tsx+// Reusable navigation context for sharing navigation functions across components++import React, { createContext, useContext, ReactNode } from 'react';+import { Screen } from '../App';++interface NavigationContextType {+ navigateToScreen: (screen: Screen) => void;+ navigateToPricing: () => void;+ navigateToDashboard: () => void;+ navigateToProfile: () => void;+ setActiveTab?: (tab: string) => void;+}++const NavigationContext = createContext<NavigationContextType | undefined>(undefined);++export const useNavigation = () => {+ const context = useContext(NavigationContext);+ if (!context) {+ throw new Error('useNavigation must be used within NavigationProvider');+ }+ return context;+};++interface NavigationProviderProps {+ children: ReactNode;+ onNavigate: (screen: Screen) => void;+ onSetActiveTab?: (tab: string) => void;+}++export const NavigationProvider: React.FC<NavigationProviderProps> = ({+ children,+ onNavigate,+ onSetActiveTab+}) => {+ const navigateToScreen = (screen: Screen) => {+ onNavigate(screen);+ };++ const navigateToPricing = () => {+ onNavigate('pricing');+ };++ const navigateToDashboard = () => {+ onNavigate('dashboard');+ };++ const navigateToProfile = () => {+ onNavigate('dashboard');+ if (onSetActiveTab) {+ // Set active tab to profile after a short delay to ensure dashboard is mounted+ setTimeout(() => onSetActiveTab('profile'), 100);+ }+ };++ const value: NavigationContextType = {+ navigateToScreen,+ navigateToPricing,+ navigateToDashboard,+ navigateToProfile,+ setActiveTab: onSetActiveTab+ };++ return (+ <NavigationContext.Provider value={value}>+ {children}+ </NavigationContext.Provider>+ );+};diff --git a/fincept-terminal-desktop/src/services/forumApi.tsx b/fincept-terminal-desktop/src/services/forumApi.tsxindex c82f13eca..cecc51b97 100644--- a/fincept-terminal-desktop/src/services/forumApi.tsx+++ b/fincept-terminal-desktop/src/services/forumApi.tsx@@ -237,13 +237,20 @@ export class ForumApiService {return makeForumRequest<PostDetails>('GET', `/forum/posts/${postUuid}`, apiKey, deviceId);}- // Create new post+ // Create new post (note: endpoint requires category_id in path according to OpenAPI spec)static async createPost(- request: CreatePostRequest,- apiKey: string,+ categoryId: number,+ request: Omit<CreatePostRequest, 'category_id'>,+ apiKey: string,deviceId?: string): Promise<ApiResponse<{ post: ForumPost }>> {- return makeForumRequest<{ post: ForumPost }>('POST', '/forum/posts', apiKey, deviceId, request);+ return makeForumRequest<{ post: ForumPost }>(+ 'POST',+ `/forum/categories/${categoryId}/posts`,+ apiKey,+ deviceId,+ { ...request, category_id: categoryId }+ );}// Add comment to post@@ -379,12 +386,140 @@ export class ForumApiService {// Pin/Unpin post (admin only)static async togglePostPin(- postUuid: string,- apiKey: string,+ postUuid: string,+ apiKey: string,deviceId?: string): Promise<ApiResponse<{ post: ForumPost }>> {return makeForumRequest<{ post: ForumPost }>('POST', `/forum/posts/${postUuid}/toggle-pin`, apiKey, deviceId);}++ // Get trending posts+ static async getTrendingPosts(+ limit: number = 10,+ timeframe: 'day' | 'week' | 'month' = 'week',+ apiKey?: string,+ deviceId?: string+ ): Promise<ApiResponse<{ posts: ForumPost[] }>> {+ return makeForumRequest<{ posts: ForumPost[] }>(+ 'GET',+ `/forum/posts/trending?limit=${limit}&timeframe=${timeframe}`,+ apiKey,+ deviceId+ );+ }++ // Get forum user profile by username+ static async getUserProfile(+ username: string,+ apiKey: string,+ deviceId?: string+ ): Promise<ApiResponse<{+ username: string;+ display_name: string;+ bio: string;+ avatar_color: string;+ signature: string;+ post_count: number;+ comment_count: number;+ reputation: number;+ joined_at: string;+ }>> {+ return makeForumRequest(+ 'GET',+ `/forum/profile/${username}`,+ apiKey,+ deviceId+ );+ }++ // Get current user's forum profile+ static async getMyProfile(+ apiKey: string,+ deviceId?: string+ ): Promise<ApiResponse<{+ username: string;+ display_name: string;+ bio: string;+ avatar_color: string;+ signature: string;+ show_email: boolean;+ email_notifications: boolean;+ post_count: number;+ comment_count: number;+ reputation: number;+ joined_at: string;+ }>> {+ return makeForumRequest(+ 'GET',+ '/forum/profile',+ apiKey,+ deviceId+ );+ }++ // Update forum profile+ static async updateProfile(+ updates: {+ display_name?: string;+ bio?: string;+ avatar_color?: string;+ signature?: string;+ show_email?: boolean;+ email_notifications?: boolean;+ },+ apiKey: string,+ deviceId?: string+ ): Promise<ApiResponse<{ message: string; profile: any }>> {+ return makeForumRequest(+ 'PUT',+ '/forum/profile',+ apiKey,+ deviceId,+ updates+ );+ }++ // Create forum category (admin only)+ static async createCategory(+ categoryData: {+ name: string;+ description: string;+ icon?: string;+ color?: string;+ },+ apiKey: string,+ deviceId?: string+ ): Promise<ApiResponse<{ category: ForumCategory }>> {+ return makeForumRequest<{ category: ForumCategory }>(+ 'POST',+ '/forum/admin/categories',+ apiKey,+ deviceId,+ categoryData+ );+ }++ // Get admin forum statistics+ static async getAdminStatistics(+ apiKey: string,+ deviceId?: string+ ): Promise<ApiResponse<{+ total_posts: number;+ total_comments: number;+ total_users: number;+ posts_today: number;+ comments_today: number;+ active_users_today: number;+ most_active_categories: Array<{ category_name: string; post_count: number }>;+ recent_activity: Array<any>;+ }>> {+ return makeForumRequest(+ 'GET',+ '/forum/admin/statistics',+ apiKey,+ deviceId+ );+ }}// Utility functions for forum operationsdiff --git a/fincept-terminal-desktop/src/services/marketDataService.ts b/fincept-terminal-desktop/src/services/marketDataService.tsindex 326c26e34..fa1658d24 100644--- a/fincept-terminal-desktop/src/services/marketDataService.ts+++ b/fincept-terminal-desktop/src/services/marketDataService.ts@@ -2,6 +2,7 @@// Modular design: gracefully handles failures and can be extended with other data sourcesimport { invoke } from '@tauri-apps/api/core';+import { sqliteService } from './sqliteService';export interface QuoteData {symbol: string;@@ -161,6 +162,61 @@ class MarketDataService {}));}+ /**+ * Fetch enhanced quotes with SQL caching+ * Checks cache first, only fetches from API if cache is stale or missing+ */+ async getEnhancedQuotesWithCache(+ symbols: string[],+ category: string,+ maxCacheAgeMinutes: number = 10+ ): Promise<(QuoteData & { seven_day?: number; thirty_day?: number })[]> {+ try {+ // Check if database is initialized+ if (!sqliteService.isReady()) {+ console.warn('[MarketDataService] Database not ready, fetching without cache');+ return await this.getEnhancedQuotes(symbols);+ }++ // Try to get cached data for all symbols+ const cachedData = await sqliteService.getCachedCategoryData(category, symbols, maxCacheAgeMinutes);++ // Identify which symbols need fresh data+ const symbolsNeedingFetch = symbols.filter(symbol => !cachedData.has(symbol));++ // If all data is cached, return it+ if (symbolsNeedingFetch.length === 0) {+ console.log(`[MarketDataService] Using cached data for ${symbols.length} symbols in ${category}`);+ return symbols.map(symbol => cachedData.get(symbol)!);+ }++ // Fetch missing data from API+ console.log(`[MarketDataService] Fetching ${symbolsNeedingFetch.length}/${symbols.length} symbols from API for ${category}`);+ const freshQuotes = await this.getEnhancedQuotes(symbolsNeedingFetch);++ // Cache the fresh data+ await Promise.all(+ freshQuotes.map(quote =>+ sqliteService.saveMarketDataCache(quote.symbol, category, quote)+ )+ );++ // Combine cached and fresh data in original order+ const result = symbols.map(symbol => {+ if (cachedData.has(symbol)) {+ return cachedData.get(symbol)!;+ }+ const freshQuote = freshQuotes.find(q => q.symbol === symbol);+ return freshQuote || null;+ }).filter(q => q !== null) as (QuoteData & { seven_day?: number; thirty_day?: number })[];++ return result;+ } catch (error) {+ console.error('[MarketDataService] Cache error, falling back to direct fetch:', error);+ return await this.getEnhancedQuotes(symbols);+ }+ }+/*** Format price change with sign*/diff --git a/fincept-terminal-desktop/src/services/marketplaceApi.tsx b/fincept-terminal-desktop/src/services/marketplaceApi.tsxnew file mode 100644index 000000000..dfa7ecca4--- /dev/null+++ b/fincept-terminal-desktop/src/services/marketplaceApi.tsx@@ -0,0 +1,383 @@+// File: src/services/marketplaceApi.tsx+// Marketplace API service for handling all marketplace-related API calls++// API Configuration+const API_CONFIG = {+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',+ API_VERSION: 'v1',+ CONNECTION_TIMEOUT: 10000,+ REQUEST_TIMEOUT: 30000+};++const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;++// API Response Types+interface ApiResponse<T = any> {+ success: boolean;+ data?: T;+ message?: string;+ error?: string;+ status_code?: number;+}++// Request Types+export interface DatasetMetadata {+ title: string;+ description: string;+ category: string;+ price_tier: string;+ tags?: string[];+}++export interface DatasetPurchaseRequest {+ payment_method?: string;+}++export interface DatasetFilters {+ category?: string;+ search?: string;+ price_tier?: string;+ page?: number;+ limit?: number;+ sort_by?: string;+ sort_order?: string;+}++// Response Types+export interface Dataset {+ id: number;+ title: string;+ description: string;+ category: string;+ price_tier: string;+ price_credits: number;+ uploader_id: number;+ uploader_username: string;+ file_name: string;+ file_size: number;+ downloads_count: number;+ rating: number;+ tags: string[];+ uploaded_at: string;+ updated_at: string;+}++export interface DatasetPurchase {+ id: number;+ dataset_id: number;+ dataset_title: string;+ price_paid: number;+ purchased_at: string;+ access_expires_at?: string;+}++export interface PricingTier {+ tier: string;+ price_credits: number;+ description: string;+ features: string[];+}++export interface DatasetAnalytics {+ total_datasets: number;+ total_downloads: number;+ total_revenue: number;+ datasets: Array<{+ id: number;+ title: string;+ downloads: number;+ revenue: number;+ rating: number;+ }>;+}++export interface RevenueAnalytics {+ total_revenue: number;+ total_transactions: number;+ revenue_by_tier: Record<string, number>;+ top_datasets: Array<{+ id: number;+ title: string;+ revenue: number;+ downloads: number;+ }>;+}++export interface MarketplaceStats {+ total_datasets: number;+ total_purchases: number;+ total_revenue: number;+ total_uploads: number;+ active_users: number;+ popular_categories: Record<string, number>;+}++// Generic API request function+const makeApiRequest = async <T = any>(+ method: string,+ endpoint: string,+ data?: any,+ headers?: Record<string, string>,+ isFormData: boolean = false+): Promise<ApiResponse<T>> => {+ try {+ const defaultHeaders: Record<string, string> = {+ ...(isFormData ? {} : { 'Content-Type': 'application/json' }),+ ...headers+ };++ const url = getApiEndpoint(endpoint);+ console.log('🚀 Making marketplace request:', {+ method,+ url,+ endpoint,+ isFormData,+ headers: { ...defaultHeaders, 'X-API-Key': (defaultHeaders as any)['X-API-Key'] ? '[REDACTED]' : undefined }+ });++ const config: RequestInit = {+ method,+ headers: defaultHeaders,+ mode: 'cors',+ };++ if (data) {+ if (isFormData) {+ config.body = data; // FormData+ } else if (method === 'POST' || method === 'PUT') {+ config.body = JSON.stringify(data);+ }+ }++ const response = await fetch(url, config);++ console.log('📡 Marketplace response received:', {+ status: response.status,+ statusText: response.statusText,+ url: response.url+ });++ const responseText = await response.text();+ console.log('📄 Raw marketplace response text:', responseText.substring(0, 200));++ let responseData;+ try {+ responseData = JSON.parse(responseText);+ console.log('✅ Parsed marketplace JSON:', responseData);+ } catch (parseError) {+ console.error('❌ Marketplace JSON parse failed:', parseError);+ return {+ success: false,+ error: `Invalid JSON response: ${responseText.substring(0, 100)}...`,+ status_code: response.status+ };+ }++ return {+ success: response.ok,+ data: responseData,+ status_code: response.status,+ error: response.ok ? undefined : responseData.message || `HTTP ${response.status}`+ };++ } catch (error) {+ console.error('💥 Marketplace request failed:', error);++ if (error instanceof TypeError && error.message.includes('Failed to fetch')) {+ return {+ success: false,+ error: 'Network error: Unable to connect to server. Please check your internet connection.'+ };+ }++ return {+ success: false,+ error: error instanceof Error ? error.message : 'Network error'+ };+ }+};++// Marketplace API Service Class+export class MarketplaceApiService {+ /**+ * 1. Upload dataset to marketplace+ * POST /marketplace/upload+ */+ static async uploadDataset(+ apiKey: string,+ file: File,+ metadata: DatasetMetadata+ ): Promise<ApiResponse<Dataset>> {+ try {+ const formData = new FormData();+ formData.append('file', file);++ // Create proper metadata object without tags if empty+ const metadataObj = {+ title: metadata.title,+ description: metadata.description,+ category: metadata.category,+ price_tier: metadata.price_tier,+ ...(metadata.tags && metadata.tags.length > 0 ? { tags: metadata.tags } : {})+ };++ const metadataString = JSON.stringify(metadataObj);+ console.log('Upload metadata:', metadataObj);++ // Append as query parameter in the URL+ const endpoint = `/marketplace/upload?metadata=${encodeURIComponent(metadataString)}`;++ return makeApiRequest<Dataset>(+ 'POST',+ endpoint,+ formData,+ { 'X-API-Key': apiKey },+ true // isFormData+ );+ } catch (error) {+ console.error('Upload dataset error:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Upload failed'+ };+ }+ }++ /**+ * 2. Browse datasets in marketplace+ * GET /marketplace/datasets+ */+ static async browseDatasets(+ apiKey: string,+ filters?: DatasetFilters+ ): Promise<ApiResponse<{ datasets: Dataset[]; total: number; page: number; total_pages: number }>> {+ const queryParams = new URLSearchParams();++ if (filters?.category) queryParams.append('category', filters.category);+ if (filters?.search) queryParams.append('search', filters.search);+ if (filters?.price_tier) queryParams.append('price_tier', filters.price_tier);+ if (filters?.page) queryParams.append('page', filters.page.toString());+ if (filters?.limit) queryParams.append('limit', filters.limit.toString());+ if (filters?.sort_by) queryParams.append('sort_by', filters.sort_by);+ if (filters?.sort_order) queryParams.append('sort_order', filters.sort_order);++ const endpoint = `/marketplace/datasets${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;++ return makeApiRequest('GET', endpoint, undefined, { 'X-API-Key': apiKey });+ }++ /**+ * 3. Get dataset details+ * GET /marketplace/datasets/{dataset_id}+ */+ static async getDatasetDetails(+ apiKey: string,+ datasetId: number+ ): Promise<ApiResponse<Dataset>> {+ return makeApiRequest<Dataset>(+ 'GET',+ `/marketplace/datasets/${datasetId}`,+ undefined,+ { 'X-API-Key': apiKey }+ );+ }++ /**+ * 4. Purchase dataset access+ * POST /marketplace/datasets/{dataset_id}/purchase+ */+ static async purchaseDataset(+ apiKey: string,+ datasetId: number,+ purchaseData?: DatasetPurchaseRequest+ ): Promise<ApiResponse<{ purchase_id: number; access_granted: boolean; credits_remaining: number }>> {+ return makeApiRequest(+ 'POST',+ `/marketplace/datasets/${datasetId}/purchase`,+ purchaseData || { payment_method: 'subscription_credit' },+ { 'X-API-Key': apiKey }+ );+ }++ /**+ * 5. Download dataset+ * POST /marketplace/datasets/{dataset_id}/download+ */+ static async downloadDataset(+ apiKey: string,+ datasetId: number+ ): Promise<ApiResponse<{ download_url: string; expires_at: string }>> {+ return makeApiRequest(+ 'POST',+ `/marketplace/datasets/${datasetId}/download`,+ undefined,+ { 'X-API-Key': apiKey }+ );+ }++ /**+ * 6. Get user's purchases+ * GET /marketplace/my-purchases+ */+ static async getUserPurchases(+ apiKey: string,+ page: number = 1,+ limit: number = 20+ ): Promise<ApiResponse<{ purchases: DatasetPurchase[]; total: number; page: number; total_pages: number }>> {+ return makeApiRequest(+ 'GET',+ `/marketplace/my-purchases?page=${page}&limit=${limit}`,+ undefined,+ { 'X-API-Key': apiKey }+ );+ }++ /**+ * 7. Get pricing tiers+ * GET /marketplace/pricing+ */+ static async getPricingTiers(apiKey: string): Promise<ApiResponse<{ tiers: PricingTier[] }>> {+ return makeApiRequest('GET', '/marketplace/pricing', undefined, { 'X-API-Key': apiKey });+ }++ /**+ * 8. Get dataset analytics (for uploader)+ * GET /marketplace/my-datasets/analytics+ */+ static async getDatasetAnalytics(apiKey: string): Promise<ApiResponse<DatasetAnalytics>> {+ return makeApiRequest<DatasetAnalytics>(+ 'GET',+ '/marketplace/my-datasets/analytics',+ undefined,+ { 'X-API-Key': apiKey }+ );+ }++ /**+ * 9. Get admin revenue analytics+ * GET /marketplace/admin/revenue-analytics+ */+ static async getAdminRevenueAnalytics(apiKey: string): Promise<ApiResponse<RevenueAnalytics>> {+ return makeApiRequest<RevenueAnalytics>(+ 'GET',+ '/marketplace/admin/revenue-analytics',+ undefined,+ { 'X-API-Key': apiKey }+ );+ }++ /**+ * 10. Get marketplace statistics+ * GET /marketplace/admin/stats+ */+ static async getMarketplaceStats(apiKey: string): Promise<ApiResponse<MarketplaceStats>> {+ return makeApiRequest<MarketplaceStats>(+ 'GET',+ '/marketplace/admin/stats',+ undefined,+ { 'X-API-Key': apiKey }+ );+ }+}++export default MarketplaceApiService;diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.tsindex 710fa6cae..ec31f0b48 100644--- a/fincept-terminal-desktop/src/services/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/sqliteService.ts@@ -252,6 +252,17 @@ class SQLiteService {)`);+ // Market data cache table+ await this.db.execute(`+ CREATE TABLE IF NOT EXISTS market_data_cache (+ symbol TEXT NOT NULL,+ category TEXT NOT NULL,+ quote_data TEXT NOT NULL,+ cached_at TEXT DEFAULT (datetime('now')),+ PRIMARY KEY (symbol, category)+ )+ `);+// Create indexesawait this.db.execute(`CREATE INDEX IF NOT EXISTS idx_credentials_service ON credentials(service_name)`);await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category)`);@@ -260,6 +271,8 @@ class SQLiteService {await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_tools_server ON mcp_tools(server_id)`);await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_usage_server ON mcp_tool_usage(server_id)`);await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_usage_timestamp ON mcp_tool_usage(timestamp DESC)`);+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_market_cache_category ON market_data_cache(category)`);+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_market_cache_time ON market_data_cache(cached_at)`);}private async seedDefaultSettings(): Promise<void> {@@ -993,6 +1006,97 @@ class SQLiteService {success: log.success === 1}));}++ // ==================== MARKET DATA CACHE ====================++ /**+ * Save market data to cache+ */+ async saveMarketDataCache(symbol: string, category: string, quoteData: any): Promise<void> {+ if (!this.db) throw new Error('Database not initialized');++ await this.db.execute(+ `INSERT OR REPLACE INTO market_data_cache (symbol, category, quote_data, cached_at)+ VALUES ($1, $2, $3, datetime('now'))`,+ [symbol, category, JSON.stringify(quoteData)]+ );+ }++ /**+ * Get cached market data if it's less than maxAgeMinutes old+ */+ async getCachedMarketData(symbol: string, category: string, maxAgeMinutes: number = 10): Promise<any | null> {+ if (!this.db) throw new Error('Database not initialized');++ const result = await this.db.select<Array<{+ quote_data: string;+ cached_at: string;+ }>>(+ `SELECT quote_data, cached_at FROM market_data_cache+ WHERE symbol = $1 AND category = $2+ AND datetime(cached_at) > datetime('now', '-${maxAgeMinutes} minutes')`,+ [symbol, category]+ );++ if (result.length > 0) {+ try {+ return JSON.parse(result[0].quote_data);+ } catch (error) {+ console.error('Error parsing cached market data:', error);+ return null;+ }+ }++ return null;+ }++ /**+ * Get all cached market data for a category that's less than maxAgeMinutes old+ */+ async getCachedCategoryData(category: string, symbols: string[], maxAgeMinutes: number = 10): Promise<Map<string, any>> {+ if (!this.db) throw new Error('Database not initialized');++ const placeholders = symbols.map((_, i) => `$${i + 2}`).join(',');+ const result = await this.db.select<Array<{+ symbol: string;+ quote_data: string;+ cached_at: string;+ }>>(+ `SELECT symbol, quote_data, cached_at FROM market_data_cache+ WHERE category = $1 AND symbol IN (${placeholders})+ AND datetime(cached_at) > datetime('now', '-${maxAgeMinutes} minutes')`,+ [category, ...symbols]+ );++ const dataMap = new Map<string, any>();+ result.forEach(row => {+ try {+ dataMap.set(row.symbol, JSON.parse(row.quote_data));+ } catch (error) {+ console.error(`Error parsing cached data for ${row.symbol}:`, error);+ }+ });++ return dataMap;+ }++ /**+ * Clear all market data cache+ */+ async clearMarketDataCache(): Promise<void> {+ if (!this.db) throw new Error('Database not initialized');+ await this.db.execute('DELETE FROM market_data_cache');+ }++ /**+ * Clear expired cache entries (older than maxAgeMinutes)+ */+ async clearExpiredMarketCache(maxAgeMinutes: number = 10): Promise<void> {+ if (!this.db) throw new Error('Database not initialized');+ await this.db.execute(+ `DELETE FROM market_data_cache WHERE datetime(cached_at) <= datetime('now', '-${maxAgeMinutes} minutes')`+ );+ }}// Singleton instancediff --git a/fincept-terminal-desktop/src/services/supportApi.tsx b/fincept-terminal-desktop/src/services/supportApi.tsxnew file mode 100644index 000000000..a3cecdaa2--- /dev/null+++ b/fincept-terminal-desktop/src/services/supportApi.tsx@@ -0,0 +1,143 @@+// File: src/services/supportApi.tsx+// Support Ticket API Service++// API Configuration+const API_CONFIG = {+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',+};++const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;++interface ApiResponse<T = any> {+ success: boolean;+ data?: T;+ error?: string;+ status_code: number;+}++// Generic API request handler+async function makeApiRequest<T = any>(+ endpoint: string,+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',+ apiKey?: string,+ body?: any+): Promise<ApiResponse<T>> {+ try {+ const options: RequestInit = {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...(apiKey && { 'X-API-Key': apiKey }),+ },+ };++ if (body && (method === 'POST' || method === 'PUT')) {+ options.body = JSON.stringify(body);+ }++ console.log(`[SupportAPI] ${method} ${endpoint}`, body || '');++ const response = await fetch(getApiEndpoint(endpoint), options);+ const data = await response.json();++ console.log(`[SupportAPI] Response:`, data);++ return {+ success: response.ok,+ data: data,+ error: response.ok ? undefined : data.detail || data.error || 'Request failed',+ status_code: response.status,+ };+ } catch (error) {+ console.error(`[SupportAPI] Error in ${method} ${endpoint}:`, error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Network error',+ status_code: 500,+ };+ }+}++export class SupportApiService {+ // ========================+ // SUPPORT TICKETS+ // ========================++ static async getUserTickets(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/support/tickets', 'GET', apiKey);+ }++ static async createTicket(apiKey: string, ticketData: {+ subject: string;+ description: string;+ category: string;+ priority?: string;+ }): Promise<ApiResponse> {+ return makeApiRequest('/support/tickets', 'POST', apiKey, ticketData);+ }++ static async getTicketDetails(apiKey: string, ticketId: number): Promise<ApiResponse> {+ return makeApiRequest(`/support/tickets/${ticketId}`, 'GET', apiKey);+ }++ static async updateTicket(apiKey: string, ticketId: number, status: string): Promise<ApiResponse> {+ return makeApiRequest(`/support/tickets/${ticketId}`, 'PUT', apiKey, { status });+ }++ static async addTicketMessage(apiKey: string, ticketId: number, message: string): Promise<ApiResponse> {+ return makeApiRequest(`/support/tickets/${ticketId}/messages`, 'POST', apiKey, { message });+ }++ static async getSupportStats(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/support/stats', 'GET', apiKey);+ }++ // ========================+ // CONTACT & FEEDBACK (Public)+ // ========================++ static async submitContactForm(formData: {+ name: string;+ email: string;+ subject: string;+ message: string;+ }): Promise<ApiResponse> {+ return makeApiRequest('/support/contact', 'POST', undefined, formData);+ }++ static async submitFeedback(feedbackData: {+ name?: string;+ email?: string;+ rating: number;+ feedback_text: string;+ category?: string;+ }): Promise<ApiResponse> {+ return makeApiRequest('/support/feedback', 'POST', undefined, feedbackData);+ }++ static async getSupportCategories(): Promise<ApiResponse> {+ return makeApiRequest('/support/categories', 'GET');+ }++ // ========================+ // NEWSLETTER (Public)+ // ========================++ static async subscribeToNewsletter(email: string, name?: string): Promise<ApiResponse> {+ return makeApiRequest('/support/newsletter/subscribe', 'POST', undefined, {+ email,+ name,+ source: 'terminal'+ });+ }++ static async unsubscribeFromNewsletter(email: string, token?: string): Promise<ApiResponse> {+ const params = new URLSearchParams({ email });+ if (token) params.append('token', token);+ return makeApiRequest(`/support/newsletter/unsubscribe?${params.toString()}`, 'POST');+ }++ static async checkNewsletterStatus(email: string): Promise<ApiResponse> {+ return makeApiRequest(`/support/newsletter/status?email=${encodeURIComponent(email)}`, 'GET');+ }+}diff --git a/fincept-terminal-desktop/src/services/userApi.tsx b/fincept-terminal-desktop/src/services/userApi.tsxnew file mode 100644index 000000000..13718dd9e--- /dev/null+++ b/fincept-terminal-desktop/src/services/userApi.tsx@@ -0,0 +1,229 @@+// File: src/services/userApi.tsx+// User and Profile API Service++// API Configuration+const API_CONFIG = {+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',+};++const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;++interface ApiResponse<T = any> {+ success: boolean;+ data?: T;+ error?: string;+ status_code: number;+}++// Generic API request handler+async function makeApiRequest<T = any>(+ endpoint: string,+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',+ apiKey: string,+ body?: any+): Promise<ApiResponse<T>> {+ try {+ const options: RequestInit = {+ method,+ headers: {+ 'Content-Type': 'application/json',+ 'X-API-Key': apiKey,+ },+ };++ if (body && (method === 'POST' || method === 'PUT')) {+ options.body = JSON.stringify(body);+ }++ console.log(`[UserAPI] ${method} ${endpoint}`, body || '');++ const response = await fetch(getApiEndpoint(endpoint), options);+ const data = await response.json();++ console.log(`[UserAPI] Response:`, data);++ return {+ success: response.ok,+ data: data,+ error: response.ok ? undefined : data.detail || data.error || 'Request failed',+ status_code: response.status,+ };+ } catch (error) {+ console.error(`[UserAPI] Error in ${method} ${endpoint}:`, error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Network error',+ status_code: 500,+ };+ }+}++export class UserApiService {+ // ========================+ // PROFILE MANAGEMENT+ // ========================++ static async getUserProfile(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/user/profile', 'GET', apiKey);+ }++ static async updateUserProfile(apiKey: string, profileData: any): Promise<ApiResponse> {+ return makeApiRequest('/user/profile', 'PUT', apiKey, profileData);+ }++ static async regenerateApiKey(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/user/regenerate-api-key', 'POST', apiKey);+ }++ static async getUserUsage(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/user/usage', 'GET', apiKey);+ }++ static async deleteUserAccount(apiKey: string, confirmationData: any): Promise<ApiResponse> {+ return makeApiRequest('/user/account', 'DELETE', apiKey, confirmationData);+ }++ // ========================+ // SUBSCRIPTIONS & DATABASES+ // ========================++ static async subscribeToDatabase(apiKey: string, databaseName: string): Promise<ApiResponse> {+ return makeApiRequest('/user/subscribe', 'POST', apiKey, { database_name: databaseName });+ }++ static async getUserSubscriptions(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/user/subscriptions', 'GET', apiKey);+ }++ static async getUserTransactions(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/user/transactions', 'GET', apiKey);+ }++ // ========================+ // PAYMENT MANAGEMENT+ // ========================++ static async getUserSubscription(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/payment/subscription', 'GET', apiKey);+ }++ static async getUsageDetails(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/payment/usage', 'GET', apiKey);+ }++ static async cancelSubscription(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/payment/cancel', 'POST', apiKey);+ }++ static async reactivateSubscription(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/payment/reactivate', 'POST', apiKey);+ }++ static async getPaymentHistory(apiKey: string, page: number = 1, limit: number = 10): Promise<ApiResponse> {+ return makeApiRequest(`/payment/payments?page=${page}&limit=${limit}`, 'GET', apiKey);+ }++ static async getPaymentDetails(apiKey: string, paymentUuid: string): Promise<ApiResponse> {+ return makeApiRequest(`/payment/payments/${paymentUuid}`, 'GET', apiKey);+ }++ // ========================+ // GUEST USER ENDPOINTS+ // ========================++ static async getGuestStatus(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/guest/status', 'GET', apiKey);+ }++ static async extendGuestSession(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/guest/extend', 'POST', apiKey);+ }++ static async getGuestUsage(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/guest/usage', 'GET', apiKey);+ }++ static async deleteGuestSession(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/guest/session', 'DELETE', apiKey);+ }++ // ========================+ // SUPPORT & TICKETS+ // ========================++ static async getUserTickets(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/support/tickets', 'GET', apiKey);+ }++ static async createTicket(apiKey: string, ticketData: {+ subject: string;+ description: string;+ category: string;+ priority?: string;+ }): Promise<ApiResponse> {+ return makeApiRequest('/support/tickets', 'POST', apiKey, ticketData);+ }++ static async getTicketDetails(apiKey: string, ticketId: number): Promise<ApiResponse> {+ return makeApiRequest(`/support/tickets/${ticketId}`, 'GET', apiKey);+ }++ static async updateTicket(apiKey: string, ticketId: number, status: string): Promise<ApiResponse> {+ return makeApiRequest(`/support/tickets/${ticketId}`, 'PUT', apiKey, { status });+ }++ static async addTicketMessage(apiKey: string, ticketId: number, message: string): Promise<ApiResponse> {+ return makeApiRequest(`/support/tickets/${ticketId}/messages`, 'POST', apiKey, { message });+ }++ static async getSupportStats(apiKey: string): Promise<ApiResponse> {+ return makeApiRequest('/support/stats', 'GET', apiKey);+ }++ // ========================+ // NEWSLETTER+ // ========================++ static async subscribeToNewsletter(email: string, name?: string): Promise<ApiResponse> {+ // No API key required - public endpoint+ try {+ const response = await fetch(getApiEndpoint('/support/newsletter/subscribe'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ email, name, source: 'terminal' }),+ });+ const data = await response.json();+ return {+ success: response.ok,+ data,+ error: response.ok ? undefined : data.detail || 'Subscription failed',+ status_code: response.status,+ };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Network error',+ status_code: 500,+ };+ }+ }++ static async checkNewsletterStatus(email: string): Promise<ApiResponse> {+ try {+ const response = await fetch(getApiEndpoint(`/support/newsletter/status?email=${encodeURIComponent(email)}`));+ const data = await response.json();+ return {+ success: response.ok,+ data,+ error: response.ok ? undefined : data.detail,+ status_code: response.status,+ };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Network error',+ status_code: 500,+ };+ }+ }+}diff --git a/images/Geopolitics.png b/images/Geopolitics.pngindex e46187573..36e52a281 100644Binary files a/images/Geopolitics.png and b/images/Geopolitics.png differ