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
payment update
tilakpatel22aa247f0beecc
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex e4a1e24c0..dc47b50bb 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -1,7 +1,7 @@{"name": "fincept-terminal-desktop","private": true,- "version": "0.1.0",+ "version": "3.0.0","type": "module","scripts": {"dev": "vite",diff --git a/fincept-terminal-desktop/python_backend/main.py b/fincept-terminal-desktop/python_backend/main.pydeleted file mode 100644index fc5112288..000000000--- a/fincept-terminal-desktop/python_backend/main.py+++ /dev/null@@ -1,62 +0,0 @@-import sys-import json-import yfinance as yf---def get_stock_data(symbol):- try:- ticker = yf.Ticker(symbol)- # Get basic info- info = ticker.info- # Get recent price data (last 30 days)- hist = ticker.history(period="1mo")-- return {- "success": True,- "symbol": symbol,- "info": {- "name": info.get("longName", "N/A"),- "price": info.get("currentPrice", "N/A"),- "currency": info.get("currency", "USD")- },- "recent_data": hist.tail(5).to_dict("records") if not hist.empty else []- }- except Exception as e:- return {"success": False, "error": str(e)}---def get_multiple_stocks(symbols_str):- try:- symbols = symbols_str.split(",")- results = []- for symbol in symbols[:5]: # Limit to 5 stocks- data = yf.download(symbol.strip(), period="5d", interval="1d")- if not data.empty:- latest = data.iloc[-1]- results.append({- "symbol": symbol.strip(),- "close": float(latest['Close']),- "volume": int(latest['Volume'])- })-- return {"success": True, "data": results}- except Exception as e:- return {"success": False, "error": str(e)}---if __name__ == "__main__":- if len(sys.argv) < 3:- print(json.dumps({"error": "Usage: python main.py <command> <param>"}))- sys.exit(1)-- command = sys.argv[1]- param = sys.argv[2]-- if command == "stock":- result = get_stock_data(param)- elif command == "multiple":- result = get_multiple_stocks(param)- else:- result = {"error": "Unknown command"}-- print(json.dumps(result))\ No newline at end of filediff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lockindex 29c72872f..3e2629325 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.lock+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock@@ -1071,7 +1071,7 @@ dependencies = [[[package]]name = "fincept-terminal-desktop"-version = "1.0.0"+version = "3.0.0"dependencies = ["anyhow","chrono",diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex 671aa98e2..8dde4e01a 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "fincept-terminal-desktop"-version = "1.0.0"+version = "3.0.0"description = "Professional-grade financial analysis platform with AI-powered insights and real-time market data"authors = ["Fincept Corporation <[email protected]>"]edition = "2021"diff --git a/fincept-terminal-desktop/src-tauri/nsis/installer.nsi b/fincept-terminal-desktop/src-tauri/nsis/installer.nsinew file mode 100644index 000000000..4b0b59f35--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/nsis/installer.nsi@@ -0,0 +1,44 @@+; Custom NSIS installer script for Fincept Terminal+; This ensures complete cleanup on uninstall including AppData and user settings++!include MUI2.nsh++; Custom uninstaller section to remove all leftover files+Section "Uninstall"+ ; Remove application files (default Tauri behavior)+ ; This section is merged with Tauri's default uninstall++ ; Remove user data directories+ ; AppData\Local\com.fincept.terminal (Tauri app data)+ RMDir /r "$LOCALAPPDATA\com.fincept.terminal"++ ; AppData\Roaming\com.fincept.terminal (user settings, logs, etc.)+ RMDir /r "$APPDATA\com.fincept.terminal"++ ; Remove any leftover configuration files+ Delete "$APPDATA\fincept-terminal\*.*"+ RMDir "$APPDATA\fincept-terminal"++ ; Remove temp files if any+ Delete "$TEMP\fincept-terminal-*.*"++ ; Clean up any leftover registry entries+ DeleteRegKey HKCU "Software\Fincept Corporation\Fincept Terminal"+ DeleteRegKey HKCU "Software\com.fincept.terminal"++ ; Remove start menu shortcuts+ Delete "$SMPROGRAMS\Fincept Terminal\*.*"+ RMDir "$SMPROGRAMS\Fincept Terminal"++ ; Remove desktop shortcut if exists+ Delete "$DESKTOP\Fincept Terminal.lnk"++ ; Remove from installed programs+ DeleteRegKey HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\{com.fincept.terminal}"++SectionEnd++; Custom installer section (optional)+Section "Install"+ ; Default Tauri install behavior will handle the main installation+SectionEnddiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.pynew file mode 100644index 000000000..ba850c574--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.py@@ -0,0 +1,522 @@+"""+EconDB Data Fetcher+Fetches global economic indicators from EconDB (econdb.com)+Returns JSON output for Rust integration+Based on OpenBB EconDB provider+"""++import sys+import json+import asyncio+from datetime import datetime, timedelta+from typing import Optional, List, Dict, Any+import aiohttp++# EconDB API Configuration+ECONDB_BASE_URL = "https://www.econdb.com"+ECONDB_API_BASE = f"{ECONDB_BASE_URL}/api/series"+ECONDB_CONTEXT_BASE = f"{ECONDB_BASE_URL}/series/context"+ECONDB_TRENDS_BASE = f"{ECONDB_BASE_URL}/trends"++# Country mapping (ISO 2-letter codes)+COUNTRIES = {+ "us": "US", "usa": "US", "united_states": "US",+ "uk": "UK", "united_kingdom": "UK", "gb": "UK",+ "cn": "CN", "china": "CN",+ "jp": "JP", "japan": "JP",+ "de": "DE", "germany": "DE",+ "fr": "FR", "france": "FR",+ "in": "IN", "india": "IN",+ "ca": "CA", "canada": "CA",+ "au": "AU", "australia": "AU",+ "br": "BR", "brazil": "BR",+ "mx": "MX", "mexico": "MX",+ "kr": "KR", "south_korea": "KR",+ "it": "IT", "italy": "IT",+ "es": "ES", "spain": "ES",+ "nl": "NL", "netherlands": "NL",+ "ch": "CH", "switzerland": "CH",+ "se": "SE", "sweden": "SE",+ "pl": "PL", "poland": "PL",+ "be": "BE", "belgium": "BE",+ "at": "AT", "austria": "AT",+ "no": "NO", "norway": "NO",+ "dk": "DK", "denmark": "DK",+ "fi": "FI", "finland": "FI",+ "pt": "PT", "portugal": "PT",+ "gr": "GR", "greece": "GR",+ "cz": "CZ", "czech_republic": "CZ", "czechia": "CZ",+ "ie": "IE", "ireland": "IE",+ "nz": "NZ", "new_zealand": "NZ",+ "sg": "SG", "singapore": "SG",+ "hk": "HK", "hong_kong": "HK",+ "ru": "RU", "russia": "RU",+ "tr": "TR", "turkey": "TR",+ "za": "ZA", "south_africa": "ZA",+ "ar": "AR", "argentina": "AR",+ "cl": "CL", "chile": "CL",+ "co": "CO", "colombia": "CO",+ "pe": "PE", "peru": "PE",+ "id": "ID", "indonesia": "ID",+ "th": "TH", "thailand": "TH",+ "my": "MY", "malaysia": "MY",+ "ph": "PH", "philippines": "PH",+ "vn": "VN", "vietnam": "VN",+ "eg": "EG", "egypt": "EG",+ "ng": "NG", "nigeria": "NG",+ "pk": "PK", "pakistan": "PK",+ "bd": "BD", "bangladesh": "BD",+ "ua": "UA", "ukraine": "UA",+ "ro": "RO", "romania": "RO",+ "hu": "HU", "hungary": "HU",+}++# Common economic indicators+INDICATORS = {+ "gdp": "GDP", # GDP (nominal)+ "rgdp": "RGDP", # GDP (real)+ "cpi": "CPI", # Consumer Price Index+ "ppi": "PPI", # Producer Price Index+ "core": "CORE", # Core CPI+ "urate": "URATE", # Unemployment Rate+ "emp": "EMP", # Employment+ "ip": "IP", # Industrial Production+ "reta": "RETA", # Retail Sales+ "conf": "CONF", # Consumer Confidence+ "polir": "POLIR", # Policy Interest Rate+ "y10yd": "Y10YD", # 10-Year Government Bond Yield+ "m3yd": "M3YD", # 3-Month Treasury Yield+ "gdebt": "GDEBT", # Government Debt+ "ca": "CA", # Current Account+ "tb": "TB", # Trade Balance+ "pop": "POP", # Population+ "prc": "PRC", # Private Consumption+ "gfcf": "GFCF", # Gross Fixed Capital Formation+ "exp": "EXP", # Exports+ "imp": "IMP", # Imports+}++# Transformations+TRANSFORMATIONS = {+ "toya": "Change from one year ago (YoY)",+ "tpop": "Change from previous period",+ "tusd": "Values as US dollars",+ "tpgp": "Values as a percent of GDP",+ "level": "Level (no transformation)",+}++async def create_temp_token() -> str:+ """Create a temporary API token from EconDB"""+ url = f"{ECONDB_BASE_URL}/user/create_token/?reset=0"+ try:+ async with aiohttp.ClientSession() as session:+ async with session.get(url, timeout=10) as response:+ if response.status == 200:+ data = await response.json()+ return data.get("api_key", "")+ return ""+ except Exception as e:+ return ""++async def make_econdb_request(url: str, token: Optional[str] = None) -> Dict:+ """Make async request to EconDB API"""+ try:+ async with aiohttp.ClientSession() as session:+ # Add token to URL if provided+ request_url = f"{url}&token={token}" if token and "?" in url else url+ async with session.get(request_url, timeout=20) as response:+ if response.status == 200:+ return await response.json()+ else:+ return {"error": f"HTTP {response.status}: {response.reason}"}+ except asyncio.TimeoutError:+ return {"error": "Request timeout"}+ except Exception as e:+ return {"error": str(e)}++def normalize_country(country: str) -> Optional[str]:+ """Normalize country name to 2-letter ISO code"""+ country_lower = country.lower().strip()+ return COUNTRIES.get(country_lower, country.upper() if len(country) == 2 else None)++def normalize_indicator(indicator: str) -> Optional[str]:+ """Normalize indicator name to EconDB symbol"""+ indicator_lower = indicator.lower().strip()+ return INDICATORS.get(indicator_lower, indicator.upper())++async def get_economic_indicators(+ symbol: str,+ country: str,+ start_date: Optional[str] = None,+ end_date: Optional[str] = None,+ transform: Optional[str] = None+) -> Dict:+ """+ Fetch economic indicators from EconDB++ Args:+ symbol: Indicator symbol (e.g., 'GDP', 'CPI', 'URATE')+ country: Country code (2-letter ISO) or name+ start_date: Start date YYYY-MM-DD+ end_date: End date YYYY-MM-DD+ transform: Transformation (toya, tpop, tusd, tpgp)+ """+ try:+ # Normalize inputs+ country_code = normalize_country(country)+ if not country_code:+ return {"error": f"Invalid country code: {country}"}++ indicator = normalize_indicator(symbol)+ if not indicator:+ return {"error": f"Invalid indicator: {symbol}"}++ # Create temporary token (optional)+ token = await create_temp_token()++ # Build ticker symbol (e.g., GDPUS, CPICN)+ ticker = f"{indicator}{country_code}"+ if transform and transform.lower() in TRANSFORMATIONS:+ ticker += f"~{transform.upper()}"++ # Build URL+ url = f"{ECONDB_API_BASE}/?ticker=%5B{ticker}%5D&format=json"+ if start_date:+ url += f"&from={start_date}"+ if end_date:+ url += f"&to={end_date}"++ # Make request+ response = await make_econdb_request(url, token)++ if "error" in response:+ return response++ # Parse results+ if not response.get("results"):+ return {"error": "No data returned"}++ result = response["results"][0]++ # Extract metadata+ metadata = {+ "ticker": result.get("ticker", ""),+ "description": result.get("description", ""),+ "country": result.get("geography", ""),+ "frequency": result.get("frequency", ""),+ "dataset": result.get("dataset", ""),+ "last_update": result.get("last_update", ""),+ }++ # Extract time series data+ data_dict = result.get("data", {})+ dates = data_dict.get("dates", [])+ values = data_dict.get("values", [])++ observations = []+ for date, value in zip(dates, values):+ if value is not None and value != "nan":+ observations.append({+ "date": date,+ "value": float(value) if value != "" else None+ })++ return {+ "indicator": indicator,+ "country": country_code,+ "transform": transform.upper() if transform else "LEVEL",+ "metadata": metadata,+ "observations": observations,+ "observation_count": len(observations)+ }++ except Exception as e:+ return {"error": str(e)}++async def get_country_profile(+ country: str,+ latest: bool = True+) -> Dict:+ """+ Get comprehensive country economic profile++ Args:+ country: Country code (2-letter ISO) or name+ latest: If True, return only latest values+ """+ try:+ country_code = normalize_country(country)+ if not country_code:+ return {"error": f"Invalid country code: {country}"}++ token = await create_temp_token()++ # Key indicators for country profile+ indicators = [+ ("GDP", "tusd"), # GDP in USD+ ("RGDP", "toya"), # Real GDP YoY growth+ ("RGDP", "tpop"), # Real GDP QoQ growth+ ("CPI", "toya"), # Inflation YoY+ ("CORE", "toya"), # Core inflation YoY+ ("URATE", None), # Unemployment rate+ ("POLIR", None), # Policy rate+ ("Y10YD", None), # 10Y yield+ ("RETA", "toya"), # Retail sales YoY+ ("IP", "toya"), # Industrial production YoY+ ("POP", None), # Population+ ]++ # Build tickers+ tickers = []+ for ind, trans in indicators:+ ticker = f"{ind}{country_code}"+ if trans:+ ticker += f"~{trans.upper()}"+ tickers.append(ticker)++ # Make request for all indicators+ tickers_string = ",".join(tickers)+ url = f"{ECONDB_API_BASE}/?ticker=%5B{tickers_string}%5D&format=json"++ response = await make_econdb_request(url, token)++ if "error" in response:+ return response++ if not response.get("results"):+ return {"error": "No data returned"}++ profile = {+ "country": country_code,+ "indicators": {}+ }++ for result in response["results"]:+ ticker = result.get("ticker", "")+ indicator_name = result.get("description", "")++ data_dict = result.get("data", {})+ dates = data_dict.get("dates", [])+ values = data_dict.get("values", [])++ if latest and dates and values:+ # Get most recent non-null value+ for date, value in zip(reversed(dates), reversed(values)):+ if value is not None and value != "nan" and value != "":+ profile["indicators"][indicator_name] = {+ "date": date,+ "value": float(value)+ }+ break+ else:+ observations = []+ for date, value in zip(dates, values):+ if value is not None and value != "nan" and value != "":+ observations.append({+ "date": date,+ "value": float(value)+ })+ profile["indicators"][indicator_name] = observations++ return profile++ except Exception as e:+ return {"error": str(e)}++async def get_main_indicators(+ country: str,+ start_date: Optional[str] = None,+ end_date: Optional[str] = None,+ frequency: str = "quarter",+ transform: Optional[str] = "toya"+) -> Dict:+ """+ Get main economic indicators for a country from EconDB trends endpoint++ Args:+ country: Country code (2-letter ISO) or name+ start_date: Start date YYYY-MM-DD+ end_date: End date YYYY-MM-DD+ frequency: annual, quarter, month+ transform: toya, tpop, tusd, or None+ """+ try:+ country_code = normalize_country(country)+ if not country_code:+ return {"error": f"Invalid country code: {country}"}++ # Default dates+ if not start_date:+ start_date = (datetime.now() - timedelta(weeks=52 * 3)).strftime("%Y-%m-%d")+ if not end_date:+ end_date = datetime.now().strftime("%Y-%m-%d")++ # Map frequency+ freq_map = {"annual": "Y", "quarter": "Q", "month": "M"}+ freq = freq_map.get(frequency, "Q")++ # Map transform+ transform_map = {"tpop": 1, "toya": 2, "level": 3, "tusd": 9, None: 3}+ trans_num = transform_map.get(transform, 2)++ # Build URL+ url = (+ f"{ECONDB_TRENDS_BASE}/country_forecast/"+ f"?country={country_code}&freq={freq}&transform={trans_num}"+ f"&dateStart={start_date}&dateEnd={end_date}"+ )++ response = await make_econdb_request(url)++ if "error" in response:+ return response++ # Parse response+ row_names = response.get("row_names", [])+ units_col = response.get("units_col", [])+ data = response.get("data", [])++ # Build indicator mapping+ indicators_info = {}+ for idx, row_info in enumerate(row_names):+ code = row_info.get("code", "")+ indicators_info[code] = {+ "name": row_info.get("verbose", "").title(),+ "is_parent": row_info.get("is_parent", False),+ "units": units_col[idx] if idx < len(units_col) else ""+ }++ # Parse time series data+ time_series = {}+ for entry in data:+ indicator = entry.get("indicator", "")+ obs_time = entry.get("obs_time", "")+ obs_value = entry.get("obs_value", None)++ if indicator not in time_series:+ time_series[indicator] = []++ if obs_value is not None and obs_value != "":+ time_series[indicator].append({+ "date": obs_time,+ "value": float(obs_value)+ })++ return {+ "country": country_code,+ "frequency": frequency,+ "transform": transform,+ "start_date": start_date,+ "end_date": end_date,+ "indicators_info": indicators_info,+ "time_series": time_series,+ "footnote": response.get("footnote", [])+ }++ except Exception as e:+ return {"error": str(e)}++async def list_indicators() -> Dict:+ """List all available indicators with descriptions"""+ return {+ "indicators": [+ {"code": code, "name": name, "description": f"{name} indicator"}+ for code, name in INDICATORS.items()+ ],+ "transformations": [+ {"code": code, "description": desc}+ for code, desc in TRANSFORMATIONS.items()+ ]+ }++async def list_countries() -> Dict:+ """List all supported countries"""+ # Get unique country codes+ unique_countries = {}+ for name, code in COUNTRIES.items():+ if code not in unique_countries:+ unique_countries[code] = name.replace("_", " ").title()++ return {+ "countries": [+ {"code": code, "name": name}+ for code, name in sorted(unique_countries.items())+ ],+ "count": len(unique_countries)+ }++def main():+ """Main CLI entry point"""+ if len(sys.argv) < 2:+ print(json.dumps({+ "error": "Usage: python econdb_data.py <command> <args>",+ "commands": [+ "indicator <symbol> <country> [start_date] [end_date] [transform]",+ "profile <country> [latest]",+ "main <country> [start_date] [end_date] [frequency] [transform]",+ "list-indicators",+ "list-countries"+ ]+ }))+ sys.exit(1)++ command = sys.argv[1]++ try:+ if command == "indicator":+ if len(sys.argv) < 4:+ print(json.dumps({"error": "Usage: python econdb_data.py indicator <symbol> <country> [start_date] [end_date] [transform]"}))+ sys.exit(1)++ symbol = sys.argv[2]+ country = sys.argv[3]+ start_date = sys.argv[4] if len(sys.argv) > 4 else None+ end_date = sys.argv[5] if len(sys.argv) > 5 else None+ transform = sys.argv[6] if len(sys.argv) > 6 else None++ result = asyncio.run(get_economic_indicators(symbol, country, start_date, end_date, transform))+ print(json.dumps(result, indent=2))++ elif command == "profile":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python econdb_data.py profile <country> [latest]"}))+ sys.exit(1)++ country = sys.argv[2]+ latest = sys.argv[3].lower() == "true" if len(sys.argv) > 3 else True++ result = asyncio.run(get_country_profile(country, latest))+ print(json.dumps(result, indent=2))++ elif command == "main":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python econdb_data.py main <country> [start_date] [end_date] [frequency] [transform]"}))+ sys.exit(1)++ country = sys.argv[2]+ start_date = sys.argv[3] if len(sys.argv) > 3 else None+ end_date = sys.argv[4] if len(sys.argv) > 4 else None+ frequency = sys.argv[5] if len(sys.argv) > 5 else "quarter"+ transform = sys.argv[6] if len(sys.argv) > 6 else "toya"++ result = asyncio.run(get_main_indicators(country, start_date, end_date, frequency, transform))+ print(json.dumps(result, indent=2))++ elif command == "list-indicators":+ result = asyncio.run(list_indicators())+ print(json.dumps(result, indent=2))++ elif command == "list-countries":+ result = asyncio.run(list_countries())+ print(json.dumps(result, indent=2))++ else:+ print(json.dumps({"error": f"Unknown command: {command}"}))+ sys.exit(1)++ except Exception as e:+ print(json.dumps({"error": str(e)}))+ sys.exit(1)++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.pynew file mode 100644index 000000000..19a82e4d9--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py@@ -0,0 +1,308 @@+"""+FRED Data Fetcher+Fetches economic data from Federal Reserve Economic Data (FRED)+Returns JSON output for Rust integration+Based on OpenBB FRED provider+"""++import sys+import json+import os+import requests+from datetime import datetime+from typing import Optional, List, Dict, Any++FRED_API_BASE = "https://api.stlouisfed.org/fred"+FRED_API_KEY = os.environ.get('FRED_API_KEY', '') # API key from environment variable++def make_fred_request(endpoint: str, params: Dict[str, Any]) -> Dict:+ """Make request to FRED API"""+ if not FRED_API_KEY:+ return {"error": "FRED API key not configured"}++ params['api_key'] = FRED_API_KEY+ params['file_type'] = 'json'++ url = f"{FRED_API_BASE}/{endpoint}"+ try:+ response = requests.get(url, params=params, timeout=10)+ response.raise_for_status()+ return response.json()+ except requests.exceptions.RequestException as e:+ return {"error": str(e)}++def get_series(series_id: str, start_date: Optional[str] = None, end_date: Optional[str] = None,+ frequency: Optional[str] = None, transform: Optional[str] = None) -> Dict:+ """+ Fetch FRED series data++ Args:+ series_id: FRED series ID (e.g., 'GDP', 'UNRATE', 'CPIAUCSL')+ start_date: Start date YYYY-MM-DD+ end_date: End date YYYY-MM-DD+ frequency: a=Annual, q=Quarterly, m=Monthly, w=Weekly, d=Daily+ transform: chg=Change, pch=Percent Change, log=Natural Log+ """+ try:+ # Get series observations+ params = {'series_id': series_id}+ if start_date:+ params['observation_start'] = start_date+ if end_date:+ params['observation_end'] = end_date+ if frequency:+ params['frequency'] = frequency+ if transform:+ params['units'] = transform++ obs_data = make_fred_request('series/observations', params)++ if 'error' in obs_data:+ return obs_data++ # Get series metadata+ metadata = make_fred_request('series', {'series_id': series_id})++ if 'error' in metadata:+ return obs_data # Return observations even if metadata fails++ series_info = metadata.get('seriess', [{}])[0] if 'seriess' in metadata else {}++ # Format observations+ observations = []+ for obs in obs_data.get('observations', []):+ if obs['value'] != '.': # Skip missing values+ observations.append({+ 'date': obs['date'],+ 'value': float(obs['value'])+ })++ return {+ 'series_id': series_id,+ 'title': series_info.get('title', 'N/A'),+ 'units': series_info.get('units', 'N/A'),+ 'frequency': series_info.get('frequency', 'N/A'),+ 'seasonal_adjustment': series_info.get('seasonal_adjustment', 'N/A'),+ 'last_updated': series_info.get('last_updated', 'N/A'),+ 'observations': observations,+ 'observation_count': len(observations)+ }+ except Exception as e:+ return {"error": str(e), "series_id": series_id}++def search_series(search_text: str, limit: int = 10) -> Dict:+ """Search for FRED series"""+ try:+ params = {+ 'search_text': search_text,+ 'limit': limit,+ 'order_by': 'popularity',+ 'sort_order': 'desc'+ }++ result = make_fred_request('series/search', params)++ if 'error' in result:+ return result++ series_list = []+ for series in result.get('seriess', []):+ series_list.append({+ 'id': series.get('id'),+ 'title': series.get('title'),+ 'frequency': series.get('frequency'),+ 'units': series.get('units'),+ 'seasonal_adjustment': series.get('seasonal_adjustment'),+ 'last_updated': series.get('last_updated'),+ 'popularity': series.get('popularity')+ })++ return {+ 'search_text': search_text,+ 'count': len(series_list),+ 'series': series_list+ }+ except Exception as e:+ return {"error": str(e), "search_text": search_text}++def get_categories(category_id: int = 0) -> Dict:+ """Get FRED categories"""+ try:+ params = {'category_id': category_id}+ result = make_fred_request('category/children', params)++ if 'error' in result:+ return result++ categories = []+ for cat in result.get('categories', []):+ categories.append({+ 'id': cat.get('id'),+ 'name': cat.get('name'),+ 'parent_id': cat.get('parent_id')+ })++ return {+ 'category_id': category_id,+ 'categories': categories+ }+ except Exception as e:+ return {"error": str(e), "category_id": category_id}++def get_category_series(category_id: int, limit: int = 50) -> Dict:+ """Get series in a category"""+ try:+ params = {+ 'category_id': category_id,+ 'limit': limit,+ 'order_by': 'popularity',+ 'sort_order': 'desc'+ }+ result = make_fred_request('category/series', params)++ if 'error' in result:+ return result++ series_list = []+ for series in result.get('seriess', []):+ series_list.append({+ 'id': series.get('id'),+ 'title': series.get('title'),+ 'frequency': series.get('frequency'),+ 'units': series.get('units'),+ 'seasonal_adjustment': series.get('seasonal_adjustment'),+ 'last_updated': series.get('last_updated'),+ 'popularity': series.get('popularity', 0)+ })++ return {+ 'category_id': category_id,+ 'count': len(series_list),+ 'series': series_list+ }+ except Exception as e:+ return {"error": str(e), "category_id": category_id}++def get_release_dates(release_id: int, limit: int = 10) -> Dict:+ """Get FRED release dates"""+ try:+ params = {+ 'release_id': release_id,+ 'limit': limit+ }++ result = make_fred_request('release/dates', params)++ if 'error' in result:+ return result++ dates = []+ for date in result.get('release_dates', []):+ dates.append({+ 'release_id': date.get('release_id'),+ 'date': date.get('date')+ })++ return {+ 'release_id': release_id,+ 'dates': dates+ }+ except Exception as e:+ return {"error": str(e), "release_id": release_id}++def get_multiple_series(series_ids: List[str], start_date: Optional[str] = None,+ end_date: Optional[str] = None) -> List[Dict]:+ """Fetch multiple FRED series at once"""+ results = []+ for series_id in series_ids:+ result = get_series(series_id, start_date, end_date)+ results.append(result)+ return results++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": "Usage: python fred_data.py <command> <args>"}))+ sys.exit(1)++ command = sys.argv[1]++ if command == "series":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python fred_data.py series <series_id> [start_date] [end_date] [frequency] [transform]"}))+ sys.exit(1)++ series_id = sys.argv[2]+ start_date = sys.argv[3] if len(sys.argv) > 3 else None+ end_date = sys.argv[4] if len(sys.argv) > 4 else None+ frequency = sys.argv[5] if len(sys.argv) > 5 else None+ transform = sys.argv[6] if len(sys.argv) > 6 else None++ result = get_series(series_id, start_date, end_date, frequency, transform)+ print(json.dumps(result, indent=2))++ elif command == "multiple":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python fred_data.py multiple <series_id1> <series_id2> ... [start_date] [end_date]"}))+ sys.exit(1)++ # Find where dates start (if they exist)+ series_ids = []+ start_date = None+ end_date = None++ for i in range(2, len(sys.argv)):+ if '-' in sys.argv[i] and len(sys.argv[i]) == 10: # Date format YYYY-MM-DD+ if start_date is None:+ start_date = sys.argv[i]+ else:+ end_date = sys.argv[i]+ else:+ series_ids.append(sys.argv[i])++ result = get_multiple_series(series_ids, start_date, end_date)+ print(json.dumps(result, indent=2))++ elif command == "search":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python fred_data.py search <search_text> [limit]"}))+ sys.exit(1)++ search_text = sys.argv[2]+ limit = int(sys.argv[3]) if len(sys.argv) > 3 else 10++ result = search_series(search_text, limit)+ print(json.dumps(result, indent=2))++ elif command == "categories":+ category_id = int(sys.argv[2]) if len(sys.argv) > 2 else 0+ result = get_categories(category_id)+ print(json.dumps(result, indent=2))++ elif command == "category_series":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python fred_data.py category_series <category_id> [limit]"}))+ sys.exit(1)++ category_id = int(sys.argv[2])+ limit = int(sys.argv[3]) if len(sys.argv) > 3 else 50++ result = get_category_series(category_id, limit)+ print(json.dumps(result, indent=2))++ elif command == "releases":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: python fred_data.py releases <release_id> [limit]"}))+ sys.exit(1)++ release_id = int(sys.argv[2])+ limit = int(sys.argv[3]) if len(sys.argv) > 3 else 10++ result = get_release_dates(release_id, limit)+ print(json.dumps(result, indent=2))++ else:+ print(json.dumps({"error": f"Unknown command: {command}"}))+ sys.exit(1)++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/sign-wrapper.ps1 b/fincept-terminal-desktop/src-tauri/sign-wrapper.ps1new file mode 100644index 000000000..23e341da0--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/sign-wrapper.ps1@@ -0,0 +1,16 @@+param($FilePath)++# Log what we're checking+Write-Host "Checking file: $FilePath"++# Match any file in python directory+if ($FilePath -like "*\python\*" -or $FilePath -like "*/python/*") {+ Write-Host "SKIPPED Python file"+ exit 0+}++# Sign other files+$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path+Write-Host "Signing with relic..."+& relic sign --file $FilePath --key azure --config "$scriptDir\relic.conf"+exit $LASTEXITCODE\ No newline at end of filediff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex ff267dbbe..7faf91d1f 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -199,6 +199,49 @@ fn sha256_hash(input: String) -> String {format!("{:x}", result)}+// Execute Python script with arguments and environment variables+#[tauri::command]+fn execute_python_script(+ script_name: String,+ args: Vec<String>,+ env: Option<HashMap<String, String>>,+) -> Result<String, String> {+ println!("[Tauri] Executing Python script: {} with args: {:?}", script_name, args);++ let python_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("resources")+ .join("python")+ .join("python.exe");++ let script_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("resources")+ .join("scripts")+ .join(&script_name);++ let mut cmd = Command::new(&python_path);+ cmd.arg(&script_path).args(&args);++ // Add environment variables if provided+ if let Some(env_vars) = env {+ for (key, value) in env_vars {+ cmd.env(key, value);+ }+ }++ match cmd.output() {+ Ok(output) => {+ if output.status.success() {+ String::from_utf8(output.stdout)+ .map_err(|e| format!("Failed to parse output: {}", e))+ } else {+ let error = String::from_utf8_lossy(&output.stderr);+ Err(format!("Python script failed: {}", error))+ }+ }+ Err(e) => Err(format!("Failed to execute Python script: {}", e)),+ }+}+#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {tauri::Builder::default()@@ -216,6 +259,7 @@ pub fn run() {ping_mcp_server,kill_mcp_server,sha256_hash,+ execute_python_script,commands::market_data::get_market_quote,commands::market_data::get_market_quotes,commands::market_data::get_period_returns,diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.jsonindex 854ff119c..ef62f9307 100644--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "Fincept Terminal",- "version": "1.0.0",+ "version": "3.0.0","identifier": "com.fincept.terminal","build": {"beforeDevCommand": "npm run dev",@@ -32,6 +32,7 @@"targets": ["msi", "nsis"],"icon": ["icons/32x32.png",+ "icons/64x64.png","icons/128x128.png","icons/[email protected]","icons/icon.icns",@@ -58,7 +59,6 @@"language": "en-US"},"nsis": {- "languages": ["English"],"installerIcon": "icons/icon.ico","installMode": "currentUser"}diff --git a/fincept-terminal-desktop/src-tauri/tauri.microsoftstore.conf.json b/fincept-terminal-desktop/src-tauri/tauri.microsoftstore.conf.jsonindex 531b530d3..665b000a1 100644--- a/fincept-terminal-desktop/src-tauri/tauri.microsoftstore.conf.json+++ b/fincept-terminal-desktop/src-tauri/tauri.microsoftstore.conf.json@@ -2,7 +2,7 @@"$schema": "https://schema.tauri.app/config/2","bundle": {"windows": {- "signCommand": "relic sign --file %1 --key azure --config relic.conf",+ "signCommand": "powershell -ExecutionPolicy Bypass -File sign-wrapper.ps1 %1","digestAlgorithm": "sha256","timestampUrl": "http://timestamp.digicert.com","webviewInstallMode": {diff --git a/fincept-terminal-desktop/src-tauri/wix/main.wxs b/fincept-terminal-desktop/src-tauri/wix/main.wxsnew file mode 100644index 000000000..8c4efcabe--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/wix/main.wxs@@ -0,0 +1,76 @@+<?xml version="1.0" encoding="UTF-8"?>+<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">+ <Product+ Id="*"+ Name="Fincept Terminal"+ Language="1033"+ Version="1.0.0"+ Manufacturer="Fincept Corporation"+ UpgradeCode="{{upgrade_code}}">++ <Package+ InstallerVersion="200"+ Compressed="yes"+ InstallScope="perUser"+ Description="Professional-grade financial analysis platform" />++ <MajorUpgrade+ DowngradeErrorMessage="A newer version of Fincept Terminal is already installed."+ Schedule="afterInstallInitialize" />++ <MediaTemplate EmbedCab="yes" />++ <!-- Main Feature -->+ <Feature Id="MainApplication" Title="Fincept Terminal" Level="1">+ <ComponentGroupRef Id="ProductComponents" />+ </Feature>++ <!-- Custom action to remove AppData on uninstall -->+ <Property Id="REMOVEAPPDATA" Value="1" />++ <CustomAction+ Id="RemoveAppDataFolder"+ Directory="LOCALAPPDATA"+ ExeCommand='cmd.exe /C "rmdir /s /q "%LOCALAPPDATA%\com.fincept.terminal" && rmdir /s /q "%APPDATA%\com.fincept.terminal""'+ Execute="deferred"+ Impersonate="yes"+ Return="ignore" />++ <InstallExecuteSequence>+ <Custom Action="RemoveAppDataFolder" Before="RemoveFiles">+ (NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")+ </Custom>+ </InstallExecuteSequence>++ </Product>++ <!-- Directory structure -->+ <Fragment>+ <Directory Id="TARGETDIR" Name="SourceDir">+ <Directory Id="LocalAppDataFolder">+ <Directory Id="APPLICATIONFOLDER" Name="Fincept Terminal">+ {{component_groups}}+ </Directory>+ </Directory>+ <Directory Id="ProgramMenuFolder">+ <Directory Id="ApplicationProgramsFolder" Name="Fincept Terminal"/>+ </Directory>+ </Directory>+ </Fragment>++ <!-- Components -->+ <Fragment>+ <ComponentGroup Id="ProductComponents" Directory="APPLICATIONFOLDER">+ <!-- Tauri will inject components here -->+ {{components}}++ <!-- Additional cleanup component -->+ <Component Id="CleanupComponent" Guid="*">+ <RemoveFolder Id="RemoveApplicationFolder" Directory="APPLICATIONFOLDER" On="uninstall"/>+ <RemoveFolder Id="RemoveLocalAppData" Directory="LOCALAPPDATA" On="uninstall"/>+ <RegistryValue Root="HKCU" Key="Software\Fincept Corporation\Fincept Terminal"+ Name="Installed" Type="integer" Value="1" KeyPath="yes"/>+ </Component>+ </ComponentGroup>+ </Fragment>+</Wix>diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsxindex f0ceb660d..15d64e091 100644--- a/fincept-terminal-desktop/src/App.tsx+++ b/fincept-terminal-desktop/src/App.tsx@@ -86,12 +86,13 @@ const App: React.FC = () => {onCancel: () => {console.log('PaymentManager: Payment cancelled by user');setPaymentWindow(prev => ({ ...prev, isOpen: false }));+ setCurrentScreen('pricing');resolve(false);},onError: (error: string) => {console.error('PaymentManager: Payment error:', error);setPaymentWindow(prev => ({ ...prev, isOpen: false }));- alert(`Payment failed: ${error}`);+ setCurrentScreen('pricing');resolve(false);}});diff --git a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsxindex ee7bea07d..0ccd41232 100644--- a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx+++ b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx@@ -43,7 +43,19 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {// App.tsx useEffect will handle navigation based on account_type} else {console.log('Login failed:', result.error);- setError(result.error || 'Login failed. Please check your credentials.');++ // Check for specific error messages and provide helpful feedback+ const errorMessage = result.error || 'Login failed. Please check your credentials.';++ if (errorMessage.toLowerCase().includes('user not found') ||+ errorMessage.toLowerCase().includes('invalid credentials') ||+ errorMessage.toLowerCase().includes('user does not exist')) {+ setError("Account not found. Please sign up first to create an account.");+ } else if (errorMessage.toLowerCase().includes('password')) {+ setError("Incorrect password. Please try again or reset your password.");+ } else {+ setError(errorMessage);+ }}} catch (err) {console.error('Login error:', err);diff --git a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsxindex 376baa1a4..eb96a68ac 100644--- a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx+++ b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx@@ -86,9 +86,14 @@ const PricingScreen: React.FC<PricingScreenProps> = ({// Separate effect to set default selection when plans are loadeduseEffect(() => {if (availablePlans.length > 0 && !selectedPlan) {- setSelectedPlan('starter_20');+ const currentPlanId = (session?.subscription as any)?.data?.subscription?.plan?.plan_id ||+ session?.subscription?.subscription?.plan?.plan_id;+ // Don't auto-select if user already has current plan, otherwise select starter+ if (!currentPlanId) {+ setSelectedPlan('starter_20');+ }}- }, [availablePlans.length, selectedPlan]);+ }, [availablePlans.length, selectedPlan, session?.subscription]);const getAnnualPrice = (monthlyPrice: number) => {return monthlyPrice * 10; // 2 months free when billed annually@@ -177,10 +182,8 @@ const handleSelectPlan = async () => {const getPlanCard = (plan: any) => {const isSelected = selectedPlan === plan.plan_id;- const displayPrice = billingPeriod === 'annually' && plan.price_usd > 0- ? getAnnualPrice(plan.price_usd)- : plan.price_usd;- const priceUnit = billingPeriod === 'annually' ? 'year' : 'month';+ const displayPrice = plan.price_usd;+ const priceUnit = 'month';// Determine if plan is popular or recommendedconst isPopular = plan.plan_id === 'starter_20';@@ -246,12 +249,6 @@ const handleSelectPlan = async () => {</span><span className="text-zinc-400 text-xs ml-1">/{priceUnit}</span></div>-- {billingPeriod === 'annually' && plan.price_usd > 0 && (- <div className="text-green-400 text-xs mt-0.5">- Save {PaymentUtils.formatCurrency(PaymentUtils.calculateAnnualSavings(plan.price_usd))}/year- </div>- )}</div><p className="text-zinc-400 text-xs">{plan.description}</p>@@ -334,7 +331,7 @@ const handleSelectPlan = async () => {<ButtononClick={handleContinueWithFree}variant="outline"- className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"+ className="w-full bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700 hover:border-zinc-500">Continue with Free Plan</Button>@@ -347,6 +344,14 @@ const handleSelectPlan = async () => {const selectedPlanData = availablePlans.find(p => p.plan_id === selectedPlan);+ // Get current plan info+ const currentPlanId = (session?.subscription as any)?.data?.subscription?.plan?.plan_id ||+ session?.subscription?.subscription?.plan?.plan_id;+ const currentPlanData = availablePlans.find(p => p.plan_id === currentPlanId);+ const hasActiveSubscription = (session?.subscription as any)?.data?.has_subscription ||+ session?.subscription?.has_subscription;+ const isCurrentPlanSelected = selectedPlan === currentPlanId;+return (<div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-6 w-full max-w-5xl mx-auto shadow-2xl"><div className="mb-6">@@ -371,34 +376,12 @@ const handleSelectPlan = async () => {</h2></div>- <div className="flex items-center bg-zinc-800 rounded-lg p-0.5">- <button- onClick={() => setBillingPeriod('monthly')}- className={`px-3 py-1.5 text-xs rounded-md transition-colors ${- billingPeriod === 'monthly'- ? 'bg-zinc-600 text-white'- : 'text-zinc-400 hover:text-white'- }`}- disabled={isLoading}- >- Monthly- </button>- <button- onClick={() => setBillingPeriod('annually')}- className={`px-3 py-1.5 text-xs rounded-md transition-colors ${- billingPeriod === 'annually'- ? 'bg-zinc-600 text-white'- : 'text-zinc-400 hover:text-white'- }`}- disabled={isLoading}- >- Annual <span className="text-green-400">(-17%)</span>- </button>- </div></div><p className="text-zinc-400 text-sm">- {userType === 'existing'+ {hasActiveSubscription && currentPlanData+ ? `Currently on ${currentPlanData.name} plan. Select a different plan to upgrade or downgrade.`+ : userType === 'existing'? 'Currently on Free plan. Upgrade for advanced features and higher limits.': 'Select a plan that fits your financial analysis needs. Start with 14-day free trial.'}@@ -440,12 +423,7 @@ const handleSelectPlan = async () => {<div className="text-zinc-400 text-xs">{selectedPlanData ? (<>- {PaymentUtils.formatCurrency(- billingPeriod === 'annually'- ? getAnnualPrice(selectedPlanData.price_usd)- : selectedPlanData.price_usd- )}- /{billingPeriod === 'annually' ? 'year' : 'month'} • 14-day free trial • Cancel anytime+ {PaymentUtils.formatCurrency(selectedPlanData.price_usd)}/month • 14-day free trial • Cancel anytime</>) : ('Select a plan to continue'@@ -454,27 +432,42 @@ const handleSelectPlan = async () => {</div><div className="flex gap-3">- {userType === 'existing' && (+ {userType === 'existing' && !hasActiveSubscription && (<ButtononClick={handleContinueWithFree}variant="outline"- className="border-zinc-600 text-zinc-300 hover:bg-zinc-800 px-4 py-2 text-sm transition-colors"+ className="bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700 hover:border-zinc-500 px-4 py-2 text-sm transition-colors"disabled={isLoading}>Stay Free</Button>)}+ {hasActiveSubscription && (+ <Button+ onClick={onProceedToDashboard}+ variant="outline"+ className="bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700 hover:border-zinc-500 px-4 py-2 text-sm transition-colors"+ disabled={isLoading}+ >+ Keep Current Plan+ </Button>+ )}+<ButtononClick={handleSelectPlan}- disabled={!selectedPlan || isLoading}- className="bg-blue-600 hover:bg-blue-500 text-white px-6 py-2 text-sm transition-colors disabled:opacity-50"+ disabled={!selectedPlan || isLoading || isCurrentPlanSelected}+ className="bg-blue-600 hover:bg-blue-500 text-white font-medium px-6 py-2 text-sm transition-colors disabled:opacity-50">{isLoading ? (<div className="flex items-center"><Loader2 className="w-3 h-3 animate-spin mr-2" />Processing...</div>+ ) : isCurrentPlanSelected ? (+ 'Current Plan'+ ) : hasActiveSubscription ? (+ `Change to ${selectedPlanData?.name || 'Plan'}`) : (`Start Free Trial - ${selectedPlanData?.name || 'Plan'}`)}diff --git a/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx b/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsxindex 293bd02f8..120b4b25d 100644--- a/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx+++ b/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx@@ -5,7 +5,7 @@ import React, { useState, useEffect } from 'react';import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { ArrowLeft, User, Mail, Phone, Building, Lock, Key, ChevronDown } from "lucide-react";+import { ArrowLeft, User, Mail, Phone, Building, Lock, Key, ChevronDown, Check, X } from "lucide-react";import { Screen } from '../../App';import { useAuth } from '@/contexts/AuthContext';@@ -43,6 +43,15 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {const [isCountryDropdownOpen, setIsCountryDropdownOpen] = useState(false);const [countrySearchTerm, setCountrySearchTerm] = useState("");+ // Password validation state+ const [passwordValidation, setPasswordValidation] = useState({+ minLength: false,+ hasUpperCase: false,+ hasLowerCase: false,+ hasNumber: false,+ hasSpecialChar: false+ });+// Fetch countries data from REST Countries APIuseEffect(() => {const fetchCountries = async () => {@@ -99,6 +108,17 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {const handleChange = (field: string, value: string) => {setFormData(prev => ({ ...prev, [field]: value }));if (error) setError("");++ // Real-time password validation+ if (field === 'password') {+ setPasswordValidation({+ minLength: value.length >= 8,+ hasUpperCase: /[A-Z]/.test(value),+ hasLowerCase: /[a-z]/.test(value),+ hasNumber: /[0-9]/.test(value),+ hasSpecialChar: /[!@#$%^&*(),.?":{}|<>]/.test(value)+ });+ }};const handleCountrySelect = (country: Country) => {@@ -146,10 +166,21 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {if (result.success) {console.log('Registration successful, OTP sent to:', formData.email);+ // Note: Backend handles re-registration for unverified accounts automatically+ // A fresh OTP is sent even if the user previously registered but didn't verifysetStep('otp-verification');} else {console.log('Registration failed:', result.error);- setError(result.error || 'Registration failed. Please try again.');+ // Enhanced error handling for common scenarios+ const errorMessage = result.error || 'Registration failed. Please try again.';++ // If the error indicates an already verified account, show helpful message+ if (errorMessage.toLowerCase().includes('already exists') ||+ errorMessage.toLowerCase().includes('already registered')) {+ setError("This email is already registered and verified. Please use the login page instead.");+ } else {+ setError(errorMessage);+ }}} catch (err) {console.error('Registration error:', err);@@ -387,45 +418,77 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {</div></div>- <div className="grid grid-cols-2 gap-3">- <div className="space-y-1">- <Label htmlFor="password" className="text-white text-xs">- Password *- </Label>- <div className="relative">- <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />- <Input- id="password"- type="password"- placeholder="Create password"- value={formData.password}- onChange={(e) => handleChange("password", e.target.value)}- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"- disabled={isLoading}- required- minLength={8}- />- </div>+ <div className="space-y-1">+ <Label htmlFor="password" className="text-white text-xs">+ Password *+ </Label>+ <div className="relative">+ <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />+ <Input+ id="password"+ type="password"+ placeholder="Create password"+ value={formData.password}+ onChange={(e) => handleChange("password", e.target.value)}+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"+ disabled={isLoading}+ required+ minLength={8}+ /></div>- <div className="space-y-1">- <Label htmlFor="confirmPassword" className="text-white text-xs">- Confirm Password *- </Label>- <div className="relative">- <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />- <Input- id="confirmPassword"- type="password"- placeholder="Confirm password"- value={formData.confirmPassword}- onChange={(e) => handleChange("confirmPassword", e.target.value)}- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"- disabled={isLoading}- required- />+ {/* Password Strength Indicators */}+ {formData.password && (+ <div className="mt-2 space-y-1 text-xs">+ <div className={`flex items-center gap-1.5 ${passwordValidation.minLength ? 'text-green-400' : 'text-zinc-500'}`}>+ {passwordValidation.minLength ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}+ <span>At least 8 characters</span>+ </div>+ <div className={`flex items-center gap-1.5 ${passwordValidation.hasUpperCase ? 'text-green-400' : 'text-zinc-500'}`}>+ {passwordValidation.hasUpperCase ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}+ <span>One uppercase letter</span>+ </div>+ <div className={`flex items-center gap-1.5 ${passwordValidation.hasLowerCase ? 'text-green-400' : 'text-zinc-500'}`}>+ {passwordValidation.hasLowerCase ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}+ <span>One lowercase letter</span>+ </div>+ <div className={`flex items-center gap-1.5 ${passwordValidation.hasNumber ? 'text-green-400' : 'text-zinc-500'}`}>+ {passwordValidation.hasNumber ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}+ <span>One number</span>+ </div>+ <div className={`flex items-center gap-1.5 ${passwordValidation.hasSpecialChar ? 'text-green-400' : 'text-zinc-500'}`}>+ {passwordValidation.hasSpecialChar ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}+ <span>One special character</span>+ </div></div>+ )}+ </div>++ <div className="space-y-1">+ <Label htmlFor="confirmPassword" className="text-white text-xs">+ Confirm Password *+ </Label>+ <div className="relative">+ <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />+ <Input+ id="confirmPassword"+ type="password"+ placeholder="Confirm password"+ value={formData.confirmPassword}+ onChange={(e) => handleChange("confirmPassword", e.target.value)}+ className={`bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500 ${+ formData.confirmPassword && formData.password !== formData.confirmPassword ? 'border-red-500' : ''+ }`}+ disabled={isLoading}+ required+ /></div>+ {formData.confirmPassword && formData.password !== formData.confirmPassword && (+ <div className="flex items-center gap-1.5 text-red-400 text-xs mt-1">+ <X className="h-3 w-3" />+ <span>Passwords do not match</span>+ </div>+ )}</div>{error && (@@ -475,7 +538,7 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {);}- // Step 2: OTP Verification (unchanged)+ // Step 2: OTP Verificationif (step === 'otp-verification') {return (<div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">@@ -494,6 +557,9 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {We've sent a verification code to <span className="text-white">{formData.email}</span>.Please enter the code below to complete your registration.</p>+ <p className="text-zinc-500 text-xs leading-5 mt-2">+ Note: If you've registered before but didn't verify, a fresh code has been sent to your email.+ </p></div><form onSubmit={handleVerifyOtp} className="space-y-4">diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 2715310ed..b3b7d0bf2 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -3,6 +3,7 @@ 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 { APP_VERSION } from '@/constants/version';import ForumTab from '@/components/tabs/ForumTab';import DashboardTab from '@/components/tabs/DashboardTab';import MarketsTab from '@/components/tabs/MarketsTab';@@ -21,6 +22,7 @@ import EconomicCalendarTab from '@/components/tabs/EconomicCalendarTab';import ScreenerTab from '@/components/tabs/ScreenerTab';import AlertsTab from '@/components/tabs/AlertsTab';import DBnomicsTab from '@/components/tabs/DBnomicsTab';+import EconomicsTab from '@/components/tabs/EconomicsTab';import CodeEditorTab from '@/components/tabs/CodeEditorTab';import DocsTab from '@/components/tabs/DocsTab';import MaritimeTab from '@/components/tabs/MaritimeTab';@@ -129,7 +131,21 @@ export default function FinxeptTerminal() {document.documentElement.style.backgroundColor = '#000000';document.documentElement.style.overflow = 'hidden';document.documentElement.style.overscrollBehavior = 'none';-++ // Initialize database on app start+ (async () => {+ try {+ const { sqliteService } = await import('@/services/sqliteService');+ if (!sqliteService.isReady()) {+ console.log('Initializing database on app start...');+ await sqliteService.initialize();+ console.log('Database initialized successfully');+ }+ } catch (error) {+ console.error('Failed to initialize database on app start:', error);+ }+ })();+return () => {document.body.style.overflow = 'auto';document.body.style.overscrollBehavior = 'auto';@@ -326,7 +342,7 @@ export default function FinxeptTerminal() {{ label: 'Video Tutorials', icon: null, separator: true },{ label: 'Contact Support', icon: null },{ label: 'Report Bug', icon: null, separator: true },- { label: 'About Finxept', icon: null }+ { label: `About Finxept v${APP_VERSION}`, icon: null }];const tabStyles = {@@ -625,6 +641,12 @@ export default function FinxeptTerminal() {>DBnomics</TabsTrigger>+ <TabsTrigger+ value="economics"+ style={activeTab === 'economics' ? tabStyles.active : tabStyles.default}+ >+ Economics+ </TabsTrigger><TabsTriggervalue="code"style={activeTab === 'code' ? tabStyles.active : tabStyles.default}@@ -672,13 +694,13 @@ export default function FinxeptTerminal() {style={activeTab === 'datamapping' ? tabStyles.active : tabStyles.default}>Data Mapping+ </TabsTrigger><TabsTriggervalue="support"style={activeTab === 'support' ? tabStyles.active : tabStyles.default}>Support</TabsTrigger>- </TabsTrigger></TabsList></Tabs></div>@@ -701,6 +723,8 @@ export default function FinxeptTerminal() {<span style={{ color: '#a3a3a3', fontSize: '10px' }}>Search</span><div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div><span style={{ color: '#a3a3a3', fontSize: '10px' }}>2025-09-26 14:00:49</span>+ <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>+ <span style={{ color: '#10b981', fontSize: '10px', fontWeight: 'bold' }}>v{APP_VERSION}</span>{isFullscreen && (<><div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>@@ -797,6 +821,9 @@ export default function FinxeptTerminal() {<TabsContent value="dbnomics" className="h-full m-0 p-0"><DBnomicsTab /></TabsContent>+ <TabsContent value="economics" className="h-full m-0 p-0">+ <EconomicsTab />+ </TabsContent><TabsContent value="code" className="h-full m-0 p-0"><CodeEditorTab /></TabsContent>diff --git a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsxindex c626188b1..d19769d5f 100644--- a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx+++ b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx@@ -275,21 +275,30 @@ const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({)}{(status === 'waiting' || status === 'processing') && (- <Button- onClick={handleManualRefresh}- variant="outline"- className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"- >- <RefreshCw className="w-4 h-4 mr-2" />- Check Status Now- </Button>+ <div className="space-y-2">+ <Button+ onClick={handleManualRefresh}+ variant="outline"+ className="w-full bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700 hover:border-zinc-500"+ >+ <RefreshCw className="w-4 h-4 mr-2" />+ Check Status Now+ </Button>+ <Button+ onClick={handleBackToPricing}+ variant="outline"+ className="w-full bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700 hover:border-zinc-500"+ >+ Back to Plans+ </Button>+ </div>)}{(status === 'failed' || status === 'cancelled' || status === 'timeout') && (<div className="space-y-2"><ButtononClick={handleManualRefresh}- className="w-full bg-blue-600 hover:bg-blue-500 text-white"+ className="w-full bg-blue-600 hover:bg-blue-500 text-white font-medium"><RefreshCw className="w-4 h-4 mr-2" />Check Again@@ -297,7 +306,7 @@ const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({<ButtononClick={handleBackToPricing}variant="outline"- className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"+ className="w-full bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700 hover:border-zinc-500">Back to Plans</Button>diff --git a/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsxnew file mode 100644index 000000000..789f65b71--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx@@ -0,0 +1,404 @@+import React, { useState } from 'react';+import { RefreshCw, Download, Globe, TrendingUp, BarChart3, PieChart } from 'lucide-react';+import { invoke } from '@tauri-apps/api/core';++interface Indicator {+ code: string;+ name: string;+ description: string;+}++interface Country {+ code: string;+ name: string;+}++interface Observation {+ date: string;+ value: number;+}++interface IndicatorData {+ indicator: string;+ country: string;+ transform: string;+ observations: Observation[];+ metadata: any;+}++interface ProfileData {+ country: string;+ indicators: Record<string, { date: string; value: number }>;+}++export default function EconomicsTab() {+ const [view, setView] = useState<'indicator' | 'profile' | 'countries'>('indicator');+ const [loading, setLoading] = useState(false);+ const [status, setStatus] = useState('Ready');++ // Indicator view state+ const [selectedIndicator, setSelectedIndicator] = useState('GDP');+ const [selectedCountry, setSelectedCountry] = useState('US');+ const [selectedTransform, setSelectedTransform] = useState('level');+ const [indicatorData, setIndicatorData] = useState<IndicatorData | null>(null);++ // Profile view state+ const [profileCountry, setProfileCountry] = useState('US');+ const [profileData, setProfileData] = useState<ProfileData | null>(null);++ // Available options+ const indicators: Indicator[] = [+ { code: 'GDP', name: 'GDP (Nominal)', description: 'Gross Domestic Product' },+ { code: 'RGDP', name: 'GDP (Real)', description: 'Real GDP' },+ { code: 'CPI', name: 'CPI', description: 'Consumer Price Index' },+ { code: 'PPI', name: 'PPI', description: 'Producer Price Index' },+ { code: 'CORE', name: 'Core CPI', description: 'Core Inflation' },+ { code: 'URATE', name: 'Unemployment', description: 'Unemployment Rate' },+ { code: 'EMP', name: 'Employment', description: 'Employment Level' },+ { code: 'IP', name: 'Industrial Production', description: 'Industrial Production Index' },+ { code: 'RETA', name: 'Retail Sales', description: 'Retail Sales' },+ { code: 'CONF', name: 'Consumer Confidence', description: 'Consumer Confidence Index' },+ { code: 'POLIR', name: 'Policy Rate', description: 'Policy Interest Rate' },+ { code: 'Y10YD', name: '10Y Yield', description: '10-Year Government Bond Yield' },+ { code: 'M3YD', name: '3M Yield', description: '3-Month Treasury Yield' },+ { code: 'GDEBT', name: 'Government Debt', description: 'Government Debt' },+ { code: 'CA', name: 'Current Account', description: 'Current Account Balance' },+ { code: 'TB', name: 'Trade Balance', description: 'Trade Balance' },+ { code: 'POP', name: 'Population', description: 'Total Population' },+ ];++ const countries: Country[] = [+ { code: 'US', name: 'United States' },+ { code: 'CN', name: 'China' },+ { code: 'JP', name: 'Japan' },+ { code: 'DE', name: 'Germany' },+ { code: 'UK', name: 'United Kingdom' },+ { code: 'FR', name: 'France' },+ { code: 'IN', name: 'India' },+ { code: 'IT', name: 'Italy' },+ { code: 'BR', name: 'Brazil' },+ { code: 'CA', name: 'Canada' },+ { code: 'KR', name: 'South Korea' },+ { code: 'RU', name: 'Russia' },+ { code: 'AU', name: 'Australia' },+ { code: 'ES', name: 'Spain' },+ { code: 'MX', name: 'Mexico' },+ { code: 'ID', name: 'Indonesia' },+ { code: 'NL', name: 'Netherlands' },+ { code: 'SA', name: 'Saudi Arabia' },+ { code: 'TR', name: 'Turkey' },+ { code: 'CH', name: 'Switzerland' },+ ];++ const transforms = [+ { code: 'level', name: 'Level', description: 'No transformation' },+ { code: 'toya', name: 'YoY %', description: 'Year-over-year change' },+ { code: 'tpop', name: 'QoQ %', description: 'Quarter-over-quarter change' },+ { code: 'tusd', name: 'USD', description: 'Convert to USD' },+ { code: 'tpgp', name: '% of GDP', description: 'As percent of GDP' },+ ];++ const fetchIndicator = async () => {+ setLoading(true);+ setStatus(`Fetching ${selectedIndicator} for ${selectedCountry}...`);++ try {+ const result = await invoke('execute_python_script', {+ scriptName: 'econdb_data.py',+ args: ['indicator', selectedIndicator, selectedCountry, '', '', selectedTransform]+ }) as string;++ const data = JSON.parse(result);++ if (data.error) {+ setStatus(`Error: ${data.error}`);+ } else {+ setIndicatorData(data);+ setStatus(`Loaded ${data.observation_count} observations`);+ }+ } catch (error) {+ setStatus(`Error: ${error}`);+ } finally {+ setLoading(false);+ }+ };++ const fetchProfile = async () => {+ setLoading(true);+ setStatus(`Fetching profile for ${profileCountry}...`);++ try {+ const result = await invoke('execute_python_script', {+ scriptName: 'econdb_data.py',+ args: ['profile', profileCountry, 'true']+ }) as string;++ const data = JSON.parse(result);++ if (data.error) {+ setStatus(`Error: ${data.error}`);+ } else {+ setProfileData(data);+ setStatus(`Profile loaded for ${profileCountry}`);+ }+ } catch (error) {+ setStatus(`Error: ${error}`);+ } finally {+ setLoading(false);+ }+ };++ const exportData = () => {+ if (!indicatorData) return;++ const csv = [+ 'Date,Value',+ ...indicatorData.observations.map(obs => `${obs.date},${obs.value}`)+ ].join('\n');++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `econdb_${selectedIndicator}_${selectedCountry}_${Date.now()}.csv`;+ a.click();+ URL.revokeObjectURL(url);+ setStatus('Data exported');+ };++ const renderChart = (data: Observation[]) => {+ if (data.length === 0) return null;++ const w = 800;+ const h = 300;+ const ml = 70;+ const mr = 20;+ const mt = 20;+ const mb = 50;+ const pw = w - ml - mr;+ const ph = h - mt - mb;++ const values = data.map(d => d.value);+ const yMin = Math.min(...values) * 0.95;+ const yMax = Math.max(...values) * 1.05;+ const yRange = yMax - yMin;++ return (+ <svg width={w} height={h} style={{ backgroundColor: '#0a0a0a', width: '100%', height: 'auto' }}>+ {/* Axes */}+ <line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke="#404040" strokeWidth="1" />+ <line x1={ml} y1={h - mb} x2={w - mr} y2={h - mb} stroke="#404040" strokeWidth="1" />++ {/* Y-axis grid and labels */}+ {[0, 1, 2, 3, 4].map(i => {+ const val = yMin + (yRange * i) / 4;+ const y = h - mb - (ph * i) / 4;+ return (+ <g key={i}>+ <line x1={ml} y1={y} x2={w - mr} y2={y} stroke="#1a1a1a" strokeDasharray="2,2" />+ <text x={ml - 10} y={y + 4} textAnchor="end" fill="#737373" fontSize="10" fontFamily="monospace">+ {val.toFixed(2)}+ </text>+ </g>+ );+ })}++ {/* Line and points */}+ {data.map((obs, idx) => {+ const x = ml + (pw * idx) / (data.length - 1 || 1);+ const y = h - mb - (ph * ((obs.value - yMin) / yRange));++ return (+ <g key={idx}>+ <circle cx={x} cy={y} r="3" fill="#ea580c" />+ {idx < data.length - 1 && (+ <line+ x1={x}+ y1={y}+ x2={ml + (pw * (idx + 1)) / (data.length - 1 || 1)}+ y2={h - mb - (ph * ((data[idx + 1].value - yMin) / yRange))}+ stroke="#ea580c"+ strokeWidth="2"+ />+ )}+ </g>+ );+ })}++ {/* X-axis labels */}+ {data.map((obs, idx) => {+ if (idx % Math.max(1, Math.floor(data.length / 8)) !== 0 && idx !== data.length - 1) return null;+ const x = ml + (pw * idx) / (data.length - 1 || 1);+ return (+ <text key={idx} x={x} y={h - mb + 20} textAnchor="middle" fill="#737373" fontSize="9" fontFamily="monospace">+ {obs.date.substring(0, 10)}+ </text>+ );+ })}+ </svg>+ );+ };++ return (+ <div style={{ width: '100%', height: '100%', backgroundColor: '#000', color: '#d4d4d4', fontFamily: 'Consolas, monospace', fontSize: '11px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Header */}+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #404040', display: 'flex', alignItems: 'center', gap: '12px', flexShrink: 0 }}>+ <span style={{ color: '#ea580c', fontWeight: 'bold' }}>ECONOMICS - ECONDB</span>+ <span style={{ color: '#10b981', fontSize: '10px' }}>● {status}</span>+ <div style={{ flex: 1 }}></div>+ <button onClick={() => setView('indicator')} style={{ padding: '4px 10px', backgroundColor: view === 'indicator' ? '#ea580c' : '#2d2d2d', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '9px' }}>+ <BarChart3 size={10} style={{ display: 'inline', marginRight: '4px' }} />INDICATOR+ </button>+ <button onClick={() => setView('profile')} style={{ padding: '4px 10px', backgroundColor: view === 'profile' ? '#ea580c' : '#2d2d2d', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '9px' }}>+ <PieChart size={10} style={{ display: 'inline', marginRight: '4px' }} />PROFILE+ </button>+ <button onClick={() => setView('countries')} style={{ padding: '4px 10px', backgroundColor: view === 'countries' ? '#ea580c' : '#2d2d2d', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '9px' }}>+ <Globe size={10} style={{ display: 'inline', marginRight: '4px' }} />COUNTRIES+ </button>+ </div>++ {/* Main Content */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Left Panel - Controls */}+ <div style={{ width: '300px', borderRight: '1px solid #404040', display: 'flex', flexDirection: 'column', backgroundColor: '#0a0a0a', overflowY: 'auto' }}>+ {view === 'indicator' && (+ <div style={{ padding: '12px' }}>+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>INDICATOR</div>+ <select value={selectedIndicator} onChange={(e) => setSelectedIndicator(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>+ {indicators.map(ind => (+ <option key={ind.code} value={ind.code}>{ind.name}</option>+ ))}+ </select>++ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>COUNTRY</div>+ <select value={selectedCountry} onChange={(e) => setSelectedCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>+ {countries.map(c => (+ <option key={c.code} value={c.code}>{c.name}</option>+ ))}+ </select>++ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>TRANSFORM</div>+ <select value={selectedTransform} onChange={(e) => setSelectedTransform(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '16px', fontSize: '10px' }}>+ {transforms.map(t => (+ <option key={t.code} value={t.code}>{t.name}</option>+ ))}+ </select>++ <button onClick={fetchIndicator} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: '#fff', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px', marginBottom: '8px' }}>+ {loading ? 'Loading...' : 'FETCH DATA'}+ </button>++ <button onClick={exportData} disabled={!indicatorData} style={{ width: '100%', padding: '8px', backgroundColor: '#2d2d2d', color: '#d4d4d4', border: '1px solid #404040', cursor: !indicatorData ? 'not-allowed' : 'pointer', fontSize: '10px' }}>+ <Download size={10} style={{ display: 'inline', marginRight: '4px' }} />EXPORT CSV+ </button>++ {indicatorData && (+ <div style={{ marginTop: '16px', padding: '8px', backgroundColor: '#1a1a1a', border: '1px solid #404040', fontSize: '9px' }}>+ <div style={{ color: '#fbbf24', marginBottom: '4px' }}>METADATA</div>+ <div style={{ color: '#737373' }}>Country: {indicatorData.country}</div>+ <div style={{ color: '#737373' }}>Indicator: {indicatorData.indicator}</div>+ <div style={{ color: '#737373' }}>Transform: {indicatorData.transform}</div>+ <div style={{ color: '#737373' }}>Points: {indicatorData.observation_count}</div>+ </div>+ )}+ </div>+ )}++ {view === 'profile' && (+ <div style={{ padding: '12px' }}>+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>SELECT COUNTRY</div>+ <select value={profileCountry} onChange={(e) => setProfileCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '16px', fontSize: '10px' }}>+ {countries.map(c => (+ <option key={c.code} value={c.code}>{c.name}</option>+ ))}+ </select>++ <button onClick={fetchProfile} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: '#fff', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px' }}>+ {loading ? 'Loading...' : 'LOAD PROFILE'}+ </button>+ </div>+ )}++ {view === 'countries' && (+ <div style={{ padding: '12px' }}>+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>AVAILABLE COUNTRIES ({countries.length})</div>+ {countries.map(c => (+ <div key={c.code} style={{ padding: '6px 8px', backgroundColor: '#1a1a1a', border: '1px solid #404040', marginBottom: '4px', fontSize: '10px' }}>+ <span style={{ color: '#fbbf24' }}>{c.code}</span> - {c.name}+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Right Panel - Data Display */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ <div style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>+ {view === 'indicator' && indicatorData && (+ <>+ <div style={{ marginBottom: '16px' }}>+ <div style={{ color: '#ea580c', fontSize: '12px', marginBottom: '8px' }}>+ {indicatorData.metadata.description || indicatorData.indicator}+ </div>+ <div style={{ color: '#737373', fontSize: '10px' }}>+ {indicatorData.country} • {indicatorData.observation_count} observations+ </div>+ </div>++ {renderChart(indicatorData.observations)}++ <div style={{ marginTop: '24px' }}>+ <div style={{ color: '#ea580c', fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>+ <div style={{ maxHeight: '400px', overflowY: 'auto', border: '1px solid #404040', backgroundColor: '#0a0a0a' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a' }}>+ <tr>+ <th style={{ padding: '8px', textAlign: 'left', color: '#ea580c', borderBottom: '2px solid #404040' }}>Date</th>+ <th style={{ padding: '8px', textAlign: 'right', color: '#ea580c', borderBottom: '2px solid #404040' }}>Value</th>+ </tr>+ </thead>+ <tbody>+ {indicatorData.observations.slice().reverse().map((obs, idx) => (+ <tr key={idx} style={{ borderBottom: '1px solid #1a1a1a' }}>+ <td style={{ padding: '6px 8px', color: '#d4d4d4' }}>{obs.date}</td>+ <td style={{ padding: '6px 8px', textAlign: 'right', color: '#a3a3a3' }}>{obs.value.toFixed(4)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </>+ )}++ {view === 'profile' && profileData && (+ <div>+ <div style={{ color: '#ea580c', fontSize: '12px', marginBottom: '16px' }}>+ ECONOMIC PROFILE - {profileData.country}+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '12px' }}>+ {Object.entries(profileData.indicators).map(([name, data]) => (+ <div key={name} style={{ padding: '12px', backgroundColor: '#0a0a0a', border: '1px solid #404040' }}>+ <div style={{ color: '#fbbf24', fontSize: '10px', marginBottom: '8px' }}>{name}</div>+ <div style={{ color: '#fff', fontSize: '20px', fontWeight: 'bold', marginBottom: '4px' }}>+ {typeof data.value === 'number' ? data.value.toFixed(4) : data.value}+ </div>+ <div style={{ color: '#737373', fontSize: '9px' }}>{data.date}</div>+ </div>+ ))}+ </div>+ </div>+ )}++ {!indicatorData && !profileData && view !== 'countries' && (+ <div style={{ textAlign: 'center', color: '#737373', paddingTop: '80px' }}>+ <TrendingUp size={48} style={{ margin: '0 auto 16px', opacity: 0.3 }} />+ <div>Select parameters and fetch data to begin</div>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx b/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsxindex afb32a15f..2dd8a4a20 100644--- a/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx@@ -1,819 +1,1112 @@-import React, { useState, useEffect } from 'react';+import React, { useState, useEffect, useMemo } from 'react';+import { Search, Download, TrendingUp, BarChart3, Loader2, AlertCircle, FolderTree, X, Plus, ArrowLeft, ChevronRight } from 'lucide-react';+import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';+import { sqliteService } from '@/services/sqliteService';+import { invoke } from '@tauri-apps/api/core';-interface Stock {- ticker: string;+interface SeriesData {+ date: string;+ value: number;+}++interface FREDSeries {+ series_id: string;+ title: string;+ units: string;+ frequency: string;+ seasonal_adjustment: string;+ last_updated: string;+ observations: SeriesData[];+ observation_count: number;+}++interface SearchResult {+ id: string;+ title: string;+ frequency: string;+ units: string;+ seasonal_adjustment: string;+ last_updated: string;+ popularity: number;+}++interface Category {+ id: number;name: string;- sector: string;- price: number;- change: number;- changePercent: number;- marketCap: string;- pe: number;- ps: number;- pb: number;- forwardPE: number;- peg: number;- dividend: number;- roe: number;- roa: number;- debtToEquity: number;- currentRatio: number;- eps: number;- revenue: string;- revenueGrowth: number;- profitMargin: number;- beta: number;- volume: string;- avgVolume: string;- week52High: number;- week52Low: number;+ parent_id: number;}-const ScreenerTab: React.FC = () => {- const [currentTime, setCurrentTime] = useState(new Date());- const [filters, setFilters] = useState({- marketCapMin: '',- marketCapMax: '',- peMin: '',- peMax: '',- dividendMin: '',- priceMin: '',- priceMax: '',- sector: 'ALL',- volumeMin: ''- });-- const COLOR_ORANGE = '#FFA500';- const COLOR_WHITE = '#FFFFFF';- const COLOR_RED = '#FF0000';- const COLOR_GREEN = '#00C800';- const COLOR_YELLOW = '#FFFF00';- const COLOR_GRAY = '#787878';- const COLOR_BLUE = '#6496FA';- const COLOR_PURPLE = '#C864FF';- const COLOR_CYAN = '#00FFFF';- const COLOR_DARK_BG = '#000000';- const COLOR_PANEL_BG = '#0a0a0a';+const POPULAR_SERIES = [+ { id: 'GDP', name: 'Gross Domestic Product', cat: 'Economic' },+ { id: 'UNRATE', name: 'Unemployment Rate', cat: 'Labor' },+ { id: 'CPIAUCSL', name: 'Consumer Price Index', cat: 'Inflation' },+ { id: 'FEDFUNDS', name: 'Federal Funds Rate', cat: 'Interest Rates' },+ { id: 'DGS10', name: '10-Year Treasury Rate', cat: 'Bonds' },+ { id: 'DEXUSEU', name: 'USD/EUR Exchange Rate', cat: 'Forex' },+ { id: 'DCOILWTICO', name: 'WTI Crude Oil Price', cat: 'Commodities' },+ { id: 'GOLDAMGBD228NLBM', name: 'Gold Price', cat: 'Commodities' }+];++const POPULAR_CATEGORIES = [+ { id: 32991, name: '💰 Money, Banking, & Finance', desc: 'Money supply, interest rates, banking data' },+ { id: 10, name: '📊 Population, Employment, Labor', desc: 'Employment, unemployment, labor statistics' },+ { id: 32455, name: '💵 Prices', desc: 'Inflation, CPI, PPI, commodity prices' },+ { id: 1, name: '🏭 Production & Business', desc: 'Industrial production, capacity utilization' },+ { id: 32263, name: '🌍 International Data', desc: 'Trade, exchange rates, foreign markets' },+ { id: 33060, name: '🏛️ U.S. Regional Data', desc: 'State and metro area statistics' },+];++export default function ScreenerTab() {+ const [seriesIds, setSeriesIds] = useState('GDP');+ const [startDate, setStartDate] = useState('2000-01-01');+ const [endDate, setEndDate] = useState(new Date().toISOString().split('T')[0]);+ const [data, setData] = useState<FREDSeries[]>([]);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [chartType, setChartType] = useState<'line' | 'area'>('line');+ const [apiKeyConfigured, setApiKeyConfigured] = useState<boolean>(false);++ // Series browser modal state+ const [showBrowser, setShowBrowser] = useState(false);+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<SearchResult[]>([]);+ const [searchLoading, setSearchLoading] = useState(false);+ const [categories, setCategories] = useState<Category[]>([]);+ const [currentCategory, setCurrentCategory] = useState<number>(0);+ const [categoryPath, setCategoryPath] = useState<{id: number, name: string}[]>([{id: 0, name: 'All Categories'}]);+ const [categoryLoading, setCategoryLoading] = useState(false);+ const [categorySeriesResults, setCategorySeriesResults] = useState<SearchResult[]>([]);useEffect(() => {- const timer = setInterval(() => setCurrentTime(new Date()), 1000);- return () => clearInterval(timer);+ checkApiKey();+ // Auto-load GDP data on mount+ const autoLoadData = async () => {+ const apiKey = await sqliteService.getApiKey('FRED');+ if (apiKey) {+ fetchData();+ }+ };+ autoLoadData();}, []);- const stocks: Stock[] = [- {- ticker: 'AAPL',- name: 'Apple Inc',- sector: 'Technology',- price: 178.45,- change: 2.34,- changePercent: 1.33,- marketCap: '$2.78T',- pe: 28.4,- ps: 7.2,- pb: 45.6,- forwardPE: 26.8,- peg: 2.1,- dividend: 0.55,- roe: 147.3,- roa: 27.8,- debtToEquity: 1.89,- currentRatio: 0.98,- eps: 6.29,- revenue: '$394.3B',- revenueGrowth: 2.1,- profitMargin: 25.3,- beta: 1.24,- volume: '$42.5M',- avgVolume: '$38.2M',- week52High: 199.62,- week52Low: 164.08- },- {- ticker: 'MSFT',- name: 'Microsoft Corp',- sector: 'Technology',- price: 412.34,- change: 5.67,- changePercent: 1.39,- marketCap: '$3.07T',- pe: 35.2,- ps: 12.4,- pb: 12.8,- forwardPE: 31.4,- peg: 2.4,- dividend: 0.72,- roe: 42.7,- roa: 16.4,- debtToEquity: 0.45,- currentRatio: 1.77,- eps: 11.73,- revenue: '$227.6B',- revenueGrowth: 13.2,- profitMargin: 36.7,- beta: 0.89,- volume: '$28.3M',- avgVolume: '$25.7M',- week52High: 425.22,- week52Low: 309.45- },- {- ticker: 'GOOGL',- name: 'Alphabet Inc',- sector: 'Technology',- price: 145.67,- change: -1.23,- changePercent: -0.84,- marketCap: '$1.82T',- pe: 24.6,- ps: 5.8,- pb: 6.4,- forwardPE: 22.1,- peg: 1.8,- dividend: 0.00,- roe: 27.8,- roa: 18.9,- debtToEquity: 0.12,- currentRatio: 2.56,- eps: 5.93,- revenue: '$307.4B',- revenueGrowth: 8.7,- profitMargin: 25.9,- beta: 1.05,- volume: '$19.8M',- avgVolume: '$21.4M',- week52High: 156.23,- week52Low: 121.46- },- {- ticker: 'NVDA',- name: 'NVIDIA Corp',- sector: 'Technology',- price: 878.34,- change: 12.45,- changePercent: 1.44,- marketCap: '$2.18T',- pe: 68.7,- ps: 38.2,- pb: 55.4,- forwardPE: 52.3,- peg: 1.2,- dividend: 0.04,- roe: 98.4,- roa: 56.7,- debtToEquity: 0.28,- currentRatio: 3.45,- eps: 12.79,- revenue: '$60.9B',- revenueGrowth: 125.9,- profitMargin: 53.4,- beta: 1.67,- volume: '$52.3M',- avgVolume: '$48.9M',- week52High: 974.23,- week52Low: 389.12- },- {- ticker: 'JPM',- name: 'JPMorgan Chase',- sector: 'Financials',- price: 187.23,- change: 1.89,- changePercent: 1.02,- marketCap: '$535.6B',- pe: 11.2,- ps: 3.4,- pb: 1.8,- forwardPE: 10.4,- peg: 1.1,- dividend: 2.84,- roe: 16.8,- roa: 1.3,- debtToEquity: 1.34,- currentRatio: 0.78,- eps: 16.72,- revenue: '$158.1B',- revenueGrowth: 22.3,- profitMargin: 32.1,- beta: 1.12,- volume: '$8.9M',- avgVolume: '$9.2M',- week52High: 199.45,- week52Low: 135.23- },- {- ticker: 'JNJ',- name: 'Johnson & Johnson',- sector: 'Healthcare',- price: 156.78,- change: 0.45,- changePercent: 0.29,- marketCap: '$389.2B',- pe: 15.4,- ps: 4.2,- pb: 5.6,- forwardPE: 14.8,- peg: 2.8,- dividend: 2.95,- roe: 23.4,- roa: 9.8,- debtToEquity: 0.52,- currentRatio: 1.12,- eps: 10.18,- revenue: '$85.2B',- revenueGrowth: -1.2,- profitMargin: 16.8,- beta: 0.54,- volume: '$5.6M',- avgVolume: '$6.1M',- week52High: 169.23,- week52Low: 143.45- },- {- ticker: 'XOM',- name: 'Exxon Mobil',- sector: 'Energy',- price: 112.45,- change: -0.89,- changePercent: -0.79,- marketCap: '$456.7B',- pe: 13.8,- ps: 1.2,- pb: 2.1,- forwardPE: 12.6,- peg: 1.5,- dividend: 3.45,- roe: 17.2,- roa: 9.4,- debtToEquity: 0.28,- currentRatio: 1.34,- eps: 8.15,- revenue: '$344.6B',- revenueGrowth: -8.9,- profitMargin: 10.8,- beta: 0.87,- volume: '$12.3M',- avgVolume: '$14.2M',- week52High: 121.34,- week52Low: 95.67- },- {- ticker: 'TSLA',- name: 'Tesla Inc',- sector: 'Consumer Discretionary',- price: 187.92,- change: 3.45,- changePercent: 1.87,- marketCap: '$598.3B',- pe: 58.9,- ps: 7.4,- pb: 12.3,- forwardPE: 48.7,- peg: 2.9,- dividend: 0.00,- roe: 22.4,- roa: 8.9,- debtToEquity: 0.17,- currentRatio: 1.73,- eps: 3.19,- revenue: '$96.8B',- revenueGrowth: 18.8,- profitMargin: 14.4,- beta: 2.01,- volume: '$98.4M',- avgVolume: '$102.3M',- week52High: 299.29,- week52Low: 138.80- },- {- ticker: 'WMT',- name: 'Walmart Inc',- sector: 'Consumer Staples',- price: 178.34,- change: 1.23,- changePercent: 0.69,- marketCap: '$478.9B',- pe: 28.7,- ps: 0.8,- pb: 6.9,- forwardPE: 26.4,- peg: 3.2,- dividend: 1.42,- roe: 21.8,- roa: 6.7,- debtToEquity: 0.56,- currentRatio: 0.79,- eps: 6.21,- revenue: '$648.1B',- revenueGrowth: 5.4,- profitMargin: 2.4,- beta: 0.52,- volume: '$6.8M',- avgVolume: '$7.3M',- week52High: 183.45,- week52Low: 142.67- },- {- ticker: 'BA',- name: 'Boeing Co',- sector: 'Industrials',- price: 189.23,- change: -2.34,- changePercent: -1.22,- marketCap: '$113.4B',- pe: -24.5,- ps: 1.8,- pb: -8.9,- forwardPE: 34.2,- peg: -1.4,- dividend: 0.00,- roe: -28.4,- roa: -3.2,- debtToEquity: 8.45,- currentRatio: 1.12,- eps: -7.72,- revenue: '$77.8B',- revenueGrowth: 10.2,- profitMargin: -8.9,- beta: 1.78,- volume: '$9.8M',- avgVolume: '$11.2M',- week52High: 267.54,- week52Low: 173.12+ const checkApiKey = async () => {+ try {+ const apiKey = await sqliteService.getApiKey('FRED');+ setApiKeyConfigured(!!apiKey);+ } catch (error) {+ console.error('Failed to check FRED API key:', error);+ setApiKeyConfigured(false);+ }+ };++ // Search series+ const searchSeries = async (query: string) => {+ if (!query.trim()) {+ setSearchResults([]);+ return;+ }++ setSearchLoading(true);+ try {+ const apiKey = await sqliteService.getApiKey('FRED');+ if (!apiKey) return;++ const result = await invoke<string>('execute_python_script', {+ scriptName: 'fred_data.py',+ args: ['search', query, '50'],+ env: { FRED_API_KEY: apiKey }+ });++ const parsed = JSON.parse(result);+ if (!parsed.error && parsed.series) {+ setSearchResults(parsed.series);+ } else {+ setSearchResults([]);+ }+ } catch (err) {+ setSearchResults([]);+ } finally {+ setSearchLoading(false);}- ];-- const sectors = ['ALL', 'Technology', 'Financials', 'Healthcare', 'Energy', 'Consumer Discretionary', 'Consumer Staples', 'Industrials'];-- const presetScreens = [- { name: 'Dividend Aristocrats', desc: 'Dividend > 2%, PE < 20' },- { name: 'Growth Stocks', desc: 'Revenue Growth > 20%, PE < 40' },- { name: 'Value Stocks', desc: 'PE < 15, P/B < 3' },- { name: 'Large Cap Tech', desc: 'Market Cap > $100B, Sector: Tech' },- { name: 'High Momentum', desc: 'Beta > 1.5, 52W High < 20%' }- ];-- const parseMarketCap = (mcap: string): number => {- const value = parseFloat(mcap.replace(/[^0-9.]/g, ''));- if (mcap.includes('T')) return value * 1000000;- if (mcap.includes('B')) return value * 1000;- if (mcap.includes('M')) return value;- return value;};- const filteredStocks = stocks.filter(stock => {- const mcap = parseMarketCap(stock.marketCap);+ // Load categories+ const loadCategories = async (categoryId: number = 0) => {+ setCategoryLoading(true);+ try {+ const apiKey = await sqliteService.getApiKey('FRED');+ if (!apiKey) return;- if (filters.marketCapMin && mcap < parseFloat(filters.marketCapMin)) return false;- if (filters.marketCapMax && mcap > parseFloat(filters.marketCapMax)) return false;- if (filters.peMin && stock.pe < parseFloat(filters.peMin)) return false;- if (filters.peMax && stock.pe > parseFloat(filters.peMax)) return false;- if (filters.dividendMin && stock.dividend < parseFloat(filters.dividendMin)) return false;- if (filters.priceMin && stock.price < parseFloat(filters.priceMin)) return false;- if (filters.priceMax && stock.price > parseFloat(filters.priceMax)) return false;- if (filters.sector !== 'ALL' && stock.sector !== filters.sector) return false;+ const result = await invoke<string>('execute_python_script', {+ scriptName: 'fred_data.py',+ args: ['categories', categoryId.toString()],+ env: { FRED_API_KEY: apiKey }+ });- return true;- });+ const parsed = JSON.parse(result);+ if (!parsed.error && parsed.categories) {+ setCategories(parsed.categories);+ } else {+ setCategories([]);+ }+ } catch (err) {+ setCategories([]);+ } finally {+ setCategoryLoading(false);+ }+ };++ // Load series in a category+ const loadCategorySeries = async (categoryId: number) => {+ try {+ const apiKey = await sqliteService.getApiKey('FRED');+ if (!apiKey) return;++ const result = await invoke<string>('execute_python_script', {+ scriptName: 'fred_data.py',+ args: ['category_series', categoryId.toString(), '50'],+ env: { FRED_API_KEY: apiKey }+ });++ const parsed = JSON.parse(result);+ if (!parsed.error && parsed.series) {+ setCategorySeriesResults(parsed.series);+ } else {+ setCategorySeriesResults([]);+ }+ } catch (err) {+ setCategorySeriesResults([]);+ }+ };++ // Navigate to category+ const navigateToCategory = async (cat: {id: number, name: string}) => {+ setCurrentCategory(cat.id);+ setCategoryPath([...categoryPath, cat]);+ setSearchQuery('');+ setSearchResults([]);+ setCategorySeriesResults([]);- const updateFilter = (key: string, value: string) => {- setFilters({ ...filters, [key]: value });+ // Load both subcategories and series+ await Promise.all([+ loadCategories(cat.id),+ loadCategorySeries(cat.id)+ ]);};+ // Navigate back+ const navigateBack = () => {+ if (categoryPath.length > 1) {+ const newPath = categoryPath.slice(0, -1);+ setCategoryPath(newPath);+ const parentId = newPath[newPath.length - 1].id;+ setCurrentCategory(parentId);+ loadCategories(parentId);+ }+ };++ // Open browser modal+ const openBrowser = () => {+ setShowBrowser(true);+ if (categories.length === 0) {+ loadCategories(0);+ }+ };++ // Add series from browser+ const addSeriesFromBrowser = (id: string) => {+ if (!getCurrentSeriesIds().includes(id)) {+ setSeriesIds(prev => prev ? `${prev},${id}` : id);+ }+ };++ const fetchData = async () => {+ setLoading(true);+ setError(null);++ // Use setTimeout to make it non-blocking+ setTimeout(async () => {+ try {+ const apiKey = await sqliteService.getApiKey('FRED');+ if (!apiKey) {+ setError('FRED API key not configured. Please add it in Settings > Credentials.');+ setApiKeyConfigured(false);+ setLoading(false);+ return;+ }++ // Remove duplicates and trim+ const ids = [...new Set(seriesIds.split(',').map(s => s.trim()).filter(Boolean))];++ if (ids.length === 0) {+ setError('Please enter at least one series ID');+ setLoading(false);+ return;+ }++ const args = ['multiple', ...ids, startDate, endDate];++ const result = await invoke<string>('execute_python_script', {+ scriptName: 'fred_data.py',+ args,+ env: { FRED_API_KEY: apiKey }+ });++ const parsed = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ } else {+ setData(parsed);+ }+ } catch (err: any) {+ setError(err.message || 'Failed to fetch data');+ } finally {+ setLoading(false);+ }+ }, 0);+ };++ // Helper to get current series IDs as array+ const getCurrentSeriesIds = () => {+ return seriesIds.split(',').map(s => s.trim()).filter(Boolean);+ };++ const addPopularSeries = (id: string) => {+ if (!getCurrentSeriesIds().includes(id)) {+ setSeriesIds(prev => prev ? `${prev},${id}` : id);+ }+ };++ const prepareChartData = () => {+ if (data.length === 0) return [];++ const allDates = new Set<string>();+ data.forEach(series => {+ series.observations.forEach(obs => allDates.add(obs.date));+ });++ const sortedDates = Array.from(allDates).sort();++ return sortedDates.map(date => {+ const point: any = { date };+ data.forEach(series => {+ const obs = series.observations.find(o => o.date === date);+ point[series.series_id] = obs?.value || null;+ });+ return point;+ });+ };++ const exportToCSV = () => {+ const chartData = prepareChartData();+ const headers = ['Date', ...data.map(s => s.series_id)].join(',');+ const rows = chartData.map(row => {+ return [row.date, ...data.map(s => row[s.series_id] || '')].join(',');+ });+ const csv = [headers, ...rows].join('\n');++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `fred_data_${new Date().toISOString()}.csv`;+ a.click();+ };++ // Memoize current series IDs set for performance+ const currentSeriesIdsSet = useMemo(() => {+ return new Set(getCurrentSeriesIds());+ }, [seriesIds]);++ // Use effect for search debounce+ useEffect(() => {+ const timer = setTimeout(() => {+ if (searchQuery && showBrowser) {+ searchSeries(searchQuery);+ }+ }, 500);+ return () => clearTimeout(timer);+ }, [searchQuery, showBrowser]);+return (- <div style={{- height: '100%',- backgroundColor: COLOR_DARK_BG,- color: COLOR_WHITE,- fontFamily: 'Consolas, monospace',- overflow: 'hidden',- display: 'flex',- flexDirection: 'column',- fontSize: '12px'- }}>- {/* Header */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- borderBottom: `2px solid ${COLOR_GRAY}`,- padding: '8px 16px',- flexShrink: 0- }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '16px' }}>- STOCK SCREENER- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_CYAN }}>ADVANCED FILTERING • TECHNICAL • FUNDAMENTAL</span>- </div>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <span style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>- {filteredStocks.length} matches- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>- {currentTime.toLocaleTimeString()}- </span>- </div>- </div>- </div>+ <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: '#000', overflow: 'hidden' }}>+ <style>{`+ *::-webkit-scrollbar { width: 8px; height: 8px; }+ *::-webkit-scrollbar-track { background: #0a0a0a; }+ *::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 4px; }+ *::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }+ `}</style>- {/* Main Content */}- <div style={{ flex: 1, overflow: 'auto', display: 'flex', gap: '12px', padding: '12px' }}>- {/* Left Panel - Filters */}- <div style={{ width: '320px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Preset Screens */}+ {/* Series Browser Modal */}+ {showBrowser && (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ background: 'rgba(0,0,0,0.9)',+ zIndex: 1000,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '20px'+ }}><div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_PURPLE}`,- padding: '12px'+ background: '#0a0a0a',+ border: '2px solid #ea580c',+ borderRadius: '8px',+ width: '90%',+ maxWidth: '1200px',+ height: '85vh',+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden'}}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- PRESET SCREENS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>- {presetScreens.map((preset, index) => (- <div key={index}- style={{- padding: '10px',- backgroundColor: 'rgba(200,100,255,0.05)',- border: `1px solid ${COLOR_PURPLE}`,- cursor: 'pointer'- }}- onMouseEnter={(e) => {- e.currentTarget.style.backgroundColor = 'rgba(200,100,255,0.15)';- }}- onMouseLeave={(e) => {- e.currentTarget.style.backgroundColor = 'rgba(200,100,255,0.05)';- }}>- <div style={{ color: COLOR_PURPLE, fontWeight: 'bold', fontSize: '11px', marginBottom: '4px' }}>- {preset.name}- </div>- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>- {preset.desc}- </div>- </div>- ))}+ {/* Modal Header */}+ <div style={{+ borderBottom: '2px solid #ea580c',+ padding: '16px 20px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <FolderTree size={20} color="#ea580c" />+ <span style={{ color: '#ea580c', fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>+ FRED SERIES BROWSER+ </span>+ </div>+ <button+ onClick={() => setShowBrowser(false)}+ style={{+ background: 'transparent',+ border: 'none',+ color: '#888',+ cursor: 'pointer',+ padding: '4px'+ }}+ >+ <X size={24} />+ </button></div>- </div>- {/* Price Filters */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_GREEN}`,- padding: '12px'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- PRICE FILTERS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Min Price ($)- </label>- <input- type="number"- value={filters.priceMin}- onChange={(e) => updateFilter('priceMin', e.target.value)}- style={{- width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace'- }}- />- </div>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Max Price ($)- </label>+ {/* Search Bar */}+ <div style={{ padding: '16px 20px', borderBottom: '1px solid #1a1a1a' }}>+ <div style={{ position: 'relative' }}>+ <Search size={16} color="#666" style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)' }} /><input- type="number"- value={filters.priceMax}- onChange={(e) => updateFilter('priceMax', e.target.value)}+ type="text"+ placeholder="Search FRED series by keyword (e.g., 'unemployment', 'inflation', 'GDP')..."+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}style={{width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,+ background: '#000',+ border: '1px solid #2a2a2a',+ color: '#fff',+ padding: '12px 12px 12px 40px',fontSize: '11px',- fontFamily: 'Consolas, monospace'+ borderRadius: '4px'}}/>+ {searchLoading && (+ <Loader2 size={16} className="animate-spin" style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)', color: '#ea580c' }} />+ )}</div></div>- </div>- {/* Valuation Filters */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_YELLOW}`,- padding: '12px'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- VALUATION FILTERS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Min P/E Ratio- </label>- <input- type="number"- value={filters.peMin}- onChange={(e) => updateFilter('peMin', e.target.value)}- style={{- width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace'- }}- />- </div>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Max P/E Ratio- </label>- <input- type="number"- value={filters.peMax}- onChange={(e) => updateFilter('peMax', e.target.value)}- style={{- width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace'- }}- />- </div>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Min Dividend Yield (%)- </label>- <input- type="number"- value={filters.dividendMin}- onChange={(e) => updateFilter('dividendMin', e.target.value)}- style={{- width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace'- }}- />+ {/* Content Area */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Left Panel - Categories or Popular */}+ {!searchQuery && (+ <div style={{+ width: '350px',+ borderRight: '1px solid #1a1a1a',+ display: 'flex',+ flexDirection: 'column',+ background: '#050505'+ }}>+ {/* Breadcrumb */}+ <div style={{+ padding: '12px 16px',+ borderBottom: '1px solid #1a1a1a',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ {categoryPath.length > 1 && (+ <button+ onClick={navigateBack}+ style={{+ background: '#0a0a0a',+ border: '1px solid #2a2a2a',+ color: '#ea580c',+ padding: '4px 8px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <ArrowLeft size={12} />+ BACK+ </button>+ )}+ <span style={{ color: '#888', fontSize: '10px', flex: 1 }}>+ {categoryPath.map((p, i) => (+ <span key={`${p.id}-${i}`}>+ {i > 0 && ' > '}+ {p.name}+ </span>+ ))}+ </span>+ </div>++ {/* Popular Categories (only at root) */}+ {currentCategory === 0 && (+ <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a', maxHeight: '200px', overflowY: 'auto' }}>+ <h4 style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px', fontWeight: 'bold' }}>+ POPULAR CATEGORIES+ </h4>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>+ {POPULAR_CATEGORIES.map((cat, idx) => (+ <button+ key={`pop-${cat.id}-${idx}`}+ onClick={() => navigateToCategory({ id: cat.id, name: cat.name.replace(/[^\w\s]/gi, '').trim() })}+ style={{+ background: '#0a0a0a',+ border: '1px solid #2a2a2a',+ color: '#fff',+ padding: '6px 8px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ textAlign: 'left',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontWeight: 'bold', marginBottom: '2px', fontSize: '9px' }}>{cat.name}</div>+ </div>+ <ChevronRight size={12} color="#666" />+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Category List */}+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>+ <h4 style={{ color: '#888', fontSize: '9px', marginBottom: '8px', fontWeight: 'bold' }}>+ {categoryLoading ? 'LOADING...' : `SUBCATEGORIES (${categories.length})`}+ </h4>+ {categories.length === 0 && !categoryLoading && currentCategory !== 0 && (+ <p style={{ color: '#666', fontSize: '10px' }}>No subcategories found</p>+ )}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>+ {categories.map((cat, idx) => (+ <button+ key={`cat-${cat.id}-${idx}`}+ onClick={() => navigateToCategory(cat)}+ style={{+ background: '#0a0a0a',+ border: '1px solid #2a2a2a',+ color: '#fff',+ padding: '8px 10px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ textAlign: 'left',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}+ >+ <span>{cat.name}</span>+ <ChevronRight size={12} color="#666" />+ </button>+ ))}+ </div>+ </div>+ </div>+ )}++ {/* Right Panel - Search Results or Series in Category */}+ <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px' }}>+ {searchQuery ? (+ // Search Results+ <>+ <h3 style={{ color: '#ea580c', fontSize: '11px', marginBottom: '12px', fontWeight: 'bold' }}>+ SEARCH RESULTS ({searchResults.length})+ </h3>+ {searchResults.length === 0 && !searchLoading && (+ <p style={{ color: '#666', fontSize: '10px' }}>No results found</p>+ )}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {searchResults.map((result) => (+ <div+ key={result.id}+ style={{+ background: '#0a0a0a',+ border: '1px solid #1a1a1a',+ borderRadius: '4px',+ padding: '12px',+ display: 'flex',+ alignItems: 'flex-start',+ justifyContent: 'space-between',+ gap: '12px'+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>+ <span style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', fontFamily: 'monospace' }}>+ {result.id}+ </span>+ <span style={{ color: '#666', fontSize: '9px' }}>+ Pop: {result.popularity}+ </span>+ </div>+ <p style={{ color: '#fff', fontSize: '10px', marginBottom: '4px' }}>+ {result.title}+ </p>+ <div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: '#666' }}>+ <span>Freq: {result.frequency}</span>+ <span>Units: {result.units}</span>+ <span>Updated: {result.last_updated.split('T')[0]}</span>+ </div>+ </div>+ <button+ onClick={() => addSeriesFromBrowser(result.id)}+ disabled={currentSeriesIdsSet.has(result.id)}+ style={{+ background: currentSeriesIdsSet.has(result.id) ? '#1a3a1a' : '#ea580c',+ border: 'none',+ color: '#fff',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: currentSeriesIdsSet.has(result.id) ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ fontWeight: 'bold',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ whiteSpace: 'nowrap',+ opacity: currentSeriesIdsSet.has(result.id) ? 0.5 : 1+ }}+ >+ <Plus size={12} />+ {currentSeriesIdsSet.has(result.id) ? 'ADDED' : 'ADD'}+ </button>+ </div>+ ))}+ </div>+ </>+ ) : categorySeriesResults.length > 0 ? (+ // Category Series Results+ <>+ <h3 style={{ color: '#ea580c', fontSize: '11px', marginBottom: '12px', fontWeight: 'bold' }}>+ SERIES IN THIS CATEGORY ({categorySeriesResults.length})+ </h3>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {categorySeriesResults.map((result) => (+ <div+ key={result.id}+ style={{+ background: '#0a0a0a',+ border: '1px solid #1a1a1a',+ borderRadius: '4px',+ padding: '12px',+ display: 'flex',+ alignItems: 'flex-start',+ justifyContent: 'space-between',+ gap: '12px'+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>+ <span style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', fontFamily: 'monospace' }}>+ {result.id}+ </span>+ <span style={{ color: '#666', fontSize: '9px' }}>+ Pop: {result.popularity}+ </span>+ </div>+ <p style={{ color: '#fff', fontSize: '10px', marginBottom: '4px' }}>+ {result.title}+ </p>+ <div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: '#666' }}>+ <span>Freq: {result.frequency}</span>+ <span>Units: {result.units}</span>+ <span>Updated: {result.last_updated.split('T')[0]}</span>+ </div>+ </div>+ <button+ onClick={() => addSeriesFromBrowser(result.id)}+ disabled={currentSeriesIdsSet.has(result.id)}+ style={{+ background: currentSeriesIdsSet.has(result.id) ? '#1a3a1a' : '#ea580c',+ border: 'none',+ color: '#fff',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: currentSeriesIdsSet.has(result.id) ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ fontWeight: 'bold',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ whiteSpace: 'nowrap',+ opacity: currentSeriesIdsSet.has(result.id) ? 0.5 : 1+ }}+ >+ <Plus size={12} />+ {currentSeriesIdsSet.has(result.id) ? 'ADDED' : 'ADD'}+ </button>+ </div>+ ))}+ </div>+ </>+ ) : (+ // Instructions or Category Info+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}>+ <TrendingUp size={48} color="#333" />+ <div style={{ textAlign: 'center', maxWidth: '500px' }}>+ <p style={{ color: '#888', fontSize: '12px', marginBottom: '8px' }}>+ <strong>Search for any economic data series</strong>+ </p>+ <p style={{ color: '#666', fontSize: '10px', lineHeight: '1.5' }}>+ Try searching for terms like "unemployment", "inflation", "GDP", "interest rates", "housing", etc.+ Or browse through categories on the left to discover available data series.+ </p>+ </div>+ </div>+ )}</div></div>- </div>- {/* Market Cap Filter */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_CYAN}`,- padding: '12px'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- MARKET CAP ($M)- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Min Market Cap- </label>- <input- type="number"- value={filters.marketCapMin}- onChange={(e) => updateFilter('marketCapMin', e.target.value)}- style={{- width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace'- }}- />- </div>- <div>- <label style={{ color: COLOR_GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>- Max Market Cap- </label>- <input- type="number"- value={filters.marketCapMax}- onChange={(e) => updateFilter('marketCapMax', e.target.value)}- style={{- width: '100%',- padding: '6px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace'- }}- />- </div>+ {/* Modal Footer */}+ <div style={{+ borderTop: '1px solid #1a1a1a',+ padding: '12px 20px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ background: '#0a0a0a'+ }}>+ <span style={{ color: '#666', fontSize: '9px' }}>+ Federal Reserve Economic Data (FRED) | 800,000+ series available+ </span>+ <button+ onClick={() => setShowBrowser(false)}+ style={{+ background: '#ea580c',+ border: 'none',+ color: '#fff',+ padding: '8px 16px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ fontWeight: 'bold'+ }}+ >+ DONE+ </button></div></div>+ </div>+ )}- {/* Sector Filter */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_BLUE}`,- padding: '12px'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- SECTOR- </div>- <select- value={filters.sector}- onChange={(e) => updateFilter('sector', e.target.value)}+ {/* Header */}+ <div style={{+ borderBottom: '2px solid #ea580c',+ padding: '12px 16px',+ background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexShrink: 0+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <BarChart3 size={20} color="#ea580c" />+ <span style={{ color: '#ea580c', fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>+ FRED DATA EXPLORER+ </span>+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => setChartType(chartType === 'line' ? 'area' : 'line')}+ style={{+ background: '#0a0a0a',+ border: '1px solid #2a2a2a',+ color: '#ea580c',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ fontWeight: 'bold'+ }}+ >+ {chartType === 'line' ? 'AREA' : 'LINE'}+ </button>+ <button+ onClick={exportToCSV}+ disabled={data.length === 0}+ style={{+ background: '#0a0a0a',+ border: '1px solid #2a2a2a',+ color: data.length > 0 ? '#00ff00' : '#666',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: data.length > 0 ? 'pointer' : 'not-allowed',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontWeight: 'bold'+ }}+ >+ <Download size={12} />+ CSV+ </button>+ </div>+ </div>++ {/* API Key Warning */}+ {!apiKeyConfigured && (+ <div style={{+ background: '#3a1a0a',+ border: '1px solid #ea580c',+ padding: '12px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ flexShrink: 0+ }}>+ <AlertCircle size={20} color="#ea580c" />+ <div style={{ flex: 1 }}>+ <p style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>+ FRED API Key Required+ </p>+ <p style={{ color: '#888', fontSize: '10px' }}>+ Please add your FRED API key in Settings → Credentials to use this feature. Get your free key at <span style={{ color: '#ea580c' }}>research.stlouisfed.org/useraccount/apikey</span>+ </p>+ </div>+ </div>+ )}++ {/* Query Panel */}+ <div style={{+ borderBottom: '1px solid #1a1a1a',+ padding: '16px',+ background: '#0a0a0a',+ flexShrink: 0+ }}>+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: '12px', marginBottom: '12px' }}>+ <div>+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ FRED SERIES IDs (comma-separated)+ </label>+ <input+ type="text"+ value={seriesIds}+ onChange={(e) => setSeriesIds(e.target.value)}+ placeholder="GDP,UNRATE,CPIAUCSL"style={{width: '100%',+ background: '#000',+ border: '1px solid #2a2a2a',+ color: '#fff',padding: '8px',- backgroundColor: COLOR_DARK_BG,- border: `2px solid ${COLOR_GRAY}`,- color: COLOR_CYAN,- fontSize: '11px',- fontFamily: 'Consolas, monospace',- fontWeight: 'bold'- }}>- {sectors.map(sector => (- <option key={sector} value={sector}>{sector}</option>- ))}- </select>+ fontSize: '10px',+ borderRadius: '3px'+ }}+ />+ </div>+ <div>+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ START DATE+ </label>+ <input+ type="date"+ value={startDate}+ onChange={(e) => setStartDate(e.target.value)}+ style={{+ width: '100%',+ background: '#000',+ border: '1px solid #2a2a2a',+ color: '#fff',+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ />+ </div>+ <div>+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ END DATE+ </label>+ <input+ type="date"+ value={endDate}+ onChange={(e) => setEndDate(e.target.value)}+ style={{+ width: '100%',+ background: '#000',+ border: '1px solid #2a2a2a',+ color: '#fff',+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ /></div>-- {/* Clear Filters Button */}<button- onClick={() => setFilters({- marketCapMin: '',- marketCapMax: '',- peMin: '',- peMax: '',- dividendMin: '',- priceMin: '',- priceMax: '',- sector: 'ALL',- volumeMin: ''- })}+ onClick={fetchData}+ disabled={loading}style={{- padding: '12px',- backgroundColor: COLOR_RED,+ background: '#ea580c',border: 'none',- color: COLOR_DARK_BG,- fontSize: '12px',+ color: '#fff',+ padding: '0 20px',+ fontSize: '10px',+ cursor: loading ? 'not-allowed' : 'pointer',+ borderRadius: '3px',fontWeight: 'bold',- cursor: 'pointer',- fontFamily: 'Consolas, monospace'- }}>- CLEAR ALL FILTERS+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ alignSelf: 'end',+ opacity: loading ? 0.5 : 1+ }}+ >+ {loading ? <Loader2 size={14} className="animate-spin" /> : <Search size={14} />}+ {loading ? 'LOADING' : 'FETCH'}</button></div>- {/* Right Panel - Results */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>+ {/* Popular Series Quick Add & Browse Button */}+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: '12px' }}>+ <div style={{ flex: 1 }}>+ <label style={{ color: '#888', fontSize: '9px', marginBottom: '6px', display: 'block' }}>+ QUICK ADD:+ </label>+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>+ {POPULAR_SERIES.map(series => (+ <button+ key={series.id}+ onClick={() => addPopularSeries(series.id)}+ style={{+ background: currentSeriesIdsSet.has(series.id) ? '#1a3a1a' : '#0a0a0a',+ border: `1px solid ${currentSeriesIdsSet.has(series.id) ? '#00ff00' : '#2a2a2a'}`,+ color: currentSeriesIdsSet.has(series.id) ? '#00ff00' : '#666',+ padding: '4px 8px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px'+ }}+ >+ {series.id}+ </button>+ ))}+ </div>+ </div>+ <button+ onClick={openBrowser}+ disabled={!apiKeyConfigured}+ style={{+ background: 'linear-gradient(135deg, #ea580c 0%, #c2410c 100%)',+ border: '1px solid #ea580c',+ color: '#fff',+ padding: '8px 16px',+ fontSize: '10px',+ cursor: apiKeyConfigured ? 'pointer' : 'not-allowed',+ borderRadius: '3px',+ fontWeight: 'bold',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ whiteSpace: 'nowrap',+ opacity: apiKeyConfigured ? 1 : 0.5,+ boxShadow: apiKeyConfigured ? '0 2px 8px rgba(234, 88, 12, 0.3)' : 'none'+ }}+ >+ <FolderTree size={14} />+ BROWSE ALL SERIES+ </button>+ </div>+ </div>++ {/* Main Content */}+ <div style={{ flex: 1, display: 'flex', gap: '16px', padding: '16px', overflow: 'hidden', minHeight: 0 }}>++ {/* Chart Section */}+ <div style={{ flex: 2, display: 'flex', flexDirection: 'column', minWidth: 0 }}><div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- flex: 1,- overflow: 'auto'+ background: '#0a0a0a',+ border: '1px solid #1a1a1a',+ borderRadius: '4px',+ padding: '16px',+ height: '100%',+ display: 'flex',+ flexDirection: 'column'}}>- {/* Table Header */}- <div style={{- display: 'grid',- gridTemplateColumns: '80px 180px 120px 90px 90px 100px 70px 70px 80px 80px 80px 80px',- padding: '10px 12px',- backgroundColor: 'rgba(255,165,0,0.1)',- borderBottom: `2px solid ${COLOR_ORANGE}`,- position: 'sticky',- top: 0,- zIndex: 10,- fontSize: '10px'- }}>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>TICKER</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>NAME</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>SECTOR</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>PRICE</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>CHANGE</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>MKT CAP</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>P/E</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>P/B</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>DIV%</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>ROE%</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>REV GR%</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>BETA</div>- </div>+ <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>+ TIME SERIES CHART+ </h3>- {/* Table Body */}- {filteredStocks.map((stock, index) => (- <div key={index}- style={{- display: 'grid',- gridTemplateColumns: '80px 180px 120px 90px 90px 100px 70px 70px 80px 80px 80px 80px',- padding: '10px 12px',- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',- borderBottom: `1px solid ${COLOR_GRAY}`,- cursor: 'pointer',- fontSize: '11px'- }}- onMouseEnter={(e) => {- e.currentTarget.style.backgroundColor = 'rgba(255,165,0,0.1)';- }}- onMouseLeave={(e) => {- e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent';- }}>- <div style={{ color: COLOR_CYAN, fontWeight: 'bold' }}>{stock.ticker}</div>- <div style={{ color: COLOR_WHITE }}>{stock.name}</div>- <div style={{ color: COLOR_BLUE }}>{stock.sector}</div>- <div style={{ color: COLOR_WHITE, fontWeight: 'bold' }}>${stock.price.toFixed(2)}</div>- <div style={{ color: stock.change > 0 ? COLOR_GREEN : COLOR_RED }}>- {stock.change > 0 ? '+' : ''}{stock.change.toFixed(2)} ({stock.changePercent.toFixed(2)}%)- </div>- <div style={{ color: COLOR_PURPLE }}>{stock.marketCap}</div>- <div style={{ color: stock.pe > 0 ? COLOR_YELLOW : COLOR_RED }}>- {stock.pe > 0 ? stock.pe.toFixed(1) : 'N/A'}- </div>- <div style={{ color: COLOR_CYAN }}>{stock.pb.toFixed(1)}</div>- <div style={{ color: stock.dividend > 0 ? COLOR_GREEN : COLOR_GRAY }}>- {stock.dividend > 0 ? stock.dividend.toFixed(2) : '-'}- </div>- <div style={{ color: stock.roe > 0 ? COLOR_GREEN : COLOR_RED }}>- {stock.roe.toFixed(1)}- </div>- <div style={{ color: stock.revenueGrowth > 0 ? COLOR_GREEN : COLOR_RED }}>- {stock.revenueGrowth > 0 ? '+' : ''}{stock.revenueGrowth.toFixed(1)}- </div>- <div style={{ color: COLOR_ORANGE }}>{stock.beta.toFixed(2)}</div>+ {error && (+ <div style={{+ background: '#3a0a0a',+ border: '1px solid #ff0000',+ color: '#ff0000',+ padding: '12px',+ borderRadius: '3px',+ fontSize: '10px',+ marginBottom: '12px'+ }}>+ {error}+ </div>+ )}++ {data.length === 0 && !loading && !error && (+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: '#666',+ fontSize: '11px',+ flexDirection: 'column',+ gap: '8px'+ }}>+ <TrendingUp size={40} color="#333" />+ <p>Enter series IDs and click FETCH to visualize data</p>+ </div>+ )}++ {data.length > 0 && (+ <div style={{ flex: 1, minHeight: 0 }}>+ <ResponsiveContainer width="100%" height="100%">+ {chartType === 'line' ? (+ <LineChart data={prepareChartData()} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#1a1a1a" />+ <XAxis dataKey="date" stroke="#666" style={{ fontSize: '10px' }} />+ <YAxis stroke="#666" style={{ fontSize: '10px' }} />+ <Tooltip+ contentStyle={{ background: '#0a0a0a', border: '1px solid #2a2a2a', borderRadius: '3px', fontSize: '10px' }}+ labelStyle={{ color: '#ea580c' }}+ />+ <Legend wrapperStyle={{ fontSize: '10px' }} />+ {data.map((series, idx) => (+ <Line+ key={series.series_id}+ type="monotone"+ dataKey={series.series_id}+ stroke={['#ea580c', '#00ff00', '#00ffff', '#ff00ff', '#ffff00'][idx % 5]}+ strokeWidth={2}+ dot={false}+ />+ ))}+ </LineChart>+ ) : (+ <AreaChart data={prepareChartData()} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#1a1a1a" />+ <XAxis dataKey="date" stroke="#666" style={{ fontSize: '10px' }} />+ <YAxis stroke="#666" style={{ fontSize: '10px' }} />+ <Tooltip+ contentStyle={{ background: '#0a0a0a', border: '1px solid #2a2a2a', borderRadius: '3px', fontSize: '10px' }}+ labelStyle={{ color: '#ea580c' }}+ />+ <Legend wrapperStyle={{ fontSize: '10px' }} />+ {data.map((series, idx) => (+ <Area+ key={series.series_id}+ type="monotone"+ dataKey={series.series_id}+ stroke={['#ea580c', '#00ff00', '#00ffff', '#ff00ff', '#ffff00'][idx % 5]}+ fill={['#ea580c33', '#00ff0033', '#00ffff33', '#ff00ff33', '#ffff0033'][idx % 5]}+ />+ ))}+ </AreaChart>+ )}+ </ResponsiveContainer></div>- ))}+ )}</div></div>++ {/* Data Table */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflowY: 'auto' }}>+ {data.map(series => (+ <div+ key={series.series_id}+ style={{+ background: '#0a0a0a',+ border: '1px solid #1a1a1a',+ borderRadius: '4px',+ padding: '12px',+ marginBottom: '12px',+ flexShrink: 0+ }}+ >+ <div style={{ borderBottom: '1px solid #1a1a1a', paddingBottom: '8px', marginBottom: '8px' }}>+ <h4 style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>+ {series.series_id}+ </h4>+ <p style={{ color: '#888', fontSize: '9px', marginBottom: '4px' }}>{series.title}</p>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', fontSize: '9px', color: '#666' }}>+ <span>Units: {series.units}</span>+ <span>Freq: {series.frequency}</span>+ <span>Observations: {series.observation_count}</span>+ <span>Updated: {series.last_updated.split('T')[0]}</span>+ </div>+ </div>++ <div style={{ maxHeight: '200px', overflowY: 'auto' }}>+ <table style={{ width: '100%', fontSize: '9px', borderCollapse: 'collapse' }}>+ <thead style={{ position: 'sticky', top: 0, background: '#0a0a0a' }}>+ <tr style={{ borderBottom: '1px solid #1a1a1a' }}>+ <th style={{ color: '#888', textAlign: 'left', padding: '4px' }}>Date</th>+ <th style={{ color: '#888', textAlign: 'right', padding: '4px' }}>Value</th>+ </tr>+ </thead>+ <tbody>+ {series.observations.slice(-20).reverse().map((obs, idx) => (+ <tr key={idx} style={{ borderBottom: '1px solid #0a0a0a' }}>+ <td style={{ color: '#666', padding: '4px' }}>{obs.date}</td>+ <td style={{ color: '#fff', textAlign: 'right', padding: '4px', fontFamily: 'monospace' }}>+ {obs.value.toFixed(2)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ ))}+ </div></div>{/* Footer */}<div style={{- borderTop: `3px solid ${COLOR_ORANGE}`,- backgroundColor: COLOR_PANEL_BG,- padding: '12px 16px',- fontSize: '11px',- color: COLOR_WHITE,+ borderTop: '1px solid #1a1a1a',+ padding: '8px 16px',+ background: '#0a0a0a',+ fontSize: '9px',+ color: '#666',+ display: 'flex',+ justifyContent: 'space-between',flexShrink: 0}}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '13px' }}>- STOCK SCREENER v1.0- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_CYAN }}>- Advanced filtering & analysis- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GREEN }}>- {filteredStocks.length} stocks found- </span>- </div>- </div>- <div style={{- display: 'flex',- justifyContent: 'space-between',- fontSize: '10px',- paddingTop: '8px',- borderTop: `1px solid ${COLOR_GRAY}`- }}>- <div style={{ display: 'flex', gap: '16px' }}>- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F1</span> Help</span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F2</span> Save Screen</span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F3</span> Export Results</span>- </div>- <div style={{ color: COLOR_GRAY }}>- © 2025 Fincept Labs • All Rights Reserved- </div>- </div>+ <span>FRED Economic Data | Federal Reserve Bank of St. Louis</span>+ <span>{data.length} series loaded | {data.reduce((acc, s) => acc + s.observation_count, 0)} total observations</span></div></div>);-};--export default ScreenerTab;\ No newline at end of file+}diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsxindex f33fcf502..2b0a38ad4 100644--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx@@ -1,5 +1,5 @@import React, { useState, useEffect } from 'react';-import { Eye, EyeOff, Plus, Trash2, Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, ChevronDown, Edit3 } from 'lucide-react';+import { Eye, EyeOff, Plus, Trash2, Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, Edit3 } from 'lucide-react';import { sqliteService, type Credential, type LLMConfig, type LLMGlobalSettings } from '@/services/sqliteService';import { ollamaService } from '@/services/ollamaService';@@ -26,50 +26,12 @@ export default function SettingsTab() {const [ollamaError, setOllamaError] = useState<string | null>(null);const [useManualEntry, setUseManualEntry] = useState(false);- // New credential form- const [newCredential, setNewCredential] = useState<Credential>({+ // New API key form+ const [newApiKey, setNewApiKey] = useState({service_name: '',- username: '',- password: '',- api_key: '',- api_secret: '',- additional_data: ''+ api_key: ''});- // Mock user profile data- const [userProfile, setUserProfile] = useState({- full_name: 'John Doe',- email: '[email protected]',- account_type: 'Professional',- subscription_status: 'Active',- subscription_expiry: '2025-12-31',- api_calls_today: 1247,- api_limit: 10000,- storage_used: '2.4 GB',- storage_limit: '50 GB'- });-- // Mock terminal settings- const [terminalSettings, setTerminalSettings] = useState({- theme: 'dark',- font_size: '11',- auto_refresh: true,- refresh_interval: '5',- show_tooltips: true,- enable_animations: true,- data_compression: false,- cache_enabled: true- });-- // Mock notification settings- const [notificationSettings, setNotificationSettings] = useState({- email_alerts: true,- price_alerts: true,- news_alerts: false,- trade_confirmations: true,- system_updates: true,- marketing_emails: false- });useEffect(() => {initDB();@@ -131,32 +93,33 @@ export default function SettingsTab() {}};- const handleSaveCredential = async () => {- if (!newCredential.service_name || !newCredential.username || !newCredential.password) {- showMessage('error', 'Service name, username, and password are required');+ const handleSaveApiKey = async () => {+ if (!newApiKey.service_name || !newApiKey.api_key) {+ showMessage('error', 'Service name and API key are required');return;}try {setLoading(true);- const result = await sqliteService.saveCredential(newCredential);+ const credential: Credential = {+ service_name: newApiKey.service_name,+ username: 'api',+ password: 'key',+ api_key: newApiKey.api_key,+ api_secret: '',+ additional_data: ''+ };+ const result = await sqliteService.saveCredential(credential);if (result.success) {showMessage('success', result.message);- setNewCredential({- service_name: '',- username: '',- password: '',- api_key: '',- api_secret: '',- additional_data: ''- });+ setNewApiKey({ service_name: '', api_key: '' });await loadCredentials();} else {showMessage('error', result.message);}} catch (error) {- showMessage('error', 'Failed to save credential');+ showMessage('error', 'Failed to save API key');} finally {setLoading(false);}@@ -248,10 +211,6 @@ export default function SettingsTab() {setTimeout(() => setMessage(null), 5000);};- const handleSaveSettings = async (section: string) => {- showMessage('success', `${section} settings saved successfully`);- };-const getCurrentLLMConfig = () => llmConfigs.find(c => c.provider === activeProvider);return (@@ -359,14 +318,14 @@ export default function SettingsTab() {<div><div style={{ marginBottom: '24px' }}><h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>- CREDENTIAL MANAGEMENT+ API KEY MANAGEMENT</h2><p style={{ color: '#888', fontSize: '10px' }}>- Securely store API keys, passwords, and authentication tokens. All data is encrypted and stored locally in SQLite.+ Store API keys for services like FRED, Alpha Vantage, etc. All data is encrypted and stored locally.</p></div>- {/* Add New Credential */}+ {/* Add New API Key */}<div style={{background: '#0a0a0a',border: '1px solid #1a1a1a',@@ -375,99 +334,19 @@ export default function SettingsTab() {borderRadius: '4px'}}><h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>- Add New Credential+ Add New API Key</h3>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr auto', gap: '12px', alignItems: 'end' }}><div><label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>SERVICE NAME *</label><inputtype="text"- value={newCredential.service_name}- onChange={(e) => setNewCredential({ ...newCredential, service_name: e.target.value })}- placeholder="e.g., Fyers, Zerodha, Alpha Vantage"- style={{- width: '100%',- background: '#000',- border: '1px solid #2a2a2a',- color: '#fff',- padding: '8px',- fontSize: '10px',- borderRadius: '3px'- }}- />- </div>- <div>- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>- USERNAME *- </label>- <input- type="text"- value={newCredential.username}- onChange={(e) => setNewCredential({ ...newCredential, username: e.target.value })}- placeholder="Username or Client ID"- style={{- width: '100%',- background: '#000',- border: '1px solid #2a2a2a',- color: '#fff',- padding: '8px',- fontSize: '10px',- borderRadius: '3px'- }}- />- </div>- <div>- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>- PASSWORD *- </label>- <input- type="password"- value={newCredential.password}- onChange={(e) => setNewCredential({ ...newCredential, password: e.target.value })}- placeholder="Password or Secret"- style={{- width: '100%',- background: '#000',- border: '1px solid #2a2a2a',- color: '#fff',- padding: '8px',- fontSize: '10px',- borderRadius: '3px'- }}- />- </div>- <div>- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>- API KEY (Optional)- </label>- <input- type="text"- value={newCredential.api_key}- onChange={(e) => setNewCredential({ ...newCredential, api_key: e.target.value })}- placeholder="API Key"- style={{- width: '100%',- background: '#000',- border: '1px solid #2a2a2a',- color: '#fff',- padding: '8px',- fontSize: '10px',- borderRadius: '3px'- }}- />- </div>- <div>- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>- API SECRET (Optional)- </label>- <input- type="password"- value={newCredential.api_secret}- onChange={(e) => setNewCredential({ ...newCredential, api_secret: e.target.value })}- placeholder="API Secret"+ value={newApiKey.service_name}+ onChange={(e) => setNewApiKey({ ...newApiKey, service_name: e.target.value })}+ placeholder="e.g., FRED, AlphaVantage"style={{width: '100%',background: '#000',@@ -481,13 +360,13 @@ export default function SettingsTab() {</div><div><label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>- ADDITIONAL DATA (Optional)+ API KEY *</label><inputtype="text"- value={newCredential.additional_data}- onChange={(e) => setNewCredential({ ...newCredential, additional_data: e.target.value })}- placeholder="JSON or any extra data"+ value={newApiKey.api_key}+ onChange={(e) => setNewApiKey({ ...newApiKey, api_key: e.target.value })}+ placeholder="Your API key"style={{width: '100%',background: '#000',@@ -499,35 +378,35 @@ export default function SettingsTab() {}}/></div>+ <button+ onClick={handleSaveApiKey}+ disabled={loading}+ style={{+ background: '#ea580c',+ color: '#fff',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: loading ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.5 : 1,+ whiteSpace: 'nowrap'+ }}+ >+ <Plus size={14} />+ {loading ? 'SAVING...' : 'ADD'}+ </button></div>-- <button- onClick={handleSaveCredential}- disabled={loading}- style={{- background: '#ea580c',- color: '#fff',- border: 'none',- padding: '8px 16px',- fontSize: '10px',- fontWeight: 'bold',- cursor: loading ? 'not-allowed' : 'pointer',- borderRadius: '3px',- display: 'flex',- alignItems: 'center',- gap: '6px',- opacity: loading ? 0.5 : 1- }}- >- <Plus size={14} />- {loading ? 'SAVING...' : 'ADD CREDENTIAL'}- </button></div>- {/* Saved Credentials List */}+ {/* Saved API Keys List */}<div><h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>- Saved Credentials ({credentials.length})+ Saved API Keys ({credentials.length})</h3>{credentials.length === 0 ? (@@ -539,7 +418,7 @@ export default function SettingsTab() {borderRadius: '4px'}}><Lock size={32} color="#333" style={{ margin: '0 auto 12px' }} />- <p style={{ color: '#666', fontSize: '11px' }}>No credentials saved yet</p>+ <p style={{ color: '#666', fontSize: '11px' }}>No API keys saved yet</p></div>) : (<div style={{ display: 'grid', gap: '12px' }}>@@ -550,46 +429,20 @@ export default function SettingsTab() {background: '#0a0a0a',border: '1px solid #1a1a1a',padding: '16px',- borderRadius: '4px'+ borderRadius: '4px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'}}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '12px' }}>- <div>- <h4 style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>- {cred.service_name}- </h4>- <p style={{ color: '#666', fontSize: '9px' }}>- Created: {cred.created_at ? new Date(cred.created_at).toLocaleDateString() : 'N/A'}- </p>- </div>- <button- onClick={() => cred.id && handleDeleteCredential(cred.id)}- style={{- background: 'transparent',- border: '1px solid #ff0000',- color: '#ff0000',- padding: '4px 8px',- fontSize: '9px',- cursor: 'pointer',- borderRadius: '3px',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Trash2 size={12} />- DELETE- </button>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '8px', fontSize: '10px' }}>- <span style={{ color: '#888' }}>Username:</span>- <span style={{ color: '#fff' }}>{cred.username}</span>-- <span style={{ color: '#888' }}>Password:</span>+ <div style={{ flex: 1 }}>+ <h4 style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>+ {cred.service_name}+ </h4><div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: '#fff', fontFamily: 'monospace' }}>- {showPasswords[cred.id!] ? cred.password : '•'.repeat(12)}+ <span style={{ color: '#888', fontSize: '9px' }}>API Key:</span>+ <span style={{ color: '#fff', fontFamily: 'monospace', fontSize: '10px' }}>+ {showPasswords[cred.id!] ? cred.api_key : '•'.repeat(20)}</span><buttononClick={() => cred.id && togglePasswordVisibility(cred.id)}@@ -604,30 +457,28 @@ export default function SettingsTab() {{showPasswords[cred.id!] ? <EyeOff size={14} color="#888" /> : <Eye size={14} color="#888" />}</button></div>-- {cred.api_key && (- <>- <span style={{ color: '#888' }}>API Key:</span>- <span style={{ color: '#fff', fontFamily: 'monospace', wordBreak: 'break-all' }}>{cred.api_key}</span>- </>- )}-- {cred.api_secret && (- <>- <span style={{ color: '#888' }}>API Secret:</span>- <span style={{ color: '#fff', fontFamily: 'monospace' }}>- {showPasswords[cred.id!] ? cred.api_secret : '•'.repeat(12)}- </span>- </>- )}-- {cred.additional_data && (- <>- <span style={{ color: '#888' }}>Additional:</span>- <span style={{ color: '#fff', fontSize: '9px', wordBreak: 'break-all' }}>{cred.additional_data}</span>- </>- )}+ <p style={{ color: '#666', fontSize: '9px', marginTop: '4px' }}>+ Added: {cred.created_at ? new Date(cred.created_at).toLocaleDateString() : 'N/A'}+ </p></div>+ <button+ onClick={() => cred.id && handleDeleteCredential(cred.id)}+ style={{+ background: 'transparent',+ border: '1px solid #ff0000',+ color: '#ff0000',+ padding: '4px 8px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Trash2 size={12} />+ DELETE+ </button></div>))}</div>diff --git a/fincept-terminal-desktop/src/constants/version.ts b/fincept-terminal-desktop/src/constants/version.tsnew file mode 100644index 000000000..ac3bb84af--- /dev/null+++ b/fincept-terminal-desktop/src/constants/version.ts@@ -0,0 +1,21 @@+// Application version constants+// This file is the single source of truth for the app version displayed in the UI+// The build version comes from tauri.conf.json++export const APP_VERSION = '3.0.0';+export const APP_NAME = 'Fincept Terminal';+export const APP_BUILD_DATE = new Date().toISOString().split('T')[0];++// Full version string with build date+export const getFullVersionString = (): string => {+ return `${APP_NAME} v${APP_VERSION}`;+};++// Version info object for about screens+export const VERSION_INFO = {+ version: APP_VERSION,+ name: APP_NAME,+ buildDate: APP_BUILD_DATE,+ copyright: `Copyright © ${new Date().getFullYear()} Fincept Corporation. All rights reserved.`,+ description: 'Professional-grade financial analysis platform with AI-powered insights',+};diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.tsindex ec31f0b48..13edc88e3 100644--- a/fincept-terminal-desktop/src/services/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/sqliteService.ts@@ -366,6 +366,14 @@ class SQLiteService {return result.length > 0 ? result[0] : null;}+ /**+ * Get API key for a specific service (simplified retrieval)+ */+ async getApiKey(serviceName: string): Promise<string | null> {+ const credential = await this.getCredentialByService(serviceName);+ return credential?.api_key || null;+ }+async deleteCredential(id: number): Promise<{ success: boolean; message: string }> {if (!this.db) throw new Error('Database not initialized');try {